beeos-claw 0.6.63-cloud.1 → 0.6.63-cloud.3

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 (53) hide show
  1. package/dist/acp-gateway/bridge-core.js +1 -1
  2. package/dist/acp-server.js +1 -1
  3. package/dist/agent-auth.js +1 -1
  4. package/dist/canvas-orchestrator.js +1 -1
  5. package/dist/chat-envelope.js +1 -0
  6. package/dist/im-inbound-handler.js +1 -1
  7. package/dist/im-runtime-dispatch.js +1 -1
  8. package/dist/index.js +1 -1
  9. package/dist/message-client-composition.js +1 -1
  10. package/dist/message-projection-inbound-consumer.js +1 -1
  11. package/dist/runtime/callback-queue.js +1 -1
  12. package/dist/runtime/chat-handler-port.js +1 -0
  13. package/dist/runtime/conversation-title.js +1 -1
  14. package/dist/runtime/core-execution-attempt-context.js +1 -1
  15. package/dist/runtime/im-reply-sink.js +1 -1
  16. package/dist/runtime/message-service-conversation-clear-http-authority.js +1 -1
  17. package/dist/runtime/message-service-conversation-run-boundary.js +1 -1
  18. package/dist/runtime/message-service-runtime-message-channel.js +1 -1
  19. package/dist/runtime/ms-runtime-message-channel-adapter.js +1 -1
  20. package/dist/runtime/ms-runtime-message-channel-consumer-factory.js +1 -1
  21. package/dist/runtime/ms-runtime-rpc-adapter.js +1 -1
  22. package/dist/runtime/native-cloud-chat-composition.js +1 -0
  23. package/dist/runtime/native-cloud-prompt-bridge.js +1 -0
  24. package/dist/runtime/native-input-files-http.js +1 -0
  25. package/dist/runtime/native-input-files.js +1 -0
  26. package/dist/runtime/native-output-file-attempt.js +1 -0
  27. package/dist/runtime/native-prompt-authority.js +1 -0
  28. package/dist/runtime/native-prompt-preflight.js +1 -0
  29. package/dist/runtime/native-session-new-bridge.js +1 -0
  30. package/dist/runtime/reply-router.js +1 -1
  31. package/dist/runtime/runtime-error-part.js +1 -0
  32. package/dist/runtime/runtime-local-parity-matrix.js +1 -1
  33. package/dist/runtime/runtime-operation-resource-resolver.js +1 -1
  34. package/dist/runtime/runtime-parity-manifest-digest.js +1 -1
  35. package/dist/runtime/runtime-parity-manifest.js +1 -1
  36. package/dist/runtime/runtime-production-authority.js +1 -1
  37. package/dist/runtime/runtime-registration.js +1 -0
  38. package/dist/runtime/runtime-service-contract-compatibility.js +1 -1
  39. package/dist/runtime/runtime-service-production-candidate.js +1 -1
  40. package/dist/runtime/runtime-session-control-service.js +1 -1
  41. package/dist/runtime/runtime-skills-service.js +1 -1
  42. package/dist/runtime/runtime-transport-failure-policy.js +1 -0
  43. package/dist/runtime/service-runtime-attempt-ports-resolver.js +1 -1
  44. package/dist/runtime/session-new-runtime-delivery-bridge.js +1 -1
  45. package/dist/runtime/write-runtime-failure.js +1 -1
  46. package/dist/upload/tool.js +1 -1
  47. package/dist/upload/upload-file.js +1 -1
  48. package/openclaw.plugin.json +1 -15
  49. package/package.json +5 -5
  50. package/runtime-service-wire-identity.v1.json +5 -5
  51. package/dist/automation/tools.js +0 -1
  52. package/dist/automation/turn-policy.js +0 -1
  53. package/dist/automation/wake.js +0 -1
