beeos-claw 0.6.63-cloud.1 → 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 (78) 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 -1
  8. package/dist/canvas/relay-client.js +1 -1
  9. package/dist/canvas/ws-provider.js +1 -1
  10. package/dist/canvas-orchestrator.js +1 -1
  11. package/dist/chat-envelope.js +1 -0
  12. package/dist/connectors/managed-connector-tools.js +1 -0
  13. package/dist/files/fetch-tool.js +1 -1
  14. package/dist/files/list-tool.js +1 -1
  15. package/dist/im-inbound-handler.js +1 -1
  16. package/dist/im-runtime-dispatch.js +1 -1
  17. package/dist/index.js +1 -1
  18. package/dist/mcp-connector-proxy.js +1 -1
  19. package/dist/media/arouter-config.js +1 -1
  20. package/dist/media/image-provider.js +1 -1
  21. package/dist/media/video-provider.js +1 -1
  22. package/dist/message-client-composition.js +1 -1
  23. package/dist/message-projection-inbound-consumer.js +1 -1
  24. package/dist/runtime/agent-projection-production.js +1 -1
  25. package/dist/runtime/callback-queue.js +1 -1
  26. package/dist/runtime/chat-handler-port.js +1 -0
  27. package/dist/runtime/conversation-title.js +1 -1
  28. package/dist/runtime/core-execution-attempt-context.js +1 -1
  29. package/dist/runtime/im-reply-sink.js +1 -1
  30. package/dist/runtime/message-service-conversation-clear-http-authority.js +1 -1
  31. package/dist/runtime/message-service-conversation-run-boundary.js +1 -1
  32. package/dist/runtime/message-service-cron-delivery-http-authority.js +1 -1
  33. package/dist/runtime/message-service-runtime-authenticated-fetch.js +1 -1
  34. package/dist/runtime/message-service-runtime-claim-authority.js +1 -1
  35. package/dist/runtime/message-service-runtime-message-channel.js +1 -1
  36. package/dist/runtime/message-service-session-model-http-authority.js +1 -1
  37. package/dist/runtime/ms-runtime-message-channel-adapter.js +1 -1
  38. package/dist/runtime/ms-runtime-message-channel-consumer-factory.js +1 -1
  39. package/dist/runtime/ms-runtime-rpc-adapter.js +1 -1
  40. package/dist/runtime/native-cloud-chat-composition.js +1 -0
  41. package/dist/runtime/native-cloud-prompt-bridge.js +1 -0
  42. package/dist/runtime/native-input-files-http.js +1 -0
  43. package/dist/runtime/native-input-files.js +1 -0
  44. package/dist/runtime/native-output-file-attempt.js +1 -0
  45. package/dist/runtime/native-prompt-authority.js +1 -0
  46. package/dist/runtime/native-prompt-preflight.js +1 -0
  47. package/dist/runtime/native-session-new-bridge.js +1 -0
  48. package/dist/runtime/openclaw-session-model.js +1 -0
  49. package/dist/runtime/reply-router.js +1 -1
  50. package/dist/runtime/runtime-error-part.js +1 -0
  51. package/dist/runtime/runtime-local-parity-matrix.js +1 -1
  52. package/dist/runtime/runtime-operation-resource-resolver.js +1 -1
  53. package/dist/runtime/runtime-parity-manifest-digest.js +1 -1
  54. package/dist/runtime/runtime-parity-manifest.js +1 -1
  55. package/dist/runtime/runtime-production-authority.js +1 -1
  56. package/dist/runtime/runtime-registration-identity-store.js +1 -1
  57. package/dist/runtime/runtime-service-contract-compatibility.js +1 -1
  58. package/dist/runtime/runtime-service-production-candidate.js +1 -1
  59. package/dist/runtime/runtime-session-control-service.js +1 -1
  60. package/dist/runtime/runtime-skills-service.js +1 -1
  61. package/dist/runtime/session-new-runtime-delivery-bridge.js +1 -1
  62. package/dist/runtime/write-runtime-failure.js +1 -1
  63. package/dist/terminal/runtime-terminal-outbound-registration.js +1 -1
  64. package/dist/terminal/terminal-lease-bound-bridge-client.js +1 -1
  65. package/dist/upload/desktop-screenshot-tool.js +1 -1
  66. package/dist/upload/finalize-hook.js +1 -1
  67. package/dist/upload/tool-artifact-enrichment.js +1 -1
  68. package/dist/upload/tool.js +1 -1
  69. package/dist/upload/upload-file.js +1 -1
  70. package/openclaw.plugin.json +5 -1
  71. package/package.json +4 -4
  72. package/runtime-service-wire-identity.v1.json +5 -5
  73. package/dist/agent-auth.js +0 -1
  74. package/dist/bridge-discovery.js +0 -1
  75. package/dist/runtime/agent-gateway-runtime-attempt-authorization.js +0 -1
  76. package/dist/runtime/message-service-runtime-invocation-authority.js +0 -1
  77. package/dist/runtime/runtime-jwks-verifier.js +0 -1
  78. package/dist/runtime/split-runtime-authorization-verifier.js +0 -1
