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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/a2a/tools.js +1 -1
  2. package/dist/acp-gateway/beeos-file-resolver.js +1 -1
  3. package/dist/acp-gateway/bridge-core.js +1 -1
  4. package/dist/acp-gateway/gateway-events.js +1 -1
  5. package/dist/acp-server.js +1 -1
  6. package/dist/agent-sync.js +1 -1
  7. package/dist/automation/tools.js +1 -0
  8. package/dist/automation/turn-policy.js +1 -0
  9. package/dist/automation/wake.js +1 -0
  10. package/dist/canvas/relay-client.js +1 -1
  11. package/dist/canvas/ws-provider.js +1 -1
  12. package/dist/canvas-orchestrator.js +1 -1
  13. package/dist/chat-envelope.js +1 -0
  14. package/dist/connectors/managed-connector-tools.js +1 -0
  15. package/dist/files/fetch-tool.js +1 -1
  16. package/dist/files/list-tool.js +1 -1
  17. package/dist/im-inbound-handler.js +1 -1
  18. package/dist/im-runtime-dispatch.js +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/mcp-connector-proxy.js +1 -1
  21. package/dist/media/arouter-config.js +1 -1
  22. package/dist/media/image-provider.js +1 -1
  23. package/dist/media/video-provider.js +1 -1
  24. package/dist/message-client-composition.js +1 -1
  25. package/dist/runtime/agent-projection-production.js +1 -1
  26. package/dist/runtime/callback-queue.js +1 -1
  27. package/dist/runtime/chat-handler-port.js +1 -0
  28. package/dist/runtime/conversation-title.js +1 -1
  29. package/dist/runtime/core-execution-attempt-context.js +1 -1
  30. package/dist/runtime/im-reply-sink.js +1 -1
  31. package/dist/runtime/message-service-conversation-clear-http-authority.js +1 -1
  32. package/dist/runtime/message-service-conversation-history-boundary.js +1 -1
  33. package/dist/runtime/message-service-conversation-run-boundary.js +1 -1
  34. package/dist/runtime/message-service-cron-delivery-http-authority.js +1 -1
  35. package/dist/runtime/message-service-runtime-authenticated-fetch.js +1 -1
  36. package/dist/runtime/message-service-runtime-claim-authority.js +1 -1
  37. package/dist/runtime/message-service-runtime-message-channel.js +1 -1
  38. package/dist/runtime/message-service-session-model-http-authority.js +1 -1
  39. package/dist/runtime/ms-runtime-message-channel-adapter.js +1 -1
  40. package/dist/runtime/ms-runtime-message-channel-consumer-factory.js +1 -1
  41. package/dist/runtime/ms-runtime-rpc-adapter.js +1 -1
  42. package/dist/runtime/native-cloud-chat-composition.js +1 -0
  43. package/dist/runtime/native-cloud-prompt-bridge.js +1 -0
  44. package/dist/runtime/native-input-files-http.js +1 -0
  45. package/dist/runtime/native-input-files.js +1 -0
  46. package/dist/runtime/native-output-file-attempt.js +1 -0
  47. package/dist/runtime/native-prompt-authority.js +1 -0
  48. package/dist/runtime/native-prompt-preflight.js +1 -0
  49. package/dist/runtime/native-session-new-bridge.js +1 -0
  50. package/dist/runtime/openclaw-session-model.js +1 -0
  51. package/dist/runtime/reply-router.js +1 -1
  52. package/dist/runtime/runtime-error-part.js +1 -0
  53. package/dist/runtime/runtime-local-parity-matrix.js +1 -1
  54. package/dist/runtime/runtime-message-channel-contract.js +1 -1
  55. package/dist/runtime/runtime-operation-resource-resolver.js +1 -1
  56. package/dist/runtime/runtime-parity-manifest-digest.js +1 -1
  57. package/dist/runtime/runtime-parity-manifest.js +1 -1
  58. package/dist/runtime/runtime-production-authority.js +1 -1
  59. package/dist/runtime/runtime-registration-identity-store.js +1 -1
  60. package/dist/runtime/runtime-service-contract-compatibility.js +1 -1
  61. package/dist/runtime/runtime-service-production-candidate.js +1 -1
  62. package/dist/runtime/runtime-session-control-service.js +1 -1
  63. package/dist/runtime/runtime-skills-service.js +1 -1
  64. package/dist/runtime/service-runtime-attempt-ports-resolver.js +1 -1
  65. package/dist/runtime/session-new-runtime-delivery-bridge.js +1 -1
  66. package/dist/runtime/write-runtime-failure.js +1 -1
  67. package/dist/terminal/runtime-terminal-outbound-registration.js +1 -1
  68. package/dist/terminal/terminal-lease-bound-bridge-client.js +1 -1
  69. package/dist/upload/desktop-screenshot-tool.js +1 -1
  70. package/dist/upload/finalize-hook.js +1 -1
  71. package/dist/upload/tool-artifact-enrichment.js +1 -1
  72. package/dist/upload/tool.js +1 -1
  73. package/dist/upload/upload-file.js +1 -1
  74. package/openclaw.plugin.json +20 -2
  75. package/package.json +5 -4
  76. package/runtime-service-wire-identity.v1.json +5 -5
  77. package/dist/agent-auth.js +0 -1
  78. package/dist/bridge-discovery.js +0 -1
  79. package/dist/runtime/agent-gateway-runtime-attempt-authorization.js +0 -1
  80. package/dist/runtime/message-service-runtime-invocation-authority.js +0 -1
  81. package/dist/runtime/runtime-jwks-verifier.js +0 -1
  82. package/dist/runtime/runtime-registration.js +0 -1
  83. package/dist/runtime/runtime-transport-failure-policy.js +0 -1
  84. package/dist/runtime/split-runtime-authorization-verifier.js +0 -1
