beeos-claw 0.6.69 → 0.6.71

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 (112) hide show
  1. package/README.md +13 -0
  2. package/dist/a2a/tools.js +1 -1
  3. package/dist/acp-gateway/beeos-file-resolver.js +1 -1
  4. package/dist/acp-gateway/bridge-core.js +1 -1
  5. package/dist/acp-gateway/gateway-events.js +1 -1
  6. package/dist/acp-gateway/local-session-history.js +1 -1
  7. package/dist/acp-gateway/mcp-desired-state-controller.js +1 -1
  8. package/dist/acp-gateway/mcp-desired-state-store.js +1 -1
  9. package/dist/acp-gateway/mcp-service.js +1 -1
  10. package/dist/acp-server.js +1 -1
  11. package/dist/agent-auth.js +1 -0
  12. package/dist/agent-sync.js +1 -1
  13. package/dist/auto-reply-tokens.js +1 -1
  14. package/dist/automation/tools.js +1 -1
  15. package/dist/bridge-discovery.js +1 -0
  16. package/dist/canvas/relay-client.js +1 -1
  17. package/dist/canvas/static-html.js +1 -1
  18. package/dist/canvas/tools.js +1 -1
  19. package/dist/canvas/ws-provider.js +1 -1
  20. package/dist/canvas-orchestrator.js +1 -1
  21. package/dist/files/fetch-tool.js +1 -1
  22. package/dist/files/list-tool.js +1 -1
  23. package/dist/gateway-client.js +1 -1
  24. package/dist/im-inbound-handler.js +1 -1
  25. package/dist/im-runtime-dispatch.js +1 -1
  26. package/dist/index.js +1 -1
  27. package/dist/mcp-connector-proxy.js +1 -0
  28. package/dist/media/arouter-config.js +1 -1
  29. package/dist/media/image-provider.js +1 -1
  30. package/dist/media/video-provider.js +1 -1
  31. package/dist/message-client-composition.js +1 -1
  32. package/dist/message-projection-inbound-consumer.js +1 -1
  33. package/dist/plugin-registration-plan.js +1 -1
  34. package/dist/runtime/agent-gateway-runtime-attempt-authorization.js +1 -0
  35. package/dist/runtime/agent-projection-production.js +1 -1
  36. package/dist/runtime/assistant-message-commit-router.js +1 -1
  37. package/dist/runtime/callback-queue.js +1 -1
  38. package/dist/runtime/conversation-title.js +1 -1
  39. package/dist/runtime/core-execution-attempt-context.js +1 -1
  40. package/dist/runtime/deepseek-reasoning-stream.js +1 -1
  41. package/dist/runtime/im-reply-sink.js +1 -1
  42. package/dist/runtime/message-service-conversation-clear-http-authority.js +1 -1
  43. package/dist/runtime/message-service-conversation-run-boundary.js +1 -1
  44. package/dist/runtime/message-service-cron-delivery-http-authority.js +1 -1
  45. package/dist/runtime/message-service-runtime-authenticated-fetch.js +1 -1
  46. package/dist/runtime/message-service-runtime-claim-authority.js +1 -1
  47. package/dist/runtime/message-service-runtime-invocation-authority.js +1 -0
  48. package/dist/runtime/message-service-runtime-message-channel.js +1 -1
  49. package/dist/runtime/message-service-session-model-http-authority.js +1 -1
  50. package/dist/runtime/message-service-session-reasoning-http-authority.js +1 -0
  51. package/dist/runtime/ms-runtime-message-channel-adapter.js +1 -1
  52. package/dist/runtime/ms-runtime-message-channel-consumer-factory.js +1 -1
  53. package/dist/runtime/ms-runtime-rpc-adapter.js +1 -1
  54. package/dist/runtime/openclaw-native-sessions.js +1 -0
  55. package/dist/runtime/openclaw-question-adapter.js +1 -0
  56. package/dist/runtime/openclaw-runtime-capabilities.js +1 -1
  57. package/dist/runtime/openclaw-session-write-quiescence.js +1 -1
  58. package/dist/runtime/question-wire.js +1 -0
  59. package/dist/runtime/reply-router.js +1 -1
  60. package/dist/runtime/runtime-command-dispatcher.js +1 -1
  61. package/dist/runtime/runtime-command-journal.js +1 -1
  62. package/dist/runtime/runtime-jwks-verifier.js +1 -0
  63. package/dist/runtime/runtime-local-parity-matrix.js +1 -1
  64. package/dist/runtime/runtime-message-channel-contract.js +1 -1
  65. package/dist/runtime/runtime-operation-resource-resolver.js +1 -1
  66. package/dist/runtime/runtime-parity-manifest-digest.js +1 -1
  67. package/dist/runtime/runtime-parity-manifest.js +1 -1
  68. package/dist/runtime/runtime-production-authority.js +1 -1
  69. package/dist/runtime/runtime-reasoning.js +1 -0
  70. package/dist/runtime/runtime-registration.js +1 -0
  71. package/dist/runtime/runtime-service-contract-compatibility.js +1 -1
  72. package/dist/runtime/runtime-service-production-candidate.js +1 -1
  73. package/dist/runtime/runtime-session-control-service.js +1 -1
  74. package/dist/runtime/runtime-skills-service.js +1 -1
  75. package/dist/runtime/runtime-transport-failure-policy.js +1 -0
  76. package/dist/runtime/session-mutation-coordinator.js +1 -1
  77. package/dist/runtime/session-new-runtime-delivery-bridge.js +1 -1
  78. package/dist/runtime/session-set-model-mapping.js +1 -1
  79. package/dist/runtime/split-runtime-authorization-verifier.js +1 -0
  80. package/dist/runtime/write-runtime-failure.js +1 -1
  81. package/dist/terminal/runtime-terminal-outbound-registration.js +1 -1
  82. package/dist/terminal/runtime-terminal-service.js +1 -1
  83. package/dist/terminal/terminal-authority-admission.js +1 -1
  84. package/dist/terminal/terminal-authority-contract.js +1 -1
  85. package/dist/terminal/terminal-lease-bound-bridge-client.js +1 -1
  86. package/dist/upload/desktop-screenshot-tool.js +1 -1
  87. package/dist/upload/finalize-hook.js +1 -1
  88. package/dist/upload/tool-artifact-enrichment.js +1 -1
  89. package/dist/upload/tool.js +1 -1
  90. package/dist/upload/upload-file.js +1 -1
  91. package/openclaw.plugin.json +1 -1
  92. package/package.json +11 -12
  93. package/runtime-service-wire-identity.v1.json +12 -12
  94. package/scripts/runtime-blackbox-worker-main.mjs +2 -5
  95. package/dist/approval/bridge.js +0 -1
  96. package/dist/approval/presentation.js +0 -1
  97. package/dist/approval/protocol.generated.js +0 -1
  98. package/dist/chat-envelope.js +0 -1
  99. package/dist/connectors/harness-connector-mcp.js +0 -1
  100. package/dist/question/bridge.js +0 -1
  101. package/dist/runtime/chat-handler-port.js +0 -1
  102. package/dist/runtime/native-cloud-chat-composition.js +0 -1
  103. package/dist/runtime/native-cloud-prompt-bridge.js +0 -1
  104. package/dist/runtime/native-input-files-http.js +0 -1
  105. package/dist/runtime/native-input-files.js +0 -1
  106. package/dist/runtime/native-output-file-attempt.js +0 -1
  107. package/dist/runtime/native-prompt-authority.js +0 -1
  108. package/dist/runtime/native-prompt-preflight.js +0 -1
  109. package/dist/runtime/native-session-new-bridge.js +0 -1
  110. package/dist/runtime/openclaw-session-model.js +0 -1
  111. package/dist/runtime/runtime-error-part.js +0 -1
  112. package/dist/upload/native-output-tool-hook.js +0 -1