@@ -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{isDeepStrictEqual}from"node:util";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;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`,r=await this.fetch(t,e.lease,{method:"GET"});if(404===r.status)return{status:"not_found"};if(410===r.status)return{status:"expired"};const n=await responseJson(r);if(!r.ok)throw protocolFailure(r,n,"runtime history read failed");if(!isHistory(n,e.operationId))throw new RuntimeMessageChannelProtocolError("Message Service returned invalid operation history");return{status:"found",snapshot:n}}async append(e){const t=`/api/v1/runtime/operations/${encodeURIComponent(e.operationId)}/messages`,r=appendResult(await this.post(t,e.lease,{schemaVersion:1,type:e.type,payload:e.payload},e.executionGrant)),n="runtime_rpc_response"===e.type?e.payload.requestMessageId:void 0;if(r.message.channel_id!==e.operationId||r.message.type!==e.type||r.message.in_reply_to!==n||!semanticEqual(r.message.payload,e.payload))throw new RuntimeMessageChannelProtocolError("Message Service append response correlation mismatch");return r}async post(e,t,r,n,o){const i=await this.fetch(e,t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r),...o?{signal:o}:{}},n),s=await responseJson(i);if(!i.ok)throw protocolFailure(i,s,`runtime message-channel POST ${e} failed`);return s}async fetch(e,t,r,n){return await this.options.transport.fetchRuntimeChannel(new URL(e,this.options.serviceUrl),{runtimeLeaseCredential:t.runtimeLeaseCredential,scopedDeliveryKey:this.options.scopedDeliveryKey,...n?{executionGrant:n}:{}},r,{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 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 protocolFailure(e,t,r){const n=record(t)&&"string"==typeof t.code?t.code:void 0,o=record(t)&&"string"==typeof t.message?t.message:r;return new RuntimeMessageChannelProtocolError(`${o} (${e.status})`,e.status,n)}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,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{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"@beeos-ai/cloud-agent-sdk";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);if(r.envelope.payload.schemaVersion!==(this.options.requestSchemaVersion??1))return void await this.handlePoison(e,"request_realm_mismatch",t);const n=r.envelope.payload,i=e.executionGrant,s=createRuntimeAppendTimingRecorder("runtime-op",{operationId:n.operationId,method:n.method}),c=new AbortController;o(()=>c.abort());const d=async()=>{await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),s.mark("ack")},l=await this.channel.history({operationId:n.operationId,lease:t});if(s.mark("history"),"not_found"===l.status||"expired"===l.status)return void await d();if(l.snapshot.terminal&&"final_message"===l.snapshot.terminalSource)return void await d();if(this.options.allowedMethods&&!this.options.allowedMethods.has(n.method))return await this.reject(n,"unsupported_method",t),void await d();if("deadline"===l.snapshot.terminalSource||Date.parse(n.executionDeadlineAt)<=Date.now()||!l.snapshot.started&&Date.parse(n.claimDeadlineAt)<=Date.now())return await this.reject(n,"execution_deadline_exceeded",t),void await d();const p=await this.journal.getCancellation(n.operationId);s.mark("journal-cancel-read");const u=l.snapshot.cancelRequested||null!==p;if(u&&"queued"===l.snapshot.status)return await this.reject(n,"cancelled_before_dispatch",t),void await d();if(n.instanceId!==t.instanceId||n.runtimeHandlerIdentity!==t.handlerIdentity||n.dispatchEpoch!==t.runtimeEpoch)return await this.reject(n,"authority_mismatch",t),void await d();const m=l.snapshot.request.payload;if(l.snapshot.operationId!==n.operationId||l.snapshot.requestMessageId!==n.requestMessageId||l.snapshot.requestHash!==n.requestHash||!semanticEqual(m,n))return void await this.handlePoison(e,"request_history_mismatch",t);const h=l.snapshot.started?.payload,I=void 0!==h&&h.operationId===n.operationId&&h.requestMessageId===n.requestMessageId&&h.requestHash===n.requestHash&&h.executionGrantHash===n.executionGrantHash&&h.handlerIdentity===t.handlerIdentity&&h.dispatchEpoch===t.runtimeEpoch&&h.method===n.method,E=await this.journal.get(n.operationId);s.mark("journal-prior");const v=runtimeCommandIsReplayableQuery(n.command.name),f=v?ephemeralQueryAccept(n):await this.journal.acceptMessageRequest({operationId:n.operationId,command:n.command.name,paramsHash:n.paramsHash,runtimeEpoch:n.dispatchEpoch,requestMessageId:n.requestMessageId,requestHash:n.requestHash});s.mark("journal-accept");const R=I?E:f,y=v?"execute":decideMessageServiceRecovery(l.snapshot,n,R,I);if("already_terminal"===y)return void await d();if(!CORE_RECOVERY_DECISIONS.has(y))return v||await this.markOutcomeUnknownIfMutable(f),await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(n,new RuntimeCommandError("OUTCOME_UNKNOWN",`Types recovery policy requires ${y}; this runtime cannot safely replay Core`),(new Date).toISOString())}),void await d();if(await this.verifier.refresh(),s.mark("verifier-refresh"),!i)return I?await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(n,new RuntimeCommandError("OUTCOME_UNKNOWN","retained started proof has no live execution grant"),(new Date).toISOString())}):await this.reject(n,"invalid_execution_grant",t),void await d();this.verifier.verifyAndDecodeGrant(i)||await this.verifier.refresh(!0);const _=()=>c.abort();let w;a.addEventListener("abort",_,{once:!0});try{w=await verifyAndCreateMessageServiceCoreExecutionAttempt({request:n,executionGrant:i,runtimeEpoch:t.runtimeEpoch,lease:t,verifier:this.verifier,allowExpiredGrant:I,abortSignal:c.signal,resolvePorts:async()=>await this.ports.resolve({request:n,executionGrant:i,command:n.command,getLease:()=>this.currentLease(t),...this.journalLineage(),journalRecord:f,abortSignal:c.signal})})}catch(e){if(a.removeEventListener("abort",_),c.abort(),!(e instanceof RuntimeResourceResolutionError))throw e;if("transient"===e.kind)return;return I?(v||await this.markOutcomeUnknownIfMutable(f),await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(n,new RuntimeCommandError("OUTCOME_UNKNOWN","eager resources cannot be reconstructed after retained started proof"),(new Date).toISOString())})):await this.reject(n,"integrity_mismatch"===e.kind?"resource_integrity_mismatch":"resource_resolution_rejected",t),void await d()}if(!w.ok)return a.removeEventListener("abort",_),c.abort(),I?(v||await this.markOutcomeUnknownIfMutable(f),await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(n,new RuntimeCommandError("OUTCOME_UNKNOWN","execution grant cannot be revalidated after retained started proof"),(new Date).toISOString())})):await this.reject(n,"invalid_execution_grant",t),void await d();if(!u||"prepared"!==f.phase&&"started"!==f.phase||c.abort(),c.signal.aborted&&!I)return a.removeEventListener("abort",_),await this.reject(n,"cancelled_before_dispatch",t),void await d();s.mark("attempt"),I?this.currentLease(t):(await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),executionGrant:i,type:RUNTIME_MESSAGE_TYPES.started,payload:{...runtimeMessageBase(n),executionMode:"start",executionGrantHash:n.executionGrantHash,handlerIdentity:t.handlerIdentity,claimedAt:f.messageBinding?.acceptedAt??f.updatedAt}}),s.mark("append-started"));const g=this.dispatcher.dispatch(n.command,w.context);g.completion.catch(()=>{}),o(()=>{c.abort(),g.cancel()}),c.signal.aborted&&g.cancel();const M=this.forwardProgress(n,g.progress,t).catch(()=>{});let S,O=!1;try{if(("mcp/set"===n.method||"mcp/unset"===n.method)&&hasEffectReceiptHandoff(g)){const e=await g.effectCommitted;if(e){if(e.operationId!==n.operationId||e.method!==n.command.name)throw new RuntimeCommandError("OUTCOME_UNKNOWN","Core MCP receipt correlation mismatch");const a=runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:n.method,result:e.result}),o={schemaVersion:1,operationId:n.operationId,method:n.method,coreResultRef:`sha256:${a}`,coreResultHash:a};S=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,o),O=!0,await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(n),effectRecord:o,effectRecordHash:S,committedAt:e.committedAt}}),await g.acknowledgeEffectReceipt({operationId:n.operationId,method:n.command.name,effectRecordHash:S})}}const a=await g.completion;if(await M,s.mark("core"),v){const o=(new Date).toISOString();let r;try{r=sanitizeRuntimeServiceResult(n.method,a,w.context,void 0)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed Core result cannot be mapped safely",void 0,{cause:e})}const i=runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:n.method,result:r}),c=await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(n),outcome:"succeeded",response:{jsonrpc:"2.0",id:n.request.id,result:r},serviceResultHash:i,completedAt:o}});return s.mark("append-final"),this.observeRequestTerminalAccepted(e.deliveryId,c.message),await d(),void this.observeRequestAcknowledged(e.deliveryId,c.message)}const o=await this.journal.get(n.operationId);if(s.mark("journal-after-core"),!o||!isCommittedCorePhase(o.phase))throw new RuntimeCommandError("OUTCOME_UNKNOWN","Core completed without a committed local journal record");const r=o.updatedAt;let i,c;if("query"!==RUNTIME_INVOCATION_RECOVERY_CLASSES[n.method]){const e=isAgentProjectionMethod(n.method),c=g.getSnapshot().projection,l=o.agentProjectionIntent??o.agentProjectionPreparationFailure;if(e&&!l)throw new RuntimeCommandError("OUTCOME_UNKNOWN","agent effect committed without an atomic projection preparation record");if(!S&&"session/clear"!==n.method){const e=l?.coreResultHash??runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:n.method,result:a}),i=o.agentProjectionIntent?.projectionRevision??(methodRequiresProjectionRevision(n.method)?c?.revision??`${Math.max(0,o.revision)}`:void 0),d={schemaVersion:1,operationId:n.operationId,method:n.method,coreResultRef:`sha256:${e}`,coreResultHash:e,...i?{projectionRevision:i}:{}};S=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,d),O=!0,await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(n),effectRecord:d,effectRecordHash:S,committedAt:r}}),s.mark("append-effect")}let p=e?await awaitRuntimeProjection(g):c;if("session/set_model"===n.method&&"synced"!==p?.state&&(p=await this.projectSessionModelAfterEffect(n,w.context,o,p),s.mark("set-model-projection")),e&&o.agentProjectionIntent&&(!p||p.revision!==o.agentProjectionIntent.projectionRevision))throw new RuntimeCommandError("OUTCOME_UNKNOWN","agent projection receipt revision mismatch");if("pending"===p?.state)return void await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.projectionPending,payload:{...runtimeMessageBase(n),revision:p.revision}});if("synced"===p?.state&&await this.publishProjectionSynced(n,t,{...p,state:"synced"}),"blocked"===p?.state){await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.projectionBlocked,payload:{...runtimeMessageBase(n),revision:p.revision,errorCode:"PROJECTION_BLOCKED"}});const e=RUNTIME_ERROR_DESCRIPTORS.PROJECTION_BLOCKED;return await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(n),outcome:"projection_blocked",response:{jsonrpc:"2.0",id:n.request.id,error:{code:e.jsonRpcCode,message:"PROJECTION_BLOCKED",data:{code:"PROJECTION_BLOCKED",operationId:n.operationId,effectState:"committed",retryMode:e.retryMode}}},effectRecordHash:S,completedAt:r}}),void await d()}i=e?p?.platformAgentId:void 0}try{c=sanitizeRuntimeServiceResult(n.method,a,w.context,i)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed Core result cannot be mapped safely",void 0,{cause:e})}const l=runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:n.method,result:c});O=!0;const p=await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(n),outcome:"succeeded",response:{jsonrpc:"2.0",id:n.request.id,result:c},serviceResultHash:l,...S?{effectRecordHash:S}:{},completedAt:r}});if(s.mark("append-final"),this.observeRequestTerminalAccepted(e.deliveryId,p.message),("mcp/set"===n.method||"mcp/unset"===n.method)&&hasEffectReceiptHandoff(g)&&"function"==typeof g.acknowledgeTerminalReceipt){if(!S)throw new RuntimeCommandError("OUTCOME_UNKNOWN","MCP terminal response lacks its committed effect hash");await g.acknowledgeTerminalReceipt({operationId:n.operationId,method:n.command.name,effectRecordHash:S,terminalMessageId:p.message.message_id})}await d(),this.observeRequestAcknowledged(e.deliveryId,p.message)}catch(e){const a=await this.journal.get(n.operationId);if(a&&isCommittedCorePhase(a.phase)&&O)throw e;const o=!a||!isCommittedCorePhase(a.phase)||e instanceof RuntimeCommandError&&"OUTCOME_UNKNOWN"===e.code?e:new RuntimeCommandError("OUTCOME_UNKNOWN","Core effect committed before terminal mapping",void 0,{cause:e});this.observeRequestFailure(n.operationId,n.method,o);const r=failurePayload(n,o,a?.updatedAt??(new Date).toISOString());await this.channel.append({operationId:n.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:r}),s.mark("append-terminal-failure"),await d()}finally{s.finish(),c.abort(),a.removeEventListener("abort",_)}}async handlePoison(e,t,a){this.currentLease(a);(await this.poisonJournal.record({delivery:e,reason:durablePoisonReason(t),limit:this.options.poisonDeliveryLimit??3})).terminal&&await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(a)})}observeRequestTerminalAccepted(e,t){try{this.options.onRequestTerminalAccepted?.({deliveryId:e,message:t})}catch{}}observeRequestAcknowledged(e,t){try{this.options.onRequestAcknowledged?.({deliveryId:e,message:t})}catch{}}async forwardProgress(e,t,a){for await(const o of t)await this.channel.append({operationId:e.operationId,lease:this.currentLease(a),type:RUNTIME_MESSAGE_TYPES.progress,payload:{...runtimeMessageBase(e),phase:o.phase,progress:o}})}async reject(e,t,a){await this.channel.append({operationId:e.operationId,lease:this.currentLease(a),type:RUNTIME_MESSAGE_TYPES.final,payload:prestartFailurePayload(e,t)})}async markOutcomeUnknownIfMutable(e){"prepared"!==e.phase&&"started"!==e.phase||await this.journal.transition({operationId:e.operationId,expectedRevision:e.revision,phase:"outcome_unknown",errorCode:"OUTCOME_UNKNOWN"})}async projectSessionModelAfterEffect(e,t,a,o){const r=Object.freeze({state:"pending",revision:o?.revision??`${Math.max(0,a.revision)}`}),n=e.command;if("session.setModel"!==n.name||"conversation"!==n.context.scope)return r;const i=t.sessionModelProjection;if(!i)return r;try{await i.project({conversationId:n.context.conversation.runtimeConversationUid,modelOverrideId:n.params.modelOverrideId});const e=Object.freeze({state:"synced",revision:r.revision});try{const t=await this.journal.get(a.operationId)??a;if("projection_committed"===t.phase&&"synced"===t.projectionReceipt?.snapshot.state)return Object.freeze({state:"synced",revision:t.projectionReceipt.snapshot.revision});await this.journal.transition({operationId:t.operationId,expectedRevision:t.revision,phase:"projection_committed",projectionSnapshot:e})}catch{}return e}catch(e){return this.observeDeliveryError(e),r}}async publishProjectionSynced(e,t,a){const o=this.currentLease(t),r=await this.channel.history({operationId:e.operationId,lease:o});if("found"===r.status&&"synced"===r.snapshot.projectionState)return;const n={...runtimeMessageBase(e),revision:a.revision};("found"!==r.status||"reserved"===r.snapshot.projectionState||"pending"!==r.snapshot.projectionState&&void 0===r.snapshot.projectionPending)&&await this.channel.append({operationId:e.operationId,lease:o,type:RUNTIME_MESSAGE_TYPES.projectionPending,payload:n}),await this.channel.append({operationId:e.operationId,lease:o,type:RUNTIME_MESSAGE_TYPES.projectionSynced,payload:{...n,...a.platformAgentId?{platformAgentId:a.platformAgentId}:{}}})}journalLineage(){return this.options.getJournalLineage?.()??{journalStoreId:this.options.journalStoreId,journalGeneration:this.options.journalGeneration}}currentLease(e){const t=this.getLease();if(!t||t.instanceId!==e.instanceId||t.leaseId!==e.leaseId||t.runtimeEpoch!==e.runtimeEpoch||t.handlerIdentity!==e.handlerIdentity||!Number.isFinite(Date.parse(t.leaseExpiresAt))||Date.parse(t.leaseExpiresAt)<=Date.now())throw new RuntimeCommandError("INSTANCE_EPOCH_MISMATCH","runtime message lease changed");return t}}function ephemeralQueryAccept(e){return{operationId:e.operationId,command:e.command.name,paramsHash:e.paramsHash,runtimeEpoch:e.dispatchEpoch,phase:"prepared",revision:1,updatedAt:(new Date).toISOString(),messageBinding:{requestMessageId:e.requestMessageId,requestHash:e.requestHash,acceptedAt:(new Date).toISOString()}}}function durablePoisonReason(e){const t=e.replace(/[^a-z0-9_:.-]+/gi,"_").replace(/^_+|_+$/g,"").slice(0,256);if(!t)throw new Error("poison reason is empty");return t}function isCommittedCorePhase(e){return"effect_committed"===e||"projection_committed"===e}const CORE_RECOVERY_DECISIONS=new Set(["execute","resume","replay_effect_committed","resume_projection","publish_committed_result","publish_projected_result","publish_terminal_result"]);function decideMessageServiceRecovery(e,t,a,o){const r=RUNTIME_INVOCATION_PARITY_ENTRIES.find(e=>e.acpMethod===t.method),n=e.terminal?"terminal":"blocked"===e.projectionState?"projection_blocked":"synced"===e.projectionState?"projection_synced":"pending"===e.projectionState?"projection_pending":e.effectCommitted?"runtime_committed":o?"running":"queued",i="failed"===a?.phase||"outcome_unknown"===a?.phase?"terminal":a?.phase,s=a&&a.runtimeEpoch===t.dispatchEpoch&&(void 0===a.messageBinding||a.messageBinding.requestMessageId===t.requestMessageId&&a.messageBinding.requestHash===t.requestHash)?"continuous":"discontinuous";return reduceRuntimeRecoveryPolicy({recoveryClass:r?.recoveryClass??RUNTIME_INVOCATION_RECOVERY_CLASSES[t.method],projectionRequired:"mcp/set"===t.method||"mcp/unset"===t.method||(r?.projectionRequired??!1),messageServicePhase:n,executionBoundaryCrossed:o,lineageContinuity:s,journalState:a?"available":"unavailable",...i?{journalPhase:i}:{}})}export function sanitizeRuntimeServiceResult(e,t,a,o){if("session/clear"===e)return serviceClearResult(t,a?.historyBoundary);if("session/set_model"===e)return serviceSetModelResult(t,a);if(!(e in SERVICE_CANONICAL_COMMAND_NAMES))return t;const r="cron/status"===e&&record(t)?{enabled:t.enabled,jobCount:t.jobCount,..."number"==typeof t.nextWakeAtMs?{nextWakeAtMs:t.nextWakeAtMs}:{}}:t;return mapCanonicalResultToService(e,r,{...o?{platformAgentId:o}:{},classifySkillOrigin:e=>e.bundled?{origin:"bundled",slug:e.slug}:{origin:"legacy_runtime",slug:e.slug},resolveMcpView:e=>({name:e.name,transport:e.transport,origin:"legacy_runtime",...void 0===e.connected?{}:{connected:e.connected},...void 0===e.connectionTimeoutMs?{}:{connectionTimeoutMs:e.connectionTimeoutMs}}),sanitizeDiagnostic:e=>/^[A-Z][A-Z0-9_]{0,63}$/.test(e)?e:"RUNTIME_EXECUTION_FAILED"})}function serviceClearResult(e,t){if(!record(e)||!0!==e.cleared||"string"!=typeof e.historyGeneration||!t||"message-service"!==t.kind)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed clear result lacks its Message Service receipt");const a=t;if(!a.committedIntentId)throw new RuntimeCommandError("OUTCOME_UNKNOWN","Message Service clear receipt is unavailable");return{...e,clearIntentId:a.committedIntentId()}}function serviceSetModelResult(e,t){if(!record(e)||"string"!=typeof e.effectiveModelId||!t)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed set_model result is invalid");const a=t.verifiedMessageGrant?.claims.command;if(!a||"session.setModel"!==a.name||"conversation"!==a.context.scope)throw new RuntimeCommandError("OUTCOME_UNKNOWN","set_model Service target receipt is unavailable");const o=a.params.modelOverrideId;return{conversationId:a.context.conversation.runtimeConversationUid,...null===o?{defaultModelId:e.effectiveModelId}:{},modelOverrideId:o,effectiveModelId:e.effectiveModelId,effectState:"committed",projectionState:"synced",operationId:t.operationId}}function isAgentProjectionMethod(e){return"agent/create"===e||"agent/update"===e||"agent/delete"===e||"agent/applyTemplate"===e}function methodRequiresProjectionRevision(e){return isAgentProjectionMethod(e)||"session/set_model"===e}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function sameLeaseBinding(e,t){return e.instanceId===t.instanceId&&e.leaseId===t.leaseId&&e.handlerIdentity===t.handlerIdentity&&e.runtimeEpoch===t.runtimeEpoch}function failurePayload(e,t,a){const o=t instanceof RuntimeCommandError?t.code:"RUNTIME_EXECUTION_FAILED",r=o in RUNTIME_ERROR_DESCRIPTORS?o:"RUNTIME_EXECUTION_FAILED",n="OUTCOME_UNKNOWN"===r||"INSTANCE_EPOCH_MISMATCH"===r?"outcome_unknown":"COMMAND_EXPIRED"===r?"expired":"OPERATION_CANCELLED"===r?"cancelled":"failed",i="outcome_unknown"===n?"OUTCOME_UNKNOWN":r,s=RUNTIME_ERROR_DESCRIPTORS[i],c="outcome_unknown"===n?"outcome_unknown":n;return{...runtimeMessageBase(e),outcome:n,response:{jsonrpc:"2.0",id:e.request.id,error:{code:s.jsonRpcCode,message:i,data:{code:i,operationId:e.operationId,effectState:c,retryMode:s.retryMode}}},completedAt:a}}function prestartFailurePayload(e,t){const a="invalid_execution_grant"===t?"INVALID_EXECUTION_GRANT":"unsupported_method"===t?"METHOD_NOT_SUPPORTED":"authority_mismatch"===t?"INSTANCE_EPOCH_MISMATCH":"execution_deadline_exceeded"===t?"COMMAND_EXPIRED":"cancelled_before_dispatch"===t?"OPERATION_CANCELLED":"resource_resolution_rejected"===t?"INVALID_INVOCATION":"RUNTIME_EXECUTION_FAILED",o=RUNTIME_ERROR_DESCRIPTORS[a in RUNTIME_ERROR_DESCRIPTORS?a:"RUNTIME_EXECUTION_FAILED"],r="COMMAND_EXPIRED"===a?"expired":"OPERATION_CANCELLED"===a?"cancelled":"failed";return{...runtimeMessageBase(e),outcome:r,response:{jsonrpc:"2.0",id:e.request.id,error:{code:o.jsonRpcCode,message:a,data:{code:a,operationId:e.operationId,effectState:r,retryMode:o.retryMode}}},completedAt:(new Date).toISOString()}}function abortable(e,t){return t?t.aborted?Promise.resolve():new Promise((a,o)=>{const r=()=>a();t.addEventListener("abort",r,{once:!0}),e.then(()=>{t.removeEventListener("abort",r),a()},e=>{t.removeEventListener("abort",r),o(e)})}):e}function delay(e,t){return new Promise(a=>{if(t?.aborted)return a();const o=()=>{clearTimeout(r),a()},r=setTimeout(()=>{t?.removeEventListener("abort",o),a()},e);t?.addEventListener("abort",o,{once:!0})})}
1
+ import{RUNTIME_ERROR_DESCRIPTORS,RUNTIME_HASH_DOMAINS,RUNTIME_INVOCATION_PARITY_ENTRIES,RUNTIME_INVOCATION_RECOVERY_CLASSES,SERVICE_CANONICAL_COMMAND_NAMES,mapCanonicalResultToService}from"@beeos-ai/beeos-types/runtime";import{reduceRuntimeRecoveryPolicy}from"@beeos-ai/beeos-types/runtime/internal";import{verifyAndCreateMessageServiceCoreExecutionAttempt}from"./core-execution-attempt-context.js";import{awaitRuntimeProjection,hasEffectReceiptHandoff,RuntimeCommandError}from"./runtime-command-dispatcher.js";import{createRuntimeAppendTimingRecorder}from"./runtime-append-timing.js";import{runtimeCommandIsReplayableQuery}from"./runtime-command-journal.js";import{RUNTIME_MESSAGE_TYPES,runtimeMessageBase,runtimeMessageHash,semanticEqual,validateRuntimeCancelEnvelope,validateRuntimeRequestEnvelope}from"./runtime-message-channel-contract.js";import{RuntimeMessageChannelProtocolError}from"./message-service-runtime-message-channel.js";import{RuntimeResourceResolutionError}from"./runtime-operation-resource-resolver.js";import{RuntimeTransportFailurePolicy}from"@beeos-ai/cloud-agent-sdk";import{NativePromptExecutionFailure,nativePromptCancellationReason}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{CloudGatewayGrantJwksVerifier}from"./split-runtime-authorization-verifier.js";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){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 r;const n=new SdkRuntimeMessageChannel(()=>{if(!r)throw new Error("SDK runtime delivery consumer is not attached");return r}),i=new MsRuntimeMessageChannelAdapter(e.dispatcher,n,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 r=e.getBinding();return{journalStoreId:r.journalStoreId,journalGeneration:r.journalGeneration}}}:{}}),t=this.deps.client?this.deps.verifier:void 0,s=this.deps.client&&t?new SessionNewRuntimeDeliveryBridge({client:this.deps.client,consumer:()=>{if(!r)throw new Error("SDK runtime delivery consumer is not attached");return r},verifier:t,getLease:()=>e.getLease(),createRuntimeSession:e.createRuntimeSession,poison:async(e,r,n)=>{await i.acceptPoisonDelivery(e,r,n)}}):void 0,o=this.deps.client?.methods??this.deps.runtimeDelivery;if(!o)throw new Error("runtime delivery owner is unavailable");return r=o.consume({onDelivery:async(r,n)=>{const t=currentFencedLease(e,n.lease),o=decodeRuntimeBrokerDelivery(r);if(isCanonicalSessionNewDelivery(o))return s?void await s.acceptDelivery(o,t,n.signal):void await i.acceptPoisonDelivery(o,"cloud_session_new_unsupported",t);await i.acceptDelivery(o,t,n.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}),i.attachExternalDeliveryOwner(r),i}}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 r=await this.consumer().history(e.operationId);return"found"!==r.status?r:{status:"found",snapshot:decodeRuntimeOperationHistory(r.snapshot,e.operationId)}}async append(e){assertLeaseAvailable(e.lease);const r=await this.consumer().append(e.operationId,e.type,e.payload,e.executionGrant);if("created"===r.outcome||"duplicate"===r.outcome)return{disposition:"created"===r.outcome?"created":"reused",message:decodeRuntimeAppendMessage(r.message,e)};if(r.history){const n=findReconciledMessage(decodeRuntimeOperationHistory(r.history,e.operationId),e);if(n)return{disposition:"reused",message:n}}throw new RuntimeMessageChannelProtocolError("runtime append outcome is unknown after history reconcile",503,"OUTCOME_UNKNOWN")}}function currentFencedLease(e,r){const n=e.getLease(),i=e.getBinding?.()??e.binding;if(!n||n.instanceId!==r.instanceId||n.handlerIdentity!==r.handlerIdentity||n.runtimeEpoch!==r.runtimeEpoch||n.leaseId!==r.leaseId||i.journalStoreId!==r.journalStoreId||i.journalGeneration!==r.journalGeneration)throw new Error("runtime delivery lease fence changed");if(Date.parse(n.leaseExpiresAt)<=Date.now())throw new Error("runtime delivery lease expired");return n}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,r){for(let n=e.messages.length-1;n>=0;n-=1)try{return decodeRuntimeAppendMessage(e.messages[n],r)}catch{}}
1
+ import{CloudGatewayGrantJwksVerifier,GatewayGrantJwksVerifier}from"./split-runtime-authorization-verifier.js";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{}}
@@ -1 +1 @@
1
- import{randomUUID}from"node:crypto";import{verifyAndCreateServiceCoreExecutionAttempt}from"./core-execution-attempt-context.js";import{RuntimeCommandError}from"./runtime-command-dispatcher.js";import{RuntimeClaimAuthorityProtocolError}from"./message-service-runtime-claim-authority.js";import{sessionSetModelMappingMatches}from"./session-set-model-mapping.js";import{RuntimeTransportFailurePolicy}from"@beeos-ai/cloud-agent-sdk";export class MsRuntimeRpcAdapter{dispatcher;authority;authorizationVerifier;attemptPorts;authorizationJournal;getLease;options;controller;running;constructor(e,t,r,a,n,o,i){this.dispatcher=e,this.authority=t,this.authorizationVerifier=r,this.attemptPorts=a,this.authorizationJournal=n,this.getLease=o,this.options=i}start(){if(this.running)return;this.controller=new AbortController;const e=this.loop(this.controller.signal).finally(()=>{this.running===e&&(this.running=void 0)});this.running=e}async stop(e){const t=this.running;if(this.controller?.abort(),!t)return;await waitForAbort(t,e)===aborted&&this.running===t&&(this.running=void 0)}journalLineage(){return this.options.getJournalLineage?.()??{journalStoreId:this.options.journalStoreId,journalGeneration:this.options.journalGeneration}}async loop(e){let t=randomUUID(),r="",a="";for(;!e.aborted;){const n=this.getLease();if(!n){await delay(this.options.pollDelayMs??1e3,e);continue}const o=this.journalLineage(),i=`${n.instanceId}\n${n.runtimeEpoch}\n${this.options.handlerIdentity}\n${o.journalStoreId}\n${o.journalGeneration}`;if(r&&r!==i&&(t=randomUUID()),r=i,a!==i)try{const t=await this.authorizationJournal.listRecoverable(n.runtimeEpoch);for(const r of t){if(e.aborted||this.getLease()?.leaseId!==n.leaseId)break;if(!await this.recoverExact({operationId:r.operationId,requestMessageId:r.requestMessageId,dispatchEpoch:r.runtimeEpoch},n,e))throw new Error("durable runtime invocation is still owned by another claim")}a=i}catch{await delay(this.options.pollDelayMs??1e3,e);continue}let s;try{const r=this.authority.claimNext({claimRequestId:t,instanceId:n.instanceId,handlerIdentity:this.options.handlerIdentity,runtimeEpoch:n.runtimeEpoch,journalStoreId:o.journalStoreId,journalGeneration:o.journalGeneration,runtimeLeaseCredential:n.runtimeLeaseCredential}),a=await waitForAbort(r,e);if(a===aborted)return;s=a}catch(t){if(e.aborted)return;if(t instanceof RuntimeClaimAuthorityProtocolError)return;await delay(this.options.pollDelayMs??1e3,e);continue}if(e.aborted)return;t=randomUUID(),"empty"!==s.status?"fenced"!==s.status?await this.handleClaimed(s,n,e,"start").catch(()=>{}):await delay(this.options.pollDelayMs??1e3,e):await delay(Math.max(s.retryAfterMs,this.options.pollDelayMs??0),e)}}async recoverExact(e,t,r){if(e.dispatchEpoch!==t.runtimeEpoch)throw new Error("recovery candidate runtime epoch mismatch");const a=this.journalLineage(),n=await this.authority.claimExact({operationId:e.operationId,requestMessageId:e.requestMessageId,handlerIdentity:this.options.handlerIdentity,dispatchEpoch:e.dispatchEpoch,runtimeEpoch:t.runtimeEpoch,journalStoreId:a.journalStoreId,journalGeneration:a.journalGeneration,runtimeLeaseCredential:t.runtimeLeaseCredential});return"terminal"===n.status?(await this.authorizationJournal.markTerminal(e.operationId).catch(()=>{}),!0):"claimed"===n.status&&(await this.handleClaimed(n,t,r,"recovery"),!0)}async handleClaimed(e,t,r,a="start"){const n={operationId:e.request.operationId,requestMessageId:e.request.messageId,dispatchEpoch:e.request.payload.command.context.dispatchEpoch},o=async()=>{await this.authorizationJournal.markTerminal(n.operationId).catch(()=>{})},i=async e=>{await this.authority.commitFailure(e),await o()},s=()=>{const r=this.getLease(),a=r?.leaseId===t.leaseId&&r.runtimeEpoch===t.runtimeEpoch?r.runtimeLeaseCredential:t.runtimeLeaseCredential;return{operationId:n.operationId,requestMessageId:n.requestMessageId,...e.fence,runtimeLeaseCredential:a}},c=async e=>{try{await i(e)}finally{await this.authority.releaseClaim({...s(),reason:"claim_rejected"}).catch(()=>{})}};if(e.cancelRequested)return await i({operationId:n.operationId,requestMessageId:n.requestMessageId,request:e.request,fence:e.fence,claimLeaseExpiresAt:e.leaseExpiresAt,runtimeLeaseCredential:t.runtimeLeaseCredential,attempt:prestartAttempt(e.request),outcome:"cancelled",code:"OPERATION_CANCELLED"}),void await this.authority.releaseClaim({...s(),reason:"cancelled"});let u;try{u=await this.authorizationJournal.prepare({operationId:n.operationId,requestMessageId:n.requestMessageId,method:e.request.payload.request.method,commandHash:e.request.payload.commandHash,runtimeEpoch:t.runtimeEpoch,journalStoreId:e.fence.journalStoreId,journalGeneration:e.fence.journalGeneration})}catch{return void await c({operationId:n.operationId,requestMessageId:n.requestMessageId,request:e.request,fence:e.fence,claimLeaseExpiresAt:e.leaseExpiresAt,runtimeLeaseCredential:t.runtimeLeaseCredential,attempt:prestartAttempt(e.request),outcome:"failed",code:"UNAUTHORIZED_TARGET"}).catch(()=>{})}const d=await this.authority.authorize({request:e.request,fence:e.fence,lease:t,journal:u});if("authorized"!==d.status)return"terminal"===d.status?(await o(),void await this.authority.releaseClaim({...s(),reason:"completed"}).catch(()=>{})):void await c({operationId:n.operationId,requestMessageId:n.requestMessageId,request:e.request,fence:e.fence,claimLeaseExpiresAt:e.leaseExpiresAt,runtimeLeaseCredential:t.runtimeLeaseCredential,attempt:prestartAttempt(e.request),outcome:"expired"===d.status?"expired":"cancelled"===d.status?"cancelled":"failed",code:"expired"===d.status?"COMMAND_EXPIRED":"cancelled"===d.status?"OPERATION_CANCELLED":"fenced"===d.status?"INSTANCE_EPOCH_MISMATCH":"UNAUTHORIZED_TARGET"});const m={operationId:n.operationId,requestMessageId:n.requestMessageId,request:e.request,fence:e.fence,claimLeaseExpiresAt:e.leaseExpiresAt,runtimeLeaseCredential:t.runtimeLeaseCredential,attempt:d.attempt},l={...m,attempt:prestartAttempt(e.request)};let h;const p=new AbortController;let E;try{assertCommandCorrelation(e.request,d.attempt.command,t.runtimeEpoch),h=await verifyAndCreateServiceCoreExecutionAttempt({operationId:n.operationId,runtimeEpoch:t.runtimeEpoch,fence:e.fence,authorization:d.attempt.authorization,derivationContext:{...d.attempt.derivationContext,localJournalRevision:u.journalRevisionBeforeAttempt,localPreparedEntryHash:u.preparedEntryHash},verifier:this.authorizationVerifier,abortSignal:p.signal,recordVerifiedAttempt:async t=>{const r=t.request.binding;await this.authorizationJournal.recordBoundary({operationId:n.operationId,expectedRevision:u.revision,preparedEntryHash:u.preparedEntryHash,boundary:{executionBoundaryId:r.executionBoundaryId,boundaryAssertionHash:r.boundaryAssertionHash,executionMode:r.executionMode,fence:e.fence,...r.handoffId?{handoffId:r.handoffId}:{}}})},resolvePorts:async()=>E??=await this.attemptPorts.resolve(m,{getRuntimeLeaseCredential:()=>this.currentRuntimeLeaseCredential(t)})})}catch{return p.abort(),void await c({...l,outcome:"failed",code:"UNAUTHORIZED_TARGET"})}if(!h.ok)return p.abort(),void await c({...l,outcome:"failed",code:"UNAUTHORIZED_TARGET"});let I=!1,C=!1;const f=new RuntimeTransportFailurePolicy;let y,w,M,v,N=!1,A=!1,R=!1,O=!1,T=!1,_=!1,g=!1;const b=new Promise(e=>{v=e}),L=e=>{g||(g=!0,v(e))};let x;const U=()=>{T=!0,p.abort(),M&&!x&&(x=M.cancel().catch(()=>({status:"not_cancellable"})))},q=()=>{I=!0,L("fenced"),U()},S=()=>q();r.addEventListener("abort",S,{once:!0});const P=()=>{const e=this.getLease();e&&e.leaseId===t.leaseId&&e.runtimeEpoch===t.runtimeEpoch||q()},H=setInterval(P,100);H.unref?.();const D=setInterval(()=>{this.authority.renewClaim(s()).then(e=>{f.recordSuccess(),"renewed"===e.status&&e.cancelRequested?(C=!0,L("cancel_requested"),U()):"renewed"!==e.status&&q()}).catch(()=>{f.recordFailure()&&q()})},this.options.claimRenewIntervalMs??2e4);D.unref?.();const j=Date.parse(d.attempt.command.context.executionDeadline)-Date.now(),G=setTimeout(()=>{_=!0,L("deadline"),U()},Math.max(0,Math.min(j,2147483647)));G.unref?.();const z=async e=>{if(!y)return;const r=this.currentConversationRunBoundaryLease(t);await this.finishConversationRunBoundary(m,r,y,e,"recovery"===a?"recovery":"runtime"),y=void 0};try{if(P(),I||r.aborted)return void await i({...m,outcome:"outcome_unknown",code:"INSTANCE_EPOCH_MISMATCH"});if(await this.authority.appendStarted(m),I||r.aborted)return void await i({...m,outcome:"outcome_unknown",code:"INSTANCE_EPOCH_MISMATCH"});if(_)return void await i({...m,outcome:"expired",code:"COMMAND_EXPIRED"});if(C)return void await i({...m,outcome:"cancelled",code:"OPERATION_CANCELLED"});const e=await this.startConversationRunBoundary(m,t,E);if(e?.rejected)return void await i({...m,outcome:"failed",code:e.code});if(y=e,I||r.aborted)throw new RuntimeCommandError("INSTANCE_EPOCH_MISMATCH","runtime authority fenced after the conversation run boundary started");if("recovery"===a&&y)throw new RuntimeCommandError("OUTCOME_UNKNOWN","session.prompt crossed its durable run boundary before recovery");if(_)throw new RuntimeCommandError("COMMAND_EXPIRED","session.prompt expired after the conversation run boundary started");if(C)throw new RuntimeCommandError("OPERATION_CANCELLED","session.prompt was cancelled after the conversation run boundary started");let n;M=this.dispatcher.dispatch(d.attempt.command,h.context),A=!0,T&&U();const s=this.forwardProgress(M.progress,m,()=>I||r.aborted||C||_).catch(e=>{n=e}),c=M.completion.then(e=>(clearTimeout(G),{status:"completed",result:e}),e=>(clearTimeout(G),{status:"failed",error:e}));let u=await Promise.race([c,b.then(e=>({status:"interrupted",reason:e}))]);if("interrupted"===u.status){const e=u.reason;U();if("cancel_requested"===(x?await Promise.race([x,delay(this.options.cancellationGraceMs??1e3).then(()=>({status:"not_cancellable"}))]):{status:"not_cancellable"}).status&&(u=await Promise.race([c,delay(this.options.cancellationGraceMs??1e3).then(()=>({status:"interrupted",reason:e}))])),"interrupted"===u.status)throw new RuntimeCommandError("fenced"===u.reason?"INSTANCE_EPOCH_MISMATCH":"OUTCOME_UNKNOWN","session.prompt execution did not converge after interruption")}if(R=!0,"failed"===u.status)throw u.error;const l=u.result;N=!0;const p="session.prompt"===d.attempt.command.name&&!0===l.requestAborted;if(w=p?"cancelled":"completed",await s,n)throw n;if(await z(w),I||r.aborted)return void await i({...m,outcome:"outcome_unknown",code:"INSTANCE_EPOCH_MISMATCH"});if(_)return void await i({...m,outcome:"outcome_unknown",code:"OUTCOME_UNKNOWN"});if(C&&!p)throw new RuntimeCommandError("OUTCOME_UNKNOWN","cancel request raced a locally completed runtime effect");await this.authority.commitResult({...m,command:d.attempt.command,result:sanitizeServiceResult(d.attempt.command.name,l)}),await o()}catch(e){let t=e;if(y&&(!A||R))try{await z(w??(C||_?"cancelled":"failed"))}catch(r){t=new RuntimeCommandError("OUTCOME_UNKNOWN",`conversation run terminal outcome is unknown: ${errorText(r)}`,void 0,{cause:e})}if(N&&!isUncertainRuntimeError(t)&&(t=new RuntimeCommandError("OUTCOME_UNKNOWN",`runtime effect completed before its terminal receipt: ${errorText(t)}`,void 0,{cause:e})),y)return void(O=!0);const r=serviceRuntimeFailureCode(t),a="OUTCOME_UNKNOWN"===r||"INSTANCE_EPOCH_MISMATCH"===r||I||A&&(C||_),n="COMMAND_EXPIRED"===r||!A&&_,o=!A&&C;await i({...m,outcome:a?"outcome_unknown":n?"expired":o?"cancelled":"failed",code:"INSTANCE_EPOCH_MISMATCH"===r||I?"INSTANCE_EPOCH_MISMATCH":a?"OUTCOME_UNKNOWN":n?"COMMAND_EXPIRED":o?"OPERATION_CANCELLED":r??"RUNTIME_EXECUTION_FAILED"})}finally{clearInterval(H),clearInterval(D),clearTimeout(G),r.removeEventListener("abort",S),p.abort(),await this.authority.releaseClaim({...s(),reason:r.aborted||O?"worker_shutdown":"completed"}).catch(()=>{})}}async startConversationRunBoundary(e,t,r){const a=e.attempt.command;if("session.prompt"!==a.name)return;const n=r?.conversationRunBoundary;if(!n)throw new RuntimeCommandError("INVALID_PARAMS","Service session.prompt lacks its conversation run boundary");const o=a.context.conversation,i=await n.boundary.start({operationId:e.operationId,requestMessageId:e.requestMessageId,conversationId:o.runtimeConversationUid,historyGeneration:n.historyGeneration,runtimeRunId:a.params.runtimeRunId,lease:exactRunBoundaryLease(t)});if("rejected"===i.status)return{rejected:!0,code:i.reason};if(i.historyGeneration!==n.historyGeneration)throw new RuntimeCommandError("OUTCOME_UNKNOWN","conversation run boundary changed history generation");return{boundary:n.boundary,historyGeneration:n.historyGeneration,activeRunRegistrationId:i.activeRunRegistrationId,runtimeRunId:a.params.runtimeRunId}}currentRuntimeLeaseCredential(e){const t=this.getLease();if(!t||t.leaseId!==e.leaseId||t.runtimeEpoch!==e.runtimeEpoch)throw new RuntimeCommandError("INSTANCE_EPOCH_MISMATCH","runtime lease changed before deferred resource redemption");return t.runtimeLeaseCredential}currentConversationRunBoundaryLease(e){const t=this.getLease();if(!t||t.leaseId!==e.leaseId||t.runtimeEpoch!==e.runtimeEpoch||t.handlerIdentity!==e.handlerIdentity)throw new RuntimeCommandError("INSTANCE_EPOCH_MISMATCH","runtime lease changed before conversation run convergence");return t}async finishConversationRunBoundary(e,t,r,a,n){const o=e.attempt.command.context;if("conversation"!==o.scope)throw new RuntimeCommandError("OUTCOME_UNKNOWN","conversation run boundary lost its target");const i=await r.boundary.finish({activeRunRegistrationId:r.activeRunRegistrationId,operationId:e.operationId,requestMessageId:e.requestMessageId,conversationId:o.conversation.runtimeConversationUid,historyGeneration:r.historyGeneration,runtimeRunId:r.runtimeRunId,terminalState:a,source:n,lease:exactRunBoundaryLease(t)});if("rejected"===i.status||i.activeRunRegistrationId!==r.activeRunRegistrationId)throw new RuntimeCommandError("OUTCOME_UNKNOWN",`conversation run finish rejected: ${"rejected"===i.status?i.reason:"registration_mismatch"}`)}async forwardProgress(e,t,r){for await(const a of e){if(r())return;await this.authority.appendProgress({...t,progress:a})}}}function exactRunBoundaryLease(e){return{leaseId:e.leaseId,handlerIdentity:e.handlerIdentity,runtimeEpoch:e.runtimeEpoch,runtimeLeaseCredential:e.runtimeLeaseCredential}}function serviceRuntimeFailureCode(e){const t=e?.code;return t&&["OUTCOME_UNKNOWN","INSTANCE_EPOCH_MISMATCH","COMMAND_EXPIRED","OPERATION_CANCELLED","IDEMPOTENCY_CONFLICT","UNAUTHORIZED_TARGET","AGENT_DEFAULT_MODEL_NOT_CONFIGURED"].includes(t)?t:void 0}function isUncertainRuntimeError(e){return e instanceof RuntimeCommandError&&("OUTCOME_UNKNOWN"===e.code||"INSTANCE_EPOCH_MISMATCH"===e.code)}function errorText(e){return e instanceof Error?e.message:String(e)}export function sanitizeServiceResult(e,t){if("cron.status"!==e||!t||"object"!=typeof t)return t;const r=t;return{enabled:r.enabled,jobCount:r.jobCount,..."number"==typeof r.nextWakeAtMs?{nextWakeAtMs:r.nextWakeAtMs}:{}}}function assertCommandCorrelation(e,t,r){if(e.operationId!==t.context.operationId||e.payload.paramsHash!==t.context.paramsHash||t.context.dispatchEpoch!==r||e.payload.command.name!==t.name||!sessionSetModelMappingMatches(e.payload.request,t))throw new Error("runtime invocation command correlation failed")}function prestartAttempt(e){return{command:e.payload.command,executionBoundaryId:"prestart",boundaryAssertionHash:e.payload.commandHash,executionMode:"start",validationContext:{},authorization:{},derivationContext:{}}}const aborted=Symbol("aborted");function waitForAbort(e,t){return t?t.aborted?(e.catch(()=>{}),Promise.resolve(aborted)):new Promise((r,a)=>{let n=!1;const o=()=>{n||(n=!0,r(aborted))};t.addEventListener("abort",o,{once:!0}),e.then(e=>{n||(n=!0,t.removeEventListener("abort",o),r(e))},e=>{n||(n=!0,t.removeEventListener("abort",o),a(e))})}):e}const delay=(e,t)=>new Promise(r=>{if(t?.aborted)return r();const a=()=>{clearTimeout(n),r()},n=setTimeout(()=>{t?.removeEventListener("abort",a),r()},e);t?.addEventListener("abort",a,{once:!0})});
1
+ import{randomUUID}from"node:crypto";import{verifyAndCreateServiceCoreExecutionAttempt}from"./core-execution-attempt-context.js";import{RuntimeCommandError}from"./runtime-command-dispatcher.js";import{RuntimeClaimAuthorityProtocolError}from"./message-service-runtime-claim-authority.js";import{sessionSetModelMappingMatches}from"./session-set-model-mapping.js";import{RuntimeTransportFailurePolicy}from"./runtime-transport-failure-policy.js";export class MsRuntimeRpcAdapter{dispatcher;authority;authorizationVerifier;attemptPorts;authorizationJournal;getLease;options;controller;running;constructor(e,t,r,a,n,o,i){this.dispatcher=e,this.authority=t,this.authorizationVerifier=r,this.attemptPorts=a,this.authorizationJournal=n,this.getLease=o,this.options=i}start(){if(this.running)return;this.controller=new AbortController;const e=this.loop(this.controller.signal).finally(()=>{this.running===e&&(this.running=void 0)});this.running=e}async stop(e){const t=this.running;if(this.controller?.abort(),!t)return;await waitForAbort(t,e)===aborted&&this.running===t&&(this.running=void 0)}journalLineage(){return this.options.getJournalLineage?.()??{journalStoreId:this.options.journalStoreId,journalGeneration:this.options.journalGeneration}}async loop(e){let t=randomUUID(),r="",a="";for(;!e.aborted;){const n=this.getLease();if(!n){await delay(this.options.pollDelayMs??1e3,e);continue}const o=this.journalLineage(),i=`${n.instanceId}\n${n.runtimeEpoch}\n${this.options.handlerIdentity}\n${o.journalStoreId}\n${o.journalGeneration}`;if(r&&r!==i&&(t=randomUUID()),r=i,a!==i)try{const t=await this.authorizationJournal.listRecoverable(n.runtimeEpoch);for(const r of t){if(e.aborted||this.getLease()?.leaseId!==n.leaseId)break;if(!await this.recoverExact({operationId:r.operationId,requestMessageId:r.requestMessageId,dispatchEpoch:r.runtimeEpoch},n,e))throw new Error("durable runtime invocation is still owned by another claim")}a=i}catch{await delay(this.options.pollDelayMs??1e3,e);continue}let s;try{const r=this.authority.claimNext({claimRequestId:t,instanceId:n.instanceId,handlerIdentity:this.options.handlerIdentity,runtimeEpoch:n.runtimeEpoch,journalStoreId:o.journalStoreId,journalGeneration:o.journalGeneration,runtimeLeaseCredential:n.runtimeLeaseCredential}),a=await waitForAbort(r,e);if(a===aborted)return;s=a}catch(t){if(e.aborted)return;if(t instanceof RuntimeClaimAuthorityProtocolError)return;await delay(this.options.pollDelayMs??1e3,e);continue}if(e.aborted)return;t=randomUUID(),"empty"!==s.status?"fenced"!==s.status?await this.handleClaimed(s,n,e,"start").catch(()=>{}):await delay(this.options.pollDelayMs??1e3,e):await delay(Math.max(s.retryAfterMs,this.options.pollDelayMs??0),e)}}async recoverExact(e,t,r){if(e.dispatchEpoch!==t.runtimeEpoch)throw new Error("recovery candidate runtime epoch mismatch");const a=this.journalLineage(),n=await this.authority.claimExact({operationId:e.operationId,requestMessageId:e.requestMessageId,handlerIdentity:this.options.handlerIdentity,dispatchEpoch:e.dispatchEpoch,runtimeEpoch:t.runtimeEpoch,journalStoreId:a.journalStoreId,journalGeneration:a.journalGeneration,runtimeLeaseCredential:t.runtimeLeaseCredential});return"terminal"===n.status?(await this.authorizationJournal.markTerminal(e.operationId).catch(()=>{}),!0):"claimed"===n.status&&(await this.handleClaimed(n,t,r,"recovery"),!0)}async handleClaimed(e,t,r,a="start"){const n={operationId:e.request.operationId,requestMessageId:e.request.messageId,dispatchEpoch:e.request.payload.command.context.dispatchEpoch},o=async()=>{await this.authorizationJournal.markTerminal(n.operationId).catch(()=>{})},i=async e=>{await this.authority.commitFailure(e),await o()},s=()=>{const r=this.getLease(),a=r?.leaseId===t.leaseId&&r.runtimeEpoch===t.runtimeEpoch?r.runtimeLeaseCredential:t.runtimeLeaseCredential;return{operationId:n.operationId,requestMessageId:n.requestMessageId,...e.fence,runtimeLeaseCredential:a}},c=async e=>{try{await i(e)}finally{await this.authority.releaseClaim({...s(),reason:"claim_rejected"}).catch(()=>{})}};if(e.cancelRequested)return await i({operationId:n.operationId,requestMessageId:n.requestMessageId,request:e.request,fence:e.fence,claimLeaseExpiresAt:e.leaseExpiresAt,runtimeLeaseCredential:t.runtimeLeaseCredential,attempt:prestartAttempt(e.request),outcome:"cancelled",code:"OPERATION_CANCELLED"}),void await this.authority.releaseClaim({...s(),reason:"cancelled"});let u;try{u=await this.authorizationJournal.prepare({operationId:n.operationId,requestMessageId:n.requestMessageId,method:e.request.payload.request.method,commandHash:e.request.payload.commandHash,runtimeEpoch:t.runtimeEpoch,journalStoreId:e.fence.journalStoreId,journalGeneration:e.fence.journalGeneration})}catch{return void await c({operationId:n.operationId,requestMessageId:n.requestMessageId,request:e.request,fence:e.fence,claimLeaseExpiresAt:e.leaseExpiresAt,runtimeLeaseCredential:t.runtimeLeaseCredential,attempt:prestartAttempt(e.request),outcome:"failed",code:"UNAUTHORIZED_TARGET"}).catch(()=>{})}const d=await this.authority.authorize({request:e.request,fence:e.fence,lease:t,journal:u});if("authorized"!==d.status)return"terminal"===d.status?(await o(),void await this.authority.releaseClaim({...s(),reason:"completed"}).catch(()=>{})):void await c({operationId:n.operationId,requestMessageId:n.requestMessageId,request:e.request,fence:e.fence,claimLeaseExpiresAt:e.leaseExpiresAt,runtimeLeaseCredential:t.runtimeLeaseCredential,attempt:prestartAttempt(e.request),outcome:"expired"===d.status?"expired":"cancelled"===d.status?"cancelled":"failed",code:"expired"===d.status?"COMMAND_EXPIRED":"cancelled"===d.status?"OPERATION_CANCELLED":"fenced"===d.status?"INSTANCE_EPOCH_MISMATCH":"UNAUTHORIZED_TARGET"});const m={operationId:n.operationId,requestMessageId:n.requestMessageId,request:e.request,fence:e.fence,claimLeaseExpiresAt:e.leaseExpiresAt,runtimeLeaseCredential:t.runtimeLeaseCredential,attempt:d.attempt},l={...m,attempt:prestartAttempt(e.request)};let h;const p=new AbortController;let E;try{assertCommandCorrelation(e.request,d.attempt.command,t.runtimeEpoch),h=await verifyAndCreateServiceCoreExecutionAttempt({operationId:n.operationId,runtimeEpoch:t.runtimeEpoch,fence:e.fence,authorization:d.attempt.authorization,derivationContext:{...d.attempt.derivationContext,localJournalRevision:u.journalRevisionBeforeAttempt,localPreparedEntryHash:u.preparedEntryHash},verifier:this.authorizationVerifier,abortSignal:p.signal,recordVerifiedAttempt:async t=>{const r=t.request.binding;await this.authorizationJournal.recordBoundary({operationId:n.operationId,expectedRevision:u.revision,preparedEntryHash:u.preparedEntryHash,boundary:{executionBoundaryId:r.executionBoundaryId,boundaryAssertionHash:r.boundaryAssertionHash,executionMode:r.executionMode,fence:e.fence,...r.handoffId?{handoffId:r.handoffId}:{}}})},resolvePorts:async()=>E??=await this.attemptPorts.resolve(m,{getRuntimeLeaseCredential:()=>this.currentRuntimeLeaseCredential(t)})})}catch{return p.abort(),void await c({...l,outcome:"failed",code:"UNAUTHORIZED_TARGET"})}if(!h.ok)return p.abort(),void await c({...l,outcome:"failed",code:"UNAUTHORIZED_TARGET"});let I=!1,C=!1;const f=new RuntimeTransportFailurePolicy;let y,w,M,v,N=!1,A=!1,R=!1,O=!1,T=!1,_=!1,g=!1;const b=new Promise(e=>{v=e}),L=e=>{g||(g=!0,v(e))};let x;const U=()=>{T=!0,p.abort(),M&&!x&&(x=M.cancel().catch(()=>({status:"not_cancellable"})))},q=()=>{I=!0,L("fenced"),U()},S=()=>q();r.addEventListener("abort",S,{once:!0});const P=()=>{const e=this.getLease();e&&e.leaseId===t.leaseId&&e.runtimeEpoch===t.runtimeEpoch||q()},H=setInterval(P,100);H.unref?.();const D=setInterval(()=>{this.authority.renewClaim(s()).then(e=>{f.recordSuccess(),"renewed"===e.status&&e.cancelRequested?(C=!0,L("cancel_requested"),U()):"renewed"!==e.status&&q()}).catch(()=>{f.recordFailure()&&q()})},this.options.claimRenewIntervalMs??2e4);D.unref?.();const j=Date.parse(d.attempt.command.context.executionDeadline)-Date.now(),G=setTimeout(()=>{_=!0,L("deadline"),U()},Math.max(0,Math.min(j,2147483647)));G.unref?.();const z=async e=>{if(!y)return;const r=this.currentConversationRunBoundaryLease(t);await this.finishConversationRunBoundary(m,r,y,e,"recovery"===a?"recovery":"runtime"),y=void 0};try{if(P(),I||r.aborted)return void await i({...m,outcome:"outcome_unknown",code:"INSTANCE_EPOCH_MISMATCH"});if(await this.authority.appendStarted(m),I||r.aborted)return void await i({...m,outcome:"outcome_unknown",code:"INSTANCE_EPOCH_MISMATCH"});if(_)return void await i({...m,outcome:"expired",code:"COMMAND_EXPIRED"});if(C)return void await i({...m,outcome:"cancelled",code:"OPERATION_CANCELLED"});const e=await this.startConversationRunBoundary(m,t,E);if(e?.rejected)return void await i({...m,outcome:"failed",code:e.code});if(y=e,I||r.aborted)throw new RuntimeCommandError("INSTANCE_EPOCH_MISMATCH","runtime authority fenced after the conversation run boundary started");if("recovery"===a&&y)throw new RuntimeCommandError("OUTCOME_UNKNOWN","session.prompt crossed its durable run boundary before recovery");if(_)throw new RuntimeCommandError("COMMAND_EXPIRED","session.prompt expired after the conversation run boundary started");if(C)throw new RuntimeCommandError("OPERATION_CANCELLED","session.prompt was cancelled after the conversation run boundary started");let n;M=this.dispatcher.dispatch(d.attempt.command,h.context),A=!0,T&&U();const s=this.forwardProgress(M.progress,m,()=>I||r.aborted||C||_).catch(e=>{n=e}),c=M.completion.then(e=>(clearTimeout(G),{status:"completed",result:e}),e=>(clearTimeout(G),{status:"failed",error:e}));let u=await Promise.race([c,b.then(e=>({status:"interrupted",reason:e}))]);if("interrupted"===u.status){const e=u.reason;U();if("cancel_requested"===(x?await Promise.race([x,delay(this.options.cancellationGraceMs??1e3).then(()=>({status:"not_cancellable"}))]):{status:"not_cancellable"}).status&&(u=await Promise.race([c,delay(this.options.cancellationGraceMs??1e3).then(()=>({status:"interrupted",reason:e}))])),"interrupted"===u.status)throw new RuntimeCommandError("fenced"===u.reason?"INSTANCE_EPOCH_MISMATCH":"OUTCOME_UNKNOWN","session.prompt execution did not converge after interruption")}if(R=!0,"failed"===u.status)throw u.error;const l=u.result;N=!0;const p="session.prompt"===d.attempt.command.name&&!0===l.requestAborted;if(w=p?"cancelled":"completed",await s,n)throw n;if(await z(w),I||r.aborted)return void await i({...m,outcome:"outcome_unknown",code:"INSTANCE_EPOCH_MISMATCH"});if(_)return void await i({...m,outcome:"outcome_unknown",code:"OUTCOME_UNKNOWN"});if(C&&!p)throw new RuntimeCommandError("OUTCOME_UNKNOWN","cancel request raced a locally completed runtime effect");await this.authority.commitResult({...m,command:d.attempt.command,result:sanitizeServiceResult(d.attempt.command.name,l)}),await o()}catch(e){let t=e;if(y&&(!A||R))try{await z(w??(C||_?"cancelled":"failed"))}catch(r){t=new RuntimeCommandError("OUTCOME_UNKNOWN",`conversation run terminal outcome is unknown: ${errorText(r)}`,void 0,{cause:e})}if(N&&!isUncertainRuntimeError(t)&&(t=new RuntimeCommandError("OUTCOME_UNKNOWN",`runtime effect completed before its terminal receipt: ${errorText(t)}`,void 0,{cause:e})),y)return void(O=!0);const r=serviceRuntimeFailureCode(t),a="OUTCOME_UNKNOWN"===r||"INSTANCE_EPOCH_MISMATCH"===r||I||A&&(C||_),n="COMMAND_EXPIRED"===r||!A&&_,o=!A&&C;await i({...m,outcome:a?"outcome_unknown":n?"expired":o?"cancelled":"failed",code:"INSTANCE_EPOCH_MISMATCH"===r||I?"INSTANCE_EPOCH_MISMATCH":a?"OUTCOME_UNKNOWN":n?"COMMAND_EXPIRED":o?"OPERATION_CANCELLED":r??"RUNTIME_EXECUTION_FAILED"})}finally{clearInterval(H),clearInterval(D),clearTimeout(G),r.removeEventListener("abort",S),p.abort(),await this.authority.releaseClaim({...s(),reason:r.aborted||O?"worker_shutdown":"completed"}).catch(()=>{})}}async startConversationRunBoundary(e,t,r){const a=e.attempt.command;if("session.prompt"!==a.name)return;const n=r?.conversationRunBoundary;if(!n)throw new RuntimeCommandError("INVALID_PARAMS","Service session.prompt lacks its conversation run boundary");const o=a.context.conversation,i=await n.boundary.start({operationId:e.operationId,requestMessageId:e.requestMessageId,conversationId:o.runtimeConversationUid,historyGeneration:n.historyGeneration,runtimeRunId:a.params.runtimeRunId,lease:exactRunBoundaryLease(t)});if("rejected"===i.status)return{rejected:!0,code:i.reason};if(i.historyGeneration!==n.historyGeneration)throw new RuntimeCommandError("OUTCOME_UNKNOWN","conversation run boundary changed history generation");return{boundary:n.boundary,historyGeneration:n.historyGeneration,activeRunRegistrationId:i.activeRunRegistrationId,runtimeRunId:a.params.runtimeRunId}}currentRuntimeLeaseCredential(e){const t=this.getLease();if(!t||t.leaseId!==e.leaseId||t.runtimeEpoch!==e.runtimeEpoch)throw new RuntimeCommandError("INSTANCE_EPOCH_MISMATCH","runtime lease changed before deferred resource redemption");return t.runtimeLeaseCredential}currentConversationRunBoundaryLease(e){const t=this.getLease();if(!t||t.leaseId!==e.leaseId||t.runtimeEpoch!==e.runtimeEpoch||t.handlerIdentity!==e.handlerIdentity)throw new RuntimeCommandError("INSTANCE_EPOCH_MISMATCH","runtime lease changed before conversation run convergence");return t}async finishConversationRunBoundary(e,t,r,a,n){const o=e.attempt.command.context;if("conversation"!==o.scope)throw new RuntimeCommandError("OUTCOME_UNKNOWN","conversation run boundary lost its target");const i=await r.boundary.finish({activeRunRegistrationId:r.activeRunRegistrationId,operationId:e.operationId,requestMessageId:e.requestMessageId,conversationId:o.conversation.runtimeConversationUid,historyGeneration:r.historyGeneration,runtimeRunId:r.runtimeRunId,terminalState:a,source:n,lease:exactRunBoundaryLease(t)});if("rejected"===i.status||i.activeRunRegistrationId!==r.activeRunRegistrationId)throw new RuntimeCommandError("OUTCOME_UNKNOWN",`conversation run finish rejected: ${"rejected"===i.status?i.reason:"registration_mismatch"}`)}async forwardProgress(e,t,r){for await(const a of e){if(r())return;await this.authority.appendProgress({...t,progress:a})}}}function exactRunBoundaryLease(e){return{leaseId:e.leaseId,handlerIdentity:e.handlerIdentity,runtimeEpoch:e.runtimeEpoch,runtimeLeaseCredential:e.runtimeLeaseCredential}}function serviceRuntimeFailureCode(e){const t=e?.code;return t&&["OUTCOME_UNKNOWN","INSTANCE_EPOCH_MISMATCH","COMMAND_EXPIRED","OPERATION_CANCELLED","IDEMPOTENCY_CONFLICT","UNAUTHORIZED_TARGET","AGENT_DEFAULT_MODEL_NOT_CONFIGURED"].includes(t)?t:void 0}function isUncertainRuntimeError(e){return e instanceof RuntimeCommandError&&("OUTCOME_UNKNOWN"===e.code||"INSTANCE_EPOCH_MISMATCH"===e.code)}function errorText(e){return e instanceof Error?e.message:String(e)}export function sanitizeServiceResult(e,t){if("cron.status"!==e||!t||"object"!=typeof t)return t;const r=t;return{enabled:r.enabled,jobCount:r.jobCount,..."number"==typeof r.nextWakeAtMs?{nextWakeAtMs:r.nextWakeAtMs}:{}}}function assertCommandCorrelation(e,t,r){if(e.operationId!==t.context.operationId||e.payload.paramsHash!==t.context.paramsHash||t.context.dispatchEpoch!==r||e.payload.command.name!==t.name||!sessionSetModelMappingMatches(e.payload.request,t))throw new Error("runtime invocation command correlation failed")}function prestartAttempt(e){return{command:e.payload.command,executionBoundaryId:"prestart",boundaryAssertionHash:e.payload.commandHash,executionMode:"start",validationContext:{},authorization:{},derivationContext:{}}}const aborted=Symbol("aborted");function waitForAbort(e,t){return t?t.aborted?(e.catch(()=>{}),Promise.resolve(aborted)):new Promise((r,a)=>{let n=!1;const o=()=>{n||(n=!0,r(aborted))};t.addEventListener("abort",o,{once:!0}),e.then(e=>{n||(n=!0,t.removeEventListener("abort",o),r(e))},e=>{n||(n=!0,t.removeEventListener("abort",o),a(e))})}):e}const delay=(e,t)=>new Promise(r=>{if(t?.aborted)return r();const a=()=>{clearTimeout(n),r()},n=setTimeout(()=>{t?.removeEventListener("abort",a),r()},e);t?.addEventListener("abort",a,{once:!0})});
@@ -0,0 +1 @@
1
+ import{createCentrifugoRealtimePort,createRuntimeChatClient,createRuntimeChatHttpPort}from"@beeos-ai/cloud-agent-sdk";import{NativeSessionNewBridge,nativeSessionNewConversationCreator}from"./native-session-new-bridge.js";const MESSAGE_CREATED="message.created";export function nativeCloudChatAuthorityFromRuntimeAuthority(e,t=Date.now){const n=e=>{if(!e||!e.runtimeLeaseCredential)return null;const n=Date.parse(e.leaseExpiresAt);return!Number.isFinite(n)||n<=t()?null:{instanceId:e.instanceId,handlerIdentity:e.handlerIdentity,runtimeEpoch:e.runtimeEpoch,leaseId:e.leaseId,runtimeLeaseCredential:e.runtimeLeaseCredential,leaseExpiresAt:e.leaseExpiresAt}};return{currentLease:()=>n(e.authorityLease),subscribeAuthority:t=>e.subscribeAuthority(e=>t(n(e)))}}export function createNativeCloudChatComposition(e){const t=e.now??Date.now,n=e.http??createRuntimeChatHttpPort({baseUrl:e.serviceUrl,...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},now:t}),s=e.realtime??createCentrifugoRealtimePort(),i=createRuntimeChatClient({authority:{currentLease:()=>e.authority.currentLease(),subscribeLease:t=>e.authority.subscribeAuthority(t)},http:n,realtime:s,now:t,...e.reconnectDelayMs?{reconnectDelayMs:e.reconnectDelayMs}:{},...e.logger?{logger:e.logger}:{}}),o=new NativeCloudChatAdapterImpl({client:i,...e.logger?{logger:e.logger}:{}});return{client:i,adapter:o,http:n,sessionNew:new NativeSessionNewBridge({client:i,...e.logger?{logger:e.logger}:{}}),sessionNewConversation:nativeSessionNewConversationCreator(i,e.logger),disconnect:async()=>{await o.disconnect(),await i.disconnect()},dispose:()=>{o.dispose(),i.dispose()}}}class NativeCloudChatAdapterImpl{deps;messages;projections=new Map;conversationProjections=new Map;storeListeners=new Set;inboundListeners=new Set;connection="disconnected";constructor(e){this.deps=e,this.messages={startStream:e=>this.startStream(e),getEnvelope:async(e,t)=>await this.getEnvelope(e,t)},this.deps.client.on("message",e=>this.admitInbound(e)),this.deps.client.on("connection",e=>{this.connection=e,this.publish()}),this.deps.client.on("error",e=>{this.deps.logger?.warn?.(`[native-cloud-chat] realtime error: ${e instanceof Error?e.message:String(e)}`)})}async connect(){try{await this.deps.client.connect()}catch(e){throw this.connection="disconnected",this.publish(),e}}async disconnect(){this.connection="disconnected",await this.deps.client.disconnect(),this.publish()}dispose(){this.storeListeners.clear(),this.inboundListeners.clear(),this.deps.client.dispose()}listen(e,t){const n=e.eventTypes;return n&&!n.includes(MESSAGE_CREATED)?()=>{}:(this.inboundListeners.add(t),()=>{this.inboundListeners.delete(t)})}subscribe(e){return this.storeListeners.add(e),()=>{this.storeListeners.delete(e)}}getSnapshot(){const e={};for(const[t,n]of this.projections)e[t]=n;const t={};for(const[e,n]of this.conversationProjections)t[e]=n;return{connection:this.connection,messages:e,conversations:t}}admitInbound(e){const t=toInboundProjection(e);this.projections.set(t.id,t),this.publish();for(const e of[...this.inboundListeners])e(t)}publish(){for(const e of[...this.storeListeners])e()}startStream(e){return new NativeHandlerReplyStream(this.deps.client.messages.startStream({conversationId:e.conversationId,id:e.clientMessageId,type:e.type,content:e.content,...e.replyTo?{replyTo:e.replyTo}:{}}))}async getEnvelope(e,t){const n=(await this.deps.client.history(e)).messages.find(e=>e.id===t);return{state:"string"==typeof n?.state?n.state:"outcome_unknown"}}}class NativeHandlerReplyStream{inner;constructor(e){this.inner=e}get id(){return this.inner.id}get isTerminated(){return this.inner.isTerminated}get parts(){return this.inner.parts}async opened(){const e=asRecord(await this.inner.opened()),t="string"==typeof e?.messageId&&e.messageId.length>0?e.messageId:this.inner.id;return"string"==typeof e?.outcome?{messageId:t,outcome:e.outcome}:{messageId:t}}appendBody(e){this.inner.appendBody(e)}setBody(e){this.inner.setBody(e)}addPart(e){this.inner.addPart(e)}replacePart(e,t){this.inner.replacePart(e,t)}appendToolResult(e,t,n){this.inner.addToolResult({type:"tool_result",tool_use_id:e,content:t,...n?{is_error:!0}:{}})}finalize(e){return this.inner.finalize(e)}fail(e){return this.inner.fail(e)}cancel(e){return this.inner.cancel(e)}}export function toInboundProjection(e){const t=asRecord(e)??{},n="string"==typeof t.body?t.body:"",s=Array.isArray(t.parts)?t.parts:void 0,i="string"==typeof t.state?t.state:void 0,o="string"==typeof t.stopReason?t.stopReason:void 0,r="string"==typeof t.createdAt?t.createdAt:void 0,a="string"==typeof t.updatedAt?t.updatedAt:r,c="string"==typeof t.offset?t.offset:"0";return{...t,id:e.id,conversationId:e.conversationId,type:e.type,content:e.content??{},...e.senderId?{senderId:e.senderId}:{},...e.replyTo?{replyTo:e.replyTo}:{},body:n,...s?{parts:s}:{},...i?{state:i}:{},...o?{stopReason:o}:{},...r?{createdAt:r}:{},...a?{updatedAt:a}:{},offset:c}}function asRecord(e){return null===e||"object"!=typeof e||Array.isArray(e)?void 0:e}export function historyToInboundProjection(e){return toInboundProjection(e)}
@@ -0,0 +1 @@
1
+ import{createNativeOutputFileAttempt}from"./native-output-file-attempt.js";import{downloadNativeInputFile}from"./native-input-files.js";import{bindExistingRuntimeChatReply}from"@beeos-ai/cloud-agent-sdk";import{RUNTIME_HASH_DOMAINS}from"@beeos-ai/beeos-types/runtime";import{dispatchImInboundPrompt}from"../im-runtime-dispatch.js";import{prepareNativePromptInput}from"./native-prompt-preflight.js";import{verifyNativePromptAuthority}from"./native-prompt-authority.js";import{RuntimeCommandError}from"./runtime-command-dispatcher.js";import{runtimeCommandResultHash}from"./runtime-command-journal.js";import{runtimeMessageBase,runtimeMessageHash,semanticEqual}from"./runtime-message-channel-contract.js";import{openClawSessionModePatch}from"./runtime-session-control-service.js";export const nativePromptCancellationReason="chat_cancel:runtime_operation_cancel_requested";export class NativeCloudPromptBridge{options;constructor(e){if(this.options=e,"function"!=typeof e.host.resolveNativePromptSessionKey)throw new RuntimeCommandError("INVALID_PARAMS","native Core target resolver required");if("function"!=typeof e.host.prepareNativePromptModel)throw new RuntimeCommandError("INVALID_PARAMS","native Core model preparation required");if(!e.runBoundary)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native MS run boundary required")}async execute(e){const{options:t}=this;if(await t.verifier.refresh(),!e.delivery.executionGrant)throw new RuntimeCommandError("INVALID_PARAMS","native grant missing");const a=e.delivery.message.payload,n="string"==typeof a.operationId?await t.journal.get(a.operationId):null,r=!!n&&"session.prompt"===n.command&&["started","effect_committed","projection_committed","failed"].includes(n.phase)&&n.paramsHash===a.paramsHash&&n.messageBinding?.requestMessageId===a.requestMessageId&&n.messageBinding?.requestHash===a.requestHash,s=verifyNativePromptAuthority({request:e.delivery.message.payload,decoded:t.verifier.verifyAndDecodeGrant(e.delivery.executionGrant),lease:e.lease,lineage:t.getLineage(),allowExpiredReadOnly:r}),{params:i}=s,o=s.request;try{const a=e.delivery.message;if("runtime_rpc_request"!==a.type||"completed"!==a.state||a.message_id!==o.requestMessageId||a.channel_id!==o.operationId||void 0!==a.in_reply_to)throw new RuntimeCommandError("INVALID_PARAMS","native envelope binding invalid");let n;void 0!==i.mode&&openClawSessionModePatch(i.mode);try{if(void 0!==i.mentions)throw new TypeError("native host per-prompt optional binding not implemented");n=prepareNativePromptInput(i.parts)}catch(e){throw new RuntimeCommandError(r?"OUTCOME_UNKNOWN":"INVALID_PARAMS","native host part unsupported",void 0,{cause:e})}const d=n.message;if(!t.host.activeRunAuthority)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native existing active-run authority unavailable");const m=()=>{const a=t.getLease(),n=t.getLineage();if(!a||a.instanceId!==e.lease.instanceId||a.handlerIdentity!==e.lease.handlerIdentity||a.runtimeEpoch!==i.runtimeLease.runtimeEpoch||a.leaseId!==i.runtimeLease.leaseId||n.journalStoreId!==i.runtimeLease.journalStoreId||n.journalGeneration!==i.runtimeLease.journalGeneration||Date.parse(a.leaseExpiresAt)<=Date.now())throw new RuntimeCommandError("INSTANCE_EPOCH_MISMATCH","native prompt attempt fenced")};m();const u=await t.channel.history({operationId:o.operationId,lease:e.lease,currentNativePrompt:s});if(m(),"found"!==u.status||u.snapshot.requestHash!==o.requestHash||u.snapshot.requestMessageId!==o.requestMessageId||!semanticEqual(u.snapshot.request.payload,o))throw new RuntimeCommandError("INVALID_PARAMS","native retained request mismatch");let l,p=await t.journal.get(o.operationId);if(m(),p&&("session.prompt"!==p.command||p.paramsHash!==o.paramsHash||p.runtimeEpoch!==i.runtimeLease.runtimeEpoch||p.messageBinding?.requestMessageId!==o.requestMessageId||p.messageBinding.requestHash!==o.requestHash))throw new RuntimeCommandError("OUTCOME_UNKNOWN","native existing journal binding mismatch");if(!t.http.getMessage)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native task snapshot unavailable");try{l=await t.http.getMessage(t.getLease(),{conversationId:i.conversationId,messageId:i.taskRequestMessageId})}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original task snapshot unavailable",void 0,{cause:e})}if(m(),l.messageId!==i.taskRequestMessageId||l.conversationId!==i.conversationId||"chat_message"!==l.type||l.body!==d)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original task snapshot mismatch");const c=async()=>{if(!t.http.getMessage)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native single snapshot unavailable");m();const e=await t.http.getMessage(t.getLease(),{conversationId:i.conversationId,messageId:i.replyMessageId});return m(),this.assertReply(e,s),e};if(u.snapshot.started||p&&"prepared"!==p.phase){const e=u.snapshot.runBoundary?.finishedReceipt,a=u.snapshot.final;if(!(p&&["started","effect_committed","projection_committed","failed"].includes(p.phase)&&e&&"finished"===e.state&&e.activeRunRegistrationId===i.taskId&&a))throw new RuntimeCommandError("OUTCOME_UNKNOWN","native durable MS finish audit or original result unavailable");const n=await c();if("agent_reply"!==n.type||n.state!==e.replyState||n.stopReason!==e.replyStopReason||n.updatedAt!==e.replyUpdatedAt)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original terminal does not match finished audit");const r=this.terminal(n,s);if(a.payload.outcome!==r.outcome||"final_message"!==u.snapshot.terminalSource)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original final outcome mismatch");const d=a.payload.response;if("2.0"!==d.jsonrpc||d.id!==o.request.id)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original final RPC binding mismatch");const l=runtimeCommandResultHash(r.result);if(p.resultReceipt&&p.resultReceipt.resultHash!==l||void 0!==p.result&&!semanticEqual(p.result,r.result))throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original result conflicts with local receipt");if(void 0===d.result)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original canonical result evidence unavailable");{const e=u.snapshot.effectCommitted?.payload,t=runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:o.method,result:d.result});if("succeeded"!==r.outcome||void 0!==d.error||!semanticEqual(d.result,r.result)||!e||e.effectRecord.coreResultHash!==t||e.effectRecord.coreResultRef!==`sha256:${t}`||a.payload.effectRecordHash!==e.effectRecordHash||a.payload.serviceResultHash!==runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:o.method,result:d.result}))throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original final result hash evidence mismatch")}const h=d.result;return m(),"started"===p.phase&&(p=await t.journal.transition({operationId:o.operationId,expectedRevision:p.revision,phase:"succeeded"===r.outcome?"effect_committed":"failed",result:h}),m()),{request:o,outcome:r.outcome,result:h,replayedFinal:a}}if(n.files.length&&!t.inputFiles)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native authorized input file resolver unavailable");if(u.snapshot.terminal||e.signal.aborted||u.snapshot.cancelRequested||await t.journal.getCancellation(o.operationId))throw new RuntimeCommandError("OPERATION_CANCELLED","native prompt cancelled before effect");const h=await t.host.resolveNativePromptSessionKey(s,m);if(m(),p=await t.journal.acceptMessageRequest({operationId:o.operationId,command:"session.prompt",paramsHash:o.paramsHash,runtimeEpoch:i.runtimeLease.runtimeEpoch,requestMessageId:o.requestMessageId,requestHash:o.requestHash}),m(),"prepared"!==p.phase)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native task already started");let g;const v=await bindExistingRuntimeChatReply({authority:{currentLease:t.getLease},http:t.http,binding:{conversationId:i.conversationId,messageId:i.replyMessageId,taskRequestMessageId:i.taskRequestMessageId,assertAttempt:m,assertPreparedClear:e=>{if(m(),!g||e.activeRunRegistrationId!==g||e.historyGeneration!==s.historyGeneration||e.runtimeEpoch!==i.runtimeLease.runtimeEpoch)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native prepared clear does not freeze this registered attempt")},mutationKey:e=>`native-reply:${o.operationId}:${i.runtimeLease.journalStoreId}:${i.runtimeLease.journalGeneration}:${e}`}});if(m(),e.signal.aborted||await t.journal.getCancellation(o.operationId))throw new RuntimeCommandError("OPERATION_CANCELLED","native prompt cancelled before start");await t.channel.append({operationId:o.operationId,lease:t.getLease(),currentNativePrompt:s,executionGrant:e.delivery.executionGrant,type:"runtime_operation_started",payload:{...runtimeMessageBase(o),executionGrantHash:o.executionGrantHash,handlerIdentity:e.lease.handlerIdentity,executionMode:"start",claimedAt:p.updatedAt}}),m(),p=await t.journal.transition({operationId:o.operationId,expectedRevision:p.revision,phase:"started"}),m();const I=()=>{m();const e=t.getLease();return{leaseId:e.leaseId,handlerIdentity:e.handlerIdentity,runtimeEpoch:e.runtimeEpoch,runtimeLeaseCredential:e.runtimeLeaseCredential}},R={operationId:o.operationId,requestMessageId:o.requestMessageId,conversationId:s.command.context.conversation.runtimeConversationUid,historyGeneration:s.historyGeneration,runtimeRunId:i.runtimeRunId},f=await t.runBoundary.start({...R,lease:I()});if(m(),"registered"!==f.status||f.historyGeneration!==s.historyGeneration||f.activeRunRegistrationId!==i.taskId)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native MS run start did not register the original task");g=f.activeRunRegistrationId;const N=new AbortController,w=()=>N.abort(e.signal.reason);if(e.signal.addEventListener("abort",w,{once:!0}),e.signal.aborted&&w(),e.setCancel(e=>N.abort(e)),await t.journal.getCancellation(o.operationId)&&N.abort(nativePromptCancellationReason),m(),N.signal.aborted)throw e.signal.removeEventListener("abort",w),new RuntimeCommandError("OUTCOME_UNKNOWN","native registered run stopped before host invocation");const y=[];let E;const O=JSON.parse((await v.opened()).rawText),C=O.parts?.length??0,M=async e=>{const t=await e;return m(),this.assertReply(t,s),E=t,t},_={id:v.id,get isTerminated(){return v.isTerminated},get parts(){return y},opened:async()=>({messageId:v.id,outcome:"bound"}),appendBody:e=>v.appendBody(e),setBody:e=>v.setBody(e),addPart:e=>{y.push(e),v.addPart(e)},replacePart:(e,t)=>{y[e]=t,v.replacePart(C+e,t)},appendToolResult:(e,t,a)=>{const n={type:"tool_result",tool_use_id:e,content:t,...a?{is_error:!0}:{}};y.push(n),v.addPart(n)},finalize:e=>M(v.finalize(e)),fail:e=>M(v.fail(e)),cancel:e=>M(v.cancel(e))},U={message:d,mediaPaths:[],mediaTypes:[]};let q,b;const A=createNativeOutputFileAttempt({operationId:o.operationId,requestMessageId:o.requestMessageId,paramsHash:o.paramsHash,activeRunRegistrationId:g,getLease:()=>(m(),t.getLease()),assertAttempt:m,signal:N.signal});try{await dispatchImInboundPrompt({...t.host,runtimeRunId:i.runtimeRunId,onNativeAgentRunStart:e=>A.bindHostRun(e),nativeActiveRunRegistration:{runtimeConversationUid:R.conversationId,runtimeSessionKey:s.command.context.conversation.runtimeSessionKey,historyGeneration:f.historyGeneration,targetMessageId:i.taskRequestMessageId,runtimeRunId:i.runtimeRunId,activeRunRegistrationId:f.activeRunRegistrationId},assertNativeTarget:async()=>{if(await t.host.resolveNativePromptSessionKey(s,m)!==h)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native prompt target changed before host invocation")},prepareNativeModel:async e=>{m(),await t.host.prepareNativePromptModel(s,e,m),m();for(const e of n.files){if(!t.inputFiles)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native authorized input file resolver unavailable");const a=await t.inputFiles.resolve({operationId:o.operationId,requestMessageId:o.requestMessageId,paramsHash:o.paramsHash,partIndex:e.partIndex,lease:t.getLease(),signal:N.signal});m();const n=await downloadNativeInputFile({fileId:e.fileId,...a,signal:N.signal,assertAttempt:m});U.mediaPaths.push(n.path),U.mediaTypes.push(n.mimeType)}m()},onNativeRunCompletion:e=>{b=e},retainedStream:_,abortSignal:N.signal,inReplyTo:i.taskRequestMessageId,prompt:{channelId:i.conversationId,inboundMessageId:i.taskRequestMessageId,requestId:o.requestMessageId,selfPrincipalId:e.lease.instanceId,sessionKey:h,dispatchInput:U},client:{messages:{startStream(){throw new Error("native reply POST forbidden")},getEnvelope:async()=>({state:(await c()).state})},getSnapshot:()=>({connection:"connected",messages:{},conversations:{}})}})}catch(e){q=e}finally{A.close(),e.signal.removeEventListener("abort",w)}if(!b&&q)throw q;if(!b||b.runtimeRunId!==i.runtimeRunId||b.token.sessionKey!==h)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native physical host completion unavailable");try{await b.completion}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","native host/abort/drain did not converge",void 0,{cause:e})}if(m(),!E)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native kernel settled without verified original reply terminal",void 0,{cause:q});const T=this.terminal(E,s),S=await c();v.assertTerminalSnapshot(S);const P="completed"===S.state?"completed":"cancelled"===S.state?"cancelled":"failed",H=await t.runBoundary.finish({...R,activeRunRegistrationId:g,terminalState:P,source:"runtime",lease:I()});if(m(),"finished"!==H.status&&"idempotent"!==H.status||H.activeRunRegistrationId!==g)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native MS run finish was not acknowledged");return await t.journal.transition({operationId:o.operationId,expectedRevision:p.revision,phase:"succeeded"===T.outcome?"effect_committed":"failed",result:T.result}),m(),{request:o,...T}}catch(e){throw new NativePromptExecutionFailure(o,e)}}assertReply(e,t){if(e.messageId!==t.params.replyMessageId||e.conversationId!==t.params.conversationId||e.replyTo!==t.params.taskRequestMessageId)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native durable reply binding mismatch")}terminal(e,t){if(!e.stopReason||!["completed","failed","refused","cancelled"].includes(e.state))throw new RuntimeCommandError("OUTCOME_UNKNOWN","native durable terminal absent");const a="cancelled"===e.state&&"user_stop"===e.stopReason?"cancelled":"completed"===e.state&&"end_turn"===e.stopReason?"succeeded":"failed";return{outcome:a,result:{runtimeRunId:t.params.runtimeRunId,stopReason:e.stopReason,requestAborted:"cancelled"===e.state&&"user_stop"===e.stopReason,..."failed"===a?{error:e.body}:{}}}}}export class NativePromptExecutionFailure extends Error{request;failure;constructor(e,t){super(t instanceof Error?t.message:String(t),{cause:t}),this.request=e,this.failure=t}}
@@ -0,0 +1 @@
1
+ const nativeJson=JSON,object=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),integerSource=e=>{if(!nativeJson.isRawJSON(e))return null;const t=JSON.stringify(e);return/^(0|[1-9][0-9]*)$/.test(t)&&BigInt(t)<=9223372036854775807n?t:null},nonempty=e=>"string"==typeof e&&e.length>0;export class NativeInputFilesHttpError extends Error{status;code;requestId;metadata;constructor(e,t,r,n){super(`native input Files resolve failed (${e})`),this.status=e,this.code=t,this.requestId=r,this.metadata=n}}const evidenceText=e=>"string"==typeof e&&/^[A-Za-z0-9_.:-]{1,128}$/.test(e);function selectedHttpError(e,t){const r=object(t)&&object(t.error)?t.error:void 0,n={};if(r&&object(r.metadata))for(const e of["operationId","requestMessageId","paramsHash","taskId","partIndex","clearIntentId","activeRunRegistrationId","historyGeneration","runtimeEpoch"]){const t=r.metadata[e];(evidenceText(t)||nativeJson.isRawJSON(t)&&null!==integerSource(t))&&(n[e]=t)}return new NativeInputFilesHttpError(e,r&&evidenceText(r.code)?r.code:void 0,object(t)&&evidenceText(t.request_id)?t.request_id:void 0,Object.keys(n).length?n:void 0)}export class NativeInputFilesHttpClient{getLease;transport;origin;constructor(e,t,r){this.getLease=t,this.transport=r;const n=new URL(e);if(!["http:","https:"].includes(n.protocol)||n.username||n.password||"/"!==n.pathname||n.search||n.hash)throw new Error("native input Files origin invalid");this.origin=n.origin}async resolve(e){const t=()=>{const t=this.getLease();if(!t||t.instanceId!==e.lease.instanceId||t.handlerIdentity!==e.lease.handlerIdentity||t.leaseId!==e.lease.leaseId||t.runtimeEpoch!==e.lease.runtimeEpoch||!t.runtimeLeaseCredential||Date.parse(t.leaseExpiresAt)<=Date.now())throw new Error("native input Files lease fenced");return t};if(!Number.isSafeInteger(e.partIndex)||e.partIndex<0)throw new Error("native input Files part index invalid");const r=t(),n=new URL(`/api/v1/internal/runtime/operations/${encodeURIComponent(e.operationId)}/input-files/resolve`,this.origin),i=await this.transport(n,{method:"POST",redirect:"error",signal:e.signal,headers:{authorization:`Bearer ${r.runtimeLeaseCredential}`,"content-type":"application/json"},body:JSON.stringify({requestMessageId:e.requestMessageId,paramsHash:e.paramsHash,partIndex:e.partIndex})});if(t(),i.url&&new URL(i.url).origin!==this.origin)throw new Error("native input Files response origin changed");if("function"!=typeof nativeJson.rawJSON||"function"!=typeof nativeJson.isRawJSON)throw new Error("native numeric JSON source required");const s=await i.text();let o;try{o=nativeJson.parse(s,(e,t,r)=>{if("number"!=typeof t)return t;if(!r?.source)throw new Error("native numeric JSON source required");return nativeJson.rawJSON(r.source)})}catch(e){if(!(e instanceof SyntaxError))throw e;if(!i.ok)throw new NativeInputFilesHttpError(i.status);throw new Error("native input Files response JSON invalid")}if(t(),!i.ok)throw selectedHttpError(i.status,o);if(!object(o)||o.operationId!==e.operationId||o.requestMessageId!==e.requestMessageId||o.paramsHash!==e.paramsHash||o.taskId!==e.operationId||integerSource(o.partIndex)!==`${e.partIndex}`||!object(o.file)||!object(o.download))throw new Error("native input Files response binding invalid");const a=o.file,d=o.download,c=integerSource(d.size_bytes),u=integerSource(a.size_bytes),p=integerSource(a.resource_version);if(!nonempty(a.file_id)||!nonempty(a.filename)||"ready"!==a.status||null===p||null===u||!nonempty(a.content_type)||"download"!==d.direction||d.file_id!==a.file_id||"GET"!==d.http_method||!nonempty(d.url)||!nonempty(d.expires_at)||!nonempty(d.content_type)||null===c||c!==u||d.content_type!==a.content_type||d.checksum_sha256!==a.checksum_sha256||void 0!==d.checksum_sha256&&"string"!=typeof d.checksum_sha256||!object(d.required_headers)||Object.values(d.required_headers).some(e=>"string"!=typeof e))throw new Error("native input Files descriptor invalid");const l={...d,direction:"download",file_id:a.file_id,url:d.url,http_method:"GET",required_headers:d.required_headers,expires_at:d.expires_at,content_type:d.content_type,size_bytes:c,...void 0!==d.checksum_sha256?{checksum_sha256:d.checksum_sha256}:{}};return{filename:a.filename,download:l,file:a}}}
@@ -0,0 +1 @@
1
+ import{createWriteStream}from"node:fs";import{mkdir,mkdtemp,rm}from"node:fs/promises";import{join,basename}from"node:path";import{createHash}from"node:crypto";import{Readable,Transform}from"node:stream";import{pipeline}from"node:stream/promises";export async function downloadNativeInputFile(e){const t=e.download;if("download"!==t.direction||t.file_id!==e.fileId||"GET"!==t.http_method||!/^(0|[1-9][0-9]*)$/.test(t.size_bytes)||!t.content_type||!Number.isFinite(Date.parse(t.expires_at))||Date.parse(t.expires_at)<=Date.now())throw new Error("native input file descriptor invalid or expired");let r;try{r=new URL(t.url)}catch(e){if(!(e instanceof TypeError))throw e;throw new Error("native input file transfer URL invalid")}if("https:"!==r.protocol&&"http:"!==r.protocol||r.username||r.password)throw new Error("native input file transfer URL invalid");if(void 0!==t.checksum_sha256&&!/^[0-9a-f]{64}$/.test(t.checksum_sha256))throw new Error("native input file checksum invalid");e.assertAttempt();const i=e.signal,a=await fetch(r,{method:t.http_method,headers:t.required_headers,signal:i,redirect:"error"});if(!a.ok||!a.body)throw new Error(`native input file download failed (${a.status})`);e.assertAttempt();const o=process.env.OPENCLAW_HOME??join(process.env.HOME??"/home/node",".openclaw"),n=join(o,"workspace","uploads");await mkdir(n,{recursive:!0});const s=await mkdtemp(join(n,"native-input-")),p=basename(e.filename).replace(/[^\p{L}\p{N}._-]/gu,"_"),c=join(s,p&&"."!==p&&".."!==p?p:"attachment");let m=0n;const d=BigInt(t.size_bytes),l=createHash("sha256"),f=new Transform({transform(e,t,r){m+=BigInt(e.byteLength),m>d?r(new Error("native input file size mismatch")):(l.update(e),r(null,e))}});try{const r=a.body.getReader(),o=async function*(){try{for(;;){const e=await r.read();if(e.done)return;yield e.value}}finally{await r.cancel(),r.releaseLock()}};if(await pipeline(Readable.from(o()),f,createWriteStream(c,{flags:"wx",mode:384}),{signal:i}),e.assertAttempt(),m!==d||void 0!==t.checksum_sha256&&l.digest("hex")!==t.checksum_sha256)throw new Error("native input file bytes do not match confirmed descriptor");return{path:c,mimeType:t.content_type}}catch(e){throw await rm(s,{recursive:!0,force:!0}),e}}
@@ -0,0 +1 @@
1
+ const runs=new Map,tools=new Map,consumed=new Set;export function createNativeOutputFileAttempt(t){let e,o=!0;const s={...t,assertAttempt(){if(!o)throw new Error("native output file attempt finished");t.signal.throwIfAborted(),t.assertAttempt();const e=t.getLease();if(!e.runtimeLeaseCredential||!Number.isFinite(Date.parse(e.leaseExpiresAt))||Date.parse(e.leaseExpiresAt)<=Date.now())throw new Error("native output file lease fenced")},getLease:()=>(s.assertAttempt(),t.getLease())};return{bindHostRun(t){if(s.assertAttempt(),!t||void 0!==e||runs.has(t))throw new Error("native output file Host run binding ambiguous");e=t,runs.set(t,s)},close(){o=!1,e&&runs.get(e)===s&&runs.delete(e);for(const[t,e]of tools)e.assertAttempt===s.assertAttempt&&tools.delete(t);for(const e of consumed)e.startsWith(t.operationId+"\0")&&consumed.delete(e)}}}export function prepareNativeOutputTool(t,e){if(!t||!e)throw new Error("native output file trusted Host tool binding missing");const o=runs.get(t);if(!o)throw new Error("native output file trusted run missing");o.assertAttempt();const s=o.operationId+"\0"+e;if(tools.has(e)||consumed.has(s))throw new Error("native output file tool binding ambiguous or consumed");tools.set(e,{...o,toolCallId:e})}export function consumeNativeOutputTool(t){const e=tools.get(t);if(tools.delete(t),!e)throw new Error("native output file tool capability missing");return e.assertAttempt(),consumed.add(e.operationId+"\0"+t),e}
@@ -0,0 +1 @@
1
+ import{isCloudRuntimeSubject,RUNTIME_HASH_DOMAINS,runtimeCloudCallerIntentPayload,runtimeCloudIdempotencyFingerprintPayload}from"@beeos-ai/beeos-types/runtime";import{runtimeMessageHash,semanticEqual}from"./runtime-message-channel-contract.js";import{RuntimeCommandError}from"./runtime-command-dispatcher.js";import{isDeepStrictEqual}from"node:util";const verifiedPrompts=new WeakMap;export function retainedVerifiedNativePrompt(e){if(!e||"object"!=typeof e)return null;const t=verifiedPrompts.get(e);return t&&isDeepStrictEqual(e,t)?structuredClone(t):null}const object=e=>!!e&&"object"==typeof e&&!Array.isArray(e),nonempty=e=>"string"==typeof e&&!!e,digest=e=>"string"==typeof e&&/^[0-9a-f]{64}$/.test(e),decimal=e=>"string"==typeof e&&/^(0|[1-9][0-9]*)$/.test(e),exact=(e,t)=>Object.keys(e).sort().join("\0")===t.sort().join("\0"),fail=()=>{throw new RuntimeCommandError("INVALID_PARAMS","native prompt signed binding invalid")};export function verifyNativePromptAuthority(e){const t=e.request,a=e.decoded?.claims;if(!(object(t)&&object(a)&&object(t.request)&&object(t.command)&&object(t.command.context)&&object(t.command.params)&&object(t.request.params)))return fail();const n=t.request.params,r=t.command.context,o=n.runtimeLease;if(!(exact(t,["schemaVersion","authorityRealm","cloudSubject","operationId","requestMessageId","requestHash","paramsHash","commandHash","idempotencyKeyHash","idempotencyFingerprint","callerIntentHash","instanceId","leaseId","runtimeHandlerIdentity","dispatchEpoch","executionGrantHash","claimDeadlineAt","executionDeadlineAt","createdAt","method","request","command","callerExternalUserId"])&&exact(t.request,["jsonrpc","id","method","params"])&&exact(t.command,["context","name","params"])&&exact(n,["runtimeRunId","parts","conversationId","platformAgentId","taskId","taskRequestMessageId","replyMessageId","inputFingerprint","runtimeLease",...["mentions","mode","modelOverrideId"].filter(e=>void 0!==n[e])])&&object(o)&&exact(o,["runtimeEpoch","leaseId","journalStoreId","journalGeneration"])&&2===t.schemaVersion&&"cloud"===t.authorityRealm&&"session/prompt"===t.method&&t.request.method===t.method&&"2.0"===t.request.jsonrpc&&("string"==typeof t.request.id||"number"==typeof t.request.id)&&"session.prompt"===t.command.name&&isCloudRuntimeSubject(t.cloudSubject)&&isCloudRuntimeSubject(a.cloudSubject)&&semanticEqual(t.cloudSubject,a.cloudSubject)&&t.cloudSubject.instanceId===e.lease.instanceId&&t.instanceId===e.lease.instanceId&&t.runtimeHandlerIdentity===e.lease.handlerIdentity&&t.leaseId===e.lease.leaseId&&decimal(t.dispatchEpoch)&&decimal(o.runtimeEpoch)&&decimal(o.journalGeneration)&&o.runtimeEpoch===e.lease.runtimeEpoch&&o.leaseId===e.lease.leaseId&&o.journalStoreId===e.lineage.journalStoreId&&o.journalGeneration===e.lineage.journalGeneration&&nonempty(t.callerExternalUserId)&&nonempty(t.requestMessageId)&&t.requestMessageId!==n.taskRequestMessageId&&n.replyMessageId!==n.taskRequestMessageId&&[n.conversationId,n.platformAgentId,n.taskRequestMessageId,n.replyMessageId].every(nonempty)&&digest(n.inputFingerprint)&&n.taskId===t.operationId&&n.runtimeRunId===t.operationId&&"string"==typeof n.taskId&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(n.taskId)&&Array.isArray(n.parts)&&(void 0===n.mode||"string"==typeof n.mode)&&(void 0===n.modelOverrideId||"string"==typeof n.modelOverrideId)&&(void 0===n.mentions||Array.isArray(n.mentions))&&"conversation"===r.scope&&r.operationId===t.operationId&&r.dispatchEpoch===t.dispatchEpoch&&r.runtimeInstanceUid===t.instanceId&&r.paramsHash===t.paramsHash&&r.idempotencyKeyHash===t.idempotencyKeyHash&&r.claimDeadline===t.claimDeadlineAt&&r.executionDeadline===t.executionDeadlineAt&&decimal(r.historyGeneration)&&object(r.conversation)&&r.conversation.runtimeConversationUid===n.conversationId&&r.conversation.runtimeSessionKey===n.conversationId&&[t.requestHash,t.paramsHash,t.commandHash,t.callerIntentHash,t.idempotencyFingerprint,t.idempotencyKeyHash,t.executionGrantHash].every(digest)))return fail();const s={runtimeRunId:n.runtimeRunId,parts:n.parts,...void 0===n.mentions?{}:{mentions:n.mentions},...void 0===n.mode?{}:{mode:n.mode},...void 0===n.modelOverrideId?{}:{modelOverrideId:n.modelOverrideId}},i=e.now??Date.now();if(![t.createdAt,t.claimDeadlineAt,t.executionDeadlineAt].every(e=>"string"==typeof e&&Number.isFinite(Date.parse(e)))||Date.parse(t.createdAt)>Date.parse(t.claimDeadlineAt)||Date.parse(t.claimDeadlineAt)>Date.parse(t.executionDeadlineAt)||!e.allowExpiredReadOnly&&Date.parse(t.claimDeadlineAt)<=i||!e.allowExpiredReadOnly&&Date.parse(t.executionDeadlineAt)<=i||!semanticEqual(s,t.command.params)||runtimeMessageHash(RUNTIME_HASH_DOMAINS.request,t.request)!==t.requestHash||runtimeMessageHash(RUNTIME_HASH_DOMAINS.params,{method:t.method,params:n})!==t.paramsHash||runtimeMessageHash(RUNTIME_HASH_DOMAINS.command,{command:t.command})!==t.commandHash||runtimeMessageHash(RUNTIME_HASH_DOMAINS.cloudCallerIntent,runtimeCloudCallerIntentPayload(t.cloudSubject,"session/prompt",n,t.callerExternalUserId))!==t.callerIntentHash||runtimeMessageHash(RUNTIME_HASH_DOMAINS.cloudIdempotencyFingerprint,runtimeCloudIdempotencyFingerprintPayload(t.cloudSubject,"session/prompt",t.callerIntentHash))!==t.idempotencyFingerprint||e.decoded?.compactHash!==t.executionGrantHash)return fail();const d=Math.floor(i/1e3);if(!exact(a,["iss","aud","purpose","sub","jti","iat","exp","authorityRealm","cloudSubject","operationId","requestMessageId","instanceId","leaseId","handlerIdentity","dispatchEpoch","requestHash","paramsHash","commandHash","idempotencyKeyHash","executionMode","method","command","scope","callerExternalUserId","platformAgentId","runtimeAgentUid","platformConversationId","historyGeneration"])||"beeos-cloud-gateway"!==a.iss||"beeos-cloud-runtime-command"!==a.aud||"cloud-runtime-execution-grant"!==a.purpose||"cloud"!==a.authorityRealm||"start"!==a.executionMode||"conversation"!==a.scope||!nonempty(a.jti)||!nonempty(a.runtimeAgentUid)||!Number.isSafeInteger(a.iat)||!Number.isSafeInteger(a.exp)||a.iat>d||!e.allowExpiredReadOnly&&a.exp<=d||a.exp<=a.iat||a.exp-a.iat>60||a.sub!==e.lease.handlerIdentity||a.handlerIdentity!==e.lease.handlerIdentity||a.platformAgentId!==n.platformAgentId||a.platformConversationId!==n.conversationId||a.historyGeneration!==r.historyGeneration||!semanticEqual(a.command,t.command)||!semanticEqual(a.cloudSubject,t.cloudSubject)||["operationId","requestMessageId","instanceId","leaseId","dispatchEpoch","requestHash","paramsHash","commandHash","idempotencyKeyHash","callerExternalUserId","method"].some(e=>a[e]!==t[e]))return fail();const m=structuredClone(t),c={historyGeneration:r.historyGeneration,runtimeAgentUid:a.runtimeAgentUid,request:m,params:m.request.params,command:m.command};return verifiedPrompts.set(c,structuredClone(c)),c}
@@ -0,0 +1 @@
1
+ export function prepareNativePromptInput(e){const t=[],i=[];for(const[r,o]of e.entries()){if("text"===o.type){if("string"!=typeof o.text)throw new TypeError("native text part invalid");t.push(o.text);continue}if(!["image","audio","file","resource","resource_link"].includes(o.type)||void 0!==o.mimeType&&"string"!=typeof o.mimeType||"resource_link"!==o.type&&void 0!==o.fileName&&"string"!=typeof o.fileName||"resource_link"===o.type&&(void 0!==o.name&&"string"!=typeof o.name||void 0!==o.title&&"string"!=typeof o.title||void 0!==o.sizeBytes&&("string"!=typeof o.sizeBytes||!/^(0|[1-9][0-9]*)$/.test(o.sizeBytes))))throw new TypeError("native file part unsupported or invalid");const e="resource_link"===o.type?o.resourceRef:o.blobRef;if("string"!=typeof e||!/^beeos-file:\/\/[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(e))throw new TypeError("native input part unsupported: canonical Cloud file reference required");i.push({partIndex:r,fileId:e.slice(13)})}return{message:t.join("\n"),files:i}}
@@ -0,0 +1 @@
1
+ export function nativeSessionNewSyncRequest(n){const e=nonEmpty(n.operationId);if(!e)throw new Error("native session/new sync requires a retained operationId");const s=nonEmpty(n.runtimeSessionId);if(!s)throw new Error("native session/new sync requires a runtimeSessionId");const o=nonEmpty(n.runtimeSessionKey),t=nonEmpty(n.title);return{schemaVersion:1,operationId:e,runtimeSessionId:s,...o?{runtimeSessionKey:o}:{},...t?{title:t}:{}}}export function assertCanonicalConversationSyncResponse(n){if(!n||"string"!=typeof n.id||0===n.id.length)throw new Error("native session/new sync response is missing a canonical conversation id");return n}export class NativeSessionNewBridge{options;constructor(n){this.options=n}async sync(n){const e=nativeSessionNewSyncRequest(n);this.options.logger?.info?.(`[native-cloud-chat] session/new sync operationId=${e.operationId} runtimeSessionId=${e.runtimeSessionId}`);return{conversation:assertCanonicalConversationSyncResponse(await this.options.client.syncConversation(e))}}}export async function syncNativeSessionNew(n,e){const s=nativeSessionNewSyncRequest(e);return assertCanonicalConversationSyncResponse(await n.syncConversation(s))}export function nativeSessionNewConversationCreator(n,e){const s=new NativeSessionNewBridge({client:n,...e?{logger:e}:{}});return{create:async n=>({conversationId:(await s.sync({operationId:n.operationId,runtimeSessionId:n.runtimeSessionId,runtimeSessionKey:n.runtimeSessionKey,...n.title?{title:n.title}:{}})).conversation.id})}}function nonEmpty(n){return"string"==typeof n&&n.length>0?n:void 0}
@@ -1 +1 @@
1
- import{enableDeepseekReasoningStream}from"./deepseek-reasoning-stream.js";const DEFAULT_ORIGINATING_CHANNEL="beeos-claw",DEFAULT_ORIGINATING_TARGET="main",DEFAULT_ORIGINATING_ACCOUNT_ID="main",isRecord=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),assertKnownReplyProtocol=e=>{if("acp"!==e&&"im"!==e)throw new Error(`unsupported reply route protocol=${e}`)},normalizeMediaUrls=e=>{if(!Array.isArray(e))return;const o=e.filter(e=>"string"==typeof e&&e.length>0);return o.length>0?o:void 0};export const hasRuntimeReplyApi=e=>"function"==typeof e?.channel?.reply?.dispatchReplyFromConfig;export const buildFinalizedMsgContext=(e,o)=>{assertKnownReplyProtocol(o.protocol);const r=o.originatingChannel??"beeos-claw",t=o.originatingTo??"main",n=o.accountId??"main",i=normalizeMediaUrls(e.attachments);return{Body:e.message,BodyForAgent:e.agentMessage,From:`${r}:${t}`,To:t,SessionKey:o.sessionId,Surface:r,Provider:r,OriginatingChannel:r,OriginatingTo:t,AccountId:n,CommandAuthorized:!0,...i?{MediaUrls:i}:{}}};export const resolveReplySinkForRoute=(e,o)=>{assertKnownReplyProtocol(e.protocol);const r=o[e.protocol];if(!r)throw new Error(`runtime reply sink unavailable protocol=${e.protocol} requestId=${e.requestId}`);return r};const resolveRuntimeDispatchConfig=(e,o)=>{try{const o=e.config?.loadConfig?.();if(isRecord(o))return o}catch{}return o};export const dispatchRuntimeReplyWithRoute=async e=>{const o=e.runtime.channel?.reply?.dispatchReplyFromConfig;if("function"!=typeof o)throw new Error(`runtime reply API unavailable protocol=${e.replyRoute.protocol} requestId=${e.replyRoute.requestId}`);const r=resolveReplySinkForRoute(e.replyRoute,e.replySinks),t=enableDeepseekReasoningStream(resolveRuntimeDispatchConfig(e.runtime,e.pluginConfig)),n=o({ctx:buildFinalizedMsgContext(e.preparedPrompt,e.replyRoute),cfg:t,dispatcher:r.dispatcher,replyOptions:r.replyOptions});return e.onDispatchInvoked?.(),n};
1
+ import{enableDeepseekReasoningStream}from"./deepseek-reasoning-stream.js";const DEFAULT_ORIGINATING_CHANNEL="beeos-claw",DEFAULT_ORIGINATING_TARGET="main",DEFAULT_ORIGINATING_ACCOUNT_ID="main",isRecord=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),assertKnownReplyProtocol=e=>{if("acp"!==e&&"im"!==e)throw new Error(`unsupported reply route protocol=${e}`)},normalizeMediaUrls=e=>{if(!Array.isArray(e))return;const o=e.filter(e=>"string"==typeof e&&e.length>0);return o.length>0?o:void 0};export const hasRuntimeReplyApi=e=>"function"==typeof e?.channel?.reply?.dispatchReplyFromConfig;export const buildFinalizedMsgContext=(e,o)=>{assertKnownReplyProtocol(o.protocol);const r=o.originatingChannel??"beeos-claw",t=o.originatingTo??"main",n=o.accountId??"main",i=normalizeMediaUrls(e.attachments);return{Body:e.message,BodyForAgent:e.agentMessage,From:`${r}:${t}`,To:t,SessionKey:o.sessionId,Surface:r,Provider:r,OriginatingChannel:r,OriginatingTo:t,AccountId:n,CommandAuthorized:!0,...i?{MediaUrls:i}:{},...e.mediaPaths?.length?{MediaPaths:e.mediaPaths,MediaTypes:e.mediaTypes}:{}}};export const resolveReplySinkForRoute=(e,o)=>{assertKnownReplyProtocol(e.protocol);const r=o[e.protocol];if(!r)throw new Error(`runtime reply sink unavailable protocol=${e.protocol} requestId=${e.requestId}`);return r};const resolveRuntimeDispatchConfig=(e,o)=>{try{const o=e.config?.loadConfig?.();if(isRecord(o))return o}catch{}return o};export const dispatchRuntimeReplyWithRoute=async e=>{const o=e.runtime.channel?.reply?.dispatchReplyFromConfig;if("function"!=typeof o)throw new Error(`runtime reply API unavailable protocol=${e.replyRoute.protocol} requestId=${e.replyRoute.requestId}`);const r=resolveReplySinkForRoute(e.replyRoute,e.replySinks),t=enableDeepseekReasoningStream(resolveRuntimeDispatchConfig(e.runtime,e.pluginConfig)),n=o({ctx:buildFinalizedMsgContext(e.preparedPrompt,e.replyRoute),cfg:t,dispatcher:r.dispatcher,replyOptions:r.replyOptions});return e.onDispatchInvoked?.(n),n};
@@ -0,0 +1 @@
1
+ export const RUNTIME_ERROR_PART_KIND="runtime_error";const RUNTIME_ERROR_CODES=["insufficient_credits"];export function createRuntimeErrorPart(r){return{type:"custom",kind:"runtime_error",data:{code:r}}}export function parseRuntimeErrorPart(r){if(!r||"object"!=typeof r||Array.isArray(r))return;const t=r;if("custom"!==t.type||"runtime_error"!==t.kind)return;const e=t.data;if(!e||"object"!=typeof e||Array.isArray(e))return;const n=e.code;return"string"==typeof n&&RUNTIME_ERROR_CODES.includes(n)?createRuntimeErrorPart(n):void 0}
@@ -1 +1 @@
1
- import{RUNTIME_INVOCATION_RECOVERY_CLASSES,RUNTIME_METHOD_PARITY_MANIFEST}from"@beeos-ai/beeos-types/runtime";export const RUNTIME_LOCAL_PARITY_MATRIX=Object.freeze(RUNTIME_METHOD_PARITY_MANIFEST.filter(e=>"request"===e.acpMessage&&e.serviceAllowed&&e.canonicalCommand&&e.acpMethod in RUNTIME_INVOCATION_RECOVERY_CLASSES&&("methods"===e.serviceRoute||"conversation-api"===e.serviceRoute)).map(e=>{const r=e.acpMethod,t="query"===e.recoveryClass?[]:["runtime_effect_committed"];return Object.freeze({method:r,acp:Object.freeze({params:e.acpParamsType,result:e.acpResultType,errors:Object.freeze([...e.acpErrors])}),service:Object.freeze({method:e.serviceMethod,command:e.canonicalCommand,events:Object.freeze(["runtime_operation_started","runtime_operation_progress*",...t,"runtime_rpc_response"]),finalResult:`CanonicalCommandResult<${JSON.stringify(e.canonicalCommand)}>`,errors:Object.freeze([...e.serviceErrors])}),fixture:Object.freeze({status:"ready",kind:"wire-fixture",acpEvidence:"src/acp-gateway/bridge-core shared-Core request/result/error fixtures",serviceEvidence:"src/runtime/ms-runtime-rpc-adapter-parity.test.ts canonical/events/final fixtures"}),activation:Object.freeze({status:"ready",requirements:Object.freeze([])})})}));export const RUNTIME_LOCAL_FIXTURE_READY_METHODS=Object.freeze(new Set(RUNTIME_LOCAL_PARITY_MATRIX.filter(e=>"ready"===e.fixture.status).map(e=>e.method)));
1
+ import{RUNTIME_INVOCATION_RECOVERY_CLASSES,RUNTIME_METHOD_PARITY_MANIFEST}from"@beeos-ai/beeos-types/runtime";export const RUNTIME_LOCAL_PARITY_MATRIX=Object.freeze(RUNTIME_METHOD_PARITY_MANIFEST.filter(e=>"request"===e.acpMessage&&e.serviceAllowed&&e.canonicalCommand&&e.acpMethod in RUNTIME_INVOCATION_RECOVERY_CLASSES&&("methods"===e.serviceRoute||"conversation-api"===e.serviceRoute)).map(e=>{const r=e.acpMethod,t="query"===e.recoveryClass||"session/new"===r?[]:["runtime_effect_committed"];return Object.freeze({method:r,acp:Object.freeze({params:e.acpParamsType,result:e.acpResultType,errors:Object.freeze([...e.acpErrors])}),service:Object.freeze({method:e.serviceMethod,command:e.canonicalCommand,events:Object.freeze(["runtime_operation_started","runtime_operation_progress*",...t,"runtime_rpc_response"]),finalResult:`CanonicalCommandResult<${JSON.stringify(e.canonicalCommand)}>`,errors:Object.freeze([...e.serviceErrors])}),fixture:Object.freeze({status:"ready",kind:"wire-fixture",acpEvidence:"src/acp-gateway/bridge-core shared-Core request/result/error fixtures",serviceEvidence:"session/new"===r?"src/runtime/native-session-new-go-wire.test.ts Go/MS HTTP/RS256/Core/sync/final fixture":"src/runtime/ms-runtime-rpc-adapter-parity.test.ts canonical/events/final fixtures"}),activation:Object.freeze({status:"ready",requirements:Object.freeze([])})})}));export const RUNTIME_LOCAL_FIXTURE_READY_METHODS=Object.freeze(new Set(RUNTIME_LOCAL_PARITY_MATRIX.filter(e=>"ready"===e.fixture.status).map(e=>e.method)));
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";import{RUNTIME_INTERNAL_API_V1_ROUTE_CONTRACTS,hashRuntimeResourceRedemptionPayload,normalizeRuntimeResourceRedemptionHashPayload,validateRuntimeMcpResourceRedemptionCompletion,validateRuntimeSkillResourceRedemptionCompletion}from"@beeos-ai/beeos-types/runtime";export class RuntimeResourceResolutionError extends Error{kind;code;constructor(e,t,i){super(t),this.kind=e,this.code=i,this.name="RuntimeResourceResolutionError"}}export class HttpRuntimeOperationResourceResolver{options;attempts=new Map;byRef;mcp;skill;constructor(e){this.options=e;const t=e.bindings.map(e=>[e.resourceRef,Object.freeze({...e})]);if(new Set(t.map(([e])=>e)).size!==t.length)throw new Error("duplicate resource binding");this.byRef=new Map(t)}async readContent(){throw new Error("Service inline content is forbidden; use a trusted artifact reference")}async resolveMcpDefinition(e){this.mcp||(this.mcp=this.redeemMcp(e).catch(e=>{throw this.mcp=void 0,e}));const t=await this.mcp;if(!sameMcpDescriptor(t.descriptor,e))throw new Error("MCP resource descriptor mismatch");return t.config}async resolveMcpCredential(e){this.mcp||(this.mcp=this.redeemMcp(e).catch(e=>{throw this.mcp=void 0,e}));const t=await this.mcp;if(!sameMcpDescriptor(t.descriptor,e))throw new Error("MCP resource descriptor mismatch");return t.credential}async readVerifiedArtifact(e){this.skill||(this.skill=this.redeemSkill(e).catch(e=>{throw this.skill=void 0,e}));const t=await this.skill;if(!sameArtifactDescriptor(t.descriptor,e))throw new Error("skill resource descriptor mismatch");return t.parsed}async redeemMcp(e){const t=this.bindingFor("mcp",e.definitionRef);if(t.version!==e.version||t.sha256!==e.sha256)throw new Error("MCP descriptor does not match the immutable authority binding");const{request:i,reservation:r}=this.requestFor(t),o=await this.redeem(t,i);let s;try{s=await o.json()}catch{throw integrity("MCP authority response is invalid")}if(!validateRuntimeMcpResourceRedemptionCompletion({request:i,binding:t,reservation:r,expectedDisposition:s.disposition,result:s,sha256Utf8:sha256Utf8}).valid)throw integrity("MCP resource integrity failed");if(!isPlainObject(s.resource.config))throw integrity("MCP authority payload must contain public object config");const n=void 0===s.resource.credential?void 0:credentialMaterial(s.resource.credential);return{descriptor:e,config:Object.freeze({...s.resource.config}),credential:n}}async redeemSkill(e){const t=this.bindingFor("skill",e.artifactRef);if(t.version!==e.version||t.sha256!==e.sha256||t.sizeBytes!==e.sizeBytes)throw new Error("skill descriptor does not match the immutable authority binding");const{request:i,reservation:r}=this.requestFor(t),o=await this.redeem(t,i),s=new Uint8Array(await o.arrayBuffer()),n=skillHeaders(o);if(!validateRuntimeSkillResourceRedemptionCompletion({request:i,binding:t,reservation:r,expectedDisposition:n["X-BeeOS-Redemption-Disposition"],headers:n,chunks:[s],sha256Utf8:sha256Utf8,sha256Bytes:sha256Bytes}).valid)throw integrity("skill resource integrity failed");return{descriptor:e,parsed:await this.options.parseSkillArtifact(s)}}bindingFor(e,t){const i=this.byRef.get(t);if(!i||i.kind!==e||i.operationId!==this.options.operationId||i.instanceId!==this.options.instanceId||i.requestMessageId!==this.options.requestMessageId||i.paramsHash!==this.options.paramsHash)throw resolution("resource authority binding mismatch");return i}requestFor(e){const t=this.options.getAuthorization(),i=this.attempts.get(e.resourceRef),r=i?.redemptionId??(this.options.redemptionId?this.options.redemptionId():stableRedemptionId(e)),o={redemptionId:r,operationId:this.options.operationId,requestMessageId:this.options.requestMessageId,kind:e.kind,resourceRef:e.resourceRef,paramsHash:this.options.paramsHash,executionGrant:t.executionGrant,runtimeLeaseCredential:t.runtimeLeaseCredential,fence:t.fence},s=normalizeRuntimeResourceRedemptionHashPayload(o,e);if(!s)throw resolution("resource redemption request does not match immutable binding");const n=hashRuntimeResourceRedemptionPayload(s,sha256Utf8);if(i&&i.requestHash!==n)throw resolution("resource redemption intent changed");return this.attempts.set(e.resourceRef,{redemptionId:r,requestHash:n}),{request:o,reservation:{state:"reserved",redemptionId:r,redemptionRequestHash:n}}}async redeem(e,t){const i=("mcp"===e.kind?RUNTIME_INTERNAL_API_V1_ROUTE_CONTRACTS.redeemMcpResource.path:RUNTIME_INTERNAL_API_V1_ROUTE_CONTRACTS.redeemSkillResource.path).replace("{operationId}",encodeURIComponent(e.operationId)).replace("{resourceRef}",encodeURIComponent(e.resourceRef));let r;try{r=await this.options.fetchAuthorized(new URL(i,this.options.gatewayUrl),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),...this.options.signal?{signal:this.options.signal}:{}})}catch{throw transient("runtime resource authority is unavailable")}return r.ok||await throwRedemptionFailure(r,e.kind),r}}function skillHeaders(e){const t=t=>{const i=e.headers.get(t);if(!i)throw integrity(`skill authority response omitted ${t}`);return i};return{"X-BeeOS-Redemption-Id":t("X-BeeOS-Redemption-Id"),"X-BeeOS-Redemption-Disposition":t("X-BeeOS-Redemption-Disposition"),"X-BeeOS-Artifact-Ref":t("X-BeeOS-Artifact-Ref"),"X-BeeOS-Artifact-Version":t("X-BeeOS-Artifact-Version"),"X-BeeOS-Artifact-SHA256":t("X-BeeOS-Artifact-SHA256"),"X-BeeOS-Artifact-Size":t("X-BeeOS-Artifact-Size")}}function sha256Utf8(e){return createHash("sha256").update(e).digest("hex")}function stableRedemptionId(e){return`redemption:${sha256Utf8(`${e.operationId}\n${e.requestMessageId}\n${e.kind}\n${e.resourceRef}`)}`}function sha256Bytes(e){const t=createHash("sha256");for(const i of e)t.update(i);return t.digest("hex")}function sameMcpDescriptor(e,t){return e.definitionRef===t.definitionRef&&e.version===t.version&&e.sha256===t.sha256}function sameArtifactDescriptor(e,t){return e.artifactRef===t.artifactRef&&e.version===t.version&&e.sha256===t.sha256&&e.sizeBytes===t.sizeBytes&&e.source===t.source}function isPlainObject(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}function credentialMaterial(e){if(!isPlainObject(e)||Object.keys(e).some(e=>"headers"!==e&&"env"!==e))throw integrity("MCP credential payload is invalid");const t=stringMap(e.headers,"MCP credential headers"),i=stringMap(e.env,"MCP credential environment");if(!t&&!i)throw integrity("MCP credential payload is empty");return Object.freeze({...t?{headers:Object.freeze(t)}:{},...i?{env:Object.freeze(i)}:{}})}function stringMap(e,t){if(void 0!==e){if(!isPlainObject(e)||Object.entries(e).some(([e,t])=>!e||e.length>256||/[\u0000-\u001f\u007f]/.test(e)||"string"!=typeof t||t.length>16384))throw integrity(`${t} are invalid`);return{...e}}}async function throwRedemptionFailure(e,t){if(408===e.status||425===e.status||429===e.status||e.status>=500)throw transient(`runtime ${t} redemption is temporarily unavailable`);let i;try{i=await e.json()}catch{throw integrity(`runtime ${t} redemption error is invalid`)}const r=redemptionError(i);if(!r)throw integrity(`runtime ${t} redemption error is invalid`);throw new RuntimeResourceResolutionError("resolution_rejected",`runtime ${t} redemption was rejected`,r.code)}function redemptionError(e){if(!isPlainObject(e)||"string"!=typeof e.status||"string"!=typeof e.code)return;if("fenced"===e.status&&"FENCED"===e.code&&"string"==typeof e.activeRuntimeEpoch&&/^(0|[1-9][0-9]*)$/.test(e.activeRuntimeEpoch)&&exact(e,["status","code","activeRuntimeEpoch"]))return e;return[["expired","EXPIRED"],["resource_not_found","RESOURCE_NOT_FOUND"],["redemption_conflict","REDEMPTION_CONFLICT"],["resource_integrity_failed","RESOURCE_INTEGRITY_FAILED"],["unauthorized","UNAUTHORIZED"]].some(([t,i])=>e.status===t&&e.code===i&&exact(e,["status","code"]))?e:void 0}function exact(e,t){const i=Object.keys(e).sort(),r=[...t].sort();return i.length===r.length&&i.every((e,t)=>e===r[t])}function resolution(e){return new RuntimeResourceResolutionError("resolution_rejected",e)}function integrity(e){return new RuntimeResourceResolutionError("integrity_mismatch",e)}function transient(e){return new RuntimeResourceResolutionError("transient",e,"TRANSIENT")}
1
+ import{createHash}from"node:crypto";import{RUNTIME_INTERNAL_API_V1_ROUTE_CONTRACTS,hashRuntimeResourceRedemptionPayload,normalizeRuntimeResourceRedemptionHashPayload,validateRuntimeMcpResourceRedemptionCompletion,validateRuntimeSkillResourceRedemptionCompletion}from"@beeos-ai/beeos-types/runtime";export class RuntimeResourceResolutionError extends Error{kind;code;diagnostic;constructor(e,t,i,r){super(r?`${t} [${r}]`:t),this.kind=e,this.code=i,this.diagnostic=r,this.name="RuntimeResourceResolutionError"}}export class HttpRuntimeOperationResourceResolver{options;attempts=new Map;byRef;mcp;skill;constructor(e){this.options=e;const t=e.bindings.map(e=>[e.resourceRef,Object.freeze({...e})]);if(new Set(t.map(([e])=>e)).size!==t.length)throw new Error("duplicate resource binding");this.byRef=new Map(t)}async readContent(){throw new Error("Service inline content is forbidden; use a trusted artifact reference")}async resolveMcpDefinition(e){this.mcp||(this.mcp=this.redeemMcp(e).catch(e=>{throw this.mcp=void 0,e}));const t=await this.mcp;if(!sameMcpDescriptor(t.descriptor,e))throw new Error("MCP resource descriptor mismatch");return t.config}async resolveMcpCredential(e){this.mcp||(this.mcp=this.redeemMcp(e).catch(e=>{throw this.mcp=void 0,e}));const t=await this.mcp;if(!sameMcpDescriptor(t.descriptor,e))throw new Error("MCP resource descriptor mismatch");return t.credential}async readVerifiedArtifact(e){this.skill||(this.skill=this.redeemSkill(e).catch(e=>{throw this.skill=void 0,e}));const t=await this.skill;if(!sameArtifactDescriptor(t.descriptor,e))throw new Error("skill resource descriptor mismatch");return t.parsed}async redeemMcp(e){const t=this.bindingFor("mcp",e.definitionRef);if(t.version!==e.version||t.sha256!==e.sha256)throw resolution("MCP descriptor does not match the immutable authority binding","descriptor_binding_mismatch");const{request:i,reservation:r}=this.requestFor(t),s=await this.redeem(t,i);let o;try{o=await s.json()}catch{throw integrity("MCP authority response is invalid","response_not_json")}const n=validateRuntimeMcpResourceRedemptionCompletion({request:i,binding:t,reservation:r,expectedDisposition:o.disposition,result:o,sha256Utf8:sha256Utf8});if(!n.valid)throw integrity("MCP resource integrity failed",`violations=${n.violations.join(",")}`);if(!isPlainObject(o.resource.config))throw integrity("MCP authority payload must contain public object config","config_not_object");const a=void 0===o.resource.credential?void 0:credentialMaterial(o.resource.credential);return{descriptor:e,config:Object.freeze({...o.resource.config}),credential:a}}async redeemSkill(e){const t=this.bindingFor("skill",e.artifactRef);if(t.version!==e.version||t.sha256!==e.sha256||t.sizeBytes!==e.sizeBytes)throw resolution("skill descriptor does not match the immutable authority binding","descriptor_binding_mismatch");const{request:i,reservation:r}=this.requestFor(t),s=await this.redeem(t,i),o=new Uint8Array(await s.arrayBuffer()),n=skillHeaders(s),a=validateRuntimeSkillResourceRedemptionCompletion({request:i,binding:t,reservation:r,expectedDisposition:n["X-BeeOS-Redemption-Disposition"],headers:n,chunks:[o],sha256Utf8:sha256Utf8,sha256Bytes:sha256Bytes});if(!a.valid)throw integrity("skill resource integrity failed",`violations=${a.violations.join(",")} bytes=${o.byteLength}`);return{descriptor:e,parsed:await this.options.parseSkillArtifact(o)}}bindingFor(e,t){const i=this.byRef.get(t);if(!i||i.kind!==e||i.operationId!==this.options.operationId||i.instanceId!==this.options.instanceId||i.requestMessageId!==this.options.requestMessageId||i.paramsHash!==this.options.paramsHash)throw resolution("resource authority binding mismatch",`kind=${e} ${i?i.kind!==e?"field=kind":i.operationId!==this.options.operationId?"field=operationId":i.instanceId!==this.options.instanceId?"field=instanceId":i.requestMessageId!==this.options.requestMessageId?"field=requestMessageId":"field=paramsHash":"resourceRef=unbound"}`);return i}requestFor(e){const t=this.options.getAuthorization(),i=this.attempts.get(e.resourceRef),r=i?.redemptionId??(this.options.redemptionId?this.options.redemptionId():stableRedemptionId(e)),s={redemptionId:r,operationId:this.options.operationId,requestMessageId:this.options.requestMessageId,kind:e.kind,resourceRef:e.resourceRef,paramsHash:this.options.paramsHash,executionGrant:t.executionGrant,runtimeLeaseCredential:t.runtimeLeaseCredential,fence:t.fence},o=normalizeRuntimeResourceRedemptionHashPayload(s,e);if(!o)throw resolution("resource redemption request does not match immutable binding","request_binding_mismatch");const n=hashRuntimeResourceRedemptionPayload(o,sha256Utf8);if(i&&i.requestHash!==n)throw resolution("resource redemption intent changed","redemption_intent_changed");return this.attempts.set(e.resourceRef,{redemptionId:r,requestHash:n}),{request:s,reservation:{state:"reserved",redemptionId:r,redemptionRequestHash:n}}}async redeem(e,t){const i=("mcp"===e.kind?RUNTIME_INTERNAL_API_V1_ROUTE_CONTRACTS.redeemMcpResource.path:RUNTIME_INTERNAL_API_V1_ROUTE_CONTRACTS.redeemSkillResource.path).replace("{operationId}",encodeURIComponent(e.operationId)).replace("{resourceRef}",encodeURIComponent(e.resourceRef));let r;try{r=await this.options.fetchAuthorized(new URL(i,this.options.gatewayUrl),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),...this.options.signal?{signal:this.options.signal}:{}})}catch{throw transient("runtime resource authority is unavailable","fetch_rejected")}return r.ok||await throwRedemptionFailure(r,e.kind),r}}function skillHeaders(e){const t=t=>{const i=e.headers.get(t);if(!i)throw integrity(`skill authority response omitted ${t}`,`missing_header=${t}`);return i};return{"X-BeeOS-Redemption-Id":t("X-BeeOS-Redemption-Id"),"X-BeeOS-Redemption-Disposition":t("X-BeeOS-Redemption-Disposition"),"X-BeeOS-Artifact-Ref":t("X-BeeOS-Artifact-Ref"),"X-BeeOS-Artifact-Version":t("X-BeeOS-Artifact-Version"),"X-BeeOS-Artifact-SHA256":t("X-BeeOS-Artifact-SHA256"),"X-BeeOS-Artifact-Size":t("X-BeeOS-Artifact-Size")}}function sha256Utf8(e){return createHash("sha256").update(e).digest("hex")}function stableRedemptionId(e){return`redemption:${sha256Utf8(`${e.operationId}\n${e.requestMessageId}\n${e.kind}\n${e.resourceRef}`)}`}function sha256Bytes(e){const t=createHash("sha256");for(const i of e)t.update(i);return t.digest("hex")}function sameMcpDescriptor(e,t){return e.definitionRef===t.definitionRef&&e.version===t.version&&e.sha256===t.sha256}function sameArtifactDescriptor(e,t){return e.artifactRef===t.artifactRef&&e.version===t.version&&e.sha256===t.sha256&&e.sizeBytes===t.sizeBytes&&e.source===t.source}function isPlainObject(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}function credentialMaterial(e){if(!isPlainObject(e)||Object.keys(e).some(e=>"headers"!==e&&"env"!==e))throw integrity("MCP credential payload is invalid","credential_payload_invalid");const t=stringMap(e.headers,"MCP credential headers"),i=stringMap(e.env,"MCP credential environment");if(!t&&!i)throw integrity("MCP credential payload is empty","credential_payload_empty");return Object.freeze({...t?{headers:Object.freeze(t)}:{},...i?{env:Object.freeze(i)}:{}})}function stringMap(e,t){if(void 0!==e){if(!isPlainObject(e)||Object.entries(e).some(([e,t])=>!e||e.length>256||/[\u0000-\u001f\u007f]/.test(e)||"string"!=typeof t||t.length>16384))throw integrity(`${t} are invalid`,"credential_string_map_invalid");return{...e}}}async function throwRedemptionFailure(e,t){if(408===e.status||425===e.status||429===e.status||e.status>=500)throw transient(`runtime ${t} redemption is temporarily unavailable`,`http_status=${e.status}`);let i;try{i=await e.json()}catch{throw integrity(`runtime ${t} redemption error is invalid`,`http_status=${e.status} error_body=not_json`)}const r=redemptionError(i);if(!r)throw integrity(`runtime ${t} redemption error is invalid`,`http_status=${e.status} error_body=unrecognized_shape`);throw new RuntimeResourceResolutionError("resolution_rejected",`runtime ${t} redemption was rejected`,r.code,`http_status=${e.status} code=${r.code}`)}function redemptionError(e){if(!isPlainObject(e)||"string"!=typeof e.status||"string"!=typeof e.code)return;if("fenced"===e.status&&"FENCED"===e.code&&"string"==typeof e.activeRuntimeEpoch&&/^(0|[1-9][0-9]*)$/.test(e.activeRuntimeEpoch)&&exact(e,["status","code","activeRuntimeEpoch"]))return e;return[["expired","EXPIRED"],["resource_not_found","RESOURCE_NOT_FOUND"],["redemption_conflict","REDEMPTION_CONFLICT"],["resource_integrity_failed","RESOURCE_INTEGRITY_FAILED"],["unauthorized","UNAUTHORIZED"]].some(([t,i])=>e.status===t&&e.code===i&&exact(e,["status","code"]))?e:void 0}function exact(e,t){const i=Object.keys(e).sort(),r=[...t].sort();return i.length===r.length&&i.every((e,t)=>e===r[t])}function resolution(e,t){return new RuntimeResourceResolutionError("resolution_rejected",e,void 0,t)}function integrity(e,t){return new RuntimeResourceResolutionError("integrity_mismatch",e,void 0,t)}function transient(e,t){return new RuntimeResourceResolutionError("transient",e,"TRANSIENT",t)}
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";import{readFileSync}from"node:fs";import{createRequire}from"node:module";import{canonicalizeJcs}from"@beeos-ai/beeos-types/runtime";export const EXPECTED_RUNTIME_PARITY_MANIFEST_DIGEST="d5db2c5e7c78cee73e5672a3c18a8e56179b28888f6fbb660d98ec021ca9de9b";const require=createRequire(import.meta.url);export function computeRuntimeParityManifestDigest(){const e=require.resolve("@beeos-ai/beeos-types/contracts/runtime-method-manifest.v1.json"),t=JSON.parse(readFileSync(e,"utf8"));return createHash("sha256").update(canonicalizeJcs(t),"utf8").digest("hex")}export function verifiedRuntimeParityManifestDigest(){return requireExpectedRuntimeParityManifestDigest(computeRuntimeParityManifestDigest())}export function requireExpectedRuntimeParityManifestDigest(e){if(e!==EXPECTED_RUNTIME_PARITY_MANIFEST_DIGEST)throw new Error(`BeeOS Types parity manifest digest mismatch: expected ${EXPECTED_RUNTIME_PARITY_MANIFEST_DIGEST}, received ${e}`);return e}
1
+ import{createHash}from"node:crypto";import{readFileSync}from"node:fs";import{createRequire}from"node:module";import{canonicalizeJcs}from"@beeos-ai/beeos-types/runtime";export const EXPECTED_RUNTIME_PARITY_MANIFEST_DIGEST="2e58dbc13b8bef2491b95f89920945cb905085828b2fa7a4d4f621624971b186";const require=createRequire(import.meta.url);export function computeRuntimeParityManifestDigest(){const e=require.resolve("@beeos-ai/beeos-types/contracts/runtime-method-manifest.v1.json"),t=JSON.parse(readFileSync(e,"utf8"));return createHash("sha256").update(canonicalizeJcs(t),"utf8").digest("hex")}export function verifiedRuntimeParityManifestDigest(){return requireExpectedRuntimeParityManifestDigest(computeRuntimeParityManifestDigest())}export function requireExpectedRuntimeParityManifestDigest(e){if(e!==EXPECTED_RUNTIME_PARITY_MANIFEST_DIGEST)throw new Error(`BeeOS Types parity manifest digest mismatch: expected ${EXPECTED_RUNTIME_PARITY_MANIFEST_DIGEST}, received ${e}`);return e}