@@ -1 +1 @@
1
- import{randomUUID}from"node:crypto";import{performance}from"node:perf_hooks";import{RuntimeCommandError}from"./runtime-command-dispatcher.js";import{ClearConversationUseCase}from"./conversation-clear-use-case.js";import{AROUTER_PROVIDER_ID}from"../media/arouter-config.js";import{openClawSessionKeysFromList}from"./openclaw-session-key-resolution.js";async function modelSwitchTimingSpan(e,t,i){const s=performance.now();let n="succeeded";try{return await i()}catch(e){throw n="failed",e}finally{e&&process.stderr.write(`[MODEL_SWITCH_TIMING] component=runtime operationId=${e} stage=${t} outcome=${n} durationMs=${(performance.now()-s).toFixed(1)}\n`)}}export class RuntimeSessionControlService{clearRuntime;fallback;activeRuns;constructor(e,t,i){this.clearRuntime=e,this.fallback=t,this.activeRuns=i}async execute(e,t,i){const s=e;if("session.clear"===s.name){if(!i.historyBoundary)throw new RuntimeCommandError("INVALID_PARAMS",`${i.origin} clear attempt lacks its history boundary`);const e=s.context.conversation;return await new ClearConversationUseCase(i.historyBoundary,this.clearRuntime).execute({operationId:s.context.operationId,conversationId:e.runtimeConversationUid,runtimeSessionKey:e.runtimeSessionKey,runtimeEpoch:s.context.dispatchEpoch})}if("session.cancel"===s.name){if(!this.activeRuns)throw new RuntimeCommandError("INVALID_PARAMS","session.cancel active-run authority is not configured");const e=s;return await this.activeRuns.cancelExact({runtimeConversationUid:e.context.conversation.runtimeConversationUid,runtimeSessionKey:e.context.conversation.runtimeSessionKey,historyGeneration:e.context.historyGeneration,targetMessageId:e.params.targetMessageId}),{}}if(!this.fallback)throw new Error(`session command delegate is not configured: ${s.name}`);return await this.fallback.execute(s,t,i)}async projectCommitted(e,t,i){return await(this.fallback?.projectCommitted?.(e,t,i))}}export class OpenClawSessionMetadataService{metadata;constructor(e){this.metadata="function"==typeof e?new OpenClawGatewaySessionMetadataPort(e):e}async execute(e,t,i){const s=e,n=s.context.conversation.runtimeSessionKey,o={lease:t,attempt:i};switch(s.name){case"session.load":return await this.metadata.load(n,o);case"session.rename":{const e=s.params.title.slice(0,64);return await this.metadata.rename(n,e,o)}case"session.delete":return await this.metadata.delete(n,o);case"session.setMode":{const e=s.params.mode;return await this.metadata.setMode(n,e,o)}case"session.setModel":{const e=s.params.modelOverrideId;if(null!==e&&("string"!=typeof e||0===e.length||e.trim()!==e))throw new RuntimeCommandError("INVALID_PARAMS","modelOverrideId must be a non-empty string or null");const t=null===e?await modelSwitchTimingSpan(i.operationId,"resolve_agent_default_model",async()=>await this.metadata.resolveAgentDefaultModel(n,o)):void 0;if(null===e&&!t)throw new RuntimeCommandError("AGENT_DEFAULT_MODEL_NOT_CONFIGURED","agent default model is not configured");return await modelSwitchTimingSpan(i.operationId,"metadata_set_model",async()=>await this.metadata.setModel(n,e,t??void 0,o))}}throw new RuntimeCommandError("INVALID_PARAMS","unsupported session metadata command")}async projectCommitted(e,t,i){if("session.setModel"!==e.name)return;const s=e,n=t;if(this.metadata.projectCommittedSetModel&&await this.metadata.projectCommittedSetModel(s.context.conversation.runtimeSessionKey,n),"service"===i?.origin){if(!i.sessionModelProjection)throw new Error("Message Service session model projection is unavailable");return Object.freeze({state:"pending",revision:"0"})}if(!this.metadata.projectCommittedSetModel)throw new Error("session metadata projection is unavailable")}}export class OpenClawGatewaySessionMetadataPort{getGateway;projectModel;liveSessionKeys;constructor(e,t,i){this.getGateway=e,this.projectModel=t,this.liveSessionKeys=i}async load(e,t){const i=await this.requireExistingOpenClawKey(e,t);return await this.gateway().request("sessions.resolve",{sessionKey:i}),{loaded:!0}}async rename(e,t,i){const s=await this.requireExistingOpenClawStoreKey(e,i);return await this.gateway().request("sessions.patch",{key:s,label:t}),{title:t}}async delete(e,t){const i=await this.requireExistingOpenClawStoreKey(e,t);return await this.gateway().request("sessions.delete",{key:i}),{deleted:!0}}async setMode(e,t,i){const s="verbose"===t||"detailed"===t?{verboseLevel:"full"}:"reasoning"===t||"thinking"===t?{reasoningLevel:"stream"}:"concise"===t||"default"===t?{verboseLevel:"default"}:null;if(!s)throw new RuntimeCommandError("INVALID_PARAMS",`unsupported session mode: ${t}`);const n=await this.requireExistingOpenClawStoreKey(e,i);if(!isAuthoritativeSetModeAck(await this.gateway().request("sessions.patch",{key:n,...s}),n,s))throw new RuntimeCommandError("OUTCOME_UNKNOWN","sessions.patch did not acknowledge the exact target and effective mode");return{mode:t}}async resolveAgentDefaultModel(e,t){const i=runtimeAgentId(this.liveSessionKeys?(await this.resolveSetModelKey(e,t)).key:await this.requireExistingOpenClawKey(e,t)),s=await this.gateway().request("agents.list",{}),n=s?.agents?.find(e=>e.id===i),o=n?.defaultModel??n?.model;if("string"!=typeof o||!o.trim()||o.trim()!==o)return null;const r=toPlatformModelId(o),a=r.indexOf("/");return{modelId:r,...a>0?{modelProvider:r.slice(0,a)}:{}}}async setModel(e,t,i,s){const n=null===t?null:toOpenClawSessionModel(t),o=s?.attempt.operationId;let r=await modelSwitchTimingSpan(o,"resolve_set_model_key",async()=>await this.resolveSetModelKey(e,s));const a=async()=>await modelSwitchTimingSpan(o,"openclaw_sessions_patch",async()=>await this.gateway().request("sessions.patch",{key:r.key,model:n,mustExist:!r.materialized}));let l;try{l=await a()}catch(t){if(r.materialized||!isMissingOpenClawStoreSession(t,r.key))throw t;r=await modelSwitchTimingSpan(o,"materialize_set_model_key",async()=>await this.materializeSetModelKey(e,r.key,s)),l=await a()}const{key:c,materialized:d}=r;if(!isAuthoritativeSetModelAck(l,c,n,t))throw new RuntimeCommandError("OUTCOME_UNKNOWN","sessions.patch did not acknowledge the exact existing session and effective model");const m=l.resolved.model,u=toPlatformModelId(m);if(null===t&&(!i||u!==i.modelId))throw new RuntimeCommandError("OUTCOME_UNKNOWN","sessions.patch effective model does not match the prevalidated agent default");if(null!==t&&u!==t&&m!==n)throw new RuntimeCommandError("OUTCOME_UNKNOWN","sessions.patch effective model does not match the requested override");if(d){const e=await modelSwitchTimingSpan(o,"openclaw_sessions_list_post_materialize",async()=>await this.gateway().request("sessions.list",{includeDerivedTitles:!0}));if(!openClawSessionKeysFromList(e).has(c))throw new RuntimeCommandError("OUTCOME_UNKNOWN","sessions.patch acknowledged a model-intent session that is absent from the authoritative store");if(!this.liveSessionKeys?.registerMaterializedModelKey)throw new RuntimeCommandError("OUTCOME_UNKNOWN","model-intent session registration authority is unavailable");this.liveSessionKeys.registerMaterializedModelKey(c)}return{...null===t?{}:{modelOverrideId:t},effectiveModelId:u,...l.resolved?.modelProvider?{modelProvider:l.resolved.modelProvider}:{}}}async projectCommittedSetModel(e,t){if(!this.projectModel)throw new Error("session metadata projection is unavailable");const i=await this.requireExistingOpenClawKey(e);await this.projectModel(i,t)}async requireExistingOpenClawKey(e,t){if(await(this.liveSessionKeys?.waitForHydration?.()),!this.liveSessionKeys)return e;try{return this.liveSessionKeys.resolveLiveKey(e)}catch(i){if(!t||!isMissingLiveSession(i)||!this.liveSessionKeys.reconcileMissingLiveKey)throw i;return await this.liveSessionKeys.reconcileMissingLiveKey(e,t),this.liveSessionKeys.resolveLiveKey(e)}}async requireExistingOpenClawStoreKey(e,t){const i=await this.requireExistingOpenClawKey(e,t),s=await this.gateway().request("sessions.list",{includeDerivedTitles:!0});if(!openClawSessionKeysFromList(s).has(i))throw new RuntimeCommandError("INVALID_PARAMS",`OpenClaw session key does not exist (refusing sessions.patch upsert): ${i}`);return i}async resolveSetModelKey(e,t){let i;const s="service"===t?.attempt.origin&&void 0!==t.attempt.verifiedMessageGrant;try{i=await this.requireExistingOpenClawKey(e,t)}catch(e){if(!(s&&t&&isMissingLiveSession(e)&&this.liveSessionKeys?.materializeMissingModelKey&&this.liveSessionKeys.registerMaterializedModelKey))throw e}return i?{key:i,materialized:!1}:await this.materializeSetModelKey(e,void 0,t)}async materializeSetModelKey(e,t,i){if(!("service"===i?.attempt.origin&&void 0!==i.attempt.verifiedMessageGrant&&i&&this.liveSessionKeys?.materializeMissingModelKey&&this.liveSessionKeys.registerMaterializedModelKey)){throw new RuntimeCommandError("INVALID_PARAMS",`OpenClaw session key does not exist (refusing sessions.patch upsert): ${t??e}`)}const s=await this.liveSessionKeys.materializeMissingModelKey(e,i);if(t&&s!==t)throw new RuntimeCommandError("INVALID_PARAMS","verified model-intent key conflicts with the live local session");return{key:s,materialized:!0}}gateway(){const e=this.getGateway();if(!e?.isConnected)throw new RuntimeCommandError("GATEWAY_NOT_CONNECTED","Gateway not connected");return e}}function isMissingLiveSession(e){return e instanceof RuntimeCommandError&&"INVALID_PARAMS"===e.code&&e.message.startsWith("no live local session")}function isMissingOpenClawStoreSession(e,t){return e instanceof Error&&e.message===`No session found: ${t}`}function runtimeAgentId(e){const t=e.split(":");return"agent"===t[0]&&t[1]?.trim()?t[1]:"main"}function toOpenClawSessionModel(e){return e.startsWith(`${AROUTER_PROVIDER_ID}/`)?e:`${AROUTER_PROVIDER_ID}/${e}`}function toPlatformModelId(e){const t=`${AROUTER_PROVIDER_ID}/`;return e.startsWith(t)?e.slice(t.length):e}function isAuthoritativeSetModeAck(e,t,i){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const s=e;if(!0!==s.ok||s.key!==t||!s.entry||"object"!=typeof s.entry||Array.isArray(s.entry))return!1;const n=s.entry;return"verboseLevel"in i?n.verboseLevel===i.verboseLevel:n.reasoningLevel===i.reasoningLevel}function isAuthoritativeSetModelAck(e,t,i,s){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const n=e;if("ok"in n&&!0!==n.ok)return!1;if("key"in n&&n.key!==t)return!1;const o=n.resolved;if(!o||"object"!=typeof o||Array.isArray(o))return!1;const r=o.model;return"string"==typeof r&&0!==r.length&&r.trim()===r&&(null!==s||null===i)}export class LocalConversationHistoryBoundary{onCommit;kind="local";intents=new Map;convergence=new Map;generations=new Map;constructor(e){this.onCommit=e}currentGeneration(e){return String(this.generations.get(e)??0n)}async prepare(e){const t=this.intents.get(e.operationId);if(t)return t;const i=(new Date).toISOString(),s=this.generations.get(e.conversationId)??0n,n={intentId:randomUUID(),operationId:e.operationId,conversationId:e.conversationId,state:"prepared",runtimeEpoch:e.runtimeEpoch,fromGeneration:String(s),toGeneration:String(s+1n),boundaryOffset:"0",version:"1",createdAt:i,updatedAt:i};return this.intents.set(e.operationId,n),n}async markResetting(e,t){return this.assertState(e,"prepared"),this.convergence.set(e.operationId,t),this.transition(e,"resetting")}async loadRunConvergence(e){const t=this.convergence.get(e.operationId);if(!t)throw new Error("local clear convergence receipt missing");return t}async markResetDone(e){return this.assertState(e,"resetting"),this.transition(e,"reset_done")}async commit(e){return this.assertState(e,"reset_done"),await(this.onCommit?.(e.conversationId)),this.generations.set(e.conversationId,BigInt(e.toGeneration)),this.transition(e,"committed")}async abortPrepared(e){this.assertState(e,"prepared"),this.transition(e,"aborted")}transition(e,t){const i={...e,state:t,version:String(BigInt(e.version)+1n),updatedAt:(new Date).toISOString()};return this.intents.set(e.operationId,i),i}assertState(e,t){const i=this.intents.get(e.operationId);if(!i||i.version!==e.version||i.state!==t)throw new Error(`local clear transition fenced: expected ${t}`)}}
1
+ import{randomUUID}from"node:crypto";import{performance}from"node:perf_hooks";import{RuntimeCommandError}from"./runtime-command-dispatcher.js";import{ClearConversationUseCase}from"./conversation-clear-use-case.js";import{createSessionModelRefs}from"./openclaw-session-model.js";import{openClawSessionKeysFromList}from"./openclaw-session-key-resolution.js";async function modelSwitchTimingSpan(e,t,i){const s=performance.now();let n="succeeded";try{return await i()}catch(e){throw n="failed",e}finally{e&&process.stderr.write(`[MODEL_SWITCH_TIMING] component=runtime operationId=${e} stage=${t} outcome=${n} durationMs=${(performance.now()-s).toFixed(1)}\n`)}}export class RuntimeSessionControlService{clearRuntime;fallback;activeRuns;constructor(e,t,i){this.clearRuntime=e,this.fallback=t,this.activeRuns=i}async execute(e,t,i){const s=e;if("session.clear"===s.name){if(!i.historyBoundary)throw new RuntimeCommandError("INVALID_PARAMS",`${i.origin} clear attempt lacks its history boundary`);const e=s.context.conversation;return await new ClearConversationUseCase(i.historyBoundary,this.clearRuntime).execute({operationId:s.context.operationId,conversationId:e.runtimeConversationUid,runtimeSessionKey:e.runtimeSessionKey,runtimeEpoch:s.context.dispatchEpoch})}if("session.cancel"===s.name){if(!this.activeRuns)throw new RuntimeCommandError("INVALID_PARAMS","session.cancel active-run authority is not configured");const e=s;return await this.activeRuns.cancelExact({runtimeConversationUid:e.context.conversation.runtimeConversationUid,runtimeSessionKey:e.context.conversation.runtimeSessionKey,historyGeneration:e.context.historyGeneration,targetMessageId:e.params.targetMessageId}),{}}if(!this.fallback)throw new Error(`session command delegate is not configured: ${s.name}`);return await this.fallback.execute(s,t,i)}async projectCommitted(e,t,i){return await(this.fallback?.projectCommitted?.(e,t,i))}}export class OpenClawSessionMetadataService{metadata;constructor(e){this.metadata="function"==typeof e?new OpenClawGatewaySessionMetadataPort(e):e}async execute(e,t,i){const s=e,n=s.context.conversation.runtimeSessionKey,o={lease:t,attempt:i};switch(s.name){case"session.load":return await this.metadata.load(n,o);case"session.rename":{const e=s.params.title.slice(0,64);return await this.metadata.rename(n,e,o)}case"session.delete":return await this.metadata.delete(n,o);case"session.setMode":{const e=s.params.mode;return await this.metadata.setMode(n,e,o)}case"session.setModel":{const e=s.params.modelOverrideId;if(null!==e&&("string"!=typeof e||0===e.length||e.trim()!==e))throw new RuntimeCommandError("INVALID_PARAMS","modelOverrideId must be a non-empty string or null");const t=null===e?await modelSwitchTimingSpan(i.operationId,"resolve_agent_default_model",async()=>await this.metadata.resolveAgentDefaultModel(n,o)):void 0;if(null===e&&!t)throw new RuntimeCommandError("AGENT_DEFAULT_MODEL_NOT_CONFIGURED","agent default model is not configured");return await modelSwitchTimingSpan(i.operationId,"metadata_set_model",async()=>await this.metadata.setModel(n,e,t??void 0,o))}}throw new RuntimeCommandError("INVALID_PARAMS","unsupported session metadata command")}async projectCommitted(e,t,i){if("session.setModel"!==e.name)return;const s=e,n=t;if(this.metadata.projectCommittedSetModel&&await this.metadata.projectCommittedSetModel(s.context.conversation.runtimeSessionKey,n),"service"===i?.origin){if(!i.sessionModelProjection)throw new Error("Message Service session model projection is unavailable");return Object.freeze({state:"pending",revision:"0"})}if(!this.metadata.projectCommittedSetModel)throw new Error("session metadata projection is unavailable")}}export class OpenClawGatewaySessionMetadataPort{getGateway;projectModel;liveSessionKeys;modelMutations;constructor(e,t,i,s){this.getGateway=e,this.projectModel=t,this.liveSessionKeys=i,this.modelMutations=s}modelRefs(){return createSessionModelRefs()}async load(e,t){const i=await this.requireExistingOpenClawKey(e,t);return await this.gateway().request("sessions.resolve",{sessionKey:i}),{loaded:!0}}async rename(e,t,i){const s=await this.requireExistingOpenClawStoreKey(e,i);return await this.gateway().request("sessions.patch",{key:s,label:t}),{title:t}}async delete(e,t){const i=await this.requireExistingOpenClawStoreKey(e,t);return await this.gateway().request("sessions.delete",{key:i}),{deleted:!0}}async setMode(e,t,i){const s=openClawSessionModePatch(t),n=await this.requireExistingOpenClawStoreKey(e,i);if(!isAuthoritativeSetModeAck(await this.gateway().request("sessions.patch",{key:n,...s}),n,s))throw new RuntimeCommandError("OUTCOME_UNKNOWN","sessions.patch did not acknowledge the exact target and effective mode");return{mode:t}}async resolveAgentDefaultModel(e,t){const i=runtimeAgentId(this.liveSessionKeys?(await this.resolveSetModelKey(e,t)).key:await this.requireExistingOpenClawKey(e,t)),s=await this.gateway().request("agents.list",{}),n=s?.agents?.find(e=>e.id===i),o=n?.defaultModel??n?.model;if("string"!=typeof o||!o.trim()||o.trim()!==o)return null;const a=this.modelRefs().toPlatform(o),r=a.indexOf("/");return{modelId:a,...r>0?{modelProvider:a.slice(0,r)}:{}}}async setModel(e,t,i,s){const n=null===t?null:this.modelRefs().toOpenClaw(t),o=s?.attempt.operationId;let a=await modelSwitchTimingSpan(o,"resolve_set_model_key",async()=>await this.resolveSetModelKey(e,s));const r=await(this.modelMutations?.acquireInternal({sessionKey:a.key,label:"session model mutation"}));try{if(r){const t=await this.resolveSetModelKey(e,s);if(t.key!==r.sessionKey)throw new RuntimeCommandError("OUTCOME_UNKNOWN","model target changed while waiting for its physical session gate");a=t}const l=async()=>await modelSwitchTimingSpan(o,"openclaw_sessions_patch",async()=>await this.gateway().request("sessions.patch",{key:a.key,model:n,mustExist:!a.materialized}));let d;try{d=await l()}catch(t){if(a.materialized||!isMissingOpenClawStoreSession(t,a.key))throw t;a=await modelSwitchTimingSpan(o,"materialize_set_model_key",async()=>await this.materializeSetModelKey(e,a.key,s)),d=await l()}const{key:c,materialized:m}=a,u=resolveModelPatch(d,c,t,this.modelRefs()),h=u.effectiveModelId;if(null===t&&(!i||h!==i.modelId))throw new RuntimeCommandError("OUTCOME_UNKNOWN","sessions.patch effective model does not match the prevalidated agent default");if(m){const e=await modelSwitchTimingSpan(o,"openclaw_sessions_list_post_materialize",async()=>await this.gateway().request("sessions.list",{includeDerivedTitles:!0}));if(!openClawSessionKeysFromList(e).has(c))throw new RuntimeCommandError("OUTCOME_UNKNOWN","sessions.patch acknowledged a model-intent session that is absent from the authoritative store");if(!this.liveSessionKeys?.registerMaterializedModelKey)throw new RuntimeCommandError("OUTCOME_UNKNOWN","model-intent session registration authority is unavailable");this.liveSessionKeys.registerMaterializedModelKey(c)}return u}finally{this.modelMutations?.releaseBeforeRuntime(r)}}async prepareNativeModel(e,t,i,s){await i();const n=void 0===t?null:this.modelRefs().toOpenClaw(t),o=void 0===s?void 0:openClawSessionModePatch(s),a=await this.gateway().request("sessions.patch",{key:e,model:n,...o});await i();const r=a;if(!0!==r?.ok||r.key!==e)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native model patch did not acknowledge the exact qualified session");if(o&&!isAuthoritativeSetModeAck(a,e,o))throw new RuntimeCommandError("OUTCOME_UNKNOWN","sessions.patch did not acknowledge the exact target and effective mode");return resolveModelPatch(a,e,t??null,this.modelRefs())}async projectCommittedSetModel(e,t){if(!this.projectModel)throw new Error("session metadata projection is unavailable");const i=await this.requireExistingOpenClawKey(e);await this.projectModel(i,t)}async requireExistingOpenClawKey(e,t){if(await(this.liveSessionKeys?.waitForHydration?.()),!this.liveSessionKeys)return e;try{return this.liveSessionKeys.resolveLiveKey(e)}catch(i){if(!t||!isMissingLiveSession(i)||!this.liveSessionKeys.reconcileMissingLiveKey)throw i;return await this.liveSessionKeys.reconcileMissingLiveKey(e,t),this.liveSessionKeys.resolveLiveKey(e)}}async requireExistingOpenClawStoreKey(e,t){const i=await this.requireExistingOpenClawKey(e,t),s=await this.gateway().request("sessions.list",{includeDerivedTitles:!0});if(!openClawSessionKeysFromList(s).has(i))throw new RuntimeCommandError("INVALID_PARAMS",`OpenClaw session key does not exist (refusing sessions.patch upsert): ${i}`);return i}async resolveSetModelKey(e,t){let i;const s="service"===t?.attempt.origin&&void 0!==t.attempt.verifiedMessageGrant;try{i=await this.requireExistingOpenClawKey(e,t)}catch(e){if(!(s&&t&&isMissingLiveSession(e)&&this.liveSessionKeys?.materializeMissingModelKey&&this.liveSessionKeys.registerMaterializedModelKey))throw e}return i?{key:i,materialized:!1}:await this.materializeSetModelKey(e,void 0,t)}async materializeSetModelKey(e,t,i){if(!("service"===i?.attempt.origin&&void 0!==i.attempt.verifiedMessageGrant&&i&&this.liveSessionKeys?.materializeMissingModelKey&&this.liveSessionKeys.registerMaterializedModelKey)){throw new RuntimeCommandError("INVALID_PARAMS",`OpenClaw session key does not exist (refusing sessions.patch upsert): ${t??e}`)}const s=await this.liveSessionKeys.materializeMissingModelKey(e,i);if(t&&s!==t)throw new RuntimeCommandError("INVALID_PARAMS","verified model-intent key conflicts with the live local session");return{key:s,materialized:!0}}gateway(){const e=this.getGateway();if(!e?.isConnected)throw new RuntimeCommandError("GATEWAY_NOT_CONNECTED","Gateway not connected");return e}}function isMissingLiveSession(e){return e instanceof RuntimeCommandError&&"INVALID_PARAMS"===e.code&&e.message.startsWith("no live local session")}function isMissingOpenClawStoreSession(e,t){return e instanceof Error&&e.message===`No session found: ${t}`}function resolveModelPatch(e,t,i,s){const n=null===i?null:s.toOpenClaw(i);if(!isAuthoritativeSetModelAck(e,t,n,i))throw new RuntimeCommandError("OUTCOME_UNKNOWN","sessions.patch did not acknowledge the exact existing session and effective model");const o=e.resolved.model,a=s.toPlatform(o);if(null!==i&&a!==i&&o!==n)throw new RuntimeCommandError("OUTCOME_UNKNOWN","sessions.patch effective model does not match the requested override");return{...null===i?{}:{modelOverrideId:i},effectiveModelId:a,...e.resolved.modelProvider?{modelProvider:e.resolved.modelProvider}:{}}}function runtimeAgentId(e){const t=e.split(":");return"agent"===t[0]&&t[1]?.trim()?t[1]:"main"}export function openClawSessionModePatch(e){const t="verbose"===e||"detailed"===e?{verboseLevel:"full"}:"reasoning"===e||"thinking"===e?{reasoningLevel:"stream"}:"concise"===e||"default"===e?{verboseLevel:"default"}:null;if(!t)throw new RuntimeCommandError("INVALID_PARAMS",`unsupported session mode: ${e}`);return t}function isAuthoritativeSetModeAck(e,t,i){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const s=e;if(!0!==s.ok||s.key!==t||!s.entry||"object"!=typeof s.entry||Array.isArray(s.entry))return!1;const n=s.entry;return"verboseLevel"in i?n.verboseLevel===i.verboseLevel:n.reasoningLevel===i.reasoningLevel}function isAuthoritativeSetModelAck(e,t,i,s){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const n=e;if("ok"in n&&!0!==n.ok)return!1;if("key"in n&&n.key!==t)return!1;const o=n.resolved;if(!o||"object"!=typeof o||Array.isArray(o))return!1;const a=o.model;return"string"==typeof a&&0!==a.length&&a.trim()===a&&(null!==s||null===i)}export class LocalConversationHistoryBoundary{onCommit;kind="local";intents=new Map;convergence=new Map;generations=new Map;constructor(e){this.onCommit=e}currentGeneration(e){return String(this.generations.get(e)??0n)}async prepare(e){const t=this.intents.get(e.operationId);if(t)return t;const i=(new Date).toISOString(),s=this.generations.get(e.conversationId)??0n,n={intentId:randomUUID(),operationId:e.operationId,conversationId:e.conversationId,state:"prepared",runtimeEpoch:e.runtimeEpoch,fromGeneration:String(s),toGeneration:String(s+1n),boundaryOffset:"0",version:"1",createdAt:i,updatedAt:i};return this.intents.set(e.operationId,n),n}async markResetting(e,t){return this.assertState(e,"prepared"),this.convergence.set(e.operationId,t),this.transition(e,"resetting")}async loadRunConvergence(e){const t=this.convergence.get(e.operationId);if(!t)throw new Error("local clear convergence receipt missing");return t}async markResetDone(e){return this.assertState(e,"resetting"),this.transition(e,"reset_done")}async commit(e){return this.assertState(e,"reset_done"),await(this.onCommit?.(e.conversationId)),this.generations.set(e.conversationId,BigInt(e.toGeneration)),this.transition(e,"committed")}async abortPrepared(e){this.assertState(e,"prepared"),this.transition(e,"aborted")}transition(e,t){const i={...e,state:t,version:String(BigInt(e.version)+1n),updatedAt:(new Date).toISOString()};return this.intents.set(e.operationId,i),i}assertState(e,t){const i=this.intents.get(e.operationId);if(!i||i.version!==e.version||i.state!==t)throw new Error(`local clear transition fenced: expected ${t}`)}}
@@ -1 +1 @@
1
- import{access,mkdir,rename,rm,writeFile}from"node:fs/promises";import{homedir}from"node:os";import{dirname,join,resolve,sep}from"node:path";import{RuntimeCommandError}from"./runtime-command-dispatcher.js";export class RuntimeSkillsService{deps;constructor(e){this.deps=e}async execute(e,t,i){const a=e,r=this.requireGateway(),s=a.context.agent.runtimeLocalKey;if("skills.list"===a.name){const e=await r.request("skills.status",{agentId:s});return{skills:normalizeSkills(e?.skills)}}if("skills.setEnabled"===a.name){const e=a;return await r.request("skills.update",{skillKey:e.params.skillKey,enabled:e.params.enabled,agentId:s}),{skillKey:e.params.skillKey,enabled:e.params.enabled}}const n=await this.skillsRoot(r,s);if("skills.uninstall"===a.name){const e=validateSkillKey(a.params.skillKey);return await rm(contained(n,e),{recursive:!0,force:!0}),{removed:!0}}const o=a,l=await i.resources.readVerifiedArtifact(o.params.artifact),c=validateSkillKey(l.manifest?.slug??""),m=contained(n,c),d=contained(n,`.${c}.${o.context.operationId}.tmp`),u=contained(n,`.${c}.${o.context.operationId}.backup`);!await exists(m)&&await exists(u)&&await rename(u,m),await rm(d,{recursive:!0,force:!0}),await mkdir(d,{recursive:!0});try{for(const[e,t]of l.workspaceFiles){const i=contained(d,normalizeArtifactPath(e));await mkdir(dirname(i),{recursive:!0}),await writeFile(i,t,{mode:384})}await rm(u,{recursive:!0,force:!0}),await exists(m)&&await rename(m,u),await rename(d,m),await rm(u,{recursive:!0,force:!0})}catch(e){throw await rm(d,{recursive:!0,force:!0}).catch(()=>{}),!await exists(m)&&await exists(u)&&await rename(u,m).catch(()=>{}),e}return{installed:!0}}requireGateway(){const e=this.deps.getGateway();if(!e?.isConnected)throw new RuntimeCommandError("GATEWAY_NOT_CONNECTED","Gateway not connected");return e}async skillsRoot(e,t){const i=this.deps.getOpenclawHome?.()??process.env.OPENCLAW_HOME??join(homedir(),".openclaw");if("main"===t)return join(i,"skills");const a=await e.request("agents.list",{}),r=a?.agents?.find(e=>e.id===t)?.workspace;return join(r||join(i,`workspace-${t}`),"skills")}}async function exists(e){try{return await access(e),!0}catch{return!1}}function validateSkillKey(e){if(!/^[a-z0-9][a-z0-9_-]{0,63}$/i.test(e))throw new RuntimeCommandError("INVALID_PARAMS","invalid skill key");return e}function normalizeArtifactPath(e){const t=e.replaceAll("\\","/").replace(/^\.\//,"");if(!t||t.startsWith("/")||t.split("/").includes(".."))throw new RuntimeCommandError("INVALID_PARAMS",`invalid skill artifact path: ${e}`);return t}function contained(e,t){const i=resolve(e),a=resolve(i,t);if(a!==i&&!a.startsWith(`${i}${sep}`))throw new RuntimeCommandError("INVALID_PARAMS","skill path escapes workspace");return a}function normalizeSkills(e){return(e??[]).flatMap(e=>{if(!e||"object"!=typeof e)return[];const t=e,i="string"==typeof t.skillKey?t.skillKey:"string"==typeof t.name?t.name:"";return i?[{skillKey:i,slug:"string"==typeof t.slug?t.slug:i,name:"string"==typeof t.name?t.name:i,description:"string"==typeof t.description?t.description:"",enabled:!0!==t.disabled,..."string"==typeof t.emoji?{emoji:t.emoji}:{},..."boolean"==typeof t.bundled?{bundled:t.bundled}:{}}]:[]})}
1
+ import{access,mkdir,rename,rm,writeFile}from"node:fs/promises";import{homedir}from"node:os";import{basename,dirname,join,resolve,sep}from"node:path";import{RuntimeCommandError}from"./runtime-command-dispatcher.js";export class RuntimeSkillsService{deps;constructor(e){this.deps=e}async execute(e,t,i){const a=e,r=this.requireGateway(),s=a.context.agent.runtimeLocalKey;if("skills.list"===a.name){const e=await r.request("skills.status",{agentId:s});return{skills:normalizeSkills(e?.skills)}}if("skills.setEnabled"===a.name){const e=a;return await r.request("skills.update",{skillKey:e.params.skillKey,enabled:e.params.enabled,agentId:s}),{skillKey:e.params.skillKey,enabled:e.params.enabled}}const n=await this.skillsRoot(r,s);if("skills.uninstall"===a.name){const e=validateSkillKey(a.params.skillKey);return await rm(contained(n,e),{recursive:!0,force:!0}),{removed:!0}}const o=a,l=await i.resources.readVerifiedArtifact(o.params.artifact),c=l.manifest?.slug??"";if(!c)throw new RuntimeCommandError("INVALID_PARAMS","skill package declares no manifest slug (manifest.json with schema_version 1 and slug is required)");const m=contained(n,validateSkillKey(c)),d=dirname(m),u=contained(d,`.${basename(m)}.${o.context.operationId}.tmp`),p=contained(d,`.${basename(m)}.${o.context.operationId}.backup`);await mkdir(d,{recursive:!0}),!await exists(m)&&await exists(p)&&await rename(p,m),await rm(u,{recursive:!0,force:!0}),await mkdir(u,{recursive:!0});try{for(const[e,t]of l.workspaceFiles){const i=contained(u,normalizeArtifactPath(e));await mkdir(dirname(i),{recursive:!0}),await writeFile(i,t,{mode:384})}await rm(p,{recursive:!0,force:!0}),await exists(m)&&await rename(m,p),await rename(u,m),await rm(p,{recursive:!0,force:!0})}catch(e){throw await rm(u,{recursive:!0,force:!0}).catch(()=>{}),!await exists(m)&&await exists(p)&&await rename(p,m).catch(()=>{}),new RuntimeCommandError("EXECUTION_FAILED",`skill install write failed (files=${l.workspaceFiles.size}): ${e instanceof Error?e.message:String(e)}`,void 0,{cause:e})}return{installed:!0}}requireGateway(){const e=this.deps.getGateway();if(!e?.isConnected)throw new RuntimeCommandError("GATEWAY_NOT_CONNECTED","Gateway not connected");return e}async skillsRoot(e,t){const i=this.deps.getOpenclawHome?.()??process.env.OPENCLAW_HOME??join(homedir(),".openclaw");if("main"===t)return join(i,"skills");const a=await e.request("agents.list",{}),r=a?.agents?.find(e=>e.id===t)?.workspace;return join(r||join(i,`workspace-${t}`),"skills")}}async function exists(e){try{return await access(e),!0}catch{return!1}}function validateSkillKey(e){if(!/^(?:@?[A-Za-z0-9][A-Za-z0-9._-]{0,63}\/)?[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e))throw new RuntimeCommandError("INVALID_PARAMS","invalid skill key");return e}function normalizeArtifactPath(e){const t=e.replaceAll("\\","/").replace(/^\.\//,"");if(!t||t.startsWith("/")||t.split("/").includes(".."))throw new RuntimeCommandError("INVALID_PARAMS",`invalid skill artifact path: ${e}`);return t}function contained(e,t){const i=resolve(e),a=resolve(i,t);if(a!==i&&!a.startsWith(`${i}${sep}`))throw new RuntimeCommandError("INVALID_PARAMS","skill path escapes workspace");return a}function normalizeSkills(e){return(e??[]).flatMap(e=>{if(!e||"object"!=typeof e)return[];const t=e,i="string"==typeof t.skillKey?t.skillKey:"string"==typeof t.name?t.name:"";return i?[{skillKey:i,slug:"string"==typeof t.slug?t.slug:i,name:"string"==typeof t.name?t.name:i,description:"string"==typeof t.description?t.description:"",enabled:!0!==t.disabled,..."string"==typeof t.emoji?{emoji:t.emoji}:{},..."boolean"==typeof t.bundled?{bundled:t.bundled}:{}}]:[]})}
@@ -1 +1 @@
1
- import{MessageServiceConversationHistoryBoundary}from"./message-service-conversation-history-boundary.js";export class ServiceRuntimeAttemptPortsResolver{deps;constructor(e){this.deps=e}async resolve(e,r){const s=await this.deps.resources(e,r);if("session.prompt"===e.attempt.command.name){if(!this.deps.run)throw new Error("Service session.prompt run boundary is unavailable");return{resources:s,conversationRunBoundary:await this.deps.run(e)}}if("session.clear"!==e.attempt.command.name)return{resources:s};const t=await this.deps.clear(e);return{resources:s,historyBoundary:new MessageServiceConversationHistoryBoundary({operationId:e.operationId,requestMessageId:e.requestMessageId,expectedGeneration:t.expectedGeneration,fence:e.fence,authority:t.authority,...t.resolveActiveRunRegistrationId?{resolveActiveRunRegistrationId:t.resolveActiveRunRegistrationId}:{}})}}}
1
+ import{MessageServiceConversationHistoryBoundary}from"./message-service-conversation-history-boundary.js";export class ServiceRuntimeAttemptPortsResolver{deps;constructor(e){this.deps=e}async resolve(e,s){const r=await this.deps.resources(e,s);if("session.prompt"===e.attempt.command.name){if(!this.deps.run)throw new Error("Service session.prompt run boundary is unavailable");return{resources:r,conversationRunBoundary:await this.deps.run(e)}}if("session.clear"!==e.attempt.command.name)return{resources:r};const t=await this.deps.clear(e);return{resources:r,historyBoundary:new MessageServiceConversationHistoryBoundary({operationId:e.operationId,requestMessageId:e.requestMessageId,requestHash:t.requestHash??e.request.requestHash,...t.expectedGeneration?{expectedGeneration:t.expectedGeneration}:{},fence:e.fence,authority:t.authority,...t.resolveActiveRunRegistrationId?{resolveActiveRunRegistrationId:t.resolveActiveRunRegistrationId}:{}})}}}
@@ -1 +1 @@
1
- import{RUNTIME_ERROR_DESCRIPTORS,RUNTIME_HASH_DOMAINS}from"@beeos-ai/beeos-types/runtime";import{verifyAndCreateMessageServiceCoreExecutionAttempt}from"./core-execution-attempt-context.js";import{RuntimeSessionNewRejectedError}from"./runtime-rpc-consumer.js";import{RUNTIME_MESSAGE_TYPES,runtimeMessageHash}from"./runtime-message-channel-contract.js";const SESSION_NEW_METHOD="session/new",SESSION_NEW_COMMAND="session.create";export class SessionNewRuntimeDeliveryBridge{options;workers=new Map;constructor(e){this.options=e}async acceptDelivery(e,t,s){this.currentLease(t);const r=record(e.message.payload),n=string(r?.operationId)??e.message.channel_id,o=this.workers.get(n);if(o)return await o;const i=this.handleDelivery(e,t,s).finally(()=>this.workers.delete(n));this.workers.set(n,i),await i}async handleDelivery(e,t,s){const r=parseSessionNewRequest(e);if(!r.ok)return void await this.options.poison(e,`invalid_session_new:${r.reason}`,t);const n=r.request,o=this.options.consumer(),i=async()=>{this.currentLease(t),await o.acknowledge([e.deliveryId])},a=await o.history(n.operationId);if("found"!==a.status)return void await i();const d=parseSessionNewHistory(a.snapshot);if(!d.ok||d.request.operationId!==n.operationId||d.request.requestMessageId!==n.requestMessageId||d.request.requestHash!==n.requestHash)return void await this.options.poison(e,"session_new_history_mismatch",t);const c=d.request;if(d.terminal)return void await i();if(c.instanceId!==t.instanceId||c.runtimeHandlerIdentity!==t.handlerIdentity||c.dispatchEpoch!==t.runtimeEpoch)return await this.appendFailure(c,t,"INSTANCE_EPOCH_MISMATCH"),void await i();const u=Date.now();if("deadline"===d.terminalSource||Date.parse(c.executionDeadlineAt)<=u||!d.started&&Date.parse(c.claimDeadlineAt)<=u)return await this.appendFailure(c,t,"COMMAND_EXPIRED"),void await i();if(d.cancelRequested&&!d.started)return await this.appendFailure(c,t,"OPERATION_CANCELLED"),void await i();const p=e.executionGrant;if(!p)return await this.appendFailure(c,t,d.started?"OUTCOME_UNKNOWN":"INVALID_EXECUTION_GRANT"),void await i();await this.options.verifier.refresh(),this.options.verifier.verifyAndDecodeGrant(p)||await this.options.verifier.refresh(!0);const h=new AbortController,l=()=>h.abort();s.addEventListener("abort",l,{once:!0});try{const e=await verifyAndCreateMessageServiceCoreExecutionAttempt({request:c,executionGrant:p,runtimeEpoch:t.runtimeEpoch,lease:t,verifier:this.options.verifier,allowExpiredGrant:d.started,abortSignal:h.signal,resolvePorts:async()=>({resources:noSessionNewResources})});if(!e.ok)return await this.appendFailure(c,t,d.started?"OUTCOME_UNKNOWN":"INVALID_EXECUTION_GRANT"),void await i();if(s.aborted)throw new Error("session/new delivery owner stopped");d.started?this.currentLease(t):await this.append(c,t,RUNTIME_MESSAGE_TYPES.started,{...correlation(c),executionGrantHash:c.executionGrantHash,handlerIdentity:t.handlerIdentity,executionMode:"start",claimedAt:(new Date).toISOString()},p);const r=c.request.params.agentId;let n;try{n=await this.options.createRuntimeSession({operationId:c.operationId,platformAgentId:r,...optionalStringProperty(c.request.params,"cwd"),...optionalStringProperty(c.command.params,"title")},e.context)}catch(e){if(!(e instanceof RuntimeSessionNewRejectedError))throw e;return await this.appendFailure(c,t,"INVALID_INVOCATION"),void await i()}const o=c.instanceId,a=r.startsWith("agent:")?r:`agent:${r}`;let u;try{u=await this.options.client.conversations.create({agentId:r,participants:dedupe([o,a,c.callerIdentityId]),...optionalStringProperty(c.command.params,"title"),metadata:{source:"session/new",runtimeSessionId:n.sessionId,runtimeSessionKey:n.gatewaySessionKey,runtimeInstanceId:c.instanceId,runtimeEpoch:c.dispatchEpoch,platformAgentId:r},idempotencyKey:c.operationId})}catch(e){const s=httpStatus(e);if(void 0===s||s>=500||408===s||429===s)throw e;return await this.appendFailure(c,t,"INVALID_INVOCATION"),void await i()}const l={sessionId:n.sessionId,conversationId:u.id},I=runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:"session/new",result:l});await this.append(c,t,RUNTIME_MESSAGE_TYPES.final,{...correlation(c),outcome:"succeeded",response:{jsonrpc:"2.0",id:c.request.id,result:l},serviceResultHash:I,completedAt:(new Date).toISOString()}),await i()}finally{h.abort(),s.removeEventListener("abort",l)}}async appendFailure(e,t,s){const r="COMMAND_EXPIRED"===s?"expired":"OPERATION_CANCELLED"===s?"cancelled":"OUTCOME_UNKNOWN"===s||"INSTANCE_EPOCH_MISMATCH"===s?"outcome_unknown":"failed",n="outcome_unknown"===r?"OUTCOME_UNKNOWN":s,o=RUNTIME_ERROR_DESCRIPTORS[n];await this.append(e,t,RUNTIME_MESSAGE_TYPES.final,{...correlation(e),outcome:r,response:{jsonrpc:"2.0",id:e.request.id,error:{code:o.jsonRpcCode,message:n,data:{code:n,operationId:e.operationId,effectState:r,retryMode:o.retryMode}}},completedAt:(new Date).toISOString()})}async append(e,t,s,r,n){this.currentLease(t);const o=this.options.consumer(),i=await o.append(e.operationId,s,r,n);if("created"===i.outcome||"duplicate"===i.outcome)return;let a=i.history;if(void 0===a){const t=await o.history(e.operationId);"found"===t.status&&(a=t.snapshot)}if(!hasCorrelatedMessage(a,s,e))throw new Error(`session/new ${s} append outcome is unknown`)}currentLease(e){const t=this.options.getLease();if(!t||t.instanceId!==e.instanceId||t.leaseId!==e.leaseId||t.runtimeEpoch!==e.runtimeEpoch||t.handlerIdentity!==e.handlerIdentity)throw new Error("session/new runtime delivery lease fence changed");if(!Number.isFinite(Date.parse(t.leaseExpiresAt))||Date.parse(t.leaseExpiresAt)<=Date.now())throw new Error("session/new runtime delivery lease expired");return t}}export function isCanonicalSessionNewDelivery(e){return"session/new"===record(e.message.payload)?.method}function parseSessionNewRequest(e){const t=e.message,s=record(t.payload),r=record(s?.request),n=record(r?.params),o=record(s?.command),i=record(o?.context),a=void 0===o?.params?void 0:record(o.params),d=[s?.operationId,s?.requestMessageId,s?.requestHash,s?.executionGrantHash,s?.instanceId,s?.runtimeHandlerIdentity,s?.dispatchEpoch,s?.callerIdentityId,s?.claimDeadlineAt,s?.executionDeadlineAt];return 1===s?.schemaVersion&&"session/new"===s?.method&&d.every(nonempty)&&"2.0"===r?.jsonrpc&&"session/new"===r.method&&("string"==typeof r.id||"number"==typeof r.id)&&n&&nonempty(n.agentId)&&"session.create"===o?.name&&i&&"instance"===i.scope&&i.operationId===s.operationId&&i.runtimeInstanceUid===s.instanceId&&i.dispatchEpoch===s.dispatchEpoch&&(void 0===o.params||a)&&t.type===RUNTIME_MESSAGE_TYPES.request&&t.channel_id===s.operationId&&t.message_id===s.requestMessageId&&Number.isFinite(Date.parse(s.claimDeadlineAt))&&Number.isFinite(Date.parse(s.executionDeadlineAt))?{ok:!0,request:s}:{ok:!1,reason:"required session/new fields do not correlate"}}function parseSessionNewHistory(e){const t=record(e),s=parseSessionNewRequest({deliveryId:"retained",redelivered:!0,idleMs:0,message:record(t?.request)});if(!s.ok||t?.operationId!==s.request.operationId||t.requestMessageId!==s.request.requestMessageId||t.requestHash!==s.request.requestHash)return{ok:!1};const r=record(t.started),n=record(r?.payload),o=void 0!==r&&n?.operationId===s.request.operationId&&n.requestMessageId===s.request.requestMessageId&&n.requestHash===s.request.requestHash&&n.dispatchEpoch===s.request.dispatchEpoch&&"session/new"===n.method;return{ok:!0,request:s.request,terminal:!0===t.terminal,terminalSource:string(t.terminalSource)??"none",cancelRequested:!0===t.cancelRequested,started:o}}function correlation(e){return{schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,requestHash:e.requestHash,dispatchEpoch:e.dispatchEpoch,method:"session/new"}}function hasCorrelatedMessage(e,t,s){const r=record(e);return(Array.isArray(r?.messages)?r.messages:[]).some(e=>{const r=record(e),n=record(r?.payload);return r?.type===t&&n?.operationId===s.operationId&&n.requestMessageId===s.requestMessageId&&n.requestHash===s.requestHash&&n.dispatchEpoch===s.dispatchEpoch&&"session/new"===n.method})}function optionalStringProperty(e,t){const s=e?.[t];return"string"==typeof s&&s.length>0?{[t]:s}:{}}function dedupe(e){return[...new Set(e.filter(e=>e.length>0))]}function httpStatus(e){const t=record(e),s=t?.status;return"number"==typeof s?s:void 0}function record(e){return null===e||"object"!=typeof e||Array.isArray(e)?void 0:e}function string(e){return"string"==typeof e&&e.length>0?e:void 0}function nonempty(e){return"string"==typeof e&&e.length>0}const noSessionNewResources=Object.freeze({async readContent(){throw new Error("session/new does not accept content resources")},async readVerifiedArtifact(){throw new Error("session/new does not accept artifact resources")}});
1
+ import{RUNTIME_ERROR_DESCRIPTORS,RUNTIME_HASH_DOMAINS,isCloudRuntimeMessageRequest}from"@beeos-ai/beeos-types/runtime";import{verifyAndCreateMessageServiceCoreExecutionAttempt}from"./core-execution-attempt-context.js";import{RuntimeSessionNewRejectedError}from"./runtime-rpc-consumer.js";import{RUNTIME_MESSAGE_TYPES,runtimeMessageHash}from"./runtime-message-channel-contract.js";const SESSION_NEW_METHOD="session/new",SESSION_NEW_COMMAND="session.create";export class SessionNewRuntimeDeliveryBridge{options;workers=new Map;constructor(e){this.options=e}async acceptDelivery(e,t,s){this.currentLease(t);const r=record(e.message.payload),n=string(r?.operationId)??e.message.channel_id,o=this.workers.get(n);if(o)return await o;const i=this.handleDelivery(e,t,s).finally(()=>this.workers.delete(n));this.workers.set(n,i),await i}async handleDelivery(e,t,s){const r=parseSessionNewRequest(e);if(!r.ok)return void await this.options.poison(e,`invalid_session_new:${r.reason}`,t);const n=r.request,o=this.options.consumer(),i=async()=>{this.currentLease(t),await o.acknowledge([e.deliveryId])},a=await o.history(n.operationId);if("found"!==a.status)return void await i();const d=parseSessionNewHistory(a.snapshot);if(!d.ok||d.request.operationId!==n.operationId||d.request.requestMessageId!==n.requestMessageId||d.request.requestHash!==n.requestHash)return void await this.options.poison(e,"session_new_history_mismatch",t);const c=d.request;if(d.terminal)return void await i();if(c.instanceId!==t.instanceId||c.runtimeHandlerIdentity!==t.handlerIdentity||c.dispatchEpoch!==t.runtimeEpoch)return await this.appendFailure(c,t,"INSTANCE_EPOCH_MISMATCH"),void await i();const u=Date.now();if("deadline"===d.terminalSource||Date.parse(c.executionDeadlineAt)<=u||!d.started&&Date.parse(c.claimDeadlineAt)<=u)return await this.appendFailure(c,t,"COMMAND_EXPIRED"),void await i();if(d.cancelRequested&&!d.started)return await this.appendFailure(c,t,"OPERATION_CANCELLED"),void await i();const p=e.executionGrant;if(!p)return await this.appendFailure(c,t,d.started?"OUTCOME_UNKNOWN":"INVALID_EXECUTION_GRANT"),void await i();await this.options.verifier.refresh(),this.options.verifier.verifyAndDecodeGrant(p)||await this.options.verifier.refresh(!0);const l=new AbortController,h=()=>l.abort();s.addEventListener("abort",h,{once:!0});try{const e=await verifyAndCreateMessageServiceCoreExecutionAttempt({request:c,executionGrant:p,runtimeEpoch:t.runtimeEpoch,lease:t,verifier:this.options.verifier,allowExpiredGrant:d.started,abortSignal:l.signal,resolvePorts:async()=>({resources:noSessionNewResources})});if(!e.ok)return await this.appendFailure(c,t,d.started?"OUTCOME_UNKNOWN":"INVALID_EXECUTION_GRANT"),void await i();if(s.aborted)throw new Error("session/new delivery owner stopped");d.started?this.currentLease(t):await this.append(c,t,RUNTIME_MESSAGE_TYPES.started,{...correlation(c),executionGrantHash:c.executionGrantHash,handlerIdentity:t.handlerIdentity,executionMode:"start",claimedAt:(new Date).toISOString()},p);const r=c.request.params.agentId;let n,o;try{n=await this.options.createRuntimeSession({operationId:c.operationId,platformAgentId:r,..."string"==typeof c.command.params?.runtimeWorkingDirectory?{cwd:c.command.params.runtimeWorkingDirectory}:{},...optionalStringProperty(c.command.params,"title")},e.context)}catch(e){if(!(e instanceof RuntimeSessionNewRejectedError))throw e;return await this.appendFailure(c,t,"INVALID_INVOCATION"),void await i()}try{o=await this.options.conversations.create({operationId:c.operationId,runtimeSessionId:n.sessionId,runtimeSessionKey:n.gatewaySessionKey,...optionalStringProperty(c.command.params,"title"),platformAgentId:r,runtimeInstanceId:c.instanceId,callerIdentityId:c.callerIdentityId,runtimeEpoch:c.dispatchEpoch})}catch(e){const s=httpStatus(e);if(void 0===s||s>=500||408===s||429===s)throw e;return await this.appendFailure(c,t,"INVALID_INVOCATION"),void await i()}const a={sessionId:n.sessionId,conversationId:o.conversationId},u=runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:"session/new",result:a});await this.append(c,t,RUNTIME_MESSAGE_TYPES.final,{...correlation(c),outcome:"succeeded",response:{jsonrpc:"2.0",id:c.request.id,result:a},serviceResultHash:u,completedAt:(new Date).toISOString()}),await i()}finally{l.abort(),s.removeEventListener("abort",h)}}async appendFailure(e,t,s){const r="COMMAND_EXPIRED"===s?"expired":"OPERATION_CANCELLED"===s?"cancelled":"OUTCOME_UNKNOWN"===s||"INSTANCE_EPOCH_MISMATCH"===s?"outcome_unknown":"failed",n="outcome_unknown"===r?"OUTCOME_UNKNOWN":s,o=RUNTIME_ERROR_DESCRIPTORS[n];await this.append(e,t,RUNTIME_MESSAGE_TYPES.final,{...correlation(e),outcome:r,response:{jsonrpc:"2.0",id:e.request.id,error:{code:o.jsonRpcCode,message:n,data:{code:n,operationId:e.operationId,effectState:r,retryMode:o.retryMode}}},completedAt:(new Date).toISOString()})}async append(e,t,s,r,n){this.currentLease(t);const o=this.options.consumer(),i=await o.append(e.operationId,s,r,n);if("created"===i.outcome||"duplicate"===i.outcome)return;let a=i.history;if(void 0===a){const t=await o.history(e.operationId);"found"===t.status&&(a=t.snapshot)}if(!hasCorrelatedMessage(a,s,e))throw new Error(`session/new ${s} append outcome is unknown`)}currentLease(e){const t=this.options.getLease();if(!t||t.instanceId!==e.instanceId||t.leaseId!==e.leaseId||t.runtimeEpoch!==e.runtimeEpoch||t.handlerIdentity!==e.handlerIdentity)throw new Error("session/new runtime delivery lease fence changed");if(!Number.isFinite(Date.parse(t.leaseExpiresAt))||Date.parse(t.leaseExpiresAt)<=Date.now())throw new Error("session/new runtime delivery lease expired");return t}}export function isCanonicalSessionNewDelivery(e){return"session/new"===record(e.message.payload)?.method}function parseSessionNewRequest(e){const t=e.message,s=record(t.payload),r=record(s?.request),n=record(r?.params),o=record(s?.command),i=record(o?.context),a=void 0===o?.params?void 0:record(o.params),d=s?.schemaVersion;if(2===d&&!isCloudRuntimeMessageRequest(s,runtimeMessageHash))return{ok:!1,reason:"invalid Cloud session/new request contract"};const c=[s?.operationId,s?.requestMessageId,s?.requestHash,s?.executionGrantHash,s?.instanceId,s?.runtimeHandlerIdentity,s?.dispatchEpoch,s?.claimDeadlineAt,s?.executionDeadlineAt];return!(1!==d&&2!==d||"session/new"!==s?.method||!c.every(nonempty)||1===d&&!nonempty(s.callerIdentityId)||"2.0"!==r?.jsonrpc||"session/new"!==r.method||"string"!=typeof r.id&&"number"!=typeof r.id)&&n&&nonempty(n.agentId)&&"session.create"===o?.name&&i&&"instance"===i.scope&&i.operationId===s.operationId&&i.runtimeInstanceUid===s.instanceId&&i.dispatchEpoch===s.dispatchEpoch&&(void 0===o.params||a)&&t.type===RUNTIME_MESSAGE_TYPES.request&&t.channel_id===s.operationId&&t.message_id===s.requestMessageId&&Number.isFinite(Date.parse(s.claimDeadlineAt))&&Number.isFinite(Date.parse(s.executionDeadlineAt))?{ok:!0,request:s}:{ok:!1,reason:"required session/new fields do not correlate"}}function parseSessionNewHistory(e){const t=record(e),s=parseSessionNewRequest({deliveryId:"retained",redelivered:!0,idleMs:0,message:record(t?.request)});if(!s.ok||t?.operationId!==s.request.operationId||t.requestMessageId!==s.request.requestMessageId||t.requestHash!==s.request.requestHash)return{ok:!1};const r=record(t.started),n=record(r?.payload),o=void 0!==r&&n?.operationId===s.request.operationId&&n.requestMessageId===s.request.requestMessageId&&n.requestHash===s.request.requestHash&&n.dispatchEpoch===s.request.dispatchEpoch&&"session/new"===n.method;return{ok:!0,request:s.request,terminal:!0===t.terminal,terminalSource:string(t.terminalSource)??"none",cancelRequested:!0===t.cancelRequested,started:o}}function correlation(e){return{schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,requestHash:e.requestHash,dispatchEpoch:e.dispatchEpoch,method:"session/new"}}function hasCorrelatedMessage(e,t,s){const r=record(e);return(Array.isArray(r?.messages)?r.messages:[]).some(e=>{const r=record(e),n=record(r?.payload);return r?.type===t&&n?.operationId===s.operationId&&n.requestMessageId===s.requestMessageId&&n.requestHash===s.requestHash&&n.dispatchEpoch===s.dispatchEpoch&&"session/new"===n.method})}function optionalStringProperty(e,t){const s=e?.[t];return"string"==typeof s&&s.length>0?{[t]:s}:{}}function httpStatus(e){const t=record(e),s=t?.status;return"number"==typeof s?s:void 0}function record(e){return null===e||"object"!=typeof e||Array.isArray(e)?void 0:e}function string(e){return"string"==typeof e&&e.length>0?e:void 0}function nonempty(e){return"string"==typeof e&&e.length>0}const noSessionNewResources=Object.freeze({async readContent(){throw new Error("session/new does not accept content resources")},async readVerifiedArtifact(){throw new Error("session/new does not accept artifact resources")}});
@@ -1 +1 @@
1
- import{toMessagePart}from"../message-client-types.js";import{createRuntimeErrorPart,parseRuntimeErrorPart}from"@beeos-ai/message-sdk/protocol";export async function writeRuntimeFailure(r,e){if(e.businessErrorCode){r.parts.some(r=>parseRuntimeErrorPart(r))||r.addPart(toMessagePart(createRuntimeErrorPart(e.businessErrorCode)))}r.setBody(e.body),await r.fail({stopReason:e.stopReason})}
1
+ import{toMessagePart}from"../message-client-types.js";import{createRuntimeErrorPart,parseRuntimeErrorPart}from"./runtime-error-part.js";export async function writeRuntimeFailure(r,e){if(e.businessErrorCode){r.parts.some(r=>parseRuntimeErrorPart(r))||r.addPart(toMessagePart(createRuntimeErrorPart(e.businessErrorCode)))}r.setBody(e.body),await r.fail({stopReason:e.stopReason})}
@@ -1 +1 @@
1
- import{TERMINAL_MAX_FRAME_BYTES,TERMINAL_SERVICE_PROTOCOL_VERSION}from"@beeos-ai/beeos-types/runtime";import{TerminalNotFoundError}from"./session-manager.js";import{getOrCreateRuntimeTerminalService}from"./runtime-terminal-service.js";import{TerminalAuthorityAdmission}from"./terminal-authority-admission.js";const DEFAULT_REPLAY_RETENTION_MS=3e5;export class RuntimeTerminalOutboundRegistration{options;service;authorityAdmission;serviceGeneration;rings=new Map;ringBytes=new Map;droppedThrough=new Map;pending=[];pendingBytes=0;activeSend;activeFlush;flushes=new Set;connected=!1;draining=!1;stopped=!1;eventGeneration=0;transportEpoch=0;drainPromise;closePromise;replayExpiryTimers=new Map;constructor(e){this.options=e,this.service=e.service??getOrCreateRuntimeTerminalService(e.manager),this.authorityAdmission=new TerminalAuthorityAdmission(e.authorityJournal,e.authorityClock),this.serviceGeneration=this.service.setOutbound(this);const t=this.eventGeneration;e.client.on("connected",()=>{this.acceptsEvent(t)&&(this.connected||(this.transportEpoch++,this.activeFlush=void 0,this.serviceGeneration??=this.service.setOutbound(this),this.connected=!0,this.publishAvailability(!0),this.kickFlush(),e.logger?.info?.("[terminal-service] outbound registration connected")))}),e.client.on("disconnected",()=>{this.acceptsEvent(t)&&this.invalidateConnection(!1)}),e.client.on("message",(...e)=>{if(!this.acceptsEvent(t))return;const i=this.serviceGeneration,n=this.transportEpoch;if(!i||!this.acceptsTransport(n,i))return;const r=e[0],s="string"==typeof r?r:Buffer.from(r).toString("utf8");this.handleWire(s,i,n)}),e.client.on("error",(...i)=>{this.acceptsEvent(t)&&e.logger?.warn?.("[terminal-service] outbound registration error",i[0])}),e.client.on("authorityLost",()=>{this.acceptsEvent(t)&&(this.invalidateConnection(!0),e.logger?.warn?.("[terminal-service] runtime lease lost; Service terminals fenced"))}),e.client.on("transportEpochChanged",()=>{this.acceptsEvent(t)&&(this.invalidateConnection(!0),e.logger?.info?.("[terminal-service] runtime lease rotated; prior Terminal epoch fenced"))})}async start(){if(this.stopped)throw new Error("terminal outbound registration is stopped");await this.options.client.connect()}isAvailable(){return this.connected&&!this.draining&&!this.stopped}send(e){if(this.stopped)return!1;const t=JSON.stringify(e),i=Buffer.byteLength(t);return this.remember(e,t,i),!this.connected||(this.enqueueWithOutputBackpressure({clientId:e.clientId,terminalId:e.terminalId,frame:e,wire:t,bytes:i}),this.kickFlush(),!0)}resume(e,t,i){const n=this.transportEpoch;if(!this.acceptsConnection(n))throw new Error("terminal outbound registration is disconnected");const r=BigInt(i),s=r<(this.droppedThrough.get(t)??0n),a=[];let o=-1n;for(const i of this.rings.get(t)??[]){if(i.frame.clientId!==e)throw new Error("terminal resume ownership mismatch");const n=BigInt(i.frame.sequence);if(n<=o)throw new Error("terminal replay sequence is not monotonic");o=n,n<=r||a.push({clientId:e,terminalId:t,frame:i.frame,wire:i.wire,bytes:i.bytes})}if(!this.acceptsConnection(n))throw new Error("terminal outbound registration epoch changed");for(const e of a)this.enqueueWithOutputBackpressure(e);return this.acknowledgeReplay(t,r),this.kickFlush(),{gap:s}}rebindResumeClient(e,t,i){if(e===t)return;const n=this.rings.get(i);if(n?.some(t=>t.frame.clientId!==e))throw new Error("terminal resume ownership mismatch");if(n){let e=0;const r=n.map(i=>{const n=Object.freeze({...i.frame,clientId:t}),r=JSON.stringify(n),s=Buffer.byteLength(r);return e+=s,{frame:n,wire:r,bytes:s}});this.rings.set(i,r),this.ringBytes.set(i,e)}for(let n=0;n<this.pending.length;n++){const r=this.pending[n];if(r.terminalId!==i||r.clientId!==e)continue;const s={...r.frame,clientId:t},a=JSON.stringify(s),o=Buffer.byteLength(a);this.pendingBytes+=o-r.bytes,this.pending[n]={clientId:t,terminalId:i,frame:s,wire:a,bytes:o}}if(this.activeSend?.item.terminalId===i&&this.activeSend.item.clientId===e){const e=this.activeSend.item,n={...e.frame,clientId:t},r=JSON.stringify(n),s=Buffer.byteLength(r);this.activeSend.counted&&(this.pendingBytes+=s-e.bytes),this.activeSend={item:{clientId:t,terminalId:i,frame:n,wire:r,bytes:s},counted:this.activeSend.counted}}}forgetTerminal(e,t){this.prepareForgetTerminal(e,t)()}prepareForgetTerminal(e,t){const i=this.rings.get(t),n=new Set(this.pending.filter(e=>e.terminalId===t)),r=this.activeSend?.item.terminalId===t&&this.activeSend.counted?this.activeSend:void 0;if(i?.some(t=>t.frame.clientId!==e)||[...n].some(t=>t.clientId!==e)||r&&r.item.clientId!==e)throw new Error("terminal forget ownership mismatch");const s=this.replayExpiryTimers.get(t);let a=!1;return()=>{if(a)return;a=!0,s&&this.replayExpiryTimers.get(t)===s&&(clearTimeout(s),this.replayExpiryTimers.delete(t)),i&&this.rings.get(t)===i&&(this.rings.delete(t),this.ringBytes.delete(t),this.droppedThrough.delete(t));let e=0;for(const t of this.pending)n.has(t)?this.pendingBytes-=t.bytes:this.pending[e++]=t;this.pending.length=e,r&&this.activeSend===r&&r.counted&&(r.counted=!1,this.pendingBytes-=r.item.bytes),this.pendingBytes=Math.max(0,this.pendingBytes)}}startTerminalReplayExpiry(e,t){if((this.rings.get(t)??[]).some(t=>t.frame.clientId!==e))throw new Error("terminal replay expiry ownership mismatch");this.scheduleReplayExpiry(e,t)}drain(e){return this.drainPromise??=this.drainOnce(e),this.drainPromise}async drainOnce(e){this.draining=!0,this.stopped=!0,this.eventGeneration++;const t=[...this.flushes];this.invalidateConnection(!0);const i=await waitBounded(this.options.manager.drain(e.timeoutMs,e.terminateAfterTimeout),e.timeoutMs,e.signal),n=i===interrupted?"terminated":i;return i!==interrupted&&"terminated"===n&&e.terminateAfterTimeout&&await waitBounded(this.options.manager.drain(Math.min(1e3,Math.max(50,e.timeoutMs)),!1),Math.min(1e3,Math.max(50,e.timeoutMs)),e.signal),await waitBounded(Promise.allSettled(t),e.timeoutMs,e.signal),await waitBounded(this.closeClientOnce(),e.timeoutMs,e.signal),this.clearReplayState(),n}acceptsEvent(e){return!this.stopped&&e===this.eventGeneration}async handleWire(e,t,i){if(!this.acceptsTransport(i,t))return;if(Buffer.byteLength(e)>TERMINAL_MAX_FRAME_BYTES)return void this.options.logger?.warn?.("[terminal-service] oversized client frame rejected");let n,r;try{n=JSON.parse(e)}catch{return void this.options.logger?.warn?.("[terminal-service] invalid client JSON")}try{r=await this.authorityAdmission.admit(n),await this.service.handleClientFrame(r.frame,t,r.admission)}catch(e){if(this.acceptsTransport(i,t)){r&&this.sendRejectedFrame(r.frame,e);const t=e instanceof Error?e.message:String(e);this.options.logger?.warn?.(`[terminal-service] client frame rejected: ${t}`,e)}}}sendRejectedFrame(e,t){const i=(t instanceof Error?t.message:String(t)).toLowerCase(),n=t instanceof TerminalNotFoundError||i.includes("not found")?"TERMINAL_NOT_FOUND":i.includes("quota")?"TERMINAL_QUOTA_EXCEEDED":i.includes("unauthorized")||i.includes("authority")?"UNAUTHORIZED_TARGET":"TERMINAL_IO_ERROR",r=this.options.manager.getSessionIncarnation(e.terminalId),s=r?this.options.manager.nextServerSequence(e.terminalId,r):1;this.send({protocolVersion:TERMINAL_SERVICE_PROTOCOL_VERSION,type:"terminal.error",clientId:e.clientId,terminalId:e.terminalId,sequence:String(s),code:n,message:n,recoverable:"TERMINAL_IO_ERROR"===n||"TERMINAL_QUOTA_EXCEEDED"===n}),r||this.startTerminalReplayExpiry(e.clientId,e.terminalId)}remember(e,t,i){const n=this.rings.get(e.terminalId)??[];n.push({frame:Object.freeze({...e}),wire:t,bytes:i});let r=(this.ringBytes.get(e.terminalId)??0)+i;const s=this.options.maxBufferedFramesPerTerminal??512,a=this.options.maxBufferedBytesPerTerminal??1048576;for(;n.length>s||r>a;){const t=n.shift();if(!t)break;r-=t.bytes,this.droppedThrough.set(e.terminalId,BigInt(t.frame.sequence))}this.rings.set(e.terminalId,n),this.ringBytes.set(e.terminalId,r),"terminal.exit"===e.type&&this.scheduleReplayExpiry(e.clientId,e.terminalId)}enqueueWithOutputBackpressure(e){const t=this.options.maxPendingSendBytes??1048576;if(this.pendingBytes+e.bytes<=t)return this.pending.push(e),void(this.pendingBytes+=e.bytes);if("terminal.output"===e.frame.type){if(this.hasPendingTruncation(e.terminalId))return;const i=this.toTruncationMarker(e);return this.compactPendingOutput(i.bytes,t),void(this.hasPendingTruncation(e.terminalId)||(this.pending.push(i),this.pendingBytes+=i.bytes))}this.compactPendingOutput(e.bytes,t),this.pending.push(e),this.pendingBytes+=e.bytes}compactPendingOutput(e,t){for(;this.pendingBytes+e>t;){const e=this.pending.findIndex(e=>"terminal.output"===e.frame.type&&!0!==e.frame.truncated);if(e<0)return;const t=this.pending[e];if(this.hasPendingTruncation(t.terminalId,t)){this.pending.splice(e,1),this.pendingBytes-=t.bytes;continue}const i=this.toTruncationMarker(t);this.pending[e]=i,this.pendingBytes+=i.bytes-t.bytes}}hasPendingTruncation(e,t){return this.activeSend?.item!==t&&this.activeSend?.item.terminalId===e&&"terminal.output"===this.activeSend.item.frame.type&&!0===this.activeSend.item.frame.truncated||this.pending.some(i=>i!==t&&i.terminalId===e&&"terminal.output"===i.frame.type&&!0===i.frame.truncated)}toTruncationMarker(e){if("terminal.output"!==e.frame.type)throw new Error("only terminal output can be truncated");const t={...e.frame,data:"",encoding:"base64",truncated:!0},i=JSON.stringify(t);return{...e,frame:t,wire:i,bytes:Buffer.byteLength(i)}}async flush(e){for(;this.acceptsConnection(e)&&this.pending.length>0;){const t=this.pending.shift(),i={item:t,counted:!0};this.activeSend=i;try{await this.options.client.send(t.wire)}catch{return void(this.transportEpoch===e&&this.invalidateConnection(!1))}if(!this.acceptsConnection(e))return;this.activeSend===i&&(i.counted&&(this.pendingBytes-=t.bytes),this.activeSend=void 0)}}kickFlush(){if(this.activeFlush||!this.connected||0===this.pending.length)return;const e=this.transportEpoch,t=this.flush(e).finally(()=>{this.flushes.delete(t),this.activeFlush?.promise===t&&(this.activeFlush=void 0,this.acceptsConnection(e)&&this.kickFlush())});this.activeFlush={epoch:e,promise:t},this.flushes.add(t)}acceptsConnection(e){return this.connected&&!this.stopped&&e===this.transportEpoch}acceptsTransport(e,t){return this.acceptsEvent(this.eventGeneration)&&this.acceptsConnection(e)&&this.serviceGeneration===t}invalidateConnection(e){const t=this.connected;if(this.transportEpoch++,this.connected=!1,t&&this.publishAvailability(!1),this.activeFlush=void 0,this.activeSend=void 0,this.flushes.clear(),this.pending.length=0,this.pendingBytes=0,!e)return;const i=this.serviceGeneration;i&&(this.service.fenceServiceSessions("runtime_lease_lost",i),this.service.clearOutbound(this,i),this.serviceGeneration===i&&(this.serviceGeneration=void 0)),this.clearReplayState()}publishAvailability(e){try{this.options.onAvailabilityChange?.(e)}catch{}}clearReplayState(){for(const e of this.replayExpiryTimers.values())clearTimeout(e);this.replayExpiryTimers.clear(),this.rings.clear(),this.ringBytes.clear(),this.droppedThrough.clear()}acknowledgeReplay(e,t){const i=this.rings.get(e);if(!i||0===i.length)return;let n=0,r=this.droppedThrough.get(e)??0n,s=0;for(;s<i.length;){const e=i[s],a=BigInt(e.frame.sequence);if(a>t)break;n+=e.bytes,a>r&&(r=a),s++}0!==s&&(i.splice(0,s),this.ringBytes.set(e,Math.max(0,(this.ringBytes.get(e)??0)-n)),this.droppedThrough.set(e,r))}scheduleReplayExpiry(e,t){this.clearReplayExpiry(t);const i=this.serviceGeneration;if(!i)return;const n=setTimeout(()=>{if(this.replayExpiryTimers.get(t)===n){this.replayExpiryTimers.delete(t);try{this.service.expireServiceTerminalReplay(e,t,i)}catch(e){this.options.logger?.warn?.("[terminal-service] replay expiry failed",e)}}},Math.max(0,this.options.replayRetentionMs??3e5));n.unref?.(),this.replayExpiryTimers.set(t,n)}clearReplayExpiry(e){const t=this.replayExpiryTimers.get(e);t&&clearTimeout(t),this.replayExpiryTimers.delete(e)}closeClientOnce(){return this.closePromise??=this.options.client.close(!0),this.closePromise}}const interrupted=Symbol("interrupted");async function waitBounded(e,t,i){return i?.aborted?(e.catch(()=>{}),interrupted):await new Promise((n,r)=>{let s=!1;const a=e=>{s||(s=!0,clearTimeout(c),i?.removeEventListener("abort",o),n(e))},o=()=>a(interrupted),c=setTimeout(()=>a(interrupted),Math.max(0,t));c.unref?.(),i?.addEventListener("abort",o,{once:!0}),e.then(e=>a(e),e=>{s||(s=!0,clearTimeout(c),i?.removeEventListener("abort",o),r(e))})})}
1
+ import{TERMINAL_MAX_FRAME_BYTES,TERMINAL_SERVICE_PROTOCOL_VERSION}from"@beeos-ai/beeos-types/runtime";import{TerminalNotFoundError}from"./session-manager.js";import{getOrCreateRuntimeTerminalService}from"./runtime-terminal-service.js";import{TerminalAuthorityAdmission}from"./terminal-authority-admission.js";const DEFAULT_REPLAY_RETENTION_MS=3e5;export class RuntimeTerminalOutboundRegistration{options;service;authorityAdmission;serviceGeneration;rings=new Map;ringBytes=new Map;droppedThrough=new Map;pending=[];pendingBytes=0;activeSend;activeFlush;flushes=new Set;connected=!1;draining=!1;stopped=!1;eventGeneration=0;transportEpoch=0;drainPromise;closePromise;replayExpiryTimers=new Map;constructor(e){this.options=e,this.service=e.service??getOrCreateRuntimeTerminalService(e.manager),this.authorityAdmission=new TerminalAuthorityAdmission(e.authorityJournal,e.authorityClock),this.serviceGeneration=this.service.setOutbound(this);const t=this.eventGeneration;e.client.on("connected",()=>{this.acceptsEvent(t)&&(this.connected||(this.transportEpoch++,this.activeFlush=void 0,this.serviceGeneration??=this.service.setOutbound(this),this.connected=!0,this.publishAvailability(!0),this.kickFlush(),e.logger?.info?.("[terminal-service] outbound registration connected")))}),e.client.on("disconnected",()=>{this.acceptsEvent(t)&&this.invalidateConnection(!1)}),e.client.on("message",(...e)=>{if(!this.acceptsEvent(t))return;const i=this.serviceGeneration,n=this.transportEpoch;if(!i||!this.acceptsTransport(n,i))return;const s=e[0],r="string"==typeof s?s:Buffer.from(s).toString("utf8");this.handleWire(r,i,n)}),e.client.on("error",(...i)=>{this.acceptsEvent(t)&&e.logger?.warn?.("[terminal-service] outbound registration error",i[0])}),e.client.on("authorityLost",()=>{this.acceptsEvent(t)&&(this.invalidateConnection(!0),e.logger?.warn?.("[terminal-service] runtime lease lost; Service terminals fenced"))}),e.client.on("transportEpochChanged",()=>{this.acceptsEvent(t)&&(this.invalidateConnection(!0),e.logger?.info?.("[terminal-service] runtime lease rotated; prior Terminal epoch fenced"))})}async start(){if(this.stopped)throw new Error("terminal outbound registration is stopped");await this.options.client.connect()}isAvailable(){return this.connected&&!this.draining&&!this.stopped}send(e){if(this.stopped)return!1;const t=JSON.stringify(e),i=Buffer.byteLength(t);return this.remember(e,t,i),!this.connected||(this.enqueueWithOutputBackpressure({clientId:e.clientId,terminalId:e.terminalId,frame:e,wire:t,bytes:i}),this.kickFlush(),!0)}resume(e,t,i){const n=this.transportEpoch;if(!this.acceptsConnection(n))throw new Error("terminal outbound registration is disconnected");const s=BigInt(i),r=s<(this.droppedThrough.get(t)??0n),a=[];let o=-1n;for(const i of this.rings.get(t)??[]){if(i.frame.clientId!==e)throw new Error("terminal resume ownership mismatch");const n=BigInt(i.frame.sequence);if(n<=o)throw new Error("terminal replay sequence is not monotonic");o=n,n<=s||a.push({clientId:e,terminalId:t,frame:i.frame,wire:i.wire,bytes:i.bytes})}if(!this.acceptsConnection(n))throw new Error("terminal outbound registration epoch changed");for(const e of a)this.enqueueWithOutputBackpressure(e);return this.acknowledgeReplay(t,s),this.kickFlush(),{gap:r}}rebindResumeClient(e,t,i){if(e===t)return;const n=this.rings.get(i);if(n?.some(t=>t.frame.clientId!==e))throw new Error("terminal resume ownership mismatch");if(n){let e=0;const s=n.map(i=>{const n=Object.freeze({...i.frame,clientId:t}),s=JSON.stringify(n),r=Buffer.byteLength(s);return e+=r,{frame:n,wire:s,bytes:r}});this.rings.set(i,s),this.ringBytes.set(i,e)}for(let n=0;n<this.pending.length;n++){const s=this.pending[n];if(s.terminalId!==i||s.clientId!==e)continue;const r={...s.frame,clientId:t},a=JSON.stringify(r),o=Buffer.byteLength(a);this.pendingBytes+=o-s.bytes,this.pending[n]={clientId:t,terminalId:i,frame:r,wire:a,bytes:o}}if(this.activeSend?.item.terminalId===i&&this.activeSend.item.clientId===e){const e=this.activeSend.item,n={...e.frame,clientId:t},s=JSON.stringify(n),r=Buffer.byteLength(s);this.activeSend.counted&&(this.pendingBytes+=r-e.bytes),this.activeSend={item:{clientId:t,terminalId:i,frame:n,wire:s,bytes:r},counted:this.activeSend.counted}}}forgetTerminal(e,t){this.prepareForgetTerminal(e,t)()}prepareForgetTerminal(e,t){const i=this.rings.get(t),n=new Set(this.pending.filter(e=>e.terminalId===t)),s=this.activeSend?.item.terminalId===t&&this.activeSend.counted?this.activeSend:void 0;if(i?.some(t=>t.frame.clientId!==e)||[...n].some(t=>t.clientId!==e)||s&&s.item.clientId!==e)throw new Error("terminal forget ownership mismatch");const r=this.replayExpiryTimers.get(t);let a=!1;return()=>{if(a)return;a=!0,r&&this.replayExpiryTimers.get(t)===r&&(clearTimeout(r),this.replayExpiryTimers.delete(t)),i&&this.rings.get(t)===i&&(this.rings.delete(t),this.ringBytes.delete(t),this.droppedThrough.delete(t));let e=0;for(const t of this.pending)n.has(t)?this.pendingBytes-=t.bytes:this.pending[e++]=t;this.pending.length=e,s&&this.activeSend===s&&s.counted&&(s.counted=!1,this.pendingBytes-=s.item.bytes),this.pendingBytes=Math.max(0,this.pendingBytes)}}startTerminalReplayExpiry(e,t){if((this.rings.get(t)??[]).some(t=>t.frame.clientId!==e))throw new Error("terminal replay expiry ownership mismatch");this.scheduleReplayExpiry(e,t)}drain(e){return this.drainPromise??=this.drainOnce(e),this.drainPromise}async drainOnce(e){this.draining=!0,this.stopped=!0,this.eventGeneration++;const t=[...this.flushes];this.invalidateConnection(!0);const i=await waitBounded(this.options.manager.drain(e.timeoutMs,e.terminateAfterTimeout),e.timeoutMs,e.signal),n=i===interrupted?"terminated":i;return i!==interrupted&&"terminated"===n&&e.terminateAfterTimeout&&await waitBounded(this.options.manager.drain(Math.min(1e3,Math.max(50,e.timeoutMs)),!1),Math.min(1e3,Math.max(50,e.timeoutMs)),e.signal),await waitBounded(Promise.allSettled(t),e.timeoutMs,e.signal),await waitBounded(this.closeClientOnce(),e.timeoutMs,e.signal),this.clearReplayState(),n}acceptsEvent(e){return!this.stopped&&e===this.eventGeneration}async handleWire(e,t,i){if(!this.acceptsTransport(i,t))return;if(Buffer.byteLength(e)>TERMINAL_MAX_FRAME_BYTES)return void this.options.logger?.warn?.("[terminal-service] oversized client frame rejected");let n,s;try{n=JSON.parse(e)}catch{return void this.options.logger?.warn?.("[terminal-service] invalid client JSON")}try{s=await this.authorityAdmission.admit(n),await this.service.handleClientFrame(s.frame,t,s.admission)}catch(e){if(this.acceptsTransport(i,t)){s&&this.sendRejectedFrame(s.frame,e);const t=e instanceof Error?e.message:String(e);this.options.logger?.warn?.(`[terminal-service] client frame rejected: ${t}`,e)}}}sendRejectedFrame(e,t){const i=(t instanceof Error?t.message:String(t)).toLowerCase(),n=t instanceof TerminalNotFoundError||i.includes("not found")?"TERMINAL_NOT_FOUND":i.includes("quota")?"TERMINAL_QUOTA_EXCEEDED":i.includes("unauthorized")||i.includes("authority")?"UNAUTHORIZED_TARGET":"TERMINAL_IO_ERROR",s=this.rings.get(e.terminalId),r="TERMINAL_NOT_FOUND"!==n&&this.options.manager.getSession(e.terminalId)?.sessionId===e.clientId&&(!s||s.every(t=>t.frame.clientId===e.clientId)),a=r?this.options.manager.getSessionIncarnation(e.terminalId):void 0,o=r||"terminal.resume"!==e.type?a?BigInt(this.options.manager.nextServerSequence(e.terminalId,a)):1n:BigInt(e.lastServerSequence)+1n,c={protocolVersion:TERMINAL_SERVICE_PROTOCOL_VERSION,type:"terminal.error",clientId:e.clientId,terminalId:e.terminalId,sequence:String(o),code:n,message:n,recoverable:"TERMINAL_IO_ERROR"===n||"TERMINAL_QUOTA_EXCEEDED"===n};if(!r){const t=JSON.stringify(c);return this.enqueueWithOutputBackpressure({clientId:e.clientId,terminalId:e.terminalId,frame:c,wire:t,bytes:Buffer.byteLength(t)}),void this.kickFlush()}this.send(c)}remember(e,t,i){const n=this.rings.get(e.terminalId)??[];n.push({frame:Object.freeze({...e}),wire:t,bytes:i});let s=(this.ringBytes.get(e.terminalId)??0)+i;const r=this.options.maxBufferedFramesPerTerminal??512,a=this.options.maxBufferedBytesPerTerminal??1048576;for(;n.length>r||s>a;){const t=n.shift();if(!t)break;s-=t.bytes,this.droppedThrough.set(e.terminalId,BigInt(t.frame.sequence))}this.rings.set(e.terminalId,n),this.ringBytes.set(e.terminalId,s),"terminal.exit"===e.type&&this.scheduleReplayExpiry(e.clientId,e.terminalId)}enqueueWithOutputBackpressure(e){const t=this.options.maxPendingSendBytes??1048576;if(this.pendingBytes+e.bytes<=t)return this.pending.push(e),void(this.pendingBytes+=e.bytes);if("terminal.output"===e.frame.type){if(this.hasPendingTruncation(e.terminalId))return;const i=this.toTruncationMarker(e);return this.compactPendingOutput(i.bytes,t),void(this.hasPendingTruncation(e.terminalId)||(this.pending.push(i),this.pendingBytes+=i.bytes))}this.compactPendingOutput(e.bytes,t),this.pending.push(e),this.pendingBytes+=e.bytes}compactPendingOutput(e,t){for(;this.pendingBytes+e>t;){const e=this.pending.findIndex(e=>"terminal.output"===e.frame.type&&!0!==e.frame.truncated);if(e<0)return;const t=this.pending[e];if(this.hasPendingTruncation(t.terminalId,t)){this.pending.splice(e,1),this.pendingBytes-=t.bytes;continue}const i=this.toTruncationMarker(t);this.pending[e]=i,this.pendingBytes+=i.bytes-t.bytes}}hasPendingTruncation(e,t){return this.activeSend?.item!==t&&this.activeSend?.item.terminalId===e&&"terminal.output"===this.activeSend.item.frame.type&&!0===this.activeSend.item.frame.truncated||this.pending.some(i=>i!==t&&i.terminalId===e&&"terminal.output"===i.frame.type&&!0===i.frame.truncated)}toTruncationMarker(e){if("terminal.output"!==e.frame.type)throw new Error("only terminal output can be truncated");const t={...e.frame,data:"",encoding:"base64",truncated:!0},i=JSON.stringify(t);return{...e,frame:t,wire:i,bytes:Buffer.byteLength(i)}}async flush(e){for(;this.acceptsConnection(e)&&this.pending.length>0;){const t=this.pending.shift(),i={item:t,counted:!0};this.activeSend=i;try{await this.options.client.send(t.wire)}catch{return void(this.transportEpoch===e&&this.invalidateConnection(!1))}if(!this.acceptsConnection(e))return;this.activeSend===i&&(i.counted&&(this.pendingBytes-=t.bytes),this.activeSend=void 0)}}kickFlush(){if(this.activeFlush||!this.connected||0===this.pending.length)return;const e=this.transportEpoch,t=this.flush(e).finally(()=>{this.flushes.delete(t),this.activeFlush?.promise===t&&(this.activeFlush=void 0,this.acceptsConnection(e)&&this.kickFlush())});this.activeFlush={epoch:e,promise:t},this.flushes.add(t)}acceptsConnection(e){return this.connected&&!this.stopped&&e===this.transportEpoch}acceptsTransport(e,t){return this.acceptsEvent(this.eventGeneration)&&this.acceptsConnection(e)&&this.serviceGeneration===t}invalidateConnection(e){const t=this.connected;if(this.transportEpoch++,this.connected=!1,t&&this.publishAvailability(!1),this.activeFlush=void 0,this.activeSend=void 0,this.flushes.clear(),this.pending.length=0,this.pendingBytes=0,!e)return;const i=this.serviceGeneration;i&&(this.service.fenceServiceSessions("runtime_lease_lost",i),this.service.clearOutbound(this,i),this.serviceGeneration===i&&(this.serviceGeneration=void 0)),this.clearReplayState()}publishAvailability(e){try{this.options.onAvailabilityChange?.(e)}catch{}}clearReplayState(){for(const e of this.replayExpiryTimers.values())clearTimeout(e);this.replayExpiryTimers.clear(),this.rings.clear(),this.ringBytes.clear(),this.droppedThrough.clear()}acknowledgeReplay(e,t){const i=this.rings.get(e);if(!i||0===i.length)return;let n=0,s=this.droppedThrough.get(e)??0n,r=0;for(;r<i.length;){const e=i[r],a=BigInt(e.frame.sequence);if(a>t)break;n+=e.bytes,a>s&&(s=a),r++}0!==r&&(i.splice(0,r),this.ringBytes.set(e,Math.max(0,(this.ringBytes.get(e)??0)-n)),this.droppedThrough.set(e,s))}scheduleReplayExpiry(e,t){this.clearReplayExpiry(t);const i=this.serviceGeneration;if(!i)return;const n=setTimeout(()=>{if(this.replayExpiryTimers.get(t)===n){this.replayExpiryTimers.delete(t);try{this.service.expireServiceTerminalReplay(e,t,i)}catch(e){this.options.logger?.warn?.("[terminal-service] replay expiry failed",e)}}},Math.max(0,this.options.replayRetentionMs??3e5));n.unref?.(),this.replayExpiryTimers.set(t,n)}clearReplayExpiry(e){const t=this.replayExpiryTimers.get(e);t&&clearTimeout(t),this.replayExpiryTimers.delete(e)}closeClientOnce(){return this.closePromise??=this.options.client.close(!0),this.closePromise}}const interrupted=Symbol("interrupted");async function waitBounded(e,t,i){return i?.aborted?(e.catch(()=>{}),interrupted):await new Promise((n,s)=>{let r=!1;const a=e=>{r||(r=!0,clearTimeout(c),i?.removeEventListener("abort",o),n(e))},o=()=>a(interrupted),c=setTimeout(()=>a(interrupted),Math.max(0,t));c.unref?.(),i?.addEventListener("abort",o,{once:!0}),e.then(e=>a(e),e=>{r||(r=!0,clearTimeout(c),i?.removeEventListener("abort",o),s(e))})})}
@@ -1 +1 @@
1
- import{createHash,randomUUID}from"node:crypto";import{EventEmitter}from"node:events";import WebSocket from"ws";import{signAgentMessage}from"../agent-auth.js";export function terminalAgentAuthSigningMessage(e){return`terminal|${e.public_key}|${e.timestamp}|${e.nonce}|${e.runtimeLeaseCredential}|${e.handlerIdentity}|${e.runtimeEpoch}|${e.leaseId}`}export function createTerminalLeaseBoundAgentAuth(e){if(!(32===e.keys.publicKey.length&&[32,48].includes(e.keys.privateKey.length)&&e.lease.instanceId&&e.lease.leaseId&&e.lease.handlerIdentity&&e.lease.runtimeLeaseCredential&&isPositiveRuntimeEpoch(e.lease.runtimeEpoch)&&Number.isSafeInteger(e.timestamp)&&!(e.timestamp<0)&&e.nonce))throw new Error("invalid Terminal runtime lease authority binding");const t={service:"terminal",public_key:Buffer.from(e.keys.publicKey).toString("base64"),timestamp:e.timestamp,nonce:e.nonce,runtimeLeaseCredential:e.lease.runtimeLeaseCredential,handlerIdentity:e.lease.handlerIdentity,runtimeEpoch:e.lease.runtimeEpoch,leaseId:e.lease.leaseId};return{type:"agent_auth",instance_id:e.lease.instanceId,...t,signature:Buffer.from(signAgentMessage(terminalAgentAuthSigningMessage(t),e.keys.privateKey)).toString("base64")}}export class TerminalLeaseBoundBridgeClient extends EventEmitter{options;state="idle";socket;unsubscribe;expiryTimer;reconnectTimer;generation=0;stopped=!0;authenticatedBindingHash;authorityEpochBindingHash;transition=Promise.resolve();constructor(e){super(),this.options=e}async connect(){this.unsubscribe||(this.unsubscribe=this.options.authority.subscribeAuthority(e=>this.onAuthorityChanged(e))),this.stopped=!1;const e=this.options.authority.authorityLease;if(!e)throw new Error("active runtime registration lease required for Terminal auth");await this.queueTransition(()=>this.replaceConnection(e))}async send(e){const t=this.socket;if("connected"!==this.state||!t||t.readyState!==WebSocket.OPEN)throw new Error("Terminal lease-bound Bridge is not connected");await new Promise((i,n)=>t.send(e,e=>e?n(e):i()))}async close(e=!0){this.stopped=!0,this.clearTimers(),this.unsubscribe?.(),this.unsubscribe=void 0,this.authenticatedBindingHash=void 0,this.authorityEpochBindingHash=void 0,this.generation++,await this.closeSocket(e),this.state="closed"}onAuthorityChanged(e){if(this.stopped)return;if(!e)return void this.fenceAuthority();this.scheduleExpiryFence(e);const t=authorityEpochHash(e),i=authorityBindingHash(e);return this.authorityEpochBindingHash&&t!==this.authorityEpochBindingHash?(this.authorityEpochBindingHash=t,this.emit("transportEpochChanged"),void this.queueTransition(()=>this.replaceConnection(e)).catch(e=>this.emitError(e))):i!==this.authenticatedBindingHash?"connected"===this.state&&this.authenticatedBindingHash?(this.authenticatedBindingHash=i,void(this.authorityEpochBindingHash??=t)):void this.queueTransition(()=>this.replaceConnection(e)).catch(e=>this.emitError(e)):void 0}async replaceConnection(e){if(this.stopped||null===this.options.authority.authorityLease)return;this.clearReconnectTimer();const t=++this.generation;if(await this.closeSocket(!1),this.stopped||t!==this.generation)return;this.state="connecting";const i=new WebSocket(`${this.options.bridgeUrl.replace(/\/+$/,"")}/agent`);this.socket=i;const n=authorityBindingHash(e);await new Promise((s,o)=>{let r=!1;const a=setTimeout(()=>{c(new Error("Terminal auth timeout")),i.readyState!==WebSocket.CLOSED&&i.terminate()},this.options.authTimeoutMs??1e4),h=()=>{clearTimeout(a),i.off("open",u)},c=e=>{h(),r||o(e)},u=()=>{const e=this.options.authority.authorityLease;if(!e||authorityBindingHash(e)!==n||t!==this.generation)return c(new Error("Terminal runtime lease changed during auth")),void i.close();const s=createTerminalLeaseBoundAgentAuth({lease:e,keys:this.options.keys,timestamp:Math.floor((this.options.now??Date.now)()/1e3),nonce:(this.options.nonce??randomUUID)()});i.send(JSON.stringify(s),e=>{e&&c(e)})};i.on("open",u),i.on("message",o=>{if(!r){try{if("auth_ok"!==JSON.parse(o.toString()).type)return}catch{return}return r=!0,h(),t!==this.generation?void i.close():(this.authenticatedBindingHash=n,this.authorityEpochBindingHash=authorityEpochHash(e),this.state="connected",this.scheduleExpiryFence(e),this.emit("connected"),void s())}this.emit("message",o)}),i.on("error",e=>{this.emitError(e),c(e)}),i.on("close",(e,i)=>{h(),r||o(new Error(`Terminal auth rejected: ${i.toString()||"connection closed"}`)),t===this.generation&&(this.socket=void 0,this.authenticatedBindingHash=void 0,this.state="idle",this.emit("disconnected",i.toString()||"connection closed"),1008!==e?!this.stopped&&this.options.authority.authorityLease&&this.scheduleReconnect():this.fenceAuthority())})})}fenceAuthority(){this.clearTimers(),this.authenticatedBindingHash=void 0,this.authorityEpochBindingHash=void 0,this.generation++;const e=this.socket;this.socket=void 0,this.state="idle",e&&e.readyState!==WebSocket.CLOSED&&e.terminate(),this.emit("authorityLost")}scheduleExpiryFence(e){this.expiryTimer&&clearTimeout(this.expiryTimer);const t=authorityBindingHash(e);this.expiryTimer=setTimeout(()=>{const e=this.options.authority.authorityLease;e?authorityBindingHash(e)===t&&(Date.parse(e.leaseExpiresAt)>(this.options.now??Date.now)()?this.scheduleExpiryFence(e):this.fenceAuthority()):this.fenceAuthority()},Math.min(2147483647,Math.max(0,Date.parse(e.leaseExpiresAt)-(this.options.now??Date.now)()))),this.expiryTimer.unref?.()}scheduleReconnect(){this.reconnectTimer||this.stopped||(this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0;const e=this.options.authority.authorityLease;e&&this.queueTransition(()=>this.replaceConnection(e)).catch(e=>{this.emitError(e),this.scheduleReconnect()})},this.options.reconnectDelayMs??1e3),this.reconnectTimer.unref?.())}async closeSocket(e){const t=this.socket;this.socket=void 0,t&&t.readyState!==WebSocket.CLOSED&&(e&&t.readyState===WebSocket.OPEN?await new Promise(e=>{t.once("close",()=>e()),t.close()}):t.terminate())}queueTransition(e){const t=this.transition.then(e,e);return this.transition=t.catch(()=>{}),t}clearReconnectTimer(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}clearTimers(){this.clearReconnectTimer(),this.expiryTimer&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0}emitError(e){this.listenerCount("error")>0&&this.emit("error",e instanceof Error?e:new Error(String(e)))}}function authorityEpochHash(e){return createHash("sha256").update(`${e.instanceId}\0${e.leaseId}\0${e.handlerIdentity}\0${e.runtimeEpoch}`).digest("hex")}function authorityBindingHash(e){return createHash("sha256").update(`${e.instanceId}\0${e.leaseId}\0${e.handlerIdentity}\0${e.runtimeEpoch}\0${e.runtimeLeaseCredential}\0${e.leaseExpiresAt}`).digest("hex")}function isPositiveRuntimeEpoch(e){return"string"==typeof e&&/^[1-9][0-9]*$/.test(e)&&BigInt(e)<=18446744073709551615n}
1
+ import{createHash,randomUUID}from"node:crypto";import{EventEmitter}from"node:events";import WebSocket from"ws";import{createTerminalAgentAuth,terminalAgentAuthSigningMessage as harnessTerminalAgentAuthSigningMessage,terminalAgentWebSocketUrl}from"@beeos-ai/cloud-harness-sdk";export function terminalAgentAuthSigningMessage(e){return harnessTerminalAgentAuthSigningMessage({publicKey:e.public_key,timestamp:e.timestamp,nonce:e.nonce,runtimeLeaseCredential:e.runtimeLeaseCredential,handlerIdentity:e.handlerIdentity,runtimeEpoch:e.runtimeEpoch,leaseId:e.leaseId})}export function createTerminalLeaseBoundAgentAuth(e){if(!(32===e.keys.publicKey.length&&[32,48].includes(e.keys.privateKey.length)&&e.lease.instanceId&&e.lease.leaseId&&e.lease.handlerIdentity&&e.lease.runtimeLeaseCredential&&isPositiveRuntimeEpoch(e.lease.runtimeEpoch)&&Number.isSafeInteger(e.timestamp)&&!(e.timestamp<0)&&e.nonce))throw new Error("invalid Terminal runtime lease authority binding");return createTerminalAgentAuth({lease:{instanceId:e.lease.instanceId,leaseId:e.lease.leaseId,runtimeEpoch:e.lease.runtimeEpoch,runtimeLeaseCredential:e.lease.runtimeLeaseCredential,handlerIdentity:e.lease.handlerIdentity},keys:e.keys,timestamp:e.timestamp,nonce:e.nonce})}export class TerminalLeaseBoundBridgeClient extends EventEmitter{options;state="idle";socket;unsubscribe;expiryTimer;reconnectTimer;generation=0;stopped=!0;authenticatedBindingHash;authorityEpochBindingHash;transition=Promise.resolve();constructor(e){super(),this.options=e}async connect(){this.unsubscribe||(this.unsubscribe=this.options.authority.subscribeAuthority(e=>this.onAuthorityChanged(e))),this.stopped=!1;const e=this.options.authority.authorityLease;if(!e)throw new Error("active runtime registration lease required for Terminal auth");await this.queueTransition(()=>this.replaceConnection(e))}async send(e){const t=this.socket;if("connected"!==this.state||!t||t.readyState!==WebSocket.OPEN)throw new Error("Terminal lease-bound Bridge is not connected");await new Promise((i,n)=>t.send(e,e=>e?n(e):i()))}async close(e=!0){this.stopped=!0,this.clearTimers(),this.unsubscribe?.(),this.unsubscribe=void 0,this.authenticatedBindingHash=void 0,this.authorityEpochBindingHash=void 0,this.generation++,await this.closeSocket(e),this.state="closed"}onAuthorityChanged(e){if(this.stopped)return;if(!e)return void this.fenceAuthority();this.scheduleExpiryFence(e);const t=authorityEpochHash(e),i=authorityBindingHash(e);return this.authorityEpochBindingHash&&t!==this.authorityEpochBindingHash?(this.authorityEpochBindingHash=t,this.emit("transportEpochChanged"),void this.queueTransition(()=>this.replaceConnection(e)).catch(e=>this.emitError(e))):i!==this.authenticatedBindingHash?"connected"===this.state&&this.authenticatedBindingHash?(this.authenticatedBindingHash=i,void(this.authorityEpochBindingHash??=t)):void this.queueTransition(()=>this.replaceConnection(e)).catch(e=>this.emitError(e)):void 0}async replaceConnection(e){if(this.stopped||null===this.options.authority.authorityLease)return;this.clearReconnectTimer();const t=++this.generation;if(await this.closeSocket(!1),this.stopped||t!==this.generation)return;this.state="connecting";const i=new WebSocket(terminalAgentWebSocketUrl(this.options.bridgeUrl));this.socket=i;const n=authorityBindingHash(e);await new Promise((s,o)=>{let r=!1;const a=setTimeout(()=>{c(new Error("Terminal auth timeout")),i.readyState!==WebSocket.CLOSED&&i.terminate()},this.options.authTimeoutMs??1e4),h=()=>{clearTimeout(a),i.off("open",u)},c=e=>{h(),r||o(e)},u=()=>{const e=this.options.authority.authorityLease;if(!e||authorityBindingHash(e)!==n||t!==this.generation)return c(new Error("Terminal runtime lease changed during auth")),void i.close();const s=createTerminalLeaseBoundAgentAuth({lease:e,keys:this.options.keys,timestamp:Math.floor((this.options.now??Date.now)()/1e3),nonce:(this.options.nonce??randomUUID)()});i.send(JSON.stringify(s),e=>{e&&c(e)})};i.on("open",u),i.on("message",o=>{if(!r){try{if("auth_ok"!==JSON.parse(o.toString()).type)return}catch{return}return r=!0,h(),t!==this.generation?void i.close():(this.authenticatedBindingHash=n,this.authorityEpochBindingHash=authorityEpochHash(e),this.state="connected",this.scheduleExpiryFence(e),this.emit("connected"),void s())}this.emit("message",o)}),i.on("error",e=>{this.emitError(e),c(e)}),i.on("close",(e,i)=>{h(),r||o(new Error(`Terminal auth rejected: ${i.toString()||"connection closed"}`)),t===this.generation&&(this.socket=void 0,this.authenticatedBindingHash=void 0,this.state="idle",this.emit("disconnected",i.toString()||"connection closed"),1008!==e?!this.stopped&&this.options.authority.authorityLease&&this.scheduleReconnect():this.fenceAuthority())})})}fenceAuthority(){this.clearTimers(),this.authenticatedBindingHash=void 0,this.authorityEpochBindingHash=void 0,this.generation++;const e=this.socket;this.socket=void 0,this.state="idle",e&&e.readyState!==WebSocket.CLOSED&&e.terminate(),this.emit("authorityLost")}scheduleExpiryFence(e){this.expiryTimer&&clearTimeout(this.expiryTimer);const t=authorityBindingHash(e);this.expiryTimer=setTimeout(()=>{const e=this.options.authority.authorityLease;e?authorityBindingHash(e)===t&&(Date.parse(e.leaseExpiresAt)>(this.options.now??Date.now)()?this.scheduleExpiryFence(e):this.fenceAuthority()):this.fenceAuthority()},Math.min(2147483647,Math.max(0,Date.parse(e.leaseExpiresAt)-(this.options.now??Date.now)()))),this.expiryTimer.unref?.()}scheduleReconnect(){this.reconnectTimer||this.stopped||(this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0;const e=this.options.authority.authorityLease;e&&this.queueTransition(()=>this.replaceConnection(e)).catch(e=>{this.emitError(e),this.scheduleReconnect()})},this.options.reconnectDelayMs??1e3),this.reconnectTimer.unref?.())}async closeSocket(e){const t=this.socket;this.socket=void 0,t&&t.readyState!==WebSocket.CLOSED&&(e&&t.readyState===WebSocket.OPEN?await new Promise(e=>{t.once("close",()=>e()),t.close()}):t.terminate())}queueTransition(e){const t=this.transition.then(e,e);return this.transition=t.catch(()=>{}),t}clearReconnectTimer(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}clearTimers(){this.clearReconnectTimer(),this.expiryTimer&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0}emitError(e){this.listenerCount("error")>0&&this.emit("error",e instanceof Error?e:new Error(String(e)))}}function authorityEpochHash(e){return createHash("sha256").update(`${e.instanceId}\0${e.leaseId}\0${e.handlerIdentity}\0${e.runtimeEpoch}`).digest("hex")}function authorityBindingHash(e){return createHash("sha256").update(`${e.instanceId}\0${e.leaseId}\0${e.handlerIdentity}\0${e.runtimeEpoch}\0${e.runtimeLeaseCredential}\0${e.leaseExpiresAt}`).digest("hex")}function isPositiveRuntimeEpoch(e){return"string"==typeof e&&/^[1-9][0-9]*$/.test(e)&&BigInt(e)<=18446744073709551615n}
@@ -1 +1 @@
1
- import{access,constants}from"node:fs/promises";import{execFile}from"node:child_process";import{promisify}from"node:util";import{uploadLocalFile}from"./upload-file.js";const execFileAsync=promisify(execFile);export const BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME="beeos_desktop_screenshot";export const BEEOS_DESKTOP_SCREENSHOT_TOOL_DESCRIPTION="Capture the agent desktop (DISPLAY) via platform beeos-screenshot, then upload for the user. Prefer this over shell/python X11 dumps. Do not invent raw Xlib/PIL capture — those produce RGB striping. Requires openclaw-desktop image with scrot (or ImageMagick import) and /usr/local/bin/beeos-screenshot.";export const BEEOS_DESKTOP_SCREENSHOT_TOOL_SCHEMA={title:"BeeOS desktop screenshot",type:"object",description:BEEOS_DESKTOP_SCREENSHOT_TOOL_DESCRIPTION,additionalProperties:!1,properties:{path:{type:"string",minLength:1,description:"Local filesystem path for the PNG capture (default: /tmp/desktop.png)."},upload:{type:"boolean",description:"When true (default), upload the capture so the user sees a chat preview."}}};const DEFAULT_PATH="/tmp/desktop.png",REQUEST_TIMEOUT_MS=12e4,CAPTURE_TIMEOUT_MS=3e4,SCREENSHOT_BINARIES=["/usr/local/bin/beeos-screenshot","beeos-screenshot"],MISSING_BINARY_MSG="beeos-screenshot not found on PATH. Use the openclaw-desktop image with scrot installed, or install scrot + /usr/local/bin/beeos-screenshot. Do not fall back to raw Xlib/PIL capture.";let _deps={};export function setDesktopScreenshotDeps(e){_deps=e}export function resetDesktopScreenshotDeps(){_deps={}}export async function executeDesktopScreenshot(e,t,r,o){const s=parseParams(e);if(!s.ok)return errorResult(s.error);const{path:n,upload:a}=s,i=_deps.execFile??execFileAsync,p=_deps.resolveBinary?await _deps.resolveBinary():await resolveScreenshotBinary();if(!p)return errorResult(MISSING_BINARY_MSG);try{await i(p,[n],{timeout:3e4,env:{...process.env,DISPLAY:process.env.DISPLAY||":1"},signal:o})}catch(e){if(o?.aborted)throw e;if("ENOENT"===e.code)return errorResult(MISSING_BINARY_MSG);return errorResult(`desktop capture failed: ${e instanceof Error?e.message:String(e)}`)}try{await access(n,constants.R_OK)}catch{return errorResult(`capture produced no readable file at ${n}`)}if(!a){const e={ok:!0,path:n};return{...e,content:[{type:"text",text:`Desktop captured to ${n} (not uploaded)`}],output:e,result:e,details:e,isError:!1}}if(!t.agentGatewayUrl)return errorResult("agentGatewayUrl not configured — file upload requires Agent Gateway access");if(!r)return errorResult("agent key pair not available — cannot sign upload requests");const c=_deps.uploadLocalFile??uploadLocalFile;try{const e=await c(n,t.agentGatewayUrl,r,{signal:o,timeoutMs:12e4,fileNameOverride:`desktop-${Date.now()}.png`}),s=[{uri:e.uri,name:e.name,mimeType:e.mimeType,fileId:e.fileId}],a=`Desktop screenshot uploaded: ${s[0].name}`,i={ok:!0,path:n,files:s};return{...i,content:[{type:"text",text:a},{type:"resource_link",uri:s[0].uri,name:s[0].name,mimeType:s[0].mimeType}],output:i,result:i,details:i,isError:!1}}catch(e){if(o?.aborted)throw e;return errorResult(`capture ok at ${n} but upload failed: ${e instanceof Error?e.message:String(e)}`)}}async function resolveScreenshotBinary(){for(const e of SCREENSHOT_BINARIES){if(!e.includes("/"))return e;try{return await access(e,constants.X_OK),e}catch{continue}}return null}function parseParams(e){if(null==e)return{ok:!0,path:DEFAULT_PATH,upload:!0};if("object"!=typeof e)return{ok:!1,error:"params must be an object"};const t=e,r=new Set(["path","upload"]),o=Object.keys(t).filter(e=>!r.has(e));if(o.length>0)return{ok:!1,error:`unknown params: ${o.join(", ")}`};let s=DEFAULT_PATH;if(void 0!==t.path){if("string"!=typeof t.path||""===t.path.trim())return{ok:!1,error:"path must be a non-empty string"};s=t.path.trim()}let n=!0;if(void 0!==t.upload){if("boolean"!=typeof t.upload)return{ok:!1,error:"upload must be a boolean"};n=t.upload}return{ok:!0,path:s,upload:n}}function errorResult(e){const t={ok:!1,error:e};return{...t,content:[{type:"text",text:e}],output:t,result:t,details:t,isError:!0}}
1
+ import{access,constants}from"node:fs/promises";import{execFile}from"node:child_process";import{promisify}from"node:util";import{uploadLocalFile}from"./upload-file.js";const execFileAsync=promisify(execFile);export const BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME="beeos_desktop_screenshot";export const BEEOS_DESKTOP_SCREENSHOT_TOOL_DESCRIPTION="Capture the agent desktop (DISPLAY) via platform beeos-screenshot, then upload for the user. Prefer this over shell/python X11 dumps. Do not invent raw Xlib/PIL capture — those produce RGB striping. Requires openclaw-desktop image with scrot (or ImageMagick import) and /usr/local/bin/beeos-screenshot.";export const BEEOS_DESKTOP_SCREENSHOT_TOOL_SCHEMA={title:"BeeOS desktop screenshot",type:"object",description:BEEOS_DESKTOP_SCREENSHOT_TOOL_DESCRIPTION,additionalProperties:!1,properties:{path:{type:"string",minLength:1,description:"Local filesystem path for the PNG capture (default: /tmp/desktop.png)."},upload:{type:"boolean",description:"When true (default), upload the capture so the user sees a chat preview."}}};const DEFAULT_PATH="/tmp/desktop.png",REQUEST_TIMEOUT_MS=12e4,CAPTURE_TIMEOUT_MS=3e4,SCREENSHOT_BINARIES=["/usr/local/bin/beeos-screenshot","beeos-screenshot"],MISSING_BINARY_MSG="beeos-screenshot not found on PATH. Use the openclaw-desktop image with scrot installed, or install scrot + /usr/local/bin/beeos-screenshot. Do not fall back to raw Xlib/PIL capture.";let _deps={};export function setDesktopScreenshotDeps(e){_deps=e}export function resetDesktopScreenshotDeps(){_deps={}}export async function executeDesktopScreenshot(e,t,r){const o=parseParams(e);if(!o.ok)return errorResult(o.error);const{path:s,upload:n}=o,a=_deps.execFile??execFileAsync,i=_deps.resolveBinary?await _deps.resolveBinary():await resolveScreenshotBinary();if(!i)return errorResult(MISSING_BINARY_MSG);try{await a(i,[s],{timeout:3e4,env:{...process.env,DISPLAY:process.env.DISPLAY||":1"},signal:r})}catch(e){if(r?.aborted)throw e;if("ENOENT"===e.code)return errorResult(MISSING_BINARY_MSG);return errorResult(`desktop capture failed: ${e instanceof Error?e.message:String(e)}`)}try{await access(s,constants.R_OK)}catch{return errorResult(`capture produced no readable file at ${s}`)}if(!n){const e={ok:!0,path:s};return{...e,content:[{type:"text",text:`Desktop captured to ${s} (not uploaded)`}],output:e,result:e,details:e,isError:!1}}if(!t)return errorResult("Agent Gateway client unavailable — file upload requires agentGatewayUrl and a key pair");const p=_deps.uploadLocalFile??uploadLocalFile;try{const e=await p(s,t,{signal:r,timeoutMs:12e4,fileNameOverride:`desktop-${Date.now()}.png`}),o=[{uri:e.uri,name:e.name,mimeType:e.mimeType,fileId:e.fileId}],n=`Desktop screenshot uploaded: ${o[0].name}`,a={ok:!0,path:s,files:o};return{...a,content:[{type:"text",text:n},{type:"resource_link",uri:o[0].uri,name:o[0].name,mimeType:o[0].mimeType}],output:a,result:a,details:a,isError:!1}}catch(e){if(r?.aborted)throw e;return errorResult(`capture ok at ${s} but upload failed: ${e instanceof Error?e.message:String(e)}`)}}async function resolveScreenshotBinary(){for(const e of SCREENSHOT_BINARIES){if(!e.includes("/"))return e;try{return await access(e,constants.X_OK),e}catch{continue}}return null}function parseParams(e){if(null==e)return{ok:!0,path:DEFAULT_PATH,upload:!0};if("object"!=typeof e)return{ok:!1,error:"params must be an object"};const t=e,r=new Set(["path","upload"]),o=Object.keys(t).filter(e=>!r.has(e));if(o.length>0)return{ok:!1,error:`unknown params: ${o.join(", ")}`};let s=DEFAULT_PATH;if(void 0!==t.path){if("string"!=typeof t.path||""===t.path.trim())return{ok:!1,error:"path must be a non-empty string"};s=t.path.trim()}let n=!0;if(void 0!==t.upload){if("boolean"!=typeof t.upload)return{ok:!1,error:"upload must be a boolean"};n=t.upload}return{ok:!0,path:s,upload:n}}function errorResult(e){const t={ok:!1,error:e};return{...t,content:[{type:"text",text:e}],output:t,result:t,details:t,isError:!0}}
@@ -1 +1 @@
1
- import{outstandingDeliverables,rememberSessionWorkspace,stashFinalizeAttachments}from"./delivery-ledger.js";import{getUploadDeps,uploadLocalFile}from"./upload-file.js";const MAX_FINALIZE_UPLOADS=5;export async function fileDeliveryFinalizeDecision(e){if(e.stopHookActive||!e.sessionKey)return;e.cwd&&rememberSessionWorkspace(e.sessionKey,e.cwd);const s=getUploadDeps();if(!s)return;const i=outstandingDeliverables(e.sessionKey).slice(0,5),o=[];for(const e of i)try{const i=await uploadLocalFile(e,s.gatewayUrl,s.keys);o.push({uri:i.uri,name:i.name,...i.mimeType?{mimeType:i.mimeType}:{}})}catch(i){s.logger?.warn?.(`[file-delivery] finalize upload failed path=${e}: ${i instanceof Error?i.message:String(i)}`)}stashFinalizeAttachments(e.sessionKey,o)}
1
+ import{outstandingDeliverables,rememberSessionWorkspace,stashFinalizeAttachments}from"./delivery-ledger.js";import{getUploadDeps,uploadLocalFile}from"./upload-file.js";const MAX_FINALIZE_UPLOADS=5;export async function fileDeliveryFinalizeDecision(e){if(e.stopHookActive||!e.sessionKey)return;e.cwd&&rememberSessionWorkspace(e.sessionKey,e.cwd);const s=getUploadDeps();if(!s)return;const i=outstandingDeliverables(e.sessionKey).slice(0,5),o=[];for(const e of i)try{const i=await uploadLocalFile(e,s.gateway);o.push({uri:i.uri,name:i.name,...i.mimeType?{mimeType:i.mimeType}:{}})}catch(i){s.logger?.warn?.(`[file-delivery] finalize upload failed path=${e}: ${i instanceof Error?i.message:String(i)}`)}stashFinalizeAttachments(e.sessionKey,o)}
@@ -1 +1 @@
1
- import{basename}from"node:path";import{BEEOS_UPLOAD_TOOL_NAME}from"./tool.js";import{BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME}from"./desktop-screenshot-tool.js";import{extractUploadResourceLinks}from"./extract-upload-uris.js";import{resolveUploadToolResultForEnrichment,writeEnrichmentCache}from"./result-cache.js";import{tryExtractLocalFiles}from"./local-file-extractors.js";import{getUploadDeps,uploadLocalFile}from"./upload-file.js";const UPLOAD_TOOL_NAMES=new Set([BEEOS_UPLOAD_TOOL_NAME,BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME]);export function isUploadArtifactToolName(e){if(!e)return!1;if(UPLOAD_TOOL_NAMES.has(e))return!0;const t=e.toLowerCase();return t.includes("beeos_upload")||t.includes("beeos upload file")||"beeos file upload"===t||t.includes("beeos_desktop_screenshot")||t.includes("desktop screenshot")}export function isRemoteOrPlatformMediaUri(e){const t=e.trim();return!!t&&(!!t.startsWith("beeos-file://")||(!(!t.startsWith("http://")&&!t.startsWith("https://"))||!!t.startsWith("data:")))}export function isLocalMediaPath(e){const t=e.trim();return!(!t||isRemoteOrPlatformMediaUri(t))&&(!!t.startsWith("file://")||!!t.startsWith("/"))}function filePathFromMediaUri(e){const t=e.trim();if(t.startsWith("file://"))try{return decodeURIComponent(new URL(t).pathname)}catch{return t.slice(7)}return t}function linkNameFromUri(e){if(e.startsWith("beeos-file://"))return e.slice(13)||"file";try{const t=e.includes("://")?new URL(e).pathname:e;return basename(t)||"file"}catch{return"file"}}function pushUnique(e,t,o){o.uri&&!t.has(o.uri)&&(t.add(o.uri),e.push(o))}export async function resolveToolArtifactLinks(e){const t=[],o=new Set,a=getUploadDeps(),i=a?.logger;let r=!1;if(isUploadArtifactToolName(e.toolName))try{const a=await resolveUploadToolResultForEnrichment(e.toolCallId,e.toolName===BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME?BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME:BEEOS_UPLOAD_TOOL_NAME);if(null!=a)for(const e of extractUploadResourceLinks(a))pushUnique(t,o,e)}catch(t){i?.warn?.(`[enrich] resolveUploadToolResultForEnrichment failed toolCallId=${e.toolCallId}: ${t instanceof Error?t.message:String(t)}`)}if(a){const l=new Set,s=tryExtractLocalFiles({toolCallId:e.toolCallId,toolName:e.toolName,rawResult:e.rawResult,rawText:e.rawText,params:e.params,cwd:e.cwd});for(const n of s)if(!l.has(n.filePath))try{i?.debug?.(`[enrich] Uploading local file ${n.filePath} for toolCallId=${e.toolCallId}`);const s=await uploadLocalFile(n.filePath,a.gatewayUrl,a.keys,{fileNameOverride:n.suggestedName});i?.info?.(`[enrich] Uploaded: fileId=${s.fileId} toolCallId=${e.toolCallId}`),l.add(n.filePath),pushUnique(t,o,{uri:s.uri,name:s.name,...s.mimeType?{mimeType:s.mimeType}:{}}),r=!0}catch(e){i?.warn?.(`[enrich] Upload failed for ${n.filePath}: ${e instanceof Error?e.message:String(e)}, skipping`)}for(const s of e.payloadMediaUrls??[]){if(!isLocalMediaPath(s))continue;const n=filePathFromMediaUri(s);if(!l.has(n))try{i?.debug?.(`[enrich] Uploading payload media path ${n} for toolCallId=${e.toolCallId}`);const s=await uploadLocalFile(n,a.gatewayUrl,a.keys);i?.info?.(`[enrich] Uploaded payload media: fileId=${s.fileId} toolCallId=${e.toolCallId}`),l.add(n),pushUnique(t,o,{uri:s.uri,name:s.name,...s.mimeType?{mimeType:s.mimeType}:{}}),r=!0}catch(e){i?.warn?.(`[enrich] Payload media upload failed for ${n}: ${e instanceof Error?e.message:String(e)}, skipping`)}}}for(const a of e.payloadMediaUrls??[])isRemoteOrPlatformMediaUri(a)&&pushUnique(t,o,{uri:a.trim(),name:linkNameFromUri(a.trim())});if(t.length>0&&(r||t.some(e=>e.uri.startsWith("beeos-file://")))){const o=t.map(e=>({uri:e.uri,name:e.name,...e.mimeType?{mimeType:e.mimeType}:{}}));writeEnrichmentCache(e.toolCallId,o).catch(t=>{i?.warn?.(`[enrich] Cache write failed for toolCallId=${e.toolCallId}: ${t instanceof Error?t.message:String(t)}`)})}return t}
1
+ import{basename}from"node:path";import{BEEOS_UPLOAD_TOOL_NAME}from"./tool.js";import{BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME}from"./desktop-screenshot-tool.js";import{extractUploadResourceLinks}from"./extract-upload-uris.js";import{resolveUploadToolResultForEnrichment,writeEnrichmentCache}from"./result-cache.js";import{tryExtractLocalFiles}from"./local-file-extractors.js";import{getUploadDeps,uploadLocalFile}from"./upload-file.js";const UPLOAD_TOOL_NAMES=new Set([BEEOS_UPLOAD_TOOL_NAME,BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME]);export function isUploadArtifactToolName(e){if(!e)return!1;if(UPLOAD_TOOL_NAMES.has(e))return!0;const t=e.toLowerCase();return t.includes("beeos_upload")||t.includes("beeos upload file")||"beeos file upload"===t||t.includes("beeos_desktop_screenshot")||t.includes("desktop screenshot")}export function isRemoteOrPlatformMediaUri(e){const t=e.trim();return!!t&&(!!t.startsWith("beeos-file://")||(!(!t.startsWith("http://")&&!t.startsWith("https://"))||!!t.startsWith("data:")))}export function isLocalMediaPath(e){const t=e.trim();return!(!t||isRemoteOrPlatformMediaUri(t))&&(!!t.startsWith("file://")||!!t.startsWith("/"))}function filePathFromMediaUri(e){const t=e.trim();if(t.startsWith("file://"))try{return decodeURIComponent(new URL(t).pathname)}catch{return t.slice(7)}return t}function linkNameFromUri(e){if(e.startsWith("beeos-file://"))return e.slice(13)||"file";try{const t=e.includes("://")?new URL(e).pathname:e;return basename(t)||"file"}catch{return"file"}}function pushUnique(e,t,o){o.uri&&!t.has(o.uri)&&(t.add(o.uri),e.push(o))}export async function resolveToolArtifactLinks(e){const t=[],o=new Set,a=getUploadDeps(),i=a?.logger;let r=!1;if(isUploadArtifactToolName(e.toolName))try{const a=await resolveUploadToolResultForEnrichment(e.toolCallId,e.toolName===BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME?BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME:BEEOS_UPLOAD_TOOL_NAME);if(null!=a)for(const e of extractUploadResourceLinks(a))pushUnique(t,o,e)}catch(t){i?.warn?.(`[enrich] resolveUploadToolResultForEnrichment failed toolCallId=${e.toolCallId}: ${t instanceof Error?t.message:String(t)}`)}if(a){const l=new Set,s=tryExtractLocalFiles({toolCallId:e.toolCallId,toolName:e.toolName,rawResult:e.rawResult,rawText:e.rawText,params:e.params,cwd:e.cwd});for(const n of s)if(!l.has(n.filePath))try{i?.debug?.(`[enrich] Uploading local file ${n.filePath} for toolCallId=${e.toolCallId}`);const s=await uploadLocalFile(n.filePath,a.gateway,{fileNameOverride:n.suggestedName});i?.info?.(`[enrich] Uploaded: fileId=${s.fileId} toolCallId=${e.toolCallId}`),l.add(n.filePath),pushUnique(t,o,{uri:s.uri,name:s.name,...s.mimeType?{mimeType:s.mimeType}:{}}),r=!0}catch(e){i?.warn?.(`[enrich] Upload failed for ${n.filePath}: ${e instanceof Error?e.message:String(e)}, skipping`)}for(const s of e.payloadMediaUrls??[]){if(!isLocalMediaPath(s))continue;const n=filePathFromMediaUri(s);if(!l.has(n))try{i?.debug?.(`[enrich] Uploading payload media path ${n} for toolCallId=${e.toolCallId}`);const s=await uploadLocalFile(n,a.gateway);i?.info?.(`[enrich] Uploaded payload media: fileId=${s.fileId} toolCallId=${e.toolCallId}`),l.add(n),pushUnique(t,o,{uri:s.uri,name:s.name,...s.mimeType?{mimeType:s.mimeType}:{}}),r=!0}catch(e){i?.warn?.(`[enrich] Payload media upload failed for ${n}: ${e instanceof Error?e.message:String(e)}, skipping`)}}}for(const a of e.payloadMediaUrls??[])isRemoteOrPlatformMediaUri(a)&&pushUnique(t,o,{uri:a.trim(),name:linkNameFromUri(a.trim())});if(t.length>0&&(r||t.some(e=>e.uri.startsWith("beeos-file://")))){const o=t.map(e=>({uri:e.uri,name:e.name,...e.mimeType?{mimeType:e.mimeType}:{}}));writeEnrichmentCache(e.toolCallId,o).catch(t=>{i?.warn?.(`[enrich] Cache write failed for toolCallId=${e.toolCallId}: ${t instanceof Error?t.message:String(t)}`)})}return t}
@@ -1 +1 @@
1
- import{constants}from"node:fs";import{access,stat}from"node:fs/promises";import{uploadLocalFile}from"./upload-file.js";import{isBeeosFileUri}from"../files/beeos-file-uri.js";export const BEEOS_UPLOAD_TOOL_NAME="beeos_upload_file";export const BEEOS_UPLOAD_TOOL_DESCRIPTION="Upload 1-5 local files from this machine to the user via the BeeOS platform. Accepts only local filesystem paths; never pass beeos-file:// URIs because they are already BeeOS platform resources. If the call succeeds, the files are already delivered to the user — do not use any other tool to send them again. Upload modified deliverables again even if the same path was uploaded earlier; unchanged contents may reuse an existing platform file. Any file type is accepted: text, images, documents, PDFs, archives, binaries.";export const BEEOS_UPLOAD_TOOL_SCHEMA={title:"BeeOS file upload",type:"object",description:BEEOS_UPLOAD_TOOL_DESCRIPTION,additionalProperties:!1,required:["paths"],properties:{paths:{type:"array",minItems:1,maxItems:5,description:"Local filesystem paths (1-5). Absolute or workspace-relative. Do not pass beeos-file:// URIs.",items:{type:"string",minLength:1,description:"Single local filesystem path, not a beeos-file:// URI."}}}};const MAX_PATHS=5,REQUEST_TIMEOUT_MS=12e4,MAX_CONCURRENCY=3,BEEOS_FILE_URI_UPLOAD_ERROR="beeos-file:// is already a BeeOS platform file URI, not a local path. Do not upload it; display it directly.";async function runWithConcurrency(e,t){const r=new Array(e.length);let a=0;async function o(){for(;a<e.length;){const t=a++;r[t]=await e[t]()}}const s=[];for(let r=0;r<Math.min(t,e.length);r++)s.push(o());return await Promise.all(s),r}async function validateFiles(e){return Promise.all(e.map(async e=>{try{await access(e,constants.R_OK);return(await stat(e)).isFile()?{path:e,ok:!0}:{path:e,ok:!1,error:"not a regular file"}}catch(t){const r=t.code;let a;return a="ENOENT"===r?"file not found":"ENOTDIR"===r?"path component is not a directory":"EACCES"===r?"permission denied":t instanceof Error?t.message:String(t),{path:e,ok:!1,error:a}}}))}export async function executeUpload(e,t,r,a){const o=parseParams(e);if(!o.ok)return errorResult(o.error);if(!t.agentGatewayUrl)return errorResult("agentGatewayUrl not configured — file upload requires Agent Gateway access");if(!r)return errorResult("agent key pair not available — cannot sign upload requests");const s=t.agentGatewayUrl,i=o.paths,n=(await validateFiles(i)).find(e=>!e.ok);if(n)return errorResult(`${n.path}: ${n.error}`);const l=[],p=i.map(e=>async()=>{try{return await uploadSingleFile(e,s,r,a)}catch(t){if(a?.aborted)throw t;return l.push(`${e}: ${t instanceof Error?t.message:String(t)}`),null}}),c=(await runWithConcurrency(p,3)).filter(e=>null!==e);if(0===c.length)return errorResult(`All uploads failed: ${l.join("; ")}`);const u=c.map(e=>({uri:`beeos-file://${e.fileId}`,name:e.fileName,mimeType:e.mimeType,fileId:e.fileId})),f=c.length===i.length?`Uploaded ${c.length} file(s): ${u.map(e=>e.name).join(", ")}`:`Uploaded ${c.length}/${i.length} file(s): ${u.map(e=>e.name).join(", ")}. Failed: ${l.join("; ")}`,m={ok:!0,files:u};return{...m,content:[{type:"text",text:f},...u.map(e=>({type:"resource_link",uri:e.uri,name:e.name,mimeType:e.mimeType}))],output:m,result:m,details:m,isError:!1}}async function uploadSingleFile(e,t,r,a){const o=await uploadLocalFile(e,t,r,{signal:a,timeoutMs:12e4});return{fileId:o.fileId,downloadUrl:"",fileName:o.name,mimeType:o.mimeType,size:o.size}}function parseParams(e){if(!e||"object"!=typeof e)return{ok:!1,error:"params must be an object"};const t=e;if(Object.keys(t).filter(e=>"paths"!==e).length>0)return{ok:!1,error:"only paths is allowed"};if(!Array.isArray(t.paths))return{ok:!1,error:"paths must be an array"};if(t.paths.length<1)return{ok:!1,error:"paths must contain at least 1 item"};if(t.paths.length>5)return{ok:!1,error:"paths must contain no more than 5 items"};const r=[];for(let e=0;e<t.paths.length;e++){const a=t.paths[e];if("string"!=typeof a||""===a.trim())return{ok:!1,error:`paths[${e}] must be a non-empty string`};const o=a.trim();if(isBeeosFileUri(o))return{ok:!1,error:BEEOS_FILE_URI_UPLOAD_ERROR};r.push(o)}return{ok:!0,paths:r}}function errorResult(e){const t={ok:!1,error:e};return{...t,content:[{type:"text",text:e}],output:t,result:t,details:t,isError:!0}}
1
+ import{constants}from"node:fs";import{access,stat}from"node:fs/promises";import{uploadLocalFile,NativeOutputFilesError}from"./upload-file.js";import{isBeeosFileUri}from"../files/beeos-file-uri.js";export const BEEOS_UPLOAD_TOOL_NAME="beeos_upload_file";export const BEEOS_UPLOAD_TOOL_DESCRIPTION="Upload 1-5 local files from this machine to the user via the BeeOS platform. This is the only way to deliver a file to the user: whenever you produce or modify a file the user asked for, call this tool with its path. Writing the file to disk or printing it through a shell command does not deliver it. Accepts only local filesystem paths; never pass beeos-file:// URIs because they are already BeeOS platform resources. If the call succeeds, the files are already delivered to the user — do not use any other tool to send them again. Upload modified deliverables again even if the same path was uploaded earlier; unchanged contents may reuse an existing platform file. Any file type is accepted: text, images, documents, PDFs, archives, binaries.";export const BEEOS_UPLOAD_TOOL_SCHEMA={title:"BeeOS file upload",type:"object",description:BEEOS_UPLOAD_TOOL_DESCRIPTION,additionalProperties:!1,required:["paths"],properties:{paths:{type:"array",minItems:1,maxItems:5,description:"Local filesystem paths (1-5). Absolute or workspace-relative. Do not pass beeos-file:// URIs.",items:{type:"string",minLength:1,description:"Single local filesystem path, not a beeos-file:// URI."}}}};const MAX_PATHS=5;export const REQUEST_TIMEOUT_MS=12e4;const MAX_CONCURRENCY=3,BEEOS_FILE_URI_UPLOAD_ERROR="beeos-file:// is already a BeeOS platform file URI, not a local path. Do not upload it; display it directly.";async function runWithConcurrency(e,t){const r=new Array(e.length);let a=0;async function o(){for(;a<e.length;){const t=a++;r[t]=await e[t]()}}const i=[];for(let r=0;r<Math.min(t,e.length);r++)i.push(o());return await Promise.all(i),r}async function validateFiles(e){return Promise.all(e.map(async e=>{try{await access(e,constants.R_OK);return(await stat(e)).isFile()?{path:e,ok:!0}:{path:e,ok:!1,error:"not a regular file"}}catch(t){const r=t.code;let a;return a="ENOENT"===r?"file not found":"ENOTDIR"===r?"path component is not a directory":"EACCES"===r?"permission denied":t instanceof Error?t.message:String(t),{path:e,ok:!1,error:a}}}))}export async function executeUpload(e,t,r,a,o){const i=parseParams(e);if(!i.ok)return errorResult(i.error);if(!t&&!a)return errorResult("Agent Gateway client unavailable — file upload requires agentGatewayUrl and a key pair");const s=i.paths,n=(await validateFiles(s)).find(e=>!e.ok);if(n)return errorResult(`${n.path}: ${n.error}`);const l=[],c=s.map((e,i)=>async()=>{try{if(a){const t=await a(e,i);return{fileId:t.fileId,downloadUrl:"",fileName:t.name,mimeType:t.mimeType,size:t.size}}return await uploadSingleFile(e,t,r)}catch(t){if(r?.aborted)throw t;const{category:s,detail:n}=classifyUploadFailure(t,Boolean(a));return o?.warn?.(`[beeos_upload_file] upload failed index=${i} native=${Boolean(a)} category=${s} ${n}`),l.push(a?t instanceof NativeOutputFilesError?t.message:"native output Files transport or local read failed":`${e}: ${t instanceof Error?t.message:String(t)}`),null}}),p=(await runWithConcurrency(c,3)).filter(e=>null!==e);if(0===p.length)return errorResult(`All uploads failed: ${l.join("; ")}`);const u=p.map(e=>({uri:`beeos-file://${e.fileId}`,name:e.fileName,mimeType:e.mimeType,fileId:e.fileId})),f=p.length===s.length?`Uploaded ${p.length} file(s): ${u.map(e=>e.name).join(", ")}`:`Uploaded ${p.length}/${s.length} file(s): ${u.map(e=>e.name).join(", ")}. Failed: ${l.join("; ")}`,m={ok:!0,files:u};return{...m,content:[{type:"text",text:f},...u.map(e=>({type:"resource_link",uri:e.uri,name:e.name,mimeType:e.mimeType}))],output:m,result:m,details:m,isError:!1}}async function uploadSingleFile(e,t,r){const a=await uploadLocalFile(e,t,{signal:r,timeoutMs:12e4});return{fileId:a.fileId,downloadUrl:"",fileName:a.name,mimeType:a.mimeType,size:a.size}}function parseParams(e){if(!e||"object"!=typeof e)return{ok:!1,error:"params must be an object"};const t=e;if(Object.keys(t).filter(e=>"paths"!==e).length>0)return{ok:!1,error:"only paths is allowed"};if(!Array.isArray(t.paths))return{ok:!1,error:"paths must be an array"};if(t.paths.length<1)return{ok:!1,error:"paths must contain at least 1 item"};if(t.paths.length>5)return{ok:!1,error:"paths must contain no more than 5 items"};const r=[];for(let e=0;e<t.paths.length;e++){const a=t.paths[e];if("string"!=typeof a||""===a.trim())return{ok:!1,error:`paths[${e}] must be a non-empty string`};const o=a.trim();if(isBeeosFileUri(o))return{ok:!1,error:BEEOS_FILE_URI_UPLOAD_ERROR};r.push(o)}return{ok:!0,paths:r}}function classifyUploadFailure(e,t){const r=e instanceof Error?e.message:String(e),a=e instanceof Error&&e.cause instanceof Error?` cause=${e.cause.message}`:"";if(e instanceof NativeOutputFilesError)return{category:e.category,detail:`${e.detail??""} message=${r}`.trim()};if(e instanceof DOMException&&("AbortError"===e.name||"TimeoutError"===e.name))return{category:"aborted",detail:`name=${e.name} message=${r}`};if(e instanceof TypeError)return{category:"transport_rejected",detail:`message=${r}${a}`};const o=e?.code;return"string"==typeof o?{category:"local_read_failed",detail:`code=${o} message=${r}`}:{category:t?"attempt_or_lease_fenced":"unclassified",detail:`message=${r}${a}`}}function errorResult(e){const t={ok:!1,error:e};return{...t,content:[{type:"text",text:e}],output:t,result:t,details:t,isError:!0}}
@@ -1 +1 @@
1
- import{access,constants,readFile,stat}from"node:fs/promises";import{createHash}from"node:crypto";import{basename,extname,resolve}from"node:path";import{agentFetch}from"../agent-auth.js";import{noteUploadedDeliverable}from"./delivery-ledger.js";const DEFAULT_TIMEOUT_MS=3e4,UPLOAD_REUSE_TTL_MS=18e5,MAX_REUSED_UPLOADS=256,completedUploads=new Map;let _deps=null;export function setUploadDeps(e){_deps=e}export function getUploadDeps(){return _deps}export async function uploadLocalFile(e,t,a,r){await access(e,constants.R_OK);if(!(await stat(e)).isFile())throw new Error("not a regular file");const o=basename(e),s=r?.fileNameOverride??o,n=inferMimeType(s),i=await readFile(e);r?.signal?.throwIfAborted();const c=createHash("sha256").update(i).digest("hex"),p=JSON.stringify([t,Buffer.from(a.publicKey).toString("base64"),resolve(e),s,c]),l=Date.now();for(const[e,t]of completedUploads)t.expiresAt<=l&&completedUploads.delete(e);const d=completedUploads.get(p);if(d)return noteUploadedDeliverable(e),{...d.result};const m=AbortSignal.timeout(r?.timeoutMs??3e4),u=r?.signal?AbortSignal.any([r.signal,m]):m,f=`${t}/api/v1/agent/files`,g=await agentFetch(f+"/presign",a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileName:s,mimeType:n}),signal:u});if(!g.ok){const e=await g.text().catch(()=>g.statusText);throw new Error(`presign ${g.status}: ${e}`)}const x=await g.json(),w=await fetch(x.uploadUrl,{method:"PUT",headers:{"Content-Type":n},body:new Blob([i],{type:n}),signal:u});if(!w.ok)throw new Error(`S3 PUT failed: ${w.status}`);const v=await agentFetch(f+"/confirm",a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileId:x.fileId}),signal:u});if(!v.ok){const e=await v.text().catch(()=>v.statusText);throw new Error(`confirm ${v.status}: ${e}`)}const h=await v.json(),y={fileId:h.fileId,uri:`beeos-file://${h.fileId}`,name:h.fileName||s,mimeType:h.mimeType||n,size:h.size||i.byteLength};if(!y.fileId)throw new Error("confirm returned no fileId");return completedUploads.size>=256&&completedUploads.delete(completedUploads.keys().next().value),completedUploads.set(p,{result:y,expiresAt:Date.now()+18e5}),noteUploadedDeliverable(e),{...y}}function inferMimeType(e){switch(extname(e).toLowerCase()){case".txt":return"text/plain";case".md":return"text/markdown";case".json":return"application/json";case".html":return"text/html";case".css":return"text/css";case".js":case".mjs":case".cjs":return"text/javascript";case".ts":return"text/x.typescript";case".tsx":case".jsx":return"text/jsx";case".xml":return"application/xml";case".yaml":case".yml":return"application/yaml";case".toml":return"application/toml";case".pdf":return"application/pdf";case".doc":return"application/msword";case".docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case".xls":return"application/vnd.ms-excel";case".xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case".ppt":return"application/vnd.ms-powerpoint";case".pptx":return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case".rtf":return"application/rtf";case".odt":return"application/vnd.oasis.opendocument.text";case".ods":return"application/vnd.oasis.opendocument.spreadsheet";case".odp":return"application/vnd.oasis.opendocument.presentation";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";case".mp4":return"video/mp4";case".mov":return"video/quicktime";case".webm":return"video/webm";case".mkv":return"video/x-matroska";case".avi":return"video/x-msvideo";case".m4v":return"video/x-m4v";case".mp3":return"audio/mpeg";case".wav":return"audio/wav";case".flac":return"audio/flac";case".aac":return"audio/aac";case".ogg":return"audio/ogg";case".m4a":return"audio/mp4";case".csv":return"text/csv";case".zip":return"application/zip";case".tar":return"application/x-tar";case".gz":case".tgz":return"application/gzip";default:return"application/octet-stream"}}
1
+ import{access,constants,readFile,stat}from"node:fs/promises";import{request as httpsRequest}from"node:https";import{createHash}from"node:crypto";import{basename,extname,resolve}from"node:path";import{HarnessProtocolError,RuntimeLeaseHttp,RuntimeOperationFiles,putPresignedUpload}from"@beeos-ai/cloud-harness-sdk";import{noteUploadedDeliverable}from"./delivery-ledger.js";const DEFAULT_TIMEOUT_MS=3e4,UPLOAD_REUSE_TTL_MS=18e5,MAX_REUSED_UPLOADS=256,completedUploads=new Map;let claimedCloudRuntimeInstanceId,_deps=null;export function setClaimedCloudRuntimeInstanceId(e){claimedCloudRuntimeInstanceId=e}export function setUploadDeps(e){_deps=e}export function getUploadDeps(){return _deps}export async function uploadLocalFile(e,t,r){if(void 0!==claimedCloudRuntimeInstanceId)throw new Error("native output file trusted tool capability required");await access(e,constants.R_OK);if(!(await stat(e)).isFile())throw new Error("not a regular file");const i=basename(e),a=r?.fileNameOverride??i,s=inferMimeType(a),n=await readFile(e);r?.signal?.throwIfAborted();const o=createHash("sha256").update(n).digest("hex"),p=JSON.stringify([t.baseUrl.origin,resolve(e),a,o]),d=Date.now();for(const[e,t]of completedUploads)t.expiresAt<=d&&completedUploads.delete(e);const l=completedUploads.get(p);if(l)return noteUploadedDeliverable(e),{...l.result};const c=AbortSignal.timeout(r?.timeoutMs??3e4),u=r?.signal?AbortSignal.any([r.signal,c]):c,m=await t.files.upload({fileName:a,mimeType:s,data:n,signal:u}),f={fileId:m.fileId,uri:m.uri,name:m.fileName,mimeType:m.mimeType,size:n.byteLength};if(!f.fileId)throw new Error("confirm returned no fileId");return completedUploads.size>=256&&completedUploads.delete(completedUploads.keys().next().value),completedUploads.set(p,{result:f,expiresAt:Date.now()+18e5}),noteUploadedDeliverable(e),{...f}}export class NativeOutputFilesError extends Error{category;detail;constructor(e,t,r){super(e),this.category=t,this.detail=r,this.name="NativeOutputFilesError"}}export async function uploadNativeOutputFile(e,t,r,i,a,s){r.assertAttempt(),await access(e,constants.R_OK);const n=await stat(e);if(!n.isFile()||n.size<=0||n.size>104857600)throw new Error("native output file size invalid");const o=await readFile(e);if(r.assertAttempt(),o.byteLength!==n.size)throw new Error("native output file changed while reading");const p=basename(e),d=inferMimeType(p),l=createHash("sha256").update(o).digest("hex"),c=createHash("sha256").update("beeos/native-output-file/v1\0"+r.operationId+"\0"+r.toolCallId+"\0"+i).digest("hex"),u=new URL(t);if(!["http:","https:"].includes(u.protocol)||u.username||u.password||"/"!==u.pathname||u.search||u.hash)throw new Error("native output Files origin invalid");const m=AbortSignal.any([r.signal,AbortSignal.timeout(s??3e4),...a?[a]:[]]),f={requestMessageId:r.requestMessageId,paramsHash:r.paramsHash,activeRunRegistrationId:r.activeRunRegistrationId,idempotencyKey:c},h=e=>!!e&&"object"==typeof e&&!Array.isArray(e),g=new RuntimeOperationFiles(new RuntimeLeaseHttp({origin:u.origin})),w=async(e,t)=>{r.assertAttempt();const i={runtimeLeaseCredential:r.getLease().runtimeLeaseCredential},a={...f,...t};let s;try{s="presign"===e?await g.presignOutput(i,r.operationId,a,m):await g.confirmOutput(i,r.operationId,a,m)}catch(t){if(t instanceof Error&&"runtime lease response origin changed"===t.message)throw new NativeOutputFilesError("native output Files response origin changed","control_response_origin",`stage=${e}`);if(!(t instanceof HarnessProtocolError))throw t;let r;const i=t.status??0;if(t.body)try{const e=JSON.parse(t.body);h(e)&&h(e.error)&&"string"==typeof e.error.code&&/^[A-Za-z0-9_.:-]{1,128}$/.test(e.error.code)&&(r=e.error.code)}catch(t){if(!(t instanceof SyntaxError))throw new NativeOutputFilesError("native output Files error decode failed","control_error_decode",`stage=${e} http_status=${i}`)}throw new NativeOutputFilesError("native output Files "+e+" failed ("+i+(r?","+r:"")+")","control_http_error",`stage=${e} http_status=${i} code=${r??"none"}`)}if(r.assertAttempt(),"string"==typeof s||void 0===s)throw new SyntaxError("native output Files response is not JSON");if(!h(n=s)||n.operationId!==r.operationId||n.requestMessageId!==f.requestMessageId||n.paramsHash!==f.paramsHash||n.activeRunRegistrationId!==f.activeRunRegistrationId)throw new NativeOutputFilesError("native output Files response binding invalid","control_response_binding",`stage=${e}`);var n;return s},y=await w("presign",{filename:p,content_type:d,size_bytes:o.byteLength,checksum_sha256:l}),v=y.upload,_=y.transferPolicy;if(!h(v)||!h(_)||"string"!=typeof _.allowedOrigin||"upload"!==v.direction||"PUT"!==v.http_method||"string"!=typeof v.file_id||!v.file_id||"string"!=typeof v.url||"string"!=typeof v.expires_at||!Number.isFinite(Date.parse(v.expires_at))||Date.parse(v.expires_at)<=Date.now()||v.content_type!==d||v.size_bytes!==o.byteLength||v.checksum_sha256!==l||!h(v.required_headers)||Object.values(v.required_headers).some(e=>"string"!=typeof e))throw new NativeOutputFilesError("native output Files transfer descriptor invalid","transfer_descriptor_invalid",descriptorDefect(v,_,d,o.byteLength,l));const b=new URL(v.url),x=new URL(_.allowedOrigin);if("https:"!==b.protocol||b.username||b.password||b.hash||"https:"!==x.protocol||x.username||x.password||"/"!==x.pathname||x.search||x.hash||x.origin!==_.allowedOrigin||b.origin!==x.origin)throw new NativeOutputFilesError("native output Files transfer origin invalid","transfer_origin_invalid",`target_matches_allowed=${b.origin===x.origin}`);r.assertAttempt();const I=v.required_headers,O=(await putPresignedUpload({url:b.toString(),allowedOrigin:x.origin,body:o,requiredHeaders:I,signal:m,fetchImpl:()=>putRequiredHeaders(b,I,o,m)})).status;if(r.assertAttempt(),O<200||O>=300)throw new NativeOutputFilesError("native output Files PUT failed ("+O+")","put_rejected",`http_status=${O} bytes=${o.byteLength} headers=${Object.keys(I).join(",")}`);let E;try{E=await w("confirm",{fileId:v.file_id,checksumSha256:l})}catch(e){if(r.assertAttempt(),m.throwIfAborted(),!(e instanceof TypeError||e instanceof SyntaxError))throw e;E=await w("confirm",{fileId:v.file_id,checksumSha256:l})}if(E.fileId!==v.file_id||E.fileName!==p||E.mimeType!==d||E.size!==o.byteLength)throw new NativeOutputFilesError("native output Files ready metadata mismatch","ready_metadata_mismatch",`fileId=${E.fileId===v.file_id} fileName=${E.fileName===p} mimeType=${E.mimeType===d} size=${E.size===o.byteLength}`);r.assertAttempt();const F={fileId:v.file_id,uri:"beeos-file://"+v.file_id,name:p,mimeType:d,size:o.byteLength};return noteUploadedDeliverable(e),F}function putRequiredHeaders(e,t,r,i){const a=Object.keys(t).find(e=>"content-length"===e.toLowerCase());if(void 0!==a&&t[a]!==String(r.byteLength))throw new NativeOutputFilesError("native output Files transfer descriptor invalid","transfer_descriptor_invalid",`field=required_headers.content-length bytes=${r.byteLength}`);return new Promise((a,s)=>{const n=e=>{s(e instanceof Error&&"AbortError"===e.name?e:new TypeError("fetch failed",{cause:e}))},o=httpsRequest(e,{method:"PUT",headers:t,signal:i},e=>{e.on("error",n),e.resume(),e.on("end",()=>a(new Response(null,{status:e.statusCode??0})))});o.on("error",n),o.end(r)})}function descriptorDefect(e,t,r,i,a){const s=e=>!!e&&"object"==typeof e&&!Array.isArray(e);if(!s(e))return"upload=absent";if(!s(t)||"string"!=typeof t.allowedOrigin)return"transferPolicy.allowedOrigin=invalid";const n=[["direction","upload"===e.direction],["http_method","PUT"===e.http_method],["file_id","string"==typeof e.file_id&&e.file_id.length>0],["url","string"==typeof e.url],["expires_at","string"==typeof e.expires_at&&Number.isFinite(Date.parse(e.expires_at))&&Date.parse(e.expires_at)>Date.now()],["content_type",e.content_type===r],["size_bytes",e.size_bytes===i],["checksum_sha256",e.checksum_sha256===a],["required_headers",s(e.required_headers)&&Object.values(e.required_headers).every(e=>"string"==typeof e)]];return`field=${n.find(([,e])=>!e)?.[0]??"none"} bytes=${i}`}function inferMimeType(e){switch(extname(e).toLowerCase()){case".txt":return"text/plain";case".md":return"text/markdown";case".json":return"application/json";case".html":return"text/html";case".css":return"text/css";case".js":case".mjs":case".cjs":return"text/javascript";case".ts":return"text/x.typescript";case".tsx":case".jsx":return"text/jsx";case".xml":return"application/xml";case".yaml":case".yml":return"application/yaml";case".toml":return"application/toml";case".pdf":return"application/pdf";case".doc":return"application/msword";case".docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case".xls":return"application/vnd.ms-excel";case".xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case".ppt":return"application/vnd.ms-powerpoint";case".pptx":return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case".rtf":return"application/rtf";case".odt":return"application/vnd.oasis.opendocument.text";case".ods":return"application/vnd.oasis.opendocument.spreadsheet";case".odp":return"application/vnd.oasis.opendocument.presentation";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";case".mp4":return"video/mp4";case".mov":return"video/quicktime";case".webm":return"video/webm";case".mkv":return"video/x-matroska";case".avi":return"video/x-msvideo";case".m4v":return"video/x-m4v";case".mp3":return"audio/mpeg";case".wav":return"audio/wav";case".flac":return"audio/flac";case".aac":return"audio/aac";case".ogg":return"audio/ogg";case".m4a":return"audio/mp4";case".csv":return"text/csv";case".zip":return"application/zip";case".tar":return"application/x-tar";case".gz":case".tgz":return"application/gzip";default:return"application/octet-stream"}}
@@ -18,9 +18,22 @@
18
18
  "beeos_discover_agents",
19
19
  "beeos_call_agent",
20
20
  "beeos_get_task",
21
+ "beeos_automation_create",
22
+ "beeos_automation_create_webhook",
23
+ "beeos_automation_capabilities",
24
+ "beeos_automation_preflight",
25
+ "beeos_automation_list",
26
+ "beeos_automation_get",
27
+ "beeos_automation_run",
28
+ "beeos_automation_runs",
29
+ "beeos_automation_get_run",
21
30
  "cron_toggle",
22
31
  "cron_run",
23
- "cron_delete"
32
+ "cron_delete",
33
+ "list_connectors",
34
+ "search_actions",
35
+ "get_action_guide",
36
+ "execute_action"
24
37
  ],
25
38
  "imageGenerationProviders": [
26
39
  "arouter"
@@ -71,7 +84,12 @@
71
84
  "service": {
72
85
  "type": "string",
73
86
  "description": "Service type for Bridge registration (default: acp)",
74
- "enum": ["acp", "screen", "desktop", "shell"]
87
+ "enum": [
88
+ "acp",
89
+ "screen",
90
+ "desktop",
91
+ "shell"
92
+ ]
75
93
  },
76
94
  "mode": {
77
95
  "type": "string",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "beeos-claw",
3
- "version": "0.6.63-cloud.0",
3
+ "version": "0.6.63-cloud.10",
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>",
@@ -65,11 +65,12 @@
65
65
  "test:watch": "vitest"
66
66
  },
67
67
  "dependencies": {
68
- "@beeos-ai/beeos-types": "4.4.2-beta.2",
68
+ "@beeos-ai/beeos-types": "4.4.2-cloud.3",
69
69
  "@beeos-ai/bridge-client": "^0.1.0",
70
+ "@beeos-ai/cloud-harness-sdk": "1.0.0-cloud.6",
70
71
  "@beeos-ai/message-sdk": "2.0.16",
71
72
  "@modelcontextprotocol/sdk": "^1.29.0",
72
- "adm-zip": "^0.6.0",
73
+ "adm-zip": "0.6.1",
73
74
  "ws": "^8.18.0"
74
75
  },
75
76
  "devDependencies": {
@@ -87,5 +88,5 @@
87
88
  "fast-uri": ">=3.1.4",
88
89
  "brace-expansion": ">=5.0.9"
89
90
  },
90
- "gitHead": "a21e630651689bfe0cfd846a9c97a2681b3249b8"
91
+ "gitHead": "c929a8951708b211355eba4a59bcb670e4da3c74"
91
92
  }
@@ -4,18 +4,18 @@
4
4
  "hashAlgorithm": "SHA-256",
5
5
  "canonicalTypes": {
6
6
  "package": "@beeos-ai/beeos-types",
7
- "version": "4.4.2-beta.2",
7
+ "version": "4.4.2-cloud.3",
8
8
  "runtimeRpcContractRevision": "2026-07-14.3",
9
- "runtimeMethodManifestRawSHA256": "2af68ff555d4a4aa3c7b19a285e48a3df2ef9b43aa618ffddabbebc6e4280162",
10
- "runtimeMethodManifestJcsSHA256": "d5db2c5e7c78cee73e5672a3c18a8e56179b28888f6fbb660d98ec021ca9de9b"
9
+ "runtimeMethodManifestRawSHA256": "f75832c57a18ca614e946a3b1d194828df76d600907f378efe28633df94146fc",
10
+ "runtimeMethodManifestJcsSHA256": "2e58dbc13b8bef2491b95f89920945cb905085828b2fa7a4d4f621624971b186"
11
11
  },
12
12
  "artifacts": [
13
13
  {
14
14
  "name": "runtime-parity-manifest",
15
15
  "path": "openapi/runtime-parity-manifest-v1.json",
16
16
  "revision": "beeos.runtime-parity.v1.1.0",
17
- "rawSHA256": "7028b5a0dd85ee78d7df0690d2ef13ef2118acb08a1c8f718d3e9f08da8f8404",
18
- "jcsSHA256": "d464594fe15a1657c805c8829d676a4c93aec5c43e020f3b1fae21f4c9453ca7"
17
+ "rawSHA256": "f1030e7bf2084f584d558c22b9bffde0f823d6950c696a6f0571adaffcdbcee0",
18
+ "jcsSHA256": "c98ed2aa822b29530cb02badd51654f2766f1dc0ff2c53b660be6431b1f23747"
19
19
  },
20
20
  {
21
21
  "name": "runtime-message-channel",
@@ -1 +0,0 @@
1
- import*as crypto from"node:crypto";import*as fs from"node:fs";import*as path from"node:path";export const EMPTY_BODY_SHA256="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";const ED25519_PKCS8_PREFIX=Buffer.from("302e020100300506032b657004220420","hex");function wrapPrivateKey(e){return 32===e.length?Buffer.concat([ED25519_PKCS8_PREFIX,Buffer.from(e)]):Buffer.from(e)}const ED25519_SPKI_PREFIX=Buffer.from("302a300506032b6570032100","hex");function derivePublicKey(e){const r=crypto.createPrivateKey({key:wrapPrivateKey(e),format:"der",type:"pkcs8"}),t=crypto.createPublicKey(r).export({type:"spki",format:"der"});return 44===t.length?new Uint8Array(t.subarray(12)):new Uint8Array(t)}export function loadAgentKeyPair(e){if(!fs.existsSync(e))return generateAgentKeyPair(e);const r=fs.readFileSync(e,"utf-8").trim();try{const e=JSON.parse(r);if(e.publicKey&&e.privateKey)return{publicKey:new Uint8Array(Buffer.from(e.publicKey,"base64")),privateKey:new Uint8Array(Buffer.from(e.privateKey,"base64"))}}catch{}const t=new Uint8Array(Buffer.from(r,"base64"));if(32===t.length)return{publicKey:derivePublicKey(t),privateKey:t};throw new Error(`Invalid key file format at ${e}`)}function generateAgentKeyPair(e){const r=crypto.generateKeyPairSync("ed25519",{publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}}),t=r.publicKey,n=r.privateKey,o=new Uint8Array(44===t.length?t.subarray(12):t),a=new Uint8Array(48===n.length?n.subarray(16):n),i=path.dirname(e);return fs.existsSync(i)||fs.mkdirSync(i,{recursive:!0}),fs.writeFileSync(e,JSON.stringify({publicKey:Buffer.from(o).toString("base64"),privateKey:Buffer.from(a).toString("base64")},null,2),{mode:384}),{publicKey:o,privateKey:a}}export function signAgentMessage(e,r){const t=crypto.createPrivateKey({key:wrapPrivateKey(r),format:"der",type:"pkcs8"});return new Uint8Array(crypto.sign(null,Buffer.from(e),t))}export function bodyHashHex(e){const r=null==e?Buffer.alloc(0):"string"==typeof e?Buffer.from(e,"utf8"):Buffer.from(e);return crypto.createHash("sha256").update(r).digest("hex")}export function agentAuthHeaders(e,r,t,n){const o=Math.floor(Date.now()/1e3).toString(),a=crypto.randomUUID(),i=bodyHashHex(n),f=signAgentMessage(`${e.toUpperCase()}|${r}||${i}|${o}|${a}`,t.privateKey);return{"X-Agent-Public-Key":Buffer.from(t.publicKey).toString("base64"),"X-Agent-Signature":Buffer.from(f).toString("base64"),"X-Agent-Timestamp":o,"X-Agent-Nonce":a}}export function agentBoundAuthHeaders(e,r,t,n){return agentAuthHeaders(e,r,n,t)}export async function agentFetch(e,r,t){const n="string"==typeof e?new URL(e):e,o=t?.method?.toUpperCase()??"GET",a=decodeURIComponent(n.pathname);let i;if(void 0!==t?.body&&null!==t.body){if(!("string"==typeof t.body||t.body instanceof Uint8Array))throw new Error("agent-authenticated request body must be string or Uint8Array for exact signing");i=t.body}const f=agentAuthHeaders(o,a,r,i),s=new Headers(t?.headers);for(const[e,r]of Object.entries(f))s.set(e,r);s.delete("X-Agent-Body-SHA256");const c=await fetch(n,{...t,method:o,headers:s,redirect:"error"});return assertFixedOrigin(n,c),c}export async function agentBoundFetch(e,r,t){if(""!==("string"==typeof e?new URL(e):e).search)throw new Error("body-bound agent authority routes forbid query parameters");return agentFetch(e,r,t)}function assertFixedOrigin(e,r){if(r.url&&new URL(r.url).origin!==e.origin)throw new Error("agent-authenticated response origin changed")}
@@ -1 +0,0 @@
1
- export async function discoverBridgeFromGW(o,n,r){try{const i=r?`?region=${encodeURIComponent(r)}`:"",e=await n(`${o}/api/v1/bridge/config${i}`,{method:"GET"});if(e.ok){const o=await e.json();if(o.url)return{url:o.url,region:o.region}}}catch{}}
@@ -1 +0,0 @@
1
- import{canonicalizeJcs}from"@beeos-ai/beeos-types/runtime";const GRANT_ISSUER="beeos-gateway",BOUNDARY_ISSUER="message-service";export class AgentGatewayRuntimeAttemptAuthorizationClient{options;constructor(e){this.options=e}async authorize(e){if(!sameLeaseFence(e.lease,e.fence)||e.request.payload.instanceId!==e.lease.instanceId)return{status:"fenced"};const t="start",n=JSON.stringify({executionGrantRef:e.request.payload.executionGrantRef,operationId:e.request.operationId,requestMessageId:e.request.messageId,method:e.request.payload.request.method,paramsHash:e.request.payload.paramsHash,runtimeLeaseCredential:e.lease.runtimeLeaseCredential,fence:e.fence,journalAttestationHash:e.journal.journalAttestationHash,journalRevisionBeforeAttempt:e.journal.journalRevisionBeforeAttempt,preparedEntryHash:e.journal.preparedEntryHash,executionMode:t}),a=await this.options.boundAgentFetch(new URL(this.options.authorizationUrl),{method:"POST",headers:{"content-type":"application/json"},body:n});if(401===a.status||403===a.status)return{status:"fenced"};if(!a.ok)throw new Error(`Agent Gateway runtime authorization failed (${a.status})`);const o=await a.json();if(isTerminalAuthorization(o))return{status:o.status};if(!isAuthorizedResponse(o))return{status:"invalid"};if(o.operationId!==e.request.operationId||o.requestMessageId!==e.request.messageId||o.method!==e.request.payload.request.method||o.paramsHash!==e.request.payload.paramsHash||canonicalizeJcs(o.command)!==canonicalizeJcs(e.request.payload.command))return{status:"invalid"};await this.options.verifier.refresh();let i=this.options.verifier.verifyAndDecodeGrant(o.runtimeExecutionGrant),r=this.options.verifier.verifyAndDecodeBoundary(o.executionBoundaryAssertion);if(i&&r||(await this.options.verifier.refresh(!0),i=this.options.verifier.verifyAndDecodeGrant(o.runtimeExecutionGrant),r=this.options.verifier.verifyAndDecodeBoundary(o.executionBoundaryAssertion)),!i||!r||o.executionBoundaryId!==r.claims.executionBoundaryId||o.executionBoundaryId!==r.claims.jti)return{status:"invalid"};const s=invocationContext(e.request,e.fence,i.claims,t,this.options.messageServicePublisherIdentityId??BOUNDARY_ISSUER,Math.floor((this.options.now??Date.now)()/1e3));if(!s)return{status:"invalid"};const d={grant:{header:i.header,claims:i.claims,grantJwt:o.runtimeExecutionGrant},boundary:{header:r.header,claims:r.claims,assertionJwt:o.executionBoundaryAssertion}};return{status:"authorized",attempt:{command:o.command,validationContext:s,authorization:d,derivationContext:{invocation:s,boundaryIssuer:BOUNDARY_ISSUER,boundarySubject:e.request.payload.instanceId,nowEpochSeconds:s.nowEpochSeconds,localJournalRevision:e.journal.journalRevisionBeforeAttempt,localPreparedEntryHash:e.journal.preparedEntryHash},executionBoundaryId:o.executionBoundaryId,boundaryAssertionHash:r.compactHash,executionMode:t}}}}function invocationContext(e,t,n,a,o,i){const r=e.payload.command,s={operationId:e.operationId,requestMessageId:e.messageId,dispatchEpoch:r.context.dispatchEpoch,activeRuntimeEpoch:t.runtimeEpoch,requestId:e.payload.request.id,method:e.payload.request.method,gatewayPublisherIdentityId:e.publisherIdentityId,messageServicePublisherIdentityId:o,runtimePublisherIdentityId:t.handlerIdentity,requestHash:e.payload.requestHash,paramsHash:e.payload.paramsHash,commandHash:e.payload.commandHash,idempotencyKeyHash:e.payload.idempotencyKeyHash,idempotencyFingerprint:e.payload.idempotencyFingerprint,callerIntentHash:e.payload.callerIntentHash,callerUserId:e.payload.callerUserId,callerIdentityId:e.payload.callerIdentityId,instanceId:e.payload.instanceId,runtimeInstanceUid:r.context.runtimeInstanceUid,executionGrantRef:e.payload.executionGrantRef,executionGrantHash:e.payload.executionGrantHash,claimDeadlineAt:e.payload.claimDeadlineAt,executionDeadlineAt:e.payload.executionDeadlineAt,grantIssuer:GRANT_ISSUER,grantSubject:t.handlerIdentity,grantJti:`${t.claimId}:${a}`,grantStartDeadline:Math.floor(Date.parse(e.payload.claimDeadlineAt)/1e3),grantExecutionMode:a,nowEpochSeconds:i,activeFence:t};return Number.isSafeInteger(s.grantStartDeadline)?"instance"===n.scope?{...s,scope:"instance",...void 0===n.runtimeAgentUid?{}:{runtimeAgentUid:n.runtimeAgentUid}}:"agent"===n.scope&&"agent"===r.context.scope&&n.platformAgentId&&n.runtimeAgentUid?{...s,scope:"agent",platformAgentId:n.platformAgentId,runtimeAgentUid:n.runtimeAgentUid,runtimeLocalKey:r.context.agent.runtimeLocalKey}:"conversation"===n.scope&&"conversation"===r.context.scope&&n.platformAgentId&&n.runtimeAgentUid&&n.platformConversationId&&n.runtimeConversationUid&&n.runtimeSessionKey?{...s,scope:"conversation",platformAgentId:n.platformAgentId,runtimeAgentUid:n.runtimeAgentUid,platformConversationId:n.platformConversationId,runtimeConversationUid:n.runtimeConversationUid,runtimeSessionKey:n.runtimeSessionKey}:null:null}function sameLeaseFence(e,t){return e.runtimeEpoch===t.runtimeEpoch&&e.handlerIdentity===t.handlerIdentity}function isTerminalAuthorization(e){return isRecord(e)&&1===Object.keys(e).length&&("expired"===e.status||"terminal"===e.status)}function isAuthorizedResponse(e){if(!isRecord(e))return!1;const t=Object.keys(e).sort(),n=["authorizedAt","command","disposition","executionBoundaryAssertion","executionBoundaryId","expiresAt","method","operationId","paramsHash","requestMessageId","runtimeExecutionGrant","status"].sort();return t.length===n.length&&t.every((e,t)=>e===n[t])&&"authorized"===e.status&&("created"===e.disposition||"reused"===e.disposition)&&[e.operationId,e.requestMessageId,e.method,e.paramsHash,e.runtimeExecutionGrant,e.executionBoundaryAssertion,e.executionBoundaryId,e.authorizedAt,e.expiresAt].every(e=>"string"==typeof e&&e.length>0)&&isRecord(e.command)&&Number.isFinite(Date.parse(e.authorizedAt))&&Number.isFinite(Date.parse(e.expiresAt))}function isRecord(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}
@@ -1 +0,0 @@
1
- import{createHash}from"node:crypto";import{RUNTIME_ERROR_DESCRIPTORS,RUNTIME_HASH_DOMAINS,runtimeHashPreimage}from"@beeos-ai/beeos-types/runtime";import{MessageServiceRuntimeClaimHttpAuthority}from"./message-service-runtime-claim-authority.js";const QUERY_METHODS=new Set(["skills/list","models/list","cron/list","cron/status","cron/runs","mcp/list"]),PROJECTION_METHODS=new Set(["agent/create","agent/update","agent/delete","agent/applyTemplate","session/set_model"]);export class MessageServiceRuntimeInvocationHttpAuthority{deps;constructor(e){this.deps=e}claimNext=e=>this.claimAuthority().claimNext(e);claimExact=e=>this.claimAuthority().claimExact(e);renewClaim=e=>this.claimAuthority().renewClaim(e);releaseClaim=e=>this.claimAuthority().releaseClaim(e);authorize=e=>this.deps.authorization.authorize(e);async appendStarted(e){await this.append(e,"runtime_operation_started",{claimedAt:this.now(),leaseExpiresAt:e.claimLeaseExpiresAt,executionMode:e.attempt.executionMode,executionBoundaryId:e.attempt.executionBoundaryId,boundaryAssertionHash:e.attempt.boundaryAssertionHash,...e.attempt.handoffId?{handoffId:e.attempt.handoffId}:{}})}async appendProgress(e){await this.append(e,"runtime_operation_progress",{executionBoundaryId:e.attempt.executionBoundaryId,phase:e.progress.phase,...void 0===e.progress.current?{}:{current:e.progress.current},...void 0===e.progress.total?{}:{total:e.progress.total}})}async commitResult(e){const t=e.request.payload.request.method;if(PROJECTION_METHODS.has(t))throw new Error(`projection-required runtime method is not enabled by this authority: ${t}`);const o=this.now(),a=e.result,s=hash(RUNTIME_HASH_DOMAINS.serviceResult,{method:t,result:a});let r;if(!QUERY_METHODS.has(t)){const s=hash(RUNTIME_HASH_DOMAINS.coreResult,{method:t,result:a}),n={schemaVersion:1,operationId:e.operationId,method:t,coreResultRef:`sha256:${s}`,coreResultHash:s},i={schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,method:t,commandHash:e.request.payload.commandHash,executionBoundaryId:e.attempt.executionBoundaryId,boundaryAssertionHash:e.attempt.boundaryAssertionHash,fence:e.fence,journalRevision:"3",coreResultHash:s,effectRecordHash:hash(RUNTIME_HASH_DOMAINS.effectRecord,n),projection:{state:"not_required"},committedAt:o};r=hash(RUNTIME_HASH_DOMAINS.effectReceipt,i),await this.append(e,"runtime_effect_committed",{executionBoundaryId:e.attempt.executionBoundaryId,committedAt:o,effectReceipt:i,effectReceiptHash:r})}const n={schemaVersion:1,operationId:e.operationId,method:t,outcome:"succeeded",serviceResultRef:`sha256:${s}`,serviceResultHash:s},i={schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,method:t,commandHash:e.request.payload.commandHash,executionBoundaryId:e.attempt.executionBoundaryId,boundaryAssertionHash:e.attempt.boundaryAssertionHash,fence:e.fence,journalRevision:"3",terminalRecordHash:hash(RUNTIME_HASH_DOMAINS.terminalRecord,n),completedAt:o,outcome:"succeeded",serviceResultHash:s,...r?{effectReceiptHash:r}:{}};await this.appendTerminal(e,i,{outcome:"succeeded",response:{jsonrpc:"2.0",id:e.request.payload.request.id,result:a},serviceResultHash:s,terminalAuthority:r?{kind:"effect_receipt",effectReceiptHash:r}:{kind:"query_execution",executionBoundaryId:e.attempt.executionBoundaryId,boundaryAssertionHash:e.attempt.boundaryAssertionHash},completedAt:o})}async commitFailure(e){const t=e.request.payload.request.method,o=this.now(),a=normalizeErrorCode(e.outcome,e.code),s=RUNTIME_ERROR_DESCRIPTORS[a],r="outcome_unknown"===e.outcome?"outcome_unknown":"cancelled"===e.outcome?"cancelled":"expired"===e.outcome?"expired":"failed",n={code:s.jsonRpcCode,message:a,data:{code:a,operationId:e.operationId,effectState:r,retryMode:s.retryMode}},i=hash(RUNTIME_HASH_DOMAINS.terminalRecord,{operationId:e.operationId,method:t,outcome:e.outcome,code:a}),c="outcome_unknown"===e.outcome?{schemaVersion:1,operationId:e.operationId,method:t,outcome:e.outcome,uncertaintyRef:`sha256:${i}`,uncertaintyHash:i}:{schemaVersion:1,operationId:e.operationId,method:t,outcome:e.outcome,errorRef:`sha256:${i}`,errorHash:i},d={schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,method:t,commandHash:e.request.payload.commandHash,executionBoundaryId:e.attempt.executionBoundaryId,boundaryAssertionHash:e.attempt.boundaryAssertionHash,fence:e.fence,journalRevision:"2",terminalRecordHash:hash(RUNTIME_HASH_DOMAINS.terminalRecord,c),completedAt:o},u="outcome_unknown"===e.outcome?{...d,outcome:"outcome_unknown",uncertaintyHash:i}:{...d,outcome:e.outcome,noEffect:!0,errorHash:i},m={jsonrpc:"2.0",id:e.request.payload.request.id,error:n},p=terminalFailurePayload(e.outcome,o,m,e.attempt.executionBoundaryId,e.attempt.boundaryAssertionHash);await this.appendTerminal(e,u,p)}claimAuthority(){return new MessageServiceRuntimeClaimHttpAuthority({messageServiceUrl:this.deps.messageServiceUrl,fetchAuthorized:(e,t)=>this.deps.fetchMessageService(e,t)})}async append(e,t,o){await this.post(e.operationId,{schemaVersion:1,type:t,operationId:e.operationId,conversationId:e.operationId,requestMessageId:e.requestMessageId,dispatchEpoch:e.request.payload.command.context.dispatchEpoch,fence:e.fence,payload:o})}async appendTerminal(e,t,o){await this.post(e.operationId,{schemaVersion:1,type:"runtime_rpc_response",operationId:e.operationId,conversationId:e.operationId,requestMessageId:e.requestMessageId,dispatchEpoch:e.request.payload.command.context.dispatchEpoch,fence:e.fence,payload:o,replyTo:e.requestMessageId,terminalReceipt:t,terminalReceiptHash:hash(RUNTIME_HASH_DOMAINS.terminalReceipt,t)})}async post(e,t){const o=await this.deps.fetchMessageService(new URL(`/api/v1/runtime/operations/${encodeURIComponent(e)}/events`,this.deps.messageServiceUrl),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(201!==o.status)throw new Error(`Message Service runtime event append failed (${o.status})`)}now(){return(this.deps.now??(()=>new Date))().toISOString()}}function hash(e,t){return createHash("sha256").update(runtimeHashPreimage(e,t)).digest("hex")}function normalizeErrorCode(e,t){return"outcome_unknown"===e?"OUTCOME_UNKNOWN":"cancelled"===e?"OPERATION_CANCELLED":"expired"===e?"COMMAND_EXPIRED":t in RUNTIME_ERROR_DESCRIPTORS?t:"RUNTIME_EXECUTION_FAILED"}function terminalFailurePayload(e,t,o,a,s){if("outcome_unknown"===e)return{outcome:e,response:o,terminalAuthority:{kind:"uncertain_effect",executionBoundaryId:a,boundaryAssertionHash:s},completedAt:t};const r={kind:"definitive_no_effect",journalPhase:"prepared",observedAt:t};return"cancelled"===e?{outcome:e,response:o,cancellationEvidence:r,completedAt:t}:"expired"===e?{outcome:e,response:o,expirationEvidence:r,completedAt:t}:{outcome:e,response:o,failureEvidence:r,completedAt:t}}
@@ -1 +0,0 @@
1
- import{createHash,createPublicKey,verify}from"node:crypto";import{validateRuntimeExecutionGrant}from"@beeos-ai/beeos-types/runtime";export class RuntimeJwksVerifier{jwksUrl;fetcher;ttlMs;now;keys=new Map;expiresAt=0;inflight;provenance;keyMaterials=Object.freeze([]);keysetUrl;constructor(e,t=fetch,r=3e5,s=Date.now){this.jwksUrl=e,this.fetcher=t,this.ttlMs=r,this.now=s,this.keysetUrl=new URL(e).toString()}async refresh(e=!1){if(!(!e&&this.keys.size>0&&this.now()<this.expiresAt)){if(this.inflight)return await this.inflight;this.inflight=this.load();try{await this.inflight}finally{this.inflight=void 0}}}hasKid(e){return this.keys.has(e)}trustedKids(){return Object.freeze([...this.keys.keys()].sort())}trustedKeyMaterials(){return this.keyMaterials}documentProvenance(){return this.provenance}verifyAndDecodeGrant(e){const t=this.verifyCompact(e);return t?{header:t.header,claims:t.claims,compactHash:sha256(e)}:null}verifyAndValidateGrant(e,t){const r=this.verifyAndDecodeGrant(e);return r&&0===validateRuntimeExecutionGrant(r.claims,t).length?r:null}verifyAndDecodeBoundary(e){const t=this.verifyCompact(e);return t?{header:t.header,claims:t.claims,compactHash:sha256(e)}:null}async load(){const e=await this.fetcher(this.jwksUrl,{signal:AbortSignal.timeout(1e4),redirect:"error"});if(!e.ok)throw new Error(`JWKS fetch failed: HTTP ${e.status}`);const t=await e.json(),r=new Map,s=[];for(const e of t.keys??[]){if("RSA"!==e.kty||"sig"!==e.use||"RS256"!==e.alg||"string"!=typeof e.kid||!e.kid)continue;if(r.has(e.kid))throw new Error(`JWKS contains duplicate kid: ${e.kid}`);const t=createPublicKey({key:e,format:"jwk"});if((t.asymmetricKeyDetails?.modulusLength??0)<2048)continue;const i=t.export({format:"jwk"});"RSA"===i.kty&&"string"==typeof i.n&&"string"==typeof i.e&&(r.set(e.kid,t),s.push(Object.freeze({jwkThumbprint:sha256(JSON.stringify({e:i.e,kty:"RSA",n:i.n})),spkiSha256:createHash("sha256").update(t.export({format:"der",type:"spki"})).digest("hex")})))}if(0===r.size)throw new Error("JWKS contains no trusted RS256 keys");const i=e.url?new URL(e.url).toString():this.keysetUrl;if(i!==this.keysetUrl)throw new Error("JWKS response provenance URL mismatch");this.keys=r,this.keyMaterials=Object.freeze(s.sort((e,t)=>e.jwkThumbprint.localeCompare(t.jwkThumbprint)||e.spkiSha256.localeCompare(t.spkiSha256))),this.provenance=Object.freeze({sourceUrl:i,etag:e.headers.get("etag")??"",issuer:"string"==typeof t.issuer?t.issuer:"",audience:"string"==typeof t.audience?t.audience:"",purpose:"string"==typeof t.purpose?t.purpose:"",maxClaimTtlSeconds:"number"==typeof t.maxClaimTtlSeconds?t.maxClaimTtlSeconds:Number.NaN}),this.expiresAt=this.now()+this.ttlMs}verifyCompact(e){const t=e.split(".");if(3!==t.length)return null;try{if(!t.every(isCanonicalBase64Url))return null;const e=JSON.parse(decodeBase64Url(t[0]));if("RS256"!==e.alg||"JWT"!==e.typ||"string"!=typeof e.kid)return null;const r=this.keys.get(e.kid);if(!r)return null;const s=Buffer.from(`${t[0]}.${t[1]}`),i=Buffer.from(t[2],"base64url");if(!verify("RSA-SHA256",s,r,i))return null;const n=JSON.parse(decodeBase64Url(t[1]));return null===n||"object"!=typeof n||Array.isArray(n)?null:{header:e,claims:n}}catch{return null}}}function isCanonicalBase64Url(e){if(!e||!/^[A-Za-z0-9_-]+$/.test(e))return!1;return Buffer.from(e,"base64url").toString("base64url")===e}function decodeBase64Url(e){return Buffer.from(e,"base64url").toString("utf8")}function sha256(e){return createHash("sha256").update(e).digest("hex")}
@@ -1 +0,0 @@
1
- import{createHash,randomBytes,sign}from"node:crypto";import{RUNTIME_INTERNAL_API_V1_ROUTE_CONTRACTS,RUNTIME_HASH_DOMAINS,RUNTIME_RPC_PROTOCOL_VERSION,runtimeHashPreimage,runtimeIdentitySignatureMessage,validateRuntimeInternalRegistrationResult}from"@beeos-ai/beeos-types/runtime";import{RuntimeTransportFailurePolicy}from"./runtime-transport-failure-policy.js";export class RuntimeRegistrationLeaseExpiredError extends Error{constructor(){super("Instance authority returned an expired active lease"),this.name="RuntimeRegistrationLeaseExpiredError"}}export class RuntimeRegistrationHandoffRequiredError extends Error{retryAfterMs;constructor(e=65e3){super("Instance authority requires waiting for the active runtime lease to expire"),this.name="RuntimeRegistrationHandoffRequiredError",this.retryAfterMs=e}}export class RuntimeRegistrationOwnerResetRequiredError extends Error{constructor(){super("Instance authority requires owner reset authorization after a journal store change"),this.name="RuntimeRegistrationOwnerResetRequiredError"}}export class RuntimeRegistrationJournalAdvanceRequiredError extends Error{currentJournalGeneration;expectedJournalGeneration;constructor(e){super("Instance authority requires journal generation to advance exactly once after lease expiry"),this.name="RuntimeRegistrationJournalAdvanceRequiredError",this.currentJournalGeneration=e?.currentJournalGeneration,this.expectedJournalGeneration=e?.expectedJournalGeneration}}export class RuntimeRegistrationCoordinator{transport;config;onLeaseLost;now;active=null;timer;expiryTimer;stopped=!1;generation=0;heartbeatTransportFailurePolicy=new RuntimeTransportFailurePolicy;authorityListeners=new Set;constructor(e,t,i,r=Date.now){this.transport=e,this.config=t,this.onLeaseLost=i,this.now=r}get lease(){return!this.active||Date.parse(this.active.leaseExpiresAt)<=this.now()?null:this.active}get canClaimMutations(){return null!==this.lease}get authorityLease(){const e=this.lease;return e?Object.freeze({...e,handlerIdentity:this.config.handlerIdentity}):null}subscribeAuthority(e){return this.authorityListeners.add(e),()=>{this.authorityListeners.delete(e)}}async start(){const e=++this.generation;return this.stopped=!1,await this.registerOnce(e)}async registerOnce(e){if(!this.isCurrent(e))return null;this.timer=void 0,this.active&&(this.clearLeaseExpiry(),this.active=null,this.notifyAuthority());const t={registrationId:this.config.registrationId,handlerIdentity:this.config.handlerIdentity,contractRevision:this.config.contractRevision,runtimeRpcProtocolVersion:RUNTIME_RPC_PROTOCOL_VERSION,runtimeMethods:this.config.runtimeMethods,capabilities:this.config.capabilities,manifestDigest:this.config.manifestDigest,journalStoreId:this.config.journalStoreId,journalGeneration:this.config.journalGeneration};let i;try{i=await this.transport.register(this.signProof("runtime.register",t))}catch(t){if(!this.isCurrent(e))return null;if(t instanceof RuntimeRegistrationLeaseExpiredError||t instanceof RuntimeRegistrationJournalAdvanceRequiredError||t instanceof RuntimeRegistrationOwnerResetRequiredError)return this.onLeaseLost(t instanceof RuntimeRegistrationLeaseExpiredError?"expired":"heartbeat_failed",t),null;this.onLeaseLost("heartbeat_failed",t);const i=t instanceof RuntimeRegistrationHandoffRequiredError?t.retryAfterMs:5e3;return this.scheduleRegistration(i,e),null}return this.isCurrent(e)?"active"!==i.status?("fenced"===i.status?this.onLeaseLost("fenced"):this.scheduleRegistration(i.retryAfterMs,e),null):void 0!==this.config.targetInstanceId&&i.instanceId!==this.config.targetInstanceId?(this.onLeaseLost("fenced",new Error("Instance authority returned a different Cloud instance")),null):(this.active={instanceId:i.instanceId,leaseId:i.leaseId,runtimeEpoch:i.runtimeEpoch,runtimeLeaseCredential:i.runtimeLeaseCredential,leaseExpiresAt:i.leaseExpiresAt},this.heartbeatTransportFailurePolicy.recordSuccess(),this.notifyAuthority(),this.scheduleLeaseExpiry(this.active,e),this.schedule(i.heartbeatIntervalMs,e),this.active):null}stop(){this.generation++,this.stopped=!0,this.timer&&clearTimeout(this.timer),this.expiryTimer&&clearTimeout(this.expiryTimer),this.timer=void 0,this.expiryTimer=void 0,this.active=null,this.notifyAuthority()}schedule(e,t){if(!this.isCurrent(t))return;const i=this.active;i&&(this.timer=setTimeout(()=>{this.sendHeartbeat(e,t,i)},e),this.timer.unref?.())}scheduleRegistration(e,t){this.isCurrent(t)&&(this.timer=setTimeout(()=>{this.registerOnce(t)},e))}async sendHeartbeat(e,t,i){if(!this.isCurrentLease(t,i))return;const r={leaseId:i.leaseId,handlerIdentity:this.config.handlerIdentity,runtimeEpoch:i.runtimeEpoch},s=this.config.getMSConnectionStatus?{...r,msConnectionStatus:this.config.getMSConnectionStatus(i)}:r;try{const r=await this.transport.heartbeat(this.signProof("runtime.heartbeat",s));if(!this.isCurrentLease(t,i))return;if("renewed"!==r.status)return this.heartbeatTransportFailurePolicy.recordSuccess(),this.active=null,this.clearLeaseExpiry(),this.notifyAuthority(),void this.onLeaseLost(r.status);this.heartbeatTransportFailurePolicy.recordSuccess(),this.active={...i,runtimeLeaseCredential:r.runtimeLeaseCredential,leaseExpiresAt:r.leaseExpiresAt},this.notifyAuthority(),this.scheduleLeaseExpiry(this.active,t),this.schedule(e,t)}catch(r){if(!this.isCurrentLease(t,i))return;if(!this.heartbeatTransportFailurePolicy.recordFailure())return void this.schedule(Math.min(e,5e3),t);this.active=null,this.clearLeaseExpiry(),this.notifyAuthority(),this.onLeaseLost("heartbeat_failed",r),this.scheduleRegistration(5e3,t)}}scheduleLeaseExpiry(e,t){this.clearLeaseExpiry();const i=`${e.leaseId}\0${e.runtimeEpoch}\0${e.leaseExpiresAt}`,r=()=>{const s=Date.parse(e.leaseExpiresAt)-this.now();if(s>0)return this.expiryTimer=setTimeout(r,Math.min(2147483647,s)),void this.expiryTimer.unref?.();const n=this.active;this.isCurrentLease(t,e)&&n&&`${n.leaseId}\0${n.runtimeEpoch}\0${n.leaseExpiresAt}`===i&&(this.active=null,this.expiryTimer=void 0,this.notifyAuthority(),this.onLeaseLost("expired"))};r()}clearLeaseExpiry(){this.expiryTimer&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0}isCurrent(e){return!this.stopped&&e===this.generation}isCurrentLease(e,t){return this.isCurrent(e)&&this.active===t}notifyAuthority(){const e=this.authorityLease;for(const t of this.authorityListeners)try{t(e)}catch{}}signProof(e,t){const i=new Date(this.now()).toISOString(),r=randomBytes(18).toString("base64url"),s="runtime.register"===e?RUNTIME_HASH_DOMAINS.registration:RUNTIME_HASH_DOMAINS.heartbeat,n=createHash("sha256").update(runtimeHashPreimage(s,t)).digest("hex"),a=runtimeIdentitySignatureMessage({purpose:e,instanceIdentityKeyId:this.config.instanceIdentityKeyId,targetInstanceId:this.config.targetInstanceId,signedAt:i,nonce:r,payloadHash:n});return{...t,signaturePurpose:e,instanceIdentityKeyId:this.config.instanceIdentityKeyId,signedAt:i,nonce:r,payloadHash:n,...void 0===this.config.targetInstanceId?{}:{targetInstanceId:this.config.targetInstanceId},signature:sign(null,a,this.config.privateKey).toString("base64url")}}}export class InstanceAuthorityRuntimeRegistrationTransport{options;constructor(e){this.options=e}async register(e){if(e.registrationId!==this.options.registrationId)throw new Error("runtime registration id mismatch");const t=await this.post(RUNTIME_INTERNAL_API_V1_ROUTE_CONTRACTS.runtimeRegister.path,e);if("active"===t.status&&Number.isFinite(Date.parse(t.leaseExpiresAt))&&Date.parse(t.leaseExpiresAt)<=Date.now())throw new RuntimeRegistrationLeaseExpiredError;if(validateRuntimeInternalRegistrationResult(t)||"fenced"!==t.status&&(t.journalStoreId!==e.journalStoreId||t.journalGeneration!==e.journalGeneration)||"active"===t.status&&(!t.instanceId||!t.leaseId||!t.runtimeLeaseCredential||!Number.isInteger(t.heartbeatIntervalMs)||!Number.isFinite(Date.parse(t.leaseExpiresAt))||Date.parse(t.leaseExpiresAt)<=Date.now()))throw new Error("Instance authority returned an invalid registration binding");return t}async heartbeat(e){const t=await this.post(RUNTIME_INTERNAL_API_V1_ROUTE_CONTRACTS.runtimeHeartbeat.path.replace("{registrationId}",encodeURIComponent(this.options.registrationId)),e);if(!(t&&["renewed","fenced","expired"].includes(t.status)&&("renewed"!==t.status||t.runtimeLeaseCredential&&Number.isFinite(Date.parse(t.leaseExpiresAt)))))throw new Error("Instance authority returned an invalid heartbeat result");return t}async post(e,t){const i=new URL(e,this.options.agentGatewayUrl),r=await this.options.agentFetch(i,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const e=await r.text().catch(()=>"");if(409===r.status&&i.pathname.endsWith("/runtime/registrations"))throw classifyRuntimeRegistrationConflict(e);throw new Error(`runtime Instance authority request failed (${r.status} ${r.statusText}) ${i.pathname}`+(e?`: ${e.slice(0,240)}`:""))}return await r.json()}}export function classifyRuntimeRegistrationConflict(e){const t=extractConflictMessage(e);if(/journal store change requires owner reset authorization/i.test(t))return new RuntimeRegistrationOwnerResetRequiredError;if(/journal generation must advance exactly once/i.test(t)){const e=t.match(/\bcurrent=(\d+)\b/i)?.[1],i=t.match(/\bexpected=(\d+)\b/i)?.[1];return new RuntimeRegistrationJournalAdvanceRequiredError({currentJournalGeneration:e&&/^[1-9][0-9]*$/.test(e)?e:void 0,expectedJournalGeneration:i&&/^[1-9][0-9]*$/.test(i)?i:void 0})}return/active runtime lease requires explicit handoff/i.test(t)||/waiting for the active runtime lease/i.test(t),new RuntimeRegistrationHandoffRequiredError}function extractConflictMessage(e){if(!e)return"";try{const t=JSON.parse(e),i=t.error?.message;if("string"==typeof i)return i;if("string"==typeof t.message)return t.message}catch{}return e}
@@ -1 +0,0 @@
1
- export class RuntimeTransportFailurePolicy{threshold;consecutiveFailures=0;constructor(e=3){if(this.threshold=e,!Number.isSafeInteger(e)||e<=0)throw new Error("transport failure threshold must be a positive integer")}recordSuccess(){this.consecutiveFailures=0}recordFailure(){return this.consecutiveFailures+=1,!(this.consecutiveFailures<this.threshold)&&(this.consecutiveFailures=0,!0)}}