openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
6 lines โข 25.8 kB
JavaScript
import{g as readStringValue,l as normalizeOptionalString,m as readNonBlankString}from"./string-coerce-CpTFcSwY.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{o as writeRuntimeJson}from"./runtime-DIcLIHcp.mjs";import{i as isPathStrictlyInside}from"./path-guards-DGttsOJI.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{x as root}from"./fs-safe-Bxzu1j4h.mjs";import{a as redactSecrets,d as redactToolPayloadText,r as redactDiagnosticSupportBundleFile}from"./redact-BT59pdZ_.mjs";import"./paths-D_FOvGon.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{N as parseAgentSessionKey,l as resolveAgentIdFromSessionKey,o as classifySessionKeyShape}from"./session-key-BPgKfU2m.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{l as resolveSessionStorePathCore}from"./paths-CcxgiC3g.mjs";import{h as resolveConfiguredAgentId,l as resolveAgentOperationAgentId}from"./agent-scope-config-CG9CFpGX.mjs";import{u as redactSupportString}from"./diagnostic-support-redaction-fdb2R4EP.mjs";import{t as captureRuntimeConfigAsyncReader}from"./io.runtime-BvSeVFIY.mjs";import{r as resolveSqliteSessionKey}from"./session-accessor.sqlite-scope-helpers-_Zyjm1vW.mjs";import{n as parseSqliteSessionFileMarker}from"./legacy-sqlite-marker-BOXSzMrL.mjs";import{l as scanSessionTranscriptTree,t as isCanonicalSessionTranscriptEntry}from"./transcript-tree-Dwc2Zlw1.mjs";import{a as hasMeaningfulRetiredMediaCarrier,t as PERSISTED_LEGACY_MEDIA_KEYS}from"./media-facts-03ZYaqC1.mjs";import{x as withSessionTranscriptHydrationCaller}from"./session-transcript-worker-resources-BCJ3nyGg.mjs";import{t as listSessionEntriesReadOnly}from"./session-accessor.sqlite-entry-list.read-CYIxUD3r.mjs";import"./session-accessor-CY8UYP4m.mjs";import{i as safeTrajectorySessionFileName,r as TRAJECTORY_RUNTIME_FILE_MAX_BYTES}from"./paths-BQzjnVTJ.mjs";import{a as loadSessionEntryReadOnly}from"./session-accessor.sqlite-exact-read-CzR5cjvF.mjs";import"./config-DkZ8y8Gv.mjs";import{t as loadSessionTranscriptEvents}from"./session-transcript-events-C7eeuw86.mjs";import{i as resolveSessionTranscriptReadTarget}from"./session-accessor.transcript-target-CNlRFjvI.mjs";import{t as sanitizeDiagnosticPayload}from"./payload-redaction-D9V_wI0L.mjs";import{t as resolvePreferredSessionKeyForSessionIdMatches}from"./session-id-resolution-CLU1zB-T.mjs";import{n as throwExpectedCliError}from"./expected-cli-error-oDVmXYil.mjs";import{t as safeJsonStringify}from"./safe-json-9CZ2zi-Z.mjs";import{n as parseSessionFileEntriesWithWarnings,t as isSessionFileEntry}from"./session-file-parser-e7eWnuW6.mjs";import{a as writeSupportBundleDirectory,i as textSupportBundleFile,n as jsonlSupportBundleFile,r as supportBundleContents,t as jsonSupportBundleFile}from"./diagnostic-support-bundle-CJE9d-v5.mjs";import{r as loadSqliteTrajectoryRuntimeEvents}from"./runtime-store.sqlite-BsPpULCI.mjs";import{n as resolveExplicitSessionStorePath}from"./session-store-targets-BHtqyW-o.mjs";import path from"node:path";import fs from"node:fs/promises";import{pathScope}from"@openclaw/fs-safe/advanced";
//!src/trajectory/export.ts
const MAX_TRAJECTORY_RUNTIME_EVENTS=2e5;const MAX_TRAJECTORY_TOTAL_EVENTS=25e4;const MAX_TRAJECTORY_SESSION_FILE_BYTES=52428800;const MAX_TRAJECTORY_WARNING_ROWS=20;function normalizeCompleteSessionTarget(e){if(!e)return;const t=normalizeOptionalString(e.agentId);const n=normalizeOptionalString(e.sessionId);const r=normalizeOptionalString(e.sessionKey);const i=normalizeOptionalString(e.storePath);return t&&n&&r&&i?{agentId:t,sessionId:n,sessionKey:r,storePath:i}:void 0}function isFiniteNumber(e){return typeof e===`number`&&Number.isFinite(e)}function formatSessionParseWarnings(e){return e.map(e=>({source:`session`,code:e.code,row:e.row,message:e.code===`invalid-session-json`?`Skipped a session JSONL row that is not valid JSON.`:`Skipped a session JSONL row that is not a session entry object.`}))}function collectSessionEntries(e){const t=[];const n=[];const r=/* @__PURE__ */ new Map;for(const[i,a]of e.entries()){if(!isSessionFileEntry(a)){n.push({source:`session`,code:`invalid-session-row`,row:i+1,message:`Skipped a session JSONL row that is not a session entry object.`});continue}t.push(a);r.set(a,i+1)}return{entries:t,warnings:n,rowByEntry:r}}async function readSessionEntries(e){const t=normalizeCompleteSessionTarget(e.sessionTarget);if(t){const n=parseAgentSessionKey(t.sessionKey)?.agentId;const r=loadSessionEntryReadOnly({agentId:t.agentId,sessionKey:t.sessionKey,storePath:t.storePath,projection:`list`});if(t.sessionId!==e.sessionId||e.sessionKey!==void 0&&t.sessionKey!==e.sessionKey||n&&n!==t.agentId||r&&r.sessionId!==t.sessionId)throw new Error(`Trajectory export transcript target does not match the requested session`);return collectSessionEntries(await loadSessionTranscriptEvents({agentId:t.agentId,sessionId:t.sessionId,sessionKey:t.sessionKey,storePath:t.storePath,maxEventBytes:MAX_TRAJECTORY_SESSION_FILE_BYTES}))}const n=e.sessionTarget?{agentId:normalizeOptionalString(e.sessionTarget.agentId),sessionId:normalizeOptionalString(e.sessionTarget.sessionId),sessionKey:normalizeOptionalString(e.sessionTarget.sessionKey),storePath:normalizeOptionalString(e.sessionTarget.storePath)}:void 0;if(!e.sessionFile)throw new Error(`Trajectory export requires a transcript identity or artifact file`);const r=parseSqliteSessionFileMarker(e.sessionFile);if(!r){const{entries:t,warnings:n,rowByEntry:r}=parseSessionFileEntriesWithWarnings(await fs.readFile(e.sessionFile,`utf8`));return{entries:t,warnings:formatSessionParseWarnings(n),rowByEntry:r}}if(r.sessionId!==e.sessionId)throw new Error(`Trajectory export legacy marker does not match the requested session`);const i=parseAgentSessionKey(n?.sessionKey)?.agentId;const a=new Map(listSessionEntriesReadOnly({agentId:r.agentId,storePath:r.storePath,projection:`list`}).map(({sessionKey:e,entry:t})=>[e,t]));const entryForKey=(e=``)=>a.get(resolveSqliteSessionKey(e,r.agentId));const o=entryForKey(n?.sessionKey);if(n&&(n.agentId&&n.agentId!==r.agentId||n.sessionId&&n.sessionId!==r.sessionId||i&&i!==r.agentId||n.sessionKey&&o?.sessionId!==r.sessionId||n.storePath&&path.resolve(n.storePath)!==path.resolve(r.storePath)))throw new Error(`Trajectory export transcript target conflicts with the legacy marker`);const s=entryForKey(e.sessionKey);const c=[...a].filter(([,e])=>e.sessionId===r.sessionId);if(s&&s.sessionId!==r.sessionId)throw new Error(`Trajectory export session key conflicts with the legacy marker`);if(e.sessionKey&&!s&&c.length>0)throw new Error(`Trajectory export session key is not mapped to the legacy marker`);const l=s?e.sessionKey:resolvePreferredSessionKeyForSessionIdMatches(c,r.sessionId)??(c.length===0?e.sessionKey:void 0);if(!l&&c.length>0)throw new Error(`Trajectory export legacy marker session key is ambiguous`);return collectSessionEntries(await loadSessionTranscriptEvents({agentId:r.agentId,sessionId:r.sessionId,...l?{sessionKey:l}:{},storePath:r.storePath,maxEventBytes:MAX_TRAJECTORY_SESSION_FILE_BYTES}))}async function readSessionBranch(e){const{entries:t,warnings:n,rowByEntry:r}=await readSessionEntries(e);const i=t.find(e=>e.type===`session`)??null;const a=t.filter(e=>isCanonicalSessionTranscriptEntry(e)&&typeof e.id===`string`);const o=scanSessionTranscriptTree(t);if(!o.hasLeafUpdate)return{header:i,leafId:a.at(-1)?.id??null,branchEntries:a,warnings:n};const s=new Map(a.map(e=>[e.id,e]));const c=[];const l=/* @__PURE__ */ new Set;let u;let d=o.leafId;while(d){if(l.has(d)){const e=o.byId.get(d)?.entry;n.push({source:`session`,code:`cyclic-session-branch`,row:e?r.get(e)??0:0,message:`Stopped trajectory session branch export at a cyclic parent link.`});break}l.add(d);const e=o.byId.get(d);if(!e){n.push({source:`session`,code:`incomplete-session-branch`,row:0,message:`Exported the reachable session branch suffix after a missing parent link.`});break}const t=s.get(d);if(t){const n={...t,parentId:e.parentId};if(u)u.parentId=n.id;c.unshift(n);u=n}if(e.parentId&&!o.byId.has(e.parentId)){n.push({source:`session`,code:`incomplete-session-branch`,row:r.get(e.entry)??0,message:`Exported the reachable session branch suffix after a missing parent link.`});break}d=e.parentId}return{header:i,leafId:o.leafId,branchEntries:c,warnings:n}}function summarizeJsonlWarnings(e){const t=/* @__PURE__ */ new Map;for(const n of e){const e=`${n.source}:${n.code}`;const r=t.get(e);if(r){r.count+=1;if(r.rows.length<MAX_TRAJECTORY_WARNING_ROWS)r.rows.push(n.row);continue}t.set(e,{source:n.source,code:n.code,count:1,rows:[n.row],message:n.message})}return[...t.values()]}function normalizeTimestamp(e){if(typeof e===`string`||typeof e===`number`&&Number.isFinite(e)){const t=new Date(e);if(!Number.isNaN(t.getTime()))return t.toISOString()}return(/* @__PURE__ */ new Date(0)).toISOString()}function resolveMessageEventType(e){if(e.role===`user`)return`user.message`;if(e.role===`assistant`)return`assistant.message`;if(e.role===`toolResult`)return`tool.result`;return`message.${e.role}`}function extractAssistantToolCalls(e){if(e.role!==`assistant`||!Array.isArray(e.content))return[];return e.content.flatMap((e,t)=>{if(!e||typeof e!==`object`)return[];const n=e;const r=typeof n.type===`string`?n.type.trim().toLowerCase():``;if(r!==`toolcall`&&r!==`tooluse`&&r!==`functioncall`)return[];return[{id:typeof n.id===`string`?n.id:void 0,name:typeof n.name===`string`?n.name:void 0,arguments:n.arguments??n.input??n.parameters,index:t}]})}function assertCanonicalTrajectoryInputs(e,t){const n=e.some(e=>e.type===`message`&&isRecord(e.message)&&(Object.hasOwn(e.message,`media`)||PERSISTED_LEGACY_MEDIA_KEYS.some(t=>Object.hasOwn(e.message,t))));const r=t.some(e=>Array.isArray(e.data?.messagesSnapshot)&&e.data.messagesSnapshot.some(e=>isRecord(e)&&hasMeaningfulRetiredMediaCarrier(e)));if(n||r)throw new Error(`Trajectory export input contains retired top-level media fields; migrate the source transcript before exporting.`)}function sortTrajectoryEvents(e){const t={runtime:0,transcript:1,export:2};const n=e.toSorted((e,n)=>e.ts.localeCompare(n.ts)||t[e.source]-t[n.source]||(e.sourceSeq??e.seq)-(n.sourceSeq??n.seq));for(const[e,t]of n.entries())t.seq=e+1;return n}function trajectoryJsonlFile(e,t){const n=t.map(e=>safeJsonStringify(e)).filter(e=>Boolean(e));return jsonlSupportBundleFile(e,n)}function redactWorkspacePathString(e,t){const n=t.workspaceDir;if(!n)return e;const r=n.replaceAll(`\\`,`/`);let i=e;for(const e of/* @__PURE__ */ new Set([n,r])){if(!e)continue;const t=e.replace(/[.*+?^${}()|[\]\\]/gu,`\\$&`);i=i.replace(new RegExp(`${t}(?=$|[\\\\/])`,`gu`),`$WORKSPACE_DIR`)}return i}function maybeRedactPathString(e,t){const n=redactWorkspacePathString(e,t);if(n!==e||path.isAbsolute(n)||n.includes(t.stateDir)||(t.env.HOME?n.includes(t.env.HOME):false)||(t.env.USERPROFILE?n.includes(t.env.USERPROFILE):false))return redactSupportString(n,t,{maxLength:Number.MAX_SAFE_INTEGER});return n}function redactLocalPathValues(e,t){if(typeof e===`string`)return maybeRedactPathString(e,t);if(Array.isArray(e))return e.map(e=>redactLocalPathValues(e,t));if(!e||typeof e!==`object`)return e;const n=e;const r={};for(const[e,i]of Object.entries(n))r[e]=redactLocalPathValues(i,t);return r}function uniqueRedactedObjectKey(e,t){if(!t.has(e)){t.add(e);return e}let n=2;while(t.has(`${e}#${n}`))n+=1;const r=`${e}#${n}`;t.add(r);return r}function redactTrajectoryExportObjectKeys(e,t){if(Array.isArray(e))return e.map(e=>redactTrajectoryExportObjectKeys(e,t));if(!e||typeof e!==`object`)return e;const n=/* @__PURE__ */ new Set;const r={};for(const[i,a]of Object.entries(e)){const e=redactToolPayloadText(maybeRedactPathString(i,t));r[uniqueRedactedObjectKey(e,n)]=redactTrajectoryExportObjectKeys(a,t)}return r}function redactTrajectoryExportValue(e,t){return redactTrajectoryExportObjectKeys(redactSecrets(sanitizeDiagnosticPayload(redactLocalPathValues(e,t))),t)}function resolveLatestRuntimeEventData(e,t){return e.findLast(e=>e.type===t)?.data}function normalizePathForMatch(e){return e.replaceAll(`\\`,`/`).trim().toLowerCase()}function collectPotentialPathStrings(e){const t=/* @__PURE__ */ new Set;const visit=e=>{if(!e||typeof e!==`object`)return;if(Array.isArray(e)){for(const t of e)visit(t);return}for(const[n,r]of Object.entries(e))if(typeof r===`string`&&(n.toLowerCase().includes(`path`)||r.endsWith(`SKILL.md`)||r.endsWith(`skill.md`)))t.add(r);else visit(r)};visit(e);return[...t]}function resolveDefaultTrajectoryExportDir(e){const t=(e.now??/* @__PURE__ */ new Date).toISOString().replace(/[:.]/g,`-`).slice(0,19);const n=safeTrajectorySessionFileName(e.sessionId);return path.join(e.workspaceDir,`.openclaw`,`trajectory-exports`,`openclaw-trajectory-${n.slice(0,8)}-${t}`)}async function exportTrajectoryBundle(e){const t=process.env;const n={env:t,stateDir:resolveStateDir(t),workspaceDir:path.resolve(e.workspaceDir)};const r=normalizeCompleteSessionTarget(e.sessionTarget);if(e.sessionFile&&!r&&!parseSqliteSessionFileMarker(e.sessionFile)){const t=await fs.stat(e.sessionFile);if(t.size>MAX_TRAJECTORY_SESSION_FILE_BYTES)throw new Error(`Trajectory session file is too large to export (${t.size} bytes; limit ${MAX_TRAJECTORY_SESSION_FILE_BYTES})`)}const{header:i,leafId:a,branchEntries:o,warnings:s}=await withSessionTranscriptHydrationCaller(`export`,()=>readSessionBranch({sessionFile:e.sessionFile,sessionTarget:e.sessionTarget,sessionId:e.sessionId,...e.sessionKey?{sessionKey:e.sessionKey}:{}}));const{sessionFile:c,sessionId:l}=e;const u=await(async()=>{const e=r??parseSqliteSessionFileMarker(c);if(e&&e.sessionId!==l)throw new Error(`Trajectory runtime target does not match the requested session`);return e?await loadSqliteTrajectoryRuntimeEvents({agentId:e.agentId,sessionId:e.sessionId,storePath:e.storePath,maxEventBytes:TRAJECTORY_RUNTIME_FILE_MAX_BYTES,maxEventCount:MAX_TRAJECTORY_RUNTIME_EVENTS}):[]})();assertCanonicalTrajectoryInputs(o,u);const{sessionId:d,sessionKey:f,workspaceDir:p}=e;const m=(()=>{const e=[];let t=0;for(const n of o){const push=(r,i)=>{e.push({traceSchema:`openclaw-trajectory`,schemaVersion:1,traceId:d,source:`transcript`,type:r,ts:normalizeTimestamp(n.timestamp),seq:0,sourceSeq:t+=1,sessionId:d,sessionKey:f,workspaceDir:p,entryId:n.id,parentEntryId:n.parentId,data:i})};switch(n.type){case`message`:push(resolveMessageEventType(n.message),{message:sanitizeDiagnosticPayload(n.message)});for(const e of extractAssistantToolCalls(n.message))push(`tool.call`,{toolCallId:e.id,name:e.name,arguments:sanitizeDiagnosticPayload(e.arguments),assistantEntryId:n.id,blockIndex:e.index});break;case`compaction`:push(`session.compaction`,{summary:n.summary,firstKeptEntryId:n.firstKeptEntryId,tokensBefore:n.tokensBefore,details:sanitizeDiagnosticPayload(n.details),fromHook:n.fromHook??false});break;case`reset`:push(`session.reset`,{reason:n.reason,firstKeptEntryId:n.firstKeptEntryId});break;case`branch_summary`:push(`session.branch_summary`,{fromId:n.fromId,summary:n.summary,details:sanitizeDiagnosticPayload(n.details),fromHook:n.fromHook??false});break;case`custom`:push(`session.custom`,{customType:n.customType,data:sanitizeDiagnosticPayload(n.data)});break;case`custom_message`:push(`session.custom_message`,{customType:n.customType,content:sanitizeDiagnosticPayload(n.content),details:sanitizeDiagnosticPayload(n.details),display:n.display});break;case`thinking_level_change`:push(`session.thinking_level_change`,{thinkingLevel:n.thinkingLevel});break;case`model_change`:push(`session.model_change`,{provider:n.provider,modelId:n.modelId});break;case`label`:push(`session.label`,{targetId:n.targetId,label:n.label});break;case`session_info`:push(`session.info`,{name:n.name})}}return e})();const h=e.maxTotalEvents??MAX_TRAJECTORY_TOTAL_EVENTS;const g=u.length+m.length;if(g>h)throw new Error(`Trajectory export has too many events (${g}; limit ${h})`);const _=sortTrajectoryEvents([...u,...m]);const v=_.map(e=>redactTrajectoryExportValue(e,n));const y={traceSchema:`openclaw-trajectory`,schemaVersion:1,generatedAt:(/* @__PURE__ */ new Date()).toISOString(),traceId:e.sessionId,sessionId:e.sessionId,sessionKey:e.sessionKey,workspaceDir:maybeRedactPathString(e.workspaceDir,n),leafId:a,eventCount:v.length,runtimeEventCount:u.length,transcriptEventCount:m.length,sourceFiles:{session:maybeRedactPathString(r?.sessionKey??e.sessionFile??e.sessionId,n)}};const b=summarizeJsonlWarnings(s);if(b.length>0)y.warnings=b;const x=resolveLatestRuntimeEventData(u,`context.compiled`);const S=typeof x?.systemPrompt===`string`?x.systemPrompt:void 0;const C=Array.isArray(x?.tools)?x.tools:void 0;const w=[];const T=[];const captureHeader=()=>({traceSchema:`openclaw-trajectory`,schemaVersion:1,generatedAt:(/* @__PURE__ */ new Date()).toISOString(),traceId:y.traceId,sessionId:y.sessionId,sessionKey:y.sessionKey});const E={"metadata.json":(()=>{const e=resolveLatestRuntimeEventData(u,`trace.metadata`);if(!e)return;const t=u.findLast(e=>e.provider||e.modelId||e.modelApi);const n=t?{provider:t.provider,name:t.modelId,api:t.modelApi}:void 0;return{...captureHeader(),harness:e.harness,model:e.model??n,config:e.config,plugins:e.plugins,skills:(()=>{if(!e.skills||typeof e.skills!==`object`)return e.skills;const t=e.skills;if(!Array.isArray(t.entries)||t.entries.length===0)return e.skills;const n=new Set(_.flatMap(e=>e.type===`tool.call`?collectPotentialPathStrings(e.data?.arguments).map(normalizePathForMatch):[]));const r=t.entries.map(e=>{const t=typeof e.filePath===`string`?e.filePath:void 0;const r=t?normalizePathForMatch(t):void 0;const i=t?.replaceAll(`\\`,`/`).split(`/`).slice(-2,-1)[0]?.toLowerCase()??void 0;const a=r?[...n].some(e=>e===r||e.endsWith(r)||(i?e.endsWith(`/${i}/skill.md`):false)):false;return a?{...e,invoked:a,invocationDetectedBy:`tool-call-file-path`}:{...e,invoked:false}});return{...t,entries:r}})(),prompting:e.prompting,redaction:e.redaction,metadata:e.metadata}})(),"artifacts.json":(()=>{const e=u.findLastIndex(e=>e.type===`session.started`);const t=(e<0?u.filter(e=>e.type===`session.ended`&&isFiniteNumber(e.data?.startedAt)).toSorted((e,t)=>Number(e.data?.startedAt)-Number(t.data?.startedAt)).at(-1):void 0)??(e<0?u.findLast(e=>e.type===`session.ended`):void 0);const n=u[e]?.runId??t?.runId??u.at(-1)?.runId;const r=t?u.lastIndexOf(t)+1:u.length;const i=t?u.findLastIndex((e,t)=>t<r-1&&e.type===`session.ended`&&e.runId===n)+1:e;const a=u.slice(Math.max(0,i),r).filter(e=>n===void 0||e.runId===n);const o=resolveLatestRuntimeEventData(a,`trace.artifacts`);const s=resolveLatestRuntimeEventData(a,`model.completed`);const c=resolveLatestRuntimeEventData(a,`session.ended`);if(!o&&!s&&!c)return;return{...captureHeader(),finalStatus:o?.finalStatus??c?.status,aborted:o?.aborted??c?.aborted,externalAbort:o?.externalAbort??c?.externalAbort,timedOut:o?.timedOut??c?.timedOut,idleTimedOut:o?.idleTimedOut??c?.idleTimedOut,timedOutDuringCompaction:o?.timedOutDuringCompaction??c?.timedOutDuringCompaction,timedOutDuringToolExecution:o?.timedOutDuringToolExecution??c?.timedOutDuringToolExecution,timedOutByRunBudget:o?.timedOutByRunBudget??c?.timedOutByRunBudget,promptError:o?.promptError??c?.promptError??s?.promptError,promptErrorSource:o?.promptErrorSource??s?.promptErrorSource,terminalError:o?.terminalError??c?.terminalError??s?.terminalError,usage:o?.usage??s?.usage,promptCache:o?.promptCache??s?.promptCache,compactionCount:o?.compactionCount??s?.compactionCount,assistantTexts:o?.assistantTexts??s?.assistantTexts,stopReason:o?.stopReason??s?.stopReason??c?.stopReason,finalPromptText:o?.finalPromptText??s?.finalPromptText,finalPromptTextOriginalLength:o?.finalPromptTextOriginalLength??s?.finalPromptTextOriginalLength,itemLifecycle:o?.itemLifecycle,toolMetas:o?.toolMetas,didSendViaMessagingTool:o?.didSendViaMessagingTool,successfulCronAdds:o?.successfulCronAdds,messagingToolSentTexts:o?.messagingToolSentTexts,messagingToolSentMediaUrls:o?.messagingToolSentMediaUrls,messagingToolSentTargets:o?.messagingToolSentTargets,lastToolError:o?.lastToolError}})(),"prompts.json":(()=>{const e=resolveLatestRuntimeEventData(u,`trace.metadata`);const t=u.filter(e=>e.type===`prompt.submitted`).map(e=>e.data?.prompt).filter(e=>typeof e===`string`);const n=e?.prompting&&typeof e.prompting===`object`?e.prompting:void 0;const r=typeof n?.skillsPrompt===`string`?n.skillsPrompt:void 0;const i=typeof n?.userPromptPrefixText===`string`?n.userPromptPrefixText:void 0;const a=typeof n?.systemPromptReport===`object`?n.systemPromptReport:void 0;if(!S&&t.length===0&&!r&&!i)return;return{...captureHeader(),system:S,submittedPrompts:t,latestSubmittedPrompt:t.at(-1),skillsPrompt:r,userPromptPrefixText:i,systemPromptReport:a}})()};for(const[e,t]of Object.entries(E)){if(!t)continue;w.push(jsonSupportBundleFile(e,redactTrajectoryExportValue(t,n)));T.push(e)}if(T.length>0)y.supplementalFiles=T;w.push(trajectoryJsonlFile(`events.jsonl`,v));w.push(jsonSupportBundleFile(`session-branch.json`,redactTrajectoryExportValue({header:i,leafId:a,entries:o},n)));if(S)w.push(textSupportBundleFile(`system-prompt.txt`,redactTrajectoryExportValue(S,n)));if(C)w.push(jsonSupportBundleFile(`tools.json`,redactTrajectoryExportValue(C,n)));const D=w.map(redactDiagnosticSupportBundleFile);y.contents=supportBundleContents(D);const O=redactTrajectoryExportValue(y,n);const k=redactDiagnosticSupportBundleFile(jsonSupportBundleFile(`manifest.json`,O));const A=await writeSupportBundleDirectory({outputDir:e.outputDir,files:[k,...D]});return{manifest:O,outputDir:e.outputDir,events:v,header:i,supplementalFiles:T,files:A.map(e=>e.path)}}
//!src/commands/export-trajectory.ts
const ENCODED_EXPORT_REQUEST_RE=/^[A-Za-z0-9_-]{1,65536}$/u;function decodeExportTrajectoryRequest(e){if(!ENCODED_EXPORT_REQUEST_RE.test(e))throw new Error(`Encoded trajectory export request is invalid`);const t=Buffer.from(e,`base64url`);if(t.toString(`base64url`)!==e)throw new Error(`Encoded trajectory export request is invalid`);let n;try{n=JSON.parse(t.toString(`utf8`))}catch{throw new Error(`Encoded trajectory export request is invalid JSON`)}if(!isRecord(n))throw new Error(`Encoded trajectory export request must be a JSON object`);const r={};for(const e of[`sessionKey`,`output`,`store`,`agent`,`workspace`]){const t=e===`store`||e===`agent`?readStringValue(n[e]):readNonBlankString(n[e]);if(t!==void 0)r[e]=t}return r}async function exportTrajectoryCommand(e,t){let n;try{n=e.requestJsonBase64?{...e,...decodeExportTrajectoryRequest(e.requestJsonBase64)}:e}catch(e){throwExpectedCliError(`Failed to decode trajectory export request: ${formatErrorMessage(e)}`)}const r=n.sessionKey?.trim();if(!r)throwExpectedCliError(`--session-key is required. Run ${formatCliCommand(`openclaw sessions`)} to choose a session.`);const i=n.agent?.trim();if(n.agent!==void 0&&!i)throwExpectedCliError(`--agent must not be blank`);if(n.store!==void 0&&!n.store.trim())throwExpectedCliError(`--store must not be blank`);let a;const o=captureRuntimeConfigAsyncReader();try{a=i?resolveConfiguredAgentId(await o(),i):resolveAgentIdFromSessionKey(r,classifySessionKeyShape(r)===`legacy_or_alias`?resolveAgentOperationAgentId(await o()):void 0)}catch(e){throwExpectedCliError(formatErrorMessage(e))}let s=n.store?resolveSessionStorePathCore(n.store,{agentId:a}):resolveSessionStorePathCore((await o()).session?.store,{agentId:a});if(n.store)try{s=resolveExplicitSessionStorePath({storePath:s,inputStorePath:n.store,agentId:a})}catch(e){throwExpectedCliError(formatErrorMessage(e))}const c=loadSessionEntryReadOnly({agentId:a,sessionKey:r,storePath:s});if(!c?.sessionId)throwExpectedCliError(`Session not found: ${r}. Run ${formatCliCommand(`openclaw sessions`)} to see available sessions.`);let l;try{l=resolveSessionTranscriptReadTarget({agentId:a,sessionEntry:c,sessionId:c.sessionId,sessionKey:r,storePath:s})}catch(e){throwExpectedCliError(`Failed to resolve session file: ${formatErrorMessage(e)}`)}let u;try{const e={agentId:l.agentId??a,sessionId:l.sessionId,sessionKey:l.sessionKey??r,storePath:l.storePath};const t=c.sessionId;const i=path.resolve(n.workspace??process.cwd());const o=await fs.realpath(i);const s=path.join(`.openclaw`,`trajectory-exports`);const d=await pathScope(o,{label:`workspace`}).ensureDir(s,{mode:448});if(!d.ok)throw d.diagnostic??new Error(d.error);const f=path.join(i,s);const p=readNonBlankString(n.output);let m;if(!p){const e=resolveDefaultTrajectoryExportDir({workspaceDir:i,sessionId:t});m=path.join(f,path.basename(e))}else{if(path.isAbsolute(p)||p.startsWith(`~`))throw new Error(`Output path must be relative to the workspace trajectory exports directory`);const e=path.resolve(f);m=path.resolve(e,p);const t=path.relative(e,m);if(!isPathStrictlyInside(e,m))throw new Error(`Output path must stay inside the workspace trajectory exports directory`);await(await root(d.path)).resolve(`.${path.sep}${t}`)}const h=await exportTrajectoryBundle({outputDir:m,sessionTarget:e,sessionId:t,sessionKey:r,workspaceDir:i});const g=path.relative(i,h.outputDir);const _=g&&!g.startsWith(`..`)&&!path.isAbsolute(g)?g:path.basename(h.outputDir);u={outputDir:h.outputDir,displayPath:_,sessionId:t,eventCount:h.manifest.eventCount,runtimeEventCount:h.manifest.runtimeEventCount,transcriptEventCount:h.manifest.transcriptEventCount,files:[...h.files.filter(e=>!h.supplementalFiles.includes(e)),...h.supplementalFiles]}}catch(e){throwExpectedCliError(`Failed to export trajectory: ${formatErrorMessage(e)}`)}if(n.json){writeRuntimeJson(t,u);return}t.log([`โ
Trajectory exported!`,``,`๐ฆ Bundle: ${u.displayPath}`,`๐งต Session: ${u.sessionId}`,`๐ Events: ${u.eventCount}`,`๐งช Runtime events: ${u.runtimeEventCount}`,`๐ Transcript events: ${u.transcriptEventCount}`,`๐ Files: ${u.files.join(`, `)}`].join(`
`))}export{exportTrajectoryCommand};