@@ -0,0 +1 @@
1
+ const CONNECTOR_TOOL_NAMES=["list_connectors","search_actions","get_action_guide","execute_action"],objectSchema=(t,e)=>({type:"object",additionalProperties:!1,properties:t,...e&&e.length>0?{required:[...e]}:{}}),TOOLS={list_connectors:{description:"List the connectors enabled for this OpenClaw instance.",parameters:objectSchema({})},search_actions:{description:"Search actions exposed by enabled connectors.",parameters:objectSchema({query:{type:"string"},connectorId:{type:"string"},limit:{type:"integer"}})},get_action_guide:{description:"Get the input and output schema for one connector action.",parameters:objectSchema({actionId:{type:"string"}},["actionId"])},execute_action:{description:"Execute one connector action using the credential bound to this instance. For the Weather connector, actionId is wttr.get_weather and input is an object with location.",parameters:objectSchema({actionId:{type:"string"},input:{type:"object"}},["actionId","input"])}};function argumentsOf(t){if(null==t)return{};if("object"!=typeof t||Array.isArray(t))throw new Error("connector tool arguments must be an object");return t}function textFromContent(t){if(!Array.isArray(t))return;const e=t.flatMap(t=>{if(!t||"object"!=typeof t||!("text"in t))return[];const e=t.text;return"string"==typeof e?[e]:[]});return e.length>0?e.join("\n"):void 0}export function readableConnectorResult(t){if(!t||"object"!=typeof t)return{content:JSON.stringify(t)};const e=t;if(void 0!==e.error&&null!==e.error){const t=e.error,n=t&&"object"==typeof t&&"message"in t?String(t.message):JSON.stringify(t);throw new Error(n)}const n="result"in e?e.result:t;if(n&&"object"==typeof n){const t=n;if(!0===t.isError)throw new Error(textFromContent(t.content)||"connector tool failed");if(void 0!==t.structuredContent)return{content:JSON.stringify(t.structuredContent)};const e=textFromContent(t.content);if(void 0!==e)return{content:e}}return{content:"string"==typeof n?n:JSON.stringify(n)}}async function callConnectorTool(t,e,n,o){return readableConnectorResult(await t.connectors.callJson({jsonrpc:"2.0",id:e,method:"tools/call",params:{name:e,arguments:"list_connectors"===e?{}:argumentsOf(n)}},o?{signal:o}:void 0))}export function registerManagedConnectorTools(t,e){if(e)for(const n of CONNECTOR_TOOL_NAMES){const o=TOOLS[n];t.registerTool({name:n,description:o.description,parameters:o.parameters,execute:(t,o,r)=>callConnectorTool(e,n,o,r)})}}
@@ -1 +1 @@
1
- import{mkdir,writeFile}from"node:fs/promises";import{basename,dirname,isAbsolute,resolve as resolvePathFs}from"node:path";import{agentFetch}from"../agent-auth.js";import{isBeeosFileUri,parseBeeosFileUri}from"./beeos-file-uri.js";export const BEEOS_FETCH_FILE_TOOL_NAME="beeos_fetch_file";export const BEEOS_FETCH_FILE_TOOL_DESCRIPTION="Download a file from the user's BeeOS account to the local workspace by its raw fileId (discover fileIds with `beeos_list_files`). Use only when local byte analysis is required; for display, keep the beeos-file:// URI in chat or Canvas. Returns the local path where the file was saved so you can then read or process it. Any file type is supported.";export const BEEOS_FETCH_FILE_TOOL_SCHEMA={title:"BeeOS fetch account file",type:"object",description:BEEOS_FETCH_FILE_TOOL_DESCRIPTION,additionalProperties:!1,required:["fileId"],properties:{fileId:{type:"string",minLength:1,description:"The raw fileId of the account file to download, not a beeos-file:// URI."},destPath:{type:"string",description:"Optional destination path (absolute or workspace-relative). Defaults to the original file name in the current working directory."}}};const REQUEST_TIMEOUT_MS=12e4;export async function executeFetchFile(e,t,r,o){const s=parseParams(e);if(!s.ok)return errorResult(s.error);if(!t.agentGatewayUrl)return errorResult("agentGatewayUrl not configured — fetching account files requires Agent Gateway access");if(!r)return errorResult("agent key pair not available — cannot sign fetch requests");const i=AbortSignal.timeout(12e4),a=o?.signal?AbortSignal.any([o.signal,i]):i,n=`${t.agentGatewayUrl}/api/v1/agent/files/${encodeURIComponent(s.fileId)}/resolve`;let l;try{l=await agentFetch(n,r,{method:"GET",signal:a})}catch(e){return errorResult(`resolve request failed: ${e instanceof Error?e.message:String(e)}`)}if(!l.ok){const e=await l.text().catch(()=>l.statusText);return errorResult(`resolve ${l.status}: ${e}`)}const f=await l.json();if(!f.downloadUrl)return errorResult("resolve returned no download URL");let d;try{d=await fetch(f.downloadUrl,{method:"GET",signal:a})}catch(e){return errorResult(`download failed: ${e instanceof Error?e.message:String(e)}`)}if(!d.ok)return errorResult(`download failed: ${d.status}`);const c=Buffer.from(await d.arrayBuffer()),u=resolveDestPath(s.destPath,f.fileName||s.fileId,o?.resolvePath);try{await mkdir(dirname(u),{recursive:!0}),await writeFile(u,c)}catch(e){return errorResult(`write failed: ${e instanceof Error?e.message:String(e)}`)}const h={ok:!0,path:u,fileName:f.fileName,mimeType:f.mimeType,size:c.byteLength};return{...h,content:[{type:"text",text:`Downloaded ${f.fileName} to ${u} (${c.byteLength}B)`}],output:h,result:h,details:h,isError:!1}}function resolveDestPath(e,t,r){if(e)return isAbsolute(e)?e:r?r(e):resolvePathFs(process.cwd(),e);const o=basename(t)||"download";return r?r(o):resolvePathFs(process.cwd(),o)}function parseParams(e){if(!e||"object"!=typeof e)return{ok:!1,error:"params must be an object"};const t=e,r=new Set(["fileId","destPath"]),o=Object.keys(t).filter(e=>!r.has(e));if(o.length>0)return{ok:!1,error:`unexpected properties: ${o.join(", ")}`};if("string"!=typeof t.fileId||""===t.fileId.trim())return{ok:!1,error:"fileId must be a non-empty string"};const s=t.fileId.trim();if(isBeeosFileUri(s)){const e=parseBeeosFileUri(s);return{ok:!1,error:`fileId must be a raw BeeOS fileId, not a beeos-file:// URI.${e.fileId?` Use raw fileId "${e.fileId}" only when local byte analysis is required.`:" Use a raw fileId only when local byte analysis is required."}`}}let i;if(void 0!==t.destPath){if("string"!=typeof t.destPath||""===t.destPath.trim())return{ok:!1,error:"destPath must be a non-empty string"};i=t.destPath.trim()}return{ok:!0,fileId:s,destPath:i}}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{mkdir,writeFile}from"node:fs/promises";import{basename,dirname,isAbsolute,resolve as resolvePathFs}from"node:path";import{CloudHttpError}from"@beeos-ai/cloud-harness-sdk";import{isBeeosFileUri,parseBeeosFileUri}from"./beeos-file-uri.js";export const BEEOS_FETCH_FILE_TOOL_NAME="beeos_fetch_file";export const BEEOS_FETCH_FILE_TOOL_DESCRIPTION="Download a file from the user's BeeOS account to the local workspace by its raw fileId (discover fileIds with `beeos_list_files`). Use only when local byte analysis is required; for display, keep the beeos-file:// URI in chat or Canvas. Returns the local path where the file was saved so you can then read or process it. Any file type is supported.";export const BEEOS_FETCH_FILE_TOOL_SCHEMA={title:"BeeOS fetch account file",type:"object",description:BEEOS_FETCH_FILE_TOOL_DESCRIPTION,additionalProperties:!1,required:["fileId"],properties:{fileId:{type:"string",minLength:1,description:"The raw fileId of the account file to download, not a beeos-file:// URI."},destPath:{type:"string",description:"Optional destination path (absolute or workspace-relative). Defaults to the original file name in the current working directory."}}};const REQUEST_TIMEOUT_MS=12e4;export async function executeFetchFile(e,t,r){const o=parseParams(e);if(!o.ok)return errorResult(o.error);if(!t)return errorResult("Agent Gateway client unavailable — fetching account files requires agentGatewayUrl and a key pair");const i=AbortSignal.timeout(12e4),s=r?.signal?AbortSignal.any([r.signal,i]):i;let a,n;try{a=await t.files.resolve(o.fileId,{signal:s})}catch(e){return errorResult(e instanceof CloudHttpError?`resolve ${e.status}: ${e.body}`:`resolve request failed: ${e instanceof Error?e.message:String(e)}`)}if(!a.downloadUrl)return errorResult("resolve returned no download URL");try{n=Buffer.from(await t.files.download(a.downloadUrl,s))}catch(e){return errorResult(e instanceof CloudHttpError?`download failed: ${e.status}`:`download failed: ${e instanceof Error?e.message:String(e)}`)}const l=resolveDestPath(o.destPath,a.fileName||o.fileId,r?.resolvePath);try{await mkdir(dirname(l),{recursive:!0}),await writeFile(l,n)}catch(e){return errorResult(`write failed: ${e instanceof Error?e.message:String(e)}`)}const d={ok:!0,path:l,fileName:a.fileName,mimeType:a.mimeType,size:n.byteLength};return{...d,content:[{type:"text",text:`Downloaded ${a.fileName} to ${l} (${n.byteLength}B)`}],output:d,result:d,details:d,isError:!1}}function resolveDestPath(e,t,r){if(e)return isAbsolute(e)?e:r?r(e):resolvePathFs(process.cwd(),e);const o=basename(t)||"download";return r?r(o):resolvePathFs(process.cwd(),o)}function parseParams(e){if(!e||"object"!=typeof e)return{ok:!1,error:"params must be an object"};const t=e,r=new Set(["fileId","destPath"]),o=Object.keys(t).filter(e=>!r.has(e));if(o.length>0)return{ok:!1,error:`unexpected properties: ${o.join(", ")}`};if("string"!=typeof t.fileId||""===t.fileId.trim())return{ok:!1,error:"fileId must be a non-empty string"};const i=t.fileId.trim();if(isBeeosFileUri(i)){const e=parseBeeosFileUri(i);return{ok:!1,error:`fileId must be a raw BeeOS fileId, not a beeos-file:// URI.${e.fileId?` Use raw fileId "${e.fileId}" only when local byte analysis is required.`:" Use a raw fileId only when local byte analysis is required."}`}}let s;if(void 0!==t.destPath){if("string"!=typeof t.destPath||""===t.destPath.trim())return{ok:!1,error:"destPath must be a non-empty string"};s=t.destPath.trim()}return{ok:!0,fileId:i,destPath:s}}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{agentFetch}from"../agent-auth.js";export const BEEOS_LIST_FILES_TOOL_NAME="beeos_list_files";export const BEEOS_LIST_FILES_TOOL_DESCRIPTION="List files stored in the user's BeeOS account, across all their agents/instances. Use this to discover files the user (or another agent) uploaded or generated earlier, then pass a returned fileId to `beeos_fetch_file` to download it locally. Returns fileId, name, mimeType, size, source and originating instance for each file.";export const BEEOS_LIST_FILES_TOOL_SCHEMA={title:"BeeOS list account files",type:"object",description:BEEOS_LIST_FILES_TOOL_DESCRIPTION,additionalProperties:!1,properties:{query:{type:"string",description:"Optional case-insensitive substring to match against file names."},source:{type:"string",enum:["chat_upload","agent_generated","manual"],description:"Optional filter by file origin."},limit:{type:"integer",minimum:1,maximum:200,description:"Maximum number of files to return (default 50)."}}};const DEFAULT_LIMIT=50,MAX_LIMIT=200,REQUEST_TIMEOUT_MS=3e4;export async function executeListFiles(e,t,r,i){const n=parseParams(e);if(!n.ok)return errorResult(n.error);if(!t.agentGatewayUrl)return errorResult("agentGatewayUrl not configured — listing account files requires Agent Gateway access");if(!r)return errorResult("agent key pair not available — cannot sign list requests");const o=AbortSignal.timeout(3e4),s=i?AbortSignal.any([i,o]):o,a=`${t.agentGatewayUrl}/api/v1/agent/files`;let u;try{u=await agentFetch(a,r,{method:"GET",signal:s})}catch(e){return errorResult(`list request failed: ${e instanceof Error?e.message:String(e)}`)}if(!u.ok){const e=await u.text().catch(()=>u.statusText);return errorResult(`list ${u.status}: ${e}`)}let l=(await u.json()).files??[];if(n.source&&(l=l.filter(e=>e.source===n.source)),n.query){const e=n.query.toLowerCase();l=l.filter(t=>t.fileName.toLowerCase().includes(e))}l=l.slice(0,n.limit);const c=0===l.length?"No matching files found in the account.":`Found ${l.length} file(s):\n`+l.map(e=>`- ${e.fileName} (${e.mimeType}, ${e.size}B, ${e.source}${e.instanceName?`, from ${e.instanceName}`:""}) → fileId=${e.fileId}`).join("\n"),f={ok:!0,files:l};return{...f,content:[{type:"text",text:c}],output:f,result:f,details:f,isError:!1}}function parseParams(e){const t=e&&"object"==typeof e?e:{},r=new Set(["query","source","limit"]),i=Object.keys(t).filter(e=>!r.has(e));if(i.length>0)return{ok:!1,error:`unexpected properties: ${i.join(", ")}`};let n,o;if(void 0!==t.query){if("string"!=typeof t.query)return{ok:!1,error:"query must be a string"};n=t.query.trim()||void 0}if(void 0!==t.source){if("string"!=typeof t.source)return{ok:!1,error:"source must be a string"};const e=["chat_upload","agent_generated","manual"];if(!e.includes(t.source))return{ok:!1,error:`source must be one of ${e.join(", ")}`};o=t.source}let s=50;if(void 0!==t.limit){if("number"!=typeof t.limit||!Number.isInteger(t.limit)||t.limit<1)return{ok:!1,error:"limit must be a positive integer"};s=Math.min(t.limit,200)}return{ok:!0,query:n,source:o,limit:s}}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{CloudHttpError}from"@beeos-ai/cloud-harness-sdk";export const BEEOS_LIST_FILES_TOOL_NAME="beeos_list_files";export const BEEOS_LIST_FILES_TOOL_DESCRIPTION="List files stored in the user's BeeOS account, across all their agents/instances. Use this to discover files the user (or another agent) uploaded or generated earlier, then pass a returned fileId to `beeos_fetch_file` to download it locally. Returns fileId, name, mimeType, size, source and originating instance for each file.";export const BEEOS_LIST_FILES_TOOL_SCHEMA={title:"BeeOS list account files",type:"object",description:BEEOS_LIST_FILES_TOOL_DESCRIPTION,additionalProperties:!1,properties:{query:{type:"string",description:"Optional case-insensitive substring to match against file names."},source:{type:"string",enum:["chat_upload","agent_generated","manual"],description:"Optional filter by file origin."},limit:{type:"integer",minimum:1,maximum:200,description:"Maximum number of files to return (default 50)."}}};const DEFAULT_LIMIT=50,MAX_LIMIT=200,REQUEST_TIMEOUT_MS=3e4;export async function executeListFiles(e,t,r){const i=parseParams(e);if(!i.ok)return errorResult(i.error);if(!t)return errorResult("Agent Gateway client unavailable — listing account files requires agentGatewayUrl and a key pair");const o=AbortSignal.timeout(3e4),s=r?AbortSignal.any([r,o]):o;let n;try{n=await t.files.list({signal:s})}catch(e){return errorResult(e instanceof CloudHttpError?`list ${e.status}: ${e.body}`:`list request failed: ${e instanceof Error?e.message:String(e)}`)}let a=n.files??[];if(i.source&&(a=a.filter(e=>e.source===i.source)),i.query){const e=i.query.toLowerCase();a=a.filter(t=>t.fileName.toLowerCase().includes(e))}a=a.slice(0,i.limit);const l=0===a.length?"No matching files found in the account.":`Found ${a.length} file(s):\n`+a.map(e=>`- ${e.fileName} (${e.mimeType}, ${e.size}B, ${e.source}${e.instanceName?`, from ${e.instanceName}`:""}) → fileId=${e.fileId}`).join("\n"),u={ok:!0,files:a};return{...u,content:[{type:"text",text:l}],output:u,result:u,details:u,isError:!1}}function parseParams(e){const t=e&&"object"==typeof e?e:{},r=new Set(["query","source","limit"]),i=Object.keys(t).filter(e=>!r.has(e));if(i.length>0)return{ok:!1,error:`unexpected properties: ${i.join(", ")}`};let o,s;if(void 0!==t.query){if("string"!=typeof t.query)return{ok:!1,error:"query must be a string"};o=t.query.trim()||void 0}if(void 0!==t.source){if("string"!=typeof t.source)return{ok:!1,error:"source must be a string"};const e=["chat_upload","agent_generated","manual"];if(!e.includes(t.source))return{ok:!1,error:`source must be one of ${e.join(", ")}`};s=t.source}let n=50;if(void 0!==t.limit){if("number"!=typeof t.limit||!Number.isInteger(t.limit)||t.limit<1)return{ok:!1,error:"limit must be a positive integer"};n=Math.min(t.limit,200)}return{ok:!0,query:o,source:s,limit: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{extractChatPrompt}from"@beeos-ai/message-sdk/chat-envelope";import{buildMentionInstruction,parseMentionsParam}from"./delegation/mention-resolver.js";import{dispatchImInboundPrompt}from"./im-runtime-dispatch.js";import{promptRunKey}from"./runtime/prompt-run-store.js";import{decodeWake}from"./automation/wake.js";const MAX_PROTOCOL_MARKER_LEN=64,DEFAULT_ORIGIN="im",resolveOrigin=e=>"string"!=typeof e||0===e.length||e.length>64?"im":e,conversationIdFromMessage=e=>"string"==typeof e.conversationId?e.conversationId:"";export const createImInboundHandler=e=>{const{runtime:t,pluginConfig:n,client:o,localServer:a,promptRunStore:s,waitIfExclusive:r,assistantMessageCommitRouter:i,toolResultObservationRouter:c,modelCallObservationRouter:d,sessionMutationCoordinator:l,logger:u,writeObs:p,principalIdOverride:g,dispatch:m=dispatchImInboundPrompt,completeA2ATask:h,activeRunAuthority:f}=e,y=async(e,r)=>{const h=e.content??{},y=inboundFenceMetadata(e),v="string"==typeof y?.target_agent_id?y.target_agent_id:"",_=v?a.resolveLocalAgentId?.(v):void 0;if(!v||!_)return void u.warn?.(`[beeos-claw] ${r.logLabel} target_agent_id=${v||"missing"} not resolvable to a local agent — drop`);const I=_,b=conversationIdFromMessage(e),$="string"==typeof e.id?e.id:"";if(!b||!$)return void u.warn?.(`[beeos-claw] ${r.logLabel} missing channelId/messageId — drop`);const w=g||a.getDefaultPlatformAgent()?.instanceId||"";if(!w)return void u.warn?.(`[beeos-claw] ${r.logLabel} dropped (no principalId resolved, channelId=${b})`);const R="string"==typeof y?.delivery_principal?y.delivery_principal:"";if(R&&R!==w)return void u.info?.(`[beeos-claw] ${r.logLabel} skipped (delivery_principal=${R}, selfPrincipalId=${w}, message_id=${$})`);if("user.auth_grant"===r.resumeKind&&!0!==h.authorized)return void u.warn?.(`[beeos-claw] ${r.logLabel} dropped (authorized grant required, channelId=${b})`);if(!conversationHasOpenPause(o,b,r.pauseType,$))return void u.warn?.(`[beeos-claw] ${r.logLabel} dropped (no unmatched ${r.pauseType}, channelId=${b})`);const K=resumeDispatchInput(r.resumeKind,h);if(!K)return void u.warn?.(`[beeos-claw] ${r.logLabel} dropped (empty resume payload, channelId=${b})`);const C=resumeSessionKey(o,b,I,y);a.ensureImInboundSession(C,b,$,parseMentionsParam(h.mentions));const M=resolveOrigin(y?.protocol);u.debug?.(`[beeos-claw] ${r.logLabel} resume (sessionKey=${C}, channelId=${b}, pause=${r.pauseType})`);const O=e=>{p({component:"plugin",domain:"im_dispatch",name:`im.dispatch.${e.type}`,severity:"dispatch_error"===e.type?"warn":"info",payload:e})};try{await m({runtime:t,pluginConfig:n,prompt:{channelId:b,inboundMessageId:$,selfPrincipalId:w,dispatchInput:K,sessionKey:C},client:o,logger:u,promptRunStore:s,assistantMessageCommitRouter:i,toolResultObservationRouter:c,modelCallObservationRouter:d,sessionMutationCoordinator:l,abortTransport:a,origin:M,onLifecycleEvent:O,activeRunAuthority:f})}catch(e){u.error?.(`[beeos-claw] ${r.logLabel} resume failed channelId=${b} in_reply_to=${$} error_code=runtime_dispatch_failed`)}};return{onChatMessage:async y=>{const v=decodeWake(y);if("invalid"===v.kind||"wake"===v.kind&&!e.automationTurnPolicy?.isReady())return void u.warn?.("[beeos-claw] Automation Wake rejected: invalid contract or unavailable turn policy");const _=y.content??{},I=_.metadata??void 0,b="string"==typeof I?.target_agent_id?I.target_agent_id:"",$=b?a.resolveLocalAgentId?.(b):void 0;if(!b||!$)return void u.warn?.(`[beeos-claw] chat_message target_agent_id=${b||"missing"} not resolvable to a local agent — drop`);const w=extractChatPrompt(y,{source:"chat_message",localAgentId:$});if(!w)return;if(!w.channelId||!w.messageId)return void u.warn?.(`[beeos-claw] chat_message missing channelId/messageId (sessionKey=${w.sessionKey}) — drop`);const R=g||a.getDefaultPlatformAgent()?.instanceId||"";if(!R)return void u.warn?.(`[beeos-claw] chat_message dropped (no principalId resolved, sessionKey=${w.sessionKey})`);const K="string"==typeof I?.delivery_principal?I.delivery_principal:"";if(K&&K!==R)return void u.info?.(`[beeos-claw] chat_message skipped (delivery_principal=${K}, selfPrincipalId=${R}, message_id=${w.messageId})`);const C=parseMentionsParam(_.mentions);a.ensureImInboundSession(w.sessionKey,w.channelId,w.messageId,C);const M=buildMentionInstruction(C),O=M?`${M}\n${w.message}`:w.message,A=resolveOrigin(I?.protocol),P=w.messageId,L="a2a"===A&&h?(e,t)=>h(P,e,t):void 0;u.debug?.(`[beeos-claw] chat_message dispatch (sessionKey=${w.sessionKey}, channelId=${w.channelId}, origin=${A})`);const T=e=>{p({component:"plugin",domain:"im_dispatch",name:`im.dispatch.${e.type}`,severity:"dispatch_error"===e.type?"warn":"info",payload:e})};try{await m({runtime:t,pluginConfig:n,prompt:{channelId:w.channelId,inboundMessageId:w.messageId,requestId:y.requestId,selfPrincipalId:R,dispatchInput:{message:O,attachments:w.files},sessionKey:w.sessionKey},client:o,logger:u,promptRunStore:s,...r?{waitIfExclusive:r}:{},assistantMessageCommitRouter:i,toolResultObservationRouter:c,modelCallObservationRouter:d,sessionMutationCoordinator:l,abortTransport:a,origin:A,onLifecycleEvent:T,...L?{onTerminalResult:L}:{},activeRunAuthority:f,..."wake"===v.kind?{enterTurn:(t,n)=>e.automationTurnPolicy.enter(t,n,v.context)}:{}})}catch(e){u.error?.(`[beeos-claw] chat_message dispatch failed channelId=${w.channelId} in_reply_to=${w.messageId} error_code=runtime_dispatch_failed`)}},onChatCancel:async e=>{const t=e.content??{},n="string"==typeof t.target_message_id?t.target_message_id:"",o="string"==typeof t.reason?t.reason:"unknown";if(!n)return void u.warn?.(`[beeos-claw] chat_cancel dropped (no target_message_id, reason=${o})`);const a=conversationIdFromMessage(e);if(!a)return void u.warn?.(`[beeos-claw] chat_cancel dropped (no conversation identity, target_message_id=${n}, reason=${o})`);const r=`chat_cancel:${o}`,i=await s.abort(promptRunKey(a,n),r);i.ok?u.info?.(`[beeos-claw] chat_cancel accepted (target_message_id=${n}, requestId=${i.requestId}, channelId=${i.channelId}, reason=${o})`):u.info?.(`[beeos-claw] chat_cancel no-op (target_message_id=${n}, reason=${o}, why=${i.reason})`)},onChatContinue:async e=>{await y(e,{logLabel:"user.continue",pauseType:"agent.input_required",resumeKind:"user.continue"})},onChatAuthGrant:async e=>{await y(e,{logLabel:"user.auth_grant",pauseType:"agent.auth_required",resumeKind:"user.auth_grant"})}}};const inboundFenceMetadata=e=>{const t=asRecord(e.content),n=asRecord(t?.metadata);if(hasFenceKeys(n))return n;const o=asRecord(e.metadata);return hasFenceKeys(o)?o:hasFenceKeys(t)?t:n},hasFenceKeys=e=>void 0!==e&&(void 0!==e.delivery_principal||void 0!==e.target_agent_id||void 0!==e.runtime_epoch),asRecord=e=>null===e||"object"!=typeof e||Array.isArray(e)?void 0:e,conversationHasOpenPause=(e,t,n,o)=>{const a="agent.auth_required"===n?"user.auth_grant":"user.continue";let s=!1;for(const r of conversationMessages(e,t))r.id!==o&&(r.type===n&&(s=!0),r.type===a&&(s=!1));return s},conversationMessages=(e,t)=>{const n="function"==typeof e.getSnapshot?e.getSnapshot():void 0,o=n?.messages;return o?Object.values(o).filter(e=>e.conversationId===t).sort(compareSnapshotOrder):[]},compareSnapshotOrder=(e,t)=>{try{const n=BigInt(e.offset)-BigInt(t.offset);if(0n!==n)return n<0n?-1:1}catch{const n=e.offset.localeCompare(t.offset);if(0!==n)return n}return e.id.localeCompare(t.id)},resumeSessionKey=(e,t,n,o)=>{for(const o of conversationMessages(e,t)){if("chat_message"!==o.type)continue;const e=extractChatPrompt(o,{source:"chat_message",localAgentId:n});if(e?.sessionKey)return e.sessionKey}return`agent:${n}:${"string"==typeof o?.protocol&&o.protocol.length>0?o.protocol:"invoke"}:ch-${t}`},resumeDispatchInput=(e,t)=>{if("user.auth_grant"===e){if(!0!==t.authorized)return;return{message:"authorized",resumeKind:e}}const n=continueAnswer(t);if(void 0!==n)return{message:n,resumeKind:e}},continueAnswer=e=>{if("answer"in e)return resumeText(e.answer);if("input"in e)return resumeText(e.input);const t={...e};return delete t.metadata,delete t.delivery_principal,delete t.target_agent_id,delete t.runtime_epoch,delete t.channel_id,0!==Object.keys(t).length?resumeText(t):void 0},resumeText=e=>{if("string"==typeof e)return e.length>0?e:void 0;if("number"==typeof e&&Number.isFinite(e))return String(e);if("boolean"==typeof e)return e?"true":"false";if(null!=e&&"object"==typeof e)try{const t=JSON.stringify(e);return t.length>0&&"{}"!==t?t:void 0}catch{return}};
1
+ import{extractChatPrompt}from"./chat-envelope.js";import{buildMentionInstruction,parseMentionsParam}from"./delegation/mention-resolver.js";import{dispatchImInboundPrompt}from"./im-runtime-dispatch.js";import{promptRunKey}from"./runtime/prompt-run-store.js";import{decodeWake}from"./automation/wake.js";const MAX_PROTOCOL_MARKER_LEN=64,DEFAULT_ORIGIN="im",resolveOrigin=e=>"string"!=typeof e||0===e.length||e.length>64?"im":e,conversationIdFromMessage=e=>"string"==typeof e.conversationId?e.conversationId:"";export const createImInboundHandler=e=>{const{runtime:n,pluginConfig:t,client:o,localServer:a,promptRunStore:s,waitIfExclusive:r,assistantMessageCommitRouter:i,toolResultObservationRouter:d,modelCallObservationRouter:c,sessionMutationCoordinator:l,logger:m,writeObs:p,principalIdOverride:g,dispatch:u=dispatchImInboundPrompt,completeA2ATask:I,activeRunAuthority:h,applyTurnModel:v,restoreTurnModel:_}=e;return{onChatMessage:async y=>{const f=decodeWake(y);if("invalid"===f.kind||"wake"===f.kind&&!e.automationTurnPolicy?.isReady())return void m.warn?.("[beeos-claw] Automation Wake rejected: invalid contract or unavailable turn policy");const b=y.content??{},w=b.metadata??void 0,$="string"==typeof w?.target_agent_id?w.target_agent_id:"",R=$?a.resolveLocalAgentId?.($):void 0;if(!$||!R)return void m.warn?.(`[beeos-claw] chat_message target_agent_id=${$||"missing"} not resolvable to a local agent — drop`);const M=extractChatPrompt(y,{source:"chat_message",localAgentId:R});if(!M)return;if(!M.channelId||!M.messageId)return void m.warn?.(`[beeos-claw] chat_message missing channelId/messageId (sessionKey=${M.sessionKey}) — drop`);const O=g||a.getDefaultPlatformAgent()?.instanceId||"";if(!O)return void m.warn?.(`[beeos-claw] chat_message dropped (no principalId resolved, sessionKey=${M.sessionKey})`);const C="string"==typeof w?.delivery_principal?w.delivery_principal:"";if(C&&C!==O)return void m.info?.(`[beeos-claw] chat_message skipped (delivery_principal=${C}, selfPrincipalId=${O}, message_id=${M.messageId})`);const k=parseMentionsParam(b.mentions);a.ensureImInboundSession(M.sessionKey,M.channelId,M.messageId,k);const K=buildMentionInstruction(k),P=K?`${K}\n${M.message}`:M.message,T=resolveOrigin(w?.protocol),A="string"==typeof w?.modelOverrideId&&w.modelOverrideId.length>0?w.modelOverrideId:void 0,j=M.messageId,x="a2a"===T&&I?(e,n)=>I(j,e,n):void 0;m.debug?.(`[beeos-claw] chat_message dispatch (sessionKey=${M.sessionKey}, channelId=${M.channelId}, origin=${T})`);const E=e=>{p({component:"plugin",domain:"im_dispatch",name:`im.dispatch.${e.type}`,severity:"dispatch_error"===e.type?"warn":"info",payload:e})};try{await u({runtime:n,pluginConfig:t,prompt:{channelId:M.channelId,inboundMessageId:M.messageId,requestId:y.requestId,selfPrincipalId:O,dispatchInput:{message:P,attachments:M.files},sessionKey:M.sessionKey,...A?{modelOverrideId:A}:{}},...v?{applyTurnModel:v}:{},..._?{restoreTurnModel:_}:{},client:o,logger:m,promptRunStore:s,...r?{waitIfExclusive:r}:{},assistantMessageCommitRouter:i,toolResultObservationRouter:d,modelCallObservationRouter:c,sessionMutationCoordinator:l,abortTransport:a,origin:T,onLifecycleEvent:E,...x?{onTerminalResult:x}:{},activeRunAuthority:h,..."wake"===f.kind?{enterTurn:(n,t)=>e.automationTurnPolicy.enter(n,t,f.context)}:{}})}catch(e){m.error?.(`[beeos-claw] chat_message dispatch failed channelId=${M.channelId} in_reply_to=${M.messageId} error_code=runtime_dispatch_failed`)}},onChatCancel:async e=>{const n=e.content??{},t="string"==typeof n.target_message_id?n.target_message_id:"",o="string"==typeof n.reason?n.reason:"unknown";if(!t)return void m.warn?.(`[beeos-claw] chat_cancel dropped (no target_message_id, reason=${o})`);const a=conversationIdFromMessage(e);if(!a)return void m.warn?.(`[beeos-claw] chat_cancel dropped (no conversation identity, target_message_id=${t}, reason=${o})`);const r=`chat_cancel:${o}`,i=await s.abort(promptRunKey(a,t),r);i.ok?m.info?.(`[beeos-claw] chat_cancel accepted (target_message_id=${t}, requestId=${i.requestId}, channelId=${i.channelId}, reason=${o})`):m.info?.(`[beeos-claw] chat_cancel no-op (target_message_id=${t}, reason=${o}, why=${i.reason})`)}}};
@@ -1 +1 @@
1
- import{createHash,randomUUID}from"node:crypto";import{dispatchRuntimeReplyWithRoute,hasRuntimeReplyApi}from"./runtime/reply-router.js";import{createImReplySink}from"./runtime/im-reply-sink.js";import{SerializedCallbackQueue}from"./runtime/callback-queue.js";import{promptRunKey}from"./runtime/prompt-run-store.js";import{classifyAgentRuntimeFailure}from"./runtime/agent-runtime-failure-classifier.js";import{SESSION_RECOVERY_REQUIRED_CODE,SESSION_RECOVERY_REQUIRED_MESSAGE}from"./runtime/session-mutation-coordinator.js";import{interceptAgentRuntimeFailures,messageStopReasonForRuntimeFailure,SESSION_BUSY_PUBLIC_MESSAGE}from"./runtime/im-runtime-failure-policy.js";import{writeRuntimeFailure}from"./runtime/write-runtime-failure.js";import{maybeRenameImConversationTitle}from"./runtime/conversation-title.js";import{logChatLatency}from"./chat-latency.js";const normalizePositiveTimeoutMs=e=>{if("number"!=typeof e||!Number.isFinite(e))return;const n=Math.max(0,Math.trunc(e));return n>0?n:void 0},ABORT_TERMINAL_GRACE_MS=1e4,PRE_RUN_LOOP_PROBE_MS=100,PRE_RUN_LOOP_LAG_LOG_MS=500,formatErrMessage=e=>{if(e instanceof Error)return e.message;if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}},failMessageStream=async(e,n)=>{void 0!==n.body&&e.setBody(n.body),await e.fail(void 0===n.stopReason?void 0:{stopReason:n.stopReason})};export const deterministicReplyMessageId=(e,n,r,t)=>`${e}_${createHash("sha256").update(`${n}:${r}:${t}`).digest("hex").slice(0,32)}`;export const dispatchImInboundPrompt=async e=>{const{runtime:n,prompt:r,client:t,logger:a,promptRunStore:i,assistantMessageCommitRouter:s,toolResultObservationRouter:o,modelCallObservationRouter:c,sessionMutationCoordinator:d,abortTransport:l,activeRunAuthority:u}=e;if(!hasRuntimeReplyApi(n))return a.warn?.(`[im] runtime dispatch skipped reason=reply_api_unavailable channel=${r.channelId} in_reply_to=${r.inboundMessageId}`),e.onLifecycleEvent?.({type:"skipped",reason:"reply_api_unavailable",channelId:r.channelId,inboundMessageId:r.inboundMessageId}),!1;const m=r.requestId??r.inboundMessageId,p=randomUUID(),I=Date.now();logChatLatency(a,"claw.inbound.received",m,I,{origin:e.origin??"im",request_id_source:r.requestId?"realtime_correlation":"message_id_fallback"});const g=e.origin??"im",h={protocol:"im",requestId:m,sessionId:r.sessionKey??"agent:main",sourceMessageId:r.inboundMessageId,chatId:r.channelId,origin:g},y=async(n,t)=>{if(e.onTerminalResult)try{await e.onTerminalResult(n,t)}catch(e){a.warn?.(`[im] terminal business callback failed requestId=${m} channel=${r.channelId} in_reply_to=${r.inboundMessageId}: ${formatErrMessage(e)}`)}},_=promptRunKey(r.channelId,r.inboundMessageId),R=r.sessionKey??"agent:main",f=new AbortController;let b,E,w;const M=new Promise((e,n)=>{w=n});let $;const S=()=>{void 0!==$&&(clearTimeout($),$=void 0)};if(e.waitIfExclusive)try{await e.waitIfExclusive("im_dispatch",f.signal)}catch(n){return a.warn?.(`[im] runtime dispatch aborted waiting for exclusive mutation requestId=${m} channel=${r.channelId} in_reply_to=${r.inboundMessageId}`),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:r.channelId,inboundMessageId:r.inboundMessageId,error:n instanceof Error?n.message:String(n),cause:"abort"}),!1}if(!i.register(_,{requestId:m,channelId:r.channelId,requestCancel:async e=>{if(E??=e,f.abort(e),!b)return{ok:!0};const n=await d.requestCancel(b,l);return n.ok?n.terminalObservation.then(e=>{e.ok||w(new Error(SESSION_RECOVERY_REQUIRED_CODE))}):w(new Error(SESSION_RECOVERY_REQUIRED_CODE)),{ok:n.ok}},startedAt:I,sessionKey:R}))return a.warn?.(`[im] runtime dispatch rejected duplicate inboundMessageId=${r.inboundMessageId} requestId=${m} channel=${r.channelId}`),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:r.channelId,inboundMessageId:r.inboundMessageId,error:"duplicate_inbound_message_id",cause:"abort"}),!1;const v=deterministicReplyMessageId("asst",r.channelId,r.inboundMessageId,r.selfPrincipalId),C={conversationId:r.channelId,clientMessageId:v,idempotencyKey:v,replyTo:e.inReplyTo??r.inboundMessageId,requestId:m,type:"agent_reply",content:{}},q=t.messages.startStream(C);let k,O=!1;try{const e=await q.opened();O="duplicate"===e.outcome,logChatLatency(a,"claw.reply_stream.opened",m,I,{outcome:e.outcome})}catch(n){let s="unconfirmed";try{s=(await t.messages.getEnvelope(r.channelId,v)).state}catch{}return a.warn?.(`[im] runtime reply stream open outcome unknown requestId=${m} channel=${r.channelId} in_reply_to=${r.inboundMessageId} reply_id=${v} reconciled_state=${s}: ${formatErrMessage(n)}; runtime_not_invoked`),e.onLifecycleEvent?.({type:"skipped",reason:"reply_open_outcome_unknown",channelId:r.channelId,inboundMessageId:r.inboundMessageId}),i.unregister(_),!1}if(O)return a.info?.(`[im] runtime dispatch skipped existing deterministic reply requestId=${m} channel=${r.channelId} in_reply_to=${r.inboundMessageId}`),e.onLifecycleEvent?.({type:"skipped",reason:"idempotent_reply_exists",channelId:r.channelId,inboundMessageId:r.inboundMessageId}),i.unregister(_),!1;const L=new SerializedCallbackQueue,T=createImReplySink({stream:q,abortSignal:f.signal,callbackQueue:L,logger:a,requestId:m,startedAtMs:I,runId:p,channelId:r.channelId,inboundMessageId:r.inboundMessageId,origin:g,sessionKey:R,onAgentRunStart:e=>{d.bindRun(b,e),void 0!==k&&logChatLatency(a,"claw.runtime.pre_run_completed",m,k)}}),A=interceptAgentRuntimeFailures(T,"im_runtime",e=>a.warn?.(`[im] runtime failure reply suppressed requestId=${m} channel=${r.channelId} in_reply_to=${r.inboundMessageId} error_code=${e.errorCode}`)),D=A.sink;let F=!1;const U=async e=>{D.dispatcher.markComplete(e);try{await D.dispatcher.waitForIdle()}catch{}},K=()=>{S();const n=normalizePositiveTimeoutMs(e.abortTerminalGraceMs)??1e4;$=setTimeout(()=>{$=void 0,(async()=>{if(q.isTerminated)return;const e=f.signal.reason??E,n="string"==typeof e&&e.startsWith("chat_cancel");if(await U("failure"),!q.isTerminated)try{n?await q.cancel({stopReason:"user_stop"}):await failMessageStream(q,{body:SESSION_RECOVERY_REQUIRED_MESSAGE,stopReason:"error"}),a.warn?.(`[im] abort settlement watchdog terminalized reply requestId=${m} channel=${r.channelId} in_reply_to=${r.inboundMessageId} user_cancel=${n}`)}catch(e){a.warn?.(`[im] abort settlement watchdog terminal write failed requestId=${m} channel=${r.channelId}: ${formatErrMessage(e)}`)}})()},n)};f.signal.aborted?K():f.signal.addEventListener("abort",K,{once:!0});const N=()=>{if(!f.signal.aborted)return;const e=f.signal.reason;throw e instanceof Error?e:new Error(String(e??"runtime dispatch aborted"))};let P,G,Q,j,Y,x,B;const V=async e=>{if(!b)throw new Error("session_mutation_not_acquired");const n=await d.converge(b,e);return n.ok?(P=n.permit,!0):(a.error?.(`[im] session mutation recovery required requestId=${m} sessionKey=${R} reason=${n.recovery.reason}`),G={code:n.recovery.code,reason:n.recovery.reason,sessionKey:n.recovery.sessionKey,operationId:n.recovery.operationId,surface:"message_service",...n.recovery.terminalKind?{terminalKind:n.recovery.terminalKind}:{}},!1)};try{N();const l=d.tryStartInteractive({sessionKey:R,label:"im_chat_message"},"message_service");if(!l.ok){try{await failMessageStream(q,{body:SESSION_BUSY_PUBLIC_MESSAGE,stopReason:"error"})}catch(e){a.warn?.(`[im] session busy terminal write failed channel=${r.channelId} in_reply_to=${r.inboundMessageId}: ${formatErrMessage(e)}`)}return a.warn?.(`[im] session write gate busy sessionKey=${R} channel=${r.channelId} in_reply_to=${r.inboundMessageId} active_operation=${l.activeOperationId??"unknown"}`),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:r.channelId,inboundMessageId:r.inboundMessageId,error:"session_busy",cause:"runtime_error"}),!1}if(b=l.token,logChatLatency(a,"claw.session_gate.acquired",m,I),d.bindRun(b,p),j=s.register(R,T),Y=o.register(R,T),x=c.register(p,{requestId:m,startedAtMs:I,logger:a}),u){const e=d.snapshot(R);Q={runtimeConversationUid:r.channelId,runtimeSessionKey:r.channelId,historyGeneration:u.historyGeneration(r.channelId),targetMessageId:r.inboundMessageId,runtimeRunId:p,activeRunRegistrationId:`im:${e?.operationId??p}`},u.activeRuns.register(Q,async()=>{const e=`chat_cancel:activeRun:${Q.activeRunRegistrationId}`,n=await i.abort(_,e);return n.ok||"already_aborted"===n.reason?"accepted":"terminal_committing"===n.reason||"not_found"===n.reason?"already_terminal":"recovery_required"})}N(),a.info?.(`[im] runtime dispatching requestId=${m} channel=${r.channelId} in_reply_to=${r.inboundMessageId} origin=${g}`),e.onLifecycleEvent?.({type:"dispatch_start",requestId:m,channelId:r.channelId,inboundMessageId:r.inboundMessageId}),k=Date.now(),B=e.enterTurn?.(R,p),logChatLatency(a,"claw.runtime.invoke",m,I);const f=setTimeout(()=>{const e=Date.now()-k-100;e>=500&&logChatLatency(a,"claw.runtime.event_loop_lag",m,k,{lag_ms:e,phase:"pre_run"})},100);f.unref?.();const E=()=>dispatchRuntimeReplyWithRoute({runtime:n,pluginConfig:e.pluginConfig,preparedPrompt:r.dispatchInput,replyRoute:h,replySinks:{im:D},onDispatchInvoked:()=>{F=!0,logChatLatency(a,"claw.runtime.dispatch_returned",m,k)}}),w=B?B.run(E):E(),$=await Promise.race([w,M]).finally(()=>{}),S=A.detectedFailure();if(S)throw new Error(S.diagnosticMessage);if(N(),await U("success"),N(),!i.claimTerminal(_,"completion")){if(N(),"cancelling"===i.phase(_))throw new Error("cancellation in progress");throw new Error("terminal outcome already claimed")}if(!await V("completed"))return await failMessageStream(q,{body:SESSION_RECOVERY_REQUIRED_MESSAGE,stopReason:"error"}).catch(()=>{}),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:r.channelId,inboundMessageId:r.inboundMessageId,error:SESSION_RECOVERY_REQUIRED_CODE,cause:"runtime_error",...G?{recovery:G}:{}}),!1;const v=D.dispatcher.getTerminalErrorText?.();if(void 0!==v){let n=!1;const t=classifyAgentRuntimeFailure({raw:v,source:"im_runtime",runtimeKind:"openclaw"});try{await writeRuntimeFailure(q,{body:t.publicMessage,stopReason:messageStopReasonForRuntimeFailure(t),businessErrorCode:t.businessErrorCode})}catch(e){n=!0,a.warn?.(`[im] runtime reply stream error-terminal write outcome unknown requestId=${m} channel=${r.channelId} in_reply_to=${r.inboundMessageId}: ${formatErrMessage(e)}`)}return u&&Q&&u.activeRuns.markTerminal(Q,"failed"),a.warn?.(`[im] runtime dispatch ended with an error terminal requestId=${m} channel=${r.channelId} in_reply_to=${r.inboundMessageId} counts=${JSON.stringify($.counts)} terminalWriteFailed=${n} elapsed_ms=${Date.now()-I}`),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:r.channelId,inboundMessageId:r.inboundMessageId,error:"runtime_error_terminal_reply",cause:"runtime_error"}),n||await y("",v),!1}let C=!1;try{await q.finalize({stopReason:"end_turn"})}catch(e){C=!0,a.warn?.(`[im] runtime reply stream finalize outcome unknown requestId=${m} channel=${r.channelId} in_reply_to=${r.inboundMessageId}: ${formatErrMessage(e)}`)}u&&Q&&u.activeRuns.markTerminal(Q,"completed");const O={...$.counts,source:T.getSourceCount()};a.info?.(`[im] runtime dispatch completed requestId=${m} channel=${r.channelId} in_reply_to=${r.inboundMessageId} counts=${JSON.stringify(O)} elapsed_ms=${Date.now()-I}`),logChatLatency(a,"claw.turn.terminal",m,I,{outcome:C?"outcome_unknown":"completed",tool_count:O.tool}),e.onLifecycleEvent?.({type:"dispatch_complete",requestId:m,channelId:r.channelId,inboundMessageId:r.inboundMessageId,counts:O,...C?{terminalWriteFailed:!0}:{}});const L=D.dispatcher.getAccumulatedBody?.()??"";C||await y(L,"");const K="string"==typeof r.dispatchInput.message?r.dispatchInput.message:"";return maybeRenameImConversationTitle({client:t,conversationId:r.channelId,question:K,answer:L,logger:a}),!0}catch(n){await U("failure");const t=f.signal.aborted,s=t?f.signal.reason:void 0,o="cancelling"===i.phase(_),c=s??E,d="string"==typeof c&&c.startsWith("chat_cancel");let l="runtime_error";(t||o)&&(l="abort");const p=o||d||t?"cancellation":"completion";if(!i.claimTerminal(_,p)){if(a.warn?.(`[im] terminal claim raced requestId=${m} channel=${r.channelId}; best-effort envelope terminal if still streaming`),!q.isTerminated)try{d?await q.cancel({stopReason:"user_stop"}):await failMessageStream(q,{body:formatErrMessage(n),stopReason:"error"})}catch(e){a.warn?.(`[im] raced terminal write failed requestId=${m}: ${formatErrMessage(e)}`)}throw n}const g=d?"cancelled":"error";if(u&&Q&&u.activeRuns.markTerminal(Q,"cancelled"===g?"cancelled":"failed"),b&&!await V(g))throw d?await q.cancel({stopReason:"user_stop"}).catch(()=>{}):await failMessageStream(q,{body:SESSION_RECOVERY_REQUIRED_MESSAGE,stopReason:"error"}).catch(()=>{}),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:r.channelId,inboundMessageId:r.inboundMessageId,error:SESSION_RECOVERY_REQUIRED_CODE,cause:l,...G?{recovery:G}:{}}),n;const h=classifyAgentRuntimeFailure({raw:n,source:"im_runtime",runtimeKind:"openclaw",requestAborted:d}),R=d?h:A.detectedFailure()??h;let w=!1;try{d?await q.cancel({stopReason:"user_stop"}):await writeRuntimeFailure(q,{body:R.publicMessage,stopReason:messageStopReasonForRuntimeFailure(R),businessErrorCode:R.businessErrorCode})}catch(e){w=!0,a.warn?.(`[im] runtime stream terminal write failed requestId=${m} channel=${r.channelId}: ${formatErrMessage(e)}`)}throw a.warn?.(`[im] runtime dispatch failed requestId=${m} channel=${r.channelId} in_reply_to=${r.inboundMessageId} cause=${l} dispatchInvoked=${F} error_code=${R.errorCode}`),logChatLatency(a,"claw.turn.terminal",m,I,{outcome:l,error_code:R.errorCode}),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:r.channelId,inboundMessageId:r.inboundMessageId,error:R.errorCode,cause:l}),d||w||await y("",R.publicMessage),n}finally{F&&!P||B?.close(),S(),x?.(),Y?.(),j?.(),i.unregister(_),F?P&&d.release(P):d.releaseBeforeRuntime(b)}};
1
+ import{createHash,randomUUID}from"node:crypto";import{dispatchRuntimeReplyWithRoute,hasRuntimeReplyApi}from"./runtime/reply-router.js";import{createImReplySink}from"./runtime/im-reply-sink.js";import{SerializedCallbackQueue}from"./runtime/callback-queue.js";import{promptRunKey}from"./runtime/prompt-run-store.js";import{classifyAgentRuntimeFailure}from"./runtime/agent-runtime-failure-classifier.js";import{SESSION_RECOVERY_REQUIRED_CODE,SESSION_RECOVERY_REQUIRED_MESSAGE}from"./runtime/session-mutation-coordinator.js";import{interceptAgentRuntimeFailures,messageStopReasonForRuntimeFailure,SESSION_BUSY_PUBLIC_MESSAGE}from"./runtime/im-runtime-failure-policy.js";import{writeRuntimeFailure}from"./runtime/write-runtime-failure.js";import{maybeRenameImConversationTitle}from"./runtime/conversation-title.js";import{logChatLatency}from"./chat-latency.js";const normalizePositiveTimeoutMs=e=>{if("number"!=typeof e||!Number.isFinite(e))return;const n=Math.max(0,Math.trunc(e));return n>0?n:void 0},ABORT_TERMINAL_GRACE_MS=1e4,PRE_RUN_LOOP_PROBE_MS=100,PRE_RUN_LOOP_LAG_LOG_MS=500,formatErrMessage=e=>{if(e instanceof Error)return e.message;if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}},failMessageStream=async(e,n)=>{void 0!==n.body&&e.setBody(n.body),await e.fail(void 0===n.stopReason?void 0:{stopReason:n.stopReason})};export const deterministicReplyMessageId=(e,n,t,r)=>`${e}_${createHash("sha256").update(`${n}:${t}:${r}`).digest("hex").slice(0,32)}`;export const dispatchImInboundPrompt=async e=>{const{runtime:n,prompt:t,client:r,logger:a,promptRunStore:i,assistantMessageCommitRouter:o,toolResultObservationRouter:s,modelCallObservationRouter:c,sessionMutationCoordinator:l,abortTransport:d,activeRunAuthority:u}=e;if(!hasRuntimeReplyApi(n))return a.warn?.(`[im] runtime dispatch skipped reason=reply_api_unavailable channel=${t.channelId} in_reply_to=${t.inboundMessageId}`),e.onLifecycleEvent?.({type:"skipped",reason:"reply_api_unavailable",channelId:t.channelId,inboundMessageId:t.inboundMessageId}),!1;const m=t.requestId??t.inboundMessageId,p=e.runtimeRunId??randomUUID();if(!p)throw new Error("runtime run id required");const I=Date.now();logChatLatency(a,"claw.inbound.received",m,I,{origin:e.origin??"im",request_id_source:t.requestId?"realtime_correlation":"message_id_fallback"});const g=e.origin??"im",h={protocol:"im",requestId:m,sessionId:t.sessionKey??"agent:main",sourceMessageId:t.inboundMessageId,chatId:t.channelId,origin:g},y=async(n,r)=>{if(e.onTerminalResult)try{await e.onTerminalResult(n,r)}catch(e){a.warn?.(`[im] terminal business callback failed requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId}: ${formatErrMessage(e)}`)}},_=promptRunKey(t.channelId,t.inboundMessageId),R=t.sessionKey??"agent:main",f=new AbortController;let w,E,b,v,M,S,$,C;const q=new Promise((e,n)=>{C=n});e.onNativeRunCompletion&&q.catch(()=>{});const N=e.onNativeRunCompletion?{chatAbort:(e,n)=>(b=Promise.resolve().then(()=>d.chatAbort(e,n)),b)}:d;let k;const O=()=>{void 0!==k&&(clearTimeout(k),k=void 0)},T=async e=>{if($??=e,f.abort(e),!w)return{ok:!0};const n=await l.requestCancel(w,N);return n.ok?n.terminalObservation.then(e=>{e.ok||C(new Error(SESSION_RECOVERY_REQUIRED_CODE))}):C(new Error(SESSION_RECOVERY_REQUIRED_CODE)),{ok:n.ok}};if(e.waitIfExclusive)try{await e.waitIfExclusive("im_dispatch",f.signal)}catch(n){return a.warn?.(`[im] runtime dispatch aborted waiting for exclusive mutation requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId}`),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:n instanceof Error?n.message:String(n),cause:"abort"}),!1}if(!i.register(_,{requestId:m,channelId:t.channelId,requestCancel:T,startedAt:I,sessionKey:R}))return a.warn?.(`[im] runtime dispatch rejected duplicate inboundMessageId=${t.inboundMessageId} requestId=${m} channel=${t.channelId}`),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:"duplicate_inbound_message_id",cause:"abort"}),!1;const L=e.retainedStream?.id??deterministicReplyMessageId("asst",t.channelId,t.inboundMessageId,t.selfPrincipalId),A={conversationId:t.channelId,clientMessageId:L,idempotencyKey:L,replyTo:e.inReplyTo??t.inboundMessageId,requestId:m,type:"agent_reply",content:{}},D=e.retainedStream??r.messages.startStream(A);let F,U=!1;try{const e=await D.opened();U="duplicate"===e.outcome,logChatLatency(a,"claw.reply_stream.opened",m,I,{outcome:e.outcome})}catch(n){let o="unconfirmed";try{o=(await r.messages.getEnvelope(t.channelId,L)).state}catch{}return a.warn?.(`[im] runtime reply stream open outcome unknown requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} reply_id=${L} reconciled_state=${o}: ${formatErrMessage(n)}; runtime_not_invoked`),e.onLifecycleEvent?.({type:"skipped",reason:"reply_open_outcome_unknown",channelId:t.channelId,inboundMessageId:t.inboundMessageId}),i.unregister(_),!1}if(U)return a.info?.(`[im] runtime dispatch skipped existing deterministic reply requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId}`),e.onLifecycleEvent?.({type:"skipped",reason:"idempotent_reply_exists",channelId:t.channelId,inboundMessageId:t.inboundMessageId}),i.unregister(_),!1;const K=()=>{T(e.abortSignal?.reason).catch(e=>{C(e instanceof Error?e:new Error(String(e)))})};e.abortSignal?.addEventListener("abort",K,{once:!0}),e.abortSignal?.aborted&&K();const P=new SerializedCallbackQueue,Q=createImReplySink({stream:D,persistObservedToolResults:void 0!==e.retainedStream,abortSignal:f.signal,callbackQueue:P,...e.onNativeRunCompletion?{onCallbackFailure:e=>P.fail(e)}:{},logger:a,requestId:m,startedAtMs:I,runId:p,channelId:t.channelId,inboundMessageId:t.inboundMessageId,origin:g,sessionKey:R,onAgentRunStart:n=>{l.bindRun(w,n),e.onNativeAgentRunStart?.(n),void 0!==F&&logChatLatency(a,"claw.runtime.pre_run_completed",m,F)}}),G=interceptAgentRuntimeFailures(Q,"im_runtime",e=>a.warn?.(`[im] runtime failure reply suppressed requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} error_code=${e.errorCode}`)),Y=G.sink;let j=!1,x=!1;const V=async n=>{e.onNativeRunCompletion||Y.dispatcher.markComplete(n);try{e.onNativeRunCompletion&&Y.dispatcher.markComplete(n),await Y.dispatcher.waitForIdle()}catch(n){if(e.onNativeRunCompletion)throw P.fail(n),n}},B=()=>{if(e.onNativeRunCompletion)return;O();const n=normalizePositiveTimeoutMs(e.abortTerminalGraceMs)??1e4;k=setTimeout(()=>{k=void 0,(async()=>{if(D.isTerminated)return;const e=f.signal.reason??$,n="string"==typeof e&&e.startsWith("chat_cancel");if(await V("failure"),!D.isTerminated)try{n?await D.cancel({stopReason:"user_stop"}):await failMessageStream(D,{body:SESSION_RECOVERY_REQUIRED_MESSAGE,stopReason:"error"}),a.warn?.(`[im] abort settlement watchdog terminalized reply requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} user_cancel=${n}`)}catch(e){a.warn?.(`[im] abort settlement watchdog terminal write failed requestId=${m} channel=${t.channelId}: ${formatErrMessage(e)}`)}})()},n)};f.signal.aborted?B():f.signal.addEventListener("abort",B,{once:!0});const z=()=>{if(!f.signal.aborted)return;const e=f.signal.reason;throw e instanceof Error?e:new Error(String(e??"runtime dispatch aborted"))};let W,J,H,X,Z,ee,ne;const te=async e=>{if(!w)throw new Error("session_mutation_not_acquired");const n=await l.converge(w,e);return n.ok?(W=n.permit,!0):(a.error?.(`[im] session mutation recovery required requestId=${m} sessionKey=${R} reason=${n.recovery.reason}`),J={code:n.recovery.code,reason:n.recovery.reason,sessionKey:n.recovery.sessionKey,operationId:n.recovery.operationId,surface:"message_service",...n.recovery.terminalKind?{terminalKind:n.recovery.terminalKind}:{}},!1)};try{if(z(),e.onNativeRunCompletion&&!e.nativeActiveRunRegistration)throw new Error("native MS Start registration required");const d=l.tryStartInteractive({sessionKey:R,label:"im_chat_message"},"message_service");if(!d.ok){try{await failMessageStream(D,{body:SESSION_BUSY_PUBLIC_MESSAGE,stopReason:"error"})}catch(e){a.warn?.(`[im] session busy terminal write failed channel=${t.channelId} in_reply_to=${t.inboundMessageId}: ${formatErrMessage(e)}`)}return a.warn?.(`[im] session write gate busy sessionKey=${R} channel=${t.channelId} in_reply_to=${t.inboundMessageId} active_operation=${d.activeOperationId??"unknown"}`),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:"session_busy",cause:"runtime_error"}),!1}if(w=d.token,logChatLatency(a,"claw.session_gate.acquired",m,I),l.bindRun(w,p),X=o.register(R,Q),Z=s.register(R,Q),ee=c.register(p,{requestId:m,startedAtMs:I,logger:a}),u){const n=l.snapshot(R);H=e.onNativeRunCompletion?{...e.nativeActiveRunRegistration}:{runtimeConversationUid:t.channelId,runtimeSessionKey:t.channelId,historyGeneration:u.historyGeneration(t.channelId),targetMessageId:t.inboundMessageId,runtimeRunId:p,activeRunRegistrationId:`im:${n?.operationId??p}`},u.activeRuns.register(H,async()=>{const e=`chat_cancel:activeRun:${H.activeRunRegistrationId}`,n=await i.abort(_,e);return n.ok||"already_aborted"===n.reason?"accepted":"terminal_committing"===n.reason||"not_found"===n.reason?"already_terminal":"recovery_required"})}z(),a.info?.(`[im] runtime dispatching requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} origin=${g}`),e.onLifecycleEvent?.({type:"dispatch_start",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId}),e.onNativeRunCompletion&&e.assertNativeTarget&&(await e.assertNativeTarget(),z()),e.onNativeRunCompletion&&e.prepareNativeModel&&(await e.prepareNativeModel(w),z(),await(e.assertNativeTarget?.()),z());const f=t.modelOverrideId;"string"==typeof f&&f.length>0&&R.length>0&&e.applyTurnModel&&(await e.applyTurnModel(R,f),x=!0,z()),F=Date.now(),ne=e.enterTurn?.(R,p),logChatLatency(a,"claw.runtime.invoke",m,I);const S=setTimeout(()=>{const e=Date.now()-F-100;e>=500&&logChatLatency(a,"claw.runtime.event_loop_lag",m,F,{lag_ms:e,phase:"pre_run"})},100);S.unref?.();const $=()=>dispatchRuntimeReplyWithRoute({runtime:n,pluginConfig:e.pluginConfig,preparedPrompt:t.dispatchInput,replyRoute:h,replySinks:{im:Y},onDispatchInvoked:n=>{if(j=!0,e.onNativeRunCompletion){E=n;const t=new Promise((e,n)=>{v=e,M=n});t.catch(()=>{}),e.onNativeRunCompletion({runtimeRunId:p,token:w,hostCompletion:n,completion:t})}logChatLatency(a,"claw.runtime.dispatch_returned",m,F)}}),C=ne?ne.run($):$(),N=e.onNativeRunCompletion?await C:await Promise.race([C,q]).finally(()=>{});e.onNativeRunCompletion&&(await E,await b);const k=G.detectedFailure();if(k)throw new Error(k.diagnosticMessage);if(z(),await V("success"),e.onNativeRunCompletion&&await b,z(),!i.claimTerminal(_,"completion")){if(z(),"cancelling"===i.phase(_))throw new Error("cancellation in progress");throw new Error("terminal outcome already claimed")}if(!await te("completed"))return await failMessageStream(D,{body:SESSION_RECOVERY_REQUIRED_MESSAGE,stopReason:"error"}).catch(()=>{}),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:SESSION_RECOVERY_REQUIRED_CODE,cause:"runtime_error",...J?{recovery:J}:{}}),!1;const O=Y.dispatcher.getTerminalErrorText?.();if(void 0!==O){let n=!1;const r=classifyAgentRuntimeFailure({raw:O,source:"im_runtime",runtimeKind:"openclaw"});try{await writeRuntimeFailure(D,{body:r.publicMessage,stopReason:messageStopReasonForRuntimeFailure(r),businessErrorCode:r.businessErrorCode})}catch(e){n=!0,a.warn?.(`[im] runtime reply stream error-terminal write outcome unknown requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId}: ${formatErrMessage(e)}`)}return u&&H&&u.activeRuns.markTerminal(H,"failed"),a.warn?.(`[im] runtime dispatch ended with an error terminal requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} counts=${JSON.stringify(N.counts)} terminalWriteFailed=${n} elapsed_ms=${Date.now()-I}`),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:"runtime_error_terminal_reply",cause:"runtime_error"}),n||await y("",O),!1}let T=!1;try{await D.finalize({stopReason:"end_turn"})}catch(e){T=!0,a.warn?.(`[im] runtime reply stream finalize outcome unknown requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId}: ${formatErrMessage(e)}`)}u&&H&&u.activeRuns.markTerminal(H,"completed");const L={...N.counts,source:Q.getSourceCount()};a.info?.(`[im] runtime dispatch completed requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} counts=${JSON.stringify(L)} elapsed_ms=${Date.now()-I}`),logChatLatency(a,"claw.turn.terminal",m,I,{outcome:T?"outcome_unknown":"completed",tool_count:L.tool}),e.onLifecycleEvent?.({type:"dispatch_complete",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,counts:L,...T?{terminalWriteFailed:!0}:{}});const A=Y.dispatcher.getAccumulatedBody?.()??"";T||await y(A,"");const U="string"==typeof t.dispatchInput.message?t.dispatchInput.message:"";return maybeRenameImConversationTitle({client:r,conversationId:t.channelId,question:U,answer:A,logger:a}),!0}catch(n){S=n,e.onNativeRunCompletion&&(await(E?.then(()=>{},()=>{})),await b),await V("failure"),e.onNativeRunCompletion&&await b;const r=f.signal.aborted,o=r?f.signal.reason:void 0,s="cancelling"===i.phase(_),c=o??$,l="string"==typeof c&&c.startsWith("chat_cancel");let d="runtime_error";(r||s)&&(d="abort");const p=s||l||r?"cancellation":"completion";if(!i.claimTerminal(_,p)){if(a.warn?.(`[im] terminal claim raced requestId=${m} channel=${t.channelId}; best-effort envelope terminal if still streaming`),!D.isTerminated)try{l?await D.cancel({stopReason:"user_stop"}):await failMessageStream(D,{body:formatErrMessage(n),stopReason:"error"})}catch(e){a.warn?.(`[im] raced terminal write failed requestId=${m}: ${formatErrMessage(e)}`)}throw n}const g=l?"cancelled":"error";if(u&&H&&!e.onNativeRunCompletion&&u.activeRuns.markTerminal(H,"cancelled"===g?"cancelled":"failed"),w&&!await te(g))throw u&&H&&e.onNativeRunCompletion&&u.activeRuns.markTerminal(H,"cancelled"===g?"cancelled":"failed"),l?await D.cancel({stopReason:"user_stop"}).catch(()=>{}):await failMessageStream(D,{body:SESSION_RECOVERY_REQUIRED_MESSAGE,stopReason:"error"}).catch(()=>{}),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:SESSION_RECOVERY_REQUIRED_CODE,cause:d,...J?{recovery:J}:{}}),n;u&&H&&e.onNativeRunCompletion&&u.activeRuns.markTerminal(H,"cancelled"===g?"cancelled":"failed");const h=classifyAgentRuntimeFailure({raw:n,source:"im_runtime",runtimeKind:"openclaw",requestAborted:l}),R=l?h:G.detectedFailure()??h;let v=!1;try{l?await D.cancel({stopReason:"user_stop"}):await writeRuntimeFailure(D,{body:R.publicMessage,stopReason:messageStopReasonForRuntimeFailure(R),businessErrorCode:R.businessErrorCode})}catch(e){v=!0,a.warn?.(`[im] runtime stream terminal write failed requestId=${m} channel=${t.channelId}: ${formatErrMessage(e)}`)}throw a.warn?.(`[im] runtime dispatch failed requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} cause=${d} dispatchInvoked=${j} error_code=${R.errorCode}`),logChatLatency(a,"claw.turn.terminal",m,I,{outcome:d,error_code:R.errorCode}),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:R.errorCode,cause:d}),l||v||await y("",R.publicMessage),n}finally{if(e.onNativeRunCompletion&&(W?v?.(W):(j&&w&&l.requireRecovery(w,"terminal_not_observed"),M?.(S??new Error(SESSION_RECOVERY_REQUIRED_CODE)))),e.abortSignal?.removeEventListener("abort",K),j&&!W||ne?.close(),O(),ee?.(),Z?.(),X?.(),i.unregister(_),x&&e.restoreTurnModel&&R)try{await e.restoreTurnModel(R)}catch(e){a.error?.(`[im] turn model restore failed requestId=${m} sessionKey=${R}: ${formatErrMessage(e)}`)}j?W&&l.release(W):l.releaseBeforeRuntime(w)}};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{fileDeliveryFinalizeDecision}from"./upload/finalize-hook.js";import{resolveConfigWithMeta,mirrorOpenClawConfig}from"./config.js";import{hasRuntimeReplyApi}from"./runtime/reply-router.js";import{PromptRunStore}from"./runtime/prompt-run-store.js";import{createMcpNativeProjectionNudge,fingerprintMcpServers}from"./acp-gateway/mcp-native-projection-nudge.js";import{createImHotPathDeferral}from"./runtime/im-hot-path-deferral.js";import{SessionWriteGate}from"./acp-gateway/session-write-gate.js";import{OpenClawSessionWriteQuiescence}from"./runtime/openclaw-session-write-quiescence.js";import{SessionMutationCoordinator}from"./runtime/session-mutation-coordinator.js";import{scheduleProcessRuntimeRestart}from"./runtime/runtime-restart-scheduler.js";import{createImInboundHandler}from"./im-inbound-handler.js";import{AutomationTurnPolicy}from"./automation/turn-policy.js";import{registerAutomationTools}from"./automation/tools.js";import{extractBeeosConversationIdFromSessionKey}from"./runtime/openclaw-session-key-resolution.js";import{createTokenProvider}from"@beeos-ai/message-sdk/auth";import{NodeRuntimeDeliveryPort}from"@beeos-ai/cloud-agent-sdk";import{BeeosClawMessageClientProcessOwner}from"./message-client-composition.js";import{MessageProjectionInboundConsumer}from"./message-projection-inbound-consumer.js";import{MessageClientTerminalStateRecovery}from"./runtime/message-client-terminal-state-recovery.js";import{RuntimeAuthorityMessageBusLifecycle}from"./runtime/runtime-authority-message-bus-lifecycle.js";import{MSConnectionStatusSnapshot}from"./runtime/ms-connection-status.js";import{FileInboundExecutionJournal}from"./inbound-execution-journal.js";import{completeA2ATask,registerA2ATools,TaskHandleRegistry}from"./a2a/tools.js";import{BEEOS_UPLOAD_TOOL_NAME,BEEOS_UPLOAD_TOOL_SCHEMA,BEEOS_UPLOAD_TOOL_DESCRIPTION,executeUpload}from"./upload/tool.js";import{BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME,BEEOS_DESKTOP_SCREENSHOT_TOOL_SCHEMA,BEEOS_DESKTOP_SCREENSHOT_TOOL_DESCRIPTION,executeDesktopScreenshot}from"./upload/desktop-screenshot-tool.js";import{BEEOS_LIST_FILES_TOOL_NAME,BEEOS_LIST_FILES_TOOL_SCHEMA,BEEOS_LIST_FILES_TOOL_DESCRIPTION,executeListFiles}from"./files/list-tool.js";import{BEEOS_FETCH_FILE_TOOL_NAME,BEEOS_FETCH_FILE_TOOL_SCHEMA,BEEOS_FETCH_FILE_TOOL_DESCRIPTION,executeFetchFile}from"./files/fetch-tool.js";import{writeUploadToolResult,cleanupUploadToolResultCache}from"./upload/result-cache.js";import{handleFileStage}from"./upload/file-stage.js";import{handleStatusRequest}from"./status.js";import{ACPServer}from"./acp-server.js";import{GatewayClient}from"./gateway-client.js";import{createObsEventWriter}from"./observability.js";import{resolvePluginVersion}from"./plugin-version.js";import{createTerminalWebSocketService}from"./terminal/websocket.js";import{TerminalManager}from"./terminal/session-manager.js";import{loadAgentKeyPair,agentBoundFetch,agentFetch}from"./agent-auth.js";import{readDiscoveryCache,writeDiscoveryCache}from"./discovery-cache.js";import{discoverBridgeFromGW}from"./bridge-discovery.js";import{setUploadDeps}from"./upload/upload-file.js";import{registerLocalFileExtractor}from"./upload/local-file-extractors.js";import{browserScreenshotExtractor}from"./browser/screenshot-extractor.js";import{deliverableFileExtractor}from"./upload/deliverable-extractor.js";import{observeToolCallForDelivery,rememberDeliveryWorkspace}from"./upload/delivery-observe.js";import{BEEOS_FILE_RESOURCE_ROUTING_RULE}from"./files/beeos-file-uri.js";import{marksFullRuntimeRegistered,planPluginRegistration,replayCachedPluginTools,resolveCapabilityToolReplay}from"./plugin-registration-plan.js";import{buildAppendSystemContext,buildToolRoutingHint,canvasToolBlockReason}from"./prompt-system-context.js";import{CONNECTOR_MCP_PROXY_PATH,handleConnectorMcpRequest}from"./mcp-connector-proxy.js";import{CanvasStateManager}from"./canvas/state.js";import{CanvasRelayClient}from"./canvas/relay-client.js";import{createCanvasRelayService}from"./canvas/relay-service.js";import{RENDER_UI_TOOL_NAME,RENDER_UI_TOOL_DESCRIPTION,RENDER_UI_TOOL_SCHEMA,CLOSE_UI_TOOL_NAME,CLOSE_UI_TOOL_DESCRIPTION,CLOSE_UI_TOOL_SCHEMA,createRenderUiHandler,createCloseUiHandler,CANVAS_PRESENTATION_GATE,CANVAS_SYSTEM_PROMPT}from"./canvas/tools.js";import{FormSchemaRegistry}from"./surface/form-schema-registry.js";import{buildCronSchemas}from"./surface/cron-schemas.js";import{RENDER_FORM_TOOL_NAME,RENDER_FORM_TOOL_SCHEMA,buildRenderFormDescription,createRenderFormHandler}from"./surface/render-form-tool.js";import{ResourceDescriptorRegistry}from"./surface/resource-descriptor-registry.js";import{CRON_RESOURCE}from"./surface/cron-resource.js";import{generateActionTools}from"./surface/action-tool-generator.js";import{buildThirdPartyChannelSet,isThirdPartyChannel}from"./channel-detection.js";import{registerArouterMediaProviders}from"./media/index.js";import{homedir}from"node:os";import{join}from"node:path";import{RuntimeProductionAuthority,cloudRuntimeTargetInstanceId}from"./runtime/runtime-production-authority.js";import{FileRuntimeCommandJournal}from"./runtime/runtime-command-journal.js";import{FileRuntimePoisonDeliveryJournal}from"./runtime/runtime-poison-delivery-journal.js";import{OpenClawNativeMcpProjection}from"./acp-gateway/openclaw-native-mcp-projection.js";import{LocalEncryptedCredentialReferenceVault}from"./acp-gateway/mcp-credential-reference-port.js";import{AgentGatewayGrantJwksReadinessAdapter,CloudRuntimeServiceTransportReadinessAdapter,RuntimeServiceTransportReadinessAdapter,createRuntimeServiceProductionCandidate}from"./runtime/runtime-service-production-candidate.js";import{MessageServiceCronDeliveryHttpAuthority}from"./runtime/message-service-cron-delivery-http-authority.js";import{AgentMappingRegistry}from"./runtime/agent-mapping-registry.js";import{OpenClawRuntimeProcessOwner}from"./runtime/openclaw-runtime-process-owner.js";import{AgentGatewayHttpProjectionTransport,AgentGatewayTemplateOriginReporter,AgentProjectionProduction,OpenClawAgentProjectionSource}from"./runtime/agent-projection-production.js";import{MessageServiceRunOutputChannel}from"./runtime/message-service-run-output-channel.js";import{AssistantMessageCommitRouter}from"./runtime/assistant-message-commit-router.js";import{ToolResultObservationRouter}from"./runtime/tool-result-observation-router.js";import{ModelCallObservationRouter,registerModelCallObservationHooks}from"./runtime/model-call-observability.js";import{registerArouterLatencyRouting}from"./runtime/arouter-latency-routing.js";import{createPeerRunOutputRouterFactory}from"./runtime/run-output-composition.js";const PLUGIN_VERSION=resolvePluginVersion();let agentKeys=null,sharedCanvasState=null,sharedAcpServer=null;const sharedSessionWriteGate=new SessionWriteGate,sharedPromptRunStore=new PromptRunStore,sharedAutomationTurnPolicy=new AutomationTurnPolicy;let lastOpenclawConfig;const sharedMcpNativeProjectionNudge=createMcpNativeProjectionNudge({getActiveImRunCount:()=>sharedPromptRunStore.size(),nudge:()=>{sharedAcpServer?.nudgeMcpNativeProjection()}}),sharedImHotPathDeferral=createImHotPathDeferral({getActiveImRunCount:()=>sharedPromptRunStore.size()});sharedPromptRunStore.setOnBecameIdle(()=>{sharedMcpNativeProjectionNudge.flushIfIdle({fingerprint:fingerprintMcpServers(lastOpenclawConfig)}),sharedImHotPathDeferral.notifyIdle()});const sharedAssistantMessageCommitRouter=new AssistantMessageCommitRouter,sharedToolResultObservationRouter=new ToolResultObservationRouter,sharedModelCallObservationRouter=new ModelCallObservationRouter;let sharedSessionMutationCoordinator,sharedRuntimeAuthority;const sharedMSConnectionStatus=new MSConnectionStatusSnapshot,sharedAgentMappings=new AgentMappingRegistry;let sharedGatewayClient,sharedRuntimeOwner,sharedAgentProjection,sharedRuntimeAgentCapabilities,sharedMcpProjection,sharedMcpCredentialVault;const sharedMessageClientOwner=new BeeosClawMessageClientProcessOwner;let sharedActiveMessageConsumer,sharedInboundExecutionJournal;const sharedTerminalManager=new TerminalManager;let _initializing=!1,_pluginRegisteredAt=0,_fullRuntimeRegistered=!1;const cachedCapabilityTools=[];let rawRegisterTool,wrappedRegisterTool;const ensureRegisterToolCache=e=>{rawRegisterTool||(rawRegisterTool=e.registerTool.bind(e),wrappedRegisterTool=e=>(cachedCapabilityTools.push(e),rawRegisterTool(e)),e.registerTool=wrappedRegisterTool)},ED25519_PKCS8_PREFIX=Buffer.from("302e020100300506032b657004220420","hex");function agentKeyPairToIdentity(e){return{publicKeyBase64:()=>Buffer.from(e.publicKey).toString("base64"),sign:async t=>{const{createPrivateKey:r,sign:o}=await import("node:crypto"),n=r({key:32===e.privateKey.length?Buffer.concat([ED25519_PKCS8_PREFIX,Buffer.from(e.privateKey)]):Buffer.from(e.privateKey),format:"der",type:"pkcs8"});return new Uint8Array(o(null,Buffer.from(t),n))}}}let sharedPluginContext=null,unhandledRejectionObserverInstalled=!1;function installUnhandledRejectionObserver(e,t,r){unhandledRejectionObserverInstalled||(unhandledRejectionObserverInstalled=!0,process.on("unhandledRejection",r=>{const o=r instanceof Error?r.message:String(r),n=r instanceof Error?r.stack:void 0;e.logger.error?.(`[beeos-claw] unhandledRejection: ${o}${n?`\n${n}`:""}`),t({component:"plugin",domain:"fatal",name:"unhandled_rejection",severity:"error",summary:o,error:{code:"unhandled_rejection",message:o,...n?{stack:n}:{}}})}),process.on("uncaughtException",r=>{const o=r instanceof Error?r.message:String(r);e.logger.error?.(`[beeos-claw] uncaughtException: ${r instanceof Error?r.stack??r.message:String(r)}`),t({component:"plugin",domain:"fatal",name:"uncaught_exception",severity:"error",summary:o,error:{code:"uncaught_exception",message:o}})}))}function initializePlugin(e){let t,r;try{t=e.runtime?.config?.loadConfig?.()}catch{}try{r=resolveConfigWithMeta({pluginConfig:e.pluginConfig??{},openclawConfig:t})}catch(t){return e.logger.error?.(`[beeos-claw] Failed to resolve config: ${t instanceof Error?t.message:String(t)}`),null}const o=r.config,n=buildThirdPartyChannelSet(t);n.size>0&&e.logger.info?.(`[beeos-claw] Third-party channels detected: ${[...n].join(", ")}`);const a=o.log.enabled?createObsEventWriter({dir:o.log.dir,redaction:{gatewayToken:o.gateway.token},logger:e.logger}):()=>{};a({component:"plugin",domain:"lifecycle",name:"lifecycle.startup",severity:"info",payload:{pluginVersion:PLUGIN_VERSION,pid:process.pid,nodeVersion:process.version,cwd:process.cwd()}}),a({component:"plugin",domain:"config",name:"config.resolved",severity:"info",payload:{config:o,sources:r.sources,openclawConfigPath:r.openclawConfigPath}});for(const t of r.validation)a({component:"plugin",domain:"config",name:"config.validation",severity:t.severity,summary:t.message,error:{code:t.code,message:t.message,nextSteps:t.nextSteps}}),"error"===t.severity?e.logger.error?.(`[beeos-claw] ${t.message}`):e.logger.warn?.(`[beeos-claw] ${t.message}`);if(r.validation.some(e=>"error"===e.severity)&&e.logger.error?.("[beeos-claw] Plugin has configuration errors — some features may not work."),o.keyFile)try{agentKeys=loadAgentKeyPair(o.keyFile);const t=Buffer.from(agentKeys.publicKey).toString("base64");e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (publicKey: ${t})`)}catch(t){e.logger.warn?.(`[beeos-claw] Failed to load agent key pair: ${t}`),e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (no key pair — signed requests disabled)`)}else e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (no keyFile configured)`);return agentKeys&&o.agentGatewayUrl&&(setUploadDeps({gatewayUrl:o.agentGatewayUrl,keys:agentKeys,logger:e.logger}),registerLocalFileExtractor(browserScreenshotExtractor),registerLocalFileExtractor(deliverableFileExtractor),e.logger.info?.("[beeos-claw] Upload deps + local file extractors registered")),lastOpenclawConfig=t,{cfg:o,writeObs:a,thirdPartyChannels:n,openclawConfig:t}}function registerUploadTools(e,t,r){const{cfg:o,writeObs:n}=t;cleanupUploadToolResultCache().catch(t=>{e.logger.warn?.(`[beeos_upload_file] cache cleanup failed on startup: ${String(t)}`)}),e.registerTool({name:BEEOS_UPLOAD_TOOL_NAME,description:BEEOS_UPLOAD_TOOL_DESCRIPTION,parameters:BEEOS_UPLOAD_TOOL_SCHEMA,async execute(t,r,a){e.logger.debug?.(`[beeos_upload_file] toolCallId=${t} params=${JSON.stringify(r)}`);const i=await executeUpload(r,o,agentKeys,a);return e.logger.debug?.(`[beeos_upload_file] toolCallId=${t} ok=${i.ok}`),n({component:"upload-tool",domain:"tool",name:i.ok?"upload.success":"upload.failure",severity:i.ok?"info":"warn",payload:{toolCallId:t,ok:i.ok,fileCount:i.files?.length??0,error:i.error}}),(async r=>{try{await writeUploadToolResult(t,BEEOS_UPLOAD_TOOL_NAME,r),await cleanupUploadToolResultCache()}catch(r){e.logger.warn?.(`[beeos_upload_file] persist cache failed toolCallId=${t}: ${String(r)}`)}return r})(i)}}),e.registerTool({name:BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME,description:BEEOS_DESKTOP_SCREENSHOT_TOOL_DESCRIPTION,parameters:BEEOS_DESKTOP_SCREENSHOT_TOOL_SCHEMA,async execute(t,r,a){e.logger.debug?.(`[beeos_desktop_screenshot] toolCallId=${t} params=${JSON.stringify(r)}`);const i=await executeDesktopScreenshot(r,o,agentKeys,a);return e.logger.debug?.(`[beeos_desktop_screenshot] toolCallId=${t} ok=${i.ok}`),n({component:"desktop-screenshot-tool",domain:"tool",name:i.ok?"desktop_screenshot.success":"desktop_screenshot.failure",severity:i.ok?"info":"warn",payload:{toolCallId:t,ok:i.ok,path:i.path,fileCount:i.files?.length??0,error:i.error}}),(async r=>{try{await writeUploadToolResult(t,BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME,r),await cleanupUploadToolResultCache()}catch(r){e.logger.warn?.(`[beeos_desktop_screenshot] persist cache failed toolCallId=${t}: ${String(r)}`)}return r})(i)}}),e.registerHttpRoute({path:"/beeos/files/stage",auth:"gateway",async handler(e,r){await handleFileStage(e,r,t.cfg)}}),e.registerHttpRoute({path:"/beeos/status",auth:"plugin",handler(e,t){handleStatusRequest(e,t,{publicKey:agentKeys?.publicKey??null,pluginVersion:PLUGIN_VERSION})}}),e.registerTool({name:BEEOS_LIST_FILES_TOOL_NAME,description:BEEOS_LIST_FILES_TOOL_DESCRIPTION,parameters:BEEOS_LIST_FILES_TOOL_SCHEMA,async execute(t,r,a){e.logger.debug?.(`[beeos_list_files] toolCallId=${t} params=${JSON.stringify(r)}`);const i=await executeListFiles(r,o,agentKeys,a);return n({component:"file-list-tool",domain:"tool",name:i.ok?"list_files.success":"list_files.failure",severity:i.ok?"info":"warn",payload:{toolCallId:t,ok:i.ok,fileCount:i.files?.length??0,error:i.error}}),i}}),e.registerTool({name:BEEOS_FETCH_FILE_TOOL_NAME,description:BEEOS_FETCH_FILE_TOOL_DESCRIPTION,parameters:BEEOS_FETCH_FILE_TOOL_SCHEMA,async execute(t,r,a){e.logger.debug?.(`[beeos_fetch_file] toolCallId=${t} params=${JSON.stringify(r)}`);const i=await executeFetchFile(r,o,agentKeys,{signal:a,resolvePath:e.resolvePath});return n({component:"file-fetch-tool",domain:"tool",name:i.ok?"fetch_file.success":"fetch_file.failure",severity:i.ok?"info":"warn",payload:{toolCallId:t,ok:i.ok,path:i.path,size:i.size,error:i.error}}),i}})}function registerConnectorMcpProxy(e,t){e.registerHttpRoute({path:CONNECTOR_MCP_PROXY_PATH,auth:"plugin",async handler(r,o){await handleConnectorMcpRequest(r,o,{agentGatewayUrl:t.cfg.agentGatewayUrl,agentKeys:agentKeys,logger:e.logger})}})}function registerServices(e,t,r){const{cfg:o,writeObs:n,thirdPartyChannels:a}=t;if(sharedAutomationTurnPolicy.disable(),"function"==typeof e.on)try{e.on("before_tool_call",(e,t)=>sharedAutomationTurnPolicy.check(e.toolName,{sessionKey:t?.sessionKey,runId:t?.runId??e.runId}),{priority:100}),sharedAutomationTurnPolicy.enable()}catch{e.logger.warn?.("[beeos-claw] Automation Wake disabled: tool guard unavailable")}if("function"!=typeof e.on){if(o.messageBus.enabled)throw new Error("openclaw_before_message_write_hook_unavailable")}else registerModelCallObservationHooks((t,r)=>e.on(t,r),sharedModelCallObservationRouter),e.on("before_message_write",(t,r)=>{const o=t.sessionKey??r.sessionKey;if(!o)return void e.logger.debug?.("[before_message_write] ignored assistant write without sessionKey");sharedAssistantMessageCommitRouter.route(o,t.message)||e.logger.debug?.(`[before_message_write] no active IM commit target sessionKey=${o} active_targets=${sharedAssistantMessageCommitRouter.size()}`)}),e.on("after_tool_call",(t,r)=>{const o=r.sessionKey,n=t.toolCallId??r.toolCallId,a=t.toolName||r.toolName;if(!o||!n||!a)return void e.logger.debug?.(`[after_tool_call] ignored structured result without correlation sessionKey=${o??"missing"} toolCallId=${n??"missing"}`);observeToolCallForDelivery(t,o);sharedToolResultObservationRouter.route(o,{toolCallId:n,toolName:a,rawResult:t.result,isError:Boolean(t.error)})||e.logger.debug?.(`[after_tool_call] no active IM observation target sessionKey=${o} active_targets=${sharedToolResultObservationRouter.size()}`)});const i=agentKeys?(e,t)=>agentFetch(e,agentKeys,t):void 0,s=agentKeys?(e,t)=>agentBoundFetch(e,agentKeys,t):void 0,l=agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):void 0,c=join(process.env.OPENCLAW_HOME||join(homedir(),".openclaw"),"beeos"),g=sharedInboundExecutionJournal??=new FileInboundExecutionJournal(join(c,"inbound-execution-journal.v1.jsonl"));sharedMcpProjection??=new OpenClawNativeMcpProjection,!sharedMcpCredentialVault&&agentKeys&&l&&(sharedMcpCredentialVault=new LocalEncryptedCredentialReferenceVault(join(c,"mcp-credential-vault.json"),l,agentKeys.privateKey));const u=cloudRuntimeTargetInstanceId(process.env);if(u&&(!agentKeys||!o.agentGatewayUrl||!i||!s))throw new Error("Cloud runtime authority requires an agent identity and gateway transport");if(sharedRuntimeAuthority&&sharedRuntimeAuthority.cloudTargetInstanceId!==u)throw new Error("Cloud runtime authority target changed during process lifetime");if(!sharedRuntimeAuthority&&agentKeys&&o.agentGatewayUrl&&i&&s&&(sharedRuntimeAuthority=new RuntimeProductionAuthority({stateDirectory:c,agentGatewayUrl:o.agentGatewayUrl,agentFetch:i,boundAgentFetch:s,keys:agentKeys,targetInstanceId:u,logger:e.logger,getMSConnectionStatus:e=>sharedMSConnectionStatus.get(e)})),sharedGatewayClient??=new GatewayClient({url:o.gateway.url,token:o.gateway.token||"",clientId:o.gateway.clientId,openclawCanvasCompat:!!o.openclawCanvasCompat,retry:{baseMs:o.retry.baseMs,maxMs:o.retry.maxMs,maxAttempts:o.retry.maxAttempts}}),sharedRuntimeAgentCapabilities??={canvas:o.canvasEnabled,terminal:!1,webSsh:!1,fileSystem:!0,image:!0,audio:!1,mcp:!0,cron:!0,streaming:!0,pushNotifications:o.messageBus.enabled,...o.messageBus.enabled&&sharedAutomationTurnPolicy.isReady()&&i?{automationWake:!0}:{}},!sharedAgentProjection&&sharedRuntimeAuthority&&i&&o.agentGatewayUrl){const t=sharedRuntimeAuthority;sharedAgentProjection=new AgentProjectionProduction({authority:t,stateFile:join(t.stateDirectory,"runtime-agent-projection.json"),journal:t.journal,identities:t.identities,source:new OpenClawAgentProjectionSource(()=>sharedGatewayClient),transport:new AgentGatewayHttpProjectionTransport({agentGatewayUrl:o.agentGatewayUrl,boundAgentFetch:t.boundAgentFetch,getRuntimeLeaseCredential:e=>{const r=t.authorityLease;if(!r||r.instanceId!==e.instanceId||r.leaseId!==e.leaseId||r.runtimeEpoch!==e.runtimeEpoch||r.handlerIdentity!==e.handlerIdentity)throw new Error("agent projection fenced by current runtime lease");return r.runtimeLeaseCredential},onAccepted:t=>{0!==t.size&&sharedAgentMappings.replace(t).catch(t=>{e.logger.warn?.("[agent-projection] mapping publication failed: "+(t instanceof Error?t.message:String(t)))})}}),capabilities:sharedRuntimeAgentCapabilities,logger:e.logger})}sharedRuntimeOwner??=new OpenClawRuntimeProcessOwner(sharedGatewayClient,sharedAgentProjection,e.logger);const d=sharedRuntimeOwner;sharedSessionMutationCoordinator??=new SessionMutationCoordinator(sharedSessionWriteGate,new OpenClawSessionWriteQuiescence(e.logger,{agentId:o.gateway.agentId||"main"}),e.logger,{onRecoveryRequired:t=>{scheduleProcessRuntimeRestart(t,e.logger)}});const m=sharedSessionMutationCoordinator;if(!sharedAcpServer){const t=sharedRuntimeAuthority&&o.agentGatewayUrl?new AgentGatewayTemplateOriginReporter({agentGatewayUrl:o.agentGatewayUrl,boundAgentFetch:sharedRuntimeAuthority.boundAgentFetch}):void 0;sharedAcpServer=new ACPServer(o,e.logger,m,n,i,l,a,sharedTerminalManager,sharedRuntimeAuthority,void 0,sharedMcpProjection,sharedMcpCredentialVault,s,{gateway:d.client,agentProjection:sharedAgentProjection,markAgentProjectionDirty:()=>sharedAgentProjection?.markDirty(),templateOriginReporter:t,agentMappings:sharedAgentMappings,agentCapabilities:sharedRuntimeAgentCapabilities,createRunOutputRouter:createPeerRunOutputRouterFactory(new MessageServiceRunOutputChannel({getClient:()=>sharedMessageClientOwner.current?.client??null,logger:e.logger,writeObs:n})),runExclusive:(t,r,o)=>sharedImHotPathDeferral.runExclusive(t,r,e.logger,o)})}const p=sharedAcpServer,y=()=>sharedAgentMappings.snapshot()?.values().next().value;r.current=p,sharedMcpNativeProjectionNudge.request({registrationMode:e.registrationMode,fingerprint:fingerprintMcpServers(t.openclawConfig),logger:e.logger});const h=sharedPromptRunStore,{enabled:f,principalId:w,a2aEnabled:v}=o.messageBus;let R;!u&&o.agentGatewayUrl&&agentKeys&&(R=createTokenProvider({agentGatewayUrl:o.agentGatewayUrl,identity:agentKeyPairToIdentity(agentKeys)}));const C=process.env.MESSAGE_RUNTIME_DELIVERY_KEY?.trim(),b=w||process.env.BEEOS_PRINCIPAL_ID||"",S=R?sharedMessageClientOwner.configure({tokenProvider:R,identityId:b,...o.messageBus.serviceUrl?{serviceUrl:o.messageBus.serviceUrl}:{},logger:e.logger,...sharedRuntimeAuthority&&C?{runtimeDelivery:{scopedDeliveryKey:C,authority:{currentLease:()=>{const e=sharedRuntimeAuthority?.authorityLease,t=sharedRuntimeAuthority?.currentConsumerBinding();return e&&t?{...e,journalStoreId:t.journalStoreId,journalGeneration:t.journalGeneration}:null}}}}:{}}):void 0,_=u&&o.messageBus.serviceUrl&&sharedRuntimeAuthority?new NodeRuntimeDeliveryPort({serviceOrigin:async()=>o.messageBus.serviceUrl},{currentLease:()=>{const e=sharedRuntimeAuthority?.authorityLease,t=sharedRuntimeAuthority?.currentConsumerBinding();return e&&t&&e.instanceId===u?{...e,journalStoreId:t.journalStoreId,journalGeneration:t.journalGeneration}:null},subscribeAuthority:e=>sharedRuntimeAuthority.subscribeAuthority(e)}):void 0,E=sharedRuntimeAuthority,O=o.messageBus.serviceUrl;if(S&&E&&O&&C){const e=S.nodeTransport;p.setCronConversationDelivery({deliver:async t=>{const r=E.authorityLease;if(!r)throw new Error("current runtime authority lease unavailable for cron delivery");const o=new MessageServiceCronDeliveryHttpAuthority({messageServiceUrl:O,fetchAuthorized:async(t,o)=>await e.fetchRuntimeChannel(t,{runtimeLeaseCredential:r.runtimeLeaseCredential},o)});return await o.deliver({...t,runtimeLeaseCredential:r.runtimeLeaseCredential})}})}else p.setCronConversationDelivery(void 0);const A=sharedRuntimeAuthority?.journal??new FileRuntimeCommandJournal(join(c,"runtime-command-journal.json"),void 0,void 0,{onMaintenanceError:t=>e.logger.error?.(`[runtime-journal] event=checkpoint_failed trigger=threshold error=${t instanceof Error?t.message:String(t)}`)}),T=d.createRegistrationToken();e.registerService({id:"beeos-acp",async start(){const t=Date.now(),r=_pluginRegisteredAt?t-_pluginRegisteredAt:-1;e.logger.info?.(`[beeos-claw] beeos-acp service start() begin, sincePluginRegister=${r}ms, bridge.url=${o.bridge.url||"(empty)"}`);const n=await createRuntimeServiceProductionCandidate({...o.agentGatewayUrl&&i?{authorizationAdapter:new AgentGatewayGrantJwksReadinessAdapter({agentGatewayUrl:o.agentGatewayUrl})}:{},...S&&o.agentGatewayUrl&&s&&C?{transportAdapter:new RuntimeServiceTransportReadinessAdapter({agentGatewayUrl:o.agentGatewayUrl,messageService:S.nodeTransport,messageClient:S.client,configuredServiceUrl:o.messageBus.serviceUrl,boundAgentFetch:s,scopedDeliveryKey:C})}:{},..._&&o.agentGatewayUrl&&s&&o.messageBus.serviceUrl?{cloudTransportAdapter:new CloudRuntimeServiceTransportReadinessAdapter({agentGatewayUrl:o.agentGatewayUrl,boundAgentFetch:s,configuredServiceUrl:o.messageBus.serviceUrl,runtimeDelivery:_})}:{},commandJournal:A,poisonJournal:new FileRuntimePoisonDeliveryJournal(join(c,"runtime-poison-deliveries.json")),onConsumerDeliveryError:t=>{const r=t instanceof Error?`${t.name}: ${t.message}${"status"in t?` status=${t.status}`:""}${"code"in t?` code=${t.code}`:""}\n${t.stack??""}`:String(t);e.logger.error?.(`[runtime-service] delivery worker failed before acknowledgement; delivery retained for retry: ${r}`)},onConsumerLeaseStarvation:({starvedForMs:t,recovered:r})=>{const o=Math.round(t/1e3);r?e.logger.info?.(`[runtime-service] runtime authority lease restored after ${o}s without delivery reads`):e.logger.warn?.(`[runtime-service] no runtime authority lease for ${o}s; delivery reads suspended, queued runtime operations (model switch, session control) will not be consumed`)},onConsumerRequestFailure:t=>e.logger.error?.(`[runtime-service] request failed operationId=${t.operationId} method=${t.method}: ${t.error instanceof Error?t.error.stack??t.error.message:String(t.error)}`)});if(sharedRuntimeAuthority?.setRuntimeServiceMethods("ready"===n.status?n.serviceMethods:[]),sharedRuntimeAuthority?.setRuntimeResourceBindingContractRevision("ready"===n.status?n.resourceBindingContractRevision:void 0),p.setRuntimeRpcConsumerFactory("ready"===n.status?n.factory:void 0),"unavailable"===n.status?e.logger.warn?.("[runtime-service] capability fenced: "+n.blockers.map(e=>e.id).join(",")):n.capabilityBlockers.length&&e.logger.warn?.("[runtime-service] method capability fenced: "+n.capabilityBlockers.map(e=>e.method).join(",")),!o.bridge.url&&o.agentGatewayUrl&&i){const t=Date.now(),r=await discoverBridgeFromGW(o.agentGatewayUrl,i);if(e.logger.info?.(`[beeos-claw] bridge discovery took ${Date.now()-t}ms result=${r?.url??"null"}`),r)o.bridge.url=r.url,writeDiscoveryCache({bridge:{url:r.url,discoveredAt:Date.now()}}),e.logger.info?.(`[beeos-claw] Bridge URL discovered from Agent Gateway: ${r.url}`);else{const t=readDiscoveryCache();t?.bridge?.url?(o.bridge.url=t.bridge.url,e.logger.info?.(`[beeos-claw] Bridge URL from cache (GW unreachable): ${t.bridge.url}`)):e.logger.debug?.("[beeos-claw] Bridge URL not available (no GW, no cache) — bridge disabled")}}await d.acquire(T);try{await p.start(o.bridge.url||void 0)}catch(e){throw await d.release(T),e}e.logger.info?.(`[beeos-claw] ACP Server started (total service start: ${Date.now()-t}ms)`)},async stop(){try{await d.release(T)}finally{await p.stop()}await A.checkpoint(),e.logger.info?.("[runtime-service] command journal checkpoint completed"),e.logger.info?.("[beeos-claw] ACP Server stopped")}});if(f&&void 0!==R&&R){const t=sharedMessageClientOwner.createRegistrationToken(),r=async(e,t)=>{const r=await R(e);if(!r.identityId||r.identityId!==e)throw new Error("Message SDK token identity did not match the current runtime authority");return{principalId:e,runtimeEpoch:t}},a=(e,t,r)=>({getLocalAgentId:()=>t,resolveLocalAgentId:e=>e===r?t:void 0,getDefaultPlatformAgent:()=>({instanceId:e.principalId}),ensureImInboundSession:(e,t,r,o)=>{p.ensureImInboundSession(e,t,r,o)},chatAbort:(e,t)=>p.chatAbort(e,t)}),i=sharedRuntimeAuthority?new RuntimeAuthorityMessageBusLifecycle({authority:sharedRuntimeAuthority,logger:e.logger,bus:{connect:async i=>{await sharedMessageClientOwner.acquire(t,async t=>{const s=await r(i.instanceId,i.runtimeEpoch),l=t.client,c={leaseId:i.leaseId,runtimeEpoch:i.runtimeEpoch};sharedMSConnectionStatus.bind(c);const u=new Map,d=new MessageProjectionInboundConsumer({client:l,bindings:()=>{const t=sharedRuntimeAuthority?.authorityLease;if(!t||t.instanceId!==s.principalId||t.runtimeEpoch!==s.runtimeEpoch)return[];const r=sharedAgentMappings.snapshot();return r?[...r.entries()].flatMap(([r,i])=>{if(!i.id||i.instanceId!==s.principalId)return[];let c=u.get(i.id);return c&&c.localAgentId===r||(c={localAgentId:r,inbound:createImInboundHandler({automationTurnPolicy:sharedAutomationTurnPolicy,runtime:e.runtime,pluginConfig:e.pluginConfig,client:l,localServer:a(s,r,i.id),promptRunStore:h,waitIfExclusive:(t,r)=>sharedImHotPathDeferral.waitIfExclusive(t,e.logger,r).then(()=>{}),assistantMessageCommitRouter:sharedAssistantMessageCommitRouter,toolResultObservationRouter:sharedToolResultObservationRouter,modelCallObservationRouter:sharedModelCallObservationRouter,sessionMutationCoordinator:m,logger:e.logger,writeObs:n,principalIdOverride:s.principalId,activeRunAuthority:p.getActiveRunAuthority(),...o.agentGatewayUrl&&agentKeys?{completeA2ATask:(t,r,n)=>completeA2ATask({agentGatewayUrl:o.agentGatewayUrl,agentKeys:agentKeys,logger:e.logger},t,r,n)}:{}})},u.set(i.id,c)),[{principalId:s.principalId,targetAgentId:i.id,runtimeEpoch:t.runtimeEpoch,inbound:c.inbound}]}):[]},executionJournal:g,logger:e.logger}),y=sharedAgentMappings.subscribe(()=>{sharedActiveMessageConsumer===d&&d.refresh()}),f=sharedRuntimeAuthority?.subscribeAuthority(()=>{sharedActiveMessageConsumer===d&&d.refresh()})??(()=>{}),w=new MessageClientTerminalStateRecovery({logger:e.logger,isCurrent:()=>{if(sharedActiveMessageConsumer!==d)return!1;const e=sharedRuntimeAuthority?.authorityLease;return null!=e&&e.instanceId===s.principalId&&e.runtimeEpoch===s.runtimeEpoch&&e.leaseId===i.leaseId&&e.handlerIdentity===i.handlerIdentity},reconnect:async()=>{if("failed"===l.getSnapshot().connection){await l.connect();try{await p.rebindRuntimeDelivery()}catch(t){e.logger.warn?.(`[beeos-claw] runtime Service delivery rebind failed after MessageClient recovery: ${t instanceof Error?t.message:String(t)}`)}}}});let v=l.getSnapshot().connection;sharedMSConnectionStatus.setIfCurrent(c,v);const R=l.subscribe(()=>{const t=l.getSnapshot();t.connection!==v&&(v=t.connection,sharedMSConnectionStatus.setIfCurrent(c,t.connection),"connected"===t.connection?(w.notifyConnected(),e.logger.info?.(`[beeos-claw] connection transport=message_service_realtime state=connected localAgentId=${p.getLocalAgentId()} principalId=${s.principalId}`)):"failed"===t.connection?(e.logger.warn?.(`[beeos-claw] connection transport=message_service_realtime state=failed principalId=${s.principalId} recoveryError=${t.recoveryError??"unknown"}`),w.notifyFailed()):"disconnected"!==t.connection&&"reconnecting"!==t.connection||e.logger.warn?.(`[beeos-claw] connection transport=message_service_realtime state=${t.connection} principalId=${s.principalId}; SDK owns reconnect/recovery`))});sharedActiveMessageConsumer=d,d.start();try{await l.connect()}catch(e){throw sharedActiveMessageConsumer===d&&(sharedActiveMessageConsumer=void 0),sharedMSConnectionStatus.resetIfCurrent(c),w.dispose(),await d.stop(),y(),f(),R(),await l.disconnect().catch(()=>{}),e}try{await p.rebindRuntimeDelivery()}catch(t){e.logger.warn?.(`[beeos-claw] runtime Service delivery rebind failed after MessageClient connect: ${t instanceof Error?t.message:String(t)}`)}return async()=>{sharedActiveMessageConsumer===d&&(sharedActiveMessageConsumer=void 0),sharedMSConnectionStatus.resetIfCurrent(c),w.dispose(),await d.stop(),f(),R(),await l.disconnect(),e.logger.info?.("[beeos-claw] MessageClient disconnected")}})},disconnect:async()=>{await sharedMessageClientOwner.release(t)}}}):void 0;e.registerService({id:"beeos-message-bus",async start(){i?i.start():e.logger.warn?.("[beeos-claw] Message bus requires runtime authority; waiting is unavailable without Agent Gateway runtime identity")},async stop(){await(i?.stop())}})}else f?e.logger.warn?.("[beeos-claw] Message bus enabled but Agent Gateway token provider is unavailable — disabled"):e.logger.info?.(`[beeos-claw] Message bus disabled (enabled=${f})`);if(!1!==v&&o.agentGatewayUrl){const t=e=>p.getGatewaySessionKeyForToolCall(e),r=e=>p.getMentionsForToolCall(e),n=(e,t)=>{p.broadcastNotification(e,t)},a=new TaskHandleRegistry;registerA2ATools(e,{agentGatewayUrl:o.agentGatewayUrl,agentKeys:agentKeys,logger:e.logger},a,t,r,n,()=>y()?.instanceId),e.logger.info?.("[beeos-claw] A2A tools registered (beeos_discover_agents, beeos_call_agent) via REST")}if(o.agentGatewayUrl&&(registerAutomationTools(e,{agentGatewayUrl:o.agentGatewayUrl,agentKeys:agentKeys??void 0,logger:e.logger,getDefaultAgent:()=>{const e=y();return e?{id:e.id,instanceId:e.instanceId}:void 0},getCurrentConversationId:e=>{const t=p.getGatewaySessionKeyForToolCall(e);return t?extractBeeosConversationIdFromSessionKey(t):void 0}}),e.logger.info?.("[beeos-claw] Automation tools registered (create/create_webhook/capabilities/preflight/list/get/run/runs/get_run)")),o.canvasEnabled){sharedCanvasState||(sharedCanvasState=new CanvasStateManager);const t=sharedCanvasState;if(o.agentGatewayUrl&&agentKeys){let r;t.setLogger(e.logger);{const e=o.agentGatewayUrl,t=agentKeys;r=async()=>{const r=await agentFetch(`${e}/api/v1/canvas/token`,t,{method:"POST"});if(!r.ok){const e=await r.text().catch(()=>"");throw new Error(`Canvas token returned ${r.status}: ${e}`)}return r.json()}}const n=n=>{const a=new CanvasRelayClient({canvasRelayUrl:o.canvasRelayUrl,agentKeys:agentKeys,agentId:n.id,displayName:n.displayName,avatarUrl:n.avatarUrl,tokenProvider:r,onConnected:()=>p.flushPendingCanvasLinks(),onReconnect:()=>p.onRelayReconnected(),logger:e.logger});t.setRelayClient(a),t.setAgentId(n.id),p.wireRelayActionHandler(),a.connect(),e.logger.info?.(`[beeos-claw] Canvas Relay multiplexed client connected (agentId=${n.id}, name=${n.name??"none"})`)};e.registerService(createCanvasRelayService({getAgent:y,onceAgentReady:e=>sharedAgentMappings.onceReady(e),initRelay:n,stopRelay:()=>t.getRelayClient()?.disconnect(),logger:e.logger})),e.logger.info?.("[beeos-claw] Canvas Relay configured")}else e.logger.warn?.("[beeos-claw] Canvas Relay unavailable: agentGatewayUrl or agentKeys missing");const r={stateManager:t,logger:e.logger,writeObs:e=>n(e),getActiveSessionId:e=>p.getSessionIdForToolCall(e),getPlatformAgentId:e=>p.getPlatformAgentIdForToolCall(e),getGatewaySessionKey:e=>p.getGatewaySessionKeyForToolCall(e),waitForAgentSync:()=>sharedAgentMappings.waitForSynchronization()},i=new FormSchemaRegistry,s=buildCronSchemas(a);i.register(s.create),i.register(s.update);const l=new ResourceDescriptorRegistry;l.register(CRON_RESOURCE);const c=e=>async(t,r,o)=>(p.preMapToolCallSession(t),e(t,r));e.registerTool({name:RENDER_UI_TOOL_NAME,description:RENDER_UI_TOOL_DESCRIPTION,parameters:RENDER_UI_TOOL_SCHEMA,execute:c(createRenderUiHandler(r))}),e.registerTool({name:CLOSE_UI_TOOL_NAME,description:CLOSE_UI_TOOL_DESCRIPTION,parameters:CLOSE_UI_TOOL_SCHEMA,execute:c(createCloseUiHandler(r))}),p.setCanvasState(t,{schemaRegistry:i,descriptorRegistry:l});const g=p.getFormBuilder();g&&e.registerTool({name:RENDER_FORM_TOOL_NAME,description:buildRenderFormDescription(i),parameters:RENDER_FORM_TOOL_SCHEMA,execute:c(createRenderFormHandler({registry:i,builder:g,logger:e.logger}))});const u=p.getResourceRenderer();if(u){generateActionTools(l,e,async(e,t)=>p.gatewayRequest(e,t),u,e.logger)}const d=buildToolRoutingHint(BEEOS_FILE_RESOURCE_ROUTING_RULE,BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME),m=new Set([RENDER_UI_TOOL_NAME,CLOSE_UI_TOOL_NAME,RENDER_FORM_TOOL_NAME]),h=256,f=new Map;if("function"==typeof e.on){try{e.on("before_prompt_build",(e,t)=>{if(t?.sessionKey){if(f.size>=h&&!f.has(t.sessionKey)){const e=f.keys().next().value;void 0!==e&&f.delete(e)}f.set(t.sessionKey,t.channelId),rememberDeliveryWorkspace(t.sessionKey,t.workspaceDir)}const r=isThirdPartyChannel(a,{sessionKey:t?.sessionKey,channelId:t?.channelId});return t?.sessionKey||r?{appendSystemContext:buildAppendSystemContext({thirdParty:r,canvasSystemPrompt:`${CANVAS_PRESENTATION_GATE}\n\n${CANVAS_SYSTEM_PROMPT}`,toolRoutingHint:d})}:{appendSystemContext:d}}),e.logger.debug?.("[beeos-claw] Canvas system prompt hook registered: before_prompt_build")}catch{e.logger.debug?.("[beeos-claw] before_prompt_build hook not supported")}try{e.on("before_tool_call",(e,t)=>{if(t?.sessionKey&&p.setPendingToolCallSessionKey(t.sessionKey),!m.has(e.toolName))return;const r=t?.sessionKey?f.get(t.sessionKey):void 0,o=isThirdPartyChannel(a,{sessionKey:t?.sessionKey,channelId:r}),n=canvasToolBlockReason({thirdParty:o,hasSession:Boolean(t?.sessionKey)});return n?{block:!0,blockReason:n}:void 0}),e.logger.debug?.("[beeos-claw] Canvas tool guard registered: before_tool_call")}catch{e.logger.debug?.("[beeos-claw] before_tool_call hook not supported")}}e.logger.info?.("[beeos-claw] Canvas tools registered (render_ui, close_ui, render_form + auto-action tools)")}else e.logger.info?.("[beeos-claw] Canvas disabled by config (canvasEnabled=false)");if(o.bridge.shell.enabled&&!0===o.legacyTerminalWsEnabled){const t=createTerminalWebSocketService({config:{port:o.terminalWsPort,token:agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):"",allowedOrigins:o.terminalWsAllowedOrigins},terminalMgr:sharedTerminalManager,logger:e.logger,writeObs:n});e.registerService({id:"beeos-terminal-ws",start(){t.start(),e.logger.info?.(`[beeos-claw] Terminal WS started on port ${o.terminalWsPort}`)},stop(){t.stop(),e.logger.info?.("[beeos-claw] Terminal WS stopped")}})}else o.bridge.shell.enabled?e.logger.info?.("[beeos-claw] Legacy static-token Terminal WS disabled (default)"):e.logger.info?.("[beeos-claw] Terminal/shell disabled by config (bridge.shell.enabled=false)");if(t.openclawConfig){const r=mirrorOpenClawConfig(t.openclawConfig);r.copied?e.logger.info?.(`[beeos-claw] mirrored openclaw config to ${r.destinationPath}`):e.logger.debug?.(`[beeos-claw] openclaw config mirror skipped: ${r.reason}`)}}const plugin={id:"beeos-claw",name:"beeos-claw",description:"BeeOS platform bridge plugin for OpenClaw. Provides file upload/download, ACP bridge, and observability.",version:PLUGIN_VERSION,register(e){if(_initializing)return;const t=planPluginRegistration(e.registrationMode,_fullRuntimeRegistered);if("skip"!==t){_initializing=!0;try{if(!hasRuntimeReplyApi(e.runtime))throw e.logger.error?.("[beeos-claw] FATAL: OpenClaw runtime.channel.reply.dispatchReplyFromConfig not exposed. Upgrade OpenClaw or revert beeos-claw."),new Error("openclaw_runtime_reply_api_unavailable");const r=(t,r)=>{registerUploadTools(e,t,r),registerConnectorMcpProxy(e,t),registerArouterLatencyRouting(e),registerArouterMediaProviders(e)};if("capabilities"===t&&sharedPluginContext){if(cachedCapabilityTools.length>0){const t=resolveCapabilityToolReplay({currentRegisterTool:e.registerTool,wrappedRegisterTool:wrappedRegisterTool,originalRegisterTool:rawRegisterTool}),r=replayCachedPluginTools(r=>t.call(e,r),cachedCapabilityTools);return registerArouterLatencyRouting(e),registerArouterMediaProviders(e),void e.logger.info?.(`[beeos-claw] capability re-register mode=${e.registrationMode} tools_only count=${r}`)}const t={current:sharedAcpServer??null};return r(sharedPluginContext,t),registerServices(e,sharedPluginContext,t),void e.logger.info?.(`[beeos-claw] capability re-register mode=${e.registrationMode} capabilities_only`)}const o=initializePlugin(e);if(!o)return;const n={current:null};installUnhandledRejectionObserver(e,o.writeObs,n),ensureRegisterToolCache(e),cachedCapabilityTools.length=0,r(o,n),agentKeys&&o.cfg.agentGatewayUrl&&(e.on?e.on("before_agent_finalize",fileDeliveryFinalizeDecision):e.logger.warn?.("[file-delivery] OpenClaw plugin hooks unavailable; finalization check disabled")),registerServices(e,o,n),sharedPluginContext=o,marksFullRuntimeRegistered(e.registrationMode,t)&&(_fullRuntimeRegistered=!0),_pluginRegisteredAt=Date.now(),e.logger.info?.("[beeos-claw] Plugin registered successfully")}finally{_initializing=!1}}else e.logger.info?.(`[beeos-claw] skip re-register mode=${e.registrationMode??"full"} already_registered`)}};export default plugin;
1
+ import{registerManagedConnectorTools}from"./connectors/managed-connector-tools.js";import{prepareNativeOutputTool,consumeNativeOutputTool}from"./runtime/native-output-file-attempt.js";import{uploadNativeOutputFile}from"./upload/upload-file.js";import{NativeInputFilesHttpClient}from"./runtime/native-input-files-http.js";import{fileDeliveryFinalizeDecision}from"./upload/finalize-hook.js";import{resolveConfigWithMeta,mirrorOpenClawConfig}from"./config.js";import{hasRuntimeReplyApi}from"./runtime/reply-router.js";import{PromptRunStore}from"./runtime/prompt-run-store.js";import{createMcpNativeProjectionNudge,fingerprintMcpServers}from"./acp-gateway/mcp-native-projection-nudge.js";import{createImHotPathDeferral}from"./runtime/im-hot-path-deferral.js";import{SessionWriteGate}from"./acp-gateway/session-write-gate.js";import{OpenClawSessionWriteQuiescence}from"./runtime/openclaw-session-write-quiescence.js";import{SessionMutationCoordinator}from"./runtime/session-mutation-coordinator.js";import{scheduleProcessRuntimeRestart}from"./runtime/runtime-restart-scheduler.js";import{createImInboundHandler}from"./im-inbound-handler.js";import{AgentGatewayClient,NodeRuntimeDeliveryPort,agentIdentityFromKeyPair,loadAgentKeyPair,signAgentMessage}from"@beeos-ai/cloud-harness-sdk";import{MessageServiceConversationRunBoundary}from"./runtime/message-service-conversation-run-boundary.js";import{AutomationTurnPolicy}from"./automation/turn-policy.js";import{registerAutomationTools}from"./automation/tools.js";import{extractBeeosConversationIdFromSessionKey}from"./runtime/openclaw-session-key-resolution.js";import{setOpenClawConfigSnapshot}from"./runtime/openclaw-session-model.js";import{BeeosClawMessageClientProcessOwner,createBeeosClawMessageTokenProvider}from"./message-client-composition.js";import{MessageProjectionInboundConsumer}from"./message-projection-inbound-consumer.js";import{MessageClientTerminalStateRecovery}from"./runtime/message-client-terminal-state-recovery.js";import{RuntimeAuthorityMessageBusLifecycle}from"./runtime/runtime-authority-message-bus-lifecycle.js";import{createNativeCloudChatComposition,nativeCloudChatAuthorityFromRuntimeAuthority}from"./runtime/native-cloud-chat-composition.js";import{MSConnectionStatusSnapshot}from"./runtime/ms-connection-status.js";import{FileInboundExecutionJournal}from"./inbound-execution-journal.js";import{completeA2ATask,registerA2ATools,TaskHandleRegistry}from"./a2a/tools.js";import{BEEOS_UPLOAD_TOOL_NAME,BEEOS_UPLOAD_TOOL_SCHEMA,BEEOS_UPLOAD_TOOL_DESCRIPTION,REQUEST_TIMEOUT_MS as BEEOS_UPLOAD_REQUEST_TIMEOUT_MS,executeUpload}from"./upload/tool.js";import{BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME,BEEOS_DESKTOP_SCREENSHOT_TOOL_SCHEMA,BEEOS_DESKTOP_SCREENSHOT_TOOL_DESCRIPTION,executeDesktopScreenshot}from"./upload/desktop-screenshot-tool.js";import{BEEOS_LIST_FILES_TOOL_NAME,BEEOS_LIST_FILES_TOOL_SCHEMA,BEEOS_LIST_FILES_TOOL_DESCRIPTION,executeListFiles}from"./files/list-tool.js";import{BEEOS_FETCH_FILE_TOOL_NAME,BEEOS_FETCH_FILE_TOOL_SCHEMA,BEEOS_FETCH_FILE_TOOL_DESCRIPTION,executeFetchFile}from"./files/fetch-tool.js";import{writeUploadToolResult,cleanupUploadToolResultCache}from"./upload/result-cache.js";import{handleFileStage}from"./upload/file-stage.js";import{handleStatusRequest}from"./status.js";import{ACPServer}from"./acp-server.js";import{GatewayClient}from"./gateway-client.js";import{createObsEventWriter}from"./observability.js";import{resolvePluginVersion}from"./plugin-version.js";import{createTerminalWebSocketService}from"./terminal/websocket.js";import{TerminalManager}from"./terminal/session-manager.js";import{readDiscoveryCache,writeDiscoveryCache}from"./discovery-cache.js";import{setClaimedCloudRuntimeInstanceId,setUploadDeps}from"./upload/upload-file.js";import{registerLocalFileExtractor}from"./upload/local-file-extractors.js";import{browserScreenshotExtractor}from"./browser/screenshot-extractor.js";import{deliverableFileExtractor}from"./upload/deliverable-extractor.js";import{observeToolCallForDelivery,rememberDeliveryWorkspace}from"./upload/delivery-observe.js";import{BEEOS_FILE_RESOURCE_ROUTING_RULE}from"./files/beeos-file-uri.js";import{marksFullRuntimeRegistered,planPluginRegistration,replayCachedPluginTools,resolveCapabilityToolReplay}from"./plugin-registration-plan.js";import{buildAppendSystemContext,buildToolRoutingHint,canvasToolBlockReason}from"./prompt-system-context.js";import{CONNECTOR_MCP_PROXY_PATH,handleConnectorMcpRequest}from"./mcp-connector-proxy.js";import{CanvasStateManager}from"./canvas/state.js";import{CanvasRelayClient}from"./canvas/relay-client.js";import{createCanvasRelayService}from"./canvas/relay-service.js";import{RENDER_UI_TOOL_NAME,RENDER_UI_TOOL_DESCRIPTION,RENDER_UI_TOOL_SCHEMA,CLOSE_UI_TOOL_NAME,CLOSE_UI_TOOL_DESCRIPTION,CLOSE_UI_TOOL_SCHEMA,createRenderUiHandler,createCloseUiHandler,CANVAS_PRESENTATION_GATE,CANVAS_SYSTEM_PROMPT}from"./canvas/tools.js";import{FormSchemaRegistry}from"./surface/form-schema-registry.js";import{buildCronSchemas}from"./surface/cron-schemas.js";import{RENDER_FORM_TOOL_NAME,RENDER_FORM_TOOL_SCHEMA,buildRenderFormDescription,createRenderFormHandler}from"./surface/render-form-tool.js";import{ResourceDescriptorRegistry}from"./surface/resource-descriptor-registry.js";import{CRON_RESOURCE}from"./surface/cron-resource.js";import{generateActionTools}from"./surface/action-tool-generator.js";import{buildThirdPartyChannelSet,isThirdPartyChannel}from"./channel-detection.js";import{registerArouterMediaProviders}from"./media/index.js";import{homedir}from"node:os";import{join}from"node:path";import{RuntimeProductionAuthority,cloudRuntimeTargetInstanceId}from"./runtime/runtime-production-authority.js";import{FileRuntimeCommandJournal}from"./runtime/runtime-command-journal.js";import{FileRuntimePoisonDeliveryJournal}from"./runtime/runtime-poison-delivery-journal.js";import{OpenClawNativeMcpProjection}from"./acp-gateway/openclaw-native-mcp-projection.js";import{LocalEncryptedCredentialReferenceVault}from"./acp-gateway/mcp-credential-reference-port.js";import{AgentGatewayGrantJwksReadinessAdapter,CloudRuntimeServiceTransportReadinessAdapter,RuntimeServiceTransportReadinessAdapter,createRuntimeServiceProductionCandidate}from"./runtime/runtime-service-production-candidate.js";import{fetchRuntimeLeaseAttempt}from"./runtime/message-service-runtime-authenticated-fetch.js";import{MessageServiceCronDeliveryHttpAuthority}from"./runtime/message-service-cron-delivery-http-authority.js";import{AgentMappingRegistry}from"./runtime/agent-mapping-registry.js";import{OpenClawRuntimeProcessOwner}from"./runtime/openclaw-runtime-process-owner.js";import{AgentGatewayHttpProjectionTransport,AgentGatewayTemplateOriginReporter,AgentProjectionProduction,OpenClawAgentProjectionSource}from"./runtime/agent-projection-production.js";import{MessageServiceRunOutputChannel}from"./runtime/message-service-run-output-channel.js";import{AssistantMessageCommitRouter}from"./runtime/assistant-message-commit-router.js";import{ToolResultObservationRouter}from"./runtime/tool-result-observation-router.js";import{ModelCallObservationRouter,registerModelCallObservationHooks}from"./runtime/model-call-observability.js";import{registerArouterLatencyRouting}from"./runtime/arouter-latency-routing.js";import{createPeerRunOutputRouterFactory}from"./runtime/run-output-composition.js";const PLUGIN_VERSION=resolvePluginVersion();let agentKeys=null,agentGateway=null,sharedCanvasState=null,sharedAcpServer=null;const sharedSessionWriteGate=new SessionWriteGate,sharedPromptRunStore=new PromptRunStore,sharedAutomationTurnPolicy=new AutomationTurnPolicy;let lastOpenclawConfig;const sharedMcpNativeProjectionNudge=createMcpNativeProjectionNudge({getActiveImRunCount:()=>sharedPromptRunStore.size(),nudge:()=>{sharedAcpServer?.nudgeMcpNativeProjection()}}),sharedImHotPathDeferral=createImHotPathDeferral({getActiveImRunCount:()=>sharedPromptRunStore.size()});sharedPromptRunStore.setOnBecameIdle(()=>{sharedMcpNativeProjectionNudge.flushIfIdle({fingerprint:fingerprintMcpServers(lastOpenclawConfig)}),sharedImHotPathDeferral.notifyIdle()});const sharedAssistantMessageCommitRouter=new AssistantMessageCommitRouter,sharedToolResultObservationRouter=new ToolResultObservationRouter,sharedModelCallObservationRouter=new ModelCallObservationRouter;let sharedSessionMutationCoordinator,sharedRuntimeAuthority,sharedNativeCloudChat,warmClaimAttached=!1,sharedWriteObs=()=>{};const sharedMSConnectionStatus=new MSConnectionStatusSnapshot,sharedAgentMappings=new AgentMappingRegistry;let sharedGatewayClient,sharedRuntimeOwner,sharedAgentProjection,sharedRuntimeAgentCapabilities,sharedMcpProjection,sharedMcpCredentialVault;const sharedMessageClientOwner=new BeeosClawMessageClientProcessOwner;let sharedActiveMessageConsumer,sharedInboundExecutionJournal;const sharedTerminalManager=new TerminalManager;let _initializing=!1,_pluginRegisteredAt=0,_fullRuntimeRegistered=!1;const cachedCapabilityTools=[];let rawRegisterTool,wrappedRegisterTool;const ensureRegisterToolCache=e=>{rawRegisterTool||(rawRegisterTool=e.registerTool.bind(e),wrappedRegisterTool=e=>(cachedCapabilityTools.push(e),rawRegisterTool(e)),e.registerTool=wrappedRegisterTool)};function agentKeyPairToIdentity(e){return{publicKeyBase64:()=>Buffer.from(e.publicKey).toString("base64"),sign:async t=>signAgentMessage(t,e.privateKey)}}let sharedPluginContext=null,unhandledRejectionObserverInstalled=!1;function installUnhandledRejectionObserver(e,t,r){unhandledRejectionObserverInstalled||(unhandledRejectionObserverInstalled=!0,process.on("unhandledRejection",r=>{const o=r instanceof Error?r.message:String(r),a=r instanceof Error?r.stack:void 0;e.logger.error?.(`[beeos-claw] unhandledRejection: ${o}${a?`\n${a}`:""}`),t({component:"plugin",domain:"fatal",name:"unhandled_rejection",severity:"error",summary:o,error:{code:"unhandled_rejection",message:o,...a?{stack:a}:{}}})}),process.on("uncaughtException",r=>{const o=r instanceof Error?r.message:String(r);e.logger.error?.(`[beeos-claw] uncaughtException: ${r instanceof Error?r.stack??r.message:String(r)}`),t({component:"plugin",domain:"fatal",name:"uncaught_exception",severity:"error",summary:o,error:{code:"uncaught_exception",message:o}})}))}function initializePlugin(e){let t,r;try{t=e.runtime?.config?.loadConfig?.()}catch{}try{r=resolveConfigWithMeta({pluginConfig:e.pluginConfig??{},openclawConfig:t})}catch(t){return e.logger.error?.(`[beeos-claw] Failed to resolve config: ${t instanceof Error?t.message:String(t)}`),null}const o=r.config,a=buildThirdPartyChannelSet(t);a.size>0&&e.logger.info?.(`[beeos-claw] Third-party channels detected: ${[...a].join(", ")}`);const n=o.log.enabled?createObsEventWriter({dir:o.log.dir,redaction:{gatewayToken:o.gateway.token},logger:e.logger}):()=>{};n({component:"plugin",domain:"lifecycle",name:"lifecycle.startup",severity:"info",payload:{pluginVersion:PLUGIN_VERSION,pid:process.pid,nodeVersion:process.version,cwd:process.cwd()}}),n({component:"plugin",domain:"config",name:"config.resolved",severity:"info",payload:{config:o,sources:r.sources,openclawConfigPath:r.openclawConfigPath}});for(const t of r.validation)n({component:"plugin",domain:"config",name:"config.validation",severity:t.severity,summary:t.message,error:{code:t.code,message:t.message,nextSteps:t.nextSteps}}),"error"===t.severity?e.logger.error?.(`[beeos-claw] ${t.message}`):e.logger.warn?.(`[beeos-claw] ${t.message}`);if(r.validation.some(e=>"error"===e.severity)&&e.logger.error?.("[beeos-claw] Plugin has configuration errors — some features may not work."),o.keyFile)try{agentKeys=loadAgentKeyPair(o.keyFile),agentGateway=o.agentGatewayUrl?new AgentGatewayClient({baseUrl:o.agentGatewayUrl,identity:agentIdentityFromKeyPair(agentKeys),onRetry:({method:t,path:r,attempt:o,delayMs:a,error:n})=>e.logger.warn?.(`[beeos-claw] Agent Gateway ${t} ${r} retry ${o} in ${a}ms: ${n instanceof Error?n.message:String(n)}`)}):null;const t=Buffer.from(agentKeys.publicKey).toString("base64");e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (publicKey: ${t})`)}catch(t){e.logger.warn?.(`[beeos-claw] Failed to load agent key pair: ${t}`),e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (no key pair — signed requests disabled)`)}else e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (no keyFile configured)`);return agentGateway&&(setUploadDeps({gateway:agentGateway,logger:e.logger}),registerLocalFileExtractor(browserScreenshotExtractor),registerLocalFileExtractor(deliverableFileExtractor),e.logger.info?.("[beeos-claw] Upload deps + local file extractors registered")),lastOpenclawConfig=t,sharedWriteObs=n,setOpenClawConfigSnapshot(t),{cfg:o,writeObs:n,thirdPartyChannels:a,openclawConfig:t}}function registerUploadTools(e,t,r){const{cfg:o,writeObs:a}=t,n=Boolean(pluginCloudRuntimeTarget(e));if(n){if(!e.on)throw new Error("native output Files Host hook unavailable");e.on("before_tool_call",(e,t)=>{if(e.toolName===BEEOS_UPLOAD_TOOL_NAME){if(e.runId&&t.runId&&e.runId!==t.runId||e.toolCallId&&t.toolCallId&&e.toolCallId!==t.toolCallId)return{block:!0,blockReason:"native output file Host correlation conflict"};try{prepareNativeOutputTool(e.runId??t.runId,e.toolCallId??t.toolCallId)}catch{return{block:!0,blockReason:"native output file trusted capability unavailable"}}}})}cleanupUploadToolResultCache().catch(t=>{e.logger.warn?.(`[beeos_upload_file] cache cleanup failed on startup: ${String(t)}`)}),e.registerTool({name:BEEOS_UPLOAD_TOOL_NAME,description:BEEOS_UPLOAD_TOOL_DESCRIPTION,parameters:BEEOS_UPLOAD_TOOL_SCHEMA,async execute(t,r,i){const s=n?consumeNativeOutputTool(t):void 0,l=await executeUpload(r,agentGateway,i,s?(e,t)=>uploadNativeOutputFile(e,o.agentGatewayUrl,s,t,i,BEEOS_UPLOAD_REQUEST_TIMEOUT_MS):void 0,e.logger);return e.logger.debug?.(`[beeos_upload_file] toolCallId=${t} ok=${l.ok}`),a({component:"upload-tool",domain:"tool",name:l.ok?"upload.success":"upload.failure",severity:l.ok?"info":"warn",payload:{toolCallId:t,ok:l.ok,fileCount:l.files?.length??0,error:l.error}}),(async r=>{try{await writeUploadToolResult(t,BEEOS_UPLOAD_TOOL_NAME,r),await cleanupUploadToolResultCache()}catch(r){e.logger.warn?.(`[beeos_upload_file] persist cache failed toolCallId=${t}: ${String(r)}`)}return r})(l)}}),e.registerTool({name:BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME,description:BEEOS_DESKTOP_SCREENSHOT_TOOL_DESCRIPTION,parameters:BEEOS_DESKTOP_SCREENSHOT_TOOL_SCHEMA,async execute(t,r,o){e.logger.debug?.(`[beeos_desktop_screenshot] toolCallId=${t} params=${JSON.stringify(r)}`);const n=await executeDesktopScreenshot(r,agentGateway,o);return e.logger.debug?.(`[beeos_desktop_screenshot] toolCallId=${t} ok=${n.ok}`),a({component:"desktop-screenshot-tool",domain:"tool",name:n.ok?"desktop_screenshot.success":"desktop_screenshot.failure",severity:n.ok?"info":"warn",payload:{toolCallId:t,ok:n.ok,path:n.path,fileCount:n.files?.length??0,error:n.error}}),(async r=>{try{await writeUploadToolResult(t,BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME,r),await cleanupUploadToolResultCache()}catch(r){e.logger.warn?.(`[beeos_desktop_screenshot] persist cache failed toolCallId=${t}: ${String(r)}`)}return r})(n)}}),e.registerHttpRoute({path:"/beeos/files/stage",auth:"gateway",async handler(e,r){await handleFileStage(e,r,t.cfg)}}),e.registerHttpRoute({path:"/beeos/status",auth:"plugin",handler(e,t){handleStatusRequest(e,t,{publicKey:agentKeys?.publicKey??null,pluginVersion:PLUGIN_VERSION})}}),e.registerTool({name:BEEOS_LIST_FILES_TOOL_NAME,description:BEEOS_LIST_FILES_TOOL_DESCRIPTION,parameters:BEEOS_LIST_FILES_TOOL_SCHEMA,async execute(t,r,o){e.logger.debug?.(`[beeos_list_files] toolCallId=${t} params=${JSON.stringify(r)}`);const n=await executeListFiles(r,agentGateway,o);return a({component:"file-list-tool",domain:"tool",name:n.ok?"list_files.success":"list_files.failure",severity:n.ok?"info":"warn",payload:{toolCallId:t,ok:n.ok,fileCount:n.files?.length??0,error:n.error}}),n}}),e.registerTool({name:BEEOS_FETCH_FILE_TOOL_NAME,description:BEEOS_FETCH_FILE_TOOL_DESCRIPTION,parameters:BEEOS_FETCH_FILE_TOOL_SCHEMA,async execute(t,r,o){e.logger.debug?.(`[beeos_fetch_file] toolCallId=${t} params=${JSON.stringify(r)}`);const n=await executeFetchFile(r,agentGateway,{signal:o,resolvePath:e.resolvePath});return a({component:"file-fetch-tool",domain:"tool",name:n.ok?"fetch_file.success":"fetch_file.failure",severity:n.ok?"info":"warn",payload:{toolCallId:t,ok:n.ok,path:n.path,size:n.size,error:n.error}}),n}})}function registerConnectorMcpProxy(e,t){e.registerHttpRoute({path:CONNECTOR_MCP_PROXY_PATH,auth:"plugin",async handler(t,r){await handleConnectorMcpRequest(t,r,{gateway:agentGateway,logger:e.logger})}})}function registerServices(e,t,r){const{cfg:o,writeObs:a,thirdPartyChannels:n}=t;if(sharedAutomationTurnPolicy.disable(),"function"==typeof e.on)try{e.on("before_tool_call",(e,t)=>sharedAutomationTurnPolicy.check(e.toolName,{sessionKey:t?.sessionKey,runId:t?.runId??e.runId}),{priority:100}),sharedAutomationTurnPolicy.enable()}catch{e.logger.warn?.("[beeos-claw] Automation Wake disabled: tool guard unavailable")}if("function"!=typeof e.on){if(o.messageBus.enabled)throw new Error("openclaw_before_message_write_hook_unavailable")}else registerModelCallObservationHooks((t,r)=>e.on(t,r),sharedModelCallObservationRouter),e.on("before_message_write",(t,r)=>{const o=t.sessionKey??r.sessionKey;if(!o)return void e.logger.debug?.("[before_message_write] ignored assistant write without sessionKey");sharedAssistantMessageCommitRouter.route(o,t.message)||e.logger.debug?.(`[before_message_write] no active IM commit target sessionKey=${o} active_targets=${sharedAssistantMessageCommitRouter.size()}`)}),e.on("after_tool_call",(t,r)=>{const o=r.sessionKey,a=t.toolCallId??r.toolCallId,n=t.toolName||r.toolName;if(!o||!a||!n)return void e.logger.debug?.(`[after_tool_call] ignored structured result without correlation sessionKey=${o??"missing"} toolCallId=${a??"missing"}`);observeToolCallForDelivery(t,o);sharedToolResultObservationRouter.route(o,{toolCallId:a,toolName:n,rawResult:t.result,isError:Boolean(t.error)})||e.logger.debug?.(`[after_tool_call] no active IM observation target sessionKey=${o} active_targets=${sharedToolResultObservationRouter.size()}`)});const i=agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):void 0,s=join(process.env.OPENCLAW_HOME||join(homedir(),".openclaw"),"beeos"),l=sharedInboundExecutionJournal??=new FileInboundExecutionJournal(join(s,"inbound-execution-journal.v1.jsonl"));sharedMcpProjection??=new OpenClawNativeMcpProjection,!sharedMcpCredentialVault&&agentKeys&&i&&(sharedMcpCredentialVault=new LocalEncryptedCredentialReferenceVault(join(s,"mcp-credential-vault.json"),i,agentKeys.privateKey));const c=pluginCloudRuntimeTarget(e);if(c&&(!agentKeys||!agentGateway))throw new Error("Cloud runtime authority requires an agent identity and gateway transport");const u=sharedRuntimeAuthority?.cloudTargetInstanceId;if(u&&c&&u!==c)throw new Error("Cloud runtime authority target changed during process lifetime");if(sharedRuntimeAuthority&&!u&&c&&sharedRuntimeAuthority.bindCloudTarget(c),!sharedRuntimeAuthority&&agentKeys&&agentGateway&&(sharedRuntimeAuthority=new RuntimeProductionAuthority({stateDirectory:s,gateway:agentGateway,keys:agentKeys,targetInstanceId:c,logger:e.logger,getMSConnectionStatus:e=>sharedMSConnectionStatus.get(e)})),sharedGatewayClient??=new GatewayClient({url:o.gateway.url,token:o.gateway.token||"",clientId:o.gateway.clientId,openclawCanvasCompat:!!o.openclawCanvasCompat,retry:{baseMs:o.retry.baseMs,maxMs:o.retry.maxMs,maxAttempts:o.retry.maxAttempts}}),sharedRuntimeAgentCapabilities??={canvas:o.canvasEnabled,terminal:!1,webSsh:!1,fileSystem:!0,image:!0,audio:!1,mcp:!0,cron:!0,streaming:!0,pushNotifications:o.messageBus.enabled,...o.messageBus.enabled&&sharedAutomationTurnPolicy.isReady()&&agentGateway?{automationWake:!0}:{}},!sharedAgentProjection&&sharedRuntimeAuthority&&agentGateway){const t=sharedRuntimeAuthority;sharedAgentProjection=new AgentProjectionProduction({authority:t,stateFile:join(t.stateDirectory,"runtime-agent-projection.json"),journal:t.journal,identities:t.identities,source:new OpenClawAgentProjectionSource(()=>sharedGatewayClient),transport:new AgentGatewayHttpProjectionTransport({gateway:agentGateway,getRuntimeLeaseCredential:e=>{const r=t.authorityLease;if(!r||r.instanceId!==e.instanceId||r.leaseId!==e.leaseId||r.runtimeEpoch!==e.runtimeEpoch||r.handlerIdentity!==e.handlerIdentity)throw new Error("agent projection fenced by current runtime lease");return r.runtimeLeaseCredential},onAccepted:t=>{0!==t.size&&sharedAgentMappings.replace(t).catch(t=>{e.logger.warn?.("[agent-projection] mapping publication failed: "+(t instanceof Error?t.message:String(t)))})}}),capabilities:sharedRuntimeAgentCapabilities,logger:e.logger})}sharedRuntimeOwner??=new OpenClawRuntimeProcessOwner(sharedGatewayClient,sharedAgentProjection,e.logger);const g=sharedRuntimeOwner;sharedSessionMutationCoordinator??=new SessionMutationCoordinator(sharedSessionWriteGate,new OpenClawSessionWriteQuiescence(e.logger,{agentId:o.gateway.agentId||"main"}),e.logger,{onRecoveryRequired:t=>{scheduleProcessRuntimeRestart(t,e.logger)}});const d=sharedSessionMutationCoordinator;if(!sharedAcpServer){const t=sharedRuntimeAuthority&&agentGateway?new AgentGatewayTemplateOriginReporter({gateway:agentGateway}):void 0;sharedAcpServer=new ACPServer(o,e.logger,d,a,agentGateway??void 0,i,n,sharedTerminalManager,sharedRuntimeAuthority,void 0,sharedMcpProjection,sharedMcpCredentialVault,{gateway:g.client,agentProjection:sharedAgentProjection,markAgentProjectionDirty:()=>sharedAgentProjection?.markDirty(),templateOriginReporter:t,agentMappings:sharedAgentMappings,agentCapabilities:sharedRuntimeAgentCapabilities,createRunOutputRouter:createPeerRunOutputRouterFactory(new MessageServiceRunOutputChannel({getClient:()=>sharedMessageClientOwner.current?.client??null,logger:e.logger,writeObs:a})),runExclusive:(t,r,o)=>sharedImHotPathDeferral.runExclusive(t,r,e.logger,o)})}const m=sharedAcpServer,p=()=>sharedAgentMappings.snapshot()?.values().next().value;r.current=m,sharedMcpNativeProjectionNudge.request({registrationMode:e.registrationMode,fingerprint:fingerprintMcpServers(t.openclawConfig),logger:e.logger});const y=sharedPromptRunStore,{enabled:h,principalId:f,a2aEnabled:v}=o.messageBus;let w;!c&&o.agentGatewayUrl&&agentKeys&&(w=createBeeosClawMessageTokenProvider({agentGatewayUrl:o.agentGatewayUrl,identity:agentKeyPairToIdentity(agentKeys)}));const C=process.env.MESSAGE_RUNTIME_DELIVERY_KEY?.trim(),R=f||process.env.BEEOS_PRINCIPAL_ID||"",b=w?sharedMessageClientOwner.configure({tokenProvider:w,identityId:R,...o.messageBus.serviceUrl?{serviceUrl:o.messageBus.serviceUrl}:{},logger:e.logger,...sharedRuntimeAuthority&&C?{runtimeDelivery:{scopedDeliveryKey:C,authority:{currentLease:()=>{const e=sharedRuntimeAuthority?.authorityLease,t=sharedRuntimeAuthority?.currentConsumerBinding();return e&&t?{...e,journalStoreId:t.journalStoreId,journalGeneration:t.journalGeneration}:null}}}}:{}}):void 0,S=c&&o.messageBus.serviceUrl&&sharedRuntimeAuthority?new NodeRuntimeDeliveryPort({serviceOrigin:async()=>o.messageBus.serviceUrl},{currentLease:()=>{const e=sharedRuntimeAuthority?.authorityLease,t=sharedRuntimeAuthority?.currentConsumerBinding();return e&&t&&e.instanceId===c?{...e,journalStoreId:t.journalStoreId,journalGeneration:t.journalGeneration}:null},subscribeAuthority:e=>sharedRuntimeAuthority.subscribeAuthority(e)}):void 0;attachNativeCloudChat(e,o);const _=sharedRuntimeAuthority,O=o.messageBus.serviceUrl;b&&_&&O&&C?m.setCronConversationDelivery({deliver:async e=>{const t=_.authorityLease;if(!t)throw new Error("current runtime authority lease unavailable for cron delivery");const r=new MessageServiceCronDeliveryHttpAuthority({messageServiceUrl:O,scopedDeliveryKey:C,fetchAuthorized:(e,t)=>fetchRuntimeLeaseAttempt(e,t??{})});return await r.deliver({...e,runtimeLeaseCredential:t.runtimeLeaseCredential})}}):m.setCronConversationDelivery(void 0);const E=sharedRuntimeAuthority?.journal??new FileRuntimeCommandJournal(join(s,"runtime-command-journal.json"),void 0,void 0,{onMaintenanceError:t=>e.logger.error?.(`[runtime-journal] event=checkpoint_failed trigger=threshold error=${t instanceof Error?t.message:String(t)}`)}),A=g.createRegistrationToken();e.registerService({id:"beeos-acp",async start(){const t=Date.now(),r=_pluginRegisteredAt?t-_pluginRegisteredAt:-1;e.logger.info?.(`[beeos-claw] beeos-acp service start() begin, sincePluginRegister=${r}ms, bridge.url=${o.bridge.url||"(empty)"}`);const a=await createRuntimeServiceProductionCandidate({...agentGateway?{authorizationAdapter:new AgentGatewayGrantJwksReadinessAdapter({gateway:agentGateway})}:{},onGrantJwksWarm:t=>{t.ready?e.logger.info?.("[beeos-claw] Gateway grant keyset loaded"):e.logger.warn?.(`[beeos-claw] Gateway grant keyset not ready yet (attempt ${t.attempt}): ${t.error instanceof Error?t.error.message:String(t.error)}`)},...b&&agentGateway&&C?{transportAdapter:new RuntimeServiceTransportReadinessAdapter({gateway:agentGateway,messageService:b.nodeTransport,messageClient:b.client,configuredServiceUrl:o.messageBus.serviceUrl,scopedDeliveryKey:C})}:{},...S&&agentGateway&&o.messageBus.serviceUrl?{cloudTransportAdapter:new CloudRuntimeServiceTransportReadinessAdapter({gateway:agentGateway,configuredServiceUrl:o.messageBus.serviceUrl,runtimeDelivery:S,...sharedNativeCloudChat?{sessionNewConversation:sharedNativeCloudChat.sessionNewConversation,nativePrompt:{http:sharedNativeCloudChat.http,inputFiles:new NativeInputFilesHttpClient(o.agentGatewayUrl,()=>sharedRuntimeAuthority.authorityLease,(e,t)=>fetch(e,t)),runBoundary:new MessageServiceConversationRunBoundary({transport:{start:e=>S.startConversationRun(e),finish:e=>S.finishConversationRun(e)}}),host:{resolveNativePromptSessionKey:(e,t)=>m.resolveNativePromptSessionKey(e,t),prepareNativePromptModel:(e,t,r)=>m.prepareNativePromptModel(e,t,r),runtime:e.runtime,pluginConfig:o,logger:e.logger,promptRunStore:y,assistantMessageCommitRouter:sharedAssistantMessageCommitRouter,toolResultObservationRouter:sharedToolResultObservationRouter,modelCallObservationRouter:sharedModelCallObservationRouter,sessionMutationCoordinator:d,abortTransport:{chatAbort:(e,t)=>m.chatAbort(e,t)},activeRunAuthority:m.getActiveRunAuthority(),waitIfExclusive:(t,r)=>sharedImHotPathDeferral.waitIfExclusive(t,e.logger,r).then(()=>{})}}}:{}})}:{},commandJournal:E,poisonJournal:new FileRuntimePoisonDeliveryJournal(join(s,"runtime-poison-deliveries.json")),onConsumerDeliveryError:t=>{const r=null!==t&&"object"==typeof t?t:{},o=e=>"string"==typeof e&&e.length>0&&e.length<=256&&!/[\u0000-\u001f\u007f]/.test(e)?JSON.stringify(e):JSON.stringify("unavailable"),a="string"==typeof r.code&&/^[A-Za-z0-9_.:-]{1,64}$/.test(r.code)?r.code:"unavailable",n="number"==typeof r.status&&Number.isInteger(r.status)&&r.status>=100&&r.status<=599?String(r.status):"unavailable";e.logger.error?.(`[runtime-service] delivery worker failed before acknowledgement; delivery retained for retry: operation_id=${o(r.operationId)} delivery_id=${o(r.deliveryId)} code=${a} status=${n}`)},onConsumerLeaseStarvation:({starvedForMs:t,recovered:r})=>{const o=Math.round(t/1e3);r?e.logger.info?.(`[runtime-service] runtime authority lease restored after ${o}s without delivery reads`):e.logger.warn?.(`[runtime-service] no runtime authority lease for ${o}s; delivery reads suspended, queued runtime operations (model switch, session control) will not be consumed`)},onConsumerRequestFailure:t=>e.logger.error?.(`[runtime-service] request failed operationId=${t.operationId} method=${t.method}: ${t.error instanceof Error?t.error.stack??t.error.message:String(t.error)}`)});if(sharedRuntimeAuthority?.setRuntimeServiceMethods("ready"===a.status?a.serviceMethods:[]),sharedRuntimeAuthority?.setRuntimeResourceBindingContractRevision("ready"===a.status?a.resourceBindingContractRevision:void 0),m.setRuntimeRpcConsumerFactory("ready"===a.status?a.factory:void 0),"unavailable"===a.status?e.logger.warn?.("[runtime-service] capability fenced: "+a.blockers.map(e=>e.id).join(",")):a.capabilityBlockers.length&&e.logger.warn?.("[runtime-service] method capability fenced: "+a.capabilityBlockers.map(e=>e.method).join(",")),!o.bridge.url&&agentGateway){const t=Date.now(),r=await agentGateway.bridge.config();if(e.logger.info?.(`[beeos-claw] bridge discovery took ${Date.now()-t}ms result=${r?.url??"null"}`),r)o.bridge.url=r.url,writeDiscoveryCache({bridge:{url:r.url,discoveredAt:Date.now()}}),e.logger.info?.(`[beeos-claw] Bridge URL discovered from Agent Gateway: ${r.url}`);else{const t=readDiscoveryCache();t?.bridge?.url?(o.bridge.url=t.bridge.url,e.logger.info?.(`[beeos-claw] Bridge URL from cache (GW unreachable): ${t.bridge.url}`)):e.logger.debug?.("[beeos-claw] Bridge URL not available (no GW, no cache) — bridge disabled")}}await g.acquire(A);try{await m.start(o.bridge.url||void 0)}catch(e){throw await g.release(A),e}e.logger.info?.(`[beeos-claw] ACP Server started (total service start: ${Date.now()-t}ms)`)},async stop(){try{await g.release(A)}finally{await m.stop()}await E.checkpoint(),e.logger.info?.("[runtime-service] command journal checkpoint completed"),e.logger.info?.("[beeos-claw] ACP Server stopped")}});if(h&&void 0!==w&&w){const t=sharedMessageClientOwner.createRegistrationToken(),r=async(e,t)=>{const r=await w(e);if(!r.identityId||r.identityId!==e)throw new Error("Message SDK token identity did not match the current runtime authority");return{principalId:e,runtimeEpoch:t}},o=(e,t,r)=>({getLocalAgentId:()=>t,resolveLocalAgentId:e=>e===r?t:void 0,getDefaultPlatformAgent:()=>({instanceId:e.principalId}),ensureImInboundSession:(e,t,r,o)=>{m.ensureImInboundSession(e,t,r,o)},chatAbort:(e,t)=>m.chatAbort(e,t)}),n=sharedRuntimeAuthority?new RuntimeAuthorityMessageBusLifecycle({authority:sharedRuntimeAuthority,logger:e.logger,bus:{connect:async n=>{await sharedMessageClientOwner.acquire(t,async t=>{const i=await r(n.instanceId,n.runtimeEpoch),s=t.client,c={leaseId:n.leaseId,runtimeEpoch:n.runtimeEpoch};sharedMSConnectionStatus.bind(c);const u=new Map,g=new MessageProjectionInboundConsumer({client:s,bindings:()=>{const t=sharedRuntimeAuthority?.authorityLease;if(!t||t.instanceId!==i.principalId||t.runtimeEpoch!==i.runtimeEpoch)return[];const r=sharedAgentMappings.snapshot();return r?[...r.entries()].flatMap(([r,n])=>{if(!n.id||n.instanceId!==i.principalId)return[];let l=u.get(n.id);return l&&l.localAgentId===r||(l={localAgentId:r,inbound:createImInboundHandler({automationTurnPolicy:sharedAutomationTurnPolicy,runtime:e.runtime,pluginConfig:e.pluginConfig,client:s,localServer:o(i,r,n.id),promptRunStore:y,waitIfExclusive:(t,r)=>sharedImHotPathDeferral.waitIfExclusive(t,e.logger,r).then(()=>{}),assistantMessageCommitRouter:sharedAssistantMessageCommitRouter,toolResultObservationRouter:sharedToolResultObservationRouter,modelCallObservationRouter:sharedModelCallObservationRouter,sessionMutationCoordinator:d,logger:e.logger,writeObs:a,principalIdOverride:i.principalId,activeRunAuthority:m.getActiveRunAuthority(),applyTurnModel:(e,t)=>m.applyImTurnModel(e,t),restoreTurnModel:e=>m.restoreImTurnModel(e),...agentGateway?{completeA2ATask:(t,r,o)=>completeA2ATask({gateway:agentGateway,logger:e.logger},t,r,o)}:{}})},u.set(n.id,l)),[{principalId:i.principalId,targetAgentId:n.id,runtimeEpoch:t.runtimeEpoch,inbound:l.inbound}]}):[]},executionJournal:l,logger:e.logger}),p=sharedAgentMappings.subscribe(()=>{sharedActiveMessageConsumer===g&&g.refresh()}),h=sharedRuntimeAuthority?.subscribeAuthority(()=>{sharedActiveMessageConsumer===g&&g.refresh()})??(()=>{}),f=new MessageClientTerminalStateRecovery({logger:e.logger,isCurrent:()=>{if(sharedActiveMessageConsumer!==g)return!1;const e=sharedRuntimeAuthority?.authorityLease;return null!=e&&e.instanceId===i.principalId&&e.runtimeEpoch===i.runtimeEpoch&&e.leaseId===n.leaseId&&e.handlerIdentity===n.handlerIdentity},reconnect:async()=>{if("failed"===s.getSnapshot().connection){await s.connect();try{await m.rebindRuntimeDelivery()}catch(t){e.logger.warn?.(`[beeos-claw] runtime Service delivery rebind failed after MessageClient recovery: ${t instanceof Error?t.message:String(t)}`)}}}});let v=s.getSnapshot().connection;sharedMSConnectionStatus.setIfCurrent(c,v);const w=s.subscribe(()=>{const t=s.getSnapshot();t.connection!==v&&(v=t.connection,sharedMSConnectionStatus.setIfCurrent(c,t.connection),"connected"===t.connection?(f.notifyConnected(),e.logger.info?.(`[beeos-claw] connection transport=message_service_realtime state=connected localAgentId=${m.getLocalAgentId()} principalId=${i.principalId}`)):"failed"===t.connection?(e.logger.warn?.(`[beeos-claw] connection transport=message_service_realtime state=failed principalId=${i.principalId} recoveryError=${t.recoveryError??"unknown"}`),f.notifyFailed()):"disconnected"!==t.connection&&"reconnecting"!==t.connection||e.logger.warn?.(`[beeos-claw] connection transport=message_service_realtime state=${t.connection} principalId=${i.principalId}; SDK owns reconnect/recovery`))});sharedActiveMessageConsumer=g,g.start();try{await s.connect()}catch(e){throw sharedActiveMessageConsumer===g&&(sharedActiveMessageConsumer=void 0),sharedMSConnectionStatus.resetIfCurrent(c),f.dispose(),await g.stop(),p(),h(),w(),await s.disconnect().catch(()=>{}),e}try{await m.rebindRuntimeDelivery()}catch(t){e.logger.warn?.(`[beeos-claw] runtime Service delivery rebind failed after MessageClient connect: ${t instanceof Error?t.message:String(t)}`)}return async()=>{sharedActiveMessageConsumer===g&&(sharedActiveMessageConsumer=void 0),sharedMSConnectionStatus.resetIfCurrent(c),f.dispose(),await g.stop(),h(),w(),await s.disconnect(),e.logger.info?.("[beeos-claw] MessageClient disconnected")}})},disconnect:async()=>{await sharedMessageClientOwner.release(t)}}}):void 0;e.registerService({id:"beeos-message-bus",async start(){n?n.start():e.logger.warn?.("[beeos-claw] Message bus requires runtime authority; waiting is unavailable without Agent Gateway runtime identity")},async stop(){await(n?.stop())}})}else h?e.logger.warn?.("[beeos-claw] Message bus enabled but Agent Gateway token provider is unavailable — disabled"):e.logger.info?.(`[beeos-claw] Message bus disabled (enabled=${h})`);if(attachNativeCloudChat(e,o),o.messageBus.enabled&&c&&!sharedNativeCloudChat&&e.logger.warn?.("[beeos-claw] Cloud message bus enabled but native composition unavailable (messageBus.serviceUrl or runtime authority missing) — disabled"),!1!==v&&agentGateway){const t=e=>m.getGatewaySessionKeyForToolCall(e),r=e=>m.getMentionsForToolCall(e),o=(e,t)=>{m.broadcastNotification(e,t)},a=new TaskHandleRegistry;registerA2ATools(e,{gateway:agentGateway,logger:e.logger},a,t,r,o,()=>p()?.instanceId),e.logger.info?.("[beeos-claw] A2A tools registered (beeos_discover_agents, beeos_call_agent) via REST")}if(agentGateway&&(registerAutomationTools(e,{gateway:agentGateway,logger:e.logger,getDefaultAgent:()=>{const e=p();return e?{id:e.id,instanceId:e.instanceId}:void 0},getCurrentConversationId:e=>{const t=m.getGatewaySessionKeyForToolCall(e);return t?extractBeeosConversationIdFromSessionKey(t):void 0}}),e.logger.info?.("[beeos-claw] Automation tools registered (create/create_webhook/capabilities/preflight/list/get/run/runs/get_run)")),o.canvasEnabled){sharedCanvasState||(sharedCanvasState=new CanvasStateManager);const t=sharedCanvasState;if(agentGateway&&agentKeys){t.setLogger(e.logger);const r=()=>agentGateway.canvas.token(),a=a=>{const n=new CanvasRelayClient({canvasRelayUrl:o.canvasRelayUrl,agentKeys:agentKeys,agentId:a.id,displayName:a.displayName,avatarUrl:a.avatarUrl,tokenProvider:r,onConnected:()=>m.flushPendingCanvasLinks(),onReconnect:()=>m.onRelayReconnected(),logger:e.logger});t.setRelayClient(n),t.setAgentId(a.id),m.wireRelayActionHandler(),n.connect(),e.logger.info?.(`[beeos-claw] Canvas Relay multiplexed client connected (agentId=${a.id}, name=${a.name??"none"})`)};e.registerService(createCanvasRelayService({getAgent:p,onceAgentReady:e=>sharedAgentMappings.onceReady(e),initRelay:a,stopRelay:()=>t.getRelayClient()?.disconnect(),logger:e.logger})),e.logger.info?.("[beeos-claw] Canvas Relay configured")}else e.logger.warn?.("[beeos-claw] Canvas Relay unavailable: agentGatewayUrl or agentKeys missing");const r={stateManager:t,logger:e.logger,writeObs:e=>a(e),getActiveSessionId:e=>m.getSessionIdForToolCall(e),getPlatformAgentId:e=>m.getPlatformAgentIdForToolCall(e),getGatewaySessionKey:e=>m.getGatewaySessionKeyForToolCall(e),waitForAgentSync:()=>sharedAgentMappings.waitForSynchronization()},i=new FormSchemaRegistry,s=buildCronSchemas(n);i.register(s.create),i.register(s.update);const l=new ResourceDescriptorRegistry;l.register(CRON_RESOURCE);const c=e=>async(t,r,o)=>(m.preMapToolCallSession(t),e(t,r));e.registerTool({name:RENDER_UI_TOOL_NAME,description:RENDER_UI_TOOL_DESCRIPTION,parameters:RENDER_UI_TOOL_SCHEMA,execute:c(createRenderUiHandler(r))}),e.registerTool({name:CLOSE_UI_TOOL_NAME,description:CLOSE_UI_TOOL_DESCRIPTION,parameters:CLOSE_UI_TOOL_SCHEMA,execute:c(createCloseUiHandler(r))}),m.setCanvasState(t,{schemaRegistry:i,descriptorRegistry:l});const u=m.getFormBuilder();u&&e.registerTool({name:RENDER_FORM_TOOL_NAME,description:buildRenderFormDescription(i),parameters:RENDER_FORM_TOOL_SCHEMA,execute:c(createRenderFormHandler({registry:i,builder:u,logger:e.logger}))});const g=m.getResourceRenderer();if(g){generateActionTools(l,e,async(e,t)=>m.gatewayRequest(e,t),g,e.logger)}const d=buildToolRoutingHint(BEEOS_FILE_RESOURCE_ROUTING_RULE,BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME),y=new Set([RENDER_UI_TOOL_NAME,CLOSE_UI_TOOL_NAME,RENDER_FORM_TOOL_NAME]),h=256,f=new Map;if("function"==typeof e.on){try{e.on("before_prompt_build",(e,t)=>{if(t?.sessionKey){if(f.size>=h&&!f.has(t.sessionKey)){const e=f.keys().next().value;void 0!==e&&f.delete(e)}f.set(t.sessionKey,t.channelId),rememberDeliveryWorkspace(t.sessionKey,t.workspaceDir)}const r=isThirdPartyChannel(n,{sessionKey:t?.sessionKey,channelId:t?.channelId});return t?.sessionKey||r?{appendSystemContext:buildAppendSystemContext({thirdParty:r,canvasSystemPrompt:`${CANVAS_PRESENTATION_GATE}\n\n${CANVAS_SYSTEM_PROMPT}`,toolRoutingHint:d})}:{appendSystemContext:d}}),e.logger.debug?.("[beeos-claw] Canvas system prompt hook registered: before_prompt_build")}catch{e.logger.debug?.("[beeos-claw] before_prompt_build hook not supported")}try{e.on("before_tool_call",(e,t)=>{if(t?.sessionKey&&m.setPendingToolCallSessionKey(t.sessionKey),!y.has(e.toolName))return;const r=t?.sessionKey?f.get(t.sessionKey):void 0,o=isThirdPartyChannel(n,{sessionKey:t?.sessionKey,channelId:r}),a=canvasToolBlockReason({thirdParty:o,hasSession:Boolean(t?.sessionKey)});return a?{block:!0,blockReason:a}:void 0}),e.logger.debug?.("[beeos-claw] Canvas tool guard registered: before_tool_call")}catch{e.logger.debug?.("[beeos-claw] before_tool_call hook not supported")}}e.logger.info?.("[beeos-claw] Canvas tools registered (render_ui, close_ui, render_form + auto-action tools)")}else e.logger.info?.("[beeos-claw] Canvas disabled by config (canvasEnabled=false)");if(o.bridge.shell.enabled&&!0===o.legacyTerminalWsEnabled){const t=createTerminalWebSocketService({config:{port:o.terminalWsPort,token:agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):"",allowedOrigins:o.terminalWsAllowedOrigins},terminalMgr:sharedTerminalManager,logger:e.logger,writeObs:a});e.registerService({id:"beeos-terminal-ws",start(){t.start(),e.logger.info?.(`[beeos-claw] Terminal WS started on port ${o.terminalWsPort}`)},stop(){t.stop(),e.logger.info?.("[beeos-claw] Terminal WS stopped")}})}else o.bridge.shell.enabled?e.logger.info?.("[beeos-claw] Legacy static-token Terminal WS disabled (default)"):e.logger.info?.("[beeos-claw] Terminal/shell disabled by config (bridge.shell.enabled=false)");if(t.openclawConfig){const r=mirrorOpenClawConfig(t.openclawConfig);r.copied?e.logger.info?.(`[beeos-claw] mirrored openclaw config to ${r.destinationPath}`):e.logger.debug?.(`[beeos-claw] openclaw config mirror skipped: ${r.reason}`)}}function pluginCloudRuntimeTarget(e){const t=e.pluginConfig?.cloudRuntimeInstanceId,r=cloudRuntimeTargetInstanceId("string"==typeof t?t:void 0);return setClaimedCloudRuntimeInstanceId(r),r}function attachNativeCloudChat(e,t){if(warmClaimAttached)return sharedNativeCloudChat;const r=sharedRuntimeAuthority,o=t.messageBus.serviceUrl,a=sharedAcpServer,n=sharedSessionMutationCoordinator;if(!(r&&r.cloudTargetInstanceId&&o&&a&&n))return sharedNativeCloudChat;const i=sharedNativeCloudChat??createNativeCloudChatComposition({authority:nativeCloudChatAuthorityFromRuntimeAuthority(r),serviceUrl:o,logger:e.logger});if(sharedNativeCloudChat=i,!t.messageBus.enabled)return i;const s=_fullRuntimeRegistered,l=i,c=r;let u;const g=new Map,d=new RuntimeAuthorityMessageBusLifecycle({authority:c,logger:e.logger,bus:{connect:async t=>{u?.(),g.clear(),u=l.adapter.listen({eventTypes:["message.created"]},r=>{const o=(r.content??{}).metadata??{},i="string"==typeof o.target_agent_id?o.target_agent_id:"",s=i?((t,r)=>{const o=sharedAgentMappings.snapshot();if(o)for(const[i,s]of o.entries()){if(s.id!==r)continue;if(s.instanceId!==t.instanceId)continue;const o=`${i}\0${s.id}`;let c=g.get(o);return c||(c={localAgentId:i,inbound:createImInboundHandler({runtime:e.runtime,pluginConfig:e.pluginConfig,client:l.adapter,localServer:{getLocalAgentId:()=>i,resolveLocalAgentId:e=>e===s.id?i:void 0,getDefaultPlatformAgent:()=>({instanceId:t.instanceId}),ensureImInboundSession:(e,t,r,o)=>{a.ensureImInboundSession(e,t,r,o)},chatAbort:(e,t)=>a.chatAbort(e,t)},promptRunStore:sharedPromptRunStore,waitIfExclusive:(t,r)=>sharedImHotPathDeferral.waitIfExclusive(t,e.logger,r).then(()=>{}),assistantMessageCommitRouter:sharedAssistantMessageCommitRouter,toolResultObservationRouter:sharedToolResultObservationRouter,modelCallObservationRouter:sharedModelCallObservationRouter,sessionMutationCoordinator:n,logger:e.logger,writeObs:sharedWriteObs,principalIdOverride:t.instanceId,activeRunAuthority:a.getActiveRunAuthority(),applyTurnModel:(e,t)=>a.applyImTurnModel(e,t),restoreTurnModel:e=>a.restoreImTurnModel(e),...agentGateway?{completeA2ATask:(t,r,o)=>completeA2ATask({gateway:agentGateway,logger:e.logger},t,r,o)}:{}})},g.set(o,c)),c}})(t,i):void 0;if(!s)return void e.logger.warn?.(`[beeos-claw] native cloud chat dropped unresolvable target_agent_id=${i||"missing"} message_id=${r.id}`);("chat_cancel"===r.type?s.inbound.onChatCancel(r):s.inbound.onChatMessage(r)).catch(t=>{e.logger.error?.(`[beeos-claw] native cloud chat dispatch failed message_id=${r.id}: ${t instanceof Error?t.message:String(t)}`)})});try{await l.adapter.connect()}catch(e){throw u?.(),u=void 0,e}},disconnect:async()=>{u?.(),u=void 0,g.clear(),await l.adapter.disconnect()}}});return e.registerService({id:"beeos-native-cloud-chat",async start(){d.start()},async stop(){await d.stop()}}),e.logger.info?.("[beeos-claw] native Cloud personal-chat composition registered"),warmClaimAttached=!0,s&&d.start(),i}function adoptWarmClaim(e){const t=pluginCloudRuntimeTarget(e);if(!sharedRuntimeAuthority||!t)return;const r=sharedRuntimeAuthority.cloudTargetInstanceId;if(void 0===r)sharedRuntimeAuthority.bindCloudTarget(t);else if(r!==t)throw new Error("Cloud runtime authority target changed during process lifetime");if(void 0!==r||warmClaimAttached)return;let o;try{o=e.runtime?.config?.loadConfig?.()}catch{}attachNativeCloudChat(e,resolveConfigWithMeta({pluginConfig:e.pluginConfig??{},openclawConfig:o}).config)}const plugin={id:"beeos-claw",name:"beeos-claw",description:"BeeOS platform bridge plugin for OpenClaw. Provides file upload/download, ACP bridge, and observability.",version:PLUGIN_VERSION,register(e){if(_initializing)return;adoptWarmClaim(e);const t=planPluginRegistration(e.registrationMode,_fullRuntimeRegistered);if("skip"!==t){_initializing=!0;try{if(!hasRuntimeReplyApi(e.runtime))throw e.logger.error?.("[beeos-claw] FATAL: OpenClaw runtime.channel.reply.dispatchReplyFromConfig not exposed. Upgrade OpenClaw or revert beeos-claw."),new Error("openclaw_runtime_reply_api_unavailable");const r=(t,r)=>{registerUploadTools(e,t,r),registerConnectorMcpProxy(e,t),registerManagedConnectorTools(e,agentGateway),registerArouterLatencyRouting(e),registerArouterMediaProviders(e)};if("capabilities"===t&&sharedPluginContext){if(cachedCapabilityTools.length>0){const t=resolveCapabilityToolReplay({currentRegisterTool:e.registerTool,wrappedRegisterTool:wrappedRegisterTool,originalRegisterTool:rawRegisterTool}),r=replayCachedPluginTools(r=>t.call(e,r),cachedCapabilityTools);return registerArouterLatencyRouting(e),registerArouterMediaProviders(e),void e.logger.info?.(`[beeos-claw] capability re-register mode=${e.registrationMode} tools_only count=${r}`)}const t={current:sharedAcpServer??null};return r(sharedPluginContext,t),registerServices(e,sharedPluginContext,t),void e.logger.info?.(`[beeos-claw] capability re-register mode=${e.registrationMode} capabilities_only`)}const o=initializePlugin(e);if(!o)return;const a={current:null};installUnhandledRejectionObserver(e,o.writeObs,a),ensureRegisterToolCache(e),cachedCapabilityTools.length=0,r(o,a),agentGateway&&(e.on?e.on("before_agent_finalize",fileDeliveryFinalizeDecision):e.logger.warn?.("[file-delivery] OpenClaw plugin hooks unavailable; finalization check disabled")),registerServices(e,o,a),sharedPluginContext=o,marksFullRuntimeRegistered(e.registrationMode,t)&&(_fullRuntimeRegistered=!0),_pluginRegisteredAt=Date.now(),e.logger.info?.("[beeos-claw] Plugin registered successfully")}finally{_initializing=!1}}else e.logger.info?.(`[beeos-claw] skip re-register mode=${e.registrationMode??"full"} already_registered`)}};export default plugin;
@@ -1 +1 @@
1
- import{agentFetch}from"./agent-auth.js";export const CONNECTOR_MCP_PROXY_PATH="/beeos/connectors/mcp";export const CONNECTOR_MCP_UPSTREAM_PATH="/api/v1/agent/connectors/mcp";export const CONNECTOR_MCP_MAX_BODY_BYTES=262144;class RequestBodyTooLargeError extends Error{}export function isLoopbackAddress(e){return"127.0.0.1"===e||"::1"===e||"::ffff:127.0.0.1"===e}export function isLoopbackRequest(e){return isLoopbackAddress(e.socket.remoteAddress)}export function readBoundedRawBody(e,t=262144){return new Promise((r,o)=>{const n=[];let s=0,a=!1;const c=()=>{e.off("data",u),e.off("end",i),e.off("error",p),e.off("aborted",f)},d=e=>{a||(a=!0,c(),o(e))},u=r=>{const o=Buffer.isBuffer(r)?r:Buffer.from(r);if(s+=o.byteLength,s>t)return c(),e.resume(),void d(new RequestBodyTooLargeError("connector MCP request body is too large"));n.push(o)},i=()=>{a||(a=!0,c(),r(Buffer.concat(n,s)))},p=e=>d(e),f=()=>d(new Error("connector MCP request was aborted"));e.on("data",u),e.on("end",i),e.on("error",p),e.on("aborted",f)})}function writeTextResponse(e,t,r){e.statusCode=t,e.setHeader("Content-Type","text/plain; charset=utf-8"),e.end(r)}function copyRequestHeader(e,t,r){const o=e.headers[r.toLowerCase()];"string"==typeof o?t.set(r,o):Array.isArray(o)&&t.set(r,o.join(", "))}export async function handleConnectorMcpRequest(e,t,r){if(!isLoopbackRequest(e))return e.resume(),void writeTextResponse(t,403,"loopback access required");if("POST"!==e.method)return e.resume(),t.setHeader("Allow","POST"),void writeTextResponse(t,405,"method not allowed");if(e.url?.includes("?"))return e.resume(),void writeTextResponse(t,400,"query parameters are not supported");if(!r.agentKeys||!r.agentGatewayUrl)return e.resume(),void writeTextResponse(t,503,"connector MCP proxy is not configured");let o;try{o=await readBoundedRawBody(e)}catch(e){return e instanceof RequestBodyTooLargeError?void writeTextResponse(t,413,"request body too large"):(r.logger?.warn?.(`[connector-mcp] failed to read request: ${String(e)}`),void(t.writableEnded||writeTextResponse(t,400,"invalid request body")))}const n=new Headers;copyRequestHeader(e,n,"Content-Type"),copyRequestHeader(e,n,"Accept"),copyRequestHeader(e,n,"MCP-Protocol-Version");const s=`${r.agentGatewayUrl.replace(/\/+$/,"")}${CONNECTOR_MCP_UPSTREAM_PATH}`;try{const e=await(r.fetcher??agentFetch)(s,r.agentKeys,{method:"POST",headers:n,body:new Uint8Array(o)}),a=Buffer.from(await e.arrayBuffer());t.statusCode=e.status;const c=e.headers.get("content-type");c&&t.setHeader("Content-Type",c),t.end(a)}catch(e){r.logger?.warn?.(`[connector-mcp] upstream request failed: ${String(e)}`),t.writableEnded||writeTextResponse(t,502,"connector MCP upstream unavailable")}}
1
+ export const CONNECTOR_MCP_PROXY_PATH="/beeos/connectors/mcp";export const CONNECTOR_MCP_MAX_BODY_BYTES=262144;class RequestBodyTooLargeError extends Error{}export function isLoopbackAddress(e){return"127.0.0.1"===e||"::1"===e||"::ffff:127.0.0.1"===e}export function isLoopbackRequest(e){return isLoopbackAddress(e.socket.remoteAddress)}export function readBoundedRawBody(e,o=262144){return new Promise((r,t)=>{const n=[];let s=0,a=!1;const d=()=>{e.off("data",u),e.off("end",i),e.off("error",f),e.off("aborted",p)},c=e=>{a||(a=!0,d(),t(e))},u=r=>{const t=Buffer.isBuffer(r)?r:Buffer.from(r);if(s+=t.byteLength,s>o)return d(),e.resume(),void c(new RequestBodyTooLargeError("connector MCP request body is too large"));n.push(t)},i=()=>{a||(a=!0,d(),r(Buffer.concat(n,s)))},f=e=>c(e),p=()=>c(new Error("connector MCP request was aborted"));e.on("data",u),e.on("end",i),e.on("error",f),e.on("aborted",p)})}function writeTextResponse(e,o,r){e.statusCode=o,e.setHeader("Content-Type","text/plain; charset=utf-8"),e.end(r)}function copyRequestHeader(e,o,r){const t=e.headers[r.toLowerCase()];"string"==typeof t?o.set(r,t):Array.isArray(t)&&o.set(r,t.join(", "))}export async function handleConnectorMcpRequest(e,o,r){if(!isLoopbackRequest(e))return e.resume(),void writeTextResponse(o,403,"loopback access required");if("POST"!==e.method)return e.resume(),o.setHeader("Allow","POST"),void writeTextResponse(o,405,"method not allowed");if(e.url?.includes("?"))return e.resume(),void writeTextResponse(o,400,"query parameters are not supported");if(!r.gateway)return e.resume(),void writeTextResponse(o,503,"connector MCP proxy is not configured");let t;try{t=await readBoundedRawBody(e)}catch(e){return e instanceof RequestBodyTooLargeError?void writeTextResponse(o,413,"request body too large"):(r.logger?.warn?.(`[connector-mcp] failed to read request: ${String(e)}`),void(o.writableEnded||writeTextResponse(o,400,"invalid request body")))}const n=new Headers;copyRequestHeader(e,n,"Content-Type"),copyRequestHeader(e,n,"Accept"),copyRequestHeader(e,n,"MCP-Protocol-Version");try{const e=await r.gateway.connectors.mcp({method:"POST",headers:n,body:new Uint8Array(t)}),s=Buffer.from(await e.arrayBuffer());o.statusCode=e.status;const a=e.headers.get("content-type");a&&o.setHeader("Content-Type",a),o.end(s)}catch(e){r.logger?.warn?.(`[connector-mcp] upstream request failed: ${String(e)}`),o.writableEnded||writeTextResponse(o,502,"connector MCP upstream unavailable")}}
@@ -1 +1 @@
1
- export const AROUTER_PROVIDER_ID="arouter";export const DEFAULT_AROUTER_IMAGE_MODEL="gemini-2.5-flash-image";export const DEFAULT_AROUTER_VIDEO_MODEL="seedance-2.0-fast";const FALLBACK_AROUTER_BASE_URL="https://api.arouter.ai/v1";function trimTrailingSlash(t){return t.replace(/\/+$/u,"")}export function resolveArouterApiKey(){const t=process.env.AROUTER_API_KEY?.trim();return t||void 0}export function resolveArouterBaseUrl(t){const e=t?.models?.providers?.arouter?.baseUrl?.trim();if(e)return trimTrailingSlash(e);const r=process.env.AROUTER_BASE_URL?.trim();return r?`${trimTrailingSlash(r)}/v1`:FALLBACK_AROUTER_BASE_URL}export function arouterAuthHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}const DEFAULT_REQUEST_TIMEOUT_MS=6e4;export async function arouterFetch(t,e={}){const r=e.timeoutMs??6e4,o=void 0!==e.deadlineAt?Math.max(0,e.deadlineAt-Date.now()):r,n=Math.max(1,Math.min(r,o)),a={method:e.method??"GET",signal:AbortSignal.timeout(n)};return e.headers&&(a.headers=e.headers),void 0!==e.body&&(a.body=e.body),fetch(t,a)}export async function readErrorBody(t){try{return(await t.text()).slice(0,500)}catch{return""}}
1
+ export const AROUTER_PROVIDER_ID="arouter";export const DEFAULT_AROUTER_IMAGE_MODEL="gemini-2.5-flash-image";export const DEFAULT_AROUTER_VIDEO_MODEL="seedance-2.0-fast";const FALLBACK_AROUTER_BASE_URL="https://api.arouter.ai/v1";function trimTrailingSlash(r){return r.replace(/\/+$/u,"")}const PLACEHOLDER_API_KEY=/^\$\{[^}]+\}$/u;function providersOf(r){return r?.models?.providers??{}}function hasProvider(r,e){return Object.prototype.hasOwnProperty.call(r,e)&&null!=r[e]}function listedModelIds(r){if(!r||!Array.isArray(r.models))return[];const e=[];for(const o of r.models){if("string"==typeof o){const r=o.trim();r&&e.push(r);continue}if(o&&"string"==typeof o.id){const r=o.id.trim();r&&e.push(r)}}return e}function providerListingModel(r,e){const o=Object.entries(r).filter(([,r])=>listedModelIds(r).includes(e));return 1===o.length?o[0]?.[0]:void 0}function soleProviderId(r){const e=Object.keys(r).filter(e=>hasProvider(r,e));return 1===e.length?e[0]:void 0}function providerFromRef(r,e){const o=e.indexOf("/");if(o<=0||o>=e.length-1)return;const t=e.slice(0,o).trim(),i=e.slice(o+1).trim();return t&&i?hasProvider(r,t)?t:providerListingModel(r,e)??providerListingModel(r,i):void 0}function resolveModelPointer(r,e){const o=e.trim();if(o)return o.includes("/")?providerFromRef(r,o):hasProvider(r,o)?o:providerListingModel(r,o)}function readToolModelRef(r,e){const o=r?.agents?.defaults?.[e];if("string"==typeof o){return o.trim()||void 0}if(o&&"string"==typeof o.primary){return o.primary.trim()||void 0}}export function resolveToolModelProviderId(r,e){const o=providersOf(r),t=e?.model?.trim();if(t){const r=resolveModelPointer(o,t);if(r)return r}const i=e?.toolModelField?readToolModelRef(r,e.toolModelField):void 0;if(i){const r=resolveModelPointer(o,i);if(r)return r}const n=e?.capabilityProviderId?.trim();return n&&hasProvider(o,n)?n:soleProviderId(o)}function providerIdFromHint(r,e){const o=e.trim();if(o)return resolveModelPointer(providersOf(r),o)}function readProviderApiKey(r,e){if(!e)return;const o=providersOf(r);if(!hasProvider(o,e))return;const t=o[e]?.apiKey;if("string"!=typeof t)return;const i=t.trim();return i&&!PLACEHOLDER_API_KEY.test(i)?i:void 0}export function resolveArouterApiKey(r,e){return readProviderApiKey(r,"string"==typeof e?providerIdFromHint(r,e):resolveToolModelProviderId(r,e))}export function resolveArouterBaseUrl(r){const e=r?.models?.providers?.arouter?.baseUrl?.trim();if(e)return trimTrailingSlash(e);const o=process.env.AROUTER_BASE_URL?.trim();return o?`${trimTrailingSlash(o)}/v1`:FALLBACK_AROUTER_BASE_URL}export function arouterAuthHeaders(r){return{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}const DEFAULT_REQUEST_TIMEOUT_MS=6e4;export async function arouterFetch(r,e={}){const o=e.timeoutMs??6e4,t=void 0!==e.deadlineAt?Math.max(0,e.deadlineAt-Date.now()):o,i=Math.max(1,Math.min(o,t)),n={method:e.method??"GET",signal:AbortSignal.timeout(i)};return e.headers&&(n.headers=e.headers),void 0!==e.body&&(n.body=e.body),fetch(r,n)}export async function readErrorBody(r){try{return(await r.text()).slice(0,500)}catch{return""}}
@@ -1 +1 @@
1
- import{AROUTER_PROVIDER_ID,DEFAULT_AROUTER_IMAGE_MODEL,arouterAuthHeaders,arouterFetch,readErrorBody,resolveArouterApiKey,resolveArouterBaseUrl}from"./arouter-config.js";const IMAGE_MODELS=[DEFAULT_AROUTER_IMAGE_MODEL],DEFAULT_IMAGE_TIMEOUT_MS=12e4,SUPPORTED_ASPECT_RATIOS=["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9"],SUPPORTED_RESOLUTIONS=["1K","2K","4K"];function isRecord(e){return Boolean(e&&"object"==typeof e&&!Array.isArray(e))}function inferImageMimeType(e){return e.length>=8&&137===e[0]&&80===e[1]?"image/png":e.length>=3&&255===e[0]&&216===e[1]&&255===e[2]?"image/jpeg":e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12)?"image/webp":"image/png"}function toImageDataUrl(e){return`data:${e.mimeType};base64,${e.buffer.toString("base64")}`}function isGeminiImageModel(e){return/gemini/i.test(e)}function buildMessageContent(e){const t=e.inputImages??[];return 0===t.length?e.prompt:[{type:"text",text:e.prompt},...t.map(e=>({type:"image_url",image_url:{url:toImageDataUrl(e)}}))]}function buildImageConfig(e,t){if(!isGeminiImageModel(t))return{};const r={},o=e.aspectRatio?.trim();o&&(r.aspect_ratio=o);const a=e.resolution?.trim();return a&&(r.image_size=a),r}function decodeDataUrl(e){const t=/^data:([^;,]+)?(;base64)?,([\s\S]*)$/u.exec(e);if(!t)return null;const r=t[1]?.trim()||"image/png",o=Boolean(t[2]),a=t[3]??"",n=o?Buffer.from(a,"base64"):Buffer.from(decodeURIComponent(a),"utf8");return 0===n.length?null:{buffer:n,mimeType:r}}function collectImageUrls(e){const t=[];for(const r of e.choices??[]){const e=r?.message;if(!e)continue;for(const r of e.images??[]){const e=(r.image_url??r.imageUrl)?.url;"string"==typeof e&&e.length>0&&t.push(e)}const o=e.content;if("string"==typeof o&&o.length>0){const e=/data:image\/[^;]+;base64,[A-Za-z0-9+/=]+/gu;for(const r of o.matchAll(e))t.push(r[0])}else if(Array.isArray(o))for(const e of o)if(isRecord(e)&&"image_url"===e.type&&isRecord(e.image_url)){const r=e.image_url.url;"string"==typeof r&&r.length>0&&t.push(r)}}return t}async function assetFromUrl(e,t,r){let o,a=null;if(e.startsWith("data:")){const t=decodeDataUrl(e);t&&(a=t.buffer,o=t.mimeType)}else{const t=await arouterFetch(e,{deadlineAt:r});if(!t.ok)throw new Error(`ARouter image download failed (${t.status}): ${await readErrorBody(t)}`);a=Buffer.from(await t.arrayBuffer())}if(!a||0===a.length)return null;const n=o??inferImageMimeType(a);return{buffer:a,mimeType:n,fileName:`image-${t+1}.${"image/jpeg"===n?"jpg":"image/webp"===n?"webp":"png"}`}}export function createArouterImageProvider(){return{id:AROUTER_PROVIDER_ID,label:"ARouter Image",defaultModel:DEFAULT_AROUTER_IMAGE_MODEL,defaultTimeoutMs:12e4,models:IMAGE_MODELS,capabilities:{generate:{maxCount:1,supportsSize:!1,supportsAspectRatio:!0,supportsResolution:!0},edit:{enabled:!1},geometry:{aspectRatios:[...SUPPORTED_ASPECT_RATIOS],resolutions:[...SUPPORTED_RESOLUTIONS]}},isConfigured:()=>Boolean(resolveArouterApiKey()),async generateImage(e){const t=resolveArouterApiKey();if(!t)throw new Error("ARouter image generation: AROUTER_API_KEY is not configured.");const r=resolveArouterBaseUrl(e.cfg),o=e.model?.trim()||DEFAULT_AROUTER_IMAGE_MODEL,a=Date.now()+(e.timeoutMs??12e4),n=buildImageConfig(e,o),i={model:o,messages:[{role:"user",content:buildMessageContent(e)}],modalities:["image","text"]},s=e.count&&e.count>1?Math.floor(e.count):1;s>1&&(i.n=s),Object.keys(n).length>0&&(i.image_config=n);const u=await arouterFetch(`${r}/chat/completions`,{method:"POST",headers:arouterAuthHeaders(t),body:JSON.stringify(i),deadlineAt:a});if(!u.ok)throw new Error(`ARouter image generation failed (${u.status}): ${await readErrorBody(u)}`);const g=await u.json(),l=collectImageUrls(g),m=[];for(let e=0;e<l.length;e+=1){const t=await assetFromUrl(l[e],e,a);t&&m.push(t)}if(0===m.length)throw new Error("ARouter image generation response missing image data.");return{images:m,model:o,...g.usage?{metadata:{usage:g.usage}}:{}}}}}
1
+ import{AROUTER_PROVIDER_ID,DEFAULT_AROUTER_IMAGE_MODEL,arouterAuthHeaders,arouterFetch,readErrorBody,resolveArouterApiKey,resolveArouterBaseUrl}from"./arouter-config.js";const IMAGE_MODELS=[DEFAULT_AROUTER_IMAGE_MODEL],DEFAULT_IMAGE_TIMEOUT_MS=12e4,SUPPORTED_ASPECT_RATIOS=["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9"],SUPPORTED_RESOLUTIONS=["1K","2K","4K"];function isRecord(e){return Boolean(e&&"object"==typeof e&&!Array.isArray(e))}function inferImageMimeType(e){return e.length>=8&&137===e[0]&&80===e[1]?"image/png":e.length>=3&&255===e[0]&&216===e[1]&&255===e[2]?"image/jpeg":e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12)?"image/webp":"image/png"}function toImageDataUrl(e){return`data:${e.mimeType};base64,${e.buffer.toString("base64")}`}function isGeminiImageModel(e){return/gemini/i.test(e)}function buildMessageContent(e){const t=e.inputImages??[];return 0===t.length?e.prompt:[{type:"text",text:e.prompt},...t.map(e=>({type:"image_url",image_url:{url:toImageDataUrl(e)}}))]}function buildImageConfig(e,t){if(!isGeminiImageModel(t))return{};const r={},o=e.aspectRatio?.trim();o&&(r.aspect_ratio=o);const a=e.resolution?.trim();return a&&(r.image_size=a),r}function decodeDataUrl(e){const t=/^data:([^;,]+)?(;base64)?,([\s\S]*)$/u.exec(e);if(!t)return null;const r=t[1]?.trim()||"image/png",o=Boolean(t[2]),a=t[3]??"",i=o?Buffer.from(a,"base64"):Buffer.from(decodeURIComponent(a),"utf8");return 0===i.length?null:{buffer:i,mimeType:r}}function collectImageUrls(e){const t=[];for(const r of e.choices??[]){const e=r?.message;if(!e)continue;for(const r of e.images??[]){const e=(r.image_url??r.imageUrl)?.url;"string"==typeof e&&e.length>0&&t.push(e)}const o=e.content;if("string"==typeof o&&o.length>0){const e=/data:image\/[^;]+;base64,[A-Za-z0-9+/=]+/gu;for(const r of o.matchAll(e))t.push(r[0])}else if(Array.isArray(o))for(const e of o)if(isRecord(e)&&"image_url"===e.type&&isRecord(e.image_url)){const r=e.image_url.url;"string"==typeof r&&r.length>0&&t.push(r)}}return t}async function assetFromUrl(e,t,r){let o,a=null;if(e.startsWith("data:")){const t=decodeDataUrl(e);t&&(a=t.buffer,o=t.mimeType)}else{const t=await arouterFetch(e,{deadlineAt:r});if(!t.ok)throw new Error(`ARouter image download failed (${t.status}): ${await readErrorBody(t)}`);a=Buffer.from(await t.arrayBuffer())}if(!a||0===a.length)return null;const i=o??inferImageMimeType(a);return{buffer:a,mimeType:i,fileName:`image-${t+1}.${"image/jpeg"===i?"jpg":"image/webp"===i?"webp":"png"}`}}export function createArouterImageProvider(){return{id:AROUTER_PROVIDER_ID,label:"ARouter Image",defaultModel:DEFAULT_AROUTER_IMAGE_MODEL,defaultTimeoutMs:12e4,models:IMAGE_MODELS,capabilities:{generate:{maxCount:1,supportsSize:!1,supportsAspectRatio:!0,supportsResolution:!0},edit:{enabled:!1},geometry:{aspectRatios:[...SUPPORTED_ASPECT_RATIOS],resolutions:[...SUPPORTED_RESOLUTIONS]}},isConfigured:e=>Boolean(resolveArouterApiKey(e.cfg,{toolModelField:"imageGenerationModel"})),async generateImage(e){const t=resolveArouterApiKey(e.cfg,{model:e.model,capabilityProviderId:e.provider,toolModelField:"imageGenerationModel"});if(!t)throw new Error("ARouter image generation: provider apiKey is not configured.");const r=resolveArouterBaseUrl(e.cfg),o=e.model?.trim()||DEFAULT_AROUTER_IMAGE_MODEL,a=Date.now()+(e.timeoutMs??12e4),i=buildImageConfig(e,o),n={model:o,messages:[{role:"user",content:buildMessageContent(e)}],modalities:["image","text"]},s=e.count&&e.count>1?Math.floor(e.count):1;s>1&&(n.n=s),Object.keys(i).length>0&&(n.image_config=i);const l=await arouterFetch(`${r}/chat/completions`,{method:"POST",headers:arouterAuthHeaders(t),body:JSON.stringify(n),deadlineAt:a});if(!l.ok)throw new Error(`ARouter image generation failed (${l.status}): ${await readErrorBody(l)}`);const u=await l.json(),g=collectImageUrls(u),m=[];for(let e=0;e<g.length;e+=1){const t=await assetFromUrl(g[e],e,a);t&&m.push(t)}if(0===m.length)throw new Error("ARouter image generation response missing image data.");return{images:m,model:o,...u.usage?{metadata:{usage:u.usage}}:{}}}}}
@@ -1 +1 @@
1
- import{AROUTER_PROVIDER_ID,DEFAULT_AROUTER_VIDEO_MODEL,arouterAuthHeaders,arouterFetch,readErrorBody,resolveArouterApiKey,resolveArouterBaseUrl}from"./arouter-config.js";const VIDEO_MODELS=[DEFAULT_AROUTER_VIDEO_MODEL],DEFAULT_VIDEO_TIMEOUT_MS=3e5;export const AROUTER_VIDEO_POLL_INTERVAL_MS=2500;function sleep(e){return new Promise(r=>setTimeout(r,e))}function errorMessage(e){return"string"==typeof e.error?e.error:e.error&&"object"==typeof e.error&&e.error.message?e.error.message:`status=${e.status??"unknown"}`}function buildSubmitBody(e,r){const o={model:r,prompt:e.prompt,generate_audio:e.audio??!1};"number"==typeof e.durationSeconds&&Number.isFinite(e.durationSeconds)&&(o.duration=Math.max(1,Math.round(e.durationSeconds))),e.resolution?.trim()&&(o.resolution=e.resolution.trim()),e.aspectRatio?.trim()&&(o.aspect_ratio=e.aspectRatio.trim()),e.size?.trim()&&(o.size=e.size.trim());const t=(e.inputImages??[]).map(e=>e.url?.trim()).filter(e=>Boolean(e));if(t.length>0&&(o.frame_images=t),e.providerOptions)for(const[r,t]of Object.entries(e.providerOptions))void 0===t||r in o||(o[r]=t);return o}export async function pollArouterVideoTask(e){const r=`${e.baseUrl}/videos/${encodeURIComponent(e.taskId)}`,o=e.pollIntervalMs??2500;for(;;){if(Date.now()>=e.deadlineAt)throw new Error(`ARouter video task ${e.taskId} did not finish before timeout.`);const t=await arouterFetch(r,{headers:e.headers,deadlineAt:e.deadlineAt});if(!t.ok)throw new Error(`ARouter video poll failed (${t.status}): ${await readErrorBody(t)}`);const i=await t.json(),a=i.status?.toString().toLowerCase();if("completed"===a)return i;if("failed"===a||"cancelled"===a||"expired"===a)throw new Error(`ARouter video task ${e.taskId} ${a}: ${errorMessage(i)}`);await sleep(o)}}export function createArouterVideoProvider(){return{id:AROUTER_PROVIDER_ID,label:"ARouter Video",defaultModel:DEFAULT_AROUTER_VIDEO_MODEL,defaultTimeoutMs:3e5,models:VIDEO_MODELS,capabilities:{generate:{maxVideos:1,maxDurationSeconds:12,supportsResolution:!0,supportsAspectRatio:!0,supportsAudio:!0},imageToVideo:{enabled:!0,maxVideos:1,maxInputImages:1,maxDurationSeconds:12}},isConfigured:()=>Boolean(resolveArouterApiKey()),async generateVideo(e){const r=resolveArouterApiKey();if(!r)throw new Error("ARouter video generation: AROUTER_API_KEY is not configured.");const o=resolveArouterBaseUrl(e.cfg),t=e.model?.trim()||DEFAULT_AROUTER_VIDEO_MODEL,i=arouterAuthHeaders(r),a=Date.now()+(e.timeoutMs??3e5),s=await arouterFetch(`${o}/videos`,{method:"POST",headers:i,body:JSON.stringify(buildSubmitBody(e,t)),deadlineAt:a});if(!s.ok)throw new Error(`ARouter video submit failed (${s.status}): ${await readErrorBody(s)}`);const n=await s.json(),d=n.id?.trim();if(!d)throw new Error("ARouter video submit response missing task id.");const u=await pollArouterVideoTask({baseUrl:o,taskId:d,headers:i,deadlineAt:a}),l=`${o}/videos/${encodeURIComponent(d)}/content?index=0`,m=await arouterFetch(l,{headers:i,deadlineAt:a});if(!m.ok)throw new Error(`ARouter video download failed (${m.status}): ${await readErrorBody(m)}`);return{videos:[{buffer:Buffer.from(await m.arrayBuffer()),mimeType:m.headers.get("content-type")?.trim()||"video/mp4",fileName:"video-1.mp4"}],model:t,metadata:{taskId:d,status:u.status,...u.generation_id?{generationId:u.generation_id}:{},...u.usage?{usage:u.usage}:{}}}}}}
1
+ import{AROUTER_PROVIDER_ID,DEFAULT_AROUTER_VIDEO_MODEL,arouterAuthHeaders,arouterFetch,readErrorBody,resolveArouterApiKey,resolveArouterBaseUrl}from"./arouter-config.js";const VIDEO_MODELS=[DEFAULT_AROUTER_VIDEO_MODEL],DEFAULT_VIDEO_TIMEOUT_MS=3e5;export const AROUTER_VIDEO_POLL_INTERVAL_MS=2500;function sleep(e){return new Promise(o=>setTimeout(o,e))}function errorMessage(e){return"string"==typeof e.error?e.error:e.error&&"object"==typeof e.error&&e.error.message?e.error.message:`status=${e.status??"unknown"}`}function buildSubmitBody(e,o){const r={model:o,prompt:e.prompt,generate_audio:e.audio??!1};"number"==typeof e.durationSeconds&&Number.isFinite(e.durationSeconds)&&(r.duration=Math.max(1,Math.round(e.durationSeconds))),e.resolution?.trim()&&(r.resolution=e.resolution.trim()),e.aspectRatio?.trim()&&(r.aspect_ratio=e.aspectRatio.trim()),e.size?.trim()&&(r.size=e.size.trim());const t=(e.inputImages??[]).map(e=>e.url?.trim()).filter(e=>Boolean(e));if(t.length>0&&(r.frame_images=t),e.providerOptions)for(const[o,t]of Object.entries(e.providerOptions))void 0===t||o in r||(r[o]=t);return r}export async function pollArouterVideoTask(e){const o=`${e.baseUrl}/videos/${encodeURIComponent(e.taskId)}`,r=e.pollIntervalMs??2500;for(;;){if(Date.now()>=e.deadlineAt)throw new Error(`ARouter video task ${e.taskId} did not finish before timeout.`);const t=await arouterFetch(o,{headers:e.headers,deadlineAt:e.deadlineAt});if(!t.ok)throw new Error(`ARouter video poll failed (${t.status}): ${await readErrorBody(t)}`);const i=await t.json(),a=i.status?.toString().toLowerCase();if("completed"===a)return i;if("failed"===a||"cancelled"===a||"expired"===a)throw new Error(`ARouter video task ${e.taskId} ${a}: ${errorMessage(i)}`);await sleep(r)}}export function createArouterVideoProvider(){return{id:AROUTER_PROVIDER_ID,label:"ARouter Video",defaultModel:DEFAULT_AROUTER_VIDEO_MODEL,defaultTimeoutMs:3e5,models:VIDEO_MODELS,capabilities:{generate:{maxVideos:1,maxDurationSeconds:12,supportsResolution:!0,supportsAspectRatio:!0,supportsAudio:!0},imageToVideo:{enabled:!0,maxVideos:1,maxInputImages:1,maxDurationSeconds:12}},isConfigured:e=>Boolean(resolveArouterApiKey(e.cfg,{toolModelField:"videoGenerationModel"})),async generateVideo(e){const o=resolveArouterApiKey(e.cfg,{model:e.model,capabilityProviderId:e.provider,toolModelField:"videoGenerationModel"});if(!o)throw new Error("ARouter video generation: provider apiKey is not configured.");const r=resolveArouterBaseUrl(e.cfg),t=e.model?.trim()||DEFAULT_AROUTER_VIDEO_MODEL,i=arouterAuthHeaders(o),a=Date.now()+(e.timeoutMs??3e5),s=await arouterFetch(`${r}/videos`,{method:"POST",headers:i,body:JSON.stringify(buildSubmitBody(e,t)),deadlineAt:a});if(!s.ok)throw new Error(`ARouter video submit failed (${s.status}): ${await readErrorBody(s)}`);const d=await s.json(),n=d.id?.trim();if(!n)throw new Error("ARouter video submit response missing task id.");const u=await pollArouterVideoTask({baseUrl:r,taskId:n,headers:i,deadlineAt:a}),l=`${r}/videos/${encodeURIComponent(n)}/content?index=0`,m=await arouterFetch(l,{headers:i,deadlineAt:a});if(!m.ok)throw new Error(`ARouter video download failed (${m.status}): ${await readErrorBody(m)}`);return{videos:[{buffer:Buffer.from(await m.arrayBuffer()),mimeType:m.headers.get("content-type")?.trim()||"video/mp4",fileName:"video-1.mp4"}],model:t,metadata:{taskId:n,status:u.status,...u.generation_id?{generationId:u.generation_id}:{},...u.usage?{usage:u.usage}:{}}}}}}
@@ -1 +1 @@
1
- import{createMessageClient}from"@beeos-ai/message-sdk";import{createNodeMessageClientComposition}from"@beeos-ai/message-sdk/node";export class BeeosClawMessageClientProcessOwner{composition;configurationKey;registrations=new Set;activeStop;startInFlight;stopInFlight;configure(t){const i=JSON.stringify({identityId:t.identityId,serviceUrl:t.serviceUrl??"",scopedDeliveryKey:t.runtimeDelivery?.scopedDeliveryKey??""});if(this.composition){if(this.configurationKey!==i)throw new Error("MessageClient process owner rejected incompatible hot-reload configuration");return this.composition}return this.configurationKey=i,this.composition=composeMessageClient(t),this.composition}createRegistrationToken(){return Symbol("beeos-claw-message-client-registration")}async acquire(t,i){if(this.registrations.has(t))this.startInFlight&&await this.startInFlight;else{if(!this.composition)throw new Error("MessageClient process owner is not configured");this.registrations.add(t);try{if(this.stopInFlight&&await this.stopInFlight,this.activeStop)return;this.startInFlight||(this.startInFlight=(async()=>{const t=await i(this.composition);this.activeStop=t})().finally(()=>{this.startInFlight=void 0})),await this.startInFlight}catch(i){throw this.registrations.delete(t),i}}}async release(t){if(this.registrations.delete(t)&&(this.startInFlight&&await this.startInFlight.catch(()=>{}),!(this.registrations.size>0)&&this.activeStop)){if(!this.stopInFlight){const t=this.activeStop;this.activeStop=void 0,this.stopInFlight=t().finally(()=>{this.stopInFlight=void 0})}await this.stopInFlight}}get referenceCount(){return this.registrations.size}get current(){return this.composition}}export const composeMessageClient=t=>{const i=createNodeMessageClientComposition(t);return{client:createMessageClient(i),nodeTransport:i.nodeTransport}};
1
+ import{createMessageClient}from"@beeos-ai/message-sdk";import{createNodeMessageClientComposition}from"@beeos-ai/message-sdk/node";import{createTokenProvider}from"@beeos-ai/message-sdk/auth";export function createBeeosClawMessageTokenProvider(t){return createTokenProvider(t)}export class BeeosClawMessageClientProcessOwner{composition;configurationKey;registrations=new Set;activeStop;startInFlight;stopInFlight;configure(t){const e=JSON.stringify({identityId:t.identityId,serviceUrl:t.serviceUrl??"",scopedDeliveryKey:t.runtimeDelivery?.scopedDeliveryKey??""});if(this.composition){if(this.configurationKey!==e)throw new Error("MessageClient process owner rejected incompatible hot-reload configuration");return this.composition}return this.configurationKey=e,this.composition=composeMessageClient(t),this.composition}createRegistrationToken(){return Symbol("beeos-claw-message-client-registration")}async acquire(t,e){if(this.registrations.has(t))this.startInFlight&&await this.startInFlight;else{if(!this.composition)throw new Error("MessageClient process owner is not configured");this.registrations.add(t);try{if(this.stopInFlight&&await this.stopInFlight,this.activeStop)return;this.startInFlight||(this.startInFlight=(async()=>{const t=await e(this.composition);this.activeStop=t})().finally(()=>{this.startInFlight=void 0})),await this.startInFlight}catch(e){throw this.registrations.delete(t),e}}}async release(t){if(this.registrations.delete(t)&&(this.startInFlight&&await this.startInFlight.catch(()=>{}),!(this.registrations.size>0)&&this.activeStop)){if(!this.stopInFlight){const t=this.activeStop;this.activeStop=void 0,this.stopInFlight=t().finally(()=>{this.stopInFlight=void 0})}await this.stopInFlight}}get referenceCount(){return this.registrations.size}get current(){return this.composition}}export const composeMessageClient=t=>{const e=createNodeMessageClientComposition(t);return{client:createMessageClient(e),nodeTransport:e.nodeTransport}};
@@ -1 +1 @@
1
- import{deterministicReplyMessageId}from"./im-runtime-dispatch.js";import{logChatLatency}from"./chat-latency.js";export class MessageProjectionInboundConsumer{delivered=new Set;cancelledTargets=new Set;inFlightMessages=new Set;inFlightCancels=new Set;eligibleMessages=new Set;transportContext=new Map;client;bindings;logger;executionJournal;maxConcurrentConversations;conversationQueue=[];queuedConversations=new Set;activeConversations=new Set;rerunConversations=new Set;laneTasks=new Set;cancelTasks=new Set;unsubscribeProjection;unsubscribeRealtime;previousConnection;activeConversationCount=0;started=!1;constructor(e){this.client=e.client,this.bindings=e.bindings,this.logger=e.logger,this.executionJournal=e.executionJournal,this.previousConnection=e.client.getSnapshot().connection,this.maxConcurrentConversations=Math.max(1,Math.floor(e.maxConcurrentConversations??16))}start(){this.started||(this.started=!0,this.unsubscribeRealtime=this.client.listen({eventTypes:["message.created"]},e=>this.admitRealtimeMessage(e)),this.previousConnection=this.client.getSnapshot().connection,this.unsubscribeProjection=this.client.subscribe(()=>{const e=this.client.getSnapshot().connection,t="connected"===e&&"connected"!==this.previousConnection;this.previousConnection=e,t&&this.recoverDurableSnapshot()}),"connected"===this.previousConnection&&this.recoverDurableSnapshot())}async stop(){this.started=!1,this.unsubscribeProjection?.(),this.unsubscribeProjection=void 0,this.unsubscribeRealtime?.(),this.unsubscribeRealtime=void 0,this.conversationQueue.length=0,this.queuedConversations.clear(),this.rerunConversations.clear(),this.eligibleMessages.clear(),this.transportContext.clear(),await Promise.allSettled([...this.laneTasks,...this.cancelTasks])}refresh(){this.recoverDurableSnapshot()}admitRealtimeMessage(e){if(!this.started||"message.created"!==e.type)return;const{instanceId:t,agentId:n,runtimeEpoch:i,conversationId:s,messageId:o}=e.scope;if(!(t&&n&&i&&s&&o))return;if(!this.bindings().find(e=>e.principalId===t&&e.targetAgentId===n&&e.runtimeEpoch===i))return;const a=e.data.message;if(a.id!==o||a.conversationId!==s)return;const r=this.client.getSnapshot().messages[o];if(!r||!isInbound(r)||r.conversationId!==s||r.senderId!==a.senderId||!isCanonicalInboundPublisher(r,e))return;const c=`${s}:${o}`,d=validRequestId(e.correlation.requestId),l=Date.now();d&&this.transportContext.set(c,{requestId:d,admittedAtMs:l,requestIdSource:"realtime_correlation"}),logChatLatency(this.logger,"claw.inbound.realtime_admitted",d??o,l,{request_id_source:d?"realtime_correlation":"message_id_fallback"}),this.eligibleMessages.add(c),this.schedule()}recoverDurableSnapshot(){if(this.started){for(const e of Object.values(this.client.getSnapshot().messages))isInbound(e)&&isRecoverableInboundPublisher(e)&&this.eligibleMessages.add(`${e.conversationId}:${e.id}`);this.schedule()}}schedule(){if(!this.started)return;const e=Object.values(this.client.getSnapshot().messages).filter(isInbound).sort(compareProjectionOrder),t=e.filter(e=>this.eligibleMessages.has(`${e.conversationId}:${e.id}`));for(const n of t)"chat_cancel"===n.type&&this.dispatchCancel(n,e);for(const e of new Set(t.filter(isConversationLane).map(e=>e.conversationId)))this.enqueueConversation(e);this.pumpConversationQueue()}enqueueConversation(e){this.activeConversations.has(e)?this.rerunConversations.add(e):this.queuedConversations.has(e)||(this.queuedConversations.add(e),this.conversationQueue.push(e))}pumpConversationQueue(){for(;this.started&&this.activeConversationCount<this.maxConcurrentConversations&&this.conversationQueue.length>0;){const e=this.conversationQueue.shift();this.queuedConversations.delete(e),this.activeConversations.add(e),this.activeConversationCount+=1;const t=this.drainConversation(e).catch(t=>{this.logger.warn?.(`[beeos-claw] projected inbound lane failed conversation=${e}: ${t instanceof Error?t.message:String(t)}`)}).finally(()=>{this.laneTasks.delete(t),this.activeConversations.delete(e),this.activeConversationCount-=1,this.rerunConversations.delete(e)&&this.started&&this.enqueueConversation(e),this.pumpConversationQueue()});this.laneTasks.add(t)}}async drainConversation(e){const t=Object.values(this.client.getSnapshot().messages).filter(t=>isConversationLane(t)&&t.conversationId===e&&this.eligibleMessages.has(`${t.conversationId}:${t.id}`)).sort(compareProjectionOrder);for(const e of t){if(!this.started)break;const t=resolveExecutionBinding(e,this.bindings());if(!t)continue;const n=`${e.conversationId}:${e.id}`;if(this.cancelledTargets.has(n)){this.delivered.add(n),this.eligibleMessages.delete(n),this.transportContext.delete(n);continue}if(this.delivered.has(n)||this.inFlightMessages.has(n))continue;if("chat_message"===e.type){const i=await this.reconcileRequest(e,t);if(!this.started)break;if("handled"===i){this.delivered.add(n),this.eligibleMessages.delete(n),this.transportContext.delete(n);continue}if("pending"===i)break}if(!sameBinding(t,resolveExecutionBinding(e,this.bindings())))break;let i;try{i=await this.executionJournal.claim(n)}catch(t){this.logger.warn?.(`[beeos-claw] inbound execution claim failed conversation=${e.conversationId} message_id=${e.id}: ${t instanceof Error?t.message:String(t)}`);break}if(!this.started)break;if("existing"===i){this.logger.warn?.(`[beeos-claw] projected inbound skip claimed conversation=${e.conversationId} message_id=${e.id}`),this.delivered.add(n),this.eligibleMessages.delete(n),this.transportContext.delete(n);continue}if(!sameBinding(t,resolveExecutionBinding(e,this.bindings())))break;this.inFlightMessages.add(n);try{const i=this.transportContext.get(n);i&&logChatLatency(this.logger,"claw.inbound.execution_claimed",i.requestId,i.admittedAtMs,{request_id_source:i.requestIdSource}),await dispatchLaneMessage(t,i?{...e,requestId:i.requestId}:e),this.delivered.add(n),this.eligibleMessages.delete(n),this.transportContext.delete(n)}catch(t){this.logger.warn?.(`[beeos-claw] projected inbound handler failed conversation=${e.conversationId} message_id=${e.id}: ${t instanceof Error?t.message:String(t)}`);break}finally{this.inFlightMessages.delete(n)}}}dispatchCancel(e,t){const n=`${e.conversationId}:${e.id}`;if(this.delivered.has(n)||this.inFlightCancels.has(n))return;const i=resolveCancelTarget(e,t,this.bindings());if(!i)return;this.cancelledTargets.add(`${i.message.conversationId}:${i.message.id}`),this.inFlightCancels.add(n);const s=i.binding.inbound.onChatCancel(e).then(()=>{this.delivered.add(n),this.eligibleMessages.delete(n),this.transportContext.delete(n)}).catch(t=>{this.logger.warn?.(`[beeos-claw] projected inbound cancel failed conversation=${e.conversationId} message_id=${e.id}: ${t instanceof Error?t.message:String(t)}`)}).finally(()=>{this.cancelTasks.delete(s),this.inFlightCancels.delete(n)});this.cancelTasks.add(s)}async reconcileRequest(e,t){const n=Object.values(this.client.getSnapshot().messages),i=n.filter(n=>isReplyFor(n,e,t.targetAgentId));if(i.some(isTerminalReply))return"handled";if(i.length>0)return"pending";if(n.some(n=>isReasoningFor(n,e,t.targetAgentId)))return"pending";const s=deterministicReplyMessageId("asst",e.conversationId,e.id,t.principalId);try{const t=await this.client.messages.getEnvelope(e.conversationId,s);return"agent_reply"!==t.type||t.conversationId!==e.conversationId||void 0!==t.replyTo&&t.replyTo.length>0&&t.replyTo!==e.id?(this.logger.warn?.(`[beeos-claw] deterministic reply reconciliation mismatch conversation=${e.conversationId} message_id=${e.id} reply_id=${s}`),"pending"):isTerminalReply(t)?"handled":"pending"}catch(t){return 404===httpStatus(t)?"execute":(this.logger.warn?.(`[beeos-claw] deterministic reply reconciliation failed conversation=${e.conversationId} message_id=${e.id}: ${t instanceof Error?t.message:String(t)}`),"pending")}}}function isInbound(e){return"chat_message"===e.type||"chat_cancel"===e.type||"user.continue"===e.type||"user.auth_grant"===e.type}function isConversationLane(e){return"chat_message"===e.type||"user.continue"===e.type||"user.auth_grant"===e.type}async function dispatchLaneMessage(e,t){"user.continue"!==t.type?"user.auth_grant"!==t.type?await e.inbound.onChatMessage(t):await e.inbound.onChatAuthGrant(t):await e.inbound.onChatContinue(t)}function isCanonicalUserPublisher(e){return"string"==typeof e.senderId&&e.senderId.startsWith("user:")&&e.senderId.length>5}function isCanonicalA2ACommand(e){const t=asRecord(asRecord(e.content)?.metadata);return"chat_message"===e.type&&"a2a"===t?.protocol&&"string"==typeof e.senderId&&e.senderId.length>0}function isCanonicalInboundPublisher(e,t){return"user"===t.actor.kind?t.actor.id===e.senderId&&isCanonicalUserPublisher(e):"service"===t.actor.kind&&"message-service"===t.actor.id&&isCanonicalA2ACommand(e)}function isRecoverableInboundPublisher(e){return isCanonicalUserPublisher(e)||isCanonicalA2ACommand(e)}function resolveExecutionBinding(e,t){if(!e.id)return;const n=fenceMetadata(e),i=nonEmptyString(n?.delivery_principal),s=nonEmptyString(n?.target_agent_id),o=epochValue(n?.runtime_epoch);if(i&&s&&void 0!==o)for(const e of t){if(e.principalId!==i)continue;if(e.targetAgentId!==s)continue;if(epochValue(e.runtimeEpoch)===o)return e}}function epochValue(e){const t=nonEmptyString(e);if(void 0!==t&&/^\d+$/.test(t))return BigInt(t)}function sameBinding(e,t){return void 0!==t&&t.principalId===e.principalId&&t.targetAgentId===e.targetAgentId&&t.runtimeEpoch===e.runtimeEpoch&&t.inbound===e.inbound}function resolveCancelTarget(e,t,n){const i=nonEmptyString(asRecord(e.content)?.target_message_id);if(!i)return;const s=t.find(t=>"chat_message"===t.type&&t.id===i&&t.conversationId===e.conversationId);if(!s)return;const o=resolveExecutionBinding(s,n),a=resolveExecutionBinding(e,n);return o&&a&&o.principalId===a.principalId&&o.targetAgentId===a.targetAgentId&&o.runtimeEpoch===a.runtimeEpoch?{message:s,binding:o}:void 0}function isReplyFor(e,t,n){if("agent_reply"!==e.type||e.conversationId!==t.conversationId||e.replyTo!==t.id)return!1;if(e.senderId===n)return!0;if(!isTerminalReply(e))return!1;const i=nonEmptyString(asRecord(asRecord(t.content)?.metadata)?.delivery_principal);return void 0!==i&&e.senderId===i}function isReasoningFor(e,t,n){return"agent_reasoning"===e.type&&e.conversationId===t.conversationId&&e.replyTo===t.id&&e.senderId===n}function isTerminalReply(e){return"agent_reply"===e.type&&("completed"===e.state||"failed"===e.state||"refused"===e.state||"cancelled"===e.state)}function httpStatus(e){return null!==e&&"object"==typeof e&&"status"in e&&"number"==typeof e.status?e.status:void 0}function asRecord(e){return null===e||"object"!=typeof e||Array.isArray(e)?void 0:e}function fenceMetadata(e){const t=asRecord(e.content),n=asRecord(t?.metadata);if(hasFenceKeys(n))return n;const i=asRecord(e.metadata);return hasFenceKeys(i)?i:hasFenceKeys(t)?t:n}function hasFenceKeys(e){return void 0!==e&&(void 0!==e.delivery_principal||void 0!==e.target_agent_id||void 0!==e.runtime_epoch)}function nonEmptyString(e){return"string"==typeof e&&e.length>0?e:void 0}function validRequestId(e){if(!("string"!=typeof e||0===e.length||e.length>128))return/^[A-Za-z0-9._:-]+$/.test(e)?e:void 0}function compareProjectionOrder(e,t){try{const n=BigInt(e.offset)-BigInt(t.offset);if(0n!==n)return n<0n?-1:1}catch{const n=e.offset.localeCompare(t.offset);if(0!==n)return n}return e.id.localeCompare(t.id)}
1
+ import{deterministicReplyMessageId}from"./im-runtime-dispatch.js";import{logChatLatency}from"./chat-latency.js";export class MessageProjectionInboundConsumer{delivered=new Set;cancelledTargets=new Set;inFlightMessages=new Set;inFlightCancels=new Set;eligibleMessages=new Set;transportContext=new Map;client;bindings;logger;executionJournal;maxConcurrentConversations;conversationQueue=[];queuedConversations=new Set;activeConversations=new Set;rerunConversations=new Set;laneTasks=new Set;cancelTasks=new Set;unsubscribeProjection;unsubscribeRealtime;previousConnection;activeConversationCount=0;started=!1;constructor(e){this.client=e.client,this.bindings=e.bindings,this.logger=e.logger,this.executionJournal=e.executionJournal,this.previousConnection=e.client.getSnapshot().connection,this.maxConcurrentConversations=Math.max(1,Math.floor(e.maxConcurrentConversations??16))}start(){this.started||(this.started=!0,this.unsubscribeRealtime=this.client.listen({eventTypes:["message.created"]},e=>this.admitRealtimeMessage(e)),this.previousConnection=this.client.getSnapshot().connection,this.unsubscribeProjection=this.client.subscribe(()=>{const e=this.client.getSnapshot().connection,t="connected"===e&&"connected"!==this.previousConnection;this.previousConnection=e,t&&this.recoverDurableSnapshot()}),"connected"===this.previousConnection&&this.recoverDurableSnapshot())}async stop(){this.started=!1,this.unsubscribeProjection?.(),this.unsubscribeProjection=void 0,this.unsubscribeRealtime?.(),this.unsubscribeRealtime=void 0,this.conversationQueue.length=0,this.queuedConversations.clear(),this.rerunConversations.clear(),this.eligibleMessages.clear(),this.transportContext.clear(),await Promise.allSettled([...this.laneTasks,...this.cancelTasks])}refresh(){this.recoverDurableSnapshot()}admitRealtimeMessage(e){if(!this.started||"message.created"!==e.type)return;const{instanceId:t,agentId:n,runtimeEpoch:i,conversationId:s,messageId:o}=e.scope;if(!(t&&n&&i&&s&&o))return;if(!this.bindings().find(e=>e.principalId===t&&e.targetAgentId===n&&e.runtimeEpoch===i))return;const r=e.data.message;if(r.id!==o||r.conversationId!==s)return;const a=this.client.getSnapshot().messages[o];if(!a||!isInbound(a)||a.conversationId!==s||a.senderId!==r.senderId||!isCanonicalInboundPublisher(a,e))return;const c=`${s}:${o}`,d=validRequestId(e.correlation.requestId),l=Date.now();d&&this.transportContext.set(c,{requestId:d,admittedAtMs:l,requestIdSource:"realtime_correlation"}),logChatLatency(this.logger,"claw.inbound.realtime_admitted",d??o,l,{request_id_source:d?"realtime_correlation":"message_id_fallback"}),this.eligibleMessages.add(c),this.schedule()}recoverDurableSnapshot(){if(this.started){for(const e of Object.values(this.client.getSnapshot().messages))isInbound(e)&&isRecoverableInboundPublisher(e)&&this.eligibleMessages.add(`${e.conversationId}:${e.id}`);this.schedule()}}schedule(){if(!this.started)return;const e=Object.values(this.client.getSnapshot().messages).filter(isInbound).sort(compareProjectionOrder),t=e.filter(e=>this.eligibleMessages.has(`${e.conversationId}:${e.id}`));for(const n of t)"chat_cancel"===n.type&&this.dispatchCancel(n,e);for(const e of new Set(t.filter(e=>"chat_message"===e.type).map(e=>e.conversationId)))this.enqueueConversation(e);this.pumpConversationQueue()}enqueueConversation(e){this.activeConversations.has(e)?this.rerunConversations.add(e):this.queuedConversations.has(e)||(this.queuedConversations.add(e),this.conversationQueue.push(e))}pumpConversationQueue(){for(;this.started&&this.activeConversationCount<this.maxConcurrentConversations&&this.conversationQueue.length>0;){const e=this.conversationQueue.shift();this.queuedConversations.delete(e),this.activeConversations.add(e),this.activeConversationCount+=1;const t=this.drainConversation(e).catch(t=>{this.logger.warn?.(`[beeos-claw] projected inbound lane failed conversation=${e}: ${t instanceof Error?t.message:String(t)}`)}).finally(()=>{this.laneTasks.delete(t),this.activeConversations.delete(e),this.activeConversationCount-=1,this.rerunConversations.delete(e)&&this.started&&this.enqueueConversation(e),this.pumpConversationQueue()});this.laneTasks.add(t)}}async drainConversation(e){const t=Object.values(this.client.getSnapshot().messages).filter(t=>"chat_message"===t.type&&t.conversationId===e&&this.eligibleMessages.has(`${t.conversationId}:${t.id}`)).sort(compareProjectionOrder);for(const e of t){if(!this.started)break;const t=resolveExecutionBinding(e,this.bindings());if(!t)continue;const n=`${e.conversationId}:${e.id}`;if(this.cancelledTargets.has(n)){this.delivered.add(n),this.eligibleMessages.delete(n),this.transportContext.delete(n);continue}if(this.delivered.has(n)||this.inFlightMessages.has(n))continue;const i=await this.reconcileRequest(e,t);if(!this.started)break;if("handled"===i){this.delivered.add(n),this.eligibleMessages.delete(n),this.transportContext.delete(n);continue}if("pending"===i)break;if(!sameBinding(t,resolveExecutionBinding(e,this.bindings())))break;let s;try{s=await this.executionJournal.claim(n)}catch(t){this.logger.warn?.(`[beeos-claw] inbound execution claim failed conversation=${e.conversationId} message_id=${e.id}: ${t instanceof Error?t.message:String(t)}`);break}if(!this.started)break;if("existing"===s){this.logger.warn?.(`[beeos-claw] projected inbound skip claimed conversation=${e.conversationId} message_id=${e.id}`),this.delivered.add(n),this.eligibleMessages.delete(n),this.transportContext.delete(n);continue}if(!sameBinding(t,resolveExecutionBinding(e,this.bindings())))break;this.inFlightMessages.add(n);try{const i=this.transportContext.get(n);i&&logChatLatency(this.logger,"claw.inbound.execution_claimed",i.requestId,i.admittedAtMs,{request_id_source:i.requestIdSource}),await t.inbound.onChatMessage(i?{...e,requestId:i.requestId}:e),this.delivered.add(n),this.eligibleMessages.delete(n),this.transportContext.delete(n)}catch(t){this.logger.warn?.(`[beeos-claw] projected inbound handler failed conversation=${e.conversationId} message_id=${e.id}: ${t instanceof Error?t.message:String(t)}`);break}finally{this.inFlightMessages.delete(n)}}}dispatchCancel(e,t){const n=`${e.conversationId}:${e.id}`;if(this.delivered.has(n)||this.inFlightCancels.has(n))return;const i=resolveCancelTarget(e,t,this.bindings());if(!i)return;this.cancelledTargets.add(`${i.message.conversationId}:${i.message.id}`),this.inFlightCancels.add(n);const s=i.binding.inbound.onChatCancel(e).then(()=>{this.delivered.add(n),this.eligibleMessages.delete(n),this.transportContext.delete(n)}).catch(t=>{this.logger.warn?.(`[beeos-claw] projected inbound cancel failed conversation=${e.conversationId} message_id=${e.id}: ${t instanceof Error?t.message:String(t)}`)}).finally(()=>{this.cancelTasks.delete(s),this.inFlightCancels.delete(n)});this.cancelTasks.add(s)}async reconcileRequest(e,t){const n=Object.values(this.client.getSnapshot().messages),i=n.filter(n=>isReplyFor(n,e,t.targetAgentId));if(i.some(isTerminalReply))return"handled";if(i.length>0)return"pending";if(n.some(n=>isReasoningFor(n,e,t.targetAgentId)))return"pending";const s=deterministicReplyMessageId("asst",e.conversationId,e.id,t.principalId);try{const t=await this.client.messages.getEnvelope(e.conversationId,s);return"agent_reply"!==t.type||t.conversationId!==e.conversationId||void 0!==t.replyTo&&t.replyTo.length>0&&t.replyTo!==e.id?(this.logger.warn?.(`[beeos-claw] deterministic reply reconciliation mismatch conversation=${e.conversationId} message_id=${e.id} reply_id=${s}`),"pending"):isTerminalReply(t)?"handled":"pending"}catch(t){return 404===httpStatus(t)?"execute":(this.logger.warn?.(`[beeos-claw] deterministic reply reconciliation failed conversation=${e.conversationId} message_id=${e.id}: ${t instanceof Error?t.message:String(t)}`),"pending")}}}function isInbound(e){return"chat_message"===e.type||"chat_cancel"===e.type}function isCanonicalUserPublisher(e){return"string"==typeof e.senderId&&e.senderId.startsWith("user:")&&e.senderId.length>5}function isCanonicalA2ACommand(e){const t=asRecord(asRecord(e.content)?.metadata);return"chat_message"===e.type&&"a2a"===t?.protocol&&"string"==typeof e.senderId&&e.senderId.length>0}function isCanonicalInboundPublisher(e,t){return"user"===t.actor.kind?t.actor.id===e.senderId&&isCanonicalUserPublisher(e):"service"===t.actor.kind&&"message-service"===t.actor.id&&isCanonicalA2ACommand(e)}function isRecoverableInboundPublisher(e){return isCanonicalUserPublisher(e)||isCanonicalA2ACommand(e)}function resolveExecutionBinding(e,t){if(!e.id)return;const n=asRecord(e.content),i=asRecord(n?.metadata),s=nonEmptyString(i?.delivery_principal),o=nonEmptyString(i?.target_agent_id),r=epochValue(i?.runtime_epoch);if(s&&o&&void 0!==r)for(const e of t){if(e.principalId!==s)continue;if(e.targetAgentId!==o)continue;if(epochValue(e.runtimeEpoch)===r)return e}}function epochValue(e){const t=nonEmptyString(e);if(void 0!==t&&/^\d+$/.test(t))return BigInt(t)}function sameBinding(e,t){return void 0!==t&&t.principalId===e.principalId&&t.targetAgentId===e.targetAgentId&&t.runtimeEpoch===e.runtimeEpoch&&t.inbound===e.inbound}function resolveCancelTarget(e,t,n){const i=nonEmptyString(asRecord(e.content)?.target_message_id);if(!i)return;const s=t.find(t=>"chat_message"===t.type&&t.id===i&&t.conversationId===e.conversationId);if(!s)return;const o=resolveExecutionBinding(s,n),r=resolveExecutionBinding(e,n);return o&&r&&o.principalId===r.principalId&&o.targetAgentId===r.targetAgentId&&o.runtimeEpoch===r.runtimeEpoch?{message:s,binding:o}:void 0}function isReplyFor(e,t,n){if("agent_reply"!==e.type||e.conversationId!==t.conversationId||e.replyTo!==t.id)return!1;if(e.senderId===n)return!0;if(!isTerminalReply(e))return!1;const i=nonEmptyString(asRecord(asRecord(t.content)?.metadata)?.delivery_principal);return void 0!==i&&e.senderId===i}function isReasoningFor(e,t,n){return"agent_reasoning"===e.type&&e.conversationId===t.conversationId&&e.replyTo===t.id&&e.senderId===n}function isTerminalReply(e){return"agent_reply"===e.type&&("completed"===e.state||"failed"===e.state||"refused"===e.state||"cancelled"===e.state)}function httpStatus(e){return null!==e&&"object"==typeof e&&"status"in e&&"number"==typeof e.status?e.status:void 0}function asRecord(e){return null===e||"object"!=typeof e||Array.isArray(e)?void 0:e}function nonEmptyString(e){return"string"==typeof e&&e.length>0?e:void 0}function validRequestId(e){if(!("string"!=typeof e||0===e.length||e.length>128))return/^[A-Za-z0-9._:-]+$/.test(e)?e:void 0}function compareProjectionOrder(e,t){try{const n=BigInt(e.offset)-BigInt(t.offset);if(0n!==n)return n<0n?-1:1}catch{const n=e.offset.localeCompare(t.offset);if(0!==n)return n}return e.id.localeCompare(t.id)}