beeos-claw 0.5.97 → 0.5.98

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.
@@ -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{RUNTIME_MESSAGE_TYPES,runtimeMessageBase,runtimeMessageHash,semanticEqual,validateRuntimeCancelEnvelope,validateRuntimeRequestEnvelope}from"./runtime-message-channel-contract.js";import{RuntimeResourceResolutionError}from"./runtime-operation-resource-resolver.js";import{RuntimeTransportFailurePolicy}from"./runtime-transport-failure-policy.js";export class MsRuntimeMessageChannelAdapter{dispatcher;channel;verifier;ports;journal;getLease;options;controller;running;workers=new Map;poisonJournal;renewTransportFailurePolicy=new RuntimeTransportFailurePolicy;receiptHistory=this;constructor(e,t,o,n,a,r,i){if(this.dispatcher=e,this.channel=t,this.verifier=o,this.ports=n,this.journal=a,this.getLease=r,this.options=i,!i.poisonJournal)throw new Error("durable poison journal is required");if(this.poisonJournal=i.poisonJournal,!Number.isSafeInteger(i.poisonDeliveryLimit??3)||(i.poisonDeliveryLimit??3)<=0)throw new Error("poison delivery limit must be a positive integer")}start(){if(this.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?.();this.running&&await abortable(this.running,e)}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){await delay(this.options.idleDelayMs??500,e);continue}let o;try{o=await this.channel.read({maxCount:this.options.readCount??32,blockMs:this.options.blockMs??5e3,lease:t,signal:e})}catch(t){if(e.aborted)return;this.observeDeliveryError(t),await delay(this.options.idleDelayMs??500,e);continue}for(const n of o){if(e.aborted)break;if(n.message.type===RUNTIME_MESSAGE_TYPES.cancel){await this.handleCancel(n,t).catch(e=>this.observeDeliveryError(e));continue}const o=n.message.channel_id;if(this.workers.has(o))continue;const a={deliveryId:n.deliveryId,claimedLease:t,completion:Promise.resolve()};a.completion=this.handleRequest(n,t,e,e=>{a.cancel=e}).catch(e=>this.observeDeliveryError(e)).finally(()=>{this.workers.delete(o)}),this.workers.set(o,a)}}}finally{t&&clearInterval(t),await Promise.allSettled([...this.workers.values()].map(e=>e.completion))}}observeDeliveryError(e){try{this.options.onDeliveryError?.(e)}catch{}}async renewActive(){const e=this.getLease();if(!e)return;const t=[];for(const o of this.workers.values())sameLeaseBinding(o.claimedLease,e)?t.push(o.deliveryId):o.cancel?.();if(!t.length)return;let o;try{o=await this.channel.renew({deliveryIds:t,lease:e})}catch(e){if(this.observeDeliveryError(e),this.renewTransportFailurePolicy.recordFailure()){const e=new Set(t);for(const t of this.workers.values())e.has(t.deliveryId)&&t.cancel?.()}return}if(this.renewTransportFailurePolicy.recordSuccess(),o.notPending.length){const e=new Set(o.notPending);for(const t of this.workers.values())e.has(t.deliveryId)&&t.cancel?.()}}async handleCancel(e,t){const o=validateRuntimeCancelEnvelope(e.message);if(!o.ok)return void await this.handlePoison(e,`invalid_cancel:${o.reason}`,t);const n=o.envelope.payload,a=await this.channel.history({operationId:n.operationId,lease:t});if("found"===a.status&&a.snapshot.terminal&&"final_message"===a.snapshot.terminalSource)return void await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t});if("not_found"===a.status||"expired"===a.status)return void await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t});const r=a.snapshot.request.payload;r.operationId===n.operationId&&r.requestMessageId===n.requestMessageId&&r.requestHash===n.requestHash&&r.dispatchEpoch===n.dispatchEpoch&&r.method===n.method?(await this.journal.observeCancellation({operationId:n.operationId,requestMessageId:n.requestMessageId,requestHash:n.requestHash,eventId:n.eventId}),this.workers.get(n.operationId)?.cancel?.(),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t})):await this.handlePoison(e,"cancel_history_mismatch",t)}async handleRequest(e,t,o,n){const a=validateRuntimeRequestEnvelope(e.message);if(!a.ok)return void await this.handlePoison(e,`invalid_request:${a.reason}`,t);const r=a.envelope.payload,i=e.executionGrant,s=new AbortController;n(()=>s.abort());const c=async()=>await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),d=await this.channel.history({operationId:r.operationId,lease:t});if("not_found"===d.status||"expired"===d.status)return void await c();if(d.snapshot.terminal&&"final_message"===d.snapshot.terminalSource)return void await c();if(this.options.allowedMethods&&!this.options.allowedMethods.has(r.method))return await this.reject(r,"unsupported_method",t),void await c();if("deadline"===d.snapshot.terminalSource||Date.parse(r.executionDeadlineAt)<=Date.now()||!d.snapshot.started&&Date.parse(r.claimDeadlineAt)<=Date.now())return await this.reject(r,"execution_deadline_exceeded",t),void await c();const l=await this.journal.getCancellation(r.operationId),u=d.snapshot.cancelRequested||null!==l;if(u&&"queued"===d.snapshot.status)return await this.reject(r,"cancelled_before_dispatch",t),void await c();if(r.instanceId!==t.instanceId||r.runtimeHandlerIdentity!==t.handlerIdentity||r.dispatchEpoch!==t.runtimeEpoch)return await this.reject(r,"authority_mismatch",t),void await c();const p=d.snapshot.request.payload;if(d.snapshot.operationId!==r.operationId||d.snapshot.requestMessageId!==r.requestMessageId||d.snapshot.requestHash!==r.requestHash||!semanticEqual(p,r))return void await this.handlePoison(e,"request_history_mismatch",t);const h=d.snapshot.started?.payload,m=void 0!==h&&h.operationId===r.operationId&&h.requestMessageId===r.requestMessageId&&h.requestHash===r.requestHash&&h.executionGrantHash===r.executionGrantHash&&h.handlerIdentity===t.handlerIdentity&&h.dispatchEpoch===t.runtimeEpoch&&h.method===r.method,I=await this.journal.get(r.operationId),E=await this.journal.acceptMessageRequest({operationId:r.operationId,command:r.command.name,paramsHash:r.paramsHash,runtimeEpoch:r.dispatchEpoch,requestMessageId:r.requestMessageId,requestHash:r.requestHash}),f=m?I:E,v=decideMessageServiceRecovery(d.snapshot,r,f,m);if("already_terminal"===v)return void await c();if(!CORE_RECOVERY_DECISIONS.has(v))return await this.markOutcomeUnknownIfMutable(E),await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(r,new RuntimeCommandError("OUTCOME_UNKNOWN",`Types recovery policy requires ${v}; this runtime cannot safely replay Core`),(new Date).toISOString())}),void await c();if(await this.verifier.refresh(),!i)return m?await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(r,new RuntimeCommandError("OUTCOME_UNKNOWN","retained started proof has no live execution grant"),(new Date).toISOString())}):await this.reject(r,"invalid_execution_grant",t),void await c();this.verifier.verifyAndDecodeGrant(i)||await this.verifier.refresh(!0);const _=()=>s.abort();let R;o.addEventListener("abort",_,{once:!0});try{R=await verifyAndCreateMessageServiceCoreExecutionAttempt({request:r,executionGrant:i,runtimeEpoch:t.runtimeEpoch,lease:t,verifier:this.verifier,allowExpiredGrant:m,abortSignal:s.signal,resolvePorts:async()=>await this.ports.resolve({request:r,executionGrant:i,command:r.command,getLease:()=>this.currentLease(t),journalRecord:E,abortSignal:s.signal})})}catch(e){if(o.removeEventListener("abort",_),s.abort(),!(e instanceof RuntimeResourceResolutionError))throw e;if("transient"===e.kind)return;return m?(await this.markOutcomeUnknownIfMutable(E),await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(r,new RuntimeCommandError("OUTCOME_UNKNOWN","eager resources cannot be reconstructed after retained started proof"),(new Date).toISOString())})):await this.reject(r,"integrity_mismatch"===e.kind?"resource_integrity_mismatch":"resource_resolution_rejected",t),void await c()}if(!R.ok)return o.removeEventListener("abort",_),s.abort(),m?(await this.markOutcomeUnknownIfMutable(E),await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(r,new RuntimeCommandError("OUTCOME_UNKNOWN","execution grant cannot be revalidated after retained started proof"),(new Date).toISOString())})):await this.reject(r,"invalid_execution_grant",t),void await c();if(!u||"prepared"!==E.phase&&"started"!==E.phase||s.abort(),s.signal.aborted&&!m)return o.removeEventListener("abort",_),await this.reject(r,"cancelled_before_dispatch",t),void await c();m?this.currentLease(t):await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),executionGrant:i,type:RUNTIME_MESSAGE_TYPES.started,payload:{...runtimeMessageBase(r),executionMode:"start",executionGrantHash:r.executionGrantHash,handlerIdentity:t.handlerIdentity,claimedAt:E.messageBinding?.acceptedAt??E.updatedAt}});const y=this.dispatcher.dispatch(r.command,R.context);y.completion.catch(()=>{}),n(()=>{s.abort(),y.cancel()}),s.signal.aborted&&y.cancel();const M=this.forwardProgress(r,y.progress,t).catch(()=>{});let w,g=!1;try{if(("mcp/set"===r.method||"mcp/unset"===r.method)&&hasEffectReceiptHandoff(y)){const e=await y.effectCommitted;if(e){if(e.operationId!==r.operationId||e.method!==r.command.name)throw new RuntimeCommandError("OUTCOME_UNKNOWN","Core MCP receipt correlation mismatch");const o=runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:r.method,result:e.result}),n={schemaVersion:1,operationId:r.operationId,method:r.method,coreResultRef:`sha256:${o}`,coreResultHash:o};w=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,n),g=!0,await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(r),effectRecord:n,effectRecordHash:w,committedAt:e.committedAt}}),await y.acknowledgeEffectReceipt({operationId:r.operationId,method:r.command.name,effectRecordHash:w})}}const o=await y.completion;await M;const n=await this.journal.get(r.operationId);if(!n||!isCommittedCorePhase(n.phase))throw new RuntimeCommandError("OUTCOME_UNKNOWN","Core completed without a committed local journal record");const a=n.updatedAt;let i,s;if("query"!==RUNTIME_INVOCATION_RECOVERY_CLASSES[r.method]){const e=isAgentProjectionMethod(r.method),s=y.getSnapshot().projection,d=n.agentProjectionIntent??n.agentProjectionPreparationFailure;if(e&&!d)throw new RuntimeCommandError("OUTCOME_UNKNOWN","agent effect committed without an atomic projection preparation record");if(!w){const e=d?.coreResultHash??runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:r.method,result:o}),i=n.agentProjectionIntent?.projectionRevision??(methodRequiresProjectionRevision(r.method)?s?.revision??`${Math.max(0,n.revision)}`:void 0),c={schemaVersion:1,operationId:r.operationId,method:r.method,coreResultRef:`sha256:${e}`,coreResultHash:e,...i?{projectionRevision:i}:{}};w=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,c),g=!0,await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(r),effectRecord:c,effectRecordHash:w,committedAt:a}})}let l=e?await awaitRuntimeProjection(y):s;if("session/set_model"===r.method&&"synced"!==l?.state&&(l=await this.projectSessionModelAfterEffect(r,R.context,n,l)),e&&n.agentProjectionIntent&&(!l||l.revision!==n.agentProjectionIntent.projectionRevision))throw new RuntimeCommandError("OUTCOME_UNKNOWN","agent projection receipt revision mismatch");if("pending"===l?.state)return void await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.projectionPending,payload:{...runtimeMessageBase(r),revision:l.revision}});if("synced"===l?.state&&await this.publishProjectionSynced(r,t,{...l,state:"synced"}),"blocked"===l?.state){await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.projectionBlocked,payload:{...runtimeMessageBase(r),revision:l.revision,errorCode:"PROJECTION_BLOCKED"}});const e=RUNTIME_ERROR_DESCRIPTORS.PROJECTION_BLOCKED;return await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(r),outcome:"projection_blocked",response:{jsonrpc:"2.0",id:r.request.id,error:{code:e.jsonRpcCode,message:"PROJECTION_BLOCKED",data:{code:"PROJECTION_BLOCKED",operationId:r.operationId,effectState:"committed",retryMode:e.retryMode}}},effectRecordHash:w,completedAt:a}}),void await c()}i=e?l?.platformAgentId:void 0}try{s=sanitizeRuntimeServiceResult(r.method,o,R.context,i)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed Core result cannot be mapped safely",void 0,{cause:e})}const d=runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:r.method,result:s});g=!0;const l=await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(r),outcome:"succeeded",response:{jsonrpc:"2.0",id:r.request.id,result:s},serviceResultHash:d,...w?{effectRecordHash:w}:{},completedAt:a}});if(this.observeRequestTerminalAccepted(e.deliveryId,l.message),("mcp/set"===r.method||"mcp/unset"===r.method)&&hasEffectReceiptHandoff(y)&&"function"==typeof y.acknowledgeTerminalReceipt){if(!w)throw new RuntimeCommandError("OUTCOME_UNKNOWN","MCP terminal response lacks its committed effect hash");await y.acknowledgeTerminalReceipt({operationId:r.operationId,method:r.command.name,effectRecordHash:w,terminalMessageId:l.message.message_id})}await c(),this.observeRequestAcknowledged(e.deliveryId,l.message)}catch(e){const o=await this.journal.get(r.operationId);if(o&&isCommittedCorePhase(o.phase)&&g)throw e;const n=!o||!isCommittedCorePhase(o.phase)||e instanceof RuntimeCommandError&&"OUTCOME_UNKNOWN"===e.code?e:new RuntimeCommandError("OUTCOME_UNKNOWN","Core effect committed before terminal mapping",void 0,{cause:e}),a=failurePayload(r,n,o?.updatedAt??(new Date).toISOString());await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:a}),await c()}finally{s.abort(),o.removeEventListener("abort",_)}}async handlePoison(e,t,o){this.currentLease(o);(await this.poisonJournal.record({delivery:e,reason:durablePoisonReason(t),limit:this.options.poisonDeliveryLimit??3})).terminal&&await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(o)})}observeRequestTerminalAccepted(e,t){try{this.options.onRequestTerminalAccepted?.({deliveryId:e,message:t})}catch{}}observeRequestAcknowledged(e,t){try{this.options.onRequestAcknowledged?.({deliveryId:e,message:t})}catch{}}async forwardProgress(e,t,o){for await(const n of t)await this.channel.append({operationId:e.operationId,lease:this.currentLease(o),type:RUNTIME_MESSAGE_TYPES.progress,payload:{...runtimeMessageBase(e),phase:n.phase,progress:n}})}async reject(e,t,o){await this.channel.append({operationId:e.operationId,lease:this.currentLease(o),type:RUNTIME_MESSAGE_TYPES.final,payload:prestartFailurePayload(e,t)})}async markOutcomeUnknownIfMutable(e){"prepared"!==e.phase&&"started"!==e.phase||await this.journal.transition({operationId:e.operationId,expectedRevision:e.revision,phase:"outcome_unknown",errorCode:"OUTCOME_UNKNOWN"})}async projectSessionModelAfterEffect(e,t,o,n){const a=Object.freeze({state:"pending",revision:n?.revision??`${Math.max(0,o.revision)}`}),r=e.command;if("session.setModel"!==r.name||"conversation"!==r.context.scope)return a;const i=t.sessionModelProjection;if(!i)return a;try{await i.project({conversationId:r.context.conversation.runtimeConversationUid,modelOverrideId:r.params.modelOverrideId});const e=Object.freeze({state:"synced",revision:a.revision});try{const t=await this.journal.get(o.operationId)??o;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),a}}async publishProjectionSynced(e,t,o){const n=this.currentLease(t),a=await this.channel.history({operationId:e.operationId,lease:n});if("found"===a.status&&"synced"===a.snapshot.projectionState)return;const r={...runtimeMessageBase(e),revision:o.revision};("found"!==a.status||"reserved"===a.snapshot.projectionState||"pending"!==a.snapshot.projectionState&&void 0===a.snapshot.projectionPending)&&await this.channel.append({operationId:e.operationId,lease:n,type:RUNTIME_MESSAGE_TYPES.projectionPending,payload:r}),await this.channel.append({operationId:e.operationId,lease:n,type:RUNTIME_MESSAGE_TYPES.projectionSynced,payload:{...r,...o.platformAgentId?{platformAgentId:o.platformAgentId}:{}}})}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 durablePoisonReason(e){const t=e.replace(/[^a-z0-9_:.-]+/gi,"_").replace(/^_+|_+$/g,"").slice(0,256);if(!t)throw new Error("poison reason is empty");return t}function isCommittedCorePhase(e){return"effect_committed"===e||"projection_committed"===e}const CORE_RECOVERY_DECISIONS=new Set(["execute","resume","replay_effect_committed","resume_projection","publish_committed_result","publish_projected_result","publish_terminal_result"]);function decideMessageServiceRecovery(e,t,o,n){const a=RUNTIME_INVOCATION_PARITY_ENTRIES.find(e=>e.acpMethod===t.method),r=e.terminal?"terminal":"blocked"===e.projectionState?"projection_blocked":"synced"===e.projectionState?"projection_synced":"pending"===e.projectionState?"projection_pending":e.effectCommitted?"runtime_committed":n?"running":"queued",i="failed"===o?.phase||"outcome_unknown"===o?.phase?"terminal":o?.phase,s=o&&o.runtimeEpoch===t.dispatchEpoch&&(void 0===o.messageBinding||o.messageBinding.requestMessageId===t.requestMessageId&&o.messageBinding.requestHash===t.requestHash)?"continuous":"discontinuous";return reduceRuntimeRecoveryPolicy({recoveryClass:a?.recoveryClass??RUNTIME_INVOCATION_RECOVERY_CLASSES[t.method],projectionRequired:"mcp/set"===t.method||"mcp/unset"===t.method||(a?.projectionRequired??!1),messageServicePhase:r,executionBoundaryCrossed:n,lineageContinuity:s,journalState:o?"available":"unavailable",...i?{journalPhase:i}:{}})}export function sanitizeRuntimeServiceResult(e,t,o,n){if("session/clear"===e)return serviceClearResult(t,o?.historyBoundary);if("session/set_model"===e)return serviceSetModelResult(t,o);if(!(e in SERVICE_CANONICAL_COMMAND_NAMES))return t;const a="cron/status"===e&&record(t)?{enabled:t.enabled,jobCount:t.jobCount,..."number"==typeof t.nextWakeAtMs?{nextWakeAtMs:t.nextWakeAtMs}:{}}:t;return mapCanonicalResultToService(e,a,{...n?{platformAgentId:n}:{},classifySkillOrigin:e=>e.bundled?{origin:"bundled",slug:e.slug}:{origin:"legacy_runtime",slug:e.slug},resolveMcpView:e=>({name:e.name,transport:e.transport,origin:"legacy_runtime",...void 0===e.connected?{}:{connected:e.connected},...void 0===e.connectionTimeoutMs?{}:{connectionTimeoutMs:e.connectionTimeoutMs}}),sanitizeDiagnostic:e=>/^[A-Z][A-Z0-9_]{0,63}$/.test(e)?e:"RUNTIME_EXECUTION_FAILED"})}function serviceClearResult(e,t){if(!record(e)||!0!==e.cleared||"string"!=typeof e.historyGeneration||!t||"message-service"!==t.kind)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed clear result lacks its Message Service receipt");const o=t;if(!o.committedIntentId)throw new RuntimeCommandError("OUTCOME_UNKNOWN","Message Service clear receipt is unavailable");return{...e,clearIntentId:o.committedIntentId()}}function serviceSetModelResult(e,t){if(!record(e)||"string"!=typeof e.effectiveModelId||!t)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed set_model result is invalid");const o=t.verifiedMessageGrant?.claims.command;if(!o||"session.setModel"!==o.name||"conversation"!==o.context.scope)throw new RuntimeCommandError("OUTCOME_UNKNOWN","set_model Service target receipt is unavailable");const n=o.params.modelOverrideId;return{conversationId:o.context.conversation.runtimeConversationUid,...null===n?{defaultModelId:e.effectiveModelId}:{},modelOverrideId:n,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,o){const n=t instanceof RuntimeCommandError?t.code:"RUNTIME_EXECUTION_FAILED",a=n in RUNTIME_ERROR_DESCRIPTORS?n:"RUNTIME_EXECUTION_FAILED",r="OUTCOME_UNKNOWN"===a||"INSTANCE_EPOCH_MISMATCH"===a?"outcome_unknown":"COMMAND_EXPIRED"===a?"expired":"OPERATION_CANCELLED"===a?"cancelled":"failed",i="outcome_unknown"===r?"OUTCOME_UNKNOWN":a,s=RUNTIME_ERROR_DESCRIPTORS[i],c="outcome_unknown"===r?"outcome_unknown":r;return{...runtimeMessageBase(e),outcome:r,response:{jsonrpc:"2.0",id:e.request.id,error:{code:s.jsonRpcCode,message:i,data:{code:i,operationId:e.operationId,effectState:c,retryMode:s.retryMode}}},completedAt:o}}function prestartFailurePayload(e,t){const o="invalid_execution_grant"===t?"INVALID_EXECUTION_GRANT":"unsupported_method"===t?"METHOD_NOT_SUPPORTED":"authority_mismatch"===t?"INSTANCE_EPOCH_MISMATCH":"execution_deadline_exceeded"===t?"COMMAND_EXPIRED":"cancelled_before_dispatch"===t?"OPERATION_CANCELLED":"resource_resolution_rejected"===t?"INVALID_INVOCATION":"RUNTIME_EXECUTION_FAILED",n=RUNTIME_ERROR_DESCRIPTORS[o in RUNTIME_ERROR_DESCRIPTORS?o:"RUNTIME_EXECUTION_FAILED"],a="COMMAND_EXPIRED"===o?"expired":"OPERATION_CANCELLED"===o?"cancelled":"failed";return{...runtimeMessageBase(e),outcome:a,response:{jsonrpc:"2.0",id:e.request.id,error:{code:n.jsonRpcCode,message:o,data:{code:o,operationId:e.operationId,effectState:a,retryMode:n.retryMode}}},completedAt:(new Date).toISOString()}}function abortable(e,t){return t?t.aborted?Promise.resolve():new Promise((o,n)=>{const a=()=>o();t.addEventListener("abort",a,{once:!0}),e.then(()=>{t.removeEventListener("abort",a),o()},e=>{t.removeEventListener("abort",a),n(e)})}):e}function delay(e,t){return new Promise(o=>{if(t?.aborted)return o();const n=()=>{clearTimeout(a),o()},a=setTimeout(()=>{t?.removeEventListener("abort",n),o()},e);t?.addEventListener("abort",n,{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{RUNTIME_MESSAGE_TYPES,runtimeMessageBase,runtimeMessageHash,semanticEqual,validateRuntimeCancelEnvelope,validateRuntimeRequestEnvelope}from"./runtime-message-channel-contract.js";import{RuntimeResourceResolutionError}from"./runtime-operation-resource-resolver.js";import{RuntimeTransportFailurePolicy}from"./runtime-transport-failure-policy.js";export class MsRuntimeMessageChannelAdapter{dispatcher;channel;verifier;ports;journal;getLease;options;controller;running;workers=new Map;poisonJournal;renewTransportFailurePolicy=new RuntimeTransportFailurePolicy;receiptHistory=this;constructor(e,t,o,n,a,r,i){if(this.dispatcher=e,this.channel=t,this.verifier=o,this.ports=n,this.journal=a,this.getLease=r,this.options=i,!i.poisonJournal)throw new Error("durable poison journal is required");if(this.poisonJournal=i.poisonJournal,!Number.isSafeInteger(i.poisonDeliveryLimit??3)||(i.poisonDeliveryLimit??3)<=0)throw new Error("poison delivery limit must be a positive integer")}start(){if(this.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?.();this.running&&await abortable(this.running,e)}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){await delay(this.options.idleDelayMs??500,e);continue}let o;try{o=await this.channel.read({maxCount:this.options.readCount??32,blockMs:this.options.blockMs??5e3,lease:t,signal:e})}catch(t){if(e.aborted)return;this.observeDeliveryError(t),await delay(this.options.idleDelayMs??500,e);continue}for(const n of o){if(e.aborted)break;if(n.message.type===RUNTIME_MESSAGE_TYPES.cancel){await this.handleCancel(n,t).catch(e=>this.observeDeliveryError(e));continue}const o=n.message.channel_id;if(this.workers.has(o))continue;const a={deliveryId:n.deliveryId,claimedLease:t,completion:Promise.resolve()};a.completion=this.handleRequest(n,t,e,e=>{a.cancel=e}).catch(e=>this.observeDeliveryError(e)).finally(()=>{this.workers.delete(o)}),this.workers.set(o,a)}}}finally{t&&clearInterval(t),await Promise.allSettled([...this.workers.values()].map(e=>e.completion))}}observeDeliveryError(e){try{this.options.onDeliveryError?.(e)}catch{}}async renewActive(){const e=this.getLease();if(!e)return;const t=[];for(const o of this.workers.values())sameLeaseBinding(o.claimedLease,e)?t.push(o.deliveryId):o.cancel?.();if(!t.length)return;let o;try{o=await this.channel.renew({deliveryIds:t,lease:e})}catch(e){if(this.observeDeliveryError(e),this.renewTransportFailurePolicy.recordFailure()){const e=new Set(t);for(const t of this.workers.values())e.has(t.deliveryId)&&t.cancel?.()}return}if(this.renewTransportFailurePolicy.recordSuccess(),o.notPending.length){const e=new Set(o.notPending);for(const t of this.workers.values())e.has(t.deliveryId)&&t.cancel?.()}}async handleCancel(e,t){const o=validateRuntimeCancelEnvelope(e.message);if(!o.ok)return void await this.handlePoison(e,`invalid_cancel:${o.reason}`,t);const n=o.envelope.payload,a=await this.channel.history({operationId:n.operationId,lease:t});if("found"===a.status&&a.snapshot.terminal&&"final_message"===a.snapshot.terminalSource)return void await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t});if("not_found"===a.status||"expired"===a.status)return void await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t});const r=a.snapshot.request.payload;r.operationId===n.operationId&&r.requestMessageId===n.requestMessageId&&r.requestHash===n.requestHash&&r.dispatchEpoch===n.dispatchEpoch&&r.method===n.method?(await this.journal.observeCancellation({operationId:n.operationId,requestMessageId:n.requestMessageId,requestHash:n.requestHash,eventId:n.eventId}),this.workers.get(n.operationId)?.cancel?.(),await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:t})):await this.handlePoison(e,"cancel_history_mismatch",t)}async handleRequest(e,t,o,n){const a=validateRuntimeRequestEnvelope(e.message);if(!a.ok)return void await this.handlePoison(e,`invalid_request:${a.reason}`,t);const r=a.envelope.payload,i=e.executionGrant,s=new AbortController;n(()=>s.abort());const c=async()=>await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(t)}),d=await this.channel.history({operationId:r.operationId,lease:t});if("not_found"===d.status||"expired"===d.status)return void await c();if(d.snapshot.terminal&&"final_message"===d.snapshot.terminalSource)return void await c();if(this.options.allowedMethods&&!this.options.allowedMethods.has(r.method))return await this.reject(r,"unsupported_method",t),void await c();if("deadline"===d.snapshot.terminalSource||Date.parse(r.executionDeadlineAt)<=Date.now()||!d.snapshot.started&&Date.parse(r.claimDeadlineAt)<=Date.now())return await this.reject(r,"execution_deadline_exceeded",t),void await c();const l=await this.journal.getCancellation(r.operationId),u=d.snapshot.cancelRequested||null!==l;if(u&&"queued"===d.snapshot.status)return await this.reject(r,"cancelled_before_dispatch",t),void await c();if(r.instanceId!==t.instanceId||r.runtimeHandlerIdentity!==t.handlerIdentity||r.dispatchEpoch!==t.runtimeEpoch)return await this.reject(r,"authority_mismatch",t),void await c();const p=d.snapshot.request.payload;if(d.snapshot.operationId!==r.operationId||d.snapshot.requestMessageId!==r.requestMessageId||d.snapshot.requestHash!==r.requestHash||!semanticEqual(p,r))return void await this.handlePoison(e,"request_history_mismatch",t);const h=d.snapshot.started?.payload,m=void 0!==h&&h.operationId===r.operationId&&h.requestMessageId===r.requestMessageId&&h.requestHash===r.requestHash&&h.executionGrantHash===r.executionGrantHash&&h.handlerIdentity===t.handlerIdentity&&h.dispatchEpoch===t.runtimeEpoch&&h.method===r.method,I=await this.journal.get(r.operationId),E=await this.journal.acceptMessageRequest({operationId:r.operationId,command:r.command.name,paramsHash:r.paramsHash,runtimeEpoch:r.dispatchEpoch,requestMessageId:r.requestMessageId,requestHash:r.requestHash}),f=m?I:E,v=decideMessageServiceRecovery(d.snapshot,r,f,m);if("already_terminal"===v)return void await c();if(!CORE_RECOVERY_DECISIONS.has(v))return await this.markOutcomeUnknownIfMutable(E),await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(r,new RuntimeCommandError("OUTCOME_UNKNOWN",`Types recovery policy requires ${v}; this runtime cannot safely replay Core`),(new Date).toISOString())}),void await c();if(await this.verifier.refresh(),!i)return m?await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(r,new RuntimeCommandError("OUTCOME_UNKNOWN","retained started proof has no live execution grant"),(new Date).toISOString())}):await this.reject(r,"invalid_execution_grant",t),void await c();this.verifier.verifyAndDecodeGrant(i)||await this.verifier.refresh(!0);const _=()=>s.abort();let R;o.addEventListener("abort",_,{once:!0});try{R=await verifyAndCreateMessageServiceCoreExecutionAttempt({request:r,executionGrant:i,runtimeEpoch:t.runtimeEpoch,lease:t,verifier:this.verifier,allowExpiredGrant:m,abortSignal:s.signal,resolvePorts:async()=>await this.ports.resolve({request:r,executionGrant:i,command:r.command,getLease:()=>this.currentLease(t),journalStoreId:this.options.journalStoreId,journalGeneration:this.options.journalGeneration,journalRecord:E,abortSignal:s.signal})})}catch(e){if(o.removeEventListener("abort",_),s.abort(),!(e instanceof RuntimeResourceResolutionError))throw e;if("transient"===e.kind)return;return m?(await this.markOutcomeUnknownIfMutable(E),await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(r,new RuntimeCommandError("OUTCOME_UNKNOWN","eager resources cannot be reconstructed after retained started proof"),(new Date).toISOString())})):await this.reject(r,"integrity_mismatch"===e.kind?"resource_integrity_mismatch":"resource_resolution_rejected",t),void await c()}if(!R.ok)return o.removeEventListener("abort",_),s.abort(),m?(await this.markOutcomeUnknownIfMutable(E),await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:failurePayload(r,new RuntimeCommandError("OUTCOME_UNKNOWN","execution grant cannot be revalidated after retained started proof"),(new Date).toISOString())})):await this.reject(r,"invalid_execution_grant",t),void await c();if(!u||"prepared"!==E.phase&&"started"!==E.phase||s.abort(),s.signal.aborted&&!m)return o.removeEventListener("abort",_),await this.reject(r,"cancelled_before_dispatch",t),void await c();m?this.currentLease(t):await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),executionGrant:i,type:RUNTIME_MESSAGE_TYPES.started,payload:{...runtimeMessageBase(r),executionMode:"start",executionGrantHash:r.executionGrantHash,handlerIdentity:t.handlerIdentity,claimedAt:E.messageBinding?.acceptedAt??E.updatedAt}});const y=this.dispatcher.dispatch(r.command,R.context);y.completion.catch(()=>{}),n(()=>{s.abort(),y.cancel()}),s.signal.aborted&&y.cancel();const M=this.forwardProgress(r,y.progress,t).catch(()=>{});let w,g=!1;try{if(("mcp/set"===r.method||"mcp/unset"===r.method)&&hasEffectReceiptHandoff(y)){const e=await y.effectCommitted;if(e){if(e.operationId!==r.operationId||e.method!==r.command.name)throw new RuntimeCommandError("OUTCOME_UNKNOWN","Core MCP receipt correlation mismatch");const o=runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:r.method,result:e.result}),n={schemaVersion:1,operationId:r.operationId,method:r.method,coreResultRef:`sha256:${o}`,coreResultHash:o};w=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,n),g=!0,await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(r),effectRecord:n,effectRecordHash:w,committedAt:e.committedAt}}),await y.acknowledgeEffectReceipt({operationId:r.operationId,method:r.command.name,effectRecordHash:w})}}const o=await y.completion;await M;const n=await this.journal.get(r.operationId);if(!n||!isCommittedCorePhase(n.phase))throw new RuntimeCommandError("OUTCOME_UNKNOWN","Core completed without a committed local journal record");const a=n.updatedAt;let i,s;if("query"!==RUNTIME_INVOCATION_RECOVERY_CLASSES[r.method]){const e=isAgentProjectionMethod(r.method),s=y.getSnapshot().projection,d=n.agentProjectionIntent??n.agentProjectionPreparationFailure;if(e&&!d)throw new RuntimeCommandError("OUTCOME_UNKNOWN","agent effect committed without an atomic projection preparation record");if(!w){const e=d?.coreResultHash??runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:r.method,result:o}),i=n.agentProjectionIntent?.projectionRevision??(methodRequiresProjectionRevision(r.method)?s?.revision??`${Math.max(0,n.revision)}`:void 0),c={schemaVersion:1,operationId:r.operationId,method:r.method,coreResultRef:`sha256:${e}`,coreResultHash:e,...i?{projectionRevision:i}:{}};w=runtimeMessageHash(RUNTIME_HASH_DOMAINS.effectRecord,c),g=!0,await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.effectCommitted,payload:{...runtimeMessageBase(r),effectRecord:c,effectRecordHash:w,committedAt:a}})}let l=e?await awaitRuntimeProjection(y):s;if("session/set_model"===r.method&&"synced"!==l?.state&&(l=await this.projectSessionModelAfterEffect(r,R.context,n,l)),e&&n.agentProjectionIntent&&(!l||l.revision!==n.agentProjectionIntent.projectionRevision))throw new RuntimeCommandError("OUTCOME_UNKNOWN","agent projection receipt revision mismatch");if("pending"===l?.state)return void await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.projectionPending,payload:{...runtimeMessageBase(r),revision:l.revision}});if("synced"===l?.state&&await this.publishProjectionSynced(r,t,{...l,state:"synced"}),"blocked"===l?.state){await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.projectionBlocked,payload:{...runtimeMessageBase(r),revision:l.revision,errorCode:"PROJECTION_BLOCKED"}});const e=RUNTIME_ERROR_DESCRIPTORS.PROJECTION_BLOCKED;return await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(r),outcome:"projection_blocked",response:{jsonrpc:"2.0",id:r.request.id,error:{code:e.jsonRpcCode,message:"PROJECTION_BLOCKED",data:{code:"PROJECTION_BLOCKED",operationId:r.operationId,effectState:"committed",retryMode:e.retryMode}}},effectRecordHash:w,completedAt:a}}),void await c()}i=e?l?.platformAgentId:void 0}try{s=sanitizeRuntimeServiceResult(r.method,o,R.context,i)}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed Core result cannot be mapped safely",void 0,{cause:e})}const d=runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:r.method,result:s});g=!0;const l=await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:{...runtimeMessageBase(r),outcome:"succeeded",response:{jsonrpc:"2.0",id:r.request.id,result:s},serviceResultHash:d,...w?{effectRecordHash:w}:{},completedAt:a}});if(this.observeRequestTerminalAccepted(e.deliveryId,l.message),("mcp/set"===r.method||"mcp/unset"===r.method)&&hasEffectReceiptHandoff(y)&&"function"==typeof y.acknowledgeTerminalReceipt){if(!w)throw new RuntimeCommandError("OUTCOME_UNKNOWN","MCP terminal response lacks its committed effect hash");await y.acknowledgeTerminalReceipt({operationId:r.operationId,method:r.command.name,effectRecordHash:w,terminalMessageId:l.message.message_id})}await c(),this.observeRequestAcknowledged(e.deliveryId,l.message)}catch(e){const o=await this.journal.get(r.operationId);if(o&&isCommittedCorePhase(o.phase)&&g)throw e;const n=!o||!isCommittedCorePhase(o.phase)||e instanceof RuntimeCommandError&&"OUTCOME_UNKNOWN"===e.code?e:new RuntimeCommandError("OUTCOME_UNKNOWN","Core effect committed before terminal mapping",void 0,{cause:e}),a=failurePayload(r,n,o?.updatedAt??(new Date).toISOString());await this.channel.append({operationId:r.operationId,lease:this.currentLease(t),type:RUNTIME_MESSAGE_TYPES.final,payload:a}),await c()}finally{s.abort(),o.removeEventListener("abort",_)}}async handlePoison(e,t,o){this.currentLease(o);(await this.poisonJournal.record({delivery:e,reason:durablePoisonReason(t),limit:this.options.poisonDeliveryLimit??3})).terminal&&await this.channel.acknowledge({deliveryIds:[e.deliveryId],lease:this.currentLease(o)})}observeRequestTerminalAccepted(e,t){try{this.options.onRequestTerminalAccepted?.({deliveryId:e,message:t})}catch{}}observeRequestAcknowledged(e,t){try{this.options.onRequestAcknowledged?.({deliveryId:e,message:t})}catch{}}async forwardProgress(e,t,o){for await(const n of t)await this.channel.append({operationId:e.operationId,lease:this.currentLease(o),type:RUNTIME_MESSAGE_TYPES.progress,payload:{...runtimeMessageBase(e),phase:n.phase,progress:n}})}async reject(e,t,o){await this.channel.append({operationId:e.operationId,lease:this.currentLease(o),type:RUNTIME_MESSAGE_TYPES.final,payload:prestartFailurePayload(e,t)})}async markOutcomeUnknownIfMutable(e){"prepared"!==e.phase&&"started"!==e.phase||await this.journal.transition({operationId:e.operationId,expectedRevision:e.revision,phase:"outcome_unknown",errorCode:"OUTCOME_UNKNOWN"})}async projectSessionModelAfterEffect(e,t,o,n){const a=Object.freeze({state:"pending",revision:n?.revision??`${Math.max(0,o.revision)}`}),r=e.command;if("session.setModel"!==r.name||"conversation"!==r.context.scope)return a;const i=t.sessionModelProjection;if(!i)return a;try{await i.project({conversationId:r.context.conversation.runtimeConversationUid,modelOverrideId:r.params.modelOverrideId});const e=Object.freeze({state:"synced",revision:a.revision});try{const t=await this.journal.get(o.operationId)??o;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),a}}async publishProjectionSynced(e,t,o){const n=this.currentLease(t),a=await this.channel.history({operationId:e.operationId,lease:n});if("found"===a.status&&"synced"===a.snapshot.projectionState)return;const r={...runtimeMessageBase(e),revision:o.revision};("found"!==a.status||"reserved"===a.snapshot.projectionState||"pending"!==a.snapshot.projectionState&&void 0===a.snapshot.projectionPending)&&await this.channel.append({operationId:e.operationId,lease:n,type:RUNTIME_MESSAGE_TYPES.projectionPending,payload:r}),await this.channel.append({operationId:e.operationId,lease:n,type:RUNTIME_MESSAGE_TYPES.projectionSynced,payload:{...r,...o.platformAgentId?{platformAgentId:o.platformAgentId}:{}}})}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 durablePoisonReason(e){const t=e.replace(/[^a-z0-9_:.-]+/gi,"_").replace(/^_+|_+$/g,"").slice(0,256);if(!t)throw new Error("poison reason is empty");return t}function isCommittedCorePhase(e){return"effect_committed"===e||"projection_committed"===e}const CORE_RECOVERY_DECISIONS=new Set(["execute","resume","replay_effect_committed","resume_projection","publish_committed_result","publish_projected_result","publish_terminal_result"]);function decideMessageServiceRecovery(e,t,o,n){const a=RUNTIME_INVOCATION_PARITY_ENTRIES.find(e=>e.acpMethod===t.method),r=e.terminal?"terminal":"blocked"===e.projectionState?"projection_blocked":"synced"===e.projectionState?"projection_synced":"pending"===e.projectionState?"projection_pending":e.effectCommitted?"runtime_committed":n?"running":"queued",i="failed"===o?.phase||"outcome_unknown"===o?.phase?"terminal":o?.phase,s=o&&o.runtimeEpoch===t.dispatchEpoch&&(void 0===o.messageBinding||o.messageBinding.requestMessageId===t.requestMessageId&&o.messageBinding.requestHash===t.requestHash)?"continuous":"discontinuous";return reduceRuntimeRecoveryPolicy({recoveryClass:a?.recoveryClass??RUNTIME_INVOCATION_RECOVERY_CLASSES[t.method],projectionRequired:"mcp/set"===t.method||"mcp/unset"===t.method||(a?.projectionRequired??!1),messageServicePhase:r,executionBoundaryCrossed:n,lineageContinuity:s,journalState:o?"available":"unavailable",...i?{journalPhase:i}:{}})}export function sanitizeRuntimeServiceResult(e,t,o,n){if("session/clear"===e)return serviceClearResult(t,o?.historyBoundary);if("session/set_model"===e)return serviceSetModelResult(t,o);if(!(e in SERVICE_CANONICAL_COMMAND_NAMES))return t;const a="cron/status"===e&&record(t)?{enabled:t.enabled,jobCount:t.jobCount,..."number"==typeof t.nextWakeAtMs?{nextWakeAtMs:t.nextWakeAtMs}:{}}:t;return mapCanonicalResultToService(e,a,{...n?{platformAgentId:n}:{},classifySkillOrigin:e=>e.bundled?{origin:"bundled",slug:e.slug}:{origin:"legacy_runtime",slug:e.slug},resolveMcpView:e=>({name:e.name,transport:e.transport,origin:"legacy_runtime",...void 0===e.connected?{}:{connected:e.connected},...void 0===e.connectionTimeoutMs?{}:{connectionTimeoutMs:e.connectionTimeoutMs}}),sanitizeDiagnostic:e=>/^[A-Z][A-Z0-9_]{0,63}$/.test(e)?e:"RUNTIME_EXECUTION_FAILED"})}function serviceClearResult(e,t){if(!record(e)||!0!==e.cleared||"string"!=typeof e.historyGeneration||!t||"message-service"!==t.kind)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed clear result lacks its Message Service receipt");const o=t;if(!o.committedIntentId)throw new RuntimeCommandError("OUTCOME_UNKNOWN","Message Service clear receipt is unavailable");return{...e,clearIntentId:o.committedIntentId()}}function serviceSetModelResult(e,t){if(!record(e)||"string"!=typeof e.effectiveModelId||!t)throw new RuntimeCommandError("OUTCOME_UNKNOWN","committed set_model result is invalid");const o=t.verifiedMessageGrant?.claims.command;if(!o||"session.setModel"!==o.name||"conversation"!==o.context.scope)throw new RuntimeCommandError("OUTCOME_UNKNOWN","set_model Service target receipt is unavailable");const n=o.params.modelOverrideId;return{conversationId:o.context.conversation.runtimeConversationUid,...null===n?{defaultModelId:e.effectiveModelId}:{},modelOverrideId:n,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,o){const n=t instanceof RuntimeCommandError?t.code:"RUNTIME_EXECUTION_FAILED",a=n in RUNTIME_ERROR_DESCRIPTORS?n:"RUNTIME_EXECUTION_FAILED",r="OUTCOME_UNKNOWN"===a||"INSTANCE_EPOCH_MISMATCH"===a?"outcome_unknown":"COMMAND_EXPIRED"===a?"expired":"OPERATION_CANCELLED"===a?"cancelled":"failed",i="outcome_unknown"===r?"OUTCOME_UNKNOWN":a,s=RUNTIME_ERROR_DESCRIPTORS[i],c="outcome_unknown"===r?"outcome_unknown":r;return{...runtimeMessageBase(e),outcome:r,response:{jsonrpc:"2.0",id:e.request.id,error:{code:s.jsonRpcCode,message:i,data:{code:i,operationId:e.operationId,effectState:c,retryMode:s.retryMode}}},completedAt:o}}function prestartFailurePayload(e,t){const o="invalid_execution_grant"===t?"INVALID_EXECUTION_GRANT":"unsupported_method"===t?"METHOD_NOT_SUPPORTED":"authority_mismatch"===t?"INSTANCE_EPOCH_MISMATCH":"execution_deadline_exceeded"===t?"COMMAND_EXPIRED":"cancelled_before_dispatch"===t?"OPERATION_CANCELLED":"resource_resolution_rejected"===t?"INVALID_INVOCATION":"RUNTIME_EXECUTION_FAILED",n=RUNTIME_ERROR_DESCRIPTORS[o in RUNTIME_ERROR_DESCRIPTORS?o:"RUNTIME_EXECUTION_FAILED"],a="COMMAND_EXPIRED"===o?"expired":"OPERATION_CANCELLED"===o?"cancelled":"failed";return{...runtimeMessageBase(e),outcome:a,response:{jsonrpc:"2.0",id:e.request.id,error:{code:n.jsonRpcCode,message:o,data:{code:o,operationId:e.operationId,effectState:a,retryMode:n.retryMode}}},completedAt:(new Date).toISOString()}}function abortable(e,t){return t?t.aborted?Promise.resolve():new Promise((o,n)=>{const a=()=>o();t.addEventListener("abort",a,{once:!0}),e.then(()=>{t.removeEventListener("abort",a),o()},e=>{t.removeEventListener("abort",a),n(e)})}):e}function delay(e,t){return new Promise(o=>{if(t?.aborted)return o();const n=()=>{clearTimeout(a),o()},a=setTimeout(()=>{t?.removeEventListener("abort",n),o()},e);t?.addEventListener("abort",n,{once:!0})})}
@@ -1 +1 @@
1
- import{MsRuntimeMessageChannelAdapter}from"./ms-runtime-message-channel-adapter.js";export class MsRuntimeMessageChannelConsumerFactory{deps;constructor(e){this.deps=e}async create(e){return new MsRuntimeMessageChannelAdapter(e.dispatcher,this.deps.channel,this.deps.verifier,this.deps.ports,this.deps.journal,()=>e.getLease(),{...this.deps.options,allowedMethods:this.deps.allowedMethods})}}
1
+ import{MsRuntimeMessageChannelAdapter}from"./ms-runtime-message-channel-adapter.js";export class MsRuntimeMessageChannelConsumerFactory{deps;constructor(e){this.deps=e}async create(e){return new MsRuntimeMessageChannelAdapter(e.dispatcher,this.deps.channel,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})}}
@@ -1 +1 @@
1
- import{RUNTIME_RESOURCE_BINDING_CONTRACT_REVISION}from"@beeos-ai/beeos-types/runtime";import{parseAndValidateTemplatePackage}from"../acp-gateway/agent-template-package.js";import{HttpRuntimeOperationResourceResolver,RuntimeResourceResolutionError}from"./runtime-operation-resource-resolver.js";import{MessageServiceRuntimeMessageChannel}from"./message-service-runtime-message-channel.js";import{MessageServiceConversationClearHttpAuthority}from"./message-service-conversation-clear-http-authority.js";import{MessageServiceConversationHistoryBoundary}from"./message-service-conversation-history-boundary.js";import{MessageServiceSessionModelHttpAuthority}from"./message-service-session-model-http-authority.js";import{MsRuntimeMessageChannelConsumerFactory}from"./ms-runtime-message-channel-consumer-factory.js";import{RuntimeJwksVerifier}from"./runtime-jwks-verifier.js";import{GatewayGrantJwksVerifier}from"./split-runtime-authorization-verifier.js";import{RUNTIME_MESSAGE_CHANNEL_REVISION,RUNTIME_PARITY_MANIFEST}from"./runtime-parity-manifest.js";import{intersectRuntimeServiceMethodsWithBackendCapabilities,loadRuntimeServiceContractIdentity,runtimeServiceContractRequirement}from"./runtime-service-contract-compatibility.js";const CONTRACT_ARTIFACT_BLOCKER=Object.freeze({id:"contract_artifact_mismatch",owner:"backend",requiredContract:"frozen Types manifest and Service wire artifacts"}),TRANSPORT_BLOCKER=Object.freeze({id:"message_channel_transport",owner:"backend",requiredContract:`${RUNTIME_MESSAGE_CHANNEL_REVISION} HTTP delivery/history/append authority`}),JWKS_BLOCKER=Object.freeze({id:"gateway_grant_jwks",owner:"backend",requiredContract:"Purpose-bound Gateway runtime execution-grant JWKS proxy"}),POISON_JOURNAL_BLOCKER=Object.freeze({id:"poison_journal",owner:"openclaw_runtime_client",requiredContract:"Durable bounded runtime poison-delivery journal"}),grantAdapterOptions=new WeakMap;export class AgentGatewayGrantJwksReadinessAdapter{constructor(e){grantAdapterOptions.set(this,{agentGatewayUrl:new URL(e.agentGatewayUrl).toString()})}}export class AgentGatewaySplitJwksReadinessAdapter extends AgentGatewayGrantJwksReadinessAdapter{}const transportOptions=new WeakMap;export class RuntimeServiceTransportReadinessAdapter{constructor(e){transportOptions.set(this,{messageService:e.messageService,scopedDeliveryKey:e.scopedDeliveryKey,agentGatewayUrl:new URL(e.agentGatewayUrl).toString(),boundAgentFetch:e.boundAgentFetch})}}const CAPABILITY_BLOCKERS=Object.freeze(RUNTIME_PARITY_MANIFEST.filter(e=>"blocked"===e.status).map(e=>Object.freeze({method:e.method,owner:e.blockerOwner,requiredContract:e.contractRevision})));export async function createRuntimeServiceProductionCandidate(e){try{loadRuntimeServiceContractIdentity()}catch{return{status:"unavailable",blockers:Object.freeze([{...CONTRACT_ARTIFACT_BLOCKER,requiredContract:contractArtifactRequirement()}])}}if(!e.poisonJournal)return{status:"unavailable",blockers:Object.freeze([POISON_JOURNAL_BLOCKER])};let t;if(e.authorizationAdapter)try{t=await probeGatewayGrantJwks(e.authorizationAdapter)}catch{}const r=e.transportAdapter?transportOptions.get(e.transportAdapter):void 0;if(!r)return{status:"unavailable",blockers:Object.freeze([TRANSPORT_BLOCKER,...t?[]:[JWKS_BLOCKER]])};if(!t)return{status:"unavailable",blockers:Object.freeze([JWKS_BLOCKER])};try{const n=await r.messageService.ready(),a=new MessageServiceRuntimeMessageChannel({serviceUrl:n.serviceUrl,transport:r.messageService,scopedDeliveryKey:r.scopedDeliveryKey}),i=runtimeMethods(),s=e.attemptPorts??runtimeMessageAttemptPorts(r,n.serviceUrl);return{status:"ready",blockers:[],capabilityBlockers:CAPABILITY_BLOCKERS,serviceMethods:i,factory:new MsRuntimeMessageChannelConsumerFactory({channel:a,verifier:t,ports:s,journal:e.commandJournal,allowedMethods:new Set(i),options:{poisonJournal:e.poisonJournal,...e.onConsumerDeliveryError?{onDeliveryError:e.onConsumerDeliveryError}:{},...e.onConsumerRequestTerminalAccepted?{onRequestTerminalAccepted:e.onConsumerRequestTerminalAccepted}:{},...e.onConsumerRequestAcknowledged?{onRequestAcknowledged:e.onConsumerRequestAcknowledged}:{}}}),...void 0===e.attemptPorts?{resourceBindingContractRevision:RUNTIME_RESOURCE_BINDING_CONTRACT_REVISION}:{}}}catch{return{status:"unavailable",blockers:Object.freeze([TRANSPORT_BLOCKER])}}}async function probeGatewayGrantJwks(e){const t=grantAdapterOptions.get(e);if(!t)throw new Error("untrusted Gateway grant readiness adapter");const r=t.agentGatewayUrl.replace(/\/+$/,""),n=new GatewayGrantJwksVerifier(new RuntimeJwksVerifier(`${r}/.well-known/runtime-execution-grant-jwks.json`));return await n.refresh(!0),n}export function runtimeMessageAttemptPorts(e,t){const r=new MessageServiceConversationClearHttpAuthority({messageServiceUrl:t,fetchAuthorized:async(t,r)=>await e.messageService.fetch(t,r)});return{async resolve({request:n,command:a,executionGrant:i,getLease:s,journalRecord:o,abortSignal:c}){const u="skills.install"===a.name||"agent.applyTemplate"===a.name?a.params.artifact:void 0,d="mcp.set"===a.name?a.params.definition:void 0;if((u||d)&&(n.resourceBindingContractRevision!==RUNTIME_RESOURCE_BINDING_CONTRACT_REVISION||!n.resourceBindings))throw new RuntimeResourceResolutionError("resolution_rejected","resource-bound Service delivery requires the Types 4.1 binding carrier");const m=new HttpRuntimeOperationResourceResolver({gatewayUrl:e.agentGatewayUrl,operationId:n.operationId,requestMessageId:n.requestMessageId,instanceId:n.instanceId,paramsHash:n.paramsHash,bindings:n.resourceBindings??[],getAuthorization:()=>{const e=s();return{executionGrant:i,runtimeLeaseCredential:e.runtimeLeaseCredential,fence:deliveryFence(n,e)}},fetchAuthorized:async(t,r)=>await e.boundAgentFetch(t,r??{}),parseSkillArtifact:e=>parseAndValidateTemplatePackage(Buffer.from(e)),signal:c});if("prepared"!==o.phase&&"started"!==o.phase||(u&&await m.readVerifiedArtifact(u),d&&await m.resolveMcpDefinition(d)),"session.setModel"===a.name)return{resources:m,sessionModelProjection:{project:async({conversationId:r,modelOverrideId:a})=>{const i=s(),o=new MessageServiceSessionModelHttpAuthority({messageServiceUrl:t,fetchAuthorized:async(t,r)=>await e.messageService.fetchRuntimeChannel(t,{runtimeLeaseCredential:i.runtimeLeaseCredential,scopedDeliveryKey:e.scopedDeliveryKey},r)});return await o.project({conversationId:r,operationId:n.operationId,requestMessageId:n.requestMessageId,requestHash:n.requestHash,modelOverrideId:a,runtimeLeaseCredential:i.runtimeLeaseCredential})}}};if("session.clear"!==a.name)return{resources:m};const l=a.context.conversation,p=s();return{resources:m,historyBoundary:new MessageServiceConversationHistoryBoundary({operationId:n.operationId,requestMessageId:n.requestMessageId,expectedGeneration:await r.currentGeneration(l.runtimeConversationUid),fence:deliveryFence(n,p),authority:r})}}}}function runtimeMethods(){return[...intersectRuntimeServiceMethodsWithBackendCapabilities(RUNTIME_PARITY_MANIFEST.filter(e=>"ready"===e.status).map(e=>e.method))]}function contractArtifactRequirement(){try{return runtimeServiceContractRequirement()}catch{return CONTRACT_ARTIFACT_BLOCKER.requiredContract}}function deliveryFence(e,t){if(t.handlerIdentity!==e.runtimeHandlerIdentity||t.runtimeEpoch!==e.dispatchEpoch)throw new Error("runtime delivery fence does not match the retained request");return{claimId:e.requestMessageId,handlerIdentity:t.handlerIdentity,runtimeEpoch:t.runtimeEpoch,fencingToken:t.runtimeEpoch,journalStoreId:t.handlerIdentity,journalGeneration:t.runtimeEpoch}}
1
+ import{RUNTIME_RESOURCE_BINDING_CONTRACT_REVISION}from"@beeos-ai/beeos-types/runtime";import{parseAndValidateTemplatePackage}from"../acp-gateway/agent-template-package.js";import{HttpRuntimeOperationResourceResolver,RuntimeResourceResolutionError}from"./runtime-operation-resource-resolver.js";import{MessageServiceRuntimeMessageChannel}from"./message-service-runtime-message-channel.js";import{MessageServiceConversationClearHttpAuthority}from"./message-service-conversation-clear-http-authority.js";import{MessageServiceConversationHistoryBoundary}from"./message-service-conversation-history-boundary.js";import{MessageServiceSessionModelHttpAuthority}from"./message-service-session-model-http-authority.js";import{MsRuntimeMessageChannelConsumerFactory}from"./ms-runtime-message-channel-consumer-factory.js";import{RuntimeJwksVerifier}from"./runtime-jwks-verifier.js";import{GatewayGrantJwksVerifier}from"./split-runtime-authorization-verifier.js";import{RUNTIME_MESSAGE_CHANNEL_REVISION,RUNTIME_PARITY_MANIFEST}from"./runtime-parity-manifest.js";import{intersectRuntimeServiceMethodsWithBackendCapabilities,loadRuntimeServiceContractIdentity,runtimeServiceContractRequirement}from"./runtime-service-contract-compatibility.js";const CONTRACT_ARTIFACT_BLOCKER=Object.freeze({id:"contract_artifact_mismatch",owner:"backend",requiredContract:"frozen Types manifest and Service wire artifacts"}),TRANSPORT_BLOCKER=Object.freeze({id:"message_channel_transport",owner:"backend",requiredContract:`${RUNTIME_MESSAGE_CHANNEL_REVISION} HTTP delivery/history/append authority`}),JWKS_BLOCKER=Object.freeze({id:"gateway_grant_jwks",owner:"backend",requiredContract:"Purpose-bound Gateway runtime execution-grant JWKS proxy"}),POISON_JOURNAL_BLOCKER=Object.freeze({id:"poison_journal",owner:"openclaw_runtime_client",requiredContract:"Durable bounded runtime poison-delivery journal"}),grantAdapterOptions=new WeakMap;export class AgentGatewayGrantJwksReadinessAdapter{constructor(e){grantAdapterOptions.set(this,{agentGatewayUrl:new URL(e.agentGatewayUrl).toString()})}}export class AgentGatewaySplitJwksReadinessAdapter extends AgentGatewayGrantJwksReadinessAdapter{}const transportOptions=new WeakMap;export class RuntimeServiceTransportReadinessAdapter{constructor(e){transportOptions.set(this,{messageService:e.messageService,scopedDeliveryKey:e.scopedDeliveryKey,agentGatewayUrl:new URL(e.agentGatewayUrl).toString(),boundAgentFetch:e.boundAgentFetch})}}const CAPABILITY_BLOCKERS=Object.freeze(RUNTIME_PARITY_MANIFEST.filter(e=>"blocked"===e.status).map(e=>Object.freeze({method:e.method,owner:e.blockerOwner,requiredContract:e.contractRevision})));export async function createRuntimeServiceProductionCandidate(e){try{loadRuntimeServiceContractIdentity()}catch{return{status:"unavailable",blockers:Object.freeze([{...CONTRACT_ARTIFACT_BLOCKER,requiredContract:contractArtifactRequirement()}])}}if(!e.poisonJournal)return{status:"unavailable",blockers:Object.freeze([POISON_JOURNAL_BLOCKER])};let t;if(e.authorizationAdapter)try{t=await probeGatewayGrantJwks(e.authorizationAdapter)}catch{}const r=e.transportAdapter?transportOptions.get(e.transportAdapter):void 0;if(!r)return{status:"unavailable",blockers:Object.freeze([TRANSPORT_BLOCKER,...t?[]:[JWKS_BLOCKER]])};if(!t)return{status:"unavailable",blockers:Object.freeze([JWKS_BLOCKER])};try{const n=await r.messageService.ready(),a=new MessageServiceRuntimeMessageChannel({serviceUrl:n.serviceUrl,transport:r.messageService,scopedDeliveryKey:r.scopedDeliveryKey}),i=runtimeMethods(),s=e.attemptPorts??runtimeMessageAttemptPorts(r,n.serviceUrl);return{status:"ready",blockers:[],capabilityBlockers:CAPABILITY_BLOCKERS,serviceMethods:i,factory:new MsRuntimeMessageChannelConsumerFactory({channel:a,verifier:t,ports:s,journal:e.commandJournal,allowedMethods:new Set(i),options:{poisonJournal:e.poisonJournal,...e.onConsumerDeliveryError?{onDeliveryError:e.onConsumerDeliveryError}:{},...e.onConsumerRequestTerminalAccepted?{onRequestTerminalAccepted:e.onConsumerRequestTerminalAccepted}:{},...e.onConsumerRequestAcknowledged?{onRequestAcknowledged:e.onConsumerRequestAcknowledged}:{}}}),...void 0===e.attemptPorts?{resourceBindingContractRevision:RUNTIME_RESOURCE_BINDING_CONTRACT_REVISION}:{}}}catch{return{status:"unavailable",blockers:Object.freeze([TRANSPORT_BLOCKER])}}}async function probeGatewayGrantJwks(e){const t=grantAdapterOptions.get(e);if(!t)throw new Error("untrusted Gateway grant readiness adapter");const r=t.agentGatewayUrl.replace(/\/+$/,""),n=new GatewayGrantJwksVerifier(new RuntimeJwksVerifier(`${r}/.well-known/runtime-execution-grant-jwks.json`));return await n.refresh(!0),n}export function runtimeMessageAttemptPorts(e,t){const r=new MessageServiceConversationClearHttpAuthority({messageServiceUrl:t,fetchAuthorized:async(t,r)=>await e.messageService.fetch(t,r)});return{async resolve({request:n,command:a,executionGrant:i,getLease:s,journalStoreId:o,journalGeneration:c,journalRecord:u,abortSignal:d}){const m="skills.install"===a.name||"agent.applyTemplate"===a.name?a.params.artifact:void 0,l="mcp.set"===a.name?a.params.definition:void 0;if((m||l)&&(n.resourceBindingContractRevision!==RUNTIME_RESOURCE_BINDING_CONTRACT_REVISION||!n.resourceBindings))throw new RuntimeResourceResolutionError("resolution_rejected","resource-bound Service delivery requires the Types 4.1 binding carrier");const p=new HttpRuntimeOperationResourceResolver({gatewayUrl:e.agentGatewayUrl,operationId:n.operationId,requestMessageId:n.requestMessageId,instanceId:n.instanceId,paramsHash:n.paramsHash,bindings:n.resourceBindings??[],getAuthorization:()=>{const e=s();return{executionGrant:i,runtimeLeaseCredential:e.runtimeLeaseCredential,fence:deliveryFence(n,e,o,c)}},fetchAuthorized:async(t,r)=>await e.boundAgentFetch(t,r??{}),parseSkillArtifact:e=>parseAndValidateTemplatePackage(Buffer.from(e)),signal:d});if("prepared"!==u.phase&&"started"!==u.phase||(m&&await p.readVerifiedArtifact(m),l&&await p.resolveMcpDefinition(l)),"session.setModel"===a.name)return{resources:p,sessionModelProjection:{project:async({conversationId:r,modelOverrideId:a})=>{const i=s(),o=new MessageServiceSessionModelHttpAuthority({messageServiceUrl:t,fetchAuthorized:async(t,r)=>await e.messageService.fetchRuntimeChannel(t,{runtimeLeaseCredential:i.runtimeLeaseCredential,scopedDeliveryKey:e.scopedDeliveryKey},r)});return await o.project({conversationId:r,operationId:n.operationId,requestMessageId:n.requestMessageId,requestHash:n.requestHash,modelOverrideId:a,runtimeLeaseCredential:i.runtimeLeaseCredential})}}};if("session.clear"!==a.name)return{resources:p};const R=a.context.conversation,y=s();return{resources:p,historyBoundary:new MessageServiceConversationHistoryBoundary({operationId:n.operationId,requestMessageId:n.requestMessageId,expectedGeneration:await r.currentGeneration(R.runtimeConversationUid),fence:deliveryFence(n,y,o,c),authority:r})}}}}function runtimeMethods(){return[...intersectRuntimeServiceMethodsWithBackendCapabilities(RUNTIME_PARITY_MANIFEST.filter(e=>"ready"===e.status).map(e=>e.method))]}function contractArtifactRequirement(){try{return runtimeServiceContractRequirement()}catch{return CONTRACT_ARTIFACT_BLOCKER.requiredContract}}function deliveryFence(e,t,r,n){if(t.handlerIdentity!==e.runtimeHandlerIdentity||t.runtimeEpoch!==e.dispatchEpoch)throw new Error("runtime delivery fence does not match the retained request");return{claimId:e.requestMessageId,handlerIdentity:t.handlerIdentity,runtimeEpoch:t.runtimeEpoch,fencingToken:t.runtimeEpoch,journalStoreId:r,journalGeneration:n}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "beeos-claw",
3
- "version": "0.5.97",
3
+ "version": "0.5.98",
4
4
  "description": "OpenClaw plugin that bridges the BeeOS platform with the local OpenClaw Gateway, providing file transfer, ACP bridge, and observability.",
5
5
  "license": "MIT",
6
6
  "author": "BeeOS <dev@beeos.ai>",