beeos-claw 0.6.91 → 0.6.93
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/im-runtime-dispatch.js +1 -1
- package/dist/index.js +1 -1
- package/dist/runtime/central-native-delta.js +1 -1
- package/dist/runtime/central-native-host.js +1 -1
- package/dist/runtime/central-native-response.js +1 -1
- package/dist/runtime/sandbox-native-activation.js +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash,randomUUID}from"node:crypto";import{dispatchRuntimeReplyWithRoute,hasRuntimeReplyApi}from"./runtime/reply-router.js";import{createImReplySink}from"./runtime/im-reply-sink.js";import{SerializedCallbackQueue}from"./runtime/callback-queue.js";import{promptRunKey}from"./runtime/prompt-run-store.js";import{classifyAgentRuntimeFailure}from"./runtime/agent-runtime-failure-classifier.js";import{SESSION_RECOVERY_REQUIRED_CODE,SESSION_RECOVERY_REQUIRED_MESSAGE}from"./runtime/session-mutation-coordinator.js";import{interceptAgentRuntimeFailures,messageStopReasonForRuntimeFailure,SESSION_BUSY_PUBLIC_MESSAGE}from"./runtime/im-runtime-failure-policy.js";import{writeRuntimeFailure}from"./runtime/write-runtime-failure.js";import{maybeRenameImConversationTitle}from"./runtime/conversation-title.js";import{settleBeforeTerminal}from"./approval/bridge.js";import{logChatLatency}from"./chat-latency.js";const normalizePositiveTimeoutMs=e=>{if("number"!=typeof e||!Number.isFinite(e))return;const n=Math.max(0,Math.trunc(e));return n>0?n:void 0},ABORT_TERMINAL_GRACE_MS=1e4,PRE_RUN_LOOP_PROBE_MS=100,PRE_RUN_LOOP_LAG_LOG_MS=500,formatErrMessage=e=>{if(e instanceof Error)return e.message;if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}},failMessageStream=async(e,n)=>{void 0!==n.body&&e.setBody(n.body),await e.fail(void 0===n.stopReason?void 0:{stopReason:n.stopReason})};export const deterministicReplyMessageId=(e,n,t,r)=>`${e}_${createHash("sha256").update(`${n}:${t}:${r}`).digest("hex").slice(0,32)}`;export const dispatchImInboundPrompt=async e=>{const{runtime:n,prompt:t,client:r,logger:a,promptRunStore:i,assistantMessageCommitRouter:o,toolResultObservationRouter:s,modelCallObservationRouter:c,sessionMutationCoordinator:l,abortTransport:d,activeRunAuthority:u}=e;if(!hasRuntimeReplyApi(n))return a.warn?.(`[im] runtime dispatch skipped reason=reply_api_unavailable channel=${t.channelId} in_reply_to=${t.inboundMessageId}`),e.onLifecycleEvent?.({type:"skipped",reason:"reply_api_unavailable",channelId:t.channelId,inboundMessageId:t.inboundMessageId}),!1;const m=t.requestId??t.inboundMessageId,p=e.runtimeRunId??randomUUID();if(!p)throw new Error("runtime run id required");const I=Date.now();logChatLatency(a,"claw.inbound.received",m,I,{origin:e.origin??"im",request_id_source:t.requestId?"realtime_correlation":"message_id_fallback"});const g=e.origin??"im",h={protocol:"im",requestId:m,sessionId:t.sessionKey??"agent:main",sourceMessageId:t.inboundMessageId,chatId:t.channelId,origin:g},y=async(n,r)=>{if(e.onTerminalResult)try{await e.onTerminalResult(n,r)}catch(e){a.warn?.(`[im] terminal business callback failed requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId}: ${formatErrMessage(e)}`)}},_=promptRunKey(t.channelId,t.inboundMessageId),R=t.sessionKey??"agent:main",f=new AbortController;let w,b,E,v,M,S,$,C;const q=new Promise((e,n)=>{C=n});e.onNativeRunCompletion&&q.catch(()=>{});const N=e.onNativeRunCompletion?{chatAbort:(e,n)=>(E=Promise.resolve().then(()=>d.chatAbort(e,n)),E)}:d;let k;const O=()=>{void 0!==k&&(clearTimeout(k),k=void 0)},T=async e=>{if($??=e,f.abort(e),!w)return{ok:!0};const n=await l.requestCancel(w,N);return n.ok?n.terminalObservation.then(e=>{e.ok||C(new Error(SESSION_RECOVERY_REQUIRED_CODE))}):C(new Error(SESSION_RECOVERY_REQUIRED_CODE)),{ok:n.ok}};if(e.waitIfExclusive)try{await e.waitIfExclusive("im_dispatch",f.signal)}catch(n){return a.warn?.(`[im] runtime dispatch aborted waiting for exclusive mutation requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId}`),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:n instanceof Error?n.message:String(n),cause:"abort"}),!1}if(!i.register(_,{requestId:m,channelId:t.channelId,requestCancel:T,startedAt:I,sessionKey:R}))return a.warn?.(`[im] runtime dispatch rejected duplicate inboundMessageId=${t.inboundMessageId} requestId=${m} channel=${t.channelId}`),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:"duplicate_inbound_message_id",cause:"abort"}),!1;const L=e.retainedStream?.id??deterministicReplyMessageId("asst",t.channelId,t.inboundMessageId,t.selfPrincipalId),A={conversationId:t.channelId,clientMessageId:L,idempotencyKey:L,replyTo:e.inReplyTo??t.inboundMessageId,requestId:m,type:"agent_reply",content:{}};let D=()=>{};const F=settleBeforeTerminal(e.retainedStream??r.messages.startStream(A),()=>D());let U,K=!1;try{const e=await F.opened();K="duplicate"===e.outcome,logChatLatency(a,"claw.reply_stream.opened",m,I,{outcome:e.outcome})}catch(n){let o="unconfirmed";try{o=(await r.messages.getEnvelope(t.channelId,L)).state}catch{}return a.warn?.(`[im] runtime reply stream open outcome unknown requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} reply_id=${L} reconciled_state=${o}: ${formatErrMessage(n)}; runtime_not_invoked`),e.onLifecycleEvent?.({type:"skipped",reason:"reply_open_outcome_unknown",channelId:t.channelId,inboundMessageId:t.inboundMessageId}),i.unregister(_),!1}if(K)return a.info?.(`[im] runtime dispatch skipped existing deterministic reply requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId}`),e.onLifecycleEvent?.({type:"skipped",reason:"idempotent_reply_exists",channelId:t.channelId,inboundMessageId:t.inboundMessageId}),i.unregister(_),!1;const P=()=>{T(e.abortSignal?.reason).catch(e=>{C(e instanceof Error?e:new Error(String(e)))})};e.abortSignal?.addEventListener("abort",P,{once:!0}),e.abortSignal?.aborted&&P();const Q=new SerializedCallbackQueue,j=createImReplySink({stream:F,persistObservedToolResults:void 0!==e.retainedStream,htmlDelivery:e.htmlDelivery,abortSignal:f.signal,callbackQueue:Q,...e.onNativeRunCompletion?{onCallbackFailure:e=>Q.fail(e)}:{},logger:a,requestId:m,startedAtMs:I,runId:p,channelId:t.channelId,inboundMessageId:t.inboundMessageId,origin:g,sessionKey:R,onAgentRunStart:n=>{l.bindRun(w,n),e.onNativeAgentRunStart?.(n),void 0!==U&&logChatLatency(a,"claw.runtime.pre_run_completed",m,U)}}),G=interceptAgentRuntimeFailures(j,"im_runtime",e=>a.warn?.(`[im] runtime failure reply suppressed requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} error_code=${e.errorCode}`)),Y=G.sink;let x=!1,B=!1;const V=async n=>{e.onNativeRunCompletion||Y.dispatcher.markComplete(n);try{e.onNativeRunCompletion&&Y.dispatcher.markComplete(n),await Y.dispatcher.waitForIdle()}catch(n){if(e.onNativeRunCompletion)throw Q.fail(n),n}},z=()=>{if(e.onNativeRunCompletion)return;O();const n=normalizePositiveTimeoutMs(e.abortTerminalGraceMs)??1e4;k=setTimeout(()=>{k=void 0,(async()=>{if(F.isTerminated)return;const e=f.signal.reason??$,n="string"==typeof e&&e.startsWith("chat_cancel");if(await V("failure"),!F.isTerminated)try{n?await F.cancel({stopReason:"user_stop"}):await failMessageStream(F,{body:SESSION_RECOVERY_REQUIRED_MESSAGE,stopReason:"error"}),a.warn?.(`[im] abort settlement watchdog terminalized reply requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} user_cancel=${n}`)}catch(e){a.warn?.(`[im] abort settlement watchdog terminal write failed requestId=${m} channel=${t.channelId}: ${formatErrMessage(e)}`)}})()},n)};f.signal.aborted?z():f.signal.addEventListener("abort",z,{once:!0});const W=()=>{if(!f.signal.aborted)return;const e=f.signal.reason;throw e instanceof Error?e:new Error(String(e??"runtime dispatch aborted"))};let J,H,X,Z,ee,ne,te,re,ae;const ie=async e=>{if(!w)throw new Error("session_mutation_not_acquired");const n=await l.converge(w,e);return n.ok?(J=n.permit,!0):(a.error?.(`[im] session mutation recovery required requestId=${m} sessionKey=${R} reason=${n.recovery.reason}`),H={code:n.recovery.code,reason:n.recovery.reason,sessionKey:n.recovery.sessionKey,operationId:n.recovery.operationId,surface:"message_service",...n.recovery.terminalKind?{terminalKind:n.recovery.terminalKind}:{}},!1)};try{if(W(),e.onNativeRunCompletion&&!e.nativeActiveRunRegistration)throw new Error("native MS Start registration required");const d=l.tryStartInteractive({sessionKey:R,label:"im_chat_message"},"message_service");if(!d.ok){try{await failMessageStream(F,{body:SESSION_BUSY_PUBLIC_MESSAGE,stopReason:"error"})}catch(e){a.warn?.(`[im] session busy terminal write failed channel=${t.channelId} in_reply_to=${t.inboundMessageId}: ${formatErrMessage(e)}`)}return a.warn?.(`[im] session write gate busy sessionKey=${R} channel=${t.channelId} in_reply_to=${t.inboundMessageId} active_operation=${d.activeOperationId??"unknown"}`),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:"session_busy",cause:"runtime_error"}),!1}if(w=d.token,logChatLatency(a,"claw.session_gate.acquired",m,I),l.bindRun(w,p),Z=o.register(R,j),ee=s.register(R,j),ne=e.approvalStreams?.bindSession(R,j.approvalParts),te=e.questionStreams?.bindSession(R,j.questionParts,{conversationId:t.channelId,replyMessageId:F.id}),D=()=>{ne?.(),te?.()},re=c.register(p,{requestId:m,startedAtMs:I,logger:a}),u){const n=l.snapshot(R);X=e.onNativeRunCompletion?{...e.nativeActiveRunRegistration}:{runtimeConversationUid:t.channelId,runtimeSessionKey:t.channelId,historyGeneration:u.historyGeneration(t.channelId),targetMessageId:t.inboundMessageId,runtimeRunId:p,activeRunRegistrationId:`im:${n?.operationId??p}`},u.activeRuns.register(X,async()=>{const e=`chat_cancel:activeRun:${X.activeRunRegistrationId}`,n=await i.abort(_,e);return n.ok||"already_aborted"===n.reason?"accepted":"terminal_committing"===n.reason||"not_found"===n.reason?"already_terminal":"recovery_required"})}W(),a.info?.(`[im] runtime dispatching requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} origin=${g}`),e.onLifecycleEvent?.({type:"dispatch_start",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId}),e.onNativeRunCompletion&&e.assertNativeTarget&&(await e.assertNativeTarget(),W()),e.onNativeRunCompletion&&e.prepareNativeModel&&(await e.prepareNativeModel(w),W(),await(e.assertNativeTarget?.()),W());const f=t.modelOverrideId;"string"==typeof f&&f.length>0&&R.length>0&&e.applyTurnModel&&(await e.applyTurnModel(R,f),B=!0,W()),U=Date.now(),ae=e.enterTurn?.(R,p),logChatLatency(a,"claw.runtime.invoke",m,I);const S=setTimeout(()=>{const e=Date.now()-U-100;e>=500&&logChatLatency(a,"claw.runtime.event_loop_lag",m,U,{lag_ms:e,phase:"pre_run"})},100);S.unref?.();const $=()=>dispatchRuntimeReplyWithRoute({runtime:n,pluginConfig:e.pluginConfig,preparedPrompt:t.dispatchInput,replyRoute:h,replySinks:{im:Y},onDispatchInvoked:n=>{if(x=!0,e.onNativeRunCompletion){b=n;const t=new Promise((e,n)=>{v=e,M=n});t.catch(()=>{}),e.onNativeRunCompletion({runtimeRunId:p,token:w,hostCompletion:n,completion:t})}logChatLatency(a,"claw.runtime.dispatch_returned",m,U)}}),C=ae?ae.run($):$(),N=e.onNativeRunCompletion?await C:await Promise.race([C,q]).finally(()=>{});e.onNativeRunCompletion&&(await b,await E);const k=G.detectedFailure();if(k)throw new Error(k.diagnosticMessage);if(W(),await V("success"),e.onNativeRunCompletion&&await E,W(),void 0===Y.dispatcher.getTerminalErrorText?.()&&e.htmlDelivery?.assertComplete(),!i.claimTerminal(_,"completion")){if(W(),"cancelling"===i.phase(_))throw new Error("cancellation in progress");throw new Error("terminal outcome already claimed")}if(!await ie("completed"))return await failMessageStream(F,{body:SESSION_RECOVERY_REQUIRED_MESSAGE,stopReason:"error"}).catch(()=>{}),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:SESSION_RECOVERY_REQUIRED_CODE,cause:"runtime_error",...H?{recovery:H}:{}}),!1;const O=Y.dispatcher.getTerminalErrorText?.();if(void 0!==O){let n=!1;const r=classifyAgentRuntimeFailure({raw:O,source:"im_runtime",runtimeKind:"openclaw"});try{await writeRuntimeFailure(F,{body:r.publicMessage,stopReason:messageStopReasonForRuntimeFailure(r),businessErrorCode:r.businessErrorCode})}catch(e){n=!0,a.warn?.(`[im] runtime reply stream error-terminal write outcome unknown requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId}: ${formatErrMessage(e)}`)}return u&&X&&u.activeRuns.markTerminal(X,"failed"),a.warn?.(`[im] runtime dispatch ended with an error terminal requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} counts=${JSON.stringify(N.counts)} terminalWriteFailed=${n} elapsed_ms=${Date.now()-I}`),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:"runtime_error_terminal_reply",cause:"runtime_error"}),n||await y("",O),!1}let T=!1;try{await F.finalize({stopReason:"end_turn"})}catch(e){T=!0,a.warn?.(`[im] runtime reply stream finalize outcome unknown requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId}: ${formatErrMessage(e)}`)}u&&X&&u.activeRuns.markTerminal(X,"completed");const L={...N.counts,source:j.getSourceCount()};a.info?.(`[im] runtime dispatch completed requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} counts=${JSON.stringify(L)} elapsed_ms=${Date.now()-I}`),logChatLatency(a,"claw.turn.terminal",m,I,{outcome:T?"outcome_unknown":"completed",tool_count:L.tool}),e.onLifecycleEvent?.({type:"dispatch_complete",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,counts:L,...T?{terminalWriteFailed:!0}:{}});const A=Y.dispatcher.getAccumulatedBody?.()??"";T||await y(A,"");const K="string"==typeof t.dispatchInput.message?t.dispatchInput.message:"";return maybeRenameImConversationTitle({client:r,conversationId:t.channelId,question:K,answer:A,logger:a}),!0}catch(n){S=n,e.onNativeRunCompletion&&(await(b?.then(()=>{},()=>{})),await E),await V("failure"),e.onNativeRunCompletion&&await E;const r=f.signal.aborted,o=r?f.signal.reason:void 0,s="cancelling"===i.phase(_),c=o??$,l="string"==typeof c&&c.startsWith("chat_cancel");let d="runtime_error";(r||s)&&(d="abort");const p=s||l||r?"cancellation":"completion";if(!i.claimTerminal(_,p)){if(a.warn?.(`[im] terminal claim raced requestId=${m} channel=${t.channelId}; best-effort envelope terminal if still streaming`),!F.isTerminated)try{l?await F.cancel({stopReason:"user_stop"}):await failMessageStream(F,{body:formatErrMessage(n),stopReason:"error"})}catch(e){a.warn?.(`[im] raced terminal write failed requestId=${m}: ${formatErrMessage(e)}`)}throw n}const g=l?"cancelled":"error";if(u&&X&&!e.onNativeRunCompletion&&u.activeRuns.markTerminal(X,"cancelled"===g?"cancelled":"failed"),w&&!await ie(g))throw u&&X&&e.onNativeRunCompletion&&u.activeRuns.markTerminal(X,"cancelled"===g?"cancelled":"failed"),l?await F.cancel({stopReason:"user_stop"}).catch(()=>{}):await failMessageStream(F,{body:SESSION_RECOVERY_REQUIRED_MESSAGE,stopReason:"error"}).catch(()=>{}),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:SESSION_RECOVERY_REQUIRED_CODE,cause:d,...H?{recovery:H}:{}}),n;u&&X&&e.onNativeRunCompletion&&u.activeRuns.markTerminal(X,"cancelled"===g?"cancelled":"failed");const h=classifyAgentRuntimeFailure({raw:n,source:"im_runtime",runtimeKind:"openclaw",requestAborted:l}),R=l?h:G.detectedFailure()??h;let v=!1;try{l?await F.cancel({stopReason:"user_stop"}):await writeRuntimeFailure(F,{body:R.publicMessage,stopReason:messageStopReasonForRuntimeFailure(R),businessErrorCode:R.businessErrorCode})}catch(e){v=!0,a.warn?.(`[im] runtime stream terminal write failed requestId=${m} channel=${t.channelId}: ${formatErrMessage(e)}`)}throw a.warn?.(`[im] runtime dispatch failed requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} cause=${d} dispatchInvoked=${x} error_code=${R.errorCode}`),logChatLatency(a,"claw.turn.terminal",m,I,{outcome:d,error_code:R.errorCode}),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:R.errorCode,cause:d}),l||v||await y("",R.publicMessage),n}finally{if(e.onNativeRunCompletion&&(J?v?.(J):(x&&w&&l.requireRecovery(w,"terminal_not_observed"),M?.(S??new Error(SESSION_RECOVERY_REQUIRED_CODE)))),e.abortSignal?.removeEventListener("abort",P),x&&!J||ae?.close(),O(),re?.(),ee?.(),ne?.(),te?.(),Z?.(),i.unregister(_),B&&e.restoreTurnModel&&R)try{await e.restoreTurnModel(R)}catch(e){a.error?.(`[im] turn model restore failed requestId=${m} sessionKey=${R}: ${formatErrMessage(e)}`)}x?J&&l.release(J):l.releaseBeforeRuntime(w)}};
|
|
1
|
+
import{createHash,randomUUID}from"node:crypto";import{dispatchRuntimeReplyWithRoute,hasRuntimeReplyApi}from"./runtime/reply-router.js";import{createImReplySink}from"./runtime/im-reply-sink.js";import{SerializedCallbackQueue}from"./runtime/callback-queue.js";import{promptRunKey}from"./runtime/prompt-run-store.js";import{classifyAgentRuntimeFailure}from"./runtime/agent-runtime-failure-classifier.js";import{SESSION_RECOVERY_REQUIRED_CODE,SESSION_RECOVERY_REQUIRED_MESSAGE}from"./runtime/session-mutation-coordinator.js";import{interceptAgentRuntimeFailures,messageStopReasonForRuntimeFailure,SESSION_BUSY_PUBLIC_MESSAGE}from"./runtime/im-runtime-failure-policy.js";import{writeRuntimeFailure}from"./runtime/write-runtime-failure.js";import{maybeRenameImConversationTitle}from"./runtime/conversation-title.js";import{settleBeforeTerminal}from"./approval/bridge.js";import{logChatLatency}from"./chat-latency.js";const normalizePositiveTimeoutMs=e=>{if("number"!=typeof e||!Number.isFinite(e))return;const n=Math.max(0,Math.trunc(e));return n>0?n:void 0},ABORT_TERMINAL_GRACE_MS=1e4,PRE_RUN_LOOP_PROBE_MS=100,PRE_RUN_LOOP_LAG_LOG_MS=500,formatErrMessage=e=>{if(e instanceof Error)return e.message;if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}},failMessageStream=async(e,n)=>{void 0!==n.body&&e.setBody(n.body),await e.fail(void 0===n.stopReason?void 0:{stopReason:n.stopReason})};export const deterministicReplyMessageId=(e,n,t,r)=>`${e}_${createHash("sha256").update(`${n}:${t}:${r}`).digest("hex").slice(0,32)}`;export const dispatchImInboundPrompt=async e=>{const{runtime:n,prompt:t,client:r,logger:a,promptRunStore:i,assistantMessageCommitRouter:o,toolResultObservationRouter:s,modelCallObservationRouter:c,sessionMutationCoordinator:l,abortTransport:d,activeRunAuthority:u}=e;if(!hasRuntimeReplyApi(n))return a.warn?.(`[im] runtime dispatch skipped reason=reply_api_unavailable channel=${t.channelId} in_reply_to=${t.inboundMessageId}`),e.onLifecycleEvent?.({type:"skipped",reason:"reply_api_unavailable",channelId:t.channelId,inboundMessageId:t.inboundMessageId}),!1;const m=t.requestId??t.inboundMessageId,p=e.runtimeRunId??randomUUID();if(!p)throw new Error("runtime run id required");const I=Date.now();logChatLatency(a,"claw.inbound.received",m,I,{origin:e.origin??"im",request_id_source:t.requestId?"realtime_correlation":"message_id_fallback"});const g=e.origin??"im",h={protocol:"im",requestId:m,sessionId:t.sessionKey??"agent:main",sourceMessageId:t.inboundMessageId,chatId:t.channelId,origin:g},y=async(n,r)=>{if(e.onTerminalResult)try{await e.onTerminalResult(n,r)}catch(e){a.warn?.(`[im] terminal business callback failed requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId}: ${formatErrMessage(e)}`)}},_=promptRunKey(t.channelId,t.inboundMessageId),R=t.sessionKey??"agent:main",f=new AbortController;let v,w,b,E,M,S,$,C;const q=new Promise((e,n)=>{C=n});e.onNativeRunCompletion&&q.catch(()=>{});const N=e.onNativeRunCompletion?{chatAbort:(e,n)=>(b=Promise.resolve().then(()=>d.chatAbort(e,n)),b)}:d;let k;const O=()=>{void 0!==k&&(clearTimeout(k),k=void 0)},T=async e=>{if($??=e,f.abort(e),!v)return{ok:!0};const n=await l.requestCancel(v,N);return n.ok?n.terminalObservation.then(e=>{e.ok||C(new Error(SESSION_RECOVERY_REQUIRED_CODE))}):C(new Error(SESSION_RECOVERY_REQUIRED_CODE)),{ok:n.ok}};if(e.waitIfExclusive)try{await e.waitIfExclusive("im_dispatch",f.signal)}catch(n){return a.warn?.(`[im] runtime dispatch aborted waiting for exclusive mutation requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId}`),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:n instanceof Error?n.message:String(n),cause:"abort"}),!1}if(!i.register(_,{requestId:m,channelId:t.channelId,requestCancel:T,startedAt:I,sessionKey:R}))return a.warn?.(`[im] runtime dispatch rejected duplicate inboundMessageId=${t.inboundMessageId} requestId=${m} channel=${t.channelId}`),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:"duplicate_inbound_message_id",cause:"abort"}),!1;const L=e.retainedStream?.id??deterministicReplyMessageId("asst",t.channelId,t.inboundMessageId,t.selfPrincipalId),A={conversationId:t.channelId,clientMessageId:L,idempotencyKey:L,replyTo:e.inReplyTo??t.inboundMessageId,requestId:m,type:"agent_reply",content:{}};let D=()=>{};const F=settleBeforeTerminal(e.retainedStream??r.messages.startStream(A),()=>D());let U,K=!1;try{const e=await F.opened();K="duplicate"===e.outcome,logChatLatency(a,"claw.reply_stream.opened",m,I,{outcome:e.outcome})}catch(n){let o="unconfirmed";try{o=(await r.messages.getEnvelope(t.channelId,L)).state}catch{}return a.warn?.(`[im] runtime reply stream open outcome unknown requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} reply_id=${L} reconciled_state=${o}: ${formatErrMessage(n)}; runtime_not_invoked`),e.onLifecycleEvent?.({type:"skipped",reason:"reply_open_outcome_unknown",channelId:t.channelId,inboundMessageId:t.inboundMessageId}),i.unregister(_),!1}if(K)return a.info?.(`[im] runtime dispatch skipped existing deterministic reply requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId}`),e.onLifecycleEvent?.({type:"skipped",reason:"idempotent_reply_exists",channelId:t.channelId,inboundMessageId:t.inboundMessageId}),i.unregister(_),!1;const P=()=>{T(e.abortSignal?.reason).catch(e=>{C(e instanceof Error?e:new Error(String(e)))})};e.abortSignal?.addEventListener("abort",P,{once:!0}),e.abortSignal?.aborted&&P();const Q=new SerializedCallbackQueue,j=createImReplySink({stream:F,persistObservedToolResults:void 0!==e.retainedStream,htmlDelivery:e.htmlDelivery,abortSignal:f.signal,callbackQueue:Q,...e.onNativeRunCompletion?{onCallbackFailure:e=>Q.fail(e)}:{},logger:a,requestId:m,startedAtMs:I,runId:p,channelId:t.channelId,inboundMessageId:t.inboundMessageId,origin:g,sessionKey:R,onAgentRunStart:n=>{l.bindRun(v,n),e.onNativeAgentRunStart?.(n),void 0!==U&&logChatLatency(a,"claw.runtime.pre_run_completed",m,U)}}),G=interceptAgentRuntimeFailures(j,"im_runtime",e=>a.warn?.(`[im] runtime failure reply suppressed requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} error_code=${e.errorCode}`)),Y=G.sink;let x=!1,B=!1;const V=async n=>{e.onNativeRunCompletion||Y.dispatcher.markComplete(n);try{e.onNativeRunCompletion&&Y.dispatcher.markComplete(n),await Y.dispatcher.waitForIdle()}catch(n){if(e.onNativeRunCompletion)throw Q.fail(n),n}},z=()=>{if(e.onNativeRunCompletion)return;O();const n=normalizePositiveTimeoutMs(e.abortTerminalGraceMs)??1e4;k=setTimeout(()=>{k=void 0,(async()=>{if(F.isTerminated)return;const e=f.signal.reason??$,n="string"==typeof e&&e.startsWith("chat_cancel");if(await V("failure"),!F.isTerminated)try{n?await F.cancel({stopReason:"user_stop"}):await failMessageStream(F,{body:SESSION_RECOVERY_REQUIRED_MESSAGE,stopReason:"error"}),a.warn?.(`[im] abort settlement watchdog terminalized reply requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} user_cancel=${n}`)}catch(e){a.warn?.(`[im] abort settlement watchdog terminal write failed requestId=${m} channel=${t.channelId}: ${formatErrMessage(e)}`)}})()},n)};f.signal.aborted?z():f.signal.addEventListener("abort",z,{once:!0});const W=()=>{if(!f.signal.aborted)return;const e=f.signal.reason;throw e instanceof Error?e:new Error(String(e??"runtime dispatch aborted"))};let J,H,X,Z,ee,ne,te,re,ae;const ie=async e=>{if(!v)throw new Error("session_mutation_not_acquired");const n=await l.converge(v,e);return n.ok?(J=n.permit,!0):(a.error?.(`[im] session mutation recovery required requestId=${m} sessionKey=${R} reason=${n.recovery.reason}`),H={code:n.recovery.code,reason:n.recovery.reason,sessionKey:n.recovery.sessionKey,operationId:n.recovery.operationId,surface:"message_service",...n.recovery.terminalKind?{terminalKind:n.recovery.terminalKind}:{}},!1)};let oe=!0;const se=async(e,n)=>{for(let r=0;;r+=1)try{return await n(),void(oe=!1)}catch(n){if(r>=1)return oe=!0,void a.warn?.(`[im] ${e} failed after terminal redelivery requestId=${m} channel=${t.channelId}: ${formatErrMessage(n)}`);a.warn?.(`[im] ${e} failed; redelivering terminal once requestId=${m} channel=${t.channelId}: ${formatErrMessage(n)}`)}};try{if(W(),e.onNativeRunCompletion&&!e.nativeActiveRunRegistration)throw new Error("native MS Start registration required");const d=l.tryStartInteractive({sessionKey:R,label:"im_chat_message"},"message_service");if(!d.ok){try{await failMessageStream(F,{body:SESSION_BUSY_PUBLIC_MESSAGE,stopReason:"error"})}catch(e){a.warn?.(`[im] session busy terminal write failed channel=${t.channelId} in_reply_to=${t.inboundMessageId}: ${formatErrMessage(e)}`)}return a.warn?.(`[im] session write gate busy sessionKey=${R} channel=${t.channelId} in_reply_to=${t.inboundMessageId} active_operation=${d.activeOperationId??"unknown"}`),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:"session_busy",cause:"runtime_error"}),!1}if(v=d.token,logChatLatency(a,"claw.session_gate.acquired",m,I),l.bindRun(v,p),Z=o.register(R,j),ee=s.register(R,j),ne=e.approvalStreams?.bindSession(R,j.approvalParts),te=e.questionStreams?.bindSession(R,j.questionParts,{conversationId:t.channelId,replyMessageId:F.id}),D=()=>{ne?.(),te?.()},re=c.register(p,{requestId:m,startedAtMs:I,logger:a}),u){const n=l.snapshot(R);X=e.onNativeRunCompletion?{...e.nativeActiveRunRegistration}:{runtimeConversationUid:t.channelId,runtimeSessionKey:t.channelId,historyGeneration:u.historyGeneration(t.channelId),targetMessageId:t.inboundMessageId,runtimeRunId:p,activeRunRegistrationId:`im:${n?.operationId??p}`},u.activeRuns.register(X,async()=>{const e=`chat_cancel:activeRun:${X.activeRunRegistrationId}`,n=await i.abort(_,e);return n.ok||"already_aborted"===n.reason?"accepted":"terminal_committing"===n.reason||"not_found"===n.reason?"already_terminal":"recovery_required"})}W(),a.info?.(`[im] runtime dispatching requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} origin=${g}`),e.onLifecycleEvent?.({type:"dispatch_start",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId}),e.onNativeRunCompletion&&e.assertNativeTarget&&(await e.assertNativeTarget(),W()),e.onNativeRunCompletion&&e.prepareNativeModel&&(await e.prepareNativeModel(v),W(),await(e.assertNativeTarget?.()),W());const f=t.modelOverrideId;"string"==typeof f&&f.length>0&&R.length>0&&e.applyTurnModel&&(await e.applyTurnModel(R,f),B=!0,W()),U=Date.now(),ae=e.enterTurn?.(R,p),logChatLatency(a,"claw.runtime.invoke",m,I);const S=setTimeout(()=>{const e=Date.now()-U-100;e>=500&&logChatLatency(a,"claw.runtime.event_loop_lag",m,U,{lag_ms:e,phase:"pre_run"})},100);S.unref?.();const $=()=>dispatchRuntimeReplyWithRoute({runtime:n,pluginConfig:e.pluginConfig,preparedPrompt:t.dispatchInput,replyRoute:h,replySinks:{im:Y},onDispatchInvoked:n=>{if(x=!0,e.onNativeRunCompletion){w=n;const t=new Promise((e,n)=>{E=e,M=n});t.catch(()=>{}),e.onNativeRunCompletion({runtimeRunId:p,token:v,hostCompletion:n,completion:t})}logChatLatency(a,"claw.runtime.dispatch_returned",m,U)}}),C=ae?ae.run($):$(),N=e.onNativeRunCompletion?await C:await Promise.race([C,q]).finally(()=>{});e.onNativeRunCompletion&&(await w,await b);const k=G.detectedFailure();if(k)throw new Error(k.diagnosticMessage);if(W(),await V("success"),e.onNativeRunCompletion&&await b,W(),void 0===Y.dispatcher.getTerminalErrorText?.()&&e.htmlDelivery?.assertComplete(),!i.claimTerminal(_,"completion")){if(W(),"cancelling"===i.phase(_))throw new Error("cancellation in progress");throw new Error("terminal outcome already claimed")}if(!await ie("completed"))return await failMessageStream(F,{body:SESSION_RECOVERY_REQUIRED_MESSAGE,stopReason:"error"}).catch(()=>{}),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:SESSION_RECOVERY_REQUIRED_CODE,cause:"runtime_error",...H?{recovery:H}:{}}),!1;const O=Y.dispatcher.getTerminalErrorText?.();if(void 0!==O){let n=!1;const r=classifyAgentRuntimeFailure({raw:O,source:"im_runtime",runtimeKind:"openclaw"});try{await writeRuntimeFailure(F,{body:r.publicMessage,stopReason:messageStopReasonForRuntimeFailure(r),businessErrorCode:r.businessErrorCode})}catch(e){n=!0,a.warn?.(`[im] runtime reply stream error-terminal write outcome unknown requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId}: ${formatErrMessage(e)}`)}return u&&X&&u.activeRuns.markTerminal(X,"failed"),a.warn?.(`[im] runtime dispatch ended with an error terminal requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} counts=${JSON.stringify(N.counts)} terminalWriteFailed=${n} elapsed_ms=${Date.now()-I}`),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:"runtime_error_terminal_reply",cause:"runtime_error"}),n||await y("",O),!1}let T=!1;try{await F.finalize({stopReason:"end_turn"})}catch(e){T=!0,a.warn?.(`[im] runtime reply stream finalize outcome unknown requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId}: ${formatErrMessage(e)}`)}u&&X&&u.activeRuns.markTerminal(X,"completed");const L={...N.counts,source:j.getSourceCount()};a.info?.(`[im] runtime dispatch completed requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} counts=${JSON.stringify(L)} elapsed_ms=${Date.now()-I}`),logChatLatency(a,"claw.turn.terminal",m,I,{outcome:T?"outcome_unknown":"completed",tool_count:L.tool}),e.onLifecycleEvent?.({type:"dispatch_complete",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,counts:L,...T?{terminalWriteFailed:!0}:{}});const A=Y.dispatcher.getAccumulatedBody?.()??"";T||await y(A,"");const K="string"==typeof t.dispatchInput.message?t.dispatchInput.message:"";return maybeRenameImConversationTitle({client:r,conversationId:t.channelId,question:K,answer:A,logger:a}),!0}catch(n){S=n,e.onNativeRunCompletion&&(await(w?.then(()=>{},()=>{})),await b),await V("failure"),e.onNativeRunCompletion&&await b;const r=f.signal.aborted,o=r?f.signal.reason:void 0,s="cancelling"===i.phase(_),c=o??$,l="string"==typeof c&&c.startsWith("chat_cancel");let d="runtime_error";(r||s)&&(d="abort");const p=s||l||r?"cancellation":"completion";if(!i.claimTerminal(_,p))throw a.warn?.(`[im] terminal claim raced requestId=${m} channel=${t.channelId}; best-effort envelope terminal if still streaming`),F.isTerminated?oe=!1:await se("raced terminal write",()=>l?F.cancel({stopReason:"user_stop"}):failMessageStream(F,{body:formatErrMessage(n),stopReason:"error"})),n;const g=l?"cancelled":"error";if(u&&X&&!e.onNativeRunCompletion&&u.activeRuns.markTerminal(X,"cancelled"===g?"cancelled":"failed"),v&&!await ie(g))throw u&&X&&e.onNativeRunCompletion&&u.activeRuns.markTerminal(X,"cancelled"===g?"cancelled":"failed"),l?await se("session recovery cancel",()=>F.cancel({stopReason:"user_stop"})):await se("session recovery terminal write",()=>failMessageStream(F,{body:SESSION_RECOVERY_REQUIRED_MESSAGE,stopReason:"error"})),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:SESSION_RECOVERY_REQUIRED_CODE,cause:d,...H?{recovery:H}:{}}),n;u&&X&&e.onNativeRunCompletion&&u.activeRuns.markTerminal(X,"cancelled"===g?"cancelled":"failed");const h=classifyAgentRuntimeFailure({raw:n,source:"im_runtime",runtimeKind:"openclaw",requestAborted:l}),R=l?h:G.detectedFailure()??h;throw l?await se("runtime stream cancel",()=>F.cancel({stopReason:"user_stop"})):await se("runtime stream terminal write",()=>writeRuntimeFailure(F,{body:R.publicMessage,stopReason:messageStopReasonForRuntimeFailure(R),businessErrorCode:R.businessErrorCode})),a.warn?.(`[im] runtime dispatch failed requestId=${m} channel=${t.channelId} in_reply_to=${t.inboundMessageId} cause=${d} dispatchInvoked=${x} error_code=${R.errorCode}`),logChatLatency(a,"claw.turn.terminal",m,I,{outcome:d,error_code:R.errorCode}),e.onLifecycleEvent?.({type:"dispatch_error",requestId:m,channelId:t.channelId,inboundMessageId:t.inboundMessageId,error:R.errorCode,cause:d}),l||oe||await y("",R.publicMessage),n}finally{if(e.onNativeRunCompletion&&(J?E?.(J):(x&&v&&oe&&l.requireRecovery(v,"terminal_not_observed"),M?.(S??new Error(SESSION_RECOVERY_REQUIRED_CODE)))),e.abortSignal?.removeEventListener("abort",P),x&&!J||ae?.close(),O(),re?.(),ee?.(),ne?.(),te?.(),Z?.(),i.unregister(_),B&&e.restoreTurnModel&&R)try{await e.restoreTurnModel(R)}catch(e){a.error?.(`[im] turn model restore failed requestId=${m} sessionKey=${R}: ${formatErrMessage(e)}`)}x?J&&l.release(J):l.releaseBeforeRuntime(v)}};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{claimedSandboxId,identityLaneFromEnvironment}from"./runtime/identity-lane-lease.js";import{createCentralNativeComposition,requireCentralNativeSessionHost}from"./runtime/central-native-composition.js";import{createSandboxNativeTargetLookup,registerSandboxNativeActivation}from"./runtime/sandbox-native-activation.js";import{registerCentralNativeMemoryTools}from"./runtime/central-native-memory.js";import{harnessConnectorToolCaller}from"./connectors/harness-connector-mcp.js";import{registerCentralNativeContextEngine,centralNativeChatEnabled}from"./runtime/central-native-runtime.js";import{relayCentralAskUser}from"./runtime/central-native-interactions.js";import{consumeNativeOutputTool,nativeHtmlDeliveryForRun}from"./runtime/native-output-file-attempt.js";import{uploadNativeOutputFile}from"./upload/upload-file.js";import{nativeOutputToolCallGate}from"./upload/native-output-tool-hook.js";import{NativeInputFilesHttpClient}from"./runtime/native-input-files-http.js";import{fileDeliveryFinalizeDecision}from"./upload/finalize-hook.js";import{resolveConfigWithMeta,mirrorOpenClawConfig}from"./config.js";import{hasRuntimeReplyApi}from"./runtime/reply-router.js";import{PromptRunStore}from"./runtime/prompt-run-store.js";import{createMcpNativeProjectionNudge,fingerprintMcpServers}from"./acp-gateway/mcp-native-projection-nudge.js";import{createImHotPathDeferral}from"./runtime/im-hot-path-deferral.js";import{SessionWriteGate}from"./acp-gateway/session-write-gate.js";import{OpenClawSessionWriteQuiescence}from"./runtime/openclaw-session-write-quiescence.js";import{SessionMutationCoordinator}from"./runtime/session-mutation-coordinator.js";import{scheduleProcessRuntimeRestart}from"./runtime/runtime-restart-scheduler.js";import{createImInboundHandler}from"./im-inbound-handler.js";import{AgentGatewayClient,NodeRuntimeDeliveryPort,agentIdentityFromKeyPair,loadAgentKeyPair,signAgentMessage}from"@beeos-ai/cloud-harness-sdk";import{MessageServiceConversationRunBoundary}from"./runtime/message-service-conversation-run-boundary.js";import{AutomationTurnPolicy}from"./automation/turn-policy.js";import{registerAutomationTools}from"./automation/tools.js";import{extractBeeosConversationIdFromSessionKey}from"./runtime/openclaw-session-key-resolution.js";import{setOpenClawConfigSnapshot}from"./runtime/openclaw-session-model.js";import{BeeosClawMessageClientProcessOwner,createBeeosClawMessageTokenProvider}from"./message-client-composition.js";import{MessageProjectionInboundConsumer}from"./message-projection-inbound-consumer.js";import{MessageClientTerminalStateRecovery}from"./runtime/message-client-terminal-state-recovery.js";import{RuntimeAuthorityMessageBusLifecycle}from"./runtime/runtime-authority-message-bus-lifecycle.js";import{createNativeCloudChatComposition,nativeCloudChatAuthorityFromRuntimeAuthority}from"./runtime/native-cloud-chat-composition.js";import{MSConnectionStatusSnapshot}from"./runtime/ms-connection-status.js";import{FileInboundExecutionJournal}from"./inbound-execution-journal.js";import{completeA2ATask,registerA2ATools,TaskHandleRegistry}from"./a2a/tools.js";import{BEEOS_UPLOAD_TOOL_NAME,BEEOS_UPLOAD_TOOL_SCHEMA,BEEOS_UPLOAD_TOOL_DESCRIPTION,REQUEST_TIMEOUT_MS as BEEOS_UPLOAD_REQUEST_TIMEOUT_MS,executeUpload}from"./upload/tool.js";import{BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME,BEEOS_DESKTOP_SCREENSHOT_TOOL_SCHEMA,BEEOS_DESKTOP_SCREENSHOT_TOOL_DESCRIPTION,executeDesktopScreenshot}from"./upload/desktop-screenshot-tool.js";import{BEEOS_LIST_FILES_TOOL_NAME,BEEOS_LIST_FILES_TOOL_SCHEMA,BEEOS_LIST_FILES_TOOL_DESCRIPTION,executeListFiles}from"./files/list-tool.js";import{BEEOS_FETCH_FILE_TOOL_NAME,BEEOS_FETCH_FILE_TOOL_SCHEMA,BEEOS_FETCH_FILE_TOOL_DESCRIPTION,executeFetchFile}from"./files/fetch-tool.js";import{writeUploadToolResult,cleanupUploadToolResultCache}from"./upload/result-cache.js";import{handleFileStage}from"./upload/file-stage.js";import{handleStatusRequest}from"./status.js";import{ACPServer}from"./acp-server.js";import{GatewayClient}from"./gateway-client.js";import{createObsEventWriter}from"./observability.js";import{resolvePluginVersion}from"./plugin-version.js";import{createTerminalWebSocketService}from"./terminal/websocket.js";import{TerminalManager}from"./terminal/session-manager.js";import{readDiscoveryCache,writeDiscoveryCache}from"./discovery-cache.js";import{setClaimedCloudRuntimeInstanceId,setUploadDeps}from"./upload/upload-file.js";import{registerLocalFileExtractor}from"./upload/local-file-extractors.js";import{browserScreenshotExtractor}from"./browser/screenshot-extractor.js";import{deliverableFileExtractor}from"./upload/deliverable-extractor.js";import{observeToolCallForDelivery,rememberDeliveryWorkspace}from"./upload/delivery-observe.js";import{BEEOS_FILE_RESOURCE_ROUTING_RULE}from"./files/beeos-file-uri.js";import{marksFullRuntimeRegistered,planPluginRegistration,replayCachedPluginTools,resolveCapabilityToolReplay}from"./plugin-registration-plan.js";import{buildAppendSystemContext,buildToolRoutingHint,canvasToolBlockReason}from"./prompt-system-context.js";import{CanvasStateManager}from"./canvas/state.js";import{createStaticCanvasHtmlPublisher}from"./canvas/static-html.js";import{CanvasRelayClient}from"./canvas/relay-client.js";import{createSandboxCanvasTokenProvider}from"./canvas/runtime-lease-token.js";import{createCanvasRelayService}from"./canvas/relay-service.js";import{RENDER_UI_TOOL_NAME,RENDER_UI_TOOL_DESCRIPTION,RENDER_UI_TOOL_SCHEMA,CLOSE_UI_TOOL_NAME,CLOSE_UI_TOOL_DESCRIPTION,CLOSE_UI_TOOL_SCHEMA,createRenderUiToolExecutor,createCloseUiHandler,CANVAS_PRESENTATION_GATE,CANVAS_SYSTEM_PROMPT}from"./canvas/tools.js";import{FormSchemaRegistry}from"./surface/form-schema-registry.js";import{buildCronSchemas}from"./surface/cron-schemas.js";import{RENDER_FORM_TOOL_NAME,RENDER_FORM_TOOL_SCHEMA,buildRenderFormDescription,createRenderFormHandler}from"./surface/render-form-tool.js";import{ResourceDescriptorRegistry}from"./surface/resource-descriptor-registry.js";import{CRON_RESOURCE}from"./surface/cron-resource.js";import{generateActionTools}from"./surface/action-tool-generator.js";import{buildThirdPartyChannelSet,isThirdPartyChannel}from"./channel-detection.js";import{registerArouterMediaProviders}from"./media/index.js";import{homedir}from"node:os";import{join}from"node:path";import{RuntimeProductionAuthority,cloudRuntimeTargetInstanceId}from"./runtime/runtime-production-authority.js";import{FileRuntimeCommandJournal}from"./runtime/runtime-command-journal.js";import{FileRuntimePoisonDeliveryJournal}from"./runtime/runtime-poison-delivery-journal.js";import{OpenClawNativeMcpProjection}from"./acp-gateway/openclaw-native-mcp-projection.js";import{LocalEncryptedCredentialReferenceVault}from"./acp-gateway/mcp-credential-reference-port.js";import{AgentGatewayGrantJwksReadinessAdapter,CloudRuntimeServiceTransportReadinessAdapter,RuntimeServiceTransportReadinessAdapter,createRuntimeServiceProductionCandidate}from"./runtime/runtime-service-production-candidate.js";import{fetchRuntimeLeaseAttempt}from"./runtime/message-service-runtime-authenticated-fetch.js";import{MessageServiceCronDeliveryHttpAuthority}from"./runtime/message-service-cron-delivery-http-authority.js";import{AgentMappingRegistry}from"./runtime/agent-mapping-registry.js";import{OpenClawRuntimeProcessOwner}from"./runtime/openclaw-runtime-process-owner.js";import{AgentGatewayHttpProjectionTransport,AgentGatewayTemplateOriginReporter,AgentProjectionProduction,OpenClawAgentProjectionSource}from"./runtime/agent-projection-production.js";import{MessageServiceRunOutputChannel}from"./runtime/message-service-run-output-channel.js";import{AssistantMessageCommitRouter}from"./runtime/assistant-message-commit-router.js";import{OpenClawApprovalBridge}from"./approval/bridge.js";import{APPROVAL_DECISION_MESSAGE_TYPE,isApprovalDocument}from"./approval/protocol.generated.js";import{isQuestionResponseDocument,OpenClawQuestionBridge}from"./question/bridge.js";import{ToolResultObservationRouter}from"./runtime/tool-result-observation-router.js";import{ModelCallObservationRouter,registerModelCallObservationHooks}from"./runtime/model-call-observability.js";import{registerArouterLatencyRouting}from"./runtime/arouter-latency-routing.js";import{createPeerRunOutputRouterFactory}from"./runtime/run-output-composition.js";const PLUGIN_VERSION=resolvePluginVersion();let agentKeys=null,agentGateway=null,sharedCanvasState=null,sharedAcpServer=null;const sharedSessionWriteGate=new SessionWriteGate,sharedPromptRunStore=new PromptRunStore,sharedAutomationTurnPolicy=new AutomationTurnPolicy;let lastOpenclawConfig;const sharedMcpNativeProjectionNudge=createMcpNativeProjectionNudge({getActiveImRunCount:()=>sharedPromptRunStore.size(),nudge:()=>{sharedAcpServer?.nudgeMcpNativeProjection()}}),sharedImHotPathDeferral=createImHotPathDeferral({getActiveImRunCount:()=>sharedPromptRunStore.size()});sharedPromptRunStore.setOnBecameIdle(()=>{sharedMcpNativeProjectionNudge.flushIfIdle({fingerprint:fingerprintMcpServers(lastOpenclawConfig)}),sharedImHotPathDeferral.notifyIdle()});const sharedAssistantMessageCommitRouter=new AssistantMessageCommitRouter,sharedToolResultObservationRouter=new ToolResultObservationRouter;let approvalLogger;const sharedApprovalBridge=new OpenClawApprovalBridge({request:(e,t)=>sharedGatewayClient?sharedGatewayClient.request(e,t):Promise.reject(new Error("Not connected to Gateway")),logger:{info:e=>approvalLogger?.info?.(e),warn:e=>approvalLogger?.warn?.(e)}}),sharedQuestionBridge=new OpenClawQuestionBridge({request:(e,t)=>sharedGatewayClient?sharedGatewayClient.request(e,t):Promise.reject(new Error("Not connected to Gateway")),logger:{info:e=>approvalLogger?.info?.(e),warn:e=>approvalLogger?.warn?.(e)}}),sharedModelCallObservationRouter=new ModelCallObservationRouter;let sharedSessionMutationCoordinator,sharedCentralPrompt,sharedRuntimeAuthority,sharedNativeChatService,sharedNativeCloudChat,sharedWriteObs=()=>{};const sharedMSConnectionStatus=new MSConnectionStatusSnapshot,sharedAgentMappings=new AgentMappingRegistry;let sharedGatewayClient,sharedRuntimeOwner,sharedAgentProjection,sharedRuntimeAgentCapabilities,sharedMcpProjection,sharedMcpCredentialVault;const sharedMessageClientOwner=new BeeosClawMessageClientProcessOwner;let sharedActiveMessageConsumer,sharedInboundExecutionJournal;const sharedTerminalManager=new TerminalManager;let _initializing=!1,_pluginRegisteredAt=0,_fullRuntimeRegistered=!1;const cachedCapabilityTools=[];let rawRegisterTool,wrappedRegisterTool;const cachedRuntimeServices=[],cachedRuntimeHooks=[];let rawRegisterService,wrappedRegisterService,rawOn,wrappedOn;function cacheRuntimeRegistrations(e){const t=e.registerService===wrappedRegisterService?rawRegisterService:e.registerService;if(rawRegisterService=t,wrappedRegisterService=r=>{cachedRuntimeServices.push(r),t.call(e,r)},e.registerService=wrappedRegisterService,cachedRuntimeServices.length=0,cachedRuntimeHooks.length=0,e.on){const t=e.on===wrappedOn?rawOn:e.on;rawOn=t,wrappedOn=(...r)=>{cachedRuntimeHooks.push(r),t.call(e,...r)},e.on=wrappedOn}}function replayRuntimeRegistrations(e){const t=e.registerService===wrappedRegisterService?rawRegisterService:e.registerService,r=e.on===wrappedOn?rawOn:e.on;for(const t of cachedRuntimeHooks)r.call(e,...t);for(const r of cachedRuntimeServices)t.call(e,r)}const ensureRegisterToolCache=e=>{const t=e.registerTool===wrappedRegisterTool?rawRegisterTool:e.registerTool;rawRegisterTool=t.bind(e),wrappedRegisterTool=(e,t)=>(cachedCapabilityTools.push({tool:e,options:t}),rawRegisterTool(e,t)),e.registerTool=wrappedRegisterTool};function agentKeyPairToIdentity(e){return{publicKeyBase64:()=>Buffer.from(e.publicKey).toString("base64"),sign:async t=>signAgentMessage(t,e.privateKey)}}let sharedPluginContext=null,unhandledRejectionObserverInstalled=!1;function installUnhandledRejectionObserver(e,t,r){unhandledRejectionObserverInstalled||(unhandledRejectionObserverInstalled=!0,process.on("unhandledRejection",r=>{const o=r instanceof Error?r.message:String(r),a=r instanceof Error?r.stack:void 0;e.logger.error?.(`[beeos-claw] unhandledRejection: ${o}${a?`\n${a}`:""}`),t({component:"plugin",domain:"fatal",name:"unhandled_rejection",severity:"error",summary:o,error:{code:"unhandled_rejection",message:o,...a?{stack:a}:{}}})}),process.on("uncaughtException",r=>{const o=r instanceof Error?r.message:String(r);e.logger.error?.(`[beeos-claw] uncaughtException: ${r instanceof Error?r.stack??r.message:String(r)}`),t({component:"plugin",domain:"fatal",name:"uncaught_exception",severity:"error",summary:o,error:{code:"uncaught_exception",message:o}})}))}function initializePlugin(e){let t,r;try{t=e.runtime?.config?.loadConfig?.()}catch{}try{r=resolveConfigWithMeta({pluginConfig:e.pluginConfig??{},openclawConfig:t})}catch(t){return e.logger.error?.(`[beeos-claw] Failed to resolve config: ${t instanceof Error?t.message:String(t)}`),null}const o=r.config,a=buildThirdPartyChannelSet(t);a.size>0&&e.logger.info?.(`[beeos-claw] Third-party channels detected: ${[...a].join(", ")}`);const n=o.log.enabled?createObsEventWriter({dir:o.log.dir,redaction:{gatewayToken:o.gateway.token},logger:e.logger}):()=>{};n({component:"plugin",domain:"lifecycle",name:"lifecycle.startup",severity:"info",payload:{pluginVersion:PLUGIN_VERSION,pid:process.pid,nodeVersion:process.version,cwd:process.cwd()}}),n({component:"plugin",domain:"config",name:"config.resolved",severity:"info",payload:{config:o,sources:r.sources,openclawConfigPath:r.openclawConfigPath}});for(const t of r.validation)n({component:"plugin",domain:"config",name:"config.validation",severity:t.severity,summary:t.message,error:{code:t.code,message:t.message,nextSteps:t.nextSteps}}),"error"===t.severity?e.logger.error?.(`[beeos-claw] ${t.message}`):e.logger.warn?.(`[beeos-claw] ${t.message}`);if(r.validation.some(e=>"error"===e.severity)&&e.logger.error?.("[beeos-claw] Plugin has configuration errors — some features may not work."),o.keyFile)try{agentKeys=loadAgentKeyPair(o.keyFile),agentGateway=o.agentGatewayUrl?new AgentGatewayClient({baseUrl:o.agentGatewayUrl,identity:agentIdentityFromKeyPair(agentKeys),onRetry:({method:t,path:r,attempt:o,delayMs:a,error:n})=>e.logger.warn?.(`[beeos-claw] Agent Gateway ${t} ${r} retry ${o} in ${a}ms: ${n instanceof Error?n.message:String(n)}`)}):null;const t=Buffer.from(agentKeys.publicKey).toString("base64");e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (publicKey: ${t})`)}catch(t){e.logger.warn?.(`[beeos-claw] Failed to load agent key pair: ${t}`),e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (no key pair — signed requests disabled)`)}else e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (no keyFile configured)`);return agentGateway&&(setUploadDeps({gateway:agentGateway,logger:e.logger}),registerLocalFileExtractor(browserScreenshotExtractor),registerLocalFileExtractor(deliverableFileExtractor),e.logger.info?.("[beeos-claw] Upload deps + local file extractors registered")),lastOpenclawConfig=t,sharedWriteObs=n,setOpenClawConfigSnapshot(t),{cfg:o,writeObs:n,thirdPartyChannels:a,openclawConfig:t}}function registerUploadTools(e,t,r){const{cfg:o,writeObs:a}=t,n=Boolean(pluginCloudRuntimeTarget(e));if(n){if(!e.on)throw new Error("native output Files Host hook unavailable");e.on("before_tool_call",nativeOutputToolCallGate)}cleanupUploadToolResultCache().catch(t=>{e.logger.warn?.(`[beeos_upload_file] cache cleanup failed on startup: ${String(t)}`)}),e.registerTool({name:BEEOS_UPLOAD_TOOL_NAME,description:BEEOS_UPLOAD_TOOL_DESCRIPTION,parameters:BEEOS_UPLOAD_TOOL_SCHEMA,async execute(t,r,i){const s=n?consumeNativeOutputTool(t):void 0,l=await executeUpload(r,agentGateway,i,s?(e,t)=>uploadNativeOutputFile(e,o.agentGatewayUrl,s,t,i,BEEOS_UPLOAD_REQUEST_TIMEOUT_MS):void 0,e.logger);return e.logger.debug?.(`[beeos_upload_file] toolCallId=${t} ok=${l.ok}`),a({component:"upload-tool",domain:"tool",name:l.ok?"upload.success":"upload.failure",severity:l.ok?"info":"warn",payload:{toolCallId:t,ok:l.ok,fileCount:l.files?.length??0,error:l.error}}),(async r=>{try{await writeUploadToolResult(t,BEEOS_UPLOAD_TOOL_NAME,r),await cleanupUploadToolResultCache()}catch(r){e.logger.warn?.(`[beeos_upload_file] persist cache failed toolCallId=${t}: ${String(r)}`)}return r})(l)}}),e.registerTool({name:BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME,description:BEEOS_DESKTOP_SCREENSHOT_TOOL_DESCRIPTION,parameters:BEEOS_DESKTOP_SCREENSHOT_TOOL_SCHEMA,async execute(t,r,o){e.logger.debug?.(`[beeos_desktop_screenshot] toolCallId=${t} params=${JSON.stringify(r)}`);const n=await executeDesktopScreenshot(r,agentGateway,o);return e.logger.debug?.(`[beeos_desktop_screenshot] toolCallId=${t} ok=${n.ok}`),a({component:"desktop-screenshot-tool",domain:"tool",name:n.ok?"desktop_screenshot.success":"desktop_screenshot.failure",severity:n.ok?"info":"warn",payload:{toolCallId:t,ok:n.ok,path:n.path,fileCount:n.files?.length??0,error:n.error}}),(async r=>{try{await writeUploadToolResult(t,BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME,r),await cleanupUploadToolResultCache()}catch(r){e.logger.warn?.(`[beeos_desktop_screenshot] persist cache failed toolCallId=${t}: ${String(r)}`)}return r})(n)}}),e.registerHttpRoute({path:"/beeos/files/stage",auth:"gateway",async handler(e,r){await handleFileStage(e,r,t.cfg)}}),e.registerHttpRoute({path:"/beeos/status",auth:"plugin",handler(e,t){handleStatusRequest(e,t,{publicKey:agentKeys?.publicKey??null,pluginVersion:PLUGIN_VERSION})}}),e.registerTool({name:BEEOS_LIST_FILES_TOOL_NAME,description:BEEOS_LIST_FILES_TOOL_DESCRIPTION,parameters:BEEOS_LIST_FILES_TOOL_SCHEMA,async execute(t,r,o){e.logger.debug?.(`[beeos_list_files] toolCallId=${t} params=${JSON.stringify(r)}`);const n=await executeListFiles(r,agentGateway,o);return a({component:"file-list-tool",domain:"tool",name:n.ok?"list_files.success":"list_files.failure",severity:n.ok?"info":"warn",payload:{toolCallId:t,ok:n.ok,fileCount:n.files?.length??0,error:n.error}}),n}}),e.registerTool(t=>({name:BEEOS_FETCH_FILE_TOOL_NAME,description:BEEOS_FETCH_FILE_TOOL_DESCRIPTION,parameters:BEEOS_FETCH_FILE_TOOL_SCHEMA,async execute(r,i,s){e.logger.debug?.(`[beeos_fetch_file] toolCallId=${r} params=${JSON.stringify(i)}`);const l=await executeFetchFile(i,agentGateway,{signal:s,workspaceDir:t.workspaceDir,...n?{native:{gatewayUrl:o.agentGatewayUrl,capability:consumeNativeOutputTool(r)}}:{}});return a({component:"file-fetch-tool",domain:"tool",name:l.ok?"fetch_file.success":"fetch_file.failure",severity:l.ok?"info":"warn",payload:{toolCallId:r,ok:l.ok,path:l.path,size:l.size,error:l.error}}),l}}),{name:BEEOS_FETCH_FILE_TOOL_NAME})}function registerServices(e,t,r){const{cfg:o,writeObs:a,thirdPartyChannels:n}=t,i=centralNativeChatEnabled()?requireCentralNativeSessionHost(e.runtime):void 0;if(sharedAutomationTurnPolicy.disable(),"function"==typeof e.on)try{e.on("before_tool_call",(e,t)=>sharedAutomationTurnPolicy.check(e.toolName,{sessionKey:t?.sessionKey,runId:t?.runId??e.runId}),{priority:100}),sharedAutomationTurnPolicy.enable()}catch{e.logger.warn?.("[beeos-claw] Automation Wake disabled: tool guard unavailable")}if("function"!=typeof e.on){if(o.messageBus.enabled)throw new Error("openclaw_before_message_write_hook_unavailable")}else registerModelCallObservationHooks((t,r)=>e.on(t,r),sharedModelCallObservationRouter),e.on("before_message_write",(t,r)=>{const o=t.sessionKey??r.sessionKey;if(!o)return void e.logger.debug?.("[before_message_write] ignored assistant write without sessionKey");sharedAssistantMessageCommitRouter.route(o,t.message)||e.logger.debug?.(`[before_message_write] no active IM commit target sessionKey=${o} active_targets=${sharedAssistantMessageCommitRouter.size()}`)}),e.on("before_tool_call",(e,t)=>{if("ask_user"!==(e.toolName||t.toolName))return;const r={sessionKey:t.sessionKey,runId:t.runId??e.runId,toolCallId:t.toolCallId??e.toolCallId};sharedQuestionBridge.observeAskUser(r),relayCentralAskUser((e,t)=>sharedGatewayClient?sharedGatewayClient.request(e,t):Promise.reject(new Error("Not connected to Gateway")),r).catch(e=>approvalLogger?.warn?.(`[question] central relay failed: ${e instanceof Error?e.message:String(e)}`))}),e.on("after_tool_call",(t,r)=>{const o=r.sessionKey,a=t.toolCallId??r.toolCallId,n=t.toolName||r.toolName;if(t.runId&&r.runId&&t.runId!==r.runId||t.toolCallId&&r.toolCallId&&t.toolCallId!==r.toolCallId||nativeHtmlDeliveryForRun(t.runId??r.runId)?.observe(n,t.params,t.result,Boolean(t.error),a),!o||!a||!n)return void e.logger.debug?.(`[after_tool_call] ignored structured result without correlation sessionKey=${o??"missing"} toolCallId=${a??"missing"}`);observeToolCallForDelivery(t,o);sharedToolResultObservationRouter.route(o,{toolCallId:a,toolName:n,rawResult:t.result,isError:Boolean(t.error)})||e.logger.debug?.(`[after_tool_call] no active IM observation target sessionKey=${o} active_targets=${sharedToolResultObservationRouter.size()}`)});const s=agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):void 0,l=join(process.env.OPENCLAW_HOME||join(homedir(),".openclaw"),"beeos"),c=sharedInboundExecutionJournal??=new FileInboundExecutionJournal(join(l,"inbound-execution-journal.v1.jsonl"));sharedMcpProjection??=new OpenClawNativeMcpProjection,!sharedMcpCredentialVault&&agentKeys&&s&&(sharedMcpCredentialVault=new LocalEncryptedCredentialReferenceVault(join(l,"mcp-credential-vault.json"),s,agentKeys.privateKey));const u=pluginCloudRuntimeTarget(e);if(setClaimedCloudRuntimeInstanceId(u),u&&(!agentKeys||!agentGateway))throw new Error("Cloud runtime authority requires an agent identity and gateway transport");const d=sharedRuntimeAuthority?.cloudTargetInstanceId;if(d&&u&&d!==u)throw new Error("Cloud runtime authority target changed during process lifetime");if(sharedRuntimeAuthority&&!d&&u&&sharedRuntimeAuthority.bindCloudTarget(u),!sharedRuntimeAuthority&&agentKeys&&agentGateway&&(sharedRuntimeAuthority=new RuntimeProductionAuthority({stateDirectory:l,gateway:agentGateway,keys:agentKeys,targetInstanceId:u,logger:e.logger,getMSConnectionStatus:e=>sharedMSConnectionStatus.get(e),identityLane:identityLaneFromEnvironment()})),sharedGatewayClient||(sharedGatewayClient=new GatewayClient({url:o.gateway.url,token:o.gateway.token||"",clientId:o.gateway.clientId,openclawCanvasCompat:!!o.openclawCanvasCompat,retry:{baseMs:o.retry.baseMs,maxMs:o.retry.maxMs,maxAttempts:o.retry.maxAttempts}}),sharedGatewayClient.on("gateway-event",(e,t)=>{sharedApprovalBridge.onGatewayEvent(e,t),sharedQuestionBridge.onGatewayEvent(e,t)})),approvalLogger??=e.logger,sharedRuntimeAgentCapabilities??={canvas:o.canvasEnabled,terminal:!1,webSsh:!1,fileSystem:!0,image:!0,audio:!1,mcp:!0,cron:!0,streaming:!0,pushNotifications:o.messageBus.enabled,...o.messageBus.enabled&&sharedAutomationTurnPolicy.isReady()&&agentGateway?{automationWake:!0}:{}},!sharedAgentProjection&&sharedRuntimeAuthority&&agentGateway){const t=sharedRuntimeAuthority;sharedAgentProjection=new AgentProjectionProduction({authority:t,stateFile:join(t.stateDirectory,"runtime-agent-projection.json"),journal:t.journal,identities:t.identities,source:new OpenClawAgentProjectionSource(()=>sharedGatewayClient),transport:new AgentGatewayHttpProjectionTransport({gateway:agentGateway,getRuntimeLeaseCredential:e=>{const r=t.authorityLease;if(!r||r.instanceId!==e.instanceId||r.leaseId!==e.leaseId||r.runtimeEpoch!==e.runtimeEpoch||r.handlerIdentity!==e.handlerIdentity)throw new Error("agent projection fenced by current runtime lease");return r.runtimeLeaseCredential},onAccepted:t=>{0!==t.size&&sharedAgentMappings.replace(t).catch(t=>{e.logger.warn?.("[agent-projection] mapping publication failed: "+(t instanceof Error?t.message:String(t)))})}}),capabilities:sharedRuntimeAgentCapabilities,logger:e.logger})}sharedRuntimeOwner??=new OpenClawRuntimeProcessOwner(sharedGatewayClient,sharedAgentProjection,e.logger);const g=sharedRuntimeOwner;sharedSessionMutationCoordinator??=new SessionMutationCoordinator(sharedSessionWriteGate,new OpenClawSessionWriteQuiescence(e.logger,{agentId:o.gateway.agentId||"main",...i?{nativeWritersQuiescent:e=>i.nativeWritersQuiescent({sessionKey:e})}:{}}),e.logger,{onRecoveryRequired:t=>{scheduleProcessRuntimeRestart(t,e.logger)}});const m=sharedSessionMutationCoordinator;if(i&&!sharedCentralPrompt){if(!sharedRuntimeAuthority?.cloudTargetInstanceId)throw new Error("central native chat requires the provisioned Cloud runtime authority");sharedCentralPrompt=createCentralNativeComposition({runtime:e.runtime,host:i,gatewayOrigin:o.agentGatewayUrl,stateDirectory:l,authority:sharedRuntimeAuthority,coordinator:m,logger:e.logger})}if(i&®isterCentralNativeMemoryTools(e),!sharedAcpServer){const t=sharedRuntimeAuthority&&agentGateway?new AgentGatewayTemplateOriginReporter({gateway:agentGateway}):void 0;sharedAcpServer=new ACPServer(o,e.logger,m,a,agentGateway??void 0,s,n,sharedTerminalManager,sharedRuntimeAuthority,void 0,sharedMcpProjection,sharedMcpCredentialVault,{gateway:g.client,agentProjection:sharedAgentProjection,markAgentProjectionDirty:()=>sharedAgentProjection?.markDirty(),templateOriginReporter:t,agentMappings:sharedAgentMappings,agentCapabilities:sharedRuntimeAgentCapabilities,createRunOutputRouter:createPeerRunOutputRouterFactory(new MessageServiceRunOutputChannel({getClient:()=>sharedMessageClientOwner.current?.client??null,logger:e.logger,writeObs:a})),runExclusive:(t,r,o)=>sharedImHotPathDeferral.runExclusive(t,r,e.logger,o)})}const p=sharedAcpServer,h=()=>sharedAgentMappings.snapshot()?.values().next().value;r.current=p,sharedMcpNativeProjectionNudge.request({registrationMode:e.registrationMode,fingerprint:fingerprintMcpServers(t.openclawConfig),logger:e.logger});const y=sharedPromptRunStore,{enabled:v,principalId:f,a2aEnabled:w}=o.messageBus;let C;!u&&o.agentGatewayUrl&&agentKeys&&(C=createBeeosClawMessageTokenProvider({agentGatewayUrl:o.agentGatewayUrl,identity:agentKeyPairToIdentity(agentKeys)}));const R=process.env.MESSAGE_RUNTIME_DELIVERY_KEY?.trim(),b=f||process.env.BEEOS_PRINCIPAL_ID||"",S=C?sharedMessageClientOwner.configure({tokenProvider:C,identityId:b,...o.messageBus.serviceUrl?{serviceUrl:o.messageBus.serviceUrl}:{},logger:e.logger,...sharedRuntimeAuthority&&R?{runtimeDelivery:{scopedDeliveryKey:R,authority:{currentLease:()=>{const e=sharedRuntimeAuthority?.authorityLease,t=sharedRuntimeAuthority?.currentConsumerBinding();return e&&t?{...e,journalStoreId:t.journalStoreId,journalGeneration:t.journalGeneration}:null}}}}:{}}):void 0,E=u&&o.messageBus.serviceUrl&&sharedRuntimeAuthority?new NodeRuntimeDeliveryPort({serviceOrigin:async()=>o.messageBus.serviceUrl},{currentLease:()=>{const e=sharedRuntimeAuthority?.authorityLease,t=sharedRuntimeAuthority?.currentConsumerBinding();return e&&t&&e.instanceId===u?{...e,journalStoreId:t.journalStoreId,journalGeneration:t.journalGeneration}:null},subscribeAuthority:e=>sharedRuntimeAuthority.subscribeAuthority(e)}):void 0;attachNativeCloudChat(e,o);const _=sharedRuntimeAuthority,O=o.messageBus.serviceUrl;S&&_&&O&&R?p.setCronConversationDelivery({deliver:async e=>{const t=_.authorityLease;if(!t)throw new Error("current runtime authority lease unavailable for cron delivery");const r=new MessageServiceCronDeliveryHttpAuthority({messageServiceUrl:O,scopedDeliveryKey:R,fetchAuthorized:(e,t)=>fetchRuntimeLeaseAttempt(e,t??{})});return await r.deliver({...e,runtimeLeaseCredential:t.runtimeLeaseCredential})}}):p.setCronConversationDelivery(void 0);const A=sharedRuntimeAuthority?.journal??new FileRuntimeCommandJournal(join(l,"runtime-command-journal.json"),void 0,void 0,{onMaintenanceError:t=>e.logger.error?.(`[runtime-journal] event=checkpoint_failed trigger=threshold error=${t instanceof Error?t.message:String(t)}`)}),I=g.createRegistrationToken();e.registerService({id:"beeos-acp",async start(){const t=Date.now(),r=_pluginRegisteredAt?t-_pluginRegisteredAt:-1;e.logger.info?.(`[beeos-claw] beeos-acp service start() begin, sincePluginRegister=${r}ms, bridge.url=${o.bridge.url||"(empty)"}`);const a=await createRuntimeServiceProductionCandidate({...agentGateway?{authorizationAdapter:new AgentGatewayGrantJwksReadinessAdapter({gateway:agentGateway})}:{},onGrantJwksWarm:t=>{t.ready?e.logger.info?.("[beeos-claw] Gateway grant keyset loaded"):e.logger.warn?.(`[beeos-claw] Gateway grant keyset not ready yet (attempt ${t.attempt}): ${t.error instanceof Error?t.error.message:String(t.error)}`)},...S&&agentGateway&&R?{transportAdapter:new RuntimeServiceTransportReadinessAdapter({gateway:agentGateway,messageService:S.nodeTransport,messageClient:S.client,configuredServiceUrl:o.messageBus.serviceUrl,scopedDeliveryKey:R})}:{},...E&&agentGateway&&o.messageBus.serviceUrl?{cloudTransportAdapter:new CloudRuntimeServiceTransportReadinessAdapter({gateway:agentGateway,configuredServiceUrl:o.messageBus.serviceUrl,runtimeDelivery:E,...sharedCentralPrompt?{centralPrompt:sharedCentralPrompt}:{},...sharedNativeCloudChat?{sessionNewConversation:sharedNativeCloudChat.sessionNewConversation,nativePrompt:{http:sharedNativeCloudChat.http,inputFiles:new NativeInputFilesHttpClient(o.agentGatewayUrl,()=>sharedRuntimeAuthority.authorityLease,(e,t)=>fetch(e,t)),runBoundary:new MessageServiceConversationRunBoundary({transport:{start:e=>E.startConversationRun(e),finish:e=>E.finishConversationRun(e)}}),host:{htmlDeliveryEnabled:o.canvasEnabled,resolveNativePromptSessionKey:(e,t)=>p.resolveNativePromptSessionKey(e,t),prepareNativePromptModel:(e,t,r)=>p.prepareNativePromptModel(e,t,r),runtime:e.runtime,pluginConfig:o,logger:e.logger,promptRunStore:y,assistantMessageCommitRouter:sharedAssistantMessageCommitRouter,toolResultObservationRouter:sharedToolResultObservationRouter,approvalStreams:sharedApprovalBridge,questionStreams:sharedQuestionBridge,modelCallObservationRouter:sharedModelCallObservationRouter,sessionMutationCoordinator:m,abortTransport:{chatAbort:(e,t)=>p.chatAbort(e,t)},activeRunAuthority:p.getActiveRunAuthority(),waitIfExclusive:(t,r)=>sharedImHotPathDeferral.waitIfExclusive(t,e.logger,r).then(()=>{})}}}:{}})}:{},commandJournal:A,poisonJournal:new FileRuntimePoisonDeliveryJournal(join(l,"runtime-poison-deliveries.json")),onConsumerDeliveryError:t=>{const r=null!==t&&"object"==typeof t?t:{},o=e=>"string"==typeof e&&e.length>0&&e.length<=256&&!/[\u0000-\u001f\u007f]/.test(e)?JSON.stringify(e):JSON.stringify("unavailable"),a="string"==typeof r.code&&/^[A-Za-z0-9_.:-]{1,64}$/.test(r.code)?r.code:"unavailable",n="number"==typeof r.status&&Number.isInteger(r.status)&&r.status>=100&&r.status<=599?String(r.status):"unavailable";e.logger.error?.(`[runtime-service] delivery worker failed before acknowledgement; delivery retained for retry: operation_id=${o(r.operationId)} delivery_id=${o(r.deliveryId)} code=${a} status=${n}`)},onConsumerLeaseStarvation:({starvedForMs:t,recovered:r})=>{const o=Math.round(t/1e3);r?e.logger.info?.(`[runtime-service] runtime authority lease restored after ${o}s without delivery reads`):e.logger.warn?.(`[runtime-service] no runtime authority lease for ${o}s; delivery reads suspended, queued runtime operations (model switch, session control) will not be consumed`)},onConsumerRequestFailure:t=>e.logger.error?.(`[runtime-service] request failed operationId=${t.operationId} method=${t.method}: ${t.error instanceof Error?t.error.stack??t.error.message:String(t.error)}`)});if(sharedRuntimeAuthority?.setRuntimeServiceMethods("ready"===a.status?a.serviceMethods:[]),sharedRuntimeAuthority?.setRuntimeResourceBindingContractRevision("ready"===a.status?a.resourceBindingContractRevision:void 0),p.setRuntimeRpcConsumerFactory("ready"===a.status?a.factory:void 0),"unavailable"===a.status?e.logger.warn?.("[runtime-service] capability fenced: "+a.blockers.map(e=>e.id).join(",")):a.capabilityBlockers.length&&e.logger.warn?.("[runtime-service] method capability fenced: "+a.capabilityBlockers.map(e=>e.method).join(",")),!o.bridge.url&&agentGateway){const t=Date.now(),r=await agentGateway.bridge.config();if(e.logger.info?.(`[beeos-claw] bridge discovery took ${Date.now()-t}ms result=${r?.url??"null"}`),r)o.bridge.url=r.url,writeDiscoveryCache({bridge:{url:r.url,discoveredAt:Date.now()}}),e.logger.info?.(`[beeos-claw] Bridge URL discovered from Agent Gateway: ${r.url}`);else{const t=readDiscoveryCache();t?.bridge?.url?(o.bridge.url=t.bridge.url,e.logger.info?.(`[beeos-claw] Bridge URL from cache (GW unreachable): ${t.bridge.url}`)):e.logger.debug?.("[beeos-claw] Bridge URL not available (no GW, no cache) — bridge disabled")}}await g.acquire(I);try{await p.start(o.bridge.url||void 0)}catch(e){throw await g.release(I),e}e.logger.info?.(`[beeos-claw] ACP Server started (total service start: ${Date.now()-t}ms)`)},async stop(){try{await g.release(I)}finally{await p.stop()}await A.checkpoint(),e.logger.info?.("[runtime-service] command journal checkpoint completed"),e.logger.info?.("[beeos-claw] ACP Server stopped")}});if(v&&void 0!==C&&C){const t=sharedMessageClientOwner.createRegistrationToken(),r=async(e,t)=>{const r=await C(e);if(!r.identityId||r.identityId!==e)throw new Error("Message SDK token identity did not match the current runtime authority");return{principalId:e,runtimeEpoch:t}},o=(e,t,r)=>({getLocalAgentId:()=>t,resolveLocalAgentId:e=>e===r?t:void 0,getDefaultPlatformAgent:()=>({instanceId:e.principalId}),ensureImInboundSession:(e,t,r,o)=>{p.ensureImInboundSession(e,t,r,o)},chatAbort:(e,t)=>p.chatAbort(e,t)}),n=sharedRuntimeAuthority?new RuntimeAuthorityMessageBusLifecycle({authority:sharedRuntimeAuthority,logger:e.logger,bus:{connect:async n=>{await sharedMessageClientOwner.acquire(t,async t=>{const i=await r(n.instanceId,n.runtimeEpoch),s=t.client,l={leaseId:n.leaseId,runtimeEpoch:n.runtimeEpoch};sharedMSConnectionStatus.bind(l);const u=new Map,d=new MessageProjectionInboundConsumer({client:s,bindings:()=>{const t=sharedRuntimeAuthority?.authorityLease;if(!t||t.instanceId!==i.principalId||t.runtimeEpoch!==i.runtimeEpoch)return[];const r=sharedAgentMappings.snapshot();return r?[...r.entries()].flatMap(([r,n])=>{if(!n.id||n.instanceId!==i.principalId)return[];let l=u.get(n.id);return l&&l.localAgentId===r||(l={localAgentId:r,inbound:createImInboundHandler({automationTurnPolicy:sharedAutomationTurnPolicy,runtime:e.runtime,pluginConfig:e.pluginConfig,client:s,localServer:o(i,r,n.id),promptRunStore:y,waitIfExclusive:(t,r)=>sharedImHotPathDeferral.waitIfExclusive(t,e.logger,r).then(()=>{}),assistantMessageCommitRouter:sharedAssistantMessageCommitRouter,toolResultObservationRouter:sharedToolResultObservationRouter,approvalStreams:sharedApprovalBridge,questionStreams:sharedQuestionBridge,modelCallObservationRouter:sharedModelCallObservationRouter,sessionMutationCoordinator:m,logger:e.logger,writeObs:a,principalIdOverride:i.principalId,activeRunAuthority:p.getActiveRunAuthority(),applyTurnModel:(e,t)=>p.applyImTurnModel(e,t),restoreTurnModel:e=>p.restoreImTurnModel(e),...agentGateway?{completeA2ATask:(t,r,o)=>completeA2ATask({gateway:agentGateway,logger:e.logger},t,r,o)}:{}})},u.set(n.id,l)),[{principalId:i.principalId,targetAgentId:n.id,runtimeEpoch:t.runtimeEpoch,inbound:l.inbound}]}):[]},executionJournal:c,logger:e.logger}),g=sharedAgentMappings.subscribe(()=>{sharedActiveMessageConsumer===d&&d.refresh()}),h=sharedRuntimeAuthority?.subscribeAuthority(()=>{sharedActiveMessageConsumer===d&&d.refresh()})??(()=>{}),v=new MessageClientTerminalStateRecovery({logger:e.logger,isCurrent:()=>{if(sharedActiveMessageConsumer!==d)return!1;const e=sharedRuntimeAuthority?.authorityLease;return null!=e&&e.instanceId===i.principalId&&e.runtimeEpoch===i.runtimeEpoch&&e.leaseId===n.leaseId&&e.handlerIdentity===n.handlerIdentity},reconnect:async()=>{if("failed"===s.getSnapshot().connection){await s.connect();try{await p.rebindRuntimeDelivery()}catch(t){e.logger.warn?.(`[beeos-claw] runtime Service delivery rebind failed after MessageClient recovery: ${t instanceof Error?t.message:String(t)}`)}}}});let f=s.getSnapshot().connection;sharedMSConnectionStatus.setIfCurrent(l,f);const w=s.subscribe(()=>{const t=s.getSnapshot();t.connection!==f&&(f=t.connection,sharedMSConnectionStatus.setIfCurrent(l,t.connection),"connected"===t.connection?(v.notifyConnected(),e.logger.info?.(`[beeos-claw] connection transport=message_service_realtime state=connected localAgentId=${p.getLocalAgentId()} principalId=${i.principalId}`)):"failed"===t.connection?(e.logger.warn?.(`[beeos-claw] connection transport=message_service_realtime state=failed principalId=${i.principalId} recoveryError=${t.recoveryError??"unknown"}`),v.notifyFailed()):"disconnected"!==t.connection&&"reconnecting"!==t.connection||e.logger.warn?.(`[beeos-claw] connection transport=message_service_realtime state=${t.connection} principalId=${i.principalId}; SDK owns reconnect/recovery`))});sharedActiveMessageConsumer=d,d.start();try{await s.connect()}catch(e){throw sharedActiveMessageConsumer===d&&(sharedActiveMessageConsumer=void 0),sharedMSConnectionStatus.resetIfCurrent(l),v.dispose(),await d.stop(),g(),h(),w(),await s.disconnect().catch(()=>{}),e}try{await p.rebindRuntimeDelivery()}catch(t){e.logger.warn?.(`[beeos-claw] runtime Service delivery rebind failed after MessageClient connect: ${t instanceof Error?t.message:String(t)}`)}return async()=>{sharedActiveMessageConsumer===d&&(sharedActiveMessageConsumer=void 0),sharedMSConnectionStatus.resetIfCurrent(l),v.dispose(),await d.stop(),h(),w(),await s.disconnect(),e.logger.info?.("[beeos-claw] MessageClient disconnected")}})},disconnect:async()=>{await sharedMessageClientOwner.release(t)}}}):void 0;e.registerService({id:"beeos-message-bus",async start(){n?n.start():e.logger.warn?.("[beeos-claw] Message bus requires runtime authority; waiting is unavailable without Agent Gateway runtime identity")},async stop(){await(n?.stop())}})}else v?e.logger.warn?.("[beeos-claw] Message bus enabled but Agent Gateway token provider is unavailable — disabled"):e.logger.info?.(`[beeos-claw] Message bus disabled (enabled=${v})`);if(o.messageBus.enabled&&u&&!sharedNativeCloudChat&&e.logger.warn?.("[beeos-claw] Cloud message bus enabled but native composition unavailable (messageBus.serviceUrl or runtime authority missing) — disabled"),!1!==w&&agentGateway){const t=e=>p.getGatewaySessionKeyForToolCall(e),r=e=>p.getMentionsForToolCall(e),o=(e,t)=>{p.broadcastNotification(e,t)},a=new TaskHandleRegistry;registerA2ATools(e,{gateway:agentGateway,logger:e.logger},a,t,r,o,()=>h()?.instanceId),e.logger.info?.("[beeos-claw] A2A tools registered (beeos_discover_agents, beeos_call_agent) via REST")}if(agentGateway&&(registerAutomationTools(e,{gateway:agentGateway,callConnectorTool:harnessConnectorToolCaller(),logger:e.logger,getDefaultAgent:()=>{const e=h();return e?{id:e.id,instanceId:e.instanceId}:void 0},getCurrentConversationId:e=>{const t=p.getGatewaySessionKeyForToolCall(e);return t?extractBeeosConversationIdFromSessionKey(t):void 0}}),e.logger.info?.("[beeos-claw] Automation tools registered (create/create_webhook/capabilities/preflight/list/get/run/runs/get_run)")),o.canvasEnabled){sharedCanvasState||(sharedCanvasState=new CanvasStateManager);const t=sharedCanvasState;if(agentGateway&&agentKeys){t.setLogger(e.logger);const r=claimedSandboxId(),a=createSandboxCanvasTokenProvider(agentGateway,r,()=>sharedRuntimeAuthority?.authorityLease),n=n=>{const i=new CanvasRelayClient({canvasRelayUrl:o.canvasRelayUrl,agentKeys:agentKeys,...r?{}:{agentId:n.id},displayName:n.displayName,avatarUrl:n.avatarUrl,tokenProvider:a,onConnected:()=>p.flushPendingCanvasLinks(),onReconnect:()=>p.onRelayReconnected(),logger:e.logger});t.setRelayClient(i),t.setAgentId(n.id),p.wireRelayActionHandler(),i.connect(),e.logger.info?.(`[beeos-claw] Canvas Relay multiplexed client connected (agentId=${n.id}, name=${n.name??"none"})`)};e.registerService(createCanvasRelayService({getAgent:r?()=>({id:`sandbox:${r}`}):h,onceAgentReady:e=>sharedAgentMappings.onceReady(e),initRelay:n,stopRelay:()=>t.getRelayClient()?.disconnect(),logger:e.logger})),e.logger.info?.("[beeos-claw] Canvas Relay configured")}else e.logger.warn?.("[beeos-claw] Canvas Relay unavailable: agentGatewayUrl or agentKeys missing");const r={stateManager:t,logger:e.logger,writeObs:e=>a(e),getActiveSessionId:e=>p.getSessionIdForToolCall(e),getPlatformAgentId:e=>p.getPlatformAgentIdForToolCall(e),getGatewaySessionKey:e=>p.getGatewaySessionKeyForToolCall(e),waitForAgentSync:()=>sharedAgentMappings.waitForSynchronization(),publishStaticHtml:createStaticCanvasHtmlPublisher(pluginCloudRuntimeTarget(e)?o.agentGatewayUrl:void 0)},i=new FormSchemaRegistry,s=buildCronSchemas(n);i.register(s.create),i.register(s.update);const l=new ResourceDescriptorRegistry;l.register(CRON_RESOURCE);const c=e=>async(t,r,o)=>(p.preMapToolCallSession(t),e(t,r));e.registerTool({name:RENDER_UI_TOOL_NAME,description:RENDER_UI_TOOL_DESCRIPTION,parameters:RENDER_UI_TOOL_SCHEMA,execute:c(createRenderUiToolExecutor(r))}),e.registerTool({name:CLOSE_UI_TOOL_NAME,description:CLOSE_UI_TOOL_DESCRIPTION,parameters:CLOSE_UI_TOOL_SCHEMA,execute:c(createCloseUiHandler(r))}),p.setCanvasState(t,{schemaRegistry:i,descriptorRegistry:l});const u=p.getFormBuilder();u&&e.registerTool({name:RENDER_FORM_TOOL_NAME,description:buildRenderFormDescription(i),parameters:RENDER_FORM_TOOL_SCHEMA,execute:c(createRenderFormHandler({registry:i,builder:u,logger:e.logger}))});const d=p.getResourceRenderer();if(d){generateActionTools(l,e,async(e,t)=>p.gatewayRequest(e,t),d,e.logger)}const g=buildToolRoutingHint(BEEOS_FILE_RESOURCE_ROUTING_RULE,BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME),m=new Set([RENDER_UI_TOOL_NAME,CLOSE_UI_TOOL_NAME,RENDER_FORM_TOOL_NAME]),y=256,v=new Map;if("function"==typeof e.on){try{e.on("before_prompt_build",(e,t)=>{if(t?.sessionKey){if(v.size>=y&&!v.has(t.sessionKey)){const e=v.keys().next().value;void 0!==e&&v.delete(e)}v.set(t.sessionKey,t.channelId),rememberDeliveryWorkspace(t.sessionKey,t.workspaceDir)}const r=isThirdPartyChannel(n,{sessionKey:t?.sessionKey,channelId:t?.channelId});return t?.sessionKey||r?{appendSystemContext:buildAppendSystemContext({thirdParty:r,canvasSystemPrompt:`${CANVAS_PRESENTATION_GATE}\n\n${CANVAS_SYSTEM_PROMPT}`,toolRoutingHint:g})}:{appendSystemContext:g}}),e.logger.debug?.("[beeos-claw] Canvas system prompt hook registered: before_prompt_build")}catch{e.logger.debug?.("[beeos-claw] before_prompt_build hook not supported")}try{e.on("before_tool_call",(e,t)=>{if(t?.sessionKey&&p.setPendingToolCallSessionKey(t.sessionKey),!m.has(e.toolName))return;const r=t?.sessionKey?v.get(t.sessionKey):void 0,o=isThirdPartyChannel(n,{sessionKey:t?.sessionKey,channelId:r}),a=canvasToolBlockReason({thirdParty:o,hasSession:Boolean(t?.sessionKey)});return a?{block:!0,blockReason:a}:void 0}),e.logger.debug?.("[beeos-claw] Canvas tool guard registered: before_tool_call")}catch{e.logger.debug?.("[beeos-claw] before_tool_call hook not supported")}}e.logger.info?.("[beeos-claw] Canvas tools registered (render_ui, close_ui, render_form + auto-action tools)")}else e.logger.info?.("[beeos-claw] Canvas disabled by config (canvasEnabled=false)");if(o.bridge.shell.enabled&&!0===o.legacyTerminalWsEnabled){const t=createTerminalWebSocketService({config:{port:o.terminalWsPort,token:agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):"",allowedOrigins:o.terminalWsAllowedOrigins},terminalMgr:sharedTerminalManager,logger:e.logger,writeObs:a});e.registerService({id:"beeos-terminal-ws",start(){t.start(),e.logger.info?.(`[beeos-claw] Terminal WS started on port ${o.terminalWsPort}`)},stop(){t.stop(),e.logger.info?.("[beeos-claw] Terminal WS stopped")}})}else o.bridge.shell.enabled?e.logger.info?.("[beeos-claw] Legacy static-token Terminal WS disabled (default)"):e.logger.info?.("[beeos-claw] Terminal/shell disabled by config (bridge.shell.enabled=false)");if(t.openclawConfig){const r=mirrorOpenClawConfig(t.openclawConfig);r.copied?e.logger.info?.(`[beeos-claw] mirrored openclaw config to ${r.destinationPath}`):e.logger.debug?.(`[beeos-claw] openclaw config mirror skipped: ${r.reason}`)}}export function pluginCloudRuntimeTarget(e){const t=e.pluginConfig?.cloudRuntimeInstanceId;return cloudRuntimeTargetInstanceId("string"==typeof t?t:claimedSandboxId())}function attachNativeCloudChat(e,t){if(sharedNativeChatService)return e.registerService(sharedNativeChatService),sharedNativeCloudChat;const r=sharedRuntimeAuthority,o=t.messageBus.serviceUrl,a=sharedAcpServer,n=sharedSessionMutationCoordinator;if(!(r&&r.cloudTargetInstanceId&&o&&a&&n))return sharedNativeCloudChat;const i=sharedNativeCloudChat??createNativeCloudChatComposition({authority:nativeCloudChatAuthorityFromRuntimeAuthority(r),serviceUrl:o,logger:e.logger});if(sharedNativeCloudChat=i,!t.messageBus.enabled)return i;const s=i,l=r;let c;const u=new Map,d=new RuntimeAuthorityMessageBusLifecycle({authority:l,logger:e.logger,bus:{connect:async t=>{c?.(),u.clear(),c=s.adapter.listen({eventTypes:["message.created"]},r=>{if(r.type===APPROVAL_DECISION_MESSAGE_TYPE&&r.senderId?.startsWith("user:")&&isApprovalDocument(r.content))return void sharedApprovalBridge.onDecision(r.content);if("user.continue"===r.type&&isQuestionResponseDocument(r.content))return void sharedQuestionBridge.onResponse(r);const o=(r.content??{}).metadata??{},i="string"==typeof o.target_agent_id?o.target_agent_id:"",l=i?((t,r)=>{const o=sharedAgentMappings.snapshot();if(o)for(const[i,l]of o.entries()){if(l.id!==r)continue;if(l.instanceId!==t.instanceId)continue;const o=`${i}\0${l.id}`;let c=u.get(o);return c||(c={localAgentId:i,inbound:createImInboundHandler({runtime:e.runtime,pluginConfig:e.pluginConfig,client:s.adapter,localServer:{getLocalAgentId:()=>i,resolveLocalAgentId:e=>e===l.id?i:void 0,getDefaultPlatformAgent:()=>({instanceId:t.instanceId}),ensureImInboundSession:(e,t,r,o)=>{a.ensureImInboundSession(e,t,r,o)},chatAbort:(e,t)=>a.chatAbort(e,t)},promptRunStore:sharedPromptRunStore,waitIfExclusive:(t,r)=>sharedImHotPathDeferral.waitIfExclusive(t,e.logger,r).then(()=>{}),assistantMessageCommitRouter:sharedAssistantMessageCommitRouter,toolResultObservationRouter:sharedToolResultObservationRouter,approvalStreams:sharedApprovalBridge,questionStreams:sharedQuestionBridge,modelCallObservationRouter:sharedModelCallObservationRouter,sessionMutationCoordinator:n,logger:e.logger,writeObs:sharedWriteObs,principalIdOverride:t.instanceId,activeRunAuthority:a.getActiveRunAuthority(),applyTurnModel:(e,t)=>a.applyImTurnModel(e,t),restoreTurnModel:e=>a.restoreImTurnModel(e),...agentGateway?{completeA2ATask:(t,r,o)=>completeA2ATask({gateway:agentGateway,logger:e.logger},t,r,o)}:{}})},u.set(o,c)),c}})(t,i):void 0;if(!l)return void e.logger.warn?.(`[beeos-claw] native cloud chat dropped unresolvable target_agent_id=${i||"missing"} message_id=${r.id}`);("chat_cancel"===r.type?l.inbound.onChatCancel(r):l.inbound.onChatMessage(r)).catch(t=>{e.logger.error?.(`[beeos-claw] native cloud chat dispatch failed message_id=${r.id}: ${t instanceof Error?t.message:String(t)}`)})});try{await s.adapter.connect()}catch(e){throw c?.(),c=void 0,e}},disconnect:async()=>{c?.(),c=void 0,u.clear(),await s.adapter.disconnect()}}});return sharedNativeChatService={id:"beeos-native-cloud-chat",async start(){d.start()},async stop(){await d.stop()}},e.registerService(sharedNativeChatService),e.logger.info?.("[beeos-claw] native Cloud personal-chat composition registered"),i}const plugin={id:"beeos-claw",name:"beeos-claw",description:"BeeOS platform bridge plugin for OpenClaw. Provides file upload/download, ACP bridge, and observability.",version:PLUGIN_VERSION,register(e){if(_initializing)return;registerCentralNativeContextEngine(e),registerSandboxNativeActivation(e,()=>{if(!sharedSessionMutationCoordinator)throw new Error("native session writer coordinator is unavailable");return sharedSessionMutationCoordinator.activeMutationCount},createSandboxNativeTargetLookup(()=>sharedRuntimeAuthority,()=>sharedGatewayClient));const t=pluginCloudRuntimeTarget(e),r=void 0!==t&&t!==sharedRuntimeAuthority?.cloudTargetInstanceId,o=planPluginRegistration(e.registrationMode,_fullRuntimeRegistered,r);if("skip"!==o){_initializing=!0;try{if(!hasRuntimeReplyApi(e.runtime))throw e.logger.error?.("[beeos-claw] FATAL: OpenClaw runtime.channel.reply.dispatchReplyFromConfig not exposed. Upgrade OpenClaw or revert beeos-claw."),new Error("openclaw_runtime_reply_api_unavailable");const t=(t,r)=>{registerUploadTools(e,t,r),registerArouterLatencyRouting(e),registerArouterMediaProviders(e)};if("capabilities"===o&&sharedPluginContext){if(cachedCapabilityTools.length>0){const t=resolveCapabilityToolReplay({currentRegisterTool:e.registerTool,wrappedRegisterTool:wrappedRegisterTool,originalRegisterTool:rawRegisterTool}),r=replayCachedPluginTools((r,o)=>t.call(e,r,o),cachedCapabilityTools);return registerArouterLatencyRouting(e),registerArouterMediaProviders(e),void e.logger.info?.(`[beeos-claw] capability re-register mode=${e.registrationMode} tools_only count=${r}`)}const r={current:sharedAcpServer??null};return t(sharedPluginContext,r),registerServices(e,sharedPluginContext,r),void e.logger.info?.(`[beeos-claw] capability re-register mode=${e.registrationMode} capabilities_only`)}const r=initializePlugin(e);if(!r)return;const a={current:null};installUnhandledRejectionObserver(e,r.writeObs,a),ensureRegisterToolCache(e),cacheRuntimeRegistrations(e),cachedCapabilityTools.length=0,t(r,a),agentGateway&&(e.on?e.on("before_agent_finalize",async(e,t)=>{if(await fileDeliveryFinalizeDecision(e),!e.runId||!t?.runId||e.runId===t.runId)return nativeHtmlDeliveryForRun(e.runId??t?.runId)?.beforeFinalize(e)}):e.logger.warn?.("[file-delivery] OpenClaw plugin hooks unavailable; finalization check disabled")),registerServices(e,r,a),sharedPluginContext=r,marksFullRuntimeRegistered(e.registrationMode,o)&&(_fullRuntimeRegistered=!0),_pluginRegisteredAt=Date.now(),e.logger.info?.("[beeos-claw] Plugin registered successfully")}finally{_initializing=!1}}else if(!e.registrationMode||"full"===e.registrationMode){const t=resolveCapabilityToolReplay({currentRegisterTool:e.registerTool,wrappedRegisterTool:wrappedRegisterTool,originalRegisterTool:rawRegisterTool});replayCachedPluginTools((r,o)=>t.call(e,r,o),cachedCapabilityTools),replayRuntimeRegistrations(e),registerArouterLatencyRouting(e),registerArouterMediaProviders(e)}}};export default plugin;
|
|
1
|
+
import{claimedSandboxId,identityLaneFromEnvironment}from"./runtime/identity-lane-lease.js";import{createCentralNativeComposition,requireCentralNativeSessionHost}from"./runtime/central-native-composition.js";import{createSandboxNativeTargetLookup,registerSandboxNativeActivation}from"./runtime/sandbox-native-activation.js";import{registerCentralNativeMemoryTools}from"./runtime/central-native-memory.js";import{harnessConnectorToolCaller}from"./connectors/harness-connector-mcp.js";import{registerCentralNativeContextEngine,centralNativeChatEnabled}from"./runtime/central-native-runtime.js";import{relayCentralAskUser}from"./runtime/central-native-interactions.js";import{consumeNativeOutputTool,nativeHtmlDeliveryForRun}from"./runtime/native-output-file-attempt.js";import{uploadNativeOutputFile}from"./upload/upload-file.js";import{nativeOutputToolCallGate}from"./upload/native-output-tool-hook.js";import{NativeInputFilesHttpClient}from"./runtime/native-input-files-http.js";import{fileDeliveryFinalizeDecision}from"./upload/finalize-hook.js";import{resolveConfigWithMeta,mirrorOpenClawConfig}from"./config.js";import{hasRuntimeReplyApi}from"./runtime/reply-router.js";import{PromptRunStore}from"./runtime/prompt-run-store.js";import{createMcpNativeProjectionNudge,fingerprintMcpServers}from"./acp-gateway/mcp-native-projection-nudge.js";import{createImHotPathDeferral}from"./runtime/im-hot-path-deferral.js";import{SessionWriteGate}from"./acp-gateway/session-write-gate.js";import{OpenClawSessionWriteQuiescence}from"./runtime/openclaw-session-write-quiescence.js";import{SessionMutationCoordinator}from"./runtime/session-mutation-coordinator.js";import{scheduleProcessRuntimeRestart}from"./runtime/runtime-restart-scheduler.js";import{createImInboundHandler}from"./im-inbound-handler.js";import{AgentGatewayClient,NodeRuntimeDeliveryPort,agentIdentityFromKeyPair,loadAgentKeyPair,signAgentMessage}from"@beeos-ai/cloud-harness-sdk";import{MessageServiceConversationRunBoundary}from"./runtime/message-service-conversation-run-boundary.js";import{AutomationTurnPolicy}from"./automation/turn-policy.js";import{registerAutomationTools}from"./automation/tools.js";import{extractBeeosConversationIdFromSessionKey}from"./runtime/openclaw-session-key-resolution.js";import{setOpenClawConfigSnapshot}from"./runtime/openclaw-session-model.js";import{BeeosClawMessageClientProcessOwner,createBeeosClawMessageTokenProvider}from"./message-client-composition.js";import{MessageProjectionInboundConsumer}from"./message-projection-inbound-consumer.js";import{MessageClientTerminalStateRecovery}from"./runtime/message-client-terminal-state-recovery.js";import{RuntimeAuthorityMessageBusLifecycle}from"./runtime/runtime-authority-message-bus-lifecycle.js";import{createNativeCloudChatComposition,nativeCloudChatAuthorityFromRuntimeAuthority}from"./runtime/native-cloud-chat-composition.js";import{MSConnectionStatusSnapshot}from"./runtime/ms-connection-status.js";import{FileInboundExecutionJournal}from"./inbound-execution-journal.js";import{completeA2ATask,registerA2ATools,TaskHandleRegistry}from"./a2a/tools.js";import{BEEOS_UPLOAD_TOOL_NAME,BEEOS_UPLOAD_TOOL_SCHEMA,BEEOS_UPLOAD_TOOL_DESCRIPTION,REQUEST_TIMEOUT_MS as BEEOS_UPLOAD_REQUEST_TIMEOUT_MS,executeUpload}from"./upload/tool.js";import{BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME,BEEOS_DESKTOP_SCREENSHOT_TOOL_SCHEMA,BEEOS_DESKTOP_SCREENSHOT_TOOL_DESCRIPTION,executeDesktopScreenshot}from"./upload/desktop-screenshot-tool.js";import{BEEOS_LIST_FILES_TOOL_NAME,BEEOS_LIST_FILES_TOOL_SCHEMA,BEEOS_LIST_FILES_TOOL_DESCRIPTION,executeListFiles}from"./files/list-tool.js";import{BEEOS_FETCH_FILE_TOOL_NAME,BEEOS_FETCH_FILE_TOOL_SCHEMA,BEEOS_FETCH_FILE_TOOL_DESCRIPTION,executeFetchFile}from"./files/fetch-tool.js";import{writeUploadToolResult,cleanupUploadToolResultCache}from"./upload/result-cache.js";import{handleFileStage}from"./upload/file-stage.js";import{handleStatusRequest}from"./status.js";import{ACPServer}from"./acp-server.js";import{GatewayClient}from"./gateway-client.js";import{createObsEventWriter}from"./observability.js";import{resolvePluginVersion}from"./plugin-version.js";import{createTerminalWebSocketService}from"./terminal/websocket.js";import{TerminalManager}from"./terminal/session-manager.js";import{readDiscoveryCache,writeDiscoveryCache}from"./discovery-cache.js";import{setClaimedCloudRuntimeInstanceId,setUploadDeps}from"./upload/upload-file.js";import{registerLocalFileExtractor}from"./upload/local-file-extractors.js";import{browserScreenshotExtractor}from"./browser/screenshot-extractor.js";import{deliverableFileExtractor}from"./upload/deliverable-extractor.js";import{observeToolCallForDelivery,rememberDeliveryWorkspace}from"./upload/delivery-observe.js";import{BEEOS_FILE_RESOURCE_ROUTING_RULE}from"./files/beeos-file-uri.js";import{marksFullRuntimeRegistered,planPluginRegistration,replayCachedPluginTools,resolveCapabilityToolReplay}from"./plugin-registration-plan.js";import{buildAppendSystemContext,buildToolRoutingHint,canvasToolBlockReason}from"./prompt-system-context.js";import{CanvasStateManager}from"./canvas/state.js";import{createStaticCanvasHtmlPublisher}from"./canvas/static-html.js";import{CanvasRelayClient}from"./canvas/relay-client.js";import{createSandboxCanvasTokenProvider}from"./canvas/runtime-lease-token.js";import{createCanvasRelayService}from"./canvas/relay-service.js";import{RENDER_UI_TOOL_NAME,RENDER_UI_TOOL_DESCRIPTION,RENDER_UI_TOOL_SCHEMA,CLOSE_UI_TOOL_NAME,CLOSE_UI_TOOL_DESCRIPTION,CLOSE_UI_TOOL_SCHEMA,createRenderUiToolExecutor,createCloseUiHandler,CANVAS_PRESENTATION_GATE,CANVAS_SYSTEM_PROMPT}from"./canvas/tools.js";import{FormSchemaRegistry}from"./surface/form-schema-registry.js";import{buildCronSchemas}from"./surface/cron-schemas.js";import{RENDER_FORM_TOOL_NAME,RENDER_FORM_TOOL_SCHEMA,buildRenderFormDescription,createRenderFormHandler}from"./surface/render-form-tool.js";import{ResourceDescriptorRegistry}from"./surface/resource-descriptor-registry.js";import{CRON_RESOURCE}from"./surface/cron-resource.js";import{generateActionTools}from"./surface/action-tool-generator.js";import{buildThirdPartyChannelSet,isThirdPartyChannel}from"./channel-detection.js";import{registerArouterMediaProviders}from"./media/index.js";import{homedir}from"node:os";import{join}from"node:path";import{RuntimeProductionAuthority,cloudRuntimeTargetInstanceId}from"./runtime/runtime-production-authority.js";import{FileRuntimeCommandJournal}from"./runtime/runtime-command-journal.js";import{FileRuntimePoisonDeliveryJournal}from"./runtime/runtime-poison-delivery-journal.js";import{OpenClawNativeMcpProjection}from"./acp-gateway/openclaw-native-mcp-projection.js";import{LocalEncryptedCredentialReferenceVault}from"./acp-gateway/mcp-credential-reference-port.js";import{AgentGatewayGrantJwksReadinessAdapter,CloudRuntimeServiceTransportReadinessAdapter,RuntimeServiceTransportReadinessAdapter,createRuntimeServiceProductionCandidate}from"./runtime/runtime-service-production-candidate.js";import{fetchRuntimeLeaseAttempt}from"./runtime/message-service-runtime-authenticated-fetch.js";import{MessageServiceCronDeliveryHttpAuthority}from"./runtime/message-service-cron-delivery-http-authority.js";import{AgentMappingRegistry}from"./runtime/agent-mapping-registry.js";import{OpenClawRuntimeProcessOwner}from"./runtime/openclaw-runtime-process-owner.js";import{AgentGatewayHttpProjectionTransport,AgentGatewayTemplateOriginReporter,AgentProjectionProduction,OpenClawAgentProjectionSource}from"./runtime/agent-projection-production.js";import{MessageServiceRunOutputChannel}from"./runtime/message-service-run-output-channel.js";import{AssistantMessageCommitRouter}from"./runtime/assistant-message-commit-router.js";import{OpenClawApprovalBridge}from"./approval/bridge.js";import{APPROVAL_DECISION_MESSAGE_TYPE,isApprovalDocument}from"./approval/protocol.generated.js";import{isQuestionResponseDocument,OpenClawQuestionBridge}from"./question/bridge.js";import{ToolResultObservationRouter}from"./runtime/tool-result-observation-router.js";import{ModelCallObservationRouter,registerModelCallObservationHooks}from"./runtime/model-call-observability.js";import{registerArouterLatencyRouting}from"./runtime/arouter-latency-routing.js";import{createPeerRunOutputRouterFactory}from"./runtime/run-output-composition.js";const PLUGIN_VERSION=resolvePluginVersion();let agentKeys=null,agentGateway=null,sharedCanvasState=null,sharedAcpServer=null;const sharedSessionWriteGate=new SessionWriteGate,sharedPromptRunStore=new PromptRunStore,sharedAutomationTurnPolicy=new AutomationTurnPolicy;let lastOpenclawConfig;const sharedMcpNativeProjectionNudge=createMcpNativeProjectionNudge({getActiveImRunCount:()=>sharedPromptRunStore.size(),nudge:()=>{sharedAcpServer?.nudgeMcpNativeProjection()}}),sharedImHotPathDeferral=createImHotPathDeferral({getActiveImRunCount:()=>sharedPromptRunStore.size()});sharedPromptRunStore.setOnBecameIdle(()=>{sharedMcpNativeProjectionNudge.flushIfIdle({fingerprint:fingerprintMcpServers(lastOpenclawConfig)}),sharedImHotPathDeferral.notifyIdle()});const sharedAssistantMessageCommitRouter=new AssistantMessageCommitRouter,sharedToolResultObservationRouter=new ToolResultObservationRouter;let approvalLogger;const sharedApprovalBridge=new OpenClawApprovalBridge({request:(e,t)=>sharedGatewayClient?sharedGatewayClient.request(e,t):Promise.reject(new Error("Not connected to Gateway")),logger:{info:e=>approvalLogger?.info?.(e),warn:e=>approvalLogger?.warn?.(e)}}),sharedQuestionBridge=new OpenClawQuestionBridge({request:(e,t)=>sharedGatewayClient?sharedGatewayClient.request(e,t):Promise.reject(new Error("Not connected to Gateway")),logger:{info:e=>approvalLogger?.info?.(e),warn:e=>approvalLogger?.warn?.(e)}}),sharedModelCallObservationRouter=new ModelCallObservationRouter;let sharedSessionMutationCoordinator,sharedCentralPrompt,sharedRuntimeAuthority,sharedNativeChatService,sharedNativeCloudChat,sharedWriteObs=()=>{};const sharedMSConnectionStatus=new MSConnectionStatusSnapshot,sharedAgentMappings=new AgentMappingRegistry;let sharedGatewayClient,sharedRuntimeOwner,sharedAgentProjection,sharedRuntimeAgentCapabilities,sharedMcpProjection,sharedMcpCredentialVault;const sharedMessageClientOwner=new BeeosClawMessageClientProcessOwner;let sharedActiveMessageConsumer,sharedInboundExecutionJournal;const sharedTerminalManager=new TerminalManager;let _initializing=!1,_pluginRegisteredAt=0,_fullRuntimeRegistered=!1;const cachedCapabilityTools=[];let rawRegisterTool,wrappedRegisterTool;const cachedRuntimeServices=[],cachedRuntimeHooks=[];let rawRegisterService,wrappedRegisterService,rawOn,wrappedOn;function cacheRuntimeRegistrations(e){const t=e.registerService===wrappedRegisterService?rawRegisterService:e.registerService;if(rawRegisterService=t,wrappedRegisterService=r=>{cachedRuntimeServices.push(r),t.call(e,r)},e.registerService=wrappedRegisterService,cachedRuntimeServices.length=0,cachedRuntimeHooks.length=0,e.on){const t=e.on===wrappedOn?rawOn:e.on;rawOn=t,wrappedOn=(...r)=>{cachedRuntimeHooks.push(r),t.call(e,...r)},e.on=wrappedOn}}function replayRuntimeRegistrations(e){const t=e.registerService===wrappedRegisterService?rawRegisterService:e.registerService,r=e.on===wrappedOn?rawOn:e.on;for(const t of cachedRuntimeHooks)r.call(e,...t);for(const r of cachedRuntimeServices)t.call(e,r)}const ensureRegisterToolCache=e=>{const t=e.registerTool===wrappedRegisterTool?rawRegisterTool:e.registerTool;rawRegisterTool=t.bind(e),wrappedRegisterTool=(e,t)=>(cachedCapabilityTools.push({tool:e,options:t}),rawRegisterTool(e,t)),e.registerTool=wrappedRegisterTool};function agentKeyPairToIdentity(e){return{publicKeyBase64:()=>Buffer.from(e.publicKey).toString("base64"),sign:async t=>signAgentMessage(t,e.privateKey)}}let sharedPluginContext=null,unhandledRejectionObserverInstalled=!1;function installUnhandledRejectionObserver(e,t,r){unhandledRejectionObserverInstalled||(unhandledRejectionObserverInstalled=!0,process.on("unhandledRejection",r=>{const o=r instanceof Error?r.message:String(r),a=r instanceof Error?r.stack:void 0;e.logger.error?.(`[beeos-claw] unhandledRejection: ${o}${a?`\n${a}`:""}`),t({component:"plugin",domain:"fatal",name:"unhandled_rejection",severity:"error",summary:o,error:{code:"unhandled_rejection",message:o,...a?{stack:a}:{}}})}),process.on("uncaughtException",r=>{const o=r instanceof Error?r.message:String(r);e.logger.error?.(`[beeos-claw] uncaughtException: ${r instanceof Error?r.stack??r.message:String(r)}`),t({component:"plugin",domain:"fatal",name:"uncaught_exception",severity:"error",summary:o,error:{code:"uncaught_exception",message:o}})}))}function initializePlugin(e){let t,r;try{t=e.runtime?.config?.loadConfig?.()}catch{}try{r=resolveConfigWithMeta({pluginConfig:e.pluginConfig??{},openclawConfig:t})}catch(t){return e.logger.error?.(`[beeos-claw] Failed to resolve config: ${t instanceof Error?t.message:String(t)}`),null}const o=r.config,a=buildThirdPartyChannelSet(t);a.size>0&&e.logger.info?.(`[beeos-claw] Third-party channels detected: ${[...a].join(", ")}`);const n=o.log.enabled?createObsEventWriter({dir:o.log.dir,redaction:{gatewayToken:o.gateway.token},logger:e.logger}):()=>{};n({component:"plugin",domain:"lifecycle",name:"lifecycle.startup",severity:"info",payload:{pluginVersion:PLUGIN_VERSION,pid:process.pid,nodeVersion:process.version,cwd:process.cwd()}}),n({component:"plugin",domain:"config",name:"config.resolved",severity:"info",payload:{config:o,sources:r.sources,openclawConfigPath:r.openclawConfigPath}});for(const t of r.validation)n({component:"plugin",domain:"config",name:"config.validation",severity:t.severity,summary:t.message,error:{code:t.code,message:t.message,nextSteps:t.nextSteps}}),"error"===t.severity?e.logger.error?.(`[beeos-claw] ${t.message}`):e.logger.warn?.(`[beeos-claw] ${t.message}`);if(r.validation.some(e=>"error"===e.severity)&&e.logger.error?.("[beeos-claw] Plugin has configuration errors — some features may not work."),o.keyFile)try{agentKeys=loadAgentKeyPair(o.keyFile),agentGateway=o.agentGatewayUrl?new AgentGatewayClient({baseUrl:o.agentGatewayUrl,identity:agentIdentityFromKeyPair(agentKeys),onRetry:({method:t,path:r,attempt:o,delayMs:a,error:n})=>e.logger.warn?.(`[beeos-claw] Agent Gateway ${t} ${r} retry ${o} in ${a}ms: ${n instanceof Error?n.message:String(n)}`)}):null;const t=Buffer.from(agentKeys.publicKey).toString("base64");e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (publicKey: ${t})`)}catch(t){e.logger.warn?.(`[beeos-claw] Failed to load agent key pair: ${t}`),e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (no key pair — signed requests disabled)`)}else e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (no keyFile configured)`);return agentGateway&&(setUploadDeps({gateway:agentGateway,logger:e.logger}),registerLocalFileExtractor(browserScreenshotExtractor),registerLocalFileExtractor(deliverableFileExtractor),e.logger.info?.("[beeos-claw] Upload deps + local file extractors registered")),lastOpenclawConfig=t,sharedWriteObs=n,setOpenClawConfigSnapshot(t),{cfg:o,writeObs:n,thirdPartyChannels:a,openclawConfig:t}}function registerUploadTools(e,t,r){const{cfg:o,writeObs:a}=t,n=Boolean(pluginCloudRuntimeTarget(e));if(n){if(!e.on)throw new Error("native output Files Host hook unavailable");e.on("before_tool_call",nativeOutputToolCallGate)}cleanupUploadToolResultCache().catch(t=>{e.logger.warn?.(`[beeos_upload_file] cache cleanup failed on startup: ${String(t)}`)}),e.registerTool({name:BEEOS_UPLOAD_TOOL_NAME,description:BEEOS_UPLOAD_TOOL_DESCRIPTION,parameters:BEEOS_UPLOAD_TOOL_SCHEMA,async execute(t,r,i){const s=n?consumeNativeOutputTool(t):void 0,l=await executeUpload(r,agentGateway,i,s?(e,t)=>uploadNativeOutputFile(e,o.agentGatewayUrl,s,t,i,BEEOS_UPLOAD_REQUEST_TIMEOUT_MS):void 0,e.logger);return e.logger.debug?.(`[beeos_upload_file] toolCallId=${t} ok=${l.ok}`),a({component:"upload-tool",domain:"tool",name:l.ok?"upload.success":"upload.failure",severity:l.ok?"info":"warn",payload:{toolCallId:t,ok:l.ok,fileCount:l.files?.length??0,error:l.error}}),(async r=>{try{await writeUploadToolResult(t,BEEOS_UPLOAD_TOOL_NAME,r),await cleanupUploadToolResultCache()}catch(r){e.logger.warn?.(`[beeos_upload_file] persist cache failed toolCallId=${t}: ${String(r)}`)}return r})(l)}}),e.registerTool({name:BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME,description:BEEOS_DESKTOP_SCREENSHOT_TOOL_DESCRIPTION,parameters:BEEOS_DESKTOP_SCREENSHOT_TOOL_SCHEMA,async execute(t,r,o){e.logger.debug?.(`[beeos_desktop_screenshot] toolCallId=${t} params=${JSON.stringify(r)}`);const n=await executeDesktopScreenshot(r,agentGateway,o);return e.logger.debug?.(`[beeos_desktop_screenshot] toolCallId=${t} ok=${n.ok}`),a({component:"desktop-screenshot-tool",domain:"tool",name:n.ok?"desktop_screenshot.success":"desktop_screenshot.failure",severity:n.ok?"info":"warn",payload:{toolCallId:t,ok:n.ok,path:n.path,fileCount:n.files?.length??0,error:n.error}}),(async r=>{try{await writeUploadToolResult(t,BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME,r),await cleanupUploadToolResultCache()}catch(r){e.logger.warn?.(`[beeos_desktop_screenshot] persist cache failed toolCallId=${t}: ${String(r)}`)}return r})(n)}}),e.registerHttpRoute({path:"/beeos/files/stage",auth:"gateway",async handler(e,r){await handleFileStage(e,r,t.cfg)}}),e.registerHttpRoute({path:"/beeos/status",auth:"plugin",handler(e,t){handleStatusRequest(e,t,{publicKey:agentKeys?.publicKey??null,pluginVersion:PLUGIN_VERSION})}}),e.registerTool({name:BEEOS_LIST_FILES_TOOL_NAME,description:BEEOS_LIST_FILES_TOOL_DESCRIPTION,parameters:BEEOS_LIST_FILES_TOOL_SCHEMA,async execute(t,r,o){e.logger.debug?.(`[beeos_list_files] toolCallId=${t} params=${JSON.stringify(r)}`);const n=await executeListFiles(r,agentGateway,o);return a({component:"file-list-tool",domain:"tool",name:n.ok?"list_files.success":"list_files.failure",severity:n.ok?"info":"warn",payload:{toolCallId:t,ok:n.ok,fileCount:n.files?.length??0,error:n.error}}),n}}),e.registerTool(t=>({name:BEEOS_FETCH_FILE_TOOL_NAME,description:BEEOS_FETCH_FILE_TOOL_DESCRIPTION,parameters:BEEOS_FETCH_FILE_TOOL_SCHEMA,async execute(r,i,s){e.logger.debug?.(`[beeos_fetch_file] toolCallId=${r} params=${JSON.stringify(i)}`);const l=await executeFetchFile(i,agentGateway,{signal:s,workspaceDir:t.workspaceDir,...n?{native:{gatewayUrl:o.agentGatewayUrl,capability:consumeNativeOutputTool(r)}}:{}});return a({component:"file-fetch-tool",domain:"tool",name:l.ok?"fetch_file.success":"fetch_file.failure",severity:l.ok?"info":"warn",payload:{toolCallId:r,ok:l.ok,path:l.path,size:l.size,error:l.error}}),l}}),{name:BEEOS_FETCH_FILE_TOOL_NAME})}function registerServices(e,t,r){const{cfg:o,writeObs:a,thirdPartyChannels:n}=t,i=centralNativeChatEnabled()?requireCentralNativeSessionHost(e.runtime):void 0;if(sharedAutomationTurnPolicy.disable(),"function"==typeof e.on)try{e.on("before_tool_call",(e,t)=>sharedAutomationTurnPolicy.check(e.toolName,{sessionKey:t?.sessionKey,runId:t?.runId??e.runId}),{priority:100}),sharedAutomationTurnPolicy.enable()}catch{e.logger.warn?.("[beeos-claw] Automation Wake disabled: tool guard unavailable")}if("function"!=typeof e.on){if(o.messageBus.enabled)throw new Error("openclaw_before_message_write_hook_unavailable")}else registerModelCallObservationHooks((t,r)=>e.on(t,r),sharedModelCallObservationRouter),e.on("before_message_write",(t,r)=>{const o=t.sessionKey??r.sessionKey;if(!o)return void e.logger.debug?.("[before_message_write] ignored assistant write without sessionKey");sharedAssistantMessageCommitRouter.route(o,t.message)||e.logger.debug?.(`[before_message_write] no active IM commit target sessionKey=${o} active_targets=${sharedAssistantMessageCommitRouter.size()}`)}),e.on("before_tool_call",(e,t)=>{if("ask_user"!==(e.toolName||t.toolName))return;const r={sessionKey:t.sessionKey,runId:t.runId??e.runId,toolCallId:t.toolCallId??e.toolCallId};sharedQuestionBridge.observeAskUser(r),relayCentralAskUser((e,t)=>sharedGatewayClient?sharedGatewayClient.request(e,t):Promise.reject(new Error("Not connected to Gateway")),r).catch(e=>approvalLogger?.warn?.(`[question] central relay failed: ${e instanceof Error?e.message:String(e)}`))}),e.on("after_tool_call",(t,r)=>{const o=r.sessionKey,a=t.toolCallId??r.toolCallId,n=t.toolName||r.toolName;if(t.runId&&r.runId&&t.runId!==r.runId||t.toolCallId&&r.toolCallId&&t.toolCallId!==r.toolCallId||nativeHtmlDeliveryForRun(t.runId??r.runId)?.observe(n,t.params,t.result,Boolean(t.error),a),!o||!a||!n)return void e.logger.debug?.(`[after_tool_call] ignored structured result without correlation sessionKey=${o??"missing"} toolCallId=${a??"missing"}`);observeToolCallForDelivery(t,o);sharedToolResultObservationRouter.route(o,{toolCallId:a,toolName:n,rawResult:t.result,isError:Boolean(t.error)})||e.logger.debug?.(`[after_tool_call] no active IM observation target sessionKey=${o} active_targets=${sharedToolResultObservationRouter.size()}`)});const s=agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):void 0,l=join(process.env.OPENCLAW_HOME||join(homedir(),".openclaw"),"beeos"),c=sharedInboundExecutionJournal??=new FileInboundExecutionJournal(join(l,"inbound-execution-journal.v1.jsonl"));sharedMcpProjection??=new OpenClawNativeMcpProjection,!sharedMcpCredentialVault&&agentKeys&&s&&(sharedMcpCredentialVault=new LocalEncryptedCredentialReferenceVault(join(l,"mcp-credential-vault.json"),s,agentKeys.privateKey));const u=pluginCloudRuntimeTarget(e);if(setClaimedCloudRuntimeInstanceId(u),u&&(!agentKeys||!agentGateway))throw new Error("Cloud runtime authority requires an agent identity and gateway transport");const d=sharedRuntimeAuthority?.cloudTargetInstanceId;if(d&&u&&d!==u)throw new Error("Cloud runtime authority target changed during process lifetime");if(sharedRuntimeAuthority&&!d&&u&&sharedRuntimeAuthority.bindCloudTarget(u),!sharedRuntimeAuthority&&agentKeys&&agentGateway&&(sharedRuntimeAuthority=new RuntimeProductionAuthority({stateDirectory:l,gateway:agentGateway,keys:agentKeys,targetInstanceId:u,logger:e.logger,getMSConnectionStatus:e=>sharedMSConnectionStatus.get(e),identityLane:identityLaneFromEnvironment()})),sharedGatewayClient||(sharedGatewayClient=new GatewayClient({url:o.gateway.url,token:o.gateway.token||"",clientId:o.gateway.clientId,openclawCanvasCompat:!!o.openclawCanvasCompat,retry:{baseMs:o.retry.baseMs,maxMs:o.retry.maxMs,maxAttempts:o.retry.maxAttempts}}),sharedGatewayClient.on("gateway-event",(e,t)=>{sharedApprovalBridge.onGatewayEvent(e,t),sharedQuestionBridge.onGatewayEvent(e,t)})),approvalLogger??=e.logger,sharedRuntimeAgentCapabilities??={canvas:o.canvasEnabled,terminal:!1,webSsh:!1,fileSystem:!0,image:!0,audio:!1,mcp:!0,cron:!0,streaming:!0,pushNotifications:o.messageBus.enabled,...o.messageBus.enabled&&sharedAutomationTurnPolicy.isReady()&&agentGateway?{automationWake:!0}:{}},!sharedAgentProjection&&sharedRuntimeAuthority&&agentGateway){const t=sharedRuntimeAuthority;sharedAgentProjection=new AgentProjectionProduction({authority:t,stateFile:join(t.stateDirectory,"runtime-agent-projection.json"),journal:t.journal,identities:t.identities,source:new OpenClawAgentProjectionSource(()=>sharedGatewayClient),transport:new AgentGatewayHttpProjectionTransport({gateway:agentGateway,getRuntimeLeaseCredential:e=>{const r=t.authorityLease;if(!r||r.instanceId!==e.instanceId||r.leaseId!==e.leaseId||r.runtimeEpoch!==e.runtimeEpoch||r.handlerIdentity!==e.handlerIdentity)throw new Error("agent projection fenced by current runtime lease");return r.runtimeLeaseCredential},onAccepted:t=>{0!==t.size&&sharedAgentMappings.replace(t).catch(t=>{e.logger.warn?.("[agent-projection] mapping publication failed: "+(t instanceof Error?t.message:String(t)))})}}),capabilities:sharedRuntimeAgentCapabilities,logger:e.logger})}sharedRuntimeOwner??=new OpenClawRuntimeProcessOwner(sharedGatewayClient,sharedAgentProjection,e.logger);const g=sharedRuntimeOwner;sharedSessionMutationCoordinator??=new SessionMutationCoordinator(sharedSessionWriteGate,new OpenClawSessionWriteQuiescence(e.logger,{agentId:o.gateway.agentId||"main",...i?{nativeWritersQuiescent:e=>i.nativeWritersQuiescent({sessionKey:e})}:{}}),e.logger,{onRecoveryRequired:t=>{scheduleProcessRuntimeRestart(t,e.logger)}});const m=sharedSessionMutationCoordinator;if(i&&!sharedCentralPrompt){if(!sharedRuntimeAuthority?.cloudTargetInstanceId)throw new Error("central native chat requires the provisioned Cloud runtime authority");sharedCentralPrompt=createCentralNativeComposition({runtime:e.runtime,host:i,gatewayOrigin:o.agentGatewayUrl,stateDirectory:l,authority:sharedRuntimeAuthority,coordinator:m,logger:e.logger})}if(i&®isterCentralNativeMemoryTools(e),!sharedAcpServer){const t=sharedRuntimeAuthority&&agentGateway?new AgentGatewayTemplateOriginReporter({gateway:agentGateway}):void 0;sharedAcpServer=new ACPServer(o,e.logger,m,a,agentGateway??void 0,s,n,sharedTerminalManager,sharedRuntimeAuthority,void 0,sharedMcpProjection,sharedMcpCredentialVault,{gateway:g.client,agentProjection:sharedAgentProjection,markAgentProjectionDirty:()=>sharedAgentProjection?.markDirty(),templateOriginReporter:t,agentMappings:sharedAgentMappings,agentCapabilities:sharedRuntimeAgentCapabilities,createRunOutputRouter:createPeerRunOutputRouterFactory(new MessageServiceRunOutputChannel({getClient:()=>sharedMessageClientOwner.current?.client??null,logger:e.logger,writeObs:a})),runExclusive:(t,r,o)=>sharedImHotPathDeferral.runExclusive(t,r,e.logger,o)})}const p=sharedAcpServer,h=()=>sharedAgentMappings.snapshot()?.values().next().value;r.current=p,sharedMcpNativeProjectionNudge.request({registrationMode:e.registrationMode,fingerprint:fingerprintMcpServers(t.openclawConfig),logger:e.logger});const y=sharedPromptRunStore,{enabled:v,principalId:w,a2aEnabled:f}=o.messageBus;let C;!u&&o.agentGatewayUrl&&agentKeys&&(C=createBeeosClawMessageTokenProvider({agentGatewayUrl:o.agentGatewayUrl,identity:agentKeyPairToIdentity(agentKeys)}));const R=process.env.MESSAGE_RUNTIME_DELIVERY_KEY?.trim(),b=w||process.env.BEEOS_PRINCIPAL_ID||"",S=C?sharedMessageClientOwner.configure({tokenProvider:C,identityId:b,...o.messageBus.serviceUrl?{serviceUrl:o.messageBus.serviceUrl}:{},logger:e.logger,...sharedRuntimeAuthority&&R?{runtimeDelivery:{scopedDeliveryKey:R,authority:{currentLease:()=>{const e=sharedRuntimeAuthority?.authorityLease,t=sharedRuntimeAuthority?.currentConsumerBinding();return e&&t?{...e,journalStoreId:t.journalStoreId,journalGeneration:t.journalGeneration}:null}}}}:{}}):void 0,E=u&&o.messageBus.serviceUrl&&sharedRuntimeAuthority?new NodeRuntimeDeliveryPort({serviceOrigin:async()=>o.messageBus.serviceUrl},{currentLease:()=>{const e=sharedRuntimeAuthority?.authorityLease,t=sharedRuntimeAuthority?.currentConsumerBinding();return e&&t&&e.instanceId===u?{...e,journalStoreId:t.journalStoreId,journalGeneration:t.journalGeneration}:null},subscribeAuthority:e=>sharedRuntimeAuthority.subscribeAuthority(e)}):void 0;attachNativeCloudChat(e,o);const O=sharedRuntimeAuthority,_=o.messageBus.serviceUrl;S&&O&&_&&R?p.setCronConversationDelivery({deliver:async e=>{const t=O.authorityLease;if(!t)throw new Error("current runtime authority lease unavailable for cron delivery");const r=new MessageServiceCronDeliveryHttpAuthority({messageServiceUrl:_,scopedDeliveryKey:R,fetchAuthorized:(e,t)=>fetchRuntimeLeaseAttempt(e,t??{})});return await r.deliver({...e,runtimeLeaseCredential:t.runtimeLeaseCredential})}}):p.setCronConversationDelivery(void 0);const A=sharedRuntimeAuthority?.journal??new FileRuntimeCommandJournal(join(l,"runtime-command-journal.json"),void 0,void 0,{onMaintenanceError:t=>e.logger.error?.(`[runtime-journal] event=checkpoint_failed trigger=threshold error=${t instanceof Error?t.message:String(t)}`)}),I=g.createRegistrationToken();e.registerService({id:"beeos-acp",async start(){const t=Date.now(),r=_pluginRegisteredAt?t-_pluginRegisteredAt:-1;e.logger.info?.(`[beeos-claw] beeos-acp service start() begin, sincePluginRegister=${r}ms, bridge.url=${o.bridge.url||"(empty)"}`);const a=await createRuntimeServiceProductionCandidate({...agentGateway?{authorizationAdapter:new AgentGatewayGrantJwksReadinessAdapter({gateway:agentGateway})}:{},onGrantJwksWarm:t=>{t.ready?e.logger.info?.("[beeos-claw] Gateway grant keyset loaded"):e.logger.warn?.(`[beeos-claw] Gateway grant keyset not ready yet (attempt ${t.attempt}): ${t.error instanceof Error?t.error.message:String(t.error)}`)},...S&&agentGateway&&R?{transportAdapter:new RuntimeServiceTransportReadinessAdapter({gateway:agentGateway,messageService:S.nodeTransport,messageClient:S.client,configuredServiceUrl:o.messageBus.serviceUrl,scopedDeliveryKey:R})}:{},...E&&agentGateway&&o.messageBus.serviceUrl?{cloudTransportAdapter:new CloudRuntimeServiceTransportReadinessAdapter({gateway:agentGateway,configuredServiceUrl:o.messageBus.serviceUrl,runtimeDelivery:E,...sharedCentralPrompt?{centralPrompt:sharedCentralPrompt}:{},...sharedNativeCloudChat?{sessionNewConversation:sharedNativeCloudChat.sessionNewConversation,nativePrompt:{http:sharedNativeCloudChat.http,inputFiles:new NativeInputFilesHttpClient(o.agentGatewayUrl,()=>sharedRuntimeAuthority.authorityLease,(e,t)=>fetch(e,t)),runBoundary:new MessageServiceConversationRunBoundary({transport:{start:e=>E.startConversationRun(e),finish:e=>E.finishConversationRun(e)}}),host:{htmlDeliveryEnabled:o.canvasEnabled,resolveNativePromptSessionKey:(e,t)=>p.resolveNativePromptSessionKey(e,t),prepareNativePromptModel:(e,t,r)=>p.prepareNativePromptModel(e,t,r),runtime:e.runtime,pluginConfig:o,logger:e.logger,promptRunStore:y,assistantMessageCommitRouter:sharedAssistantMessageCommitRouter,toolResultObservationRouter:sharedToolResultObservationRouter,approvalStreams:sharedApprovalBridge,questionStreams:sharedQuestionBridge,modelCallObservationRouter:sharedModelCallObservationRouter,sessionMutationCoordinator:m,abortTransport:{chatAbort:(e,t)=>p.chatAbort(e,t)},activeRunAuthority:p.getActiveRunAuthority(),waitIfExclusive:(t,r)=>sharedImHotPathDeferral.waitIfExclusive(t,e.logger,r).then(()=>{})}}}:{}})}:{},commandJournal:A,poisonJournal:new FileRuntimePoisonDeliveryJournal(join(l,"runtime-poison-deliveries.json")),onConsumerDeliveryError:t=>{const r=null!==t&&"object"==typeof t?t:{},o=e=>"string"==typeof e&&e.length>0&&e.length<=256&&!/[\u0000-\u001f\u007f]/.test(e)?JSON.stringify(e):JSON.stringify("unavailable"),a="string"==typeof r.code&&/^[A-Za-z0-9_.:-]{1,64}$/.test(r.code)?r.code:"unavailable",n="number"==typeof r.status&&Number.isInteger(r.status)&&r.status>=100&&r.status<=599?String(r.status):"unavailable";e.logger.error?.(`[runtime-service] delivery worker failed before acknowledgement; delivery retained for retry: operation_id=${o(r.operationId)} delivery_id=${o(r.deliveryId)} code=${a} status=${n}`)},onConsumerLeaseStarvation:({starvedForMs:t,recovered:r})=>{const o=Math.round(t/1e3);r?e.logger.info?.(`[runtime-service] runtime authority lease restored after ${o}s without delivery reads`):e.logger.warn?.(`[runtime-service] no runtime authority lease for ${o}s; delivery reads suspended, queued runtime operations (model switch, session control) will not be consumed`)},onConsumerRequestFailure:t=>e.logger.error?.(`[runtime-service] request failed operationId=${t.operationId} method=${t.method}: ${t.error instanceof Error?t.error.stack??t.error.message:String(t.error)}`)});if(sharedRuntimeAuthority?.setRuntimeServiceMethods("ready"===a.status?a.serviceMethods:[]),sharedRuntimeAuthority?.setRuntimeResourceBindingContractRevision("ready"===a.status?a.resourceBindingContractRevision:void 0),p.setRuntimeRpcConsumerFactory("ready"===a.status?a.factory:void 0),"unavailable"===a.status?e.logger.warn?.("[runtime-service] capability fenced: "+a.blockers.map(e=>e.id).join(",")):a.capabilityBlockers.length&&e.logger.warn?.("[runtime-service] method capability fenced: "+a.capabilityBlockers.map(e=>e.method).join(",")),!o.bridge.url&&agentGateway){const t=Date.now(),r=await agentGateway.bridge.config();if(e.logger.info?.(`[beeos-claw] bridge discovery took ${Date.now()-t}ms result=${r?.url??"null"}`),r)o.bridge.url=r.url,writeDiscoveryCache({bridge:{url:r.url,discoveredAt:Date.now()}}),e.logger.info?.(`[beeos-claw] Bridge URL discovered from Agent Gateway: ${r.url}`);else{const t=readDiscoveryCache();t?.bridge?.url?(o.bridge.url=t.bridge.url,e.logger.info?.(`[beeos-claw] Bridge URL from cache (GW unreachable): ${t.bridge.url}`)):e.logger.debug?.("[beeos-claw] Bridge URL not available (no GW, no cache) — bridge disabled")}}await g.acquire(I);try{await p.start(o.bridge.url||void 0)}catch(e){throw await g.release(I),e}e.logger.info?.(`[beeos-claw] ACP Server started (total service start: ${Date.now()-t}ms)`)},async stop(){try{await g.release(I)}finally{await p.stop()}await A.checkpoint(),e.logger.info?.("[runtime-service] command journal checkpoint completed"),e.logger.info?.("[beeos-claw] ACP Server stopped")}});if(v&&void 0!==C&&C){const t=sharedMessageClientOwner.createRegistrationToken(),r=async(e,t)=>{const r=await C(e);if(!r.identityId||r.identityId!==e)throw new Error("Message SDK token identity did not match the current runtime authority");return{principalId:e,runtimeEpoch:t}},o=(e,t,r)=>({getLocalAgentId:()=>t,resolveLocalAgentId:e=>e===r?t:void 0,getDefaultPlatformAgent:()=>({instanceId:e.principalId}),ensureImInboundSession:(e,t,r,o)=>{p.ensureImInboundSession(e,t,r,o)},chatAbort:(e,t)=>p.chatAbort(e,t)}),n=sharedRuntimeAuthority?new RuntimeAuthorityMessageBusLifecycle({authority:sharedRuntimeAuthority,logger:e.logger,bus:{connect:async n=>{await sharedMessageClientOwner.acquire(t,async t=>{const i=await r(n.instanceId,n.runtimeEpoch),s=t.client,l={leaseId:n.leaseId,runtimeEpoch:n.runtimeEpoch};sharedMSConnectionStatus.bind(l);const u=new Map,d=new MessageProjectionInboundConsumer({client:s,bindings:()=>{const t=sharedRuntimeAuthority?.authorityLease;if(!t||t.instanceId!==i.principalId||t.runtimeEpoch!==i.runtimeEpoch)return[];const r=sharedAgentMappings.snapshot();return r?[...r.entries()].flatMap(([r,n])=>{if(!n.id||n.instanceId!==i.principalId)return[];let l=u.get(n.id);return l&&l.localAgentId===r||(l={localAgentId:r,inbound:createImInboundHandler({automationTurnPolicy:sharedAutomationTurnPolicy,runtime:e.runtime,pluginConfig:e.pluginConfig,client:s,localServer:o(i,r,n.id),promptRunStore:y,waitIfExclusive:(t,r)=>sharedImHotPathDeferral.waitIfExclusive(t,e.logger,r).then(()=>{}),assistantMessageCommitRouter:sharedAssistantMessageCommitRouter,toolResultObservationRouter:sharedToolResultObservationRouter,approvalStreams:sharedApprovalBridge,questionStreams:sharedQuestionBridge,modelCallObservationRouter:sharedModelCallObservationRouter,sessionMutationCoordinator:m,logger:e.logger,writeObs:a,principalIdOverride:i.principalId,activeRunAuthority:p.getActiveRunAuthority(),applyTurnModel:(e,t)=>p.applyImTurnModel(e,t),restoreTurnModel:e=>p.restoreImTurnModel(e),...agentGateway?{completeA2ATask:(t,r,o)=>completeA2ATask({gateway:agentGateway,logger:e.logger},t,r,o)}:{}})},u.set(n.id,l)),[{principalId:i.principalId,targetAgentId:n.id,runtimeEpoch:t.runtimeEpoch,inbound:l.inbound}]}):[]},executionJournal:c,logger:e.logger}),g=sharedAgentMappings.subscribe(()=>{sharedActiveMessageConsumer===d&&d.refresh()}),h=sharedRuntimeAuthority?.subscribeAuthority(()=>{sharedActiveMessageConsumer===d&&d.refresh()})??(()=>{}),v=new MessageClientTerminalStateRecovery({logger:e.logger,isCurrent:()=>{if(sharedActiveMessageConsumer!==d)return!1;const e=sharedRuntimeAuthority?.authorityLease;return null!=e&&e.instanceId===i.principalId&&e.runtimeEpoch===i.runtimeEpoch&&e.leaseId===n.leaseId&&e.handlerIdentity===n.handlerIdentity},reconnect:async()=>{if("failed"===s.getSnapshot().connection){await s.connect();try{await p.rebindRuntimeDelivery()}catch(t){e.logger.warn?.(`[beeos-claw] runtime Service delivery rebind failed after MessageClient recovery: ${t instanceof Error?t.message:String(t)}`)}}}});let w=s.getSnapshot().connection;sharedMSConnectionStatus.setIfCurrent(l,w);const f=s.subscribe(()=>{const t=s.getSnapshot();t.connection!==w&&(w=t.connection,sharedMSConnectionStatus.setIfCurrent(l,t.connection),"connected"===t.connection?(v.notifyConnected(),e.logger.info?.(`[beeos-claw] connection transport=message_service_realtime state=connected localAgentId=${p.getLocalAgentId()} principalId=${i.principalId}`)):"failed"===t.connection?(e.logger.warn?.(`[beeos-claw] connection transport=message_service_realtime state=failed principalId=${i.principalId} recoveryError=${t.recoveryError??"unknown"}`),v.notifyFailed()):"disconnected"!==t.connection&&"reconnecting"!==t.connection||e.logger.warn?.(`[beeos-claw] connection transport=message_service_realtime state=${t.connection} principalId=${i.principalId}; SDK owns reconnect/recovery`))});sharedActiveMessageConsumer=d,d.start();try{await s.connect()}catch(e){throw sharedActiveMessageConsumer===d&&(sharedActiveMessageConsumer=void 0),sharedMSConnectionStatus.resetIfCurrent(l),v.dispose(),await d.stop(),g(),h(),f(),await s.disconnect().catch(()=>{}),e}try{await p.rebindRuntimeDelivery()}catch(t){e.logger.warn?.(`[beeos-claw] runtime Service delivery rebind failed after MessageClient connect: ${t instanceof Error?t.message:String(t)}`)}return async()=>{sharedActiveMessageConsumer===d&&(sharedActiveMessageConsumer=void 0),sharedMSConnectionStatus.resetIfCurrent(l),v.dispose(),await d.stop(),h(),f(),await s.disconnect(),e.logger.info?.("[beeos-claw] MessageClient disconnected")}})},disconnect:async()=>{await sharedMessageClientOwner.release(t)}}}):void 0;e.registerService({id:"beeos-message-bus",async start(){n?n.start():e.logger.warn?.("[beeos-claw] Message bus requires runtime authority; waiting is unavailable without Agent Gateway runtime identity")},async stop(){await(n?.stop())}})}else v?e.logger.warn?.("[beeos-claw] Message bus enabled but Agent Gateway token provider is unavailable — disabled"):e.logger.info?.(`[beeos-claw] Message bus disabled (enabled=${v})`);if(o.messageBus.enabled&&u&&!sharedNativeCloudChat&&e.logger.warn?.("[beeos-claw] Cloud message bus enabled but native composition unavailable (messageBus.serviceUrl or runtime authority missing) — disabled"),!1!==f&&agentGateway){const t=e=>p.getGatewaySessionKeyForToolCall(e),r=e=>p.getMentionsForToolCall(e),o=(e,t)=>{p.broadcastNotification(e,t)},a=new TaskHandleRegistry;registerA2ATools(e,{gateway:agentGateway,logger:e.logger},a,t,r,o,()=>h()?.instanceId),e.logger.info?.("[beeos-claw] A2A tools registered (beeos_discover_agents, beeos_call_agent) via REST")}if(agentGateway&&(registerAutomationTools(e,{gateway:agentGateway,callConnectorTool:harnessConnectorToolCaller(),logger:e.logger,getDefaultAgent:()=>{const e=h();return e?{id:e.id,instanceId:e.instanceId}:void 0},getCurrentConversationId:e=>{const t=p.getGatewaySessionKeyForToolCall(e);return t?extractBeeosConversationIdFromSessionKey(t):void 0}}),e.logger.info?.("[beeos-claw] Automation tools registered (create/create_webhook/capabilities/preflight/list/get/run/runs/get_run)")),o.canvasEnabled){sharedCanvasState||(sharedCanvasState=new CanvasStateManager);const t=sharedCanvasState;if(agentGateway&&agentKeys){t.setLogger(e.logger);const r=claimedSandboxId(),a=createSandboxCanvasTokenProvider(agentGateway,r,()=>sharedRuntimeAuthority?.authorityLease),n=n=>{const i=new CanvasRelayClient({canvasRelayUrl:o.canvasRelayUrl,agentKeys:agentKeys,...r?{}:{agentId:n.id},displayName:n.displayName,avatarUrl:n.avatarUrl,tokenProvider:a,onConnected:()=>p.flushPendingCanvasLinks(),onReconnect:()=>p.onRelayReconnected(),logger:e.logger});t.setRelayClient(i),t.setAgentId(n.id),p.wireRelayActionHandler(),i.connect(),e.logger.info?.(`[beeos-claw] Canvas Relay multiplexed client connected (agentId=${n.id}, name=${n.name??"none"})`)};e.registerService(createCanvasRelayService({getAgent:r?()=>({id:`sandbox:${r}`}):h,onceAgentReady:e=>sharedAgentMappings.onceReady(e),initRelay:n,stopRelay:()=>t.getRelayClient()?.disconnect(),logger:e.logger})),e.logger.info?.("[beeos-claw] Canvas Relay configured")}else e.logger.warn?.("[beeos-claw] Canvas Relay unavailable: agentGatewayUrl or agentKeys missing");const r={stateManager:t,logger:e.logger,writeObs:e=>a(e),getActiveSessionId:e=>p.getSessionIdForToolCall(e),getPlatformAgentId:e=>p.getPlatformAgentIdForToolCall(e),getGatewaySessionKey:e=>p.getGatewaySessionKeyForToolCall(e),waitForAgentSync:()=>sharedAgentMappings.waitForSynchronization(),publishStaticHtml:createStaticCanvasHtmlPublisher(pluginCloudRuntimeTarget(e)?o.agentGatewayUrl:void 0)},i=new FormSchemaRegistry,s=buildCronSchemas(n);i.register(s.create),i.register(s.update);const l=new ResourceDescriptorRegistry;l.register(CRON_RESOURCE);const c=e=>async(t,r,o)=>(p.preMapToolCallSession(t),e(t,r));e.registerTool({name:RENDER_UI_TOOL_NAME,description:RENDER_UI_TOOL_DESCRIPTION,parameters:RENDER_UI_TOOL_SCHEMA,execute:c(createRenderUiToolExecutor(r))}),e.registerTool({name:CLOSE_UI_TOOL_NAME,description:CLOSE_UI_TOOL_DESCRIPTION,parameters:CLOSE_UI_TOOL_SCHEMA,execute:c(createCloseUiHandler(r))}),p.setCanvasState(t,{schemaRegistry:i,descriptorRegistry:l});const u=p.getFormBuilder();u&&e.registerTool({name:RENDER_FORM_TOOL_NAME,description:buildRenderFormDescription(i),parameters:RENDER_FORM_TOOL_SCHEMA,execute:c(createRenderFormHandler({registry:i,builder:u,logger:e.logger}))});const d=p.getResourceRenderer();if(d){generateActionTools(l,e,async(e,t)=>p.gatewayRequest(e,t),d,e.logger)}const g=buildToolRoutingHint(BEEOS_FILE_RESOURCE_ROUTING_RULE,BEEOS_DESKTOP_SCREENSHOT_TOOL_NAME),m=new Set([RENDER_UI_TOOL_NAME,CLOSE_UI_TOOL_NAME,RENDER_FORM_TOOL_NAME]),y=256,v=new Map;if("function"==typeof e.on){try{e.on("before_prompt_build",(e,t)=>{if(t?.sessionKey){if(v.size>=y&&!v.has(t.sessionKey)){const e=v.keys().next().value;void 0!==e&&v.delete(e)}v.set(t.sessionKey,t.channelId),rememberDeliveryWorkspace(t.sessionKey,t.workspaceDir)}const r=isThirdPartyChannel(n,{sessionKey:t?.sessionKey,channelId:t?.channelId});return t?.sessionKey||r?{appendSystemContext:buildAppendSystemContext({thirdParty:r,canvasSystemPrompt:`${CANVAS_PRESENTATION_GATE}\n\n${CANVAS_SYSTEM_PROMPT}`,toolRoutingHint:g})}:{appendSystemContext:g}}),e.logger.debug?.("[beeos-claw] Canvas system prompt hook registered: before_prompt_build")}catch{e.logger.debug?.("[beeos-claw] before_prompt_build hook not supported")}try{e.on("before_tool_call",(e,t)=>{if(t?.sessionKey&&p.setPendingToolCallSessionKey(t.sessionKey),!m.has(e.toolName))return;const r=t?.sessionKey?v.get(t.sessionKey):void 0,o=isThirdPartyChannel(n,{sessionKey:t?.sessionKey,channelId:r}),a=canvasToolBlockReason({thirdParty:o,hasSession:Boolean(t?.sessionKey)});return a?{block:!0,blockReason:a}:void 0}),e.logger.debug?.("[beeos-claw] Canvas tool guard registered: before_tool_call")}catch{e.logger.debug?.("[beeos-claw] before_tool_call hook not supported")}}e.logger.info?.("[beeos-claw] Canvas tools registered (render_ui, close_ui, render_form + auto-action tools)")}else e.logger.info?.("[beeos-claw] Canvas disabled by config (canvasEnabled=false)");if(o.bridge.shell.enabled&&!0===o.legacyTerminalWsEnabled){const t=createTerminalWebSocketService({config:{port:o.terminalWsPort,token:agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):"",allowedOrigins:o.terminalWsAllowedOrigins},terminalMgr:sharedTerminalManager,logger:e.logger,writeObs:a});e.registerService({id:"beeos-terminal-ws",start(){t.start(),e.logger.info?.(`[beeos-claw] Terminal WS started on port ${o.terminalWsPort}`)},stop(){t.stop(),e.logger.info?.("[beeos-claw] Terminal WS stopped")}})}else o.bridge.shell.enabled?e.logger.info?.("[beeos-claw] Legacy static-token Terminal WS disabled (default)"):e.logger.info?.("[beeos-claw] Terminal/shell disabled by config (bridge.shell.enabled=false)");if(t.openclawConfig){const r=mirrorOpenClawConfig(t.openclawConfig);r.copied?e.logger.info?.(`[beeos-claw] mirrored openclaw config to ${r.destinationPath}`):e.logger.debug?.(`[beeos-claw] openclaw config mirror skipped: ${r.reason}`)}}export function pluginCloudRuntimeTarget(e){const t=e.pluginConfig?.cloudRuntimeInstanceId;return cloudRuntimeTargetInstanceId("string"==typeof t?t:claimedSandboxId())}function attachNativeCloudChat(e,t){if(sharedNativeChatService)return e.registerService(sharedNativeChatService),sharedNativeCloudChat;const r=sharedRuntimeAuthority,o=t.messageBus.serviceUrl,a=sharedAcpServer,n=sharedSessionMutationCoordinator;if(!(r&&r.cloudTargetInstanceId&&o&&a&&n))return sharedNativeCloudChat;const i=sharedNativeCloudChat??createNativeCloudChatComposition({authority:nativeCloudChatAuthorityFromRuntimeAuthority(r),serviceUrl:o,logger:e.logger});if(sharedNativeCloudChat=i,!t.messageBus.enabled)return i;const s=i,l=r;let c;const u=new Map,d=new RuntimeAuthorityMessageBusLifecycle({authority:l,logger:e.logger,bus:{connect:async t=>{c?.(),u.clear(),c=s.adapter.listen({eventTypes:["message.created"]},r=>{if(r.type===APPROVAL_DECISION_MESSAGE_TYPE&&r.senderId?.startsWith("user:")&&isApprovalDocument(r.content))return void sharedApprovalBridge.onDecision(r.content);if("user.continue"===r.type&&isQuestionResponseDocument(r.content))return void sharedQuestionBridge.onResponse(r);const o=(r.content??{}).metadata??{},i="string"==typeof o.target_agent_id?o.target_agent_id:"",l=i?((t,r)=>{const o=sharedAgentMappings.snapshot();if(o)for(const[i,l]of o.entries()){if(l.id!==r)continue;if(l.instanceId!==t.instanceId)continue;const o=`${i}\0${l.id}`;let c=u.get(o);return c||(c={localAgentId:i,inbound:createImInboundHandler({runtime:e.runtime,pluginConfig:e.pluginConfig,client:s.adapter,localServer:{getLocalAgentId:()=>i,resolveLocalAgentId:e=>e===l.id?i:void 0,getDefaultPlatformAgent:()=>({instanceId:t.instanceId}),ensureImInboundSession:(e,t,r,o)=>{a.ensureImInboundSession(e,t,r,o)},chatAbort:(e,t)=>a.chatAbort(e,t)},promptRunStore:sharedPromptRunStore,waitIfExclusive:(t,r)=>sharedImHotPathDeferral.waitIfExclusive(t,e.logger,r).then(()=>{}),assistantMessageCommitRouter:sharedAssistantMessageCommitRouter,toolResultObservationRouter:sharedToolResultObservationRouter,approvalStreams:sharedApprovalBridge,questionStreams:sharedQuestionBridge,modelCallObservationRouter:sharedModelCallObservationRouter,sessionMutationCoordinator:n,logger:e.logger,writeObs:sharedWriteObs,principalIdOverride:t.instanceId,activeRunAuthority:a.getActiveRunAuthority(),applyTurnModel:(e,t)=>a.applyImTurnModel(e,t),restoreTurnModel:e=>a.restoreImTurnModel(e),...agentGateway?{completeA2ATask:(t,r,o)=>completeA2ATask({gateway:agentGateway,logger:e.logger},t,r,o)}:{}})},u.set(o,c)),c}})(t,i):void 0;if(!l)return void e.logger.warn?.(`[beeos-claw] native cloud chat dropped unresolvable target_agent_id=${i||"missing"} message_id=${r.id}`);("chat_cancel"===r.type?l.inbound.onChatCancel(r):l.inbound.onChatMessage(r)).catch(t=>{e.logger.error?.(`[beeos-claw] native cloud chat dispatch failed message_id=${r.id}: ${t instanceof Error?t.message:String(t)}`)})});try{await s.adapter.connect()}catch(e){throw c?.(),c=void 0,e}},disconnect:async()=>{c?.(),c=void 0,u.clear(),await s.adapter.disconnect()}}});return sharedNativeChatService={id:"beeos-native-cloud-chat",async start(){d.start()},async stop(){await d.stop()}},e.registerService(sharedNativeChatService),e.logger.info?.("[beeos-claw] native Cloud personal-chat composition registered"),i}const plugin={id:"beeos-claw",name:"beeos-claw",description:"BeeOS platform bridge plugin for OpenClaw. Provides file upload/download, ACP bridge, and observability.",version:PLUGIN_VERSION,register(e){if(_initializing)return;registerCentralNativeContextEngine(e),registerSandboxNativeActivation(e,()=>{if(!sharedSessionMutationCoordinator)throw new Error("native session writer coordinator is unavailable");return sharedSessionMutationCoordinator.activeMutationCount},createSandboxNativeTargetLookup(()=>sharedRuntimeAuthority,()=>sharedGatewayClient),async()=>{if(!sharedGatewayClient?.isConnected)throw new Error("OpenClaw gateway is not connected");await sharedGatewayClient.request("secrets.reload",{})});const t=pluginCloudRuntimeTarget(e),r=void 0!==t&&t!==sharedRuntimeAuthority?.cloudTargetInstanceId,o=planPluginRegistration(e.registrationMode,_fullRuntimeRegistered,r);if("skip"!==o){_initializing=!0;try{if(!hasRuntimeReplyApi(e.runtime))throw e.logger.error?.("[beeos-claw] FATAL: OpenClaw runtime.channel.reply.dispatchReplyFromConfig not exposed. Upgrade OpenClaw or revert beeos-claw."),new Error("openclaw_runtime_reply_api_unavailable");const t=(t,r)=>{registerUploadTools(e,t,r),registerArouterLatencyRouting(e),registerArouterMediaProviders(e)};if("capabilities"===o&&sharedPluginContext){if(cachedCapabilityTools.length>0){const t=resolveCapabilityToolReplay({currentRegisterTool:e.registerTool,wrappedRegisterTool:wrappedRegisterTool,originalRegisterTool:rawRegisterTool}),r=replayCachedPluginTools((r,o)=>t.call(e,r,o),cachedCapabilityTools);return registerArouterLatencyRouting(e),registerArouterMediaProviders(e),void e.logger.info?.(`[beeos-claw] capability re-register mode=${e.registrationMode} tools_only count=${r}`)}const r={current:sharedAcpServer??null};return t(sharedPluginContext,r),registerServices(e,sharedPluginContext,r),void e.logger.info?.(`[beeos-claw] capability re-register mode=${e.registrationMode} capabilities_only`)}const r=initializePlugin(e);if(!r)return;const a={current:null};installUnhandledRejectionObserver(e,r.writeObs,a),ensureRegisterToolCache(e),cacheRuntimeRegistrations(e),cachedCapabilityTools.length=0,t(r,a),agentGateway&&(e.on?e.on("before_agent_finalize",async(e,t)=>{if(await fileDeliveryFinalizeDecision(e),!e.runId||!t?.runId||e.runId===t.runId)return nativeHtmlDeliveryForRun(e.runId??t?.runId)?.beforeFinalize(e)}):e.logger.warn?.("[file-delivery] OpenClaw plugin hooks unavailable; finalization check disabled")),registerServices(e,r,a),sharedPluginContext=r,marksFullRuntimeRegistered(e.registrationMode,o)&&(_fullRuntimeRegistered=!0),_pluginRegisteredAt=Date.now(),e.logger.info?.("[beeos-claw] Plugin registered successfully")}finally{_initializing=!1}}else if(!e.registrationMode||"full"===e.registrationMode){const t=resolveCapabilityToolReplay({currentRegisterTool:e.registerTool,wrappedRegisterTool:wrappedRegisterTool,originalRegisterTool:rawRegisterTool});replayCachedPluginTools((r,o)=>t.call(e,r,o),cachedCapabilityTools),replayRuntimeRegistrations(e),registerArouterLatencyRouting(e),registerArouterMediaProviders(e)}}};export default plugin;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
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
|
|
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
|
|
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"})}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash,timingSafeEqual}from"node:crypto";import{readFile}from"node:fs/promises";import{isDeepStrictEqual}from"node:util";import{centralNativeRuntime}from"./central-native-runtime.js";import{resolveSyncAgentName}from"../agent-sync.js";import{injectOpenClawCredentials}from"./sandbox-native-credentials.js";function unboundActivation(e){const{execution_binding_version:t,...i}=e;return{...i,request_hash:""}}let executionResolver;export function installSandboxNativeExecutionResolver(e){if(executionResolver)throw new Error("native original execution authority is already installed");executionResolver=e}export function createSandboxNativeTargetLookup(e,t){return async({localAgentId:i,activation:n})=>{const r=e(),a=r?.authorityLease,o=t();if(!r||!a?.runtimeLeaseCredential||Date.parse(a.leaseExpiresAt)<=Date.now()||a.instanceId!==n.sandbox_id||!o?.isConnected)throw new Error("current native target projection authority/catalog transport is unavailable");const s=await o.request("agents.list",{}),c=s.agents?.filter(e=>e.id===i)??[];if(1!==c.length)throw new Error("actual native target catalog entry is missing or ambiguous");if(resolveSyncAgentName(c[0])!==i)throw new Error("actual native catalog key differs from the current identity projection key");const l=await r.identities.resolveOrCreate(i),d=r.authorityLease;if(e()!==r||!d||Date.parse(d.leaseExpiresAt)<=Date.now()||d.instanceId!==a.instanceId||d.leaseId!==a.leaseId||d.runtimeEpoch!==a.runtimeEpoch||d.handlerIdentity!==a.handlerIdentity)throw new Error("native target projection authority changed during observation");return{runtimeAgentUid:l,runtimeLocalKey:i,runtimeEpoch:d.runtimeEpoch,leaseIdentity:JSON.stringify({instanceId:d.instanceId,leaseId:d.leaseId,runtimeEpoch:d.runtimeEpoch,handlerIdentity:d.handlerIdentity})}}}const object=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),sha256=e=>createHash("sha256").update(e).digest("hex"),ref=e=>`native:${sha256(JSON.stringify(e))}`,nonempty=e=>"string"==typeof e&&e.length>0,secretRef=e=>object(e)&&3===Object.keys(e).length&&("env"===e.source||"file"===e.source||"exec"===e.source)&&nonempty(e.provider)&&nonempty(e.id);export function containsApplied(e,t){return secretRef(t)?isDeepStrictEqual(e,t)||nonempty(e):Array.isArray(t)?Array.isArray(e)&&e.length===t.length&&t.every((t,i)=>containsApplied(e[i],t)):object(t)?object(e)&&Object.entries(t).every(([t,i])=>containsApplied(e[t],i)):isDeepStrictEqual(e,t)}export function sessionConfigObservation(e){const{activation:t,allocation:i,native:n,execution:r,receipt:a}=e,o=n.config_components;if(!(object(o)&&object(r.loadAuthority)&&Number.isSafeInteger(i.epoch)&&nonempty(t.resolved_request_hash)&&nonempty(t.central_read_watermark)))throw new Error("actual SessionConfigReceipt inputs (components/authority/allocation/selection) are unavailable");const s=structuredClone(r.loadAuthority),c=i.id,l=r.sessionKey,d={session_load_receipt:e.sessionLoadReceipt,prepared:a.receipt_id},u=ref({config:a.receipt_id,session:l,authority:s}),p={contractVersion:"1",revision:t.config_revision,manifestRef:{id:t.config_manifest.manifest_id,digest:t.config_sha256},appliedAt:a.prepared_at,sessionId:t.session_id,applyAt:"session_start",components:structuredClone(o),binding:{bindingId:t.binding_id,agentId:t.agent_id,harnessId:t.harness,sandboxId:t.sandbox_id,allocationId:i.id,allocationEpoch:i.epoch},applicationState:"applied",authority:s,hostInstanceId:c,nativeSessionId:l,receiptId:u,mutationScope:"session_private"};return{resolvedRequestHash:t.resolved_request_hash,readWatermark:t.central_read_watermark,admission:{attemptId:r.binding.attemptId,hostInstanceId:c,executionBindingVersion:t.execution_binding_version,nativeSessionId:l,nativeIncarnation:`${process.pid}@${i.boot_id}`,requestHash:t.request_hash},sessionConfigReceipt:{receiptId:u,commandId:t.command_id,authority:s,hostInstanceId:c,nativeSessionId:l,configuration:p,evidenceRef:{id:e.sessionLoadReceipt,digest:sha256(JSON.stringify(d))},preparedConfigReceiptId:a.receipt_id},loadedFacts:{loaded_model_id:null,actual_provider_id:null,actual_model_id:null,endpoint_ref:null,api_mode:null,reasoning:null,fallback_used:null,skills_digest:null,tool_schema_digest:null,credential_activation_revision:a.credential_activation_revision,components:[],memory_observation:"not_read",memory_read_watermark:null}}}export class SandboxNativeActivation{config;activeWriters;activationFile;targetLookup;prepared;materialized;boundNativeRequestHash;targetAuthority;persona;credentialReceipt;control=Promise.resolve();serialize(e){const t=this.control.then(e,e);return this.control=t.catch(()=>{}),t}constructor(e,t,i,n){this.config=e,this.activeWriters=t,this.activationFile=i,this.targetLookup=n}prepare(e){return this.serialize(()=>this.apply(e))}target(e){return this.serialize(()=>this.apply(e,!0))}async assertEnvelope(e,t=!1){const i=JSON.parse(await readFile(this.activationFile,"utf8")),{activation:n,allocation:r,config_manifest:a}=e,o=!t&&"execution"===n.kind&&"execution"===i.activation?.kind&&""===i.activation.request_hash&&nonempty(n.request_hash)&&isDeepStrictEqual(unboundActivation(i.activation),unboundActivation(n));if(!isDeepStrictEqual(i.activation,n)&&!o||!isDeepStrictEqual(i.allocation,r)||!isDeepStrictEqual(i.config_manifest,a))throw new Error("native preparation does not match the current immutable activation");if(!nonempty(n.preparation_id)||!nonempty(r.id)||!nonempty(r.boot_id)||!Number.isFinite(Date.parse(n.deadline_at))||Date.parse(n.deadline_at)<=Date.now())throw new Error("native preparation authority/deadline is unavailable");if(!isDeepStrictEqual(JSON.parse(await readFile(e.config_manifest_path,"utf8")),a))throw new Error("native configuration bytes differ from the verified manifest");if("credential_activation"in a)throw new Error("private credential inputs must use transient authenticated delivery");if("central_chat"in a||"centralChat"in a)throw new Error("immutable native configuration must not contain per-execution chat authority")}credentials(e){return this.serialize(async()=>{if(await this.assertEnvelope(e),0!==this.activeWriters())throw new Error("native writers must drain before credential injection");if(this.materialized&&!this.credentialReceipt)throw new Error("credentials must be injected before native provider construction");const t=injectOpenClawCredentials({delivery:e.credential_delivery,activation:e.activation,allocation:e.allocation,previous:this.credentialReceipt,mcpCredentialSlots:e.config_manifest.mcp_credential_slots});return this.credentialReceipt=t,structuredClone(t)})}async apply(e,t=!1){await this.assertEnvelope(e,t);const{activation:i,allocation:n,config_manifest:r}=e;if(!this.credentialReceipt)throw new Error("actual native credential injection receipt is required, including empty credentials");if("execution"===i.kind){if(!nonempty(i.public_request_hash))throw new Error("original public request hash is required");if(t&&(""!==i.request_hash||void 0!==this.boundNativeRequestHash))throw new Error("target observation requires the original unbound native request hash");const e=i.execution_binding_version;if(t?void 0!==e&&0!==e:!(Number.isSafeInteger(e)&&e>=1))throw new Error("State execution binding version must be unbound at target and positive at Session load");if(!t&&(!nonempty(i.request_hash)||void 0!==this.boundNativeRequestHash&&this.boundNativeRequestHash!==i.request_hash))throw new Error("native canonical request hash is missing or changed")}const{execution_grant:a,credential_delivery:o,...s}=e,c={...s,activation:unboundActivation(i)};if(this.materialized&&!isDeepStrictEqual(this.materialized,c))throw new Error("a different native materialization requires a drained process restart");let l;if("execution"===i.kind&&!t){if(!nonempty(e.execution_grant)||!executionResolver)throw new Error("authenticated original canonical execution request producer is unavailable");if(l=await executionResolver(e),!this.targetAuthority||!this.targetLookup)throw new Error("the original work has no observed native target");const t=await this.targetLookup({localAgentId:r.local_agent_id,activation:i,allocation:n});if(!isDeepStrictEqual(t,this.targetAuthority))throw new Error("native target/current runtime lease changed before session load");if(l.nativeRequestHash!==i.request_hash||l.binding.sessionId!==i.session_id||l.binding.responseId!==i.response_id||l.binding.operationId!==i.operation_id||l.runtimeAgentUid!==this.targetAuthority.runtimeAgentUid||!l.sessionKey.startsWith(`agent:${r.local_agent_id}:`))throw new Error("original execution request differs from the current native activation");this.assertSelection(l.params,e)}if(!t&&this.prepared&&isDeepStrictEqual(this.prepared.envelope,s)){if(!isDeepStrictEqual(this.prepared.execution,l))throw new Error("original execution binding changed");return l&&await centralNativeRuntime().prepareReadOnly(l.sessionKey,l.binding),structuredClone(this.prepared.receipt)}if(0!==this.activeWriters())throw new Error("native writers must drain before applying configuration");if(!["configuration","credential_restart","execution"].includes(i.kind))throw new Error("unsupported native activation kind");if(1!==r.schema_version||!nonempty(r.local_agent_id)||!object(r.openclaw_config))throw new Error("resolved OpenClaw native configuration v1 is required");const d=r.mcp_credential_slots;if(void 0!==d&&(!Array.isArray(d)||d.some(e=>"string"!=typeof e||!/^[a-z][a-z0-9_]{0,63}$/.test(e)||"openai_api_key"===e)||new Set(d).size!==d.length))throw new Error("resolved MCP credential slots are invalid");const u=new Set(["agents","models","tools","skills","mcp"]);if(Object.keys(r.openclaw_config).some(e=>!u.has(e)))throw new Error("native config may only apply agent/model/tool/Skill/MCP settings");const p=r.openclaw_config.agents;if(!object(p)||!object(p.entries)||!object(p.entries[r.local_agent_id]))throw new Error("local_agent_id is not present in the resolved native agent catalog");if(this.prepared&&!isDeepStrictEqual(this.prepared.envelope,s))throw new Error("a different native activation requires a drained process restart");if(r.persona&&(!nonempty(r.persona.persona_id)||!nonempty(r.persona.revision)||!nonempty(r.persona.source_receipt_ref)||sha256(r.persona.content)!==r.persona.sha256))throw new Error("resolved Persona source/revision/content digest is invalid");if("execution"!==i.kind&&(i.session_id||i.response_id||i.execution_binding_version))throw new Error("non-execution preparation must not manufacture a Session or Response");if(t&&"execution"!==i.kind)throw new Error("target observation requires the original execution preparation");this.materialized||await this.config.mutateConfigFile({afterWrite:{mode:"auto"},mutate:e=>{for(const[t,i]of Object.entries(r.openclaw_config))e[t]=structuredClone(i)}});const h=this.config.current();if(!containsApplied(h,r.openclaw_config))throw new Error("native config has not been applied by OpenClaw");const f=h.agents;if(!object(f)||!object(f.entries)||!object(f.entries[r.local_agent_id]))throw new Error("local_agent_id is not present in the actual resolved native agent catalog");if(this.persona=r.persona?{localAgentId:r.local_agent_id,content:r.persona.content}:void 0,this.materialized=structuredClone(c),t){if(!this.targetLookup)throw new Error("actual native target identity producer is unavailable");const e=await this.targetLookup({localAgentId:r.local_agent_id,activation:i,allocation:n});if(!nonempty(e.runtimeAgentUid)||e.runtimeLocalKey!==r.local_agent_id||!/^[1-9][0-9]*$/.test(e.runtimeEpoch)||!nonempty(e.leaseIdentity))throw new Error("actual native catalog/identity projection does not match the applied target");return this.targetAuthority=structuredClone(e),{runtime_agent_uid:e.runtimeAgentUid,runtime_local_key:e.runtimeLocalKey,harness:"openclaw",config_digest:i.config_sha256,runtime_epoch:e.runtimeEpoch}}let g="";if("execution"===i.kind){if(!l)throw new Error("original central native execution authority is unavailable");this.boundNativeRequestHash=l.nativeRequestHash,await centralNativeRuntime().prepareReadOnly(l.sessionKey,l.binding),g=ref({session_key:l.sessionKey,binding:l.binding,source:centralNativeRuntime().source(l.sessionKey)})}const _=(new Date).toISOString(),v={preparation_id:i.preparation_id,kind:i.kind,binding_id:i.binding_id,config_revision:i.config_revision,config_sha256:i.config_sha256,target_intent_digest:i.target_intent_digest,authority_ref:i.authority_ref,config_manifest:i.config_manifest,credential_set_id:i.credential_set_id,credential_set_version:i.credential_set_version,credential_activation_revision:this.credentialReceipt.config.revision,receipt_scope:"configuration"===i.kind?"current_config":"activation",credential_activation_receipt_ref:this.credentialReceipt.receipt_id,host_instance_id:n.id,runtime_lineage_ref:n.boot_id,session_load_receipt_ref:g,prepared_at:_,..."execution"===i.kind?{execution_binding_version:i.execution_binding_version}:{},receipt_id:ref({activation:i,allocation:n,config:r.openclaw_config,persona:r.persona?.sha256??null,credential_receipt:this.credentialReceipt.receipt_id,sessionLoadReceipt:g})};return l&¢ralNativeRuntime().bindExecutionObservation(l.binding,sessionConfigObservation({activation:i,allocation:n,native:r,execution:l,receipt:v,sessionLoadReceipt:g})),this.prepared={envelope:structuredClone(s),execution:l&&structuredClone(l),receipt:v},v}execution(e,t){const i=this.prepared,n=i?.envelope.config_manifest,r=i?.execution;if(!(i&&"execution"===i.envelope.activation.kind&&n&&r&&isDeepStrictEqual(r.binding,t)&&containsApplied(this.config.current(),n.openclaw_config)))throw new Error("central execution does not match actual applied native configuration/Persona/binding");if(this.assertSelection(e,i.envelope),!isDeepStrictEqual(e,r.params))throw new Error("central execution differs from the prepared original request");return{sessionKey:r.sessionKey,localAgentId:n.local_agent_id,systemPrompt:n.persona?.content??""}}assertSelection(e,t){const i=e.centralChat,n=t.config_manifest.persona;if(!object(i)||!this.credentialReceipt||!isDeepStrictEqual(i.config_pin,this.credentialReceipt.config)||!isDeepStrictEqual(i.persona_ref,n?{persona_id:n.persona_id,revision:n.revision}:null)||Object.hasOwn(i,"effective_config")||Object.hasOwn(i,"persona"))throw new Error("central selection differs from the actual prepared native configuration/Persona source")}promptContext(e){if(this.persona&&object(e)&&e.agentId===this.persona.localAgentId)return{appendSystemContext:this.persona.content}}drain(e){return this.serialize(()=>this.quiesce(e))}async quiesce(e){if(!(this.prepared&&isDeepStrictEqual(e.activation,this.prepared.envelope.activation)&&isDeepStrictEqual(e.allocation,this.prepared.envelope.allocation)&&nonempty(e.command_id)))throw new Error("native drain does not match the actual prepared activation");const t=await centralNativeRuntime().drain();if(1!==t.sourceWatermarks.length)throw new Error("Runtime drain contract requires one actual central session watermark; configuration-only quiescence is not representable");const i=t.sourceWatermarks[0].watermark,n=ref({command_id:e.command_id,prepared:this.prepared.receipt.receipt_id,allocation:e.allocation,sources:t.sourceWatermarks});return{receipt_id:ref({quiesce:n,watermark:i}),central_committed_watermark:i,pending_writes:0,all_writers_quiesced:!0,quiesce_ref:n}}}let controller;async function body(e){const t=[];let i=0;for await(const n of e){const e=Buffer.isBuffer(n)?n:Buffer.from(n);if(i+=e.length,i>4194304)throw new Error("native activation payload exceeds 4 MiB");t.push(e)}try{return JSON.parse(Buffer.concat(t).toString("utf8"))}catch{throw new Error("native control request is not valid JSON")}}export function registerSandboxNativeActivation(e,t,i){const n=process.env.BEEOS_SANDBOX_ACTIVATION_FILE;if(!n)return;const r=e.runtime?.config;if(!r?.current||!r.mutateConfigFile)throw new Error("pinned OpenClaw native config APIs are required for Sandbox activation");controller??=new SandboxNativeActivation(r,t,n,i);for(const t of["credentials","target","prepare","drain"])e.registerHttpRoute({path:`/beeos/sandbox-v1/${t}`,auth:"plugin",async handler(e,i){const n=e,r=i,a=(e,t)=>{r.writeHead(e,{"content-type":"application/json","cache-control":"no-store"}),r.end(JSON.stringify(t))};if("POST"!==n.method)return void a(405,{error:{code:"method_not_allowed"}});const o=n.socket.remoteAddress;if(["127.0.0.1","::1","::ffff:127.0.0.1"].includes(o??""))try{const e=process.env.BEEOS_SANDBOX_NATIVE_TOKEN_FILE;if(!e)throw new Error("native control token file is unavailable");const i=(await readFile(e,"utf8")).trim(),r=Buffer.from(`Bearer ${i}`),o=Buffer.from(n.headers.authorization??"");if(!i||o.length!==r.length||!timingSafeEqual(o,r))return void a(401,{error:{code:"native_control_unauthorized"}});const s=await body(n);if(!object(s))throw new Error("native control request must be an object");a(200,"credentials"===t?await controller.credentials(s):"target"===t?await controller.target(s):"prepare"===t?await controller.prepare(s):await controller.drain(s))}catch(e){a(503,{error:{code:"native_preparation_unavailable",message:e instanceof Error?e.message:String(e)}})}else a(403,{error:{code:"native_loopback_required"}})}})}export function preparedSandboxNativeExecution(e,t){if(!controller)throw new Error("actual native Sandbox activation is unavailable");return controller.execution(e,t)}
|
|
1
|
+
import{createHash,timingSafeEqual}from"node:crypto";import{readFile}from"node:fs/promises";import{isDeepStrictEqual}from"node:util";import{centralNativeRuntime}from"./central-native-runtime.js";import{resolveSyncAgentName}from"../agent-sync.js";import{injectOpenClawCredentials}from"./sandbox-native-credentials.js";function unboundActivation(e){const{execution_binding_version:t,...i}=e;return{...i,request_hash:""}}let executionResolver;export function installSandboxNativeExecutionResolver(e){if(executionResolver)throw new Error("native original execution authority is already installed");executionResolver=e}export function createSandboxNativeTargetLookup(e,t){return async({localAgentId:i,activation:n})=>{const r=e(),a=r?.authorityLease,o=t();if(!r||!a?.runtimeLeaseCredential||Date.parse(a.leaseExpiresAt)<=Date.now()||a.instanceId!==n.sandbox_id||!o?.isConnected)throw new Error("current native target projection authority/catalog transport is unavailable");const s=await o.request("agents.list",{}),c=s.agents?.filter(e=>e.id===i)??[];if(1!==c.length)throw new Error("actual native target catalog entry is missing or ambiguous");if(resolveSyncAgentName(c[0])!==i)throw new Error("actual native catalog key differs from the current identity projection key");const l=await r.identities.resolveOrCreate(i),d=r.authorityLease;if(e()!==r||!d||Date.parse(d.leaseExpiresAt)<=Date.now()||d.instanceId!==a.instanceId||d.leaseId!==a.leaseId||d.runtimeEpoch!==a.runtimeEpoch||d.handlerIdentity!==a.handlerIdentity)throw new Error("native target projection authority changed during observation");return{runtimeAgentUid:l,runtimeLocalKey:i,runtimeEpoch:d.runtimeEpoch,leaseIdentity:JSON.stringify({instanceId:d.instanceId,leaseId:d.leaseId,runtimeEpoch:d.runtimeEpoch,handlerIdentity:d.handlerIdentity})}}}const object=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),sha256=e=>createHash("sha256").update(e).digest("hex"),ref=e=>`native:${sha256(JSON.stringify(e))}`,nonempty=e=>"string"==typeof e&&e.length>0,secretRef=e=>object(e)&&3===Object.keys(e).length&&("env"===e.source||"file"===e.source||"exec"===e.source)&&nonempty(e.provider)&&nonempty(e.id);export function containsApplied(e,t){return secretRef(t)?isDeepStrictEqual(e,t)||nonempty(e):Array.isArray(t)?Array.isArray(e)&&e.length===t.length&&t.every((t,i)=>containsApplied(e[i],t)):object(t)?object(e)&&Object.entries(t).every(([t,i])=>containsApplied(e[t],i)):isDeepStrictEqual(e,t)}export function sessionConfigObservation(e){const{activation:t,allocation:i,native:n,execution:r,receipt:a}=e,o=n.config_components;if(!(object(o)&&object(r.loadAuthority)&&Number.isSafeInteger(i.epoch)&&nonempty(t.resolved_request_hash)&&nonempty(t.central_read_watermark)))throw new Error("actual SessionConfigReceipt inputs (components/authority/allocation/selection) are unavailable");const s=structuredClone(r.loadAuthority),c=i.id,l=r.sessionKey,d={session_load_receipt:e.sessionLoadReceipt,prepared:a.receipt_id},u=ref({config:a.receipt_id,session:l,authority:s}),p={contractVersion:"1",revision:t.config_revision,manifestRef:{id:t.config_manifest.manifest_id,digest:t.config_sha256},appliedAt:a.prepared_at,sessionId:t.session_id,applyAt:"session_start",components:structuredClone(o),binding:{bindingId:t.binding_id,agentId:t.agent_id,harnessId:t.harness,sandboxId:t.sandbox_id,allocationId:i.id,allocationEpoch:i.epoch},applicationState:"applied",authority:s,hostInstanceId:c,nativeSessionId:l,receiptId:u,mutationScope:"session_private"};return{resolvedRequestHash:t.resolved_request_hash,readWatermark:t.central_read_watermark,admission:{attemptId:r.binding.attemptId,hostInstanceId:c,executionBindingVersion:t.execution_binding_version,nativeSessionId:l,nativeIncarnation:`${process.pid}@${i.boot_id}`,requestHash:t.request_hash},sessionConfigReceipt:{receiptId:u,commandId:t.command_id,authority:s,hostInstanceId:c,nativeSessionId:l,configuration:p,evidenceRef:{id:e.sessionLoadReceipt,digest:sha256(JSON.stringify(d))},preparedConfigReceiptId:a.receipt_id},loadedFacts:{loaded_model_id:null,actual_provider_id:null,actual_model_id:null,endpoint_ref:null,api_mode:null,reasoning:null,fallback_used:null,skills_digest:null,tool_schema_digest:null,credential_activation_revision:a.credential_activation_revision,components:[],memory_observation:"not_read",memory_read_watermark:null}}}export class SandboxNativeActivation{config;activeWriters;activationFile;targetLookup;reloadSecrets;logger;prepared;materialized;boundNativeRequestHash;targetAuthority;persona;credentialReceipt;reloadedCredentialsReceipt;control=Promise.resolve();serialize(e){const t=this.control.then(e,e);return this.control=t.catch(()=>{}),t}constructor(e,t,i,n,r,a){this.config=e,this.activeWriters=t,this.activationFile=i,this.targetLookup=n,this.reloadSecrets=r,this.logger=a}reloadSecretsAfterInjection(e){this.reloadSecrets&&this.reloadedCredentialsReceipt!==e&&(this.reloadedCredentialsReceipt=e,Promise.resolve().then(()=>this.reloadSecrets()).catch(e=>this.logger?.warn?.(`[beeos-claw] secrets reload after credential delivery failed: ${e instanceof Error?e.message:String(e)}`)))}prepare(e){return this.serialize(()=>this.apply(e))}target(e){return this.serialize(()=>this.apply(e,!0))}async assertEnvelope(e,t=!1){const i=JSON.parse(await readFile(this.activationFile,"utf8")),{activation:n,allocation:r,config_manifest:a}=e,o=!t&&"execution"===n.kind&&"execution"===i.activation?.kind&&""===i.activation.request_hash&&nonempty(n.request_hash)&&isDeepStrictEqual(unboundActivation(i.activation),unboundActivation(n));if(!isDeepStrictEqual(i.activation,n)&&!o||!isDeepStrictEqual(i.allocation,r)||!isDeepStrictEqual(i.config_manifest,a))throw new Error("native preparation does not match the current immutable activation");if(!nonempty(n.preparation_id)||!nonempty(r.id)||!nonempty(r.boot_id)||!Number.isFinite(Date.parse(n.deadline_at))||Date.parse(n.deadline_at)<=Date.now())throw new Error("native preparation authority/deadline is unavailable");if(!isDeepStrictEqual(JSON.parse(await readFile(e.config_manifest_path,"utf8")),a))throw new Error("native configuration bytes differ from the verified manifest");if("credential_activation"in a)throw new Error("private credential inputs must use transient authenticated delivery");if("central_chat"in a||"centralChat"in a)throw new Error("immutable native configuration must not contain per-execution chat authority")}credentials(e){return this.serialize(async()=>{if(await this.assertEnvelope(e),0!==this.activeWriters())throw new Error("native writers must drain before credential injection");if(this.materialized&&!this.credentialReceipt)throw new Error("credentials must be injected before native provider construction");const t=injectOpenClawCredentials({delivery:e.credential_delivery,activation:e.activation,allocation:e.allocation,previous:this.credentialReceipt,mcpCredentialSlots:e.config_manifest.mcp_credential_slots});return this.credentialReceipt=t,this.reloadSecretsAfterInjection(t.receipt_id),structuredClone(t)})}async apply(e,t=!1){await this.assertEnvelope(e,t);const{activation:i,allocation:n,config_manifest:r}=e;if(!this.credentialReceipt)throw new Error("actual native credential injection receipt is required, including empty credentials");if("execution"===i.kind){if(!nonempty(i.public_request_hash))throw new Error("original public request hash is required");if(t&&(""!==i.request_hash||void 0!==this.boundNativeRequestHash))throw new Error("target observation requires the original unbound native request hash");const e=i.execution_binding_version;if(t?void 0!==e&&0!==e:!(Number.isSafeInteger(e)&&e>=1))throw new Error("State execution binding version must be unbound at target and positive at Session load");if(!t&&(!nonempty(i.request_hash)||void 0!==this.boundNativeRequestHash&&this.boundNativeRequestHash!==i.request_hash))throw new Error("native canonical request hash is missing or changed")}const{execution_grant:a,credential_delivery:o,...s}=e,c={...s,activation:unboundActivation(i)};if(this.materialized&&!isDeepStrictEqual(this.materialized,c))throw new Error("a different native materialization requires a drained process restart");let l;if("execution"===i.kind&&!t){if(!nonempty(e.execution_grant)||!executionResolver)throw new Error("authenticated original canonical execution request producer is unavailable");if(l=await executionResolver(e),!this.targetAuthority||!this.targetLookup)throw new Error("the original work has no observed native target");const t=await this.targetLookup({localAgentId:r.local_agent_id,activation:i,allocation:n});if(!isDeepStrictEqual(t,this.targetAuthority))throw new Error("native target/current runtime lease changed before session load");if(l.nativeRequestHash!==i.request_hash||l.binding.sessionId!==i.session_id||l.binding.responseId!==i.response_id||l.binding.operationId!==i.operation_id||l.runtimeAgentUid!==this.targetAuthority.runtimeAgentUid||!l.sessionKey.startsWith(`agent:${r.local_agent_id}:`))throw new Error("original execution request differs from the current native activation");this.assertSelection(l.params,e)}if(!t&&this.prepared&&isDeepStrictEqual(this.prepared.envelope,s)){if(!isDeepStrictEqual(this.prepared.execution,l))throw new Error("original execution binding changed");return l&&await centralNativeRuntime().prepareReadOnly(l.sessionKey,l.binding),structuredClone(this.prepared.receipt)}if(0!==this.activeWriters())throw new Error("native writers must drain before applying configuration");if(!["configuration","credential_restart","execution"].includes(i.kind))throw new Error("unsupported native activation kind");if(1!==r.schema_version||!nonempty(r.local_agent_id)||!object(r.openclaw_config))throw new Error("resolved OpenClaw native configuration v1 is required");const d=r.mcp_credential_slots;if(void 0!==d&&(!Array.isArray(d)||d.some(e=>"string"!=typeof e||!/^[a-z][a-z0-9_]{0,63}$/.test(e)||"openai_api_key"===e)||new Set(d).size!==d.length))throw new Error("resolved MCP credential slots are invalid");const u=new Set(["agents","models","tools","skills","mcp"]);if(Object.keys(r.openclaw_config).some(e=>!u.has(e)))throw new Error("native config may only apply agent/model/tool/Skill/MCP settings");const p=r.openclaw_config.agents;if(!object(p)||!object(p.entries)||!object(p.entries[r.local_agent_id]))throw new Error("local_agent_id is not present in the resolved native agent catalog");if(this.prepared&&!isDeepStrictEqual(this.prepared.envelope,s))throw new Error("a different native activation requires a drained process restart");if(r.persona&&(!nonempty(r.persona.persona_id)||!nonempty(r.persona.revision)||!nonempty(r.persona.source_receipt_ref)||sha256(r.persona.content)!==r.persona.sha256))throw new Error("resolved Persona source/revision/content digest is invalid");if("execution"!==i.kind&&(i.session_id||i.response_id||i.execution_binding_version))throw new Error("non-execution preparation must not manufacture a Session or Response");if(t&&"execution"!==i.kind)throw new Error("target observation requires the original execution preparation");this.materialized||await this.config.mutateConfigFile({afterWrite:{mode:"auto"},mutate:e=>{for(const[t,i]of Object.entries(r.openclaw_config))e[t]=structuredClone(i)}});const h=this.config.current();if(!containsApplied(h,r.openclaw_config))throw new Error("native config has not been applied by OpenClaw");const f=h.agents;if(!object(f)||!object(f.entries)||!object(f.entries[r.local_agent_id]))throw new Error("local_agent_id is not present in the actual resolved native agent catalog");if(this.persona=r.persona?{localAgentId:r.local_agent_id,content:r.persona.content}:void 0,this.materialized=structuredClone(c),t){if(!this.targetLookup)throw new Error("actual native target identity producer is unavailable");const e=await this.targetLookup({localAgentId:r.local_agent_id,activation:i,allocation:n});if(!nonempty(e.runtimeAgentUid)||e.runtimeLocalKey!==r.local_agent_id||!/^[1-9][0-9]*$/.test(e.runtimeEpoch)||!nonempty(e.leaseIdentity))throw new Error("actual native catalog/identity projection does not match the applied target");return this.targetAuthority=structuredClone(e),{runtime_agent_uid:e.runtimeAgentUid,runtime_local_key:e.runtimeLocalKey,harness:"openclaw",config_digest:i.config_sha256,runtime_epoch:e.runtimeEpoch}}let g="";if("execution"===i.kind){if(!l)throw new Error("original central native execution authority is unavailable");this.boundNativeRequestHash=l.nativeRequestHash,await centralNativeRuntime().prepareReadOnly(l.sessionKey,l.binding),g=ref({session_key:l.sessionKey,binding:l.binding,source:centralNativeRuntime().source(l.sessionKey)})}const _=(new Date).toISOString(),v={preparation_id:i.preparation_id,kind:i.kind,binding_id:i.binding_id,config_revision:i.config_revision,config_sha256:i.config_sha256,target_intent_digest:i.target_intent_digest,authority_ref:i.authority_ref,config_manifest:i.config_manifest,credential_set_id:i.credential_set_id,credential_set_version:i.credential_set_version,credential_activation_revision:this.credentialReceipt.config.revision,receipt_scope:"configuration"===i.kind?"current_config":"activation",credential_activation_receipt_ref:this.credentialReceipt.receipt_id,host_instance_id:n.id,runtime_lineage_ref:n.boot_id,session_load_receipt_ref:g,prepared_at:_,..."execution"===i.kind?{execution_binding_version:i.execution_binding_version}:{},receipt_id:ref({activation:i,allocation:n,config:r.openclaw_config,persona:r.persona?.sha256??null,credential_receipt:this.credentialReceipt.receipt_id,sessionLoadReceipt:g})};return l&¢ralNativeRuntime().bindExecutionObservation(l.binding,sessionConfigObservation({activation:i,allocation:n,native:r,execution:l,receipt:v,sessionLoadReceipt:g})),this.prepared={envelope:structuredClone(s),execution:l&&structuredClone(l),receipt:v},v}execution(e,t){const i=this.prepared,n=i?.envelope.config_manifest,r=i?.execution;if(!(i&&"execution"===i.envelope.activation.kind&&n&&r&&isDeepStrictEqual(r.binding,t)&&containsApplied(this.config.current(),n.openclaw_config)))throw new Error("central execution does not match actual applied native configuration/Persona/binding");if(this.assertSelection(e,i.envelope),!isDeepStrictEqual(e,r.params))throw new Error("central execution differs from the prepared original request");return{sessionKey:r.sessionKey,localAgentId:n.local_agent_id,systemPrompt:n.persona?.content??""}}assertSelection(e,t){const i=e.centralChat,n=t.config_manifest.persona;if(!object(i)||!this.credentialReceipt||!isDeepStrictEqual(i.config_pin,this.credentialReceipt.config)||!isDeepStrictEqual(i.persona_ref,n?{persona_id:n.persona_id,revision:n.revision}:null)||Object.hasOwn(i,"effective_config")||Object.hasOwn(i,"persona"))throw new Error("central selection differs from the actual prepared native configuration/Persona source")}promptContext(e){if(this.persona&&object(e)&&e.agentId===this.persona.localAgentId)return{appendSystemContext:this.persona.content}}drain(e){return this.serialize(()=>this.quiesce(e))}async quiesce(e){if(!(this.prepared&&isDeepStrictEqual(e.activation,this.prepared.envelope.activation)&&isDeepStrictEqual(e.allocation,this.prepared.envelope.allocation)&&nonempty(e.command_id)))throw new Error("native drain does not match the actual prepared activation");const t=await centralNativeRuntime().drain();if(1!==t.sourceWatermarks.length)throw new Error("Runtime drain contract requires one actual central session watermark; configuration-only quiescence is not representable");const i=t.sourceWatermarks[0].watermark,n=ref({command_id:e.command_id,prepared:this.prepared.receipt.receipt_id,allocation:e.allocation,sources:t.sourceWatermarks});return{receipt_id:ref({quiesce:n,watermark:i}),central_committed_watermark:i,pending_writes:0,all_writers_quiesced:!0,quiesce_ref:n}}}let controller;async function body(e){const t=[];let i=0;for await(const n of e){const e=Buffer.isBuffer(n)?n:Buffer.from(n);if(i+=e.length,i>4194304)throw new Error("native activation payload exceeds 4 MiB");t.push(e)}try{return JSON.parse(Buffer.concat(t).toString("utf8"))}catch{throw new Error("native control request is not valid JSON")}}export function registerSandboxNativeActivation(e,t,i,n){const r=process.env.BEEOS_SANDBOX_ACTIVATION_FILE;if(!r)return;const a=e.runtime?.config;if(!a?.current||!a.mutateConfigFile)throw new Error("pinned OpenClaw native config APIs are required for Sandbox activation");controller??=new SandboxNativeActivation(a,t,r,i,n,e.logger);for(const t of["credentials","target","prepare","drain"])e.registerHttpRoute({path:`/beeos/sandbox-v1/${t}`,auth:"plugin",async handler(e,i){const n=e,r=i,a=(e,t)=>{r.writeHead(e,{"content-type":"application/json","cache-control":"no-store"}),r.end(JSON.stringify(t))};if("POST"!==n.method)return void a(405,{error:{code:"method_not_allowed"}});const o=n.socket.remoteAddress;if(["127.0.0.1","::1","::ffff:127.0.0.1"].includes(o??""))try{const e=process.env.BEEOS_SANDBOX_NATIVE_TOKEN_FILE;if(!e)throw new Error("native control token file is unavailable");const i=(await readFile(e,"utf8")).trim(),r=Buffer.from(`Bearer ${i}`),o=Buffer.from(n.headers.authorization??"");if(!i||o.length!==r.length||!timingSafeEqual(o,r))return void a(401,{error:{code:"native_control_unauthorized"}});const s=await body(n);if(!object(s))throw new Error("native control request must be an object");a(200,"credentials"===t?await controller.credentials(s):"target"===t?await controller.target(s):"prepare"===t?await controller.prepare(s):await controller.drain(s))}catch(e){a(503,{error:{code:"native_preparation_unavailable",message:e instanceof Error?e.message:String(e)}})}else a(403,{error:{code:"native_loopback_required"}})}})}export function preparedSandboxNativeExecution(e,t){if(!controller)throw new Error("actual native Sandbox activation is unavailable");return controller.execution(e,t)}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "beeos-claw",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.93",
|
|
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": "
|
|
93
|
+
"gitHead": "278210cc10bb594c61ebef419bb16481d9fcab4c"
|
|
94
94
|
}
|