beeos-claw 0.6.88 → 0.6.91
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.
- package/README.md +66 -6
- package/dist/acp-gateway/gateway-events.js +1 -1
- package/dist/acp-gateway/history-artifact-hydrator.js +1 -1
- package/dist/acp-gateway/history-replay.js +1 -1
- package/dist/acp-gateway/local-session-history.js +1 -1
- package/dist/canvas/html-delivery.js +1 -1
- package/dist/canvas/runtime-lease-token.js +1 -0
- package/dist/canvas/tools.js +1 -1
- package/dist/canvas-orchestrator.js +1 -1
- package/dist/index.js +1 -1
- package/dist/message-sanitization/transport-metadata-sanitizer.js +1 -1
- package/dist/runtime/agent-runtime-failure-classifier.js +1 -1
- package/dist/runtime/central-native-composition.js +1 -0
- package/dist/runtime/central-native-context-engine.js +1 -0
- package/dist/runtime/central-native-credentials.js +1 -0
- package/dist/runtime/central-native-delta.js +1 -0
- package/dist/runtime/central-native-host.js +1 -0
- package/dist/runtime/central-native-interactions.js +1 -0
- package/dist/runtime/central-native-memory.js +1 -0
- package/dist/runtime/central-native-pending-journal.js +1 -0
- package/dist/runtime/central-native-production.js +1 -0
- package/dist/runtime/central-native-response.js +1 -0
- package/dist/runtime/central-native-runtime.js +1 -0
- package/dist/runtime/central-native-titles.js +1 -0
- package/dist/runtime/central-session-key.js +1 -0
- package/dist/runtime/conversation-title.js +1 -1
- package/dist/runtime/identity-lane-lease.js +1 -0
- package/dist/runtime/im-reply-sink.js +1 -1
- package/dist/runtime/ms-runtime-message-channel-adapter.js +1 -1
- package/dist/runtime/ms-runtime-message-channel-consumer-factory.js +1 -1
- package/dist/runtime/native-cloud-prompt-bridge.js +1 -1
- package/dist/runtime/openclaw-session-write-quiescence.js +1 -1
- package/dist/runtime/reply-router.js +1 -1
- package/dist/runtime/runtime-command-journal.js +1 -1
- package/dist/runtime/runtime-production-authority.js +1 -1
- package/dist/runtime/runtime-service-contract-compatibility.js +1 -1
- package/dist/runtime/runtime-service-production-candidate.js +1 -1
- package/dist/runtime/sandbox-native-activation.js +1 -0
- package/dist/runtime/sandbox-native-credentials.js +1 -0
- package/dist/runtime/sandbox-native-execution-resolver.js +1 -0
- package/dist/runtime/session-mutation-coordinator.js +1 -1
- package/dist/terminal/runtime-terminal-outbound-registration.js +1 -1
- package/dist/terminal/session-manager.js +1 -1
- package/dist/terminal/standalone-runtime-terminal.js +1 -0
- package/dist/upload/native-output-tool-hook.js +1 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +4 -4
- package/runtime-service-wire-identity.v1.json +1 -1
|
@@ -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{isRenderUiToolName,isStaticHtmlInvocation,staticHtmlProjectionOf,staticHtmlResultOf}from"../canvas/static-html-result.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}},observedToolResultText=e=>{if(!isPlainRecord(e)||!Array.isArray(e.content))return;const t=e.content.filter(e=>isPlainRecord(e)&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text.trim()).filter(Boolean);return t.length>0?t.join("\n"):void 0};export function createImReplySink(e){const t=e.startedAtMs??Date.now();let r=!1;const s=new Map,o=new Set,a={text:""};let n="",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=[],v=new Map,y=new Map;let b,_=0,I=1;const S=(e,t={})=>({schema_version:1,seq:e,...t}),x=new Set,R=new Set,w=t=>{t!==a.text&&(t.startsWith(a.text)?e.stream.appendBody(t.slice(a.text.length)):e.stream.setBody(t),a.text=t)},P=e=>{void 0===e.publishTimer&&(e.publishTimer=setTimeout(()=>{e.publishTimer=void 0,te("body_preview_flush",()=>{m===e&&(e=>{a.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,a.text!==e&&(w(e),t.terminalPublishCount+=1),c.receivedSnapshotCount+=t.receivedSnapshotCount,c.streamingPublishCount+=t.streamingPublishCount,c.terminalPublishCount+=t.terminalPublishCount,m=void 0):w(e)},q=t=>{if(void 0!==t.partIndex)return;const r=_,s=I;e.stream.addPart(toMessagePart({type:"text",text:t.text,state:"done",_seq:s,data:S(s)})),t.partIndex=r,_+=1,I+=1},T=()=>{if(!d){d=!0;for(const e of g)q(e)}},$=e=>{const t={text:e};g.push(t),d&&q(t)},E=(t,r)=>{for(const s of t){const t=y.get(s.url);if(t){const r=mergeSearchSource(t,s);if(r.title===t.title&&r.snippet===t.snippet)continue;const o={...r,partIndex:t.partIndex,displaySeq:t.displaySeq,toolUseId:t.toolUseId};e.stream.replacePart(t.partIndex,toMessagePart({type:"source",url:o.url,...o.title?{title:o.title}:{},...o.snippet?{snippet:o.snippet}:{},tool_use_id:o.toolUseId,_seq:o.displaySeq,data:S(o.displaySeq)})),y.set(s.url,o);continue}const o={...s,partIndex:_,displaySeq:I,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:o.displaySeq,data:S(o.displaySeq)})),y.set(s.url,o),_+=1,I+=1,Y.source+=1}},C=(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:S(e.displaySeq,{started_at_ms:e.startedAtMs,...void 0!==s?{duration_ms:s}:{}})}),M=t=>{T();const r={partIndex:_,displaySeq:I,text:t,publishedText:t,receivedSnapshotCount:1,streamingPublishCount:1,startedAtMs:Date.now(),startedAtMonotonicMs:performance.now()};return e.stream.addPart(C(r,t,"streaming")),_+=1,I+=1,p=r,r},A=t=>{void 0===t.publishTimer&&(t.publishTimer=setTimeout(()=>{t.publishTimer=void 0,te("reasoning_snapshot_flush",()=>{p===t&&(t=>{t.publishedText!==t.text&&(e.stream.replacePart(t.partIndex,C(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,C(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})},O=e=>{const t=h.indexOf(e);t>=0&&h.splice(t,1)},F=e=>null!=e&&("object"!=typeof e||(Array.isArray(e)?e.length>0:Object.keys(e).length>0)),N=e=>{let t=v.get(e);return t||(t={},v.set(e,t)),t},j=(t,r,s)=>{const o="tool"===t.name&&"tool"!==r?r:t.name,a=!F(t.arguments)&&F(s)?s:t.arguments;o===t.name&&a===t.arguments||(e.stream.replacePart(t.partIndex,toMessagePart({type:"tool_use",id:t.id,name:t.htmlPresentation?.name??o,arguments:t.htmlPresentation?.arguments??a,state:t.state,_seq:t.displaySeq,data:S(t.displaySeq)})),t.name=o,t.arguments=a)},L=(t,r,s,o)=>{const a=f.get(t);if(a)return j(a,r,s),o&&!h.includes(t)&&"streaming"===a.state&&h.push(t),a;T();const n=v.get(t),i="tool"!==r?r:n?.name&&"tool"!==n.name?n.name:r,l=F(s)?s:n?.arguments??s,d=((t,r,s)=>{const o=_,a=I;return e.stream.addPart(toMessagePart({type:"tool_use",id:t,name:r,arguments:s,state:"streaming",_seq:a,data:S(a)})),_+=1,I+=1,{partIndex:o,displaySeq:a}})(t,i,l),u={id:t,name:i,arguments:l,partIndex:d.partIndex,displaySeq:d.displaySeq,state:"streaming",itemEventObserved:!0===n?.itemEventObserved,toolStartObserved:!0===n?.toolStartObserved};return f.set(t,u),(o||u.toolStartObserved||u.itemEventObserved)&&(h.includes(t)||"streaming"!==u.state||h.push(t)),n&&Q(u,n),v.delete(t),u},B=(e,t)=>{const r=(e=>f.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)&&!h.includes(r.id)&&"streaming"===r.state&&h.push(r.id),r;const s=N(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)},D=t=>{"done"!==t.state&&(e.stream.replacePart(t.partIndex,toMessagePart({type:"tool_use",id:t.id,name:t.htmlPresentation?.name??t.name,arguments:t.htmlPresentation?.arguments??t.arguments,state:"done",_seq:t.displaySeq,data:S(t.displaySeq)})),t.state="done")},H=e=>{if(null===e||"object"!=typeof e)return JSON.stringify(e)??String(e);if(Array.isArray(e))return`[${e.map(H).join(",")}]`;return`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${H(t)}`).join(",")}}`},z=(t,r,s)=>{const o=`${s?"1":"0"}:${H(r)}`;if(t.progressSignature===o)return;const a=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=_;return e.stream.addPart(a),t.progressPartIndex=r,t.progressSignature=o,void(_+=1)}e.stream.replacePart(t.progressPartIndex,a),t.progressSignature=o},Q=(e,t)=>{if(t.progress?.length)for(const r of t.progress)z(e,r.content,r.isError);t.observedResult&&(z(e,t.observedResult.content,t.observedResult.isError),e.observedResult=t.observedResult,"tool_call"!==e.name&&!isRenderUiToolName(e.name)||t.observedResult.isError||V(e,{text:t.observedResult.content,isError:t.observedResult.isError,rawResult:t.observedResult.rawResult})),(t.progress?.length||t.observedResult)&&(D(e),O(e.id)),!t.observedResult&&t.htmlPayload&&V(e,t.htmlPayload),t.sources?.length&&E(t.sources,e.id)},W=e=>[...new Set([e.mediaUrl,...e.mediaUrls??[]].filter(e=>isNonEmptyString(e)).map(e=>e.trim()).filter(Boolean))],J=(e,t=[])=>{const r=[...new Set([...W(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.":""},K=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},G=t=>{x.add(t);const r=()=>{x.delete(t)};e.onCallbackFailure?t.then(r,r):t.finally(r)},V=(t,r)=>{const s=t.observedResult,o=s?.isError??!0===r.isError,a=s?.rawResult??pickRawResultFromPayload(r),n=o?void 0:staticHtmlProjectionOf(t.name,t.arguments,a);if(!n&&isStaticHtmlInvocation(t.name,t.arguments))return;if(n&&e.htmlDelivery?.publishedFileId&&e.htmlDelivery.publishedFileId!==n.result.artifact.fileId)return;if(t.durableUploadFilesEmitted&&(!n||t.staticHtmlResultEmitted))return;e.logger.info?.(`[im-sink] schedule tool artifact enrichment requestId=${e.requestId} toolUseId=${t.id} name=${t.name}`);const i=(async()=>{let s=[];try{s=await resolveToolArtifactLinks({toolCallId:t.id,toolName:t.name,rawResult:a,rawText:"string"==typeof r.text?r.text:void 0,params:asToolParams(t.arguments),cwd:sessionWorkspaceDir(e.sessionKey),payloadMediaUrls:W(r)})}catch(r){const s=r instanceof Error?r.message:String(r);if(e.logger.warn?.(`[im-sink] resolveToolArtifactLinks failed requestId=${e.requestId} toolUseId=${t.id} error=${s}`),e.onCallbackFailure?.(r),e.onCallbackFailure)throw r;return}n&&(s=s.filter(e=>e.uri!==n.result.artifact.uri)),0!==s.length||n?(e.logger.info?.(`[im-sink] tool artifact enrichment resolved ${s.length} link(s) requestId=${e.requestId} toolUseId=${t.id}`),await new Promise((o,a)=>{const i=e.callbackQueue.enqueueSync(()=>{try{if(e.abortSignal.aborted||e.stream.isTerminated)return;const o=s.map(e=>e.uri);t.artifactMediaUrls=o;const a=t.observedResult;z(t,J(a?{text:a.content,isError:a.isError}:n?{...r,mediaUrl:r.mediaUrl===n.result.artifact.uri?void 0:r.mediaUrl,mediaUrls:r.mediaUrls?.filter(e=>e!==n.result.artifact.uri)}:r,o),a?.isError??!0===r.isError),((t,r,s,o)=>{const a=r.length>0&&!t.durableUploadFilesEmitted,n=!s&&void 0!==o&&!t.staticHtmlResultEmitted;(a||n)&&(n&&(t.htmlPresentation={name:"render_ui",arguments:o.arguments},e.stream.replacePart(t.partIndex,toMessagePart({type:"tool_use",id:t.id,...t.htmlPresentation,state:t.state,_seq:t.displaySeq,data:S(t.displaySeq)}))),e.stream.appendToolResult(t.id,[...n?[{type:"text",text:JSON.stringify(o.result)}]:[],...a?r.map(e=>({type:"resource_link",uri:e.uri,name:e.name,...e.mimeType?{mimeType:e.mimeType}:{}})):[]],s),_+=1,n&&(t.staticHtmlResultEmitted=!0,e.htmlDelivery?.recordReply(o.result)),a&&(t.durableUploadFilesEmitted=!0,K(r),s||e.htmlDelivery?.recordUploadReply(t.id,r)))})(t,s,a?.isError??!0===r.isError,n)}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}`),e.onCallbackFailure?.(r),e.onCallbackFailure&&a(r)}finally{o()}});!1===i&&e.onCallbackFailure&&e.callbackQueue.waitForIdle().then(o,a)})):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);if(e.logger.warn?.(`[im-sink] tool artifact enrichment failed requestId=${e.requestId} toolUseId=${t.id} error=${s}`),e.onCallbackFailure?.(r),e.onCallbackFailure)throw r});G(i)},X=(e,t,r)=>B(e,{name:t,arguments:r}),Y={tool:0,block:0,final:0,source:0};let Z,ee=!1;const te=(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):!ee||(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}`),e.onCallbackFailure?.(r)}})},re={sendToolResult:t=>(te("tool_progress",()=>{const r=resolveRuntimeToolCallId(t),s=resolveRuntimeToolName(t),o=resolveRuntimeToolArguments(t),a=J(t),n=!0===t.isError;let i;if(r){if(i=X(r,s,o),!i){const e=N(r);if(s&&(e.name=s),F(o)&&(e.arguments=o),e.progress=[...e.progress??[],{content:a,isError:n}],"tool_call"===s||isRenderUiToolName(s??"")){const r=pickRawResultFromPayload(t);(n||void 0!==r)&&(e.htmlPayload=!n&&staticHtmlResultOf(r)?t:void 0)}return void(Y.tool+=1)}i&&(Y.tool+=1,i.observedResult||z(i,a,n),D(i),O(i.id),V(i,t))}else e.logger.debug?.(`[im-sink] unattributed tool progress ignored requestId=${e.requestId} channel=${e.channelId} tool=${s??"unknown"} pending=${h.length}`)}),!0),sendBlockReply:e=>(te("block_reply",()=>{Y.block+=1,isNonEmptyString(e.text)&&(Z=!0!==e.isError?void 0:e.text)}),!0),sendFinalReply:t=>(te("final_reply",()=>{var r;(Y.final+=1,!0!==t.isError)?((t=>{const r=W(t).filter(e=>!R.has(e));if(0===r.length)return;for(const e of r)R.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)R.delete(e);if(e.logger.warn?.(`[im-sink] final media enrichment failed requestId=${e.requestId} error=${t instanceof Error?t.message:String(t)}`),e.onCallbackFailure?.(t),e.onCallbackFailure)throw t;return}if(0!==t.length)await new Promise((r,s)=>{!1===e.callbackQueue.enqueueSync(()=>{try{if(e.abortSignal.aborted||e.stream.isTerminated)return;K(t)}catch(t){e.logger.warn?.(`[im-sink] final media enrichment apply failed requestId=${e.requestId} error=${t instanceof Error?t.message:String(t)}`),e.onCallbackFailure?.(t),e.onCallbackFailure&&s(t)}finally{r()}})&&e.onCallbackFailure&&e.callbackQueue.waitForIdle().then(r,s)});else for(const e of r)R.delete(e)})();G(s)})(t),isNonEmptyString(t.text)&&(Z=void 0,l||(r=t.text,i="",n+=r,k(n),$(r),l=!0))):Z=t.text}),!0),waitForIdle:async()=>{for(let t=0;(e.onCallbackFailure||t<16)&&(await e.callbackQueue.waitForIdle(),0!==x.size);t++)e.onCallbackFailure?await Promise.all([...x]):await Promise.allSettled([...x]);await e.callbackQueue.waitForIdle();const t=takeFinalizeAttachments(e.sessionKey);t.length>0&&!e.abortSignal.aborted&&!e.stream.isTerminated&&K(t)},getQueuedCounts:()=>({tool:Y.tool,block:Y.block,final:Y.final}),getAccumulatedBody:()=>a.text,getTerminalErrorText:()=>Z,markComplete:r=>{U(),v.size>0&&e.logger.debug?.(`[im-sink] dropping uncommitted lifecycle tool signals requestId=${e.requestId} buffered=${v.size}`),i="",k(n),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&&V(t,{toolCallId:t.id,toolName:t.name}),"success"===r&&D(t),O(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}`)}v.clear(),ee=!0}},se={...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=>{te("partial",()=>{l||"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(a.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,P(t))})(n+i))})},onReasoningStream:e=>{te("reasoning",()=>{if(!isNonEmptyString(e.text))return;const t=e.text,r=p??M(t);t!==r.text&&(r.text.startsWith(t)||(t.startsWith(r.text)?(r.text=t,r.receivedSnapshotCount+=1,A(r)):(U(),M(t))))})},onReasoningEnd:()=>{te("reasoning_end",()=>{U()})},onAssistantMessageStart:()=>{te("assistant_message_start",()=>{i="",l=!1,k(n),e.logger.debug?.(`[im-sink] assistant_message_start requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`)})},onToolStart:r=>{te("tool_start",()=>{const o="string"==typeof r.phase?r.phase:"start",a=resolveRuntimeToolName(r)??"tool",n=resolveRuntimeToolCallId(r),i=resolveRuntimeToolArguments(r);"update"!==o?(n&&s.set(n,Date.now()),logChatLatency(e.logger,"claw.tool.start",e.requestId,t,{tool:a}),n&&B(n,{name:a,arguments:i,toolStartObserved:!0,pending:!0})):n&&B(n,{name:a,arguments:i,pending:!0})})},onItemEvent:e=>{te("item_event",()=>{const t="string"==typeof e.kind?e.kind.toLowerCase():"";if(t&&"tool"!==t)return;"string"==typeof e.phase&&e.phase.toLowerCase();const r=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);r&&s&&B(r,{name:s,itemEventObserved:!0,pending:!0})})}},oe={add(t){if(e.stream.isTerminated)return;const r=_;return e.stream.addPart(t),_+=1,r}},ae={add:e=>oe.add(e),replace:(t,r)=>!e.stream.isTerminated&&(e.stream.replacePart(t,r),!0)};return{dispatcher:re,replyOptions:se,commitAssistantMessage:t=>{te("assistant_message_commit",()=>{if(u.has(t.key))return;u.add(t.key),l=!0,Z=void 0,i="";const r=t.segments.filter(e=>"text"===e.type).map(e=>e.text).join("");n+=r,k(n);for(const e of t.segments)"text"!==e.type?L(e.id,e.name,e.arguments,!0):$(e.text);if(void 0!==t.executedModel||void 0!==b){const r=toMessagePart({type:"custom",kind:"execution_model",data:{executed_model:t.executedModel??""}});void 0===b?(e.stream.addPart(r),b=_++):e.stream.replacePart(b,r)}})},observeToolResult:r=>{te("tool_result_observation",()=>{const a=r.toolCallId.trim(),n=r.toolName.trim();if(!a||!n)return;const i=!o.has(a);if(i){o.add(a);const i=s.get(a);logChatLatency(e.logger,"claw.tool.result",e.requestId,t,{tool:n,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"}:{}})}if(e.persistObservedToolResults&&i){const e=observedToolResultText(r.rawResult)??("tool_call"===n||isRenderUiToolName(n)?"":void 0);if(void 0!==e){const t=X(a,n);if(t)z(t,J({text:e,isError:r.isError},t.artifactMediaUrls),r.isError),t.observedResult={content:e,isError:r.isError,rawResult:r.rawResult},D(t),O(t.id),"tool_call"!==t.name&&!isRenderUiToolName(t.name)||r.isError||V(t,{text:e,isError:r.isError,rawResult:r.rawResult});else{const t=N(a);t.name??=n,t.observedResult={content:e,isError:r.isError,rawResult:r.rawResult}}}}const l=searchSourceProvider(r.rawResult)??"unknown";let d=0;try{const t=extractSearchSources({toolName:n,rawResult:r.rawResult,isError:r.isError});if(d=t.length,0===d)return;const s=X(a,n);if(s)E(t,s.id);else{const e=N(a);e.name??=n,e.sources=((e,t)=>{if(!e?.length&&!t?.length)return;const r=[],s=new Map;for(const o of[...e??[],...t??[]]){const e=s.get(o.url);void 0===e?(s.set(o.url,r.length),r.push(o)):r[e]=mergeSearchSource(r[e],o)}return r})(e.sources,t)}e.logger.debug?.(`[im-sink] search source projection requestId=${e.requestId} tool=${n} provider=${l} source_count=${d}`)}catch{e.logger.warn?.(`[im-sink] search source projection ignored requestId=${e.requestId} tool=${n} provider=${l} source_count=${d}`)}})},getSourceCount:()=>Y.source,approvalParts:oe,questionParts:ae}}
|
|
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{isRenderUiToolName,isStaticHtmlInvocation,staticHtmlProjectionOf,staticHtmlResultOf}from"../canvas/static-html-result.js";import{logChatLatency}from"../chat-latency.js";import{BeeosMediaDirectiveStream}from"../message-sanitization/transport-metadata-sanitizer.js";const STREAMING_SNAPSHOT_PUBLISH_INTERVAL_MS=200;function visibleAssistantSegments(e){const t=new BeeosMediaDirectiveStream,r=[],s=()=>{const e=t.finish(),s=r.at(-1);e&&"text"===s?.type&&(s.text+=e)};for(const o of e)"text"===o.type?r.push({type:"text",text:t.write(o.text)}):(s(),r.push(o));return s(),r.filter(e=>"text"!==e.type||e.text.length>0)}const 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}},observedToolResultText=e=>{if(!isPlainRecord(e)||!Array.isArray(e.content))return;const t=e.content.filter(e=>isPlainRecord(e)&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text.trim()).filter(Boolean);return t.length>0?t.join("\n"):void 0};export function createImReplySink(e){const t=e.startedAtMs??Date.now();let r=!1;const s=new Map,o=new Set,a={text:""};let n="",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=[],v=new Map,y=new Map;let b,_=0,I=1;const S=(e,t={})=>({schema_version:1,seq:e,...t}),x=new Set,w=new Set,R=t=>{t!==a.text&&(t.startsWith(a.text)?e.stream.appendBody(t.slice(a.text.length)):e.stream.setBody(t),a.text=t)},P=e=>{void 0===e.publishTimer&&(e.publishTimer=setTimeout(()=>{e.publishTimer=void 0,te("body_preview_flush",()=>{m===e&&(e=>{a.text!==e.targetBody&&(R(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,a.text!==e&&(R(e),t.terminalPublishCount+=1),c.receivedSnapshotCount+=t.receivedSnapshotCount,c.streamingPublishCount+=t.streamingPublishCount,c.terminalPublishCount+=t.terminalPublishCount,m=void 0):R(e)},q=t=>{if(void 0!==t.partIndex)return;const r=_,s=I;e.stream.addPart(toMessagePart({type:"text",text:t.text,state:"done",_seq:s,data:S(s)})),t.partIndex=r,_+=1,I+=1},T=()=>{if(!d){d=!0;for(const e of g)q(e)}},$=e=>{const t={text:e};g.push(t),d&&q(t)},E=(t,r)=>{for(const s of t){const t=y.get(s.url);if(t){const r=mergeSearchSource(t,s);if(r.title===t.title&&r.snippet===t.snippet)continue;const o={...r,partIndex:t.partIndex,displaySeq:t.displaySeq,toolUseId:t.toolUseId};e.stream.replacePart(t.partIndex,toMessagePart({type:"source",url:o.url,...o.title?{title:o.title}:{},...o.snippet?{snippet:o.snippet}:{},tool_use_id:o.toolUseId,_seq:o.displaySeq,data:S(o.displaySeq)})),y.set(s.url,o);continue}const o={...s,partIndex:_,displaySeq:I,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:o.displaySeq,data:S(o.displaySeq)})),y.set(s.url,o),_+=1,I+=1,Y.source+=1}},C=(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:S(e.displaySeq,{started_at_ms:e.startedAtMs,...void 0!==s?{duration_ms:s}:{}})}),M=t=>{T();const r={partIndex:_,displaySeq:I,text:t,publishedText:t,receivedSnapshotCount:1,streamingPublishCount:1,startedAtMs:Date.now(),startedAtMonotonicMs:performance.now()};return e.stream.addPart(C(r,t,"streaming")),_+=1,I+=1,p=r,r},A=t=>{void 0===t.publishTimer&&(t.publishTimer=setTimeout(()=>{t.publishTimer=void 0,te("reasoning_snapshot_flush",()=>{p===t&&(t=>{t.publishedText!==t.text&&(e.stream.replacePart(t.partIndex,C(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,C(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})},O=e=>{const t=h.indexOf(e);t>=0&&h.splice(t,1)},F=e=>null!=e&&("object"!=typeof e||(Array.isArray(e)?e.length>0:Object.keys(e).length>0)),N=e=>{let t=v.get(e);return t||(t={},v.set(e,t)),t},j=(t,r,s)=>{const o="tool"===t.name&&"tool"!==r?r:t.name,a=!F(t.arguments)&&F(s)?s:t.arguments;o===t.name&&a===t.arguments||(e.stream.replacePart(t.partIndex,toMessagePart({type:"tool_use",id:t.id,name:t.htmlPresentation?.name??o,arguments:t.htmlPresentation?.arguments??a,state:t.state,_seq:t.displaySeq,data:S(t.displaySeq)})),t.name=o,t.arguments=a)},B=(t,r,s,o)=>{const a=f.get(t);if(a)return j(a,r,s),o&&!h.includes(t)&&"streaming"===a.state&&h.push(t),a;T();const n=v.get(t),i="tool"!==r?r:n?.name&&"tool"!==n.name?n.name:r,l=F(s)?s:n?.arguments??s,d=((t,r,s)=>{const o=_,a=I;return e.stream.addPart(toMessagePart({type:"tool_use",id:t,name:r,arguments:s,state:"streaming",_seq:a,data:S(a)})),_+=1,I+=1,{partIndex:o,displaySeq:a}})(t,i,l),u={id:t,name:i,arguments:l,partIndex:d.partIndex,displaySeq:d.displaySeq,state:"streaming",itemEventObserved:!0===n?.itemEventObserved,toolStartObserved:!0===n?.toolStartObserved};return f.set(t,u),(o||u.toolStartObserved||u.itemEventObserved)&&(h.includes(t)||"streaming"!==u.state||h.push(t)),n&&Q(u,n),v.delete(t),u},D=(e,t)=>{const r=(e=>f.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)&&!h.includes(r.id)&&"streaming"===r.state&&h.push(r.id),r;const s=N(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)},L=t=>{"done"!==t.state&&(e.stream.replacePart(t.partIndex,toMessagePart({type:"tool_use",id:t.id,name:t.htmlPresentation?.name??t.name,arguments:t.htmlPresentation?.arguments??t.arguments,state:"done",_seq:t.displaySeq,data:S(t.displaySeq)})),t.state="done")},H=e=>{if(null===e||"object"!=typeof e)return JSON.stringify(e)??String(e);if(Array.isArray(e))return`[${e.map(H).join(",")}]`;return`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${H(t)}`).join(",")}}`},z=(t,r,s)=>{const o=`${s?"1":"0"}:${H(r)}`;if(t.progressSignature===o)return;const a=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=_;return e.stream.addPart(a),t.progressPartIndex=r,t.progressSignature=o,void(_+=1)}e.stream.replacePart(t.progressPartIndex,a),t.progressSignature=o},Q=(e,t)=>{if(t.progress?.length)for(const r of t.progress)z(e,r.content,r.isError);t.observedResult&&(z(e,t.observedResult.content,t.observedResult.isError),e.observedResult=t.observedResult,"tool_call"!==e.name&&!isRenderUiToolName(e.name)||t.observedResult.isError||V(e,{text:t.observedResult.content,isError:t.observedResult.isError,rawResult:t.observedResult.rawResult})),(t.progress?.length||t.observedResult)&&(L(e),O(e.id)),!t.observedResult&&t.htmlPayload&&V(e,t.htmlPayload),t.sources?.length&&E(t.sources,e.id)},W=e=>[...new Set([e.mediaUrl,...e.mediaUrls??[]].filter(e=>isNonEmptyString(e)).map(e=>e.trim()).filter(Boolean))],J=(e,t=[])=>{const r=[...new Set([...W(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.":""},K=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},G=t=>{x.add(t);const r=()=>{x.delete(t)};e.onCallbackFailure?t.then(r,r):t.finally(r)},V=(t,r)=>{const s=t.observedResult,o=s?.isError??!0===r.isError,a=s?.rawResult??pickRawResultFromPayload(r),n=o?void 0:staticHtmlProjectionOf(t.name,t.arguments,a);if(!n&&isStaticHtmlInvocation(t.name,t.arguments))return;if(n&&e.htmlDelivery?.publishedFileId&&e.htmlDelivery.publishedFileId!==n.result.artifact.fileId)return;if(t.durableUploadFilesEmitted&&(!n||t.staticHtmlResultEmitted))return;e.logger.info?.(`[im-sink] schedule tool artifact enrichment requestId=${e.requestId} toolUseId=${t.id} name=${t.name}`);const i=(async()=>{let s=[];try{s=await resolveToolArtifactLinks({toolCallId:t.id,toolName:t.name,rawResult:a,rawText:"string"==typeof r.text?r.text:void 0,params:asToolParams(t.arguments),cwd:sessionWorkspaceDir(e.sessionKey),payloadMediaUrls:W(r)})}catch(r){const s=r instanceof Error?r.message:String(r);if(e.logger.warn?.(`[im-sink] resolveToolArtifactLinks failed requestId=${e.requestId} toolUseId=${t.id} error=${s}`),e.onCallbackFailure?.(r),e.onCallbackFailure)throw r;return}n&&(s=s.filter(e=>e.uri!==n.result.artifact.uri)),0!==s.length||n?(e.logger.info?.(`[im-sink] tool artifact enrichment resolved ${s.length} link(s) requestId=${e.requestId} toolUseId=${t.id}`),await new Promise((o,a)=>{const i=e.callbackQueue.enqueueSync(()=>{try{if(e.abortSignal.aborted||e.stream.isTerminated)return;const o=s.map(e=>e.uri);t.artifactMediaUrls=o;const a=t.observedResult;z(t,J(a?{text:a.content,isError:a.isError}:n?{...r,mediaUrl:r.mediaUrl===n.result.artifact.uri?void 0:r.mediaUrl,mediaUrls:r.mediaUrls?.filter(e=>e!==n.result.artifact.uri)}:r,o),a?.isError??!0===r.isError),((t,r,s,o)=>{const a=r.length>0&&!t.durableUploadFilesEmitted,n=!s&&void 0!==o&&!t.staticHtmlResultEmitted;(a||n)&&(n&&(t.htmlPresentation={name:"render_ui",arguments:o.arguments},e.stream.replacePart(t.partIndex,toMessagePart({type:"tool_use",id:t.id,...t.htmlPresentation,state:t.state,_seq:t.displaySeq,data:S(t.displaySeq)}))),e.stream.appendToolResult(t.id,[...n?[{type:"text",text:JSON.stringify(o.result)}]:[],...a?r.map(e=>({type:"resource_link",uri:e.uri,name:e.name,...e.mimeType?{mimeType:e.mimeType}:{}})):[]],s),_+=1,n&&(t.staticHtmlResultEmitted=!0,e.htmlDelivery?.recordReply(o.result)),a&&(t.durableUploadFilesEmitted=!0,K(r),s||e.htmlDelivery?.recordUploadReply(t.id,r)))})(t,s,a?.isError??!0===r.isError,n)}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}`),e.onCallbackFailure?.(r),e.onCallbackFailure&&a(r)}finally{o()}});!1===i&&e.onCallbackFailure&&e.callbackQueue.waitForIdle().then(o,a)})):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);if(e.logger.warn?.(`[im-sink] tool artifact enrichment failed requestId=${e.requestId} toolUseId=${t.id} error=${s}`),e.onCallbackFailure?.(r),e.onCallbackFailure)throw r});G(i)},X=(e,t,r)=>D(e,{name:t,arguments:r}),Y={tool:0,block:0,final:0,source:0};let Z,ee=!1;const te=(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):!ee||(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}`),e.onCallbackFailure?.(r)}})},re={sendToolResult:t=>(te("tool_progress",()=>{const r=resolveRuntimeToolCallId(t),s=resolveRuntimeToolName(t),o=resolveRuntimeToolArguments(t),a=J(t),n=!0===t.isError;let i;if(r){if(i=X(r,s,o),!i){const e=N(r);if(s&&(e.name=s),F(o)&&(e.arguments=o),e.progress=[...e.progress??[],{content:a,isError:n}],"tool_call"===s||isRenderUiToolName(s??"")){const r=pickRawResultFromPayload(t);(n||void 0!==r)&&(e.htmlPayload=!n&&staticHtmlResultOf(r)?t:void 0)}return void(Y.tool+=1)}i&&(Y.tool+=1,i.observedResult||z(i,a,n),L(i),O(i.id),V(i,t))}else e.logger.debug?.(`[im-sink] unattributed tool progress ignored requestId=${e.requestId} channel=${e.channelId} tool=${s??"unknown"} pending=${h.length}`)}),!0),sendBlockReply:e=>(te("block_reply",()=>{Y.block+=1,isNonEmptyString(e.text)&&(Z=!0!==e.isError?void 0:e.text)}),!0),sendFinalReply:t=>(te("final_reply",()=>{Y.final+=1,!0!==t.isError?((t=>{const r=W(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);if(e.logger.warn?.(`[im-sink] final media enrichment failed requestId=${e.requestId} error=${t instanceof Error?t.message:String(t)}`),e.onCallbackFailure?.(t),e.onCallbackFailure)throw t;return}if(0!==t.length)await new Promise((r,s)=>{!1===e.callbackQueue.enqueueSync(()=>{try{if(e.abortSignal.aborted||e.stream.isTerminated)return;K(t)}catch(t){e.logger.warn?.(`[im-sink] final media enrichment apply failed requestId=${e.requestId} error=${t instanceof Error?t.message:String(t)}`),e.onCallbackFailure?.(t),e.onCallbackFailure&&s(t)}finally{r()}})&&e.onCallbackFailure&&e.callbackQueue.waitForIdle().then(r,s)});else for(const e of r)w.delete(e)})();G(s)})(t),isNonEmptyString(t.text)&&(Z=void 0,l||(e=>{const t=new BeeosMediaDirectiveStream,r=t.write(e)+t.finish();i="",n+=r,k(n),r&&$(r),l=!0})(t.text))):Z=t.text}),!0),waitForIdle:async()=>{for(let t=0;(e.onCallbackFailure||t<16)&&(await e.callbackQueue.waitForIdle(),0!==x.size);t++)e.onCallbackFailure?await Promise.all([...x]):await Promise.allSettled([...x]);await e.callbackQueue.waitForIdle();const t=takeFinalizeAttachments(e.sessionKey);t.length>0&&!e.abortSignal.aborted&&!e.stream.isTerminated&&K(t)},getQueuedCounts:()=>({tool:Y.tool,block:Y.block,final:Y.final}),getAccumulatedBody:()=>a.text,getTerminalErrorText:()=>Z,markComplete:r=>{U(),v.size>0&&e.logger.debug?.(`[im-sink] dropping uncommitted lifecycle tool signals requestId=${e.requestId} buffered=${v.size}`),i="",k(n),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&&V(t,{toolCallId:t.id,toolName:t.name}),"success"===r&&L(t),O(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}`)}v.clear(),ee=!0}},se={...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=>{te("partial",()=>{l||"string"==typeof s.text&&(!r&&s.text.length>0&&(r=!0,logChatLatency(e.logger,"claw.model.first_delta",e.requestId,t)),i=(new BeeosMediaDirectiveStream).write(s.text),(e=>{const t=m;if(!t){if(a.text===e)return;return R(e),void(m={targetBody:e,receivedSnapshotCount:1,streamingPublishCount:1,terminalPublishCount:0})}t.targetBody!==e&&(t.targetBody=e,t.receivedSnapshotCount+=1,P(t))})(n+i))})},onReasoningStream:e=>{te("reasoning",()=>{if(!isNonEmptyString(e.text))return;const t=e.text,r=p??M(t);t!==r.text&&(r.text.startsWith(t)||(t.startsWith(r.text)?(r.text=t,r.receivedSnapshotCount+=1,A(r)):(U(),M(t))))})},onReasoningEnd:()=>{te("reasoning_end",()=>{U()})},onAssistantMessageStart:()=>{te("assistant_message_start",()=>{i="",l=!1,k(n),e.logger.debug?.(`[im-sink] assistant_message_start requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`)})},onToolStart:r=>{te("tool_start",()=>{const o="string"==typeof r.phase?r.phase:"start",a=resolveRuntimeToolName(r)??"tool",n=resolveRuntimeToolCallId(r),i=resolveRuntimeToolArguments(r);"update"!==o?(n&&s.set(n,Date.now()),logChatLatency(e.logger,"claw.tool.start",e.requestId,t,{tool:a}),n&&D(n,{name:a,arguments:i,toolStartObserved:!0,pending:!0})):n&&D(n,{name:a,arguments:i,pending:!0})})},onItemEvent:e=>{te("item_event",()=>{const t="string"==typeof e.kind?e.kind.toLowerCase():"";if(t&&"tool"!==t)return;"string"==typeof e.phase&&e.phase.toLowerCase();const r=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);r&&s&&D(r,{name:s,itemEventObserved:!0,pending:!0})})}},oe={add(t){if(e.stream.isTerminated)return;const r=_;return e.stream.addPart(t),_+=1,r}},ae={add:e=>oe.add(e),replace:(t,r)=>!e.stream.isTerminated&&(e.stream.replacePart(t,r),!0)};return{dispatcher:re,replyOptions:se,commitAssistantMessage:t=>{te("assistant_message_commit",()=>{if(u.has(t.key))return;u.add(t.key),l=!0,Z=void 0;const r=visibleAssistantSegments(t.segments);i="";const s=r.filter(e=>"text"===e.type).map(e=>e.text).join("");n+=s,k(n);for(const e of r)"text"!==e.type?B(e.id,e.name,e.arguments,!0):$(e.text);if(void 0!==t.executedModel||void 0!==b){const r=toMessagePart({type:"custom",kind:"execution_model",data:{executed_model:t.executedModel??""}});void 0===b?(e.stream.addPart(r),b=_++):e.stream.replacePart(b,r)}})},observeToolResult:r=>{te("tool_result_observation",()=>{const a=r.toolCallId.trim(),n=r.toolName.trim();if(!a||!n)return;const i=!o.has(a);if(i){o.add(a);const i=s.get(a);logChatLatency(e.logger,"claw.tool.result",e.requestId,t,{tool:n,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"}:{}})}if(e.persistObservedToolResults&&i){const e=observedToolResultText(r.rawResult)??("tool_call"===n||isRenderUiToolName(n)?"":void 0);if(void 0!==e){const t=X(a,n);if(t)z(t,J({text:e,isError:r.isError},t.artifactMediaUrls),r.isError),t.observedResult={content:e,isError:r.isError,rawResult:r.rawResult},L(t),O(t.id),"tool_call"!==t.name&&!isRenderUiToolName(t.name)||r.isError||V(t,{text:e,isError:r.isError,rawResult:r.rawResult});else{const t=N(a);t.name??=n,t.observedResult={content:e,isError:r.isError,rawResult:r.rawResult}}}}const l=searchSourceProvider(r.rawResult)??"unknown";let d=0;try{const t=extractSearchSources({toolName:n,rawResult:r.rawResult,isError:r.isError});if(d=t.length,0===d)return;const s=X(a,n);if(s)E(t,s.id);else{const e=N(a);e.name??=n,e.sources=((e,t)=>{if(!e?.length&&!t?.length)return;const r=[],s=new Map;for(const o of[...e??[],...t??[]]){const e=s.get(o.url);void 0===e?(s.set(o.url,r.length),r.push(o)):r[e]=mergeSearchSource(r[e],o)}return r})(e.sources,t)}e.logger.debug?.(`[im-sink] search source projection requestId=${e.requestId} tool=${n} provider=${l} source_count=${d}`)}catch{e.logger.warn?.(`[im-sink] search source projection ignored requestId=${e.requestId} tool=${n} provider=${l} source_count=${d}`)}})},getSourceCount:()=>Y.source,approvalParts:oe,questionParts:ae}}
|
|
@@ -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{RuntimeMessageChannelProtocolError}from"./message-service-runtime-message-channel.js";import{RuntimeResourceResolutionError}from"./runtime-operation-resource-resolver.js";import{RuntimeTransportFailurePolicy}from"@beeos-ai/cloud-harness-sdk";import{NativePromptExecutionFailure,nativePromptCancellationReason,nativePromptUnknownReason}from"./native-cloud-prompt-bridge.js";const leaseStarvationReportIntervalMs=3e4,maxReadBackoffMs=3e4;export class MsRuntimeMessageChannelAdapter{dispatcher;channel;verifier;ports;journal;getLease;options;controller;running;externalDeliveryOwner;workers=new Map;poisonJournal;renewTransportFailurePolicy=new RuntimeTransportFailurePolicy;readTransportFailurePolicy=new RuntimeTransportFailurePolicy;readBackoffMs=0;leaseStarvedSince;leaseStarvationReportedAt=0;receiptHistory=this;constructor(e,t,a,r,o,n,i){if(this.dispatcher=e,this.channel=t,this.verifier=a,this.ports=r,this.journal=o,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())this.cancelWorker(e);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 r=validateRuntimeRequestEnvelope(e.message),o=r.ok?r.envelope.payload.operationId:e.message.channel_id;if(this.workers.has(o))return;const n={deliveryId:e.deliveryId,claimedLease:t,completion:Promise.resolve()};n.completion=this.handleRequest(e,t,a,e=>{this.setWorkerCancel(n,e)}).catch(e=>this.observeDeliveryError(e)).finally(()=>{this.workers.delete(o)}),this.workers.set(o,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.readFailureDelayMs(t),e);continue}this.readTransportFailurePolicy.recordSuccess(),this.readBackoffMs=0;for(const r of a){if(e.aborted)break;if(r.message.type===RUNTIME_MESSAGE_TYPES.cancel){await this.handleCancel(r,t).catch(e=>this.observeDeliveryError(e));continue}const a=r.message.channel_id;if(this.workers.has(a))continue;const o={deliveryId:r.deliveryId,claimedLease:t,completion:Promise.resolve()};o.completion=this.handleRequest(r,t,e,e=>{this.setWorkerCancel(o,e)}).catch(e=>this.observeDeliveryError(e)).finally(()=>{this.workers.delete(a)}),this.workers.set(a,o)}}}finally{t&&clearInterval(t),await Promise.allSettled([...this.workers.values()].map(e=>e.completion))}}observeDeliveryError(e){try{this.options.onDeliveryError?.(e)}catch{}}readFailureDelayMs(e){const t=this.options.idleDelayMs??500,a=e instanceof RuntimeMessageChannelProtocolError?e.status:void 0;return 401===a||403===a||this.readTransportFailurePolicy.recordFailure()?(this.readBackoffMs=Math.min(this.readBackoffMs?2*this.readBackoffMs:2*t,3e4),this.readBackoffMs):t}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):this.cancelWorker(a);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)&&this.cancelWorker(t)}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)&&this.cancelWorker(t)}}cancelWorker(e,t){e.cancelRequested||(e.cancelRequested=!0,e.cancelReason=t),e.cancel?.(e.cancelReason)}setWorkerCancel(e,t){const a=e.cancelRequested&&void 0===e.cancel;e.cancel=t,a&&t(e.cancelReason)}async handleCancel(e,t){const a=validateRuntimeCancelEnvelope(e.message);if(!a.ok)return void await this.handlePoison(e,`invalid_cancel:${a.reason}`,t);const r=a.envelope.payload,o=await this.channel.history({operationId:r.operationId,lease:t});if("found"===o.status&&o.snapshot.terminal&&"final_message"===o.snapshot.terminalSource)return void await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t});if("not_found"===o.status||"expired"===o.status)return void await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t});const n=o.snapshot.request.payload;if(n.operationId!==r.operationId||n.requestMessageId!==r.requestMessageId||n.requestHash!==r.requestHash||n.dispatchEpoch!==r.dispatchEpoch||n.method!==r.method)return void await this.handlePoison(e,"cancel_history_mismatch",t);await this.journal.observeCancellation({operationId:r.operationId,requestMessageId:r.requestMessageId,requestHash:r.requestHash,eventId:r.eventId});const i=n,s=2===i.schemaVersion&&"session/prompt"===i.method,d=this.workers.get(r.operationId);d&&this.cancelWorker(d,s?nativePromptCancellationReason:void 0),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t})}async handleRequest(e,t,a,r){const o=e.message.payload;if(2===o.schemaVersion&&"session/prompt"===o.method&&this.options.nativePromptBridge){let o;try{o=await this.options.nativePromptBridge.execute({delivery:e,lease:t,signal:a,setCancel:r})}catch(a){if(!(a instanceof NativePromptExecutionFailure))throw a;a.failure instanceof RuntimeCommandError&&Object.prototype.hasOwnProperty.call(RUNTIME_ERROR_DESCRIPTORS,a.failure.code)&&a.failure.code;const r=await this.channel.append({operationId:a.request.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(a.request,a.failure,(new Date).toISOString())});return this.observeRequestTerminalAccepted(e.deliveryId,r.message),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),void this.observeRequestAcknowledged(e.deliveryId,r.message)}if(o.replayedFinal)return this.observeRequestTerminalAccepted(e.deliveryId,o.replayedFinal),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),void this.observeRequestAcknowledged(e.deliveryId,o.replayedFinal);if("succeeded"!==o.outcome){const a=await this.channel.append({operationId:o.request.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(o.request,new RuntimeCommandError("cancelled"===o.outcome?"OPERATION_CANCELLED":"EXECUTION_FAILED","native durable reply reports non-success"),(new Date).toISOString())});return this.observeRequestTerminalAccepted(e.deliveryId,a.message),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),void this.observeRequestAcknowledged(e.deliveryId,a.message)}const n=runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:o.request.method,result:o.result}),i={schemaVersion:1,operationId:o.request.operationId,method:o.request.method,coreResultRef:`sha256:${n}`,coreResultHash:n},s=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,i);await this.channel.append({operationId:o.request.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(o.request),effectRecord:i,effectRecordHash:s,committedAt:(new Date).toISOString()}});const d=await this.channel.append({operationId:o.request.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(o.request),outcome:o.outcome,response:{jsonrpc:"2.0",id:o.request.request.id,result:o.result},serviceResultHash:runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:o.request.method,result:o.result}),effectRecordHash:s,completedAt:(new Date).toISOString()}});return this.options.onRequestTerminalAccepted?.({deliveryId:e.deliveryId,message:d.message}),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),void this.options.onRequestAcknowledged?.({deliveryId:e.deliveryId,message:d.message})}const n=validateRuntimeRequestEnvelope(e.message);if(!n.ok)return void await this.handlePoison(e,`invalid_request:${n.reason}`,t);if(n.envelope.payload.schemaVersion!==(this.options.requestSchemaVersion??1))return void await this.handlePoison(e,"request_realm_mismatch",t);const i=n.envelope.payload,s=e.executionGrant,d=createRuntimeAppendTimingRecorder("runtime-op",{operationId:i.operationId,method:i.method}),c=new AbortController;r(()=>c.abort());const l=async()=>{await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),d.mark("ack")},u=await this.channel.history({operationId:i.operationId,lease:t});if(d.mark("history"),"not_found"===u.status||"expired"===u.status)return void await l();if(u.snapshot.terminal&&"final_message"===u.snapshot.terminalSource)return void await l();if(this.options.allowedMethods&&!this.options.allowedMethods.has(i.method))return await this.reject(i,"unsupported_method",t),void await l();if("deadline"===u.snapshot.terminalSource||Date.parse(i.executionDeadlineAt)<=Date.now()||!u.snapshot.started&&Date.parse(i.claimDeadlineAt)<=Date.now())return await this.reject(i,"execution_deadline_exceeded",t),void await l();const p=await this.journal.getCancellation(i.operationId);d.mark("journal-cancel-read");const h=u.snapshot.cancelRequested||null!==p;if(h&&"queued"===u.snapshot.status)return await this.reject(i,"cancelled_before_dispatch",t),void await l();if(i.instanceId!==t.instanceId||i.runtimeHandlerIdentity!==t.handlerIdentity||i.dispatchEpoch!==t.runtimeEpoch)return await this.reject(i,"authority_mismatch",t),void await l();const m=u.snapshot.request.payload;if(u.snapshot.operationId!==i.operationId||u.snapshot.requestMessageId!==i.requestMessageId||u.snapshot.requestHash!==i.requestHash||!semanticEqual(m,i))return void await this.handlePoison(e,"request_history_mismatch",t);const I=u.snapshot.started?.payload,v=void 0!==I&&I.operationId===i.operationId&&I.requestMessageId===i.requestMessageId&&I.requestHash===i.requestHash&&I.executionGrantHash===i.executionGrantHash&&I.handlerIdentity===t.handlerIdentity&&I.dispatchEpoch===t.runtimeEpoch&&I.method===i.method,E=await this.journal.get(i.operationId);d.mark("journal-prior");const f=runtimeCommandIsReplayableQuery(i.command.name),R=f?ephemeralQueryAccept(i):await this.journal.acceptMessageRequest({operationId:i.operationId,command:i.command.name,paramsHash:i.paramsHash,runtimeEpoch:i.dispatchEpoch,requestMessageId:i.requestMessageId,requestHash:i.requestHash});d.mark("journal-accept");const y=v?E:R,w=f?"execute":decideMessageServiceRecovery(u.snapshot,i,y,v);if("already_terminal"===w)return void await l();if(!CORE_RECOVERY_DECISIONS.has(w))return f||await this.markOutcomeUnknownIfMutable(R),await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(i,new RuntimeCommandError("OUTCOME_UNKNOWN",`Types recovery policy requires ${w}; this runtime cannot safely replay Core`),(new Date).toISOString())}),void await l();if(await this.verifier.refresh(),d.mark("verifier-refresh"),!s)return v?await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(i,new RuntimeCommandError("OUTCOME_UNKNOWN","retained started proof has no live execution grant"),(new Date).toISOString())}):await this.reject(i,"invalid_execution_grant",t),void await l();this.verifier.verifyAndDecodeGrant(s)||await this.verifier.refresh(!0);const g=()=>c.abort();let _;a.addEventListener("abort",g,{once:!0});try{_=await verifyAndCreateMessageServiceCoreExecutionAttempt({request:i,executionGrant:s,runtimeEpoch:t.runtimeEpoch,lease:t,verifier:this.verifier,allowExpiredGrant:v,abortSignal:c.signal,resolvePorts:async()=>await this.ports.resolve({request:i,executionGrant:s,command:i.command,getLease:()=>this.currentLease(t),...this.journalLineage(),journalRecord:R,abortSignal:c.signal})})}catch(e){if(a.removeEventListener("abort",g),c.abort(),!(e instanceof RuntimeResourceResolutionError))throw e;if(this.observeRequestFailure(i.operationId,i.method,e),"transient"===e.kind)return;return v?(f||await this.markOutcomeUnknownIfMutable(R),await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(i,new RuntimeCommandError("OUTCOME_UNKNOWN","eager resources cannot be reconstructed after retained started proof"),(new Date).toISOString())})):await this.reject(i,"integrity_mismatch"===e.kind?"resource_integrity_mismatch":"resource_resolution_rejected",t),void await l()}if(!_.ok)return a.removeEventListener("abort",g),c.abort(),this.observeRequestFailure(i.operationId,i.method,new Error(`execution grant rejected: ${_.violations.join(",")}`)),v?(f||await this.markOutcomeUnknownIfMutable(R),await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(i,new RuntimeCommandError("OUTCOME_UNKNOWN","execution grant cannot be revalidated after retained started proof"),(new Date).toISOString())})):await this.reject(i,"invalid_execution_grant",t),void await l();if(!h||"prepared"!==R.phase&&"started"!==R.phase||c.abort(),c.signal.aborted&&!v)return a.removeEventListener("abort",g),await this.reject(i,"cancelled_before_dispatch",t),void await l();d.mark("attempt"),v?this.currentLease(t):(await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),executionGrant:s,type:RUNTIME_MESSAGE_TYPES.started,payload:{...runtimeMessageBase(i),executionMode:"start",executionGrantHash:i.executionGrantHash,handlerIdentity:t.handlerIdentity,claimedAt:R.messageBinding?.acceptedAt??R.updatedAt}}),d.mark("append-started"));const M=this.dispatcher.dispatch(i.command,_.context);M.completion.catch(()=>{}),r(()=>{c.abort(),M.cancel()}),c.signal.aborted&&M.cancel();const S=this.forwardProgress(i,M.progress,t).catch(()=>{});let N,O=!1;try{if(("mcp/set"===i.method||"mcp/unset"===i.method)&&hasEffectReceiptHandoff(M)){const e=await M.effectCommitted;if(e){if(e.operationId!==i.operationId||e.method!==i.command.name)throw new RuntimeCommandError("OUTCOME_UNKNOWN","Core MCP receipt correlation mismatch");const a=runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:i.method,result:e.result}),r={schemaVersion:1,operationId:i.operationId,method:i.method,coreResultRef:`sha256:${a}`,coreResultHash:a};N=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,r),O=!0,await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(i),effectRecord:r,effectRecordHash:N,committedAt:e.committedAt}}),await M.acknowledgeEffectReceipt({operationId:i.operationId,method:i.command.name,effectRecordHash:N})}}const a=await M.completion;if(await S,d.mark("core"),f){const r=(new Date).toISOString();let o;try{o=sanitizeRuntimeServiceResult(i.method,a,_.context,void 0)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed Core result cannot be mapped safely",void 0,{cause:e})}const n=runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:i.method,result:o}),s=await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(i),outcome:"succeeded",response:{jsonrpc:"2.0",id:i.request.id,result:o},serviceResultHash:n,completedAt:r}});return d.mark("append-final"),this.observeRequestTerminalAccepted(e.deliveryId,s.message),await l(),void this.observeRequestAcknowledged(e.deliveryId,s.message)}const r=await this.journal.get(i.operationId);if(d.mark("journal-after-core"),!r||!isCommittedCorePhase(r.phase))throw new RuntimeCommandError("OUTCOME_UNKNOWN","Core completed without a committed local journal record");const o=r.updatedAt;let n,s;if("query"!==RUNTIME_INVOCATION_RECOVERY_CLASSES[i.method]){const e=isAgentProjectionMethod(i.method),s=M.getSnapshot().projection,c=r.agentProjectionIntent??r.agentProjectionPreparationFailure;if(e&&!c)throw new RuntimeCommandError("OUTCOME_UNKNOWN","agent effect committed without an atomic projection preparation record");if(!N&&"session/clear"!==i.method){const e=c?.coreResultHash??runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:i.method,result:a}),n=r.agentProjectionIntent?.projectionRevision??(methodRequiresProjectionRevision(i.method)?s?.revision??`${Math.max(0,r.revision)}`:void 0),l={schemaVersion:1,operationId:i.operationId,method:i.method,coreResultRef:`sha256:${e}`,coreResultHash:e,...n?{projectionRevision:n}:{}};N=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,l),O=!0,await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(i),effectRecord:l,effectRecordHash:N,committedAt:o}}),d.mark("append-effect")}let u=e?await awaitRuntimeProjection(M):s;if("session/set_model"===i.method&&"synced"!==u?.state&&(u=await this.projectSessionModelAfterEffect(i,_.context,r,u),d.mark("set-model-projection")),e&&r.agentProjectionIntent&&(!u||u.revision!==r.agentProjectionIntent.projectionRevision))throw new RuntimeCommandError("OUTCOME_UNKNOWN","agent projection receipt revision mismatch");if("pending"===u?.state)return void await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.projectionPending,payload:{...runtimeMessageBase(i),revision:u.revision}});if("synced"===u?.state&&await this.publishProjectionSynced(i,t,{...u,state:"synced"}),"blocked"===u?.state){await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.projectionBlocked,payload:{...runtimeMessageBase(i),revision:u.revision,errorCode:"PROJECTION_BLOCKED"}});const e=RUNTIME_ERROR_DESCRIPTORS.PROJECTION_BLOCKED;return await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(i),outcome:"projection_blocked",response:{jsonrpc:"2.0",id:i.request.id,error:{code:e.jsonRpcCode,message:"PROJECTION_BLOCKED",data:{code:"PROJECTION_BLOCKED",operationId:i.operationId,effectState:"committed",retryMode:e.retryMode}}},effectRecordHash:N,completedAt:o}}),void await l()}n=e?u?.platformAgentId:void 0}try{s=sanitizeRuntimeServiceResult(i.method,a,_.context,n)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed Core result cannot be mapped safely",void 0,{cause:e})}const c=runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:i.method,result:s});O=!0;const u=await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(i),outcome:"succeeded",response:{jsonrpc:"2.0",id:i.request.id,result:s},serviceResultHash:c,...N?{effectRecordHash:N}:{},completedAt:o}});if(d.mark("append-final"),this.observeRequestTerminalAccepted(e.deliveryId,u.message),("mcp/set"===i.method||"mcp/unset"===i.method)&&hasEffectReceiptHandoff(M)&&"function"==typeof M.acknowledgeTerminalReceipt){if(!N)throw new RuntimeCommandError("OUTCOME_UNKNOWN","MCP terminal response lacks its committed effect hash");await M.acknowledgeTerminalReceipt({operationId:i.operationId,method:i.command.name,effectRecordHash:N,terminalMessageId:u.message.message_id})}await l(),this.observeRequestAcknowledged(e.deliveryId,u.message)}catch(e){const a=await this.journal.get(i.operationId);if(a&&isCommittedCorePhase(a.phase)&&O)throw e;const r=!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(i.operationId,i.method,r);const o=failurePayload(i,r,a?.updatedAt??(new Date).toISOString());await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:o}),d.mark("append-terminal-failure"),await l()}finally{d.finish(),c.abort(),a.removeEventListener("abort",g)}}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 r of t)await this.channel.append({operationId:e.operationId,lease:this.currentLease(a),type:RUNTIME_MESSAGE_TYPES.progress,payload:{...runtimeMessageBase(e),phase:r.phase,progress:r}})}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,r){const o=Object.freeze({state:"pending",revision:r?.revision??`${Math.max(0,a.revision)}`}),n=e.command;if("session.setModel"!==n.name||"conversation"!==n.context.scope)return o;const i=t.sessionModelProjection;if(!i)return o;try{await i.project({conversationId:n.context.conversation.runtimeConversationUid,modelOverrideId:n.params.modelOverrideId});const e=Object.freeze({state:"synced",revision:o.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),o}}async publishProjectionSynced(e,t,a){const r=this.currentLease(t),o=await this.channel.history({operationId:e.operationId,lease:r});if("found"===o.status&&"synced"===o.snapshot.projectionState)return;const n={...runtimeMessageBase(e),revision:a.revision};("found"!==o.status||"reserved"===o.snapshot.projectionState||"pending"!==o.snapshot.projectionState&&void 0===o.snapshot.projectionPending)&&await this.channel.append({operationId:e.operationId,lease:r,type:RUNTIME_MESSAGE_TYPES.projectionPending,payload:n}),await this.channel.append({operationId:e.operationId,lease:r,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,r){const o=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":r?"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:o?.recoveryClass??RUNTIME_INVOCATION_RECOVERY_CLASSES[t.method],projectionRequired:"mcp/set"===t.method||"mcp/unset"===t.method||(o?.projectionRequired??!1),messageServicePhase:n,executionBoundaryCrossed:r,lineageContinuity:s,journalState:a?"available":"unavailable",...i?{journalPhase:i}:{}})}export function sanitizeRuntimeServiceResult(e,t,a,r){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 o="cron/status"===e&&record(t)?{enabled:t.enabled,jobCount:t.jobCount,..."number"==typeof t.nextWakeAtMs?{nextWakeAtMs:t.nextWakeAtMs}:{}}:t;return mapCanonicalResultToService(e,o,{...r?{platformAgentId:r}:{},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 r=a.params.modelOverrideId;return{conversationId:a.context.conversation.runtimeConversationUid,...null===r?{defaultModelId:e.effectiveModelId}:{},modelOverrideId:r,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 r=t instanceof RuntimeCommandError?t.code:"RUNTIME_EXECUTION_FAILED",o=r in RUNTIME_ERROR_DESCRIPTORS?r:"RUNTIME_EXECUTION_FAILED",n="OUTCOME_UNKNOWN"===o||"INSTANCE_EPOCH_MISMATCH"===o?"outcome_unknown":"COMMAND_EXPIRED"===o?"expired":"OPERATION_CANCELLED"===o?"cancelled":"failed",i="outcome_unknown"===n?"OUTCOME_UNKNOWN":o,s=RUNTIME_ERROR_DESCRIPTORS[i],d="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:d,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",r=RUNTIME_ERROR_DESCRIPTORS[a in RUNTIME_ERROR_DESCRIPTORS?a:"RUNTIME_EXECUTION_FAILED"],o="COMMAND_EXPIRED"===a?"expired":"OPERATION_CANCELLED"===a?"cancelled":"failed";return{...runtimeMessageBase(e),outcome:o,response:{jsonrpc:"2.0",id:e.request.id,error:{code:r.jsonRpcCode,message:a,data:{code:a,operationId:e.operationId,effectState:o,retryMode:r.retryMode}}},completedAt:(new Date).toISOString()}}function abortable(e,t){return t?t.aborted?Promise.resolve():new Promise((a,r)=>{const o=()=>a();t.addEventListener("abort",o,{once:!0}),e.then(()=>{t.removeEventListener("abort",o),a()},e=>{t.removeEventListener("abort",o),r(e)})}):e}function delay(e,t){return new Promise(a=>{if(t?.aborted)return a();const r=()=>{clearTimeout(o),a()},o=setTimeout(()=>{t?.removeEventListener("abort",r),a()},e);t?.addEventListener("abort",r,{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{RuntimeMessageChannelProtocolError}from"./message-service-runtime-message-channel.js";import{RuntimeResourceResolutionError}from"./runtime-operation-resource-resolver.js";import{RuntimeTransportFailurePolicy}from"@beeos-ai/cloud-harness-sdk";import{NativePromptExecutionFailure,nativePromptCancellationReason,nativePromptUnknownReason}from"./native-cloud-prompt-bridge.js";import{isCentralNativeResponse}from"./central-native-response.js";const leaseStarvationReportIntervalMs=3e4,maxReadBackoffMs=3e4;export class MsRuntimeMessageChannelAdapter{dispatcher;channel;verifier;ports;journal;getLease;options;controller;running;externalDeliveryOwner;workers=new Map;poisonJournal;renewTransportFailurePolicy=new RuntimeTransportFailurePolicy;readTransportFailurePolicy=new RuntimeTransportFailurePolicy;readBackoffMs=0;leaseStarvedSince;leaseStarvationReportedAt=0;receiptHistory=this;constructor(e,t,a,r,o,n,i){if(this.dispatcher=e,this.channel=t,this.verifier=a,this.ports=r,this.journal=o,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())this.cancelWorker(e);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 r=validateRuntimeRequestEnvelope(e.message),o=r.ok?r.envelope.payload.operationId:e.message.channel_id;if(this.workers.has(o))return;const n=this.createWorker(e,t);n.completion=this.handleRequest(e,t,a,e=>{this.setWorkerCancel(n,e)}).catch(e=>this.observeDeliveryError(e)).finally(()=>{n.centralVerification?.complete(),this.workers.delete(o)}),this.workers.set(o,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.readFailureDelayMs(t),e);continue}this.readTransportFailurePolicy.recordSuccess(),this.readBackoffMs=0;for(const r of a){if(e.aborted)break;if(r.message.type===RUNTIME_MESSAGE_TYPES.cancel){await this.handleCancel(r,t).catch(e=>this.observeDeliveryError(e));continue}const a=r.message.channel_id;if(this.workers.has(a))continue;const o=this.createWorker(r,t);o.completion=this.handleRequest(r,t,e,e=>{this.setWorkerCancel(o,e)}).catch(e=>this.observeDeliveryError(e)).finally(()=>{o.centralVerification?.complete(),this.workers.delete(a)}),this.workers.set(a,o)}}}finally{t&&clearInterval(t),await Promise.allSettled([...this.workers.values()].map(e=>e.completion))}}createWorker(e,t){const a={deliveryId:e.deliveryId,claimedLease:t,completion:Promise.resolve()};if(isCentralNativeResponse(e)){let e;a.centralVerification={ready:new Promise(t=>{e=t}),complete:()=>e()}}return a}observeDeliveryError(e){try{this.options.onDeliveryError?.(e)}catch{}}readFailureDelayMs(e){const t=this.options.idleDelayMs??500,a=e instanceof RuntimeMessageChannelProtocolError?e.status:void 0;return 401===a||403===a||this.readTransportFailurePolicy.recordFailure()?(this.readBackoffMs=Math.min(this.readBackoffMs?2*this.readBackoffMs:2*t,3e4),this.readBackoffMs):t}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):this.cancelWorker(a);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)&&this.cancelWorker(t)}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)&&this.cancelWorker(t)}}cancelWorker(e,t){e.cancelRequested||(e.cancelRequested=!0,e.cancelReason=t),e.cancel?.(e.cancelReason)}setWorkerCancel(e,t){const a=e.cancelRequested&&void 0===e.cancel;e.cancel=t,a&&t(e.cancelReason)}async handleCancel(e,t){const a=validateRuntimeCancelEnvelope(e.message);if(!a.ok)return void await this.handlePoison(e,`invalid_cancel:${a.reason}`,t);const r=a.envelope.payload,o=this.workers.get(r.operationId);if(o?.centralVerification){await o.centralVerification.ready;const a=o.central;if(!a)throw new Error("central cancellation original request was not verified");if(a.requestMessageId!==r.requestMessageId||a.requestHash!==r.requestHash||a.dispatchEpoch!==r.dispatchEpoch||a.method!==r.method||!sameLeaseBinding(o.claimedLease,t))throw new Error("central cancellation does not match its verified original execution");if(await this.journal.observeCancellation({operationId:r.operationId,requestMessageId:r.requestMessageId,requestHash:r.requestHash,eventId:r.eventId}),this.cancelWorker(o,nativePromptCancellationReason),await o.completion,"projection_committed"!==(await this.journal.get(r.operationId))?.phase)throw new Error("central cancellation terminal remains unknown");return void await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)})}const n=await this.channel.history({operationId:r.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 i=n.snapshot.request.payload;if(i.operationId!==r.operationId||i.requestMessageId!==r.requestMessageId||i.requestHash!==r.requestHash||i.dispatchEpoch!==r.dispatchEpoch||i.method!==r.method)return void await this.handlePoison(e,"cancel_history_mismatch",t);await this.journal.observeCancellation({operationId:r.operationId,requestMessageId:r.requestMessageId,requestHash:r.requestHash,eventId:r.eventId});const s=i,c=2===s.schemaVersion&&"session/prompt"===s.method,d=this.workers.get(r.operationId);d&&this.cancelWorker(d,c?nativePromptCancellationReason:void 0),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t})}async handleRequest(e,t,a,r){if(isCentralNativeResponse(e)){if(!this.options.centralPromptBridge)throw new Error("central native Response startup composition is unavailable");const o=new AbortController,n=()=>o.abort(a.reason);a.addEventListener("abort",n,{once:!0}),a.aborted&&n(),r(e=>o.abort(e));try{if(!(await this.options.centralPromptBridge.execute({delivery:e,lease:t,signal:o.signal,onVerified:e=>{const t=this.workers.get(e.operationId);t&&(t.central=e,t.centralVerification?.complete())}})).terminal)throw new Error("central native terminal receipt is unavailable");return void await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)})}finally{a.removeEventListener("abort",n)}}const o=e.message.payload;if(2===o.schemaVersion&&"session/prompt"===o.method&&this.options.nativePromptBridge){let o;try{o=await this.options.nativePromptBridge.execute({delivery:e,lease:t,signal:a,setCancel:r})}catch(a){if(!(a instanceof NativePromptExecutionFailure))throw a;a.failure instanceof RuntimeCommandError&&Object.prototype.hasOwnProperty.call(RUNTIME_ERROR_DESCRIPTORS,a.failure.code)&&a.failure.code;const r=await this.channel.append({operationId:a.request.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(a.request,a.failure,(new Date).toISOString())});return this.observeRequestTerminalAccepted(e.deliveryId,r.message),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),void this.observeRequestAcknowledged(e.deliveryId,r.message)}if(o.replayedFinal)return this.observeRequestTerminalAccepted(e.deliveryId,o.replayedFinal),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),void this.observeRequestAcknowledged(e.deliveryId,o.replayedFinal);if("succeeded"!==o.outcome){const a=await this.channel.append({operationId:o.request.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(o.request,new RuntimeCommandError("cancelled"===o.outcome?"OPERATION_CANCELLED":"EXECUTION_FAILED","native durable reply reports non-success"),(new Date).toISOString())});return this.observeRequestTerminalAccepted(e.deliveryId,a.message),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),void this.observeRequestAcknowledged(e.deliveryId,a.message)}const n=runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:o.request.method,result:o.result}),i={schemaVersion:1,operationId:o.request.operationId,method:o.request.method,coreResultRef:`sha256:${n}`,coreResultHash:n},s=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,i);await this.channel.append({operationId:o.request.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(o.request),effectRecord:i,effectRecordHash:s,committedAt:(new Date).toISOString()}});const c=await this.channel.append({operationId:o.request.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(o.request),outcome:o.outcome,response:{jsonrpc:"2.0",id:o.request.request.id,result:o.result},serviceResultHash:runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:o.request.method,result:o.result}),effectRecordHash:s,completedAt:(new Date).toISOString()}});return this.options.onRequestTerminalAccepted?.({deliveryId:e.deliveryId,message:c.message}),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),void this.options.onRequestAcknowledged?.({deliveryId:e.deliveryId,message:c.message})}const n=validateRuntimeRequestEnvelope(e.message);if(!n.ok)return void await this.handlePoison(e,`invalid_request:${n.reason}`,t);if(n.envelope.payload.schemaVersion!==(this.options.requestSchemaVersion??1))return void await this.handlePoison(e,"request_realm_mismatch",t);const i=n.envelope.payload,s=e.executionGrant,c=createRuntimeAppendTimingRecorder("runtime-op",{operationId:i.operationId,method:i.method}),d=new AbortController;r(()=>d.abort());const l=async()=>{await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),c.mark("ack")},u=await this.channel.history({operationId:i.operationId,lease:t});if(c.mark("history"),"not_found"===u.status||"expired"===u.status)return void await l();if(u.snapshot.terminal&&"final_message"===u.snapshot.terminalSource)return void await l();if(this.options.allowedMethods&&!this.options.allowedMethods.has(i.method))return await this.reject(i,"unsupported_method",t),void await l();if("deadline"===u.snapshot.terminalSource||Date.parse(i.executionDeadlineAt)<=Date.now()||!u.snapshot.started&&Date.parse(i.claimDeadlineAt)<=Date.now())return await this.reject(i,"execution_deadline_exceeded",t),void await l();const p=await this.journal.getCancellation(i.operationId);c.mark("journal-cancel-read");const h=u.snapshot.cancelRequested||null!==p;if(h&&"queued"===u.snapshot.status)return await this.reject(i,"cancelled_before_dispatch",t),void await l();if(i.instanceId!==t.instanceId||i.runtimeHandlerIdentity!==t.handlerIdentity||i.dispatchEpoch!==t.runtimeEpoch)return await this.reject(i,"authority_mismatch",t),void await l();const m=u.snapshot.request.payload;if(u.snapshot.operationId!==i.operationId||u.snapshot.requestMessageId!==i.requestMessageId||u.snapshot.requestHash!==i.requestHash||!semanticEqual(m,i))return void await this.handlePoison(e,"request_history_mismatch",t);const I=u.snapshot.started?.payload,v=void 0!==I&&I.operationId===i.operationId&&I.requestMessageId===i.requestMessageId&&I.requestHash===i.requestHash&&I.executionGrantHash===i.executionGrantHash&&I.handlerIdentity===t.handlerIdentity&&I.dispatchEpoch===t.runtimeEpoch&&I.method===i.method,E=await this.journal.get(i.operationId);c.mark("journal-prior");const f=runtimeCommandIsReplayableQuery(i.command.name),R=f?ephemeralQueryAccept(i):await this.journal.acceptMessageRequest({operationId:i.operationId,command:i.command.name,paramsHash:i.paramsHash,runtimeEpoch:i.dispatchEpoch,requestMessageId:i.requestMessageId,requestHash:i.requestHash});c.mark("journal-accept");const y=v?E:R,w=f?"execute":decideMessageServiceRecovery(u.snapshot,i,y,v);if("already_terminal"===w)return void await l();if(!CORE_RECOVERY_DECISIONS.has(w))return f||await this.markOutcomeUnknownIfMutable(R),await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(i,new RuntimeCommandError("OUTCOME_UNKNOWN",`Types recovery policy requires ${w}; this runtime cannot safely replay Core`),(new Date).toISOString())}),void await l();if(await this.verifier.refresh(),c.mark("verifier-refresh"),!s)return v?await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(i,new RuntimeCommandError("OUTCOME_UNKNOWN","retained started proof has no live execution grant"),(new Date).toISOString())}):await this.reject(i,"invalid_execution_grant",t),void await l();this.verifier.verifyAndDecodeGrant(s)||await this.verifier.refresh(!0);const g=()=>d.abort();let _;a.addEventListener("abort",g,{once:!0});try{_=await verifyAndCreateMessageServiceCoreExecutionAttempt({request:i,executionGrant:s,runtimeEpoch:t.runtimeEpoch,lease:t,verifier:this.verifier,allowExpiredGrant:v,abortSignal:d.signal,resolvePorts:async()=>await this.ports.resolve({request:i,executionGrant:s,command:i.command,getLease:()=>this.currentLease(t),...this.journalLineage(),journalRecord:R,abortSignal:d.signal})})}catch(e){if(a.removeEventListener("abort",g),d.abort(),!(e instanceof RuntimeResourceResolutionError))throw e;if(this.observeRequestFailure(i.operationId,i.method,e),"transient"===e.kind)return;return v?(f||await this.markOutcomeUnknownIfMutable(R),await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(i,new RuntimeCommandError("OUTCOME_UNKNOWN","eager resources cannot be reconstructed after retained started proof"),(new Date).toISOString())})):await this.reject(i,"integrity_mismatch"===e.kind?"resource_integrity_mismatch":"resource_resolution_rejected",t),void await l()}if(!_.ok)return a.removeEventListener("abort",g),d.abort(),this.observeRequestFailure(i.operationId,i.method,new Error(`execution grant rejected: ${_.violations.join(",")}`)),v?(f||await this.markOutcomeUnknownIfMutable(R),await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(i,new RuntimeCommandError("OUTCOME_UNKNOWN","execution grant cannot be revalidated after retained started proof"),(new Date).toISOString())})):await this.reject(i,"invalid_execution_grant",t),void await l();if(!h||"prepared"!==R.phase&&"started"!==R.phase||d.abort(),d.signal.aborted&&!v)return a.removeEventListener("abort",g),await this.reject(i,"cancelled_before_dispatch",t),void await l();c.mark("attempt"),v?this.currentLease(t):(await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),executionGrant:s,type:RUNTIME_MESSAGE_TYPES.started,payload:{...runtimeMessageBase(i),executionMode:"start",executionGrantHash:i.executionGrantHash,handlerIdentity:t.handlerIdentity,claimedAt:R.messageBinding?.acceptedAt??R.updatedAt}}),c.mark("append-started"));const M=this.dispatcher.dispatch(i.command,_.context);M.completion.catch(()=>{}),r(()=>{d.abort(),M.cancel()}),d.signal.aborted&&M.cancel();const S=this.forwardProgress(i,M.progress,t).catch(()=>{});let N,O=!1;try{if(("mcp/set"===i.method||"mcp/unset"===i.method)&&hasEffectReceiptHandoff(M)){const e=await M.effectCommitted;if(e){if(e.operationId!==i.operationId||e.method!==i.command.name)throw new RuntimeCommandError("OUTCOME_UNKNOWN","Core MCP receipt correlation mismatch");const a=runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:i.method,result:e.result}),r={schemaVersion:1,operationId:i.operationId,method:i.method,coreResultRef:`sha256:${a}`,coreResultHash:a};N=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,r),O=!0,await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(i),effectRecord:r,effectRecordHash:N,committedAt:e.committedAt}}),await M.acknowledgeEffectReceipt({operationId:i.operationId,method:i.command.name,effectRecordHash:N})}}const a=await M.completion;if(await S,c.mark("core"),f){const r=(new Date).toISOString();let o;try{o=sanitizeRuntimeServiceResult(i.method,a,_.context,void 0)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed Core result cannot be mapped safely",void 0,{cause:e})}const n=runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:i.method,result:o}),s=await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(i),outcome:"succeeded",response:{jsonrpc:"2.0",id:i.request.id,result:o},serviceResultHash:n,completedAt:r}});return c.mark("append-final"),this.observeRequestTerminalAccepted(e.deliveryId,s.message),await l(),void this.observeRequestAcknowledged(e.deliveryId,s.message)}const r=await this.journal.get(i.operationId);if(c.mark("journal-after-core"),!r||!isCommittedCorePhase(r.phase))throw new RuntimeCommandError("OUTCOME_UNKNOWN","Core completed without a committed local journal record");const o=r.updatedAt;let n,s;if("query"!==RUNTIME_INVOCATION_RECOVERY_CLASSES[i.method]){const e=isAgentProjectionMethod(i.method),s=M.getSnapshot().projection,d=r.agentProjectionIntent??r.agentProjectionPreparationFailure;if(e&&!d)throw new RuntimeCommandError("OUTCOME_UNKNOWN","agent effect committed without an atomic projection preparation record");if(!N&&"session/clear"!==i.method){const e=d?.coreResultHash??runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:i.method,result:a}),n=r.agentProjectionIntent?.projectionRevision??(methodRequiresProjectionRevision(i.method)?s?.revision??`${Math.max(0,r.revision)}`:void 0),l={schemaVersion:1,operationId:i.operationId,method:i.method,coreResultRef:`sha256:${e}`,coreResultHash:e,...n?{projectionRevision:n}:{}};N=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,l),O=!0,await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(i),effectRecord:l,effectRecordHash:N,committedAt:o}}),c.mark("append-effect")}let u=e?await awaitRuntimeProjection(M):s;if("session/set_model"===i.method&&"synced"!==u?.state&&(u=await this.projectSessionModelAfterEffect(i,_.context,r,u),c.mark("set-model-projection")),e&&r.agentProjectionIntent&&(!u||u.revision!==r.agentProjectionIntent.projectionRevision))throw new RuntimeCommandError("OUTCOME_UNKNOWN","agent projection receipt revision mismatch");if("pending"===u?.state)return void await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.projectionPending,payload:{...runtimeMessageBase(i),revision:u.revision}});if("synced"===u?.state&&await this.publishProjectionSynced(i,t,{...u,state:"synced"}),"blocked"===u?.state){await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.projectionBlocked,payload:{...runtimeMessageBase(i),revision:u.revision,errorCode:"PROJECTION_BLOCKED"}});const e=RUNTIME_ERROR_DESCRIPTORS.PROJECTION_BLOCKED;return await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(i),outcome:"projection_blocked",response:{jsonrpc:"2.0",id:i.request.id,error:{code:e.jsonRpcCode,message:"PROJECTION_BLOCKED",data:{code:"PROJECTION_BLOCKED",operationId:i.operationId,effectState:"committed",retryMode:e.retryMode}}},effectRecordHash:N,completedAt:o}}),void await l()}n=e?u?.platformAgentId:void 0}try{s=sanitizeRuntimeServiceResult(i.method,a,_.context,n)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed Core result cannot be mapped safely",void 0,{cause:e})}const d=runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:i.method,result:s});O=!0;const u=await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(i),outcome:"succeeded",response:{jsonrpc:"2.0",id:i.request.id,result:s},serviceResultHash:d,...N?{effectRecordHash:N}:{},completedAt:o}});if(c.mark("append-final"),this.observeRequestTerminalAccepted(e.deliveryId,u.message),("mcp/set"===i.method||"mcp/unset"===i.method)&&hasEffectReceiptHandoff(M)&&"function"==typeof M.acknowledgeTerminalReceipt){if(!N)throw new RuntimeCommandError("OUTCOME_UNKNOWN","MCP terminal response lacks its committed effect hash");await M.acknowledgeTerminalReceipt({operationId:i.operationId,method:i.command.name,effectRecordHash:N,terminalMessageId:u.message.message_id})}await l(),this.observeRequestAcknowledged(e.deliveryId,u.message)}catch(e){const a=await this.journal.get(i.operationId);if(a&&isCommittedCorePhase(a.phase)&&O)throw e;const r=!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(i.operationId,i.method,r);const o=failurePayload(i,r,a?.updatedAt??(new Date).toISOString());await this.channel.append({operationId:i.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:o}),c.mark("append-terminal-failure"),await l()}finally{c.finish(),d.abort(),a.removeEventListener("abort",g)}}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 r of t)await this.channel.append({operationId:e.operationId,lease:this.currentLease(a),type:RUNTIME_MESSAGE_TYPES.progress,payload:{...runtimeMessageBase(e),phase:r.phase,progress:r}})}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,r){const o=Object.freeze({state:"pending",revision:r?.revision??`${Math.max(0,a.revision)}`}),n=e.command;if("session.setModel"!==n.name||"conversation"!==n.context.scope)return o;const i=t.sessionModelProjection;if(!i)return o;try{await i.project({conversationId:n.context.conversation.runtimeConversationUid,modelOverrideId:n.params.modelOverrideId});const e=Object.freeze({state:"synced",revision:o.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),o}}async publishProjectionSynced(e,t,a){const r=this.currentLease(t),o=await this.channel.history({operationId:e.operationId,lease:r});if("found"===o.status&&"synced"===o.snapshot.projectionState)return;const n={...runtimeMessageBase(e),revision:a.revision};("found"!==o.status||"reserved"===o.snapshot.projectionState||"pending"!==o.snapshot.projectionState&&void 0===o.snapshot.projectionPending)&&await this.channel.append({operationId:e.operationId,lease:r,type:RUNTIME_MESSAGE_TYPES.projectionPending,payload:n}),await this.channel.append({operationId:e.operationId,lease:r,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,r){const o=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":r?"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:o?.recoveryClass??RUNTIME_INVOCATION_RECOVERY_CLASSES[t.method],projectionRequired:"mcp/set"===t.method||"mcp/unset"===t.method||(o?.projectionRequired??!1),messageServicePhase:n,executionBoundaryCrossed:r,lineageContinuity:s,journalState:a?"available":"unavailable",...i?{journalPhase:i}:{}})}export function sanitizeRuntimeServiceResult(e,t,a,r){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 o="cron/status"===e&&record(t)?{enabled:t.enabled,jobCount:t.jobCount,..."number"==typeof t.nextWakeAtMs?{nextWakeAtMs:t.nextWakeAtMs}:{}}:t;return mapCanonicalResultToService(e,o,{...r?{platformAgentId:r}:{},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 r=a.params.modelOverrideId;return{conversationId:a.context.conversation.runtimeConversationUid,...null===r?{defaultModelId:e.effectiveModelId}:{},modelOverrideId:r,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 r=t instanceof RuntimeCommandError?t.code:"RUNTIME_EXECUTION_FAILED",o=r in RUNTIME_ERROR_DESCRIPTORS?r:"RUNTIME_EXECUTION_FAILED",n="OUTCOME_UNKNOWN"===o||"INSTANCE_EPOCH_MISMATCH"===o?"outcome_unknown":"COMMAND_EXPIRED"===o?"expired":"OPERATION_CANCELLED"===o?"cancelled":"failed",i="outcome_unknown"===n?"OUTCOME_UNKNOWN":o,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",r=RUNTIME_ERROR_DESCRIPTORS[a in RUNTIME_ERROR_DESCRIPTORS?a:"RUNTIME_EXECUTION_FAILED"],o="COMMAND_EXPIRED"===a?"expired":"OPERATION_CANCELLED"===a?"cancelled":"failed";return{...runtimeMessageBase(e),outcome:o,response:{jsonrpc:"2.0",id:e.request.id,error:{code:r.jsonRpcCode,message:a,data:{code:a,operationId:e.operationId,effectState:o,retryMode:r.retryMode}}},completedAt:(new Date).toISOString()}}function abortable(e,t){return t?t.aborted?Promise.resolve():new Promise((a,r)=>{const o=()=>a();t.addEventListener("abort",o,{once:!0}),e.then(()=>{t.removeEventListener("abort",o),a()},e=>{t.removeEventListener("abort",o),r(e)})}):e}function delay(e,t){return new Promise(a=>{if(t?.aborted)return a();const r=()=>{clearTimeout(o),a()},o=setTimeout(()=>{t?.removeEventListener("abort",r),a()},e);t?.addEventListener("abort",r,{once:!0})})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CloudGatewayGrantJwksVerifier,GatewayGrantJwksVerifier}from"@beeos-ai/cloud-harness-sdk";import{MsRuntimeMessageChannelAdapter}from"./ms-runtime-message-channel-adapter.js";import{decodeRuntimeAppendMessage,decodeRuntimeBrokerDelivery,decodeRuntimeOperationHistory,decodeNativePromptOperationHistory,RuntimeMessageChannelProtocolError}from"./message-service-runtime-message-channel.js";import{isCanonicalSessionNewDelivery,SessionNewRuntimeDeliveryBridge}from"./session-new-runtime-delivery-bridge.js";import{NativeCloudPromptBridge}from"./native-cloud-prompt-bridge.js";export class MsRuntimeMessageChannelConsumerFactory{deps;constructor(e){if(this.deps=e,Boolean(e.client)===Boolean(e.runtimeDelivery))throw new Error("exactly one runtime delivery owner is required");if(e.runtimeDelivery&&!(e.verifier instanceof CloudGatewayGrantJwksVerifier))throw new Error("runtime delivery owner and grant realm differ")}async create(e){let t;const r=new SdkRuntimeMessageChannel(()=>{if(!t)throw new Error("SDK runtime delivery consumer is not attached");return t}),n=new MsRuntimeMessageChannelAdapter(e.dispatcher,r,this.deps.verifier,this.deps.ports,this.deps.journal,()=>e.getLease(),{...this.deps.options,allowedMethods:this.deps.allowedMethods,...this.deps.nativePrompt&&this.deps.verifier instanceof CloudGatewayGrantJwksVerifier?{nativePromptBridge:new NativeCloudPromptBridge({...this.deps.nativePrompt,verifier:this.deps.verifier,channel:r,journal:this.deps.journal,getLease:()=>e.getLease(),getLineage:()=>{const t=e.getBinding?.()??e.binding;return{journalStoreId:t.journalStoreId,journalGeneration:t.journalGeneration}}})}:{},journalStoreId:e.binding.journalStoreId,journalGeneration:e.binding.journalGeneration,...e.getBinding?{getJournalLineage:()=>{const t=e.getBinding();return{journalStoreId:t.journalStoreId,journalGeneration:t.journalGeneration}}}:{}}),
|
|
1
|
+
import{CloudGatewayGrantJwksVerifier,GatewayGrantJwksVerifier}from"@beeos-ai/cloud-harness-sdk";import{MsRuntimeMessageChannelAdapter}from"./ms-runtime-message-channel-adapter.js";import{decodeRuntimeAppendMessage,decodeRuntimeBrokerDelivery,decodeRuntimeOperationHistory,decodeNativePromptOperationHistory,RuntimeMessageChannelProtocolError}from"./message-service-runtime-message-channel.js";import{isCanonicalSessionNewDelivery,SessionNewRuntimeDeliveryBridge}from"./session-new-runtime-delivery-bridge.js";import{NativeCloudPromptBridge}from"./native-cloud-prompt-bridge.js";import{CentralNativeResponse,isCentralNativeResponse}from"./central-native-response.js";export class MsRuntimeMessageChannelConsumerFactory{deps;constructor(e){if(this.deps=e,Boolean(e.client)===Boolean(e.runtimeDelivery))throw new Error("exactly one runtime delivery owner is required");if(e.runtimeDelivery&&!(e.verifier instanceof CloudGatewayGrantJwksVerifier))throw new Error("runtime delivery owner and grant realm differ")}async create(e){let t;const r=new SdkRuntimeMessageChannel(()=>{if(!t)throw new Error("SDK runtime delivery consumer is not attached");return t}),n=this.deps.centralPrompt&&this.deps.verifier instanceof CloudGatewayGrantJwksVerifier?new CentralNativeResponse({...this.deps.centralPrompt,verifier:this.deps.verifier,journal:this.deps.journal,getLease:()=>e.getLease()}):void 0,i=new MsRuntimeMessageChannelAdapter(e.dispatcher,r,this.deps.verifier,this.deps.ports,this.deps.journal,()=>e.getLease(),{...this.deps.options,allowedMethods:this.deps.allowedMethods,...n?{centralPromptBridge:n}:{},...this.deps.nativePrompt&&this.deps.verifier instanceof CloudGatewayGrantJwksVerifier?{nativePromptBridge:new NativeCloudPromptBridge({...this.deps.nativePrompt,verifier:this.deps.verifier,channel:r,journal:this.deps.journal,getLease:()=>e.getLease(),getLineage:()=>{const t=e.getBinding?.()??e.binding;return{journalStoreId:t.journalStoreId,journalGeneration:t.journalGeneration}}})}:{},journalStoreId:e.binding.journalStoreId,journalGeneration:e.binding.journalGeneration,...e.getBinding?{getJournalLineage:()=>{const t=e.getBinding();return{journalStoreId:t.journalStoreId,journalGeneration:t.journalGeneration}}}:{}}),s=this.deps.client&&this.deps.verifier instanceof GatewayGrantJwksVerifier?legacySessionNewConversationCreator(this.deps.client):this.deps.runtimeDelivery&&this.deps.verifier instanceof CloudGatewayGrantJwksVerifier?this.deps.sessionNewConversation:void 0,o=s?new SessionNewRuntimeDeliveryBridge({conversations:s,consumer:()=>{if(!t)throw new Error("SDK runtime delivery consumer is not attached");return t},verifier:this.deps.verifier,getLease:()=>e.getLease(),createRuntimeSession:e.createRuntimeSession,poison:async(e,t,r)=>{await i.acceptPoisonDelivery(e,t,r)}}):void 0,a=this.deps.client?.methods??this.deps.runtimeDelivery;if(!a)throw new Error("runtime delivery owner is unavailable");return t=a.consume({onDelivery:async(t,r)=>{runtimeDeliveryTrace(t);let s="fence";try{const a=currentFencedLease(e,r.lease);s="decode";if(isCentralNativeResponse(t)&&!n)throw new Error("central native Response startup composition is unavailable");const d=t,l=this.deps.nativePrompt&&2===d.message?.payload?.schemaVersion&&"session/prompt"===d.message.payload.method?t:decodeRuntimeBrokerDelivery(t);if(s="dispatch",isCanonicalSessionNewDelivery(l))return o?void await o.acceptDelivery(l,a,r.signal):void await i.acceptPoisonDelivery(l,"cloud_session_new_unsupported",a);await i.acceptDelivery(l,a,r.signal)}catch(e){runtimeDeliveryError(e);throw e}},onError:this.deps.options.onDeliveryError,readCount:this.deps.options.readCount,blockMs:this.deps.options.blockMs,idleDelayMs:this.deps.options.idleDelayMs,renewIntervalMs:this.deps.options.renewIntervalMs}),i.attachExternalDeliveryOwner(t),i}}export class SdkRuntimeMessageChannel{consumer;constructor(e){this.consumer=e}async read(){throw new Error("MessageClient owns runtime delivery reads")}async renew(){throw new Error("MessageClient owns runtime delivery renewal")}async acknowledge(e){assertLeaseAvailable(e.lease),await this.consumer().acknowledge(e.deliveryIds)}async history(e){assertLeaseAvailable(e.lease);const t=await this.consumer().history(e.operationId);return"found"!==t.status?t:{status:"found",snapshot:this.decodeHistory(t.snapshot,e)}}async append(e){assertLeaseAvailable(e.lease);const t=await this.consumer().append(e.operationId,e.type,e.payload,e.executionGrant);if("created"===t.outcome||"duplicate"===t.outcome)return{disposition:"created"===t.outcome?"created":"reused",message:decodeRuntimeAppendMessage(t.message,e)};if(t.history){const r=findReconciledMessage(this.decodeHistory(t.history,e),e);if(r)return{disposition:"reused",message:r}}throw new RuntimeMessageChannelProtocolError("runtime append outcome is unknown after history reconcile",503,"OUTCOME_UNKNOWN")}decodeHistory(e,t){if(!t.currentNativePrompt)return decodeRuntimeOperationHistory(e,t.operationId);if(t.currentNativePrompt.request.operationId!==t.operationId)throw new RuntimeMessageChannelProtocolError("native history operation does not match current proof");return decodeNativePromptOperationHistory(e,t.currentNativePrompt)}}function currentFencedLease(e,t){const r=e.getLease(),n=e.getBinding?.()??e.binding;if(!r||r.instanceId!==t.instanceId||r.handlerIdentity!==t.handlerIdentity||r.runtimeEpoch!==t.runtimeEpoch||r.leaseId!==t.leaseId||n.journalStoreId!==t.journalStoreId||n.journalGeneration!==t.journalGeneration)throw new Error("runtime delivery lease fence changed");if(Date.parse(r.leaseExpiresAt)<=Date.now())throw new Error("runtime delivery lease expired");return r}function assertLeaseAvailable(e){if(!Number.isFinite(Date.parse(e.leaseExpiresAt))||Date.parse(e.leaseExpiresAt)<=Date.now())throw new Error("runtime delivery lease expired")}function legacySessionNewConversationCreator(e){return{async create(t){const r=t.platformAgentId.startsWith("agent:")?t.platformAgentId:`agent:${t.platformAgentId}`;return{conversationId:(await e.conversations.create({agentId:t.platformAgentId,participants:dedupe([t.runtimeInstanceId,r,t.callerIdentityId??""]),...t.title?{title:t.title}:{},metadata:{source:"session/new",runtimeSessionId:t.runtimeSessionId,runtimeSessionKey:t.runtimeSessionKey,runtimeInstanceId:t.runtimeInstanceId,runtimeEpoch:t.runtimeEpoch,platformAgentId:t.platformAgentId},idempotencyKey:t.operationId})).id}}}}function dedupe(e){return[...new Set(e.filter(e=>e.length>0))]}function safeRuntimeDeliveryId(e){return"string"==typeof e&&e.length>0&&e.length<=256&&!/[\u0000-\u001f\u007f]/.test(e)?JSON.stringify(e):JSON.stringify("unavailable")}function safeRuntimeDeliveryCode(e){return"string"==typeof e&&/^[A-Za-z0-9_.:-]{1,64}$/.test(e)?e:"unavailable"}function runtimeDeliveryTrace(e){const t=null!==e&&"object"==typeof e?e:{};return{channelId:safeRuntimeDeliveryId((null!==t.message&&"object"==typeof t.message?t.message:{}).channel_id),deliveryId:safeRuntimeDeliveryId(t.deliveryId)}}function runtimeDeliveryError(e){const t=null!==e&&"object"==typeof e?e:{};return{code:safeRuntimeDeliveryCode(t.code),status:"number"==typeof t.status&&Number.isInteger(t.status)&&t.status>=100&&t.status<=599?String(t.status):"unavailable"}}function findReconciledMessage(e,t){for(let r=e.messages.length-1;r>=0;r-=1)try{return decodeRuntimeAppendMessage(e.messages[r],t)}catch{}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{HtmlDeliveryGuard}from"../canvas/html-delivery.js";import{createNativeOutputFileAttempt}from"./native-output-file-attempt.js";import{downloadNativeInputFile}from"./native-input-files.js";import{bindExistingRuntimeChatReply}from"@beeos-ai/cloud-harness-sdk";import{RUNTIME_HASH_DOMAINS}from"@beeos-ai/beeos-types/runtime";import{dispatchImInboundPrompt}from"../im-runtime-dispatch.js";import{prepareNativePromptInput}from"./native-prompt-preflight.js";import{verifyNativePromptAuthority}from"./native-prompt-authority.js";import{RuntimeCommandError}from"./runtime-command-dispatcher.js";import{runtimeCommandResultHash}from"./runtime-command-journal.js";import{runtimeMessageBase,runtimeMessageHash,semanticEqual}from"./runtime-message-channel-contract.js";import{openClawSessionModePatch}from"./runtime-session-control-service.js";export const nativePromptCancellationReason="chat_cancel:runtime_operation_cancel_requested";export const nativePromptExecutionDeadlineReason="deadline exceeded: the Cloud turn execution budget is about to expire";const nativePromptWrapUpMarginMs=3e4;export class NativeCloudPromptBridge{options;constructor(e){if(this.options=e,"function"!=typeof e.host.resolveNativePromptSessionKey)throw new RuntimeCommandError("INVALID_PARAMS","native Core target resolver required");if("function"!=typeof e.host.prepareNativePromptModel)throw new RuntimeCommandError("INVALID_PARAMS","native Core model preparation required");if(!e.runBoundary)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native MS run boundary required")}async execute(e){const{options:t}=this;if(await t.verifier.refresh(),!e.delivery.executionGrant)throw new RuntimeCommandError("INVALID_PARAMS","native grant missing");const a=e.delivery.message.payload,n="string"==typeof a.operationId?await t.journal.get(a.operationId):null,i=!!n&&"session.prompt"===n.command&&["started","effect_committed","projection_committed","failed"].includes(n.phase)&&n.paramsHash===a.paramsHash&&n.messageBinding?.requestMessageId===a.requestMessageId&&n.messageBinding?.requestHash===a.requestHash,r=verifyNativePromptAuthority({request:e.delivery.message.payload,decoded:t.verifier.verifyAndDecodeGrant(e.delivery.executionGrant),lease:e.lease,lineage:t.getLineage(),allowExpiredReadOnly:i}),{params:o}=r,s=r.request;try{const a=e.delivery.message;if("runtime_rpc_request"!==a.type||"completed"!==a.state||a.message_id!==s.requestMessageId||a.channel_id!==s.operationId||void 0!==a.in_reply_to)throw new RuntimeCommandError("INVALID_PARAMS","native envelope binding invalid");let n;void 0!==o.mode&&openClawSessionModePatch(o.mode);try{if(void 0!==o.mentions)throw new TypeError("native host per-prompt optional binding not implemented");n=prepareNativePromptInput(o.parts)}catch(e){throw new RuntimeCommandError(i?"OUTCOME_UNKNOWN":"INVALID_PARAMS","native host part unsupported",void 0,{cause:e})}const d=n.message;if(!t.host.activeRunAuthority)throw new RuntimeCommandError("EXECUTION_FAILED","native existing active-run authority unavailable");const m=()=>{const a=t.getLease(),n=t.getLineage();if(!a||a.instanceId!==e.lease.instanceId||a.handlerIdentity!==e.lease.handlerIdentity||a.runtimeEpoch!==o.runtimeLease.runtimeEpoch||a.leaseId!==o.runtimeLease.leaseId||n.journalStoreId!==o.runtimeLease.journalStoreId||n.journalGeneration!==o.runtimeLease.journalGeneration||Date.parse(a.leaseExpiresAt)<=Date.now())throw new RuntimeCommandError("INSTANCE_EPOCH_MISMATCH","native prompt attempt fenced")};m();const l=await t.channel.history({operationId:s.operationId,lease:e.lease,currentNativePrompt:r});if(m(),"found"!==l.status||l.snapshot.requestHash!==s.requestHash||l.snapshot.requestMessageId!==s.requestMessageId||!semanticEqual(l.snapshot.request.payload,s))throw new RuntimeCommandError("INVALID_PARAMS","native retained request mismatch");let u,p=await t.journal.get(s.operationId);if(m(),p&&("session.prompt"!==p.command||p.paramsHash!==s.paramsHash||p.runtimeEpoch!==o.runtimeLease.runtimeEpoch||p.messageBinding?.requestMessageId!==s.requestMessageId||p.messageBinding.requestHash!==s.requestHash))throw new RuntimeCommandError("OUTCOME_UNKNOWN","native existing journal binding mismatch");if(!t.http.getMessage)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native task snapshot unavailable");try{u=await t.http.getMessage(t.getLease(),{conversationId:o.conversationId,messageId:o.taskRequestMessageId})}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original task snapshot unavailable",void 0,{cause:e})}if(m(),u.messageId!==o.taskRequestMessageId||u.conversationId!==o.conversationId||"chat_message"!==u.type||u.body!==d)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original task snapshot mismatch");const c=async()=>{if(!t.http.getMessage)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native single snapshot unavailable");m();const e=await t.http.getMessage(t.getLease(),{conversationId:o.conversationId,messageId:o.replyMessageId});return m(),this.assertReply(e,r),e};if(l.snapshot.started||p&&"prepared"!==p.phase){const e=l.snapshot.runBoundary?.finishedReceipt,a=l.snapshot.final;if(!(p&&["started","effect_committed","projection_committed","failed"].includes(p.phase)&&e&&"finished"===e.state&&e.activeRunRegistrationId===o.taskId&&a))throw new RuntimeCommandError("OUTCOME_UNKNOWN","native durable MS finish audit or original result unavailable");const n=await c();if("agent_reply"!==n.type||n.state!==e.replyState||n.stopReason!==e.replyStopReason||n.updatedAt!==e.replyUpdatedAt)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original terminal does not match finished audit");const i=this.terminal(n,r);if(a.payload.outcome!==i.outcome||"final_message"!==l.snapshot.terminalSource)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original final outcome mismatch");const d=a.payload.response;if("2.0"!==d.jsonrpc||d.id!==s.request.id)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original final RPC binding mismatch");const u=runtimeCommandResultHash(i.result);if(p.resultReceipt&&p.resultReceipt.resultHash!==u||void 0!==p.result&&!semanticEqual(p.result,i.result))throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original result conflicts with local receipt");if(void 0===d.result)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original canonical result evidence unavailable");{const e=l.snapshot.effectCommitted?.payload,t=runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:s.method,result:d.result});if("succeeded"!==i.outcome||void 0!==d.error||!semanticEqual(d.result,i.result)||!e||e.effectRecord.coreResultHash!==t||e.effectRecord.coreResultRef!==`sha256:${t}`||a.payload.effectRecordHash!==e.effectRecordHash||a.payload.serviceResultHash!==runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:s.method,result:d.result}))throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original final result hash evidence mismatch")}const h=d.result;return m(),"started"===p.phase&&(p=await t.journal.transition({operationId:s.operationId,expectedRevision:p.revision,phase:"succeeded"===i.outcome?"effect_committed":"failed",result:h}),m()),{request:s,outcome:i.outcome,result:h,replayedFinal:a}}if(n.files.length&&!t.inputFiles)throw new RuntimeCommandError("EXECUTION_FAILED","native authorized input file resolver unavailable");if(l.snapshot.terminal||e.signal.aborted||l.snapshot.cancelRequested||await t.journal.getCancellation(s.operationId))throw new RuntimeCommandError("OPERATION_CANCELLED","native prompt cancelled before effect");const h=await t.host.resolveNativePromptSessionKey(r,m);if(m(),p=await t.journal.acceptMessageRequest({operationId:s.operationId,command:"session.prompt",paramsHash:s.paramsHash,runtimeEpoch:o.runtimeLease.runtimeEpoch,requestMessageId:s.requestMessageId,requestHash:s.requestHash}),m(),"prepared"!==p.phase)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native task already started");let v;const g=await bindExistingRuntimeChatReply({authority:{currentLease:t.getLease},http:t.http,binding:{conversationId:o.conversationId,messageId:o.replyMessageId,taskRequestMessageId:o.taskRequestMessageId,assertAttempt:m,assertPreparedClear:e=>{if(m(),!v||e.activeRunRegistrationId!==v||e.historyGeneration!==r.historyGeneration||e.runtimeEpoch!==o.runtimeLease.runtimeEpoch)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native prepared clear does not freeze this registered attempt")},mutationKey:e=>`native-reply:${s.operationId}:${o.runtimeLease.journalStoreId}:${o.runtimeLease.journalGeneration}:${e}`}});if(m(),e.signal.aborted||await t.journal.getCancellation(s.operationId))throw new RuntimeCommandError("OPERATION_CANCELLED","native prompt cancelled before start");await t.channel.append({operationId:s.operationId,lease:t.getLease(),currentNativePrompt:r,executionGrant:e.delivery.executionGrant,type:"runtime_operation_started",payload:{...runtimeMessageBase(s),executionGrantHash:s.executionGrantHash,handlerIdentity:e.lease.handlerIdentity,executionMode:"start",claimedAt:p.updatedAt}}),m(),p=await t.journal.transition({operationId:s.operationId,expectedRevision:p.revision,phase:"started"}),m();const I=()=>{m();const e=t.getLease();return{leaseId:e.leaseId,handlerIdentity:e.handlerIdentity,runtimeEpoch:e.runtimeEpoch,runtimeLeaseCredential:e.runtimeLeaseCredential}},f={operationId:s.operationId,requestMessageId:s.requestMessageId,conversationId:r.command.context.conversation.runtimeConversationUid,historyGeneration:r.historyGeneration,runtimeRunId:o.runtimeRunId},R=await t.runBoundary.start({...f,lease:I()});if(m(),"registered"!==R.status||R.historyGeneration!==r.historyGeneration||R.activeRunRegistrationId!==o.taskId)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native MS run start did not register the original task");v=R.activeRunRegistrationId;const N=new AbortController,w=()=>N.abort(e.signal.reason);if(e.signal.addEventListener("abort",w,{once:!0}),e.signal.aborted&&w(),e.setCancel(e=>N.abort(e)),await t.journal.getCancellation(s.operationId)&&N.abort(nativePromptCancellationReason),m(),N.signal.aborted){if(e.signal.removeEventListener("abort",w),N.signal.reason===nativePromptCancellationReason)throw new RuntimeCommandError("OPERATION_CANCELLED","native prompt cancelled before host invocation");throw new RuntimeCommandError("OUTCOME_UNKNOWN","native registered run stopped before host invocation")}const y=[];let E;const C=JSON.parse((await g.opened()).rawText),O=C.parts?.length??0,M=async e=>{const t=await e;return m(),this.assertReply(t,r),E=t,t},_={id:g.id,get isTerminated(){return g.isTerminated},get parts(){return y},opened:async()=>({messageId:g.id,outcome:"bound"}),appendBody:e=>g.appendBody(e),setBody:e=>g.setBody(e),addPart:e=>{y.push(e),g.addPart(e)},replacePart:(e,t)=>{y[e]=t,g.replacePart(O+e,t)},appendToolResult:(e,t,a)=>{const n={type:"tool_result",tool_use_id:e,content:t,...a?{is_error:!0}:{}};y.push(n),g.addPart(n)},finalize:e=>M(g.finalize(e)),fail:e=>M(g.fail(e)),cancel:e=>M(g.cancel(e))},b={message:d,mediaPaths:[],mediaTypes:[]};let U,A;const q=t.host.htmlDeliveryRequired?new HtmlDeliveryGuard:void 0,T=createNativeOutputFileAttempt({htmlDelivery:q,operationId:s.operationId,requestMessageId:s.requestMessageId,paramsHash:s.paramsHash,activeRunRegistrationId:v,getLease:()=>(m(),t.getLease()),assertAttempt:m,signal:N.signal}),P=setTimeout(()=>N.abort(nativePromptExecutionDeadlineReason),Math.max(0,Math.min(Date.parse(s.executionDeadlineAt)-3e4-Date.now(),2147483647)));P.unref?.();try{await dispatchImInboundPrompt({...t.host,htmlDelivery:q,runtimeRunId:o.runtimeRunId,onNativeAgentRunStart:e=>T.bindHostRun(e),nativeActiveRunRegistration:{runtimeConversationUid:f.conversationId,runtimeSessionKey:r.command.context.conversation.runtimeSessionKey,historyGeneration:R.historyGeneration,targetMessageId:o.taskRequestMessageId,runtimeRunId:o.runtimeRunId,activeRunRegistrationId:R.activeRunRegistrationId},assertNativeTarget:async()=>{if(await t.host.resolveNativePromptSessionKey(r,m)!==h)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native prompt target changed before host invocation")},prepareNativeModel:async e=>{m(),await t.host.prepareNativePromptModel(r,e,m),m();for(const e of n.files){if(!t.inputFiles)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native authorized input file resolver unavailable");const a=await t.inputFiles.resolve({operationId:s.operationId,requestMessageId:s.requestMessageId,paramsHash:s.paramsHash,partIndex:e.partIndex,lease:t.getLease(),signal:N.signal});m();const n=await downloadNativeInputFile({fileId:e.fileId,...a,signal:N.signal,assertAttempt:m});b.mediaPaths.push(n.path),b.mediaTypes.push(n.mimeType)}m()},onNativeRunCompletion:e=>{A=e},retainedStream:_,abortSignal:N.signal,inReplyTo:o.taskRequestMessageId,prompt:{channelId:o.conversationId,inboundMessageId:o.taskRequestMessageId,requestId:s.requestMessageId,selfPrincipalId:e.lease.instanceId,sessionKey:h,dispatchInput:b},client:{messages:{startStream(){throw new Error("native reply POST forbidden")},getEnvelope:async()=>({state:(await c()).state})},getSnapshot:()=>({connection:"connected",messages:{},conversations:{}})}})}catch(e){U=e}finally{clearTimeout(P),T.close(),e.signal.removeEventListener("abort",w)}if(!A&&U)throw U;if(!A||A.runtimeRunId!==o.runtimeRunId||A.token.sessionKey!==h)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native physical host completion unavailable");let S;try{await A.completion}catch(e){S=e}if(m(),!E)throw new RuntimeCommandError("OUTCOME_UNKNOWN",void 0!==S?"native host/abort/drain did not converge":"native kernel settled without verified original reply terminal",void 0,{cause:S??U});const H=this.terminal(E,r),L=await c();g.assertTerminalSnapshot(L);const x="completed"===L.state?"completed":"cancelled"===L.state?"cancelled":"failed",K=await t.runBoundary.finish({...f,activeRunRegistrationId:v,terminalState:x,source:"runtime",lease:I()});if(m(),"finished"!==K.status&&"idempotent"!==K.status||K.activeRunRegistrationId!==v)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native MS run finish was not acknowledged");return await t.journal.transition({operationId:s.operationId,expectedRevision:p.revision,phase:"succeeded"===H.outcome?"effect_committed":"failed",result:H.result}),m(),{request:s,...H}}catch(e){throw new NativePromptExecutionFailure(s,e)}}assertReply(e,t){if(e.messageId!==t.params.replyMessageId||e.conversationId!==t.params.conversationId||e.replyTo!==t.params.taskRequestMessageId)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native durable reply binding mismatch")}terminal(e,t){if(!e.stopReason||!["completed","failed","refused","cancelled"].includes(e.state))throw new RuntimeCommandError("OUTCOME_UNKNOWN","native durable terminal absent");const a="cancelled"===e.state&&"user_stop"===e.stopReason?"cancelled":"completed"===e.state&&"end_turn"===e.stopReason?"succeeded":"failed";return{outcome:a,result:{runtimeRunId:t.params.runtimeRunId,stopReason:e.stopReason,requestAborted:"cancelled"===e.state&&"user_stop"===e.stopReason,..."failed"===a?{error:e.body}:{}}}}}export const NATIVE_PROMPT_UNKNOWN_REASONS=new Set(["native MS run boundary required","native existing journal binding mismatch","native task snapshot unavailable","native original task snapshot unavailable","native original task snapshot mismatch","native single snapshot unavailable","native durable MS finish audit or original result unavailable","native original terminal does not match finished audit","native original final outcome mismatch","native original final RPC binding mismatch","native original result conflicts with local receipt","native original final result hash evidence mismatch","native original canonical result evidence unavailable","native task already started","native prepared clear does not freeze this registered attempt","native MS run start did not register the original task","native registered run stopped before host invocation","native prompt target changed before host invocation","native authorized input file resolver unavailable","native physical host completion unavailable","native host/abort/drain did not converge","native kernel settled without verified original reply terminal","native MS run finish was not acknowledged","native durable reply binding mismatch","native durable terminal absent"]);export function nativePromptUnknownReason(e){return e instanceof RuntimeCommandError&&"OUTCOME_UNKNOWN"===e.code?NATIVE_PROMPT_UNKNOWN_REASONS.has(e.message)?e.message:"unlisted":"not_unknown"}export class NativePromptExecutionFailure extends Error{request;failure;constructor(e,t){super(t instanceof Error?t.message:String(t),{cause:t}),this.request=e,this.failure=t}}
|
|
1
|
+
import{HtmlDeliveryGuard}from"../canvas/html-delivery.js";import{createNativeOutputFileAttempt}from"./native-output-file-attempt.js";import{downloadNativeInputFile}from"./native-input-files.js";import{bindExistingRuntimeChatReply}from"@beeos-ai/cloud-harness-sdk";import{RUNTIME_HASH_DOMAINS}from"@beeos-ai/beeos-types/runtime";import{dispatchImInboundPrompt}from"../im-runtime-dispatch.js";import{prepareNativePromptInput}from"./native-prompt-preflight.js";import{verifyNativePromptAuthority}from"./native-prompt-authority.js";import{RuntimeCommandError}from"./runtime-command-dispatcher.js";import{runtimeCommandResultHash}from"./runtime-command-journal.js";import{runtimeMessageBase,runtimeMessageHash,semanticEqual}from"./runtime-message-channel-contract.js";import{openClawSessionModePatch}from"./runtime-session-control-service.js";export const nativePromptCancellationReason="chat_cancel:runtime_operation_cancel_requested";export const nativePromptExecutionDeadlineReason="deadline exceeded: the Cloud turn execution budget is about to expire";const nativePromptWrapUpMarginMs=3e4;export class NativeCloudPromptBridge{options;constructor(e){if(this.options=e,"function"!=typeof e.host.resolveNativePromptSessionKey)throw new RuntimeCommandError("INVALID_PARAMS","native Core target resolver required");if("function"!=typeof e.host.prepareNativePromptModel)throw new RuntimeCommandError("INVALID_PARAMS","native Core model preparation required");if(!e.runBoundary)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native MS run boundary required")}async execute(e){const{options:t}=this;if(await t.verifier.refresh(),!e.delivery.executionGrant)throw new RuntimeCommandError("INVALID_PARAMS","native grant missing");const a=e.delivery.message.payload,n="string"==typeof a.operationId?await t.journal.get(a.operationId):null,i=!!n&&"session.prompt"===n.command&&["started","effect_committed","projection_committed","failed"].includes(n.phase)&&n.paramsHash===a.paramsHash&&n.messageBinding?.requestMessageId===a.requestMessageId&&n.messageBinding?.requestHash===a.requestHash,r=verifyNativePromptAuthority({request:e.delivery.message.payload,decoded:t.verifier.verifyAndDecodeGrant(e.delivery.executionGrant),lease:e.lease,lineage:t.getLineage(),allowExpiredReadOnly:i}),{params:o}=r,s=r.request;try{const a=e.delivery.message;if("runtime_rpc_request"!==a.type||"completed"!==a.state||a.message_id!==s.requestMessageId||a.channel_id!==s.operationId||void 0!==a.in_reply_to)throw new RuntimeCommandError("INVALID_PARAMS","native envelope binding invalid");let n;void 0!==o.mode&&openClawSessionModePatch(o.mode);try{if(void 0!==o.mentions)throw new TypeError("native host per-prompt optional binding not implemented");n=prepareNativePromptInput(o.parts)}catch(e){throw new RuntimeCommandError(i?"OUTCOME_UNKNOWN":"INVALID_PARAMS","native host part unsupported",void 0,{cause:e})}const d=n.message;if(!t.host.activeRunAuthority)throw new RuntimeCommandError("EXECUTION_FAILED","native existing active-run authority unavailable");const m=()=>{const a=t.getLease(),n=t.getLineage();if(!a||a.instanceId!==e.lease.instanceId||a.handlerIdentity!==e.lease.handlerIdentity||a.runtimeEpoch!==o.runtimeLease.runtimeEpoch||a.leaseId!==o.runtimeLease.leaseId||n.journalStoreId!==o.runtimeLease.journalStoreId||n.journalGeneration!==o.runtimeLease.journalGeneration||Date.parse(a.leaseExpiresAt)<=Date.now())throw new RuntimeCommandError("INSTANCE_EPOCH_MISMATCH","native prompt attempt fenced")};m();const l=await t.channel.history({operationId:s.operationId,lease:e.lease,currentNativePrompt:r});if(m(),"found"!==l.status||l.snapshot.requestHash!==s.requestHash||l.snapshot.requestMessageId!==s.requestMessageId||!semanticEqual(l.snapshot.request.payload,s))throw new RuntimeCommandError("INVALID_PARAMS","native retained request mismatch");let u,p=await t.journal.get(s.operationId);if(m(),p&&("session.prompt"!==p.command||p.paramsHash!==s.paramsHash||p.runtimeEpoch!==o.runtimeLease.runtimeEpoch||p.messageBinding?.requestMessageId!==s.requestMessageId||p.messageBinding.requestHash!==s.requestHash))throw new RuntimeCommandError("OUTCOME_UNKNOWN","native existing journal binding mismatch");if(!t.http.getMessage)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native task snapshot unavailable");try{u=await t.http.getMessage(t.getLease(),{conversationId:o.conversationId,messageId:o.taskRequestMessageId})}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original task snapshot unavailable",void 0,{cause:e})}if(m(),u.messageId!==o.taskRequestMessageId||u.conversationId!==o.conversationId||"chat_message"!==u.type||u.body!==d)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original task snapshot mismatch");const c=async()=>{if(!t.http.getMessage)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native single snapshot unavailable");m();const e=await t.http.getMessage(t.getLease(),{conversationId:o.conversationId,messageId:o.replyMessageId});return m(),this.assertReply(e,r),e};if(l.snapshot.started||p&&"prepared"!==p.phase){const e=l.snapshot.runBoundary?.finishedReceipt,a=l.snapshot.final;if(!(p&&["started","effect_committed","projection_committed","failed"].includes(p.phase)&&e&&"finished"===e.state&&e.activeRunRegistrationId===o.taskId&&a))throw new RuntimeCommandError("OUTCOME_UNKNOWN","native durable MS finish audit or original result unavailable");const n=await c();if("agent_reply"!==n.type||n.state!==e.replyState||n.stopReason!==e.replyStopReason||n.updatedAt!==e.replyUpdatedAt)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original terminal does not match finished audit");const i=this.terminal(n,r);if(a.payload.outcome!==i.outcome||"final_message"!==l.snapshot.terminalSource)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original final outcome mismatch");const d=a.payload.response;if("2.0"!==d.jsonrpc||d.id!==s.request.id)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original final RPC binding mismatch");const u=runtimeCommandResultHash(i.result);if(p.resultReceipt&&p.resultReceipt.resultHash!==u||void 0!==p.result&&!semanticEqual(p.result,i.result))throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original result conflicts with local receipt");if(void 0===d.result)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original canonical result evidence unavailable");{const e=l.snapshot.effectCommitted?.payload,t=runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:s.method,result:d.result});if("succeeded"!==i.outcome||void 0!==d.error||!semanticEqual(d.result,i.result)||!e||e.effectRecord.coreResultHash!==t||e.effectRecord.coreResultRef!==`sha256:${t}`||a.payload.effectRecordHash!==e.effectRecordHash||a.payload.serviceResultHash!==runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:s.method,result:d.result}))throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original final result hash evidence mismatch")}const h=d.result;return m(),"started"===p.phase&&(p=await t.journal.transition({operationId:s.operationId,expectedRevision:p.revision,phase:"succeeded"===i.outcome?"effect_committed":"failed",result:h}),m()),{request:s,outcome:i.outcome,result:h,replayedFinal:a}}if(n.files.length&&!t.inputFiles)throw new RuntimeCommandError("EXECUTION_FAILED","native authorized input file resolver unavailable");if(l.snapshot.terminal||e.signal.aborted||l.snapshot.cancelRequested||await t.journal.getCancellation(s.operationId))throw new RuntimeCommandError("OPERATION_CANCELLED","native prompt cancelled before effect");const h=await t.host.resolveNativePromptSessionKey(r,m);if(m(),p=await t.journal.acceptMessageRequest({operationId:s.operationId,command:"session.prompt",paramsHash:s.paramsHash,runtimeEpoch:o.runtimeLease.runtimeEpoch,requestMessageId:s.requestMessageId,requestHash:s.requestHash}),m(),"prepared"!==p.phase)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native task already started");let v;const g=await bindExistingRuntimeChatReply({authority:{currentLease:t.getLease},http:t.http,binding:{conversationId:o.conversationId,messageId:o.replyMessageId,taskRequestMessageId:o.taskRequestMessageId,assertAttempt:m,assertPreparedClear:e=>{if(m(),!v||e.activeRunRegistrationId!==v||e.historyGeneration!==r.historyGeneration||e.runtimeEpoch!==o.runtimeLease.runtimeEpoch)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native prepared clear does not freeze this registered attempt")},mutationKey:e=>`native-reply:${s.operationId}:${o.runtimeLease.journalStoreId}:${o.runtimeLease.journalGeneration}:${e}`}});if(m(),e.signal.aborted||await t.journal.getCancellation(s.operationId))throw new RuntimeCommandError("OPERATION_CANCELLED","native prompt cancelled before start");await t.channel.append({operationId:s.operationId,lease:t.getLease(),currentNativePrompt:r,executionGrant:e.delivery.executionGrant,type:"runtime_operation_started",payload:{...runtimeMessageBase(s),executionGrantHash:s.executionGrantHash,handlerIdentity:e.lease.handlerIdentity,executionMode:"start",claimedAt:p.updatedAt}}),m(),p=await t.journal.transition({operationId:s.operationId,expectedRevision:p.revision,phase:"started"}),m();const I=()=>{m();const e=t.getLease();return{leaseId:e.leaseId,handlerIdentity:e.handlerIdentity,runtimeEpoch:e.runtimeEpoch,runtimeLeaseCredential:e.runtimeLeaseCredential}},f={operationId:s.operationId,requestMessageId:s.requestMessageId,conversationId:r.command.context.conversation.runtimeConversationUid,historyGeneration:r.historyGeneration,runtimeRunId:o.runtimeRunId},R=await t.runBoundary.start({...f,lease:I()});if(m(),"registered"!==R.status||R.historyGeneration!==r.historyGeneration||R.activeRunRegistrationId!==o.taskId)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native MS run start did not register the original task");v=R.activeRunRegistrationId;const N=new AbortController,w=()=>N.abort(e.signal.reason);if(e.signal.addEventListener("abort",w,{once:!0}),e.signal.aborted&&w(),e.setCancel(e=>N.abort(e)),await t.journal.getCancellation(s.operationId)&&N.abort(nativePromptCancellationReason),m(),N.signal.aborted){if(e.signal.removeEventListener("abort",w),N.signal.reason===nativePromptCancellationReason)throw new RuntimeCommandError("OPERATION_CANCELLED","native prompt cancelled before host invocation");throw new RuntimeCommandError("OUTCOME_UNKNOWN","native registered run stopped before host invocation")}const E=[];let y;const C=JSON.parse((await g.opened()).rawText),O=C.parts?.length??0,M=async e=>{const t=await e;return m(),this.assertReply(t,r),y=t,t},_={id:g.id,get isTerminated(){return g.isTerminated},get parts(){return E},opened:async()=>({messageId:g.id,outcome:"bound"}),appendBody:e=>g.appendBody(e),setBody:e=>g.setBody(e),addPart:e=>{E.push(e),g.addPart(e)},replacePart:(e,t)=>{E[e]=t,g.replacePart(O+e,t)},appendToolResult:(e,t,a)=>{const n={type:"tool_result",tool_use_id:e,content:t,...a?{is_error:!0}:{}};E.push(n),g.addPart(n)},finalize:e=>M(g.finalize(e)),fail:e=>M(g.fail(e)),cancel:e=>M(g.cancel(e))},b={message:d,mediaPaths:[],mediaTypes:[]};let U,A;const q=t.host.htmlDeliveryEnabled?new HtmlDeliveryGuard(!1):void 0,T=createNativeOutputFileAttempt({htmlDelivery:q,operationId:s.operationId,requestMessageId:s.requestMessageId,paramsHash:s.paramsHash,activeRunRegistrationId:v,getLease:()=>(m(),t.getLease()),assertAttempt:m,signal:N.signal}),P=setTimeout(()=>N.abort(nativePromptExecutionDeadlineReason),Math.max(0,Math.min(Date.parse(s.executionDeadlineAt)-3e4-Date.now(),2147483647)));P.unref?.();try{await dispatchImInboundPrompt({...t.host,htmlDelivery:q,runtimeRunId:o.runtimeRunId,onNativeAgentRunStart:e=>T.bindHostRun(e),nativeActiveRunRegistration:{runtimeConversationUid:f.conversationId,runtimeSessionKey:r.command.context.conversation.runtimeSessionKey,historyGeneration:R.historyGeneration,targetMessageId:o.taskRequestMessageId,runtimeRunId:o.runtimeRunId,activeRunRegistrationId:R.activeRunRegistrationId},assertNativeTarget:async()=>{if(await t.host.resolveNativePromptSessionKey(r,m)!==h)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native prompt target changed before host invocation")},prepareNativeModel:async e=>{m(),await t.host.prepareNativePromptModel(r,e,m),m();for(const e of n.files){if(!t.inputFiles)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native authorized input file resolver unavailable");const a=await t.inputFiles.resolve({operationId:s.operationId,requestMessageId:s.requestMessageId,paramsHash:s.paramsHash,partIndex:e.partIndex,lease:t.getLease(),signal:N.signal});m();const n=await downloadNativeInputFile({fileId:e.fileId,...a,signal:N.signal,assertAttempt:m});b.mediaPaths.push(n.path),b.mediaTypes.push(n.mimeType)}m()},onNativeRunCompletion:e=>{A=e},retainedStream:_,abortSignal:N.signal,inReplyTo:o.taskRequestMessageId,prompt:{channelId:o.conversationId,inboundMessageId:o.taskRequestMessageId,requestId:s.requestMessageId,selfPrincipalId:e.lease.instanceId,sessionKey:h,dispatchInput:b},client:{messages:{startStream(){throw new Error("native reply POST forbidden")},getEnvelope:async()=>({state:(await c()).state})},getSnapshot:()=>({connection:"connected",messages:{},conversations:{}})}})}catch(e){U=e}finally{clearTimeout(P),T.close(),e.signal.removeEventListener("abort",w)}if(!A&&U)throw U;if(!A||A.runtimeRunId!==o.runtimeRunId||A.token.sessionKey!==h)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native physical host completion unavailable");let S;try{await A.completion}catch(e){S=e}if(m(),!y)throw new RuntimeCommandError("OUTCOME_UNKNOWN",void 0!==S?"native host/abort/drain did not converge":"native kernel settled without verified original reply terminal",void 0,{cause:S??U});const H=this.terminal(y,r),L=await c();g.assertTerminalSnapshot(L);const x="completed"===L.state?"completed":"cancelled"===L.state?"cancelled":"failed",K=await t.runBoundary.finish({...f,activeRunRegistrationId:v,terminalState:x,source:"runtime",lease:I()});if(m(),"finished"!==K.status&&"idempotent"!==K.status||K.activeRunRegistrationId!==v)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native MS run finish was not acknowledged");return await t.journal.transition({operationId:s.operationId,expectedRevision:p.revision,phase:"succeeded"===H.outcome?"effect_committed":"failed",result:H.result}),m(),{request:s,...H}}catch(e){throw new NativePromptExecutionFailure(s,e)}}assertReply(e,t){if(e.messageId!==t.params.replyMessageId||e.conversationId!==t.params.conversationId||e.replyTo!==t.params.taskRequestMessageId)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native durable reply binding mismatch")}terminal(e,t){if(!e.stopReason||!["completed","failed","refused","cancelled"].includes(e.state))throw new RuntimeCommandError("OUTCOME_UNKNOWN","native durable terminal absent");const a="cancelled"===e.state&&"user_stop"===e.stopReason?"cancelled":"completed"===e.state&&"end_turn"===e.stopReason?"succeeded":"failed";return{outcome:a,result:{runtimeRunId:t.params.runtimeRunId,stopReason:e.stopReason,requestAborted:"cancelled"===e.state&&"user_stop"===e.stopReason,..."failed"===a?{error:e.body}:{}}}}}export const NATIVE_PROMPT_UNKNOWN_REASONS=new Set(["native MS run boundary required","native existing journal binding mismatch","native task snapshot unavailable","native original task snapshot unavailable","native original task snapshot mismatch","native single snapshot unavailable","native durable MS finish audit or original result unavailable","native original terminal does not match finished audit","native original final outcome mismatch","native original final RPC binding mismatch","native original result conflicts with local receipt","native original final result hash evidence mismatch","native original canonical result evidence unavailable","native task already started","native prepared clear does not freeze this registered attempt","native MS run start did not register the original task","native registered run stopped before host invocation","native prompt target changed before host invocation","native authorized input file resolver unavailable","native physical host completion unavailable","native host/abort/drain did not converge","native kernel settled without verified original reply terminal","native MS run finish was not acknowledged","native durable reply binding mismatch","native durable terminal absent"]);export function nativePromptUnknownReason(e){return e instanceof RuntimeCommandError&&"OUTCOME_UNKNOWN"===e.code?NATIVE_PROMPT_UNKNOWN_REASONS.has(e.message)?e.message:"unlisted":"not_unknown"}export class NativePromptExecutionFailure extends Error{request;failure;constructor(e,t){super(t instanceof Error?t.message:String(t),{cause:t}),this.request=e,this.failure=t}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync,readFileSync}from"node:fs";import{isAbsolute,join}from"node:path";import{resolveOpenClawStateDir}from"./openclaw-state-dir.js";const DEFAULT_POLL_INTERVAL_MS=250,DEFAULT_QUIET_CONFIRMATION_MS=750,DEFAULT_UNRESOLVED_GRACE_MS=1e4;export class OpenClawSessionWriteQuiescence{logger;stateDir;defaultAgentId;pollIntervalMs;quietConfirmationMs;unresolvedGraceMs;now;sleep;constructor(e,s={}){this.logger=e,this.stateDir=s.stateDir??resolveOpenClawStateDir(),this.defaultAgentId=s.agentId??"main",this.pollIntervalMs=s.pollIntervalMs??250,this.quietConfirmationMs=s.quietConfirmationMs??750,this.unresolvedGraceMs=s.unresolvedGraceMs??1e4,this.now=s.now??(()=>Date.now()),this.sleep=s.sleep??(e=>new Promise(s=>{const t=setTimeout(s,e);t.unref?.()}))}async waitForQuiescence(e,s){const t=this.now();let i,o
|
|
1
|
+
import{existsSync,readFileSync}from"node:fs";import{isAbsolute,join}from"node:path";import{resolveOpenClawStateDir}from"./openclaw-state-dir.js";const DEFAULT_POLL_INTERVAL_MS=250,DEFAULT_QUIET_CONFIRMATION_MS=750,DEFAULT_UNRESOLVED_GRACE_MS=1e4;export class OpenClawSessionWriteQuiescence{logger;options;stateDir;defaultAgentId;pollIntervalMs;quietConfirmationMs;unresolvedGraceMs;now;sleep;constructor(e,s={}){this.logger=e,this.options=s,this.stateDir=s.stateDir??resolveOpenClawStateDir(),this.defaultAgentId=s.agentId??"main",this.pollIntervalMs=s.pollIntervalMs??250,this.quietConfirmationMs=s.quietConfirmationMs??750,this.unresolvedGraceMs=s.unresolvedGraceMs??1e4,this.now=s.now??(()=>Date.now()),this.sleep=s.sleep??(e=>new Promise(s=>{const t=setTimeout(s,e);t.unref?.()}))}async waitForQuiescence(e,s){const t=this.now();let i,n,o;for(;this.now()-t<s;){if(this.options.nativeWritersQuiescent){if(this.options.nativeWritersQuiescent(e))return{quiescent:!0,reason:"native_writer_fence",elapsedMs:this.now()-t};await this.sleep(this.pollIntervalMs);continue}const s=o??this.resolveLockPath(e);if(s){if(n=s,o=s,existsSync(s))i=void 0;else if(i??=this.now(),this.now()-i>=this.quietConfirmationMs)return{quiescent:!0,reason:"unlocked",lockPath:s,elapsedMs:this.now()-t};await this.sleep(this.pollIntervalMs)}else{if(this.hasSqliteSessionStore(e))return{quiescent:!0,reason:"native_writer_fence",elapsedMs:this.now()-t};if(this.now()-t>=this.unresolvedGraceMs)break;await this.sleep(this.pollIntervalMs)}}return this.logger.warn?.(`[im] session writer did not become quiescent sessionKey=${e} timeout_ms=${s}`),{quiescent:!1,reason:n?"timeout":"session_unresolved",...n?{lockPath:n}:{},elapsedMs:this.now()-t}}agentRoot(e){const s=/^agent:([^:]+):/.exec(e)?.[1]??this.defaultAgentId;return join(this.stateDir,"agents",s)}hasSqliteSessionStore(e){return existsSync(join(this.agentRoot(e),"agent","openclaw-agent.sqlite"))}resolveLockPath(e){const s=join(this.agentRoot(e),"sessions"),t=join(s,"sessions.json");if(!existsSync(t))return;let i;try{const s=JSON.parse(readFileSync(t,"utf8"));if(!s||"object"!=typeof s)return;const n=s[e];n&&"object"==typeof n&&(i=n)}catch(s){return void this.logger.debug?.(`[im] session index read deferred sessionKey=${e} error=${s instanceof Error?s.message:String(s)}`)}if(!i)return;const n="string"==typeof i.sessionFile?i.sessionFile.trim():"",o="string"==typeof i.sessionId?i.sessionId.trim():"",r=n?isAbsolute(n)?n:join(s,n):o?join(s,`${o}.jsonl`):"";return r?`${r}.lock`:void 0}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{enableDeepseekReasoningStream}from"./deepseek-reasoning-stream.js";const DEFAULT_SURFACE="beeos-claw",DEFAULT_ORIGINATING_CHANNEL="webchat",DEFAULT_ORIGINATING_TARGET="main",DEFAULT_ORIGINATING_ACCOUNT_ID="main",isRecord=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),assertKnownReplyProtocol=e=>{if("acp"!==e&&"im"!==e)throw new Error(`unsupported reply route protocol=${e}`)},normalizeMediaUrls=e=>{if(!Array.isArray(e))return;const o=e.filter(e=>"string"==typeof e&&e.length>0);return o.length>0?o:void 0};export const hasRuntimeReplyApi=e=>"function"==typeof e?.channel?.reply?.dispatchReplyFromConfig;export const buildFinalizedMsgContext=(e,o)=>{assertKnownReplyProtocol(o.protocol);const
|
|
1
|
+
import{enableDeepseekReasoningStream}from"./deepseek-reasoning-stream.js";const DEFAULT_SURFACE="beeos-claw",DEFAULT_ORIGINATING_CHANNEL="webchat",DEFAULT_ORIGINATING_TARGET="main",DEFAULT_ORIGINATING_ACCOUNT_ID="main",isRecord=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),assertKnownReplyProtocol=e=>{if("acp"!==e&&"im"!==e)throw new Error(`unsupported reply route protocol=${e}`)},normalizeMediaUrls=e=>{if(!Array.isArray(e))return;const o=e.filter(e=>"string"==typeof e&&e.length>0);return o.length>0?o:void 0};export const hasRuntimeReplyApi=e=>"function"==typeof e?.channel?.reply?.dispatchReplyFromConfig;export const buildFinalizedMsgContext=(e,o)=>{assertKnownReplyProtocol(o.protocol);const t=o.originatingChannel??"beeos-claw",r=o.originatingChannel??"webchat",n=o.originatingTo??"main",i=o.accountId??"main",s=normalizeMediaUrls(e.attachments);return{Body:e.message,BodyForAgent:e.agentMessage,From:`${t}:${n}`,To:n,SessionKey:o.sessionId,Surface:t,Provider:t,OriginatingChannel:r,OriginatingTo:n,AccountId:i,CommandAuthorized:!0,...e.nativeSystemContext?{GroupSystemPrompt:e.nativeSystemContext}:{},...s?{MediaUrls:s}:{},...e.mediaPaths?.length?{MediaPaths:e.mediaPaths,MediaTypes:e.mediaTypes}:{}}};export const resolveReplySinkForRoute=(e,o)=>{assertKnownReplyProtocol(e.protocol);const t=o[e.protocol];if(!t)throw new Error(`runtime reply sink unavailable protocol=${e.protocol} requestId=${e.requestId}`);return t};const resolveRuntimeDispatchConfig=(e,o)=>{try{const o=e.config?.loadConfig?.();if(isRecord(o))return o}catch{}return o};export const dispatchRuntimeReplyWithRoute=async e=>{const o=e.runtime.channel?.reply?.dispatchReplyFromConfig;if("function"!=typeof o)throw new Error(`runtime reply API unavailable protocol=${e.replyRoute.protocol} requestId=${e.replyRoute.requestId}`);const t=resolveReplySinkForRoute(e.replyRoute,e.replySinks),r=enableDeepseekReasoningStream(resolveRuntimeDispatchConfig(e.runtime,e.pluginConfig)),n=o({ctx:buildFinalizedMsgContext(e.preparedPrompt,e.replyRoute),cfg:r,dispatcher:t.dispatcher,replyOptions:t.replyOptions});return e.onDispatchInvoked?.(n),n};
|