@@ -1 +1 @@
1
- import{access,constants,readFile,stat}from"node:fs/promises";import{request as httpsRequest}from"node:https";import{createHash}from"node:crypto";import{basename,extname,resolve}from"node:path";import{HarnessProtocolError,RuntimeLeaseHttp,RuntimeOperationFiles,putPresignedUpload}from"@beeos-ai/cloud-harness-sdk";import{noteUploadedDeliverable}from"./delivery-ledger.js";const DEFAULT_TIMEOUT_MS=3e4,UPLOAD_REUSE_TTL_MS=18e5,MAX_REUSED_UPLOADS=256,completedUploads=new Map;let claimedCloudRuntimeInstanceId,_deps=null;export function setClaimedCloudRuntimeInstanceId(e){claimedCloudRuntimeInstanceId=e}export function setUploadDeps(e){_deps=e}export function getUploadDeps(){return _deps}export async function uploadLocalFile(e,t,r){if(void 0!==claimedCloudRuntimeInstanceId)throw new Error("native output file trusted tool capability required");await access(e,constants.R_OK);if(!(await stat(e)).isFile())throw new Error("not a regular file");const i=basename(e),a=r?.fileNameOverride??i,s=inferMimeType(a),n=await readFile(e);r?.signal?.throwIfAborted();const o=createHash("sha256").update(n).digest("hex"),p=JSON.stringify([t.baseUrl.origin,resolve(e),a,o]),d=Date.now();for(const[e,t]of completedUploads)t.expiresAt<=d&&completedUploads.delete(e);const l=completedUploads.get(p);if(l)return noteUploadedDeliverable(e),{...l.result};const c=AbortSignal.timeout(r?.timeoutMs??3e4),u=r?.signal?AbortSignal.any([r.signal,c]):c,m=await t.files.upload({fileName:a,mimeType:s,data:n,signal:u}),f={fileId:m.fileId,uri:m.uri,name:m.fileName,mimeType:m.mimeType,size:n.byteLength};if(!f.fileId)throw new Error("confirm returned no fileId");return completedUploads.size>=256&&completedUploads.delete(completedUploads.keys().next().value),completedUploads.set(p,{result:f,expiresAt:Date.now()+18e5}),noteUploadedDeliverable(e),{...f}}export class NativeOutputFilesError extends Error{category;detail;constructor(e,t,r){super(e),this.category=t,this.detail=r,this.name="NativeOutputFilesError"}}export async function uploadNativeOutputFile(e,t,r,i,a,s){r.assertAttempt(),await access(e,constants.R_OK);const n=await stat(e);if(!n.isFile()||n.size<=0||n.size>104857600)throw new Error("native output file size invalid");const o=await readFile(e);if(r.assertAttempt(),o.byteLength!==n.size)throw new Error("native output file changed while reading");const p=basename(e),d=inferMimeType(p),l=createHash("sha256").update(o).digest("hex"),c=createHash("sha256").update("beeos/native-output-file/v1\0"+r.operationId+"\0"+r.toolCallId+"\0"+i).digest("hex"),u=new URL(t);if(!["http:","https:"].includes(u.protocol)||u.username||u.password||"/"!==u.pathname||u.search||u.hash)throw new Error("native output Files origin invalid");const m=AbortSignal.any([r.signal,AbortSignal.timeout(s??3e4),...a?[a]:[]]),f={requestMessageId:r.requestMessageId,paramsHash:r.paramsHash,activeRunRegistrationId:r.activeRunRegistrationId,idempotencyKey:c},h=e=>!!e&&"object"==typeof e&&!Array.isArray(e),g=new RuntimeOperationFiles(new RuntimeLeaseHttp({origin:u.origin})),w=async(e,t)=>{r.assertAttempt();const i={runtimeLeaseCredential:r.getLease().runtimeLeaseCredential},a={...f,...t};let s;try{s="presign"===e?await g.presignOutput(i,r.operationId,a,m):await g.confirmOutput(i,r.operationId,a,m)}catch(t){if(t instanceof Error&&"runtime lease response origin changed"===t.message)throw new NativeOutputFilesError("native output Files response origin changed","control_response_origin",`stage=${e}`);if(!(t instanceof HarnessProtocolError))throw t;let r;const i=t.status??0;if(t.body)try{const e=JSON.parse(t.body);h(e)&&h(e.error)&&"string"==typeof e.error.code&&/^[A-Za-z0-9_.:-]{1,128}$/.test(e.error.code)&&(r=e.error.code)}catch(t){if(!(t instanceof SyntaxError))throw new NativeOutputFilesError("native output Files error decode failed","control_error_decode",`stage=${e} http_status=${i}`)}throw new NativeOutputFilesError("native output Files "+e+" failed ("+i+(r?","+r:"")+")","control_http_error",`stage=${e} http_status=${i} code=${r??"none"}`)}if(r.assertAttempt(),"string"==typeof s||void 0===s)throw new SyntaxError("native output Files response is not JSON");if(!h(n=s)||n.operationId!==r.operationId||n.requestMessageId!==f.requestMessageId||n.paramsHash!==f.paramsHash||n.activeRunRegistrationId!==f.activeRunRegistrationId)throw new NativeOutputFilesError("native output Files response binding invalid","control_response_binding",`stage=${e}`);var n;return s},y=await w("presign",{filename:p,content_type:d,size_bytes:o.byteLength,checksum_sha256:l}),v=y.upload,_=y.transferPolicy;if(!h(v)||!h(_)||"string"!=typeof _.allowedOrigin||"upload"!==v.direction||"PUT"!==v.http_method||"string"!=typeof v.file_id||!v.file_id||"string"!=typeof v.url||"string"!=typeof v.expires_at||!Number.isFinite(Date.parse(v.expires_at))||Date.parse(v.expires_at)<=Date.now()||v.content_type!==d||v.size_bytes!==o.byteLength||v.checksum_sha256!==l||!h(v.required_headers)||Object.values(v.required_headers).some(e=>"string"!=typeof e))throw new NativeOutputFilesError("native output Files transfer descriptor invalid","transfer_descriptor_invalid",descriptorDefect(v,_,d,o.byteLength,l));const b=new URL(v.url),x=new URL(_.allowedOrigin);if("https:"!==b.protocol||b.username||b.password||b.hash||"https:"!==x.protocol||x.username||x.password||"/"!==x.pathname||x.search||x.hash||x.origin!==_.allowedOrigin||b.origin!==x.origin)throw new NativeOutputFilesError("native output Files transfer origin invalid","transfer_origin_invalid",`target_matches_allowed=${b.origin===x.origin}`);r.assertAttempt();const I=v.required_headers,O=(await putPresignedUpload({url:b.toString(),allowedOrigin:x.origin,body:o,requiredHeaders:I,signal:m,fetchImpl:()=>putRequiredHeaders(b,I,o,m)})).status;if(r.assertAttempt(),O<200||O>=300)throw new NativeOutputFilesError("native output Files PUT failed ("+O+")","put_rejected",`http_status=${O} bytes=${o.byteLength} headers=${Object.keys(I).join(",")}`);let E;try{E=await w("confirm",{fileId:v.file_id,checksumSha256:l})}catch(e){if(r.assertAttempt(),m.throwIfAborted(),!(e instanceof TypeError||e instanceof SyntaxError))throw e;E=await w("confirm",{fileId:v.file_id,checksumSha256:l})}if(E.fileId!==v.file_id||E.fileName!==p||E.mimeType!==d||E.size!==o.byteLength)throw new NativeOutputFilesError("native output Files ready metadata mismatch","ready_metadata_mismatch",`fileId=${E.fileId===v.file_id} fileName=${E.fileName===p} mimeType=${E.mimeType===d} size=${E.size===o.byteLength}`);r.assertAttempt();const F={fileId:v.file_id,uri:"beeos-file://"+v.file_id,name:p,mimeType:d,size:o.byteLength};return noteUploadedDeliverable(e),F}function putRequiredHeaders(e,t,r,i){const a=Object.keys(t).find(e=>"content-length"===e.toLowerCase());if(void 0!==a&&t[a]!==String(r.byteLength))throw new NativeOutputFilesError("native output Files transfer descriptor invalid","transfer_descriptor_invalid",`field=required_headers.content-length bytes=${r.byteLength}`);return new Promise((a,s)=>{const n=e=>{s(e instanceof Error&&"AbortError"===e.name?e:new TypeError("fetch failed",{cause:e}))},o=httpsRequest(e,{method:"PUT",headers:t,signal:i},e=>{e.on("error",n),e.resume(),e.on("end",()=>a(new Response(null,{status:e.statusCode??0})))});o.on("error",n),o.end(r)})}function descriptorDefect(e,t,r,i,a){const s=e=>!!e&&"object"==typeof e&&!Array.isArray(e);if(!s(e))return"upload=absent";if(!s(t)||"string"!=typeof t.allowedOrigin)return"transferPolicy.allowedOrigin=invalid";const n=[["direction","upload"===e.direction],["http_method","PUT"===e.http_method],["file_id","string"==typeof e.file_id&&e.file_id.length>0],["url","string"==typeof e.url],["expires_at","string"==typeof e.expires_at&&Number.isFinite(Date.parse(e.expires_at))&&Date.parse(e.expires_at)>Date.now()],["content_type",e.content_type===r],["size_bytes",e.size_bytes===i],["checksum_sha256",e.checksum_sha256===a],["required_headers",s(e.required_headers)&&Object.values(e.required_headers).every(e=>"string"==typeof e)]];return`field=${n.find(([,e])=>!e)?.[0]??"none"} bytes=${i}`}function inferMimeType(e){switch(extname(e).toLowerCase()){case".txt":return"text/plain";case".md":return"text/markdown";case".json":return"application/json";case".html":return"text/html";case".css":return"text/css";case".js":case".mjs":case".cjs":return"text/javascript";case".ts":return"text/x.typescript";case".tsx":case".jsx":return"text/jsx";case".xml":return"application/xml";case".yaml":case".yml":return"application/yaml";case".toml":return"application/toml";case".pdf":return"application/pdf";case".doc":return"application/msword";case".docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case".xls":return"application/vnd.ms-excel";case".xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case".ppt":return"application/vnd.ms-powerpoint";case".pptx":return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case".rtf":return"application/rtf";case".odt":return"application/vnd.oasis.opendocument.text";case".ods":return"application/vnd.oasis.opendocument.spreadsheet";case".odp":return"application/vnd.oasis.opendocument.presentation";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";case".mp4":return"video/mp4";case".mov":return"video/quicktime";case".webm":return"video/webm";case".mkv":return"video/x-matroska";case".avi":return"video/x-msvideo";case".m4v":return"video/x-m4v";case".mp3":return"audio/mpeg";case".wav":return"audio/wav";case".flac":return"audio/flac";case".aac":return"audio/aac";case".ogg":return"audio/ogg";case".m4a":return"audio/mp4";case".csv":return"text/csv";case".zip":return"application/zip";case".tar":return"application/x-tar";case".gz":case".tgz":return"application/gzip";default:return"application/octet-stream"}}
1
+ import{access,constants,readFile,stat}from"node:fs/promises";import{createHash}from"node:crypto";import{basename,extname,resolve}from"node:path";import{agentFetch}from"../agent-auth.js";import{noteUploadedDeliverable}from"./delivery-ledger.js";const DEFAULT_TIMEOUT_MS=3e4,UPLOAD_REUSE_TTL_MS=18e5,MAX_REUSED_UPLOADS=256,completedUploads=new Map;let _deps=null;export function setUploadDeps(e){_deps=e}export function getUploadDeps(){return _deps}export async function uploadLocalFile(e,t,a,r){await access(e,constants.R_OK);if(!(await stat(e)).isFile())throw new Error("not a regular file");const o=basename(e),s=r?.fileNameOverride??o,n=inferMimeType(s),i=await readFile(e);r?.signal?.throwIfAborted();const c=createHash("sha256").update(i).digest("hex"),p=JSON.stringify([t,Buffer.from(a.publicKey).toString("base64"),resolve(e),s,c]),l=Date.now();for(const[e,t]of completedUploads)t.expiresAt<=l&&completedUploads.delete(e);const d=completedUploads.get(p);if(d)return noteUploadedDeliverable(e),{...d.result};const m=AbortSignal.timeout(r?.timeoutMs??3e4),u=r?.signal?AbortSignal.any([r.signal,m]):m,f=`${t}/api/v1/agent/files`,g=await agentFetch(f+"/presign",a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileName:s,mimeType:n}),signal:u});if(!g.ok){const e=await g.text().catch(()=>g.statusText);throw new Error(`presign ${g.status}: ${e}`)}const x=await g.json(),w=await fetch(x.uploadUrl,{method:"PUT",headers:{"Content-Type":n},body:new Blob([i],{type:n}),signal:u});if(!w.ok)throw new Error(`S3 PUT failed: ${w.status}`);const v=await agentFetch(f+"/confirm",a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileId:x.fileId}),signal:u});if(!v.ok){const e=await v.text().catch(()=>v.statusText);throw new Error(`confirm ${v.status}: ${e}`)}const h=await v.json(),y={fileId:h.fileId,uri:`beeos-file://${h.fileId}`,name:h.fileName||s,mimeType:h.mimeType||n,size:h.size||i.byteLength};if(!y.fileId)throw new Error("confirm returned no fileId");return completedUploads.size>=256&&completedUploads.delete(completedUploads.keys().next().value),completedUploads.set(p,{result:y,expiresAt:Date.now()+18e5}),noteUploadedDeliverable(e),{...y}}function inferMimeType(e){switch(extname(e).toLowerCase()){case".txt":return"text/plain";case".md":return"text/markdown";case".json":return"application/json";case".html":return"text/html";case".css":return"text/css";case".js":case".mjs":case".cjs":return"text/javascript";case".ts":return"text/x.typescript";case".tsx":case".jsx":return"text/jsx";case".xml":return"application/xml";case".yaml":case".yml":return"application/yaml";case".toml":return"application/toml";case".pdf":return"application/pdf";case".doc":return"application/msword";case".docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case".xls":return"application/vnd.ms-excel";case".xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case".ppt":return"application/vnd.ms-powerpoint";case".pptx":return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case".rtf":return"application/rtf";case".odt":return"application/vnd.oasis.opendocument.text";case".ods":return"application/vnd.oasis.opendocument.spreadsheet";case".odp":return"application/vnd.oasis.opendocument.presentation";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";case".mp4":return"video/mp4";case".mov":return"video/quicktime";case".webm":return"video/webm";case".mkv":return"video/x-matroska";case".avi":return"video/x-msvideo";case".m4v":return"video/x-m4v";case".mp3":return"audio/mpeg";case".wav":return"audio/wav";case".flac":return"audio/flac";case".aac":return"audio/aac";case".ogg":return"audio/ogg";case".m4a":return"audio/mp4";case".csv":return"text/csv";case".zip":return"application/zip";case".tar":return"application/x-tar";case".gz":case".tgz":return"application/gzip";default:return"application/octet-stream"}}
@@ -2,7 +2,7 @@
2
2
  "id": "beeos-claw",
3
3
  "name": "beeos-claw",
4
4
  "description": "BeeOS platform bridge plugin for OpenClaw. Provides file upload/download, ACP bridge, and observability.",
5
- "version": "0.6.48-staging.1",
5
+ "version": "0.6.67",
6
6
  "activation": {
7
7
  "onStartup": true
8
8
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "beeos-claw",
3
- "version": "0.6.69",
3
+ "version": "0.6.71",
4
4
  "description": "OpenClaw plugin that bridges the BeeOS platform with the local OpenClaw Gateway, providing file transfer, ACP bridge, and observability.",
5
5
  "license": "MIT",
6
6
  "author": "BeeOS <dev@beeos.ai>",
@@ -44,7 +44,7 @@
44
44
  "verify:release-evidence": "node ./scripts/verify-release-evidence.mjs",
45
45
  "verify:release-types-pin": "node ./scripts/verify-release-types-pin.mjs",
46
46
  "verify:release-package": "npm run build:release && node ./scripts/verify-release-package.mjs",
47
- "test:release-workflows": "node ./scripts/test-release-workflows.mjs && node --test ./scripts/run-ci-gates.test.mjs ./scripts/openclaw-promotion-receipt.test.mjs ./scripts/verify-tag-release-request.test.mjs ./scripts/openclaw-release-authority.test.mjs ./scripts/openclaw-release-dispatch.test.mjs ./scripts/openclaw-release-finalizer.test.mjs ./scripts/openclaw-release-completion.test.mjs ./scripts/openclaw-release-recovery.test.mjs ./scripts/verify-openclaw-dispatch-contract.test.mjs ./scripts/verify-promotion-evidence.test.mjs ./scripts/verify-package-equivalence.test.mjs ./scripts/verify-package-equivalence.e2e.test.mjs ./scripts/cloud-staging-publish.test.mjs",
47
+ "test:release-workflows": "node ./scripts/test-release-workflows.mjs && node --test ./scripts/run-ci-gates.test.mjs ./scripts/openclaw-promotion-receipt.test.mjs ./scripts/verify-tag-release-request.test.mjs ./scripts/openclaw-release-authority.test.mjs ./scripts/openclaw-release-dispatch.test.mjs ./scripts/openclaw-release-finalizer.test.mjs ./scripts/openclaw-release-completion.test.mjs ./scripts/openclaw-release-recovery.test.mjs ./scripts/verify-openclaw-dispatch-contract.test.mjs ./scripts/verify-promotion-evidence.test.mjs ./scripts/verify-package-equivalence.test.mjs ./scripts/verify-package-equivalence.e2e.test.mjs",
48
48
  "ci:gates": "node ./scripts/run-ci-gates.mjs",
49
49
  "check:runtime-blackbox-worker": "node --check ./scripts/runtime-blackbox-worker.mjs && node --check ./scripts/runtime-blackbox-worker-main.mjs && node --check ./scripts/runtime-blackbox-worker-lease.mjs && node --check ./scripts/runtime-blackbox-worker-lifecycle.mjs && node --check ./scripts/runtime-journal-checkpoint.mjs && node --test ./scripts/runtime-blackbox-worker-lease.test.mjs ./scripts/runtime-blackbox-worker-lifecycle.test.mjs ./scripts/runtime-blackbox-worker-launcher.test.mjs",
50
50
  "prepublishOnly": "npm run verify:release-types-pin",
@@ -58,19 +58,18 @@
58
58
  "build": "npm run clean && tsc -p tsconfig.build.json",
59
59
  "build:release": "npm run build && npm run minify",
60
60
  "typecheck": "tsc -p tsconfig.json --noEmit",
61
- "question:verify": "node ./src/contracts/question/verify.mjs",
62
61
  "lint": "npm run question:verify && npm run typecheck && eslint \"src/**/*.ts\"",
63
62
  "minify": "find dist -name '*.js' -exec sh -c 'for file do terser \"$file\" --compress drop_console=true,drop_debugger=true --mangle --output \"$file.min\" && mv \"$file.min\" \"$file\" || exit 1; done' sh {} + && find dist -name '*.d.ts' -delete && find dist -name '*.d.ts.map' -delete",
64
63
  "test": "npm run test:ci",
65
64
  "test:ci": "node ./scripts/test-ci.mjs",
66
- "test:watch": "vitest"
65
+ "test:watch": "vitest",
66
+ "question:verify": "node src/contracts/question/verify.mjs"
67
67
  },
68
68
  "dependencies": {
69
- "@beeos-ai/beeos-types": "4.4.2-cloud.3",
69
+ "@beeos-ai/beeos-types": "4.4.2-thinking.0",
70
70
  "@beeos-ai/bridge-client": "^0.1.0",
71
- "@beeos-ai/cloud-harness-sdk": "1.0.0-cloud.6",
72
- "@beeos-ai/message-sdk": "2.0.16",
73
- "@modelcontextprotocol/sdk": "^1.29.0",
71
+ "@beeos-ai/message-sdk": "2.0.18-question.0",
72
+ "@modelcontextprotocol/sdk": "^1.32.1",
74
73
  "adm-zip": "0.6.1",
75
74
  "ws": "^8.18.0"
76
75
  },
@@ -83,11 +82,11 @@
83
82
  "eslint": "^9.39.4",
84
83
  "terser": "^5.39.0",
85
84
  "typescript": "^5.6.3",
86
- "vitest": "^4.1.0"
85
+ "vitest": "^4.1.11"
87
86
  },
88
87
  "overrides": {
89
- "fast-uri": ">=3.1.4",
90
- "brace-expansion": ">=5.0.9"
88
+ "fast-uri": ">=4.2.1",
89
+ "brace-expansion": ">=5.0.12"
91
90
  },
92
- "gitHead": "5c7b5e576bd84fc1dc8958bf783416725781cdd1"
91
+ "gitHead": "1c0040a0466b8e3fdfab3cda4a477916bb1f0dbe"
93
92
  }
