beeos-claw 0.6.66-cloud.1 → 0.6.66-cloud.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +13 -0
  2. package/dist/acp-gateway/bridge-core.js +1 -1
  3. package/dist/contracts/question/codec.js +1 -0
  4. package/dist/gateway-client.js +1 -1
  5. package/dist/im-inbound-handler.js +1 -1
  6. package/dist/im-runtime-dispatch.js +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/message-projection-inbound-consumer.js +1 -1
  9. package/dist/runtime/agent-projection-production.js +1 -1
  10. package/dist/runtime/core-execution-attempt-context.js +1 -1
  11. package/dist/runtime/im-reply-sink.js +1 -1
  12. package/dist/runtime/message-service-runtime-invocation-authority.js +1 -1
  13. package/dist/runtime/message-service-session-reasoning-http-authority.js +1 -0
  14. package/dist/runtime/ms-runtime-message-channel-adapter.js +1 -1
  15. package/dist/runtime/openclaw-native-sessions.js +1 -1
  16. package/dist/runtime/openclaw-question-adapter.js +1 -0
  17. package/dist/runtime/openclaw-runtime-capabilities.js +1 -1
  18. package/dist/runtime/question-wire.js +1 -0
  19. package/dist/runtime/runtime-command-dispatcher.js +1 -1
  20. package/dist/runtime/runtime-command-journal.js +1 -1
  21. package/dist/runtime/runtime-parity-manifest-digest.js +1 -1
  22. package/dist/runtime/runtime-parity-manifest.js +1 -1
  23. package/dist/runtime/runtime-production-authority.js +1 -1
  24. package/dist/runtime/runtime-reasoning.js +1 -0
  25. package/dist/runtime/runtime-service-contract-compatibility.js +1 -1
  26. package/dist/runtime/runtime-service-production-candidate.js +1 -1
  27. package/dist/runtime/runtime-session-control-service.js +1 -1
  28. package/dist/runtime/session-set-model-mapping.js +1 -1
  29. package/dist/terminal/runtime-terminal-outbound-registration.js +1 -1
  30. package/dist/terminal/runtime-terminal-service.js +1 -1
  31. package/dist/terminal/terminal-lease-bound-bridge-client.js +1 -1
  32. package/package.json +7 -6
  33. package/runtime-service-wire-identity.v1.json +12 -12
