beeos-claw 0.6.63-cloud.5 → 0.6.63-cloud.7
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.
- package/dist/a2a/tools.js +1 -1
- package/dist/acp-gateway/beeos-file-resolver.js +1 -1
- package/dist/acp-gateway/bridge-core.js +1 -1
- package/dist/acp-gateway/gateway-events.js +1 -1
- package/dist/acp-server.js +1 -1
- package/dist/agent-sync.js +1 -1
- package/dist/automation/tools.js +1 -0
- package/dist/automation/turn-policy.js +1 -0
- package/dist/automation/wake.js +1 -0
- package/dist/canvas/relay-client.js +1 -1
- package/dist/canvas/ws-provider.js +1 -1
- package/dist/connectors/managed-connector-tools.js +1 -0
- package/dist/files/fetch-tool.js +1 -1
- package/dist/files/list-tool.js +1 -1
- package/dist/im-inbound-handler.js +1 -1
- package/dist/im-runtime-dispatch.js +1 -1
- package/dist/index.js +1 -1
- package/dist/mcp-connector-proxy.js +1 -1
- package/dist/runtime/agent-projection-production.js +1 -1
- package/dist/runtime/ms-runtime-message-channel-adapter.js +1 -1
- package/dist/runtime/ms-runtime-message-channel-consumer-factory.js +1 -1
- package/dist/runtime/ms-runtime-rpc-adapter.js +1 -1
- package/dist/runtime/native-cloud-chat-composition.js +1 -1
- package/dist/runtime/native-cloud-prompt-bridge.js +1 -1
- package/dist/runtime/native-prompt-preflight.js +1 -1
- package/dist/runtime/runtime-operation-resource-resolver.js +1 -1
- package/dist/runtime/runtime-production-authority.js +1 -1
- package/dist/runtime/runtime-registration-identity-store.js +1 -1
- package/dist/runtime/runtime-service-production-candidate.js +1 -1
- package/dist/runtime/service-runtime-attempt-ports-resolver.js +1 -1
- package/dist/terminal/runtime-terminal-outbound-registration.js +1 -1
- package/dist/terminal/terminal-lease-bound-bridge-client.js +1 -1
- package/dist/upload/desktop-screenshot-tool.js +1 -1
- package/dist/upload/finalize-hook.js +1 -1
- package/dist/upload/tool-artifact-enrichment.js +1 -1
- package/dist/upload/tool.js +1 -1
- package/dist/upload/upload-file.js +1 -1
- package/openclaw.plugin.json +15 -1
- package/package.json +4 -4
- package/dist/agent-auth.js +0 -1
- package/dist/bridge-discovery.js +0 -1
- package/dist/runtime/agent-gateway-runtime-attempt-authorization.js +0 -1
- package/dist/runtime/message-service-runtime-invocation-authority.js +0 -1
- package/dist/runtime/runtime-jwks-verifier.js +0 -1
- package/dist/runtime/runtime-registration.js +0 -1
- package/dist/runtime/runtime-transport-failure-policy.js +0 -1
- package/dist/runtime/split-runtime-authorization-verifier.js +0 -1
package/dist/upload/tool.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{constants}from"node:fs";import{access,stat}from"node:fs/promises";import{uploadLocalFile,NativeOutputFilesError}from"./upload-file.js";import{isBeeosFileUri}from"../files/beeos-file-uri.js";export const BEEOS_UPLOAD_TOOL_NAME="beeos_upload_file";export const BEEOS_UPLOAD_TOOL_DESCRIPTION="Upload 1-5 local files from this machine to the user via the BeeOS platform. This is the only way to deliver a file to the user: whenever you produce or modify a file the user asked for, call this tool with its path. Writing the file to disk or printing it through a shell command does not deliver it. Accepts only local filesystem paths; never pass beeos-file:// URIs because they are already BeeOS platform resources. If the call succeeds, the files are already delivered to the user — do not use any other tool to send them again. Upload modified deliverables again even if the same path was uploaded earlier; unchanged contents may reuse an existing platform file. Any file type is accepted: text, images, documents, PDFs, archives, binaries.";export const BEEOS_UPLOAD_TOOL_SCHEMA={title:"BeeOS file upload",type:"object",description:BEEOS_UPLOAD_TOOL_DESCRIPTION,additionalProperties:!1,required:["paths"],properties:{paths:{type:"array",minItems:1,maxItems:5,description:"Local filesystem paths (1-5). Absolute or workspace-relative. Do not pass beeos-file:// URIs.",items:{type:"string",minLength:1,description:"Single local filesystem path, not a beeos-file:// URI."}}}};const MAX_PATHS=5;export const REQUEST_TIMEOUT_MS=12e4;const MAX_CONCURRENCY=3,BEEOS_FILE_URI_UPLOAD_ERROR="beeos-file:// is already a BeeOS platform file URI, not a local path. Do not upload it; display it directly.";async function runWithConcurrency(e,t){const r=new Array(e.length);let a=0;async function o(){for(;a<e.length;){const t=a++;r[t]=await e[t]()}}const i=[];for(let r=0;r<Math.min(t,e.length);r++)i.push(o());return await Promise.all(i),r}async function validateFiles(e){return Promise.all(e.map(async e=>{try{await access(e,constants.R_OK);return(await stat(e)).isFile()?{path:e,ok:!0}:{path:e,ok:!1,error:"not a regular file"}}catch(t){const r=t.code;let a;return a="ENOENT"===r?"file not found":"ENOTDIR"===r?"path component is not a directory":"EACCES"===r?"permission denied":t instanceof Error?t.message:String(t),{path:e,ok:!1,error:a}}}))}export async function executeUpload(e,t,r,a,o
|
|
1
|
+
import{constants}from"node:fs";import{access,stat}from"node:fs/promises";import{uploadLocalFile,NativeOutputFilesError}from"./upload-file.js";import{isBeeosFileUri}from"../files/beeos-file-uri.js";export const BEEOS_UPLOAD_TOOL_NAME="beeos_upload_file";export const BEEOS_UPLOAD_TOOL_DESCRIPTION="Upload 1-5 local files from this machine to the user via the BeeOS platform. This is the only way to deliver a file to the user: whenever you produce or modify a file the user asked for, call this tool with its path. Writing the file to disk or printing it through a shell command does not deliver it. Accepts only local filesystem paths; never pass beeos-file:// URIs because they are already BeeOS platform resources. If the call succeeds, the files are already delivered to the user — do not use any other tool to send them again. Upload modified deliverables again even if the same path was uploaded earlier; unchanged contents may reuse an existing platform file. Any file type is accepted: text, images, documents, PDFs, archives, binaries.";export const BEEOS_UPLOAD_TOOL_SCHEMA={title:"BeeOS file upload",type:"object",description:BEEOS_UPLOAD_TOOL_DESCRIPTION,additionalProperties:!1,required:["paths"],properties:{paths:{type:"array",minItems:1,maxItems:5,description:"Local filesystem paths (1-5). Absolute or workspace-relative. Do not pass beeos-file:// URIs.",items:{type:"string",minLength:1,description:"Single local filesystem path, not a beeos-file:// URI."}}}};const MAX_PATHS=5;export const REQUEST_TIMEOUT_MS=12e4;const MAX_CONCURRENCY=3,BEEOS_FILE_URI_UPLOAD_ERROR="beeos-file:// is already a BeeOS platform file URI, not a local path. Do not upload it; display it directly.";async function runWithConcurrency(e,t){const r=new Array(e.length);let a=0;async function o(){for(;a<e.length;){const t=a++;r[t]=await e[t]()}}const i=[];for(let r=0;r<Math.min(t,e.length);r++)i.push(o());return await Promise.all(i),r}async function validateFiles(e){return Promise.all(e.map(async e=>{try{await access(e,constants.R_OK);return(await stat(e)).isFile()?{path:e,ok:!0}:{path:e,ok:!1,error:"not a regular file"}}catch(t){const r=t.code;let a;return a="ENOENT"===r?"file not found":"ENOTDIR"===r?"path component is not a directory":"EACCES"===r?"permission denied":t instanceof Error?t.message:String(t),{path:e,ok:!1,error:a}}}))}export async function executeUpload(e,t,r,a,o){const i=parseParams(e);if(!i.ok)return errorResult(i.error);if(!t&&!a)return errorResult("Agent Gateway client unavailable — file upload requires agentGatewayUrl and a key pair");const s=i.paths,n=(await validateFiles(s)).find(e=>!e.ok);if(n)return errorResult(`${n.path}: ${n.error}`);const l=[],c=s.map((e,i)=>async()=>{try{if(a){const t=await a(e,i);return{fileId:t.fileId,downloadUrl:"",fileName:t.name,mimeType:t.mimeType,size:t.size}}return await uploadSingleFile(e,t,r)}catch(t){if(r?.aborted)throw t;const{category:s,detail:n}=classifyUploadFailure(t,Boolean(a));return o?.warn?.(`[beeos_upload_file] upload failed index=${i} native=${Boolean(a)} category=${s} ${n}`),l.push(a?t instanceof NativeOutputFilesError?t.message:"native output Files transport or local read failed":`${e}: ${t instanceof Error?t.message:String(t)}`),null}}),p=(await runWithConcurrency(c,3)).filter(e=>null!==e);if(0===p.length)return errorResult(`All uploads failed: ${l.join("; ")}`);const u=p.map(e=>({uri:`beeos-file://${e.fileId}`,name:e.fileName,mimeType:e.mimeType,fileId:e.fileId})),f=p.length===s.length?`Uploaded ${p.length} file(s): ${u.map(e=>e.name).join(", ")}`:`Uploaded ${p.length}/${s.length} file(s): ${u.map(e=>e.name).join(", ")}. Failed: ${l.join("; ")}`,m={ok:!0,files:u};return{...m,content:[{type:"text",text:f},...u.map(e=>({type:"resource_link",uri:e.uri,name:e.name,mimeType:e.mimeType}))],output:m,result:m,details:m,isError:!1}}async function uploadSingleFile(e,t,r){const a=await uploadLocalFile(e,t,{signal:r,timeoutMs:12e4});return{fileId:a.fileId,downloadUrl:"",fileName:a.name,mimeType:a.mimeType,size:a.size}}function parseParams(e){if(!e||"object"!=typeof e)return{ok:!1,error:"params must be an object"};const t=e;if(Object.keys(t).filter(e=>"paths"!==e).length>0)return{ok:!1,error:"only paths is allowed"};if(!Array.isArray(t.paths))return{ok:!1,error:"paths must be an array"};if(t.paths.length<1)return{ok:!1,error:"paths must contain at least 1 item"};if(t.paths.length>5)return{ok:!1,error:"paths must contain no more than 5 items"};const r=[];for(let e=0;e<t.paths.length;e++){const a=t.paths[e];if("string"!=typeof a||""===a.trim())return{ok:!1,error:`paths[${e}] must be a non-empty string`};const o=a.trim();if(isBeeosFileUri(o))return{ok:!1,error:BEEOS_FILE_URI_UPLOAD_ERROR};r.push(o)}return{ok:!0,paths:r}}function classifyUploadFailure(e,t){const r=e instanceof Error?e.message:String(e),a=e instanceof Error&&e.cause instanceof Error?` cause=${e.cause.message}`:"";if(e instanceof NativeOutputFilesError)return{category:e.category,detail:`${e.detail??""} message=${r}`.trim()};if(e instanceof DOMException&&("AbortError"===e.name||"TimeoutError"===e.name))return{category:"aborted",detail:`name=${e.name} message=${r}`};if(e instanceof TypeError)return{category:"transport_rejected",detail:`message=${r}${a}`};const o=e?.code;return"string"==typeof o?{category:"local_read_failed",detail:`code=${o} message=${r}`}:{category:t?"attempt_or_lease_fenced":"unclassified",detail:`message=${r}${a}`}}function errorResult(e){const t={ok:!1,error:e};return{...t,content:[{type:"text",text:e}],output:t,result:t,details:t,isError:!0}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{cloudRuntimeTargetInstanceId}from"../runtime/runtime-production-authority.js";import{access,constants,readFile,stat}from"node:fs/promises";import{createHash}from"node:crypto";import{basename,extname,resolve}from"node:path";import{
|
|
1
|
+
import{cloudRuntimeTargetInstanceId}from"../runtime/runtime-production-authority.js";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{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,r){if(cloudRuntimeTargetInstanceId(process.env))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 a=basename(e),i=r?.fileNameOverride??a,s=inferMimeType(i),o=await readFile(e);r?.signal?.throwIfAborted();const n=createHash("sha256").update(o).digest("hex"),p=JSON.stringify([t.baseUrl.origin,resolve(e),i,n]),c=Date.now();for(const[e,t]of completedUploads)t.expiresAt<=c&&completedUploads.delete(e);const d=completedUploads.get(p);if(d)return noteUploadedDeliverable(e),{...d.result};const l=AbortSignal.timeout(r?.timeoutMs??3e4),u=r?.signal?AbortSignal.any([r.signal,l]):l,m=await t.files.upload({fileName:i,mimeType:s,data:o,signal:u}),f={fileId:m.fileId,uri:m.uri,name:m.fileName,mimeType:m.mimeType,size:o.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,a,i,s){r.assertAttempt(),await access(e,constants.R_OK);const o=await stat(e);if(!o.isFile()||o.size<=0||o.size>104857600)throw new Error("native output file size invalid");const n=await readFile(e);if(r.assertAttempt(),n.byteLength!==o.size)throw new Error("native output file changed while reading");const p=basename(e),c=inferMimeType(p),d=createHash("sha256").update(n).digest("hex"),l=createHash("sha256").update("beeos/native-output-file/v1\0"+r.operationId+"\0"+r.toolCallId+"\0"+a).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),...i?[i]:[]]),f={requestMessageId:r.requestMessageId,paramsHash:r.paramsHash,activeRunRegistrationId:r.activeRunRegistrationId,idempotencyKey:l},h=e=>!!e&&"object"==typeof e&&!Array.isArray(e),g=async(e,t)=>{r.assertAttempt();const a=r.getLease(),i=await fetch(new URL("/api/v1/internal/runtime/operations/"+encodeURIComponent(r.operationId)+"/output-files/"+e,u),{method:"POST",redirect:"error",signal:m,headers:{authorization:"Bearer "+a.runtimeLeaseCredential,"content-type":"application/json"},body:JSON.stringify({...f,...t})});if(r.assertAttempt(),!i.ok){let t;try{const e=await i.json();h(e)&&h(e.error)&&"string"==typeof e.error.code&&/^[A-Za-z0-9_.:-]{1,128}$/.test(e.error.code)&&(t=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.status}`)}throw new NativeOutputFilesError("native output Files "+e+" failed ("+i.status+(t?","+t:"")+")","control_http_error",`stage=${e} http_status=${i.status} code=${t??"none"}`)}if(i.url&&new URL(i.url).origin!==u.origin)throw new NativeOutputFilesError("native output Files response origin changed","control_response_origin",`stage=${e}`);const s=await i.json();if(r.assertAttempt(),!h(o=s)||o.operationId!==r.operationId||o.requestMessageId!==f.requestMessageId||o.paramsHash!==f.paramsHash||o.activeRunRegistrationId!==f.activeRunRegistrationId)throw new NativeOutputFilesError("native output Files response binding invalid","control_response_binding",`stage=${e}`);var o;return s},v=await g("presign",{filename:p,content_type:c,size_bytes:n.byteLength,checksum_sha256:d}),y=v.upload,w=v.transferPolicy;if(!h(y)||!h(w)||"string"!=typeof w.allowedOrigin||"upload"!==y.direction||"PUT"!==y.http_method||"string"!=typeof y.file_id||!y.file_id||"string"!=typeof y.url||"string"!=typeof y.expires_at||!Number.isFinite(Date.parse(y.expires_at))||Date.parse(y.expires_at)<=Date.now()||y.content_type!==c||y.size_bytes!==n.byteLength||y.checksum_sha256!==d||!h(y.required_headers)||Object.values(y.required_headers).some(e=>"string"!=typeof e))throw new NativeOutputFilesError("native output Files transfer descriptor invalid","transfer_descriptor_invalid",descriptorDefect(y,w,c,n.byteLength,d));const _=new URL(y.url),x=new URL(w.allowedOrigin);if("https:"!==_.protocol||_.username||_.password||_.hash||"https:"!==x.protocol||x.username||x.password||"/"!==x.pathname||x.search||x.hash||x.origin!==w.allowedOrigin||_.origin!==x.origin)throw new NativeOutputFilesError("native output Files transfer origin invalid","transfer_origin_invalid",`target_matches_allowed=${_.origin===x.origin}`);r.assertAttempt();const b=y.required_headers,F=await putRequiredHeaders(_,b,n,m);if(r.assertAttempt(),F<200||F>=300)throw new NativeOutputFilesError("native output Files PUT failed ("+F+")","put_rejected",`http_status=${F} bytes=${n.byteLength} headers=${Object.keys(b).join(",")}`);let I;try{I=await g("confirm",{fileId:y.file_id,checksumSha256:d})}catch(e){if(r.assertAttempt(),m.throwIfAborted(),!(e instanceof TypeError||e instanceof SyntaxError))throw e;I=await g("confirm",{fileId:y.file_id,checksumSha256:d})}if(I.fileId!==y.file_id||I.fileName!==p||I.mimeType!==c||I.size!==n.byteLength)throw new NativeOutputFilesError("native output Files ready metadata mismatch","ready_metadata_mismatch",`fileId=${I.fileId===y.file_id} fileName=${I.fileName===p} mimeType=${I.mimeType===c} size=${I.size===n.byteLength}`);r.assertAttempt();const U={fileId:y.file_id,uri:"beeos-file://"+y.file_id,name:p,mimeType:c,size:n.byteLength};return noteUploadedDeliverable(e),U}function putRequiredHeaders(e,t,r,a){const i=Object.keys(t).find(e=>"content-length"===e.toLowerCase());if(void 0!==i&&t[i]!==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((i,s)=>{const o=e=>{s(e instanceof Error&&"AbortError"===e.name?e:new TypeError("fetch failed",{cause:e}))},n=httpsRequest(e,{method:"PUT",headers:t,signal:a},e=>{e.on("error",o),e.resume(),e.on("end",()=>i(e.statusCode??0))});n.on("error",o),n.end(r)})}function descriptorDefect(e,t,r,a,i){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 o=[["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===a],["checksum_sha256",e.checksum_sha256===i],["required_headers",s(e.required_headers)&&Object.values(e.required_headers).every(e=>"string"==typeof e)]];return`field=${o.find(([,e])=>!e)?.[0]??"none"} bytes=${a}`}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"}}
|
package/openclaw.plugin.json
CHANGED
|
@@ -18,6 +18,15 @@
|
|
|
18
18
|
"beeos_discover_agents",
|
|
19
19
|
"beeos_call_agent",
|
|
20
20
|
"beeos_get_task",
|
|
21
|
+
"beeos_automation_create",
|
|
22
|
+
"beeos_automation_create_webhook",
|
|
23
|
+
"beeos_automation_capabilities",
|
|
24
|
+
"beeos_automation_preflight",
|
|
25
|
+
"beeos_automation_list",
|
|
26
|
+
"beeos_automation_get",
|
|
27
|
+
"beeos_automation_run",
|
|
28
|
+
"beeos_automation_runs",
|
|
29
|
+
"beeos_automation_get_run",
|
|
21
30
|
"cron_toggle",
|
|
22
31
|
"cron_run",
|
|
23
32
|
"cron_delete"
|
|
@@ -71,7 +80,12 @@
|
|
|
71
80
|
"service": {
|
|
72
81
|
"type": "string",
|
|
73
82
|
"description": "Service type for Bridge registration (default: acp)",
|
|
74
|
-
"enum": [
|
|
83
|
+
"enum": [
|
|
84
|
+
"acp",
|
|
85
|
+
"screen",
|
|
86
|
+
"desktop",
|
|
87
|
+
"shell"
|
|
88
|
+
]
|
|
75
89
|
},
|
|
76
90
|
"mode": {
|
|
77
91
|
"type": "string",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "beeos-claw",
|
|
3
|
-
"version": "0.6.63-cloud.
|
|
3
|
+
"version": "0.6.63-cloud.7",
|
|
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>",
|
|
@@ -67,10 +67,10 @@
|
|
|
67
67
|
"dependencies": {
|
|
68
68
|
"@beeos-ai/beeos-types": "4.4.2-cloud.3",
|
|
69
69
|
"@beeos-ai/bridge-client": "^0.1.0",
|
|
70
|
-
"@beeos-ai/cloud-
|
|
70
|
+
"@beeos-ai/cloud-harness-sdk": "1.0.0-cloud.5",
|
|
71
71
|
"@beeos-ai/message-sdk": "2.0.16",
|
|
72
72
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
73
|
-
"adm-zip": "
|
|
73
|
+
"adm-zip": "0.6.1",
|
|
74
74
|
"ws": "^8.18.0"
|
|
75
75
|
},
|
|
76
76
|
"devDependencies": {
|
|
@@ -88,5 +88,5 @@
|
|
|
88
88
|
"fast-uri": ">=3.1.4",
|
|
89
89
|
"brace-expansion": ">=5.0.9"
|
|
90
90
|
},
|
|
91
|
-
"gitHead": "
|
|
91
|
+
"gitHead": "8bcfd4c17bf147782a7e7059326854f3175bda06"
|
|
92
92
|
}
|
package/dist/agent-auth.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import*as crypto from"node:crypto";import*as fs from"node:fs";import*as path from"node:path";export const EMPTY_BODY_SHA256="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";const ED25519_PKCS8_PREFIX=Buffer.from("302e020100300506032b657004220420","hex");function wrapPrivateKey(e){return 32===e.length?Buffer.concat([ED25519_PKCS8_PREFIX,Buffer.from(e)]):Buffer.from(e)}const ED25519_SPKI_PREFIX=Buffer.from("302a300506032b6570032100","hex");function derivePublicKey(e){const r=crypto.createPrivateKey({key:wrapPrivateKey(e),format:"der",type:"pkcs8"}),t=crypto.createPublicKey(r).export({type:"spki",format:"der"});return 44===t.length?new Uint8Array(t.subarray(12)):new Uint8Array(t)}export function loadAgentKeyPair(e){if(!fs.existsSync(e))return generateAgentKeyPair(e);const r=fs.readFileSync(e,"utf-8").trim();try{const e=JSON.parse(r);if(e.publicKey&&e.privateKey)return{publicKey:new Uint8Array(Buffer.from(e.publicKey,"base64")),privateKey:new Uint8Array(Buffer.from(e.privateKey,"base64"))}}catch{}const t=new Uint8Array(Buffer.from(r,"base64"));if(32===t.length)return{publicKey:derivePublicKey(t),privateKey:t};throw new Error(`Invalid key file format at ${e}`)}function generateAgentKeyPair(e){const r=crypto.generateKeyPairSync("ed25519",{publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}}),t=r.publicKey,n=r.privateKey,o=new Uint8Array(44===t.length?t.subarray(12):t),a=new Uint8Array(48===n.length?n.subarray(16):n),i=path.dirname(e);return fs.existsSync(i)||fs.mkdirSync(i,{recursive:!0}),fs.writeFileSync(e,JSON.stringify({publicKey:Buffer.from(o).toString("base64"),privateKey:Buffer.from(a).toString("base64")},null,2),{mode:384}),{publicKey:o,privateKey:a}}export function signAgentMessage(e,r){const t=crypto.createPrivateKey({key:wrapPrivateKey(r),format:"der",type:"pkcs8"});return new Uint8Array(crypto.sign(null,Buffer.from(e),t))}export function bodyHashHex(e){const r=null==e?Buffer.alloc(0):"string"==typeof e?Buffer.from(e,"utf8"):Buffer.from(e);return crypto.createHash("sha256").update(r).digest("hex")}export function agentAuthHeaders(e,r,t,n){const o=Math.floor(Date.now()/1e3).toString(),a=crypto.randomUUID(),i=bodyHashHex(n),f=signAgentMessage(`${e.toUpperCase()}|${r}||${i}|${o}|${a}`,t.privateKey);return{"X-Agent-Public-Key":Buffer.from(t.publicKey).toString("base64"),"X-Agent-Signature":Buffer.from(f).toString("base64"),"X-Agent-Timestamp":o,"X-Agent-Nonce":a}}export function agentBoundAuthHeaders(e,r,t,n){return agentAuthHeaders(e,r,n,t)}export async function agentFetch(e,r,t){const n="string"==typeof e?new URL(e):e,o=t?.method?.toUpperCase()??"GET",a=decodeURIComponent(n.pathname);let i;if(void 0!==t?.body&&null!==t.body){if(!("string"==typeof t.body||t.body instanceof Uint8Array))throw new Error("agent-authenticated request body must be string or Uint8Array for exact signing");i=t.body}const f=agentAuthHeaders(o,a,r,i),s=new Headers(t?.headers);for(const[e,r]of Object.entries(f))s.set(e,r);s.delete("X-Agent-Body-SHA256");const c=await fetch(n,{...t,method:o,headers:s,redirect:"error"});return assertFixedOrigin(n,c),c}export async function agentBoundFetch(e,r,t){if(""!==("string"==typeof e?new URL(e):e).search)throw new Error("body-bound agent authority routes forbid query parameters");return agentFetch(e,r,t)}function assertFixedOrigin(e,r){if(r.url&&new URL(r.url).origin!==e.origin)throw new Error("agent-authenticated response origin changed")}
|
package/dist/bridge-discovery.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export async function discoverBridgeFromGW(o,n,r){try{const i=r?`?region=${encodeURIComponent(r)}`:"",e=await n(`${o}/api/v1/bridge/config${i}`,{method:"GET"});if(e.ok){const o=await e.json();if(o.url)return{url:o.url,region:o.region}}}catch{}}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{canonicalizeJcs}from"@beeos-ai/beeos-types/runtime";const GRANT_ISSUER="beeos-gateway",BOUNDARY_ISSUER="message-service";export class AgentGatewayRuntimeAttemptAuthorizationClient{options;constructor(e){this.options=e}async authorize(e){if(!sameLeaseFence(e.lease,e.fence)||e.request.payload.instanceId!==e.lease.instanceId)return{status:"fenced"};const t="start",n=JSON.stringify({executionGrantRef:e.request.payload.executionGrantRef,operationId:e.request.operationId,requestMessageId:e.request.messageId,method:e.request.payload.request.method,paramsHash:e.request.payload.paramsHash,runtimeLeaseCredential:e.lease.runtimeLeaseCredential,fence:e.fence,journalAttestationHash:e.journal.journalAttestationHash,journalRevisionBeforeAttempt:e.journal.journalRevisionBeforeAttempt,preparedEntryHash:e.journal.preparedEntryHash,executionMode:t}),a=await this.options.boundAgentFetch(new URL(this.options.authorizationUrl),{method:"POST",headers:{"content-type":"application/json"},body:n});if(401===a.status||403===a.status)return{status:"fenced"};if(!a.ok)throw new Error(`Agent Gateway runtime authorization failed (${a.status})`);const o=await a.json();if(isTerminalAuthorization(o))return{status:o.status};if(!isAuthorizedResponse(o))return{status:"invalid"};if(o.operationId!==e.request.operationId||o.requestMessageId!==e.request.messageId||o.method!==e.request.payload.request.method||o.paramsHash!==e.request.payload.paramsHash||canonicalizeJcs(o.command)!==canonicalizeJcs(e.request.payload.command))return{status:"invalid"};await this.options.verifier.refresh();let i=this.options.verifier.verifyAndDecodeGrant(o.runtimeExecutionGrant),r=this.options.verifier.verifyAndDecodeBoundary(o.executionBoundaryAssertion);if(i&&r||(await this.options.verifier.refresh(!0),i=this.options.verifier.verifyAndDecodeGrant(o.runtimeExecutionGrant),r=this.options.verifier.verifyAndDecodeBoundary(o.executionBoundaryAssertion)),!i||!r||o.executionBoundaryId!==r.claims.executionBoundaryId||o.executionBoundaryId!==r.claims.jti)return{status:"invalid"};const s=invocationContext(e.request,e.fence,i.claims,t,this.options.messageServicePublisherIdentityId??BOUNDARY_ISSUER,Math.floor((this.options.now??Date.now)()/1e3));if(!s)return{status:"invalid"};const d={grant:{header:i.header,claims:i.claims,grantJwt:o.runtimeExecutionGrant},boundary:{header:r.header,claims:r.claims,assertionJwt:o.executionBoundaryAssertion}};return{status:"authorized",attempt:{command:o.command,validationContext:s,authorization:d,derivationContext:{invocation:s,boundaryIssuer:BOUNDARY_ISSUER,boundarySubject:e.request.payload.instanceId,nowEpochSeconds:s.nowEpochSeconds,localJournalRevision:e.journal.journalRevisionBeforeAttempt,localPreparedEntryHash:e.journal.preparedEntryHash},executionBoundaryId:o.executionBoundaryId,boundaryAssertionHash:r.compactHash,executionMode:t}}}}function invocationContext(e,t,n,a,o,i){const r=e.payload.command,s={operationId:e.operationId,requestMessageId:e.messageId,dispatchEpoch:r.context.dispatchEpoch,activeRuntimeEpoch:t.runtimeEpoch,requestId:e.payload.request.id,method:e.payload.request.method,gatewayPublisherIdentityId:e.publisherIdentityId,messageServicePublisherIdentityId:o,runtimePublisherIdentityId:t.handlerIdentity,requestHash:e.payload.requestHash,paramsHash:e.payload.paramsHash,commandHash:e.payload.commandHash,idempotencyKeyHash:e.payload.idempotencyKeyHash,idempotencyFingerprint:e.payload.idempotencyFingerprint,callerIntentHash:e.payload.callerIntentHash,callerUserId:e.payload.callerUserId,callerIdentityId:e.payload.callerIdentityId,instanceId:e.payload.instanceId,runtimeInstanceUid:r.context.runtimeInstanceUid,executionGrantRef:e.payload.executionGrantRef,executionGrantHash:e.payload.executionGrantHash,claimDeadlineAt:e.payload.claimDeadlineAt,executionDeadlineAt:e.payload.executionDeadlineAt,grantIssuer:GRANT_ISSUER,grantSubject:t.handlerIdentity,grantJti:`${t.claimId}:${a}`,grantStartDeadline:Math.floor(Date.parse(e.payload.claimDeadlineAt)/1e3),grantExecutionMode:a,nowEpochSeconds:i,activeFence:t};return Number.isSafeInteger(s.grantStartDeadline)?"instance"===n.scope?{...s,scope:"instance",...void 0===n.runtimeAgentUid?{}:{runtimeAgentUid:n.runtimeAgentUid}}:"agent"===n.scope&&"agent"===r.context.scope&&n.platformAgentId&&n.runtimeAgentUid?{...s,scope:"agent",platformAgentId:n.platformAgentId,runtimeAgentUid:n.runtimeAgentUid,runtimeLocalKey:r.context.agent.runtimeLocalKey}:"conversation"===n.scope&&"conversation"===r.context.scope&&n.platformAgentId&&n.runtimeAgentUid&&n.platformConversationId&&n.runtimeConversationUid&&n.runtimeSessionKey?{...s,scope:"conversation",platformAgentId:n.platformAgentId,runtimeAgentUid:n.runtimeAgentUid,platformConversationId:n.platformConversationId,runtimeConversationUid:n.runtimeConversationUid,runtimeSessionKey:n.runtimeSessionKey}:null:null}function sameLeaseFence(e,t){return e.runtimeEpoch===t.runtimeEpoch&&e.handlerIdentity===t.handlerIdentity}function isTerminalAuthorization(e){return isRecord(e)&&1===Object.keys(e).length&&("expired"===e.status||"terminal"===e.status)}function isAuthorizedResponse(e){if(!isRecord(e))return!1;const t=Object.keys(e).sort(),n=["authorizedAt","command","disposition","executionBoundaryAssertion","executionBoundaryId","expiresAt","method","operationId","paramsHash","requestMessageId","runtimeExecutionGrant","status"].sort();return t.length===n.length&&t.every((e,t)=>e===n[t])&&"authorized"===e.status&&("created"===e.disposition||"reused"===e.disposition)&&[e.operationId,e.requestMessageId,e.method,e.paramsHash,e.runtimeExecutionGrant,e.executionBoundaryAssertion,e.executionBoundaryId,e.authorizedAt,e.expiresAt].every(e=>"string"==typeof e&&e.length>0)&&isRecord(e.command)&&Number.isFinite(Date.parse(e.authorizedAt))&&Number.isFinite(Date.parse(e.expiresAt))}function isRecord(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{RUNTIME_ERROR_DESCRIPTORS,RUNTIME_HASH_DOMAINS,runtimeHashPreimage}from"@beeos-ai/beeos-types/runtime";import{MessageServiceRuntimeClaimHttpAuthority}from"./message-service-runtime-claim-authority.js";const QUERY_METHODS=new Set(["skills/list","models/list","cron/list","cron/status","cron/runs","mcp/list"]),PROJECTION_METHODS=new Set(["agent/create","agent/update","agent/delete","agent/applyTemplate","session/set_model"]);export class MessageServiceRuntimeInvocationHttpAuthority{deps;constructor(e){this.deps=e}claimNext=e=>this.claimAuthority().claimNext(e);claimExact=e=>this.claimAuthority().claimExact(e);renewClaim=e=>this.claimAuthority().renewClaim(e);releaseClaim=e=>this.claimAuthority().releaseClaim(e);authorize=e=>this.deps.authorization.authorize(e);async appendStarted(e){await this.append(e,"runtime_operation_started",{claimedAt:this.now(),leaseExpiresAt:e.claimLeaseExpiresAt,executionMode:e.attempt.executionMode,executionBoundaryId:e.attempt.executionBoundaryId,boundaryAssertionHash:e.attempt.boundaryAssertionHash,...e.attempt.handoffId?{handoffId:e.attempt.handoffId}:{}})}async appendProgress(e){await this.append(e,"runtime_operation_progress",{executionBoundaryId:e.attempt.executionBoundaryId,phase:e.progress.phase,...void 0===e.progress.current?{}:{current:e.progress.current},...void 0===e.progress.total?{}:{total:e.progress.total}})}async commitResult(e){const t=e.request.payload.request.method;if(PROJECTION_METHODS.has(t))throw new Error(`projection-required runtime method is not enabled by this authority: ${t}`);const o=this.now(),a=e.result,s=hash(RUNTIME_HASH_DOMAINS.serviceResult,{method:t,result:a});let r;if(!QUERY_METHODS.has(t)){const s=hash(RUNTIME_HASH_DOMAINS.coreResult,{method:t,result:a}),n={schemaVersion:1,operationId:e.operationId,method:t,coreResultRef:`sha256:${s}`,coreResultHash:s},i={schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,method:t,commandHash:e.request.payload.commandHash,executionBoundaryId:e.attempt.executionBoundaryId,boundaryAssertionHash:e.attempt.boundaryAssertionHash,fence:e.fence,journalRevision:"3",coreResultHash:s,effectRecordHash:hash(RUNTIME_HASH_DOMAINS.effectRecord,n),projection:{state:"not_required"},committedAt:o};r=hash(RUNTIME_HASH_DOMAINS.effectReceipt,i),await this.append(e,"runtime_effect_committed",{executionBoundaryId:e.attempt.executionBoundaryId,committedAt:o,effectReceipt:i,effectReceiptHash:r})}const n={schemaVersion:1,operationId:e.operationId,method:t,outcome:"succeeded",serviceResultRef:`sha256:${s}`,serviceResultHash:s},i={schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,method:t,commandHash:e.request.payload.commandHash,executionBoundaryId:e.attempt.executionBoundaryId,boundaryAssertionHash:e.attempt.boundaryAssertionHash,fence:e.fence,journalRevision:"3",terminalRecordHash:hash(RUNTIME_HASH_DOMAINS.terminalRecord,n),completedAt:o,outcome:"succeeded",serviceResultHash:s,...r?{effectReceiptHash:r}:{}};await this.appendTerminal(e,i,{outcome:"succeeded",response:{jsonrpc:"2.0",id:e.request.payload.request.id,result:a},serviceResultHash:s,terminalAuthority:r?{kind:"effect_receipt",effectReceiptHash:r}:{kind:"query_execution",executionBoundaryId:e.attempt.executionBoundaryId,boundaryAssertionHash:e.attempt.boundaryAssertionHash},completedAt:o})}async commitFailure(e){const t=e.request.payload.request.method,o=this.now(),a=normalizeErrorCode(e.outcome,e.code),s=RUNTIME_ERROR_DESCRIPTORS[a],r="outcome_unknown"===e.outcome?"outcome_unknown":"cancelled"===e.outcome?"cancelled":"expired"===e.outcome?"expired":"failed",n={code:s.jsonRpcCode,message:a,data:{code:a,operationId:e.operationId,effectState:r,retryMode:s.retryMode}},i=hash(RUNTIME_HASH_DOMAINS.terminalRecord,{operationId:e.operationId,method:t,outcome:e.outcome,code:a}),c="outcome_unknown"===e.outcome?{schemaVersion:1,operationId:e.operationId,method:t,outcome:e.outcome,uncertaintyRef:`sha256:${i}`,uncertaintyHash:i}:{schemaVersion:1,operationId:e.operationId,method:t,outcome:e.outcome,errorRef:`sha256:${i}`,errorHash:i},d={schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,method:t,commandHash:e.request.payload.commandHash,executionBoundaryId:e.attempt.executionBoundaryId,boundaryAssertionHash:e.attempt.boundaryAssertionHash,fence:e.fence,journalRevision:"2",terminalRecordHash:hash(RUNTIME_HASH_DOMAINS.terminalRecord,c),completedAt:o},u="outcome_unknown"===e.outcome?{...d,outcome:"outcome_unknown",uncertaintyHash:i}:{...d,outcome:e.outcome,noEffect:!0,errorHash:i},m={jsonrpc:"2.0",id:e.request.payload.request.id,error:n},p=terminalFailurePayload(e.outcome,o,m,e.attempt.executionBoundaryId,e.attempt.boundaryAssertionHash);await this.appendTerminal(e,u,p)}claimAuthority(){return new MessageServiceRuntimeClaimHttpAuthority({messageServiceUrl:this.deps.messageServiceUrl,fetchAuthorized:(e,t)=>this.deps.fetchMessageService(e,t)})}async append(e,t,o){await this.post(e.operationId,{schemaVersion:1,type:t,operationId:e.operationId,conversationId:e.operationId,requestMessageId:e.requestMessageId,dispatchEpoch:e.request.payload.command.context.dispatchEpoch,fence:e.fence,payload:o})}async appendTerminal(e,t,o){await this.post(e.operationId,{schemaVersion:1,type:"runtime_rpc_response",operationId:e.operationId,conversationId:e.operationId,requestMessageId:e.requestMessageId,dispatchEpoch:e.request.payload.command.context.dispatchEpoch,fence:e.fence,payload:o,replyTo:e.requestMessageId,terminalReceipt:t,terminalReceiptHash:hash(RUNTIME_HASH_DOMAINS.terminalReceipt,t)})}async post(e,t){const o=await this.deps.fetchMessageService(new URL(`/api/v1/runtime/operations/${encodeURIComponent(e)}/events`,this.deps.messageServiceUrl),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(201!==o.status)throw new Error(`Message Service runtime event append failed (${o.status})`)}now(){return(this.deps.now??(()=>new Date))().toISOString()}}function hash(e,t){return createHash("sha256").update(runtimeHashPreimage(e,t)).digest("hex")}function normalizeErrorCode(e,t){return"outcome_unknown"===e?"OUTCOME_UNKNOWN":"cancelled"===e?"OPERATION_CANCELLED":"expired"===e?"COMMAND_EXPIRED":t in RUNTIME_ERROR_DESCRIPTORS?t:"RUNTIME_EXECUTION_FAILED"}function terminalFailurePayload(e,t,o,a,s){if("outcome_unknown"===e)return{outcome:e,response:o,terminalAuthority:{kind:"uncertain_effect",executionBoundaryId:a,boundaryAssertionHash:s},completedAt:t};const r={kind:"definitive_no_effect",journalPhase:"prepared",observedAt:t};return"cancelled"===e?{outcome:e,response:o,cancellationEvidence:r,completedAt:t}:"expired"===e?{outcome:e,response:o,expirationEvidence:r,completedAt:t}:{outcome:e,response:o,failureEvidence:r,completedAt:t}}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createHash,createPublicKey,verify}from"node:crypto";import{validateRuntimeExecutionGrant}from"@beeos-ai/beeos-types/runtime";export class RuntimeJwksVerifier{jwksUrl;fetcher;ttlMs;now;keys=new Map;expiresAt=0;inflight;provenance;keyMaterials=Object.freeze([]);keysetUrl;constructor(e,t=fetch,r=3e5,s=Date.now){this.jwksUrl=e,this.fetcher=t,this.ttlMs=r,this.now=s,this.keysetUrl=new URL(e).toString()}async refresh(e=!1){if(!(!e&&this.keys.size>0&&this.now()<this.expiresAt)){if(this.inflight)return await this.inflight;this.inflight=this.load();try{await this.inflight}finally{this.inflight=void 0}}}hasKid(e){return this.keys.has(e)}trustedKids(){return Object.freeze([...this.keys.keys()].sort())}trustedKeyMaterials(){return this.keyMaterials}documentProvenance(){return this.provenance}verifyAndDecodeGrant(e){const t=this.verifyCompact(e);return t?{header:t.header,claims:t.claims,compactHash:sha256(e)}:null}verifyAndValidateGrant(e,t){const r=this.verifyAndDecodeGrant(e);return r&&0===validateRuntimeExecutionGrant(r.claims,t).length?r:null}verifyAndDecodeBoundary(e){const t=this.verifyCompact(e);return t?{header:t.header,claims:t.claims,compactHash:sha256(e)}:null}async load(){const e=await this.fetcher(this.jwksUrl,{signal:AbortSignal.timeout(1e4),redirect:"error"});if(!e.ok)throw new Error(`JWKS fetch failed: HTTP ${e.status}`);const t=await e.json(),r=new Map,s=[];for(const e of t.keys??[]){if("RSA"!==e.kty||"sig"!==e.use||"RS256"!==e.alg||"string"!=typeof e.kid||!e.kid)continue;if(r.has(e.kid))throw new Error(`JWKS contains duplicate kid: ${e.kid}`);const t=createPublicKey({key:e,format:"jwk"});if((t.asymmetricKeyDetails?.modulusLength??0)<2048)continue;const i=t.export({format:"jwk"});"RSA"===i.kty&&"string"==typeof i.n&&"string"==typeof i.e&&(r.set(e.kid,t),s.push(Object.freeze({jwkThumbprint:sha256(JSON.stringify({e:i.e,kty:"RSA",n:i.n})),spkiSha256:createHash("sha256").update(t.export({format:"der",type:"spki"})).digest("hex")})))}if(0===r.size)throw new Error("JWKS contains no trusted RS256 keys");const i=e.url?new URL(e.url).toString():this.keysetUrl;if(i!==this.keysetUrl)throw new Error("JWKS response provenance URL mismatch");this.keys=r,this.keyMaterials=Object.freeze(s.sort((e,t)=>e.jwkThumbprint.localeCompare(t.jwkThumbprint)||e.spkiSha256.localeCompare(t.spkiSha256))),this.provenance=Object.freeze({sourceUrl:i,etag:e.headers.get("etag")??"",issuer:"string"==typeof t.issuer?t.issuer:"",audience:"string"==typeof t.audience?t.audience:"",purpose:"string"==typeof t.purpose?t.purpose:"",maxClaimTtlSeconds:"number"==typeof t.maxClaimTtlSeconds?t.maxClaimTtlSeconds:Number.NaN}),this.expiresAt=this.now()+this.ttlMs}verifyCompact(e){const t=e.split(".");if(3!==t.length)return null;try{if(!t.every(isCanonicalBase64Url))return null;const e=JSON.parse(decodeBase64Url(t[0]));if("RS256"!==e.alg||"JWT"!==e.typ||"string"!=typeof e.kid)return null;const r=this.keys.get(e.kid);if(!r)return null;const s=Buffer.from(`${t[0]}.${t[1]}`),i=Buffer.from(t[2],"base64url");if(!verify("RSA-SHA256",s,r,i))return null;const n=JSON.parse(decodeBase64Url(t[1]));return null===n||"object"!=typeof n||Array.isArray(n)?null:{header:e,claims:n}}catch{return null}}}function isCanonicalBase64Url(e){if(!e||!/^[A-Za-z0-9_-]+$/.test(e))return!1;return Buffer.from(e,"base64url").toString("base64url")===e}function decodeBase64Url(e){return Buffer.from(e,"base64url").toString("utf8")}function sha256(e){return createHash("sha256").update(e).digest("hex")}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createHash,randomBytes,sign}from"node:crypto";import{RUNTIME_INTERNAL_API_V1_ROUTE_CONTRACTS,RUNTIME_HASH_DOMAINS,RUNTIME_RPC_PROTOCOL_VERSION,runtimeHashPreimage,runtimeIdentitySignatureMessage,validateRuntimeInternalRegistrationResult}from"@beeos-ai/beeos-types/runtime";import{RuntimeTransportFailurePolicy}from"./runtime-transport-failure-policy.js";export class RuntimeRegistrationLeaseExpiredError extends Error{constructor(){super("Instance authority returned an expired active lease"),this.name="RuntimeRegistrationLeaseExpiredError"}}export class RuntimeRegistrationHandoffRequiredError extends Error{retryAfterMs;constructor(e=65e3){super("Instance authority requires waiting for the active runtime lease to expire"),this.name="RuntimeRegistrationHandoffRequiredError",this.retryAfterMs=e}}export class RuntimeRegistrationOwnerResetRequiredError extends Error{constructor(){super("Instance authority requires owner reset authorization after a journal store change"),this.name="RuntimeRegistrationOwnerResetRequiredError"}}export class RuntimeRegistrationJournalAdvanceRequiredError extends Error{currentJournalGeneration;expectedJournalGeneration;constructor(e){super("Instance authority requires journal generation to advance exactly once after lease expiry"),this.name="RuntimeRegistrationJournalAdvanceRequiredError",this.currentJournalGeneration=e?.currentJournalGeneration,this.expectedJournalGeneration=e?.expectedJournalGeneration}}export class RuntimeRegistrationCoordinator{transport;config;onLeaseLost;now;active=null;timer;expiryTimer;stopped=!1;generation=0;heartbeatTransportFailurePolicy=new RuntimeTransportFailurePolicy;authorityListeners=new Set;constructor(e,t,i,r=Date.now){this.transport=e,this.config=t,this.onLeaseLost=i,this.now=r}get lease(){return!this.active||Date.parse(this.active.leaseExpiresAt)<=this.now()?null:this.active}get canClaimMutations(){return null!==this.lease}get authorityLease(){const e=this.lease;return e?Object.freeze({...e,handlerIdentity:this.config.handlerIdentity}):null}subscribeAuthority(e){return this.authorityListeners.add(e),()=>{this.authorityListeners.delete(e)}}async start(){const e=++this.generation;return this.stopped=!1,await this.registerOnce(e)}async registerOnce(e){if(!this.isCurrent(e))return null;this.timer=void 0,this.active&&(this.clearLeaseExpiry(),this.active=null,this.notifyAuthority());const t={registrationId:this.config.registrationId,handlerIdentity:this.config.handlerIdentity,contractRevision:this.config.contractRevision,runtimeRpcProtocolVersion:RUNTIME_RPC_PROTOCOL_VERSION,runtimeMethods:this.config.runtimeMethods,capabilities:this.config.capabilities,manifestDigest:this.config.manifestDigest,journalStoreId:this.config.journalStoreId,journalGeneration:this.config.journalGeneration};let i;try{i=await this.transport.register(this.signProof("runtime.register",t))}catch(t){if(!this.isCurrent(e))return null;if(t instanceof RuntimeRegistrationLeaseExpiredError||t instanceof RuntimeRegistrationJournalAdvanceRequiredError||t instanceof RuntimeRegistrationOwnerResetRequiredError)return this.onLeaseLost(t instanceof RuntimeRegistrationLeaseExpiredError?"expired":"heartbeat_failed",t),null;this.onLeaseLost("heartbeat_failed",t);const i=t instanceof RuntimeRegistrationHandoffRequiredError?t.retryAfterMs:5e3;return this.scheduleRegistration(i,e),null}return this.isCurrent(e)?"active"!==i.status?("fenced"===i.status?this.onLeaseLost("fenced"):this.scheduleRegistration(i.retryAfterMs,e),null):void 0!==this.config.targetInstanceId&&i.instanceId!==this.config.targetInstanceId?(this.onLeaseLost("fenced",new Error("Instance authority returned a different Cloud instance")),null):(this.active={instanceId:i.instanceId,leaseId:i.leaseId,runtimeEpoch:i.runtimeEpoch,runtimeLeaseCredential:i.runtimeLeaseCredential,leaseExpiresAt:i.leaseExpiresAt},this.heartbeatTransportFailurePolicy.recordSuccess(),this.notifyAuthority(),this.scheduleLeaseExpiry(this.active,e),this.schedule(i.heartbeatIntervalMs,e),this.active):null}stop(){this.generation++,this.stopped=!0,this.timer&&clearTimeout(this.timer),this.expiryTimer&&clearTimeout(this.expiryTimer),this.timer=void 0,this.expiryTimer=void 0,this.active=null,this.notifyAuthority()}schedule(e,t){if(!this.isCurrent(t))return;const i=this.active;i&&(this.timer=setTimeout(()=>{this.sendHeartbeat(e,t,i)},e),this.timer.unref?.())}scheduleRegistration(e,t){this.isCurrent(t)&&(this.timer=setTimeout(()=>{this.registerOnce(t)},e))}async sendHeartbeat(e,t,i){if(!this.isCurrentLease(t,i))return;const r={leaseId:i.leaseId,handlerIdentity:this.config.handlerIdentity,runtimeEpoch:i.runtimeEpoch},s=this.config.getMSConnectionStatus?{...r,msConnectionStatus:this.config.getMSConnectionStatus(i)}:r;try{const r=await this.transport.heartbeat(this.signProof("runtime.heartbeat",s));if(!this.isCurrentLease(t,i))return;if("renewed"!==r.status)return this.heartbeatTransportFailurePolicy.recordSuccess(),this.active=null,this.clearLeaseExpiry(),this.notifyAuthority(),void this.onLeaseLost(r.status);this.heartbeatTransportFailurePolicy.recordSuccess(),this.active={...i,runtimeLeaseCredential:r.runtimeLeaseCredential,leaseExpiresAt:r.leaseExpiresAt},this.notifyAuthority(),this.scheduleLeaseExpiry(this.active,t),this.schedule(e,t)}catch(r){if(!this.isCurrentLease(t,i))return;if(!this.heartbeatTransportFailurePolicy.recordFailure())return void this.schedule(Math.min(e,5e3),t);this.active=null,this.clearLeaseExpiry(),this.notifyAuthority(),this.onLeaseLost("heartbeat_failed",r),this.scheduleRegistration(5e3,t)}}scheduleLeaseExpiry(e,t){this.clearLeaseExpiry();const i=`${e.leaseId}\0${e.runtimeEpoch}\0${e.leaseExpiresAt}`,r=()=>{const s=Date.parse(e.leaseExpiresAt)-this.now();if(s>0)return this.expiryTimer=setTimeout(r,Math.min(2147483647,s)),void this.expiryTimer.unref?.();const n=this.active;this.isCurrentLease(t,e)&&n&&`${n.leaseId}\0${n.runtimeEpoch}\0${n.leaseExpiresAt}`===i&&(this.active=null,this.expiryTimer=void 0,this.notifyAuthority(),this.onLeaseLost("expired"))};r()}clearLeaseExpiry(){this.expiryTimer&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0}isCurrent(e){return!this.stopped&&e===this.generation}isCurrentLease(e,t){return this.isCurrent(e)&&this.active===t}notifyAuthority(){const e=this.authorityLease;for(const t of this.authorityListeners)try{t(e)}catch{}}signProof(e,t){const i=new Date(this.now()).toISOString(),r=randomBytes(18).toString("base64url"),s="runtime.register"===e?RUNTIME_HASH_DOMAINS.registration:RUNTIME_HASH_DOMAINS.heartbeat,n=createHash("sha256").update(runtimeHashPreimage(s,t)).digest("hex"),a=runtimeIdentitySignatureMessage({purpose:e,instanceIdentityKeyId:this.config.instanceIdentityKeyId,targetInstanceId:this.config.targetInstanceId,signedAt:i,nonce:r,payloadHash:n});return{...t,signaturePurpose:e,instanceIdentityKeyId:this.config.instanceIdentityKeyId,signedAt:i,nonce:r,payloadHash:n,...void 0===this.config.targetInstanceId?{}:{targetInstanceId:this.config.targetInstanceId},signature:sign(null,a,this.config.privateKey).toString("base64url")}}}export class InstanceAuthorityRuntimeRegistrationTransport{options;constructor(e){this.options=e}async register(e){if(e.registrationId!==this.options.registrationId)throw new Error("runtime registration id mismatch");const t=await this.post(RUNTIME_INTERNAL_API_V1_ROUTE_CONTRACTS.runtimeRegister.path,e);if("active"===t.status&&Number.isFinite(Date.parse(t.leaseExpiresAt))&&Date.parse(t.leaseExpiresAt)<=Date.now())throw new RuntimeRegistrationLeaseExpiredError;if(validateRuntimeInternalRegistrationResult(t)||"fenced"!==t.status&&(t.journalStoreId!==e.journalStoreId||t.journalGeneration!==e.journalGeneration)||"active"===t.status&&(!t.instanceId||!t.leaseId||!t.runtimeLeaseCredential||!Number.isInteger(t.heartbeatIntervalMs)||!Number.isFinite(Date.parse(t.leaseExpiresAt))||Date.parse(t.leaseExpiresAt)<=Date.now()))throw new Error("Instance authority returned an invalid registration binding");return t}async heartbeat(e){const t=await this.post(RUNTIME_INTERNAL_API_V1_ROUTE_CONTRACTS.runtimeHeartbeat.path.replace("{registrationId}",encodeURIComponent(this.options.registrationId)),e);if(!(t&&["renewed","fenced","expired"].includes(t.status)&&("renewed"!==t.status||t.runtimeLeaseCredential&&Number.isFinite(Date.parse(t.leaseExpiresAt)))))throw new Error("Instance authority returned an invalid heartbeat result");return t}async post(e,t){const i=new URL(e,this.options.agentGatewayUrl),r=await this.options.agentFetch(i,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const e=await r.text().catch(()=>"");if(409===r.status&&i.pathname.endsWith("/runtime/registrations"))throw classifyRuntimeRegistrationConflict(e);throw new Error(`runtime Instance authority request failed (${r.status} ${r.statusText}) ${i.pathname}`+(e?`: ${e.slice(0,240)}`:""))}return await r.json()}}export function classifyRuntimeRegistrationConflict(e){const t=extractConflictMessage(e);if(/journal store change requires owner reset authorization/i.test(t))return new RuntimeRegistrationOwnerResetRequiredError;if(/journal generation must advance exactly once/i.test(t)){const e=t.match(/\bcurrent=(\d+)\b/i)?.[1],i=t.match(/\bexpected=(\d+)\b/i)?.[1];return new RuntimeRegistrationJournalAdvanceRequiredError({currentJournalGeneration:e&&/^[1-9][0-9]*$/.test(e)?e:void 0,expectedJournalGeneration:i&&/^[1-9][0-9]*$/.test(i)?i:void 0})}return/active runtime lease requires explicit handoff/i.test(t)||/waiting for the active runtime lease/i.test(t),new RuntimeRegistrationHandoffRequiredError}function extractConflictMessage(e){if(!e)return"";try{const t=JSON.parse(e),i=t.error?.message;if("string"==typeof i)return i;if("string"==typeof t.message)return t.message}catch{}return e}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export class RuntimeTransportFailurePolicy{threshold;consecutiveFailures=0;constructor(e=3){if(this.threshold=e,!Number.isSafeInteger(e)||e<=0)throw new Error("transport failure threshold must be a positive integer")}recordSuccess(){this.consecutiveFailures=0}recordFailure(){return this.consecutiveFailures+=1,!(this.consecutiveFailures<this.threshold)&&(this.consecutiveFailures=0,!0)}}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{CLOUD_RUNTIME_EXECUTION_GRANT_DOMAIN}from"@beeos-ai/beeos-types/runtime";const GATEWAY_GRANT_PROVENANCE=Object.freeze({issuer:"beeos-gateway",audience:"beeos-runtime-command",purpose:"runtime-execution-grant",maxClaimTtlSeconds:60}),CLOUD_GRANT_PROVENANCE=Object.freeze({issuer:CLOUD_RUNTIME_EXECUTION_GRANT_DOMAIN.issuer,audience:CLOUD_RUNTIME_EXECUTION_GRANT_DOMAIN.audience,purpose:CLOUD_RUNTIME_EXECUTION_GRANT_DOMAIN.purpose,maxClaimTtlSeconds:60}),MESSAGE_BOUNDARY_PROVENANCE=Object.freeze({issuer:"message-service",audience:"beeos-runtime-execution-boundary",purpose:"runtime-execution-boundary",maxClaimTtlSeconds:60});export class GatewayGrantJwksVerifier{verifier;purpose="gateway-runtime-grant";keysetProvenance;constructor(e){this.verifier=e,this.keysetProvenance=e.keysetUrl}async refresh(e=!1){await this.verifier.refresh(e),assertResponseProvenance(this.verifier,GATEWAY_GRANT_PROVENANCE)}trustedKeyMaterials(){return this.verifier.trustedKeyMaterials()}responseProvenance(){return this.verifier.documentProvenance()}verifyAndDecodeGrant(e){const r=this.verifier.verifyAndDecodeGrant(e);return"beeos-gateway"===r?.claims.iss&&"beeos-runtime-command"===r.claims.aud&&"runtime-execution-grant"===r.claims.purpose?r:null}}export class CloudGatewayGrantJwksVerifier{verifier;keysetProvenance;constructor(e){this.verifier=e,this.keysetProvenance=e.keysetUrl}async refresh(e=!1){await this.verifier.refresh(e),assertResponseProvenance(this.verifier,CLOUD_GRANT_PROVENANCE)}verifyAndDecodeGrant(e){const r=this.verifier.verifyAndDecodeGrant(e),s=r?.claims;return s?.iss===CLOUD_RUNTIME_EXECUTION_GRANT_DOMAIN.issuer&&s.aud===CLOUD_RUNTIME_EXECUTION_GRANT_DOMAIN.audience&&s.purpose===CLOUD_RUNTIME_EXECUTION_GRANT_DOMAIN.purpose?r:null}}export class MessageServiceBoundaryJwksVerifier{verifier;purpose="message-service-execution-boundary";keysetProvenance;constructor(e){this.verifier=e,this.keysetProvenance=e.keysetUrl}async refresh(e=!1){await this.verifier.refresh(e),assertResponseProvenance(this.verifier,MESSAGE_BOUNDARY_PROVENANCE)}trustedKeyMaterials(){return this.verifier.trustedKeyMaterials()}responseProvenance(){return this.verifier.documentProvenance()}verifyAndDecodeBoundary(e){const r=this.verifier.verifyAndDecodeBoundary(e);return"message-service"===r?.claims.iss&&"beeos-runtime-execution-boundary"===r.claims.aud?r:null}}export class SplitIssuerRuntimeAuthorizationVerifier{grant;boundary;constructor(e,r){if(this.grant=e,this.boundary=r,e.keysetProvenance===r.keysetProvenance)throw new Error("grant and boundary JWKS keysets require distinct provenance")}async refresh(e=!1){await Promise.all([this.grant.refresh(e),this.boundary.refresh(e)]);const r=this.grant.responseProvenance(),s=this.boundary.responseProvenance();if(!r||!s||r.sourceUrl===s.sourceUrl||r.etag===s.etag)throw new Error("grant and boundary JWKS responses require distinct provenance");const n=new Set(this.boundary.trustedKeyMaterials().flatMap(e=>[e.jwkThumbprint,e.spkiSha256]));if(this.grant.trustedKeyMaterials().some(e=>n.has(e.jwkThumbprint)||n.has(e.spkiSha256)))throw new Error("grant and boundary JWKS keysets reuse public-key material")}verifyAndDecodeGrant(e){return this.grant.verifyAndDecodeGrant(e)}verifyAndDecodeBoundary(e){return this.boundary.verifyAndDecodeBoundary(e)}}function assertResponseProvenance(e,r){const s=e.documentProvenance();if(!s||!s.etag||s.sourceUrl!==e.keysetUrl||s.issuer!==r.issuer||s.audience!==r.audience||s.purpose!==r.purpose||s.maxClaimTtlSeconds!==r.maxClaimTtlSeconds)throw new Error(`JWKS response provenance mismatch for ${r.purpose}`)}
|