@@ -4,32 +4,32 @@
4
4
  "hashAlgorithm": "SHA-256",
5
5
  "canonicalTypes": {
6
6
  "package": "@beeos-ai/beeos-types",
7
- "version": "4.4.2-cloud.3",
7
+ "version": "4.4.2-thinking.0",
8
8
  "runtimeRpcContractRevision": "2026-07-14.3",
9
- "runtimeMethodManifestRawSHA256": "f75832c57a18ca614e946a3b1d194828df76d600907f378efe28633df94146fc",
10
- "runtimeMethodManifestJcsSHA256": "2e58dbc13b8bef2491b95f89920945cb905085828b2fa7a4d4f621624971b186"
9
+ "runtimeMethodManifestRawSHA256": "dd0eca4c8229ef26b788a86b39dfd2b05ab1a096d94b53ae355511f4c99756ed",
10
+ "runtimeMethodManifestJcsSHA256": "de658b3a2ac506d1199c8972dc081f35ead75e601a2bf36dd567ba7634d883ac"
11
11
  },
12
12
  "artifacts": [
13
13
  {
14
14
  "name": "runtime-parity-manifest",
15
15
  "path": "openapi/runtime-parity-manifest-v1.json",
16
- "revision": "beeos.runtime-parity.v1.1.0",
17
- "rawSHA256": "f1030e7bf2084f584d558c22b9bffde0f823d6950c696a6f0571adaffcdbcee0",
18
- "jcsSHA256": "c98ed2aa822b29530cb02badd51654f2766f1dc0ff2c53b660be6431b1f23747"
16
+ "revision": "beeos.runtime-parity.v1.2.0",
17
+ "rawSHA256": "a88335bd662d3ef94c24aa01f0174e6917524766c6c6cac3695c7282a239ff7d",
18
+ "jcsSHA256": "a49592ac3be446dc20537cf1d7fe3b0c517a9ccb5e6aca8b69b421f777066f52"
19
19
  },
20
20
  {
21
21
  "name": "runtime-message-channel",
22
22
  "path": "openapi/runtime-message-channel-v1.contract.json",
23
- "revision": "beeos.runtime-message-channel.v2.0.0",
24
- "rawSHA256": "dd791ce5f49b7bee1dba21a71e7b2cfbf4db7d77cb787aab5f04c7f4b0e3101b",
25
- "jcsSHA256": "e950f1a86bf2bd8bf472603a91111c15b920fcac4c06fd8ac70e2c3f4c3a408f"
23
+ "revision": "beeos.runtime-message-channel.v2.1.0",
24
+ "rawSHA256": "79e66c441fac7f1bd493f837a4814b1c1d82fb0110863d99bcc8d85fe040d5e9",
25
+ "jcsSHA256": "cec634cca225629056b7bff9605008ee975249da11e493f0c54da85c848635b2"
26
26
  },
27
27
  {
28
28
  "name": "runtime-authority-ports",
29
29
  "path": "openapi/runtime-authority-ports-v1.contract.json",
30
- "revision": "beeos.runtime-authority-ports.v2.0.0",
31
- "rawSHA256": "a2e9565ae617bcaeb4d837fe176a3602be041913d28a3f0a3a9ec2e3dae0d7b4",
32
- "jcsSHA256": "3bd582f1f6babcdbe953a082faf813247c960f6bbf4c0f713e7fd92e27d163f5"
30
+ "revision": "beeos.runtime-authority-ports.v2.1.0",
31
+ "rawSHA256": "42b99ef67bb889375ede81803d3800c47a52ce5ea10faffa1ccfb7d3062afcde",
32
+ "jcsSHA256": "8ebee5df8bd325da15bc47e75db444eb25390d61285f579bb54e31f114f70e36"
33
33
  }
34
34
  ]
35
35
  }
@@ -2,7 +2,7 @@ import { readFile } from "node:fs/promises";
2
2
  import { createHash } from "node:crypto";
3
3
  import { join } from "node:path";
4
4
  import { GatewayClient } from "../dist/gateway-client.js";
5
- import { agentIdentityFromKeyPair, authenticatedAgentFetch, loadAgentKeyPair } from "@beeos-ai/cloud-harness-sdk";
5
+ import { loadAgentKeyPair, agentBoundFetch } from "../dist/agent-auth.js";
6
6
  import { OpenClawRuntimeCapabilities } from "../dist/runtime/openclaw-runtime-capabilities.js";
7
7
  import { OpenClawRuntimeCommandDispatcher } from "../dist/runtime/runtime-command-dispatcher.js";
8
8
  import { FileRuntimeAgentIdentityRegistry } from "../dist/runtime/runtime-agent-identity-registry.js";
@@ -48,7 +48,6 @@ export async function main() {
48
48
  if (agentKeys.publicKey.length !== 32 || agentKeys.privateKey.length !== 32) {
49
49
  throw new Error("blackbox Agent identity must contain 32-byte Ed25519 public/seed keys");
50
50
  }
51
- const agentIdentity = agentIdentityFromKeyPair(agentKeys);
52
51
  const leaseClaims = decodeRuntimeLease(nonempty(authority.runtimeLeaseCredential,
53
52
  "authority.runtimeLeaseCredential"));
54
53
  const instanceId = requiredEnvironment("FIXTURE_INSTANCE_ID");
@@ -102,13 +101,11 @@ export async function main() {
102
101
  });
103
102
  const messageFetch = messageComposition.nodeTransport;
104
103
  const boundAgentFetch = async (url, init = {}) => {
105
- // The Gateway v2 signing preimage covers the path only, so a query would be unsigned.
106
- if (new URL(url).search !== "") throw new Error("body-bound agent authority routes forbid query parameters");
107
104
  const headers = new Headers(init.headers);
108
105
  headers.set("X-Instance-ID", instanceId);
109
106
  headers.set("X-Instance-Owner-ID", ownerId);
110
107
  httpRequests += 1;
111
- return await withinDeadline((signal) => authenticatedAgentFetch(url, agentIdentity, { ...init, headers, signal }), deadline);
108
+ return await withinDeadline((signal) => agentBoundFetch(url, agentKeys, { ...init, headers, signal }), deadline);
112
109
  };
113
110
  const statePrefix = join(receiptDir, "claw-worker");
114
111
  const commandJournal = new FileRuntimeCommandJournal(`${statePrefix}-commands.json`);
