beeos-claw 0.6.91 → 0.6.92

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- const DELTA_UNITS=4096;export function createCentralNativeDeltaStream(t,e,n){let a,i=-1,s="",l=[];const r=e=>{const n=l.at(-1);n&&n.output_index===i?n.delta+=e:l.push({item_id:`${t.responseId}:message:${i}`,output_index:i,content_index:0,delta:e})};return{partial(o){if("string"==typeof o&&0!==o.length){if(i>=0&&o.startsWith(s)){if(o.length===s.length)return;r(o.slice(s.length))}else{if(i>=0&&s.startsWith(o))return;i+=1,r(o)}s=o,a??=(async()=>{for(;l.length;){const a=l.shift();for(let i=0;i<a.delta.length;i+=4096)try{await e(t,{...a,delta:a.delta.slice(i,i+4096)})}catch(t){n(t)}}a=void 0})()}},async flush(){for(;a;)await a}}}
1
+ const MAX_DELTA_BYTES=16384;export function splitCentralNativeDelta(t){const e=[];let n="",i=0;for(const s of t){const t=Buffer.byteLength(s,"utf8");i+t>16384&&(e.push(n),n="",i=0),n+=s,i+=t}return n&&e.push(n),e}export function createCentralNativeDeltaStream(t,e,n){let i,s=-1,r="",l=!1,a=!1,o=[];const f=f=>{a||0===f.length||(l&&r.length>0&&(s+=1,r=""),s<0&&(s=0),l=!1,(e=>{const n=o.at(-1);n&&n.output_index===s?n.delta+=e:o.push({item_id:`${t.responseId}:message:${s}`,output_index:s,content_index:0,delta:e})})(f),r+=f,i??=(async()=>{for(;o.length;){const i=o.shift();for(const s of splitCentralNativeDelta(i.delta))try{await e(t,{...i,delta:s})}catch(t){n(t)}}i=void 0})())};return{partial(t){if(!a&&"string"==typeof t&&0!==t.length)if(l)f(t);else if(s>=0&&t.startsWith(r)){if(t.length===r.length)return;f(t.slice(r.length))}else{if(s>=0&&r.startsWith(t))return;l=s>=0,f(t)}},block(t){if(a||"string"!=typeof t||0===t.length)return;if(s<0||l)return void f(t);if(t===r||r.startsWith(t))return;if(t.startsWith(r))return void f(t.slice(r.length));let e=Math.min(r.length,t.length);for(;e>0&&t.slice(0,e)!==r.slice(r.length-e);)e-=1;f(t.slice(e))},beginMessage(){!a&&s>=0&&(l=!0)},async close(){for(a=!0;i;)await i}}}
@@ -1 +1 @@
1
- import{RUNTIME_HASH_DOMAINS}from"@beeos-ai/beeos-types/runtime";import{centralNativeRuntime}from"./central-native-runtime.js";import{createCentralNativeMemoryAttempt}from"./central-native-memory.js";import{preparedSandboxNativeExecution}from"./sandbox-native-activation.js";import{dispatchRuntimeReplyWithRoute}from"./reply-router.js";import{prepareNativePromptInput}from"./native-prompt-preflight.js";import{downloadNativeInputFile}from"./native-input-files.js";import{runtimeMessageHash}from"./runtime-message-channel-contract.js";import{createCentralNativeDeltaStream}from"./central-native-delta.js";import{bindCentralInteractions}from"./central-native-interactions.js";export function createCentralNativeHost(e){return{async run(t){t.assertCurrent(),t.signal.throwIfAborted();const n=preparedSandboxNativeExecution(t.params,t.binding),r=t.params.runtimeRunId;if("string"!=typeof r||!r)throw new Error("original native RunID is unavailable");const i=e.coordinator.tryStartExclusive({sessionKey:n.sessionKey,label:t.binding.operationId},"message_service");if(!i.ok)throw new Error("central native physical session is busy");const a=i.token;let o=!1;const s=new AbortController,l=AbortSignal.any([t.signal,s.signal]),p=createCentralNativeMemoryAttempt({binding:t.binding,signal:l,assertCurrent:t.assertCurrent}),d=new Set;let c;const m=(n,r)=>{if(centralNativeRuntime().receipt(t.binding.operationId)?.terminal)return;const i={type:"response.beeos.part",response_id:t.binding.responseId,kind:n,data:JSON.stringify(r)};let a;try{a=e.recordPublicEvent(t.binding,i)}catch(e){a=Promise.reject(e)}d.add(a),a.then(()=>d.delete(a),e=>{d.delete(a),c??=e,s.abort(e)})},u=createCentralNativeDeltaStream(t.binding,e.publishDelta,t=>{e.logger.warn?.(`central output delta was not published: ${t instanceof Error?t.name:"error"}`)}),g=e=>{centralNativeRuntime().receipt(t.binding.operationId)?.terminal||u.partial(e.text)};let b="";const v=(e,n)=>(t.assertCurrent(),"final"===e&&"string"==typeof n.text&&n.text.length>0&&(b=b?`${b}\n${n.text}`:n.text),m(e,n),!0),y={sendToolResult:e=>v("tool",e),sendBlockReply:e=>v("block",e),sendFinalReply:e=>v("final",e),waitForIdle:async()=>{},getQueuedCounts:()=>({tool:0,block:0,final:0}),markComplete:()=>{}};try{const i=t.params.parts,s=Array.isArray(i)?prepareNativePromptInput(i):"string"==typeof t.params.text?{message:t.params.text,files:[]}:void 0;if(!s)throw new Error("central native signed prompt parts are unavailable");await centralNativeRuntime().prepare(n.sessionKey,t.binding);const v=[],I=[];for(const n of s.files){t.assertCurrent();const r=e.getLease();if(!r)throw new Error("central native input Files lease is unavailable");const i=await e.inputFiles.resolve({operationId:t.binding.operationId,requestMessageId:t.requestMessageId,paramsHash:runtimeMessageHash(RUNTIME_HASH_DOMAINS.params,{method:"session/prompt",params:t.params}),partIndex:n.partIndex,lease:r,signal:t.signal}),a=await downloadNativeInputFile({fileId:n.fileId,...i,signal:t.signal,assertAttempt:t.assertCurrent});v.push(a.path),I.push(a.mimeType)}let f;t.assertCurrent(),t.signal.throwIfAborted();const h=bindCentralInteractions(n.sessionKey,{responseId:t.binding.responseId,attemptId:t.binding.attemptId,mode:t.params.approvalMode,signal:l,publish:n=>e.recordPublicEvent(t.binding,{type:"response.interaction",response_id:t.binding.responseId,interaction:n}),decide:n=>e.decideInteraction(t.binding,n)});try{await dispatchRuntimeReplyWithRoute({runtime:{...e.runtime,config:{loadConfig:e.currentConfig}},preparedPrompt:{message:s.message,mediaPaths:v,mediaTypes:I,nativeSystemContext:n.systemPrompt},replyRoute:{protocol:"acp",requestId:t.binding.operationId,sessionId:n.sessionKey,sourceMessageId:t.requestMessageId,originatingChannel:"webchat",originatingTo:n.localAgentId,accountId:n.localAgentId,origin:"beeos-central-response"},replySinks:{acp:{dispatcher:y,replyOptions:{runId:r,abortSignal:l,disableBlockStreaming:!1,onAgentRunStart:t=>{e.coordinator.bindRun(a,t),p.bindHostRun(t)},onPartialReply:g,onReasoningStream:e=>{m("reasoning",e)},onToolStart:e=>{m("tool.start",e)},onItemEvent:e=>{m("item",e)}}}},onDispatchInvoked:()=>{o=!0}})}catch(e){f=e}try{await h()}catch(e){f??=e}await Promise.allSettled([...d,u.flush()]),f??=c;const w=t.signal.aborted,R=centralNativeRuntime().receipt(t.binding.operationId)?.terminal,C=await e.coordinator.converge(a,w?"cancelled":"completed"===R?.status?"completed":"error");if(!C.ok)throw new Error("central native physical writer did not quiesce");if(t.assertCurrent(),!e.native.nativeWritersQuiescent({sessionKey:n.sessionKey}))throw new Error("central native admission still owns the physical writer");if(f&&!w)throw f;const N=centralNativeRuntime().receipt(t.binding.operationId)?.terminal;if(!N||N.response_id!==t.binding.responseId)throw new Error("native outcome has no original central terminal transaction receipt");const S=N.status;return t.assertCurrent(),e.coordinator.release(C.permit),{status:S,...b?{finalText:b}:{}}}catch(t){throw o?e.coordinator.snapshot(n.sessionKey)&&e.coordinator.requireRecovery(a,"terminal_not_observed"):e.coordinator.releaseBeforeRuntime(a),t}finally{p.close()}}}}
1
+ import{RUNTIME_HASH_DOMAINS}from"@beeos-ai/beeos-types/runtime";import{centralNativeRuntime}from"./central-native-runtime.js";import{createCentralNativeMemoryAttempt}from"./central-native-memory.js";import{preparedSandboxNativeExecution}from"./sandbox-native-activation.js";import{dispatchRuntimeReplyWithRoute}from"./reply-router.js";import{prepareNativePromptInput}from"./native-prompt-preflight.js";import{downloadNativeInputFile}from"./native-input-files.js";import{runtimeMessageHash}from"./runtime-message-channel-contract.js";import{createCentralNativeDeltaStream}from"./central-native-delta.js";import{bindCentralInteractions}from"./central-native-interactions.js";export function createCentralNativeHost(e){return{async run(t){t.assertCurrent(),t.signal.throwIfAborted();const n=preparedSandboxNativeExecution(t.params,t.binding),r=t.params.runtimeRunId;if("string"!=typeof r||!r)throw new Error("original native RunID is unavailable");const a=e.coordinator.tryStartExclusive({sessionKey:n.sessionKey,label:t.binding.operationId},"message_service");if(!a.ok)throw new Error("central native physical session is busy");const i=a.token;let o=!1;const s=new AbortController,l=AbortSignal.any([t.signal,s.signal]),p=createCentralNativeMemoryAttempt({binding:t.binding,signal:l,assertCurrent:t.assertCurrent}),c=new Set;let d;const m=(n,r)=>{if(centralNativeRuntime().receipt(t.binding.operationId)?.terminal)return;const a={type:"response.beeos.part",response_id:t.binding.responseId,kind:n,data:JSON.stringify(r)};let i;try{i=e.recordPublicEvent(t.binding,a)}catch(e){i=Promise.reject(e)}c.add(i),i.then(()=>c.delete(i),e=>{c.delete(i),d??=e,s.abort(e)})},u=createCentralNativeDeltaStream(t.binding,e.publishDelta,t=>{e.logger.warn?.(`central output delta was not published: ${t instanceof Error?t.name:"error"}`)}),g=()=>centralNativeRuntime().receipt(t.binding.operationId)?.terminal,b=e=>{g()||u.partial(e.text)},v=e=>{g()||u.block(e.text)},y=()=>{g()||u.beginMessage()};let I="";const f=(e,n)=>(t.assertCurrent(),"final"===e&&"string"==typeof n.text&&n.text.length>0&&(I=I?`${I}\n${n.text}`:n.text),m(e,n),!0),h={sendToolResult:e=>f("tool",e),sendBlockReply:e=>{const t=f("block",e);return t&&v(e),t},sendFinalReply:e=>f("final",e),waitForIdle:async()=>{},getQueuedCounts:()=>({tool:0,block:0,final:0}),markComplete:()=>{}};try{const a=t.params.parts,s=Array.isArray(a)?prepareNativePromptInput(a):"string"==typeof t.params.text?{message:t.params.text,files:[]}:void 0;if(!s)throw new Error("central native signed prompt parts are unavailable");await centralNativeRuntime().prepare(n.sessionKey,t.binding);const g=[],f=[];for(const n of s.files){t.assertCurrent();const r=e.getLease();if(!r)throw new Error("central native input Files lease is unavailable");const a=await e.inputFiles.resolve({operationId:t.binding.operationId,requestMessageId:t.requestMessageId,paramsHash:runtimeMessageHash(RUNTIME_HASH_DOMAINS.params,{method:"session/prompt",params:t.params}),partIndex:n.partIndex,lease:r,signal:t.signal}),i=await downloadNativeInputFile({fileId:n.fileId,...a,signal:t.signal,assertAttempt:t.assertCurrent});g.push(i.path),f.push(i.mimeType)}let w;t.assertCurrent(),t.signal.throwIfAborted();const R=bindCentralInteractions(n.sessionKey,{responseId:t.binding.responseId,attemptId:t.binding.attemptId,mode:t.params.approvalMode,signal:l,publish:n=>e.recordPublicEvent(t.binding,{type:"response.interaction",response_id:t.binding.responseId,interaction:n}),decide:n=>e.decideInteraction(t.binding,n)});try{await dispatchRuntimeReplyWithRoute({runtime:{...e.runtime,config:{loadConfig:e.currentConfig}},preparedPrompt:{message:s.message,mediaPaths:g,mediaTypes:f,nativeSystemContext:n.systemPrompt},replyRoute:{protocol:"acp",requestId:t.binding.operationId,sessionId:n.sessionKey,sourceMessageId:t.requestMessageId,originatingChannel:"webchat",originatingTo:n.localAgentId,accountId:n.localAgentId,origin:"beeos-central-response"},replySinks:{acp:{dispatcher:h,replyOptions:{runId:r,abortSignal:l,disableBlockStreaming:!1,onAgentRunStart:t=>{e.coordinator.bindRun(i,t),p.bindHostRun(t)},onPartialReply:b,onBlockReplyQueued:e=>{v(e)},onAssistantMessageStart:y,onReasoningStream:e=>{m("reasoning",e)},onToolStart:e=>{m("tool.start",e)},onItemEvent:e=>{m("item",e)}}}},onDispatchInvoked:()=>{o=!0}})}catch(e){w=e}try{await R()}catch(e){w??=e}await Promise.allSettled([...c,u.close()]),w??=d;const C=t.signal.aborted,N=centralNativeRuntime().receipt(t.binding.operationId)?.terminal,S=await e.coordinator.converge(i,C?"cancelled":"completed"===N?.status?"completed":"error");if(!S.ok)throw new Error("central native physical writer did not quiesce");if(t.assertCurrent(),!e.native.nativeWritersQuiescent({sessionKey:n.sessionKey}))throw new Error("central native admission still owns the physical writer");if(w&&!C)throw w;const x=centralNativeRuntime().receipt(t.binding.operationId)?.terminal;if(!x||x.response_id!==t.binding.responseId)throw new Error("native outcome has no original central terminal transaction receipt");const A=x.status;return t.assertCurrent(),e.coordinator.release(S.permit),{status:A,...I?{finalText:I}:{}}}catch(t){throw o?e.coordinator.snapshot(n.sessionKey)&&e.coordinator.requireRecovery(i,"terminal_not_observed"):e.coordinator.releaseBeforeRuntime(i),t}finally{p.close()}}}}
@@ -1 +1 @@
1
- import{isDeepStrictEqual}from"node:util";import{RUNTIME_HASH_DOMAINS}from"@beeos-ai/beeos-types/runtime";import{assertCentralNativeReceipt}from"./central-native-context-engine.js";import{runtimeMessageHash}from"./runtime-message-channel-contract.js";const object=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),promptText=e=>{if("string"==typeof e.text&&e.text.length>0)return e.text;return(Array.isArray(e.parts)?e.parts:[]).filter(object).filter(e=>"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n")},text=e=>"string"==typeof e&&e.length>0,decimal=e=>"string"==typeof e&&/^(0|[1-9][0-9]*)$/.test(e),associationKeys=["context","session_id","history_generation","branch_id","writer","response_id","attempt_id","watermark","config_pin","persona_ref"];export function isCentralNativeResponse(e){const t=e.message?.payload,r=t?.request;return 2===t?.schemaVersion&&"session/prompt"===t.method&&object(r)&&object(r.params)&&Object.hasOwn(r.params,"centralChat")}export function verifyCentralNativeIntent(e){const t=e.executionGrant,r=e.request,i=t?e.verifier.verifyAndDecodeGrant(t):null,a=i?.claims,n=object(r.request)?r.request:{},s=object(n.params)?n.params:{},o=object(s.centralChat)?s.centralChat:{},c=object(r.command)?r.command:{},p=object(c.context)?c.context:{},d=object(p.conversation)?p.conversation:{},l=object(o.context)?o.context:{},m=object(o.writer)?o.writer:{},u=object(o.config_pin)?o.config_pin:{},h=u.credential_set_ref,g=()=>{const t=e.getLease();if(!t||t.instanceId!==e.lease.instanceId||t.leaseId!==e.lease.leaseId||t.handlerIdentity!==e.lease.handlerIdentity||t.runtimeEpoch!==e.lease.runtimeEpoch||!Number.isFinite(Date.parse(t.leaseExpiresAt))||Date.parse(t.leaseExpiresAt)<=Date.now())throw new Error("central native execution is fenced")},f=Math.floor(Date.now()/1e3);if(!object(r)||2!==r.schemaVersion||"session/prompt"!==r.method||!Object.hasOwn(s,"centralChat")||!t||!a||"string"!=typeof r.executionGrantHash||!/^[a-f0-9]{64}$/.test(r.executionGrantHash)||"cloud"!==r.authorityRealm||!object(r.cloudSubject)||r.cloudSubject.instanceId!==e.lease.instanceId||!isDeepStrictEqual(r.cloudSubject,a.cloudSubject)||r.instanceId!==e.lease.instanceId||r.leaseId!==e.lease.leaseId||r.runtimeHandlerIdentity!==e.lease.handlerIdentity||r.dispatchEpoch!==e.lease.runtimeEpoch||"cloud"!==a.authorityRealm||"session/prompt"!==a.method||"conversation"!==a.scope||"start"!==a.executionMode||a.platformConversationId!==o.session_id||a.historyGeneration!==o.history_generation||a.platformAgentId!==s.platformAgentId||!text(a.runtimeAgentUid)||s.conversationId!==o.session_id||"conversation"!==p.scope||d.runtimeConversationUid!==o.session_id||d.runtimeSessionKey!==o.session_id||p.historyGeneration!==o.history_generation||p.operationId!==r.operationId||p.runtimeInstanceUid!==r.instanceId||p.dispatchEpoch!==r.dispatchEpoch||p.paramsHash!==r.paramsHash||!isDeepStrictEqual(a.command,c)||!Number.isSafeInteger(a.iat)||!Number.isSafeInteger(a.exp)||a.iat>f||a.exp<=f||a.exp<=a.iat||a.exp-a.iat>60||a.sub!==e.lease.handlerIdentity||a.handlerIdentity!==e.lease.handlerIdentity||["operationId","requestMessageId","instanceId","leaseId","dispatchEpoch","requestHash","paramsHash","commandHash","idempotencyKeyHash"].some(e=>!text(r[e])||a[e]!==r[e])||"2.0"!==n.jsonrpc||"session/prompt"!==n.method||"session.prompt"!==c.name||!text(s.runtimeRunId)||s.taskId!==r.operationId||s.taskRequestMessageId!==r.requestMessageId||runtimeMessageHash(RUNTIME_HASH_DOMAINS.request,n)!==r.requestHash||runtimeMessageHash(RUNTIME_HASH_DOMAINS.params,{method:r.method,params:s})!==r.paramsHash||runtimeMessageHash(RUNTIME_HASH_DOMAINS.command,{command:c})!==r.commandHash||![o.session_id,o.history_generation,o.branch_id,o.response_id,o.attempt_id,l.tenant_ref,l.scope_ref,l.request_id,m.writer_id,m.writer_epoch].every(text)||!Number.isSafeInteger(l.authorization_revision)||l.authorization_revision<1||!Number.isSafeInteger(l.erasure_epoch)||l.erasure_epoch<0||!decimal(o.history_generation)||!decimal(o.watermark)||!decimal(m.writer_epoch)||"0"===m.writer_epoch||Object.keys(o).length!==associationKeys.length||!associationKeys.every(e=>Object.hasOwn(o,e))||4!==Object.keys(u).length||u.agent_id!==s.platformAgentId||!text(u.revision)||"string"!=typeof u.content_sha256||!/^[a-f0-9]{64}$/.test(u.content_sha256)||null!==h&&(!object(h)||2!==Object.keys(h).length||!text(h.set_id)||!Number.isSafeInteger(h.version)||h.version<1)||null!==o.persona_ref&&(!object(o.persona_ref)||2!==Object.keys(o.persona_ref).length||!text(o.persona_ref.persona_id)||!text(o.persona_ref.revision)))throw new Error("central native original signed intent is invalid");g();return{binding:{sessionId:o.session_id,historyGeneration:o.history_generation,branchId:o.branch_id,responseId:o.response_id,attemptId:o.attempt_id,operationId:r.operationId,context:l,writer:m},params:structuredClone(s),assertCurrent:g}}export class CentralNativeResponse{options;constructor(e){this.options=e}async execute(e){const t=this.options;await t.verifier.refresh();const r=e.delivery.message.payload;if("runtime_rpc_request"!==e.delivery.message.type||"completed"!==e.delivery.message.state||e.delivery.message.message_id!==r.requestMessageId||e.delivery.message.channel_id!==r.operationId)throw new Error("central native original delivery is invalid");const i=e.delivery.executionGrant,{binding:a,params:n,assertCurrent:s}=verifyCentralNativeIntent({request:r,executionGrant:i,verifier:t.verifier,lease:e.lease,getLease:t.getLease});e.onVerified?.({operationId:r.operationId,requestMessageId:r.requestMessageId,requestHash:r.requestHash,dispatchEpoch:r.dispatchEpoch,method:"session/prompt"}),t.bindCredential(a,i,r.requestHash,{requestMessageId:r.requestMessageId,verifier:t.verifier});const o=await t.pending.terminal(a);if(o){const e=o.request??{binding:o.binding,idempotencyKey:o.receipt.idempotency_key,payloadDigest:o.receipt.payload_sha256},{context:r,...i}=e.binding,{context:n,...c}=a;if(!isDeepStrictEqual(i,c)||r.tenant_ref!==n.tenant_ref||r.scope_ref!==n.scope_ref)throw new Error("central terminal original binding changed");const p=await t.store.receipt({...e,binding:a});if(s(),!p?.terminal||o.receipt&&!isDeepStrictEqual(p,o.receipt))throw new Error("central terminal outcome is unknown");return o.request&&(assertCentralNativeReceipt(o.request,p),await t.pending.complete(o.request,p)),await this.settleJournal(a.operationId),p}const c=await t.store.load(a);if(c.terminal?.response_id===a.responseId)throw new Error("original Response is already terminal; reconcile its original receipt before native execution");const p="completed"!==c.terminal?.status;if(s(),e.signal.aborted)throw new Error("central native execution stopped before dispatch; original owner stop reconciliation is required");let d=await t.journal.get(a.operationId);if(d&&("session.prompt"!==d.command||d.paramsHash!==r.paramsHash||d.runtimeEpoch!==e.lease.runtimeEpoch||"prepared"!==d.phase))throw new Error("central native execution already started; original terminal reconciliation is required");if(d=await t.journal.acceptMessageRequest({operationId:a.operationId,command:"session.prompt",paramsHash:r.paramsHash,runtimeEpoch:e.lease.runtimeEpoch,requestMessageId:r.requestMessageId,requestHash:r.requestHash}),s(),await t.journal.transition({operationId:a.operationId,expectedRevision:d.revision,phase:"started"}),e.signal.aborted)throw new Error("central native execution stopped before dispatch; original owner stop reconciliation is required");const l=await t.host.run({params:structuredClone(n),binding:a,requestMessageId:r.requestMessageId,signal:e.signal,assertCurrent:s});s();const m=await t.pending.terminal(a);if(!m?.receipt||!m.receipt.terminal||m.receipt.terminal.status!==l.status)throw new Error("native owner did not confirm its original atomic suffix/terminal transaction");const u=await t.store.receipt({binding:a,idempotencyKey:m.receipt.idempotency_key,payloadDigest:m.receipt.payload_sha256});if(s(),!u||!isDeepStrictEqual(u,m.receipt))throw new Error("original native terminal receipt is unavailable");return await this.settleJournal(a.operationId),"completed"===l.status&&p&&t.recordGeneratedTitle?.({binding:a,question:promptText(n),answer:l.finalText??""}),u}async settleJournal(e){let t=await this.options.journal.get(e);"started"===t?.phase&&(t=await this.options.journal.transition({operationId:e,expectedRevision:t.revision,phase:"effect_committed"})),"effect_committed"===t?.phase&&await this.options.journal.transition({operationId:e,expectedRevision:t.revision,phase:"projection_committed"})}}
1
+ import{isDeepStrictEqual}from"node:util";import{CLOUD_RUNTIME_EXECUTION_GRANT_DOMAIN,RUNTIME_HASH_DOMAINS}from"@beeos-ai/beeos-types/runtime";import{assertCentralNativeReceipt}from"./central-native-context-engine.js";import{runtimeMessageHash}from"./runtime-message-channel-contract.js";const object=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),promptText=e=>{if("string"==typeof e.text&&e.text.length>0)return e.text;return(Array.isArray(e.parts)?e.parts:[]).filter(object).filter(e=>"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n")},text=e=>"string"==typeof e&&e.length>0,decimal=e=>"string"==typeof e&&/^(0|[1-9][0-9]*)$/.test(e),associationKeys=["context","session_id","history_generation","branch_id","writer","response_id","attempt_id","watermark","config_pin","persona_ref"],GRANT_CLOCK_SKEW_SECONDS=30,grantInvalid=e=>new Error(`central native original signed intent is invalid: ${e}`),grantDecodeReason=e=>{const t=e.split(".")[1];if(!t)return"grant_signature_invalid";let r;try{const e=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));if(!object(e))return"grant_signature_invalid";r=e}catch{return"grant_signature_invalid"}return r.iss!==CLOUD_RUNTIME_EXECUTION_GRANT_DOMAIN.issuer?"grant_issuer_mismatch":r.aud!==CLOUD_RUNTIME_EXECUTION_GRANT_DOMAIN.audience?"grant_audience_mismatch":r.purpose!==CLOUD_RUNTIME_EXECUTION_GRANT_DOMAIN.purpose?"grant_binding_mismatch":"grant_signature_invalid"};export function isCentralNativeResponse(e){const t=e.message?.payload,r=t?.request;return 2===t?.schemaVersion&&"session/prompt"===t.method&&object(r)&&object(r.params)&&Object.hasOwn(r.params,"centralChat")}export function verifyCentralNativeIntent(e){const t=e.executionGrant,r=e.request;if(!t)throw grantInvalid("grant_binding_mismatch");const i=e.verifier.verifyAndDecodeGrant(t);if(!i)throw grantInvalid(grantDecodeReason(t));const n=i.claims,a=object(r.request)?r.request:{},s=object(a.params)?a.params:{},o=object(s.centralChat)?s.centralChat:{},c=object(r.command)?r.command:{},d=object(c.context)?c.context:{},p=object(d.conversation)?d.conversation:{},l=object(o.context)?o.context:{},m=object(o.writer)?o.writer:{},u=object(o.config_pin)?o.config_pin:{},h=u.credential_set_ref,g=()=>{const t=e.getLease();if(!t||t.instanceId!==e.lease.instanceId||t.leaseId!==e.lease.leaseId||t.handlerIdentity!==e.lease.handlerIdentity||t.runtimeEpoch!==e.lease.runtimeEpoch||!Number.isFinite(Date.parse(t.leaseExpiresAt))||Date.parse(t.leaseExpiresAt)<=Date.now())throw new Error("central native execution is fenced")},_=Math.floor(Date.now()/1e3);if(!Number.isSafeInteger(n.iat)||!Number.isSafeInteger(n.exp)||n.exp<=n.iat||n.exp-n.iat>60)throw grantInvalid("grant_binding_mismatch");if(n.exp+30<_)throw grantInvalid("grant_expired");if(n.iat>_+30)throw grantInvalid("grant_iat_future");if(!object(r)||2!==r.schemaVersion||"session/prompt"!==r.method||!Object.hasOwn(s,"centralChat")||"string"!=typeof r.executionGrantHash||!/^[a-f0-9]{64}$/.test(r.executionGrantHash)||"cloud"!==r.authorityRealm||!object(r.cloudSubject)||r.cloudSubject.instanceId!==e.lease.instanceId||!isDeepStrictEqual(r.cloudSubject,n.cloudSubject)||r.instanceId!==e.lease.instanceId||r.leaseId!==e.lease.leaseId||r.runtimeHandlerIdentity!==e.lease.handlerIdentity||r.dispatchEpoch!==e.lease.runtimeEpoch||"cloud"!==n.authorityRealm||"session/prompt"!==n.method||"conversation"!==n.scope||"start"!==n.executionMode||n.platformConversationId!==o.session_id||n.historyGeneration!==o.history_generation||n.platformAgentId!==s.platformAgentId||!text(n.runtimeAgentUid)||s.conversationId!==o.session_id||"conversation"!==d.scope||p.runtimeConversationUid!==o.session_id||p.runtimeSessionKey!==o.session_id||d.historyGeneration!==o.history_generation||d.operationId!==r.operationId||d.runtimeInstanceUid!==r.instanceId||d.dispatchEpoch!==r.dispatchEpoch||d.paramsHash!==r.paramsHash||!isDeepStrictEqual(n.command,c)||n.sub!==e.lease.handlerIdentity||n.handlerIdentity!==e.lease.handlerIdentity||["operationId","requestMessageId","instanceId","leaseId","dispatchEpoch","requestHash","paramsHash","commandHash","idempotencyKeyHash"].some(e=>!text(r[e])||n[e]!==r[e])||"2.0"!==a.jsonrpc||"session/prompt"!==a.method||"session.prompt"!==c.name||!text(s.runtimeRunId)||s.taskId!==r.operationId||s.taskRequestMessageId!==r.requestMessageId||runtimeMessageHash(RUNTIME_HASH_DOMAINS.request,a)!==r.requestHash||runtimeMessageHash(RUNTIME_HASH_DOMAINS.params,{method:r.method,params:s})!==r.paramsHash||runtimeMessageHash(RUNTIME_HASH_DOMAINS.command,{command:c})!==r.commandHash||![o.session_id,o.history_generation,o.branch_id,o.response_id,o.attempt_id,l.tenant_ref,l.scope_ref,l.request_id,m.writer_id,m.writer_epoch].every(text)||!Number.isSafeInteger(l.authorization_revision)||l.authorization_revision<1||!Number.isSafeInteger(l.erasure_epoch)||l.erasure_epoch<0||!decimal(o.history_generation)||!decimal(o.watermark)||!decimal(m.writer_epoch)||"0"===m.writer_epoch||Object.keys(o).length!==associationKeys.length||!associationKeys.every(e=>Object.hasOwn(o,e))||4!==Object.keys(u).length||u.agent_id!==s.platformAgentId||!text(u.revision)||"string"!=typeof u.content_sha256||!/^[a-f0-9]{64}$/.test(u.content_sha256)||null!==h&&(!object(h)||2!==Object.keys(h).length||!text(h.set_id)||!Number.isSafeInteger(h.version)||h.version<1)||null!==o.persona_ref&&(!object(o.persona_ref)||2!==Object.keys(o.persona_ref).length||!text(o.persona_ref.persona_id)||!text(o.persona_ref.revision)))throw grantInvalid("grant_binding_mismatch");g();return{binding:{sessionId:o.session_id,historyGeneration:o.history_generation,branchId:o.branch_id,responseId:o.response_id,attemptId:o.attempt_id,operationId:r.operationId,context:l,writer:m},params:structuredClone(s),assertCurrent:g}}export class CentralNativeResponse{options;constructor(e){this.options=e}async execute(e){const t=this.options;await t.verifier.refresh();const r=e.delivery.message.payload;if("runtime_rpc_request"!==e.delivery.message.type||"completed"!==e.delivery.message.state||e.delivery.message.message_id!==r.requestMessageId||e.delivery.message.channel_id!==r.operationId)throw new Error("central native original delivery is invalid");const i=e.delivery.executionGrant,{binding:n,params:a,assertCurrent:s}=verifyCentralNativeIntent({request:r,executionGrant:i,verifier:t.verifier,lease:e.lease,getLease:t.getLease});e.onVerified?.({operationId:r.operationId,requestMessageId:r.requestMessageId,requestHash:r.requestHash,dispatchEpoch:r.dispatchEpoch,method:"session/prompt"}),t.bindCredential(n,i,r.requestHash,{requestMessageId:r.requestMessageId,verifier:t.verifier});const o=await t.pending.terminal(n);if(o){const e=o.request??{binding:o.binding,idempotencyKey:o.receipt.idempotency_key,payloadDigest:o.receipt.payload_sha256},{context:r,...i}=e.binding,{context:a,...c}=n;if(!isDeepStrictEqual(i,c)||r.tenant_ref!==a.tenant_ref||r.scope_ref!==a.scope_ref)throw new Error("central terminal original binding changed");const d=await t.store.receipt({...e,binding:n});if(s(),!d?.terminal||o.receipt&&!isDeepStrictEqual(d,o.receipt))throw new Error("central terminal outcome is unknown");return o.request&&(assertCentralNativeReceipt(o.request,d),await t.pending.complete(o.request,d)),await this.settleJournal(n.operationId),d}const c=await t.store.load(n);if(c.terminal?.response_id===n.responseId)throw new Error("original Response is already terminal; reconcile its original receipt before native execution");const d="completed"!==c.terminal?.status;if(s(),e.signal.aborted)throw new Error("central native execution stopped before dispatch; original owner stop reconciliation is required");let p=await t.journal.get(n.operationId);if(p&&("session.prompt"!==p.command||p.paramsHash!==r.paramsHash||p.runtimeEpoch!==e.lease.runtimeEpoch||"prepared"!==p.phase))throw new Error("central native execution already started; original terminal reconciliation is required");if(p=await t.journal.acceptMessageRequest({operationId:n.operationId,command:"session.prompt",paramsHash:r.paramsHash,runtimeEpoch:e.lease.runtimeEpoch,requestMessageId:r.requestMessageId,requestHash:r.requestHash}),s(),await t.journal.transition({operationId:n.operationId,expectedRevision:p.revision,phase:"started"}),e.signal.aborted)throw new Error("central native execution stopped before dispatch; original owner stop reconciliation is required");const l=await t.host.run({params:structuredClone(a),binding:n,requestMessageId:r.requestMessageId,signal:e.signal,assertCurrent:s});s();const m=await t.pending.terminal(n);if(!m?.receipt||!m.receipt.terminal||m.receipt.terminal.status!==l.status)throw new Error("native owner did not confirm its original atomic suffix/terminal transaction");const u=await t.store.receipt({binding:n,idempotencyKey:m.receipt.idempotency_key,payloadDigest:m.receipt.payload_sha256});if(s(),!u||!isDeepStrictEqual(u,m.receipt))throw new Error("original native terminal receipt is unavailable");return await this.settleJournal(n.operationId),"completed"===l.status&&d&&t.recordGeneratedTitle?.({binding:n,question:promptText(a),answer:l.finalText??""}),u}async settleJournal(e){let t=await this.options.journal.get(e);"started"===t?.phase&&(t=await this.options.journal.transition({operationId:e,expectedRevision:t.revision,phase:"effect_committed"})),"effect_committed"===t?.phase&&await this.options.journal.transition({operationId:e,expectedRevision:t.revision,phase:"projection_committed"})}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "beeos-claw",
3
- "version": "0.6.91",
3
+ "version": "0.6.92",
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>",
@@ -90,5 +90,5 @@
90
90
  "brace-expansion": ">=5.0.9",
91
91
  "@beeos-ai/beeos-types": "$@beeos-ai/beeos-types"
92
92
  },
93
- "gitHead": "aa1d2d61d47ae88872cdfb6b039356c7f5a4bd45"
93
+ "gitHead": "11274ec6ff443e3ce83e46865be0daee310e546a"
94
94
  }