beeos-claw 0.6.63-cloud.0 → 0.6.63-cloud.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/a2a/tools.js +1 -1
  2. package/dist/acp-gateway/beeos-file-resolver.js +1 -1
  3. package/dist/acp-gateway/bridge-core.js +1 -1
  4. package/dist/acp-gateway/gateway-events.js +1 -1
  5. package/dist/acp-server.js +1 -1
  6. package/dist/agent-sync.js +1 -1
  7. package/dist/automation/tools.js +1 -0
  8. package/dist/automation/turn-policy.js +1 -0
  9. package/dist/automation/wake.js +1 -0
  10. package/dist/canvas/relay-client.js +1 -1
  11. package/dist/canvas/ws-provider.js +1 -1
  12. package/dist/canvas-orchestrator.js +1 -1
  13. package/dist/chat-envelope.js +1 -0
  14. package/dist/connectors/managed-connector-tools.js +1 -0
  15. package/dist/files/fetch-tool.js +1 -1
  16. package/dist/files/list-tool.js +1 -1
  17. package/dist/im-inbound-handler.js +1 -1
  18. package/dist/im-runtime-dispatch.js +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/mcp-connector-proxy.js +1 -1
  21. package/dist/media/arouter-config.js +1 -1
  22. package/dist/media/image-provider.js +1 -1
  23. package/dist/media/video-provider.js +1 -1
  24. package/dist/message-client-composition.js +1 -1
  25. package/dist/runtime/agent-projection-production.js +1 -1
  26. package/dist/runtime/callback-queue.js +1 -1
  27. package/dist/runtime/chat-handler-port.js +1 -0
  28. package/dist/runtime/conversation-title.js +1 -1
  29. package/dist/runtime/core-execution-attempt-context.js +1 -1
  30. package/dist/runtime/im-reply-sink.js +1 -1
  31. package/dist/runtime/message-service-conversation-clear-http-authority.js +1 -1
  32. package/dist/runtime/message-service-conversation-history-boundary.js +1 -1
  33. package/dist/runtime/message-service-conversation-run-boundary.js +1 -1
  34. package/dist/runtime/message-service-cron-delivery-http-authority.js +1 -1
  35. package/dist/runtime/message-service-runtime-authenticated-fetch.js +1 -1
  36. package/dist/runtime/message-service-runtime-claim-authority.js +1 -1
  37. package/dist/runtime/message-service-runtime-message-channel.js +1 -1
  38. package/dist/runtime/message-service-session-model-http-authority.js +1 -1
  39. package/dist/runtime/ms-runtime-message-channel-adapter.js +1 -1
  40. package/dist/runtime/ms-runtime-message-channel-consumer-factory.js +1 -1
  41. package/dist/runtime/ms-runtime-rpc-adapter.js +1 -1
  42. package/dist/runtime/native-cloud-chat-composition.js +1 -0
  43. package/dist/runtime/native-cloud-prompt-bridge.js +1 -0
  44. package/dist/runtime/native-input-files-http.js +1 -0
  45. package/dist/runtime/native-input-files.js +1 -0
  46. package/dist/runtime/native-output-file-attempt.js +1 -0
  47. package/dist/runtime/native-prompt-authority.js +1 -0
  48. package/dist/runtime/native-prompt-preflight.js +1 -0
  49. package/dist/runtime/native-session-new-bridge.js +1 -0
  50. package/dist/runtime/openclaw-session-model.js +1 -0
  51. package/dist/runtime/reply-router.js +1 -1
  52. package/dist/runtime/runtime-error-part.js +1 -0
  53. package/dist/runtime/runtime-local-parity-matrix.js +1 -1
  54. package/dist/runtime/runtime-message-channel-contract.js +1 -1
  55. package/dist/runtime/runtime-operation-resource-resolver.js +1 -1
  56. package/dist/runtime/runtime-parity-manifest-digest.js +1 -1
  57. package/dist/runtime/runtime-parity-manifest.js +1 -1
  58. package/dist/runtime/runtime-production-authority.js +1 -1
  59. package/dist/runtime/runtime-registration-identity-store.js +1 -1
  60. package/dist/runtime/runtime-service-contract-compatibility.js +1 -1
  61. package/dist/runtime/runtime-service-production-candidate.js +1 -1
  62. package/dist/runtime/runtime-session-control-service.js +1 -1
  63. package/dist/runtime/runtime-skills-service.js +1 -1
  64. package/dist/runtime/service-runtime-attempt-ports-resolver.js +1 -1
  65. package/dist/runtime/session-new-runtime-delivery-bridge.js +1 -1
  66. package/dist/runtime/write-runtime-failure.js +1 -1
  67. package/dist/terminal/runtime-terminal-outbound-registration.js +1 -1
  68. package/dist/terminal/terminal-lease-bound-bridge-client.js +1 -1
  69. package/dist/upload/desktop-screenshot-tool.js +1 -1
  70. package/dist/upload/finalize-hook.js +1 -1
  71. package/dist/upload/tool-artifact-enrichment.js +1 -1
  72. package/dist/upload/tool.js +1 -1
  73. package/dist/upload/upload-file.js +1 -1
  74. package/openclaw.plugin.json +20 -2
  75. package/package.json +5 -4
  76. package/runtime-service-wire-identity.v1.json +5 -5
  77. package/dist/agent-auth.js +0 -1
  78. package/dist/bridge-discovery.js +0 -1
  79. package/dist/runtime/agent-gateway-runtime-attempt-authorization.js +0 -1
  80. package/dist/runtime/message-service-runtime-invocation-authority.js +0 -1
  81. package/dist/runtime/runtime-jwks-verifier.js +0 -1
  82. package/dist/runtime/runtime-registration.js +0 -1
  83. package/dist/runtime/runtime-transport-failure-policy.js +0 -1
  84. package/dist/runtime/split-runtime-authorization-verifier.js +0 -1