@@ -1 +0,0 @@
1
- import{toMessagePart}from"../message-client-types.js";import{approvalPresentation}from"./presentation.js";import{APPROVAL_PART_KIND,APPROVAL_SCHEMA_VERSION,readApprovalDocument}from"./protocol.generated.js";export function settleBeforeTerminal(e,t){return{get id(){return e.id},get isTerminated(){return e.isTerminated},get parts(){return e.parts},opened:()=>e.opened(),appendBody:t=>e.appendBody(t),setBody:t=>e.setBody(t),addPart:t=>e.addPart(t),replacePart:(t,r)=>e.replacePart(t,r),appendToolResult:(t,r,n)=>e.appendToolResult(t,r,n),finalize:r=>(t(),e.finalize(r)),fail:r=>(t(),e.fail(r)),cancel:r=>(t(),e.cancel(r))}}const NATIVE_DECISIONS=["allow-once","allow-always","deny"],ACTION_OF={"allow-once":"approve_once","allow-always":"approve_always",deny:"deny"},NATIVE_OF={approve_once:"allow-once",approve_always:"allow-always",deny:"deny"},record=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),text=e=>"string"==typeof e&&e.length>0?e:void 0;export class OpenClawApprovalBridge{deps;sinks=new Map;pending=new Map;constructor(e){this.deps=e}bindSession(e,t){return this.sinks.set(e,t),()=>{if(this.sinks.get(e)===t){this.sinks.delete(e);for(const[e,r]of this.pending)r.sink===t&&(this.pending.delete(e),t.add(approvalPart(cancelledByRunEnd(e,r.request))))}}}onGatewayEvent(e,t){switch(e){case"exec.approval.requested":return this.requested("exec",t);case"plugin.approval.requested":return this.requested("plugin",t);case"exec.approval.resolved":case"plugin.approval.resolved":return this.resolved(t);default:return}}async onDecision(e){const t=readApprovalDocument(e);if(!t||"approval_decision"!==t.kind)return!1;const r=this.pending.get(t.request_id);if(!r)return this.deps.logger.info?.(`[approval] decision for unknown or settled request_id=${t.request_id}`),!0;if(r.actionId)return!0;const n=NATIVE_OF[t.decision];if(!n||!r.request.available_actions.includes(t.decision))return this.deps.logger.warn?.(`[approval] unsupported decision=${t.decision} request_id=${t.request_id}`),!0;r.actionId=t.action_id;try{await this.deps.request("approval.resolve",{id:t.request_id,kind:r.kind,decision:n})}catch(e){r.actionId=void 0,this.deps.logger.warn?.(`[approval] approval.resolve failed request_id=${t.request_id}: ${e instanceof Error?e.message:String(e)}`)}return!0}requested(e,t){if(!record(t)||!record(t.request))return;const r=text(t.id),n=text(t.request.sessionKey);if(!r||!n||this.pending.has(r))return;const a=this.sinks.get(n);if(!a)return;const o=toApprovalRequest(e,r,t.request,t.expiresAtMs);void 0!==a.add(approvalPart(o))&&this.pending.set(r,{kind:e,sink:a,request:o})}resolved(e){if(!record(e))return;const t=text(e.id),r=t?this.pending.get(t):void 0;t&&r&&(this.pending.delete(t),r.sink.add(approvalPart(toApprovalResolved(t,e,r))))}}export function approvalPart(e){return toMessagePart({type:"custom",kind:APPROVAL_PART_KIND,data:e})}function toApprovalRequest(e,t,r,n){const a=Array.isArray(r.allowedDecisions)?NATIVE_DECISIONS.filter(e=>r.allowedDecisions.includes(e)):[...NATIVE_DECISIONS],o=Array.isArray(r.unavailableDecisions)?r.unavailableDecisions:[],i="exec"===e?{tool_name:"exec",summary:text(r.commandPreview)??text(r.command)??"",...text(r.cwd)?{detail:r.cwd}:{}}:{...text(r.toolName)?{tool_name:r.toolName}:{},summary:text(r.title)??"",...text(r.description)||text(r.detail)?{detail:[text(r.description),text(r.detail)].filter(Boolean).join("\n\n")}:{}},s="number"==typeof n&&Number.isFinite(n)?n:Date.now();return{schema_version:APPROVAL_SCHEMA_VERSION,kind:"approval_request",request_id:t,source:"exec"===e?"command":"plugin",operation:approvalPresentation(i,[]),available_actions:a.filter(e=>!o.includes(e)).map(e=>ACTION_OF[e]),expires_at:new Date(s).toISOString(),native:{kind:e,...approvalPresentation(r,[])}}}function requestContent(e){return{source:e.source,operation:e.operation}}function cancelledByRunEnd(e,t){return{schema_version:APPROVAL_SCHEMA_VERSION,kind:"approval_resolved",request_id:e,status:"cancelled",reason:"run_aborted",...requestContent(t),resolved_at:(new Date).toISOString()}}function toApprovalResolved(e,t,r){const{actionId:n}=r,a=text(t.terminalStatus),o=text(t.decision),i="number"==typeof t.ts&&Number.isFinite(t.ts)?t.ts:Date.now(),s="deny"===o&&!n&&i>=Date.parse(r.request.expires_at),d="expired"===a||!a&&s?"expired":"cancelled"===a?"cancelled":"deny"===o?"denied":o?"approved":a??"cancelled",p=o&&NATIVE_DECISIONS.includes(o)?ACTION_OF[o]:void 0;return{schema_version:APPROVAL_SCHEMA_VERSION,kind:"approval_resolved",request_id:e,status:d,..."expired"===d?{reason:"timeout"}:"approved"===d||"denied"===d?{reason:"user"}:{},...!n||"approved"!==d&&"denied"!==d?{}:{action_id:n},...!p||"approved"!==d&&"denied"!==d?{}:{decision:p},...requestContent(r.request),resolved_at:new Date(i).toISOString()}}
@@ -1 +0,0 @@
1
- import{redact}from"../observability.js";const sensitive=/(?:password|passwd|secret|token|authorization|api[_-]?key|cookie|credential)/iu;export function approvalPresentation(e,t){return function e(t){return null===t||"boolean"==typeof t||"number"==typeof t?t:"string"==typeof t?t.replace(/\bBearer\s+[^\s"']+/giu,"Bearer [redacted]").replace(/\b([A-Z_]*(?:TOKEN|SECRET|PASSWORD|API_KEY)[A-Z_]*=)(?:"[^"]*"|'[^']*'|[^\s;]+)/giu,"$1[redacted]").replace(/(https?:\/\/)[^\s/:]+:[^\s/@]+@/giu,"$1[redacted]@"):Array.isArray(t)?t.map(e):t&&"object"==typeof t?Object.fromEntries(Object.entries(t).map(([t,r])=>[t,sensitive.test(t)?"[redacted]":e(r)])):"[unavailable]"}(redact(e,[...t]))}
@@ -1 +0,0 @@
1
- export const APPROVAL_SCHEMA_VERSION="beeos.approval.v1";export const APPROVAL_REQUEST_MESSAGE_TYPE="agent.input_required";export const APPROVAL_DECISION_MESSAGE_TYPE="user.continue";export const APPROVAL_RESOLVED_MESSAGE_TYPE="approval.resolved";export const APPROVAL_PART_KIND="approval";export const APPROVAL_REQUESTED_EVENT="beeos.approval.requested";export const APPROVAL_RESOLVED_EVENT="beeos.approval.resolved";export const APPROVAL_SOURCES=["command","code_execution","protected_write","plugin","system"];export const APPROVAL_ACTIONS=["approve_once","approve_session","approve_always","deny"];export const APPROVAL_STATUSES=["approved","denied","expired","cancelled"];export const APPROVAL_REASONS=["user","timeout","no_human","run_aborted"];export function approvalRequestMessageId(e){return`approval_request:${e}`}export function approvalResolvedMessageId(e){return`approval_resolved:${e}`}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function text(e){return"string"==typeof e&&e.length>0}function optionalText(e){return void 0===e||"string"==typeof e}function isOperation(e){return record(e)&&"string"==typeof e.summary&&optionalText(e.tool_name)&&optionalText(e.detail)}export function isApprovalDocument(e){return record(e)&&"beeos.approval.v1"===e.schema_version}export function readApprovalDocument(e){if(!isApprovalDocument(e)||!text(e.request_id))return null;switch(e.kind){case"approval_request":return text(e.source)&&isOperation(e.operation)&&Array.isArray(e.available_actions)&&e.available_actions.every(text)&&text(e.expires_at)&&(void 0===e.native||record(e.native))?e:null;case"approval_decision":return text(e.action_id)&&text(e.decision)&&optionalText(e.reason)?e:null;case"approval_resolved":return text(e.status)&&optionalText(e.reason)&&optionalText(e.action_id)&&text(e.resolved_at)&&(void 0===e.decision||text(e.decision))&&(void 0===e.source||text(e.source))&&(void 0===e.operation||isOperation(e.operation))?e:null;default:return null}}export function knownApprovalActions(e){return e.available_actions.filter(e=>APPROVAL_ACTIONS.includes(e))}export function isKnownApprovalStatus(e){return APPROVAL_STATUSES.includes(e)}
@@ -1 +0,0 @@
1
- export const A2A_PROTOCOL_FIELDS=Object.freeze(["task_id","skills","artifacts","protocol_version","caller_protocol","correlation_id","callback_url","trace_parent","trace_state","openapi_invocation_id","mcp_request_id","agent_card"]);export function extractChatPrompt(t,e={}){const n=t.content??{},o=n.metadata??{},r=extractMessageText(n);if(!r)return null;const c=pickString(t.conversationId,n.channel_id),i=pickString(n.context_id,o.context_id),s=extractFiles(n),a=pickString(t.id)||void 0,f={message:r,files:s,sessionKey:computeSessionKey({content:n,source:e.source??("agent_request"===t.type?"agent_request":"chat_message"),localAgentId:e.localAgentId??"",contextId:i,channelId:c,generateSuffix:e.generateSuffix??defaultSuffix})};return c&&(f.channelId=c),i&&(f.contextId=i),a&&(f.messageId=a),f}function extractMessageText(t){const e=pickString(t.message);if(e)return e;const n=t.parts;if(Array.isArray(n)){const t=[];for(const e of n)if(e&&"object"==typeof e&&"text"===e.type){const n=e.text;"string"==typeof n&&t.push(n)}if(t.length>0)return t.join("\n")}return""}function extractFiles(t){const e=[],n=t.parts;if(Array.isArray(n))for(const t of n){if(!t||"object"!=typeof t)continue;const n=t.file_url;"string"==typeof n&&n.length>0&&e.push(n)}const o=t.files;if(Array.isArray(o))for(const t of o)if("string"==typeof t&&t.length>0)e.push(t);else if(t&&"object"==typeof t){const n=pickString(t.url,t.uri);n&&e.push(n)}const r=t.attachments;if(Array.isArray(r))for(const t of r){if(!t||"object"!=typeof t)continue;const n=t,o=pickString(n.download_url,n.url,n.uri);o&&e.push(o)}return e}function computeSessionKey(t){const e=pickString(t.content.session_key);if(e)return e;const n=pickString((t.content.metadata&&"object"==typeof t.content.metadata?t.content.metadata:{}).protocol),o=n||("agent_request"===t.source?"a2a":"invoke"),r=`agent:${t.localAgentId}:${o}`;if("chat_message"===t.source||n){if(t.contextId)return`${r}:ctx-${t.contextId}`;if(t.channelId)return`${r}:ch-${t.channelId}`}return`${r}:${t.generateSuffix()}`}function defaultSuffix(){return Math.random().toString(36).slice(2,14)}function pickString(...t){for(const e of t)if("string"==typeof e&&e.length>0)return e;return""}
@@ -1 +0,0 @@
1
- import{listMcpServers}from"../openclaw-cli.js";import{connectMcpServer}from"../acp-gateway/mcp-tool-bridge.js";export function harnessConnectorToolCaller(r={}){const t=r.list??listMcpServers,o=r.connect??connectMcpServer;return async(r,e,n,c)=>{const s=await t();if(!Object.hasOwn(s,r))return;const a=s[r];if("streamable-http"!==a.transport&&"sse"!==a.transport)throw new Error(`connector MCP server ${r} is not a remote server`);if("string"!=typeof a.url)throw new Error(`connector MCP server ${r} has no url`);const i=await o({transport:a.transport,url:a.url,..."number"==typeof a.connectionTimeoutMs?{connectionTimeoutMs:a.connectionTimeoutMs}:{}},a.headers?{headers:a.headers}:void 0);try{return await i.callTool(e,n,c)}catch{throw new Error("MCP tool invocation failed")}finally{await i.close().catch(()=>{})}}}
@@ -1 +0,0 @@
1
- import{createHash,randomUUID}from"node:crypto";import{isDeepStrictEqual}from"node:util";import{toMessagePart}from"../message-client-types.js";import{decodeQuestion,decodeResponse,validateResponse,QUESTION_SCHEMA}from"../contracts/question/codec.js";export const QUESTION_PART_KIND="question";const REQUEST_MESSAGE="请回答以下问题以继续当前任务。",WATCH_INTERVAL_MS=1500,LOOKUP_ATTEMPTS=10;export function askUserQuestionId(e,t){return`ask_${createHash("sha256").update(`${e}\0${t}`).digest("hex").slice(0,32)}`}const record=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),text=e=>"string"==typeof e&&e.length>0?e:void 0,message=e=>e instanceof Error?e.message:String(e);export function isQuestionResponseDocument(e){return record(e)&&e.schema_version===QUESTION_SCHEMA&&"question_response"===e.kind}export class OpenClawQuestionBridge{deps;bindings=new Map;pending=new Map;byRequest=new Map;constructor(e){this.deps=e}bindSession(e,t,s){const n={sink:t,scope:s};return this.bindings.set(e,n),()=>{this.bindings.get(e)===n&&this.bindings.delete(e);for(const e of[...this.pending.values()])e.binding===n&&(this.settle(e,"cancelled"),this.deps.request("question.resolve",{id:e.nativeId,cancel:!0,resolvedBy:"beeos:reply_ended"}).catch(()=>{}))}}onGatewayEvent(e,t){"question.requested"===e?this.requested(t):"question.resolved"===e&&this.resolved(t)}observeAskUser(e){const{sessionKey:t,runId:s,toolCallId:n}=e;t&&s&&n&&this.bindings.has(t)&&this.watch(askUserQuestionId(s,n)).catch(e=>this.deps.logger.warn?.(`[question] watch failed ${s}: ${message(e)}`))}async watch(e){for(let t=0;!this.pending.has(e);t++){if(10===t)return void this.deps.logger.warn?.(`[question] ask_user question ${e} not found`);await this.sleep(0===t?200:1500);const s=await this.get(e);if(s){if("pending"!==s.status)return;if(this.requested(s),!this.pending.has(e))return}}for(;this.pending.has(e);){await this.sleep(1500);const t=await this.get(e);t&&"pending"!==t.status&&this.resolved(t)}}async get(e){try{const t=await this.deps.request("question.get",{id:e});return record(t)&&record(t.question)?t.question:void 0}catch{return}}async onResponse(e){if(!isQuestionResponseDocument(e.content))return!1;let t;try{t=decodeResponse(e.content)}catch(t){return this.deps.logger.warn?.(`[question] invalid response message_id=${e.id}: ${message(t)}`),!0}const s=this.byRequest.get(t.request_id);if(!s||s.binding.scope.conversationId!==e.conversationId)return this.deps.logger.info?.(`[question] response for unknown or settled request_id=${t.request_id}`),!0;if(!e.senderId?.startsWith("user:")||s.attempt)return!0;let n;try{validateResponse(s.request,t),n="answered"===t.outcome?nativeAnswers(s,t):void 0}catch(e){return this.deps.logger.warn?.(`[question] response rejected request_id=${t.request_id}: ${message(e)}`),!0}s.attempt={responseMessageId:e.id,response:t,...n?{native:n}:{}};try{await this.deps.request("question.resolve",n?{id:s.nativeId,answers:{answers:n},resolvedBy:e.senderId,resolutionId:randomUUID()}:{id:s.nativeId,cancel:!0,resolvedBy:e.senderId})}catch(e){this.pending.get(s.nativeId)===s&&(s.attempt=void 0),this.deps.logger.warn?.(`[question] question.resolve failed request_id=${t.request_id}: ${message(e)}`)}return!0}requested(e){if(!record(e)||"pending"!==e.status)return;const t=text(e.id),s=text(e.sessionKey);if(!t||!s||this.pending.has(t))return;const n=this.bindings.get(s);if(!n)return;const i=nativeQuestions(e.questions);let r;try{if(!i)throw new Error("unsupported native question shape");const t=e.expiresAtMs;if("number"!=typeof t||!Number.isFinite(t))throw new Error("missing expiry");r=toQuestionRequest(`qreq_${randomUUID()}`,i,t)}catch(e){return this.deps.logger.warn?.(`[question] cannot present question ${t}: ${message(e)}`),void this.deps.request("question.resolve",{id:t,cancel:!0,resolvedBy:"beeos:unsupported"}).catch(()=>{})}const o=n.sink.add(questionPart(r));if(void 0===o)return;const a={nativeId:t,binding:n,index:o,request:r,native:i};this.pending.set(t,a),this.byRequest.set(r.request_id,a),this.deps.logger.info?.(`[question] presented ${t} request_id=${r.request_id}`)}resolved(e){if(!record(e))return;const t=text(e.id),s=t?this.pending.get(t):void 0;if(!s)return;const n=e.status;if("expired"===n||"cancelled"===n){const e="cancelled"===n&&"cancelled"===s.attempt?.response.outcome;return void this.settle(s,n,e?{response_message_id:s.attempt.responseMessageId}:{})}if("answered"!==n)return;const i=record(e.answers)&&record(e.answers.answers)?e.answers.answers:{},r=s.attempt;if(r?.native&&sameAnswers(s.native,r.native,i)&&"answered"===r.response.outcome)return void this.settle(s,"answered",{answers:r.response.answers,response_message_id:r.responseMessageId});const o=answersFromNative(s,i);o?this.settle(s,"answered",{answers:o}):this.settle(s,"cancelled")}settle(e,t,s={}){this.pending.delete(e.nativeId),this.byRequest.delete(e.request.request_id),e.binding.sink.replace(e.index,questionPart(toQuestionResolved(e.request,t,s,this.now())))}now(){return this.deps.now?.()??Date.now()}sleep(e){return this.deps.sleep?.(e)??new Promise(t=>setTimeout(t,e))}}export function questionPart(e){return toMessagePart({type:"custom",kind:"question",data:e})}function nativeQuestions(e){if(!Array.isArray(e)||0===e.length)return;const t=[];for(const s of e){if(!record(s)||!0===s.isSecret||void 0!==s.secretStore||void 0!==s.url)return;const e=text(s.questionId),n=text(s.question);if(!e||!n||"string"!=typeof s.header||!Array.isArray(s.options))return;const i=[];for(const e of s.options){if(!record(e)||!text(e.label)||void 0!==e.description&&"string"!=typeof e.description)return;i.push({label:e.label,..."string"==typeof e.description&&e.description?{description:e.description}:{}})}t.push({questionId:e,header:s.header,question:n,options:i,multiSelect:!0===s.multiSelect,isOther:!0===s.isOther})}return t}function toQuestionRequest(e,t,s){return decodeQuestion({schema_version:QUESTION_SCHEMA,kind:"question",request_id:e,message:REQUEST_MESSAGE,expires_at:new Date(s).toISOString(),questions:t.map((e,t)=>({id:e.questionId,header:e.header.trim()||`问题 ${t+1}`,text:e.question,input:0===e.options.length?{type:"text"}:{type:e.multiSelect?"multi_select":"single_select",allow_other:e.isOther,options:e.options.map((e,t)=>({value:`option_${t+1}`,...e}))}}))})}function toQuestionResolved(e,t,s,n){return{schema_version:QUESTION_SCHEMA,kind:"question_resolved",request_id:e.request_id,status:t,resolved_at:new Date(n).toISOString(),message:e.message,questions:e.questions,expires_at:e.expires_at,..."answered"===t&&s.answers?{answers:s.answers}:{},...s.response_message_id?{response_message_id:s.response_message_id}:{}}}function nativeAnswers(e,t){const s={};return e.request.questions.forEach((n,i)=>{const r=t.answers[n.id];void 0===r.text?s[n.id]=r.values.map(t=>{const s=Number(t.slice(7))-1;return e.native[i].options[s].label}):s[n.id]=[r.text]}),s}function sameAnswers(e,t,s){return e.every(e=>{const n=(t[e.questionId]??[]).map(t=>e.options.find(e=>e.label.trim()===t.trim())?.label??t.trim());return isDeepStrictEqual(n,s[e.questionId])})}function answersFromNative(e,t){const s={};for(const[n,i]of e.request.questions.entries()){const r=t[i.id];if(!Array.isArray(r)||0===r.length||!r.every(e=>"string"==typeof e&&e.trim()))return;const o=e.native[n].options.map(e=>e.label),a=r.map(e=>o.indexOf(e));if("text"!==i.input.type&&a.every(e=>e>=0))s[i.id]={values:a.map(e=>`option_${e+1}`)};else{if("text"!==i.input.type&&!i.input.allow_other)return;s[i.id]={text:r.join(", ")}}}return s}
@@ -1 +0,0 @@
1
- export{};
@@ -1 +0,0 @@
1
- import{createCentrifugoRealtimePort,createRuntimeChatClient,createRuntimeChatHttpPort}from"@beeos-ai/cloud-harness-sdk";import{NativeSessionNewBridge,nativeSessionNewConversationCreator}from"./native-session-new-bridge.js";const MESSAGE_CREATED="message.created";export function nativeCloudChatAuthorityFromRuntimeAuthority(e,t=Date.now){const n=e=>{if(!e||!e.runtimeLeaseCredential)return null;const n=Date.parse(e.leaseExpiresAt);return!Number.isFinite(n)||n<=t()?null:{instanceId:e.instanceId,handlerIdentity:e.handlerIdentity,runtimeEpoch:e.runtimeEpoch,leaseId:e.leaseId,runtimeLeaseCredential:e.runtimeLeaseCredential,leaseExpiresAt:e.leaseExpiresAt}};return{currentLease:()=>n(e.authorityLease),subscribeAuthority:t=>e.subscribeAuthority(e=>t(n(e)))}}export function createNativeCloudChatComposition(e){const t=e.now??Date.now,n=e.http??createRuntimeChatHttpPort({baseUrl:e.serviceUrl,...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},now:t}),s=e.realtime??createCentrifugoRealtimePort(),i=createRuntimeChatClient({authority:{currentLease:()=>e.authority.currentLease(),subscribeLease:t=>e.authority.subscribeAuthority(t)},http:n,realtime:s,now:t,...e.reconnectDelayMs?{reconnectDelayMs:e.reconnectDelayMs}:{},...e.logger?{logger:e.logger}:{}}),o=new NativeCloudChatAdapterImpl({client:i,...e.logger?{logger:e.logger}:{}});return{client:i,adapter:o,http:n,sessionNew:new NativeSessionNewBridge({client:i,...e.logger?{logger:e.logger}:{}}),sessionNewConversation:nativeSessionNewConversationCreator(i,e.logger),disconnect:async()=>{await o.disconnect(),await i.disconnect()},dispose:()=>{o.dispose(),i.dispose()}}}class NativeCloudChatAdapterImpl{deps;messages;projections=new Map;conversationProjections=new Map;storeListeners=new Set;inboundListeners=new Set;connection="disconnected";constructor(e){this.deps=e,this.messages={startStream:e=>this.startStream(e),getEnvelope:async(e,t)=>await this.getEnvelope(e,t)},this.deps.client.on("message",e=>this.admitInbound(e)),this.deps.client.on("connection",e=>{this.connection=e,this.publish()}),this.deps.client.on("error",e=>{this.deps.logger?.warn?.(`[native-cloud-chat] realtime error: ${e instanceof Error?e.message:String(e)}`)})}async connect(){try{await this.deps.client.connect()}catch(e){throw this.connection="disconnected",this.publish(),e}}async disconnect(){this.connection="disconnected",await this.deps.client.disconnect(),this.publish()}dispose(){this.storeListeners.clear(),this.inboundListeners.clear(),this.deps.client.dispose()}listen(e,t){const n=e.eventTypes;return n&&!n.includes(MESSAGE_CREATED)?()=>{}:(this.inboundListeners.add(t),()=>{this.inboundListeners.delete(t)})}subscribe(e){return this.storeListeners.add(e),()=>{this.storeListeners.delete(e)}}getSnapshot(){const e={};for(const[t,n]of this.projections)e[t]=n;const t={};for(const[e,n]of this.conversationProjections)t[e]=n;return{connection:this.connection,messages:e,conversations:t}}admitInbound(e){const t=toInboundProjection(e);this.projections.set(t.id,t),this.publish();for(const e of[...this.inboundListeners])e(t)}publish(){for(const e of[...this.storeListeners])e()}startStream(e){return new NativeHandlerReplyStream(this.deps.client.messages.startStream({conversationId:e.conversationId,id:e.clientMessageId,type:e.type,content:e.content,...e.replyTo?{replyTo:e.replyTo}:{}}))}async getEnvelope(e,t){const n=(await this.deps.client.history(e)).messages.find(e=>e.id===t);return{state:"string"==typeof n?.state?n.state:"outcome_unknown"}}}class NativeHandlerReplyStream{inner;constructor(e){this.inner=e}get id(){return this.inner.id}get isTerminated(){return this.inner.isTerminated}get parts(){return this.inner.parts}async opened(){const e=asRecord(await this.inner.opened()),t="string"==typeof e?.messageId&&e.messageId.length>0?e.messageId:this.inner.id;return"string"==typeof e?.outcome?{messageId:t,outcome:e.outcome}:{messageId:t}}appendBody(e){this.inner.appendBody(e)}setBody(e){this.inner.setBody(e)}addPart(e){this.inner.addPart(e)}replacePart(e,t){this.inner.replacePart(e,t)}appendToolResult(e,t,n){this.inner.addToolResult({type:"tool_result",tool_use_id:e,content:t,...n?{is_error:!0}:{}})}finalize(e){return this.inner.finalize(e)}fail(e){return this.inner.fail(e)}cancel(e){return this.inner.cancel(e)}}export function toInboundProjection(e){const t=asRecord(e)??{},n="string"==typeof t.body?t.body:"",s=Array.isArray(t.parts)?t.parts:void 0,i="string"==typeof t.state?t.state:void 0,o="string"==typeof t.stopReason?t.stopReason:void 0,r="string"==typeof t.createdAt?t.createdAt:void 0,a="string"==typeof t.updatedAt?t.updatedAt:r,c="string"==typeof t.offset?t.offset:"0";return{...t,id:e.id,conversationId:e.conversationId,type:e.type,content:e.content??{},...e.senderId?{senderId:e.senderId}:{},...e.replyTo?{replyTo:e.replyTo}:{},body:n,...s?{parts:s}:{},...i?{state:i}:{},...o?{stopReason:o}:{},...r?{createdAt:r}:{},...a?{updatedAt:a}:{},offset:c}}function asRecord(e){return null===e||"object"!=typeof e||Array.isArray(e)?void 0:e}export function historyToInboundProjection(e){return toInboundProjection(e)}
@@ -1 +0,0 @@
1
- import{createNativeOutputFileAttempt}from"./native-output-file-attempt.js";import{downloadNativeInputFile}from"./native-input-files.js";import{bindExistingRuntimeChatReply}from"@beeos-ai/cloud-harness-sdk";import{RUNTIME_HASH_DOMAINS}from"@beeos-ai/beeos-types/runtime";import{dispatchImInboundPrompt}from"../im-runtime-dispatch.js";import{prepareNativePromptInput}from"./native-prompt-preflight.js";import{verifyNativePromptAuthority}from"./native-prompt-authority.js";import{RuntimeCommandError}from"./runtime-command-dispatcher.js";import{runtimeCommandResultHash}from"./runtime-command-journal.js";import{runtimeMessageBase,runtimeMessageHash,semanticEqual}from"./runtime-message-channel-contract.js";import{openClawSessionModePatch}from"./runtime-session-control-service.js";export const nativePromptCancellationReason="chat_cancel:runtime_operation_cancel_requested";export const nativePromptExecutionDeadlineReason="deadline exceeded: the Cloud turn execution budget is about to expire";const nativePromptWrapUpMarginMs=3e4;export class NativeCloudPromptBridge{options;constructor(e){if(this.options=e,"function"!=typeof e.host.resolveNativePromptSessionKey)throw new RuntimeCommandError("INVALID_PARAMS","native Core target resolver required");if("function"!=typeof e.host.prepareNativePromptModel)throw new RuntimeCommandError("INVALID_PARAMS","native Core model preparation required");if(!e.runBoundary)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native MS run boundary required")}async execute(e){const{options:t}=this;if(await t.verifier.refresh(),!e.delivery.executionGrant)throw new RuntimeCommandError("INVALID_PARAMS","native grant missing");const a=e.delivery.message.payload,n="string"==typeof a.operationId?await t.journal.get(a.operationId):null,i=!!n&&"session.prompt"===n.command&&["started","effect_committed","projection_committed","failed"].includes(n.phase)&&n.paramsHash===a.paramsHash&&n.messageBinding?.requestMessageId===a.requestMessageId&&n.messageBinding?.requestHash===a.requestHash,r=verifyNativePromptAuthority({request:e.delivery.message.payload,decoded:t.verifier.verifyAndDecodeGrant(e.delivery.executionGrant),lease:e.lease,lineage:t.getLineage(),allowExpiredReadOnly:i}),{params:o}=r,s=r.request;try{const a=e.delivery.message;if("runtime_rpc_request"!==a.type||"completed"!==a.state||a.message_id!==s.requestMessageId||a.channel_id!==s.operationId||void 0!==a.in_reply_to)throw new RuntimeCommandError("INVALID_PARAMS","native envelope binding invalid");let n;void 0!==o.mode&&openClawSessionModePatch(o.mode);try{if(void 0!==o.mentions)throw new TypeError("native host per-prompt optional binding not implemented");n=prepareNativePromptInput(o.parts)}catch(e){throw new RuntimeCommandError(i?"OUTCOME_UNKNOWN":"INVALID_PARAMS","native host part unsupported",void 0,{cause:e})}const d=n.message;if(!t.host.activeRunAuthority)throw new RuntimeCommandError("EXECUTION_FAILED","native existing active-run authority unavailable");const m=()=>{const a=t.getLease(),n=t.getLineage();if(!a||a.instanceId!==e.lease.instanceId||a.handlerIdentity!==e.lease.handlerIdentity||a.runtimeEpoch!==o.runtimeLease.runtimeEpoch||a.leaseId!==o.runtimeLease.leaseId||n.journalStoreId!==o.runtimeLease.journalStoreId||n.journalGeneration!==o.runtimeLease.journalGeneration||Date.parse(a.leaseExpiresAt)<=Date.now())throw new RuntimeCommandError("INSTANCE_EPOCH_MISMATCH","native prompt attempt fenced")};m();const u=await t.channel.history({operationId:s.operationId,lease:e.lease,currentNativePrompt:r});if(m(),"found"!==u.status||u.snapshot.requestHash!==s.requestHash||u.snapshot.requestMessageId!==s.requestMessageId||!semanticEqual(u.snapshot.request.payload,s))throw new RuntimeCommandError("INVALID_PARAMS","native retained request mismatch");let l,p=await t.journal.get(s.operationId);if(m(),p&&("session.prompt"!==p.command||p.paramsHash!==s.paramsHash||p.runtimeEpoch!==o.runtimeLease.runtimeEpoch||p.messageBinding?.requestMessageId!==s.requestMessageId||p.messageBinding.requestHash!==s.requestHash))throw new RuntimeCommandError("OUTCOME_UNKNOWN","native existing journal binding mismatch");if(!t.http.getMessage)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native task snapshot unavailable");try{l=await t.http.getMessage(t.getLease(),{conversationId:o.conversationId,messageId:o.taskRequestMessageId})}catch(e){throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original task snapshot unavailable",void 0,{cause:e})}if(m(),l.messageId!==o.taskRequestMessageId||l.conversationId!==o.conversationId||"chat_message"!==l.type||l.body!==d)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original task snapshot mismatch");const c=async()=>{if(!t.http.getMessage)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native single snapshot unavailable");m();const e=await t.http.getMessage(t.getLease(),{conversationId:o.conversationId,messageId:o.replyMessageId});return m(),this.assertReply(e,r),e};if(u.snapshot.started||p&&"prepared"!==p.phase){const e=u.snapshot.runBoundary?.finishedReceipt,a=u.snapshot.final;if(!(p&&["started","effect_committed","projection_committed","failed"].includes(p.phase)&&e&&"finished"===e.state&&e.activeRunRegistrationId===o.taskId&&a))throw new RuntimeCommandError("OUTCOME_UNKNOWN","native durable MS finish audit or original result unavailable");const n=await c();if("agent_reply"!==n.type||n.state!==e.replyState||n.stopReason!==e.replyStopReason||n.updatedAt!==e.replyUpdatedAt)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original terminal does not match finished audit");const i=this.terminal(n,r);if(a.payload.outcome!==i.outcome||"final_message"!==u.snapshot.terminalSource)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original final outcome mismatch");const d=a.payload.response;if("2.0"!==d.jsonrpc||d.id!==s.request.id)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original final RPC binding mismatch");const l=runtimeCommandResultHash(i.result);if(p.resultReceipt&&p.resultReceipt.resultHash!==l||void 0!==p.result&&!semanticEqual(p.result,i.result))throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original result conflicts with local receipt");if(void 0===d.result)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original canonical result evidence unavailable");{const e=u.snapshot.effectCommitted?.payload,t=runtimeMessageHash(RUNTIME_HASH_DOMAINS.coreResult,{method:s.method,result:d.result});if("succeeded"!==i.outcome||void 0!==d.error||!semanticEqual(d.result,i.result)||!e||e.effectRecord.coreResultHash!==t||e.effectRecord.coreResultRef!==`sha256:${t}`||a.payload.effectRecordHash!==e.effectRecordHash||a.payload.serviceResultHash!==runtimeMessageHash(RUNTIME_HASH_DOMAINS.serviceResult,{method:s.method,result:d.result}))throw new RuntimeCommandError("OUTCOME_UNKNOWN","native original final result hash evidence mismatch")}const h=d.result;return m(),"started"===p.phase&&(p=await t.journal.transition({operationId:s.operationId,expectedRevision:p.revision,phase:"succeeded"===i.outcome?"effect_committed":"failed",result:h}),m()),{request:s,outcome:i.outcome,result:h,replayedFinal:a}}if(n.files.length&&!t.inputFiles)throw new RuntimeCommandError("EXECUTION_FAILED","native authorized input file resolver unavailable");if(u.snapshot.terminal||e.signal.aborted||u.snapshot.cancelRequested||await t.journal.getCancellation(s.operationId))throw new RuntimeCommandError("OPERATION_CANCELLED","native prompt cancelled before effect");const h=await t.host.resolveNativePromptSessionKey(r,m);if(m(),p=await t.journal.acceptMessageRequest({operationId:s.operationId,command:"session.prompt",paramsHash:s.paramsHash,runtimeEpoch:o.runtimeLease.runtimeEpoch,requestMessageId:s.requestMessageId,requestHash:s.requestHash}),m(),"prepared"!==p.phase)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native task already started");let v;const g=await bindExistingRuntimeChatReply({authority:{currentLease:t.getLease},http:t.http,binding:{conversationId:o.conversationId,messageId:o.replyMessageId,taskRequestMessageId:o.taskRequestMessageId,assertAttempt:m,assertPreparedClear:e=>{if(m(),!v||e.activeRunRegistrationId!==v||e.historyGeneration!==r.historyGeneration||e.runtimeEpoch!==o.runtimeLease.runtimeEpoch)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native prepared clear does not freeze this registered attempt")},mutationKey:e=>`native-reply:${s.operationId}:${o.runtimeLease.journalStoreId}:${o.runtimeLease.journalGeneration}:${e}`}});if(m(),e.signal.aborted||await t.journal.getCancellation(s.operationId))throw new RuntimeCommandError("OPERATION_CANCELLED","native prompt cancelled before start");await t.channel.append({operationId:s.operationId,lease:t.getLease(),currentNativePrompt:r,executionGrant:e.delivery.executionGrant,type:"runtime_operation_started",payload:{...runtimeMessageBase(s),executionGrantHash:s.executionGrantHash,handlerIdentity:e.lease.handlerIdentity,executionMode:"start",claimedAt:p.updatedAt}}),m(),p=await t.journal.transition({operationId:s.operationId,expectedRevision:p.revision,phase:"started"}),m();const I=()=>{m();const e=t.getLease();return{leaseId:e.leaseId,handlerIdentity:e.handlerIdentity,runtimeEpoch:e.runtimeEpoch,runtimeLeaseCredential:e.runtimeLeaseCredential}},f={operationId:s.operationId,requestMessageId:s.requestMessageId,conversationId:r.command.context.conversation.runtimeConversationUid,historyGeneration:r.historyGeneration,runtimeRunId:o.runtimeRunId},R=await t.runBoundary.start({...f,lease:I()});if(m(),"registered"!==R.status||R.historyGeneration!==r.historyGeneration||R.activeRunRegistrationId!==o.taskId)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native MS run start did not register the original task");v=R.activeRunRegistrationId;const N=new AbortController,w=()=>N.abort(e.signal.reason);if(e.signal.addEventListener("abort",w,{once:!0}),e.signal.aborted&&w(),e.setCancel(e=>N.abort(e)),await t.journal.getCancellation(s.operationId)&&N.abort(nativePromptCancellationReason),m(),N.signal.aborted){if(e.signal.removeEventListener("abort",w),N.signal.reason===nativePromptCancellationReason)throw new RuntimeCommandError("OPERATION_CANCELLED","native prompt cancelled before host invocation");throw new RuntimeCommandError("OUTCOME_UNKNOWN","native registered run stopped before host invocation")}const E=[];let y;const C=JSON.parse((await g.opened()).rawText),O=C.parts?.length??0,M=async e=>{const t=await e;return m(),this.assertReply(t,r),y=t,t},_={id:g.id,get isTerminated(){return g.isTerminated},get parts(){return E},opened:async()=>({messageId:g.id,outcome:"bound"}),appendBody:e=>g.appendBody(e),setBody:e=>g.setBody(e),addPart:e=>{E.push(e),g.addPart(e)},replacePart:(e,t)=>{E[e]=t,g.replacePart(O+e,t)},appendToolResult:(e,t,a)=>{const n={type:"tool_result",tool_use_id:e,content:t,...a?{is_error:!0}:{}};E.push(n),g.addPart(n)},finalize:e=>M(g.finalize(e)),fail:e=>M(g.fail(e)),cancel:e=>M(g.cancel(e))},b={message:d,mediaPaths:[],mediaTypes:[]};let U,A;const q=createNativeOutputFileAttempt({operationId:s.operationId,requestMessageId:s.requestMessageId,paramsHash:s.paramsHash,activeRunRegistrationId:v,getLease:()=>(m(),t.getLease()),assertAttempt:m,signal:N.signal}),T=setTimeout(()=>N.abort(nativePromptExecutionDeadlineReason),Math.max(0,Math.min(Date.parse(s.executionDeadlineAt)-3e4-Date.now(),2147483647)));T.unref?.();try{await dispatchImInboundPrompt({...t.host,runtimeRunId:o.runtimeRunId,onNativeAgentRunStart:e=>q.bindHostRun(e),nativeActiveRunRegistration:{runtimeConversationUid:f.conversationId,runtimeSessionKey:r.command.context.conversation.runtimeSessionKey,historyGeneration:R.historyGeneration,targetMessageId:o.taskRequestMessageId,runtimeRunId:o.runtimeRunId,activeRunRegistrationId:R.activeRunRegistrationId},assertNativeTarget:async()=>{if(await t.host.resolveNativePromptSessionKey(r,m)!==h)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native prompt target changed before host invocation")},prepareNativeModel:async e=>{m(),await t.host.prepareNativePromptModel(r,e,m),m();for(const e of n.files){if(!t.inputFiles)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native authorized input file resolver unavailable");const a=await t.inputFiles.resolve({operationId:s.operationId,requestMessageId:s.requestMessageId,paramsHash:s.paramsHash,partIndex:e.partIndex,lease:t.getLease(),signal:N.signal});m();const n=await downloadNativeInputFile({fileId:e.fileId,...a,signal:N.signal,assertAttempt:m});b.mediaPaths.push(n.path),b.mediaTypes.push(n.mimeType)}m()},onNativeRunCompletion:e=>{A=e},retainedStream:_,abortSignal:N.signal,inReplyTo:o.taskRequestMessageId,prompt:{channelId:o.conversationId,inboundMessageId:o.taskRequestMessageId,requestId:s.requestMessageId,selfPrincipalId:e.lease.instanceId,sessionKey:h,dispatchInput:b},client:{messages:{startStream(){throw new Error("native reply POST forbidden")},getEnvelope:async()=>({state:(await c()).state})},getSnapshot:()=>({connection:"connected",messages:{},conversations:{}})}})}catch(e){U=e}finally{clearTimeout(T),q.close(),e.signal.removeEventListener("abort",w)}if(!A&&U)throw U;if(!A||A.runtimeRunId!==o.runtimeRunId||A.token.sessionKey!==h)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native physical host completion unavailable");let P;try{await A.completion}catch(e){P=e}if(m(),!y)throw new RuntimeCommandError("OUTCOME_UNKNOWN",void 0!==P?"native host/abort/drain did not converge":"native kernel settled without verified original reply terminal",void 0,{cause:P??U});const S=this.terminal(y,r),L=await c();g.assertTerminalSnapshot(L);const x="completed"===L.state?"completed":"cancelled"===L.state?"cancelled":"failed",H=await t.runBoundary.finish({...f,activeRunRegistrationId:v,terminalState:x,source:"runtime",lease:I()});if(m(),"finished"!==H.status&&"idempotent"!==H.status||H.activeRunRegistrationId!==v)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native MS run finish was not acknowledged");return await t.journal.transition({operationId:s.operationId,expectedRevision:p.revision,phase:"succeeded"===S.outcome?"effect_committed":"failed",result:S.result}),m(),{request:s,...S}}catch(e){throw new NativePromptExecutionFailure(s,e)}}assertReply(e,t){if(e.messageId!==t.params.replyMessageId||e.conversationId!==t.params.conversationId||e.replyTo!==t.params.taskRequestMessageId)throw new RuntimeCommandError("OUTCOME_UNKNOWN","native durable reply binding mismatch")}terminal(e,t){if(!e.stopReason||!["completed","failed","refused","cancelled"].includes(e.state))throw new RuntimeCommandError("OUTCOME_UNKNOWN","native durable terminal absent");const a="cancelled"===e.state&&"user_stop"===e.stopReason?"cancelled":"completed"===e.state&&"end_turn"===e.stopReason?"succeeded":"failed";return{outcome:a,result:{runtimeRunId:t.params.runtimeRunId,stopReason:e.stopReason,requestAborted:"cancelled"===e.state&&"user_stop"===e.stopReason,..."failed"===a?{error:e.body}:{}}}}}export const NATIVE_PROMPT_UNKNOWN_REASONS=new Set(["native MS run boundary required","native existing journal binding mismatch","native task snapshot unavailable","native original task snapshot unavailable","native original task snapshot mismatch","native single snapshot unavailable","native durable MS finish audit or original result unavailable","native original terminal does not match finished audit","native original final outcome mismatch","native original final RPC binding mismatch","native original result conflicts with local receipt","native original final result hash evidence mismatch","native original canonical result evidence unavailable","native task already started","native prepared clear does not freeze this registered attempt","native MS run start did not register the original task","native registered run stopped before host invocation","native prompt target changed before host invocation","native authorized input file resolver unavailable","native physical host completion unavailable","native host/abort/drain did not converge","native kernel settled without verified original reply terminal","native MS run finish was not acknowledged","native durable reply binding mismatch","native durable terminal absent"]);export function nativePromptUnknownReason(e){return e instanceof RuntimeCommandError&&"OUTCOME_UNKNOWN"===e.code?NATIVE_PROMPT_UNKNOWN_REASONS.has(e.message)?e.message:"unlisted":"not_unknown"}export class NativePromptExecutionFailure extends Error{request;failure;constructor(e,t){super(t instanceof Error?t.message:String(t),{cause:t}),this.request=e,this.failure=t}}
@@ -1 +0,0 @@
1
- import{CLOUD_GATEWAY_RUNTIME_ROUTES}from"@beeos-ai/cloud-harness-sdk";import{runtimeLeaseHttp}from"./message-service-runtime-authenticated-fetch.js";const nativeJson=JSON,object=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),integerSource=e=>{if(!nativeJson.isRawJSON(e))return null;const t=JSON.stringify(e);return/^(0|[1-9][0-9]*)$/.test(t)&&BigInt(t)<=9223372036854775807n?t:null},nonempty=e=>"string"==typeof e&&e.length>0;export class NativeInputFilesHttpError extends Error{status;code;requestId;metadata;constructor(e,t,r,n){super(`native input Files resolve failed (${e})`),this.status=e,this.code=t,this.requestId=r,this.metadata=n}}const evidenceText=e=>"string"==typeof e&&/^[A-Za-z0-9_.:-]{1,128}$/.test(e);function selectedHttpError(e,t){const r=object(t)&&object(t.error)?t.error:void 0,n={};if(r&&object(r.metadata))for(const e of["operationId","requestMessageId","paramsHash","taskId","partIndex","clearIntentId","activeRunRegistrationId","historyGeneration","runtimeEpoch"]){const t=r.metadata[e];(evidenceText(t)||nativeJson.isRawJSON(t)&&null!==integerSource(t))&&(n[e]=t)}return new NativeInputFilesHttpError(e,r&&evidenceText(r.code)?r.code:void 0,object(t)&&evidenceText(t.request_id)?t.request_id:void 0,Object.keys(n).length?n:void 0)}export class NativeInputFilesHttpClient{getLease;transport;origin;constructor(e,t,r){this.getLease=t,this.transport=r;const n=new URL(e);if(!["http:","https:"].includes(n.protocol)||n.username||n.password||"/"!==n.pathname||n.search||n.hash)throw new Error("native input Files origin invalid");this.origin=n.origin}async resolve(e){const t=()=>{const t=this.getLease();if(!t||t.instanceId!==e.lease.instanceId||t.handlerIdentity!==e.lease.handlerIdentity||t.leaseId!==e.lease.leaseId||t.runtimeEpoch!==e.lease.runtimeEpoch||!t.runtimeLeaseCredential||Date.parse(t.leaseExpiresAt)<=Date.now())throw new Error("native input Files lease fenced");return t};if(!Number.isSafeInteger(e.partIndex)||e.partIndex<0)throw new Error("native input Files part index invalid");const r=t(),n=await runtimeLeaseHttp(this.origin,(e,t)=>this.transport(e,t??{})).postJson(CLOUD_GATEWAY_RUNTIME_ROUTES.inputFilesResolve(e.operationId),{runtimeLeaseCredential:r.runtimeLeaseCredential},{requestMessageId:e.requestMessageId,paramsHash:e.paramsHash,partIndex:e.partIndex},void 0,e.signal);if(t(),n.url&&new URL(n.url).origin!==this.origin)throw new Error("native input Files response origin changed");if("function"!=typeof nativeJson.rawJSON||"function"!=typeof nativeJson.isRawJSON)throw new Error("native numeric JSON source required");const i=await n.text();let s;try{s=nativeJson.parse(i,(e,t,r)=>{if("number"!=typeof t)return t;if(!r?.source)throw new Error("native numeric JSON source required");return nativeJson.rawJSON(r.source)})}catch(e){if(!(e instanceof SyntaxError))throw e;if(!n.ok)throw new NativeInputFilesHttpError(n.status);throw new Error("native input Files response JSON invalid")}if(t(),!n.ok)throw selectedHttpError(n.status,s);if(!object(s)||s.operationId!==e.operationId||s.requestMessageId!==e.requestMessageId||s.paramsHash!==e.paramsHash||s.taskId!==e.operationId||integerSource(s.partIndex)!==`${e.partIndex}`||!object(s.file)||!object(s.download))throw new Error("native input Files response binding invalid");const o=s.file,a=s.download,d=integerSource(a.size_bytes),c=integerSource(o.size_bytes),u=integerSource(o.resource_version);if(!nonempty(o.file_id)||!nonempty(o.filename)||"ready"!==o.status||null===u||null===c||!nonempty(o.content_type)||"download"!==a.direction||a.file_id!==o.file_id||"GET"!==a.http_method||!nonempty(a.url)||!nonempty(a.expires_at)||!nonempty(a.content_type)||null===d||d!==c||a.content_type!==o.content_type||a.checksum_sha256!==o.checksum_sha256||void 0!==a.checksum_sha256&&"string"!=typeof a.checksum_sha256||!object(a.required_headers)||Object.values(a.required_headers).some(e=>"string"!=typeof e))throw new Error("native input Files descriptor invalid");const p={...a,direction:"download",file_id:o.file_id,url:a.url,http_method:"GET",required_headers:a.required_headers,expires_at:a.expires_at,content_type:a.content_type,size_bytes:d,...void 0!==a.checksum_sha256?{checksum_sha256:a.checksum_sha256}:{}};return{filename:o.filename,download:p,file:o}}}
@@ -1 +0,0 @@
1
- import{createWriteStream}from"node:fs";import{mkdir,mkdtemp,rm}from"node:fs/promises";import{join,basename}from"node:path";import{createHash}from"node:crypto";import{Readable,Transform}from"node:stream";import{pipeline}from"node:stream/promises";export async function downloadNativeInputFile(e){const t=e.download;if("download"!==t.direction||t.file_id!==e.fileId||"GET"!==t.http_method||!/^(0|[1-9][0-9]*)$/.test(t.size_bytes)||!t.content_type||!Number.isFinite(Date.parse(t.expires_at))||Date.parse(t.expires_at)<=Date.now())throw new Error("native input file descriptor invalid or expired");let r;try{r=new URL(t.url)}catch(e){if(!(e instanceof TypeError))throw e;throw new Error("native input file transfer URL invalid")}if("https:"!==r.protocol&&"http:"!==r.protocol||r.username||r.password)throw new Error("native input file transfer URL invalid");if(void 0!==t.checksum_sha256&&!/^[0-9a-f]{64}$/.test(t.checksum_sha256))throw new Error("native input file checksum invalid");e.assertAttempt();const i=e.signal,a=await fetch(r,{method:t.http_method,headers:t.required_headers,signal:i,redirect:"error"});if(!a.ok||!a.body)throw new Error(`native input file download failed (${a.status})`);e.assertAttempt();const o=process.env.OPENCLAW_HOME??join(process.env.HOME??"/home/node",".openclaw"),n=join(o,"workspace","uploads");await mkdir(n,{recursive:!0});const s=await mkdtemp(join(n,"native-input-")),p=basename(e.filename).replace(/[^\p{L}\p{N}._-]/gu,"_"),c=join(s,p&&"."!==p&&".."!==p?p:"attachment");let m=0n;const d=BigInt(t.size_bytes),l=createHash("sha256"),f=new Transform({transform(e,t,r){m+=BigInt(e.byteLength),m>d?r(new Error("native input file size mismatch")):(l.update(e),r(null,e))}});try{const r=a.body.getReader(),o=async function*(){try{for(;;){const e=await r.read();if(e.done)return;yield e.value}}finally{await r.cancel(),r.releaseLock()}};if(await pipeline(Readable.from(o()),f,createWriteStream(c,{flags:"wx",mode:384}),{signal:i}),e.assertAttempt(),m!==d||void 0!==t.checksum_sha256&&l.digest("hex")!==t.checksum_sha256)throw new Error("native input file bytes do not match confirmed descriptor");return{path:c,mimeType:t.content_type}}catch(e){throw await rm(s,{recursive:!0,force:!0}),e}}
@@ -1 +0,0 @@
1
- const runs=new Map,tools=new Map,consumed=new Set;export function createNativeOutputFileAttempt(t){let e,o=!0;const s={...t,assertAttempt(){if(!o)throw new Error("native output file attempt finished");t.signal.throwIfAborted(),t.assertAttempt();const e=t.getLease();if(!e.runtimeLeaseCredential||!Number.isFinite(Date.parse(e.leaseExpiresAt))||Date.parse(e.leaseExpiresAt)<=Date.now())throw new Error("native output file lease fenced")},getLease:()=>(s.assertAttempt(),t.getLease())};return{bindHostRun(t){if(s.assertAttempt(),!t||void 0!==e||runs.has(t))throw new Error("native output file Host run binding ambiguous");e=t,runs.set(t,s)},close(){o=!1,e&&runs.get(e)===s&&runs.delete(e);for(const[t,e]of tools)e.assertAttempt===s.assertAttempt&&tools.delete(t);for(const e of consumed)e.startsWith(t.operationId+"\0")&&consumed.delete(e)}}}export function prepareNativeOutputTool(t,e){if(!t||!e)throw new Error("native output file trusted Host tool binding missing");const o=runs.get(t);if(!o)throw new Error("native output file trusted run missing");o.assertAttempt();const s=o.operationId+"\0"+e;if(tools.has(e)||consumed.has(s))throw new Error("native output file tool binding ambiguous or consumed");tools.set(e,{...o,toolCallId:e})}export function consumeNativeOutputTool(t){const e=tools.get(t);if(tools.delete(t),!e)throw new Error("native output file tool capability missing");return e.assertAttempt(),consumed.add(e.operationId+"\0"+t),e}
@@ -1 +0,0 @@
1
- import{isCloudRuntimeSubject,RUNTIME_HASH_DOMAINS,runtimeCloudCallerIntentPayload,runtimeCloudIdempotencyFingerprintPayload}from"@beeos-ai/beeos-types/runtime";import{runtimeMessageHash,semanticEqual}from"./runtime-message-channel-contract.js";import{RuntimeCommandError}from"./runtime-command-dispatcher.js";import{isDeepStrictEqual}from"node:util";const verifiedPrompts=new WeakMap;export function retainedVerifiedNativePrompt(e){if(!e||"object"!=typeof e)return null;const t=verifiedPrompts.get(e);return t&&isDeepStrictEqual(e,t)?structuredClone(t):null}const object=e=>!!e&&"object"==typeof e&&!Array.isArray(e),nonempty=e=>"string"==typeof e&&!!e,digest=e=>"string"==typeof e&&/^[0-9a-f]{64}$/.test(e),decimal=e=>"string"==typeof e&&/^(0|[1-9][0-9]*)$/.test(e),exact=(e,t)=>Object.keys(e).sort().join("\0")===t.sort().join("\0"),fail=()=>{throw new RuntimeCommandError("INVALID_PARAMS","native prompt signed binding invalid")},validReasoning=e=>object(e)&&exact(e,["modelId","reasoningOverrideId"])&&nonempty(e.modelId)&&(null===e.reasoningOverrideId||nonempty(e.reasoningOverrideId));export function verifyNativePromptAuthority(e){const t=e.request,a=e.decoded?.claims;if(!(object(t)&&object(a)&&object(t.request)&&object(t.command)&&object(t.command.context)&&object(t.command.params)&&object(t.request.params)))return fail();const n=t.request.params,o=t.command.context,r=n.runtimeLease;if(!(exact(t,["schemaVersion","authorityRealm","cloudSubject","operationId","requestMessageId","requestHash","paramsHash","commandHash","idempotencyKeyHash","idempotencyFingerprint","callerIntentHash","instanceId","leaseId","runtimeHandlerIdentity","dispatchEpoch","executionGrantHash","claimDeadlineAt","executionDeadlineAt","createdAt","method","request","command","callerExternalUserId"])&&exact(t.request,["jsonrpc","id","method","params"])&&exact(t.command,["context","name","params"])&&exact(n,["runtimeRunId","parts","conversationId","platformAgentId","taskId","taskRequestMessageId","replyMessageId","inputFingerprint","runtimeLease",...["mentions","mode","modelOverrideId","reasoning","approvalMode"].filter(e=>void 0!==n[e])])&&object(r)&&exact(r,["runtimeEpoch","leaseId","journalStoreId","journalGeneration"])&&2===t.schemaVersion&&"cloud"===t.authorityRealm&&"session/prompt"===t.method&&t.request.method===t.method&&"2.0"===t.request.jsonrpc&&("string"==typeof t.request.id||"number"==typeof t.request.id)&&"session.prompt"===t.command.name&&isCloudRuntimeSubject(t.cloudSubject)&&isCloudRuntimeSubject(a.cloudSubject)&&semanticEqual(t.cloudSubject,a.cloudSubject)&&t.cloudSubject.instanceId===e.lease.instanceId&&t.instanceId===e.lease.instanceId&&t.runtimeHandlerIdentity===e.lease.handlerIdentity&&t.leaseId===e.lease.leaseId&&decimal(t.dispatchEpoch)&&decimal(r.runtimeEpoch)&&decimal(r.journalGeneration)&&r.runtimeEpoch===e.lease.runtimeEpoch&&r.leaseId===e.lease.leaseId&&r.journalStoreId===e.lineage.journalStoreId&&r.journalGeneration===e.lineage.journalGeneration&&nonempty(t.callerExternalUserId)&&nonempty(t.requestMessageId)&&t.requestMessageId!==n.taskRequestMessageId&&n.replyMessageId!==n.taskRequestMessageId&&[n.conversationId,n.platformAgentId,n.taskRequestMessageId,n.replyMessageId].every(nonempty)&&digest(n.inputFingerprint)&&n.taskId===t.operationId&&n.runtimeRunId===t.operationId&&"string"==typeof n.taskId&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(n.taskId)&&Array.isArray(n.parts)&&(void 0===n.mode||"string"==typeof n.mode)&&(void 0===n.modelOverrideId||"string"==typeof n.modelOverrideId)&&(void 0===n.reasoning||validReasoning(n.reasoning))&&(void 0===n.approvalMode||"string"==typeof n.approvalMode)&&(void 0===n.mentions||Array.isArray(n.mentions))&&"conversation"===o.scope&&o.operationId===t.operationId&&o.dispatchEpoch===t.dispatchEpoch&&o.runtimeInstanceUid===t.instanceId&&o.paramsHash===t.paramsHash&&o.idempotencyKeyHash===t.idempotencyKeyHash&&o.claimDeadline===t.claimDeadlineAt&&o.executionDeadline===t.executionDeadlineAt&&decimal(o.historyGeneration)&&object(o.conversation)&&o.conversation.runtimeConversationUid===n.conversationId&&o.conversation.runtimeSessionKey===n.conversationId&&[t.requestHash,t.paramsHash,t.commandHash,t.callerIntentHash,t.idempotencyFingerprint,t.idempotencyKeyHash,t.executionGrantHash].every(digest)))return fail();const i={runtimeRunId:n.runtimeRunId,parts:n.parts,...void 0===n.mentions?{}:{mentions:n.mentions},...void 0===n.mode?{}:{mode:n.mode},...void 0===n.modelOverrideId?{}:{modelOverrideId:n.modelOverrideId},...void 0===n.reasoning?{}:{reasoning:n.reasoning},...void 0===n.approvalMode?{}:{approvalMode:n.approvalMode}},s=e.now??Date.now();if(![t.createdAt,t.claimDeadlineAt,t.executionDeadlineAt].every(e=>"string"==typeof e&&Number.isFinite(Date.parse(e)))||Date.parse(t.createdAt)>Date.parse(t.claimDeadlineAt)||Date.parse(t.claimDeadlineAt)>Date.parse(t.executionDeadlineAt)||!e.allowExpiredReadOnly&&Date.parse(t.claimDeadlineAt)<=s||!e.allowExpiredReadOnly&&Date.parse(t.executionDeadlineAt)<=s||!semanticEqual(i,t.command.params)||runtimeMessageHash(RUNTIME_HASH_DOMAINS.request,t.request)!==t.requestHash||runtimeMessageHash(RUNTIME_HASH_DOMAINS.params,{method:t.method,params:n})!==t.paramsHash||runtimeMessageHash(RUNTIME_HASH_DOMAINS.command,{command:t.command})!==t.commandHash||runtimeMessageHash(RUNTIME_HASH_DOMAINS.cloudCallerIntent,runtimeCloudCallerIntentPayload(t.cloudSubject,"session/prompt",n,t.callerExternalUserId))!==t.callerIntentHash||runtimeMessageHash(RUNTIME_HASH_DOMAINS.cloudIdempotencyFingerprint,runtimeCloudIdempotencyFingerprintPayload(t.cloudSubject,"session/prompt",t.callerIntentHash))!==t.idempotencyFingerprint||e.decoded?.compactHash!==t.executionGrantHash)return fail();const d=Math.floor(s/1e3);if(!exact(a,["iss","aud","purpose","sub","jti","iat","exp","authorityRealm","cloudSubject","operationId","requestMessageId","instanceId","leaseId","handlerIdentity","dispatchEpoch","requestHash","paramsHash","commandHash","idempotencyKeyHash","executionMode","method","command","scope","callerExternalUserId","platformAgentId","runtimeAgentUid","platformConversationId","historyGeneration"])||"beeos-cloud-gateway"!==a.iss||"beeos-cloud-runtime-command"!==a.aud||"cloud-runtime-execution-grant"!==a.purpose||"cloud"!==a.authorityRealm||"start"!==a.executionMode||"conversation"!==a.scope||!nonempty(a.jti)||!nonempty(a.runtimeAgentUid)||!Number.isSafeInteger(a.iat)||!Number.isSafeInteger(a.exp)||a.iat>d||!e.allowExpiredReadOnly&&a.exp<=d||a.exp<=a.iat||a.exp-a.iat>60||a.sub!==e.lease.handlerIdentity||a.handlerIdentity!==e.lease.handlerIdentity||a.platformAgentId!==n.platformAgentId||a.platformConversationId!==n.conversationId||a.historyGeneration!==o.historyGeneration||!semanticEqual(a.command,t.command)||!semanticEqual(a.cloudSubject,t.cloudSubject)||["operationId","requestMessageId","instanceId","leaseId","dispatchEpoch","requestHash","paramsHash","commandHash","idempotencyKeyHash","callerExternalUserId","method"].some(e=>a[e]!==t[e]))return fail();const m=structuredClone(t),c={historyGeneration:o.historyGeneration,runtimeAgentUid:a.runtimeAgentUid,request:m,params:m.request.params,command:m.command};return verifiedPrompts.set(c,structuredClone(c)),c}
@@ -1 +0,0 @@
1
- export function prepareNativePromptInput(e){const t=[],i=[];for(const[r,n]of e.entries()){if("text"===n.type){if("string"!=typeof n.text||hasUnexpectedKey(n,["type","text"]))throw new TypeError("native text part unsupported or invalid");t.push(n.text);continue}if(!["image","audio","file","resource","resource_link"].includes(n.type)||void 0!==n.mimeType&&"string"!=typeof n.mimeType||"resource_link"!==n.type&&void 0!==n.fileName&&"string"!=typeof n.fileName||"resource_link"===n.type&&(void 0!==n.name&&"string"!=typeof n.name||void 0!==n.title&&"string"!=typeof n.title||void 0!==n.sizeBytes&&("string"!=typeof n.sizeBytes||!/^(0|[1-9][0-9]*)$/.test(n.sizeBytes))))throw new TypeError("native file part unsupported or invalid");const e="resource_link"===n.type?n.resourceRef:n.blobRef;if("string"!=typeof e||!/^beeos-file:\/\/[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(e))throw new TypeError("native input part unsupported: canonical Cloud file reference required");i.push({partIndex:r,fileId:e.slice(13)})}return{message:t.join("\n"),files:i}}function hasUnexpectedKey(e,t){return Object.keys(e).some(e=>!t.includes(e))}
@@ -1 +0,0 @@
1
- export function nativeSessionNewSyncRequest(n){const e=nonEmpty(n.operationId);if(!e)throw new Error("native session/new sync requires a retained operationId");const s=nonEmpty(n.runtimeSessionId);if(!s)throw new Error("native session/new sync requires a runtimeSessionId");const o=nonEmpty(n.runtimeSessionKey),t=nonEmpty(n.title);return{schemaVersion:1,operationId:e,runtimeSessionId:s,...o?{runtimeSessionKey:o}:{},...t?{title:t}:{}}}export function assertCanonicalConversationSyncResponse(n){if(!n||"string"!=typeof n.id||0===n.id.length)throw new Error("native session/new sync response is missing a canonical conversation id");return n}export class NativeSessionNewBridge{options;constructor(n){this.options=n}async sync(n){const e=nativeSessionNewSyncRequest(n);this.options.logger?.info?.(`[native-cloud-chat] session/new sync operationId=${e.operationId} runtimeSessionId=${e.runtimeSessionId}`);return{conversation:assertCanonicalConversationSyncResponse(await this.options.client.syncConversation(e))}}}export async function syncNativeSessionNew(n,e){const s=nativeSessionNewSyncRequest(e);return assertCanonicalConversationSyncResponse(await n.syncConversation(s))}export function nativeSessionNewConversationCreator(n,e){const s=new NativeSessionNewBridge({client:n,...e?{logger:e}:{}});return{create:async n=>({conversationId:(await s.sync({operationId:n.operationId,runtimeSessionId:n.runtimeSessionId,runtimeSessionKey:n.runtimeSessionKey,...n.title?{title:n.title}:{}})).conversation.id})}}function nonEmpty(n){return"string"==typeof n&&n.length>0?n:void 0}
@@ -1 +0,0 @@
1
- import{AROUTER_PROVIDER_ID}from"../media/arouter-config.js";let snapshot;export function setOpenClawConfigSnapshot(t){snapshot=t}function listedModelIds(t){if(!t||!Array.isArray(t.models))return[];const o=[];for(const e of t.models){if("string"==typeof e){const t=e.trim();t&&o.push(t);continue}if(e&&"string"==typeof e.id){const t=e.id.trim();t&&o.push(t)}}return o}function primaryProvider(t){const o=t?.agents?.defaults?.model?.primary;if("string"!=typeof o)return;const e=o.indexOf("/");return e>0?o.slice(0,e):void 0}export function createSessionModelRefs(t=snapshot){const o=t?.models?.providers??{},e=Object.keys(o).filter(t=>null!=o[t]),n=new Map;for(const t of e)for(const e of listedModelIds(o[t]))n.set(e,n.has(e)?void 0:t);const r=primaryProvider(t),s=r&&e.includes(r)?r:1===e.length?e[0]:AROUTER_PROVIDER_ID,i=e.includes(AROUTER_PROVIDER_ID)?e:[...e,AROUTER_PROVIDER_ID],f=t=>i.find(o=>t.startsWith(`${o}/`));return{toOpenClaw(t){return f(t)?t:`${o=t,n.get(o)??s}/${t}`;var o},toPlatform(t){const o=f(t);return o?t.slice(o.length+1):t}}}
@@ -1 +0,0 @@
1
- export const RUNTIME_ERROR_PART_KIND="runtime_error";const RUNTIME_ERROR_CODES=["insufficient_credits"];export function createRuntimeErrorPart(r){return{type:"custom",kind:"runtime_error",data:{code:r}}}export function parseRuntimeErrorPart(r){if(!r||"object"!=typeof r||Array.isArray(r))return;const t=r;if("custom"!==t.type||"runtime_error"!==t.kind)return;const e=t.data;if(!e||"object"!=typeof e||Array.isArray(e))return;const n=e.code;return"string"==typeof n&&RUNTIME_ERROR_CODES.includes(n)?createRuntimeErrorPart(n):void 0}
@@ -1 +0,0 @@
1
- import{prepareNativeOutputTool}from"../runtime/native-output-file-attempt.js";import{RENDER_UI_TOOL_NAME}from"../canvas/tools.js";import{BEEOS_UPLOAD_TOOL_NAME}from"./tool.js";export function needsNativeOutputCapability(t,o){return t===BEEOS_UPLOAD_TOOL_NAME||t===RENDER_UI_TOOL_NAME&&Object.prototype.hasOwnProperty.call(o,"html")}export function nativeOutputToolCallGate(t,o){if(needsNativeOutputCapability(t.toolName,t.params)){if(t.runId&&o.runId&&t.runId!==o.runId||t.toolCallId&&o.toolCallId&&t.toolCallId!==o.toolCallId)return{block:!0,blockReason:"native output file Host correlation conflict"};try{prepareNativeOutputTool(t.runId??o.runId,t.toolCallId??o.toolCallId)}catch{return{block:!0,blockReason:"native output file trusted capability unavailable"}}}}