@@ -1 +1 @@
1
- import{toMessagePart}from"../message-client-types.js";import{isUploadArtifactToolName,resolveToolArtifactLinks}from"../upload/tool-artifact-enrichment.js";import{sessionWorkspaceDir,takeFinalizeAttachments}from"../upload/delivery-ledger.js";import{resolveRuntimeToolArguments,resolveRuntimeToolCallId,resolveRuntimeToolName}from"./tool-envelope-metadata.js";import{extractSearchSources,mergeSearchSource,searchSourceProvider}from"./search-source-extractor.js";import{logChatLatency}from"../chat-latency.js";const STREAMING_SNAPSHOT_PUBLISH_INTERVAL_MS=200,isNonEmptyString=e=>"string"==typeof e&&e.length>0,isPlainRecord=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);function pickRawResultFromPayload(e){if(void 0!==e.rawResult)return e.rawResult;if(void 0!==e.result)return e.result;if(void 0!==e.details)return e.details;if(void 0!==e.toolResult)return e.toolResult;if(isPlainRecord(e.channelData)){const t=e.channelData;if(void 0!==t.rawResult)return t.rawResult;if(void 0!==t.result)return t.result;if(void 0!==t.details)return t.details}}function asToolParams(e){if(e&&"object"==typeof e&&!Array.isArray(e))return e}const summarizeObservedToolError=e=>{if(null==e)return;if("string"==typeof e)return e.slice(0,180);if("object"!=typeof e)return String(e).slice(0,180);const t=e;for(const e of["error","message","blockReason","details","text"]){const r=t[e];if("string"==typeof r&&r.trim())return r.slice(0,180);if(isPlainRecord(r)&&"string"==typeof r.message&&r.message.trim())return r.message.slice(0,180)}try{const t=JSON.stringify(e);return t?t.slice(0,180):void 0}catch{return}};export function createImReplySink(e){const t=e.startedAtMs??Date.now();let r=!1;const n=new Map,s=new Set,o={text:""};let a="",i="",l=!1,d=!1;const u=new Set;let m;const c={receivedSnapshotCount:0,streamingPublishCount:0,terminalPublishCount:0},g=[];let p;const h=new Map,f=new Map,v=[],y=[],b=new Map,I=new Map;let _=0,S=1;const x=(e,t={})=>({schema_version:1,seq:e,...t}),$=new Set,q=new Set,w=t=>{t!==o.text&&(t.startsWith(o.text)?e.stream.appendBody(t.slice(o.text.length)):e.stream.setBody(t),o.text=t)},T=e=>{void 0===e.publishTimer&&(e.publishTimer=setTimeout(()=>{e.publishTimer=void 0,de("body_preview_flush",()=>{m===e&&(e=>{o.text!==e.targetBody&&(w(e.targetBody),e.streamingPublishCount+=1)})(e)})},200))},k=e=>{const t=m;t?(void 0!==t.publishTimer&&(clearTimeout(t.publishTimer),t.publishTimer=void 0),t.targetBody=e,o.text!==e&&(w(e),t.terminalPublishCount+=1),c.receivedSnapshotCount+=t.receivedSnapshotCount,c.streamingPublishCount+=t.streamingPublishCount,c.terminalPublishCount+=t.terminalPublishCount,m=void 0):w(e)},P=t=>{if(void 0!==t.partIndex)return;const r=_,n=S;e.stream.addPart(toMessagePart({type:"text",text:t.text,state:"done",_seq:n,data:x(n)})),t.partIndex=r,_+=1,S+=1},E=()=>{if(!d){d=!0;for(const e of g)P(e)}},C=e=>{const t={text:e};g.push(t),d&&P(t)},R=(t,r)=>{for(const n of t){const t=I.get(n.url);if(t){const r=mergeSearchSource(t,n);if(r.title===t.title&&r.snippet===t.snippet)continue;const s={...r,partIndex:t.partIndex,displaySeq:t.displaySeq,toolUseId:t.toolUseId};e.stream.replacePart(t.partIndex,toMessagePart({type:"source",url:s.url,...s.title?{title:s.title}:{},...s.snippet?{snippet:s.snippet}:{},tool_use_id:s.toolUseId,_seq:s.displaySeq,data:x(s.displaySeq)})),I.set(n.url,s);continue}const s={...n,partIndex:_,displaySeq:S,toolUseId:r};e.stream.addPart(toMessagePart({type:"source",url:n.url,...n.title?{title:n.title}:{},...n.snippet?{snippet:n.snippet}:{},tool_use_id:r,_seq:s.displaySeq,data:x(s.displaySeq)})),I.set(n.url,s),_+=1,S+=1,ae.source+=1}},M=(e,t,r,n)=>toMessagePart({type:"thinking",text:t,state:r,_seq:e.displaySeq,_started_at_ms:e.startedAtMs,...void 0!==n?{_duration_ms:n}:{},data:x(e.displaySeq,{started_at_ms:e.startedAtMs,...void 0!==n?{duration_ms:n}:{}})}),O=t=>{E();const r={partIndex:_,displaySeq:S,text:t,publishedText:t,receivedSnapshotCount:1,streamingPublishCount:1,startedAtMs:Date.now(),startedAtMonotonicMs:performance.now()};return e.stream.addPart(M(r,t,"streaming")),_+=1,S+=1,p=r,r},A=t=>{void 0===t.publishTimer&&(t.publishTimer=setTimeout(()=>{t.publishTimer=void 0,de("reasoning_snapshot_flush",()=>{p===t&&(t=>{t.publishedText!==t.text&&(e.stream.replacePart(t.partIndex,M(t,t.text,"streaming")),t.publishedText=t.text,t.streamingPublishCount+=1)})(t)})},200))},N=()=>{const r=p;if(!r)return;void 0!==r.publishTimer&&(clearTimeout(r.publishTimer),r.publishTimer=void 0);const n=Math.max(0,Math.round(performance.now()-r.startedAtMonotonicMs));e.stream.replacePart(r.partIndex,M(r,r.text,"done",n)),p=void 0,logChatLatency(e.logger,"claw.reasoning.settled",e.requestId,t,{reasoning_duration_ms:n,reasoning_chars:r.text.length,reasoning_snapshot_count:r.receivedSnapshotCount,reasoning_streaming_publish_count:r.streamingPublishCount,reasoning_coalesced_snapshot_count:Math.max(0,r.receivedSnapshotCount-r.streamingPublishCount),reasoning_publish_interval_ms:200})},U=e=>{const t=v.indexOf(e);t>=0&&v.splice(t,1)},j=e=>{const t=e?v.filter(t=>h.get(t)?.name===e):v;return 1===t.length?t[0]:void 0},L=e=>{const t=y.map((e,t)=>({hint:e,index:t})).filter(({hint:t})=>!e||t.name===e);if(1!==t.length)return;const[{hint:r,index:n}]=t;return y.splice(n,1),r},B=(e,t)=>{if(f.set(e,t),e===t)return;const r=b.get(e);if(!r)return;const n=D(t);W(n,r),b.delete(e);const s=h.get(t);s&&(Y(s,n),b.delete(t))},F=e=>f.get(e)??e,z=e=>null!=e&&("object"!=typeof e||(Array.isArray(e)?e.length>0:Object.keys(e).length>0)),D=e=>{let t=b.get(e);return t||(t={},b.set(e,t)),t},Q=(e,t)=>{if(!e?.length&&!t?.length)return;const r=[],n=new Map;for(const s of[...e??[],...t??[]]){const e=n.get(s.url);void 0===e?(n.set(s.url,r.length),r.push(s)):r[e]=mergeSearchSource(r[e],s)}return r},W=(e,t)=>{e.name??=t.name,e.arguments??=t.arguments,t.toolStartObserved&&(e.toolStartObserved=!0),t.itemEventObserved&&(e.itemEventObserved=!0),t.progress?.length&&(e.progress=[...e.progress??[],...t.progress]),e.sources=Q(e.sources,t.sources)},J=(t,r,n)=>{const s="tool"===t.name&&"tool"!==r?r:t.name,o=!z(t.arguments)&&z(n)?n:t.arguments;s===t.name&&o===t.arguments||(e.stream.replacePart(t.partIndex,toMessagePart({type:"tool_use",id:t.id,name:s,arguments:o,state:t.state,_seq:t.displaySeq,data:x(t.displaySeq)})),t.name=s,t.arguments=o)},H=(t,r,n,s)=>{const o=h.get(t);if(o)return J(o,r,n),s&&!v.includes(t)&&"streaming"===o.state&&v.push(t),o;E();const a=b.get(t),i="tool"!==r?r:a?.name&&"tool"!==a.name?a.name:r,l=z(n)?n:a?.arguments??n,d=((t,r,n)=>{const s=_,o=S;return e.stream.addPart(toMessagePart({type:"tool_use",id:t,name:r,arguments:n,state:"streaming",_seq:o,data:x(o)})),_+=1,S+=1,{partIndex:s,displaySeq:o}})(t,i,l),u={id:t,name:i,arguments:l,partIndex:d.partIndex,displaySeq:d.displaySeq,state:"streaming",itemEventObserved:!0===a?.itemEventObserved,toolStartObserved:!0===a?.toolStartObserved};return h.set(t,u),(s||u.toolStartObserved||u.itemEventObserved)&&(v.includes(t)||"streaming"!==u.state||v.push(t)),a&&Y(u,a),b.delete(t),u},K=(e,t)=>{const r=(e=>{const t=f.get(e);return t?h.get(t):h.get(e)})(e);if(r)return void 0===t.name&&void 0===t.arguments||J(r,t.name??r.name,t.arguments??r.arguments),t.toolStartObserved&&(r.toolStartObserved=!0),t.itemEventObserved&&(r.itemEventObserved=!0),(t.pending||t.toolStartObserved||t.itemEventObserved)&&!v.includes(r.id)&&"streaming"===r.state&&v.push(r.id),r;const n=D(e);void 0!==t.name&&(n.name=t.name),void 0!==t.arguments&&(n.arguments=t.arguments),t.toolStartObserved&&(n.toolStartObserved=!0),t.itemEventObserved&&(n.itemEventObserved=!0)},G=t=>{"done"!==t.state&&(e.stream.replacePart(t.partIndex,toMessagePart({type:"tool_use",id:t.id,name:t.name,arguments:t.arguments,state:"done",_seq:t.displaySeq,data:x(t.displaySeq)})),t.state="done")},V=e=>{if(null===e||"object"!=typeof e)return JSON.stringify(e)??String(e);if(Array.isArray(e))return`[${e.map(V).join(",")}]`;return`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${V(t)}`).join(",")}}`},X=(t,r,n)=>{const s=`${n?"1":"0"}:${V(r)}`;if(t.progressSignature===s)return;const o=toMessagePart({type:"custom",kind:"tool_progress",data:{tool_use_id:t.id,content:r,...n?{is_error:!0}:{}}});if(void 0===t.progressPartIndex){const r=_;return e.stream.addPart(o),t.progressPartIndex=r,t.progressSignature=s,void(_+=1)}e.stream.replacePart(t.progressPartIndex,o),t.progressSignature=s},Y=(e,t)=>{if(t.progress?.length){for(const r of t.progress)X(e,r.content,r.isError);G(e),U(e.id)}t.sources?.length&&R(t.sources,e.id)},Z=e=>[...new Set([e.mediaUrl,...e.mediaUrls??[]].filter(e=>isNonEmptyString(e)).map(e=>e.trim()).filter(Boolean))],ee=(e,t=[])=>{const r=[...new Set([...Z(e),...t])];return isNonEmptyString(e.text)&&r.length>0?{text:e.text,media_urls:r}:isNonEmptyString(e.text)?e.text:1===r.length?r[0]:r.length>1?{media_urls:r}:!0===e.isError?"Tool execution failed.":""},te=t=>{for(const r of t)e.stream.addPart(toMessagePart({type:"resource_link",uri:r.uri,name:r.name,...r.mimeType?{mimeType:r.mimeType}:{}})),_+=1},re=e=>{$.add(e),e.finally(()=>{$.delete(e)})},ne=(t,r)=>{if(t.durableUploadFilesEmitted)return;e.logger.info?.(`[im-sink] schedule tool artifact enrichment requestId=${e.requestId} toolUseId=${t.id} name=${t.name}`);const n=pickRawResultFromPayload(r),s=(async()=>{let s=[];try{s=await resolveToolArtifactLinks({toolCallId:t.id,toolName:t.name,rawResult:n,rawText:"string"==typeof r.text?r.text:void 0,params:asToolParams(t.arguments),cwd:sessionWorkspaceDir(e.sessionKey),payloadMediaUrls:Z(r)})}catch(r){const n=r instanceof Error?r.message:String(r);return void e.logger.warn?.(`[im-sink] resolveToolArtifactLinks failed requestId=${e.requestId} toolUseId=${t.id} error=${n}`)}0!==s.length?(e.logger.info?.(`[im-sink] tool artifact enrichment resolved ${s.length} link(s) requestId=${e.requestId} toolUseId=${t.id}`),await new Promise(n=>{e.callbackQueue.enqueueSync(()=>{try{if(e.abortSignal.aborted||e.stream.isTerminated)return;const n=s.map(e=>e.uri);X(t,ee(r,n),!0===r.isError),((t,r,n)=>{0===r.length||t.durableUploadFilesEmitted||(t.durableUploadFilesEmitted=!0,e.stream.appendToolResult(t.id,r.map(e=>({type:"resource_link",uri:e.uri,name:e.name,...e.mimeType?{mimeType:e.mimeType}:{}})),n),_+=1,te(r))})(t,s,!0===r.isError)}catch(r){const n=r instanceof Error?r.message:String(r);e.logger.warn?.(`[im-sink] tool artifact enrichment apply failed requestId=${e.requestId} toolUseId=${t.id} error=${n}`)}finally{n()}})})):e.logger.debug?.(`[im-sink] tool artifact enrichment found no links requestId=${e.requestId} toolUseId=${t.id} name=${t.name}`)})().catch(r=>{const n=r instanceof Error?r.message:String(r);e.logger.warn?.(`[im-sink] tool artifact enrichment failed requestId=${e.requestId} toolUseId=${t.id} error=${n}`)});re(s)},se=(e,t,r)=>{const n=f.get(e);if(n)return K(n,{name:t,arguments:r});const s=K(e,{name:t,arguments:r});if(s)return s;const o=j(t);if(o)return B(e,o),K(o,{name:t,arguments:r});K(e,{name:t,arguments:r})},oe=(e,t)=>{const r=f.get(e);if(r)return K(r,{name:t,itemEventObserved:!0,pending:!0});const n=K(e,{name:t,itemEventObserved:!0,pending:!0});if(n)return n;const s=(e=>{const t=v.filter(t=>{const r=h.get(t);return!(void 0===r||e&&r.name!==e||r.itemEventObserved)});return 1===t.length?t[0]:void 0})(t);if(s)return B(e,s),K(s,{name:t,itemEventObserved:!0,pending:!0});const o=L(t);K(e,{name:t,arguments:o?.arguments,itemEventObserved:!0,pending:!0})},ae={tool:0,block:0,final:0,source:0};let ie,le=!1;const de=(t,r)=>{e.callbackQueue.enqueueSync(()=>{if((t=>e.abortSignal.aborted?(e.logger.debug?.(`[im-sink] ${t} ignored after abort requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`),!1):e.stream.isTerminated?(e.logger.debug?.(`[im-sink] ${t} ignored after stream_terminated requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`),!1):!le||(e.logger.debug?.(`[im-sink] ${t} ignored after mark_complete requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`),!1))(t))try{r()}catch(r){const n=r instanceof Error?r.message:String(r);e.logger.warn?.(`[im-sink] ${t} mapping failed requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId} error=${n}`)}})};return{dispatcher:{sendToolResult:t=>(de("tool_progress",()=>{const r=resolveRuntimeToolCallId(t),n=resolveRuntimeToolName(t),s=resolveRuntimeToolArguments(t),o=ee(t),a=!0===t.isError;let i;if(r){if(i=se(r,n,s),!i){const e=D(r);return n&&(e.name=n),z(s)&&(e.arguments=s),e.progress=[...e.progress??[],{content:o,isError:a}],void(ae.tool+=1)}}else{const t=n?j(n):j();if(!t)return L(n),void e.logger.debug?.(`[im-sink] unattributed tool progress ignored requestId=${e.requestId} channel=${e.channelId} tool=${n??"unknown"} pending=${v.length}`);i=K(t,{name:n,arguments:s})}i&&(ae.tool+=1,X(i,o,a),G(i),U(i.id),ne(i,t))}),!0),sendBlockReply:e=>(de("block_reply",()=>{ae.block+=1,isNonEmptyString(e.text)&&(ie=!0!==e.isError?void 0:e.text)}),!0),sendFinalReply:t=>(de("final_reply",()=>{var r;(ae.final+=1,!0!==t.isError)?((t=>{const r=Z(t).filter(e=>!q.has(e));if(0===r.length)return;for(const e of r)q.add(e);const n=(async()=>{let t=[];try{t=await resolveToolArtifactLinks({toolCallId:`final:${e.runId??e.requestId}`,toolName:"final_reply_media",payloadMediaUrls:r})}catch(t){for(const e of r)q.delete(e);return void e.logger.warn?.(`[im-sink] final media enrichment failed requestId=${e.requestId} error=${t instanceof Error?t.message:String(t)}`)}if(0!==t.length)await new Promise(r=>{e.callbackQueue.enqueueSync(()=>{try{if(e.abortSignal.aborted||e.stream.isTerminated)return;te(t)}catch(t){e.logger.warn?.(`[im-sink] final media enrichment apply failed requestId=${e.requestId} error=${t instanceof Error?t.message:String(t)}`)}finally{r()}})});else for(const e of r)q.delete(e)})();re(n)})(t),isNonEmptyString(t.text)&&(ie=void 0,l||(r=t.text,i="",a+=r,k(a),C(r),l=!0))):ie=t.text}),!0),waitForIdle:async()=>{for(let t=0;t<16&&(await e.callbackQueue.waitForIdle(),0!==$.size);t++)await Promise.allSettled([...$]);await e.callbackQueue.waitForIdle();const t=takeFinalizeAttachments(e.sessionKey);t.length>0&&!e.abortSignal.aborted&&!e.stream.isTerminated&&te(t)},getQueuedCounts:()=>({tool:ae.tool,block:ae.block,final:ae.final}),getAccumulatedBody:()=>o.text,getTerminalErrorText:()=>ie,markComplete:r=>{N(),(y.length>0||b.size>0)&&e.logger.debug?.(`[im-sink] dropping uncommitted lifecycle tool signals requestId=${e.requestId} legacy_hints=${y.length} buffered=${b.size}`),i="",k(a),c.receivedSnapshotCount>0&&logChatLatency(e.logger,"claw.text_preview.settled",e.requestId,t,{text_preview_snapshot_count:c.receivedSnapshotCount,text_preview_streaming_publish_count:c.streamingPublishCount,text_preview_terminal_publish_count:c.terminalPublishCount,text_preview_coalesced_snapshot_count:Math.max(0,c.receivedSnapshotCount-c.streamingPublishCount-c.terminalPublishCount),text_preview_publish_interval_ms:200});for(const t of h.values())try{"success"===r&&isUploadArtifactToolName(t.name)&&!t.durableUploadFilesEmitted&&ne(t,{toolCallId:t.id,toolName:t.name}),"success"===r&&G(t),U(t.id)}catch(r){const n=r instanceof Error?r.message:String(r);e.logger.warn?.(`[im-sink] tool finalization failed requestId=${e.requestId} toolUseId=${t.id} error=${n}`)}y.length=0,b.clear(),le=!0}},replyOptions:{...e.runId?{runId:e.runId}:{},abortSignal:e.abortSignal,disableBlockStreaming:!0,onAgentRunStart:r=>{e.onAgentRunStart?.(r),logChatLatency(e.logger,"claw.runtime.run_started",e.requestId,t),e.logger.info?.(`[im-sink] run_start requestId=${e.requestId} runId=${r} channel=${e.channelId} in_reply_to=${e.inboundMessageId} origin=${e.origin??"im"}`)},onPartialReply:n=>{de("partial",()=>{"string"==typeof n.text&&(!r&&n.text.length>0&&(r=!0,logChatLatency(e.logger,"claw.model.first_delta",e.requestId,t)),i=n.text,(e=>{const t=m;if(!t){if(o.text===e)return;return w(e),void(m={targetBody:e,receivedSnapshotCount:1,streamingPublishCount:1,terminalPublishCount:0})}t.targetBody!==e&&(t.targetBody=e,t.receivedSnapshotCount+=1,T(t))})(a+i))})},onReasoningStream:e=>{de("reasoning",()=>{if(!isNonEmptyString(e.text))return;const t=e.text,r=p??O(t);t!==r.text&&(r.text.startsWith(t)||(t.startsWith(r.text)?(r.text=t,r.receivedSnapshotCount+=1,A(r)):(N(),O(t))))})},onReasoningEnd:()=>{de("reasoning_end",()=>{N()})},onAssistantMessageStart:()=>{de("assistant_message_start",()=>{i="",l=!1,k(a),e.logger.debug?.(`[im-sink] assistant_message_start requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`)})},onToolStart:r=>{de("tool_start",()=>{const s="string"==typeof r.phase?r.phase:"start",o=resolveRuntimeToolName(r)??"tool",a=resolveRuntimeToolCallId(r),i=resolveRuntimeToolArguments(r);if("update"===s)return void(a&&K(F(a),{name:o,arguments:i,pending:!0}));if(a&&n.set(a,Date.now()),logChatLatency(e.logger,"claw.tool.start",e.requestId,t,{tool:o}),a){K(a,{name:o,arguments:i,toolStartObserved:!0,pending:!0});const e=j(o);return void(e&&e!==a&&!f.has(a)&&(B(a,e),K(e,{name:o,arguments:i,toolStartObserved:!0,pending:!0})))}const l=(d=o,v.map(e=>h.get(e)).filter(e=>void 0!==e&&(!d||e.name===d)&&e.itemEventObserved));var d;if(1===l.length)return void K(l[0].id,{name:o,arguments:i,toolStartObserved:!0,pending:!0});if(l.length>1)return void e.logger.debug?.(`[im-sink] ambiguous id-less tool start ignored requestId=${e.requestId} channel=${e.channelId} tool=${o} candidates=${l.length}`);const u=[...b.entries()].filter(([,e])=>!e.name||e.name===o||"tool"===e.name);1!==u.length?y.push({name:o,arguments:i}):K(u[0][0],{name:o,arguments:i,toolStartObserved:!0,pending:!0})})},onItemEvent:e=>{de("item_event",()=>{const t="string"==typeof e.kind?e.kind.toLowerCase():"";if(t&&"tool"!==t)return;const r="string"==typeof e.phase?e.phase.toLowerCase():"update",n=resolveRuntimeToolCallId(e)??("string"==typeof e.itemId&&e.itemId.trim()?e.itemId.trim():void 0),s=resolveRuntimeToolName(e)??("string"==typeof e.title&&e.title.trim()?e.title.trim():void 0);n&&s&&("update"!==r?oe(n,s):K(F(n),{name:s,itemEventObserved:!0,pending:!0}))})}},commitAssistantMessage:e=>{de("assistant_message_commit",()=>{if(u.has(e.key))return;u.add(e.key),l=!0,ie=void 0,i="";const t=e.segments.filter(e=>"text"===e.type).map(e=>e.text).join("");a+=t,k(a);for(const t of e.segments)"text"!==t.type?H(t.id,t.name,t.arguments,!0):C(t.text)})},observeToolResult:r=>{de("tool_result_observation",()=>{const o=r.toolCallId.trim(),a=r.toolName.trim();if(!o||!a)return;if(!s.has(o)){s.add(o);const i=n.get(o);logChatLatency(e.logger,"claw.tool.result",e.requestId,t,{tool:a,tool_elapsed_ms:void 0===i?void 0:Math.max(0,Date.now()-i),outcome:r.isError?"error":"success",...r.isError?{error:summarizeObservedToolError(r.rawResult)??"error"}:{}})}const i=searchSourceProvider(r.rawResult)??"unknown";let l=0;try{const t=extractSearchSources({toolName:a,rawResult:r.rawResult,isError:r.isError});if(l=t.length,0===l)return;const n=se(o,a);if(n)R(t,n.id);else{const e=D(F(o));e.name??=a,e.sources=Q(e.sources,t)}e.logger.debug?.(`[im-sink] search source projection requestId=${e.requestId} tool=${a} provider=${i} source_count=${l}`)}catch{e.logger.warn?.(`[im-sink] search source projection ignored requestId=${e.requestId} tool=${a} provider=${i} source_count=${l}`)}})},getSourceCount:()=>ae.source}}
1
+ import{toMessagePart}from"../message-client-types.js";import{isUploadArtifactToolName,resolveToolArtifactLinks}from"../upload/tool-artifact-enrichment.js";import{sessionWorkspaceDir,takeFinalizeAttachments}from"../upload/delivery-ledger.js";import{resolveRuntimeToolArguments,resolveRuntimeToolCallId,resolveRuntimeToolName}from"./tool-envelope-metadata.js";import{extractSearchSources,mergeSearchSource,searchSourceProvider}from"./search-source-extractor.js";import{logChatLatency}from"../chat-latency.js";const STREAMING_SNAPSHOT_PUBLISH_INTERVAL_MS=200,isNonEmptyString=e=>"string"==typeof e&&e.length>0,isPlainRecord=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);function pickRawResultFromPayload(e){if(void 0!==e.rawResult)return e.rawResult;if(void 0!==e.result)return e.result;if(void 0!==e.details)return e.details;if(void 0!==e.toolResult)return e.toolResult;if(isPlainRecord(e.channelData)){const t=e.channelData;if(void 0!==t.rawResult)return t.rawResult;if(void 0!==t.result)return t.result;if(void 0!==t.details)return t.details}}function asToolParams(e){if(e&&"object"==typeof e&&!Array.isArray(e))return e}const summarizeObservedToolError=e=>{if(null==e)return;if("string"==typeof e)return e.slice(0,180);if("object"!=typeof e)return String(e).slice(0,180);const t=e;for(const e of["error","message","blockReason","details","text"]){const r=t[e];if("string"==typeof r&&r.trim())return r.slice(0,180);if(isPlainRecord(r)&&"string"==typeof r.message&&r.message.trim())return r.message.slice(0,180)}try{const t=JSON.stringify(e);return t?t.slice(0,180):void 0}catch{return}};export function createImReplySink(e){const t=e.startedAtMs??Date.now();let r=!1;const s=new Map,n=new Set,o={text:""};let a="",i="",l=!1,d=!1;const u=new Set;let m;const c={receivedSnapshotCount:0,streamingPublishCount:0,terminalPublishCount:0},g=[];let p;const f=new Map,h=new Map,v=[],_=[],y=new Map,b=new Map;let I=0;const S=new Map;let q=1;const x=(e,t={})=>({schema_version:1,seq:e,...t}),$=new Set,w=new Set,P=t=>{t!==o.text&&(t.startsWith(o.text)?e.stream.appendBody(t.slice(o.text.length)):e.stream.setBody(t),o.text=t)},T=e=>{void 0===e.publishTimer&&(e.publishTimer=setTimeout(()=>{e.publishTimer=void 0,ue("body_preview_flush",()=>{m===e&&(e=>{o.text!==e.targetBody&&(P(e.targetBody),e.streamingPublishCount+=1)})(e)})},200))},k=e=>{const t=m;t?(void 0!==t.publishTimer&&(clearTimeout(t.publishTimer),t.publishTimer=void 0),t.targetBody=e,o.text!==e&&(P(e),t.terminalPublishCount+=1),c.receivedSnapshotCount+=t.receivedSnapshotCount,c.streamingPublishCount+=t.streamingPublishCount,c.terminalPublishCount+=t.terminalPublishCount,m=void 0):P(e)},E=t=>{if(void 0!==t.partIndex)return;const r=I,s=q;e.stream.addPart(toMessagePart({type:"text",text:t.text,state:"done",_seq:s,data:x(s)})),t.partIndex=r,I+=1,q+=1},C=()=>{if(!d){d=!0;for(const e of g)E(e)}},M=e=>{const t={text:e};g.push(t),d&&E(t)},R=(t,r)=>{for(const s of t){const t=b.get(s.url);if(t){const r=mergeSearchSource(t,s);if(r.title===t.title&&r.snippet===t.snippet)continue;const n={...r,partIndex:t.partIndex,displaySeq:t.displaySeq,toolUseId:t.toolUseId};e.stream.replacePart(t.partIndex,toMessagePart({type:"source",url:n.url,...n.title?{title:n.title}:{},...n.snippet?{snippet:n.snippet}:{},tool_use_id:n.toolUseId,_seq:n.displaySeq,data:x(n.displaySeq)})),b.set(s.url,n);continue}const n={...s,partIndex:I,displaySeq:q,toolUseId:r};e.stream.addPart(toMessagePart({type:"source",url:s.url,...s.title?{title:s.title}:{},...s.snippet?{snippet:s.snippet}:{},tool_use_id:r,_seq:n.displaySeq,data:x(n.displaySeq)})),b.set(s.url,n),I+=1,q+=1,ie.source+=1}},O=(e,t,r,s)=>toMessagePart({type:"thinking",text:t,state:r,_seq:e.displaySeq,_started_at_ms:e.startedAtMs,...void 0!==s?{_duration_ms:s}:{},data:x(e.displaySeq,{started_at_ms:e.startedAtMs,...void 0!==s?{duration_ms:s}:{}})}),A=t=>{C();const r={partIndex:I,displaySeq:q,text:t,publishedText:t,receivedSnapshotCount:1,streamingPublishCount:1,startedAtMs:Date.now(),startedAtMonotonicMs:performance.now()};return e.stream.addPart(O(r,t,"streaming")),I+=1,q+=1,p=r,r},N=t=>{void 0===t.publishTimer&&(t.publishTimer=setTimeout(()=>{t.publishTimer=void 0,ue("reasoning_snapshot_flush",()=>{p===t&&(t=>{t.publishedText!==t.text&&(e.stream.replacePart(t.partIndex,O(t,t.text,"streaming")),t.publishedText=t.text,t.streamingPublishCount+=1)})(t)})},200))},U=()=>{const r=p;if(!r)return;void 0!==r.publishTimer&&(clearTimeout(r.publishTimer),r.publishTimer=void 0);const s=Math.max(0,Math.round(performance.now()-r.startedAtMonotonicMs));e.stream.replacePart(r.partIndex,O(r,r.text,"done",s)),p=void 0,logChatLatency(e.logger,"claw.reasoning.settled",e.requestId,t,{reasoning_duration_ms:s,reasoning_chars:r.text.length,reasoning_snapshot_count:r.receivedSnapshotCount,reasoning_streaming_publish_count:r.streamingPublishCount,reasoning_coalesced_snapshot_count:Math.max(0,r.receivedSnapshotCount-r.streamingPublishCount),reasoning_publish_interval_ms:200})},j=e=>{const t=v.indexOf(e);t>=0&&v.splice(t,1)},L=e=>{const t=e?v.filter(t=>f.get(t)?.name===e):v;return 1===t.length?t[0]:void 0},B=e=>{const t=_.map((e,t)=>({hint:e,index:t})).filter(({hint:t})=>!e||t.name===e);if(1!==t.length)return;const[{hint:r,index:s}]=t;return _.splice(s,1),r},F=(e,t)=>{if(h.set(e,t),e===t)return;const r=y.get(e);if(!r)return;const s=Q(t);J(s,r),y.delete(e);const n=f.get(t);n&&(Z(n,s),y.delete(t))},z=e=>h.get(e)??e,D=e=>null!=e&&("object"!=typeof e||(Array.isArray(e)?e.length>0:Object.keys(e).length>0)),Q=e=>{let t=y.get(e);return t||(t={},y.set(e,t)),t},W=(e,t)=>{if(!e?.length&&!t?.length)return;const r=[],s=new Map;for(const n of[...e??[],...t??[]]){const e=s.get(n.url);void 0===e?(s.set(n.url,r.length),r.push(n)):r[e]=mergeSearchSource(r[e],n)}return r},J=(e,t)=>{e.name??=t.name,e.arguments??=t.arguments,t.toolStartObserved&&(e.toolStartObserved=!0),t.itemEventObserved&&(e.itemEventObserved=!0),t.progress?.length&&(e.progress=[...e.progress??[],...t.progress]),e.sources=W(e.sources,t.sources)},H=(t,r,s)=>{const n="tool"===t.name&&"tool"!==r?r:t.name,o=!D(t.arguments)&&D(s)?s:t.arguments;n===t.name&&o===t.arguments||(e.stream.replacePart(t.partIndex,toMessagePart({type:"tool_use",id:t.id,name:n,arguments:o,state:t.state,_seq:t.displaySeq,data:x(t.displaySeq)})),t.name=n,t.arguments=o)},K=(t,r,s,n)=>{const o=f.get(t);if(o)return H(o,r,s),n&&!v.includes(t)&&"streaming"===o.state&&v.push(t),o;C();const a=y.get(t),i="tool"!==r?r:a?.name&&"tool"!==a.name?a.name:r,l=D(s)?s:a?.arguments??s,d=((t,r,s)=>{const n=I,o=q;return e.stream.addPart(toMessagePart({type:"tool_use",id:t,name:r,arguments:s,state:"streaming",_seq:o,data:x(o)})),I+=1,q+=1,{partIndex:n,displaySeq:o}})(t,i,l),u={id:t,name:i,arguments:l,partIndex:d.partIndex,displaySeq:d.displaySeq,state:"streaming",itemEventObserved:!0===a?.itemEventObserved,toolStartObserved:!0===a?.toolStartObserved};return f.set(t,u),(n||u.toolStartObserved||u.itemEventObserved)&&(v.includes(t)||"streaming"!==u.state||v.push(t)),a&&Z(u,a),y.delete(t),u},G=(e,t)=>{const r=(e=>{const t=h.get(e);return t?f.get(t):f.get(e)})(e);if(r)return void 0===t.name&&void 0===t.arguments||H(r,t.name??r.name,t.arguments??r.arguments),t.toolStartObserved&&(r.toolStartObserved=!0),t.itemEventObserved&&(r.itemEventObserved=!0),(t.pending||t.toolStartObserved||t.itemEventObserved)&&!v.includes(r.id)&&"streaming"===r.state&&v.push(r.id),r;const s=Q(e);void 0!==t.name&&(s.name=t.name),void 0!==t.arguments&&(s.arguments=t.arguments),t.toolStartObserved&&(s.toolStartObserved=!0),t.itemEventObserved&&(s.itemEventObserved=!0)},V=t=>{"done"!==t.state&&(e.stream.replacePart(t.partIndex,toMessagePart({type:"tool_use",id:t.id,name:t.name,arguments:t.arguments,state:"done",_seq:t.displaySeq,data:x(t.displaySeq)})),t.state="done")},X=e=>{if(null===e||"object"!=typeof e)return JSON.stringify(e)??String(e);if(Array.isArray(e))return`[${e.map(X).join(",")}]`;return`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${X(t)}`).join(",")}}`},Y=(t,r,s)=>{const n=`${s?"1":"0"}:${X(r)}`;if(t.progressSignature===n)return;const o=toMessagePart({type:"custom",kind:"tool_progress",data:{tool_use_id:t.id,content:r,...s?{is_error:!0}:{}}});if(void 0===t.progressPartIndex){const r=I;return e.stream.addPart(o),t.progressPartIndex=r,t.progressSignature=n,void(I+=1)}e.stream.replacePart(t.progressPartIndex,o),t.progressSignature=n},Z=(e,t)=>{if(t.progress?.length){for(const r of t.progress)Y(e,r.content,r.isError);V(e),j(e.id)}t.sources?.length&&R(t.sources,e.id)},ee=e=>[...new Set([e.mediaUrl,...e.mediaUrls??[]].filter(e=>isNonEmptyString(e)).map(e=>e.trim()).filter(Boolean))],te=(e,t=[])=>{const r=[...new Set([...ee(e),...t])];return isNonEmptyString(e.text)&&r.length>0?{text:e.text,media_urls:r}:isNonEmptyString(e.text)?e.text:1===r.length?r[0]:r.length>1?{media_urls:r}:!0===e.isError?"Tool execution failed.":""},re=t=>{for(const r of t)e.stream.addPart(toMessagePart({type:"resource_link",uri:r.uri,name:r.name,...r.mimeType?{mimeType:r.mimeType}:{}})),I+=1},se=e=>{$.add(e),e.finally(()=>{$.delete(e)})},ne=(t,r)=>{if(t.durableUploadFilesEmitted)return;e.logger.info?.(`[im-sink] schedule tool artifact enrichment requestId=${e.requestId} toolUseId=${t.id} name=${t.name}`);const s=pickRawResultFromPayload(r),n=(async()=>{let n=[];try{n=await resolveToolArtifactLinks({toolCallId:t.id,toolName:t.name,rawResult:s,rawText:"string"==typeof r.text?r.text:void 0,params:asToolParams(t.arguments),cwd:sessionWorkspaceDir(e.sessionKey),payloadMediaUrls:ee(r)})}catch(r){const s=r instanceof Error?r.message:String(r);return void e.logger.warn?.(`[im-sink] resolveToolArtifactLinks failed requestId=${e.requestId} toolUseId=${t.id} error=${s}`)}0!==n.length?(e.logger.info?.(`[im-sink] tool artifact enrichment resolved ${n.length} link(s) requestId=${e.requestId} toolUseId=${t.id}`),await new Promise(s=>{e.callbackQueue.enqueueSync(()=>{try{if(e.abortSignal.aborted||e.stream.isTerminated)return;const s=n.map(e=>e.uri);Y(t,te(r,s),!0===r.isError),((t,r,s)=>{0===r.length||t.durableUploadFilesEmitted||(t.durableUploadFilesEmitted=!0,e.stream.appendToolResult(t.id,r.map(e=>({type:"resource_link",uri:e.uri,name:e.name,...e.mimeType?{mimeType:e.mimeType}:{}})),s),I+=1,re(r))})(t,n,!0===r.isError)}catch(r){const s=r instanceof Error?r.message:String(r);e.logger.warn?.(`[im-sink] tool artifact enrichment apply failed requestId=${e.requestId} toolUseId=${t.id} error=${s}`)}finally{s()}})})):e.logger.debug?.(`[im-sink] tool artifact enrichment found no links requestId=${e.requestId} toolUseId=${t.id} name=${t.name}`)})().catch(r=>{const s=r instanceof Error?r.message:String(r);e.logger.warn?.(`[im-sink] tool artifact enrichment failed requestId=${e.requestId} toolUseId=${t.id} error=${s}`)});se(n)},oe=(e,t,r)=>{const s=h.get(e);if(s)return G(s,{name:t,arguments:r});const n=G(e,{name:t,arguments:r});if(n)return n;const o=L(t);if(o)return F(e,o),G(o,{name:t,arguments:r});G(e,{name:t,arguments:r})},ae=(e,t)=>{const r=h.get(e);if(r)return G(r,{name:t,itemEventObserved:!0,pending:!0});const s=G(e,{name:t,itemEventObserved:!0,pending:!0});if(s)return s;const n=(e=>{const t=v.filter(t=>{const r=f.get(t);return!(void 0===r||e&&r.name!==e||r.itemEventObserved)});return 1===t.length?t[0]:void 0})(t);if(n)return F(e,n),G(n,{name:t,itemEventObserved:!0,pending:!0});const o=B(t);G(e,{name:t,arguments:o?.arguments,itemEventObserved:!0,pending:!0})},ie={tool:0,block:0,final:0,source:0};let le,de=!1;const ue=(t,r)=>{e.callbackQueue.enqueueSync(()=>{if((t=>e.abortSignal.aborted?(e.logger.debug?.(`[im-sink] ${t} ignored after abort requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`),!1):e.stream.isTerminated?(e.logger.debug?.(`[im-sink] ${t} ignored after stream_terminated requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`),!1):!de||(e.logger.debug?.(`[im-sink] ${t} ignored after mark_complete requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`),!1))(t))try{r()}catch(r){const s=r instanceof Error?r.message:String(r);e.logger.warn?.(`[im-sink] ${t} mapping failed requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId} error=${s}`)}})};return{dispatcher:{sendToolResult:t=>(ue("tool_progress",()=>{const r=resolveRuntimeToolCallId(t),s=resolveRuntimeToolName(t),n=resolveRuntimeToolArguments(t),o=te(t),a=!0===t.isError;let i;if(r){if(i=oe(r,s,n),!i){const e=Q(r);return s&&(e.name=s),D(n)&&(e.arguments=n),e.progress=[...e.progress??[],{content:o,isError:a}],void(ie.tool+=1)}}else{const t=s?L(s):L();if(!t)return B(s),void e.logger.debug?.(`[im-sink] unattributed tool progress ignored requestId=${e.requestId} channel=${e.channelId} tool=${s??"unknown"} pending=${v.length}`);i=G(t,{name:s,arguments:n})}i&&(ie.tool+=1,Y(i,o,a),V(i),j(i.id),ne(i,t))}),!0),sendBlockReply:e=>(ue("block_reply",()=>{ie.block+=1,isNonEmptyString(e.text)&&(le=!0!==e.isError?void 0:e.text)}),!0),sendFinalReply:t=>(ue("final_reply",()=>{var r;(ie.final+=1,!0!==t.isError)?((t=>{const r=ee(t).filter(e=>!w.has(e));if(0===r.length)return;for(const e of r)w.add(e);const s=(async()=>{let t=[];try{t=await resolveToolArtifactLinks({toolCallId:`final:${e.runId??e.requestId}`,toolName:"final_reply_media",payloadMediaUrls:r})}catch(t){for(const e of r)w.delete(e);return void e.logger.warn?.(`[im-sink] final media enrichment failed requestId=${e.requestId} error=${t instanceof Error?t.message:String(t)}`)}if(0!==t.length)await new Promise(r=>{e.callbackQueue.enqueueSync(()=>{try{if(e.abortSignal.aborted||e.stream.isTerminated)return;re(t)}catch(t){e.logger.warn?.(`[im-sink] final media enrichment apply failed requestId=${e.requestId} error=${t instanceof Error?t.message:String(t)}`)}finally{r()}})});else for(const e of r)w.delete(e)})();se(s)})(t),isNonEmptyString(t.text)&&(le=void 0,l||(r=t.text,i="",a+=r,k(a),M(r),l=!0))):le=t.text}),!0),waitForIdle:async()=>{for(let t=0;t<16&&(await e.callbackQueue.waitForIdle(),0!==$.size);t++)await Promise.allSettled([...$]);await e.callbackQueue.waitForIdle();const t=takeFinalizeAttachments(e.sessionKey);t.length>0&&!e.abortSignal.aborted&&!e.stream.isTerminated&&re(t)},getQueuedCounts:()=>({tool:ie.tool,block:ie.block,final:ie.final}),getAccumulatedBody:()=>o.text,getTerminalErrorText:()=>le,markComplete:r=>{U(),(_.length>0||y.size>0)&&e.logger.debug?.(`[im-sink] dropping uncommitted lifecycle tool signals requestId=${e.requestId} legacy_hints=${_.length} buffered=${y.size}`),i="",k(a),c.receivedSnapshotCount>0&&logChatLatency(e.logger,"claw.text_preview.settled",e.requestId,t,{text_preview_snapshot_count:c.receivedSnapshotCount,text_preview_streaming_publish_count:c.streamingPublishCount,text_preview_terminal_publish_count:c.terminalPublishCount,text_preview_coalesced_snapshot_count:Math.max(0,c.receivedSnapshotCount-c.streamingPublishCount-c.terminalPublishCount),text_preview_publish_interval_ms:200});for(const t of f.values())try{"success"===r&&isUploadArtifactToolName(t.name)&&!t.durableUploadFilesEmitted&&ne(t,{toolCallId:t.id,toolName:t.name}),"success"===r&&V(t),j(t.id)}catch(r){const s=r instanceof Error?r.message:String(r);e.logger.warn?.(`[im-sink] tool finalization failed requestId=${e.requestId} toolUseId=${t.id} error=${s}`)}_.length=0,y.clear(),de=!0}},replyOptions:{...e.runId?{runId:e.runId}:{},abortSignal:e.abortSignal,disableBlockStreaming:!0,onAgentRunStart:r=>{e.onAgentRunStart?.(r),logChatLatency(e.logger,"claw.runtime.run_started",e.requestId,t),e.logger.info?.(`[im-sink] run_start requestId=${e.requestId} runId=${r} channel=${e.channelId} in_reply_to=${e.inboundMessageId} origin=${e.origin??"im"}`)},onPartialReply:s=>{ue("partial",()=>{"string"==typeof s.text&&(!r&&s.text.length>0&&(r=!0,logChatLatency(e.logger,"claw.model.first_delta",e.requestId,t)),i=s.text,(e=>{const t=m;if(!t){if(o.text===e)return;return P(e),void(m={targetBody:e,receivedSnapshotCount:1,streamingPublishCount:1,terminalPublishCount:0})}t.targetBody!==e&&(t.targetBody=e,t.receivedSnapshotCount+=1,T(t))})(a+i))})},onReasoningStream:e=>{ue("reasoning",()=>{if(!isNonEmptyString(e.text))return;const t=e.text,r=p??A(t);t!==r.text&&(r.text.startsWith(t)||(t.startsWith(r.text)?(r.text=t,r.receivedSnapshotCount+=1,N(r)):(U(),A(t))))})},onReasoningEnd:()=>{ue("reasoning_end",()=>{U()})},onAssistantMessageStart:()=>{ue("assistant_message_start",()=>{i="",l=!1,k(a),e.logger.debug?.(`[im-sink] assistant_message_start requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`)})},onToolStart:r=>{ue("tool_start",()=>{const n="string"==typeof r.phase?r.phase:"start",o=resolveRuntimeToolName(r)??"tool",a=resolveRuntimeToolCallId(r),i=resolveRuntimeToolArguments(r);if("update"===n)return void(a&&G(z(a),{name:o,arguments:i,pending:!0}));if(a&&e.onQuestionToolStart?.(o,a),a&&s.set(a,Date.now()),logChatLatency(e.logger,"claw.tool.start",e.requestId,t,{tool:o}),a){G(a,{name:o,arguments:i,toolStartObserved:!0,pending:!0});const e=L(o);return void(e&&e!==a&&!h.has(a)&&(F(a,e),G(e,{name:o,arguments:i,toolStartObserved:!0,pending:!0})))}const l=(d=o,v.map(e=>f.get(e)).filter(e=>void 0!==e&&(!d||e.name===d)&&e.itemEventObserved));var d;if(1===l.length)return void G(l[0].id,{name:o,arguments:i,toolStartObserved:!0,pending:!0});if(l.length>1)return void e.logger.debug?.(`[im-sink] ambiguous id-less tool start ignored requestId=${e.requestId} channel=${e.channelId} tool=${o} candidates=${l.length}`);const u=[...y.entries()].filter(([,e])=>!e.name||e.name===o||"tool"===e.name);1!==u.length?_.push({name:o,arguments:i}):G(u[0][0],{name:o,arguments:i,toolStartObserved:!0,pending:!0})})},onItemEvent:e=>{ue("item_event",()=>{const t="string"==typeof e.kind?e.kind.toLowerCase():"";if(t&&"tool"!==t)return;const r="string"==typeof e.phase?e.phase.toLowerCase():"update",s=resolveRuntimeToolCallId(e)??("string"==typeof e.itemId&&e.itemId.trim()?e.itemId.trim():void 0),n=resolveRuntimeToolName(e)??("string"==typeof e.title&&e.title.trim()?e.title.trim():void 0);s&&n&&("update"!==r?ae(s,n):G(z(s),{name:n,itemEventObserved:!0,pending:!0}))})}},commitAssistantMessage:e=>{ue("assistant_message_commit",()=>{if(u.has(e.key))return;u.add(e.key),l=!0,le=void 0,i="";const t=e.segments.filter(e=>"text"===e.type).map(e=>e.text).join("");a+=t,k(a);for(const t of e.segments)"text"!==t.type?K(t.id,t.name,t.arguments,!0):M(t.text)})},projectUserInputStatus:t=>ue("user_input_status",()=>{const r=t.response_message_id??t.submission_message_id,s="string"==typeof r&&["accepted","cancelled","rejected","unconfirmed"].includes(String(t.status)),n=["accepted","cancelled","expired","answered_elsewhere","unavailable","unsupported"].includes(String(t.status))||"answered"===t.native_status||"cancelled"===t.native_status,o="string"==typeof t.request_id?S.get(t.request_id):void 0;s&&n&&o&&e.stream.replacePart(o.index,toMessagePart({type:"custom",_seq:o.seq,kind:"question_wait",data:{...x(o.seq),request_id:t.request_id,status:t.status,observed_at_ms:t.updated_at_ms},value:{...t,type:"user_input_resolution"}}));const a=s?`receipt:${r}`:t.request_id;if("string"!=typeof a||!a)return;C();let i=S.get(a);const l=!i;i||(i={index:I++,seq:q++},S.set(a,i));const d=toMessagePart({type:"custom",_seq:i.seq,kind:s?"message_processing_receipt":"question_wait",data:{...x(i.seq),request_id:t.request_id,status:s&&"cancelled"===t.status?"accepted":t.status,observed_at_ms:t.updated_at_ms,...s?{response_message_id:r,..."cancelled"===t.status?{outcome:"cancelled"}:{}}:{},...t.error_code?{error_code:t.error_code}:{}},value:{...t,type:n?"user_input_resolution":"user_input_wait"}});l?e.stream.addPart(d):e.stream.replacePart(i.index,d)}),observeToolResult:r=>{ue("tool_result_observation",()=>{const o=r.toolCallId.trim(),a=r.toolName.trim();if(!o||!a)return;if(!n.has(o)){n.add(o);const i=s.get(o);logChatLatency(e.logger,"claw.tool.result",e.requestId,t,{tool:a,tool_elapsed_ms:void 0===i?void 0:Math.max(0,Date.now()-i),outcome:r.isError?"error":"success",...r.isError?{error:summarizeObservedToolError(r.rawResult)??"error"}:{}})}const i=searchSourceProvider(r.rawResult)??"unknown";let l=0;try{const t=extractSearchSources({toolName:a,rawResult:r.rawResult,isError:r.isError});if(l=t.length,0===l)return;const s=oe(o,a);if(s)R(t,s.id);else{const e=Q(z(o));e.name??=a,e.sources=W(e.sources,t)}e.logger.debug?.(`[im-sink] search source projection requestId=${e.requestId} tool=${a} provider=${i} source_count=${l}`)}catch{e.logger.warn?.(`[im-sink] search source projection ignored requestId=${e.requestId} tool=${a} provider=${i} source_count=${l}`)}})},getSourceCount:()=>ie.source}}
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";import{RUNTIME_ERROR_DESCRIPTORS,RUNTIME_HASH_DOMAINS,runtimeHashPreimage}from"@beeos-ai/beeos-types/runtime";import{MessageServiceRuntimeClaimHttpAuthority}from"./message-service-runtime-claim-authority.js";const QUERY_METHODS=new Set(["skills/list","models/list","cron/list","cron/status","cron/runs","mcp/list"]),PROJECTION_METHODS=new Set(["agent/create","agent/update","agent/delete","agent/applyTemplate","session/set_model"]);export class MessageServiceRuntimeInvocationHttpAuthority{deps;constructor(e){this.deps=e}claimNext=e=>this.claimAuthority().claimNext(e);claimExact=e=>this.claimAuthority().claimExact(e);renewClaim=e=>this.claimAuthority().renewClaim(e);releaseClaim=e=>this.claimAuthority().releaseClaim(e);authorize=e=>this.deps.authorization.authorize(e);async appendStarted(e){await this.append(e,"runtime_operation_started",{claimedAt:this.now(),leaseExpiresAt:e.claimLeaseExpiresAt,executionMode:e.attempt.executionMode,executionBoundaryId:e.attempt.executionBoundaryId,boundaryAssertionHash:e.attempt.boundaryAssertionHash,...e.attempt.handoffId?{handoffId:e.attempt.handoffId}:{}})}async appendProgress(e){await this.append(e,"runtime_operation_progress",{executionBoundaryId:e.attempt.executionBoundaryId,phase:e.progress.phase,...void 0===e.progress.current?{}:{current:e.progress.current},...void 0===e.progress.total?{}:{total:e.progress.total}})}async commitResult(e){const t=e.request.payload.request.method;if(PROJECTION_METHODS.has(t))throw new Error(`projection-required runtime method is not enabled by this authority: ${t}`);const o=this.now(),a=e.result,s=hash(RUNTIME_HASH_DOMAINS.serviceResult,{method:t,result:a});let r;if(!QUERY_METHODS.has(t)){const s=hash(RUNTIME_HASH_DOMAINS.coreResult,{method:t,result:a}),n={schemaVersion:1,operationId:e.operationId,method:t,coreResultRef:`sha256:${s}`,coreResultHash:s},i={schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,method:t,commandHash:e.request.payload.commandHash,executionBoundaryId:e.attempt.executionBoundaryId,boundaryAssertionHash:e.attempt.boundaryAssertionHash,fence:e.fence,journalRevision:"3",coreResultHash:s,effectRecordHash:hash(RUNTIME_HASH_DOMAINS.effectRecord,n),projection:{state:"not_required"},committedAt:o};r=hash(RUNTIME_HASH_DOMAINS.effectReceipt,i),await this.append(e,"runtime_effect_committed",{executionBoundaryId:e.attempt.executionBoundaryId,committedAt:o,effectReceipt:i,effectReceiptHash:r})}const n={schemaVersion:1,operationId:e.operationId,method:t,outcome:"succeeded",serviceResultRef:`sha256:${s}`,serviceResultHash:s},i={schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,method:t,commandHash:e.request.payload.commandHash,executionBoundaryId:e.attempt.executionBoundaryId,boundaryAssertionHash:e.attempt.boundaryAssertionHash,fence:e.fence,journalRevision:"3",terminalRecordHash:hash(RUNTIME_HASH_DOMAINS.terminalRecord,n),completedAt:o,outcome:"succeeded",serviceResultHash:s,...r?{effectReceiptHash:r}:{}};await this.appendTerminal(e,i,{outcome:"succeeded",response:{jsonrpc:"2.0",id:e.request.payload.request.id,result:a},serviceResultHash:s,terminalAuthority:r?{kind:"effect_receipt",effectReceiptHash:r}:{kind:"query_execution",executionBoundaryId:e.attempt.executionBoundaryId,boundaryAssertionHash:e.attempt.boundaryAssertionHash},completedAt:o})}async commitFailure(e){const t=e.request.payload.request.method,o=this.now(),a=normalizeErrorCode(e.outcome,e.code),s=RUNTIME_ERROR_DESCRIPTORS[a],r="outcome_unknown"===e.outcome?"outcome_unknown":"cancelled"===e.outcome?"cancelled":"expired"===e.outcome?"expired":"failed",n={code:s.jsonRpcCode,message:a,data:{code:a,operationId:e.operationId,effectState:r,retryMode:s.retryMode}},i=hash(RUNTIME_HASH_DOMAINS.terminalRecord,{operationId:e.operationId,method:t,outcome:e.outcome,code:a}),c="outcome_unknown"===e.outcome?{schemaVersion:1,operationId:e.operationId,method:t,outcome:e.outcome,uncertaintyRef:`sha256:${i}`,uncertaintyHash:i}:{schemaVersion:1,operationId:e.operationId,method:t,outcome:e.outcome,errorRef:`sha256:${i}`,errorHash:i},d={schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,method:t,commandHash:e.request.payload.commandHash,executionBoundaryId:e.attempt.executionBoundaryId,boundaryAssertionHash:e.attempt.boundaryAssertionHash,fence:e.fence,journalRevision:"2",terminalRecordHash:hash(RUNTIME_HASH_DOMAINS.terminalRecord,c),completedAt:o},u="outcome_unknown"===e.outcome?{...d,outcome:"outcome_unknown",uncertaintyHash:i}:{...d,outcome:e.outcome,noEffect:!0,errorHash:i},m={jsonrpc:"2.0",id:e.request.payload.request.id,error:n},p=terminalFailurePayload(e.outcome,o,m,e.attempt.executionBoundaryId,e.attempt.boundaryAssertionHash);await this.appendTerminal(e,u,p)}claimAuthority(){return new MessageServiceRuntimeClaimHttpAuthority({messageServiceUrl:this.deps.messageServiceUrl,fetchAuthorized:(e,t)=>this.deps.fetchMessageService(e,t)})}async append(e,t,o){await this.post(e.operationId,{schemaVersion:1,type:t,operationId:e.operationId,conversationId:e.operationId,requestMessageId:e.requestMessageId,dispatchEpoch:e.request.payload.command.context.dispatchEpoch,fence:e.fence,payload:o})}async appendTerminal(e,t,o){await this.post(e.operationId,{schemaVersion:1,type:"runtime_rpc_response",operationId:e.operationId,conversationId:e.operationId,requestMessageId:e.requestMessageId,dispatchEpoch:e.request.payload.command.context.dispatchEpoch,fence:e.fence,payload:o,replyTo:e.requestMessageId,terminalReceipt:t,terminalReceiptHash:hash(RUNTIME_HASH_DOMAINS.terminalReceipt,t)})}async post(e,t){const o=await this.deps.fetchMessageService(new URL(`/api/v1/runtime/operations/${encodeURIComponent(e)}/events`,this.deps.messageServiceUrl),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(201!==o.status)throw new Error(`Message Service runtime event append failed (${o.status})`)}now(){return(this.deps.now??(()=>new Date))().toISOString()}}function hash(e,t){return createHash("sha256").update(runtimeHashPreimage(e,t)).digest("hex")}function normalizeErrorCode(e,t){return"outcome_unknown"===e?"OUTCOME_UNKNOWN":"cancelled"===e?"OPERATION_CANCELLED":"expired"===e?"COMMAND_EXPIRED":t in RUNTIME_ERROR_DESCRIPTORS?t:"RUNTIME_EXECUTION_FAILED"}function terminalFailurePayload(e,t,o,a,s){if("outcome_unknown"===e)return{outcome:e,response:o,terminalAuthority:{kind:"uncertain_effect",executionBoundaryId:a,boundaryAssertionHash:s},completedAt:t};const r={kind:"definitive_no_effect",journalPhase:"prepared",observedAt:t};return"cancelled"===e?{outcome:e,response:o,cancellationEvidence:r,completedAt:t}:"expired"===e?{outcome:e,response:o,expirationEvidence:r,completedAt:t}:{outcome:e,response:o,failureEvidence:r,completedAt:t}}
1
+ import{createHash}from"node:crypto";import{RUNTIME_ERROR_DESCRIPTORS,RUNTIME_HASH_DOMAINS,runtimeHashPreimage}from"@beeos-ai/beeos-types/runtime";import{MessageServiceRuntimeClaimHttpAuthority}from"./message-service-runtime-claim-authority.js";const QUERY_METHODS=new Set(["skills/list","models/list","cron/list","cron/status","cron/runs","mcp/list"]),PROJECTION_METHODS=new Set(["agent/create","agent/update","agent/delete","agent/applyTemplate","session/set_model","session/set_reasoning"]);export class MessageServiceRuntimeInvocationHttpAuthority{deps;constructor(e){this.deps=e}claimNext=e=>this.claimAuthority().claimNext(e);claimExact=e=>this.claimAuthority().claimExact(e);renewClaim=e=>this.claimAuthority().renewClaim(e);releaseClaim=e=>this.claimAuthority().releaseClaim(e);authorize=e=>this.deps.authorization.authorize(e);async appendStarted(e){await this.append(e,"runtime_operation_started",{claimedAt:this.now(),leaseExpiresAt:e.claimLeaseExpiresAt,executionMode:e.attempt.executionMode,executionBoundaryId:e.attempt.executionBoundaryId,boundaryAssertionHash:e.attempt.boundaryAssertionHash,...e.attempt.handoffId?{handoffId:e.attempt.handoffId}:{}})}async appendProgress(e){await this.append(e,"runtime_operation_progress",{executionBoundaryId:e.attempt.executionBoundaryId,phase:e.progress.phase,...void 0===e.progress.current?{}:{current:e.progress.current},...void 0===e.progress.total?{}:{total:e.progress.total}})}async commitResult(e){const t=e.request.payload.request.method;if(PROJECTION_METHODS.has(t))throw new Error(`projection-required runtime method is not enabled by this authority: ${t}`);const o=this.now(),a=e.result,s=hash(RUNTIME_HASH_DOMAINS.serviceResult,{method:t,result:a});let r;if(!QUERY_METHODS.has(t)){const s=hash(RUNTIME_HASH_DOMAINS.coreResult,{method:t,result:a}),n={schemaVersion:1,operationId:e.operationId,method:t,coreResultRef:`sha256:${s}`,coreResultHash:s},i={schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,method:t,commandHash:e.request.payload.commandHash,executionBoundaryId:e.attempt.executionBoundaryId,boundaryAssertionHash:e.attempt.boundaryAssertionHash,fence:e.fence,journalRevision:"3",coreResultHash:s,effectRecordHash:hash(RUNTIME_HASH_DOMAINS.effectRecord,n),projection:{state:"not_required"},committedAt:o};r=hash(RUNTIME_HASH_DOMAINS.effectReceipt,i),await this.append(e,"runtime_effect_committed",{executionBoundaryId:e.attempt.executionBoundaryId,committedAt:o,effectReceipt:i,effectReceiptHash:r})}const n={schemaVersion:1,operationId:e.operationId,method:t,outcome:"succeeded",serviceResultRef:`sha256:${s}`,serviceResultHash:s},i={schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,method:t,commandHash:e.request.payload.commandHash,executionBoundaryId:e.attempt.executionBoundaryId,boundaryAssertionHash:e.attempt.boundaryAssertionHash,fence:e.fence,journalRevision:"3",terminalRecordHash:hash(RUNTIME_HASH_DOMAINS.terminalRecord,n),completedAt:o,outcome:"succeeded",serviceResultHash:s,...r?{effectReceiptHash:r}:{}};await this.appendTerminal(e,i,{outcome:"succeeded",response:{jsonrpc:"2.0",id:e.request.payload.request.id,result:a},serviceResultHash:s,terminalAuthority:r?{kind:"effect_receipt",effectReceiptHash:r}:{kind:"query_execution",executionBoundaryId:e.attempt.executionBoundaryId,boundaryAssertionHash:e.attempt.boundaryAssertionHash},completedAt:o})}async commitFailure(e){const t=e.request.payload.request.method,o=this.now(),a=normalizeErrorCode(e.outcome,e.code),s=RUNTIME_ERROR_DESCRIPTORS[a],r="outcome_unknown"===e.outcome?"outcome_unknown":"cancelled"===e.outcome?"cancelled":"expired"===e.outcome?"expired":"failed",n={code:s.jsonRpcCode,message:a,data:{code:a,operationId:e.operationId,effectState:r,retryMode:s.retryMode}},i=hash(RUNTIME_HASH_DOMAINS.terminalRecord,{operationId:e.operationId,method:t,outcome:e.outcome,code:a}),c="outcome_unknown"===e.outcome?{schemaVersion:1,operationId:e.operationId,method:t,outcome:e.outcome,uncertaintyRef:`sha256:${i}`,uncertaintyHash:i}:{schemaVersion:1,operationId:e.operationId,method:t,outcome:e.outcome,errorRef:`sha256:${i}`,errorHash:i},d={schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,method:t,commandHash:e.request.payload.commandHash,executionBoundaryId:e.attempt.executionBoundaryId,boundaryAssertionHash:e.attempt.boundaryAssertionHash,fence:e.fence,journalRevision:"2",terminalRecordHash:hash(RUNTIME_HASH_DOMAINS.terminalRecord,c),completedAt:o},u="outcome_unknown"===e.outcome?{...d,outcome:"outcome_unknown",uncertaintyHash:i}:{...d,outcome:e.outcome,noEffect:!0,errorHash:i},m={jsonrpc:"2.0",id:e.request.payload.request.id,error:n},p=terminalFailurePayload(e.outcome,o,m,e.attempt.executionBoundaryId,e.attempt.boundaryAssertionHash);await this.appendTerminal(e,u,p)}claimAuthority(){return new MessageServiceRuntimeClaimHttpAuthority({messageServiceUrl:this.deps.messageServiceUrl,fetchAuthorized:(e,t)=>this.deps.fetchMessageService(e,t)})}async append(e,t,o){await this.post(e.operationId,{schemaVersion:1,type:t,operationId:e.operationId,conversationId:e.operationId,requestMessageId:e.requestMessageId,dispatchEpoch:e.request.payload.command.context.dispatchEpoch,fence:e.fence,payload:o})}async appendTerminal(e,t,o){await this.post(e.operationId,{schemaVersion:1,type:"runtime_rpc_response",operationId:e.operationId,conversationId:e.operationId,requestMessageId:e.requestMessageId,dispatchEpoch:e.request.payload.command.context.dispatchEpoch,fence:e.fence,payload:o,replyTo:e.requestMessageId,terminalReceipt:t,terminalReceiptHash:hash(RUNTIME_HASH_DOMAINS.terminalReceipt,t)})}async post(e,t){const o=await this.deps.fetchMessageService(new URL(`/api/v1/runtime/operations/${encodeURIComponent(e)}/events`,this.deps.messageServiceUrl),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(201!==o.status)throw new Error(`Message Service runtime event append failed (${o.status})`)}now(){return(this.deps.now??(()=>new Date))().toISOString()}}function hash(e,t){return createHash("sha256").update(runtimeHashPreimage(e,t)).digest("hex")}function normalizeErrorCode(e,t){return"outcome_unknown"===e?"OUTCOME_UNKNOWN":"cancelled"===e?"OPERATION_CANCELLED":"expired"===e?"COMMAND_EXPIRED":t in RUNTIME_ERROR_DESCRIPTORS?t:"RUNTIME_EXECUTION_FAILED"}function terminalFailurePayload(e,t,o,a,s){if("outcome_unknown"===e)return{outcome:e,response:o,terminalAuthority:{kind:"uncertain_effect",executionBoundaryId:a,boundaryAssertionHash:s},completedAt:t};const r={kind:"definitive_no_effect",journalPhase:"prepared",observedAt:t};return"cancelled"===e?{outcome:e,response:o,cancellationEvidence:r,completedAt:t}:"expired"===e?{outcome:e,response:o,expirationEvidence:r,completedAt:t}:{outcome:e,response:o,failureEvidence:r,completedAt:t}}
@@ -0,0 +1 @@
1
+ export async function projectSessionReasoning(e){const n=await e.fetchAuthorized(new URL(`/api/v1/runtime/conversations/${encodeURIComponent(e.conversationId)}/metadata/reasoning`,e.messageServiceUrl),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,requestHash:e.requestHash,runtimeLeaseCredential:e.runtimeLeaseCredential,reasoning:e.reasoning})});if(!n.ok)throw new Error(`Message Service reasoning projection failed: ${n.status}`)}
@@ -1 +1 @@
1
- import{RUNTIME_ERROR_DESCRIPTORS,RUNTIME_HASH_DOMAINS,RUNTIME_INVOCATION_PARITY_ENTRIES,RUNTIME_INVOCATION_RECOVERY_CLASSES,SERVICE_CANONICAL_COMMAND_NAMES,mapCanonicalResultToService}from"@beeos-ai/beeos-types/runtime";import{reduceRuntimeRecoveryPolicy}from"@beeos-ai/beeos-types/runtime/internal";import{verifyAndCreateMessageServiceCoreExecutionAttempt}from"./core-execution-attempt-context.js";import{awaitRuntimeProjection,hasEffectReceiptHandoff,RuntimeCommandError}from"./runtime-command-dispatcher.js";import{createRuntimeAppendTimingRecorder}from"./runtime-append-timing.js";import{runtimeCommandIsReplayableQuery}from"./runtime-command-journal.js";import{RUNTIME_MESSAGE_TYPES,runtimeMessageBase,runtimeMessageHash,semanticEqual,validateRuntimeCancelEnvelope,validateRuntimeRequestEnvelope}from"./runtime-message-channel-contract.js";import{RuntimeResourceResolutionError}from"./runtime-operation-resource-resolver.js";import{RuntimeTransportFailurePolicy}from"./runtime-transport-failure-policy.js";const leaseStarvationReportIntervalMs=3e4;export class MsRuntimeMessageChannelAdapter{dispatcher;channel;verifier;ports;journal;getLease;options;controller;running;externalDeliveryOwner;workers=new Map;poisonJournal;renewTransportFailurePolicy=new RuntimeTransportFailurePolicy;leaseStarvedSince;leaseStarvationReportedAt=0;receiptHistory=this;constructor(e,t,a,o,r,n,i){if(this.dispatcher=e,this.channel=t,this.verifier=a,this.ports=o,this.journal=r,this.getLease=n,this.options=i,!i.poisonJournal)throw new Error("durable poison journal is required");if(this.poisonJournal=i.poisonJournal,!Number.isSafeInteger(i.poisonDeliveryLimit??3)||(i.poisonDeliveryLimit??3)<=0)throw new Error("poison delivery limit must be a positive integer")}start(){if(this.externalDeliveryOwner)return void this.externalDeliveryOwner.start();if(this.running)return;const e=new AbortController;this.controller=e;const t=this.loop(e.signal).catch(t=>{e.signal.aborted||this.observeDeliveryError(t)}).finally(()=>{this.running===t&&(this.running=void 0)});this.running=t}async stop(e){this.controller?.abort();for(const e of this.workers.values())e.cancel?.();if(this.externalDeliveryOwner)return await this.externalDeliveryOwner.stop(e),void await Promise.allSettled([...this.workers.values()].map(e=>e.completion));this.running&&await abortable(this.running,e)}attachExternalDeliveryOwner(e){if(this.running||this.externalDeliveryOwner)throw new Error("runtime delivery owner is already attached");this.externalDeliveryOwner=e}async acceptDelivery(e,t,a){if(this.currentLease(t),e.message.type===RUNTIME_MESSAGE_TYPES.cancel)return void await this.handleCancel(e,t);const o=validateRuntimeRequestEnvelope(e.message),r=o.ok?o.envelope.payload.operationId:e.message.channel_id;if(this.workers.has(r))return;const n={deliveryId:e.deliveryId,claimedLease:t,completion:Promise.resolve()};n.completion=this.handleRequest(e,t,a,e=>{n.cancel=e}).catch(e=>this.observeDeliveryError(e)).finally(()=>{this.workers.delete(r)}),this.workers.set(r,n),await n.completion}async acceptPoisonDelivery(e,t,a){await this.handlePoison(e,t,a)}async readOperationHistory(e){const t=this.getLease();if(!t)return{status:"unavailable"};try{return await this.channel.history({operationId:e.operationId,lease:t})}catch{return{status:"unavailable"}}}async loop(e){let t;(()=>{t||(t=setInterval(()=>{this.renewActive().catch(e=>this.observeDeliveryError(e))},this.options.renewIntervalMs??2e4),t.unref?.())})();try{for(;!e.aborted;){const t=this.getLease();if(!t){this.observeLeaseStarvation(),await delay(this.options.idleDelayMs??500,e);continue}let a;this.observeLeaseRestored();try{a=await this.channel.read({maxCount:this.options.readCount??32,blockMs:this.options.blockMs??5e3,lease:t,signal:e})}catch(t){if(e.aborted)return;this.observeDeliveryError(t),await delay(this.options.idleDelayMs??500,e);continue}for(const o of a){if(e.aborted)break;if(o.message.type===RUNTIME_MESSAGE_TYPES.cancel){await this.handleCancel(o,t).catch(e=>this.observeDeliveryError(e));continue}const a=o.message.channel_id;if(this.workers.has(a))continue;const r={deliveryId:o.deliveryId,claimedLease:t,completion:Promise.resolve()};r.completion=this.handleRequest(o,t,e,e=>{r.cancel=e}).catch(e=>this.observeDeliveryError(e)).finally(()=>{this.workers.delete(a)}),this.workers.set(a,r)}}}finally{t&&clearInterval(t),await Promise.allSettled([...this.workers.values()].map(e=>e.completion))}}observeDeliveryError(e){try{this.options.onDeliveryError?.(e)}catch{}}observeLeaseStarvation(){const e=Date.now();this.leaseStarvedSince??=e;const t=e-this.leaseStarvedSince;if(!(t<3e4||this.leaseStarvationReportedAt&&e-this.leaseStarvationReportedAt<3e4)){this.leaseStarvationReportedAt=e;try{this.options.onLeaseStarvation?.({starvedForMs:t,recovered:!1})}catch{}}}observeLeaseRestored(){const e=this.leaseStarvedSince;if(void 0===e)return;this.leaseStarvedSince=void 0;const t=this.leaseStarvationReportedAt;if(this.leaseStarvationReportedAt=0,t)try{this.options.onLeaseStarvation?.({starvedForMs:Date.now()-e,recovered:!0})}catch{}}observeRequestFailure(e,t,a){try{this.options.onRequestFailure?.({operationId:e,method:t,error:a})}catch{}}async renewActive(){const e=this.getLease();if(!e)return;const t=[];for(const a of this.workers.values())sameLeaseBinding(a.claimedLease,e)?t.push(a.deliveryId):a.cancel?.();if(!t.length)return;let a;try{a=await this.channel.renew({deliveryIds:t,lease:e})}catch(e){if(this.observeDeliveryError(e),this.renewTransportFailurePolicy.recordFailure()){const e=new Set(t);for(const t of this.workers.values())e.has(t.deliveryId)&&t.cancel?.()}return}if(this.renewTransportFailurePolicy.recordSuccess(),a.notPending.length){const e=new Set(a.notPending);for(const t of this.workers.values())e.has(t.deliveryId)&&t.cancel?.()}}async handleCancel(e,t){const a=validateRuntimeCancelEnvelope(e.message);if(!a.ok)return void await this.handlePoison(e,`invalid_cancel:${a.reason}`,t);const o=a.envelope.payload,r=await this.channel.history({operationId:o.operationId,lease:t});if("found"===r.status&&r.snapshot.terminal&&"final_message"===r.snapshot.terminalSource)return void await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t});if("not_found"===r.status||"expired"===r.status)return void await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t});const n=r.snapshot.request.payload;n.operationId===o.operationId&&n.requestMessageId===o.requestMessageId&&n.requestHash===o.requestHash&&n.dispatchEpoch===o.dispatchEpoch&&n.method===o.method?(await this.journal.observeCancellation({operationId:o.operationId,requestMessageId:o.requestMessageId,requestHash:o.requestHash,eventId:o.eventId}),this.workers.get(o.operationId)?.cancel?.(),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t})):await this.handlePoison(e,"cancel_history_mismatch",t)}async handleRequest(e,t,a,o){const r=validateRuntimeRequestEnvelope(e.message);if(!r.ok)return void await this.handlePoison(e,`invalid_request:${r.reason}`,t);const n=r.envelope.payload,i=e.executionGrant,s=createRuntimeAppendTimingRecorder("runtime-op",{operationId:n.operationId,method:n.method}),c=new AbortController;o(()=>c.abort());const d=async()=>{await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),s.mark("ack")},l=await this.channel.history({operationId:n.operationId,lease:t});if(s.mark("history"),"not_found"===l.status||"expired"===l.status)return void await d();if(l.snapshot.terminal&&"final_message"===l.snapshot.terminalSource)return void await d();if(this.options.allowedMethods&&!this.options.allowedMethods.has(n.method))return await this.reject(n,"unsupported_method",t),void await d();if("deadline"===l.snapshot.terminalSource||Date.parse(n.executionDeadlineAt)<=Date.now()||!l.snapshot.started&&Date.parse(n.claimDeadlineAt)<=Date.now())return await this.reject(n,"execution_deadline_exceeded",t),void await d();const p=await this.journal.getCancellation(n.operationId);s.mark("journal-cancel-read");const u=l.snapshot.cancelRequested||null!==p;if(u&&"queued"===l.snapshot.status)return await this.reject(n,"cancelled_before_dispatch",t),void await d();if(n.instanceId!==t.instanceId||n.runtimeHandlerIdentity!==t.handlerIdentity||n.dispatchEpoch!==t.runtimeEpoch)return await this.reject(n,"authority_mismatch",t),void await d();const m=l.snapshot.request.payload;if(l.snapshot.operationId!==n.operationId||l.snapshot.requestMessageId!==n.requestMessageId||l.snapshot.requestHash!==n.requestHash||!semanticEqual(m,n))return void await this.handlePoison(e,"request_history_mismatch",t);const h=l.snapshot.started?.payload,I=void 0!==h&&h.operationId===n.operationId&&h.requestMessageId===n.requestMessageId&&h.requestHash===n.requestHash&&h.executionGrantHash===n.executionGrantHash&&h.handlerIdentity===t.handlerIdentity&&h.dispatchEpoch===t.runtimeEpoch&&h.method===n.method,E=await this.journal.get(n.operationId);s.mark("journal-prior");const v=runtimeCommandIsReplayableQuery(n.command.name),f=v?ephemeralQueryAccept(n):await this.journal.acceptMessageRequest({operationId:n.operationId,command:n.command.name,paramsHash:n.paramsHash,runtimeEpoch:n.dispatchEpoch,requestMessageId:n.requestMessageId,requestHash:n.requestHash});s.mark("journal-accept");const R=I?E:f,y=v?"execute":decideMessageServiceRecovery(l.snapshot,n,R,I);if("already_terminal"===y)return void await d();if(!CORE_RECOVERY_DECISIONS.has(y))return v||await this.markOutcomeUnknownIfMutable(f),await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(n,new RuntimeCommandError("OUTCOME_UNKNOWN",`Types recovery policy requires ${y}; this runtime cannot safely replay Core`),(new Date).toISOString())}),void await d();if(await this.verifier.refresh(),s.mark("verifier-refresh"),!i)return I?await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(n,new RuntimeCommandError("OUTCOME_UNKNOWN","retained started proof has no live execution grant"),(new Date).toISOString())}):await this.reject(n,"invalid_execution_grant",t),void await d();this.verifier.verifyAndDecodeGrant(i)||await this.verifier.refresh(!0);const _=()=>c.abort();let w;a.addEventListener("abort",_,{once:!0});try{w=await verifyAndCreateMessageServiceCoreExecutionAttempt({request:n,executionGrant:i,runtimeEpoch:t.runtimeEpoch,lease:t,verifier:this.verifier,allowExpiredGrant:I,abortSignal:c.signal,resolvePorts:async()=>await this.ports.resolve({request:n,executionGrant:i,command:n.command,getLease:()=>this.currentLease(t),...this.journalLineage(),journalRecord:f,abortSignal:c.signal})})}catch(e){if(a.removeEventListener("abort",_),c.abort(),!(e instanceof RuntimeResourceResolutionError))throw e;if("transient"===e.kind)return;return I?(v||await this.markOutcomeUnknownIfMutable(f),await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(n,new RuntimeCommandError("OUTCOME_UNKNOWN","eager resources cannot be reconstructed after retained started proof"),(new Date).toISOString())})):await this.reject(n,"integrity_mismatch"===e.kind?"resource_integrity_mismatch":"resource_resolution_rejected",t),void await d()}if(!w.ok)return a.removeEventListener("abort",_),c.abort(),I?(v||await this.markOutcomeUnknownIfMutable(f),await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(n,new RuntimeCommandError("OUTCOME_UNKNOWN","execution grant cannot be revalidated after retained started proof"),(new Date).toISOString())})):await this.reject(n,"invalid_execution_grant",t),void await d();if(!u||"prepared"!==f.phase&&"started"!==f.phase||c.abort(),c.signal.aborted&&!I)return a.removeEventListener("abort",_),await this.reject(n,"cancelled_before_dispatch",t),void await d();s.mark("attempt"),I?this.currentLease(t):(await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),executionGrant:i,type:RUNTIME_MESSAGE_TYPES.started,payload:{...runtimeMessageBase(n),executionMode:"start",executionGrantHash:n.executionGrantHash,handlerIdentity:t.handlerIdentity,claimedAt:f.messageBinding?.acceptedAt??f.updatedAt}}),s.mark("append-started"));const g=this.dispatcher.dispatch(n.command,w.context);g.completion.catch(()=>{}),o(()=>{c.abort(),g.cancel()}),c.signal.aborted&&g.cancel();const M=this.forwardProgress(n,g.progress,t).catch(()=>{});let S,O=!1;try{if(("mcp/set"===n.method||"mcp/unset"===n.method)&&hasEffectReceiptHandoff(g)){const e=await g.effectCommitted;if(e){if(e.operationId!==n.operationId||e.method!==n.command.name)throw new RuntimeCommandError("OUTCOME_UNKNOWN","Core MCP receipt correlation mismatch");const a=runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:n.method,result:e.result}),o={schemaVersion:1,operationId:n.operationId,method:n.method,coreResultRef:`sha256:${a}`,coreResultHash:a};S=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,o),O=!0,await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(n),effectRecord:o,effectRecordHash:S,committedAt:e.committedAt}}),await g.acknowledgeEffectReceipt({operationId:n.operationId,method:n.command.name,effectRecordHash:S})}}const a=await g.completion;if(await M,s.mark("core"),v){const o=(new Date).toISOString();let r;try{r=sanitizeRuntimeServiceResult(n.method,a,w.context,void 0)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed Core result cannot be mapped safely",void 0,{cause:e})}const i=runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:n.method,result:r}),c=await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(n),outcome:"succeeded",response:{jsonrpc:"2.0",id:n.request.id,result:r},serviceResultHash:i,completedAt:o}});return s.mark("append-final"),this.observeRequestTerminalAccepted(e.deliveryId,c.message),await d(),void this.observeRequestAcknowledged(e.deliveryId,c.message)}const o=await this.journal.get(n.operationId);if(s.mark("journal-after-core"),!o||!isCommittedCorePhase(o.phase))throw new RuntimeCommandError("OUTCOME_UNKNOWN","Core completed without a committed local journal record");const r=o.updatedAt;let i,c;if("query"!==RUNTIME_INVOCATION_RECOVERY_CLASSES[n.method]){const e=isAgentProjectionMethod(n.method),c=g.getSnapshot().projection,l=o.agentProjectionIntent??o.agentProjectionPreparationFailure;if(e&&!l)throw new RuntimeCommandError("OUTCOME_UNKNOWN","agent effect committed without an atomic projection preparation record");if(!S&&"session/clear"!==n.method){const e=l?.coreResultHash??runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:n.method,result:a}),i=o.agentProjectionIntent?.projectionRevision??(methodRequiresProjectionRevision(n.method)?c?.revision??`${Math.max(0,o.revision)}`:void 0),d={schemaVersion:1,operationId:n.operationId,method:n.method,coreResultRef:`sha256:${e}`,coreResultHash:e,...i?{projectionRevision:i}:{}};S=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,d),O=!0,await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(n),effectRecord:d,effectRecordHash:S,committedAt:r}}),s.mark("append-effect")}let p=e?await awaitRuntimeProjection(g):c;if("session/set_model"===n.method&&"synced"!==p?.state&&(p=await this.projectSessionModelAfterEffect(n,w.context,o,p),s.mark("set-model-projection")),e&&o.agentProjectionIntent&&(!p||p.revision!==o.agentProjectionIntent.projectionRevision))throw new RuntimeCommandError("OUTCOME_UNKNOWN","agent projection receipt revision mismatch");if("pending"===p?.state)return void await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.projectionPending,payload:{...runtimeMessageBase(n),revision:p.revision}});if("synced"===p?.state&&await this.publishProjectionSynced(n,t,{...p,state:"synced"}),"blocked"===p?.state){await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.projectionBlocked,payload:{...runtimeMessageBase(n),revision:p.revision,errorCode:"PROJECTION_BLOCKED"}});const e=RUNTIME_ERROR_DESCRIPTORS.PROJECTION_BLOCKED;return await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(n),outcome:"projection_blocked",response:{jsonrpc:"2.0",id:n.request.id,error:{code:e.jsonRpcCode,message:"PROJECTION_BLOCKED",data:{code:"PROJECTION_BLOCKED",operationId:n.operationId,effectState:"committed",retryMode:e.retryMode}}},effectRecordHash:S,completedAt:r}}),void await d()}i=e?p?.platformAgentId:void 0}try{c=sanitizeRuntimeServiceResult(n.method,a,w.context,i)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed Core result cannot be mapped safely",void 0,{cause:e})}const l=runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:n.method,result:c});O=!0;const p=await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(n),outcome:"succeeded",response:{jsonrpc:"2.0",id:n.request.id,result:c},serviceResultHash:l,...S?{effectRecordHash:S}:{},completedAt:r}});if(s.mark("append-final"),this.observeRequestTerminalAccepted(e.deliveryId,p.message),("mcp/set"===n.method||"mcp/unset"===n.method)&&hasEffectReceiptHandoff(g)&&"function"==typeof g.acknowledgeTerminalReceipt){if(!S)throw new RuntimeCommandError("OUTCOME_UNKNOWN","MCP terminal response lacks its committed effect hash");await g.acknowledgeTerminalReceipt({operationId:n.operationId,method:n.command.name,effectRecordHash:S,terminalMessageId:p.message.message_id})}await d(),this.observeRequestAcknowledged(e.deliveryId,p.message)}catch(e){const a=await this.journal.get(n.operationId);if(a&&isCommittedCorePhase(a.phase)&&O)throw e;const o=!a||!isCommittedCorePhase(a.phase)||e instanceof RuntimeCommandError&&"OUTCOME_UNKNOWN"===e.code?e:new RuntimeCommandError("OUTCOME_UNKNOWN","Core effect committed before terminal mapping",void 0,{cause:e});this.observeRequestFailure(n.operationId,n.method,o);const r=failurePayload(n,o,a?.updatedAt??(new Date).toISOString());await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:r}),s.mark("append-terminal-failure"),await d()}finally{s.finish(),c.abort(),a.removeEventListener("abort",_)}}async handlePoison(e,t,a){this.currentLease(a);(await this.poisonJournal.record({delivery:e,reason:durablePoisonReason(t),limit:this.options.poisonDeliveryLimit??3})).terminal&&await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(a)})}observeRequestTerminalAccepted(e,t){try{this.options.onRequestTerminalAccepted?.({deliveryId:e,message:t})}catch{}}observeRequestAcknowledged(e,t){try{this.options.onRequestAcknowledged?.({deliveryId:e,message:t})}catch{}}async forwardProgress(e,t,a){for await(const o of t)await this.channel.append({operationId:e.operationId,lease:this.currentLease(a),type:RUNTIME_MESSAGE_TYPES.progress,payload:{...runtimeMessageBase(e),phase:o.phase,progress:o}})}async reject(e,t,a){await this.channel.append({operationId:e.operationId,lease:this.currentLease(a),type:RUNTIME_MESSAGE_TYPES.final,payload:prestartFailurePayload(e,t)})}async markOutcomeUnknownIfMutable(e){"prepared"!==e.phase&&"started"!==e.phase||await this.journal.transition({operationId:e.operationId,expectedRevision:e.revision,phase:"outcome_unknown",errorCode:"OUTCOME_UNKNOWN"})}async projectSessionModelAfterEffect(e,t,a,o){const r=Object.freeze({state:"pending",revision:o?.revision??`${Math.max(0,a.revision)}`}),n=e.command;if("session.setModel"!==n.name||"conversation"!==n.context.scope)return r;const i=t.sessionModelProjection;if(!i)return r;try{await i.project({conversationId:n.context.conversation.runtimeConversationUid,modelOverrideId:n.params.modelOverrideId});const e=Object.freeze({state:"synced",revision:r.revision});try{const t=await this.journal.get(a.operationId)??a;if("projection_committed"===t.phase&&"synced"===t.projectionReceipt?.snapshot.state)return Object.freeze({state:"synced",revision:t.projectionReceipt.snapshot.revision});await this.journal.transition({operationId:t.operationId,expectedRevision:t.revision,phase:"projection_committed",projectionSnapshot:e})}catch{}return e}catch(e){return this.observeDeliveryError(e),r}}async publishProjectionSynced(e,t,a){const o=this.currentLease(t),r=await this.channel.history({operationId:e.operationId,lease:o});if("found"===r.status&&"synced"===r.snapshot.projectionState)return;const n={...runtimeMessageBase(e),revision:a.revision};("found"!==r.status||"reserved"===r.snapshot.projectionState||"pending"!==r.snapshot.projectionState&&void 0===r.snapshot.projectionPending)&&await this.channel.append({operationId:e.operationId,lease:o,type:RUNTIME_MESSAGE_TYPES.projectionPending,payload:n}),await this.channel.append({operationId:e.operationId,lease:o,type:RUNTIME_MESSAGE_TYPES.projectionSynced,payload:{...n,...a.platformAgentId?{platformAgentId:a.platformAgentId}:{}}})}journalLineage(){return this.options.getJournalLineage?.()??{journalStoreId:this.options.journalStoreId,journalGeneration:this.options.journalGeneration}}currentLease(e){const t=this.getLease();if(!t||t.instanceId!==e.instanceId||t.leaseId!==e.leaseId||t.runtimeEpoch!==e.runtimeEpoch||t.handlerIdentity!==e.handlerIdentity||!Number.isFinite(Date.parse(t.leaseExpiresAt))||Date.parse(t.leaseExpiresAt)<=Date.now())throw new RuntimeCommandError("INSTANCE_EPOCH_MISMATCH","runtime message lease changed");return t}}function ephemeralQueryAccept(e){return{operationId:e.operationId,command:e.command.name,paramsHash:e.paramsHash,runtimeEpoch:e.dispatchEpoch,phase:"prepared",revision:1,updatedAt:(new Date).toISOString(),messageBinding:{requestMessageId:e.requestMessageId,requestHash:e.requestHash,acceptedAt:(new Date).toISOString()}}}function durablePoisonReason(e){const t=e.replace(/[^a-z0-9_:.-]+/gi,"_").replace(/^_+|_+$/g,"").slice(0,256);if(!t)throw new Error("poison reason is empty");return t}function isCommittedCorePhase(e){return"effect_committed"===e||"projection_committed"===e}const CORE_RECOVERY_DECISIONS=new Set(["execute","resume","replay_effect_committed","resume_projection","publish_committed_result","publish_projected_result","publish_terminal_result"]);function decideMessageServiceRecovery(e,t,a,o){const r=RUNTIME_INVOCATION_PARITY_ENTRIES.find(e=>e.acpMethod===t.method),n=e.terminal?"terminal":"blocked"===e.projectionState?"projection_blocked":"synced"===e.projectionState?"projection_synced":"pending"===e.projectionState?"projection_pending":e.effectCommitted?"runtime_committed":o?"running":"queued",i="failed"===a?.phase||"outcome_unknown"===a?.phase?"terminal":a?.phase,s=a&&a.runtimeEpoch===t.dispatchEpoch&&(void 0===a.messageBinding||a.messageBinding.requestMessageId===t.requestMessageId&&a.messageBinding.requestHash===t.requestHash)?"continuous":"discontinuous";return reduceRuntimeRecoveryPolicy({recoveryClass:r?.recoveryClass??RUNTIME_INVOCATION_RECOVERY_CLASSES[t.method],projectionRequired:"mcp/set"===t.method||"mcp/unset"===t.method||(r?.projectionRequired??!1),messageServicePhase:n,executionBoundaryCrossed:o,lineageContinuity:s,journalState:a?"available":"unavailable",...i?{journalPhase:i}:{}})}export function sanitizeRuntimeServiceResult(e,t,a,o){if("session/clear"===e)return serviceClearResult(t,a?.historyBoundary);if("session/set_model"===e)return serviceSetModelResult(t,a);if(!(e in SERVICE_CANONICAL_COMMAND_NAMES))return t;const r="cron/status"===e&&record(t)?{enabled:t.enabled,jobCount:t.jobCount,..."number"==typeof t.nextWakeAtMs?{nextWakeAtMs:t.nextWakeAtMs}:{}}:t;return mapCanonicalResultToService(e,r,{...o?{platformAgentId:o}:{},classifySkillOrigin:e=>e.bundled?{origin:"bundled",slug:e.slug}:{origin:"legacy_runtime",slug:e.slug},resolveMcpView:e=>({name:e.name,transport:e.transport,origin:"legacy_runtime",...void 0===e.connected?{}:{connected:e.connected},...void 0===e.connectionTimeoutMs?{}:{connectionTimeoutMs:e.connectionTimeoutMs}}),sanitizeDiagnostic:e=>/^[A-Z][A-Z0-9_]{0,63}$/.test(e)?e:"RUNTIME_EXECUTION_FAILED"})}function serviceClearResult(e,t){if(!record(e)||!0!==e.cleared||"string"!=typeof e.historyGeneration||!t||"message-service"!==t.kind)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed clear result lacks its Message Service receipt");const a=t;if(!a.committedIntentId)throw new RuntimeCommandError("OUTCOME_UNKNOWN","Message Service clear receipt is unavailable");return{...e,clearIntentId:a.committedIntentId()}}function serviceSetModelResult(e,t){if(!record(e)||"string"!=typeof e.effectiveModelId||!t)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed set_model result is invalid");const a=t.verifiedMessageGrant?.claims.command;if(!a||"session.setModel"!==a.name||"conversation"!==a.context.scope)throw new RuntimeCommandError("OUTCOME_UNKNOWN","set_model Service target receipt is unavailable");const o=a.params.modelOverrideId;return{conversationId:a.context.conversation.runtimeConversationUid,...null===o?{defaultModelId:e.effectiveModelId}:{},modelOverrideId:o,effectiveModelId:e.effectiveModelId,effectState:"committed",projectionState:"synced",operationId:t.operationId}}function isAgentProjectionMethod(e){return"agent/create"===e||"agent/update"===e||"agent/delete"===e||"agent/applyTemplate"===e}function methodRequiresProjectionRevision(e){return isAgentProjectionMethod(e)||"session/set_model"===e}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function sameLeaseBinding(e,t){return e.instanceId===t.instanceId&&e.leaseId===t.leaseId&&e.handlerIdentity===t.handlerIdentity&&e.runtimeEpoch===t.runtimeEpoch}function failurePayload(e,t,a){const o=t instanceof RuntimeCommandError?t.code:"RUNTIME_EXECUTION_FAILED",r=o in RUNTIME_ERROR_DESCRIPTORS?o:"RUNTIME_EXECUTION_FAILED",n="OUTCOME_UNKNOWN"===r||"INSTANCE_EPOCH_MISMATCH"===r?"outcome_unknown":"COMMAND_EXPIRED"===r?"expired":"OPERATION_CANCELLED"===r?"cancelled":"failed",i="outcome_unknown"===n?"OUTCOME_UNKNOWN":r,s=RUNTIME_ERROR_DESCRIPTORS[i],c="outcome_unknown"===n?"outcome_unknown":n;return{...runtimeMessageBase(e),outcome:n,response:{jsonrpc:"2.0",id:e.request.id,error:{code:s.jsonRpcCode,message:i,data:{code:i,operationId:e.operationId,effectState:c,retryMode:s.retryMode}}},completedAt:a}}function prestartFailurePayload(e,t){const a="invalid_execution_grant"===t?"INVALID_EXECUTION_GRANT":"unsupported_method"===t?"METHOD_NOT_SUPPORTED":"authority_mismatch"===t?"INSTANCE_EPOCH_MISMATCH":"execution_deadline_exceeded"===t?"COMMAND_EXPIRED":"cancelled_before_dispatch"===t?"OPERATION_CANCELLED":"resource_resolution_rejected"===t?"INVALID_INVOCATION":"RUNTIME_EXECUTION_FAILED",o=RUNTIME_ERROR_DESCRIPTORS[a in RUNTIME_ERROR_DESCRIPTORS?a:"RUNTIME_EXECUTION_FAILED"],r="COMMAND_EXPIRED"===a?"expired":"OPERATION_CANCELLED"===a?"cancelled":"failed";return{...runtimeMessageBase(e),outcome:r,response:{jsonrpc:"2.0",id:e.request.id,error:{code:o.jsonRpcCode,message:a,data:{code:a,operationId:e.operationId,effectState:r,retryMode:o.retryMode}}},completedAt:(new Date).toISOString()}}function abortable(e,t){return t?t.aborted?Promise.resolve():new Promise((a,o)=>{const r=()=>a();t.addEventListener("abort",r,{once:!0}),e.then(()=>{t.removeEventListener("abort",r),a()},e=>{t.removeEventListener("abort",r),o(e)})}):e}function delay(e,t){return new Promise(a=>{if(t?.aborted)return a();const o=()=>{clearTimeout(r),a()},r=setTimeout(()=>{t?.removeEventListener("abort",o),a()},e);t?.addEventListener("abort",o,{once:!0})})}
1
+ import{RUNTIME_ERROR_DESCRIPTORS,RUNTIME_HASH_DOMAINS,RUNTIME_INVOCATION_PARITY_ENTRIES,RUNTIME_INVOCATION_RECOVERY_CLASSES,SERVICE_CANONICAL_COMMAND_NAMES,mapCanonicalResultToService}from"@beeos-ai/beeos-types/runtime";import{reduceRuntimeRecoveryPolicy}from"@beeos-ai/beeos-types/runtime/internal";import{verifyAndCreateMessageServiceCoreExecutionAttempt}from"./core-execution-attempt-context.js";import{awaitRuntimeProjection,hasEffectReceiptHandoff,RuntimeCommandError}from"./runtime-command-dispatcher.js";import{createRuntimeAppendTimingRecorder}from"./runtime-append-timing.js";import{runtimeCommandIsReplayableQuery}from"./runtime-command-journal.js";import{RUNTIME_MESSAGE_TYPES,runtimeMessageBase,runtimeMessageHash,semanticEqual,validateRuntimeCancelEnvelope,validateRuntimeRequestEnvelope}from"./runtime-message-channel-contract.js";import{RuntimeResourceResolutionError}from"./runtime-operation-resource-resolver.js";import{RuntimeTransportFailurePolicy}from"./runtime-transport-failure-policy.js";const leaseStarvationReportIntervalMs=3e4;export class MsRuntimeMessageChannelAdapter{dispatcher;channel;verifier;ports;journal;getLease;options;controller;running;externalDeliveryOwner;workers=new Map;poisonJournal;renewTransportFailurePolicy=new RuntimeTransportFailurePolicy;leaseStarvedSince;leaseStarvationReportedAt=0;receiptHistory=this;constructor(e,t,o,a,n,r,i){if(this.dispatcher=e,this.channel=t,this.verifier=o,this.ports=a,this.journal=n,this.getLease=r,this.options=i,!i.poisonJournal)throw new Error("durable poison journal is required");if(this.poisonJournal=i.poisonJournal,!Number.isSafeInteger(i.poisonDeliveryLimit??3)||(i.poisonDeliveryLimit??3)<=0)throw new Error("poison delivery limit must be a positive integer")}start(){if(this.externalDeliveryOwner)return void this.externalDeliveryOwner.start();if(this.running)return;const e=new AbortController;this.controller=e;const t=this.loop(e.signal).catch(t=>{e.signal.aborted||this.observeDeliveryError(t)}).finally(()=>{this.running===t&&(this.running=void 0)});this.running=t}async stop(e){this.controller?.abort();for(const e of this.workers.values())e.cancel?.();if(this.externalDeliveryOwner)return await this.externalDeliveryOwner.stop(e),void await Promise.allSettled([...this.workers.values()].map(e=>e.completion));this.running&&await abortable(this.running,e)}attachExternalDeliveryOwner(e){if(this.running||this.externalDeliveryOwner)throw new Error("runtime delivery owner is already attached");this.externalDeliveryOwner=e}async acceptDelivery(e,t,o){if(this.currentLease(t),e.message.type===RUNTIME_MESSAGE_TYPES.cancel)return void await this.handleCancel(e,t);const a=validateRuntimeRequestEnvelope(e.message),n=a.ok?a.envelope.payload.operationId:e.message.channel_id;if(this.workers.has(n))return;const r={deliveryId:e.deliveryId,claimedLease:t,completion:Promise.resolve()};r.completion=this.handleRequest(e,t,o,e=>{r.cancel=e}).catch(e=>this.observeDeliveryError(e)).finally(()=>{this.workers.delete(n)}),this.workers.set(n,r),await r.completion}async acceptPoisonDelivery(e,t,o){await this.handlePoison(e,t,o)}async readOperationHistory(e){const t=this.getLease();if(!t)return{status:"unavailable"};try{return await this.channel.history({operationId:e.operationId,lease:t})}catch{return{status:"unavailable"}}}async loop(e){let t;(()=>{t||(t=setInterval(()=>{this.renewActive().catch(e=>this.observeDeliveryError(e))},this.options.renewIntervalMs??2e4),t.unref?.())})();try{for(;!e.aborted;){const t=this.getLease();if(!t){this.observeLeaseStarvation(),await delay(this.options.idleDelayMs??500,e);continue}let o;this.observeLeaseRestored();try{o=await this.channel.read({maxCount:this.options.readCount??32,blockMs:this.options.blockMs??5e3,lease:t,signal:e})}catch(t){if(e.aborted)return;this.observeDeliveryError(t),await delay(this.options.idleDelayMs??500,e);continue}for(const a of o){if(e.aborted)break;if(a.message.type===RUNTIME_MESSAGE_TYPES.cancel){await this.handleCancel(a,t).catch(e=>this.observeDeliveryError(e));continue}const o=a.message.channel_id;if(this.workers.has(o))continue;const n={deliveryId:a.deliveryId,claimedLease:t,completion:Promise.resolve()};n.completion=this.handleRequest(a,t,e,e=>{n.cancel=e}).catch(e=>this.observeDeliveryError(e)).finally(()=>{this.workers.delete(o)}),this.workers.set(o,n)}}}finally{t&&clearInterval(t),await Promise.allSettled([...this.workers.values()].map(e=>e.completion))}}observeDeliveryError(e){try{this.options.onDeliveryError?.(e)}catch{}}observeLeaseStarvation(){const e=Date.now();this.leaseStarvedSince??=e;const t=e-this.leaseStarvedSince;if(!(t<3e4||this.leaseStarvationReportedAt&&e-this.leaseStarvationReportedAt<3e4)){this.leaseStarvationReportedAt=e;try{this.options.onLeaseStarvation?.({starvedForMs:t,recovered:!1})}catch{}}}observeLeaseRestored(){const e=this.leaseStarvedSince;if(void 0===e)return;this.leaseStarvedSince=void 0;const t=this.leaseStarvationReportedAt;if(this.leaseStarvationReportedAt=0,t)try{this.options.onLeaseStarvation?.({starvedForMs:Date.now()-e,recovered:!0})}catch{}}observeRequestFailure(e,t,o){try{this.options.onRequestFailure?.({operationId:e,method:t,error:o})}catch{}}async renewActive(){const e=this.getLease();if(!e)return;const t=[];for(const o of this.workers.values())sameLeaseBinding(o.claimedLease,e)?t.push(o.deliveryId):o.cancel?.();if(!t.length)return;let o;try{o=await this.channel.renew({deliveryIds:t,lease:e})}catch(e){if(this.observeDeliveryError(e),this.renewTransportFailurePolicy.recordFailure()){const e=new Set(t);for(const t of this.workers.values())e.has(t.deliveryId)&&t.cancel?.()}return}if(this.renewTransportFailurePolicy.recordSuccess(),o.notPending.length){const e=new Set(o.notPending);for(const t of this.workers.values())e.has(t.deliveryId)&&t.cancel?.()}}async handleCancel(e,t){const o=validateRuntimeCancelEnvelope(e.message);if(!o.ok)return void await this.handlePoison(e,`invalid_cancel:${o.reason}`,t);const a=o.envelope.payload,n=await this.channel.history({operationId:a.operationId,lease:t});if("found"===n.status&&n.snapshot.terminal&&"final_message"===n.snapshot.terminalSource)return void await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t});if("not_found"===n.status||"expired"===n.status)return void await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t});const r=n.snapshot.request.payload;r.operationId===a.operationId&&r.requestMessageId===a.requestMessageId&&r.requestHash===a.requestHash&&r.dispatchEpoch===a.dispatchEpoch&&r.method===a.method?(await this.journal.observeCancellation({operationId:a.operationId,requestMessageId:a.requestMessageId,requestHash:a.requestHash,eventId:a.eventId}),this.workers.get(a.operationId)?.cancel?.(),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t})):await this.handlePoison(e,"cancel_history_mismatch",t)}async handleRequest(e,t,o,a){const n=validateRuntimeRequestEnvelope(e.message);if(!n.ok)return void await this.handlePoison(e,`invalid_request:${n.reason}`,t);const r=n.envelope.payload,i=e.executionGrant,s=createRuntimeAppendTimingRecorder("runtime-op",{operationId:r.operationId,method:r.method}),c=new AbortController;a(()=>c.abort());const d=async()=>{await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),s.mark("ack")},l=await this.channel.history({operationId:r.operationId,lease:t});if(s.mark("history"),"not_found"===l.status||"expired"===l.status)return void await d();if(l.snapshot.terminal&&"final_message"===l.snapshot.terminalSource)return void await d();if(this.options.allowedMethods&&!this.options.allowedMethods.has(r.method))return await this.reject(r,"unsupported_method",t),void await d();if("deadline"===l.snapshot.terminalSource||Date.parse(r.executionDeadlineAt)<=Date.now()||!l.snapshot.started&&Date.parse(r.claimDeadlineAt)<=Date.now())return await this.reject(r,"execution_deadline_exceeded",t),void await d();const p=await this.journal.getCancellation(r.operationId);s.mark("journal-cancel-read");const u=l.snapshot.cancelRequested||null!==p;if(u&&"queued"===l.snapshot.status)return await this.reject(r,"cancelled_before_dispatch",t),void await d();if(r.instanceId!==t.instanceId||r.runtimeHandlerIdentity!==t.handlerIdentity||r.dispatchEpoch!==t.runtimeEpoch)return await this.reject(r,"authority_mismatch",t),void await d();const m=l.snapshot.request.payload;if(l.snapshot.operationId!==r.operationId||l.snapshot.requestMessageId!==r.requestMessageId||l.snapshot.requestHash!==r.requestHash||!semanticEqual(m,r))return void await this.handlePoison(e,"request_history_mismatch",t);const h=l.snapshot.started?.payload,I=void 0!==h&&h.operationId===r.operationId&&h.requestMessageId===r.requestMessageId&&h.requestHash===r.requestHash&&h.executionGrantHash===r.executionGrantHash&&h.handlerIdentity===t.handlerIdentity&&h.dispatchEpoch===t.runtimeEpoch&&h.method===r.method,E=await this.journal.get(r.operationId);s.mark("journal-prior");const v=runtimeCommandIsReplayableQuery(r.command.name),f=v?ephemeralQueryAccept(r):await this.journal.acceptMessageRequest({operationId:r.operationId,command:r.command.name,paramsHash:r.paramsHash,runtimeEpoch:r.dispatchEpoch,requestMessageId:r.requestMessageId,requestHash:r.requestHash});s.mark("journal-accept");const R=I?E:f,y=v?"execute":decideMessageServiceRecovery(l.snapshot,r,R,I);if("already_terminal"===y)return void await d();if(!CORE_RECOVERY_DECISIONS.has(y))return v||await this.markOutcomeUnknownIfMutable(f),await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(r,new RuntimeCommandError("OUTCOME_UNKNOWN",`Types recovery policy requires ${y}; this runtime cannot safely replay Core`),(new Date).toISOString())}),void await d();if(await this.verifier.refresh(),s.mark("verifier-refresh"),!i)return I?await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(r,new RuntimeCommandError("OUTCOME_UNKNOWN","retained started proof has no live execution grant"),(new Date).toISOString())}):await this.reject(r,"invalid_execution_grant",t),void await d();this.verifier.verifyAndDecodeGrant(i)||await this.verifier.refresh(!0);const _=()=>c.abort();let w;o.addEventListener("abort",_,{once:!0});try{w=await verifyAndCreateMessageServiceCoreExecutionAttempt({request:r,executionGrant:i,runtimeEpoch:t.runtimeEpoch,lease:t,verifier:this.verifier,allowExpiredGrant:I,abortSignal:c.signal,resolvePorts:async()=>await this.ports.resolve({request:r,executionGrant:i,command:r.command,getLease:()=>this.currentLease(t),...this.journalLineage(),journalRecord:f,abortSignal:c.signal})})}catch(e){if(o.removeEventListener("abort",_),c.abort(),!(e instanceof RuntimeResourceResolutionError))throw e;if("transient"===e.kind)return;return I?(v||await this.markOutcomeUnknownIfMutable(f),await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(r,new RuntimeCommandError("OUTCOME_UNKNOWN","eager resources cannot be reconstructed after retained started proof"),(new Date).toISOString())})):await this.reject(r,"integrity_mismatch"===e.kind?"resource_integrity_mismatch":"resource_resolution_rejected",t),void await d()}if(!w.ok)return o.removeEventListener("abort",_),c.abort(),I?(v||await this.markOutcomeUnknownIfMutable(f),await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(r,new RuntimeCommandError("OUTCOME_UNKNOWN","execution grant cannot be revalidated after retained started proof"),(new Date).toISOString())})):await this.reject(r,"invalid_execution_grant",t),void await d();if(!u||"prepared"!==f.phase&&"started"!==f.phase||c.abort(),c.signal.aborted&&!I)return o.removeEventListener("abort",_),await this.reject(r,"cancelled_before_dispatch",t),void await d();s.mark("attempt"),I?this.currentLease(t):(await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),executionGrant:i,type:RUNTIME_MESSAGE_TYPES.started,payload:{...runtimeMessageBase(r),executionMode:"start",executionGrantHash:r.executionGrantHash,handlerIdentity:t.handlerIdentity,claimedAt:f.messageBinding?.acceptedAt??f.updatedAt}}),s.mark("append-started"));const g=this.dispatcher.dispatch(r.command,w.context);g.completion.catch(()=>{}),a(()=>{c.abort(),g.cancel()}),c.signal.aborted&&g.cancel();const M=this.forwardProgress(r,g.progress,t).catch(()=>{});let S,O=!1;try{if(("mcp/set"===r.method||"mcp/unset"===r.method)&&hasEffectReceiptHandoff(g)){const e=await g.effectCommitted;if(e){if(e.operationId!==r.operationId||e.method!==r.command.name)throw new RuntimeCommandError("OUTCOME_UNKNOWN","Core MCP receipt correlation mismatch");const o=runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:r.method,result:e.result}),a={schemaVersion:1,operationId:r.operationId,method:r.method,coreResultRef:`sha256:${o}`,coreResultHash:o};S=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,a),O=!0,await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(r),effectRecord:a,effectRecordHash:S,committedAt:e.committedAt}}),await g.acknowledgeEffectReceipt({operationId:r.operationId,method:r.command.name,effectRecordHash:S})}}const o=await g.completion;if(await M,s.mark("core"),v){const a=(new Date).toISOString();let n;try{n=sanitizeRuntimeServiceResult(r.method,o,w.context,void 0)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed Core result cannot be mapped safely",void 0,{cause:e})}const i=runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:r.method,result:n}),c=await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(r),outcome:"succeeded",response:{jsonrpc:"2.0",id:r.request.id,result:n},serviceResultHash:i,completedAt:a}});return s.mark("append-final"),this.observeRequestTerminalAccepted(e.deliveryId,c.message),await d(),void this.observeRequestAcknowledged(e.deliveryId,c.message)}const a=await this.journal.get(r.operationId);if(s.mark("journal-after-core"),!a||!isCommittedCorePhase(a.phase))throw new RuntimeCommandError("OUTCOME_UNKNOWN","Core completed without a committed local journal record");const n=a.updatedAt;let i,c;if("query"!==RUNTIME_INVOCATION_RECOVERY_CLASSES[r.method]){const e=isAgentProjectionMethod(r.method),c=g.getSnapshot().projection,l=a.agentProjectionIntent??a.agentProjectionPreparationFailure;if(e&&!l)throw new RuntimeCommandError("OUTCOME_UNKNOWN","agent effect committed without an atomic projection preparation record");if(!S&&"session/clear"!==r.method){const e=l?.coreResultHash??runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:r.method,result:o}),i=a.agentProjectionIntent?.projectionRevision??(methodRequiresProjectionRevision(r.method)?c?.revision??`${Math.max(0,a.revision)}`:void 0),d={schemaVersion:1,operationId:r.operationId,method:r.method,coreResultRef:`sha256:${e}`,coreResultHash:e,...i?{projectionRevision:i}:{}};S=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,d),O=!0,await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(r),effectRecord:d,effectRecordHash:S,committedAt:n}}),s.mark("append-effect")}let p=e?await awaitRuntimeProjection(g):c;if("session/set_model"!==r.method&&"session/set_reasoning"!==r.method||"synced"===p?.state||(p=await this.projectSessionModelAfterEffect(r,w.context,a,p,o),s.mark("set-model-projection")),e&&a.agentProjectionIntent&&(!p||p.revision!==a.agentProjectionIntent.projectionRevision))throw new RuntimeCommandError("OUTCOME_UNKNOWN","agent projection receipt revision mismatch");if("pending"===p?.state)return void await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.projectionPending,payload:{...runtimeMessageBase(r),revision:p.revision}});if("synced"===p?.state&&await this.publishProjectionSynced(r,t,{...p,state:"synced"}),"blocked"===p?.state){await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.projectionBlocked,payload:{...runtimeMessageBase(r),revision:p.revision,errorCode:"PROJECTION_BLOCKED"}});const e=RUNTIME_ERROR_DESCRIPTORS.PROJECTION_BLOCKED;return await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(r),outcome:"projection_blocked",response:{jsonrpc:"2.0",id:r.request.id,error:{code:e.jsonRpcCode,message:"PROJECTION_BLOCKED",data:{code:"PROJECTION_BLOCKED",operationId:r.operationId,effectState:"committed",retryMode:e.retryMode}}},effectRecordHash:S,completedAt:n}}),void await d()}i=e?p?.platformAgentId:void 0}try{c=sanitizeRuntimeServiceResult(r.method,o,w.context,i)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed Core result cannot be mapped safely",void 0,{cause:e})}const l=runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:r.method,result:c});O=!0;const p=await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(r),outcome:"succeeded",response:{jsonrpc:"2.0",id:r.request.id,result:c},serviceResultHash:l,...S?{effectRecordHash:S}:{},completedAt:n}});if(s.mark("append-final"),this.observeRequestTerminalAccepted(e.deliveryId,p.message),("mcp/set"===r.method||"mcp/unset"===r.method)&&hasEffectReceiptHandoff(g)&&"function"==typeof g.acknowledgeTerminalReceipt){if(!S)throw new RuntimeCommandError("OUTCOME_UNKNOWN","MCP terminal response lacks its committed effect hash");await g.acknowledgeTerminalReceipt({operationId:r.operationId,method:r.command.name,effectRecordHash:S,terminalMessageId:p.message.message_id})}await d(),this.observeRequestAcknowledged(e.deliveryId,p.message)}catch(e){const o=await this.journal.get(r.operationId);if(o&&isCommittedCorePhase(o.phase)&&O)throw e;const a=!o||!isCommittedCorePhase(o.phase)||e instanceof RuntimeCommandError&&"OUTCOME_UNKNOWN"===e.code?e:new RuntimeCommandError("OUTCOME_UNKNOWN","Core effect committed before terminal mapping",void 0,{cause:e});this.observeRequestFailure(r.operationId,r.method,a);const n=failurePayload(r,a,o?.updatedAt??(new Date).toISOString());await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:n}),s.mark("append-terminal-failure"),await d()}finally{s.finish(),c.abort(),o.removeEventListener("abort",_)}}async handlePoison(e,t,o){this.currentLease(o);(await this.poisonJournal.record({delivery:e,reason:durablePoisonReason(t),limit:this.options.poisonDeliveryLimit??3})).terminal&&await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(o)})}observeRequestTerminalAccepted(e,t){try{this.options.onRequestTerminalAccepted?.({deliveryId:e,message:t})}catch{}}observeRequestAcknowledged(e,t){try{this.options.onRequestAcknowledged?.({deliveryId:e,message:t})}catch{}}async forwardProgress(e,t,o){for await(const a of t)await this.channel.append({operationId:e.operationId,lease:this.currentLease(o),type:RUNTIME_MESSAGE_TYPES.progress,payload:{...runtimeMessageBase(e),phase:a.phase,progress:a}})}async reject(e,t,o){await this.channel.append({operationId:e.operationId,lease:this.currentLease(o),type:RUNTIME_MESSAGE_TYPES.final,payload:prestartFailurePayload(e,t)})}async markOutcomeUnknownIfMutable(e){"prepared"!==e.phase&&"started"!==e.phase||await this.journal.transition({operationId:e.operationId,expectedRevision:e.revision,phase:"outcome_unknown",errorCode:"OUTCOME_UNKNOWN"})}async projectSessionModelAfterEffect(e,t,o,a,n){const r=Object.freeze({state:"pending",revision:a?.revision??`${Math.max(0,o.revision)}`}),i=e.command;if("conversation"!==i.context.scope)return r;if("session.setModel"!==i.name&&"session.setReasoning"!==i.name)return r;try{const e=i.context.conversation.runtimeConversationUid;if("session.setReasoning"===i.name){if(!t.sessionReasoningProjection||!n)return r;await t.sessionReasoningProjection.project({conversationId:e,reasoning:n})}else{if(!t.sessionModelProjection)return r;await t.sessionModelProjection.project({conversationId:e,modelOverrideId:i.params.modelOverrideId})}const a=Object.freeze({state:"synced",revision:r.revision});try{const e=await this.journal.get(o.operationId)??o;if("projection_committed"===e.phase&&"synced"===e.projectionReceipt?.snapshot.state)return Object.freeze({state:"synced",revision:e.projectionReceipt.snapshot.revision});await this.journal.transition({operationId:e.operationId,expectedRevision:e.revision,phase:"projection_committed",projectionSnapshot:a})}catch{}return a}catch(e){return this.observeDeliveryError(e),r}}async publishProjectionSynced(e,t,o){const a=this.currentLease(t),n=await this.channel.history({operationId:e.operationId,lease:a});if("found"===n.status&&"synced"===n.snapshot.projectionState)return;const r={...runtimeMessageBase(e),revision:o.revision};("found"!==n.status||"reserved"===n.snapshot.projectionState||"pending"!==n.snapshot.projectionState&&void 0===n.snapshot.projectionPending)&&await this.channel.append({operationId:e.operationId,lease:a,type:RUNTIME_MESSAGE_TYPES.projectionPending,payload:r}),await this.channel.append({operationId:e.operationId,lease:a,type:RUNTIME_MESSAGE_TYPES.projectionSynced,payload:{...r,...o.platformAgentId?{platformAgentId:o.platformAgentId}:{}}})}journalLineage(){return this.options.getJournalLineage?.()??{journalStoreId:this.options.journalStoreId,journalGeneration:this.options.journalGeneration}}currentLease(e){const t=this.getLease();if(!t||t.instanceId!==e.instanceId||t.leaseId!==e.leaseId||t.runtimeEpoch!==e.runtimeEpoch||t.handlerIdentity!==e.handlerIdentity||!Number.isFinite(Date.parse(t.leaseExpiresAt))||Date.parse(t.leaseExpiresAt)<=Date.now())throw new RuntimeCommandError("INSTANCE_EPOCH_MISMATCH","runtime message lease changed");return t}}function ephemeralQueryAccept(e){return{operationId:e.operationId,command:e.command.name,paramsHash:e.paramsHash,runtimeEpoch:e.dispatchEpoch,phase:"prepared",revision:1,updatedAt:(new Date).toISOString(),messageBinding:{requestMessageId:e.requestMessageId,requestHash:e.requestHash,acceptedAt:(new Date).toISOString()}}}function durablePoisonReason(e){const t=e.replace(/[^a-z0-9_:.-]+/gi,"_").replace(/^_+|_+$/g,"").slice(0,256);if(!t)throw new Error("poison reason is empty");return t}function isCommittedCorePhase(e){return"effect_committed"===e||"projection_committed"===e}const CORE_RECOVERY_DECISIONS=new Set(["execute","resume","replay_effect_committed","resume_projection","publish_committed_result","publish_projected_result","publish_terminal_result"]);function decideMessageServiceRecovery(e,t,o,a){const n=RUNTIME_INVOCATION_PARITY_ENTRIES.find(e=>e.acpMethod===t.method),r=e.terminal?"terminal":"blocked"===e.projectionState?"projection_blocked":"synced"===e.projectionState?"projection_synced":"pending"===e.projectionState?"projection_pending":e.effectCommitted?"runtime_committed":a?"running":"queued",i="failed"===o?.phase||"outcome_unknown"===o?.phase?"terminal":o?.phase,s=o&&o.runtimeEpoch===t.dispatchEpoch&&(void 0===o.messageBinding||o.messageBinding.requestMessageId===t.requestMessageId&&o.messageBinding.requestHash===t.requestHash)?"continuous":"discontinuous";return reduceRuntimeRecoveryPolicy({recoveryClass:n?.recoveryClass??RUNTIME_INVOCATION_RECOVERY_CLASSES[t.method],projectionRequired:"mcp/set"===t.method||"mcp/unset"===t.method||(n?.projectionRequired??!1),messageServicePhase:r,executionBoundaryCrossed:a,lineageContinuity:s,journalState:o?"available":"unavailable",...i?{journalPhase:i}:{}})}export function sanitizeRuntimeServiceResult(e,t,o,a){if("session/clear"===e)return serviceClearResult(t,o?.historyBoundary);if("session/set_model"===e)return serviceSetModelResult(t,o);if(!(e in SERVICE_CANONICAL_COMMAND_NAMES))return t;const n="cron/status"===e&&record(t)?{enabled:t.enabled,jobCount:t.jobCount,..."number"==typeof t.nextWakeAtMs?{nextWakeAtMs:t.nextWakeAtMs}:{}}:t;return mapCanonicalResultToService(e,n,{...a?{platformAgentId:a}:{},classifySkillOrigin:e=>e.bundled?{origin:"bundled",slug:e.slug}:{origin:"legacy_runtime",slug:e.slug},resolveMcpView:e=>({name:e.name,transport:e.transport,origin:"legacy_runtime",...void 0===e.connected?{}:{connected:e.connected},...void 0===e.connectionTimeoutMs?{}:{connectionTimeoutMs:e.connectionTimeoutMs}}),sanitizeDiagnostic:e=>/^[A-Z][A-Z0-9_]{0,63}$/.test(e)?e:"RUNTIME_EXECUTION_FAILED"})}function serviceClearResult(e,t){if(!record(e)||!0!==e.cleared||"string"!=typeof e.historyGeneration||!t||"message-service"!==t.kind)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed clear result lacks its Message Service receipt");const o=t;if(!o.committedIntentId)throw new RuntimeCommandError("OUTCOME_UNKNOWN","Message Service clear receipt is unavailable");return{...e,clearIntentId:o.committedIntentId()}}function serviceSetModelResult(e,t){if(!record(e)||"string"!=typeof e.effectiveModelId||!t)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed set_model result is invalid");const o=t.verifiedMessageGrant?.claims.command;if(!o||"session.setModel"!==o.name||"conversation"!==o.context.scope)throw new RuntimeCommandError("OUTCOME_UNKNOWN","set_model Service target receipt is unavailable");const a=o.params.modelOverrideId;return{conversationId:o.context.conversation.runtimeConversationUid,...null===a?{defaultModelId:e.effectiveModelId}:{},modelOverrideId:a,effectiveModelId:e.effectiveModelId,effectState:"committed",projectionState:"synced",operationId:t.operationId}}function isAgentProjectionMethod(e){return"agent/create"===e||"agent/update"===e||"agent/delete"===e||"agent/applyTemplate"===e}function methodRequiresProjectionRevision(e){return isAgentProjectionMethod(e)||"session/set_model"===e||"session/set_reasoning"===e}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function sameLeaseBinding(e,t){return e.instanceId===t.instanceId&&e.leaseId===t.leaseId&&e.handlerIdentity===t.handlerIdentity&&e.runtimeEpoch===t.runtimeEpoch}function failurePayload(e,t,o){const a=t instanceof RuntimeCommandError?t.code:"RUNTIME_EXECUTION_FAILED",n=a in RUNTIME_ERROR_DESCRIPTORS?a:"RUNTIME_EXECUTION_FAILED",r="OUTCOME_UNKNOWN"===n||"INSTANCE_EPOCH_MISMATCH"===n?"outcome_unknown":"COMMAND_EXPIRED"===n?"expired":"OPERATION_CANCELLED"===n?"cancelled":"failed",i="outcome_unknown"===r?"OUTCOME_UNKNOWN":n,s=RUNTIME_ERROR_DESCRIPTORS[i],c="outcome_unknown"===r?"outcome_unknown":r;return{...runtimeMessageBase(e),outcome:r,response:{jsonrpc:"2.0",id:e.request.id,error:{code:s.jsonRpcCode,message:i,data:{code:i,operationId:e.operationId,effectState:c,retryMode:s.retryMode}}},completedAt:o}}function prestartFailurePayload(e,t){const o="invalid_execution_grant"===t?"INVALID_EXECUTION_GRANT":"unsupported_method"===t?"METHOD_NOT_SUPPORTED":"authority_mismatch"===t?"INSTANCE_EPOCH_MISMATCH":"execution_deadline_exceeded"===t?"COMMAND_EXPIRED":"cancelled_before_dispatch"===t?"OPERATION_CANCELLED":"resource_resolution_rejected"===t?"INVALID_INVOCATION":"RUNTIME_EXECUTION_FAILED",a=RUNTIME_ERROR_DESCRIPTORS[o in RUNTIME_ERROR_DESCRIPTORS?o:"RUNTIME_EXECUTION_FAILED"],n="COMMAND_EXPIRED"===o?"expired":"OPERATION_CANCELLED"===o?"cancelled":"failed";return{...runtimeMessageBase(e),outcome:n,response:{jsonrpc:"2.0",id:e.request.id,error:{code:a.jsonRpcCode,message:o,data:{code:o,operationId:e.operationId,effectState:n,retryMode:a.retryMode}}},completedAt:(new Date).toISOString()}}function abortable(e,t){return t?t.aborted?Promise.resolve():new Promise((o,a)=>{const n=()=>o();t.addEventListener("abort",n,{once:!0}),e.then(()=>{t.removeEventListener("abort",n),o()},e=>{t.removeEventListener("abort",n),a(e)})}):e}function delay(e,t){return new Promise(o=>{if(t?.aborted)return o();const a=()=>{clearTimeout(n),o()},n=setTimeout(()=>{t?.removeEventListener("abort",a),o()},e);t?.addEventListener("abort",a,{once:!0})})}
@@ -1 +1 @@
1
- import{existsSync,readFileSync,readdirSync,realpathSync}from"node:fs";import{createRequire}from"node:module";import{dirname,join,resolve}from"node:path";const adapters=new Map;export function getOpenClawNativeSessions(){const e=process.env.OPENCLAW_ROOT?.trim()||hostRoot();if(!e)return;const n=JSON.parse(readFileSync(join(e,"package.json"),"utf8"));if("openclaw"!==n.name)return;if("2026.9.8"!==n.version)throw new Error(`unsupported OpenClaw native session contract: ${n.version}`);const t=adapters.get(e);if(t)return t;const r=createRequire(join(e,"package.json")),s=r("openclaw/plugin-sdk/session-store-runtime"),o=join(e,"dist"),i=readdirSync(o).filter(e=>/^runs-.*\.mjs$/u.test(e)&&/export \{[^}]*\bwaitForEmbeddedAgentRunEnd\s*[,}]/u.test(readFileSync(join(o,e),"utf8")));if(1!==i.length)throw new Error("OpenClaw native run-end facade is missing or ambiguous");const a=r(join(o,i[0]));if("function"!=typeof s.getSessionEntry||"function"!=typeof s.loadTranscriptEventsSync||"function"!=typeof s.readTranscriptStatsSync||"function"!=typeof a.waitForEmbeddedAgentRunEnd)throw new Error("OpenClaw native session contract is unavailable");const c={getEntry:(e,n)=>s.getSessionEntry({agentId:e,sessionKey:n,readConsistency:"latest"}),readEvents:(e,n,t)=>{const r={agentId:e,sessionKey:n,sessionId:t},o=s.readTranscriptStatsSync(r);if(!Number.isSafeInteger(o.sizeBytes)||o.sizeBytes<0||o.sizeBytes>1048576||!Number.isSafeInteger(o.eventCount)||o.eventCount<0||o.eventCount>6400)throw new Error("native transcript exceeds the local recovery budget; use Gateway history pagination");return s.loadTranscriptEventsSync(r)},waitForRunEnd:(e,n)=>a.waitForEmbeddedAgentRunEnd(e,n)};return adapters.set(e,c),c}function hostRoot(){if(!process.argv[1]||!existsSync(process.argv[1]))return;let e=dirname(realpathSync(resolve(process.argv[1])));for(let n=0;n<4;n++){const n=join(e,"package.json");if(existsSync(n)&&"openclaw"===JSON.parse(readFileSync(n,"utf8")).name)return e;const t=dirname(e);if(t===e)break;e=t}}
1
+ import{existsSync,readFileSync,readdirSync,realpathSync}from"node:fs";import{createRequire}from"node:module";import{dirname,join,resolve}from"node:path";const adapters=new Map;export function getOpenClawNativeSessions(){const e=process.env.OPENCLAW_ROOT?.trim()||hostRoot();if(!e)return;const n=JSON.parse(readFileSync(join(e,"package.json"),"utf8"));if("openclaw"!==n.name)return;if("2026.9.8"!==n.version&&"2026.9.9"!==n.version)throw new Error(`unsupported OpenClaw native session contract: ${n.version}`);const t=adapters.get(e);if(t)return t;const r=createRequire(join(e,"package.json")),s=r("openclaw/plugin-sdk/session-store-runtime"),o=join(e,"dist"),i=readdirSync(o).filter(e=>/^runs-.*\.mjs$/u.test(e)&&/export \{[^}]*\bwaitForEmbeddedAgentRunEnd\s*[,}]/u.test(readFileSync(join(o,e),"utf8")));if(1!==i.length)throw new Error("OpenClaw native run-end facade is missing or ambiguous");const a=r(join(o,i[0]));if("function"!=typeof s.getSessionEntry||"function"!=typeof s.loadTranscriptEventsSync||"function"!=typeof s.readTranscriptStatsSync||"function"!=typeof a.waitForEmbeddedAgentRunEnd)throw new Error("OpenClaw native session contract is unavailable");const c={getEntry:(e,n)=>s.getSessionEntry({agentId:e,sessionKey:n,readConsistency:"latest"}),readEvents:(e,n,t)=>{const r={agentId:e,sessionKey:n,sessionId:t},o=s.readTranscriptStatsSync(r);if(!Number.isSafeInteger(o.sizeBytes)||o.sizeBytes<0||o.sizeBytes>1048576||!Number.isSafeInteger(o.eventCount)||o.eventCount<0||o.eventCount>6400)throw new Error("native transcript exceeds the local recovery budget; use Gateway history pagination");return s.loadTranscriptEventsSync(r)},waitForRunEnd:(e,n)=>a.waitForEmbeddedAgentRunEnd(e,n)};return adapters.set(e,c),c}function hostRoot(){if(!process.argv[1]||!existsSync(process.argv[1]))return;let e=dirname(realpathSync(resolve(process.argv[1])));for(let n=0;n<4;n++){const n=join(e,"package.json");if(existsSync(n)&&"openclaw"===JSON.parse(readFileSync(n,"utf8")).name)return e;const t=dirname(e);if(t===e)break;e=t}}
@@ -0,0 +1 @@
1
+ import{decodeResponse,QuestionError}from"../contracts/question/codec.js";import{createHash,randomUUID}from"node:crypto";import{isDeepStrictEqual}from"node:util";import{asRecord,nativeAnswers,nonEmpty,projectQuestion,questionRecord,USER_INPUT_SCHEMA}from"./question-wire.js";export function observeQuestionTool(e,t,s){const i=asRecord(t),n=asRecord(s);if(!i||!n)return;const r=i.toolName;if("ask_user"!==r)return;const o=n.runId??i.runId,a=n.toolCallId??i.toolCallId;nonEmpty(n.sessionKey)&&nonEmpty(a)&&nonEmpty(o)&&(void 0===n.agentId||nonEmpty(n.agentId))&&e.observeNativeTool(r,{sessionKey:n.sessionKey,toolCallId:a,runId:o,agentId:n.agentId})}export class OpenClawQuestionAdapter{options;turns=new Set;allowed=new Map;routes=new Map;byWire=new Map;tasks=new Set;timer;polling=!1;started=!1;onEvent=(...e)=>{if("question.requested"===e[0]&&this.background(this.accept(e[1])),"question.resolved"===e[0]){const t=asRecord(e[1])?.id;"string"==typeof t&&this.background(this.refreshRoute(t))}};onConnected=()=>{this.background(this.reconcile())};constructor(e){this.options=e}start(){this.started||(this.started=!0,this.options.gateway.on("gateway-event",this.onEvent),this.options.gateway.on("connected",this.onConnected),this.timer=setInterval(()=>this.background(this.reconcile()),this.options.heartbeatMs??3e4),this.timer.unref?.())}beginTurn(e){if(!this.started||!e.senderId.startsWith("user:")||e.senderId.length<=5)throw new Error("Question turn requires an authenticated human source");e.assertCurrent();const t=asRecord(e.deliveryContext),s=asRecord(t?.scope);if(t?.parent_message_id!==e.turnMessageId||t?.target_agent_id!==e.targetAgentId||t?.delivery_principal!==e.instanceId||t?.runtime_epoch!==e.runtimeEpoch||!["task","conversation_turn"].includes(String(s?.kind))||!nonEmpty(s?.id))throw new Error("Question origin is not source bound");const i={context:e,live:!0,ids:new Set};return this.turns.add(i),{bindRun:e=>{i.live&&(i.context.runId=e)},observeTool:(e,t)=>{this.observeTool(i,e,t)},close:()=>this.closeTurn(i)}}observeNativeTool(e,t){if(t.sessionKey&&t.toolCallId)for(const s of this.turns){const i=s.context;i.sessionKey!==t.sessionKey||t.runId&&i.runId!==t.runId||t.agentId&&i.localAgentId!==t.agentId||this.observeTool(s,e,t.toolCallId)}}observeTool(e,t,s){if("ask_user"!==t||!s||!this.current(e))return;const i=`ask_${createHash("sha256").update(`${e.context.runId}\0${s}`).digest("hex").slice(0,32)}`;e.ids.add(i),this.allowed.set(i,e),this.background(this.refreshRoute(i))}async stop(){this.started=!1,this.timer&&clearInterval(this.timer),this.options.gateway.off("gateway-event",this.onEvent),this.options.gateway.off("connected",this.onConnected),await Promise.allSettled([...this.turns].map(async e=>{try{await e.context.cancelRun("question_adapter_shutdown")}finally{this.closeTurn(e)}})),await Promise.allSettled([...this.tasks])}async handleContinue(e){const t=asRecord(e.content),s="string"==typeof t?.request_id?this.byWire.get(t.request_id):void 0;if(!s)return this.rejectMissing(e);if(!this.authorized(s,e))return;const i=(s.answering??Promise.resolve()).then(async()=>{if(!this.authorized(s,e))return;if(s.terminal)return void this.reject(s,e.id,"expired"===s.terminal?"PENDING_EXPIRED":"PENDING_ALREADY_RESOLVED");if(!s.delivered)return void this.reject(s,e.id,"PENDING_NOT_FOUND");if(s.attempt?.uncertain&&(await this.receipt(s),s.attempt?.uncertain&&!s.terminal))return"deferred";let t;try{t=decodeResponse(e.content,e.type),nativeAnswers(s.native,t)}catch(t){return void this.reject(s,e.id,t instanceof QuestionError?t.code:"INVALID_CONTENT")}await this.submit(s,e,t)});s.answering=i;try{return await i}finally{s.answering===i&&(s.answering=void 0)}}async reconcile(){if(this.started&&!this.polling&&0!==this.allowed.size){this.polling=!0;try{const e=asRecord(await this.options.gateway.request("question.list",{},5e3));if(!Array.isArray(e?.questions))throw new Error("Invalid question.list result");const t=new Set;for(const s of e.questions){const e=asRecord(s)?.id;if("string"!=typeof e||!this.allowed.has(e))continue;t.add(e),await this.accept(s);const i=this.routes.get(e);i&&i.attempt?.uncertain&&await this.receipt(i)}for(const[e,s]of this.routes)!this.current(s.turn)||s.terminal||t.has(e)||await this.refreshRoute(e)}finally{this.polling=!1}}}current(e){if(!this.started||!e.live||e.context.signal.aborted)return!1;try{return e.context.assertCurrent(),!0}catch{return!1}}authorized(e,t){return this.authorizedTurn(e.turn,t)}authorizedTurn(e,t){const s=e.context,i=asRecord(t.deliveryContext),n=asRecord(s.deliveryContext),r=asRecord(i?.scope),o=asRecord(n?.scope);return this.current(e)&&t.conversationId===s.conversationId&&t.senderId===s.senderId&&i?.target_agent_id===s.targetAgentId&&i.delivery_principal===s.instanceId&&i.runtime_epoch===s.runtimeEpoch&&i.parent_message_id===s.turnMessageId&&r?.kind===o?.kind&&r?.id===o?.id&&void 0!==o?.id&&void 0===t.replyTo&&(void 0===s.historyGeneration||t.historyGeneration===s.historyGeneration)}async rejectMissing(e){if(!this.started)return;const t=asRecord(e.content);if(!nonEmpty(t?.request_id))return;let s="PENDING_NOT_FOUND";try{decodeResponse(e.content,e.type)}catch(e){s=e instanceof QuestionError?e.code:"INVALID_CONTENT"}for(const i of this.turns)if(this.authorizedTurn(i,e))return void i.context.publishStatus({request_id:t.request_id,status:"rejected",response_message_id:e.id,error_code:s,updated_at_ms:Date.now()});const i=asRecord(e.deliveryContext);if(this.options.assertDeliveryCurrent&&i&&nonEmpty(i.parent_message_id)&&void 0===e.replyTo&&e.senderId?.startsWith("user:"))try{this.options.assertDeliveryCurrent(e);const n=await this.options.client.messages.getEnvelope(e.conversationId,i.parent_message_id);this.options.assertDeliveryCurrent(e);const r=asRecord(n.deliveryContext);if("chat_message"!==n.type||n.conversationId!==e.conversationId||n.senderId!==e.senderId||n.historyGeneration!==e.historyGeneration||!sameOrigin(r,e.deliveryContext))return;const o=`receipt_${createHash("sha256").update(`${e.conversationId}\0${e.id}\0${i.delivery_principal}`).digest("hex").slice(0,32)}`,a={conversationId:e.conversationId,clientMessageId:o,idempotencyKey:o,type:"agent_reply",deliveryContext:e.deliveryContext,content:{}},d=this.options.client.messages.startStream(a),c=await d.opened();if(this.options.assertDeliveryCurrent(e),"duplicate"===c.outcome)return;d.addPart({type:"custom",kind:"message_processing_receipt",data:{request_id:t.request_id,response_message_id:e.id,status:"rejected",error_code:s,observed_at_ms:Date.now()}}),await d.finalize()}catch{return"deferred"}}owns(e,t){const s=e.context;return t.agentId===s.localAgentId&&t.sessionKey===s.sessionKey&&t.runId===s.runId}async refreshRoute(e){const t=this.allowed.get(e);if(!t||!this.current(t))return;const s=this.routes.get(e);try{const t=asRecord(await this.options.gateway.request("question.get",{id:e},5e3));if(asRecord(t?.question)?.id!==e)return void this.markUnavailable(e,s);await this.accept(t?.question);const i=questionRecord(t?.question);if(!i||i.id!==e)return void this.markUnavailable(e,s)}catch(t){if("INVALID_REQUEST"===asRecord(t)?.code)return void this.markUnavailable(e,s);throw t}}markUnavailable(e,t){const s=this.routes.get(e);t&&s===t&&!s.terminal&&this.current(s.turn)&&(this.status(s,"unavailable"),s.terminal="unavailable")}async accept(e){const t=questionRecord(e);if(!t){const t=asRecord(e),s="string"==typeof t?.id?this.allowed.get(t.id):void 0;if(!s||!this.current(s)||t?.agentId!==s.context.localAgentId||t.sessionKey!==s.context.sessionKey||t.runId!==s.context.runId||"pending"!==t.status)return;const i=Array.isArray(t.questions)&&t.questions.some(e=>{const t=asRecord(e);return!0===t?.isSecret||void 0!==t?.secretStore});return this.sourceError(s,i?"SECRET_INPUT_UNSUPPORTED":"INVALID_CONTENT"),void await s.context.cancelRun("question_profile_unsupported")}const s=this.allowed.get(t.id);if(!s||!this.current(s)||!this.owns(s,t))return;let i=this.routes.get(t.id);if(i){if(i.terminal)return;if(i.turn!==s||JSON.stringify(i.native.questions)!==JSON.stringify(t.questions))return;i.native=t}else{if("pending"!==t.status)return;try{projectQuestion(t,"profile_validation")}catch{return this.sourceError(s,"INVALID_CONTENT"),void await s.context.cancelRun("question_profile_unsupported")}if([...this.routes.values()].some(e=>e.turn===s&&!e.terminal))return this.sourceError(s,"PENDING_INPUT_EXISTS"),void await s.context.cancelRun("question_profile_multiple_pending");i={turn:s,native:t,requestId:`qreq_${randomUUID()}`,messageId:randomUUID(),delivered:!1},this.routes.set(t.id,i),this.byWire.set(i.requestId,i)}"pending"===t.status?(i.delivered||await this.deliver(i),i.attempt?i.attempt.uncertain&&this.status(i,"unconfirmed",{submission_message_id:i.attempt.messageId}):this.status(i,i.delivered?"pending":"delivery_unconfirmed")):"answered"===t.status?i.attempt?await this.receipt(i):(this.status(i,"answered_elsewhere"),i.terminal="answered_elsewhere"):i.attempt&&"cancelled"===t.status?(this.status(i,"unconfirmed",{submission_message_id:i.attempt.messageId,native_status:"cancelled"}),i.terminal="unconfirmed"):i.attempt&&"expired"===t.status?(this.reject(i,i.attempt.messageId,"PENDING_EXPIRED"),i.terminal="expired"):(this.status(i,t.status),i.terminal=t.status)}async deliver(e){if(e.sending)return await e.sending,void(e.delivered||await this.reconcileDelivery(e));const t=(async()=>{const t=e.turn.context;if(this.current(e.turn))try{const s={conversationId:t.conversationId,agentId:t.targetAgentId,clientMessageId:e.messageId,idempotencyKey:e.messageId,type:"agent.input_required",deliveryContext:t.deliveryContext,content:projectQuestion(e.native,e.requestId)};"outcome_unknown"===(await this.options.client.messages.send(s)).outcome?await this.reconcileDelivery(e):this.current(e.turn)&&(e.delivered=!0)}catch(t){await this.reconcileDelivery(e),e.delivered||(this.status(e,"delivery_unconfirmed"),this.options.logger.warn?.("[question] durable prompt delivery unconfirmed"))}})();e.sending=t,await t}async reconcileDelivery(e){if(!this.current(e.turn))return;const t=e.turn.context;try{const s=await this.options.client.messages.getEnvelope(t.conversationId,e.messageId);!this.current(e.turn)||"agent.input_required"!==s.type||s.conversationId!==t.conversationId||s.senderId!==t.instanceId&&s.senderId!==t.targetAgentId||void 0!==t.historyGeneration&&s.historyGeneration!==t.historyGeneration||!sameOrigin(asRecord(s.deliveryContext),t.deliveryContext)||!isDeepStrictEqual(s.content,projectQuestion(e.native,e.requestId))||(e.delivered=!0)}catch{}}async submit(e,t,s){let i=!1;try{const n=asRecord(await this.options.gateway.request("question.get",{id:e.native.id},5e3)),r=questionRecord(n?.question);if(!r||!this.owns(e.turn,r)||!this.authorized(e,t))return;if("pending"!==r.status)return await this.accept(r),void this.reject(e,t.id,"expired"===r.status?"PENDING_EXPIRED":"PENDING_ALREADY_RESOLVED");if(JSON.stringify(r.questions)!==JSON.stringify(e.native.questions))return;if(Date.now()>=r.expiresAtMs)return void this.reject(e,t.id,"PENDING_EXPIRED");const o=nativeAnswers(r,s);if(!this.authorized(e,t))return;e.attempt={messageId:t.id,resolutionId:randomUUID(),uncertain:!1},this.status(e,"submitted",{submission_message_id:t.id}),i=!0;const a=asRecord(await this.options.gateway.request("question.resolve","cancelled"===s.outcome?{id:r.id,cancel:!0,resolvedBy:t.senderId}:{id:r.id,answers:o,resolvedBy:t.senderId,resolutionId:e.attempt.resolutionId},5e3));if(a?.status!==("cancelled"===s.outcome?"cancelled":"answered"))throw new Error("Invalid question.resolve result");if(!this.current(e.turn))return;this.status(e,"cancelled"===s.outcome?"cancelled":"accepted",{submission_message_id:t.id}),e.terminal="cancelled"===s.outcome?"cancelled":"accepted"}catch(s){if(!this.current(e.turn)||e.terminal)return;i&&e.attempt?!0===asRecord(s)?.gatewayRejected?(e.attempt=void 0,this.reject(e,t.id,"INVALID_CONTENT"),await this.refreshRoute(e.native.id)):(e.attempt.uncertain=!0,this.status(e,"unconfirmed",{submission_message_id:t.id}),await this.receipt(e)):this.status(e,"pending",{error_code:"question_read_unavailable"})}}async receipt(e){const t=e.attempt;if(t&&!e.terminal&&this.current(e.turn))try{const s=asRecord(await this.options.gateway.request("question.waitAnswer",{id:e.native.id,timeoutMs:1,includeResolutionId:!0},3e3));if(!this.current(e.turn)||e.attempt!==t||e.terminal)return;if("answered"===s?.status){const i=nonEmpty(s.resolutionId)?s.resolutionId===t.resolutionId?"accepted":"answered_elsewhere":"unconfirmed";"answered_elsewhere"===i?this.reject(e,t.messageId,"PENDING_ALREADY_RESOLVED"):this.status(e,i,{submission_message_id:t.messageId,native_status:"answered"}),e.terminal=i}else"cancelled"!==s?.status&&"expired"!==s?.status||("expired"===s.status?this.reject(e,t.messageId,"PENDING_EXPIRED"):this.status(e,"unconfirmed",{submission_message_id:t.messageId,native_status:"cancelled"}),e.terminal="expired"===s.status?"expired":"unconfirmed")}catch{}}sourceError(e,t){this.current(e)&&e.context.publishStatus({request_id:`qreq_${randomUUID()}`,status:"unsupported",error_code:t,updated_at_ms:Date.now()})}status(e,t,s={}){this.current(e.turn)&&e.turn.context.publishStatus({schema_version:USER_INPUT_SCHEMA,request_id:e.requestId,status:t,updated_at_ms:Date.now(),...s})}reject(e,t,s){this.status(e,"rejected",{response_message_id:t,error_code:s})}closeTurn(e){e.live=!1,this.turns.delete(e);for(const t of e.ids){this.allowed.get(t)===e&&this.allowed.delete(t);const s=this.routes.get(t);s?.turn===e&&(this.routes.delete(t),this.byWire.delete(s.requestId))}}background(e){const t=e.catch(()=>{this.options.logger.warn?.("[question] native question observation unavailable")}).finally(()=>this.tasks.delete(t));this.tasks.add(t)}}function sameOrigin(e,t){const s=asRecord(t),i=asRecord(e?.scope),n=asRecord(s?.scope);return!!(e&&s&&i&&n&&e.target_agent_id===s.target_agent_id&&e.delivery_principal===s.delivery_principal&&e?.runtime_epoch===s.runtime_epoch&&e?.parent_message_id===s.parent_message_id&&i.kind===n.kind&&i.id===n.id)}
@@ -1 +1 @@
1
- export class OpenClawRuntimeCapabilities{deps;constructor(t){this.deps=t}async execute(t,e,s){const i=t;if(i.name.startsWith("session."))return await this.deps.sessions.execute(i,e,s);if(i.name.startsWith("skills."))return await this.deps.skills.execute(i,e,s);if(i.name.startsWith("mcp."))return await this.deps.mcp.execute(i,e,s);if(i.name.startsWith("terminal."))return await this.deps.terminal.execute(i,e,s);if(i.name.startsWith("canvas."))return await this.deps.canvas.execute(i,e,s);if(i.name.startsWith("cron."))return await this.deps.cron.execute(i,e,s);const n=this.requireGateway();switch(i.name){case"models.list":return normalizeModels(await n.request("models.list",{}));case"agent.listProjection":return await this.listAgents(n)}throw new Error(`canonical capability has no owner: ${i.name}`)}async cancel(t){for(const e of[this.deps.sessions,this.deps.skills,this.deps.mcp,this.deps.terminal,this.deps.canvas,this.deps.cron]){const s=await(e.cancel?.(t));if("cancel_requested"===s)return s}return"not_cancellable"}async afterCommit(t,e){const s=t.name.startsWith("session.")?this.deps.sessions:t.name.startsWith("skills.")?this.deps.skills:t.name.startsWith("mcp.")?this.deps.mcp:t.name.startsWith("terminal.")?this.deps.terminal:t.name.startsWith("canvas.")?this.deps.canvas:t.name.startsWith("cron.")?this.deps.cron:void 0;await(s?.afterCommit?.(t,e))}async projectCommitted(t,e,s){const i=t.name.startsWith("session.")?this.deps.sessions:t.name.startsWith("skills.")?this.deps.skills:t.name.startsWith("mcp.")?this.deps.mcp:t.name.startsWith("terminal.")?this.deps.terminal:t.name.startsWith("canvas.")?this.deps.canvas:t.name.startsWith("cron.")?this.deps.cron:void 0,n=i?.projectCommitted;return!!n&&(await n.call(i,t,e,s)??!0)}requireGateway(){const t=this.deps.getGateway();if(!t?.isConnected)throw new Error("Gateway not connected");return t}async listAgents(t){const e=await t.request("agents.list",{}),s=[];for(const t of e?.agents??[]){const e=t.id?.trim();e&&s.push({runtimeAgentUid:await this.deps.identities.resolveOrCreate(e),runtimeLocalKey:e,name:t.identity?.name||t.name||e,...t.identity?.emoji?{emoji:t.identity.emoji}:{},...t.identity?.avatarUrl||t.identity?.avatar?{avatarUrl:t.identity.avatarUrl||t.identity.avatar}:{}})}return{...e?.defaultId?{defaultRuntimeLocalKey:e.defaultId}:{},agents:s}}}function normalizeModels(t){return{models:(t?.models??[]).flatMap(t=>{if(!t||"object"!=typeof t)return[];const e=t,s="string"==typeof e.id?e.id:"";if(!s)return[];const i="string"==typeof e.provider?e.provider:s.split("/")[0]||"unknown",n=Array.isArray(e.input)?e.input.filter(t=>"text"===t||"image"===t||"document"===t):void 0,a=e.pricing&&"object"==typeof e.pricing?e.pricing:void 0;return[{id:s,name:"string"==typeof e.name?e.name:s,provider:i,..."number"==typeof e.contextWindow?{contextWindow:e.contextWindow}:{},..."boolean"==typeof e.reasoning?{reasoning:e.reasoning}:{},...n?.length?{input:n}:{},..."string"==typeof a?.prompt&&"string"==typeof a.completion?{pricing:{prompt:a.prompt,completion:a.completion}}:{},..."number"==typeof e.completionMultiplier?{completionMultiplier:e.completionMultiplier}:{}}]})}}
1
+ export class OpenClawRuntimeCapabilities{deps;constructor(t){this.deps=t}async execute(t,e,s){const i=t;if(i.name.startsWith("session."))return await this.deps.sessions.execute(i,e,s);if(i.name.startsWith("skills."))return await this.deps.skills.execute(i,e,s);if(i.name.startsWith("mcp."))return await this.deps.mcp.execute(i,e,s);if(i.name.startsWith("terminal."))return await this.deps.terminal.execute(i,e,s);if(i.name.startsWith("canvas."))return await this.deps.canvas.execute(i,e,s);if(i.name.startsWith("cron."))return await this.deps.cron.execute(i,e,s);const n=this.requireGateway();switch(i.name){case"models.list":return normalizeModels(await n.request("models.list",{}));case"agent.listProjection":return await this.listAgents(n)}throw new Error(`canonical capability has no owner: ${i.name}`)}async cancel(t){for(const e of[this.deps.sessions,this.deps.skills,this.deps.mcp,this.deps.terminal,this.deps.canvas,this.deps.cron]){const s=await(e.cancel?.(t));if("cancel_requested"===s)return s}return"not_cancellable"}async afterCommit(t,e){const s=t.name.startsWith("session.")?this.deps.sessions:t.name.startsWith("skills.")?this.deps.skills:t.name.startsWith("mcp.")?this.deps.mcp:t.name.startsWith("terminal.")?this.deps.terminal:t.name.startsWith("canvas.")?this.deps.canvas:t.name.startsWith("cron.")?this.deps.cron:void 0;await(s?.afterCommit?.(t,e))}async projectCommitted(t,e,s){const i=t.name.startsWith("session.")?this.deps.sessions:t.name.startsWith("skills.")?this.deps.skills:t.name.startsWith("mcp.")?this.deps.mcp:t.name.startsWith("terminal.")?this.deps.terminal:t.name.startsWith("canvas.")?this.deps.canvas:t.name.startsWith("cron.")?this.deps.cron:void 0,n=i?.projectCommitted;return!!n&&(await n.call(i,t,e,s)??!0)}requireGateway(){const t=this.deps.getGateway();if(!t?.isConnected)throw new Error("Gateway not connected");return t}async listAgents(t){const e=await t.request("agents.list",{}),s=[];for(const t of e?.agents??[]){const e=t.id?.trim();e&&s.push({runtimeAgentUid:await this.deps.identities.resolveOrCreate(e),runtimeLocalKey:e,name:t.identity?.name||t.name||e,...t.identity?.emoji?{emoji:t.identity.emoji}:{},...t.identity?.avatarUrl||t.identity?.avatar?{avatarUrl:t.identity.avatarUrl||t.identity.avatar}:{}})}return{...e?.defaultId?{defaultRuntimeLocalKey:e.defaultId}:{},agents:s}}}function normalizeModels(t){return{models:(t?.models??[]).flatMap(t=>{if(!t||"object"!=typeof t)return[];const e=t,s="string"==typeof e.id?e.id:"";if(!s)return[];const i="string"==typeof e.provider?e.provider:s.split("/")[0]||"unknown",n=Array.isArray(e.input)?e.input.filter(t=>"text"===t||"image"===t||"document"===t):void 0,a=e.pricing&&"object"==typeof e.pricing?e.pricing:void 0;return[{id:s,name:"string"==typeof e.name?e.name:s,provider:i,..."number"==typeof e.contextWindow?{contextWindow:e.contextWindow}:{},..."boolean"==typeof e.reasoning?{reasoning:e.reasoning}:{},...runtimeReasoningOptions(e)?{reasoningOptions:runtimeReasoningOptions(e)}:{},...n?.length?{input:n}:{},..."string"==typeof a?.prompt&&"string"==typeof a.completion?{pricing:{prompt:a.prompt,completion:a.completion}}:{},..."number"==typeof e.completionMultiplier?{completionMultiplier:e.completionMultiplier}:{}}]})}}import{runtimeReasoningOptions}from"./runtime-reasoning.js";
@@ -0,0 +1 @@
1
+ import{QUESTION_SCHEMA,decodeQuestion,decodeResponse,validateResponse,QuestionError}from"../contracts/question/codec.js";export const USER_INPUT_SCHEMA=QUESTION_SCHEMA;export const LEGACY_USER_INPUT_SCHEMA="openclaw.user_input.v1";export const questionRecord=e=>{const t=asRecord(e);if(!(t&&nonEmpty(t.id)&&nonEmpty(t.agentId)&&nonEmpty(t.sessionKey)&&nonEmpty(t.runId)&&["pending","answered","cancelled","expired"].includes(String(t.status))&&"number"==typeof t.expiresAtMs&&Number.isFinite(t.expiresAtMs)&&Array.isArray(t.questions)&&0!==t.questions.length))return;const o=[];for(const e of t.questions){const t=asRecord(e);if(!(t&&!0!==t.isSecret&&void 0===t.secretStore&&void 0===t.url&&nonEmpty(t.questionId)&&"string"==typeof t.header&&nonEmpty(t.question)&&Array.isArray(t.options)))return;const s=[];for(const e of t.options){const t=asRecord(e);if(!t||!nonEmpty(t.label)||void 0!==t.description&&"string"!=typeof t.description)return;s.push({label:t.label,..."string"==typeof t.description?{description:t.description}:{}})}if(void 0!==t.multiSelect&&"boolean"!=typeof t.multiSelect||void 0!==t.isOther&&"boolean"!=typeof t.isOther)return;o.push({questionId:t.questionId,header:t.header,question:t.question,options:s,multiSelect:!0===t.multiSelect,isOther:!0===t.isOther})}return new Set(o.map(e=>e.questionId)).size===o.length?{id:t.id,agentId:t.agentId,sessionKey:t.sessionKey,runId:t.runId,status:t.status,expiresAtMs:t.expiresAtMs,questions:o}:void 0};export function projectQuestion(e,t){for(const t of e.questions)if(t.options.length<2||new Set(t.options.map(e=>e.label)).size!==t.options.length)throw new QuestionError("INVALID_CONTENT");return decodeQuestion({schema_version:USER_INPUT_SCHEMA,kind:"question",request_id:t,message:"请回答以下问题,以继续当前任务。",expires_at:new Date(e.expiresAtMs).toISOString(),questions:e.questions.map((e,t)=>({id:e.questionId,header:e.header||`问题 ${t+1}`,text:e.question,input:{type:e.multiSelect?"multi_select":"single_select",allow_other:!0===e.isOther,options:e.options.map((e,t)=>({value:`option_${t+1}`,...e}))}}))})}export function parseContinue(e){try{return decodeResponse(e)}catch{return}}export function nativeAnswers(e,t){if(validateResponse(projectQuestion(e,t.request_id),t),"cancelled"===t.outcome)return;const o=Object.create(null);for(const s of e.questions){const e=t.answers[s.questionId];o[s.questionId]=void 0!==e.text?[e.text]:e.values.map(e=>{const t=Number(e.slice(7))-1;return s.options[t].label})}return{answers:o}}export const asRecord=e=>"object"!=typeof e||null===e||Array.isArray(e)?void 0:e;export const nonEmpty=e=>"string"==typeof e&&e.length>0;
@@ -1 +1 @@
1
- import{createHash,randomUUID}from"node:crypto";import{mkdir,writeFile}from"node:fs/promises";import{homedir}from"node:os";import path,{join,relative,resolve}from"node:path";import{RUNTIME_HASH_DOMAINS,RUNTIME_METHOD_PARITY_MANIFEST,runtimeHashPreimage}from"@beeos-ai/beeos-types/runtime";import{reduceRuntimeRecoveryPolicy}from"@beeos-ai/beeos-types/runtime/internal";import{assertTrustedCoreExecutionAttempt}from"./core-execution-attempt-context.js";import{InMemoryRuntimeCommandJournal,RuntimeCommandJournalConflictError,runtimeCommandIsReplayableQuery,runtimeCommandResultHash}from"./runtime-command-journal.js";import{RuntimeProjectionTransportError}from"./agent-projection-worker.js";import{ImHotPathAbortedError}from"./im-hot-path-deferral.js";import{prepareOpenClawToolCatalog}from"./prepare-openclaw-tool-catalog.js";const DEFAULT_AGENT_ID="main",AGENT_VALID_ID_RE=/^[a-z0-9][a-z0-9_-]{0,63}$/i,AGENT_INVALID_CHARS_RE=/[^a-z0-9_-]+/g;export function normalizeRuntimeAgentLocalKey(e){const t=(e??"").trim();return t?AGENT_VALID_ID_RE.test(t)?t.toLowerCase():t.toLowerCase().replace(AGENT_INVALID_CHARS_RE,"-").replace(/^-+/,"").replace(/-+$/,"").slice(0,64)||"main":"main"}export async function awaitRuntimeProjection(e){const t=e;return await(t.awaitProjection?.()??Promise.resolve(e.getSnapshot().projection))}export function hasEffectReceiptHandoff(e){const t=e;return t.effectCommitted instanceof Promise&&"function"==typeof t.acknowledgeEffectReceipt}export class RuntimeCommandError extends Error{code;param;constructor(e,t,r,i){super(t,i),this.code=e,this.param=r,this.name="RuntimeCommandError"}}const emptyProgress=async function*(){};function deferred(){let e;return{promise:new Promise(t=>{e=t}),resolve:e}}async function waitForEffectReceipt(e,t){if(!t)return await e;if(t.aborted)throw new RuntimeCommandError("OUTCOME_UNKNOWN","MCP effect receipt was not durably published before the Service attempt ended");await new Promise((r,i)=>{const a=()=>i(new RuntimeCommandError("OUTCOME_UNKNOWN","MCP effect receipt was not durably published before the Service attempt ended"));t.addEventListener("abort",a,{once:!0}),e.then(()=>{t.removeEventListener("abort",a),r()},e=>{t.removeEventListener("abort",a),i(e)})})}export class OpenClawRuntimeCommandDispatcher{deps;logger;getOpenclawHome;createAgentId;journal;capabilities;constructor(e){this.deps=e,this.logger=e.logger??{},this.getOpenclawHome=e.getOpenclawHome??(()=>process.env.OPENCLAW_HOME||join(homedir(),".openclaw")),this.createAgentId=e.createAgentId??(()=>`agent-${randomUUID().replace(/-/g,"").slice(0,12)}`),this.journal=e.journal??new InMemoryRuntimeCommandJournal,this.capabilities=e.capabilities}setCapabilities(e){this.capabilities=e}dispatch(e,t){const r=e;assertTrustedCoreExecutionAttempt(t,{operationId:r.context.operationId,runtimeEpoch:r.context.dispatchEpoch});let i,a,n,o="running";const s=deferred(),c=deferred();let m;const d="service"===t.origin&&("mcp.set"===r.name||"mcp.unset"===r.name),p=this.executeWithLease(r,t,(e,t)=>{o="committed",m={operationId:r.context.operationId,method:r.name,record:t},s.resolve({...m,result:e,committedAt:t.updatedAt})},async()=>{d?await waitForEffectReceipt(c.promise,t.abortSignal):"acp"!==t.origin||"mcp.set"!==r.name&&"mcp.unset"!==r.name||!m?.record.mcpDesiredStateCommit||(await this.journal.releaseMcpLiveEffect({operationId:r.context.operationId,source:"acp_local"}),await this.journal.promoteMcpDesiredStateActive({operationId:r.context.operationId,source:"acp_local"}))},d,e=>{i=e},e=>{a=e}).then(e=>(o="committed",e),e=>{throw o=e instanceof RuntimeCommandError&&("OUTCOME_UNKNOWN"===e.code||"INSTANCE_EPOCH_MISMATCH"===e.code)?"outcome_unknown":"failed",s.resolve(void 0),e});return{operationId:r.context.operationId,getSnapshot:()=>({effectState:o,...i?{projection:i}:{}}),completion:p,progress:emptyProgress(),effectCommitted:s.promise,acknowledgeEffectReceipt:async e=>{if(!m||e.operationId!==m.operationId||e.method!==m.method)throw new RuntimeCommandError("OUTCOME_UNKNOWN","MCP effect receipt does not match this operation");if(!/^[a-f0-9]{64}$/.test(e.effectRecordHash))throw new RuntimeCommandError("OUTCOME_UNKNOWN","MCP effect receipt hash is invalid");await this.journal.releaseMcpLiveEffect({operationId:e.operationId,source:"service",effectRecordHash:e.effectRecordHash}),c.resolve()},acknowledgeTerminalReceipt:async e=>{if(!(d&&m&&e.operationId===m.operationId&&e.method===m.method&&/^[a-f0-9]{64}$/.test(e.effectRecordHash)&&e.terminalMessageId))throw new RuntimeCommandError("OUTCOME_UNKNOWN","MCP terminal receipt does not match this operation");await this.journal.promoteMcpDesiredStateActive({operationId:e.operationId,source:"service",effectRecordHash:e.effectRecordHash,terminalMessageId:e.terminalMessageId});const n=await this.requireReleasedRecord(e.operationId);if(void 0===n.result)throw new RuntimeCommandError("OUTCOME_UNKNOWN","active MCP desired state lost its committed result");await this.afterCommittedEffect(r,n.result,n,t,e=>{i=e},e=>{a=e})},cancel:async()=>"running"===o?{status:"cancel_requested"===await(this.capabilities?.cancel?.(r.context.operationId))?"cancel_requested":"not_cancellable"}:{status:"already_terminal"},awaitProjection:async()=>a?(n??=a(),await n):i}}async executeWithLease(e,t,r,i,a,n,o){return await this.withExclusiveLifecycle(e,t.abortSignal,()=>this.executeClaimedLifecycle(e,t,r,i,a,n,o))}async executeClaimedLifecycle(e,t,r,i,a,n,o){const s=await this.deps.leases.claim(e.context.operationId,e.context.dispatchEpoch);if(s.runtimeEpoch!==e.context.dispatchEpoch)throw await this.deps.leases.release(s),new RuntimeCommandError("INSTANCE_EPOCH_MISMATCH","runtime operation lease epoch mismatch");const c=this.deps.leases.startHeartbeat(s);try{if(runtimeCommandIsReplayableQuery(e.name))return await this.executeReplayableQuery(e,s,t,r,i);let c;await this.recoverInterruptedCreates(e.context.operationId);try{c=await this.journal.prepare({operationId:e.context.operationId,command:e.name,paramsHash:e.context.paramsHash,runtimeEpoch:s.runtimeEpoch})}catch(e){if(e instanceof RuntimeCommandJournalConflictError)throw new RuntimeCommandError("OUTCOME_UNKNOWN",e.message,void 0,{cause:e});throw e}if(("effect_committed"===c.phase||"projection_committed"===c.phase)&&void 0!==c.result){if(r(c.result,c),await i(),c=await this.requireReleasedRecord(c.operationId),void 0===c.result)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed result disappeared from command journal");return a||await this.afterCommittedEffect(e,c.result,c,t,n,o),c.result}if(("effect_committed"===c.phase||"projection_committed"===c.phase)&&"hash_only"===c.resultReceipt?.policy&&runtimeCommandIsReplayableQuery(e.name)){const a=await this.execute(e,s,t);if(runtimeCommandResultHash(a)!==c.resultReceipt.resultHash)throw new RuntimeCommandError("OUTCOME_UNKNOWN","redacted committed query result changed");return r(a,c),await i(),a}if(("effect_committed"===c.phase||"projection_committed"===c.phase)&&"hash_only"===c.resultReceipt?.policy){if(r(void 0,c),await i(),c=await this.requireReleasedRecord(c.operationId),!a){if(isRuntimeAgentMutation(e)&&(c.agentProjectionIntent||c.agentProjectionPreparationFailure)){const r=agentProjectionRecoveryResult(c.agentProjectionIntent??c.agentProjectionPreparationFailure);return await this.afterCommittedEffect(e,r,c,t,n,o),r}await this.runAfterEffect(e,void 0,c,t,n)}throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed mutation result is redacted")}if("effect_committed"===c.phase||"projection_committed"===c.phase)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed result receipt is unavailable");if("outcome_unknown"===c.phase)throw new RuntimeCommandError("OUTCOME_UNKNOWN","previous execution outcome is unknown");if("started"===c.phase&&isRuntimeAgentMutation(e)){let a;try{a=await this.recoverStartedAgentMutation(e,s,t)}catch(e){throw await this.markJournalUnknown(c),e instanceof RuntimeCommandError?e:new RuntimeCommandError("OUTCOME_UNKNOWN",`agent desired-state recovery could not prove its effect: ${errorText(e)}`,void 0,{cause:e})}const m=this.deps.projection?await this.prepareAgentProjectionCommit(e,a,t):void 0,d=await this.journal.transition({operationId:c.operationId,expectedRevision:c.revision,phase:"effect_committed",result:a,...m?{agentProjection:m}:{}});return r(a,d),await i(),await this.afterCommittedEffect(e,a,d,t,n,o),this.scheduleJournalCompaction(),a}if("started"===c.phase&&"outcome_unknown"===this.recoveryDecision(e.name,c.phase))throw await this.markJournalUnknown(c),new RuntimeCommandError("OUTCOME_UNKNOWN","imperative action crossed its execution boundary");if("failed"===c.phase)throw new RuntimeCommandError("EXECUTION_FAILED","previous execution failed");"prepared"===c.phase&&(c=await this.journal.transition({operationId:c.operationId,expectedRevision:c.revision,phase:"started"}));let m=!1;try{const d=await this.execute(e,s,t);m=!0;const p=isRuntimeAgentMutation(e)&&this.deps.projection?await this.prepareAgentProjectionCommit(e,d,t):void 0;let u;try{const e=await this.requireReleasedRecord(c.operationId);u=await this.journal.transition({operationId:e.operationId,expectedRevision:e.revision,phase:"effect_committed",result:d,...p?{agentProjection:p}:{}})}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN",`effect completed before its journal commit: ${errorText(e)}`,void 0,{cause:e})}return r(d,u),await i(),u=await this.requireReleasedRecord(u.operationId),a||await this.afterCommittedEffect(e,d,u,t,n,o),this.scheduleJournalCompaction(),d}catch(t){if(m)throw t;const r=t instanceof RuntimeCommandError&&("OUTCOME_UNKNOWN"===t.code||"INSTANCE_EPOCH_MISMATCH"===t.code);if(r&&"clear-saga"===recoveryMetadata(e.name).recoveryClass)throw t;try{await this.journal.transition({operationId:c.operationId,expectedRevision:c.revision,phase:r?"outcome_unknown":"failed",errorCode:r?"OUTCOME_UNKNOWN":"EXECUTION_FAILED"})}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN",`command and journal outcome unknown: ${errorText(e)}`,void 0,{cause:t})}throw t}}finally{try{await c.stop(),await this.deps.leases.release(s)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN",`runtime operation lease finalization unknown: ${errorText(e)}`,void 0,{cause:e})}}}async executeReplayableQuery(e,t,r,i,a){const n=await this.execute(e,t,r);return i(n,{operationId:e.context.operationId,command:e.name,paramsHash:e.context.paramsHash,runtimeEpoch:t.runtimeEpoch,phase:"effect_committed",revision:1,updatedAt:(new Date).toISOString(),resultReceipt:{policy:"hash_only",resultHash:runtimeCommandResultHash(n),redacted:{kind:"query_result",command:e.name}}}),await a(),await this.runPostCommit(e,n),n}scheduleJournalCompaction(){this.journal.compact().catch(e=>this.logger.error?.(`[runtime-journal] event=checkpoint_failed trigger=effect_committed error=${errorText(e)}`))}async execute(e,t,r){switch(e.name){case"agent.create":return await this.createAgent(e,t,r);case"agent.update":return await this.updateAgent(e);case"agent.delete":return await this.deleteAgent(e,t);case"agent.applyTemplate":return await this.applyTemplate(e,t,r)}if(!this.capabilities)throw new RuntimeCommandError("INVALID_PARAMS",`Unsupported runtime command: ${e.name}`);return await this.capabilities.execute(e,t,r)}async recoverStartedAgentMutation(e,t,r){if("agent.create"===e.name||"agent.applyTemplate"===e.name){let i=await this.bindCreateOperation(e,t,!1);if(i||(i=await this.findCreateRecoveryIdentity(e,!1),"allocated"===i.state&&void 0===i.createOperation?.paramsHash&&await this.bindCreateOperation(e,t,!1),i=await this.findCreateRecoveryIdentity(e)),"active"===i.state)return await this.recoverActiveCreateEffect(i);if(await this.runtimeAgentExists(i.observedRuntimeLocalKey??i.runtimeLocalKey)){const a={runtimeLocalKey:i.observedRuntimeLocalKey??i.runtimeLocalKey,workspacePath:join(this.getOpenclawHome(),`workspace-${i.runtimeLocalKey}`)};return"agent.create"===e.name?await this.completeCreatedAgent(e,t,r,a):await this.completeTemplateAgent(e,t,r,a)}return await this.execute(e,t,r)}const i=e.context.agent,a=await this.runtimeAgentExists(i.runtimeLocalKey);if("agent.delete"===e.name&&!a)return await this.deps.identities.commitDeleteTombstone(i.runtimeAgentUid,i.runtimeLocalKey,t),{runtimeAgentUid:i.runtimeAgentUid,runtimeLocalKey:i.runtimeLocalKey};if("agent.update"===e.name&&!a)throw new RuntimeCommandError("OUTCOME_UNKNOWN","update recovery target is absent");return await this.execute(e,t,r)}async runtimeAgentExists(e){const t=await this.requireGateway().request("agents.list",{});if(!Array.isArray(t?.agents))throw new RuntimeCommandError("OUTCOME_UNKNOWN","runtime agent directory query is incomplete");return t.agents.some(t=>null!==t&&"object"==typeof t&&(t.id===e||t.name===e))}async findCreateRecoveryIdentity(e,t=!0){const r={operationId:e.context.operationId,command:e.name,runtimeEpoch:e.context.dispatchEpoch,paramsHash:e.context.paramsHash,runtimeAgentUid:e.params.runtimeAgentUid},i=void 0!==this.deps.identities.findCreateOperation,a=i?await this.deps.identities.findCreateOperation(r):(await this.deps.identities.pendingAllocations()).filter(e=>e.operationId===r.operationId&&e.command===r.command&&e.runtimeEpoch===r.runtimeEpoch&&e.runtimeAgentUid===r.runtimeAgentUid);if(1!==a.length)throw new RuntimeCommandError("OUTCOME_UNKNOWN","create recovery identity binding is missing or ambiguous");const n=a[0];if(i&&(!n.createOperation||t&&n.createOperation.paramsHash!==r.paramsHash||n.createOperation.operationId!==r.operationId||n.createOperation.command!==r.command||n.createOperation.runtimeEpoch!==r.runtimeEpoch))throw new RuntimeCommandError("OUTCOME_UNKNOWN","create recovery identity hash binding conflicts");return n}async bindCreateOperation(e,t,r=!0){if(!this.deps.identities.findCreateOperation||!this.deps.identities.bindCreateOperation)return;const i={operationId:e.context.operationId,command:e.name,runtimeEpoch:e.context.dispatchEpoch,paramsHash:e.context.paramsHash,runtimeAgentUid:e.params.runtimeAgentUid};try{let a=await this.deps.identities.findCreateOperation(i);if(0===a.length){if(!r)throw new RuntimeCommandError("OUTCOME_UNKNOWN","create recovery identity binding is missing");if((await this.deps.identities.allocateCreate(t,e.name,e.params.runtimeAgentUid)).runtimeAgentUid!==e.params.runtimeAgentUid)throw new RuntimeCommandError("OUTCOME_UNKNOWN","create allocation UID does not match the canonical command");a=await this.deps.identities.findCreateOperation(i)}if(1!==a.length)throw new RuntimeCommandError("OUTCOME_UNKNOWN","create identity binding is missing or ambiguous");const n=a[0],o=await this.deps.identities.bindCreateOperation(n.runtimeAgentUid,n.runtimeLocalKey,{operationId:e.context.operationId,command:e.name,runtimeEpoch:e.context.dispatchEpoch,paramsHash:e.context.paramsHash});if(!o.createOperation||o.runtimeAgentUid!==e.params.runtimeAgentUid||o.createOperation.operationId!==i.operationId||o.createOperation.command!==i.command||o.createOperation.runtimeEpoch!==i.runtimeEpoch||o.createOperation.paramsHash!==i.paramsHash)throw new Error("create operation identity binding changed during compare-and-set");if("tombstoned"===o.state)throw new Error("create operation identity is tombstoned");return o}catch(e){if(e instanceof RuntimeCommandError)throw e;throw new RuntimeCommandError("OUTCOME_UNKNOWN",`create operation identity binding is corrupt: ${errorText(e)}`,void 0,{cause:e})}}async recoverActiveCreateEffect(e){const t=e.observedRuntimeLocalKey??e.runtimeLocalKey;if(!await this.runtimeAgentExists(t))throw new RuntimeCommandError("OUTCOME_UNKNOWN","active create identity is absent from the runtime directory");return{runtimeAgentUid:e.runtimeAgentUid,runtimeLocalKey:t,workspacePath:join(this.getOpenclawHome(),`workspace-${e.runtimeLocalKey}`)}}async markJournalUnknown(e){try{await this.journal.transition({operationId:e.operationId,expectedRevision:e.revision,phase:"outcome_unknown",errorCode:"OUTCOME_UNKNOWN"})}catch{}}async requireReleasedRecord(e){const t=await this.journal.get(e);if(!t)throw new RuntimeCommandError("OUTCOME_UNKNOWN","command journal record disappeared");return t}async afterCommittedEffect(e,t,r,i,a,n){if(!isRuntimeAgentMutation(e))return void await this.runAfterEffect(e,t,r,i,a);const o=await this.prepareAgentProjection(e,t,r,i,a);o&&(n(o),"acp"===i.origin&&o().catch(e=>this.logger.warn?.(`[runtime-core] deferred ACP agent projection failed: ${errorText(e)}`)))}async prepareAgentProjectionCommit(e,t,r){const i=agentProjectionRecoverySummary(e,t,r);try{const r=await this.deps.projection.prepareCommittedMutation({command:e,result:t,...i.expectedPlatformAgentId?{expectedPlatformAgentId:i.expectedPlatformAgentId}:{}});return Object.freeze({...r,...i})}catch(e){const t=!(e instanceof RuntimeProjectionTransportError)||e.retryable;return this.logger.warn?.(`[runtime-core] agent projection preparation ${t?"deferred":"blocked"}: ${errorText(e)}`),Object.freeze({...i,state:t?"pending":"blocked",errorKind:t?"snapshot_retryable":"snapshot_nonretryable"})}}async prepareAgentProjection(e,t,r,i,a){if("projection_committed"===r.phase)return a(r.projectionReceipt?.snapshot??Object.freeze({state:"synced",revision:`${Math.max(0,r.revision-1)}`})),r.agentProjectionIntent&&await this.compactAgentProjectionReference(r.agentProjectionIntent),void await this.runPostCommit(e,t);if("effect_committed"!==r.phase||!this.deps.projection)return;let n=r,o=n.agentProjectionIntent;const s=n.agentProjectionPreparationFailure;if(o&&"blocked"===n.agentProjectionTerminal?.state)return a(Object.freeze({state:"blocked",revision:n.agentProjectionTerminal.revision})),await this.compactAgentProjectionReference(o),void await this.runPostCommit(e,t);let c;return o&&a(Object.freeze({state:"pending",revision:o.projectionRevision})),async()=>(c??=(async()=>{if(!o){if(!s||"blocked"===s.state)return Object.freeze({state:"blocked",revision:`${Math.max(0,n.revision)}`});const t=await this.prepareAgentProjectionCommit(e,agentProjectionRecoveryResult(s),i);if(!isProjectionIntent(t))return"blocked"===t.state?Object.freeze({state:"blocked",revision:`${Math.max(0,n.revision)}`}):Object.freeze({state:"pending",revision:`${Math.max(0,n.revision)}`});o=t;try{n=await this.journal.recordAgentProjectionIntent({operationId:n.operationId,expectedRevision:n.revision,intent:o})}catch(e){return void this.logger.warn?.(`[runtime-core] agent projection reservation recovery deferred: ${errorText(e)}`)}a(Object.freeze({state:"pending",revision:o.projectionRevision}))}const r=Object.freeze({state:"pending",revision:o.projectionRevision});let c;try{c=await this.deps.projection.applyCommittedMutation(o)}catch(e){this.logger.warn?.(`[runtime-core] agent projection receipt deferred: ${errorText(e)}`),c=r}if(c.revision!==o.projectionRevision&&(c=Object.freeze({state:"blocked",revision:o.projectionRevision})),"synced"===c.state)try{n=await this.journal.transition({operationId:n.operationId,expectedRevision:n.revision,phase:"projection_committed",projectionSnapshot:c}),await this.compactAgentProjectionReference(o)}catch(e){this.logger.warn?.(`[runtime-core] projection phase commit deferred: ${errorText(e)}`),c=Object.freeze({state:"pending",revision:o.projectionRevision})}if("blocked"===c.state)try{n=await this.journal.recordAgentProjectionBlocked({operationId:n.operationId,expectedRevision:n.revision,revision:o.projectionRevision}),await this.compactAgentProjectionReference(o)}catch(e){this.logger.warn?.(`[runtime-core] blocked projection terminal commit deferred: ${errorText(e)}`),c=r}return"synced"===c.state&&c.platformAgentId&&"projection_committed"===n.phase&&this.reportTemplateOriginBestEffort(e,c.platformAgentId),a(c),await this.runPostCommit(e,t),c})(),await c)}async compactAgentProjectionReference(e){if(this.deps.projection)try{await this.deps.projection.compactCommittedMutation(e)}catch(e){this.logger.warn?.(`[runtime-core] projection reference compaction deferred: ${errorText(e)}`)}}reportTemplateOriginBestEffort(e,t){if("agent.applyTemplate"!==e.name||!this.deps.templateOriginReporter)return;const r=e.params.templateId;r&&this.deps.templateOriginReporter.report({platformAgentId:t,templateId:r}).catch(e=>{this.logger.warn?.(`[runtime-core] active template origin report failed, client fallback remains: ${errorText(e)}`)})}async runAfterEffect(e,t,r,i,a){if("projection_committed"===r.phase)return a(r.projectionReceipt?.snapshot??Object.freeze({state:"synced",revision:`${Math.max(0,r.revision-1)}`})),void await this.runPostCommit(e,t);const n="effect_committed"===r.phase&&await this.runProjection(e,t,i),o=!0===n?Object.freeze({state:"synced",revision:`${r.revision}`}):n&&"object"==typeof n?Object.freeze({...n,revision:`${r.revision}`}):"session.setModel"===e.name?Object.freeze({state:"pending",revision:`${r.revision}`}):void 0;if("synced"===o?.state)try{const e=o;await this.journal.transition({operationId:r.operationId,expectedRevision:r.revision,phase:"projection_committed",projectionSnapshot:e}),a(o)}catch(e){return this.logger.warn?.(`[runtime-core] projection phase commit deferred: ${errorText(e)}`),void a(Object.freeze({revision:o.revision,state:"pending"}))}else o&&a(o);await this.runPostCommit(e,t)}async runPostCommit(e,t){if(this.capabilities?.afterCommit)try{await this.capabilities.afterCommit(e,t)}catch(e){this.logger.warn?.(`[runtime-core] post-commit action failed: ${errorText(e)}`)}}async runProjection(e,t,r){if(!recoveryMetadata(e.name).projectionRequired)return!1;try{return!isRuntimeAgentMutation(e)&&(await(this.capabilities?.projectCommitted?.(e,t,r))??!1)}catch(e){return this.logger.warn?.(`[runtime-core] agent projection deferred: ${errorText(e)}`),!1}}recoveryDecision(e,t){const r=recoveryMetadata(e);return reduceRuntimeRecoveryPolicy({...r,messageServicePhase:"queued",executionBoundaryCrossed:"prepared"!==t,lineageContinuity:"continuous",journalState:"available",journalPhase:t})}requireGateway(){const e=this.deps.getGateway();if(!e?.isConnected)throw new RuntimeCommandError("GATEWAY_NOT_CONNECTED","Gateway not connected");return e}exclusiveLifecycleReason(e){switch(e.name){case"agent.applyTemplate":return"applyTemplate";case"agent.create":return"createAgent";case"agent.delete":return"deleteAgent";case"agent.update":return"updateAgent";default:return}}async withExclusiveLifecycle(e,t,r){const i=this.exclusiveLifecycleReason(e);if(!i)return await r();if(this.deps.runExclusive)try{return await this.deps.runExclusive(i,r,t)}catch(e){if(e instanceof ImHotPathAbortedError)throw new RuntimeCommandError("INVALID_PARAMS",`${i} aborted while waiting for in-flight chat`);throw e}return await(this.deps.waitForChatIdle?.(i,t)),await r()}async createAgentShell(e,t,r,i,a,n){const o=this.requireGateway(),s=(await this.deps.identities.pendingAllocations()).find(t=>t.runtimeAgentUid===e),c=n??s?.runtimeLocalKey??this.createAgentId(),m=join(this.getOpenclawHome(),`workspace-${c}`);let d;try{if(a&&!this.deps.declareModel)throw new Error("OpenClaw model configuration runtime is unavailable");const e=a?await this.deps.declareModel(a):void 0;d=await o.request("agents.create",{name:c,workspace:m,...e?{model:e}:{},...i?.emoji?{emoji:i.emoji}:{},...i?.avatar?{avatar:i.avatar}:{}})}catch(r){if(isDeterministicAgentsCreateParamsRejection(r)&&(void 0!==n||void 0!==s))try{await this.deps.identities.tombstone(e,c,t)}catch(e){this.logger.warn?.(`[runtime-core] rejected-create allocation cleanup deferred: ${errorText(e)}`)}throw r}const p=d?.agentId??c,u=d?.workspace??m;if(await this.deps.identities.observeEffectKey(e,c,p,t),p!==c)throw new RuntimeCommandError("OUTCOME_UNKNOWN",`Create agent outcome unknown: gateway changed reserved local key to ${p}`);try{await o.request("agents.update",{agentId:p,name:r})}catch(e){this.logger.warn?.(`[runtime-core] display-name update failed agent=${p}: ${errorText(e)}`)}return{runtimeLocalKey:p,workspacePath:u}}async createAgent(e,t,r){const i=e.params.name.trim();if(!i)throw new RuntimeCommandError("INVALID_PARAMS","Missing agent name");try{const a=await this.bindCreateOperation(e,t);if("active"===a?.state)return await this.recoverActiveCreateEffect(a);const n=await this.createAgentShell(e.params.runtimeAgentUid,t,i,e.params.identity,e.params.defaultModelId,a?.runtimeLocalKey);return await this.completeCreatedAgent(e,t,r,n)}catch(e){throw this.executionError("Create agent",e)}}async updateAgent(e){const{runtimeAgentUid:t,runtimeLocalKey:r}=e.context.agent;if(!r.trim())throw new RuntimeCommandError("MISSING_PARAM","Missing agentId","agentId");const i=e.params,a=i.name?.trim(),n=i.defaultModelId,o=i.identity?.emoji?.trim(),s=i.identity?.avatar?.trim();if(!(a||n||o||s||void 0!==i.description||void 0!==i.version||void 0!==i.capabilities||void 0!==i.skills||void 0!==i.avatarUrl||void 0!==i.homepage||void 0!==i.status||void 0!==i.identity?.vibe))throw new RuntimeCommandError("INVALID_PARAMS","No updatable fields provided (name/model/identity)");try{if(await this.deps.identities.requireActive(t,r),n&&!this.deps.declareModel)throw new Error("OpenClaw model configuration runtime is unavailable");const e=n?await this.deps.declareModel(n):void 0;return await this.requireGateway().request("agents.update",{agentId:r,...a?{name:a}:{},...e?{model:e}:{},...o?{emoji:o}:{},...s?{avatar:s}:{},...i.identity?.vibe?{vibe:i.identity.vibe}:{},...void 0!==i.description?{description:i.description}:{},...void 0!==i.version?{version:i.version}:{},...void 0!==i.capabilities?{capabilities:i.capabilities}:{},...void 0!==i.skills?{skills:i.skills}:{},...void 0!==i.avatarUrl?{avatarUrl:i.avatarUrl}:{},...void 0!==i.homepage?{homepage:i.homepage}:{},...void 0!==i.status?{status:i.status}:{}}),{runtimeAgentUid:t,runtimeLocalKey:r}}catch(e){throw this.executionError("Update agent",e)}}async deleteAgent(e,t){const{runtimeAgentUid:r,runtimeLocalKey:i}=e.context.agent;if(!i.trim())throw new RuntimeCommandError("MISSING_PARAM","Missing agentId","agentId");if("main"===normalizeRuntimeAgentLocalKey(i))throw new RuntimeCommandError("INVALID_PARAMS",'"main" cannot be deleted; delete the instance instead');try{if("tombstoned"===await this.deps.identities.requireDeleteTarget(r,i))return{runtimeAgentUid:r,runtimeLocalKey:i};if(!await this.runtimeAgentExists(i))return await this.deps.identities.commitDeleteTombstone(r,i,t),{runtimeAgentUid:r,runtimeLocalKey:i};const a=requireCommittedOpenClawDeleteAck(await this.requireGateway().request("agents.delete",{agentId:i,deleteFiles:e.params.deleteFiles??!0}),i);try{await this.deps.identities.commitDeleteTombstone(r,i,t)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN",`Delete agent outcome unknown: identity tombstone failed: ${errorText(e)}`,void 0,{cause:e})}return{runtimeAgentUid:r,runtimeLocalKey:i,...void 0===a.removedBindings?{}:{removedBindings:a.removedBindings}}}catch(e){throw this.executionError("Delete agent",e)}}async applyTemplate(e,t,r){const i=e.params.name.trim();if(!i)throw new RuntimeCommandError("INVALID_PARAMS","Missing agent name");this.requireGateway();try{const a=await this.bindCreateOperation(e,t);if("active"===a?.state)return await this.recoverActiveCreateEffect(a);const n=await r.resources.readVerifiedArtifact(e.params.artifact),o=await this.createAgentShell(e.params.runtimeAgentUid,t,i,e.params.identity,e.params.defaultModelId,a?.runtimeLocalKey);return await this.completeTemplateAgent(e,t,r,o,n)}catch(e){throw this.executionError("Apply template",e)}}async completeCreatedAgent(e,t,r,i){for(const t of e.params.bootstrapFiles??[]){if("IDENTITY.md"===t.name){this.logger.warn?.("[runtime-core] agent.create ignoring IDENTITY.md; identity is structured");continue}const e=await r.resources.readContent(t.contentRef);try{await this.requireGateway().request("agents.files.set",{agentId:i.runtimeLocalKey,name:t.name,content:e})}catch(e){this.logger.warn?.(`[runtime-core] bootstrap write failed file=${t.name}: ${errorText(e)}`)}}try{await this.deps.identities.activate(e.params.runtimeAgentUid,i.runtimeLocalKey,t)}catch(r){throw await this.compensateCreatedAgent(e.params.runtimeAgentUid,i.runtimeLocalKey,t,r,"Create agent"),new RuntimeCommandError("EXECUTION_FAILED",`Create agent failed after compensation: ${errorText(r)}`)}return await this.prepareAgentToolCatalog(i.runtimeLocalKey),{runtimeAgentUid:e.params.runtimeAgentUid,runtimeLocalKey:i.runtimeLocalKey,workspacePath:i.workspacePath}}async completeTemplateAgent(e,t,r,i,a){const n=a??await r.resources.readVerifiedArtifact(e.params.artifact);try{for(const[e,t]of n.workspaceFiles){const r=resolve(i.workspacePath,e),a=relative(i.workspacePath,r);if(""===a||a.startsWith("..")||path.isAbsolute(a))throw new Error(`refusing to write outside workspace: ${e}`);await(this.deps.mkdirWorkspace??mkdir)(path.dirname(r),{recursive:!0}),await(this.deps.writeWorkspaceFile??writeFile)(r,t)}await this.deps.identities.activate(e.params.runtimeAgentUid,i.runtimeLocalKey,t)}catch(r){throw await this.compensateCreatedAgent(e.params.runtimeAgentUid,i.runtimeLocalKey,t,r,"Apply template"),new RuntimeCommandError("EXECUTION_FAILED",`Apply template failed after compensation: ${errorText(r)}`,void 0,{cause:r})}return await this.prepareAgentToolCatalog(i.runtimeLocalKey),{runtimeAgentUid:e.params.runtimeAgentUid,runtimeLocalKey:i.runtimeLocalKey,workspacePath:i.workspacePath}}async prepareAgentToolCatalog(e){await prepareOpenClawToolCatalog({request:(e,t)=>this.requireGateway().request(e,t),agentId:e,mode:"catalog",keyKind:"boot",logger:this.logger})}executionError(e,t){return t instanceof RuntimeCommandError?t:(this.logger.error?.(`[runtime-core] ${e.toLowerCase()} failed: ${errorText(t)}`),new RuntimeCommandError("EXECUTION_FAILED",`${e} failed: ${errorText(t)}`,void 0,{cause:t}))}async compensateCreatedAgent(e,t,r,i,a){try{const i=this.requireGateway();requireCommittedOpenClawDeleteAck(await i.request("agents.delete",{agentId:t,deleteFiles:!0}),t),await this.deps.identities.tombstone(e,t,r)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN",`${a} outcome unknown after ${errorText(i)}; compensation unproven: ${errorText(e)}`,void 0,{cause:e})}}async recoverInterruptedCreates(e){const t=await this.deps.identities.pendingAllocations();for(const r of t){if(r.operationId===e)continue;const t=await this.deps.leases.claimExpiredForRecovery(r.operationId);if(!t)continue;const i=this.deps.leases.startHeartbeat(t);try{await this.deps.identities.adoptRecoveryLease(r.runtimeAgentUid,r.runtimeLocalKey,t);const e=r.observedRuntimeLocalKey;if(!e){const e=r.createOperation?.operationId??r.operationId,i=await this.journal.get(e);if("failed"===i?.phase&&i.command===r.command&&!await this.runtimeAgentExists(r.runtimeLocalKey)){await this.deps.identities.tombstone(r.runtimeAgentUid,r.runtimeLocalKey,t);continue}throw new Error("no persisted gateway effect key; absence cannot be proven")}requireCommittedOpenClawDeleteAck(await this.requireGateway().request("agents.delete",{agentId:e,deleteFiles:!0}),e),await this.deps.identities.tombstone(r.runtimeAgentUid,r.runtimeLocalKey,t)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN",`Interrupted ${r.command} recovery outcome unknown for operation ${r.operationId}: ${errorText(e)}`,void 0,{cause:e})}finally{let e;try{await i.stop()}catch(t){e=t}try{await this.deps.leases.release(t)}catch(t){e??=t}if(e)throw new RuntimeCommandError("OUTCOME_UNKNOWN",`Interrupted recovery lease finalization unknown: ${errorText(e)}`,void 0,{cause:e})}}}}function isRuntimeAgentMutation(e){return"agent.create"===e.name||"agent.update"===e.name||"agent.delete"===e.name||"agent.applyTemplate"===e.name}function servicePlatformAgentId(e){const t=e.verifiedMessageGrant?.claims;return"agent"===t?.scope?t.platformAgentId:void 0}function agentCoreResultHash(e,t){return createHash("sha256").update(runtimeHashPreimage(RUNTIME_HASH_DOMAINS.coreResult,{method:e.name.replace(".","/"),result:t})).digest("hex")}function agentProjectionRecoverySummary(e,t,r){const i="agent.update"===e.name||"agent.delete"===e.name?e.context.agent:createProjectionTarget(e,t),a=t;return Object.freeze({schemaVersion:1,operationId:e.context.operationId,method:e.name,runtimeEpoch:e.context.dispatchEpoch,runtimeAgentUid:i.runtimeAgentUid,runtimeLocalKey:i.runtimeLocalKey,coreResultHash:agentCoreResultHash(e,t),...servicePlatformAgentId(r)?{expectedPlatformAgentId:servicePlatformAgentId(r)}:{},..."agent.delete"===e.name&&Number.isSafeInteger(a?.removedBindings)?{removedBindings:a.removedBindings}:{}})}function createProjectionTarget(e,t){const r=t;if(!r||r.runtimeAgentUid!==e.params.runtimeAgentUid||"string"!=typeof r.runtimeLocalKey||!r.runtimeLocalKey)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed agent effect lacks a recoverable local identity");return{runtimeAgentUid:r.runtimeAgentUid,runtimeLocalKey:r.runtimeLocalKey}}function agentProjectionRecoveryResult(e){return Object.freeze({runtimeAgentUid:e.runtimeAgentUid,runtimeLocalKey:e.runtimeLocalKey,...void 0===e.removedBindings?{}:{removedBindings:e.removedBindings}})}function isProjectionIntent(e){return"projectionRevision"in e}function recoveryMetadata(e){const t=RUNTIME_METHOD_PARITY_MANIFEST.filter(t=>t.serviceAllowed&&t.canonicalCommand===e),r=t[0]?.recoveryClass;return r?{recoveryClass:r,projectionRequired:"mcp.set"===e||"mcp.unset"===e||t.some(e=>!0===e.projectionRequired)}:{recoveryClass:"imperative-ambiguous",projectionRequired:!1}}export function isDeterministicAgentsCreateParamsRejection(e){return e instanceof Error&&/^invalid agents\.create params\b/.test(e.message)}export function requireCommittedOpenClawDeleteAck(e,t){if(!e||"object"!=typeof e)throw new Error("gateway delete lacks the committed target acknowledgement");const r=e,i=Object.keys(r).every(e=>"ok"===e||"agentId"===e||"removedBindings"===e),a=void 0===r.removedBindings||Number.isSafeInteger(r.removedBindings)&&r.removedBindings>=0;if(!i||!0!==r.ok||r.agentId!==t||!a)throw new Error("gateway delete lacks the committed target acknowledgement");return{ok:!0,agentId:t,...void 0===r.removedBindings?{}:{removedBindings:r.removedBindings}}}function errorText(e){return e instanceof Error?e.message:String(e)}
1
+ import{createHash,randomUUID}from"node:crypto";import{mkdir,writeFile}from"node:fs/promises";import{homedir}from"node:os";import path,{join,relative,resolve}from"node:path";import{RUNTIME_HASH_DOMAINS,RUNTIME_METHOD_PARITY_MANIFEST,runtimeHashPreimage}from"@beeos-ai/beeos-types/runtime";import{reduceRuntimeRecoveryPolicy}from"@beeos-ai/beeos-types/runtime/internal";import{assertTrustedCoreExecutionAttempt}from"./core-execution-attempt-context.js";import{InMemoryRuntimeCommandJournal,RuntimeCommandJournalConflictError,runtimeCommandIsReplayableQuery,runtimeCommandResultHash}from"./runtime-command-journal.js";import{RuntimeProjectionTransportError}from"./agent-projection-worker.js";import{ImHotPathAbortedError}from"./im-hot-path-deferral.js";import{prepareOpenClawToolCatalog}from"./prepare-openclaw-tool-catalog.js";const DEFAULT_AGENT_ID="main",AGENT_VALID_ID_RE=/^[a-z0-9][a-z0-9_-]{0,63}$/i,AGENT_INVALID_CHARS_RE=/[^a-z0-9_-]+/g;export function normalizeRuntimeAgentLocalKey(e){const t=(e??"").trim();return t?AGENT_VALID_ID_RE.test(t)?t.toLowerCase():t.toLowerCase().replace(AGENT_INVALID_CHARS_RE,"-").replace(/^-+/,"").replace(/-+$/,"").slice(0,64)||"main":"main"}export async function awaitRuntimeProjection(e){const t=e;return await(t.awaitProjection?.()??Promise.resolve(e.getSnapshot().projection))}export function hasEffectReceiptHandoff(e){const t=e;return t.effectCommitted instanceof Promise&&"function"==typeof t.acknowledgeEffectReceipt}export class RuntimeCommandError extends Error{code;param;constructor(e,t,r,i){super(t,i),this.code=e,this.param=r,this.name="RuntimeCommandError"}}const emptyProgress=async function*(){};function deferred(){let e;return{promise:new Promise(t=>{e=t}),resolve:e}}async function waitForEffectReceipt(e,t){if(!t)return await e;if(t.aborted)throw new RuntimeCommandError("OUTCOME_UNKNOWN","MCP effect receipt was not durably published before the Service attempt ended");await new Promise((r,i)=>{const a=()=>i(new RuntimeCommandError("OUTCOME_UNKNOWN","MCP effect receipt was not durably published before the Service attempt ended"));t.addEventListener("abort",a,{once:!0}),e.then(()=>{t.removeEventListener("abort",a),r()},e=>{t.removeEventListener("abort",a),i(e)})})}export class OpenClawRuntimeCommandDispatcher{deps;logger;getOpenclawHome;createAgentId;journal;capabilities;constructor(e){this.deps=e,this.logger=e.logger??{},this.getOpenclawHome=e.getOpenclawHome??(()=>process.env.OPENCLAW_HOME||join(homedir(),".openclaw")),this.createAgentId=e.createAgentId??(()=>`agent-${randomUUID().replace(/-/g,"").slice(0,12)}`),this.journal=e.journal??new InMemoryRuntimeCommandJournal,this.capabilities=e.capabilities}setCapabilities(e){this.capabilities=e}dispatch(e,t){const r=e;assertTrustedCoreExecutionAttempt(t,{operationId:r.context.operationId,runtimeEpoch:r.context.dispatchEpoch});let i,a,n,o="running";const s=deferred(),c=deferred();let m;const d="service"===t.origin&&("mcp.set"===r.name||"mcp.unset"===r.name),p=this.executeWithLease(r,t,(e,t)=>{o="committed",m={operationId:r.context.operationId,method:r.name,record:t},s.resolve({...m,result:e,committedAt:t.updatedAt})},async()=>{d?await waitForEffectReceipt(c.promise,t.abortSignal):"acp"!==t.origin||"mcp.set"!==r.name&&"mcp.unset"!==r.name||!m?.record.mcpDesiredStateCommit||(await this.journal.releaseMcpLiveEffect({operationId:r.context.operationId,source:"acp_local"}),await this.journal.promoteMcpDesiredStateActive({operationId:r.context.operationId,source:"acp_local"}))},d,e=>{i=e},e=>{a=e}).then(e=>(o="committed",e),e=>{throw o=e instanceof RuntimeCommandError&&("OUTCOME_UNKNOWN"===e.code||"INSTANCE_EPOCH_MISMATCH"===e.code)?"outcome_unknown":"failed",s.resolve(void 0),e});return{operationId:r.context.operationId,getSnapshot:()=>({effectState:o,...i?{projection:i}:{}}),completion:p,progress:emptyProgress(),effectCommitted:s.promise,acknowledgeEffectReceipt:async e=>{if(!m||e.operationId!==m.operationId||e.method!==m.method)throw new RuntimeCommandError("OUTCOME_UNKNOWN","MCP effect receipt does not match this operation");if(!/^[a-f0-9]{64}$/.test(e.effectRecordHash))throw new RuntimeCommandError("OUTCOME_UNKNOWN","MCP effect receipt hash is invalid");await this.journal.releaseMcpLiveEffect({operationId:e.operationId,source:"service",effectRecordHash:e.effectRecordHash}),c.resolve()},acknowledgeTerminalReceipt:async e=>{if(!(d&&m&&e.operationId===m.operationId&&e.method===m.method&&/^[a-f0-9]{64}$/.test(e.effectRecordHash)&&e.terminalMessageId))throw new RuntimeCommandError("OUTCOME_UNKNOWN","MCP terminal receipt does not match this operation");await this.journal.promoteMcpDesiredStateActive({operationId:e.operationId,source:"service",effectRecordHash:e.effectRecordHash,terminalMessageId:e.terminalMessageId});const n=await this.requireReleasedRecord(e.operationId);if(void 0===n.result)throw new RuntimeCommandError("OUTCOME_UNKNOWN","active MCP desired state lost its committed result");await this.afterCommittedEffect(r,n.result,n,t,e=>{i=e},e=>{a=e})},cancel:async()=>"running"===o?{status:"cancel_requested"===await(this.capabilities?.cancel?.(r.context.operationId))?"cancel_requested":"not_cancellable"}:{status:"already_terminal"},awaitProjection:async()=>a?(n??=a(),await n):i}}async executeWithLease(e,t,r,i,a,n,o){return await this.withExclusiveLifecycle(e,t.abortSignal,()=>this.executeClaimedLifecycle(e,t,r,i,a,n,o))}async executeClaimedLifecycle(e,t,r,i,a,n,o){const s=await this.deps.leases.claim(e.context.operationId,e.context.dispatchEpoch);if(s.runtimeEpoch!==e.context.dispatchEpoch)throw await this.deps.leases.release(s),new RuntimeCommandError("INSTANCE_EPOCH_MISMATCH","runtime operation lease epoch mismatch");const c=this.deps.leases.startHeartbeat(s);try{if(runtimeCommandIsReplayableQuery(e.name))return await this.executeReplayableQuery(e,s,t,r,i);let c;await this.recoverInterruptedCreates(e.context.operationId);try{c=await this.journal.prepare({operationId:e.context.operationId,command:e.name,paramsHash:e.context.paramsHash,runtimeEpoch:s.runtimeEpoch})}catch(e){if(e instanceof RuntimeCommandJournalConflictError)throw new RuntimeCommandError("OUTCOME_UNKNOWN",e.message,void 0,{cause:e});throw e}if(("effect_committed"===c.phase||"projection_committed"===c.phase)&&void 0!==c.result){if(r(c.result,c),await i(),c=await this.requireReleasedRecord(c.operationId),void 0===c.result)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed result disappeared from command journal");return a||await this.afterCommittedEffect(e,c.result,c,t,n,o),c.result}if(("effect_committed"===c.phase||"projection_committed"===c.phase)&&"hash_only"===c.resultReceipt?.policy&&runtimeCommandIsReplayableQuery(e.name)){const a=await this.execute(e,s,t);if(runtimeCommandResultHash(a)!==c.resultReceipt.resultHash)throw new RuntimeCommandError("OUTCOME_UNKNOWN","redacted committed query result changed");return r(a,c),await i(),a}if(("effect_committed"===c.phase||"projection_committed"===c.phase)&&"hash_only"===c.resultReceipt?.policy){if(r(void 0,c),await i(),c=await this.requireReleasedRecord(c.operationId),!a){if(isRuntimeAgentMutation(e)&&(c.agentProjectionIntent||c.agentProjectionPreparationFailure)){const r=agentProjectionRecoveryResult(c.agentProjectionIntent??c.agentProjectionPreparationFailure);return await this.afterCommittedEffect(e,r,c,t,n,o),r}await this.runAfterEffect(e,void 0,c,t,n)}throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed mutation result is redacted")}if("effect_committed"===c.phase||"projection_committed"===c.phase)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed result receipt is unavailable");if("outcome_unknown"===c.phase)throw new RuntimeCommandError("OUTCOME_UNKNOWN","previous execution outcome is unknown");if("started"===c.phase&&isRuntimeAgentMutation(e)){let a;try{a=await this.recoverStartedAgentMutation(e,s,t)}catch(e){throw await this.markJournalUnknown(c),e instanceof RuntimeCommandError?e:new RuntimeCommandError("OUTCOME_UNKNOWN",`agent desired-state recovery could not prove its effect: ${errorText(e)}`,void 0,{cause:e})}const m=this.deps.projection?await this.prepareAgentProjectionCommit(e,a,t):void 0,d=await this.journal.transition({operationId:c.operationId,expectedRevision:c.revision,phase:"effect_committed",result:a,...m?{agentProjection:m}:{}});return r(a,d),await i(),await this.afterCommittedEffect(e,a,d,t,n,o),this.scheduleJournalCompaction(),a}if("started"===c.phase&&"outcome_unknown"===this.recoveryDecision(e.name,c.phase))throw await this.markJournalUnknown(c),new RuntimeCommandError("OUTCOME_UNKNOWN","imperative action crossed its execution boundary");if("failed"===c.phase)throw new RuntimeCommandError("EXECUTION_FAILED","previous execution failed");"prepared"===c.phase&&(c=await this.journal.transition({operationId:c.operationId,expectedRevision:c.revision,phase:"started"}));let m=!1;try{const d=await this.execute(e,s,t);m=!0;const p=isRuntimeAgentMutation(e)&&this.deps.projection?await this.prepareAgentProjectionCommit(e,d,t):void 0;let u;try{const e=await this.requireReleasedRecord(c.operationId);u=await this.journal.transition({operationId:e.operationId,expectedRevision:e.revision,phase:"effect_committed",result:d,...p?{agentProjection:p}:{}})}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN",`effect completed before its journal commit: ${errorText(e)}`,void 0,{cause:e})}return r(d,u),await i(),u=await this.requireReleasedRecord(u.operationId),a||await this.afterCommittedEffect(e,d,u,t,n,o),this.scheduleJournalCompaction(),d}catch(t){if(m)throw t;const r=t instanceof RuntimeCommandError&&("OUTCOME_UNKNOWN"===t.code||"INSTANCE_EPOCH_MISMATCH"===t.code);if(r&&"clear-saga"===recoveryMetadata(e.name).recoveryClass)throw t;try{await this.journal.transition({operationId:c.operationId,expectedRevision:c.revision,phase:r?"outcome_unknown":"failed",errorCode:r?"OUTCOME_UNKNOWN":"EXECUTION_FAILED"})}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN",`command and journal outcome unknown: ${errorText(e)}`,void 0,{cause:t})}throw t}}finally{try{await c.stop(),await this.deps.leases.release(s)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN",`runtime operation lease finalization unknown: ${errorText(e)}`,void 0,{cause:e})}}}async executeReplayableQuery(e,t,r,i,a){const n=await this.execute(e,t,r);return i(n,{operationId:e.context.operationId,command:e.name,paramsHash:e.context.paramsHash,runtimeEpoch:t.runtimeEpoch,phase:"effect_committed",revision:1,updatedAt:(new Date).toISOString(),resultReceipt:{policy:"hash_only",resultHash:runtimeCommandResultHash(n),redacted:{kind:"query_result",command:e.name}}}),await a(),await this.runPostCommit(e,n),n}scheduleJournalCompaction(){this.journal.compact().catch(e=>this.logger.error?.(`[runtime-journal] event=checkpoint_failed trigger=effect_committed error=${errorText(e)}`))}async execute(e,t,r){switch(e.name){case"agent.create":return await this.createAgent(e,t,r);case"agent.update":return await this.updateAgent(e);case"agent.delete":return await this.deleteAgent(e,t);case"agent.applyTemplate":return await this.applyTemplate(e,t,r)}if(!this.capabilities)throw new RuntimeCommandError("INVALID_PARAMS",`Unsupported runtime command: ${e.name}`);return await this.capabilities.execute(e,t,r)}async recoverStartedAgentMutation(e,t,r){if("agent.create"===e.name||"agent.applyTemplate"===e.name){let i=await this.bindCreateOperation(e,t,!1);if(i||(i=await this.findCreateRecoveryIdentity(e,!1),"allocated"===i.state&&void 0===i.createOperation?.paramsHash&&await this.bindCreateOperation(e,t,!1),i=await this.findCreateRecoveryIdentity(e)),"active"===i.state)return await this.recoverActiveCreateEffect(i);if(await this.runtimeAgentExists(i.observedRuntimeLocalKey??i.runtimeLocalKey)){const a={runtimeLocalKey:i.observedRuntimeLocalKey??i.runtimeLocalKey,workspacePath:join(this.getOpenclawHome(),`workspace-${i.runtimeLocalKey}`)};return"agent.create"===e.name?await this.completeCreatedAgent(e,t,r,a):await this.completeTemplateAgent(e,t,r,a)}return await this.execute(e,t,r)}const i=e.context.agent,a=await this.runtimeAgentExists(i.runtimeLocalKey);if("agent.delete"===e.name&&!a)return await this.deps.identities.commitDeleteTombstone(i.runtimeAgentUid,i.runtimeLocalKey,t),{runtimeAgentUid:i.runtimeAgentUid,runtimeLocalKey:i.runtimeLocalKey};if("agent.update"===e.name&&!a)throw new RuntimeCommandError("OUTCOME_UNKNOWN","update recovery target is absent");return await this.execute(e,t,r)}async runtimeAgentExists(e){const t=await this.requireGateway().request("agents.list",{});if(!Array.isArray(t?.agents))throw new RuntimeCommandError("OUTCOME_UNKNOWN","runtime agent directory query is incomplete");return t.agents.some(t=>null!==t&&"object"==typeof t&&(t.id===e||t.name===e))}async findCreateRecoveryIdentity(e,t=!0){const r={operationId:e.context.operationId,command:e.name,runtimeEpoch:e.context.dispatchEpoch,paramsHash:e.context.paramsHash,runtimeAgentUid:e.params.runtimeAgentUid},i=void 0!==this.deps.identities.findCreateOperation,a=i?await this.deps.identities.findCreateOperation(r):(await this.deps.identities.pendingAllocations()).filter(e=>e.operationId===r.operationId&&e.command===r.command&&e.runtimeEpoch===r.runtimeEpoch&&e.runtimeAgentUid===r.runtimeAgentUid);if(1!==a.length)throw new RuntimeCommandError("OUTCOME_UNKNOWN","create recovery identity binding is missing or ambiguous");const n=a[0];if(i&&(!n.createOperation||t&&n.createOperation.paramsHash!==r.paramsHash||n.createOperation.operationId!==r.operationId||n.createOperation.command!==r.command||n.createOperation.runtimeEpoch!==r.runtimeEpoch))throw new RuntimeCommandError("OUTCOME_UNKNOWN","create recovery identity hash binding conflicts");return n}async bindCreateOperation(e,t,r=!0){if(!this.deps.identities.findCreateOperation||!this.deps.identities.bindCreateOperation)return;const i={operationId:e.context.operationId,command:e.name,runtimeEpoch:e.context.dispatchEpoch,paramsHash:e.context.paramsHash,runtimeAgentUid:e.params.runtimeAgentUid};try{let a=await this.deps.identities.findCreateOperation(i);if(0===a.length){if(!r)throw new RuntimeCommandError("OUTCOME_UNKNOWN","create recovery identity binding is missing");if((await this.deps.identities.allocateCreate(t,e.name,e.params.runtimeAgentUid)).runtimeAgentUid!==e.params.runtimeAgentUid)throw new RuntimeCommandError("OUTCOME_UNKNOWN","create allocation UID does not match the canonical command");a=await this.deps.identities.findCreateOperation(i)}if(1!==a.length)throw new RuntimeCommandError("OUTCOME_UNKNOWN","create identity binding is missing or ambiguous");const n=a[0],o=await this.deps.identities.bindCreateOperation(n.runtimeAgentUid,n.runtimeLocalKey,{operationId:e.context.operationId,command:e.name,runtimeEpoch:e.context.dispatchEpoch,paramsHash:e.context.paramsHash});if(!o.createOperation||o.runtimeAgentUid!==e.params.runtimeAgentUid||o.createOperation.operationId!==i.operationId||o.createOperation.command!==i.command||o.createOperation.runtimeEpoch!==i.runtimeEpoch||o.createOperation.paramsHash!==i.paramsHash)throw new Error("create operation identity binding changed during compare-and-set");if("tombstoned"===o.state)throw new Error("create operation identity is tombstoned");return o}catch(e){if(e instanceof RuntimeCommandError)throw e;throw new RuntimeCommandError("OUTCOME_UNKNOWN",`create operation identity binding is corrupt: ${errorText(e)}`,void 0,{cause:e})}}async recoverActiveCreateEffect(e){const t=e.observedRuntimeLocalKey??e.runtimeLocalKey;if(!await this.runtimeAgentExists(t))throw new RuntimeCommandError("OUTCOME_UNKNOWN","active create identity is absent from the runtime directory");return{runtimeAgentUid:e.runtimeAgentUid,runtimeLocalKey:t,workspacePath:join(this.getOpenclawHome(),`workspace-${e.runtimeLocalKey}`)}}async markJournalUnknown(e){try{await this.journal.transition({operationId:e.operationId,expectedRevision:e.revision,phase:"outcome_unknown",errorCode:"OUTCOME_UNKNOWN"})}catch{}}async requireReleasedRecord(e){const t=await this.journal.get(e);if(!t)throw new RuntimeCommandError("OUTCOME_UNKNOWN","command journal record disappeared");return t}async afterCommittedEffect(e,t,r,i,a,n){if(!isRuntimeAgentMutation(e))return void await this.runAfterEffect(e,t,r,i,a);const o=await this.prepareAgentProjection(e,t,r,i,a);o&&(n(o),"acp"===i.origin&&o().catch(e=>this.logger.warn?.(`[runtime-core] deferred ACP agent projection failed: ${errorText(e)}`)))}async prepareAgentProjectionCommit(e,t,r){const i=agentProjectionRecoverySummary(e,t,r);try{const r=await this.deps.projection.prepareCommittedMutation({command:e,result:t,...i.expectedPlatformAgentId?{expectedPlatformAgentId:i.expectedPlatformAgentId}:{}});return Object.freeze({...r,...i})}catch(e){const t=!(e instanceof RuntimeProjectionTransportError)||e.retryable;return this.logger.warn?.(`[runtime-core] agent projection preparation ${t?"deferred":"blocked"}: ${errorText(e)}`),Object.freeze({...i,state:t?"pending":"blocked",errorKind:t?"snapshot_retryable":"snapshot_nonretryable"})}}async prepareAgentProjection(e,t,r,i,a){if("projection_committed"===r.phase)return a(r.projectionReceipt?.snapshot??Object.freeze({state:"synced",revision:`${Math.max(0,r.revision-1)}`})),r.agentProjectionIntent&&await this.compactAgentProjectionReference(r.agentProjectionIntent),void await this.runPostCommit(e,t);if("effect_committed"!==r.phase||!this.deps.projection)return;let n=r,o=n.agentProjectionIntent;const s=n.agentProjectionPreparationFailure;if(o&&"blocked"===n.agentProjectionTerminal?.state)return a(Object.freeze({state:"blocked",revision:n.agentProjectionTerminal.revision})),await this.compactAgentProjectionReference(o),void await this.runPostCommit(e,t);let c;return o&&a(Object.freeze({state:"pending",revision:o.projectionRevision})),async()=>(c??=(async()=>{if(!o){if(!s||"blocked"===s.state)return Object.freeze({state:"blocked",revision:`${Math.max(0,n.revision)}`});const t=await this.prepareAgentProjectionCommit(e,agentProjectionRecoveryResult(s),i);if(!isProjectionIntent(t))return"blocked"===t.state?Object.freeze({state:"blocked",revision:`${Math.max(0,n.revision)}`}):Object.freeze({state:"pending",revision:`${Math.max(0,n.revision)}`});o=t;try{n=await this.journal.recordAgentProjectionIntent({operationId:n.operationId,expectedRevision:n.revision,intent:o})}catch(e){return void this.logger.warn?.(`[runtime-core] agent projection reservation recovery deferred: ${errorText(e)}`)}a(Object.freeze({state:"pending",revision:o.projectionRevision}))}const r=Object.freeze({state:"pending",revision:o.projectionRevision});let c;try{c=await this.deps.projection.applyCommittedMutation(o)}catch(e){this.logger.warn?.(`[runtime-core] agent projection receipt deferred: ${errorText(e)}`),c=r}if(c.revision!==o.projectionRevision&&(c=Object.freeze({state:"blocked",revision:o.projectionRevision})),"synced"===c.state)try{n=await this.journal.transition({operationId:n.operationId,expectedRevision:n.revision,phase:"projection_committed",projectionSnapshot:c}),await this.compactAgentProjectionReference(o)}catch(e){this.logger.warn?.(`[runtime-core] projection phase commit deferred: ${errorText(e)}`),c=Object.freeze({state:"pending",revision:o.projectionRevision})}if("blocked"===c.state)try{n=await this.journal.recordAgentProjectionBlocked({operationId:n.operationId,expectedRevision:n.revision,revision:o.projectionRevision}),await this.compactAgentProjectionReference(o)}catch(e){this.logger.warn?.(`[runtime-core] blocked projection terminal commit deferred: ${errorText(e)}`),c=r}return"synced"===c.state&&c.platformAgentId&&"projection_committed"===n.phase&&this.reportTemplateOriginBestEffort(e,c.platformAgentId),a(c),await this.runPostCommit(e,t),c})(),await c)}async compactAgentProjectionReference(e){if(this.deps.projection)try{await this.deps.projection.compactCommittedMutation(e)}catch(e){this.logger.warn?.(`[runtime-core] projection reference compaction deferred: ${errorText(e)}`)}}reportTemplateOriginBestEffort(e,t){if("agent.applyTemplate"!==e.name||!this.deps.templateOriginReporter)return;const r=e.params.templateId;r&&this.deps.templateOriginReporter.report({platformAgentId:t,templateId:r}).catch(e=>{this.logger.warn?.(`[runtime-core] active template origin report failed, client fallback remains: ${errorText(e)}`)})}async runAfterEffect(e,t,r,i,a){if("projection_committed"===r.phase)return a(r.projectionReceipt?.snapshot??Object.freeze({state:"synced",revision:`${Math.max(0,r.revision-1)}`})),void await this.runPostCommit(e,t);const n="effect_committed"===r.phase&&await this.runProjection(e,t,i),o=!0===n?Object.freeze({state:"synced",revision:`${r.revision}`}):n&&"object"==typeof n?Object.freeze({...n,revision:`${r.revision}`}):"session.setModel"===e.name||"session.setReasoning"===e.name?Object.freeze({state:"pending",revision:`${r.revision}`}):void 0;if("synced"===o?.state)try{const e=o;await this.journal.transition({operationId:r.operationId,expectedRevision:r.revision,phase:"projection_committed",projectionSnapshot:e}),a(o)}catch(e){return this.logger.warn?.(`[runtime-core] projection phase commit deferred: ${errorText(e)}`),void a(Object.freeze({revision:o.revision,state:"pending"}))}else o&&a(o);await this.runPostCommit(e,t)}async runPostCommit(e,t){if(this.capabilities?.afterCommit)try{await this.capabilities.afterCommit(e,t)}catch(e){this.logger.warn?.(`[runtime-core] post-commit action failed: ${errorText(e)}`)}}async runProjection(e,t,r){if(!recoveryMetadata(e.name).projectionRequired)return!1;try{return!isRuntimeAgentMutation(e)&&(await(this.capabilities?.projectCommitted?.(e,t,r))??!1)}catch(e){return this.logger.warn?.(`[runtime-core] agent projection deferred: ${errorText(e)}`),!1}}recoveryDecision(e,t){const r=recoveryMetadata(e);return reduceRuntimeRecoveryPolicy({...r,messageServicePhase:"queued",executionBoundaryCrossed:"prepared"!==t,lineageContinuity:"continuous",journalState:"available",journalPhase:t})}requireGateway(){const e=this.deps.getGateway();if(!e?.isConnected)throw new RuntimeCommandError("GATEWAY_NOT_CONNECTED","Gateway not connected");return e}exclusiveLifecycleReason(e){switch(e.name){case"agent.applyTemplate":return"applyTemplate";case"agent.create":return"createAgent";case"agent.delete":return"deleteAgent";case"agent.update":return"updateAgent";default:return}}async withExclusiveLifecycle(e,t,r){const i=this.exclusiveLifecycleReason(e);if(!i)return await r();if(this.deps.runExclusive)try{return await this.deps.runExclusive(i,r,t)}catch(e){if(e instanceof ImHotPathAbortedError)throw new RuntimeCommandError("INVALID_PARAMS",`${i} aborted while waiting for in-flight chat`);throw e}return await(this.deps.waitForChatIdle?.(i,t)),await r()}async createAgentShell(e,t,r,i,a,n){const o=this.requireGateway(),s=(await this.deps.identities.pendingAllocations()).find(t=>t.runtimeAgentUid===e),c=n??s?.runtimeLocalKey??this.createAgentId(),m=join(this.getOpenclawHome(),`workspace-${c}`);let d;try{if(a&&!this.deps.declareModel)throw new Error("OpenClaw model configuration runtime is unavailable");const e=a?await this.deps.declareModel(a):void 0;d=await o.request("agents.create",{name:c,workspace:m,...e?{model:e}:{},...i?.emoji?{emoji:i.emoji}:{},...i?.avatar?{avatar:i.avatar}:{}})}catch(r){if(isDeterministicAgentsCreateParamsRejection(r)&&(void 0!==n||void 0!==s))try{await this.deps.identities.tombstone(e,c,t)}catch(e){this.logger.warn?.(`[runtime-core] rejected-create allocation cleanup deferred: ${errorText(e)}`)}throw r}const p=d?.agentId??c,u=d?.workspace??m;if(await this.deps.identities.observeEffectKey(e,c,p,t),p!==c)throw new RuntimeCommandError("OUTCOME_UNKNOWN",`Create agent outcome unknown: gateway changed reserved local key to ${p}`);try{await o.request("agents.update",{agentId:p,name:r})}catch(e){this.logger.warn?.(`[runtime-core] display-name update failed agent=${p}: ${errorText(e)}`)}return{runtimeLocalKey:p,workspacePath:u}}async createAgent(e,t,r){const i=e.params.name.trim();if(!i)throw new RuntimeCommandError("INVALID_PARAMS","Missing agent name");try{const a=await this.bindCreateOperation(e,t);if("active"===a?.state)return await this.recoverActiveCreateEffect(a);const n=await this.createAgentShell(e.params.runtimeAgentUid,t,i,e.params.identity,e.params.defaultModelId,a?.runtimeLocalKey);return await this.completeCreatedAgent(e,t,r,n)}catch(e){throw this.executionError("Create agent",e)}}async updateAgent(e){const{runtimeAgentUid:t,runtimeLocalKey:r}=e.context.agent;if(!r.trim())throw new RuntimeCommandError("MISSING_PARAM","Missing agentId","agentId");const i=e.params,a=i.name?.trim(),n=i.defaultModelId,o=i.identity?.emoji?.trim(),s=i.identity?.avatar?.trim();if(!(a||n||o||s||void 0!==i.description||void 0!==i.version||void 0!==i.capabilities||void 0!==i.skills||void 0!==i.avatarUrl||void 0!==i.homepage||void 0!==i.status||void 0!==i.identity?.vibe))throw new RuntimeCommandError("INVALID_PARAMS","No updatable fields provided (name/model/identity)");try{if(await this.deps.identities.requireActive(t,r),n&&!this.deps.declareModel)throw new Error("OpenClaw model configuration runtime is unavailable");const e=n?await this.deps.declareModel(n):void 0;return await this.requireGateway().request("agents.update",{agentId:r,...a?{name:a}:{},...e?{model:e}:{},...o?{emoji:o}:{},...s?{avatar:s}:{},...i.identity?.vibe?{vibe:i.identity.vibe}:{},...void 0!==i.description?{description:i.description}:{},...void 0!==i.version?{version:i.version}:{},...void 0!==i.capabilities?{capabilities:i.capabilities}:{},...void 0!==i.skills?{skills:i.skills}:{},...void 0!==i.avatarUrl?{avatarUrl:i.avatarUrl}:{},...void 0!==i.homepage?{homepage:i.homepage}:{},...void 0!==i.status?{status:i.status}:{}}),{runtimeAgentUid:t,runtimeLocalKey:r}}catch(e){throw this.executionError("Update agent",e)}}async deleteAgent(e,t){const{runtimeAgentUid:r,runtimeLocalKey:i}=e.context.agent;if(!i.trim())throw new RuntimeCommandError("MISSING_PARAM","Missing agentId","agentId");if("main"===normalizeRuntimeAgentLocalKey(i))throw new RuntimeCommandError("INVALID_PARAMS",'"main" cannot be deleted; delete the instance instead');try{if("tombstoned"===await this.deps.identities.requireDeleteTarget(r,i))return{runtimeAgentUid:r,runtimeLocalKey:i};if(!await this.runtimeAgentExists(i))return await this.deps.identities.commitDeleteTombstone(r,i,t),{runtimeAgentUid:r,runtimeLocalKey:i};const a=requireCommittedOpenClawDeleteAck(await this.requireGateway().request("agents.delete",{agentId:i,deleteFiles:e.params.deleteFiles??!0}),i);try{await this.deps.identities.commitDeleteTombstone(r,i,t)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN",`Delete agent outcome unknown: identity tombstone failed: ${errorText(e)}`,void 0,{cause:e})}return{runtimeAgentUid:r,runtimeLocalKey:i,...void 0===a.removedBindings?{}:{removedBindings:a.removedBindings}}}catch(e){throw this.executionError("Delete agent",e)}}async applyTemplate(e,t,r){const i=e.params.name.trim();if(!i)throw new RuntimeCommandError("INVALID_PARAMS","Missing agent name");this.requireGateway();try{const a=await this.bindCreateOperation(e,t);if("active"===a?.state)return await this.recoverActiveCreateEffect(a);const n=await r.resources.readVerifiedArtifact(e.params.artifact),o=await this.createAgentShell(e.params.runtimeAgentUid,t,i,e.params.identity,e.params.defaultModelId,a?.runtimeLocalKey);return await this.completeTemplateAgent(e,t,r,o,n)}catch(e){throw this.executionError("Apply template",e)}}async completeCreatedAgent(e,t,r,i){for(const t of e.params.bootstrapFiles??[]){if("IDENTITY.md"===t.name){this.logger.warn?.("[runtime-core] agent.create ignoring IDENTITY.md; identity is structured");continue}const e=await r.resources.readContent(t.contentRef);try{await this.requireGateway().request("agents.files.set",{agentId:i.runtimeLocalKey,name:t.name,content:e})}catch(e){this.logger.warn?.(`[runtime-core] bootstrap write failed file=${t.name}: ${errorText(e)}`)}}try{await this.deps.identities.activate(e.params.runtimeAgentUid,i.runtimeLocalKey,t)}catch(r){throw await this.compensateCreatedAgent(e.params.runtimeAgentUid,i.runtimeLocalKey,t,r,"Create agent"),new RuntimeCommandError("EXECUTION_FAILED",`Create agent failed after compensation: ${errorText(r)}`)}return await this.prepareAgentToolCatalog(i.runtimeLocalKey),{runtimeAgentUid:e.params.runtimeAgentUid,runtimeLocalKey:i.runtimeLocalKey,workspacePath:i.workspacePath}}async completeTemplateAgent(e,t,r,i,a){const n=a??await r.resources.readVerifiedArtifact(e.params.artifact);try{for(const[e,t]of n.workspaceFiles){const r=resolve(i.workspacePath,e),a=relative(i.workspacePath,r);if(""===a||a.startsWith("..")||path.isAbsolute(a))throw new Error(`refusing to write outside workspace: ${e}`);await(this.deps.mkdirWorkspace??mkdir)(path.dirname(r),{recursive:!0}),await(this.deps.writeWorkspaceFile??writeFile)(r,t)}await this.deps.identities.activate(e.params.runtimeAgentUid,i.runtimeLocalKey,t)}catch(r){throw await this.compensateCreatedAgent(e.params.runtimeAgentUid,i.runtimeLocalKey,t,r,"Apply template"),new RuntimeCommandError("EXECUTION_FAILED",`Apply template failed after compensation: ${errorText(r)}`,void 0,{cause:r})}return await this.prepareAgentToolCatalog(i.runtimeLocalKey),{runtimeAgentUid:e.params.runtimeAgentUid,runtimeLocalKey:i.runtimeLocalKey,workspacePath:i.workspacePath}}async prepareAgentToolCatalog(e){await prepareOpenClawToolCatalog({request:(e,t)=>this.requireGateway().request(e,t),agentId:e,mode:"catalog",keyKind:"boot",logger:this.logger})}executionError(e,t){return t instanceof RuntimeCommandError?t:(this.logger.error?.(`[runtime-core] ${e.toLowerCase()} failed: ${errorText(t)}`),new RuntimeCommandError("EXECUTION_FAILED",`${e} failed: ${errorText(t)}`,void 0,{cause:t}))}async compensateCreatedAgent(e,t,r,i,a){try{const i=this.requireGateway();requireCommittedOpenClawDeleteAck(await i.request("agents.delete",{agentId:t,deleteFiles:!0}),t),await this.deps.identities.tombstone(e,t,r)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN",`${a} outcome unknown after ${errorText(i)}; compensation unproven: ${errorText(e)}`,void 0,{cause:e})}}async recoverInterruptedCreates(e){const t=await this.deps.identities.pendingAllocations();for(const r of t){if(r.operationId===e)continue;const t=await this.deps.leases.claimExpiredForRecovery(r.operationId);if(!t)continue;const i=this.deps.leases.startHeartbeat(t);try{await this.deps.identities.adoptRecoveryLease(r.runtimeAgentUid,r.runtimeLocalKey,t);const e=r.observedRuntimeLocalKey;if(!e){const e=r.createOperation?.operationId??r.operationId,i=await this.journal.get(e);if("failed"===i?.phase&&i.command===r.command&&!await this.runtimeAgentExists(r.runtimeLocalKey)){await this.deps.identities.tombstone(r.runtimeAgentUid,r.runtimeLocalKey,t);continue}throw new Error("no persisted gateway effect key; absence cannot be proven")}requireCommittedOpenClawDeleteAck(await this.requireGateway().request("agents.delete",{agentId:e,deleteFiles:!0}),e),await this.deps.identities.tombstone(r.runtimeAgentUid,r.runtimeLocalKey,t)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN",`Interrupted ${r.command} recovery outcome unknown for operation ${r.operationId}: ${errorText(e)}`,void 0,{cause:e})}finally{let e;try{await i.stop()}catch(t){e=t}try{await this.deps.leases.release(t)}catch(t){e??=t}if(e)throw new RuntimeCommandError("OUTCOME_UNKNOWN",`Interrupted recovery lease finalization unknown: ${errorText(e)}`,void 0,{cause:e})}}}}function isRuntimeAgentMutation(e){return"agent.create"===e.name||"agent.update"===e.name||"agent.delete"===e.name||"agent.applyTemplate"===e.name}function servicePlatformAgentId(e){const t=e.verifiedMessageGrant?.claims;return"agent"===t?.scope?t.platformAgentId:void 0}function agentCoreResultHash(e,t){return createHash("sha256").update(runtimeHashPreimage(RUNTIME_HASH_DOMAINS.coreResult,{method:e.name.replace(".","/"),result:t})).digest("hex")}function agentProjectionRecoverySummary(e,t,r){const i="agent.update"===e.name||"agent.delete"===e.name?e.context.agent:createProjectionTarget(e,t),a=t;return Object.freeze({schemaVersion:1,operationId:e.context.operationId,method:e.name,runtimeEpoch:e.context.dispatchEpoch,runtimeAgentUid:i.runtimeAgentUid,runtimeLocalKey:i.runtimeLocalKey,coreResultHash:agentCoreResultHash(e,t),...servicePlatformAgentId(r)?{expectedPlatformAgentId:servicePlatformAgentId(r)}:{},..."agent.delete"===e.name&&Number.isSafeInteger(a?.removedBindings)?{removedBindings:a.removedBindings}:{}})}function createProjectionTarget(e,t){const r=t;if(!r||r.runtimeAgentUid!==e.params.runtimeAgentUid||"string"!=typeof r.runtimeLocalKey||!r.runtimeLocalKey)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed agent effect lacks a recoverable local identity");return{runtimeAgentUid:r.runtimeAgentUid,runtimeLocalKey:r.runtimeLocalKey}}function agentProjectionRecoveryResult(e){return Object.freeze({runtimeAgentUid:e.runtimeAgentUid,runtimeLocalKey:e.runtimeLocalKey,...void 0===e.removedBindings?{}:{removedBindings:e.removedBindings}})}function isProjectionIntent(e){return"projectionRevision"in e}function recoveryMetadata(e){const t=RUNTIME_METHOD_PARITY_MANIFEST.filter(t=>t.serviceAllowed&&t.canonicalCommand===e),r=t[0]?.recoveryClass;return r?{recoveryClass:r,projectionRequired:"mcp.set"===e||"mcp.unset"===e||t.some(e=>!0===e.projectionRequired)}:{recoveryClass:"imperative-ambiguous",projectionRequired:!1}}export function isDeterministicAgentsCreateParamsRejection(e){return e instanceof Error&&/^invalid agents\.create params\b/.test(e.message)}export function requireCommittedOpenClawDeleteAck(e,t){if(!e||"object"!=typeof e)throw new Error("gateway delete lacks the committed target acknowledgement");const r=e,i=Object.keys(r).every(e=>"ok"===e||"agentId"===e||"removedBindings"===e),a=void 0===r.removedBindings||Number.isSafeInteger(r.removedBindings)&&r.removedBindings>=0;if(!i||!0!==r.ok||r.agentId!==t||!a)throw new Error("gateway delete lacks the committed target acknowledgement");return{ok:!0,agentId:t,...void 0===r.removedBindings?{}:{removedBindings:r.removedBindings}}}function errorText(e){return e instanceof Error?e.message:String(e)}