@@ -1 +1 @@
1
- import{canonicalizeJcs,verifyAndDeriveCoreExecutionAttempt}from"@beeos-ai/beeos-types/runtime";const TRUSTED_CORE_ATTEMPT=Symbol("beeos.trusted-core-attempt"),VERIFIED_MESSAGE_GRANT=Symbol("beeos.verified-message-grant");export function createAcpCoreExecutionAttempt(e){if(e.historyBoundary&&"local"!==e.historyBoundary.kind)throw new Error("ACP attempt cannot use a Message Service history boundary");return Object.freeze({...e,origin:"acp",[TRUSTED_CORE_ATTEMPT]:!0})}export async function verifyAndCreateServiceCoreExecutionAttempt(e){let t;try{t=verifyAndDeriveCoreExecutionAttempt(e.authorization,e.derivationContext,e.verifier)}catch{return{ok:!1,violations:["MALFORMED_EXECUTION_AUTHORIZATION"]}}if(!t.ok)return t;await e.recordVerifiedAttempt(t.attempt);const o=await e.resolvePorts();if(o.historyBoundary&&"message-service"!==o.historyBoundary.kind)throw new Error("Service attempt cannot fall back to local conversation history");if(o.sessionModelProjection&&o.historyBoundary)throw new Error("Service attempt cannot bind clear history and session model projection together");return{ok:!0,context:Object.freeze({operationId:e.operationId,runtimeEpoch:e.runtimeEpoch,fence:e.fence,resources:o.resources,...o.historyBoundary?{historyBoundary:o.historyBoundary}:{},...o.sessionModelProjection?{sessionModelProjection:o.sessionModelProjection}:{},...o.canvasControl?{canvasControl:o.canvasControl}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{},verifiedAttempt:t.attempt,origin:"service",[TRUSTED_CORE_ATTEMPT]:!0})}}export async function verifyAndCreateMessageServiceCoreExecutionAttempt(e){const t=e.verifier.verifyAndDecodeGrant(e.executionGrant);if(!t)return{ok:!1,violations:["GRANT_SIGNATURE_INVALID"]};if(t.compactHash!==e.request.executionGrantHash)return{ok:!1,violations:["GRANT_HASH_MISMATCH"]};const o=t.claims,n=validateMessageGrant(o,e.request,e.lease,e.nowEpochSeconds??Math.floor(Date.now()/1e3),!0===e.allowExpiredGrant);if(n.length)return{ok:!1,violations:n};const r=await e.resolvePorts();if(r.historyBoundary&&"message-service"!==r.historyBoundary.kind)throw new Error("Service attempt cannot fall back to local conversation history");if(r.sessionModelProjection&&r.historyBoundary)throw new Error("Service attempt cannot bind clear history and session model projection together");const i=Object.freeze({[VERIFIED_MESSAGE_GRANT]:!0,claims:Object.freeze({...o}),compactHash:t.compactHash});return{ok:!0,grant:i,context:Object.freeze({operationId:e.request.operationId,runtimeEpoch:e.runtimeEpoch,resources:r.resources,...r.historyBoundary?{historyBoundary:r.historyBoundary}:{},...r.sessionModelProjection?{sessionModelProjection:r.sessionModelProjection}:{},...r.canvasControl?{canvasControl:r.canvasControl}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{},verifiedMessageGrant:i,origin:"service",[TRUSTED_CORE_ATTEMPT]:!0})}}export function assertTrustedCoreExecutionAttempt(e,t){if(!e||!0!==e[TRUSTED_CORE_ATTEMPT]||e.operationId!==t.operationId||e.runtimeEpoch!==t.runtimeEpoch)throw new Error("untrusted or mismatched Core execution attempt context");if(!("service"!==e.origin||e.verifiedMessageGrant||e.fence&&e.verifiedAttempt))throw new Error("Service Core execution attempt lacks verified authorization")}function validateMessageGrant(e,t,o,n,r){if(!e||"object"!=typeof e)return["MALFORMED_EXECUTION_GRANT"];const i="historyGeneration"in e?e.historyGeneration:void 0,s="instance"===e.scope&&"runtimeAgentUid"in e?e.runtimeAgentUid:void 0;if(!exactKeys(e,["iss","aud","purpose","sub","jti","iat","exp","operationId","requestMessageId","instanceId","handlerIdentity","dispatchEpoch","method","requestHash","paramsHash","commandHash","idempotencyKeyHash","callerUserId","callerIdentityId","scope","command","executionMode",..."instance"===e.scope?void 0!==s?["runtimeAgentUid"]:[]:"agent"===e.scope?["platformAgentId","runtimeAgentUid"]:"conversation"===e.scope?["platformConversationId","runtimeConversationUid","runtimeSessionKey","platformAgentId","runtimeAgentUid",...void 0!==i?["historyGeneration"]:[]]:[]]))return["GRANT_FIELDS_INVALID"];const a=[];"beeos-gateway"===e.iss&&"beeos-runtime-command"===e.aud&&"runtime-execution-grant"===e.purpose&&e.sub===t.runtimeHandlerIdentity&&e.handlerIdentity===t.runtimeHandlerIdentity&&"start"===e.executionMode||a.push("GRANT_IDENTITY_MISMATCH"),(!Number.isSafeInteger(e.iat)||!Number.isSafeInteger(e.exp)||"string"!=typeof e.jti||0===e.jti.length||e.iat>n||e.exp<=e.iat||!r&&e.exp<=n||e.exp-e.iat>60)&&a.push("GRANT_TIME_INVALID");if([[e.operationId,t.operationId],[e.requestMessageId,t.requestMessageId],[e.instanceId,t.instanceId],[e.dispatchEpoch,t.dispatchEpoch],[e.method,t.method],[e.requestHash,t.requestHash],[e.paramsHash,t.paramsHash],[e.commandHash,t.commandHash],[e.idempotencyKeyHash,t.idempotencyKeyHash],[e.callerUserId,t.callerUserId],[e.callerIdentityId,t.callerIdentityId],[o.instanceId,t.instanceId],[o.handlerIdentity,t.runtimeHandlerIdentity],[o.runtimeEpoch,t.dispatchEpoch]].some(([e,t])=>e!==t)&&a.push("GRANT_REQUEST_MISMATCH"),semanticEqual(e.command,t.command)||a.push("GRANT_COMMAND_MISMATCH"),targetMatches(e,t)||a.push("GRANT_TARGET_MISMATCH"),"conversation"===e.scope){const o=t.command.context,n=o?.agent;o&&"conversation"===o.scope&&n?.platformAgentId===e.platformAgentId&&n?.runtimeAgentUid===e.runtimeAgentUid||a.push("GRANT_TARGET_MISMATCH");const r=o?.historyGeneration;"session/cancel"===e.method?"string"==typeof i&&0!==i.length&&i===r||a.push("GRANT_HISTORY_GENERATION_MISMATCH"):void 0!==i&&a.push("GRANT_HISTORY_GENERATION_MISMATCH")}return a}function semanticEqual(e,t){try{return canonicalizeJcs(e)===canonicalizeJcs(t)}catch{return!1}}function targetMatches(e,t){const o=t.command.context,n=t.request.params;if(!o||o.scope!==e.scope)return!1;if("instance"===o.scope){if(!("runtimeAgentUid"in e))return!0;const o=e.runtimeAgentUid;if("string"!=typeof o||0===o.length)return!1;const n=t.command.params;return n?.runtimeAgentUid===o}if("agent"===o.scope)return o.agent.runtimeAgentUid===e.runtimeAgentUid&&null!==n&&"object"==typeof n&&!Array.isArray(n)&&n.platformAgentId===e.platformAgentId;const r=null===n||"object"!=typeof n||Array.isArray(n)?void 0:"string"==typeof n.conversationId?n.conversationId:"string"==typeof n.sessionId?n.sessionId:void 0;return o.conversation.runtimeConversationUid===e.runtimeConversationUid&&o.conversation?.runtimeSessionKey===e.runtimeSessionKey&&r===e.platformConversationId}function exactKeys(e,t){const o=Object.keys(e).sort(),n=[...t].sort();return o.length===n.length&&o.every((e,t)=>e===n[t])}
1
+ import{canonicalizeJcs,isCloudRuntimeExecutionGrant,verifyAndDeriveCoreExecutionAttempt}from"@beeos-ai/beeos-types/runtime";const TRUSTED_CORE_ATTEMPT=Symbol("beeos.trusted-core-attempt"),VERIFIED_MESSAGE_GRANT=Symbol("beeos.verified-message-grant");export function createAcpCoreExecutionAttempt(e){if(e.historyBoundary&&"local"!==e.historyBoundary.kind)throw new Error("ACP attempt cannot use a Message Service history boundary");return Object.freeze({...e,origin:"acp",[TRUSTED_CORE_ATTEMPT]:!0})}export async function verifyAndCreateServiceCoreExecutionAttempt(e){let t;try{t=verifyAndDeriveCoreExecutionAttempt(e.authorization,e.derivationContext,e.verifier)}catch{return{ok:!1,violations:["MALFORMED_EXECUTION_AUTHORIZATION"]}}if(!t.ok)return t;await e.recordVerifiedAttempt(t.attempt);const o=await e.resolvePorts();if(o.historyBoundary&&"message-service"!==o.historyBoundary.kind)throw new Error("Service attempt cannot fall back to local conversation history");if(o.sessionModelProjection&&o.historyBoundary)throw new Error("Service attempt cannot bind clear history and session model projection together");return{ok:!0,context:Object.freeze({operationId:e.operationId,runtimeEpoch:e.runtimeEpoch,fence:e.fence,resources:o.resources,...o.historyBoundary?{historyBoundary:o.historyBoundary}:{},...o.sessionModelProjection?{sessionModelProjection:o.sessionModelProjection}:{},...o.canvasControl?{canvasControl:o.canvasControl}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{},verifiedAttempt:t.attempt,origin:"service",[TRUSTED_CORE_ATTEMPT]:!0})}}export async function verifyAndCreateMessageServiceCoreExecutionAttempt(e){const t=e.verifier.verifyAndDecodeGrant(e.executionGrant);if(!t)return{ok:!1,violations:["GRANT_SIGNATURE_INVALID"]};if(t.compactHash!==e.request.executionGrantHash)return{ok:!1,violations:["GRANT_HASH_MISMATCH"]};const o=e.nowEpochSeconds??Math.floor(Date.now()/1e3),n=t.claims,r=e.request,i=2===e.request.schemaVersion?isCloudRuntimeExecutionGrant(t.claims,e.request,{...e.lease,leaseId:e.lease.leaseId??""},o,{allowExpiredAfterRetainedStart:!0===e.allowExpiredGrant&&("models/list"===r.method||"skills/list"===r.method)})?[]:["CLOUD_GRANT_REQUEST_MISMATCH"]:validateMessageGrant(n,e.request,e.lease,o,!0===e.allowExpiredGrant);if(i.length)return{ok:!1,violations:i};const s=await e.resolvePorts();if(s.historyBoundary&&"message-service"!==s.historyBoundary.kind)throw new Error("Service attempt cannot fall back to local conversation history");if(s.sessionModelProjection&&s.historyBoundary)throw new Error("Service attempt cannot bind clear history and session model projection together");const a=Object.freeze({[VERIFIED_MESSAGE_GRANT]:!0,claims:Object.freeze({...n}),compactHash:t.compactHash});return{ok:!0,grant:a,context:Object.freeze({operationId:e.request.operationId,runtimeEpoch:e.runtimeEpoch,resources:s.resources,...s.historyBoundary?{historyBoundary:s.historyBoundary}:{},...s.sessionModelProjection?{sessionModelProjection:s.sessionModelProjection}:{},...s.canvasControl?{canvasControl:s.canvasControl}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{},verifiedMessageGrant:a,origin:"service",[TRUSTED_CORE_ATTEMPT]:!0})}}export function assertTrustedCoreExecutionAttempt(e,t){if(!e||!0!==e[TRUSTED_CORE_ATTEMPT]||e.operationId!==t.operationId||e.runtimeEpoch!==t.runtimeEpoch)throw new Error("untrusted or mismatched Core execution attempt context");if(!("service"!==e.origin||e.verifiedMessageGrant||e.fence&&e.verifiedAttempt))throw new Error("Service Core execution attempt lacks verified authorization")}function validateMessageGrant(e,t,o,n,r){if(!e||"object"!=typeof e)return["MALFORMED_EXECUTION_GRANT"];const i="historyGeneration"in e?e.historyGeneration:void 0,s="instance"===e.scope&&"runtimeAgentUid"in e?e.runtimeAgentUid:void 0;if(!exactKeys(e,["iss","aud","purpose","sub","jti","iat","exp","operationId","requestMessageId","instanceId","handlerIdentity","dispatchEpoch","method","requestHash","paramsHash","commandHash","idempotencyKeyHash","callerUserId","callerIdentityId","scope","command","executionMode",..."instance"===e.scope?void 0!==s?["runtimeAgentUid"]:[]:"agent"===e.scope?["platformAgentId","runtimeAgentUid"]:"conversation"===e.scope?["platformConversationId","runtimeConversationUid","runtimeSessionKey","platformAgentId","runtimeAgentUid",...void 0!==i?["historyGeneration"]:[]]:[]]))return["GRANT_FIELDS_INVALID"];const a=[];"beeos-gateway"===e.iss&&"beeos-runtime-command"===e.aud&&"runtime-execution-grant"===e.purpose&&e.sub===t.runtimeHandlerIdentity&&e.handlerIdentity===t.runtimeHandlerIdentity&&"start"===e.executionMode||a.push("GRANT_IDENTITY_MISMATCH"),(!Number.isSafeInteger(e.iat)||!Number.isSafeInteger(e.exp)||"string"!=typeof e.jti||0===e.jti.length||e.iat>n||e.exp<=e.iat||!r&&e.exp<=n||e.exp-e.iat>60)&&a.push("GRANT_TIME_INVALID");if([[e.operationId,t.operationId],[e.requestMessageId,t.requestMessageId],[e.instanceId,t.instanceId],[e.dispatchEpoch,t.dispatchEpoch],[e.method,t.method],[e.requestHash,t.requestHash],[e.paramsHash,t.paramsHash],[e.commandHash,t.commandHash],[e.idempotencyKeyHash,t.idempotencyKeyHash],[e.callerUserId,t.callerUserId],[e.callerIdentityId,t.callerIdentityId],[o.instanceId,t.instanceId],[o.handlerIdentity,t.runtimeHandlerIdentity],[o.runtimeEpoch,t.dispatchEpoch]].some(([e,t])=>e!==t)&&a.push("GRANT_REQUEST_MISMATCH"),semanticEqual(e.command,t.command)||a.push("GRANT_COMMAND_MISMATCH"),targetMatches(e,t)||a.push("GRANT_TARGET_MISMATCH"),"conversation"===e.scope){const o=t.command.context,n=o?.agent;o&&"conversation"===o.scope&&n?.platformAgentId===e.platformAgentId&&n?.runtimeAgentUid===e.runtimeAgentUid||a.push("GRANT_TARGET_MISMATCH");const r=o?.historyGeneration;"session/cancel"===e.method?"string"==typeof i&&0!==i.length&&i===r||a.push("GRANT_HISTORY_GENERATION_MISMATCH"):void 0!==i&&a.push("GRANT_HISTORY_GENERATION_MISMATCH")}return a}function semanticEqual(e,t){try{return canonicalizeJcs(e)===canonicalizeJcs(t)}catch{return!1}}function targetMatches(e,t){const o=t.command.context,n=t.request.params;if(!o||o.scope!==e.scope)return!1;if("instance"===o.scope){if(!("runtimeAgentUid"in e))return!0;const o=e.runtimeAgentUid;if("string"!=typeof o||0===o.length)return!1;const n=t.command.params;return n?.runtimeAgentUid===o}if("agent"===o.scope)return o.agent.runtimeAgentUid===e.runtimeAgentUid&&null!==n&&"object"==typeof n&&!Array.isArray(n)&&n.platformAgentId===e.platformAgentId;const r=null===n||"object"!=typeof n||Array.isArray(n)?void 0:"string"==typeof n.conversationId?n.conversationId:"string"==typeof n.sessionId?n.sessionId:void 0;return o.conversation.runtimeConversationUid===e.runtimeConversationUid&&o.conversation?.runtimeSessionKey===e.runtimeSessionKey&&r===e.platformConversationId}function exactKeys(e,t){const o=Object.keys(e).sort(),n=[...t].sort();return o.length===n.length&&o.every((e,t)=>e===n[t])}
@@ -1 +1 @@
1
- import{toMessagePart}from"../message-client-types.js";import{isUploadArtifactToolName,resolveToolArtifactLinks}from"../upload/tool-artifact-enrichment.js";import{sessionWorkspaceDir,takeFinalizeAttachments}from"../upload/delivery-ledger.js";import{resolveRuntimeToolArguments,resolveRuntimeToolCallId,resolveRuntimeToolName}from"./tool-envelope-metadata.js";import{extractSearchSources,mergeSearchSource,searchSourceProvider}from"./search-source-extractor.js";import{logChatLatency}from"../chat-latency.js";const STREAMING_SNAPSHOT_PUBLISH_INTERVAL_MS=200,isNonEmptyString=e=>"string"==typeof e&&e.length>0,isPlainRecord=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);function pickRawResultFromPayload(e){if(void 0!==e.rawResult)return e.rawResult;if(void 0!==e.result)return e.result;if(void 0!==e.details)return e.details;if(void 0!==e.toolResult)return e.toolResult;if(isPlainRecord(e.channelData)){const t=e.channelData;if(void 0!==t.rawResult)return t.rawResult;if(void 0!==t.result)return t.result;if(void 0!==t.details)return t.details}}function asToolParams(e){if(e&&"object"==typeof e&&!Array.isArray(e))return e}const summarizeObservedToolError=e=>{if(null==e)return;if("string"==typeof e)return e.slice(0,180);if("object"!=typeof e)return String(e).slice(0,180);const t=e;for(const e of["error","message","blockReason","details","text"]){const r=t[e];if("string"==typeof r&&r.trim())return r.slice(0,180);if(isPlainRecord(r)&&"string"==typeof r.message&&r.message.trim())return r.message.slice(0,180)}try{const t=JSON.stringify(e);return t?t.slice(0,180):void 0}catch{return}};export function createImReplySink(e){const t=e.startedAtMs??Date.now();let r=!1;const n=new Map,s=new Set,o={text:""};let a="",i="",l=!1,d=!1;const u=new Set;let m;const c={receivedSnapshotCount:0,streamingPublishCount:0,terminalPublishCount:0},g=[];let p;const h=new Map,f=new Map,v=[],y=[],b=new Map,I=new Map;let _=0,S=1;const x=(e,t={})=>({schema_version:1,seq:e,...t}),$=new Set,q=new Set,w=t=>{t!==o.text&&(t.startsWith(o.text)?e.stream.appendBody(t.slice(o.text.length)):e.stream.setBody(t),o.text=t)},T=e=>{void 0===e.publishTimer&&(e.publishTimer=setTimeout(()=>{e.publishTimer=void 0,le("body_preview_flush",()=>{m===e&&(e=>{o.text!==e.targetBody&&(w(e.targetBody),e.streamingPublishCount+=1)})(e)})},200))},k=e=>{const t=m;t?(void 0!==t.publishTimer&&(clearTimeout(t.publishTimer),t.publishTimer=void 0),t.targetBody=e,o.text!==e&&(w(e),t.terminalPublishCount+=1),c.receivedSnapshotCount+=t.receivedSnapshotCount,c.streamingPublishCount+=t.streamingPublishCount,c.terminalPublishCount+=t.terminalPublishCount,m=void 0):w(e)},P=t=>{if(void 0!==t.partIndex)return;const r=_,n=S;e.stream.addPart(toMessagePart({type:"text",text:t.text,state:"done",_seq:n,data:x(n)})),t.partIndex=r,_+=1,S+=1},E=()=>{if(!d){d=!0;for(const e of g)P(e)}},C=e=>{const t={text:e};g.push(t),d&&P(t)},R=(t,r)=>{for(const n of t){const t=I.get(n.url);if(t){const r=mergeSearchSource(t,n);if(r.title===t.title&&r.snippet===t.snippet)continue;const s={...r,partIndex:t.partIndex,displaySeq:t.displaySeq,toolUseId:t.toolUseId};e.stream.replacePart(t.partIndex,toMessagePart({type:"source",url:s.url,...s.title?{title:s.title}:{},...s.snippet?{snippet:s.snippet}:{},tool_use_id:s.toolUseId,_seq:s.displaySeq,data:x(s.displaySeq)})),I.set(n.url,s);continue}const s={...n,partIndex:_,displaySeq:S,toolUseId:r};e.stream.addPart(toMessagePart({type:"source",url:n.url,...n.title?{title:n.title}:{},...n.snippet?{snippet:n.snippet}:{},tool_use_id:r,_seq:s.displaySeq,data:x(s.displaySeq)})),I.set(n.url,s),_+=1,S+=1,oe.source+=1}},M=(e,t,r,n)=>toMessagePart({type:"thinking",text:t,state:r,_seq:e.displaySeq,_started_at_ms:e.startedAtMs,...void 0!==n?{_duration_ms:n}:{},data:x(e.displaySeq,{started_at_ms:e.startedAtMs,...void 0!==n?{duration_ms:n}:{}})}),O=t=>{void 0===t.publishTimer&&(t.publishTimer=setTimeout(()=>{t.publishTimer=void 0,le("reasoning_snapshot_flush",()=>{p===t&&(t=>{t.publishedText!==t.text&&(e.stream.replacePart(t.partIndex,M(t,t.text,"streaming")),t.publishedText=t.text,t.streamingPublishCount+=1)})(t)})},200))},A=()=>{const r=p;if(!r)return;void 0!==r.publishTimer&&(clearTimeout(r.publishTimer),r.publishTimer=void 0);const n=Math.max(0,Math.round(performance.now()-r.startedAtMonotonicMs));e.stream.replacePart(r.partIndex,M(r,r.text,"done",n)),p=void 0,logChatLatency(e.logger,"claw.reasoning.settled",e.requestId,t,{reasoning_duration_ms:n,reasoning_chars:r.text.length,reasoning_snapshot_count:r.receivedSnapshotCount,reasoning_streaming_publish_count:r.streamingPublishCount,reasoning_coalesced_snapshot_count:Math.max(0,r.receivedSnapshotCount-r.streamingPublishCount),reasoning_publish_interval_ms:200})},N=e=>{const t=v.indexOf(e);t>=0&&v.splice(t,1)},U=e=>{const t=e?v.filter(t=>h.get(t)?.name===e):v;return 1===t.length?t[0]:void 0},j=e=>{const t=y.map((e,t)=>({hint:e,index:t})).filter(({hint:t})=>!e||t.name===e);if(1!==t.length)return;const[{hint:r,index:n}]=t;return y.splice(n,1),r},L=(e,t)=>{if(f.set(e,t),e===t)return;const r=b.get(e);if(!r)return;const n=z(t);Q(n,r),b.delete(e);const s=h.get(t);s&&(X(s,n),b.delete(t))},B=e=>f.get(e)??e,F=e=>null!=e&&("object"!=typeof e||(Array.isArray(e)?e.length>0:Object.keys(e).length>0)),z=e=>{let t=b.get(e);return t||(t={},b.set(e,t)),t},D=(e,t)=>{if(!e?.length&&!t?.length)return;const r=[],n=new Map;for(const s of[...e??[],...t??[]]){const e=n.get(s.url);void 0===e?(n.set(s.url,r.length),r.push(s)):r[e]=mergeSearchSource(r[e],s)}return r},Q=(e,t)=>{e.name??=t.name,e.arguments??=t.arguments,t.toolStartObserved&&(e.toolStartObserved=!0),t.itemEventObserved&&(e.itemEventObserved=!0),t.progress?.length&&(e.progress=[...e.progress??[],...t.progress]),e.sources=D(e.sources,t.sources)},W=(t,r,n)=>{const s="tool"===t.name&&"tool"!==r?r:t.name,o=!F(t.arguments)&&F(n)?n:t.arguments;s===t.name&&o===t.arguments||(e.stream.replacePart(t.partIndex,toMessagePart({type:"tool_use",id:t.id,name:s,arguments:o,state:t.state,_seq:t.displaySeq,data:x(t.displaySeq)})),t.name=s,t.arguments=o)},J=(t,r,n,s)=>{const o=h.get(t);if(o)return W(o,r,n),s&&!v.includes(t)&&"streaming"===o.state&&v.push(t),o;E();const a=b.get(t),i="tool"!==r?r:a?.name&&"tool"!==a.name?a.name:r,l=F(n)?n:a?.arguments??n,d=((t,r,n)=>{const s=_,o=S;return e.stream.addPart(toMessagePart({type:"tool_use",id:t,name:r,arguments:n,state:"streaming",_seq:o,data:x(o)})),_+=1,S+=1,{partIndex:s,displaySeq:o}})(t,i,l),u={id:t,name:i,arguments:l,partIndex:d.partIndex,displaySeq:d.displaySeq,state:"streaming",itemEventObserved:!0===a?.itemEventObserved,toolStartObserved:!0===a?.toolStartObserved};return h.set(t,u),(s||u.toolStartObserved||u.itemEventObserved)&&(v.includes(t)||"streaming"!==u.state||v.push(t)),a&&X(u,a),b.delete(t),u},H=(e,t)=>{const r=(e=>{const t=f.get(e);return t?h.get(t):h.get(e)})(e);if(r)return void 0===t.name&&void 0===t.arguments||W(r,t.name??r.name,t.arguments??r.arguments),t.toolStartObserved&&(r.toolStartObserved=!0),t.itemEventObserved&&(r.itemEventObserved=!0),(t.pending||t.toolStartObserved||t.itemEventObserved)&&!v.includes(r.id)&&"streaming"===r.state&&v.push(r.id),r;const n=z(e);void 0!==t.name&&(n.name=t.name),void 0!==t.arguments&&(n.arguments=t.arguments),t.toolStartObserved&&(n.toolStartObserved=!0),t.itemEventObserved&&(n.itemEventObserved=!0)},K=t=>{"done"!==t.state&&(e.stream.replacePart(t.partIndex,toMessagePart({type:"tool_use",id:t.id,name:t.name,arguments:t.arguments,state:"done",_seq:t.displaySeq,data:x(t.displaySeq)})),t.state="done")},G=e=>{if(null===e||"object"!=typeof e)return JSON.stringify(e)??String(e);if(Array.isArray(e))return`[${e.map(G).join(",")}]`;return`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${G(t)}`).join(",")}}`},V=(t,r,n)=>{const s=`${n?"1":"0"}:${G(r)}`;if(t.progressSignature===s)return;const o=toMessagePart({type:"custom",kind:"tool_progress",data:{tool_use_id:t.id,content:r,...n?{is_error:!0}:{}}});if(void 0===t.progressPartIndex){const r=_;return e.stream.addPart(o),t.progressPartIndex=r,t.progressSignature=s,void(_+=1)}e.stream.replacePart(t.progressPartIndex,o),t.progressSignature=s},X=(e,t)=>{if(t.progress?.length){for(const r of t.progress)V(e,r.content,r.isError);K(e),N(e.id)}t.sources?.length&&R(t.sources,e.id)},Y=e=>[...new Set([e.mediaUrl,...e.mediaUrls??[]].filter(e=>isNonEmptyString(e)).map(e=>e.trim()).filter(Boolean))],Z=(e,t=[])=>{const r=[...new Set([...Y(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.":""},ee=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},te=e=>{$.add(e),e.finally(()=>{$.delete(e)})},re=(t,r)=>{if(t.durableUploadFilesEmitted)return;e.logger.info?.(`[im-sink] schedule tool artifact enrichment requestId=${e.requestId} toolUseId=${t.id} name=${t.name}`);const n=pickRawResultFromPayload(r),s=(async()=>{let s=[];try{s=await resolveToolArtifactLinks({toolCallId:t.id,toolName:t.name,rawResult:n,rawText:"string"==typeof r.text?r.text:void 0,params:asToolParams(t.arguments),cwd:sessionWorkspaceDir(e.sessionKey),payloadMediaUrls:Y(r)})}catch(r){const n=r instanceof Error?r.message:String(r);return void e.logger.warn?.(`[im-sink] resolveToolArtifactLinks failed requestId=${e.requestId} toolUseId=${t.id} error=${n}`)}0!==s.length?(e.logger.info?.(`[im-sink] tool artifact enrichment resolved ${s.length} link(s) requestId=${e.requestId} toolUseId=${t.id}`),await new Promise(n=>{e.callbackQueue.enqueueSync(()=>{try{if(e.abortSignal.aborted||e.stream.isTerminated)return;const n=s.map(e=>e.uri);V(t,Z(r,n),!0===r.isError),((t,r,n)=>{0===r.length||t.durableUploadFilesEmitted||(t.durableUploadFilesEmitted=!0,e.stream.appendToolResult(t.id,r.map(e=>({type:"resource_link",uri:e.uri,name:e.name,...e.mimeType?{mimeType:e.mimeType}:{}})),n),_+=1,ee(r))})(t,s,!0===r.isError)}catch(r){const n=r instanceof Error?r.message:String(r);e.logger.warn?.(`[im-sink] tool artifact enrichment apply failed requestId=${e.requestId} toolUseId=${t.id} error=${n}`)}finally{n()}})})):e.logger.debug?.(`[im-sink] tool artifact enrichment found no links requestId=${e.requestId} toolUseId=${t.id} name=${t.name}`)})().catch(r=>{const n=r instanceof Error?r.message:String(r);e.logger.warn?.(`[im-sink] tool artifact enrichment failed requestId=${e.requestId} toolUseId=${t.id} error=${n}`)});te(s)},ne=(e,t,r)=>{const n=f.get(e);if(n)return H(n,{name:t,arguments:r});const s=H(e,{name:t,arguments:r});if(s)return s;const o=U(t);if(o)return L(e,o),H(o,{name:t,arguments:r});H(e,{name:t,arguments:r})},se=(e,t)=>{const r=f.get(e);if(r)return H(r,{name:t,itemEventObserved:!0,pending:!0});const n=H(e,{name:t,itemEventObserved:!0,pending:!0});if(n)return n;const s=(e=>{const t=v.filter(t=>{const r=h.get(t);return!(void 0===r||e&&r.name!==e||r.itemEventObserved)});return 1===t.length?t[0]:void 0})(t);if(s)return L(e,s),H(s,{name:t,itemEventObserved:!0,pending:!0});const o=j(t);H(e,{name:t,arguments:o?.arguments,itemEventObserved:!0,pending:!0})},oe={tool:0,block:0,final:0,source:0};let ae,ie=!1;const le=(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):!ie||(e.logger.debug?.(`[im-sink] ${t} ignored after mark_complete requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`),!1))(t))try{r()}catch(r){const n=r instanceof Error?r.message:String(r);e.logger.warn?.(`[im-sink] ${t} mapping failed requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId} error=${n}`)}})};return{dispatcher:{sendToolResult:t=>(le("tool_progress",()=>{const r=resolveRuntimeToolCallId(t),n=resolveRuntimeToolName(t),s=resolveRuntimeToolArguments(t),o=Z(t),a=!0===t.isError;let i;if(r){if(i=ne(r,n,s),!i){const e=z(r);return n&&(e.name=n),F(s)&&(e.arguments=s),e.progress=[...e.progress??[],{content:o,isError:a}],void(oe.tool+=1)}}else{const t=n?U(n):U();if(!t)return j(n),void e.logger.debug?.(`[im-sink] unattributed tool progress ignored requestId=${e.requestId} channel=${e.channelId} tool=${n??"unknown"} pending=${v.length}`);i=H(t,{name:n,arguments:s})}i&&(oe.tool+=1,V(i,o,a),K(i),N(i.id),re(i,t))}),!0),sendBlockReply:e=>(le("block_reply",()=>{oe.block+=1,isNonEmptyString(e.text)&&(ae=!0!==e.isError?void 0:e.text)}),!0),sendFinalReply:t=>(le("final_reply",()=>{var r;(oe.final+=1,!0!==t.isError)?((t=>{const r=Y(t).filter(e=>!q.has(e));if(0===r.length)return;for(const e of r)q.add(e);const n=(async()=>{let t=[];try{t=await resolveToolArtifactLinks({toolCallId:`final:${e.runId??e.requestId}`,toolName:"final_reply_media",payloadMediaUrls:r})}catch(t){for(const e of r)q.delete(e);return void e.logger.warn?.(`[im-sink] final media enrichment failed requestId=${e.requestId} error=${t instanceof Error?t.message:String(t)}`)}if(0!==t.length)await new Promise(r=>{e.callbackQueue.enqueueSync(()=>{try{if(e.abortSignal.aborted||e.stream.isTerminated)return;ee(t)}catch(t){e.logger.warn?.(`[im-sink] final media enrichment apply failed requestId=${e.requestId} error=${t instanceof Error?t.message:String(t)}`)}finally{r()}})});else for(const e of r)q.delete(e)})();te(n)})(t),isNonEmptyString(t.text)&&(ae=void 0,l||(r=t.text,i="",a+=r,k(a),C(r),l=!0))):ae=t.text}),!0),waitForIdle:async()=>{for(let t=0;t<16&&(await e.callbackQueue.waitForIdle(),0!==$.size);t++)await Promise.allSettled([...$]);await e.callbackQueue.waitForIdle();const t=takeFinalizeAttachments(e.sessionKey);t.length>0&&!e.abortSignal.aborted&&!e.stream.isTerminated&&ee(t)},getQueuedCounts:()=>({tool:oe.tool,block:oe.block,final:oe.final}),getAccumulatedBody:()=>o.text,getTerminalErrorText:()=>ae,markComplete:r=>{A(),(y.length>0||b.size>0)&&e.logger.debug?.(`[im-sink] dropping uncommitted lifecycle tool signals requestId=${e.requestId} legacy_hints=${y.length} buffered=${b.size}`),i="",k(a),c.receivedSnapshotCount>0&&logChatLatency(e.logger,"claw.text_preview.settled",e.requestId,t,{text_preview_snapshot_count:c.receivedSnapshotCount,text_preview_streaming_publish_count:c.streamingPublishCount,text_preview_terminal_publish_count:c.terminalPublishCount,text_preview_coalesced_snapshot_count:Math.max(0,c.receivedSnapshotCount-c.streamingPublishCount-c.terminalPublishCount),text_preview_publish_interval_ms:200});for(const t of h.values())try{"success"===r&&isUploadArtifactToolName(t.name)&&!t.durableUploadFilesEmitted&&re(t,{toolCallId:t.id,toolName:t.name}),"success"===r&&K(t),N(t.id)}catch(r){const n=r instanceof Error?r.message:String(r);e.logger.warn?.(`[im-sink] tool finalization failed requestId=${e.requestId} toolUseId=${t.id} error=${n}`)}y.length=0,b.clear(),ie=!0}},replyOptions:{...e.runId?{runId:e.runId}:{},abortSignal:e.abortSignal,disableBlockStreaming:!0,onAgentRunStart:r=>{e.onAgentRunStart?.(r),logChatLatency(e.logger,"claw.runtime.run_started",e.requestId,t),e.logger.info?.(`[im-sink] run_start requestId=${e.requestId} runId=${r} channel=${e.channelId} in_reply_to=${e.inboundMessageId} origin=${e.origin??"im"}`)},onPartialReply:n=>{le("partial",()=>{"string"==typeof n.text&&(!r&&n.text.length>0&&(r=!0,logChatLatency(e.logger,"claw.model.first_delta",e.requestId,t)),i=n.text,(e=>{const t=m;if(!t){if(o.text===e)return;return w(e),void(m={targetBody:e,receivedSnapshotCount:1,streamingPublishCount:1,terminalPublishCount:0})}t.targetBody!==e&&(t.targetBody=e,t.receivedSnapshotCount+=1,T(t))})(a+i))})},onReasoningStream:t=>{le("reasoning",()=>{if(!isNonEmptyString(t.text))return;const r=t.text,n=p??(t=>{E();const r={partIndex:_,displaySeq:S,text:t,publishedText:t,receivedSnapshotCount:1,streamingPublishCount:1,startedAtMs:Date.now(),startedAtMonotonicMs:performance.now()};return e.stream.addPart(M(r,t,"streaming")),_+=1,S+=1,p=r,r})(r);r!==n.text&&(n.text.startsWith(r)||(n.text=r,n.receivedSnapshotCount+=1,O(n)))})},onReasoningEnd:()=>{le("reasoning_end",()=>{A()})},onAssistantMessageStart:()=>{le("assistant_message_start",()=>{i="",l=!1,k(a),e.logger.debug?.(`[im-sink] assistant_message_start requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`)})},onToolStart:r=>{le("tool_start",()=>{const s="string"==typeof r.phase?r.phase:"start",o=resolveRuntimeToolName(r)??"tool",a=resolveRuntimeToolCallId(r),i=resolveRuntimeToolArguments(r);if("update"===s)return void(a&&H(B(a),{name:o,arguments:i,pending:!0}));if(a&&n.set(a,Date.now()),logChatLatency(e.logger,"claw.tool.start",e.requestId,t,{tool:o}),a){H(a,{name:o,arguments:i,toolStartObserved:!0,pending:!0});const e=U(o);return void(e&&e!==a&&!f.has(a)&&(L(a,e),H(e,{name:o,arguments:i,toolStartObserved:!0,pending:!0})))}const l=(d=o,v.map(e=>h.get(e)).filter(e=>void 0!==e&&(!d||e.name===d)&&e.itemEventObserved));var d;if(1===l.length)return void H(l[0].id,{name:o,arguments:i,toolStartObserved:!0,pending:!0});if(l.length>1)return void e.logger.debug?.(`[im-sink] ambiguous id-less tool start ignored requestId=${e.requestId} channel=${e.channelId} tool=${o} candidates=${l.length}`);const u=[...b.entries()].filter(([,e])=>!e.name||e.name===o||"tool"===e.name);1!==u.length?y.push({name:o,arguments:i}):H(u[0][0],{name:o,arguments:i,toolStartObserved:!0,pending:!0})})},onItemEvent:e=>{le("item_event",()=>{const t="string"==typeof e.kind?e.kind.toLowerCase():"";if(t&&"tool"!==t)return;const r="string"==typeof e.phase?e.phase.toLowerCase():"update",n=resolveRuntimeToolCallId(e)??("string"==typeof e.itemId&&e.itemId.trim()?e.itemId.trim():void 0),s=resolveRuntimeToolName(e)??("string"==typeof e.title&&e.title.trim()?e.title.trim():void 0);n&&s&&("update"!==r?se(n,s):H(B(n),{name:s,itemEventObserved:!0,pending:!0}))})}},commitAssistantMessage:e=>{le("assistant_message_commit",()=>{if(u.has(e.key))return;u.add(e.key),l=!0,ae=void 0,i="";const t=e.segments.filter(e=>"text"===e.type).map(e=>e.text).join("");a+=t,k(a);for(const t of e.segments)"text"!==t.type?J(t.id,t.name,t.arguments,!0):C(t.text)})},observeToolResult:r=>{le("tool_result_observation",()=>{const o=r.toolCallId.trim(),a=r.toolName.trim();if(!o||!a)return;if(!s.has(o)){s.add(o);const i=n.get(o);logChatLatency(e.logger,"claw.tool.result",e.requestId,t,{tool:a,tool_elapsed_ms:void 0===i?void 0:Math.max(0,Date.now()-i),outcome:r.isError?"error":"success",...r.isError?{error:summarizeObservedToolError(r.rawResult)??"error"}:{}})}const i=searchSourceProvider(r.rawResult)??"unknown";let l=0;try{const t=extractSearchSources({toolName:a,rawResult:r.rawResult,isError:r.isError});if(l=t.length,0===l)return;const n=ne(o,a);if(n)R(t,n.id);else{const e=z(B(o));e.name??=a,e.sources=D(e.sources,t)}e.logger.debug?.(`[im-sink] search source projection requestId=${e.requestId} tool=${a} provider=${i} source_count=${l}`)}catch{e.logger.warn?.(`[im-sink] search source projection ignored requestId=${e.requestId} tool=${a} provider=${i} source_count=${l}`)}})},getSourceCount:()=>oe.source}}
1
+ import{toMessagePart}from"../message-client-types.js";import{isUploadArtifactToolName,resolveToolArtifactLinks}from"../upload/tool-artifact-enrichment.js";import{sessionWorkspaceDir,takeFinalizeAttachments}from"../upload/delivery-ledger.js";import{resolveRuntimeToolArguments,resolveRuntimeToolCallId,resolveRuntimeToolName}from"./tool-envelope-metadata.js";import{extractSearchSources,mergeSearchSource,searchSourceProvider}from"./search-source-extractor.js";import{logChatLatency}from"../chat-latency.js";const STREAMING_SNAPSHOT_PUBLISH_INTERVAL_MS=200,isNonEmptyString=e=>"string"==typeof e&&e.length>0,isPlainRecord=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);function pickRawResultFromPayload(e){if(void 0!==e.rawResult)return e.rawResult;if(void 0!==e.result)return e.result;if(void 0!==e.details)return e.details;if(void 0!==e.toolResult)return e.toolResult;if(isPlainRecord(e.channelData)){const t=e.channelData;if(void 0!==t.rawResult)return t.rawResult;if(void 0!==t.result)return t.result;if(void 0!==t.details)return t.details}}function asToolParams(e){if(e&&"object"==typeof e&&!Array.isArray(e))return e}const summarizeObservedToolError=e=>{if(null==e)return;if("string"==typeof e)return e.slice(0,180);if("object"!=typeof e)return String(e).slice(0,180);const t=e;for(const e of["error","message","blockReason","details","text"]){const r=t[e];if("string"==typeof r&&r.trim())return r.slice(0,180);if(isPlainRecord(r)&&"string"==typeof r.message&&r.message.trim())return r.message.slice(0,180)}try{const t=JSON.stringify(e);return t?t.slice(0,180):void 0}catch{return}},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,n=new Set,o={text:""};let a="",i="",l=!1,d=!1;const u=new Set;let c;const m={receivedSnapshotCount:0,streamingPublishCount:0,terminalPublishCount:0},g=[];let p;const f=new Map,h=new Map,v=[],b=[],y=new Map,I=new Map;let _=0,S=1;const x=(e,t={})=>({schema_version:1,seq:e,...t}),k=new Set,$=new Set,q=t=>{t!==o.text&&(t.startsWith(o.text)?e.stream.appendBody(t.slice(o.text.length)):e.stream.setBody(t),o.text=t)},w=e=>{void 0===e.publishTimer&&(e.publishTimer=setTimeout(()=>{e.publishTimer=void 0,le("body_preview_flush",()=>{c===e&&(e=>{o.text!==e.targetBody&&(q(e.targetBody),e.streamingPublishCount+=1)})(e)})},200))},C=e=>{const t=c;t?(void 0!==t.publishTimer&&(clearTimeout(t.publishTimer),t.publishTimer=void 0),t.targetBody=e,o.text!==e&&(q(e),t.terminalPublishCount+=1),m.receivedSnapshotCount+=t.receivedSnapshotCount,m.streamingPublishCount+=t.streamingPublishCount,m.terminalPublishCount+=t.terminalPublishCount,c=void 0):q(e)},E=t=>{if(void 0!==t.partIndex)return;const r=_,s=S;e.stream.addPart(toMessagePart({type:"text",text:t.text,state:"done",_seq:s,data:x(s)})),t.partIndex=r,_+=1,S+=1},T=()=>{if(!d){d=!0;for(const e of g)E(e)}},P=e=>{const t={text:e};g.push(t),d&&E(t)},R=(t,r)=>{for(const s of t){const t=I.get(s.url);if(t){const r=mergeSearchSource(t,s);if(r.title===t.title&&r.snippet===t.snippet)continue;const n={...r,partIndex:t.partIndex,displaySeq:t.displaySeq,toolUseId:t.toolUseId};e.stream.replacePart(t.partIndex,toMessagePart({type:"source",url:n.url,...n.title?{title:n.title}:{},...n.snippet?{snippet:n.snippet}:{},tool_use_id:n.toolUseId,_seq:n.displaySeq,data:x(n.displaySeq)})),I.set(s.url,n);continue}const n={...s,partIndex:_,displaySeq:S,toolUseId:r};e.stream.addPart(toMessagePart({type:"source",url:s.url,...s.title?{title:s.title}:{},...s.snippet?{snippet:s.snippet}:{},tool_use_id:r,_seq:n.displaySeq,data:x(n.displaySeq)})),I.set(s.url,n),_+=1,S+=1,oe.source+=1}},M=(e,t,r,s)=>toMessagePart({type:"thinking",text:t,state:r,_seq:e.displaySeq,_started_at_ms:e.startedAtMs,...void 0!==s?{_duration_ms:s}:{},data:x(e.displaySeq,{started_at_ms:e.startedAtMs,...void 0!==s?{duration_ms:s}:{}})}),O=t=>{void 0===t.publishTimer&&(t.publishTimer=setTimeout(()=>{t.publishTimer=void 0,le("reasoning_snapshot_flush",()=>{p===t&&(t=>{t.publishedText!==t.text&&(e.stream.replacePart(t.partIndex,M(t,t.text,"streaming")),t.publishedText=t.text,t.streamingPublishCount+=1)})(t)})},200))},A=()=>{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,M(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})},F=e=>{const t=v.indexOf(e);t>=0&&v.splice(t,1)},N=e=>{const t=e?v.filter(t=>f.get(t)?.name===e):v;return 1===t.length?t[0]:void 0},U=e=>{const t=b.map((e,t)=>({hint:e,index:t})).filter(({hint:t})=>!e||t.name===e);if(1!==t.length)return;const[{hint:r,index:s}]=t;return b.splice(s,1),r},j=(e,t)=>{if(h.set(e,t),e===t)return;const r=y.get(e);if(!r)return;const s=z(t);Q(s,r),y.delete(e);const n=f.get(t);n&&(X(n,s),y.delete(t))},L=e=>h.get(e)??e,B=e=>null!=e&&("object"!=typeof e||(Array.isArray(e)?e.length>0:Object.keys(e).length>0)),z=e=>{let t=y.get(e);return t||(t={},y.set(e,t)),t},D=(e,t)=>{if(!e?.length&&!t?.length)return;const r=[],s=new Map;for(const n of[...e??[],...t??[]]){const e=s.get(n.url);void 0===e?(s.set(n.url,r.length),r.push(n)):r[e]=mergeSearchSource(r[e],n)}return r},Q=(e,t)=>{e.name??=t.name,e.arguments??=t.arguments,t.toolStartObserved&&(e.toolStartObserved=!0),t.itemEventObserved&&(e.itemEventObserved=!0),t.progress?.length&&(e.progress=[...e.progress??[],...t.progress]),e.observedResult??=t.observedResult,e.sources=D(e.sources,t.sources)},W=(t,r,s)=>{const n="tool"===t.name&&"tool"!==r?r:t.name,o=!B(t.arguments)&&B(s)?s:t.arguments;n===t.name&&o===t.arguments||(e.stream.replacePart(t.partIndex,toMessagePart({type:"tool_use",id:t.id,name:n,arguments:o,state:t.state,_seq:t.displaySeq,data:x(t.displaySeq)})),t.name=n,t.arguments=o)},J=(t,r,s,n)=>{const o=f.get(t);if(o)return W(o,r,s),n&&!v.includes(t)&&"streaming"===o.state&&v.push(t),o;T();const a=y.get(t),i="tool"!==r?r:a?.name&&"tool"!==a.name?a.name:r,l=B(s)?s:a?.arguments??s,d=((t,r,s)=>{const n=_,o=S;return e.stream.addPart(toMessagePart({type:"tool_use",id:t,name:r,arguments:s,state:"streaming",_seq:o,data:x(o)})),_+=1,S+=1,{partIndex:n,displaySeq:o}})(t,i,l),u={id:t,name:i,arguments:l,partIndex:d.partIndex,displaySeq:d.displaySeq,state:"streaming",itemEventObserved:!0===a?.itemEventObserved,toolStartObserved:!0===a?.toolStartObserved};return f.set(t,u),(n||u.toolStartObserved||u.itemEventObserved)&&(v.includes(t)||"streaming"!==u.state||v.push(t)),a&&X(u,a),y.delete(t),u},H=(e,t)=>{const r=(e=>{const t=h.get(e);return t?f.get(t):f.get(e)})(e);if(r)return void 0===t.name&&void 0===t.arguments||W(r,t.name??r.name,t.arguments??r.arguments),t.toolStartObserved&&(r.toolStartObserved=!0),t.itemEventObserved&&(r.itemEventObserved=!0),(t.pending||t.toolStartObserved||t.itemEventObserved)&&!v.includes(r.id)&&"streaming"===r.state&&v.push(r.id),r;const s=z(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)},K=t=>{"done"!==t.state&&(e.stream.replacePart(t.partIndex,toMessagePart({type:"tool_use",id:t.id,name:t.name,arguments:t.arguments,state:"done",_seq:t.displaySeq,data:x(t.displaySeq)})),t.state="done")},G=e=>{if(null===e||"object"!=typeof e)return JSON.stringify(e)??String(e);if(Array.isArray(e))return`[${e.map(G).join(",")}]`;return`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${G(t)}`).join(",")}}`},V=(t,r,s)=>{const n=`${s?"1":"0"}:${G(r)}`;if(t.progressSignature===n)return;const o=toMessagePart({type:"custom",kind:"tool_progress",data:{tool_use_id:t.id,content:r,...s?{is_error:!0}:{}}});if(void 0===t.progressPartIndex){const r=_;return e.stream.addPart(o),t.progressPartIndex=r,t.progressSignature=n,void(_+=1)}e.stream.replacePart(t.progressPartIndex,o),t.progressSignature=n},X=(e,t)=>{if(t.progress?.length)for(const r of t.progress)V(e,r.content,r.isError);t.observedResult&&(V(e,t.observedResult.content,t.observedResult.isError),e.observedResult=t.observedResult),(t.progress?.length||t.observedResult)&&(K(e),F(e.id)),t.sources?.length&&R(t.sources,e.id)},Y=e=>[...new Set([e.mediaUrl,...e.mediaUrls??[]].filter(e=>isNonEmptyString(e)).map(e=>e.trim()).filter(Boolean))],Z=(e,t=[])=>{const r=[...new Set([...Y(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.":""},ee=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},te=t=>{k.add(t);const r=()=>{k.delete(t)};e.onCallbackFailure?t.then(r,r):t.finally(r)},re=(t,r)=>{if(t.durableUploadFilesEmitted)return;e.logger.info?.(`[im-sink] schedule tool artifact enrichment requestId=${e.requestId} toolUseId=${t.id} name=${t.name}`);const s=pickRawResultFromPayload(r),n=(async()=>{let n=[];try{n=await resolveToolArtifactLinks({toolCallId:t.id,toolName:t.name,rawResult:s,rawText:"string"==typeof r.text?r.text:void 0,params:asToolParams(t.arguments),cwd:sessionWorkspaceDir(e.sessionKey),payloadMediaUrls:Y(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}0!==n.length?(e.logger.info?.(`[im-sink] tool artifact enrichment resolved ${n.length} link(s) requestId=${e.requestId} toolUseId=${t.id}`),await new Promise((s,o)=>{!1===e.callbackQueue.enqueueSync(()=>{try{if(e.abortSignal.aborted||e.stream.isTerminated)return;const s=n.map(e=>e.uri);t.artifactMediaUrls=s;const o=t.observedResult;V(t,Z(o?{text:o.content,isError:o.isError}:r,s),o?.isError??!0===r.isError),((t,r,s)=>{0===r.length||t.durableUploadFilesEmitted||(t.durableUploadFilesEmitted=!0,e.stream.appendToolResult(t.id,r.map(e=>({type:"resource_link",uri:e.uri,name:e.name,...e.mimeType?{mimeType:e.mimeType}:{}})),s),_+=1,ee(r))})(t,n,o?.isError??!0===r.isError)}catch(r){const s=r instanceof Error?r.message:String(r);e.logger.warn?.(`[im-sink] tool artifact enrichment apply failed requestId=${e.requestId} toolUseId=${t.id} error=${s}`),e.onCallbackFailure?.(r),e.onCallbackFailure&&o(r)}finally{s()}})&&e.onCallbackFailure&&e.callbackQueue.waitForIdle().then(s,o)})):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});te(n)},se=(e,t,r)=>{const s=h.get(e);if(s)return H(s,{name:t,arguments:r});const n=H(e,{name:t,arguments:r});if(n)return n;const o=N(t);if(o)return j(e,o),H(o,{name:t,arguments:r});H(e,{name:t,arguments:r})},ne=(e,t)=>{const r=h.get(e);if(r)return H(r,{name:t,itemEventObserved:!0,pending:!0});const s=H(e,{name:t,itemEventObserved:!0,pending:!0});if(s)return s;const n=(e=>{const t=v.filter(t=>{const r=f.get(t);return!(void 0===r||e&&r.name!==e||r.itemEventObserved)});return 1===t.length?t[0]:void 0})(t);if(n)return j(e,n),H(n,{name:t,itemEventObserved:!0,pending:!0});const o=U(t);H(e,{name:t,arguments:o?.arguments,itemEventObserved:!0,pending:!0})},oe={tool:0,block:0,final:0,source:0};let ae,ie=!1;const le=(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):!ie||(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)}})};return{dispatcher:{sendToolResult:t=>(le("tool_progress",()=>{const r=resolveRuntimeToolCallId(t),s=resolveRuntimeToolName(t),n=resolveRuntimeToolArguments(t),o=Z(t),a=!0===t.isError;let i;if(r){if(i=se(r,s,n),!i){const e=z(r);return s&&(e.name=s),B(n)&&(e.arguments=n),e.progress=[...e.progress??[],{content:o,isError:a}],void(oe.tool+=1)}}else{const t=s?N(s):N();if(!t)return U(s),void e.logger.debug?.(`[im-sink] unattributed tool progress ignored requestId=${e.requestId} channel=${e.channelId} tool=${s??"unknown"} pending=${v.length}`);i=H(t,{name:s,arguments:n})}i&&(oe.tool+=1,i.observedResult||V(i,o,a),K(i),F(i.id),re(i,t))}),!0),sendBlockReply:e=>(le("block_reply",()=>{oe.block+=1,isNonEmptyString(e.text)&&(ae=!0!==e.isError?void 0:e.text)}),!0),sendFinalReply:t=>(le("final_reply",()=>{var r;(oe.final+=1,!0!==t.isError)?((t=>{const r=Y(t).filter(e=>!$.has(e));if(0===r.length)return;for(const e of 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)$.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;ee(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)$.delete(e)})();te(s)})(t),isNonEmptyString(t.text)&&(ae=void 0,l||(r=t.text,i="",a+=r,C(a),P(r),l=!0))):ae=t.text}),!0),waitForIdle:async()=>{for(let t=0;(e.onCallbackFailure||t<16)&&(await e.callbackQueue.waitForIdle(),0!==k.size);t++)e.onCallbackFailure?await Promise.all([...k]):await Promise.allSettled([...k]);await e.callbackQueue.waitForIdle();const t=takeFinalizeAttachments(e.sessionKey);t.length>0&&!e.abortSignal.aborted&&!e.stream.isTerminated&&ee(t)},getQueuedCounts:()=>({tool:oe.tool,block:oe.block,final:oe.final}),getAccumulatedBody:()=>o.text,getTerminalErrorText:()=>ae,markComplete:r=>{A(),(b.length>0||y.size>0)&&e.logger.debug?.(`[im-sink] dropping uncommitted lifecycle tool signals requestId=${e.requestId} legacy_hints=${b.length} buffered=${y.size}`),i="",C(a),m.receivedSnapshotCount>0&&logChatLatency(e.logger,"claw.text_preview.settled",e.requestId,t,{text_preview_snapshot_count:m.receivedSnapshotCount,text_preview_streaming_publish_count:m.streamingPublishCount,text_preview_terminal_publish_count:m.terminalPublishCount,text_preview_coalesced_snapshot_count:Math.max(0,m.receivedSnapshotCount-m.streamingPublishCount-m.terminalPublishCount),text_preview_publish_interval_ms:200});for(const t of f.values())try{"success"===r&&isUploadArtifactToolName(t.name)&&!t.durableUploadFilesEmitted&&re(t,{toolCallId:t.id,toolName:t.name}),"success"===r&&K(t),F(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}`)}b.length=0,y.clear(),ie=!0}},replyOptions:{...e.runId?{runId:e.runId}:{},abortSignal:e.abortSignal,disableBlockStreaming:!0,onAgentRunStart:r=>{e.onAgentRunStart?.(r),logChatLatency(e.logger,"claw.runtime.run_started",e.requestId,t),e.logger.info?.(`[im-sink] run_start requestId=${e.requestId} runId=${r} channel=${e.channelId} in_reply_to=${e.inboundMessageId} origin=${e.origin??"im"}`)},onPartialReply:s=>{le("partial",()=>{"string"==typeof s.text&&(!r&&s.text.length>0&&(r=!0,logChatLatency(e.logger,"claw.model.first_delta",e.requestId,t)),i=s.text,(e=>{const t=c;if(!t){if(o.text===e)return;return q(e),void(c={targetBody:e,receivedSnapshotCount:1,streamingPublishCount:1,terminalPublishCount:0})}t.targetBody!==e&&(t.targetBody=e,t.receivedSnapshotCount+=1,w(t))})(a+i))})},onReasoningStream:t=>{le("reasoning",()=>{if(!isNonEmptyString(t.text))return;const r=t.text,s=p??(t=>{T();const r={partIndex:_,displaySeq:S,text:t,publishedText:t,receivedSnapshotCount:1,streamingPublishCount:1,startedAtMs:Date.now(),startedAtMonotonicMs:performance.now()};return e.stream.addPart(M(r,t,"streaming")),_+=1,S+=1,p=r,r})(r);r!==s.text&&(s.text.startsWith(r)||(s.text=r,s.receivedSnapshotCount+=1,O(s)))})},onReasoningEnd:()=>{le("reasoning_end",()=>{A()})},onAssistantMessageStart:()=>{le("assistant_message_start",()=>{i="",l=!1,C(a),e.logger.debug?.(`[im-sink] assistant_message_start requestId=${e.requestId} channel=${e.channelId} in_reply_to=${e.inboundMessageId}`)})},onToolStart:r=>{le("tool_start",()=>{const n="string"==typeof r.phase?r.phase:"start",o=resolveRuntimeToolName(r)??"tool",a=resolveRuntimeToolCallId(r),i=resolveRuntimeToolArguments(r);if("update"===n)return void(a&&H(L(a),{name:o,arguments:i,pending:!0}));if(a&&s.set(a,Date.now()),logChatLatency(e.logger,"claw.tool.start",e.requestId,t,{tool:o}),a){H(a,{name:o,arguments:i,toolStartObserved:!0,pending:!0});const e=N(o);return void(e&&e!==a&&!h.has(a)&&(j(a,e),H(e,{name:o,arguments:i,toolStartObserved:!0,pending:!0})))}const l=(d=o,v.map(e=>f.get(e)).filter(e=>void 0!==e&&(!d||e.name===d)&&e.itemEventObserved));var d;if(1===l.length)return void H(l[0].id,{name:o,arguments:i,toolStartObserved:!0,pending:!0});if(l.length>1)return void e.logger.debug?.(`[im-sink] ambiguous id-less tool start ignored requestId=${e.requestId} channel=${e.channelId} tool=${o} candidates=${l.length}`);const u=[...y.entries()].filter(([,e])=>!e.name||e.name===o||"tool"===e.name);1!==u.length?b.push({name:o,arguments:i}):H(u[0][0],{name:o,arguments:i,toolStartObserved:!0,pending:!0})})},onItemEvent:e=>{le("item_event",()=>{const t="string"==typeof e.kind?e.kind.toLowerCase():"";if(t&&"tool"!==t)return;const r="string"==typeof e.phase?e.phase.toLowerCase():"update",s=resolveRuntimeToolCallId(e)??("string"==typeof e.itemId&&e.itemId.trim()?e.itemId.trim():void 0),n=resolveRuntimeToolName(e)??("string"==typeof e.title&&e.title.trim()?e.title.trim():void 0);s&&n&&("update"!==r?ne(s,n):H(L(s),{name:n,itemEventObserved:!0,pending:!0}))})}},commitAssistantMessage:e=>{le("assistant_message_commit",()=>{if(u.has(e.key))return;u.add(e.key),l=!0,ae=void 0,i="";const t=e.segments.filter(e=>"text"===e.type).map(e=>e.text).join("");a+=t,C(a);for(const t of e.segments)"text"!==t.type?J(t.id,t.name,t.arguments,!0):P(t.text)})},observeToolResult:r=>{le("tool_result_observation",()=>{const o=r.toolCallId.trim(),a=r.toolName.trim();if(!o||!a)return;const i=!n.has(o);if(i){n.add(o);const i=s.get(o);logChatLatency(e.logger,"claw.tool.result",e.requestId,t,{tool:a,tool_elapsed_ms:void 0===i?void 0:Math.max(0,Date.now()-i),outcome:r.isError?"error":"success",...r.isError?{error:summarizeObservedToolError(r.rawResult)??"error"}:{}})}if(e.persistObservedToolResults&&i){const e=observedToolResultText(r.rawResult);if(void 0!==e){const t=se(o,a);if(t)V(t,Z({text:e,isError:r.isError},t.artifactMediaUrls),r.isError),t.observedResult={content:e,isError:r.isError},K(t),F(t.id);else{const t=z(L(o));t.name??=a,t.observedResult={content:e,isError:r.isError}}}}const l=searchSourceProvider(r.rawResult)??"unknown";let d=0;try{const t=extractSearchSources({toolName:a,rawResult:r.rawResult,isError:r.isError});if(d=t.length,0===d)return;const s=se(o,a);if(s)R(t,s.id);else{const e=z(L(o));e.name??=a,e.sources=D(e.sources,t)}e.logger.debug?.(`[im-sink] search source projection requestId=${e.requestId} tool=${a} provider=${l} source_count=${d}`)}catch{e.logger.warn?.(`[im-sink] search source projection ignored requestId=${e.requestId} tool=${a} provider=${l} source_count=${d}`)}})},getSourceCount:()=>oe.source}}
@@ -1 +1 @@
1
- export class MessageServiceConversationClearHttpAuthority{options;constructor(e){this.options=e}async currentGeneration(e){const t=await this.options.fetchAuthorized(new URL(`/api/v1/conversations/${encodeURIComponent(e)}`,this.options.messageServiceUrl)),n=await decodeRaw(t);if(!t.ok)throw new Error(`Message Service conversation read failed (${t.status})`);const r=record(n)&&record(n.data)?n.data:n,o=record(r)?r.historyGeneration??r.history_generation:void 0;if("string"!=typeof o||!/^(0|[1-9][0-9]*)$/.test(o))throw new Error("Message Service conversation generation is unavailable");return o}async prepare(e){return this.map(await this.post(e.conversationId,"prepare",e))}async markResetting(e){return this.map(await this.transition("resetting",e))}async markResetDone(e){return this.map(await this.transition("reset-done",e))}async commit(e){return this.map(await this.transition("commit",e))}async abortPrepared(e){return this.map(await this.transition("abort",e))}async get(e){const t=this.url(e.conversationId,`intents/${encodeURIComponent(e.intentId)}`),n=await this.options.fetchAuthorized(t);return this.map(await decode(n))}async transition(e,t){return await this.post(t.intent.conversationId,e,{intentId:t.intent.intentId,operationId:t.intent.operationId,requestMessageId:t.requestMessageId,conversationId:t.intent.conversationId,expectedVersion:t.intent.version,fence:t.fence,...t.reason?{reason:t.reason}:{},...t.runConvergence?{runConvergence:t.runConvergence}:{},...t.activeRunRegistrationId?{activeRunRegistrationId:t.activeRunRegistrationId}:{}})}async post(e,t,n){const r=await this.options.fetchAuthorized(this.url(e,t),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)});return await decode(r)}url(e,t){return new URL(`/api/v1/control/conversations/${encodeURIComponent(e)}/clear/${t}`,this.options.messageServiceUrl)}map(e){const t=e.clearIntent,n=e.receipt;if(!t||!n||e.conversationId!==t.conversationId||e.boundaryOffset!==t.boundaryOffset||n.operationId!==t.operationId||n.intentId!==t.intentId||n.conversationId!==t.conversationId||n.boundaryOffset!==t.boundaryOffset||n.fromGeneration!==t.fromGeneration||n.toGeneration!==t.toGeneration||n.status!==t.state||n.version!==t.version||!/^[0-9a-f]{64}$/.test(n.receiptHash))throw new Error("Message Service clear receipt/intent mismatch");if("prepared"!==t.state&&"aborted"!==t.state&&!n.runConvergence)throw new Error("Message Service clear receipt omitted runConvergence");return{intent:t,...n.runConvergence?{runConvergence:n.runConvergence}:{},...n.activeRunRegistrationId?{activeRunRegistrationId:n.activeRunRegistrationId}:{}}}}async function decode(e){const t=await decodeRaw(e);if(!e.ok)throw new Error(`Message Service clear authority failed (${e.status})`);return t}async function decodeRaw(e){try{return await e.json()}catch{return}}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}
1
+ import{RUNTIME_HASH_DOMAINS,validateClearResetConvergence,validateConversationClearIntent}from"@beeos-ai/beeos-types/runtime";import{HarnessProtocolError,RuntimeMessagePlane}from"@beeos-ai/cloud-harness-sdk";import{runtimeLeaseHttp}from"./message-service-runtime-authenticated-fetch.js";import{runtimeMessageHash}from"./runtime-message-channel-contract.js";import{RuntimeCommandError}from"./runtime-command-dispatcher.js";export class MessageServiceConversationClearHttpAuthority{options;requests=new Map;plane;constructor(e){this.options=e,this.plane=new RuntimeMessagePlane(runtimeLeaseHttp(e.messageServiceUrl,e.fetchAuthorized))}async prepare(e){const t={...e,requestHash:e.requestHash??"",requestMessageId:e.requestMessageId??e.fence.claimId},n=await this.post(t,"prepare");return this.requests.set(n.intent.intentId,t),n}async markResetting(e){return await this.post(this.binding(e),"resetting",{boundaryToken:e.intent.intentId,runConvergence:e.runConvergence,...e.activeRunRegistrationId?{activeRunRegistrationId:e.activeRunRegistrationId}:{}})}async markResetDone(e){return await this.transition(e,"reset_done")}async commit(e){const t=this.binding(e),n=await this.get({conversationId:e.intent.conversationId,intentId:e.intent.intentId});if("committed"===n.intent.state)return n;if("reset_done"!==n.intent.state||n.intent.version!==e.intent.version)throw unknown("clear commit requires the exact durable reset_done version");const r={cleared:!0,historyGeneration:n.intent.toGeneration,runConvergence:n.runConvergence},i=runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:"session/clear",result:r}),o={schemaVersion:1,operationId:e.intent.operationId,method:"session/clear",coreResultRef:`sha256:${i}`,coreResultHash:i},s=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,o),a={schemaVersion:1,operationId:e.intent.operationId,requestMessageId:e.requestMessageId,requestHash:t.requestHash,dispatchEpoch:e.fence.runtimeEpoch,method:"session/clear",effectRecord:o,effectRecordHash:s,committedAt:(new Date).toISOString()};return await this.post(t,"commit",{boundaryToken:n.intent.intentId,effectReceipt:a})}async abortPrepared(e){return await this.transition(e,"abort")}async get(e){const t=this.requests.get(e.intentId);if(!t||t.conversationId!==e.conversationId)throw unknown("clear durable read requires a prepared request binding");return await this.post(t,"reconcile",{boundaryToken:e.intentId})}async transition(e,t,n={}){return await this.post(this.binding(e),t,{boundaryToken:e.intent.intentId,...n})}binding(e){const t=this.requests.get(e.intent.intentId);if(!t||t.operationId!==e.intent.operationId||t.conversationId!==e.intent.conversationId||t.requestMessageId!==e.requestMessageId||e.fence.runtimeEpoch!==t.fence.runtimeEpoch)throw unknown("clear request binding mismatch or unavailable");return{...t,fence:e.fence}}async post(e,t,n={}){const r={schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,requestHash:e.requestHash,...this.options.runtimeLeaseCredential?{runtimeLeaseCredential:this.options.runtimeLeaseCredential}:{},...n};let i;try{i=await this.plane.historyBoundary({runtimeLeaseCredential:this.options.runtimeLeaseCredential??""},e.conversationId,t,r)}catch(e){if(e instanceof HarnessProtocolError)throw unknown(`Message Service clear authority failed (${e.status})`);throw e}if("string"==typeof i||void 0===i)throw new RuntimeCommandError("OUTCOME_UNKNOWN","Message Service clear receipt is not JSON");if(!record(i)||!record(i.intent))throw unknown("Message Service omitted canonical clear intent");const o=i.intent;if(!["intentId","operationId","conversationId","runtimeEpoch","createdAt","updatedAt"].every(e=>"string"==typeof o[e]&&o[e].length>0)||!["prepared","resetting","reset_done","committed","aborted"].includes(o.state)||!["fromGeneration","toGeneration","boundaryOffset","version"].every(e=>"string"==typeof o[e]&&/^\d+$/.test(o[e]))||void 0!==o.boundaryMessageId&&"string"!=typeof o.boundaryMessageId||!Number.isFinite(Date.parse(o.createdAt))||!Number.isFinite(Date.parse(o.updatedAt)))throw unknown("Message Service returned an incomplete canonical clear intent");const s=o;if(i.status!==s.state||i.conversationId!==s.conversationId||i.boundaryToken!==s.intentId||"string"!=typeof i.disposition||i.historyGeneration!==("committed"===s.state?s.toGeneration:s.fromGeneration)||i.boundaryOffset!==s.boundaryOffset)throw unknown("Message Service clear receipt summary disagrees with canonical intent");if(s.operationId!==e.operationId||s.conversationId!==e.conversationId||s.runtimeEpoch!==e.fence.runtimeEpoch||void 0!==n.boundaryToken&&s.intentId!==n.boundaryToken||validateConversationClearIntent(s).length)throw unknown("Message Service clear intent identity/fence mismatch");const a=i.runConvergence,c=i.activeRunRegistrationId;if(["resetting","reset_done","committed"].includes(s.state)&&!record(a))throw unknown("durable clear convergence receipt is missing");if(void 0!==a){if(!record(a)||!["no_active_run","already_terminal","terminal_observed"].includes(a.state)||!record(a.quiescence)||"verified"!==a.quiescence.state||"string"!=typeof a.quiescence.observedAt||"no_active_run"!==a.state&&("string"!=typeof a.runtimeRunId||0===a.runtimeRunId.length||!["completed","failed","cancelled"].includes(a.terminalState)||"string"!=typeof c||0===c.length)||"terminal_observed"===a.state&&(!record(a.abortObservation)||!["target_acknowledged","already_stopped","transport_unknown"].includes(a.abortObservation.state)||"transport_unknown"!==a.abortObservation.state&&(!Array.isArray(a.abortObservation.runIds)||!a.abortObservation.runIds.every(e=>"string"==typeof e))||"target_acknowledged"===a.abortObservation.state&&(!0!==a.abortObservation.aborted||!0!==a.abortObservation.targetRunAcknowledged)||"already_stopped"===a.abortObservation.state&&!1!==a.abortObservation.aborted)||"no_active_run"===a.state&&void 0!==c||validateClearResetConvergence(a,s.createdAt).length)throw unknown("durable clear convergence or active run registration is invalid")}else if(void 0!==c&&("string"!=typeof c||0===c.length))throw unknown("durable clear active run registration is invalid");return{intent:s,...void 0!==a?{runConvergence:a}:{},...void 0!==c?{activeRunRegistrationId:c}:{}}}}function unknown(e){return new RuntimeCommandError("OUTCOME_UNKNOWN",e)}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}
@@ -1 +1 @@
1
- import{validateClearResetConvergence,validateConversationClearIntent,validateConversationClearIntentReuse,canonicalizeJcs}from"@beeos-ai/beeos-types/runtime";export class MessageServiceConversationHistoryBoundary{deps;kind="message-service";preparedActiveRunRegistrationId;activeRunBinding;latestIntent;constructor(e){this.deps=e}async prepare(e){this.assertAttempt(e.operationId,e.runtimeEpoch);const t=await this.deps.authority.prepare({operationId:e.operationId,conversationId:e.conversationId,expectedGeneration:this.deps.expectedGeneration,fence:this.deps.fence});return this.assertState(t,{operationId:e.operationId,conversationId:e.conversationId}),this.rememberActiveRun(t),this.latestIntent=t.intent,t.intent}async markResetting(e,t){this.assertState({intent:e},{previous:e,requiredState:"prepared"});const n="no_active_run"===t.state?void 0:this.activeRunBinding?.activeRunRegistrationId??this.preparedActiveRunRegistrationId??await(this.deps.resolveActiveRunRegistrationId?.(t.runtimeRunId));if("no_active_run"!==t.state&&!n)throw new Error("active run registration authority is required before clear resetting");const r=await this.deps.authority.markResetting({intent:e,requestMessageId:this.deps.requestMessageId,fence:this.deps.fence,runConvergence:t,...n?{activeRunRegistrationId:n}:{}});return this.assertState(r,{previous:e,requiredState:"resetting",convergence:t}),this.rememberActiveRun(r),this.latestIntent=r.intent,r.intent}async loadRunConvergence(e){const t=await this.deps.authority.get({conversationId:e.conversationId,intentId:e.intentId});if(this.assertState(t,{previous:e}),this.rememberActiveRun(t),this.latestIntent=t.intent,!t.runConvergence)throw new Error("durable clear convergence receipt is missing");return this.assertConvergence(t.intent,t.runConvergence),t.runConvergence}async markResetDone(e){const t=await this.deps.authority.markResetDone({intent:e,requestMessageId:this.deps.requestMessageId,fence:this.deps.fence});if(this.assertState(t,{previous:e,requiredState:"reset_done"}),this.rememberActiveRun(t),this.latestIntent=t.intent,!t.runConvergence)throw new Error("reset_done receipt lost run convergence");return t.intent}async commit(e){const t=await this.deps.authority.commit({intent:e,requestMessageId:this.deps.requestMessageId,fence:this.deps.fence});if(this.assertState(t,{previous:e,requiredState:"committed"}),this.rememberActiveRun(t),this.latestIntent=t.intent,!t.runConvergence)throw new Error("committed receipt lost run convergence");return t.intent}async abortPrepared(e,t){if("prepared"!==e.state)throw new Error(`clear abort forbidden from ${e.state}`);const n=await this.deps.authority.abortPrepared({intent:e,requestMessageId:this.deps.requestMessageId,fence:this.deps.fence,reason:t});this.assertState(n,{previous:e,requiredState:"aborted"}),this.latestIntent=n.intent}committedIntentId(){if("committed"!==this.latestIntent?.state)throw new Error("conversation clear has no committed Message Service receipt");return this.latestIntent.intentId}assertAttempt(e,t){if(e!==this.deps.operationId||t!==this.deps.fence.runtimeEpoch)throw new Error("conversation clear attempt/fence mismatch")}rememberActiveRun(e){const t=e.runConvergence;if(!t){if(!e.activeRunRegistrationId)return;if(this.preparedActiveRunRegistrationId&&this.preparedActiveRunRegistrationId!==e.activeRunRegistrationId)throw new Error("conversation clear active run registration changed");return void(this.preparedActiveRunRegistrationId=e.activeRunRegistrationId)}if("no_active_run"===t.state){if(e.activeRunRegistrationId||this.activeRunBinding)throw new Error("no-active-run clear receipt carried an active run registration");return}if(!e.activeRunRegistrationId)throw new Error("durable clear convergence omitted active run registration");const n={activeRunRegistrationId:e.activeRunRegistrationId,runtimeRunId:t.runtimeRunId};if(this.preparedActiveRunRegistrationId&&this.preparedActiveRunRegistrationId!==n.activeRunRegistrationId)throw new Error("conversation clear active run registration changed");if(this.activeRunBinding&&(this.activeRunBinding.activeRunRegistrationId!==n.activeRunRegistrationId||this.activeRunBinding.runtimeRunId!==n.runtimeRunId))throw new Error("conversation clear active run binding changed");this.activeRunBinding=n}assertState(e,t){const n=validateConversationClearIntent(e.intent);if(n.length)throw new Error(`invalid clear intent: ${n.join(",")}`);if(e.intent.operationId!==(t.operationId??this.deps.operationId)||t.conversationId&&e.intent.conversationId!==t.conversationId||e.intent.runtimeEpoch!==this.deps.fence.runtimeEpoch||t.requiredState&&e.intent.state!==t.requiredState)throw new Error("conversation clear authority identity/state mismatch");if(t.previous){const n=validateConversationClearIntentReuse(t.previous,e.intent);if(n.length)throw new Error(`conversation clear boundary changed: ${n.join(",")}`);if(BigInt(e.intent.version)<BigInt(t.previous.version))throw new Error("conversation clear authority version regressed");if(t.requiredState&&e.intent.state!==t.previous.state&&BigInt(e.intent.version)!==BigInt(t.previous.version)+1n)throw new Error("conversation clear authority skipped a transition version")}if(t.convergence){if(!e.runConvergence||canonicalizeJcs(e.runConvergence)!==canonicalizeJcs(t.convergence))throw new Error("conversation clear authority changed the convergence receipt");this.assertConvergence(e.intent,e.runConvergence)}}assertConvergence(e,t){const n=validateClearResetConvergence(t,e.createdAt);if(n.length)throw new Error(`invalid durable clear convergence: ${n.join(",")}`)}}
1
+ import{validateClearResetConvergence,validateConversationClearIntent,validateConversationClearIntentReuse,canonicalizeJcs}from"@beeos-ai/beeos-types/runtime";export class MessageServiceConversationHistoryBoundary{deps;kind="message-service";preparedActiveRunRegistrationId;activeRunBinding;latestIntent;constructor(e){this.deps=e}async prepare(e){this.assertAttempt(e.operationId,e.runtimeEpoch);const t=await this.deps.authority.prepare({operationId:e.operationId,conversationId:e.conversationId,requestHash:this.deps.requestHash,requestMessageId:this.deps.requestMessageId,...this.deps.expectedGeneration?{expectedGeneration:this.deps.expectedGeneration}:{},fence:this.deps.fence});return this.assertState(t,{operationId:e.operationId,conversationId:e.conversationId}),this.rememberActiveRun(t),this.latestIntent=t.intent,t.intent}async markResetting(e,t){this.assertState({intent:e},{previous:e,requiredState:"prepared"});const n="no_active_run"===t.state?void 0:this.activeRunBinding?.activeRunRegistrationId??this.preparedActiveRunRegistrationId??await(this.deps.resolveActiveRunRegistrationId?.(t.runtimeRunId));if("no_active_run"!==t.state&&!n)throw new Error("active run registration authority is required before clear resetting");const r=await this.deps.authority.markResetting({intent:e,requestMessageId:this.deps.requestMessageId,fence:this.deps.fence,runConvergence:t,...n?{activeRunRegistrationId:n}:{}});return this.assertState(r,{previous:e,requiredState:"resetting",convergence:t}),this.rememberActiveRun(r),this.latestIntent=r.intent,r.intent}async loadRunConvergence(e){const t=await this.deps.authority.get({conversationId:e.conversationId,intentId:e.intentId});if(this.assertState(t,{previous:e}),this.rememberActiveRun(t),this.latestIntent=t.intent,!t.runConvergence)throw new Error("durable clear convergence receipt is missing");return this.assertConvergence(t.intent,t.runConvergence),t.runConvergence}async markResetDone(e){const t=await this.deps.authority.markResetDone({intent:e,requestMessageId:this.deps.requestMessageId,fence:this.deps.fence});if(this.assertState(t,{previous:e,requiredState:"reset_done"}),this.rememberActiveRun(t),this.latestIntent=t.intent,!t.runConvergence)throw new Error("reset_done receipt lost run convergence");return t.intent}async commit(e){const t=await this.deps.authority.commit({intent:e,requestMessageId:this.deps.requestMessageId,fence:this.deps.fence});if(this.assertState(t,{previous:e,requiredState:"committed"}),this.rememberActiveRun(t),this.latestIntent=t.intent,!t.runConvergence)throw new Error("committed receipt lost run convergence");return t.intent}async abortPrepared(e,t){if("prepared"!==e.state)throw new Error(`clear abort forbidden from ${e.state}`);const n=await this.deps.authority.abortPrepared({intent:e,requestMessageId:this.deps.requestMessageId,fence:this.deps.fence,reason:t});this.assertState(n,{previous:e,requiredState:"aborted"}),this.latestIntent=n.intent}committedIntentId(){if("committed"!==this.latestIntent?.state)throw new Error("conversation clear has no committed Message Service receipt");return this.latestIntent.intentId}assertAttempt(e,t){if(e!==this.deps.operationId||t!==this.deps.fence.runtimeEpoch)throw new Error("conversation clear attempt/fence mismatch")}rememberActiveRun(e){const t=e.runConvergence;if(!t){if(!e.activeRunRegistrationId)return;if(this.preparedActiveRunRegistrationId&&this.preparedActiveRunRegistrationId!==e.activeRunRegistrationId)throw new Error("conversation clear active run registration changed");return void(this.preparedActiveRunRegistrationId=e.activeRunRegistrationId)}if("no_active_run"===t.state){if(e.activeRunRegistrationId||this.activeRunBinding)throw new Error("no-active-run clear receipt carried an active run registration");return}if(!e.activeRunRegistrationId)throw new Error("durable clear convergence omitted active run registration");const n={activeRunRegistrationId:e.activeRunRegistrationId,runtimeRunId:t.runtimeRunId};if(this.preparedActiveRunRegistrationId&&this.preparedActiveRunRegistrationId!==n.activeRunRegistrationId)throw new Error("conversation clear active run registration changed");if(this.activeRunBinding&&(this.activeRunBinding.activeRunRegistrationId!==n.activeRunRegistrationId||this.activeRunBinding.runtimeRunId!==n.runtimeRunId))throw new Error("conversation clear active run binding changed");this.activeRunBinding=n}assertState(e,t){const n=validateConversationClearIntent(e.intent);if(n.length)throw new Error(`invalid clear intent: ${n.join(",")}`);if(e.intent.operationId!==(t.operationId??this.deps.operationId)||t.conversationId&&e.intent.conversationId!==t.conversationId||e.intent.runtimeEpoch!==this.deps.fence.runtimeEpoch||t.requiredState&&e.intent.state!==t.requiredState)throw new Error("conversation clear authority identity/state mismatch");if(t.previous){const n=validateConversationClearIntentReuse(t.previous,e.intent);if(n.length)throw new Error(`conversation clear boundary changed: ${n.join(",")}`);if(BigInt(e.intent.version)<BigInt(t.previous.version))throw new Error("conversation clear authority version regressed");if(t.requiredState&&e.intent.state!==t.previous.state&&BigInt(e.intent.version)!==BigInt(t.previous.version)+1n)throw new Error("conversation clear authority skipped a transition version")}if(t.convergence){if(!e.runConvergence||canonicalizeJcs(e.runConvergence)!==canonicalizeJcs(t.convergence))throw new Error("conversation clear authority changed the convergence receipt");this.assertConvergence(e.intent,e.runConvergence)}}assertConvergence(e,t){const n=validateClearResetConvergence(t,e.createdAt);if(n.length)throw new Error(`invalid durable clear convergence: ${n.join(",")}`)}}
@@ -1 +1 @@
1
- export class MessageServiceConversationRunBoundary{options;constructor(t){this.options=t}async start(t){const e=await this.post(t.conversationId,"start",t);if(isStartResult(e))return e;throw new Error("Message Service returned an invalid conversation run start result")}async finish(t){const e=await this.post(t.conversationId,"finish",t);if(isFinishResult(e))return e;throw new Error("Message Service returned an invalid conversation run finish result")}async post(t,e,s){const i="start"===e?this.options.startUrl(t):this.options.finishUrl(t),n=await this.options.fetchAuthorized(i,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)});if(!n.ok)throw new Error(`Message Service conversation run ${e} failed (${n.status})`);return await n.json()}}function isStartResult(t){if(!isRecord(t))return!1;if("registered"===t.status)return exactKeys(t,["status","activeRunRegistrationId","historyGeneration"])&&isString(t.activeRunRegistrationId)&&isDecimal(t.historyGeneration);if("rejected"!==t.status||!["HISTORY_GENERATION_MISMATCH","CONVERSATION_CLEARING","ACTIVE_RUN_CONFLICT"].includes(t.reason))return!1;const e=void 0===t.currentGeneration?["status","reason"]:["status","reason","currentGeneration"];return exactKeys(t,e)&&(void 0===t.currentGeneration||isDecimal(t.currentGeneration))}function isFinishResult(t){if(!isRecord(t))return!1;if("finished"===t.status||"idempotent"===t.status)return exactKeys(t,["status","activeRunRegistrationId"])&&isString(t.activeRunRegistrationId);if("rejected"!==t.status||!["ACTIVE_RUN_MISMATCH","HISTORY_GENERATION_MISMATCH","RUNTIME_EPOCH_MISMATCH"].includes(t.reason))return!1;const e=void 0===t.activeRunRegistrationId?["status","reason"]:["status","reason","activeRunRegistrationId"];return exactKeys(t,e)&&(void 0===t.activeRunRegistrationId||isString(t.activeRunRegistrationId))}const isRecord=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),isString=t=>"string"==typeof t&&t.length>0,isDecimal=t=>"string"==typeof t&&/^(0|[1-9][0-9]*)$/.test(t),exactKeys=(t,e)=>{const s=Object.keys(t).sort(),i=[...e].sort();return s.length===i.length&&s.every((t,e)=>t===i[e])};
1
+ export class MessageServiceConversationRunBoundary{options;constructor(t){this.options=t}async start(t){const s=await this.post("start",t);if(isStartResult(s))return s;throw new Error("Message Service returned an invalid conversation run start result")}async finish(t){const s=await this.post("finish",t);if(isFinishResult(s))return s;throw new Error("Message Service returned an invalid conversation run finish result")}async post(t,s){let e;if("transport"in this.options)e="start"===t?await this.options.transport.start(s):await this.options.transport.finish(s);else{const i="start"===t?this.options.startUrl(s.conversationId):this.options.finishUrl(s.conversationId);e=await this.options.fetchAuthorized(i,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)})}if(!e.ok)throw new Error(`Message Service conversation run ${t} failed (${e.status})`);return await e.json()}}function isStartResult(t){if(!isRecord(t))return!1;if("registered"===t.status)return exactKeys(t,["status","activeRunRegistrationId","historyGeneration"])&&isString(t.activeRunRegistrationId)&&isDecimal(t.historyGeneration);if("rejected"!==t.status||!["HISTORY_GENERATION_MISMATCH","CONVERSATION_CLEARING","ACTIVE_RUN_CONFLICT"].includes(t.reason))return!1;const s=void 0===t.currentGeneration?["status","reason"]:["status","reason","currentGeneration"];return exactKeys(t,s)&&(void 0===t.currentGeneration||isDecimal(t.currentGeneration))}function isFinishResult(t){if(!isRecord(t))return!1;if("finished"===t.status||"idempotent"===t.status)return exactKeys(t,["status","activeRunRegistrationId"])&&isString(t.activeRunRegistrationId);if("rejected"!==t.status||!["ACTIVE_RUN_MISMATCH","HISTORY_GENERATION_MISMATCH","RUNTIME_EPOCH_MISMATCH"].includes(t.reason))return!1;const s=void 0===t.activeRunRegistrationId?["status","reason"]:["status","reason","activeRunRegistrationId"];return exactKeys(t,s)&&(void 0===t.activeRunRegistrationId||isString(t.activeRunRegistrationId))}const isRecord=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),isString=t=>"string"==typeof t&&t.length>0,isDecimal=t=>"string"==typeof t&&/^(0|[1-9][0-9]*)$/.test(t),exactKeys=(t,s)=>{const e=Object.keys(t).sort(),i=[...s].sort();return e.length===i.length&&e.every((t,s)=>t===i[s])};
@@ -1 +1 @@
1
- export class MessageServiceCronDeliveryHttpAuthority{options;constructor(e){this.options=e}async deliver(e){const s=new URL(`/api/v1/runtime/conversations/${encodeURIComponent(e.conversationId)}/deliveries/cron`,this.options.messageServiceUrl),o=await this.options.fetchAuthorized(s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({schemaVersion:1,jobId:e.jobId,...e.runId?{runId:e.runId}:{},...void 0!==e.runAtMs?{runAtMs:e.runAtMs}:{},...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body,...e.status?{status:e.status}:{},runtimeLeaseCredential:e.runtimeLeaseCredential})}),r=await decodeRaw(o);if(!o.ok){const e=record(r)&&"string"==typeof r.message&&r.message?`: ${r.code??"error"}: ${r.message}`:"";throw new Error(`Message Service cron conversation delivery failed (${o.status})${e}`)}const t=record(r)&&record(r.data)?r.data:r;if(!record(t)||"delivered"!==t.status||"created"!==t.disposition&&"reused"!==t.disposition||t.conversationId!==e.conversationId||"string"!=typeof t.messageId||!t.messageId)throw new Error("Message Service cron conversation delivery receipt mismatch");return{status:"delivered",disposition:t.disposition,conversationId:e.conversationId,messageId:t.messageId}}}async function decodeRaw(e){try{return await e.json()}catch{return}}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}
1
+ import{HarnessProtocolError,RuntimeMessagePlane}from"@beeos-ai/cloud-harness-sdk";import{runtimeLeaseHttp}from"./message-service-runtime-authenticated-fetch.js";export class MessageServiceCronDeliveryHttpAuthority{options;plane;constructor(e){if(this.options=e,!e.scopedDeliveryKey)throw new Error("cron delivery requires X-Runtime-Delivery-Key");this.plane=new RuntimeMessagePlane(runtimeLeaseHttp(e.messageServiceUrl,e.fetchAuthorized))}async deliver(e){const r={schemaVersion:1,jobId:e.jobId,...e.runId?{runId:e.runId}:{},...void 0!==e.runAtMs?{runAtMs:e.runAtMs}:{},...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body,...e.status?{status:e.status}:{},runtimeLeaseCredential:e.runtimeLeaseCredential};let s;try{s=await this.plane.deliverCron({runtimeLeaseCredential:e.runtimeLeaseCredential,scopedDeliveryKey:this.options.scopedDeliveryKey},e.conversationId,r)}catch(e){if(e instanceof HarnessProtocolError)throw cronFailure(e);throw e}const t=record(s)&&record(s.data)?s.data:s;if(!record(t)||"delivered"!==t.status||"created"!==t.disposition&&"reused"!==t.disposition||t.conversationId!==e.conversationId||"string"!=typeof t.messageId||!t.messageId)throw new Error("Message Service cron conversation delivery receipt mismatch");return{status:"delivered",disposition:t.disposition,conversationId:e.conversationId,messageId:t.messageId}}}function cronFailure(e){const r=harnessDetail(e);return new Error(`Message Service cron conversation delivery failed (${e.status})${r}`)}function harnessDetail(e){let r;if(e.body)try{r=JSON.parse(e.body)}catch{r=void 0}return record(r)&&"string"==typeof r.message&&r.message?`: ${r.code??"error"}: ${r.message}`:""}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}
@@ -1 +1 @@
1
- const DEFAULT_FETCH_TIMEOUT_MS=8e3,DEFAULT_TRANSIENT_RETRY_BACKOFFS_MS=[200,500],TRANSIENT_STATUSES=new Set([502,503,504]);export class MessageServiceRuntimeAuthenticatedFetch{options;cached;inflight;constructor(e){this.options=e}async ready(){const e=await this.token();return{serviceUrl:this.serviceUrl(e),identityId:e.identityId}}async fetch(e,t={}){let i=await this.token(),r=await this.execute(e,t,i);return 401!==r.status||(this.cached?.token===i.token&&(this.cached=void 0),i=await this.token(),r=await this.execute(e,t,i)),r}async fetchRuntimeChannel(e,t,i={},r){const n=await this.token(),s="string"==typeof e?new URL(e):e,o=new URL(this.serviceUrl(n));if(s.origin!==o.origin)throw new Error("Message Service runtime authority cannot be sent to another origin");const a=new Headers(i.headers);a.set("authorization",`Bearer ${t.runtimeLeaseCredential}`),a.set("x-runtime-delivery-key",t.scopedDeliveryKey),t.executionGrant&&a.set("x-beeos-execution-grant",t.executionGrant);const c=await this.fetchResilient(s,{...i,headers:a,redirect:"error"},r);if(c.url&&new URL(c.url).origin!==o.origin)throw new Error("Message Service runtime response origin changed");return c}async token(){const e=Math.floor((this.options.now??Date.now)()/1e3),t=this.options.refreshSkewSeconds??15;return this.cached&&this.cached.expiresAt>e+t?this.cached:(this.inflight||(this.inflight=this.options.tokenProvider(this.options.identityHint??"").then(t=>{if(!t?.token||!t.identityId||!Number.isSafeInteger(t.expiresAt)||t.expiresAt<=e||!this.serviceUrl(t))throw new Error("Message Service runtime credential response is incomplete or expired");return this.cached=t,t}).finally(()=>{this.inflight=void 0})),await this.inflight)}serviceUrl(e){const t=this.options.configuredServiceUrl?.trim(),i=e.serviceUrl?.trim();if(!t&&!i)throw new Error("Message Service runtime URL is unavailable");const r=t?new URL(t):void 0,n=i?new URL(i):void 0;if(r&&n&&r.origin!==n.origin)throw new Error("Message Service configured and credential origins do not match");return(r??n).toString()}async execute(e,t,i){const r="string"==typeof e?new URL(e):e,n=new URL(this.serviceUrl(i));if(r.origin!==n.origin)throw new Error("Message Service runtime credential cannot be sent to another origin");const s=new Headers(t.headers);s.set("authorization",`Bearer ${i.token}`),s.set("sender-identity",i.identityId);const o=await this.fetchResilient(r,{...t,headers:s,redirect:"error"});if(o.url&&new URL(o.url).origin!==n.origin)throw new Error("Message Service authenticated response origin changed");return o}async fetchResilient(e,t,i){const r=this.options.fetcher??fetch,n=this.options.fetchTimeoutMs??8e3,s=this.options.transientRetryBackoffsMs??DEFAULT_TRANSIENT_RETRY_BACKOFFS_MS,o=i?.retryTransientStatus??!0,a=s.length+1;for(let i=1;i<=a;i++){const c=AbortSignal.timeout(n),h=t.signal?AbortSignal.any([t.signal,c]):c;let u;try{u=await r(e,{...t,signal:h})}catch(e){if(!isTransientTransportError(e)||i===a)throw i===a&&e instanceof Error&&(e.message=`${e.message} (Message Service runtime request failed after ${i} attempts)`),e;await delay(s[i-1]);continue}if(!o||!TRANSIENT_STATUSES.has(u.status))return u;if(i===a)throw new Error(`Message Service runtime request failed after ${i} attempts (last status ${u.status})`);await delay(s[i-1])}throw new Error("Message Service runtime request resilience loop exited without a result")}}function isTransientTransportError(e){return e instanceof TypeError||e instanceof DOMException&&("TimeoutError"===e.name||"AbortError"===e.name)}const delay=e=>new Promise(t=>setTimeout(t,e));
1
+ import{RuntimeLeaseHttp}from"@beeos-ai/cloud-harness-sdk";const DEFAULT_FETCH_TIMEOUT_MS=8e3,DEFAULT_TRANSIENT_RETRY_BACKOFFS_MS=[200,500],TRANSIENT_STATUSES=new Set([502,503,504]);export class MessageServiceRuntimeAuthenticatedFetch{options;cached;inflight;constructor(e){this.options=e}async ready(){const e=await this.token();return{serviceUrl:this.serviceUrl(e),identityId:e.identityId}}async fetch(e,t={}){let i=await this.token(),r=await this.execute(e,t,i);return 401!==r.status||(this.cached?.token===i.token&&(this.cached=void 0),i=await this.token(),r=await this.execute(e,t,i)),r}async fetchRuntimeChannel(e,t,i={},r){const n=await this.token(),s=new URL(this.serviceUrl(n)),o={runtimeLeaseCredential:t.runtimeLeaseCredential,...t.scopedDeliveryKey?{scopedDeliveryKey:t.scopedDeliveryKey}:{},...t.executionGrant?{executionGrant:t.executionGrant}:{}},a=new RuntimeLeaseHttp({origin:s.origin,fetch:(e,t)=>this.fetchBounded(e instanceof Request?e.url:e,t)});return await a.fetch(e,o,i,{retry:!0===r?.retryTransientStatus})}async fetchBounded(e,t={}){const i=await this.token(),r=new URL(e),n=new URL(this.serviceUrl(i));if(r.origin!==n.origin)throw new Error("Message Service runtime authority cannot be sent to another origin");const s=this.options.fetchTimeoutMs??8e3,o=AbortSignal.timeout(s),a=t.signal?AbortSignal.any([t.signal,o]):o,c=await(this.options.fetcher??fetch)(r,{...t,signal:a});if(c.url&&new URL(c.url).origin!==n.origin)throw new Error("Message Service runtime response origin changed");return c}async token(){const e=Math.floor((this.options.now??Date.now)()/1e3),t=this.options.refreshSkewSeconds??15;return this.cached&&this.cached.expiresAt>e+t?this.cached:(this.inflight||(this.inflight=this.options.tokenProvider(this.options.identityHint??"").then(t=>{if(!t?.token||!t.identityId||!Number.isSafeInteger(t.expiresAt)||t.expiresAt<=e||!this.serviceUrl(t))throw new Error("Message Service runtime credential response is incomplete or expired");return this.cached=t,t}).finally(()=>{this.inflight=void 0})),await this.inflight)}serviceUrl(e){const t=this.options.configuredServiceUrl?.trim(),i=e.serviceUrl?.trim();if(!t&&!i)throw new Error("Message Service runtime URL is unavailable");const r=t?new URL(t):void 0,n=i?new URL(i):void 0;if(r&&n&&r.origin!==n.origin)throw new Error("Message Service configured and credential origins do not match");return(r??n).toString()}async execute(e,t,i){const r="string"==typeof e?new URL(e):e,n=new URL(this.serviceUrl(i));if(r.origin!==n.origin)throw new Error("Message Service runtime credential cannot be sent to another origin");const s=new Headers(t.headers);s.set("authorization",`Bearer ${i.token}`),s.set("sender-identity",i.identityId);const o=await this.fetchResilient(r,{...t,headers:s,redirect:"error"});if(o.url&&new URL(o.url).origin!==n.origin)throw new Error("Message Service authenticated response origin changed");return o}async fetchResilient(e,t,i){const r=this.options.fetcher??fetch,n=this.options.fetchTimeoutMs??8e3,s=this.options.transientRetryBackoffsMs??DEFAULT_TRANSIENT_RETRY_BACKOFFS_MS,o=i?.retryTransientStatus??!0,a=s.length+1;for(let i=1;i<=a;i++){const c=AbortSignal.timeout(n),h=t.signal?AbortSignal.any([t.signal,c]):c;let u;try{u=await r(e,{...t,signal:h})}catch(e){if(!isTransientTransportError(e)||i===a)throw i===a&&e instanceof Error&&(e.message=`${e.message} (Message Service runtime request failed after ${i} attempts)`),e;await delay(s[i-1]);continue}if(!o||!TRANSIENT_STATUSES.has(u.status))return u;if(i===a)throw new Error(`Message Service runtime request failed after ${i} attempts (last status ${u.status})`);await delay(s[i-1])}throw new Error("Message Service runtime request resilience loop exited without a result")}}function isTransientTransportError(e){return e instanceof TypeError||e instanceof DOMException&&("TimeoutError"===e.name||"AbortError"===e.name)}const delay=e=>new Promise(t=>setTimeout(t,e));export function runtimeLeaseHttp(e,t){return new RuntimeLeaseHttp({origin:e,fetch:(e,i)=>t(e instanceof Request?e.url:e,i)})}export function fetchRuntimeLeaseAttempt(e,t={}){const i=AbortSignal.timeout(8e3),r=t.signal?AbortSignal.any([t.signal,i]):i;return fetch(e,{...t,signal:r})}
@@ -1 +1 @@
1
- import{RUNTIME_INTERNAL_API_V1_ROUTE_CONTRACTS}from"@beeos-ai/beeos-types/runtime";export class RuntimeClaimAuthorityProtocolError extends Error{constructor(e){super(e),this.name="RuntimeClaimAuthorityProtocolError"}}export class MessageServiceRuntimeClaimHttpAuthority{options;constructor(e){this.options=e}async claimNext(e){const t=await this.postJson(RUNTIME_INTERNAL_API_V1_ROUTE_CONTRACTS.claimNext.path,e);return assertClaimNextResult(t,e),t}async claimExact(e){const t=operationPath(RUNTIME_INTERNAL_API_V1_ROUTE_CONTRACTS.claimExact.path,e.operationId),r=await this.postJson(t,e);return assertClaimExactResult(r,e),r}async renewClaim(e){const t=operationPath(RUNTIME_INTERNAL_API_V1_ROUTE_CONTRACTS.claimRenew.path,e.operationId),r=await this.postJson(t,e);if(!r||!["renewed","fenced","expired","terminal"].includes(r.status))throw new RuntimeClaimAuthorityProtocolError("Message Service returned an invalid claim renew result");return r}async releaseClaim(e){const t=operationPath(RUNTIME_INTERNAL_API_V1_ROUTE_CONTRACTS.claimRelease.path,e.operationId),r=await this.options.fetchAuthorized(new URL(t,this.options.messageServiceUrl),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)});if(204!==r.status)throw new RuntimeClaimAuthorityProtocolError(`Message Service claim release failed (${r.status})`)}async postJson(e,t){const r=await this.options.fetchAuthorized(new URL(e,this.options.messageServiceUrl),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!r.ok)throw new RuntimeClaimAuthorityProtocolError(`Message Service claim authority failed (${r.status})`);return await r.json()}}function operationPath(e,t){return e.replace("{operationId}",encodeURIComponent(t))}function assertClaimNextResult(e,t){if(!e||!["claimed","empty","fenced"].includes(e.status))throw new RuntimeClaimAuthorityProtocolError("Message Service returned an invalid claim-next result");if("claimed"!==e.status)return;const r=e.request.payload.command;if(e.request.payload.instanceId!==t.instanceId||e.fence.handlerIdentity!==t.handlerIdentity||e.fence.runtimeEpoch!==t.runtimeEpoch||e.fence.journalStoreId!==t.journalStoreId||e.fence.journalGeneration!==t.journalGeneration||r.context.dispatchEpoch!==t.runtimeEpoch)throw new RuntimeClaimAuthorityProtocolError("Message Service claim-next result does not match the request lease binding")}function assertClaimExactResult(e,t){if(!e||!["claimed","already_claimed","fenced","epoch_handoff_required","terminal"].includes(e.status))throw new RuntimeClaimAuthorityProtocolError("Message Service returned an invalid exact-claim result");if("claimed"===e.status&&(e.request.operationId!==t.operationId||e.request.messageId!==t.requestMessageId||e.fence.handlerIdentity!==t.handlerIdentity||e.fence.runtimeEpoch!==t.runtimeEpoch||e.fence.journalStoreId!==t.journalStoreId||e.fence.journalGeneration!==t.journalGeneration))throw new RuntimeClaimAuthorityProtocolError("Message Service exact-claim result does not match the recovery request")}
1
+ import{HarnessProtocolError,RuntimeClaimClient}from"@beeos-ai/cloud-harness-sdk";import{runtimeLeaseHttp}from"./message-service-runtime-authenticated-fetch.js";export class RuntimeClaimAuthorityProtocolError extends Error{constructor(e){super(e),this.name="RuntimeClaimAuthorityProtocolError"}}export class MessageServiceRuntimeClaimHttpAuthority{claims;constructor(e){this.claims=new RuntimeClaimClient(runtimeLeaseHttp(e.messageServiceUrl,e.fetchAuthorized))}async claimNext(e){const t=await this.call("Message Service returned an invalid claim-next result",!1,()=>this.claims.claimNext(credential(e.runtimeLeaseCredential),e));return assertClaimNextResult(t,e),t}async claimExact(e){const t=await this.call("Message Service returned an invalid exact-claim result",!1,()=>this.claims.claimExact(credential(e.runtimeLeaseCredential),e));return assertClaimExactResult(t,e),t}async renewClaim(e){const t=await this.call("Message Service returned an invalid claim renew result",!1,()=>this.claims.renewClaim(credential(e.runtimeLeaseCredential),e));if(!t||!["renewed","fenced","expired","terminal"].includes(t.status))throw new RuntimeClaimAuthorityProtocolError("Message Service returned an invalid claim renew result");return t}async releaseClaim(e){await this.call("Message Service claim release failed",!0,()=>this.claims.releaseClaim(credential(e.runtimeLeaseCredential),e))}async call(e,t,r){try{return await r()}catch(r){if(!(r instanceof HarnessProtocolError))throw r;if(void 0!==r.status)throw new RuntimeClaimAuthorityProtocolError(t?`Message Service claim release failed (${r.status})`:`Message Service claim authority failed (${r.status})`);throw new RuntimeClaimAuthorityProtocolError(e)}}}function credential(e){return{runtimeLeaseCredential:e}}function assertClaimNextResult(e,t){if(!e||!["claimed","empty","fenced"].includes(e.status))throw new RuntimeClaimAuthorityProtocolError("Message Service returned an invalid claim-next result");if("claimed"!==e.status)return;const r=e.request.payload.command;if(e.request.payload.instanceId!==t.instanceId||e.fence.handlerIdentity!==t.handlerIdentity||e.fence.runtimeEpoch!==t.runtimeEpoch||e.fence.journalStoreId!==t.journalStoreId||e.fence.journalGeneration!==t.journalGeneration||r.context.dispatchEpoch!==t.runtimeEpoch)throw new RuntimeClaimAuthorityProtocolError("Message Service claim-next result does not match the request lease binding")}function assertClaimExactResult(e,t){if(!e||!["claimed","already_claimed","fenced","epoch_handoff_required","terminal"].includes(e.status))throw new RuntimeClaimAuthorityProtocolError("Message Service returned an invalid exact-claim result");if("claimed"===e.status&&(e.request.operationId!==t.operationId||e.request.messageId!==t.requestMessageId||e.fence.handlerIdentity!==t.handlerIdentity||e.fence.runtimeEpoch!==t.runtimeEpoch||e.fence.journalStoreId!==t.journalStoreId||e.fence.journalGeneration!==t.journalGeneration))throw new RuntimeClaimAuthorityProtocolError("Message Service exact-claim result does not match the recovery request")}
@@ -1 +1 @@
1
- import{RUNTIME_HASH_DOMAINS}from"@beeos-ai/beeos-types/runtime";import{runtimeMessageHash,semanticEqual,validateRuntimeCancelEnvelope,validateRuntimeRequestEnvelope}from"./runtime-message-channel-contract.js";export class RuntimeMessageChannelProtocolError extends Error{status;code;constructor(e,t,o){super(e),this.status=t,this.code=o,this.name="RuntimeMessageChannelProtocolError"}}export class MessageServiceRuntimeMessageChannel{options;constructor(e){if(this.options=e,!e.scopedDeliveryKey)throw new Error("Message runtime delivery credential is required")}async read(e){const t=await this.post("/api/v1/runtime/deliveries/read",e.lease,{schemaVersion:1,maxCount:e.maxCount,blockMs:e.blockMs},void 0,e.signal);if(!record(t)||"deliveries"!==t.status||!Array.isArray(t.deliveries)||t.deliveries.length>e.maxCount||!t.deliveries.every(isDelivery)||new Set(t.deliveries.map(e=>e.deliveryId)).size!==t.deliveries.length)throw new RuntimeMessageChannelProtocolError("Message Service returned invalid runtime deliveries");return t.deliveries}async renew(e){const t=await this.post("/api/v1/runtime/deliveries/renew",e.lease,{schemaVersion:1,deliveryIds:e.deliveryIds});if(!(record(t)&&"renewed"===t.status&&strings(t.renewed)&&strings(t.notPending)&&exactIdPartition(e.deliveryIds,t.renewed,t.notPending)))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid delivery renewal");return{renewed:t.renewed,notPending:t.notPending}}async acknowledge(e){const t=await this.post("/api/v1/runtime/deliveries/ack",e.lease,{schemaVersion:1,deliveryIds:e.deliveryIds});if(!record(t)||"acknowledged"!==t.status||!strings(t.deliveryIds)||!sameIds(t.deliveryIds,e.deliveryIds))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid delivery acknowledgement")}async history(e){const t=`/api/v1/runtime/operations/${encodeURIComponent(e.operationId)}/history`,o=await this.fetch(t,e.lease,{method:"GET"});if(404===o.status)return{status:"not_found"};if(410===o.status)return{status:"expired"};const r=await responseJson(o);if(!o.ok)throw protocolFailure(o,r,"runtime history read failed");if(!isHistory(r,e.operationId))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid operation history");return{status:"found",snapshot:r}}async append(e){const t=`/api/v1/runtime/operations/${encodeURIComponent(e.operationId)}/messages`,o=appendResult(await this.post(t,e.lease,{schemaVersion:1,type:e.type,payload:e.payload},e.executionGrant)),r="runtime_rpc_response"===e.type?e.payload.requestMessageId:void 0;if(o.message.channel_id!==e.operationId||o.message.type!==e.type||o.message.in_reply_to!==r||!semanticEqual(o.message.payload,e.payload))throw new RuntimeMessageChannelProtocolError("Message Service append response correlation mismatch");return o}async post(e,t,o,r,n){const i=await this.fetch(e,t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o),...n?{signal:n}:{}},r),s=await responseJson(i);if(!i.ok)throw protocolFailure(i,s,`runtime message-channel POST ${e} failed`);return s}async fetch(e,t,o,r){return await this.options.transport.fetchRuntimeChannel(new URL(e,this.options.serviceUrl),{runtimeLeaseCredential:t.runtimeLeaseCredential,scopedDeliveryKey:this.options.scopedDeliveryKey,...r?{executionGrant:r}:{}},o,{retryTransientStatus:!1})}}export function decodeRuntimeBrokerDelivery(e){if(!isDelivery(e))throw new RuntimeMessageChannelProtocolError("Message Service returned an invalid runtime delivery");return e}export function decodeRuntimeOperationHistory(e,t){if(!isHistory(e,t))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid operation history");return e}export function decodeRuntimeAppendMessage(e,t){if(!envelope(e))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid append result");const o="runtime_rpc_response"===t.type?t.payload.requestMessageId:void 0;if(e.channel_id!==t.operationId||e.type!==t.type||e.in_reply_to!==o||!semanticEqual(e.payload,t.payload))throw new RuntimeMessageChannelProtocolError("Message Service append response correlation mismatch");return e}function appendResult(e){if(!record(e)||"persisted"!==e.status||"created"!==e.disposition&&"reused"!==e.disposition||!envelope(e.message))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid append result");return{disposition:e.disposition,message:e.message}}function protocolFailure(e,t,o){const r=record(t)&&"string"==typeof t.code?t.code:void 0,n=record(t)&&"string"==typeof t.message?t.message:o;return new RuntimeMessageChannelProtocolError(`${n} (${e.status})`,e.status,r)}async function responseJson(e){try{return await e.json()}catch{return}}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function strings(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function sameIds(e,t){return e.length===t.length&&[...e].sort().every((e,o)=>e===[...t].sort()[o])}function exactIdPartition(e,...t){return new Set(e).size===e.length&&!t.some(e=>new Set(e).size!==e.length)&&sameIds(t.flat(),e)}function envelope(e){return!!record(e)&&("string"==typeof e.message_id&&Number.isInteger(e.offset)&&e.offset>=1&&"string"==typeof e.channel_id&&(void 0===e.in_reply_to||"string"==typeof e.in_reply_to)&&["runtime_rpc_request","runtime_operation_started","runtime_operation_progress","runtime_effect_committed","runtime_projection_pending","runtime_projection_synced","runtime_projection_blocked","runtime_rpc_response","runtime_operation_cancel_requested"].includes(e.type)&&record(e.payload)&&"string"==typeof e.publisher_id&&"string"==typeof e.idempotency_key&&"string"==typeof e.created_at&&"completed"===e.state)}function isDelivery(e){return record(e)&&"string"==typeof e.deliveryId&&"boolean"==typeof e.redelivered&&Number.isInteger(e.idleMs)&&e.idleMs>=0&&envelope(e.message)&&(void 0===e.executionGrant||"string"==typeof e.executionGrant&&/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e.executionGrant))&&["runtime_rpc_request","runtime_operation_cancel_requested"].includes(e.message.type)}function isHistory(e,t){if(!record(e))return!1;if(!(1===e.schemaVersion&&"string"==typeof e.operationId&&e.operationId===t&&"string"==typeof e.requestMessageId&&"string"==typeof e.requestHash&&["queued","running","runtime_committed","projection_pending","projection_blocked","succeeded","failed","cancelled","expired","outcome_unknown"].includes(e.status)&&["","committed"].includes(e.effectState)&&"boolean"==typeof e.terminal&&["none","final_message","deadline"].includes(e.terminalSource)&&"boolean"==typeof e.cancelRequested&&["","reserved","pending","synced","blocked","not_applicable"].includes(e.projectionState)&&Array.isArray(e.messages)&&e.messages.every(envelope)&&Number.isInteger(e.latestOffset)&&!(e.latestOffset<1)))return!1;const o=validateRuntimeRequestEnvelope(e.request);if(!o.ok||e.request.channel_id!==e.operationId||o.envelope.payload.operationId!==e.operationId||o.envelope.payload.requestMessageId!==e.requestMessageId||o.envelope.payload.requestHash!==e.requestHash)return!1;const r=o.envelope.payload;if(void 0!==e.started&&!correlatedEnvelope(e.started,"runtime_operation_started",r,["schemaVersion","operationId","requestMessageId","requestHash","executionGrantHash","handlerIdentity","dispatchEpoch","method","executionMode","claimedAt"]))return!1;if(void 0!==e.latestProgress&&!correlatedEnvelope(e.latestProgress,"runtime_operation_progress",r,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","phase","progress"]))return!1;if(!(void 0===e.effectCommitted||correlatedEnvelope(e.effectCommitted,"runtime_effect_committed",r,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","effectRecord","effectRecordHash","committedAt"])&&validEffectCommitted(e.effectCommitted.payload,r)))return!1;if(void 0!==e.projectionPending&&!correlatedEnvelope(e.projectionPending,"runtime_projection_pending",r,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","revision"]))return!1;if(void 0!==e.projectionSynced&&!correlatedEnvelope(e.projectionSynced,"runtime_projection_synced",r,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","revision"]))return!1;if(void 0!==e.projectionBlocked&&!correlatedEnvelope(e.projectionBlocked,"runtime_projection_blocked",r,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","revision","errorCode"]))return!1;if(void 0!==e.cancel){const t=validateRuntimeCancelEnvelope(e.cancel);if(!t.ok||!sameCorrelation(t.envelope,r))return!1}if(void 0!==e.final&&!correlatedEnvelope(e.final,"runtime_rpc_response",r,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","outcome","response","completedAt"]))return!1;const n=e.messages;if(0===n.length||e.latestOffset!==n.length||n.some((t,o)=>t.offset!==o+1||t.channel_id!==e.operationId)||!semanticEqual(n[0],e.request)||!historyMessagesMatchSummaries(n,e)||!projectionStateMatches(e))return!1;if(e.terminal!==("none"!==e.terminalSource)||"committed"===e.effectState!=(void 0!==e.effectCommitted)||void 0!==e.effectCommitted&&void 0===e.started||"queued"===e.status&&(void 0!==e.started||void 0!==e.effectCommitted)||["running","runtime_committed","projection_pending","projection_blocked"].includes(e.status)&&void 0===e.started)return!1;if("none"===e.terminalSource)return void 0===e.final&&["queued","running","runtime_committed","projection_pending","projection_blocked"].includes(e.status);if("deadline"===e.terminalSource)return void 0===e.final&&(void 0===e.started?"expired"===e.status:"outcome_unknown"===e.status);if(!envelope(e.final))return!1;const i=e.final.payload.outcome,s="succeeded"===i?"succeeded":"cancelled"===i?"cancelled":"expired"===i?"expired":"outcome_unknown"===i?"outcome_unknown":"projection_blocked"===i?"projection_blocked":"failed"===i?"failed":void 0;return e.status===s}function validEffectCommitted(e,t){const o=e.effectRecord;return!!(record(o)&&1===o.schemaVersion&&o.operationId===t.operationId&&o.method===t.method&&"string"==typeof o.coreResultRef&&0!==o.coreResultRef.length&&"string"==typeof o.coreResultHash&&/^[0-9a-f]{64}$/.test(o.coreResultHash)&&(void 0===o.projectionRevision||"string"==typeof o.projectionRevision&&/^(0|[1-9][0-9]*)$/.test(o.projectionRevision))&&"string"==typeof e.effectRecordHash&&/^[0-9a-f]{64}$/.test(e.effectRecordHash)&&runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,o)===e.effectRecordHash&&"string"==typeof e.committedAt&&Number.isFinite(Date.parse(e.committedAt)))}function projectionStateMatches(e){const t=e.effectCommitted?.payload?.effectRecord?.projectionRevision,o="deadline"===e.terminalSource,r=e=>record(e)&&record(e.payload)&&e.payload.revision===t;switch(e.projectionState){case"":return void 0===e.effectCommitted&&void 0===e.projectionPending&&void 0===e.projectionSynced&&void 0===e.projectionBlocked&&(o||["queued","running","succeeded","failed","cancelled","expired","outcome_unknown"].includes(e.status));case"not_applicable":return void 0!==e.effectCommitted&&void 0===t&&void 0===e.projectionPending&&void 0===e.projectionSynced&&void 0===e.projectionBlocked&&(o||["runtime_committed","succeeded","outcome_unknown"].includes(e.status));case"reserved":return void 0!==e.effectCommitted&&void 0!==t&&void 0===e.projectionPending&&void 0===e.projectionSynced&&void 0===e.projectionBlocked&&(o||"runtime_committed"===e.status);case"pending":return void 0!==t&&r(e.projectionPending)&&void 0===e.projectionSynced&&void 0===e.projectionBlocked&&(o||"projection_pending"===e.status);case"synced":return void 0!==t&&r(e.projectionPending)&&r(e.projectionSynced)&&void 0===e.projectionBlocked&&(o||["runtime_committed","succeeded"].includes(e.status));case"blocked":return void 0!==t&&r(e.projectionPending)&&void 0===e.projectionSynced&&r(e.projectionBlocked)&&(o||"projection_blocked"===e.status);default:return!1}}function historyMessagesMatchSummaries(e,t){const o=t=>e.filter(e=>e.type===t),r=(e,t,r=1)=>{const n=o(e);return n.length<=r&&(void 0===t?0===n.length:n.length>0&&semanticEqual(t,n.at(-1)))};if(!(r("runtime_rpc_request",t.request)&&r("runtime_operation_started",t.started)&&r("runtime_effect_committed",t.effectCommitted)&&r("runtime_projection_pending",t.projectionPending)&&r("runtime_projection_synced",t.projectionSynced)&&r("runtime_projection_blocked",t.projectionBlocked)&&r("runtime_operation_cancel_requested",t.cancel)&&r("runtime_rpc_response",t.final)))return!1;const n=o("runtime_operation_progress");if(void 0===t.latestProgress?0!==n.length:0===n.length||!semanticEqual(t.latestProgress,n.at(-1)))return!1;if(t.cancelRequested!==(void 0!==t.cancel))return!1;const i=e.findIndex(e=>"runtime_rpc_response"===e.type);return-1===i||i===e.length-1}function correlatedEnvelope(e,t,o,r){const n="runtime_rpc_response"===t?o.requestMessageId:void 0;return!(!envelope(e)||e.type!==t||!hasKeys(e.payload,r)||e.in_reply_to!==n)&&sameCorrelation(e,o)}function sameCorrelation(e,t){const o=e.payload;return e.channel_id===t.operationId&&o.operationId===t.operationId&&o.requestMessageId===t.requestMessageId&&o.requestHash===t.requestHash&&o.dispatchEpoch===t.dispatchEpoch&&o.method===t.method}function hasKeys(e,t){return t.every(t=>void 0!==e[t])}
1
+ import{RUNTIME_HASH_DOMAINS}from"@beeos-ai/beeos-types/runtime";import{HarnessProtocolError,RuntimeMessagePlane}from"@beeos-ai/cloud-harness-sdk";import{isDeepStrictEqual}from"node:util";import{runtimeLeaseHttp}from"./message-service-runtime-authenticated-fetch.js";import{retainedVerifiedNativePrompt}from"./native-prompt-authority.js";import{runtimeMessageHash,semanticEqual,validateRuntimeCancelEnvelope,validateRuntimeRequestEnvelope}from"./runtime-message-channel-contract.js";export class RuntimeMessageChannelProtocolError extends Error{status;code;constructor(e,t,r){super(e),this.status=t,this.code=r,this.name="RuntimeMessageChannelProtocolError"}}export class MessageServiceRuntimeMessageChannel{options;plane;constructor(e){if(this.options=e,!e.scopedDeliveryKey)throw new Error("Message runtime delivery credential is required");this.plane=new RuntimeMessagePlane(runtimeLeaseHttp(e.serviceUrl,(t,r)=>e.transport.fetchBounded(t,r)))}async read(e){const t=await this.invoke(()=>this.plane.readDeliveries(this.credential(e.lease),{maxCount:e.maxCount,blockMs:e.blockMs},e.signal),"runtime delivery read failed");if(!record(t)||"deliveries"!==t.status||!Array.isArray(t.deliveries)||t.deliveries.length>e.maxCount||!t.deliveries.every(isDelivery)||new Set(t.deliveries.map(e=>e.deliveryId)).size!==t.deliveries.length)throw new RuntimeMessageChannelProtocolError("Message Service returned invalid runtime deliveries");return t.deliveries}async renew(e){const t=await this.invoke(()=>this.plane.renewDeliveries(this.credential(e.lease),e.deliveryIds),"runtime delivery renew failed");if(!(record(t)&&"renewed"===t.status&&strings(t.renewed)&&strings(t.notPending)&&exactIdPartition(e.deliveryIds,t.renewed,t.notPending)))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid delivery renewal");return{renewed:t.renewed,notPending:t.notPending}}async acknowledge(e){const t=await this.invoke(()=>this.plane.ackDeliveries(this.credential(e.lease),e.deliveryIds),"runtime delivery ack failed");if(!record(t)||"acknowledged"!==t.status||!strings(t.deliveryIds)||!sameIds(t.deliveryIds,e.deliveryIds))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid delivery acknowledgement")}async history(e){let t;try{t=await this.plane.operationHistory(this.credential(e.lease),e.operationId)}catch(e){if(!(e instanceof HarnessProtocolError))throw e;if(404===e.status)return{status:"not_found"};if(410===e.status)return{status:"expired"};throw harnessFailure(e,"runtime history read failed")}if(!isHistory(t,e.operationId))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid operation history");return{status:"found",snapshot:t}}async append(e){const t=appendResult(await this.invoke(()=>this.plane.appendOperationMessage(this.credential(e.lease,e.executionGrant),e.operationId,{type:e.type,payload:e.payload}),"runtime message-channel append failed")),r="runtime_rpc_response"===e.type?e.payload.requestMessageId:void 0;if(t.message.channel_id!==e.operationId||t.message.type!==e.type||t.message.in_reply_to!==r||!semanticEqual(t.message.payload,e.payload))throw new RuntimeMessageChannelProtocolError("Message Service append response correlation mismatch");return t}credential(e,t){return{runtimeLeaseCredential:e.runtimeLeaseCredential,scopedDeliveryKey:this.options.scopedDeliveryKey,...t?{executionGrant:t}:{}}}async invoke(e,t){try{return await e()}catch(e){if(e instanceof HarnessProtocolError)throw harnessFailure(e,t);throw e}}}export function decodeRuntimeBrokerDelivery(e){if(!isDelivery(e))throw new RuntimeMessageChannelProtocolError("Message Service returned an invalid runtime delivery");return e}export function decodeRuntimeOperationHistory(e,t){if(!isHistory(e,t))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid operation history");return e}export function decodeNativePromptOperationHistory(e,t){const r=retainedVerifiedNativePrompt(t);if(!(r&&record(e)&&envelope(e.request)&&"runtime_rpc_request"===e.request.type&&void 0===e.request.in_reply_to&&e.request.message_id===r.request.requestMessageId&&e.request.channel_id===r.request.operationId&&isDeepStrictEqual(e.request.payload,r.request)&&isHistory(e,r.request.operationId,e.request)))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid native prompt operation history");if(void 0!==e.runBoundary&&!validNativeRunObservation(e.runBoundary,r))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid native run audit");return e}function validNativeRunObservation(e,t){if(!record(e))return!1;const r=t.params,n=t.request,o=["operationId","requestMessageId","requestHash","conversationId","runtimeRunId","taskRequestMessageId","replyMessageId","historyGeneration"];if(o.some(t=>"string"!=typeof e[t])||Object.keys(e).some(e=>![...o,"registration","finishedReceipt"].includes(e))||e.operationId!==n.operationId||e.requestMessageId!==n.requestMessageId||e.requestHash!==n.requestHash||e.conversationId!==r.conversationId||e.runtimeRunId!==r.runtimeRunId||e.taskRequestMessageId!==r.taskRequestMessageId||e.replyMessageId!==r.replyMessageId||e.historyGeneration!==t.historyGeneration)return!1;const i=(e,t)=>{if(!record(e)||e.activeRunRegistrationId!==r.taskId||!["active","finished"].includes(e.state)||t&&"finished"!==e.state||Object.keys(e).some(e=>!["activeRunRegistrationId","state","terminalState","source","replyState","replyStopReason","replyUpdatedAt","finishedAt"].includes(e)))return!1;if("active"===e.state)return 2===Object.keys(e).length;const n=e=>"string"==typeof e&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(e)&&Date.parse(e)>0,o=e=>{const t=e.match(/\.(\d{1,9})/)?.[1]??"";return 1000000n*BigInt(Date.parse(e))+BigInt(t.padEnd(9,"0").slice(3))};return["completed","failed","cancelled"].includes(e.terminalState)&&["runtime","recovery"].includes(e.source)&&["completed","failed","refused","cancelled"].includes(e.replyState)&&("refused"===e.replyState?"failed":e.replyState)===e.terminalState&&"string"==typeof e.replyStopReason&&e.replyStopReason.length>0&&n(e.replyUpdatedAt)&&n(e.finishedAt)&&o(e.finishedAt)>=o(e.replyUpdatedAt)};return(void 0===e.registration||i(e.registration,!1))&&(void 0===e.finishedReceipt||i(e.finishedReceipt,!0))}export function decodeRuntimeAppendMessage(e,t){if(!envelope(e))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid append result");const r="runtime_rpc_response"===t.type?t.payload.requestMessageId:void 0;if(e.channel_id!==t.operationId||e.type!==t.type||e.in_reply_to!==r||!semanticEqual(e.payload,t.payload))throw new RuntimeMessageChannelProtocolError("Message Service append response correlation mismatch");return e}function appendResult(e){if(!record(e)||"persisted"!==e.status||"created"!==e.disposition&&"reused"!==e.disposition||!envelope(e.message))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid append result");return{disposition:e.disposition,message:e.message}}function harnessFailure(e,t){let r;if(e.body)try{r=JSON.parse(e.body)}catch{r=void 0}const n=record(r)&&"string"==typeof r.code?r.code:void 0,o=record(r)&&"string"==typeof r.message?r.message:t;return new RuntimeMessageChannelProtocolError(`${o} (${e.status})`,e.status,n)}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function strings(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function sameIds(e,t){return e.length===t.length&&[...e].sort().every((e,r)=>e===[...t].sort()[r])}function exactIdPartition(e,...t){return new Set(e).size===e.length&&!t.some(e=>new Set(e).size!==e.length)&&sameIds(t.flat(),e)}function envelope(e){return!!record(e)&&("string"==typeof e.message_id&&Number.isInteger(e.offset)&&e.offset>=1&&"string"==typeof e.channel_id&&(void 0===e.in_reply_to||"string"==typeof e.in_reply_to)&&["runtime_rpc_request","runtime_operation_started","runtime_operation_progress","runtime_effect_committed","runtime_projection_pending","runtime_projection_synced","runtime_projection_blocked","runtime_rpc_response","runtime_operation_cancel_requested"].includes(e.type)&&record(e.payload)&&"string"==typeof e.publisher_id&&"string"==typeof e.idempotency_key&&"string"==typeof e.created_at&&"completed"===e.state)}function isDelivery(e){return record(e)&&"string"==typeof e.deliveryId&&"boolean"==typeof e.redelivered&&Number.isInteger(e.idleMs)&&e.idleMs>=0&&envelope(e.message)&&(void 0===e.executionGrant||"string"==typeof e.executionGrant&&/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e.executionGrant))&&["runtime_rpc_request","runtime_operation_cancel_requested"].includes(e.message.type)}function isHistory(e,t,r){if(!record(e))return!1;if(!(1===e.schemaVersion&&"string"==typeof e.operationId&&e.operationId===t&&"string"==typeof e.requestMessageId&&"string"==typeof e.requestHash&&["queued","running","runtime_committed","projection_pending","projection_blocked","succeeded","failed","cancelled","expired","outcome_unknown"].includes(e.status)&&["","committed"].includes(e.effectState)&&"boolean"==typeof e.terminal&&["none","final_message","deadline"].includes(e.terminalSource)&&"boolean"==typeof e.cancelRequested&&["","reserved","pending","synced","blocked","not_applicable"].includes(e.projectionState)&&Array.isArray(e.messages)&&e.messages.every(envelope)&&Number.isInteger(e.latestOffset)&&!(e.latestOffset<1)))return!1;const n=r?{ok:!0,envelope:r}:validateRuntimeRequestEnvelope(e.request);if(!n.ok||e.request.channel_id!==e.operationId||n.envelope.payload.operationId!==e.operationId||n.envelope.payload.requestMessageId!==e.requestMessageId||n.envelope.payload.requestHash!==e.requestHash)return!1;const o=n.envelope.payload;if(void 0!==e.started&&!correlatedEnvelope(e.started,"runtime_operation_started",o,["schemaVersion","operationId","requestMessageId","requestHash","executionGrantHash","handlerIdentity","dispatchEpoch","method","executionMode","claimedAt"]))return!1;if(void 0!==e.latestProgress&&!correlatedEnvelope(e.latestProgress,"runtime_operation_progress",o,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","phase","progress"]))return!1;if(!(void 0===e.effectCommitted||correlatedEnvelope(e.effectCommitted,"runtime_effect_committed",o,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","effectRecord","effectRecordHash","committedAt"])&&validEffectCommitted(e.effectCommitted.payload,o)))return!1;if(void 0!==e.projectionPending&&!correlatedEnvelope(e.projectionPending,"runtime_projection_pending",o,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","revision"]))return!1;if(void 0!==e.projectionSynced&&!correlatedEnvelope(e.projectionSynced,"runtime_projection_synced",o,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","revision"]))return!1;if(void 0!==e.projectionBlocked&&!correlatedEnvelope(e.projectionBlocked,"runtime_projection_blocked",o,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","revision","errorCode"]))return!1;if(void 0!==e.cancel){const t=validateRuntimeCancelEnvelope(e.cancel);if(!t.ok||!sameCorrelation(t.envelope,o))return!1}if(void 0!==e.final&&!correlatedEnvelope(e.final,"runtime_rpc_response",o,["schemaVersion","operationId","requestMessageId","requestHash","dispatchEpoch","method","outcome","response","completedAt"]))return!1;const i=e.messages;if(0===i.length||e.latestOffset!==i.length||i.some((t,r)=>t.offset!==r+1||t.channel_id!==e.operationId)||!semanticEqual(i[0],e.request)||!historyMessagesMatchSummaries(i,e)||!projectionStateMatches(e))return!1;if(e.terminal!==("none"!==e.terminalSource)||"committed"===e.effectState!=(void 0!==e.effectCommitted)||void 0!==e.effectCommitted&&void 0===e.started||"queued"===e.status&&(void 0!==e.started||void 0!==e.effectCommitted)||["running","runtime_committed","projection_pending","projection_blocked"].includes(e.status)&&void 0===e.started)return!1;if("none"===e.terminalSource)return void 0===e.final&&["queued","running","runtime_committed","projection_pending","projection_blocked"].includes(e.status);if("deadline"===e.terminalSource)return void 0===e.final&&(void 0===e.started?"expired"===e.status:"outcome_unknown"===e.status);if(!envelope(e.final))return!1;const s=e.final.payload.outcome,a="succeeded"===s?"succeeded":"cancelled"===s?"cancelled":"expired"===s?"expired":"outcome_unknown"===s?"outcome_unknown":"projection_blocked"===s?"projection_blocked":"failed"===s?"failed":void 0;return e.status===a}function validEffectCommitted(e,t){const r=e.effectRecord;return!!(record(r)&&1===r.schemaVersion&&r.operationId===t.operationId&&r.method===t.method&&"string"==typeof r.coreResultRef&&0!==r.coreResultRef.length&&"string"==typeof r.coreResultHash&&/^[0-9a-f]{64}$/.test(r.coreResultHash)&&(void 0===r.projectionRevision||"string"==typeof r.projectionRevision&&/^(0|[1-9][0-9]*)$/.test(r.projectionRevision))&&"string"==typeof e.effectRecordHash&&/^[0-9a-f]{64}$/.test(e.effectRecordHash)&&runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,r)===e.effectRecordHash&&"string"==typeof e.committedAt&&Number.isFinite(Date.parse(e.committedAt)))}function projectionStateMatches(e){const t=e.effectCommitted?.payload?.effectRecord?.projectionRevision,r="deadline"===e.terminalSource,n=e=>record(e)&&record(e.payload)&&e.payload.revision===t;switch(e.projectionState){case"":return void 0===e.effectCommitted&&void 0===e.projectionPending&&void 0===e.projectionSynced&&void 0===e.projectionBlocked&&(r||["queued","running","succeeded","failed","cancelled","expired","outcome_unknown"].includes(e.status));case"not_applicable":return void 0!==e.effectCommitted&&void 0===t&&void 0===e.projectionPending&&void 0===e.projectionSynced&&void 0===e.projectionBlocked&&(r||["runtime_committed","succeeded","outcome_unknown"].includes(e.status));case"reserved":return void 0!==e.effectCommitted&&void 0!==t&&void 0===e.projectionPending&&void 0===e.projectionSynced&&void 0===e.projectionBlocked&&(r||"runtime_committed"===e.status);case"pending":return void 0!==t&&n(e.projectionPending)&&void 0===e.projectionSynced&&void 0===e.projectionBlocked&&(r||"projection_pending"===e.status);case"synced":return void 0!==t&&n(e.projectionPending)&&n(e.projectionSynced)&&void 0===e.projectionBlocked&&(r||["runtime_committed","succeeded"].includes(e.status));case"blocked":return void 0!==t&&n(e.projectionPending)&&void 0===e.projectionSynced&&n(e.projectionBlocked)&&(r||"projection_blocked"===e.status);default:return!1}}function historyMessagesMatchSummaries(e,t){const r=t=>e.filter(e=>e.type===t),n=(e,t,n=1)=>{const o=r(e);return o.length<=n&&(void 0===t?0===o.length:o.length>0&&semanticEqual(t,o.at(-1)))};if(!(n("runtime_rpc_request",t.request)&&n("runtime_operation_started",t.started)&&n("runtime_effect_committed",t.effectCommitted)&&n("runtime_projection_pending",t.projectionPending)&&n("runtime_projection_synced",t.projectionSynced)&&n("runtime_projection_blocked",t.projectionBlocked)&&n("runtime_operation_cancel_requested",t.cancel)&&n("runtime_rpc_response",t.final)))return!1;const o=r("runtime_operation_progress");if(void 0===t.latestProgress?0!==o.length:0===o.length||!semanticEqual(t.latestProgress,o.at(-1)))return!1;if(t.cancelRequested!==(void 0!==t.cancel))return!1;const i=e.findIndex(e=>"runtime_rpc_response"===e.type);return-1===i||i===e.length-1}function correlatedEnvelope(e,t,r,n){const o="runtime_rpc_response"===t?r.requestMessageId:void 0;return!(!envelope(e)||e.type!==t||!hasKeys(e.payload,n)||e.in_reply_to!==o)&&sameCorrelation(e,r)}function sameCorrelation(e,t){const r=e.payload;return e.channel_id===t.operationId&&r.operationId===t.operationId&&r.requestMessageId===t.requestMessageId&&r.requestHash===t.requestHash&&r.dispatchEpoch===t.dispatchEpoch&&r.method===t.method}function hasKeys(e,t){return t.every(t=>void 0!==e[t])}
@@ -1 +1 @@
1
- import{performance}from"node:perf_hooks";export class MessageServiceSessionModelHttpAuthority{options;constructor(e){this.options=e}async project(e){const o=performance.now();let r="succeeded";try{const o=new URL(`/api/v1/runtime/conversations/${encodeURIComponent(e.conversationId)}/metadata/model`,this.options.messageServiceUrl),r=await this.options.fetchAuthorized(o,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,requestHash:e.requestHash,modelOverrideId:e.modelOverrideId,runtimeLeaseCredential:e.runtimeLeaseCredential})}),t=await decodeRaw(r);if(!r.ok){const e=record(t)&&"string"==typeof t.message&&t.message?`: ${t.code??"error"}: ${t.message}`:"";throw new Error(`Message Service session model projection failed (${r.status})${e}`)}const s=record(t)&&record(t.data)?t.data:t;if(!record(s)||"projected"!==s.status||"created"!==s.disposition&&"reused"!==s.disposition||s.conversationId!==e.conversationId)throw new Error("Message Service session model projection receipt mismatch");const i=void 0===s.modelOverrideId||null===s.modelOverrideId?null:"string"==typeof s.modelOverrideId?s.modelOverrideId:void 0;if(void 0===i||i!==e.modelOverrideId)throw new Error("Message Service session model projection modelOverrideId mismatch");return{status:"projected",disposition:s.disposition,conversationId:e.conversationId,modelOverrideId:i}}catch(e){throw r="failed",e}finally{process.stderr.write(`[MODEL_SWITCH_TIMING] component=runtime operationId=${e.operationId} stage=message_service_project_model outcome=${r} durationMs=${(performance.now()-o).toFixed(1)}\n`)}}}async function decodeRaw(e){try{return await e.json()}catch{return}}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}
1
+ import{performance}from"node:perf_hooks";import{HarnessProtocolError,RuntimeMessagePlane}from"@beeos-ai/cloud-harness-sdk";import{runtimeLeaseHttp}from"./message-service-runtime-authenticated-fetch.js";export class MessageServiceSessionModelHttpAuthority{options;plane;constructor(e){if(this.options=e,!e.scopedDeliveryKey)throw new Error("session model requires X-Runtime-Delivery-Key");this.plane=new RuntimeMessagePlane(runtimeLeaseHttp(e.messageServiceUrl,e.fetchAuthorized))}async project(e){const r=performance.now();let o="succeeded";try{let r;try{r=await this.plane.projectSessionModel({runtimeLeaseCredential:e.runtimeLeaseCredential,scopedDeliveryKey:this.options.scopedDeliveryKey},e.conversationId,{schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,requestHash:e.requestHash,modelOverrideId:e.modelOverrideId,runtimeLeaseCredential:e.runtimeLeaseCredential})}catch(e){if(e instanceof HarnessProtocolError)throw sessionModelFailure(e);throw e}const o=record(r)&&record(r.data)?r.data:r;if(!record(o)||"projected"!==o.status||"created"!==o.disposition&&"reused"!==o.disposition||o.conversationId!==e.conversationId)throw new Error("Message Service session model projection receipt mismatch");const s=void 0===o.modelOverrideId||null===o.modelOverrideId?null:"string"==typeof o.modelOverrideId?o.modelOverrideId:void 0;if(void 0===s||s!==e.modelOverrideId)throw new Error("Message Service session model projection modelOverrideId mismatch");return{status:"projected",disposition:o.disposition,conversationId:e.conversationId,modelOverrideId:s}}catch(e){throw o="failed",e}finally{process.stderr.write(`[MODEL_SWITCH_TIMING] component=runtime operationId=${e.operationId} stage=message_service_project_model outcome=${o} durationMs=${(performance.now()-r).toFixed(1)}\n`)}}}function sessionModelFailure(e){let r;if(e.body)try{r=JSON.parse(e.body)}catch{r=void 0}const o=record(r)&&"string"==typeof r.message&&r.message?`: ${r.code??"error"}: ${r.message}`:"";return new Error(`Message Service session model projection failed (${e.status})${o}`)}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}
@@ -1 +1 @@
1
- import{RUNTIME_ERROR_DESCRIPTORS,RUNTIME_HASH_DOMAINS,RUNTIME_INVOCATION_PARITY_ENTRIES,RUNTIME_INVOCATION_RECOVERY_CLASSES,SERVICE_CANONICAL_COMMAND_NAMES,mapCanonicalResultToService}from"@beeos-ai/beeos-types/runtime";import{reduceRuntimeRecoveryPolicy}from"@beeos-ai/beeos-types/runtime/internal";import{verifyAndCreateMessageServiceCoreExecutionAttempt}from"./core-execution-attempt-context.js";import{awaitRuntimeProjection,hasEffectReceiptHandoff,RuntimeCommandError}from"./runtime-command-dispatcher.js";import{createRuntimeAppendTimingRecorder}from"./runtime-append-timing.js";import{runtimeCommandIsReplayableQuery}from"./runtime-command-journal.js";import{RUNTIME_MESSAGE_TYPES,runtimeMessageBase,runtimeMessageHash,semanticEqual,validateRuntimeCancelEnvelope,validateRuntimeRequestEnvelope}from"./runtime-message-channel-contract.js";import{RuntimeResourceResolutionError}from"./runtime-operation-resource-resolver.js";import{RuntimeTransportFailurePolicy}from"./runtime-transport-failure-policy.js";const leaseStarvationReportIntervalMs=3e4;export class MsRuntimeMessageChannelAdapter{dispatcher;channel;verifier;ports;journal;getLease;options;controller;running;externalDeliveryOwner;workers=new Map;poisonJournal;renewTransportFailurePolicy=new RuntimeTransportFailurePolicy;leaseStarvedSince;leaseStarvationReportedAt=0;receiptHistory=this;constructor(e,t,a,o,r,n,i){if(this.dispatcher=e,this.channel=t,this.verifier=a,this.ports=o,this.journal=r,this.getLease=n,this.options=i,!i.poisonJournal)throw new Error("durable poison journal is required");if(this.poisonJournal=i.poisonJournal,!Number.isSafeInteger(i.poisonDeliveryLimit??3)||(i.poisonDeliveryLimit??3)<=0)throw new Error("poison delivery limit must be a positive integer")}start(){if(this.externalDeliveryOwner)return void this.externalDeliveryOwner.start();if(this.running)return;const e=new AbortController;this.controller=e;const t=this.loop(e.signal).catch(t=>{e.signal.aborted||this.observeDeliveryError(t)}).finally(()=>{this.running===t&&(this.running=void 0)});this.running=t}async stop(e){this.controller?.abort();for(const e of this.workers.values())e.cancel?.();if(this.externalDeliveryOwner)return await this.externalDeliveryOwner.stop(e),void await Promise.allSettled([...this.workers.values()].map(e=>e.completion));this.running&&await abortable(this.running,e)}attachExternalDeliveryOwner(e){if(this.running||this.externalDeliveryOwner)throw new Error("runtime delivery owner is already attached");this.externalDeliveryOwner=e}async acceptDelivery(e,t,a){if(this.currentLease(t),e.message.type===RUNTIME_MESSAGE_TYPES.cancel)return void await this.handleCancel(e,t);const o=validateRuntimeRequestEnvelope(e.message),r=o.ok?o.envelope.payload.operationId:e.message.channel_id;if(this.workers.has(r))return;const n={deliveryId:e.deliveryId,claimedLease:t,completion:Promise.resolve()};n.completion=this.handleRequest(e,t,a,e=>{n.cancel=e}).catch(e=>this.observeDeliveryError(e)).finally(()=>{this.workers.delete(r)}),this.workers.set(r,n),await n.completion}async acceptPoisonDelivery(e,t,a){await this.handlePoison(e,t,a)}async readOperationHistory(e){const t=this.getLease();if(!t)return{status:"unavailable"};try{return await this.channel.history({operationId:e.operationId,lease:t})}catch{return{status:"unavailable"}}}async loop(e){let t;(()=>{t||(t=setInterval(()=>{this.renewActive().catch(e=>this.observeDeliveryError(e))},this.options.renewIntervalMs??2e4),t.unref?.())})();try{for(;!e.aborted;){const t=this.getLease();if(!t){this.observeLeaseStarvation(),await delay(this.options.idleDelayMs??500,e);continue}let a;this.observeLeaseRestored();try{a=await this.channel.read({maxCount:this.options.readCount??32,blockMs:this.options.blockMs??5e3,lease:t,signal:e})}catch(t){if(e.aborted)return;this.observeDeliveryError(t),await delay(this.options.idleDelayMs??500,e);continue}for(const o of a){if(e.aborted)break;if(o.message.type===RUNTIME_MESSAGE_TYPES.cancel){await this.handleCancel(o,t).catch(e=>this.observeDeliveryError(e));continue}const a=o.message.channel_id;if(this.workers.has(a))continue;const r={deliveryId:o.deliveryId,claimedLease:t,completion:Promise.resolve()};r.completion=this.handleRequest(o,t,e,e=>{r.cancel=e}).catch(e=>this.observeDeliveryError(e)).finally(()=>{this.workers.delete(a)}),this.workers.set(a,r)}}}finally{t&&clearInterval(t),await Promise.allSettled([...this.workers.values()].map(e=>e.completion))}}observeDeliveryError(e){try{this.options.onDeliveryError?.(e)}catch{}}observeLeaseStarvation(){const e=Date.now();this.leaseStarvedSince??=e;const t=e-this.leaseStarvedSince;if(!(t<3e4||this.leaseStarvationReportedAt&&e-this.leaseStarvationReportedAt<3e4)){this.leaseStarvationReportedAt=e;try{this.options.onLeaseStarvation?.({starvedForMs:t,recovered:!1})}catch{}}}observeLeaseRestored(){const e=this.leaseStarvedSince;if(void 0===e)return;this.leaseStarvedSince=void 0;const t=this.leaseStarvationReportedAt;if(this.leaseStarvationReportedAt=0,t)try{this.options.onLeaseStarvation?.({starvedForMs:Date.now()-e,recovered:!0})}catch{}}observeRequestFailure(e,t,a){try{this.options.onRequestFailure?.({operationId:e,method:t,error:a})}catch{}}async renewActive(){const e=this.getLease();if(!e)return;const t=[];for(const a of this.workers.values())sameLeaseBinding(a.claimedLease,e)?t.push(a.deliveryId):a.cancel?.();if(!t.length)return;let a;try{a=await this.channel.renew({deliveryIds:t,lease:e})}catch(e){if(this.observeDeliveryError(e),this.renewTransportFailurePolicy.recordFailure()){const e=new Set(t);for(const t of this.workers.values())e.has(t.deliveryId)&&t.cancel?.()}return}if(this.renewTransportFailurePolicy.recordSuccess(),a.notPending.length){const e=new Set(a.notPending);for(const t of this.workers.values())e.has(t.deliveryId)&&t.cancel?.()}}async handleCancel(e,t){const a=validateRuntimeCancelEnvelope(e.message);if(!a.ok)return void await this.handlePoison(e,`invalid_cancel:${a.reason}`,t);const o=a.envelope.payload,r=await this.channel.history({operationId:o.operationId,lease:t});if("found"===r.status&&r.snapshot.terminal&&"final_message"===r.snapshot.terminalSource)return void await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t});if("not_found"===r.status||"expired"===r.status)return void await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t});const n=r.snapshot.request.payload;n.operationId===o.operationId&&n.requestMessageId===o.requestMessageId&&n.requestHash===o.requestHash&&n.dispatchEpoch===o.dispatchEpoch&&n.method===o.method?(await this.journal.observeCancellation({operationId:o.operationId,requestMessageId:o.requestMessageId,requestHash:o.requestHash,eventId:o.eventId}),this.workers.get(o.operationId)?.cancel?.(),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t})):await this.handlePoison(e,"cancel_history_mismatch",t)}async handleRequest(e,t,a,o){const r=validateRuntimeRequestEnvelope(e.message);if(!r.ok)return void await this.handlePoison(e,`invalid_request:${r.reason}`,t);const n=r.envelope.payload,i=e.executionGrant,s=createRuntimeAppendTimingRecorder("runtime-op",{operationId:n.operationId,method:n.method}),c=new AbortController;o(()=>c.abort());const d=async()=>{await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),s.mark("ack")},l=await this.channel.history({operationId:n.operationId,lease:t});if(s.mark("history"),"not_found"===l.status||"expired"===l.status)return void await d();if(l.snapshot.terminal&&"final_message"===l.snapshot.terminalSource)return void await d();if(this.options.allowedMethods&&!this.options.allowedMethods.has(n.method))return await this.reject(n,"unsupported_method",t),void await d();if("deadline"===l.snapshot.terminalSource||Date.parse(n.executionDeadlineAt)<=Date.now()||!l.snapshot.started&&Date.parse(n.claimDeadlineAt)<=Date.now())return await this.reject(n,"execution_deadline_exceeded",t),void await d();const p=await this.journal.getCancellation(n.operationId);s.mark("journal-cancel-read");const u=l.snapshot.cancelRequested||null!==p;if(u&&"queued"===l.snapshot.status)return await this.reject(n,"cancelled_before_dispatch",t),void await d();if(n.instanceId!==t.instanceId||n.runtimeHandlerIdentity!==t.handlerIdentity||n.dispatchEpoch!==t.runtimeEpoch)return await this.reject(n,"authority_mismatch",t),void await d();const m=l.snapshot.request.payload;if(l.snapshot.operationId!==n.operationId||l.snapshot.requestMessageId!==n.requestMessageId||l.snapshot.requestHash!==n.requestHash||!semanticEqual(m,n))return void await this.handlePoison(e,"request_history_mismatch",t);const h=l.snapshot.started?.payload,I=void 0!==h&&h.operationId===n.operationId&&h.requestMessageId===n.requestMessageId&&h.requestHash===n.requestHash&&h.executionGrantHash===n.executionGrantHash&&h.handlerIdentity===t.handlerIdentity&&h.dispatchEpoch===t.runtimeEpoch&&h.method===n.method,E=await this.journal.get(n.operationId);s.mark("journal-prior");const v=runtimeCommandIsReplayableQuery(n.command.name),f=v?ephemeralQueryAccept(n):await this.journal.acceptMessageRequest({operationId:n.operationId,command:n.command.name,paramsHash:n.paramsHash,runtimeEpoch:n.dispatchEpoch,requestMessageId:n.requestMessageId,requestHash:n.requestHash});s.mark("journal-accept");const R=I?E:f,y=v?"execute":decideMessageServiceRecovery(l.snapshot,n,R,I);if("already_terminal"===y)return void await d();if(!CORE_RECOVERY_DECISIONS.has(y))return v||await this.markOutcomeUnknownIfMutable(f),await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(n,new RuntimeCommandError("OUTCOME_UNKNOWN",`Types recovery policy requires ${y}; this runtime cannot safely replay Core`),(new Date).toISOString())}),void await d();if(await this.verifier.refresh(),s.mark("verifier-refresh"),!i)return I?await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(n,new RuntimeCommandError("OUTCOME_UNKNOWN","retained started proof has no live execution grant"),(new Date).toISOString())}):await this.reject(n,"invalid_execution_grant",t),void await d();this.verifier.verifyAndDecodeGrant(i)||await this.verifier.refresh(!0);const _=()=>c.abort();let w;a.addEventListener("abort",_,{once:!0});try{w=await verifyAndCreateMessageServiceCoreExecutionAttempt({request:n,executionGrant:i,runtimeEpoch:t.runtimeEpoch,lease:t,verifier:this.verifier,allowExpiredGrant:I,abortSignal:c.signal,resolvePorts:async()=>await this.ports.resolve({request:n,executionGrant:i,command:n.command,getLease:()=>this.currentLease(t),...this.journalLineage(),journalRecord:f,abortSignal:c.signal})})}catch(e){if(a.removeEventListener("abort",_),c.abort(),!(e instanceof RuntimeResourceResolutionError))throw e;if("transient"===e.kind)return;return I?(v||await this.markOutcomeUnknownIfMutable(f),await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(n,new RuntimeCommandError("OUTCOME_UNKNOWN","eager resources cannot be reconstructed after retained started proof"),(new Date).toISOString())})):await this.reject(n,"integrity_mismatch"===e.kind?"resource_integrity_mismatch":"resource_resolution_rejected",t),void await d()}if(!w.ok)return a.removeEventListener("abort",_),c.abort(),I?(v||await this.markOutcomeUnknownIfMutable(f),await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(n,new RuntimeCommandError("OUTCOME_UNKNOWN","execution grant cannot be revalidated after retained started proof"),(new Date).toISOString())})):await this.reject(n,"invalid_execution_grant",t),void await d();if(!u||"prepared"!==f.phase&&"started"!==f.phase||c.abort(),c.signal.aborted&&!I)return a.removeEventListener("abort",_),await this.reject(n,"cancelled_before_dispatch",t),void await d();s.mark("attempt"),I?this.currentLease(t):(await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),executionGrant:i,type:RUNTIME_MESSAGE_TYPES.started,payload:{...runtimeMessageBase(n),executionMode:"start",executionGrantHash:n.executionGrantHash,handlerIdentity:t.handlerIdentity,claimedAt:f.messageBinding?.acceptedAt??f.updatedAt}}),s.mark("append-started"));const g=this.dispatcher.dispatch(n.command,w.context);g.completion.catch(()=>{}),o(()=>{c.abort(),g.cancel()}),c.signal.aborted&&g.cancel();const M=this.forwardProgress(n,g.progress,t).catch(()=>{});let S,O=!1;try{if(("mcp/set"===n.method||"mcp/unset"===n.method)&&hasEffectReceiptHandoff(g)){const e=await g.effectCommitted;if(e){if(e.operationId!==n.operationId||e.method!==n.command.name)throw new RuntimeCommandError("OUTCOME_UNKNOWN","Core MCP receipt correlation mismatch");const a=runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:n.method,result:e.result}),o={schemaVersion:1,operationId:n.operationId,method:n.method,coreResultRef:`sha256:${a}`,coreResultHash:a};S=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,o),O=!0,await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(n),effectRecord:o,effectRecordHash:S,committedAt:e.committedAt}}),await g.acknowledgeEffectReceipt({operationId:n.operationId,method:n.command.name,effectRecordHash:S})}}const a=await g.completion;if(await M,s.mark("core"),v){const o=(new Date).toISOString();let r;try{r=sanitizeRuntimeServiceResult(n.method,a,w.context,void 0)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed Core result cannot be mapped safely",void 0,{cause:e})}const i=runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:n.method,result:r}),c=await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(n),outcome:"succeeded",response:{jsonrpc:"2.0",id:n.request.id,result:r},serviceResultHash:i,completedAt:o}});return s.mark("append-final"),this.observeRequestTerminalAccepted(e.deliveryId,c.message),await d(),void this.observeRequestAcknowledged(e.deliveryId,c.message)}const o=await this.journal.get(n.operationId);if(s.mark("journal-after-core"),!o||!isCommittedCorePhase(o.phase))throw new RuntimeCommandError("OUTCOME_UNKNOWN","Core completed without a committed local journal record");const r=o.updatedAt;let i,c;if("query"!==RUNTIME_INVOCATION_RECOVERY_CLASSES[n.method]){const e=isAgentProjectionMethod(n.method),c=g.getSnapshot().projection,l=o.agentProjectionIntent??o.agentProjectionPreparationFailure;if(e&&!l)throw new RuntimeCommandError("OUTCOME_UNKNOWN","agent effect committed without an atomic projection preparation record");if(!S){const e=l?.coreResultHash??runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:n.method,result:a}),i=o.agentProjectionIntent?.projectionRevision??(methodRequiresProjectionRevision(n.method)?c?.revision??`${Math.max(0,o.revision)}`:void 0),d={schemaVersion:1,operationId:n.operationId,method:n.method,coreResultRef:`sha256:${e}`,coreResultHash:e,...i?{projectionRevision:i}:{}};S=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,d),O=!0,await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(n),effectRecord:d,effectRecordHash:S,committedAt:r}}),s.mark("append-effect")}let p=e?await awaitRuntimeProjection(g):c;if("session/set_model"===n.method&&"synced"!==p?.state&&(p=await this.projectSessionModelAfterEffect(n,w.context,o,p),s.mark("set-model-projection")),e&&o.agentProjectionIntent&&(!p||p.revision!==o.agentProjectionIntent.projectionRevision))throw new RuntimeCommandError("OUTCOME_UNKNOWN","agent projection receipt revision mismatch");if("pending"===p?.state)return void await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.projectionPending,payload:{...runtimeMessageBase(n),revision:p.revision}});if("synced"===p?.state&&await this.publishProjectionSynced(n,t,{...p,state:"synced"}),"blocked"===p?.state){await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.projectionBlocked,payload:{...runtimeMessageBase(n),revision:p.revision,errorCode:"PROJECTION_BLOCKED"}});const e=RUNTIME_ERROR_DESCRIPTORS.PROJECTION_BLOCKED;return await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(n),outcome:"projection_blocked",response:{jsonrpc:"2.0",id:n.request.id,error:{code:e.jsonRpcCode,message:"PROJECTION_BLOCKED",data:{code:"PROJECTION_BLOCKED",operationId:n.operationId,effectState:"committed",retryMode:e.retryMode}}},effectRecordHash:S,completedAt:r}}),void await d()}i=e?p?.platformAgentId:void 0}try{c=sanitizeRuntimeServiceResult(n.method,a,w.context,i)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed Core result cannot be mapped safely",void 0,{cause:e})}const l=runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:n.method,result:c});O=!0;const p=await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(n),outcome:"succeeded",response:{jsonrpc:"2.0",id:n.request.id,result:c},serviceResultHash:l,...S?{effectRecordHash:S}:{},completedAt:r}});if(s.mark("append-final"),this.observeRequestTerminalAccepted(e.deliveryId,p.message),("mcp/set"===n.method||"mcp/unset"===n.method)&&hasEffectReceiptHandoff(g)&&"function"==typeof g.acknowledgeTerminalReceipt){if(!S)throw new RuntimeCommandError("OUTCOME_UNKNOWN","MCP terminal response lacks its committed effect hash");await g.acknowledgeTerminalReceipt({operationId:n.operationId,method:n.command.name,effectRecordHash:S,terminalMessageId:p.message.message_id})}await d(),this.observeRequestAcknowledged(e.deliveryId,p.message)}catch(e){const a=await this.journal.get(n.operationId);if(a&&isCommittedCorePhase(a.phase)&&O)throw e;const o=!a||!isCommittedCorePhase(a.phase)||e instanceof RuntimeCommandError&&"OUTCOME_UNKNOWN"===e.code?e:new RuntimeCommandError("OUTCOME_UNKNOWN","Core effect committed before terminal mapping",void 0,{cause:e});this.observeRequestFailure(n.operationId,n.method,o);const r=failurePayload(n,o,a?.updatedAt??(new Date).toISOString());await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:r}),s.mark("append-terminal-failure"),await d()}finally{s.finish(),c.abort(),a.removeEventListener("abort",_)}}async handlePoison(e,t,a){this.currentLease(a);(await this.poisonJournal.record({delivery:e,reason:durablePoisonReason(t),limit:this.options.poisonDeliveryLimit??3})).terminal&&await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(a)})}observeRequestTerminalAccepted(e,t){try{this.options.onRequestTerminalAccepted?.({deliveryId:e,message:t})}catch{}}observeRequestAcknowledged(e,t){try{this.options.onRequestAcknowledged?.({deliveryId:e,message:t})}catch{}}async forwardProgress(e,t,a){for await(const o of t)await this.channel.append({operationId:e.operationId,lease:this.currentLease(a),type:RUNTIME_MESSAGE_TYPES.progress,payload:{...runtimeMessageBase(e),phase:o.phase,progress:o}})}async reject(e,t,a){await this.channel.append({operationId:e.operationId,lease:this.currentLease(a),type:RUNTIME_MESSAGE_TYPES.final,payload:prestartFailurePayload(e,t)})}async markOutcomeUnknownIfMutable(e){"prepared"!==e.phase&&"started"!==e.phase||await this.journal.transition({operationId:e.operationId,expectedRevision:e.revision,phase:"outcome_unknown",errorCode:"OUTCOME_UNKNOWN"})}async projectSessionModelAfterEffect(e,t,a,o){const r=Object.freeze({state:"pending",revision:o?.revision??`${Math.max(0,a.revision)}`}),n=e.command;if("session.setModel"!==n.name||"conversation"!==n.context.scope)return r;const i=t.sessionModelProjection;if(!i)return r;try{await i.project({conversationId:n.context.conversation.runtimeConversationUid,modelOverrideId:n.params.modelOverrideId});const e=Object.freeze({state:"synced",revision:r.revision});try{const t=await this.journal.get(a.operationId)??a;if("projection_committed"===t.phase&&"synced"===t.projectionReceipt?.snapshot.state)return Object.freeze({state:"synced",revision:t.projectionReceipt.snapshot.revision});await this.journal.transition({operationId:t.operationId,expectedRevision:t.revision,phase:"projection_committed",projectionSnapshot:e})}catch{}return e}catch(e){return this.observeDeliveryError(e),r}}async publishProjectionSynced(e,t,a){const o=this.currentLease(t),r=await this.channel.history({operationId:e.operationId,lease:o});if("found"===r.status&&"synced"===r.snapshot.projectionState)return;const n={...runtimeMessageBase(e),revision:a.revision};("found"!==r.status||"reserved"===r.snapshot.projectionState||"pending"!==r.snapshot.projectionState&&void 0===r.snapshot.projectionPending)&&await this.channel.append({operationId:e.operationId,lease:o,type:RUNTIME_MESSAGE_TYPES.projectionPending,payload:n}),await this.channel.append({operationId:e.operationId,lease:o,type:RUNTIME_MESSAGE_TYPES.projectionSynced,payload:{...n,...a.platformAgentId?{platformAgentId:a.platformAgentId}:{}}})}journalLineage(){return this.options.getJournalLineage?.()??{journalStoreId:this.options.journalStoreId,journalGeneration:this.options.journalGeneration}}currentLease(e){const t=this.getLease();if(!t||t.instanceId!==e.instanceId||t.leaseId!==e.leaseId||t.runtimeEpoch!==e.runtimeEpoch||t.handlerIdentity!==e.handlerIdentity||!Number.isFinite(Date.parse(t.leaseExpiresAt))||Date.parse(t.leaseExpiresAt)<=Date.now())throw new RuntimeCommandError("INSTANCE_EPOCH_MISMATCH","runtime message lease changed");return t}}function ephemeralQueryAccept(e){return{operationId:e.operationId,command:e.command.name,paramsHash:e.paramsHash,runtimeEpoch:e.dispatchEpoch,phase:"prepared",revision:1,updatedAt:(new Date).toISOString(),messageBinding:{requestMessageId:e.requestMessageId,requestHash:e.requestHash,acceptedAt:(new Date).toISOString()}}}function durablePoisonReason(e){const t=e.replace(/[^a-z0-9_:.-]+/gi,"_").replace(/^_+|_+$/g,"").slice(0,256);if(!t)throw new Error("poison reason is empty");return t}function isCommittedCorePhase(e){return"effect_committed"===e||"projection_committed"===e}const CORE_RECOVERY_DECISIONS=new Set(["execute","resume","replay_effect_committed","resume_projection","publish_committed_result","publish_projected_result","publish_terminal_result"]);function decideMessageServiceRecovery(e,t,a,o){const r=RUNTIME_INVOCATION_PARITY_ENTRIES.find(e=>e.acpMethod===t.method),n=e.terminal?"terminal":"blocked"===e.projectionState?"projection_blocked":"synced"===e.projectionState?"projection_synced":"pending"===e.projectionState?"projection_pending":e.effectCommitted?"runtime_committed":o?"running":"queued",i="failed"===a?.phase||"outcome_unknown"===a?.phase?"terminal":a?.phase,s=a&&a.runtimeEpoch===t.dispatchEpoch&&(void 0===a.messageBinding||a.messageBinding.requestMessageId===t.requestMessageId&&a.messageBinding.requestHash===t.requestHash)?"continuous":"discontinuous";return reduceRuntimeRecoveryPolicy({recoveryClass:r?.recoveryClass??RUNTIME_INVOCATION_RECOVERY_CLASSES[t.method],projectionRequired:"mcp/set"===t.method||"mcp/unset"===t.method||(r?.projectionRequired??!1),messageServicePhase:n,executionBoundaryCrossed:o,lineageContinuity:s,journalState:a?"available":"unavailable",...i?{journalPhase:i}:{}})}export function sanitizeRuntimeServiceResult(e,t,a,o){if("session/clear"===e)return serviceClearResult(t,a?.historyBoundary);if("session/set_model"===e)return serviceSetModelResult(t,a);if(!(e in SERVICE_CANONICAL_COMMAND_NAMES))return t;const r="cron/status"===e&&record(t)?{enabled:t.enabled,jobCount:t.jobCount,..."number"==typeof t.nextWakeAtMs?{nextWakeAtMs:t.nextWakeAtMs}:{}}:t;return mapCanonicalResultToService(e,r,{...o?{platformAgentId:o}:{},classifySkillOrigin:e=>e.bundled?{origin:"bundled",slug:e.slug}:{origin:"legacy_runtime",slug:e.slug},resolveMcpView:e=>({name:e.name,transport:e.transport,origin:"legacy_runtime",...void 0===e.connected?{}:{connected:e.connected},...void 0===e.connectionTimeoutMs?{}:{connectionTimeoutMs:e.connectionTimeoutMs}}),sanitizeDiagnostic:e=>/^[A-Z][A-Z0-9_]{0,63}$/.test(e)?e:"RUNTIME_EXECUTION_FAILED"})}function serviceClearResult(e,t){if(!record(e)||!0!==e.cleared||"string"!=typeof e.historyGeneration||!t||"message-service"!==t.kind)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed clear result lacks its Message Service receipt");const a=t;if(!a.committedIntentId)throw new RuntimeCommandError("OUTCOME_UNKNOWN","Message Service clear receipt is unavailable");return{...e,clearIntentId:a.committedIntentId()}}function serviceSetModelResult(e,t){if(!record(e)||"string"!=typeof e.effectiveModelId||!t)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed set_model result is invalid");const a=t.verifiedMessageGrant?.claims.command;if(!a||"session.setModel"!==a.name||"conversation"!==a.context.scope)throw new RuntimeCommandError("OUTCOME_UNKNOWN","set_model Service target receipt is unavailable");const o=a.params.modelOverrideId;return{conversationId:a.context.conversation.runtimeConversationUid,...null===o?{defaultModelId:e.effectiveModelId}:{},modelOverrideId:o,effectiveModelId:e.effectiveModelId,effectState:"committed",projectionState:"synced",operationId:t.operationId}}function isAgentProjectionMethod(e){return"agent/create"===e||"agent/update"===e||"agent/delete"===e||"agent/applyTemplate"===e}function methodRequiresProjectionRevision(e){return isAgentProjectionMethod(e)||"session/set_model"===e}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function sameLeaseBinding(e,t){return e.instanceId===t.instanceId&&e.leaseId===t.leaseId&&e.handlerIdentity===t.handlerIdentity&&e.runtimeEpoch===t.runtimeEpoch}function failurePayload(e,t,a){const o=t instanceof RuntimeCommandError?t.code:"RUNTIME_EXECUTION_FAILED",r=o in RUNTIME_ERROR_DESCRIPTORS?o:"RUNTIME_EXECUTION_FAILED",n="OUTCOME_UNKNOWN"===r||"INSTANCE_EPOCH_MISMATCH"===r?"outcome_unknown":"COMMAND_EXPIRED"===r?"expired":"OPERATION_CANCELLED"===r?"cancelled":"failed",i="outcome_unknown"===n?"OUTCOME_UNKNOWN":r,s=RUNTIME_ERROR_DESCRIPTORS[i],c="outcome_unknown"===n?"outcome_unknown":n;return{...runtimeMessageBase(e),outcome:n,response:{jsonrpc:"2.0",id:e.request.id,error:{code:s.jsonRpcCode,message:i,data:{code:i,operationId:e.operationId,effectState:c,retryMode:s.retryMode}}},completedAt:a}}function prestartFailurePayload(e,t){const a="invalid_execution_grant"===t?"INVALID_EXECUTION_GRANT":"unsupported_method"===t?"METHOD_NOT_SUPPORTED":"authority_mismatch"===t?"INSTANCE_EPOCH_MISMATCH":"execution_deadline_exceeded"===t?"COMMAND_EXPIRED":"cancelled_before_dispatch"===t?"OPERATION_CANCELLED":"resource_resolution_rejected"===t?"INVALID_INVOCATION":"RUNTIME_EXECUTION_FAILED",o=RUNTIME_ERROR_DESCRIPTORS[a in RUNTIME_ERROR_DESCRIPTORS?a:"RUNTIME_EXECUTION_FAILED"],r="COMMAND_EXPIRED"===a?"expired":"OPERATION_CANCELLED"===a?"cancelled":"failed";return{...runtimeMessageBase(e),outcome:r,response:{jsonrpc:"2.0",id:e.request.id,error:{code:o.jsonRpcCode,message:a,data:{code:a,operationId:e.operationId,effectState:r,retryMode:o.retryMode}}},completedAt:(new Date).toISOString()}}function abortable(e,t){return t?t.aborted?Promise.resolve():new Promise((a,o)=>{const r=()=>a();t.addEventListener("abort",r,{once:!0}),e.then(()=>{t.removeEventListener("abort",r),a()},e=>{t.removeEventListener("abort",r),o(e)})}):e}function delay(e,t){return new Promise(a=>{if(t?.aborted)return a();const o=()=>{clearTimeout(r),a()},r=setTimeout(()=>{t?.removeEventListener("abort",o),a()},e);t?.addEventListener("abort",o,{once:!0})})}
1
+ import{RUNTIME_ERROR_DESCRIPTORS,RUNTIME_HASH_DOMAINS,RUNTIME_INVOCATION_PARITY_ENTRIES,RUNTIME_INVOCATION_RECOVERY_CLASSES,SERVICE_CANONICAL_COMMAND_NAMES,mapCanonicalResultToService}from"@beeos-ai/beeos-types/runtime";import{reduceRuntimeRecoveryPolicy}from"@beeos-ai/beeos-types/runtime/internal";import{verifyAndCreateMessageServiceCoreExecutionAttempt}from"./core-execution-attempt-context.js";import{awaitRuntimeProjection,hasEffectReceiptHandoff,RuntimeCommandError}from"./runtime-command-dispatcher.js";import{createRuntimeAppendTimingRecorder}from"./runtime-append-timing.js";import{runtimeCommandIsReplayableQuery}from"./runtime-command-journal.js";import{RUNTIME_MESSAGE_TYPES,runtimeMessageBase,runtimeMessageHash,semanticEqual,validateRuntimeCancelEnvelope,validateRuntimeRequestEnvelope}from"./runtime-message-channel-contract.js";import{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 +1 @@
1
- import{MsRuntimeMessageChannelAdapter}from"./ms-runtime-message-channel-adapter.js";import{decodeRuntimeAppendMessage,decodeRuntimeBrokerDelivery,decodeRuntimeOperationHistory,RuntimeMessageChannelProtocolError}from"./message-service-runtime-message-channel.js";import{isCanonicalSessionNewDelivery,SessionNewRuntimeDeliveryBridge}from"./session-new-runtime-delivery-bridge.js";export class MsRuntimeMessageChannelConsumerFactory{deps;constructor(e){this.deps=e}async create(e){let n;const s=new SdkRuntimeMessageChannel(()=>{if(!n)throw new Error("SDK runtime delivery consumer is not attached");return n}),r=new MsRuntimeMessageChannelAdapter(e.dispatcher,s,this.deps.verifier,this.deps.ports,this.deps.journal,()=>e.getLease(),{...this.deps.options,allowedMethods:this.deps.allowedMethods,journalStoreId:e.binding.journalStoreId,journalGeneration:e.binding.journalGeneration,...e.getBinding?{getJournalLineage:()=>{const n=e.getBinding();return{journalStoreId:n.journalStoreId,journalGeneration:n.journalGeneration}}}:{}}),t=new SessionNewRuntimeDeliveryBridge({client:this.deps.client,consumer:()=>{if(!n)throw new Error("SDK runtime delivery consumer is not attached");return n},verifier:this.deps.verifier,getLease:()=>e.getLease(),createRuntimeSession:e.createRuntimeSession,poison:async(e,n,s)=>{await r.acceptPoisonDelivery(e,n,s)}});return n=this.deps.client.methods.consume({onDelivery:async(n,s)=>{const i=currentFencedLease(e,s.lease),o=decodeRuntimeBrokerDelivery(n);isCanonicalSessionNewDelivery(o)?await t.acceptDelivery(o,i,s.signal):await r.acceptDelivery(o,i,s.signal)},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}),r.attachExternalDeliveryOwner(n),r}}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 n=await this.consumer().history(e.operationId);return"found"!==n.status?n:{status:"found",snapshot:decodeRuntimeOperationHistory(n.snapshot,e.operationId)}}async append(e){assertLeaseAvailable(e.lease);const n=await this.consumer().append(e.operationId,e.type,e.payload,e.executionGrant);if("created"===n.outcome||"duplicate"===n.outcome)return{disposition:"created"===n.outcome?"created":"reused",message:decodeRuntimeAppendMessage(n.message,e)};if(n.history){const s=findReconciledMessage(decodeRuntimeOperationHistory(n.history,e.operationId),e);if(s)return{disposition:"reused",message:s}}throw new RuntimeMessageChannelProtocolError("runtime append outcome is unknown after history reconcile",503,"OUTCOME_UNKNOWN")}}function currentFencedLease(e,n){const s=e.getLease(),r=e.getBinding?.()??e.binding;if(!s||s.instanceId!==n.instanceId||s.handlerIdentity!==n.handlerIdentity||s.runtimeEpoch!==n.runtimeEpoch||s.leaseId!==n.leaseId||r.journalStoreId!==n.journalStoreId||r.journalGeneration!==n.journalGeneration)throw new Error("runtime delivery lease fence changed");if(Date.parse(s.leaseExpiresAt)<=Date.now())throw new Error("runtime delivery lease expired");return s}function assertLeaseAvailable(e){if(!Number.isFinite(Date.parse(e.leaseExpiresAt))||Date.parse(e.leaseExpiresAt)<=Date.now())throw new Error("runtime delivery lease expired")}function findReconciledMessage(e,n){for(let s=e.messages.length-1;s>=0;s-=1)try{return decodeRuntimeAppendMessage(e.messages[s],n)}catch{}}
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}}}:{}}),i=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,s=i?new SessionNewRuntimeDeliveryBridge({conversations:i,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 n.acceptPoisonDelivery(e,t,r)}}):void 0,o=this.deps.client?.methods??this.deps.runtimeDelivery;if(!o)throw new Error("runtime delivery owner is unavailable");return t=o.consume({onDelivery:async(t,r)=>{runtimeDeliveryTrace(t);let i="fence";try{const o=currentFencedLease(e,r.lease);i="decode";const a=t,d=this.deps.nativePrompt&&2===a.message?.payload?.schemaVersion&&"session/prompt"===a.message.payload.method?t:decodeRuntimeBrokerDelivery(t);if(i="dispatch",isCanonicalSessionNewDelivery(d))return s?void await s.acceptDelivery(d,o,r.signal):void await n.acceptPoisonDelivery(d,"cloud_session_new_unsupported",o);await n.acceptDelivery(d,o,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}),n.attachExternalDeliveryOwner(t),n}}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{}}