beeos-claw 0.6.41 → 0.6.42
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/acp-gateway/bridge-core.js +1 -1
- package/dist/canvas/relay-client.js +1 -1
- package/dist/canvas/tools.js +1 -1
- package/dist/canvas-orchestrator.js +1 -1
- package/dist/runtime/openclaw-session-key-resolution.js +1 -1
- package/package.json +3 -2
- package/scripts/runtime-blackbox-worker-lease.mjs +18 -0
- package/scripts/runtime-blackbox-worker-main.mjs +6 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID,createHash}from"node:crypto";import{mkdir,readFile,rm,stat,readdir,rename,cp}from"node:fs/promises";import path from"node:path";import{join,resolve,relative,sep}from"node:path";import{homedir}from"node:os";import AdmZip from"adm-zip";import{sanitizePromptPayload}from"../message-sanitization/prompt-payload-sanitizer.js";import{previewSanitizedText,stripTransportMetadata}from"../message-sanitization/transport-metadata-sanitizer.js";import{isHeartbeatPromptText,isCronPromptText,extractCronJobId,classifyHeartbeatFilter}from"../message-sanitization/message-classifier.js";import{createCronOverridesStore,createInMemoryCronOverridesStore}from"../cron-overrides.js";import{CRON_DURATION_FLOOR_MS}from"../config.js";import{CANVAS_TERM_MAPPING,CANVAS_UPDATE_HINT,buildActiveSurfacesContext}from"../canvas/tools.js";import{parseMentionsParam,buildMentionInstruction}from"../delegation/mention-resolver.js";import{EXTERNAL_PROTOCOL_TAGS}from"./external-protocol-tags.js";import{extractPromptBlocks,toGatewayPrompt,resolveSlashCommandName as resolveSlashCmd}from"./prompt-converter.js";import{extractBeeosUserTextFromHistoryContent}from"./beeos-user-envelope.js";import{loadHistory,loadHistoryPage,groupIntoTurns,splitUserReplayBlocks}from"./history-replay.js";import{classifyHistoricalAssistantTurnCompletion}from"./history-turn-completion-policy.js";import{LocalSessionHistory}from"./local-session-history.js";import{reconcileMissingArtifacts}from"./missing-artifacts-reconciler.js";import{buildResolutionPlan,resolveResources,applyResolutions}from"./prompt-resource-resolver.js";import{readEnrichmentCache,readUploadToolResult}from"../upload/result-cache.js";import{buildToolResultSessionContentBlocks}from"./tool-result-blocks.js";import{prefersChatFileArtifacts}from"./file-artifact-presenter.js";import{buildToolCallPayload,buildToolCallUpdatePayload}from"./tool-call-payload-builder.js";import{Errors}from"../errors/index.js";import{classifyAgentRuntimeFailure,INTERRUPTED_PUBLIC_MESSAGE}from"../runtime/agent-runtime-failure-classifier.js";import{isPlaceholderTitle}from"../runtime/conversation-title.js";import{SESSION_RECOVERY_REQUIRED_CODE,SESSION_RECOVERY_REQUIRED_MESSAGE}from"../runtime/session-mutation-coordinator.js";import{observeLifecyclePromise}from"../runtime/lifecycle-promise-observer.js";import{RuntimeSessionNewRejectedError}from"../runtime/runtime-rpc-consumer.js";import{normalizeRuntimeAgentLocalKey,OpenClawRuntimeCommandDispatcher,RuntimeCommandError}from"../runtime/runtime-command-dispatcher.js";import{FileRuntimeAgentIdentityRegistry}from"../runtime/runtime-agent-identity-registry.js";import{FileRuntimeLeasePort}from"../runtime/runtime-operation-lease.js";import{FileRuntimeCommandJournal,InMemoryRuntimeCommandJournal}from"../runtime/runtime-command-journal.js";import{OpenClawRuntimeCapabilities}from"../runtime/openclaw-runtime-capabilities.js";import{RuntimeCanvasService}from"../canvas/runtime-canvas-service.js";import{RuntimeSkillsService}from"../runtime/runtime-skills-service.js";import{RuntimeCronService,encodeBeeosChannelTag}from"../runtime/runtime-cron-service.js";export{BEEOS_CHANNEL_TAG_RE,decodeBeeosChannelId,encodeBeeosChannelTag,stripBeeosChannelTag}from"../runtime/runtime-cron-service.js";import{openClawKeyMatchesConversation,openClawSessionKeysFromList,resolveLiveOpenClawSessionKey}from"../runtime/openclaw-session-key-resolution.js";import{LocalConversationHistoryBoundary,OpenClawGatewaySessionMetadataPort,OpenClawSessionMetadataService,RuntimeSessionControlService}from"../runtime/runtime-session-control-service.js";import{pageRuntimeSessions,parseRuntimeSessionListPage}from"../runtime/runtime-session-list-policy.js";import{assertTrustedCoreExecutionAttempt,createAcpCoreExecutionAttempt}from"../runtime/core-execution-attempt-context.js";import{CompositeActiveRunPort}from"../runtime/composite-active-run-port.js";import{resolveChannelFromSessionKey}from"../channel-detection.js";import{resolveTurnId,recordTurnIdForRole,recordToolCallTurnForUpdate}from"./gateway-events.js";import{emitToolResultProjectionForTurn}from"./tool-result-emitter.js";import{extractPersistedToolResultEnvelope,findPersistedToolResultEnvelopeByMessageId}from"./tool-result-transcript.js";import{projectPersistedToolResultForReplay}from"./tool-result-projection.js";import{McpService}from"./mcp-service.js";import{McpDesiredStateStore,normalizeMcpPublicServerConfig}from"./mcp-desired-state-store.js";import{requireSecretFreeMcpServerName}from"./mcp-public-config-security.js";import{McpDesiredStateController}from"./mcp-desired-state-controller.js";import{McpNativeConfigProjector}from"./mcp-native-config-projector.js";import{CredentialReferenceRuntimeResolver}from"./mcp-credential-reference-port.js";import{DEFAULT_PROMPT_TIMEOUT_MS}from"./types.js";import{ACP_PROTOCOL_VERSION}from"@beeos-ai/beeos-types/acp";import{canonicalizeJcs}from"@beeos-ai/beeos-types/runtime";import{MAX_ZIP_BYTES,parseAndValidateTemplatePackage,TemplatePackageError}from"./agent-template-package.js";const DEFAULT_AGENT_ID="main";export function normalizeAgentId(e){return normalizeRuntimeAgentLocalKey(e)}function narrowContentBlock(e){switch(e.type){case"text":return"string"==typeof e.text?{type:"text",text:e.text}:void 0;case"resource_link":return"string"==typeof e.uri?{type:"resource_link",uri:e.uri,...void 0!==e.name?{name:e.name}:{},...void 0!==e.mimeType?{mimeType:e.mimeType}:{}}:void 0;case"file":return{type:"file",...void 0!==e.text?{text:e.text}:{},...void 0!==e.uri?{uri:e.uri}:{},...void 0!==e.mimeType?{mimeType:e.mimeType}:{}};case"image":return{type:"image",...void 0!==e.uri?{uri:e.uri}:{},...void 0!==e.mimeType?{mimeType:e.mimeType}:{}};default:return}}const DEFAULT_MODE={id:"default",name:"Default",description:"Default agent mode"},USER_MESSAGE_PREFIX="User Message From BeeOS:",USER_MESSAGE_PREFIX_WITH_NEWLINE=`${USER_MESSAGE_PREFIX}\n`,SLASH_COMMAND_NAME_RE=/^[a-z0-9_-]+$/i,HISTORY_PAGE_DEFAULT_LIMIT=100,HISTORY_PAGE_MAX_LIMIT=1e3;function withUserMessagePrefix(e){return e.startsWith(USER_MESSAGE_PREFIX)?e:`${USER_MESSAGE_PREFIX_WITH_NEWLINE}${e}`}const BACKGROUND_SESSION_PATTERNS=[":cron:",":hook:","node-",...EXTERNAL_PROTOCOL_TAGS];function isBackgroundSessionKey(e){return BACKGROUND_SESSION_PATTERNS.some(t=>e.includes(t))}function isSystemDefaultSessionKey(e){const t=e.split(":");if(t.length<3||"agent"!==t[0])return!1;const s=t.slice(2).join(":");return"main"===s||s===t[1]}function cleanGatewayDerivedTitle(e){if(!e)return;let t=extractBeeosUserTextFromHistoryContent(e).text;return/^\[System\b/.test(t)?void 0:(t=t.trim(),t||void 0)}function cleanHistoryUserContent(e){return extractBeeosUserTextFromHistoryContent(e).text.trim()}function mergePersistedToolResultEnvelopes(e,t){if(e||t)return{toolName:e?.toolName||t?.toolName||"tool",...e?.toolCallId||t?.toolCallId?{toolCallId:e?.toolCallId??t?.toolCallId}:{},...e?.rawText??t?.rawText?{rawText:e?.rawText??t?.rawText}:{},...void 0!==e?.rawResult||void 0!==t?.rawResult?{rawResult:e?.rawResult??t?.rawResult}:{},...e?.timestamp||t?.timestamp?{timestamp:e?.timestamp??t?.timestamp}:{}}}function resolveStandaloneSlashCommandName(e,t){if(0===e.length)return;if(e.some(e=>"text"!==e.type))return;const s=t.trim();if(!s||s.includes("\n")||!s.startsWith("/"))return;const i=s.match(/^\/([^\s:]+)(?::|\s|$)/)?.[1]?.trim();return i&&!i.includes("/")&&SLASH_COMMAND_NAME_RE.test(i)?i.toLowerCase():void 0}class AcpRuntimeCommandResourceStore{fetchPackage;parsePackage;isValidationError;content=new Map;artifacts=new Map;mcpDefinitions=new Map;constructor(e,t,s){this.fetchPackage=e,this.parsePackage=t,this.isValidationError=s}registerContent(e){const t=`acp-content:sha256:${createHash("sha256").update(e).digest("hex")}`;return this.content.set(t,e),t}registerMcpDefinition(e,t){this.mcpDefinitions.set(JSON.stringify(e),structuredClone(t))}async resolveMcpDefinition(e){const t=this.mcpDefinitions.get(JSON.stringify(e));if(!t)throw new Error("ACP MCP definition was not verified for this request");return structuredClone(t)}async registerArtifact(e,t){try{const s=await this.fetchPackage(e);if(!s.ok)throw new TemplatePackageError(`failed to download package: HTTP ${s.status}`);const i=Buffer.from(await s.arrayBuffer());if(i.length>MAX_ZIP_BYTES)throw new TemplatePackageError(`package too large: ${i.length} bytes (max ${MAX_ZIP_BYTES})`);const n=createHash("sha256").update(i).digest("hex");if(t?.trim()&&t.trim().toLowerCase()!==n)throw new TemplatePackageError("package sha256 mismatch");const r=this.parsePackage(i),o=`acp-artifact:sha256:${n}`;return this.artifacts.set(o,r),{artifactRef:o,version:r.manifest?.version??"0.0.0",sha256:n,sizeBytes:String(i.length),source:"acp-verified"}}catch(e){if(e instanceof TemplatePackageError||this.isValidationError(e))throw new RuntimeCommandError("INVALID_PARAMS",`Invalid template package: ${e instanceof Error?e.message:String(e)}`);throw new RuntimeCommandError("EXECUTION_FAILED",`Apply template failed: ${e instanceof Error?e.message:String(e)}`)}}registerParsedArtifact(e){const t=createHash("sha256");for(const[s,i]of[...e.workspaceFiles].sort(([e],[t])=>e.localeCompare(t)))t.update(s).update("\0").update(i).update("\0");const s=t.digest("hex"),i=`acp-artifact:sha256:${s}`;this.artifacts.set(i,e);const n=[...e.workspaceFiles.values()].reduce((e,t)=>e+t.byteLength,0);return{artifactRef:i,version:e.manifest?.version??"0.0.0",sha256:s,sizeBytes:String(n),source:"acp-verified"}}async readContent(e){const t=this.content.get(e);if(void 0===t)throw new Error(`unknown contentRef: ${e}`);return t}async readVerifiedArtifact(e){const t=this.artifacts.get(e.artifactRef);if(!t)throw new Error(`unknown verified artifact: ${e.artifactRef}`);return t}}export const lateBoundRuntimeAgentProjectionPort=e=>({prepareCommittedMutation:async t=>{const s=e();if(!s)throw new Error("agent projection production is unavailable");return await s.prepareCommittedMutation(t)},applyCommittedMutation:async t=>{const s=e();if(!s)throw new Error("agent projection production is unavailable");return await s.applyCommittedMutation(t)},compactCommittedMutation:async t=>{const s=e();if(!s)throw new Error("agent projection production is unavailable");await s.compactCommittedMutation(t)}});function deriveSessionId(e,t){const s=createHash("sha256").update(`${t}:${e}`).digest("hex").substring(0,32);return`session:${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20,32)}`}function parseAgentIdFromKey(e){const t=e.split(":");return(t.length>=3&&"agent"===t[0]?t[1]:"")||"main"}function createSessionObject(e){const t=parseAgentIdFromKey(e.gatewayKey);return{sessionId:deriveSessionId(e.gatewayKey,e.instanceId),gatewaySessionKey:e.gatewayKey,agentId:t,platformAgentId:e.resolvePlatformAgentId?.(t),createdAt:Date.now(),chatReplayDedupKeys:new Set,cwd:e.cwd,title:e.title,channelType:resolveChannelFromSessionKey(e.gatewayKey,e.thirdPartyChannels)}}class HistoryUpdateRecorder{transport;updates=[];constructor(e){this.transport=e}sendSessionUpdate(e,t,s){const i=this.transport.materializeSessionUpdate(t,s);return null!==i&&this.updates.push(i),!0}}export class AcpGatewayBridgeCore{state;transport;config;logger;writeObs;getGateway;thirdPartyChannels;beeosFileResolver;agentFetch;agentGatewayUrl;triggerAgentSync;sessionMutationCoordinator;runtimeCommands;runtimeAgentIdentities;runtimeLeases;runtimeCommandResources;localHistoryBoundary;activeRuns;markAgentProjectionDirty;projectionObservationTimeoutMs;cronChannelCache=new Map;static CRON_CHANNEL_CACHE_MAX=256;localSessionHistory;mcp;runtimeTerminalService;initialized=!1;agentMapping=null;_syncResolvers=[];_mappingReadyCallbacks=[];_mappingUpdateCallbacks=[];cronIsolatedSessionKeys=new Set;cronOverrides;cronReady;sessionPreloadInFlight=null;sessionPreloadInFlightGeneration=null;sessionPreloadReady=Promise.resolve();resolveSessionPreloadReady=null;rejectSessionPreloadReady=null;sessionPreloadGeneration=0;sessionPreloadBarrierActive=!1;sessionPreloadFailed=!1;async setAgentMapping(e){this.agentMapping=e;for(const t of this.state.sessions.values())!t.platformAgentId&&t.agentId&&(t.platformAgentId=e.get(t.agentId)?.id);for(const e of this._syncResolvers)e();this._syncResolvers=[];for(const e of this._mappingReadyCallbacks)e();this._mappingReadyCallbacks=[];for(const t of this._mappingUpdateCallbacks)t(e);this.sessionPreloadFailed&&this.beginGatewaySessionPreload(),this.sessionPreloadBarrierActive&&await this.preloadSessionsFromGateway()}beginGatewaySessionPreload(){this.sessionPreloadBarrierActive&&this.sessionPreloadReady.catch(()=>{}),this.sessionPreloadGeneration+=1,this.sessionPreloadBarrierActive=!0,this.sessionPreloadFailed=!1,this.sessionPreloadReady=new Promise((e,t)=>{this.resolveSessionPreloadReady=e,this.rejectSessionPreloadReady=t}),this.sessionPreloadReady.catch(()=>{})}failGatewaySessionPreload(){this.sessionPreloadBarrierActive&&(this.sessionPreloadBarrierActive=!1,this.sessionPreloadFailed=!0,this.rejectSessionPreloadReady?.(new RuntimeCommandError("GATEWAY_NOT_CONNECTED","Gateway disconnected before session hydration completed")),this.resolveSessionPreloadReady=null,this.rejectSessionPreloadReady=null)}async waitForGatewaySessionPreload(){await this.sessionPreloadReady}onceAgentMappingReady(e){this.agentMapping&&this.agentMapping.size>0?e():this._mappingReadyCallbacks.push(e)}onAgentMappingUpdated(e){this._mappingUpdateCallbacks.push(e),this.agentMapping&&this.agentMapping.size>0&&e(this.agentMapping)}markAgentSyncDone(){for(const e of this._syncResolvers)e();this._syncResolvers=[]}waitForAgentMapping(e=15e3){return this.agentMapping?Promise.resolve():new Promise(t=>{this._syncResolvers.push(t);const s=setTimeout(()=>{const e=this._syncResolvers.indexOf(t);-1!==e&&this._syncResolvers.splice(e,1),t()},e);"object"==typeof s&&"unref"in s&&s.unref()})}handleTerminalRequest=null;handleTerminalNotification=null;onRunComplete=null;onRunFailed=null;onRunEnded=null;handleSlashCommand=null;onPromptStart=null;instanceId;getAuthoritativeInstanceId;mcpCredentialReferences;constructor(e){this.state=e.state,this.transport=e.transport,this.config=e.config,this.logger=e.logger,this.writeObs=e.writeObs,this.getGateway=e.getGateway,this.instanceId=e.instanceId||"unknown",this.getAuthoritativeInstanceId=e.getAuthoritativeInstanceId,this.mcpCredentialReferences=e.mcpCredentialReferences,this.thirdPartyChannels=e.thirdPartyChannels??new Set,this.beeosFileResolver=e.beeosFileResolver,this.agentFetch=e.agentFetch,this.agentGatewayUrl=e.agentGatewayUrl,this.triggerAgentSync=e.triggerAgentSync,this.markAgentProjectionDirty=e.markAgentProjectionDirty,this.projectionObservationTimeoutMs=e.projectionObservationTimeoutMs??5e3,this.sessionMutationCoordinator=e.sessionMutationCoordinator,this.runtimeAgentIdentities=e.runtimeAgentIdentities??new FileRuntimeAgentIdentityRegistry(join(process.env.OPENCLAW_HOME||join(homedir(),".openclaw"),"beeos","runtime-agent-identities.json")),this.runtimeLeases=e.runtimeLeases??new FileRuntimeLeasePort(join(process.env.OPENCLAW_HOME||join(homedir(),".openclaw"),"beeos","runtime-operation-leases.json")),this.runtimeCommandResources=e.runtimeCommandResources??new AcpRuntimeCommandResourceStore(e.agentFetch??((e,t)=>fetch(e,t)),e.runtimeTemplatePackageParser?.parse??parseAndValidateTemplatePackage,e.runtimeTemplatePackageParser?.isValidationError??(e=>e instanceof TemplatePackageError));const t=e.runtimeCommandJournal??(e.runtimeLeases||process.env.VITEST?new InMemoryRuntimeCommandJournal:new FileRuntimeCommandJournal(join(process.env.OPENCLAW_HOME||join(homedir(),".openclaw"),"beeos","runtime-command-journal.json")));this.localSessionHistory=new LocalSessionHistory({logger:this.logger}),this.cronOverrides=e.cronOverrides??(process.env.VITEST?createInMemoryCronOverridesStore():createCronOverridesStore(this.logger)),this.cronReady=this.cronOverrides.initialize(),this.cronReady.catch(()=>{});const s=e.mcpCredentialReferences?new CredentialReferenceRuntimeResolver(e.mcpCredentialReferences):void 0,i=e.mcpToolBridge?new McpDesiredStateController(new McpDesiredStateStore(e.mcpDesiredStatePath??join(process.env.OPENCLAW_HOME||join(homedir(),".openclaw"),"beeos","mcp-desired-state.json")),e.mcpToolBridge,s,e.mcpCredentialReferences,t,e.runtimeReceiptHistory,new McpNativeConfigProjector({logger:this.logger})):void 0;this.mcp=new McpService({transport:this.transport,logger:this.logger,state:this.state,...i?{desiredState:i}:{}}),this.localHistoryBoundary=new LocalConversationHistoryBoundary(e=>{const t=this.state.sessions.get(e);t&&(t.chatReplayDedupKeys.clear(),this.onSessionCleared?.(t.sessionId,t.gatewaySessionKey))}),this.activeRuns=e.activeRuns??new CompositeActiveRunPort;const n=new RuntimeCronService({getGateway:e.getGateway,overrides:this.cronOverrides,durationFloorMs:CRON_DURATION_FLOOR_MS,durationCapMs:this.config.cronMaxDurationCapMs,channels:{allocate:async e=>await this.allocateCronChannel(e),lookup:e=>this.cronChannelCache.get(e),remember:(e,t)=>this.setCronChannelCache(e,t),forget:e=>{this.cronChannelCache.delete(e)}}}),r=new RuntimeSessionControlService({convergeRun:async({runtimeSessionKey:e})=>{const t=this.state.sessionsByGatewayKey.get(e),s=(new Date).toISOString();if(!t||t.promptDone&&void 0===t.pendingPromptId&&void 0===t.currentRunId)return{state:"no_active_run",quiescence:{state:"verified",observedAt:s}};const i=this.getGateway();if(!i?.isConnected)return{state:"recovery_required",reason:"gateway_disconnected"};if(!t.writeGateToken||!t.currentRunId)return{state:"recovery_required",reason:"run_conflict",runtimeRunId:t.currentRunId??"unknown"};const n=t.currentRunId,r=await this.sessionMutationCoordinator.requestCancel(t.writeGateToken,i);if(!r.ok)return{state:"recovery_required",reason:"terminal_not_observed",runtimeRunId:n};const o=await r.terminalObservation;return o.ok?{state:"terminal_observed",runtimeRunId:n,abortObservation:r.acknowledged?{state:"target_acknowledged",aborted:!0,runIds:[n],targetRunAcknowledged:!0}:{state:"already_stopped",aborted:!1,runIds:[]},terminalState:"cancelled",quiescence:{state:"verified",observedAt:(new Date).toISOString()}}:{state:"recovery_required",reason:"quiescence_failed"===o.recovery.reason?"quiescence_failed":"quiescence_timeout"===o.recovery.reason?"quiescence_timeout":"terminal_not_observed",runtimeRunId:n}},reset:async e=>{const t=this.getGateway();if(!t?.isConnected)throw new RuntimeCommandError("GATEWAY_NOT_CONNECTED","Gateway not connected");await t.sessionsReset(e)}},new OpenClawSessionMetadataService(new OpenClawGatewaySessionMetadataPort(e.getGateway,(e,t)=>{const s=this.state.sessionsByGatewayKey.get(e);if(!s)throw new RuntimeCommandError("INVALID_PARAMS",`setModel projection requires a live local session for key=${e}`);void 0===t.modelOverrideId?delete s.modelOverrideId:s.modelOverrideId=t.modelOverrideId,s.effectiveModelId=t.effectiveModelId,void 0===t.modelProvider?delete s.modelProvider:s.modelProvider=t.modelProvider},{resolveLiveKey:e=>resolveLiveOpenClawSessionKey(e,this.state.sessions.values()),waitForHydration:async()=>await this.waitForGatewaySessionPreload(),reconcileMissingLiveKey:async(e,t)=>await this.reconcileMissingGatewaySession(e,t),materializeMissingModelKey:async(e,t)=>await this.materializeMissingModelSessionKey(e,t),registerMaterializedModelKey:e=>this.registerMaterializedModelSession(e)})),this.activeRuns),o=e.getAgentProjection?lateBoundRuntimeAgentProjectionPort(e.getAgentProjection):void 0,a=e.runtimeCommandDispatcher??new OpenClawRuntimeCommandDispatcher({getGateway:e.getGateway,resources:this.runtimeCommandResources,identities:this.runtimeAgentIdentities,leases:this.runtimeLeases,journal:t,logger:e.logger,...o?{projection:o}:{},...e.templateOriginReporter?{templateOriginReporter:e.templateOriginReporter}:{}});this.runtimeCommands=a,a instanceof OpenClawRuntimeCommandDispatcher&&a.setCapabilities(new OpenClawRuntimeCapabilities({getGateway:e.getGateway,identities:this.runtimeAgentIdentities,sessions:r,skills:new RuntimeSkillsService({getGateway:e.getGateway,resources:this.runtimeCommandResources,getOpenclawHome:()=>this.getOpenclawHome()}),mcp:this.mcp,terminal:{execute:async(e,t)=>{if(!this.runtimeTerminalService)throw new RuntimeCommandError("INVALID_PARAMS","terminal canonical delegate is not configured");return await this.runtimeTerminalService.execute(e,t)}},canvas:new RuntimeCanvasService({apply:async(e,t)=>{await this.applyCanonicalCanvasControl(e,t)}}),cron:n})),this.transport.setSessionUpdateObserver((e,t,s)=>{const i=s?.turnId;if(!i)return;const n=this.state.sessions.get(e);n&&(recordTurnIdForRole(n,t,i),recordToolCallTurnForUpdate(n,t,i))})}setRuntimeTerminalService(e){this.runtimeTerminalService=e}setRuntimeReceiptHistoryPort(e){this.mcp.setRuntimeReceiptHistoryPort(e)}getRuntimeCommandDispatcher(){return this.runtimeCommands}async startMcp(){await this.mcp.start()}async stopMcp(){await this.mcp.stop()}nudgeMcpNativeProjection(){this.mcp.nudgeNativeProjection()}observeActiveRun(e){const t=e.currentRunId,s=e.writeGateToken,i=this.sessionMutationCoordinator.snapshot(e.gatewaySessionKey),n=void 0===e.pendingPromptId?e.gatewayRequestId??t:String(e.pendingPromptId);if(!t||!i||!n)return;const r={runtimeConversationUid:e.sessionId,runtimeSessionKey:e.gatewaySessionKey,historyGeneration:this.localHistoryBoundary.currentGeneration(e.sessionId),targetMessageId:n,runtimeRunId:t,activeRunRegistrationId:`acp:${i.operationId}`};return this.activeRuns.register(r,async()=>{const n=this.getGateway();if(!n?.isConnected||e.currentRunId!==t)return"recovery_required";const r=s?.operationId===i.operationId?await this.sessionMutationCoordinator.requestCancel(s,n):await this.sessionMutationCoordinator.requestCancelForSession(e.gatewaySessionKey,n);return r.ok?"accepted":!("reason"in r)||"terminal_already_observed"!==r.reason&&"no_active_mutation"!==r.reason?"recovery_required":"already_terminal"}),e.activeRunBinding=r,r}getActiveRunAuthority(){return{activeRuns:this.activeRuns,historyGeneration:e=>this.localHistoryBoundary.currentGeneration(e)}}resolvePlatformAgentId(e){return this.agentMapping?.get(e)?.id}resolveLocalAgentId(e){if(this.agentMapping&&e)for(const[t,s]of this.agentMapping)if(s.id===e)return t}getDefaultAgentId(){return this.agentMapping&&this.agentMapping.size>0?this.agentMapping.keys().next().value??"main":"main"}registerSession(e,t={}){const{ensureVerbose:s=!0}=t;this.state.sessions.has(e.sessionId);this.state.sessions.set(e.sessionId,e),this.state.sessionsByGatewayKey.set(e.gatewaySessionKey,e),s&&this.ensureVerboseFull(e),this.subscribeSessionMessages(e)}async ensureVerboseFull(e){if(e.verbosePatched)return;const t=this.getGateway();if(t?.isConnected){e.verbosePatched=!0;try{await t.sessionsPatch(e.gatewaySessionKey,{verboseLevel:"full"})}catch(t){e.verbosePatched=!1,this.logger.debug?.(`[bridge-core] ensureVerboseFull failed: ${t instanceof Error?t.message:t}`)}}}ensureSessionForKey(e){const t=this.state.findSessionByKey(e);if(t)return t;const s=createSessionObject({gatewayKey:e,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels});return this.registerSession(s),this.logger.debug?.(`[bridge-core] ensureSessionForKey: lazily created session sid=${s.sessionId} key=${e}`),s}async preloadSessionsFromGateway(){const e=this.sessionPreloadGeneration;if(this.sessionPreloadInFlight&&this.sessionPreloadInFlightGeneration===e)return await this.sessionPreloadInFlight;const t=this.preloadGatewaySessionIndex(e);this.sessionPreloadInFlight=t,this.sessionPreloadInFlightGeneration=e;try{await t,e===this.sessionPreloadGeneration&&this.sessionPreloadBarrierActive&&(this.sessionPreloadBarrierActive=!1,this.resolveSessionPreloadReady?.(),this.resolveSessionPreloadReady=null,this.rejectSessionPreloadReady=null)}catch(t){throw e===this.sessionPreloadGeneration&&this.sessionPreloadBarrierActive&&(this.sessionPreloadBarrierActive=!1,this.sessionPreloadFailed=!0,this.rejectSessionPreloadReady?.(t instanceof Error?t:new Error("session preload failed")),this.resolveSessionPreloadReady=null,this.rejectSessionPreloadReady=null),t}finally{this.sessionPreloadInFlight===t&&(this.sessionPreloadInFlight=null,this.sessionPreloadInFlightGeneration=null)}}async preloadGatewaySessionIndex(e){const t=this.getGateway();if(this.logSessionAuthority("session_preload_start",{generation:e,reason:t?.isConnected?"gateway_connected":"gateway_not_connected"}),!t?.isConnected)throw this.logSessionAuthority("session_preload_failure",{generation:e,reason:"gateway_not_connected"}),new RuntimeCommandError("GATEWAY_NOT_CONNECTED","Gateway not connected for session hydration");try{const s=await t.sessionsList(),i=this.mergeGatewaySessions(s);this.logSessionAuthority("session_preload_success",{generation:e,loaded:i,reason:"authoritative_sessions_list"})}catch(t){throw this.logSessionAuthority("session_preload_failure",{generation:e,reason:t instanceof RuntimeCommandError?t.code:"sessions_list_failed"}),t}}mergeGatewaySessions(e,t){if(!e||"object"!=typeof e)return 0;const s=e.sessions;if(!Array.isArray(s))return 0;let i=0;for(const e of s){if(!e||"object"!=typeof e||Array.isArray(e))continue;const s=e,n=s.sessionKey??s.key??s.id??s.name;if("string"!=typeof n||!n.trim()||n.trim()!==n||t&&!t(n)||this.state.findSessionByKey(n))continue;const r=s.label||s.derivedTitle||s.title||void 0,o=r&&!isPlaceholderTitle(r)?r:void 0;this.registerSession(createSessionObject({gatewayKey:n,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,title:o}),{ensureVerbose:!1}),i+=1}return i}async reconcileMissingGatewaySession(e,t){await this.assertSessionReconcileFence(t);const s=this.getGateway();if(!s?.isConnected)throw this.logSessionAuthority("session_reconcile_decision",{reason:"gateway_not_connected",runtimeSessionKeyHash:this.sessionKeyHash(e)}),new RuntimeCommandError("GATEWAY_NOT_CONNECTED","Gateway not connected for session reconciliation");const i=await s.sessionsList();await this.assertSessionReconcileFence(t);const n=!e.startsWith("agent:"),r=[...openClawSessionKeysFromList(i)].filter(t=>t===e?!n:openClawKeyMatchesConversation(t,e));if(this.logSessionAuthority("session_reconcile_decision",{reason:r.length?"exact_candidates":"no_exact_candidate",runtimeSessionKeyHash:this.sessionKeyHash(e),candidateHashes:r.map(e=>this.sessionKeyHash(e))}),!r.length)return;const o=new Set(r),a=this.mergeGatewaySessions(i,e=>o.has(e));this.logSessionAuthority("session_reconcile_decision",{reason:"reconciled_exact_candidates",runtimeSessionKeyHash:this.sessionKeyHash(e),loaded:a,candidateHashes:r.map(e=>this.sessionKeyHash(e))})}async materializeMissingModelSessionKey(e,t){await this.assertSessionReconcileFence(t);const s=t.attempt,i=s.verifiedMessageGrant?.claims,n=i?.command;if("service"!==s.origin||!i||"conversation"!==i.scope||"session/set_model"!==i.method||"session.setModel"!==n?.name||"conversation"!==n.context.scope||i.runtimeSessionKey!==e||i.runtimeConversationUid!==e||n.context.conversation.runtimeSessionKey!==e||n.context.conversation.runtimeConversationUid!==i.runtimeConversationUid)throw this.logSessionAuthority("model_intent_materialization_rejected",{reason:"verified_service_target_required",runtimeSessionKeyHash:this.sessionKeyHash(e)}),new RuntimeCommandError("INVALID_PARAMS","model-intent session materialization requires an exact verified Service target");if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e))throw new RuntimeCommandError("INVALID_PARAMS","model-intent session materialization requires a canonical conversation UUID");let r;try{if(!this.runtimeAgentIdentities.resolveActiveLocalKey)throw new Error("identity resolver unavailable");r=await this.runtimeAgentIdentities.resolveActiveLocalKey(i.runtimeAgentUid)}catch{throw new RuntimeCommandError("INVALID_PARAMS","verified model-intent runtime agent is not active")}if(this.resolveLocalAgentId(i.platformAgentId)!==r)throw new RuntimeCommandError("INVALID_PARAMS","verified model-intent agent does not match the active platform projection");const o=`agent:${r}:beeos-conversation:ctx-${e}`,a=this.getGateway();if(!a?.isConnected)throw new RuntimeCommandError("GATEWAY_NOT_CONNECTED","Gateway not connected for model-intent session materialization");const l=await a.sessionsList();await this.assertSessionReconcileFence(t);const c=[...openClawSessionKeysFromList(l)].filter(t=>openClawKeyMatchesConversation(t,e));if(c.length){if(1===c.length&&c[0]===o)return this.mergeGatewaySessions(l,e=>e===o),o;throw new RuntimeCommandError("INVALID_PARAMS","verified model-intent target conflicts with an existing OpenClaw session")}return this.logSessionAuthority("model_intent_materialization_allowed",{runtimeSessionKeyHash:this.sessionKeyHash(e),openClawSessionKeyHash:this.sessionKeyHash(o)}),o}registerMaterializedModelSession(e){this.state.findSessionByKey(e)||(this.registerSession(createSessionObject({gatewayKey:e,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels}),{ensureVerbose:!1}),this.logSessionAuthority("model_intent_materialization_committed",{openClawSessionKeyHash:this.sessionKeyHash(e)}))}async assertSessionReconcileFence(e){if(e.lease.operationId!==e.attempt.operationId||e.lease.runtimeEpoch!==e.attempt.runtimeEpoch||e.attempt.abortSignal?.aborted)throw this.logSessionAuthority("session_reconcile_decision",{reason:"operation_fence_mismatch"}),new RuntimeCommandError("INVALID_PARAMS","session reconciliation is fenced");try{await this.runtimeLeases.renew(e.lease)}catch{throw this.logSessionAuthority("session_reconcile_decision",{reason:"lease_epoch_mismatch"}),new RuntimeCommandError("INVALID_PARAMS","session reconciliation is fenced")}if(e.attempt.abortSignal?.aborted)throw this.logSessionAuthority("session_reconcile_decision",{reason:"operation_aborted"}),new RuntimeCommandError("INVALID_PARAMS","session reconciliation is fenced")}sessionKeyHash(e){return createHash("sha256").update(e).digest("hex").slice(0,16)}logSessionAuthority(e,t){this.logger.info?.(`[bridge-core] ${JSON.stringify({event:e,...t})}`)}async handleRequest(e){this.writeObs({component:"bridge-core",domain:"forward",name:`rpc.request.${e.method}`,severity:"debug",payload:{id:e.id,method:e.method}});const t=e;try{switch(t.method){case"initialize":await this.handleInitialize(t);break;case"ping":this.transport.sendResult(t.id,{pong:!0});break;case"session/new":await this.handleSessionNew(t);break;case"session/load":await this.handleSessionLoad(t);break;case"session/list":await this.handleSessionList(t);break;case"session/rename":await this.handleSessionRename(t);break;case"session/delete":await this.handleSessionDelete(t);break;case"session/clear":await this.handleSessionClear(t);break;case"session/prompt":await this.handleSessionPrompt(t);break;case"session/set_mode":await this.handleSessionSetMode(t);break;case"session/set_model":await this.handleSessionSetModel(t);break;case"agent/create":await this.handleAgentCreate(t);break;case"agent/update":await this.handleAgentUpdate(t);break;case"agent/delete":await this.handleAgentDelete(t);break;case"agent/applyTemplate":await this.handleApplyTemplate(t);break;case"skills/list":await this.handleSkillsList(t);break;case"skills/install":await this.handleSkillsInstall(t);break;case"skills/uninstall":await this.handleSkillsUninstall(t);break;case"skills/update":await this.handleSkillsUpdate(t);break;case"models/list":await this.handleModelsList(t);break;case"session/cancel":await this.handleSessionCancel(t.id,t.params);break;case"cron/list":case"cron/status":case"cron/add":case"cron/update":case"cron/remove":case"cron/run":case"cron/runs":await this.handleCronRequest(t);break;default:"agent/list"===e.method?await this.handleAgentList(e):"_beeos/session/history"===e.method?await this.handleSessionHistoryPage(e):"mcp/list"===e.method?await this.handleMcpList(e):"mcp/set"===e.method?await this.handleMcpSet(e):"mcp/unset"===e.method?await this.handleMcpUnset(e):e.method.startsWith("terminal/")&&this.handleTerminalRequest?await this.handleTerminalRequest(e):this.transport.sendAcpError(e.id,Errors.MethodNotFound,{message:`Method not found: ${e.method}`})}}catch(t){this.transport.sendAcpError(e.id,Errors.InternalError,{message:t instanceof Error?t.message:"Internal error"})}}handleCanvasNotification=null;getCanvasState=null;onSessionLoaded=null;onSkillInstalled=null;onSessionDeleted=null;onSessionCleared=null;handleNotification(e){switch(e.method){case"session/cancel":this.observeLifecycle(this.handleSessionCancel(void 0,e.params),"session_cancel_notification");break;case"canvas/toggle":case"canvas/clear":case"canvas/reference":case"canvas/dimensions":this.observeLifecycle(this.dispatchLegacyCanvasNotification(e.method,e.params),`canvas_notification_${e.method.replace("/","_")}`);break;default:e.method.startsWith("terminal/")&&this.handleTerminalNotification?this.handleTerminalNotification(e.method,e.params):this.logger.debug?.(`[bridge-core] Unknown notification: ${e.method}`)}}async handleInitialize(e){await this.cronReady,this.initialized=!0;const t=this.transport.forwardControl;!1===e.params?.forwardThinking&&(t.forwardThinking=!1),!1===e.params?.forwardToolCalls&&(t.forwardToolCalls=!1),this.transport.sendResult(e.id,{protocolVersion:ACP_PROTOCOL_VERSION,agentCapabilities:{loadSession:!0,skills:!0,multipleSessions:!0,sessionCapabilities:{"web-ssh":!!this.config.bridge.shell.enabled,canvas:!!this.config.canvasEnabled},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcp:{}},agentInfo:{name:"beeos-claw",title:"BeeOS Agent Bridge",version:"0.1.0"},_meta:{},authMethods:[]})}async createRuntimeSession(e,t){const s=e.operationId.trim(),i=e.platformAgentId.trim();if(!s)throw new Error("session/new operationId is required");if(assertTrustedCoreExecutionAttempt(t,{operationId:s,runtimeEpoch:t.runtimeEpoch}),"service"!==t.origin)throw new Error("session/new runtime allocation requires Service authority");const n=this.resolveLocalAgentId(i);if(!i||!n)throw new RuntimeSessionNewRejectedError("session/new target agent is unknown");const r=`agent:${n}:service:${s}`;return{sessionId:this.allocateSession({agentId:n,gatewaySessionKey:r,cwd:e.cwd??".",...void 0===e.title?{}:{title:e.title}}).sessionId,gatewaySessionKey:r,agentId:n,platformAgentId:i}}async handleSessionNew(e){const t="string"==typeof e.params?.agentId&&e.params.agentId||this.config.gateway.agentId||this.getDefaultAgentId(),s=`agent:${t}:${randomUUID()}`,i="string"==typeof e.params?.cwd?e.params.cwd:".",n=this.allocateSession({agentId:t,gatewaySessionKey:s,cwd:i});this.transport.sendResult(e.id,{sessionId:n.sessionId,modes:{availableModes:[{...DEFAULT_MODE}],currentModeId:DEFAULT_MODE.id},_meta:{sessionKey:s,agentId:n.agentId,platformAgentId:n.platformAgentId??null}}),this.fetchHistoryInBackground(s)}allocateSession(e){const t=this.state.findSessionByKey(e.gatewaySessionKey);if(t)return t;const s=createSessionObject({gatewayKey:e.gatewaySessionKey,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,...void 0===e.cwd?{}:{cwd:e.cwd},...void 0===e.title?{}:{title:e.title}});if(s.agentId!==e.agentId)throw new Error("session/new gateway key agent mismatch");return this.registerSession(s,{ensureVerbose:!1}),s}fetchHistoryInBackground(e){const t=this.getGateway();t?.isConnected&&loadHistory(t,e,50).catch(e=>{this.logger.debug?.(`[bridge-core] Background history fetch failed: ${e instanceof Error?e.message:e}`)})}async subscribeSessionMessages(e){if(e.messageSubscriptionActive)return;const t=this.getGateway();if(t?.isConnected)try{await t.sessionsMessagesSubscribe(e.gatewaySessionKey),e.messageSubscriptionActive=!0,this.logger.debug?.(`[bridge-core] session.message subscribed sessionKey=${e.gatewaySessionKey}`)}catch(t){this.logger.debug?.(`[bridge-core] session.message subscribe failed key=${e.gatewaySessionKey}: ${t instanceof Error?t.message:t}`)}}async resubscribeAllSessionMessages(){for(const e of this.state.sessions.values())e.messageSubscriptionActive=!1,await this.subscribeSessionMessages(e)}handleSessionMessage(e){const t=e?.sessionKey,s=e?.messageId;if(!t||!s)return;const i=this.state.sessionsByGatewayKey.get(t);if(!i)return;const n=e.message?.role;if("toolResult"===n||"tool"===n)return void this.handlePersistedToolResultMessage(i,e).catch(e=>{this.logger.warn?.(`[bridge-core] persisted toolResult handling failed sessionKey=${t} messageId=${s}: ${e instanceof Error?e.message:String(e)}`)});const r="user"===n?"user":"system"===n?"system":"assistant",o=i.lastTurnIdByRole?.[r];if(!o)return void this.logger.debug?.(`[bridge-core] session.message skipped: no lastTurnId role=${r} sessionKey=${t} messageId=${s}`);const a=e.message?.timestamp,l="number"==typeof a&&a>0?new Date(a).toISOString():void 0,c={turnId:o};"number"==typeof e.messageSeq&&(c.seq=e.messageSeq),this.transport.sendSessionUpdate(i.sessionId,{sessionUpdate:"message_id_bind",role:r,messageId:s,...l?{timestamp:l}:{}},c),i.lastTurnIdByRole&&(i.lastTurnIdByRole[r]=void 0),"assistant"===r&&reconcileMissingArtifacts({localHistory:this.localSessionHistory,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,getCanvasState:()=>this.getCanvasState?.()??null,isSessionAlive:e=>this.state.sessions.has(e)},{session:i,turnId:o,messageId:s,runId:void 0})}async handlePersistedToolResultMessage(e,t){const s=t.messageId;if(!s)return;const i=extractPersistedToolResultEnvelope(t.message),n=this.extractPersistedToolResultFromHistory(e,s),r=mergePersistedToolResultEnvelopes(n,i);if(!r?.toolCallId)return void this.writeObs({component:"bridge-core",domain:"tool_result",name:"tool_result.skipped_no_tool_call_id",severity:"warn",payload:{sessionId:e.sessionId,messageId:s}});n&&this.writeObs({component:"bridge-core",domain:"tool_result",name:"tool_result.hydrated_from_history",severity:"debug",payload:{sessionId:e.sessionId,messageId:s,toolCallId:r.toolCallId,toolName:r.toolName}});const o=e.toolCallTurns?.get(r.toolCallId),a=o?.turnId??resolveTurnId(e);if(!a)return void this.writeObs({component:"bridge-core",domain:"tool_result",name:"tool_result.skipped_no_turn",severity:"warn",payload:{sessionId:e.sessionId,messageId:t.messageId,toolCallId:r.toolCallId,toolName:r.toolName}});const l=projectPersistedToolResultForReplay({toolCallId:r.toolCallId,toolName:r.toolName||o?.toolName||"tool",...r.rawText?{rawText:r.rawText}:{},...r.rawResult?{rawResult:r.rawResult}:{},...r.timestamp?{timestamp:r.timestamp}:{}});await emitToolResultProjectionForTurn({session:e,projection:l,toolCallId:r.toolCallId,turnId:a,config:this.config,logger:this.logger,writeObs:this.writeObs,getCanvasState:()=>this.getCanvasState?.()??null,sendUpdate:s=>(a&&void 0===s._turnId&&(s._turnId=a),this.transport.sendSessionUpdate(e.sessionId,s,{turnId:a,..."number"==typeof t.messageSeq?{seq:t.messageSeq}:{}}))})}extractPersistedToolResultFromHistory(e,t){if(!e.agentId)return;const s=this.localSessionHistory.readEntries({agentId:e.agentId,sessionKey:e.gatewaySessionKey,sessionId:e.sessionId});return findPersistedToolResultEnvelopeByMessageId(s,t)}async recoverSessionFromGateway(e){const t=this.getGateway();if(t?.isConnected)try{const s=await t.sessionsList();if(!s||"object"!=typeof s)return;const i=s.sessions;if(!Array.isArray(i))return;for(const t of i){const s=t,i=s.sessionKey??s.key??s.id??s.name;if(i&&"string"==typeof i&&deriveSessionId(i,this.instanceId)===e){const e=s.label||s.derivedTitle||s.title||void 0,t=e&&!isPlaceholderTitle(e)?e:void 0,n=createSessionObject({gatewayKey:i,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,title:t});return this.registerSession(n),n}}}catch(e){this.logger.debug?.("[bridge-core] recoverSessionFromGateway failed:",e)}}async resolveOrCreateSession(e){let t=this.state.sessions.get(e);if(!t&&e.startsWith("agent:")&&(t=this.state.findSessionByKey(e)),t||e.startsWith("agent:")||(t=await this.recoverSessionFromGateway(e)),t)return{session:t,created:!1};const s=e.startsWith("agent:"),i=this.config.gateway.agentId||this.getDefaultAgentId();return t=createSessionObject({gatewayKey:s?e:`agent:${i}:${e}`,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels}),this.registerSession(t),{session:t,created:!0}}async handleSessionLoad(e){const t=e.params?.sessionId;if(!t)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const{session:s}=await this.resolveOrCreateSession(t),i=s.sessionId;this.state.lastActiveSessionId=i,s.chatReplayDedupKeys.clear(),s.sessionLoadInProgress=!0;try{const e=await this.emitHistoryTurns(s);this.emitCurrentStreamSnapshot(s,e)}finally{s.sessionLoadInProgress=!1}this.transport.sendResult(e.id,{sessionId:i}),this.onSessionLoaded?.(i,s.gatewaySessionKey,s.platformAgentId),this.pushSkillsList().catch(e=>{this.logger.warn?.(`[bridge-core] pushSkillsList failed: ${e instanceof Error?e.message:e}`)})}async emitHistoryTurns(e){const t=new Set,s=e.sessionId;try{const i=this.getGateway(),n=e.assistantMq&&!e.assistantMq.closed,r=n?null:i,o=await loadHistory(r,e.gatewaySessionKey,100,{localHistory:this.localSessionHistory,agentId:e.agentId,sessionId:e.sessionId,logger:this.logger,emitObs:e=>{this.writeObs({component:"history-replay",domain:"lifecycle",name:e.name,severity:e.severity,payload:e.payload})}}),a=groupIntoTurns(o),l=a.filter(e=>"user"===e.role).length,c=a.filter(e=>"assistant"===e.role).length,d=a.filter(e=>e.toolCalls?.length).length,m=a.reduce((e,t)=>e+(t.toolCalls?.length??0),0);if(this.logger.debug?.(`[bridge-core] handleSessionLoad sid=${s} messages=${o.length} turns=${a.length} userTurns=${l} asstTurns=${c} turnsWithToolCalls=${d} totalToolCalls=${m}`),l>0&&e.pendingUserTurnUpdates&&e.pendingUserTurnUpdates.length>0&&(e.pendingUserTurnUpdates=[]),a.length>0&&isPlaceholderTitle(e.title)&&"manual"!==e.titleSource){const t=a.find(e=>{if("user"!==e.role)return!1;if("internal_system"===e.provenance?.kind)return!1;if(isCronPromptText(e.content))return!1;const t=cleanHistoryUserContent(e.content);return t.length>0&&!/^Sender\s*\(untrusted/i.test(t)});if(t?.content){const i=cleanHistoryUserContent(t.content).slice(0,64).replace(/\n/g," ").trim();if(i){e.title=i,e.titleSource="truncated";const t=this.getGateway();t?.isConnected&&t.sessionsPatch(e.gatewaySessionKey,{label:i}).catch(()=>{}),this.transport.sendSessionUpdate(s,{sessionUpdate:"title_update",title:i}),this.tryGenerateTitleFromHistory(e,s,a)}}}const u=t=>`history:${e.gatewaySessionKey}:${t}`;let p=-1;if(n)for(let e=a.length-1;e>=0;e--)if("assistant"===a[e].role){p=e;break}const{replayedToolCallIds:h,streamCompleteCount:g}=await this.replayHistoryTurnsToSink(e,a,this.transport,{mqActive:Boolean(n),lastAsstIdx:p,turnIdFor:(e,t)=>u(t)});for(const e of h)t.add(e);this.logger.debug?.(`[bridge-core] emitHistoryTurns DONE sid=${s} historyStreamCompleteEmitted=${g} replayedToolCallIds=${t.size}`)}catch(e){this.logger.warn?.("[bridge-core] Failed to load session history:",e)}return t}async replayHistoryTurnsToSink(e,t,s,i){const n=e.sessionId,r=new Set;let o=0;for(let a=0;a<t.length;a++){const l=t[a],c=i.turnIdFor(l,a);if(i.mqActive&&a===i.lastAsstIdx){const e=classifyHistoricalAssistantTurnCompletion(l,{mqActive:i.mqActive,isSkippedForLiveMq:!0});this.logger.debug?.(`[bridge-core] SKIP history_turn[${a}] assistant — ${"live"===e.kind?e.reason:"mq active"}, deferring to emitCurrentStreamSnapshot`);continue}if("user"===l.role&&"internal_system"===l.provenance?.kind){this.logger.debug?.(`[bridge-core] SKIP history_turn[${a}] internal_system user message`);continue}if("user"===l.role&&/^\s*system\s*\(untrusted[^)]*\)/i.test(l.content)){this.logger.debug?.(`[bridge-core] SKIP history_turn[${a}] system-injected user message`);continue}if("user"===l.role&&isHeartbeatPromptText(l.content)){this.logger.info?.(`[bridge-core] SKIP history_turn[${a}] heartbeat cron prompt sessionId=${e.sessionId} contentLen=${l.content.length} preview="${previewSanitizedText(l.content)}"`);continue}if("user"===l.role&&isCronPromptText(l.content)){this.logger.info?.(`[bridge-core] SKIP history_turn[${a}] cron-triggered user message sessionId=${e.sessionId} contentLen=${l.content.length} preview="${previewSanitizedText(l.content)}"`);continue}if("assistant"===l.role){const t=classifyHeartbeatFilter(l.content);if(t.filtered){this.logger.info?.(`[bridge-core] SKIP history_turn[${a}] heartbeat assistant reply reason=${t.reason} sessionId=${e.sessionId} contentLen=${l.content.length} preview="${previewSanitizedText(l.content)}"`);continue}}const d="assistant"===l.role?classifyHistoricalAssistantTurnCompletion(l,{mqActive:i.mqActive,isSkippedForLiveMq:!1}):void 0;if("error"===d?.kind||"interrupted"===d?.kind&&d.failure)s.sendSessionUpdate(n,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:""},...l.timestamp?{timestamp:l.timestamp}:{}},{turnId:c,...void 0!==l._seq?{seq:l._seq}:{}}),s.sendSessionUpdate(n,{sessionUpdate:"stream_complete",stopReason:d.stopReason,error:d.message,errorCode:d.errorCode},{turnId:c}),this.logger.info?.(`[bridge-core] history_runtime_failure_terminalized session_id=${n} turn_id=${c} error_code=${d.errorCode} stop_reason=${d.stopReason} source=history_replay`),o+=1;else if("system"!==l.role)if(this.logger.debug?.(`[bridge-core] SENDING history_turn[${a}] role=${l.role} contentLen=${l.content.length} content=${JSON.stringify(l.content.slice(0,80))} tcCount=${l.toolCalls?.length??0}`),"user"===l.role)this.replayUserTurnAsChunks(s,n,l.content,l.metadata,l.timestamp,c,l._seq);else{if(await this.replayAssistantTurnAsStream(s,n,l,c),l.toolCalls)for(const e of l.toolCalls)e.id&&r.add(e.id);const e=d??classifyHistoricalAssistantTurnCompletion(l,{mqActive:i.mqActive,isSkippedForLiveMq:!1});if("interrupted"===e.kind){const t=new Set(e.incompleteToolCallIds);for(const i of l.toolCalls??[])t.has(i.id)&&s.sendSessionUpdate(n,buildToolCallUpdatePayload({toolCallId:i.id,toolName:i.name,outputText:e.message,kind:i.kind,status:"failed",timestamp:l.timestamp}),{turnId:c});this.logger.info?.(`[bridge-core] history_orphan_turn_terminalized session_id=${n} turn_id=${c} tool_call_ids=${e.incompleteToolCallIds.join(",")} stop_reason=${e.stopReason} source=history_replay`),s.sendSessionUpdate(n,{sessionUpdate:"stream_complete",stopReason:e.stopReason,error:e.message,errorCode:e.errorCode},{turnId:c}),o+=1;continue}if("completed"!==e.kind)continue;s.sendSessionUpdate(n,{sessionUpdate:"stream_complete",stopReason:e.stopReason},{turnId:c}),o+=1}else this.logger.debug?.(`[bridge-core] SENDING system_message[${a}] contentLen=${l.content.length}`),s.sendSessionUpdate(n,{sessionUpdate:"system_message_chunk",content:{type:"text",text:l.content},metadata:l.metadata,...l.timestamp?{timestamp:l.timestamp}:{}},{turnId:c,...void 0!==l._seq?{seq:l._seq}:{}})}return{replayedToolCallIds:r,streamCompleteCount:o}}async handleSessionHistoryPage(e){const t=e.params??{},s="string"==typeof t.sessionId?t.sessionId:"";if(!s)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const i="string"==typeof t.cursor&&t.cursor.length>0?t.cursor:void 0,n="number"==typeof t.limit&&Number.isFinite(t.limit)&&t.limit>0?Math.min(1e3,Math.floor(t.limit)):100,{session:r}=await this.resolveOrCreateSession(s),o=this.getGateway(),a=await loadHistoryPage(o,r.gatewaySessionKey,{...i?{cursor:i}:{},limit:n,logger:this.logger}),l=groupIntoTurns(a.messages),c=new HistoryUpdateRecorder(this.transport);await this.replayHistoryTurnsToSink(r,l,c,{mqActive:!1,lastAsstIdx:-1,turnIdFor:(e,t)=>void 0!==e._seq?`history:${r.gatewaySessionKey}:seq:${e._seq}`:`history:${r.gatewaySessionKey}:seq:none:${i??"head"}:${t}`}),this.logger.debug?.(`[bridge-core] _beeos/session/history sid=${r.sessionId} cursor=${i??"<head>"} limit=${n} turns=${l.length} updates=${c.updates.length} hasMore=${a.hasMore} nextCursor=${a.nextCursor??"<none>"}`),this.transport.sendResult(e.id,{updates:c.updates,...a.nextCursor?{nextCursor:a.nextCursor}:{},hasMore:a.hasMore})}emitCurrentStreamSnapshot(e,t){const s=e.pendingUserTurnUpdates;if(s&&s.length>0)for(const t of s)this.transport.sendSessionUpdate(e.sessionId,t);const i=e.assistantMq;if(i&&!i.closed){const s=i.peek(0);let n=0;if(t&&t.size>0)for(let e=0;e<s.length;e++){const i=s[e],r=i.sessionUpdate,o=i.toolCallId;if("tool_call"!==r&&"tool_call_update"!==r||!o||!t.has(o)){if("agent_message_chunk"===r){if(""===(i.content?.text??"").trim()&&e<s.length-1){const i=s[e+1];if(("tool_call"===i.sessionUpdate||"tool_call_update"===i.sessionUpdate)&&i.toolCallId&&t.has(i.toolCallId)){n=e+1;continue}}break}break}n=e+1}const r=resolveTurnId(e),o=r?{turnId:r}:void 0;for(let t=n;t<s.length;t++)this.transport.sendSessionUpdate(e.sessionId,s[t],o)}}async handleSessionList(e){let t;try{t=parseRuntimeSessionListPage(e.params)}catch(t){return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:t instanceof Error?t.message:"Invalid session/list params"})}const s=[];for(const[,e]of this.state.sessions)isBackgroundSessionKey(e.gatewaySessionKey)||this.cronIsolatedSessionKeys.has(e.gatewaySessionKey)||!t.includeDeleted&&this.state.deletedGatewaySessionKeys.has(e.gatewaySessionKey)||s.push({sessionId:e.sessionId,title:e.title||"New chat",cwd:e.cwd,updatedAt:e.lastStreamActivityTs??e.createdAt,agentId:e.agentId,platformAgentId:e.platformAgentId,deletable:!isSystemDefaultSessionKey(e.gatewaySessionKey)});const i=this.getGateway();if(i?.isConnected)try{const e=await i.sessionsList();if(e&&"object"==typeof e&&Array.isArray(e.sessions)){const i=e.sessions;for(const e of i){const i=e,n=i.sessionKey??i.key??i.id??i.name;if(!n||"string"!=typeof n)continue;if(isBackgroundSessionKey(n))continue;if(this.cronIsolatedSessionKeys.has(n))continue;const r=deriveSessionId(n,this.instanceId),o=s.find(e=>e.sessionId===n||e.sessionId===r||this.state.sessions.get(e.sessionId)?.gatewaySessionKey===n);if(!0===i.deleted){if(this.state.deletedGatewaySessionKeys.add(n),!t.includeDeleted)continue}else this.state.deletedGatewaySessionKeys.delete(n);const a=i.label||cleanGatewayDerivedTitle(i.derivedTitle)||i.title||void 0,l=a&&!isPlaceholderTitle(a)?a:void 0,c=i.model,d=i.modelProvider;if(o){if(l&&isPlaceholderTitle(o.title)){o.title=l;const e=this.state.sessions.get(o.sessionId);e&&isPlaceholderTitle(e.title)&&(e.title=l)}const e=i.updatedAt;e&&(o.updatedAt=e),c&&(o.model=c),d&&(o.modelProvider=d)}else{const e=createSessionObject({gatewayKey:n,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,cwd:i.cwd,title:l});this.registerSession(e,{ensureVerbose:!1}),s.push({sessionId:e.sessionId,title:l||"",cwd:i.cwd,updatedAt:i.updatedAt,agentId:e.agentId,platformAgentId:e.platformAgentId,deletable:!isSystemDefaultSessionKey(n),model:c,modelProvider:d})}}}}catch(e){this.logger.debug?.("[bridge-core] sessions.list enrichment failed:",e)}const n=t.includeDeleted?s:s.filter(e=>{const t=this.state.sessions.get(e.sessionId)?.gatewaySessionKey;return!t||!this.state.deletedGatewaySessionKeys.has(t)});n.sort((e,t)=>(t.updatedAt??0)-(e.updatedAt??0)||e.sessionId.localeCompare(t.sessionId)),this.transport.sendResult(e.id,{sessions:pageRuntimeSessions(n,t)})}async handleSessionRename(e){const t=e.params?.sessionId,s=e.params?.title;if(!t||!s)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId, title"});const i=s.slice(0,64),n=this.state.sessions.get(t);if(n)try{const s=await this.dispatchLegacyConversationCapability("session.rename",n,{title:i});n.title=s.title,n.titleSource="manual",this.transport.sendResult(e.id,{sessionId:t,title:s.title})}catch(s){this.logger.warn?.(`[bridge-core] ACP rename projection deferred: ${s instanceof Error?s.message:String(s)}`),n.title=i,n.titleSource="manual",this.transport.sendResult(e.id,{sessionId:t,title:i})}else this.transport.sendAcpError(e.id,Errors.SessionNotFound)}static TITLE_TEMPLATES=[{match:["今日日报","日报"],zh:"今日工作日报",en:"Daily Work Log"},{match:["周报","周报总结","本周周报"],zh:"本周工作周报",en:"Weekly Work Report"},{match:["月报","月度汇报","月度总结"],zh:"本月工作月报",en:"Monthly Work Report"},{match:["工作日志","日志"],zh:"工作日志整理",en:"Work Log Review"},{match:["晨会","今日晨会"],zh:"今日晨会纪要",en:"Daily Standup Notes"},{match:["复盘","今日复盘"],zh:"今日工作复盘",en:"Daily Retrospective"}];static TITLE_SYSTEM_PROMPT='You are a conversation title generator. Your task is to generate a concise, human-readable title summarizing the topic of the user\'s question together with the assistant\'s answer.\n\n### Rules:\n- Length: 3-6 words in English, or 6-20 characters in Chinese/Japanese/Korean (up to 24 if needed to keep all key domain terms intact).\n- Language: Match the user\'s input language exactly. Mixed zh/en input → use the dominant language. Do NOT switch languages. (IM path injects Client UI locale via conversation-title.ts — keep ACP in sync with that module when changing examples.)\n- Extract the core topic (noun-centric) of the Q&A exchange, not the action verb.\n- Use the assistant\'s answer to disambiguate or enrich the topic when the question alone is vague (e.g. "帮我看下" + an answer about x402 → "x402 支付集成").\n- No punctuation, no quotation marks, no emojis, no markdown.\n- No prefix like "Title:" or "Here is". Output the title only.\n- Avoid generic words: "help", "question", "chat", "problem", "task".\n- Greetings and self-introductions ARE concrete topics (e.g. "自我介绍", "自己紹介", "Self Introduction") — never treat them as vague.\n- NEVER return placeholder / empty-chat titles such as "新会话", "新對話", "New chat", "New Conversation", "新しいチャット", "새 채팅", "แชตใหม่". Always invent a concrete noun-centric topic from whatever words are present.\n\n### Input Format:\nThe user message will contain both the question and the assistant\'s answer, delimited like this:\n[User Question]\n...question text...\n\n[Assistant Answer]\n...answer text (may be truncated with "..." in the middle)...\n\n### Output Format:\nRespond ONLY with valid JSON, no other text:\n{"title": "<your title here>"}\n\n### Examples:\nInput:\n[User Question]\n帮我写一个关于BeeOS设备接入的PRD\n\n[Assistant Answer]\n好的,这是 BeeOS 设备接入 PRD 的草稿:1. 目标 ...\nOutput: {"title": "BeeOS 设备接入 PRD"}\n\nInput:\n[User Question]\n帮我看下\n\n[Assistant Answer]\n你说的 x402 支付协议是一个基于 HTTP 402 的链上支付标准 ...\nOutput: {"title": "x402 支付协议解析"}\n\nInput:\n[User Question]\nWhat\'s the best way to integrate x402 payment protocol?\n\n[Assistant Answer]\nYou have three options: 1. Use the official SDK ...\nOutput: {"title": "x402 Payment Integration"}\n\nInput:\n[User Question]\n用一句话介绍一下你自己。\n\n[Assistant Answer]\n我是 BeeOS 智能助手,可以帮助你完成设备控制与任务协作。\nOutput: {"title": "自我介绍"}\n\nInput:\n[User Question]\nhi\n\n[Assistant Answer]\nHello! How can I help you today?\nOutput: {"title": "Greeting"}';matchTitleTemplate(e){const t=e.trim().toLowerCase();for(const s of AcpGatewayBridgeCore.TITLE_TEMPLATES)if(s.match.some(e=>e.toLowerCase()===t))return/[\u4e00-\u9fff]/.test(e)?s.zh:s.en}isGuardMessage(e){const t=e.trim();return[...t].length<3||[...t].every(e=>/[\p{P}\p{S}\s]/u.test(e))}truncateQuestionForTitle(e){return e.length>2e3?e.slice(0,1500):e}truncateAnswerForTitle(e){return e.length<=1e3?e:`${e.slice(0,500)}\n...\n${e.slice(-500)}`}generateTitleFromQA(e,t,s,i){if(this.isGuardMessage(s))return void this.logger.info?.(`[bridge-core] title-gen SKIP guard message sid=${t}`);const n=this.matchTitleTemplate(s);if(n){e.title=n,e.titleSource="template";const s=this.getGateway();return s?.isConnected&&s.sessionsPatch(e.gatewaySessionKey,{label:n}).catch(()=>{}),void this.transport.sendSessionUpdate(t,{sessionUpdate:"title_update",title:n})}const r=(process.env.AROUTER_BASE_URL||"").replace(/\/$/,""),o=process.env.AROUTER_API_KEY||"";if(!r||!o)return void this.logger.info?.(`[bridge-core] title-gen SKIP sid=${t}: no AROUTER env vars`);const a=`[User Question]\n${this.truncateQuestionForTitle(s)}\n\n[Assistant Answer]\n${this.truncateAnswerForTitle(i)}`;this.logger.info?.(`[bridge-core] title-gen CALLING LLM sid=${t} q="${s.slice(0,60)}" aLen=${i.length}`),fetch(`${r}/v1/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({model:"openai/gpt-4o-mini",max_tokens:32,temperature:.3,messages:[{role:"system",content:AcpGatewayBridgeCore.TITLE_SYSTEM_PROMPT},{role:"user",content:a}]})}).then(async s=>{if(!s.ok){const e=await s.text().catch(()=>"");return void this.logger.info?.(`[bridge-core] title-gen FAILED sid=${t} status=${s.status} body=${e.slice(0,300)}`)}const i=await s.json(),n=i.choices?.[0]?.message?.content?.trim();if(!n)return;const r=n.replace(/^```json\s*/,"").replace(/```$/,"").trim();let o;try{o=JSON.parse(r).title?.trim()??""}catch{return void this.logger.debug?.(`[bridge-core] title-gen JSON parse failed: ${r}`)}if(!o)return;if(isPlaceholderTitle(o))return void this.logger.debug?.("[bridge-core] title-gen discarded: placeholder LLM title");if("manual"===e.titleSource)return void this.logger.debug?.("[bridge-core] title-gen discarded: user already renamed");this.logger.info?.(`[bridge-core] title-gen OK sid=${t} title="${o}"`),e.title=o,e.titleSource="auto";const a=this.getGateway();a?.isConnected&&a.sessionsPatch(e.gatewaySessionKey,{label:o}).catch(()=>{}),this.transport.sendSessionUpdate(t,{sessionUpdate:"title_update",title:o})}).catch(e=>{this.logger.info?.(`[bridge-core] title-gen ERROR sid=${t}: ${e instanceof Error?e.message:e}`)})}async tryGenerateTitleFromHistory(e,t,s){if("manual"===e.titleSource||"auto"===e.titleSource)return;const i=this.getGateway();if(!i?.isConnected)return;let n=s;if(!n)try{const t=await loadHistory(i,e.gatewaySessionKey);n=groupIntoTurns(t)}catch(e){return void this.logger.debug?.(`[bridge-core] title-gen loadHistory failed sid=${t}: ${e instanceof Error?e.message:e}`)}const r=n.find(e=>{if("user"!==e.role)return!1;if(!e.content?.trim())return!1;if("internal_system"===e.provenance?.kind)return!1;if(isCronPromptText(e.content))return!1;const t=cleanHistoryUserContent(e.content);return!!t&&!/^Sender\s*\(untrusted/i.test(t)});if(!r)return;const o=n.indexOf(r),a=n.slice(o+1).find(e=>"assistant"===e.role&&!!e.content?.trim());if(!a)return;const l=cleanHistoryUserContent(r.content),c=a.content.trim();l&&c&&this.generateTitleFromQA(e,t,l,c)}async handleSessionDelete(e){const t=e.params?.sessionId;if(!t)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const s=this.state.sessions.get(t);if(!s)return this.logger.info?.(`[bridge-core] session/delete sessionId=${t} NOT FOUND in local state`),void this.transport.sendAcpError(e.id,Errors.SessionNotFound);const i=s.gatewaySessionKey,n=this.sessionMutationCoordinator.tryStartExclusive({sessionKey:i,label:"session_delete"},"acp");if(!n.ok)return void this.sendSessionBusy(s,e.id,"active_session_mutation",n.queueDepth);const r=n.token;try{if(this.hasActiveRun(s)){const t=this.sessionMutationCoordinator.gateSnapshot(i);return void this.sendSessionBusy(s,e.id,"active_session_mutation",t.queueDepth)}this.logger.info?.(`[bridge-core] session/delete sessionId=${t} gatewayKey=${i} gwConnected=${!!this.getGateway()?.isConnected}`);let n=!1;const r=this.getGateway();if(r?.isConnected&&i)try{await r.sessionsDelete(i),n=!0,this.logger.info?.(`[bridge-core] Gateway sessions.delete SUCCESS for key=${i}`)}catch(t){const s=t instanceof Error?t.message:String(t);if(this.logger.info?.(`[bridge-core] Gateway sessions.delete FAILED for key=${i}: ${s}`),!s.includes("Cannot delete the main session"))return void this.transport.sendResult(e.id,{deleted:!1});try{await r.sessionsReset(i),n=!0,this.logger.info?.(`[bridge-core] Gateway sessions.reset SUCCESS for key=${i}`)}catch(t){return this.logger.warn?.(`[bridge-core] Gateway sessions.reset also failed for key=${i}: ${t instanceof Error?t.message:t}`),void this.transport.sendResult(e.id,{deleted:!1})}}else i&&this.logger.warn?.(`[bridge-core] Gateway not connected, proceeding with local-only delete for key=${i}`);this.state.clearPromptTimeout(s),this.state.clearStreamIdleTimer(s),s.assistantMq?.close(),s.assistantMq=void 0,s.currentRunId&&this.state.promptsByRunId.delete(s.currentRunId);const o=new Set;for(const[e,s]of this.state.toolCallToSessionMap)s===t&&(this.state.toolCallToSessionMap.delete(e),o.add(e));for(const[e,t]of this.state.toolCallIdMap)o.has(t)&&this.state.toolCallIdMap.delete(e);this.state.sessions.delete(t),this.state.sessionsByGatewayKey.delete(i),this.state.deletedGatewaySessionKeys.add(i),this.transport.resetSessionUpdateCount(t),n&&this.onSessionDeleted?.(i),this.logger.info?.(`[bridge-core] session/delete DONE sessionId=${t} gatewayKey=${i} deleted=true`),this.transport.sendResult(e.id,{deleted:!0})}finally{this.sessionMutationCoordinator.releaseBeforeRuntime(r)}}async handleSessionClear(e){this.logger.info?.(`[bridge-core] handleSessionClear called, params=${JSON.stringify(e.params)}`);const t=e.params?.sessionId;if(!t)return this.logger.warn?.("[bridge-core] session/clear missing sessionId"),void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const s=this.state.sessions.get(t);if(!s)return this.logger.warn?.(`[bridge-core] session/clear sessionId=${t} not found in state`),void this.transport.sendAcpError(e.id,Errors.SessionNotFound);this.logger.info?.(`[bridge-core] session/clear sessionId=${t} gatewayKey=${s.gatewaySessionKey}`);const i=this.getGateway(),n=i?.isConnected;if(!s.promptDone&&(void 0!==s.pendingPromptId||void 0!==s.currentRunId)){this.logger.info?.(`[bridge-core] session/clear: cancelling active run sid=${t} runId=${s.currentRunId}`);const r=s.writeGateToken;let o=!1;if(n&&r){const e=await this.sessionMutationCoordinator.requestCancel(r,i);o="recovery_required"===await this.handleCancellationResult(s,e)}else n&&await i.chatAbort(s.gatewaySessionKey,s.currentRunId);return void this.transport.sendError(e.id,Errors.AgentError.rpcCode,o?SESSION_RECOVERY_REQUIRED_MESSAGE:"Cancellation is still converging",o?{code:SESSION_RECOVERY_REQUIRED_CODE,stopReason:"interrupted"}:{code:"session_cancellation_pending",stopReason:"cancelled"})}try{await this.dispatchLegacyConversationCapability("session.clear",s,{}),this.transport.sendResult(e.id,{cleared:!0}),this.logger.info?.("[bridge-core] session/clear DONE, sent cleared=true")}catch(t){this.sendRuntimeCommandError(e.id,t)}}async handleSessionSetMode(e){const t=e.params?.sessionId,s=e.params?.mode,i=t?this.state.sessions.get(t):void 0;if(t&&s)if(i)try{const t=await this.dispatchLegacyConversationCapability("session.setMode",i,{mode:s});this.transport.sendResult(e.id,t)}catch(t){this.sendRuntimeCommandError(e.id,t)}else this.transport.sendAcpError(e.id,Errors.SessionNotFound);else this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId, mode"})}async handleSessionSetModel(e){const t=e.params,s=null===t||"object"!=typeof t||Array.isArray(t)?void 0:t,i="string"==typeof s?.sessionId?s.sessionId:void 0;if(!i||!s||!Object.prototype.hasOwnProperty.call(s,"model"))return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId, model"});const n=s.model;if(null!==n&&("string"!=typeof n||0===n.length||n.trim()!==n))return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"model must be a non-empty string or null"});const r=i?this.state.sessions.get(i):void 0;if(r)try{const t=await this.dispatchLegacyConversationCapability("session.setModel",r,{modelOverrideId:n});this.transport.sendResult(e.id,{model:t.effectiveModelId,modelProvider:t.modelProvider??null})}catch(t){this.sendRuntimeCommandError(e.id,t)}else this.transport.sendAcpError(e.id,Errors.SessionNotFound)}sendRuntimeCommandError(e,t){if(t instanceof RuntimeCommandError)switch(t.code){case"MISSING_PARAM":return void this.transport.sendAcpError(e,Errors.MissingParam,{...t.param?{param:t.param}:{}});case"INVALID_PARAMS":return void this.transport.sendAcpError(e,Errors.InvalidParams,{message:t.message});case"GATEWAY_NOT_CONNECTED":return void this.transport.sendAcpError(e,Errors.GatewayNotConnected);case"EXECUTION_FAILED":case"AGENT_DEFAULT_MODEL_NOT_CONFIGURED":case"OUTCOME_UNKNOWN":case"INSTANCE_EPOCH_MISMATCH":case"COMMAND_EXPIRED":case"IDEMPOTENCY_CONFLICT":case"UNAUTHORIZED_TARGET":return void this.transport.sendAcpError(e,Errors.InternalError,{message:t.message})}else this.transport.sendAcpError(e,Errors.InternalError,{message:t instanceof Error?t.message:"Internal error"})}createOperationId(){const e=randomUUID();return`${e.slice(0,14)}7${e.slice(15)}`}canonicalContextBase(e,t=this.createOperationId(),s="0"){const i=Date.now(),n=createHash("sha256").update(JSON.stringify(e)).digest("hex");return{operationId:t,runtimeInstanceUid:this.instanceId,dispatchEpoch:s,paramsHash:n,idempotencyKeyHash:createHash("sha256").update(t).digest("hex"),claimDeadline:new Date(i+3e4).toISOString(),executionDeadline:new Date(i+3e5).toISOString()}}acpExecutionAttempt(e){return createAcpCoreExecutionAttempt({operationId:e.context.operationId,runtimeEpoch:e.context.dispatchEpoch,resources:this.runtimeCommandResources,historyBoundary:this.localHistoryBoundary})}instanceCommand(e,t,s){return{name:e,params:t,context:{...this.canonicalContextBase(t,s.operationId,s.runtimeEpoch),scope:"instance"}}}async agentCommand(e,t,s,i){return{name:e,params:s,context:{...this.canonicalContextBase(s,i.operationId,i.runtimeEpoch),scope:"agent",agent:{runtimeLocalKey:t,runtimeAgentUid:await this.runtimeAgentIdentities.resolveOrCreate(t)}}}}async dispatchLegacyAgentCapability(e,t,s){const i=normalizeRuntimeAgentLocalKey(t),n=await this.runtimeLeases.claim(this.createOperationId());let r=!1;try{const t={name:e,params:s,context:{...this.canonicalContextBase(s,n.operationId,n.runtimeEpoch),scope:"agent",agent:{runtimeLocalKey:i,runtimeAgentUid:await this.runtimeAgentIdentities.resolveOrCreate(i)}}},o=this.runtimeCommands.dispatch(t,this.acpExecutionAttempt(t));return r=!0,await o.completion}finally{r||await this.runtimeLeases.release(n)}}async dispatchLegacyInstanceCapability(e,t){const s=await this.runtimeLeases.claim(this.createOperationId());let i=!1;try{const n={name:e,params:t,context:{...this.canonicalContextBase(t,s.operationId,s.runtimeEpoch),scope:"instance"}},r=this.runtimeCommands.dispatch(n,this.acpExecutionAttempt(n));return i=!0,await r.completion}finally{i||await this.runtimeLeases.release(s)}}async handleMcpList(e){const t=await this.dispatchLegacyInstanceCapability("mcp.list",{});this.transport.sendResult(e.id,{servers:Object.fromEntries(t.servers.map(e=>[e.name,{transport:e.transport,...e.url?{url:e.url}:{},...e.command?{command:e.command}:{},...e.args?{args:[...e.args]}:{},...e.cwd?{cwd:e.cwd}:{},...e.connectionTimeoutMs?{connectionTimeoutMs:e.connectionTimeoutMs}:{}}]))})}async handleMcpSet(e){const t=e.params&&"object"==typeof e.params?e.params:{},s="string"==typeof t.name?t.name:"";let i;try{if(requireSecretFreeMcpServerName(s),!t.server||"object"!=typeof t.server||Array.isArray(t.server))throw new Error("mcp/set requires name and server");const e=t.server,n=extractMcpCredentialMaterial(e),r={...e};delete r.headers,delete r.env;const o=e.transport??("string"==typeof e.command?"stdio":"string"==typeof e.url?"streamable-http":void 0),a=normalizeMcpPublicServerConfig({...r,transport:o}),l=createHash("sha256").update(canonicalizeJcs(a)).digest("hex");i={definition:{definitionRef:`acp-mcp:sha256:${l}`,version:"local-v1",sha256:l,...n?{credentialRef:await requireCredentialReferencePort(this.mcpCredentialReferences).put({serverName:s,material:n})}:{}},config:structuredClone(a)}}catch(t){return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:t instanceof Error?t.message:"Invalid MCP server config"})}this.runtimeCommandResources.registerMcpDefinition?.(i.definition,i.config);try{await this.dispatchLegacyInstanceCapability("mcp.set",{name:s,definition:i.definition})}catch(e){if(i.definition.credentialRef){!await this.mcp.removeCredentialIfUnreferenced(i.definition.credentialRef)&&this.mcpCredentialReferences?.owns(i.definition.credentialRef)&&await this.mcpCredentialReferences.remove(i.definition.credentialRef)}throw e}this.transport.sendResult(e.id,{ok:!0,restarting:!1})}async handleMcpUnset(e){const t=e.params&&"object"==typeof e.params?e.params:{};let s;try{s=requireSecretFreeMcpServerName(t.name)}catch{return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"mcp/unset requires name"})}await this.dispatchLegacyInstanceCapability("mcp.unset",{name:s}),this.transport.sendResult(e.id,{ok:!0,restarting:!1})}async dispatchLegacyConversationCapability(e,t,s){const i=await this.runtimeLeases.claim(this.createOperationId());let n=!1;try{const r={name:e,params:s,context:{...this.canonicalContextBase(s,i.operationId,i.runtimeEpoch),scope:"conversation",conversation:{runtimeConversationUid:t.sessionId,runtimeSessionKey:t.gatewaySessionKey}}},o=this.runtimeCommands.dispatch(r,this.acpExecutionAttempt(r));return n=!0,await o.completion}finally{n||await this.runtimeLeases.release(i)}}async dispatchLegacyTerminalCapability(e,t,s,i){const n=await this.runtimeLeases.claim(this.createOperationId());let r=!1;try{const o={name:e,params:i,context:{...this.canonicalContextBase(i,n.operationId,n.runtimeEpoch),scope:"terminal",terminal:{terminalId:t,clientId:s}}},a=this.runtimeCommands.dispatch(o,this.acpExecutionAttempt(o));return r=!0,await a.completion}finally{r||await this.runtimeLeases.release(n)}}async dispatchLegacyCanvasNotification(e,t){const s=t&&"object"==typeof t?t:{},i=e.replace("/","."),n="canvas.toggle"===i?{visible:!0===s.visible||!0===s.enabled}:"canvas.reference"===i?{surfaceId:"string"==typeof s.surfaceId?s.surfaceId:""}:"canvas.dimensions"===i?{width:Number(s.width),height:Number(s.height),..."number"==typeof s.devicePixelRatio?{devicePixelRatio:s.devicePixelRatio}:{}}:{},r="string"==typeof s.sessionId?s.sessionId:"acp",o="string"==typeof s.canvasId?s.canvasId:r,a=await this.runtimeLeases.claim(this.createOperationId());let l=!1;try{const e={name:i,params:n,context:{...this.canonicalContextBase(n,a.operationId,a.runtimeEpoch),scope:"canvas",canvas:{canvasId:o,sessionId:r}}},t=this.runtimeCommands.dispatch(e,this.acpExecutionAttempt(e));l=!0,await t.completion}finally{l||await this.runtimeLeases.release(a)}}async applyCanonicalCanvasControl(e,t){if("canvas/reference"===e){const e=this.state.resolveSessionFromParams(t);if(!e)throw new RuntimeCommandError("INVALID_PARAMS","canvas session not found");const s="string"==typeof t.surfaceId?t.surfaceId:void 0;return void(e.referencedSurfaceId=s||void 0)}if(!this.handleCanvasNotification)throw new RuntimeCommandError("INVALID_PARAMS","canvas control delegate is not configured");await this.handleCanvasNotification(e,t)}async dispatchLegacyCronCapability(e,t){const s=normalizeRuntimeAgentLocalKey(this.config.gateway.agentId),i=await this.runtimeLeases.claim(this.createOperationId());let n=!1;try{const r="cron.add"===e?{...t,runtimeCronJobUid:`runtime-cron:${i.operationId}`}:"cron.run"===e?{...t,runToken:`runtime-run:${i.operationId}`}:t,o={name:e,params:r,context:{...this.canonicalContextBase(r,i.operationId,i.runtimeEpoch),scope:"agent",agent:{runtimeLocalKey:s,runtimeAgentUid:await this.runtimeAgentIdentities.resolveOrCreate(s)}}},a=this.runtimeCommands.dispatch(o,this.acpExecutionAttempt(o));return n=!0,await a.completion}finally{n||await this.runtimeLeases.release(i)}}validateConnectedGateway(){if(!this.getGateway()?.isConnected)throw new RuntimeCommandError("GATEWAY_NOT_CONNECTED","Gateway not connected")}async finishClaimedLegacyAgentMutation(e,t){let s=!1;try{const e=await t(),i=this.runtimeCommands.dispatch(e,this.acpExecutionAttempt(e));s=!0;const n=await i.completion;return queueMicrotask(()=>{this.observeAgentProjection()}),n}finally{s||await this.runtimeLeases.release(e)}}async observeAgentProjection(){await(async(e,t)=>{if(!t)return;let s;try{await Promise.race([Promise.resolve().then(t),new Promise((t,i)=>{s=setTimeout(()=>i(new Error(`${e} timed out`)),this.projectionObservationTimeoutMs)})])}catch(t){this.logger.warn?.(`[acp] ${e} failed: ${t instanceof Error?t.message:String(t)}`)}finally{s&&clearTimeout(s)}})("agent projection sync",this.triggerAgentSync)}async handleAgentCreate(e){try{const t=e.params?.name?.trim()??"";if(!t)throw new RuntimeCommandError("INVALID_PARAMS","Missing agent name");this.validateConnectedGateway();const s=this.createOperationId(),i=await this.runtimeLeases.claim(s),n=await this.finishClaimedLegacyAgentMutation(i,async()=>{const s=await this.runtimeAgentIdentities.allocateCreate(i,"agent.create"),n=Object.entries(e.params?.files??{}).filter(e=>"string"==typeof e[1]).map(([e,t])=>({name:e,contentRef:this.runtimeCommandResources.registerContent(t)}));return this.instanceCommand("agent.create",{runtimeAgentUid:s.runtimeAgentUid,name:t,...e.params?.identity?{identity:e.params.identity}:{},...e.params?.model?{defaultModelId:e.params.model}:{},...n.length?{bootstrapFiles:n}:{}},i)});this.transport.sendResult(e.id,{agentId:n.runtimeLocalKey,platformAgentId:this.resolvePlatformAgentId(n.runtimeLocalKey)??"",workspace:n.workspacePath})}catch(t){this.sendRuntimeCommandError(e.id,t)}}async handleApplyTemplate(e){try{const t=e.params?.name?.trim()??"";if(!t)throw new RuntimeCommandError("INVALID_PARAMS","Missing agent name");const s=e.params?.packageUrl?.trim()??"";if(!s)throw new RuntimeCommandError("MISSING_PARAM","Missing packageUrl","packageUrl");this.validateConnectedGateway();const i=await this.runtimeCommandResources.registerArtifact(s,e.params?.sha256),n=this.createOperationId(),r=await this.runtimeLeases.claim(n),o=await this.finishClaimedLegacyAgentMutation(r,async()=>{const s=await this.runtimeAgentIdentities.allocateCreate(r,"agent.applyTemplate");return this.instanceCommand("agent.applyTemplate",{runtimeAgentUid:s.runtimeAgentUid,name:t,artifact:i,...e.params?.identity?{identity:e.params.identity}:{},...e.params?.model?{defaultModelId:e.params.model}:{}},r)});this.transport.sendResult(e.id,{agentId:o.runtimeLocalKey,platformAgentId:this.resolvePlatformAgentId(o.runtimeLocalKey)??"",workspace:o.workspacePath})}catch(t){this.sendRuntimeCommandError(e.id,t)}}async handleAgentUpdate(e){try{const t=e.params?.agentId?.trim()??"";if(!t)throw new RuntimeCommandError("MISSING_PARAM","Missing agentId","agentId");const s={...void 0!==e.params?.name?{name:e.params.name}:{},...void 0!==e.params?.model?{defaultModelId:e.params.model}:{},...void 0!==e.params?.identity?{identity:e.params.identity}:{}};if(0===Object.keys(s).length)throw new RuntimeCommandError("INVALID_PARAMS","No updatable fields provided (name/model/identity)");this.validateConnectedGateway();const i=await this.runtimeLeases.claim(this.createOperationId()),n=await this.finishClaimedLegacyAgentMutation(i,()=>this.agentCommand("agent.update",t,s,i));this.transport.sendResult(e.id,{agentId:n.runtimeLocalKey})}catch(t){this.sendRuntimeCommandError(e.id,t)}}async handleAgentDelete(e){try{const t=e.params?.agentId?.trim()??"";if(!t)throw new RuntimeCommandError("MISSING_PARAM","Missing agentId","agentId");if("main"===normalizeRuntimeAgentLocalKey(t))throw new RuntimeCommandError("INVALID_PARAMS",'"main" cannot be deleted; delete the instance instead');this.validateConnectedGateway();const s=await this.runtimeLeases.claim(this.createOperationId()),i=await this.finishClaimedLegacyAgentMutation(s,()=>this.agentCommand("agent.delete",t,void 0===e.params?.deleteFiles?{}:{deleteFiles:e.params.deleteFiles},s));this.transport.sendResult(e.id,{agentId:i.runtimeLocalKey,...void 0===i.removedBindings?{}:{removedBindings:i.removedBindings}})}catch(t){this.sendRuntimeCommandError(e.id,t)}}async handleAgentList(e){try{const t=await this.dispatchLegacyInstanceCapability("agent.listProjection",{}),s=t.agents.map(e=>({agentId:e.runtimeLocalKey,name:e.name,...e.emoji?{emoji:e.emoji}:{},...e.avatarUrl?{avatarUrl:e.avatarUrl}:{}})),i={...t.defaultRuntimeLocalKey?{defaultId:t.defaultRuntimeLocalKey}:{},agents:s};this.transport.sendResult(e.id,i)}catch(t){this.sendRuntimeCommandError(e.id,t)}}async handleModelsList(e){try{this.transport.sendResult(e.id,await this.dispatchLegacyInstanceCapability("models.list",{}))}catch(t){this.sendRuntimeCommandError(e.id,t)}}async handleSkillsList(e){try{const t=await this.dispatchLegacyAgentCapability("skills.list",e.params?.agentId,{});this.transport.sendResult(e.id,{skills:t.skills.map(e=>({name:e.name,description:e.description??"",...e.emoji?{emoji:e.emoji}:{},...e.always?{always:!0}:{},...e.bundled?{bundled:!0}:{},...e.enabled?{}:{disabled:!0},skillKey:e.skillKey,...e.iconUrl?{iconUrl:e.iconUrl}:{}}))})}catch(t){this.sendRuntimeCommandError(e.id,t)}}async fetchSimplifiedSkills(e){const t=this.getGateway();if(!t?.isConnected)return[];try{const s=await t.skillsStatus(e);if(!s?.skills)return[];const i=s.skills.filter(e=>!1!==e.eligible||!0===e.disabled).sort((e,t)=>e.always&&!t.always?-1:!e.always&&t.always?1:e.name.localeCompare(t.name)).map(e=>({name:e.name,description:e.description,emoji:e.emoji,always:e.always||void 0,bundled:e.bundled||void 0,disabled:e.disabled||void 0,skillKey:e.skillKey||void 0,iconUrl:void 0})),n=await this.getSkillsDir(e);for(const e of i){const t=e.skillKey??e.name;try{const s=await readFile(join(n,t,".beeos-meta.json"),"utf8"),i=JSON.parse(s);i?.iconUrl&&(e.iconUrl=i.iconUrl)}catch{}}return i}catch(e){return this.logger.warn?.(`[bridge-core] Failed to fetch skills: ${e instanceof Error?e.message:e}`),[]}}async pushSkillsList(e){const t=await this.fetchSimplifiedSkills(e);this.transport.sendNotification("session/update",{sessionId:"_system",update:{sessionUpdate:"available_commands_update",commands:t}}),this.writeObs({component:"bridge-core",domain:"lifecycle",name:"skills.pushed",severity:"debug",payload:{count:t.length}})}getOpenclawHome(){return process.env.OPENCLAW_HOME||join(homedir(),".openclaw")}async getSkillsDir(e){const t=this.getOpenclawHome();if(!e||"main"===e)return join(t,"skills");const s=await this.resolveAgentWorkspaceDir(e);return join(s??join(t,`workspace-${e}`),"skills")}async resolveAgentWorkspaceDir(e){const t=this.getGateway();if(!t?.isConnected)return null;try{const s=await t.request("agents.list",{}),i=normalizeAgentId(e),n=s?.agents?.find(e=>normalizeAgentId(e.id)===i);return n?.workspace??null}catch(t){return this.logger.warn?.(`[bridge-core] resolveAgentWorkspaceDir("${e}") failed: ${t instanceof Error?t.message:t}`),null}}async handleSkillsInstall(e){const t=e.params,s=t?.zipUrl,i=t?.files,n=t?.agentId;let r;try{r=validateSkillSlug(t?.slug||t?.name||"")}catch{return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Invalid or missing skill slug"})}if(i?.length||s)try{let o;if(s){o=parseSkillZip(await fetchWithRetry(s,{maxRetries:4,logger:this.logger}))}else{if(!i?.length)throw new RuntimeCommandError("INVALID_PARAMS","Missing skill files or zipUrl");o=new Map;for(const e of i){const t=normalizeSkillArtifactPath(e.path),s=await fetchWithRetry(e.downloadUrl,{maxRetries:4,logger:this.logger});o.set(t,new Uint8Array(s))}}if(t?.iconUrl&&o.set(".beeos-meta.json",(new TextEncoder).encode(JSON.stringify({iconUrl:t.iconUrl}))),!this.runtimeCommandResources.registerParsedArtifact)throw new RuntimeCommandError("EXECUTION_FAILED","ACP skill artifact ingress is not configured");const a=this.runtimeCommandResources.registerParsedArtifact({manifest:{slug:r,version:"0.0.0"},workspaceFiles:o});await this.dispatchLegacyAgentCapability("skills.install",n,{artifact:a}),this.transport.sendResult(e.id,{success:!0}),this.onSkillInstalled?.(r,resolveSkillInstallDir(await this.getSkillsDir(n),r)),await this.pushSkillsList(n)}catch(t){this.logger.error?.(`[bridge-core] Failed to install skill "${r}": ${t instanceof Error?t.message:t}`),this.transport.sendAcpError(e.id,Errors.InternalError,{message:`Install failed: ${t instanceof Error?t.message:String(t)}`})}else this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Missing skill files or zipUrl"})}async handleSkillsUninstall(e){const t=e.params,s=t?.agentId;let i;try{i=validateSkillSlug(t?.slug||t?.name||"")}catch{return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Invalid or missing skill name"})}try{await this.dispatchLegacyAgentCapability("skills.uninstall",s,{skillKey:i}),this.transport.sendResult(e.id,{success:!0}),await this.pushSkillsList(s)}catch(t){this.logger.error?.(`[bridge-core] Failed to uninstall skill "${i}": ${t instanceof Error?t.message:t}`),this.transport.sendAcpError(e.id,Errors.InternalError,{message:`Uninstall failed: ${t instanceof Error?t.message:String(t)}`})}}async handleSkillsUpdate(e){const t=e.params,s=t?.skillKey,i=t?.enabled,n=t?.agentId;if(s&&"boolean"==typeof i)try{await this.dispatchLegacyAgentCapability("skills.setEnabled",n,{skillKey:s,enabled:i}),this.logger.info?.(`[bridge-core] Updated skill "${s}" enabled=${i}${n?` for agent "${n}"`:""}`),this.transport.sendResult(e.id,{ok:!0,skillKey:s,enabled:i}),await this.pushSkillsList(n)}catch(t){this.logger.error?.(`[bridge-core] Failed to update skill "${s}": ${t instanceof Error?t.message:t}`),this.transport.sendAcpError(e.id,Errors.InternalError,{message:`Update failed: ${t instanceof Error?t.message:String(t)}`})}else this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Missing skillKey or enabled"})}async handleSessionPrompt(e){const t=e.params?.sessionId,s=e.params?.prompt;if(!t||!s)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId, prompt"});const{session:i,created:n}=await this.resolveOrCreateSession(t);n&&this.onSessionLoaded?.(i.sessionId,i.gatewaySessionKey,i.platformAgentId);const r=i.sessionId;this.state.lastActiveSessionId=r,this.onPromptStart?.();const o=this.getGateway();if(!o?.isConnected)return void this.transport.sendAcpError(e.id,Errors.GatewayNotConnected);if(this.hasActiveRun(i)){const t=this.sessionMutationCoordinator.gateSnapshot(i.gatewaySessionKey);return void this.sendSessionBusy(i,e.id,"active_run",t.queueDepth)}try{await this.ensureVerboseFull(i)}catch(t){return this.releaseSessionWriteGate(i),void this.transport.sendAcpError(e.id,Errors.InternalError,{message:`Failed to prepare agent context: ${t instanceof Error?t.message:String(t)}`})}let a=extractPromptBlocks(sanitizePromptPayload(s));const l=a.filter(e=>"text"===e.type&&"text"in e&&"string"==typeof e.text).map(e=>e.text).join("\n");if(i.fileArtifactDisplayMode=prefersChatFileArtifacts(l)?"chat":"auto",!i.title||isPlaceholderTitle(i.title)){const e=a.find(e=>"text"===e.type&&e.text);if(e&&"text"in e&&e.text){const t=stripTransportMetadata(e.text).trim();if(this.logger.info?.(`[bridge-core] title-gen sid=${r} existing="${i.title}" cleanText="${t.slice(0,80)}" isPlaceholder=${isPlaceholderTitle(t)}`),t&&!isPlaceholderTitle(t)){const e=t.slice(0,64).replace(/\n/g," ").trim();i.title=e,i.titleSource="truncated",o?.isConnected&&e&&o.sessionsPatch(i.gatewaySessionKey,{label:e}).catch(e=>{this.logger.debug?.(`[bridge-core] sessionsPatch (title) failed: ${e instanceof Error?e.message:e}`)}),this.transport.sendSessionUpdate(r,{sessionUpdate:"title_update",title:e})}}}const c=buildResolutionPlan(a);if(c.refs.length>0)try{const e=await resolveResources(c,this.writeObs);a=applyResolutions(a,e)}catch(e){this.logger.warn?.(`[bridge-core] Resource pre-resolution failed: ${e instanceof Error?e.message:e}`)}let d;if(this.beeosFileResolver){const e=this.beeosFileResolver.buildResolutionPlan(a);if(e.refs.length>0)try{d=await this.beeosFileResolver.resolveMetadataForPrompt(e)}catch(e){this.logger.warn?.(`[bridge-core] BeeOS file resolution failed: ${e instanceof Error?e.message:e}`)}}const m=toGatewayPrompt(a,{beeosFileResolutionsByUri:d});if("error"in m)return this.releaseSessionWriteGate(i),void this.transport.sendAcpError(e.id,Errors.PromptConvertFailed,{message:m.error});const{message:u,attachments:p}=m,h=resolveStandaloneSlashCommandName(a,u)??resolveSlashCmd(a,u),g="string"==typeof h;if(h&&this.handleSlashCommand){const t=this;if(await(async()=>{try{return await t.handleSlashCommand(h)}catch(e){return t.logger.warn?.(`[bridge-core] /${h} handler failed: ${e instanceof Error?e.message:e}`),!1}})())return this.emitPromptAsUserSessionUpdates(i,a,resolveTurnId(i)),this.transport.sendSessionUpdate(r,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Loading ${h}...`},timestamp:(new Date).toISOString()},{turnId:resolveTurnId(i)}),this.transport.sendResult(e.id,{stopReason:"end_turn"}),void this.releaseSessionWriteGate(i)}const y="chat.send";let f=g?u:withUserMessagePrefix(u);const w=this.config.canvasEnabled&&!g&&!0===i.canvasActive&&!i.channelType;if(w){const e=i.promptsSinceCanvasInjection??0;!i.canvasPromptInjected||e>=10?(f=`${CANVAS_TERM_MAPPING}\n\n${f}`,i.canvasPromptInjected=!0,i.promptsSinceCanvasInjection=0,this.logger.debug?.("[bridge-core] Canvas term mapping injected (re-inject cycle)")):i.promptsSinceCanvasInjection=e+1}if(w){const e=this.getCanvasState?.();if(e){const t=e.resolveCanvasForSession(i.gatewaySessionKey);f=`${buildActiveSurfacesContext(e,t)??"[Canvas] Canvas panel is available. Use render_ui for structured/visual content."}\n\n${f}`}const t=i.referencedSurfaceId;t&&(f=`${CANVAS_UPDATE_HINT}\n[IMPORTANT: The user selected canvas surface "${t}" for editing. You MUST call render_ui with id="${t}" to UPDATE this existing surface. Do NOT create a new surface with a different id.]\n${f}`,i.referencedSurfaceId=void 0)}if(!g){const t=parseMentionsParam(e.params?.mentions);if(t.length>0){i.activeMentions=t;f=`${buildMentionInstruction(t)}\n${f}`,this.logger.debug?.(`[bridge-core] delegation mention instruction injected for ${t.length} agent(s)`)}else i.activeMentions=void 0}if(g&&this.logger.info?.(`[bridge-core] slash command passthrough sessionId=${r} command=/${h}`),this.hasActiveRun(i)){const t=this.sessionMutationCoordinator.gateSnapshot(i.gatewaySessionKey);return void this.sendSessionBusy(i,e.id,"active_run_after_prepare",t.queueDepth)}const v=this.sessionMutationCoordinator.tryStartInteractive({sessionKey:i.gatewaySessionKey,label:"session/prompt"},"acp");if(!v.ok)return void this.sendSessionBusy(i,e.id,v.reason,v.queueDepth);i.writeGateToken=v.token,this.state.resetForNewRun(i,r,this.transport),i.pendingPromptId=e.id,i.gatewayMethod=y;const I=resolveTurnId(i);this.emitPromptAsUserSessionUpdates(i,a,I),this.transport.sendSessionUpdate(r,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:""},timestamp:(new Date).toISOString()},I?{turnId:I}:void 0);const S=extractCronJobId(u);S&&(i.cronJobId=S),this.schedulePromptTimeout(i);const C=p.length>0?p.map(e=>({type:e.type,content:e.content,...e.mimeType?{mimeType:e.mimeType}:{},...e.fileName?{fileName:e.fileName}:{}})):void 0,R=`req_${randomUUID().replace(/-/g,"")}`,A={sessionKey:i.gatewaySessionKey,message:f,deliver:!1,idempotencyKey:randomUUID()};C?.length&&(A.attachments=C);if(!o.sendFrame({type:"req",id:R,method:y,params:A}))return this.state.clearPromptTimeout(i),i.pendingPromptId=void 0,i.assistantMq?.close(),i.assistantMq=void 0,i.pendingUserTurnUpdates=void 0,this.releaseSessionWriteGate(i),void this.transport.sendAcpError(e.id,Errors.SendFailed,{message:"failed to send prompt to gateway"});i.gatewayRequestId=R,this.state.promptsByGatewayRequestId.set(R,i)}replayUserTurnAsChunks(e,t,s,i,n,r,o){const a=splitUserReplayBlocks(s),l=r||void 0!==o?{...r?{turnId:r}:{},...void 0!==o?{seq:o}:{}}:void 0;for(const s of a){let r;if("text"===s.type){if(!s.text)continue;r={type:"text",text:s.text}}else r="resource_link"===s.type?{type:"resource_link",uri:s.uri??"",...s.fileName?{name:s.fileName}:{},...s.mimeType?{mimeType:s.mimeType}:{}}:{type:s.type,...s.mimeType?{mimeType:s.mimeType}:{},...s.fileName?{fileName:s.fileName}:{}};e.sendSessionUpdate(t,{sessionUpdate:"user_message_chunk",content:r,...i?{metadata:i}:{},...n?{timestamp:n}:{}},l)}}async replayAssistantTurnAsStream(e,t,s,i){const n=e=>{if(i||void 0!==e)return{...i?{turnId:i}:{},...void 0!==e?{seq:e}:{}}},r=new Set,o=(s,i,o)=>{if(!s?.length)return;const a=n(o);for(const n of s)n.uri&&!r.has(n.uri)&&(r.add(n.uri),e.sendSessionUpdate(t,{sessionUpdate:"agent_message_chunk",content:{type:"resource_link",uri:n.uri,name:n.name??"file",...n.mimeType?{mimeType:n.mimeType}:{}},...i?{timestamp:i}:{}},a))},a=n(s._seq);if(!s.sourceMessages?.length){const i={sessionUpdate:"history_turn",role:s.role,content:s.content,reasoning:s.reasoning,toolCalls:s.toolCalls,...s.timestamp?{timestamp:s.timestamp}:{}};return s.metadata&&(i.metadata=s.metadata),e.sendSessionUpdate(t,i,a),void o(s.files,s.timestamp,s._seq)}for(const i of s.sourceMessages){const r=i.updateType??"agent_message_chunk",a=n(i._seq);switch(r){case"agent_message_chunk":e.sendSessionUpdate(t,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:i.content},...i.timestamp?{timestamp:i.timestamp}:{},...i.metadata?{metadata:i.metadata}:{}},a);break;case"agent_thought_chunk":e.sendSessionUpdate(t,{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:i.content},...i.timestamp?{timestamp:i.timestamp}:{}},a);break;case"tool_call":{const n=i.toolCallId??"",r=s.toolCalls?.find(e=>e.id===n),o=i.toolName??"tool",l=i.content??"";let c={};if(l)try{c=JSON.parse(l)}catch{}e.sendSessionUpdate(t,buildToolCallPayload({toolCallId:n,toolName:o,args:c,kind:r?.kind,status:r?.status??"in_progress",timestamp:i.timestamp}),a);break}case"tool_call_update":{const n=i.toolCallId??"",r=s.toolCalls?.find(e=>e.id===n),l=i.toolName??r?.name??"tool",c=i.content??r?.output??"",d=await this.resolveReplayResourceLinks(n,l,i.files);e.sendSessionUpdate(t,buildToolCallUpdatePayload({toolCallId:n,toolName:l,outputText:c,kind:r?.kind,status:r?.status??"completed",resourceLinks:d,timestamp:i.timestamp}),a),o(d,i.timestamp,i._seq);break}}}o(s.files,s.timestamp,s._seq)}async resolveReplayResourceLinks(e,t,s){let i=s?.map(e=>({uri:e.uri,name:e.name??"file",...e.mimeType?{mimeType:e.mimeType}:{}}));if(i?.length)return i;if(i=await readEnrichmentCache(e).catch(()=>{}),i?.length)return i;if("beeos_upload_file"!==t)return;const n=await readUploadToolResult(e).catch(()=>{});if(!n)return;const r=buildToolResultSessionContentBlocks(t,n).filter(e=>"resource_link"===e.content?.type&&e.content.uri).map(e=>({uri:e.content.uri,name:e.content.name??"file",...e.content.mimeType?{mimeType:e.content.mimeType}:{}}));return r.length>0?r:void 0}emitPromptAsUserSessionUpdates(e,t,s){const i=(new Date).toISOString(),n=s?{turnId:s}:void 0;for(const r of t){const t=this.toUserSessionUpdateContent(r);if(!t)continue;const o={sessionUpdate:"user_message_chunk",content:t,timestamp:i};s&&void 0===o._turnId&&(o._turnId=s),this.transport.sendSessionUpdate(e.sessionId,o,n),e.pendingUserTurnUpdates?.push(o)}}toUserSessionUpdateContent(e){if("text"===e.type){if(!e.text)return;return{type:"text",text:e.text}}if("image"===e.type){const t=e.mimeType??e.mime_type??"application/octet-stream",s=e.fileName??e.file_name??e.name;if(!e.data&&!e.uri)return;return{type:"image",...e.data?{data:e.data}:{},...e.uri?{uri:e.uri}:{},...t?{mimeType:t}:{},...s?{fileName:s}:{}}}if("resource_link"===e.type){if(!e.uri)return;return{type:"resource_link",uri:e.uri,...e.title?{title:e.title}:{},...e.name?{name:e.name}:{},...e.mimeType??e.mime_type?{mimeType:e.mimeType??e.mime_type}:{}}}if("file"===e.type){const t=e.mimeType??e.mime_type??"application/octet-stream",s=e.fileName??e.file_name??e.filename??e.name;if(!e.data&&!e.text&&!e.uri)return;return{type:"file",...e.data?{data:e.data}:{},...e.text?{text:e.text}:{},...e.uri?{uri:e.uri}:{},...t?{mimeType:t}:{},...s?{fileName:s}:{}}}if("resource"===e.type){const t=e.resource??{},s=t.uri??e.uri,i=t.mimeType??t.mime_type??e.mimeType??e.mime_type,n=t.text??e.text,r=t.data??e.data,o=t.fileName??t.file_name??t.filename??t.name??e.fileName??e.file_name??e.filename??e.name;if(!s&&!n&&!r)return;return{type:"resource",resource:{...s?{uri:s}:{},...i?{mimeType:i}:{},...n?{text:n}:{},...r?{data:r}:{},...o?{fileName:o}:{}}}}}async handleSessionCancel(e,t){const s=t&&"object"==typeof t&&"sessionId"in t?t.sessionId:void 0;if(!s)return void(void 0!==e&&this.transport.sendAcpError(e,Errors.MissingParam,{param:"sessionId"}));const i=this.state.sessions.get(s);if(!i)return void(void 0!==e&&this.transport.sendAcpError(e,Errors.SessionNotFound));const n=i.activeRunBinding??this.observeActiveRun(i);if(!n){const t=this.sessionMutationCoordinator.snapshot(i.gatewaySessionKey);if("exclusive"===t?.attachmentPolicy&&void 0!==e){const t=this.sessionMutationCoordinator.gateSnapshot(i.gatewaySessionKey);return void this.sendSessionBusy(i,e,"exclusive_session_mutation",t.queueDepth)}return void(void 0!==e&&this.transport.sendResult(e,{}))}const r=await this.runtimeLeases.claim(this.createOperationId());let o=!1;try{const s=t&&"object"==typeof t&&"reason"in t&&"string"==typeof t.reason?t.reason:void 0,i={targetMessageId:n.targetMessageId,...s?{reason:s}:{}},a={name:"session.cancel",params:i,context:{...this.canonicalContextBase(i,r.operationId,r.runtimeEpoch),scope:"conversation",historyGeneration:n.historyGeneration,conversation:{runtimeConversationUid:n.runtimeConversationUid,runtimeSessionKey:n.runtimeSessionKey}}},l=this.runtimeCommands.dispatch(a,this.acpExecutionAttempt(a));o=!0,await l.completion,void 0!==e&&this.transport.sendResult(e,{})}catch(t){void 0!==e&&this.sendRuntimeCommandError(e,t)}finally{o||await this.runtimeLeases.release(r)}}hasActiveRun(e){return!e.promptDone&&(void 0!==e.pendingPromptId||void 0!==e.currentRunId||void 0!==e.gatewayRequestId)}observeLifecycle(e,t,s){observeLifecyclePromise(e,this.logger,{component:"bridge-core",action:t,...s?{sessionId:s.sessionId,gatewaySessionKey:s.gatewaySessionKey}:{}})}async handleCancellationResult(e,t){return t.ok?(this.observeLifecycle(t.terminalObservation.then(t=>{if(!t.ok)return this.publishCancellationRecovery(e)}),"cancel_terminal_observation",e),"accepted"):"recovery"in t?(await this.publishCancellationRecovery(e),"recovery_required"):"terminal_already_observed"}async publishCancellationRecovery(e){await this.endRun(e,{kind:"interrupted",stopReason:"interrupted",message:SESSION_RECOVERY_REQUIRED_MESSAGE,errorCode:SESSION_RECOVERY_REQUIRED_CODE})}releaseSessionWriteGate(e){if(!e.writeGateToken)return;const t=e.writeGateToken;e.writeGateToken=void 0,this.sessionMutationCoordinator.releaseBeforeRuntime(t)}logRuntimeFailure(e,t){this.logger.warn?.(`[bridge-core] runtime_failure_classified session_id=${e.sessionId} gateway_session_key=${e.gatewaySessionKey} run_id=${e.currentRunId??""} gateway_request_id=${e.gatewayRequestId??""} error_code=${t.errorCode} stop_reason=${t.stopReason} source=${t.source} runtime=${t.runtimeKind}`)}sendSessionBusy(e,t,s,i){this.logger.warn?.(`[bridge-core] session_write_gate_busy session_id=${e.sessionId} gateway_session_key=${e.gatewaySessionKey} reason=${s} queue_depth=${i}`),this.transport.sendError(t,Errors.AgentError.rpcCode,"Agent is busy",{code:"session_busy",reason:s,queueDepth:i}),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:"interrupted",error:INTERRUPTED_PUBLIC_MESSAGE,errorCode:"session_busy"},{turnId:`req:${String(t)}`})}async endRun(e,t){if(e.promptDone||e.mutationTerminalCommitting)return this.logger.debug?.(`[bridge-core] endRun skipped (promptDone=true) sessionId=${e.sessionId} outcome=${t.kind}`),!1;if(void 0===e.pendingPromptId&&void 0===e.currentRunId&&void 0===e.gatewayRequestId)return this.logger.debug?.(`[bridge-core] endRun skipped (no pendingPromptId and no currentRunId) sessionId=${e.sessionId} outcome=${t.kind}`),!1;e.mutationTerminalCommitting=!0,this.state.clearPromptTimeout(e),this.state.clearStreamIdleTimer(e);const s=e.writeGateToken,i=e.activeRunBinding;let n,r,o,a,l="timeout"===e.mutationTerminalOverride?{kind:"interrupted",stopReason:"timeout",message:"The agent did not finish before the session timeout.",errorCode:"gateway_timeout"}:t;if(s){const e="complete"===l.kind?"cancelled"===l.stopReason?"cancelled":"completed":"interrupted"===l.kind&&"timeout"===l.stopReason?"timeout":"error",t=await this.sessionMutationCoordinator.converge(s,e);t.ok?n=t.permit:l={kind:"interrupted",stopReason:"interrupted",message:SESSION_RECOVERY_REQUIRED_MESSAGE,errorCode:SESSION_RECOVERY_REQUIRED_CODE}}try{const t=resolveTurnId(e),s=t?{turnId:t}:void 0;e.promptDone=!0;const i=e.currentRunId;if("complete"===l.kind){if(i&&this.onRunComplete){const t=e.agentAssistantTextSoFar??e.chatAssistantTextSoFar??"";this.onRunComplete(i,t,l.stopReason)}void 0!==e.pendingPromptId&&this.transport.sendResult(e.pendingPromptId,{stopReason:l.stopReason}),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:l.stopReason},s),this.tryGenerateTitleFromHistory(e,e.sessionId)}else"interrupted"===l.kind?(i&&this.onRunFailed&&this.onRunFailed(i,l.message),void 0!==e.pendingPromptId&&this.transport.sendError(e.pendingPromptId,Errors.AgentError.rpcCode,l.message,{code:l.errorCode??"interrupted",stopReason:l.stopReason}),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:l.stopReason,error:l.message,...l.errorCode?{errorCode:l.errorCode}:{}},s)):(i&&this.onRunFailed&&this.onRunFailed(i,l.message),void 0!==e.pendingPromptId&&this.transport.sendError(e.pendingPromptId,l.code,l.message),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:"error",error:l.message},s))}catch(e){r=e}try{this.cleanupPrompt(e)}catch(e){o=e}finally{e.writeGateToken=void 0,e.activeRunBinding=void 0,n&&this.sessionMutationCoordinator.release(n)}if(i){const e="complete"===l.kind?"cancelled"===l.stopReason?"cancelled":"completed":"interrupted"===l.kind&&"cancelled"===l.stopReason?"cancelled":"failed";this.activeRuns.markTerminal(i,e)}try{this.onRunEnded?.(e,l)}catch(e){a=e}if(r)throw r;if(o)throw o;if(a)throw a;return!0}schedulePromptTimeout(e){let t;if(this.state.clearPromptTimeout(e),e.cronJobId){if(!this.cronOverrides.isInitialized())return void this.cronReady.then(()=>{!e.cronJobId||void 0===e.pendingPromptId&&void 0===e.currentRunId||this.schedulePromptTimeout(e)}).catch(e=>this.logger.error?.(`[bridge-core] cron overrides readiness failed: ${e instanceof Error?e.message:e}`));const s=this.cronOverrides.get(e.cronJobId)??this.config.cronMaxDurationDefaultMs;t=Math.max(CRON_DURATION_FLOOR_MS,Math.min(this.config.cronMaxDurationCapMs,s))}else t=this.config.promptTimeoutMs??DEFAULT_PROMPT_TIMEOUT_MS;t<=0||(e.promptTimeoutTimer=setTimeout(()=>{if(e.mutationTerminalCommitting)return;if(void 0===e.pendingPromptId&&void 0===e.currentRunId)return;this.logger.warn?.(`[bridge-core] Prompt timed out sessionId=${e.sessionId} after ${t}ms`),e.mutationTerminalOverride="timeout";const s=this.getGateway(),i=e.writeGateToken;s?.isConnected&&i?this.observeLifecycle(this.sessionMutationCoordinator.requestCancel(i,s).then(t=>this.handleCancellationResult(e,t)),"prompt_timeout_cancel",e):s?.isConnected?this.observeLifecycle(s.chatAbort(e.gatewaySessionKey,e.currentRunId).then(()=>this.interruptPrompt(e,classifyAgentRuntimeFailure({raw:`Prompt timed out after ${t}ms`,source:"live_gateway",runtimeKind:"openclaw"}))),"prompt_timeout_unowned_cancel",e):i&&(this.sessionMutationCoordinator.requireRecovery(i,"gateway_disconnected","disconnect"),this.observeLifecycle(this.endRun(e,{kind:"interrupted",stopReason:"interrupted",message:SESSION_RECOVERY_REQUIRED_MESSAGE,errorCode:SESSION_RECOVERY_REQUIRED_CODE}),"prompt_timeout_disconnected",e))},t),"object"==typeof e.promptTimeoutTimer&&"unref"in e.promptTimeoutTimer&&e.promptTimeoutTimer.unref())}adoptBackgroundMutation(e,t){const s=this.sessionMutationCoordinator.attachOrStartExternal({sessionKey:e.gatewaySessionKey,label:"background_run"},"acp",t);return s.ok?("owner"===s.ownership&&(e.writeGateToken=s.token),s):(this.logger.error?.(`[bridge-core] background mutation rejected sessionKey=${e.gatewaySessionKey} runId=${t} reason=${s.reason}`),s)}cleanupPrompt(e){this.state.clearPromptTimeout(e),this.state.clearStreamIdleTimer(e);const t=e.currentRunId;if(t){this.state.promptsByRunId.delete(t),this.state.runIdToCronJobId.delete(t),this.state.markRunCompleted(t);const e=`tc_${t}_`;for(const[t,s]of this.state.toolCallIdMap)s.startsWith(e)&&this.state.toolCallIdMap.delete(t)}e.gatewayRequestId&&this.state.promptsByGatewayRequestId.delete(e.gatewayRequestId),e.pendingPromptId=void 0,e.promptDone=void 0,e.currentRunId=void 0,e.gatewayRequestId=void 0,e.assistantStreamStartedAt=void 0,e.gatewayMethod=void 0,e.mutationTerminalOverride=void 0,e.mutationTerminalCommitting=void 0,e.assistantMq?.close(),e.assistantMq=void 0,e.pendingUserTurnUpdates=void 0}async completePrompt(e,t){await this.endRun(e,{kind:"complete",stopReason:t})}async interruptPrompt(e,t){this.logRuntimeFailure(e,t),await this.endRun(e,{kind:"interrupted",stopReason:t.stopReason,message:t.publicMessage,errorCode:t.errorCode})}async failPrompt(e,t,s){await this.endRun(e,{kind:"error",code:t,message:s})}cleanupAllPendingPrompts(){for(const e of this.state.sessions.values())e.writeGateToken?(this.sessionMutationCoordinator.requireRecovery(e.writeGateToken,"gateway_disconnected","disconnect"),this.observeLifecycle(this.endRun(e,{kind:"interrupted",stopReason:"interrupted",message:SESSION_RECOVERY_REQUIRED_MESSAGE,errorCode:SESSION_RECOVERY_REQUIRED_CODE}),"gateway_disconnect_recovery",e)):this.observeLifecycle(this.interruptPrompt(e,classifyAgentRuntimeFailure({raw:Errors.GatewayDisconnected.message,source:"live_gateway",runtimeKind:"openclaw"})),"gateway_disconnect_interrupt",e)}handleGatewayResponse(e){const t=e.id;if(!t)return;const s=this.state.promptsByGatewayRequestId.get(t);if(!s||s.promptDone)return;if(!e.ok){const i=e.error,n=i?.message??"gateway returned error";this.logger.warn?.(`[bridge-core] handleGatewayResponse: gateway rejected prompt gatewayRequestId=${t} error=${n}`);const r=classifyAgentRuntimeFailure({raw:n,source:"live_gateway",runtimeKind:"openclaw"});return void("interrupted"===r.kind?this.observeLifecycle(this.interruptPrompt(s,r),"gateway_response_interrupt",s):(this.logRuntimeFailure(s,r),this.observeLifecycle(this.failPrompt(s,Errors.SendFailed.rpcCode,r.publicMessage),"gateway_response_failure",s)))}const i=e.payload,n=i?.runId;n?(s.currentRunId=n,this.sessionMutationCoordinator.bindRun(s.writeGateToken,n),this.observeActiveRun(s),s.assistantStreamStartedAt=Date.now(),this.state.promptsByRunId.set(n,s),this.logger.debug?.(`[bridge-core] handleGatewayResponse: bound runId=${n} gatewayRequestId=${t} sessionId=${s.sessionId}`)):this.logger.debug?.(`[bridge-core] handleGatewayResponse: no runId in payload gatewayRequestId=${t} sessionId=${s.sessionId}`)}maybeCompletePromptFromChatState(e,t){if(e.promptDone||"chat.send"!==e.gatewayMethod)return;const s="string"==typeof t.state?t.state.toLowerCase():void 0;if(s)if("final"===s){const s="string"==typeof t.stopReason?t.stopReason:void 0;this.observeLifecycle(this.completePrompt(e,s||"end_turn"),"chat_state_final",e)}else if("aborted"===s||"cancelled"===s||"cancel"===s)this.observeLifecycle(this.completePrompt(e,"cancelled"),"chat_state_cancelled",e);else if("error"===s){const s=("string"==typeof t.summary?t.summary:void 0)??("string"==typeof t.message?t.message:void 0)??"gateway chat error",i=classifyAgentRuntimeFailure({raw:s,source:"chat_state",runtimeKind:"openclaw"});"interrupted"===i.kind?this.observeLifecycle(this.interruptPrompt(e,i),"chat_state_interrupt",e):(this.logRuntimeFailure(e,i),this.observeLifecycle(this.failPrompt(e,Errors.AgentError.rpcCode,i.publicMessage),"chat_state_failure",e))}}async handleCronRequest(e){const t=this.getGateway();if(!t?.isConnected)return void this.transport.sendAcpError(e.id,Errors.GatewayNotConnected);const s=e.method.replace("/","."),i={...e.params??{}};["cron.add","cron.update","cron.remove","cron.run","cron.runs"].includes(s)&&(i.__beeosCronIngress="acp"),"cron.update"===s&&(i.patch=i.patch&&"object"==typeof i.patch?{...i.patch}:{});try{const t=await this.dispatchLegacyCronCapability(s,i),n=await this.mapCronResultForAcp(s,t);this.transport.sendResult(e.id,n??{}),"cron.add"!==s&&"cron.update"!==s&&"cron.remove"!==s||this.refreshCronIsolatedSessionKeys()}catch(t){const i=t instanceof Error?t.message:"cron request failed";this.logger.warn?.(`[bridge-core] ${s} failed: ${i}`),this.transport.sendAcpError(e.id,Errors.SendFailed,{message:i})}}async mapCronResultForAcp(e,t){if(!t||"object"!=typeof t)return t;const s=t;await this.cronOverrides.snapshot();const i="cron.list"===e||"cron.status"===e,n=e=>{if(!e||"object"!=typeof e)return e;const t=e,s=t.id;if("string"!=typeof s)return e;const n=this.cronOverrides.localId(s)??s,r=this.cronChannelCache.get(n),o=r?encodeBeeosChannelTag("string"==typeof t.description?t.description:void 0,r):t.description,a=this.cronOverrides.get(n);return{...t,id:n,...void 0===o?{}:{description:o},...i&&"number"==typeof a?{_beeos_meta:{maxDurationMs:a}}:{}}};if(Array.isArray(s.jobs))return{...s,jobs:s.jobs.map(n)};if(s.jobs&&"object"==typeof s.jobs){const e=s.jobs,t={};for(const[s,i]of Object.entries(e))t[s]=n(i);return{...s,jobs:t}}return Array.isArray(s.runs)?{...s,runs:s.runs.map(e=>{if(!e||"object"!=typeof e)return e;const t=e,s="string"==typeof t.jobId?this.cronOverrides.localId(t.jobId)??t.jobId:t.jobId;return{...t,jobId:s}})}:"cron.add"===e||"cron.update"===e?n(t):t}async allocateCronChannel(e){if(!this.agentFetch||!this.agentGatewayUrl)return void this.logger.debug?.("[bridge-core] agentFetch/agentGatewayUrl unavailable, skip channel alloc");const t=this.getAuthoritativeInstanceId?.()?.trim();if(!t?.startsWith("inst_"))return void this.logger.warn?.("[bridge-core] no authoritative inst_* instance id resolved yet, skip channel alloc");const s=this.config.gateway.agentId||this.getDefaultAgentId(),i=this.resolvePlatformAgentId(s)?.trim();if(!i)return void this.logger.warn?.(`[bridge-core] no platform agent id for localAgentId=${s}, skip channel alloc`);const n={source:"cron",job_name:e,protocol:"beeos-conversation",target_agent_id:i,title:e};try{const e=`${this.agentGatewayUrl}/api/v1/channels`,s=await this.agentFetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({participants:[t,"service:cron"],metadata:n})});if(!s.ok)return void this.logger.warn?.(`[bridge-core] channel alloc failed: ${s.status}`);return(await s.json()).id}catch(e){return void this.logger.warn?.(`[bridge-core] channel alloc error: ${e instanceof Error?e.message:e}`)}}setCronChannelCache(e,t){if(this.cronChannelCache.size>=AcpGatewayBridgeCore.CRON_CHANNEL_CACHE_MAX){const e=this.cronChannelCache.keys().next().value;void 0!==e&&this.cronChannelCache.delete(e)}this.cronChannelCache.set(e,t)}async refreshCronIsolatedSessionKeys(){const e=this.getGateway();if(e?.isConnected)try{const t=await e.request("cron.list",{}),s=t?.jobs;if(!Array.isArray(s))return;const i=new Set,n=[];for(const e of s){if(!e||"object"!=typeof e)continue;const t=e;if("string"==typeof t.id&&n.push(t.id),"isolated"!==t.sessionTarget)continue;const s=t.sessionKey;"string"==typeof s&&s.length>0&&i.add(s)}this.cronIsolatedSessionKeys=i,await this.cronOverrides.reconcile(n)}catch(e){this.logger.debug?.(`[bridge-core] refreshCronIsolatedSessionKeys failed: ${e instanceof Error?e.message:e}`)}}}async function fetchWithRetry(e,t={}){const s=t.maxRetries??3;let i;for(let n=0;n<=s;n++){const r=await fetch(e,{signal:AbortSignal.timeout(12e4),redirect:"follow"});if(r.ok)return Buffer.from(await r.arrayBuffer());if(429===r.status||r.status>=500){const o=Number(r.headers.get("retry-after"))||0,a=1e3*Math.max(o,2**n);if(i=new Error(`HTTP ${r.status} from ${e}`),n<s){t.logger?.info?.(`[bridge-core] Download ${r.status}, retry ${n+1}/${s} in ${(a/1e3).toFixed(0)}s`),await new Promise(e=>setTimeout(e,a));continue}}throw new Error(`Failed to download ${e}: HTTP ${r.status}`)}throw i??new Error(`Download failed after retries: ${e}`)}const SKILL_ROOT_MARKERS=["SKILL.md","skill.md","SKILL.MD"];function normalizeSkillArtifactPath(e){const t=e.replaceAll("\\","/").replace(/^\.\//,"");if(!t||t.startsWith("/")||t.split("/").includes(".."))throw new RuntimeCommandError("INVALID_PARAMS",`Invalid skill artifact path: ${e}`);return t}function parseSkillZip(e){if(e.byteLength>MAX_ZIP_BYTES)throw new RuntimeCommandError("INVALID_PARAMS","Skill archive too large");const t=new AdmZip(e).getEntries().filter(e=>!e.isDirectory).map(e=>({name:normalizeSkillArtifactPath(e.entryName),bytes:e.getData()})).filter(e=>!e.name.split("/").includes("__MACOSX"));if(0===t.length)throw new RuntimeCommandError("INVALID_PARAMS","Skill archive is empty");const s=1===new Set(t.map(e=>e.name.split("/")[0])).size&&t.every(e=>e.name.includes("/")),i=new Map;for(const e of t){const t=s?e.name.slice(e.name.indexOf("/")+1):e.name;if(!t||i.has(t))throw new RuntimeCommandError("INVALID_PARAMS",`Duplicate skill path: ${t}`);i.set(t,e.bytes)}return i}async function resolveSkillRoot(e){for(const t of SKILL_ROOT_MARKERS)try{return await stat(join(e,t)),e}catch{}const t=(await readdir(e,{withFileTypes:!0})).filter(e=>e.isDirectory()&&!e.name.startsWith(".")&&"__MACOSX"!==e.name);if(1===t.length){const s=join(e,t[0].name);for(const e of SKILL_ROOT_MARKERS)try{return await stat(join(s,e)),s}catch{}return s}return e}async function extractZipToDir(e,t){const s=new AdmZip(e),i=join(t,".beeos-extract-tmp-"+Date.now());try{await mkdir(i,{recursive:!0}),s.extractAllTo(i,!0);const e=await resolveSkillRoot(i),n=await readdir(e,{withFileTypes:!0});let r=0;for(const s of n){if(s.name.startsWith(".beeos-extract-tmp")||"__MACOSX"===s.name)continue;const i=join(e,s.name),n=join(t,s.name);await rename(i,n).catch(async()=>{await cp(i,n,{recursive:!0})}),r++}if(0===r)throw new Error("Zip archive contained no extractable files")}finally{await rm(i,{recursive:!0,force:!0}).catch(()=>{})}}const VALID_SLUG_PATTERN=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,NON_ASCII_PATTERN=/[^\x00-\x7F]/;function validateSkillSlug(e){const t=e.trim();if(!t||t.includes("/")||t.includes("\\")||t.includes(".."))throw new Error(`Invalid skill slug: ${e}`);if(NON_ASCII_PATTERN.test(t)||!VALID_SLUG_PATTERN.test(t))throw new Error(`Invalid skill slug: ${e}`);return t}function safeDirName(e){const t=e.trim();return t?t.replaceAll("/","__").replaceAll("\\","__"):t}function extractMcpCredentialMaterial(e){const t=mcpStringMap(e.headers,"MCP headers"),s=mcpStringMap(e.env,"MCP environment");if(!(t&&0!==Object.keys(t).length||s&&0!==Object.keys(s).length))return;const i=e.transport??("string"==typeof e.command?"stdio":"string"==typeof e.url?"streamable-http":void 0);if("stdio"===i&&t&&Object.keys(t).length)throw new Error("MCP stdio config cannot include headers");if("stdio"!==i&&s&&Object.keys(s).length)throw new Error("MCP HTTP config cannot include env");return{...t&&Object.keys(t).length?{headers:t}:{},...s&&Object.keys(s).length?{env:s}:{}}}function mcpStringMap(e,t){if(void 0!==e){if(!e||"object"!=typeof e||Array.isArray(e)||Object.entries(e).some(([e,t])=>!e||/[\u0000-\u001f\u007f]/.test(e)||"string"!=typeof t))throw new Error(`${t} invalid`);return{...e}}}function requireCredentialReferencePort(e){if(!e)throw new Error("MCP credential reference vault is unavailable");return e}function resolveSkillInstallDir(e,t){const s=safeDirName(t),i=join(e,s),n=resolve(e),r=resolve(i),o=relative(n,r);if(!o||".."===o||o.startsWith(`..${sep}`)||path.isAbsolute(o))throw new Error("Invalid skill target path");return i}
|
|
1
|
+
import{randomUUID,createHash}from"node:crypto";import{mkdir,readFile,rm,stat,readdir,rename,cp}from"node:fs/promises";import path from"node:path";import{join,resolve,relative,sep}from"node:path";import{homedir}from"node:os";import AdmZip from"adm-zip";import{sanitizePromptPayload}from"../message-sanitization/prompt-payload-sanitizer.js";import{previewSanitizedText,stripTransportMetadata}from"../message-sanitization/transport-metadata-sanitizer.js";import{isHeartbeatPromptText,isCronPromptText,extractCronJobId,classifyHeartbeatFilter}from"../message-sanitization/message-classifier.js";import{createCronOverridesStore,createInMemoryCronOverridesStore}from"../cron-overrides.js";import{CRON_DURATION_FLOOR_MS}from"../config.js";import{CANVAS_TERM_MAPPING,CANVAS_UPDATE_HINT,buildActiveSurfacesContext}from"../canvas/tools.js";import{parseMentionsParam,buildMentionInstruction}from"../delegation/mention-resolver.js";import{EXTERNAL_PROTOCOL_TAGS}from"./external-protocol-tags.js";import{extractPromptBlocks,toGatewayPrompt,resolveSlashCommandName as resolveSlashCmd}from"./prompt-converter.js";import{extractBeeosUserTextFromHistoryContent}from"./beeos-user-envelope.js";import{loadHistory,loadHistoryPage,groupIntoTurns,splitUserReplayBlocks}from"./history-replay.js";import{classifyHistoricalAssistantTurnCompletion}from"./history-turn-completion-policy.js";import{LocalSessionHistory}from"./local-session-history.js";import{reconcileMissingArtifacts}from"./missing-artifacts-reconciler.js";import{buildResolutionPlan,resolveResources,applyResolutions}from"./prompt-resource-resolver.js";import{readEnrichmentCache,readUploadToolResult}from"../upload/result-cache.js";import{buildToolResultSessionContentBlocks}from"./tool-result-blocks.js";import{prefersChatFileArtifacts}from"./file-artifact-presenter.js";import{buildToolCallPayload,buildToolCallUpdatePayload}from"./tool-call-payload-builder.js";import{Errors}from"../errors/index.js";import{classifyAgentRuntimeFailure,INTERRUPTED_PUBLIC_MESSAGE}from"../runtime/agent-runtime-failure-classifier.js";import{isPlaceholderTitle}from"../runtime/conversation-title.js";import{SESSION_RECOVERY_REQUIRED_CODE,SESSION_RECOVERY_REQUIRED_MESSAGE}from"../runtime/session-mutation-coordinator.js";import{observeLifecyclePromise}from"../runtime/lifecycle-promise-observer.js";import{RuntimeSessionNewRejectedError}from"../runtime/runtime-rpc-consumer.js";import{normalizeRuntimeAgentLocalKey,OpenClawRuntimeCommandDispatcher,RuntimeCommandError}from"../runtime/runtime-command-dispatcher.js";import{FileRuntimeAgentIdentityRegistry}from"../runtime/runtime-agent-identity-registry.js";import{FileRuntimeLeasePort}from"../runtime/runtime-operation-lease.js";import{FileRuntimeCommandJournal,InMemoryRuntimeCommandJournal}from"../runtime/runtime-command-journal.js";import{OpenClawRuntimeCapabilities}from"../runtime/openclaw-runtime-capabilities.js";import{RuntimeCanvasService}from"../canvas/runtime-canvas-service.js";import{RuntimeSkillsService}from"../runtime/runtime-skills-service.js";import{RuntimeCronService,encodeBeeosChannelTag}from"../runtime/runtime-cron-service.js";export{BEEOS_CHANNEL_TAG_RE,decodeBeeosChannelId,encodeBeeosChannelTag,stripBeeosChannelTag}from"../runtime/runtime-cron-service.js";import{openClawKeyMatchesConversation,openClawSessionKeysFromList,resolveLiveOpenClawSessionKey}from"../runtime/openclaw-session-key-resolution.js";import{LocalConversationHistoryBoundary,OpenClawGatewaySessionMetadataPort,OpenClawSessionMetadataService,RuntimeSessionControlService}from"../runtime/runtime-session-control-service.js";import{pageRuntimeSessions,parseRuntimeSessionListPage}from"../runtime/runtime-session-list-policy.js";import{assertTrustedCoreExecutionAttempt,createAcpCoreExecutionAttempt}from"../runtime/core-execution-attempt-context.js";import{CompositeActiveRunPort}from"../runtime/composite-active-run-port.js";import{resolveChannelFromSessionKey}from"../channel-detection.js";import{resolveTurnId,recordTurnIdForRole,recordToolCallTurnForUpdate}from"./gateway-events.js";import{emitToolResultProjectionForTurn}from"./tool-result-emitter.js";import{extractPersistedToolResultEnvelope,findPersistedToolResultEnvelopeByMessageId}from"./tool-result-transcript.js";import{projectPersistedToolResultForReplay}from"./tool-result-projection.js";import{McpService}from"./mcp-service.js";import{McpDesiredStateStore,normalizeMcpPublicServerConfig}from"./mcp-desired-state-store.js";import{requireSecretFreeMcpServerName}from"./mcp-public-config-security.js";import{McpDesiredStateController}from"./mcp-desired-state-controller.js";import{McpNativeConfigProjector}from"./mcp-native-config-projector.js";import{CredentialReferenceRuntimeResolver}from"./mcp-credential-reference-port.js";import{DEFAULT_PROMPT_TIMEOUT_MS}from"./types.js";import{ACP_PROTOCOL_VERSION}from"@beeos-ai/beeos-types/acp";import{canonicalizeJcs}from"@beeos-ai/beeos-types/runtime";import{MAX_ZIP_BYTES,parseAndValidateTemplatePackage,TemplatePackageError}from"./agent-template-package.js";const DEFAULT_AGENT_ID="main";export function normalizeAgentId(e){return normalizeRuntimeAgentLocalKey(e)}function narrowContentBlock(e){switch(e.type){case"text":return"string"==typeof e.text?{type:"text",text:e.text}:void 0;case"resource_link":return"string"==typeof e.uri?{type:"resource_link",uri:e.uri,...void 0!==e.name?{name:e.name}:{},...void 0!==e.mimeType?{mimeType:e.mimeType}:{}}:void 0;case"file":return{type:"file",...void 0!==e.text?{text:e.text}:{},...void 0!==e.uri?{uri:e.uri}:{},...void 0!==e.mimeType?{mimeType:e.mimeType}:{}};case"image":return{type:"image",...void 0!==e.uri?{uri:e.uri}:{},...void 0!==e.mimeType?{mimeType:e.mimeType}:{}};default:return}}const DEFAULT_MODE={id:"default",name:"Default",description:"Default agent mode"},USER_MESSAGE_PREFIX="User Message From BeeOS:",USER_MESSAGE_PREFIX_WITH_NEWLINE=`${USER_MESSAGE_PREFIX}\n`,SLASH_COMMAND_NAME_RE=/^[a-z0-9_-]+$/i,HISTORY_PAGE_DEFAULT_LIMIT=100,HISTORY_PAGE_MAX_LIMIT=1e3;function withUserMessagePrefix(e){return e.startsWith(USER_MESSAGE_PREFIX)?e:`${USER_MESSAGE_PREFIX_WITH_NEWLINE}${e}`}const BACKGROUND_SESSION_PATTERNS=[":cron:",":hook:","node-",...EXTERNAL_PROTOCOL_TAGS];function isBackgroundSessionKey(e){return BACKGROUND_SESSION_PATTERNS.some(t=>e.includes(t))}function isSystemDefaultSessionKey(e){const t=e.split(":");if(t.length<3||"agent"!==t[0])return!1;const s=t.slice(2).join(":");return"main"===s||s===t[1]}function cleanGatewayDerivedTitle(e){if(!e)return;let t=extractBeeosUserTextFromHistoryContent(e).text;return/^\[System\b/.test(t)?void 0:(t=t.trim(),t||void 0)}function cleanHistoryUserContent(e){return extractBeeosUserTextFromHistoryContent(e).text.trim()}function mergePersistedToolResultEnvelopes(e,t){if(e||t)return{toolName:e?.toolName||t?.toolName||"tool",...e?.toolCallId||t?.toolCallId?{toolCallId:e?.toolCallId??t?.toolCallId}:{},...e?.rawText??t?.rawText?{rawText:e?.rawText??t?.rawText}:{},...void 0!==e?.rawResult||void 0!==t?.rawResult?{rawResult:e?.rawResult??t?.rawResult}:{},...e?.timestamp||t?.timestamp?{timestamp:e?.timestamp??t?.timestamp}:{}}}function resolveStandaloneSlashCommandName(e,t){if(0===e.length)return;if(e.some(e=>"text"!==e.type))return;const s=t.trim();if(!s||s.includes("\n")||!s.startsWith("/"))return;const i=s.match(/^\/([^\s:]+)(?::|\s|$)/)?.[1]?.trim();return i&&!i.includes("/")&&SLASH_COMMAND_NAME_RE.test(i)?i.toLowerCase():void 0}class AcpRuntimeCommandResourceStore{fetchPackage;parsePackage;isValidationError;content=new Map;artifacts=new Map;mcpDefinitions=new Map;constructor(e,t,s){this.fetchPackage=e,this.parsePackage=t,this.isValidationError=s}registerContent(e){const t=`acp-content:sha256:${createHash("sha256").update(e).digest("hex")}`;return this.content.set(t,e),t}registerMcpDefinition(e,t){this.mcpDefinitions.set(JSON.stringify(e),structuredClone(t))}async resolveMcpDefinition(e){const t=this.mcpDefinitions.get(JSON.stringify(e));if(!t)throw new Error("ACP MCP definition was not verified for this request");return structuredClone(t)}async registerArtifact(e,t){try{const s=await this.fetchPackage(e);if(!s.ok)throw new TemplatePackageError(`failed to download package: HTTP ${s.status}`);const i=Buffer.from(await s.arrayBuffer());if(i.length>MAX_ZIP_BYTES)throw new TemplatePackageError(`package too large: ${i.length} bytes (max ${MAX_ZIP_BYTES})`);const n=createHash("sha256").update(i).digest("hex");if(t?.trim()&&t.trim().toLowerCase()!==n)throw new TemplatePackageError("package sha256 mismatch");const r=this.parsePackage(i),o=`acp-artifact:sha256:${n}`;return this.artifacts.set(o,r),{artifactRef:o,version:r.manifest?.version??"0.0.0",sha256:n,sizeBytes:String(i.length),source:"acp-verified"}}catch(e){if(e instanceof TemplatePackageError||this.isValidationError(e))throw new RuntimeCommandError("INVALID_PARAMS",`Invalid template package: ${e instanceof Error?e.message:String(e)}`);throw new RuntimeCommandError("EXECUTION_FAILED",`Apply template failed: ${e instanceof Error?e.message:String(e)}`)}}registerParsedArtifact(e){const t=createHash("sha256");for(const[s,i]of[...e.workspaceFiles].sort(([e],[t])=>e.localeCompare(t)))t.update(s).update("\0").update(i).update("\0");const s=t.digest("hex"),i=`acp-artifact:sha256:${s}`;this.artifacts.set(i,e);const n=[...e.workspaceFiles.values()].reduce((e,t)=>e+t.byteLength,0);return{artifactRef:i,version:e.manifest?.version??"0.0.0",sha256:s,sizeBytes:String(n),source:"acp-verified"}}async readContent(e){const t=this.content.get(e);if(void 0===t)throw new Error(`unknown contentRef: ${e}`);return t}async readVerifiedArtifact(e){const t=this.artifacts.get(e.artifactRef);if(!t)throw new Error(`unknown verified artifact: ${e.artifactRef}`);return t}}export const lateBoundRuntimeAgentProjectionPort=e=>({prepareCommittedMutation:async t=>{const s=e();if(!s)throw new Error("agent projection production is unavailable");return await s.prepareCommittedMutation(t)},applyCommittedMutation:async t=>{const s=e();if(!s)throw new Error("agent projection production is unavailable");return await s.applyCommittedMutation(t)},compactCommittedMutation:async t=>{const s=e();if(!s)throw new Error("agent projection production is unavailable");await s.compactCommittedMutation(t)}});function deriveSessionId(e,t){const s=createHash("sha256").update(`${t}:${e}`).digest("hex").substring(0,32);return`session:${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20,32)}`}function parseAgentIdFromKey(e){const t=e.split(":");return(t.length>=3&&"agent"===t[0]?t[1]:"")||"main"}function createSessionObject(e){const t=parseAgentIdFromKey(e.gatewayKey);return{sessionId:deriveSessionId(e.gatewayKey,e.instanceId),gatewaySessionKey:e.gatewayKey,agentId:t,platformAgentId:e.resolvePlatformAgentId?.(t),createdAt:Date.now(),chatReplayDedupKeys:new Set,cwd:e.cwd,title:e.title,channelType:resolveChannelFromSessionKey(e.gatewayKey,e.thirdPartyChannels)}}class HistoryUpdateRecorder{transport;updates=[];constructor(e){this.transport=e}sendSessionUpdate(e,t,s){const i=this.transport.materializeSessionUpdate(t,s);return null!==i&&this.updates.push(i),!0}}export class AcpGatewayBridgeCore{state;transport;config;logger;writeObs;getGateway;thirdPartyChannels;beeosFileResolver;agentFetch;agentGatewayUrl;triggerAgentSync;sessionMutationCoordinator;runtimeCommands;runtimeAgentIdentities;runtimeLeases;runtimeCommandResources;localHistoryBoundary;activeRuns;markAgentProjectionDirty;projectionObservationTimeoutMs;cronChannelCache=new Map;static CRON_CHANNEL_CACHE_MAX=256;localSessionHistory;mcp;runtimeTerminalService;initialized=!1;agentMapping=null;_syncResolvers=[];_mappingReadyCallbacks=[];_mappingUpdateCallbacks=[];cronIsolatedSessionKeys=new Set;cronOverrides;cronReady;sessionPreloadInFlight=null;sessionPreloadInFlightGeneration=null;sessionPreloadReady=Promise.resolve();resolveSessionPreloadReady=null;rejectSessionPreloadReady=null;sessionPreloadGeneration=0;sessionPreloadBarrierActive=!1;sessionPreloadFailed=!1;async setAgentMapping(e){this.agentMapping=e;for(const t of this.state.sessions.values())!t.platformAgentId&&t.agentId&&(t.platformAgentId=e.get(t.agentId)?.id);for(const e of this._syncResolvers)e();this._syncResolvers=[];for(const e of this._mappingReadyCallbacks)e();this._mappingReadyCallbacks=[];for(const t of this._mappingUpdateCallbacks)t(e);this.sessionPreloadFailed&&this.beginGatewaySessionPreload(),this.sessionPreloadBarrierActive&&await this.preloadSessionsFromGateway()}beginGatewaySessionPreload(){this.sessionPreloadBarrierActive&&this.sessionPreloadReady.catch(()=>{}),this.sessionPreloadGeneration+=1,this.sessionPreloadBarrierActive=!0,this.sessionPreloadFailed=!1,this.sessionPreloadReady=new Promise((e,t)=>{this.resolveSessionPreloadReady=e,this.rejectSessionPreloadReady=t}),this.sessionPreloadReady.catch(()=>{})}failGatewaySessionPreload(){this.sessionPreloadBarrierActive&&(this.sessionPreloadBarrierActive=!1,this.sessionPreloadFailed=!0,this.rejectSessionPreloadReady?.(new RuntimeCommandError("GATEWAY_NOT_CONNECTED","Gateway disconnected before session hydration completed")),this.resolveSessionPreloadReady=null,this.rejectSessionPreloadReady=null)}async waitForGatewaySessionPreload(){await this.sessionPreloadReady}onceAgentMappingReady(e){this.agentMapping&&this.agentMapping.size>0?e():this._mappingReadyCallbacks.push(e)}onAgentMappingUpdated(e){this._mappingUpdateCallbacks.push(e),this.agentMapping&&this.agentMapping.size>0&&e(this.agentMapping)}markAgentSyncDone(){for(const e of this._syncResolvers)e();this._syncResolvers=[]}waitForAgentMapping(e=15e3){return this.agentMapping?Promise.resolve():new Promise(t=>{this._syncResolvers.push(t);const s=setTimeout(()=>{const e=this._syncResolvers.indexOf(t);-1!==e&&this._syncResolvers.splice(e,1),t()},e);"object"==typeof s&&"unref"in s&&s.unref()})}handleTerminalRequest=null;handleTerminalNotification=null;onRunComplete=null;onRunFailed=null;onRunEnded=null;handleSlashCommand=null;onPromptStart=null;instanceId;getAuthoritativeInstanceId;mcpCredentialReferences;constructor(e){this.state=e.state,this.transport=e.transport,this.config=e.config,this.logger=e.logger,this.writeObs=e.writeObs,this.getGateway=e.getGateway,this.instanceId=e.instanceId||"unknown",this.getAuthoritativeInstanceId=e.getAuthoritativeInstanceId,this.mcpCredentialReferences=e.mcpCredentialReferences,this.thirdPartyChannels=e.thirdPartyChannels??new Set,this.beeosFileResolver=e.beeosFileResolver,this.agentFetch=e.agentFetch,this.agentGatewayUrl=e.agentGatewayUrl,this.triggerAgentSync=e.triggerAgentSync,this.markAgentProjectionDirty=e.markAgentProjectionDirty,this.projectionObservationTimeoutMs=e.projectionObservationTimeoutMs??5e3,this.sessionMutationCoordinator=e.sessionMutationCoordinator,this.runtimeAgentIdentities=e.runtimeAgentIdentities??new FileRuntimeAgentIdentityRegistry(join(process.env.OPENCLAW_HOME||join(homedir(),".openclaw"),"beeos","runtime-agent-identities.json")),this.runtimeLeases=e.runtimeLeases??new FileRuntimeLeasePort(join(process.env.OPENCLAW_HOME||join(homedir(),".openclaw"),"beeos","runtime-operation-leases.json")),this.runtimeCommandResources=e.runtimeCommandResources??new AcpRuntimeCommandResourceStore(e.agentFetch??((e,t)=>fetch(e,t)),e.runtimeTemplatePackageParser?.parse??parseAndValidateTemplatePackage,e.runtimeTemplatePackageParser?.isValidationError??(e=>e instanceof TemplatePackageError));const t=e.runtimeCommandJournal??(e.runtimeLeases||process.env.VITEST?new InMemoryRuntimeCommandJournal:new FileRuntimeCommandJournal(join(process.env.OPENCLAW_HOME||join(homedir(),".openclaw"),"beeos","runtime-command-journal.json")));this.localSessionHistory=new LocalSessionHistory({logger:this.logger}),this.cronOverrides=e.cronOverrides??(process.env.VITEST?createInMemoryCronOverridesStore():createCronOverridesStore(this.logger)),this.cronReady=this.cronOverrides.initialize(),this.cronReady.catch(()=>{});const s=e.mcpCredentialReferences?new CredentialReferenceRuntimeResolver(e.mcpCredentialReferences):void 0,i=e.mcpToolBridge?new McpDesiredStateController(new McpDesiredStateStore(e.mcpDesiredStatePath??join(process.env.OPENCLAW_HOME||join(homedir(),".openclaw"),"beeos","mcp-desired-state.json")),e.mcpToolBridge,s,e.mcpCredentialReferences,t,e.runtimeReceiptHistory,new McpNativeConfigProjector({logger:this.logger})):void 0;this.mcp=new McpService({transport:this.transport,logger:this.logger,state:this.state,...i?{desiredState:i}:{}}),this.localHistoryBoundary=new LocalConversationHistoryBoundary(e=>{const t=this.state.sessions.get(e);t&&(t.chatReplayDedupKeys.clear(),this.onSessionCleared?.(t.sessionId,t.gatewaySessionKey))}),this.activeRuns=e.activeRuns??new CompositeActiveRunPort;const n=new RuntimeCronService({getGateway:e.getGateway,overrides:this.cronOverrides,durationFloorMs:CRON_DURATION_FLOOR_MS,durationCapMs:this.config.cronMaxDurationCapMs,channels:{allocate:async e=>await this.allocateCronChannel(e),lookup:e=>this.cronChannelCache.get(e),remember:(e,t)=>this.setCronChannelCache(e,t),forget:e=>{this.cronChannelCache.delete(e)}}}),r=new RuntimeSessionControlService({convergeRun:async({runtimeSessionKey:e})=>{const t=this.state.sessionsByGatewayKey.get(e),s=(new Date).toISOString();if(!t||t.promptDone&&void 0===t.pendingPromptId&&void 0===t.currentRunId)return{state:"no_active_run",quiescence:{state:"verified",observedAt:s}};const i=this.getGateway();if(!i?.isConnected)return{state:"recovery_required",reason:"gateway_disconnected"};if(!t.writeGateToken||!t.currentRunId)return{state:"recovery_required",reason:"run_conflict",runtimeRunId:t.currentRunId??"unknown"};const n=t.currentRunId,r=await this.sessionMutationCoordinator.requestCancel(t.writeGateToken,i);if(!r.ok)return{state:"recovery_required",reason:"terminal_not_observed",runtimeRunId:n};const o=await r.terminalObservation;return o.ok?{state:"terminal_observed",runtimeRunId:n,abortObservation:r.acknowledged?{state:"target_acknowledged",aborted:!0,runIds:[n],targetRunAcknowledged:!0}:{state:"already_stopped",aborted:!1,runIds:[]},terminalState:"cancelled",quiescence:{state:"verified",observedAt:(new Date).toISOString()}}:{state:"recovery_required",reason:"quiescence_failed"===o.recovery.reason?"quiescence_failed":"quiescence_timeout"===o.recovery.reason?"quiescence_timeout":"terminal_not_observed",runtimeRunId:n}},reset:async e=>{const t=this.getGateway();if(!t?.isConnected)throw new RuntimeCommandError("GATEWAY_NOT_CONNECTED","Gateway not connected");await t.sessionsReset(e)}},new OpenClawSessionMetadataService(new OpenClawGatewaySessionMetadataPort(e.getGateway,(e,t)=>{const s=this.state.sessionsByGatewayKey.get(e);if(!s)throw new RuntimeCommandError("INVALID_PARAMS",`setModel projection requires a live local session for key=${e}`);void 0===t.modelOverrideId?delete s.modelOverrideId:s.modelOverrideId=t.modelOverrideId,s.effectiveModelId=t.effectiveModelId,void 0===t.modelProvider?delete s.modelProvider:s.modelProvider=t.modelProvider},{resolveLiveKey:e=>resolveLiveOpenClawSessionKey(e,this.state.sessions.values()),waitForHydration:async()=>await this.waitForGatewaySessionPreload(),reconcileMissingLiveKey:async(e,t)=>await this.reconcileMissingGatewaySession(e,t),materializeMissingModelKey:async(e,t)=>await this.materializeMissingModelSessionKey(e,t),registerMaterializedModelKey:e=>this.registerMaterializedModelSession(e)})),this.activeRuns),o=e.getAgentProjection?lateBoundRuntimeAgentProjectionPort(e.getAgentProjection):void 0,a=e.runtimeCommandDispatcher??new OpenClawRuntimeCommandDispatcher({getGateway:e.getGateway,resources:this.runtimeCommandResources,identities:this.runtimeAgentIdentities,leases:this.runtimeLeases,journal:t,logger:e.logger,...o?{projection:o}:{},...e.templateOriginReporter?{templateOriginReporter:e.templateOriginReporter}:{}});this.runtimeCommands=a,a instanceof OpenClawRuntimeCommandDispatcher&&a.setCapabilities(new OpenClawRuntimeCapabilities({getGateway:e.getGateway,identities:this.runtimeAgentIdentities,sessions:r,skills:new RuntimeSkillsService({getGateway:e.getGateway,resources:this.runtimeCommandResources,getOpenclawHome:()=>this.getOpenclawHome()}),mcp:this.mcp,terminal:{execute:async(e,t)=>{if(!this.runtimeTerminalService)throw new RuntimeCommandError("INVALID_PARAMS","terminal canonical delegate is not configured");return await this.runtimeTerminalService.execute(e,t)}},canvas:new RuntimeCanvasService({apply:async(e,t)=>{await this.applyCanonicalCanvasControl(e,t)}}),cron:n})),this.transport.setSessionUpdateObserver((e,t,s)=>{const i=s?.turnId;if(!i)return;const n=this.state.sessions.get(e);n&&(recordTurnIdForRole(n,t,i),recordToolCallTurnForUpdate(n,t,i))})}setRuntimeTerminalService(e){this.runtimeTerminalService=e}setRuntimeReceiptHistoryPort(e){this.mcp.setRuntimeReceiptHistoryPort(e)}getRuntimeCommandDispatcher(){return this.runtimeCommands}async startMcp(){await this.mcp.start()}async stopMcp(){await this.mcp.stop()}nudgeMcpNativeProjection(){this.mcp.nudgeNativeProjection()}observeActiveRun(e){const t=e.currentRunId,s=e.writeGateToken,i=this.sessionMutationCoordinator.snapshot(e.gatewaySessionKey),n=void 0===e.pendingPromptId?e.gatewayRequestId??t:String(e.pendingPromptId);if(!t||!i||!n)return;const r={runtimeConversationUid:e.sessionId,runtimeSessionKey:e.gatewaySessionKey,historyGeneration:this.localHistoryBoundary.currentGeneration(e.sessionId),targetMessageId:n,runtimeRunId:t,activeRunRegistrationId:`acp:${i.operationId}`};return this.activeRuns.register(r,async()=>{const n=this.getGateway();if(!n?.isConnected||e.currentRunId!==t)return"recovery_required";const r=s?.operationId===i.operationId?await this.sessionMutationCoordinator.requestCancel(s,n):await this.sessionMutationCoordinator.requestCancelForSession(e.gatewaySessionKey,n);return r.ok?"accepted":!("reason"in r)||"terminal_already_observed"!==r.reason&&"no_active_mutation"!==r.reason?"recovery_required":"already_terminal"}),e.activeRunBinding=r,r}getActiveRunAuthority(){return{activeRuns:this.activeRuns,historyGeneration:e=>this.localHistoryBoundary.currentGeneration(e)}}resolvePlatformAgentId(e){return this.agentMapping?.get(e)?.id}resolveLocalAgentId(e){if(this.agentMapping&&e)for(const[t,s]of this.agentMapping)if(s.id===e)return t}getDefaultAgentId(){return this.agentMapping&&this.agentMapping.size>0?this.agentMapping.keys().next().value??"main":"main"}registerSession(e,t={}){const{ensureVerbose:s=!0}=t;this.state.sessions.has(e.sessionId);this.state.sessions.set(e.sessionId,e),this.state.sessionsByGatewayKey.set(e.gatewaySessionKey,e),s&&this.ensureVerboseFull(e),this.subscribeSessionMessages(e)}async ensureVerboseFull(e){if(e.verbosePatched)return;const t=this.getGateway();if(t?.isConnected){e.verbosePatched=!0;try{await t.sessionsPatch(e.gatewaySessionKey,{verboseLevel:"full"})}catch(t){e.verbosePatched=!1,this.logger.debug?.(`[bridge-core] ensureVerboseFull failed: ${t instanceof Error?t.message:t}`)}}}ensureSessionForKey(e){const t=this.state.findSessionByKey(e);if(t)return t;const s=createSessionObject({gatewayKey:e,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels});return this.registerSession(s),this.logger.debug?.(`[bridge-core] ensureSessionForKey: lazily created session sid=${s.sessionId} key=${e}`),s}async preloadSessionsFromGateway(){const e=this.sessionPreloadGeneration;if(this.sessionPreloadInFlight&&this.sessionPreloadInFlightGeneration===e)return await this.sessionPreloadInFlight;const t=this.preloadGatewaySessionIndex(e);this.sessionPreloadInFlight=t,this.sessionPreloadInFlightGeneration=e;try{await t,e===this.sessionPreloadGeneration&&this.sessionPreloadBarrierActive&&(this.sessionPreloadBarrierActive=!1,this.resolveSessionPreloadReady?.(),this.resolveSessionPreloadReady=null,this.rejectSessionPreloadReady=null)}catch(t){throw e===this.sessionPreloadGeneration&&this.sessionPreloadBarrierActive&&(this.sessionPreloadBarrierActive=!1,this.sessionPreloadFailed=!0,this.rejectSessionPreloadReady?.(t instanceof Error?t:new Error("session preload failed")),this.resolveSessionPreloadReady=null,this.rejectSessionPreloadReady=null),t}finally{this.sessionPreloadInFlight===t&&(this.sessionPreloadInFlight=null,this.sessionPreloadInFlightGeneration=null)}}async preloadGatewaySessionIndex(e){const t=this.getGateway();if(this.logSessionAuthority("session_preload_start",{generation:e,reason:t?.isConnected?"gateway_connected":"gateway_not_connected"}),!t?.isConnected)throw this.logSessionAuthority("session_preload_failure",{generation:e,reason:"gateway_not_connected"}),new RuntimeCommandError("GATEWAY_NOT_CONNECTED","Gateway not connected for session hydration");try{const s=await t.sessionsList(),i=this.mergeGatewaySessions(s);this.logSessionAuthority("session_preload_success",{generation:e,loaded:i,reason:"authoritative_sessions_list"})}catch(t){throw this.logSessionAuthority("session_preload_failure",{generation:e,reason:t instanceof RuntimeCommandError?t.code:"sessions_list_failed"}),t}}mergeGatewaySessions(e,t){if(!e||"object"!=typeof e)return 0;const s=e.sessions;if(!Array.isArray(s))return 0;let i=0;for(const e of s){if(!e||"object"!=typeof e||Array.isArray(e))continue;const s=e,n=s.sessionKey??s.key??s.id??s.name;if("string"!=typeof n||!n.trim()||n.trim()!==n||t&&!t(n)||this.state.findSessionByKey(n))continue;const r=s.label||s.derivedTitle||s.title||void 0,o=r&&!isPlaceholderTitle(r)?r:void 0,a=createSessionObject({gatewayKey:n,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,title:o});this.registerSession(a,{ensureVerbose:!1}),this.onSessionLoaded?.(a.sessionId,a.gatewaySessionKey,a.platformAgentId),i+=1}return i}async reconcileMissingGatewaySession(e,t){await this.assertSessionReconcileFence(t);const s=this.getGateway();if(!s?.isConnected)throw this.logSessionAuthority("session_reconcile_decision",{reason:"gateway_not_connected",runtimeSessionKeyHash:this.sessionKeyHash(e)}),new RuntimeCommandError("GATEWAY_NOT_CONNECTED","Gateway not connected for session reconciliation");const i=await s.sessionsList();await this.assertSessionReconcileFence(t);const n=!e.startsWith("agent:"),r=[...openClawSessionKeysFromList(i)].filter(t=>t===e?!n:openClawKeyMatchesConversation(t,e));if(this.logSessionAuthority("session_reconcile_decision",{reason:r.length?"exact_candidates":"no_exact_candidate",runtimeSessionKeyHash:this.sessionKeyHash(e),candidateHashes:r.map(e=>this.sessionKeyHash(e))}),!r.length)return;const o=new Set(r),a=this.mergeGatewaySessions(i,e=>o.has(e));this.logSessionAuthority("session_reconcile_decision",{reason:"reconciled_exact_candidates",runtimeSessionKeyHash:this.sessionKeyHash(e),loaded:a,candidateHashes:r.map(e=>this.sessionKeyHash(e))})}async materializeMissingModelSessionKey(e,t){await this.assertSessionReconcileFence(t);const s=t.attempt,i=s.verifiedMessageGrant?.claims,n=i?.command;if("service"!==s.origin||!i||"conversation"!==i.scope||"session/set_model"!==i.method||"session.setModel"!==n?.name||"conversation"!==n.context.scope||i.runtimeSessionKey!==e||i.runtimeConversationUid!==e||n.context.conversation.runtimeSessionKey!==e||n.context.conversation.runtimeConversationUid!==i.runtimeConversationUid)throw this.logSessionAuthority("model_intent_materialization_rejected",{reason:"verified_service_target_required",runtimeSessionKeyHash:this.sessionKeyHash(e)}),new RuntimeCommandError("INVALID_PARAMS","model-intent session materialization requires an exact verified Service target");if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e))throw new RuntimeCommandError("INVALID_PARAMS","model-intent session materialization requires a canonical conversation UUID");let r;try{if(!this.runtimeAgentIdentities.resolveActiveLocalKey)throw new Error("identity resolver unavailable");r=await this.runtimeAgentIdentities.resolveActiveLocalKey(i.runtimeAgentUid)}catch{throw new RuntimeCommandError("INVALID_PARAMS","verified model-intent runtime agent is not active")}if(this.resolveLocalAgentId(i.platformAgentId)!==r)throw new RuntimeCommandError("INVALID_PARAMS","verified model-intent agent does not match the active platform projection");const o=`agent:${r}:beeos-conversation:ctx-${e}`,a=this.getGateway();if(!a?.isConnected)throw new RuntimeCommandError("GATEWAY_NOT_CONNECTED","Gateway not connected for model-intent session materialization");const l=await a.sessionsList();await this.assertSessionReconcileFence(t);const c=[...openClawSessionKeysFromList(l)].filter(t=>openClawKeyMatchesConversation(t,e));if(c.length){if(1===c.length&&c[0]===o)return this.mergeGatewaySessions(l,e=>e===o),o;throw new RuntimeCommandError("INVALID_PARAMS","verified model-intent target conflicts with an existing OpenClaw session")}return this.logSessionAuthority("model_intent_materialization_allowed",{runtimeSessionKeyHash:this.sessionKeyHash(e),openClawSessionKeyHash:this.sessionKeyHash(o)}),o}registerMaterializedModelSession(e){this.state.findSessionByKey(e)||(this.registerSession(createSessionObject({gatewayKey:e,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels}),{ensureVerbose:!1}),this.logSessionAuthority("model_intent_materialization_committed",{openClawSessionKeyHash:this.sessionKeyHash(e)}))}async assertSessionReconcileFence(e){if(e.lease.operationId!==e.attempt.operationId||e.lease.runtimeEpoch!==e.attempt.runtimeEpoch||e.attempt.abortSignal?.aborted)throw this.logSessionAuthority("session_reconcile_decision",{reason:"operation_fence_mismatch"}),new RuntimeCommandError("INVALID_PARAMS","session reconciliation is fenced");try{await this.runtimeLeases.renew(e.lease)}catch{throw this.logSessionAuthority("session_reconcile_decision",{reason:"lease_epoch_mismatch"}),new RuntimeCommandError("INVALID_PARAMS","session reconciliation is fenced")}if(e.attempt.abortSignal?.aborted)throw this.logSessionAuthority("session_reconcile_decision",{reason:"operation_aborted"}),new RuntimeCommandError("INVALID_PARAMS","session reconciliation is fenced")}sessionKeyHash(e){return createHash("sha256").update(e).digest("hex").slice(0,16)}logSessionAuthority(e,t){this.logger.info?.(`[bridge-core] ${JSON.stringify({event:e,...t})}`)}async handleRequest(e){this.writeObs({component:"bridge-core",domain:"forward",name:`rpc.request.${e.method}`,severity:"debug",payload:{id:e.id,method:e.method}});const t=e;try{switch(t.method){case"initialize":await this.handleInitialize(t);break;case"ping":this.transport.sendResult(t.id,{pong:!0});break;case"session/new":await this.handleSessionNew(t);break;case"session/load":await this.handleSessionLoad(t);break;case"session/list":await this.handleSessionList(t);break;case"session/rename":await this.handleSessionRename(t);break;case"session/delete":await this.handleSessionDelete(t);break;case"session/clear":await this.handleSessionClear(t);break;case"session/prompt":await this.handleSessionPrompt(t);break;case"session/set_mode":await this.handleSessionSetMode(t);break;case"session/set_model":await this.handleSessionSetModel(t);break;case"agent/create":await this.handleAgentCreate(t);break;case"agent/update":await this.handleAgentUpdate(t);break;case"agent/delete":await this.handleAgentDelete(t);break;case"agent/applyTemplate":await this.handleApplyTemplate(t);break;case"skills/list":await this.handleSkillsList(t);break;case"skills/install":await this.handleSkillsInstall(t);break;case"skills/uninstall":await this.handleSkillsUninstall(t);break;case"skills/update":await this.handleSkillsUpdate(t);break;case"models/list":await this.handleModelsList(t);break;case"session/cancel":await this.handleSessionCancel(t.id,t.params);break;case"cron/list":case"cron/status":case"cron/add":case"cron/update":case"cron/remove":case"cron/run":case"cron/runs":await this.handleCronRequest(t);break;default:"agent/list"===e.method?await this.handleAgentList(e):"_beeos/session/history"===e.method?await this.handleSessionHistoryPage(e):"mcp/list"===e.method?await this.handleMcpList(e):"mcp/set"===e.method?await this.handleMcpSet(e):"mcp/unset"===e.method?await this.handleMcpUnset(e):e.method.startsWith("terminal/")&&this.handleTerminalRequest?await this.handleTerminalRequest(e):this.transport.sendAcpError(e.id,Errors.MethodNotFound,{message:`Method not found: ${e.method}`})}}catch(t){this.transport.sendAcpError(e.id,Errors.InternalError,{message:t instanceof Error?t.message:"Internal error"})}}handleCanvasNotification=null;getCanvasState=null;onSessionLoaded=null;onSkillInstalled=null;onSessionDeleted=null;onSessionCleared=null;handleNotification(e){switch(e.method){case"session/cancel":this.observeLifecycle(this.handleSessionCancel(void 0,e.params),"session_cancel_notification");break;case"canvas/toggle":case"canvas/clear":case"canvas/reference":case"canvas/dimensions":this.observeLifecycle(this.dispatchLegacyCanvasNotification(e.method,e.params),`canvas_notification_${e.method.replace("/","_")}`);break;default:e.method.startsWith("terminal/")&&this.handleTerminalNotification?this.handleTerminalNotification(e.method,e.params):this.logger.debug?.(`[bridge-core] Unknown notification: ${e.method}`)}}async handleInitialize(e){await this.cronReady,this.initialized=!0;const t=this.transport.forwardControl;!1===e.params?.forwardThinking&&(t.forwardThinking=!1),!1===e.params?.forwardToolCalls&&(t.forwardToolCalls=!1),this.transport.sendResult(e.id,{protocolVersion:ACP_PROTOCOL_VERSION,agentCapabilities:{loadSession:!0,skills:!0,multipleSessions:!0,sessionCapabilities:{"web-ssh":!!this.config.bridge.shell.enabled,canvas:!!this.config.canvasEnabled},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcp:{}},agentInfo:{name:"beeos-claw",title:"BeeOS Agent Bridge",version:"0.1.0"},_meta:{},authMethods:[]})}async createRuntimeSession(e,t){const s=e.operationId.trim(),i=e.platformAgentId.trim();if(!s)throw new Error("session/new operationId is required");if(assertTrustedCoreExecutionAttempt(t,{operationId:s,runtimeEpoch:t.runtimeEpoch}),"service"!==t.origin)throw new Error("session/new runtime allocation requires Service authority");const n=this.resolveLocalAgentId(i);if(!i||!n)throw new RuntimeSessionNewRejectedError("session/new target agent is unknown");const r=`agent:${n}:service:${s}`;return{sessionId:this.allocateSession({agentId:n,gatewaySessionKey:r,cwd:e.cwd??".",...void 0===e.title?{}:{title:e.title}}).sessionId,gatewaySessionKey:r,agentId:n,platformAgentId:i}}async handleSessionNew(e){const t="string"==typeof e.params?.agentId&&e.params.agentId||this.config.gateway.agentId||this.getDefaultAgentId(),s=`agent:${t}:${randomUUID()}`,i="string"==typeof e.params?.cwd?e.params.cwd:".",n=this.allocateSession({agentId:t,gatewaySessionKey:s,cwd:i});this.transport.sendResult(e.id,{sessionId:n.sessionId,modes:{availableModes:[{...DEFAULT_MODE}],currentModeId:DEFAULT_MODE.id},_meta:{sessionKey:s,agentId:n.agentId,platformAgentId:n.platformAgentId??null}}),this.fetchHistoryInBackground(s)}allocateSession(e){const t=this.state.findSessionByKey(e.gatewaySessionKey);if(t)return t;const s=createSessionObject({gatewayKey:e.gatewaySessionKey,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,...void 0===e.cwd?{}:{cwd:e.cwd},...void 0===e.title?{}:{title:e.title}});if(s.agentId!==e.agentId)throw new Error("session/new gateway key agent mismatch");return this.registerSession(s,{ensureVerbose:!1}),s}fetchHistoryInBackground(e){const t=this.getGateway();t?.isConnected&&loadHistory(t,e,50).catch(e=>{this.logger.debug?.(`[bridge-core] Background history fetch failed: ${e instanceof Error?e.message:e}`)})}async subscribeSessionMessages(e){if(e.messageSubscriptionActive)return;const t=this.getGateway();if(t?.isConnected)try{await t.sessionsMessagesSubscribe(e.gatewaySessionKey),e.messageSubscriptionActive=!0,this.logger.debug?.(`[bridge-core] session.message subscribed sessionKey=${e.gatewaySessionKey}`)}catch(t){this.logger.debug?.(`[bridge-core] session.message subscribe failed key=${e.gatewaySessionKey}: ${t instanceof Error?t.message:t}`)}}async resubscribeAllSessionMessages(){for(const e of this.state.sessions.values())e.messageSubscriptionActive=!1,await this.subscribeSessionMessages(e)}handleSessionMessage(e){const t=e?.sessionKey,s=e?.messageId;if(!t||!s)return;const i=this.state.sessionsByGatewayKey.get(t);if(!i)return;const n=e.message?.role;if("toolResult"===n||"tool"===n)return void this.handlePersistedToolResultMessage(i,e).catch(e=>{this.logger.warn?.(`[bridge-core] persisted toolResult handling failed sessionKey=${t} messageId=${s}: ${e instanceof Error?e.message:String(e)}`)});const r="user"===n?"user":"system"===n?"system":"assistant",o=i.lastTurnIdByRole?.[r];if(!o)return void this.logger.debug?.(`[bridge-core] session.message skipped: no lastTurnId role=${r} sessionKey=${t} messageId=${s}`);const a=e.message?.timestamp,l="number"==typeof a&&a>0?new Date(a).toISOString():void 0,c={turnId:o};"number"==typeof e.messageSeq&&(c.seq=e.messageSeq),this.transport.sendSessionUpdate(i.sessionId,{sessionUpdate:"message_id_bind",role:r,messageId:s,...l?{timestamp:l}:{}},c),i.lastTurnIdByRole&&(i.lastTurnIdByRole[r]=void 0),"assistant"===r&&reconcileMissingArtifacts({localHistory:this.localSessionHistory,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,getCanvasState:()=>this.getCanvasState?.()??null,isSessionAlive:e=>this.state.sessions.has(e)},{session:i,turnId:o,messageId:s,runId:void 0})}async handlePersistedToolResultMessage(e,t){const s=t.messageId;if(!s)return;const i=extractPersistedToolResultEnvelope(t.message),n=this.extractPersistedToolResultFromHistory(e,s),r=mergePersistedToolResultEnvelopes(n,i);if(!r?.toolCallId)return void this.writeObs({component:"bridge-core",domain:"tool_result",name:"tool_result.skipped_no_tool_call_id",severity:"warn",payload:{sessionId:e.sessionId,messageId:s}});n&&this.writeObs({component:"bridge-core",domain:"tool_result",name:"tool_result.hydrated_from_history",severity:"debug",payload:{sessionId:e.sessionId,messageId:s,toolCallId:r.toolCallId,toolName:r.toolName}});const o=e.toolCallTurns?.get(r.toolCallId),a=o?.turnId??resolveTurnId(e);if(!a)return void this.writeObs({component:"bridge-core",domain:"tool_result",name:"tool_result.skipped_no_turn",severity:"warn",payload:{sessionId:e.sessionId,messageId:t.messageId,toolCallId:r.toolCallId,toolName:r.toolName}});const l=projectPersistedToolResultForReplay({toolCallId:r.toolCallId,toolName:r.toolName||o?.toolName||"tool",...r.rawText?{rawText:r.rawText}:{},...r.rawResult?{rawResult:r.rawResult}:{},...r.timestamp?{timestamp:r.timestamp}:{}});await emitToolResultProjectionForTurn({session:e,projection:l,toolCallId:r.toolCallId,turnId:a,config:this.config,logger:this.logger,writeObs:this.writeObs,getCanvasState:()=>this.getCanvasState?.()??null,sendUpdate:s=>(a&&void 0===s._turnId&&(s._turnId=a),this.transport.sendSessionUpdate(e.sessionId,s,{turnId:a,..."number"==typeof t.messageSeq?{seq:t.messageSeq}:{}}))})}extractPersistedToolResultFromHistory(e,t){if(!e.agentId)return;const s=this.localSessionHistory.readEntries({agentId:e.agentId,sessionKey:e.gatewaySessionKey,sessionId:e.sessionId});return findPersistedToolResultEnvelopeByMessageId(s,t)}async recoverSessionFromGateway(e){const t=this.getGateway();if(t?.isConnected)try{const s=await t.sessionsList();if(!s||"object"!=typeof s)return;const i=s.sessions;if(!Array.isArray(i))return;for(const t of i){const s=t,i=s.sessionKey??s.key??s.id??s.name;if(i&&"string"==typeof i&&deriveSessionId(i,this.instanceId)===e){const e=s.label||s.derivedTitle||s.title||void 0,t=e&&!isPlaceholderTitle(e)?e:void 0,n=createSessionObject({gatewayKey:i,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,title:t});return this.registerSession(n),n}}}catch(e){this.logger.debug?.("[bridge-core] recoverSessionFromGateway failed:",e)}}async resolveOrCreateSession(e){let t=this.state.sessions.get(e);if(!t&&e.startsWith("agent:")&&(t=this.state.findSessionByKey(e)),t||e.startsWith("agent:")||(t=await this.recoverSessionFromGateway(e)),t)return{session:t,created:!1};const s=e.startsWith("agent:"),i=this.config.gateway.agentId||this.getDefaultAgentId();return t=createSessionObject({gatewayKey:s?e:`agent:${i}:${e}`,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels}),this.registerSession(t),{session:t,created:!0}}async handleSessionLoad(e){const t=e.params?.sessionId;if(!t)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const{session:s}=await this.resolveOrCreateSession(t),i=s.sessionId;this.state.lastActiveSessionId=i,s.chatReplayDedupKeys.clear(),s.sessionLoadInProgress=!0;try{const e=await this.emitHistoryTurns(s);this.emitCurrentStreamSnapshot(s,e)}finally{s.sessionLoadInProgress=!1}this.transport.sendResult(e.id,{sessionId:i}),this.onSessionLoaded?.(i,s.gatewaySessionKey,s.platformAgentId),this.pushSkillsList().catch(e=>{this.logger.warn?.(`[bridge-core] pushSkillsList failed: ${e instanceof Error?e.message:e}`)})}async emitHistoryTurns(e){const t=new Set,s=e.sessionId;try{const i=this.getGateway(),n=e.assistantMq&&!e.assistantMq.closed,r=n?null:i,o=await loadHistory(r,e.gatewaySessionKey,100,{localHistory:this.localSessionHistory,agentId:e.agentId,sessionId:e.sessionId,logger:this.logger,emitObs:e=>{this.writeObs({component:"history-replay",domain:"lifecycle",name:e.name,severity:e.severity,payload:e.payload})}}),a=groupIntoTurns(o),l=a.filter(e=>"user"===e.role).length,c=a.filter(e=>"assistant"===e.role).length,d=a.filter(e=>e.toolCalls?.length).length,m=a.reduce((e,t)=>e+(t.toolCalls?.length??0),0);if(this.logger.debug?.(`[bridge-core] handleSessionLoad sid=${s} messages=${o.length} turns=${a.length} userTurns=${l} asstTurns=${c} turnsWithToolCalls=${d} totalToolCalls=${m}`),l>0&&e.pendingUserTurnUpdates&&e.pendingUserTurnUpdates.length>0&&(e.pendingUserTurnUpdates=[]),a.length>0&&isPlaceholderTitle(e.title)&&"manual"!==e.titleSource){const t=a.find(e=>{if("user"!==e.role)return!1;if("internal_system"===e.provenance?.kind)return!1;if(isCronPromptText(e.content))return!1;const t=cleanHistoryUserContent(e.content);return t.length>0&&!/^Sender\s*\(untrusted/i.test(t)});if(t?.content){const i=cleanHistoryUserContent(t.content).slice(0,64).replace(/\n/g," ").trim();if(i){e.title=i,e.titleSource="truncated";const t=this.getGateway();t?.isConnected&&t.sessionsPatch(e.gatewaySessionKey,{label:i}).catch(()=>{}),this.transport.sendSessionUpdate(s,{sessionUpdate:"title_update",title:i}),this.tryGenerateTitleFromHistory(e,s,a)}}}const u=t=>`history:${e.gatewaySessionKey}:${t}`;let p=-1;if(n)for(let e=a.length-1;e>=0;e--)if("assistant"===a[e].role){p=e;break}const{replayedToolCallIds:h,streamCompleteCount:g}=await this.replayHistoryTurnsToSink(e,a,this.transport,{mqActive:Boolean(n),lastAsstIdx:p,turnIdFor:(e,t)=>u(t)});for(const e of h)t.add(e);this.logger.debug?.(`[bridge-core] emitHistoryTurns DONE sid=${s} historyStreamCompleteEmitted=${g} replayedToolCallIds=${t.size}`)}catch(e){this.logger.warn?.("[bridge-core] Failed to load session history:",e)}return t}async replayHistoryTurnsToSink(e,t,s,i){const n=e.sessionId,r=new Set;let o=0;for(let a=0;a<t.length;a++){const l=t[a],c=i.turnIdFor(l,a);if(i.mqActive&&a===i.lastAsstIdx){const e=classifyHistoricalAssistantTurnCompletion(l,{mqActive:i.mqActive,isSkippedForLiveMq:!0});this.logger.debug?.(`[bridge-core] SKIP history_turn[${a}] assistant — ${"live"===e.kind?e.reason:"mq active"}, deferring to emitCurrentStreamSnapshot`);continue}if("user"===l.role&&"internal_system"===l.provenance?.kind){this.logger.debug?.(`[bridge-core] SKIP history_turn[${a}] internal_system user message`);continue}if("user"===l.role&&/^\s*system\s*\(untrusted[^)]*\)/i.test(l.content)){this.logger.debug?.(`[bridge-core] SKIP history_turn[${a}] system-injected user message`);continue}if("user"===l.role&&isHeartbeatPromptText(l.content)){this.logger.info?.(`[bridge-core] SKIP history_turn[${a}] heartbeat cron prompt sessionId=${e.sessionId} contentLen=${l.content.length} preview="${previewSanitizedText(l.content)}"`);continue}if("user"===l.role&&isCronPromptText(l.content)){this.logger.info?.(`[bridge-core] SKIP history_turn[${a}] cron-triggered user message sessionId=${e.sessionId} contentLen=${l.content.length} preview="${previewSanitizedText(l.content)}"`);continue}if("assistant"===l.role){const t=classifyHeartbeatFilter(l.content);if(t.filtered){this.logger.info?.(`[bridge-core] SKIP history_turn[${a}] heartbeat assistant reply reason=${t.reason} sessionId=${e.sessionId} contentLen=${l.content.length} preview="${previewSanitizedText(l.content)}"`);continue}}const d="assistant"===l.role?classifyHistoricalAssistantTurnCompletion(l,{mqActive:i.mqActive,isSkippedForLiveMq:!1}):void 0;if("error"===d?.kind||"interrupted"===d?.kind&&d.failure)s.sendSessionUpdate(n,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:""},...l.timestamp?{timestamp:l.timestamp}:{}},{turnId:c,...void 0!==l._seq?{seq:l._seq}:{}}),s.sendSessionUpdate(n,{sessionUpdate:"stream_complete",stopReason:d.stopReason,error:d.message,errorCode:d.errorCode},{turnId:c}),this.logger.info?.(`[bridge-core] history_runtime_failure_terminalized session_id=${n} turn_id=${c} error_code=${d.errorCode} stop_reason=${d.stopReason} source=history_replay`),o+=1;else if("system"!==l.role)if(this.logger.debug?.(`[bridge-core] SENDING history_turn[${a}] role=${l.role} contentLen=${l.content.length} content=${JSON.stringify(l.content.slice(0,80))} tcCount=${l.toolCalls?.length??0}`),"user"===l.role)this.replayUserTurnAsChunks(s,n,l.content,l.metadata,l.timestamp,c,l._seq);else{if(await this.replayAssistantTurnAsStream(s,n,l,c),l.toolCalls)for(const e of l.toolCalls)e.id&&r.add(e.id);const e=d??classifyHistoricalAssistantTurnCompletion(l,{mqActive:i.mqActive,isSkippedForLiveMq:!1});if("interrupted"===e.kind){const t=new Set(e.incompleteToolCallIds);for(const i of l.toolCalls??[])t.has(i.id)&&s.sendSessionUpdate(n,buildToolCallUpdatePayload({toolCallId:i.id,toolName:i.name,outputText:e.message,kind:i.kind,status:"failed",timestamp:l.timestamp}),{turnId:c});this.logger.info?.(`[bridge-core] history_orphan_turn_terminalized session_id=${n} turn_id=${c} tool_call_ids=${e.incompleteToolCallIds.join(",")} stop_reason=${e.stopReason} source=history_replay`),s.sendSessionUpdate(n,{sessionUpdate:"stream_complete",stopReason:e.stopReason,error:e.message,errorCode:e.errorCode},{turnId:c}),o+=1;continue}if("completed"!==e.kind)continue;s.sendSessionUpdate(n,{sessionUpdate:"stream_complete",stopReason:e.stopReason},{turnId:c}),o+=1}else this.logger.debug?.(`[bridge-core] SENDING system_message[${a}] contentLen=${l.content.length}`),s.sendSessionUpdate(n,{sessionUpdate:"system_message_chunk",content:{type:"text",text:l.content},metadata:l.metadata,...l.timestamp?{timestamp:l.timestamp}:{}},{turnId:c,...void 0!==l._seq?{seq:l._seq}:{}})}return{replayedToolCallIds:r,streamCompleteCount:o}}async handleSessionHistoryPage(e){const t=e.params??{},s="string"==typeof t.sessionId?t.sessionId:"";if(!s)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const i="string"==typeof t.cursor&&t.cursor.length>0?t.cursor:void 0,n="number"==typeof t.limit&&Number.isFinite(t.limit)&&t.limit>0?Math.min(1e3,Math.floor(t.limit)):100,{session:r}=await this.resolveOrCreateSession(s),o=this.getGateway(),a=await loadHistoryPage(o,r.gatewaySessionKey,{...i?{cursor:i}:{},limit:n,logger:this.logger}),l=groupIntoTurns(a.messages),c=new HistoryUpdateRecorder(this.transport);await this.replayHistoryTurnsToSink(r,l,c,{mqActive:!1,lastAsstIdx:-1,turnIdFor:(e,t)=>void 0!==e._seq?`history:${r.gatewaySessionKey}:seq:${e._seq}`:`history:${r.gatewaySessionKey}:seq:none:${i??"head"}:${t}`}),this.logger.debug?.(`[bridge-core] _beeos/session/history sid=${r.sessionId} cursor=${i??"<head>"} limit=${n} turns=${l.length} updates=${c.updates.length} hasMore=${a.hasMore} nextCursor=${a.nextCursor??"<none>"}`),this.transport.sendResult(e.id,{updates:c.updates,...a.nextCursor?{nextCursor:a.nextCursor}:{},hasMore:a.hasMore})}emitCurrentStreamSnapshot(e,t){const s=e.pendingUserTurnUpdates;if(s&&s.length>0)for(const t of s)this.transport.sendSessionUpdate(e.sessionId,t);const i=e.assistantMq;if(i&&!i.closed){const s=i.peek(0);let n=0;if(t&&t.size>0)for(let e=0;e<s.length;e++){const i=s[e],r=i.sessionUpdate,o=i.toolCallId;if("tool_call"!==r&&"tool_call_update"!==r||!o||!t.has(o)){if("agent_message_chunk"===r){if(""===(i.content?.text??"").trim()&&e<s.length-1){const i=s[e+1];if(("tool_call"===i.sessionUpdate||"tool_call_update"===i.sessionUpdate)&&i.toolCallId&&t.has(i.toolCallId)){n=e+1;continue}}break}break}n=e+1}const r=resolveTurnId(e),o=r?{turnId:r}:void 0;for(let t=n;t<s.length;t++)this.transport.sendSessionUpdate(e.sessionId,s[t],o)}}async handleSessionList(e){let t;try{t=parseRuntimeSessionListPage(e.params)}catch(t){return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:t instanceof Error?t.message:"Invalid session/list params"})}const s=[];for(const[,e]of this.state.sessions)isBackgroundSessionKey(e.gatewaySessionKey)||this.cronIsolatedSessionKeys.has(e.gatewaySessionKey)||!t.includeDeleted&&this.state.deletedGatewaySessionKeys.has(e.gatewaySessionKey)||s.push({sessionId:e.sessionId,title:e.title||"New chat",cwd:e.cwd,updatedAt:e.lastStreamActivityTs??e.createdAt,agentId:e.agentId,platformAgentId:e.platformAgentId,deletable:!isSystemDefaultSessionKey(e.gatewaySessionKey)});const i=this.getGateway();if(i?.isConnected)try{const e=await i.sessionsList();if(e&&"object"==typeof e&&Array.isArray(e.sessions)){const i=e.sessions;for(const e of i){const i=e,n=i.sessionKey??i.key??i.id??i.name;if(!n||"string"!=typeof n)continue;if(isBackgroundSessionKey(n))continue;if(this.cronIsolatedSessionKeys.has(n))continue;const r=deriveSessionId(n,this.instanceId),o=s.find(e=>e.sessionId===n||e.sessionId===r||this.state.sessions.get(e.sessionId)?.gatewaySessionKey===n);if(!0===i.deleted){if(this.state.deletedGatewaySessionKeys.add(n),!t.includeDeleted)continue}else this.state.deletedGatewaySessionKeys.delete(n);const a=i.label||cleanGatewayDerivedTitle(i.derivedTitle)||i.title||void 0,l=a&&!isPlaceholderTitle(a)?a:void 0,c=i.model,d=i.modelProvider;if(o){if(l&&isPlaceholderTitle(o.title)){o.title=l;const e=this.state.sessions.get(o.sessionId);e&&isPlaceholderTitle(e.title)&&(e.title=l)}const e=i.updatedAt;e&&(o.updatedAt=e),c&&(o.model=c),d&&(o.modelProvider=d)}else{const e=createSessionObject({gatewayKey:n,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,cwd:i.cwd,title:l});this.registerSession(e,{ensureVerbose:!1}),s.push({sessionId:e.sessionId,title:l||"",cwd:i.cwd,updatedAt:i.updatedAt,agentId:e.agentId,platformAgentId:e.platformAgentId,deletable:!isSystemDefaultSessionKey(n),model:c,modelProvider:d})}}}}catch(e){this.logger.debug?.("[bridge-core] sessions.list enrichment failed:",e)}const n=t.includeDeleted?s:s.filter(e=>{const t=this.state.sessions.get(e.sessionId)?.gatewaySessionKey;return!t||!this.state.deletedGatewaySessionKeys.has(t)});n.sort((e,t)=>(t.updatedAt??0)-(e.updatedAt??0)||e.sessionId.localeCompare(t.sessionId)),this.transport.sendResult(e.id,{sessions:pageRuntimeSessions(n,t)})}async handleSessionRename(e){const t=e.params?.sessionId,s=e.params?.title;if(!t||!s)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId, title"});const i=s.slice(0,64),n=this.state.sessions.get(t);if(n)try{const s=await this.dispatchLegacyConversationCapability("session.rename",n,{title:i});n.title=s.title,n.titleSource="manual",this.transport.sendResult(e.id,{sessionId:t,title:s.title})}catch(s){this.logger.warn?.(`[bridge-core] ACP rename projection deferred: ${s instanceof Error?s.message:String(s)}`),n.title=i,n.titleSource="manual",this.transport.sendResult(e.id,{sessionId:t,title:i})}else this.transport.sendAcpError(e.id,Errors.SessionNotFound)}static TITLE_TEMPLATES=[{match:["今日日报","日报"],zh:"今日工作日报",en:"Daily Work Log"},{match:["周报","周报总结","本周周报"],zh:"本周工作周报",en:"Weekly Work Report"},{match:["月报","月度汇报","月度总结"],zh:"本月工作月报",en:"Monthly Work Report"},{match:["工作日志","日志"],zh:"工作日志整理",en:"Work Log Review"},{match:["晨会","今日晨会"],zh:"今日晨会纪要",en:"Daily Standup Notes"},{match:["复盘","今日复盘"],zh:"今日工作复盘",en:"Daily Retrospective"}];static TITLE_SYSTEM_PROMPT='You are a conversation title generator. Your task is to generate a concise, human-readable title summarizing the topic of the user\'s question together with the assistant\'s answer.\n\n### Rules:\n- Length: 3-6 words in English, or 6-20 characters in Chinese/Japanese/Korean (up to 24 if needed to keep all key domain terms intact).\n- Language: Match the user\'s input language exactly. Mixed zh/en input → use the dominant language. Do NOT switch languages. (IM path injects Client UI locale via conversation-title.ts — keep ACP in sync with that module when changing examples.)\n- Extract the core topic (noun-centric) of the Q&A exchange, not the action verb.\n- Use the assistant\'s answer to disambiguate or enrich the topic when the question alone is vague (e.g. "帮我看下" + an answer about x402 → "x402 支付集成").\n- No punctuation, no quotation marks, no emojis, no markdown.\n- No prefix like "Title:" or "Here is". Output the title only.\n- Avoid generic words: "help", "question", "chat", "problem", "task".\n- Greetings and self-introductions ARE concrete topics (e.g. "自我介绍", "自己紹介", "Self Introduction") — never treat them as vague.\n- NEVER return placeholder / empty-chat titles such as "新会话", "新對話", "New chat", "New Conversation", "新しいチャット", "새 채팅", "แชตใหม่". Always invent a concrete noun-centric topic from whatever words are present.\n\n### Input Format:\nThe user message will contain both the question and the assistant\'s answer, delimited like this:\n[User Question]\n...question text...\n\n[Assistant Answer]\n...answer text (may be truncated with "..." in the middle)...\n\n### Output Format:\nRespond ONLY with valid JSON, no other text:\n{"title": "<your title here>"}\n\n### Examples:\nInput:\n[User Question]\n帮我写一个关于BeeOS设备接入的PRD\n\n[Assistant Answer]\n好的,这是 BeeOS 设备接入 PRD 的草稿:1. 目标 ...\nOutput: {"title": "BeeOS 设备接入 PRD"}\n\nInput:\n[User Question]\n帮我看下\n\n[Assistant Answer]\n你说的 x402 支付协议是一个基于 HTTP 402 的链上支付标准 ...\nOutput: {"title": "x402 支付协议解析"}\n\nInput:\n[User Question]\nWhat\'s the best way to integrate x402 payment protocol?\n\n[Assistant Answer]\nYou have three options: 1. Use the official SDK ...\nOutput: {"title": "x402 Payment Integration"}\n\nInput:\n[User Question]\n用一句话介绍一下你自己。\n\n[Assistant Answer]\n我是 BeeOS 智能助手,可以帮助你完成设备控制与任务协作。\nOutput: {"title": "自我介绍"}\n\nInput:\n[User Question]\nhi\n\n[Assistant Answer]\nHello! How can I help you today?\nOutput: {"title": "Greeting"}';matchTitleTemplate(e){const t=e.trim().toLowerCase();for(const s of AcpGatewayBridgeCore.TITLE_TEMPLATES)if(s.match.some(e=>e.toLowerCase()===t))return/[\u4e00-\u9fff]/.test(e)?s.zh:s.en}isGuardMessage(e){const t=e.trim();return[...t].length<3||[...t].every(e=>/[\p{P}\p{S}\s]/u.test(e))}truncateQuestionForTitle(e){return e.length>2e3?e.slice(0,1500):e}truncateAnswerForTitle(e){return e.length<=1e3?e:`${e.slice(0,500)}\n...\n${e.slice(-500)}`}generateTitleFromQA(e,t,s,i){if(this.isGuardMessage(s))return void this.logger.info?.(`[bridge-core] title-gen SKIP guard message sid=${t}`);const n=this.matchTitleTemplate(s);if(n){e.title=n,e.titleSource="template";const s=this.getGateway();return s?.isConnected&&s.sessionsPatch(e.gatewaySessionKey,{label:n}).catch(()=>{}),void this.transport.sendSessionUpdate(t,{sessionUpdate:"title_update",title:n})}const r=(process.env.AROUTER_BASE_URL||"").replace(/\/$/,""),o=process.env.AROUTER_API_KEY||"";if(!r||!o)return void this.logger.info?.(`[bridge-core] title-gen SKIP sid=${t}: no AROUTER env vars`);const a=`[User Question]\n${this.truncateQuestionForTitle(s)}\n\n[Assistant Answer]\n${this.truncateAnswerForTitle(i)}`;this.logger.info?.(`[bridge-core] title-gen CALLING LLM sid=${t} q="${s.slice(0,60)}" aLen=${i.length}`),fetch(`${r}/v1/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({model:"openai/gpt-4o-mini",max_tokens:32,temperature:.3,messages:[{role:"system",content:AcpGatewayBridgeCore.TITLE_SYSTEM_PROMPT},{role:"user",content:a}]})}).then(async s=>{if(!s.ok){const e=await s.text().catch(()=>"");return void this.logger.info?.(`[bridge-core] title-gen FAILED sid=${t} status=${s.status} body=${e.slice(0,300)}`)}const i=await s.json(),n=i.choices?.[0]?.message?.content?.trim();if(!n)return;const r=n.replace(/^```json\s*/,"").replace(/```$/,"").trim();let o;try{o=JSON.parse(r).title?.trim()??""}catch{return void this.logger.debug?.(`[bridge-core] title-gen JSON parse failed: ${r}`)}if(!o)return;if(isPlaceholderTitle(o))return void this.logger.debug?.("[bridge-core] title-gen discarded: placeholder LLM title");if("manual"===e.titleSource)return void this.logger.debug?.("[bridge-core] title-gen discarded: user already renamed");this.logger.info?.(`[bridge-core] title-gen OK sid=${t} title="${o}"`),e.title=o,e.titleSource="auto";const a=this.getGateway();a?.isConnected&&a.sessionsPatch(e.gatewaySessionKey,{label:o}).catch(()=>{}),this.transport.sendSessionUpdate(t,{sessionUpdate:"title_update",title:o})}).catch(e=>{this.logger.info?.(`[bridge-core] title-gen ERROR sid=${t}: ${e instanceof Error?e.message:e}`)})}async tryGenerateTitleFromHistory(e,t,s){if("manual"===e.titleSource||"auto"===e.titleSource)return;const i=this.getGateway();if(!i?.isConnected)return;let n=s;if(!n)try{const t=await loadHistory(i,e.gatewaySessionKey);n=groupIntoTurns(t)}catch(e){return void this.logger.debug?.(`[bridge-core] title-gen loadHistory failed sid=${t}: ${e instanceof Error?e.message:e}`)}const r=n.find(e=>{if("user"!==e.role)return!1;if(!e.content?.trim())return!1;if("internal_system"===e.provenance?.kind)return!1;if(isCronPromptText(e.content))return!1;const t=cleanHistoryUserContent(e.content);return!!t&&!/^Sender\s*\(untrusted/i.test(t)});if(!r)return;const o=n.indexOf(r),a=n.slice(o+1).find(e=>"assistant"===e.role&&!!e.content?.trim());if(!a)return;const l=cleanHistoryUserContent(r.content),c=a.content.trim();l&&c&&this.generateTitleFromQA(e,t,l,c)}async handleSessionDelete(e){const t=e.params?.sessionId;if(!t)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const s=this.state.sessions.get(t);if(!s)return this.logger.info?.(`[bridge-core] session/delete sessionId=${t} NOT FOUND in local state`),void this.transport.sendAcpError(e.id,Errors.SessionNotFound);const i=s.gatewaySessionKey,n=this.sessionMutationCoordinator.tryStartExclusive({sessionKey:i,label:"session_delete"},"acp");if(!n.ok)return void this.sendSessionBusy(s,e.id,"active_session_mutation",n.queueDepth);const r=n.token;try{if(this.hasActiveRun(s)){const t=this.sessionMutationCoordinator.gateSnapshot(i);return void this.sendSessionBusy(s,e.id,"active_session_mutation",t.queueDepth)}this.logger.info?.(`[bridge-core] session/delete sessionId=${t} gatewayKey=${i} gwConnected=${!!this.getGateway()?.isConnected}`);let n=!1;const r=this.getGateway();if(r?.isConnected&&i)try{await r.sessionsDelete(i),n=!0,this.logger.info?.(`[bridge-core] Gateway sessions.delete SUCCESS for key=${i}`)}catch(t){const s=t instanceof Error?t.message:String(t);if(this.logger.info?.(`[bridge-core] Gateway sessions.delete FAILED for key=${i}: ${s}`),!s.includes("Cannot delete the main session"))return void this.transport.sendResult(e.id,{deleted:!1});try{await r.sessionsReset(i),n=!0,this.logger.info?.(`[bridge-core] Gateway sessions.reset SUCCESS for key=${i}`)}catch(t){return this.logger.warn?.(`[bridge-core] Gateway sessions.reset also failed for key=${i}: ${t instanceof Error?t.message:t}`),void this.transport.sendResult(e.id,{deleted:!1})}}else i&&this.logger.warn?.(`[bridge-core] Gateway not connected, proceeding with local-only delete for key=${i}`);this.state.clearPromptTimeout(s),this.state.clearStreamIdleTimer(s),s.assistantMq?.close(),s.assistantMq=void 0,s.currentRunId&&this.state.promptsByRunId.delete(s.currentRunId);const o=new Set;for(const[e,s]of this.state.toolCallToSessionMap)s===t&&(this.state.toolCallToSessionMap.delete(e),o.add(e));for(const[e,t]of this.state.toolCallIdMap)o.has(t)&&this.state.toolCallIdMap.delete(e);this.state.sessions.delete(t),this.state.sessionsByGatewayKey.delete(i),this.state.deletedGatewaySessionKeys.add(i),this.transport.resetSessionUpdateCount(t),n&&this.onSessionDeleted?.(i),this.logger.info?.(`[bridge-core] session/delete DONE sessionId=${t} gatewayKey=${i} deleted=true`),this.transport.sendResult(e.id,{deleted:!0})}finally{this.sessionMutationCoordinator.releaseBeforeRuntime(r)}}async handleSessionClear(e){this.logger.info?.(`[bridge-core] handleSessionClear called, params=${JSON.stringify(e.params)}`);const t=e.params?.sessionId;if(!t)return this.logger.warn?.("[bridge-core] session/clear missing sessionId"),void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const s=this.state.sessions.get(t);if(!s)return this.logger.warn?.(`[bridge-core] session/clear sessionId=${t} not found in state`),void this.transport.sendAcpError(e.id,Errors.SessionNotFound);this.logger.info?.(`[bridge-core] session/clear sessionId=${t} gatewayKey=${s.gatewaySessionKey}`);const i=this.getGateway(),n=i?.isConnected;if(!s.promptDone&&(void 0!==s.pendingPromptId||void 0!==s.currentRunId)){this.logger.info?.(`[bridge-core] session/clear: cancelling active run sid=${t} runId=${s.currentRunId}`);const r=s.writeGateToken;let o=!1;if(n&&r){const e=await this.sessionMutationCoordinator.requestCancel(r,i);o="recovery_required"===await this.handleCancellationResult(s,e)}else n&&await i.chatAbort(s.gatewaySessionKey,s.currentRunId);return void this.transport.sendError(e.id,Errors.AgentError.rpcCode,o?SESSION_RECOVERY_REQUIRED_MESSAGE:"Cancellation is still converging",o?{code:SESSION_RECOVERY_REQUIRED_CODE,stopReason:"interrupted"}:{code:"session_cancellation_pending",stopReason:"cancelled"})}try{await this.dispatchLegacyConversationCapability("session.clear",s,{}),this.transport.sendResult(e.id,{cleared:!0}),this.logger.info?.("[bridge-core] session/clear DONE, sent cleared=true")}catch(t){this.sendRuntimeCommandError(e.id,t)}}async handleSessionSetMode(e){const t=e.params?.sessionId,s=e.params?.mode,i=t?this.state.sessions.get(t):void 0;if(t&&s)if(i)try{const t=await this.dispatchLegacyConversationCapability("session.setMode",i,{mode:s});this.transport.sendResult(e.id,t)}catch(t){this.sendRuntimeCommandError(e.id,t)}else this.transport.sendAcpError(e.id,Errors.SessionNotFound);else this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId, mode"})}async handleSessionSetModel(e){const t=e.params,s=null===t||"object"!=typeof t||Array.isArray(t)?void 0:t,i="string"==typeof s?.sessionId?s.sessionId:void 0;if(!i||!s||!Object.prototype.hasOwnProperty.call(s,"model"))return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId, model"});const n=s.model;if(null!==n&&("string"!=typeof n||0===n.length||n.trim()!==n))return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"model must be a non-empty string or null"});const r=i?this.state.sessions.get(i):void 0;if(r)try{const t=await this.dispatchLegacyConversationCapability("session.setModel",r,{modelOverrideId:n});this.transport.sendResult(e.id,{model:t.effectiveModelId,modelProvider:t.modelProvider??null})}catch(t){this.sendRuntimeCommandError(e.id,t)}else this.transport.sendAcpError(e.id,Errors.SessionNotFound)}sendRuntimeCommandError(e,t){if(t instanceof RuntimeCommandError)switch(t.code){case"MISSING_PARAM":return void this.transport.sendAcpError(e,Errors.MissingParam,{...t.param?{param:t.param}:{}});case"INVALID_PARAMS":return void this.transport.sendAcpError(e,Errors.InvalidParams,{message:t.message});case"GATEWAY_NOT_CONNECTED":return void this.transport.sendAcpError(e,Errors.GatewayNotConnected);case"EXECUTION_FAILED":case"AGENT_DEFAULT_MODEL_NOT_CONFIGURED":case"OUTCOME_UNKNOWN":case"INSTANCE_EPOCH_MISMATCH":case"COMMAND_EXPIRED":case"IDEMPOTENCY_CONFLICT":case"UNAUTHORIZED_TARGET":return void this.transport.sendAcpError(e,Errors.InternalError,{message:t.message})}else this.transport.sendAcpError(e,Errors.InternalError,{message:t instanceof Error?t.message:"Internal error"})}createOperationId(){const e=randomUUID();return`${e.slice(0,14)}7${e.slice(15)}`}canonicalContextBase(e,t=this.createOperationId(),s="0"){const i=Date.now(),n=createHash("sha256").update(JSON.stringify(e)).digest("hex");return{operationId:t,runtimeInstanceUid:this.instanceId,dispatchEpoch:s,paramsHash:n,idempotencyKeyHash:createHash("sha256").update(t).digest("hex"),claimDeadline:new Date(i+3e4).toISOString(),executionDeadline:new Date(i+3e5).toISOString()}}acpExecutionAttempt(e){return createAcpCoreExecutionAttempt({operationId:e.context.operationId,runtimeEpoch:e.context.dispatchEpoch,resources:this.runtimeCommandResources,historyBoundary:this.localHistoryBoundary})}instanceCommand(e,t,s){return{name:e,params:t,context:{...this.canonicalContextBase(t,s.operationId,s.runtimeEpoch),scope:"instance"}}}async agentCommand(e,t,s,i){return{name:e,params:s,context:{...this.canonicalContextBase(s,i.operationId,i.runtimeEpoch),scope:"agent",agent:{runtimeLocalKey:t,runtimeAgentUid:await this.runtimeAgentIdentities.resolveOrCreate(t)}}}}async dispatchLegacyAgentCapability(e,t,s){const i=normalizeRuntimeAgentLocalKey(t),n=await this.runtimeLeases.claim(this.createOperationId());let r=!1;try{const t={name:e,params:s,context:{...this.canonicalContextBase(s,n.operationId,n.runtimeEpoch),scope:"agent",agent:{runtimeLocalKey:i,runtimeAgentUid:await this.runtimeAgentIdentities.resolveOrCreate(i)}}},o=this.runtimeCommands.dispatch(t,this.acpExecutionAttempt(t));return r=!0,await o.completion}finally{r||await this.runtimeLeases.release(n)}}async dispatchLegacyInstanceCapability(e,t){const s=await this.runtimeLeases.claim(this.createOperationId());let i=!1;try{const n={name:e,params:t,context:{...this.canonicalContextBase(t,s.operationId,s.runtimeEpoch),scope:"instance"}},r=this.runtimeCommands.dispatch(n,this.acpExecutionAttempt(n));return i=!0,await r.completion}finally{i||await this.runtimeLeases.release(s)}}async handleMcpList(e){const t=await this.dispatchLegacyInstanceCapability("mcp.list",{});this.transport.sendResult(e.id,{servers:Object.fromEntries(t.servers.map(e=>[e.name,{transport:e.transport,...e.url?{url:e.url}:{},...e.command?{command:e.command}:{},...e.args?{args:[...e.args]}:{},...e.cwd?{cwd:e.cwd}:{},...e.connectionTimeoutMs?{connectionTimeoutMs:e.connectionTimeoutMs}:{}}]))})}async handleMcpSet(e){const t=e.params&&"object"==typeof e.params?e.params:{},s="string"==typeof t.name?t.name:"";let i;try{if(requireSecretFreeMcpServerName(s),!t.server||"object"!=typeof t.server||Array.isArray(t.server))throw new Error("mcp/set requires name and server");const e=t.server,n=extractMcpCredentialMaterial(e),r={...e};delete r.headers,delete r.env;const o=e.transport??("string"==typeof e.command?"stdio":"string"==typeof e.url?"streamable-http":void 0),a=normalizeMcpPublicServerConfig({...r,transport:o}),l=createHash("sha256").update(canonicalizeJcs(a)).digest("hex");i={definition:{definitionRef:`acp-mcp:sha256:${l}`,version:"local-v1",sha256:l,...n?{credentialRef:await requireCredentialReferencePort(this.mcpCredentialReferences).put({serverName:s,material:n})}:{}},config:structuredClone(a)}}catch(t){return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:t instanceof Error?t.message:"Invalid MCP server config"})}this.runtimeCommandResources.registerMcpDefinition?.(i.definition,i.config);try{await this.dispatchLegacyInstanceCapability("mcp.set",{name:s,definition:i.definition})}catch(e){if(i.definition.credentialRef){!await this.mcp.removeCredentialIfUnreferenced(i.definition.credentialRef)&&this.mcpCredentialReferences?.owns(i.definition.credentialRef)&&await this.mcpCredentialReferences.remove(i.definition.credentialRef)}throw e}this.transport.sendResult(e.id,{ok:!0,restarting:!1})}async handleMcpUnset(e){const t=e.params&&"object"==typeof e.params?e.params:{};let s;try{s=requireSecretFreeMcpServerName(t.name)}catch{return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"mcp/unset requires name"})}await this.dispatchLegacyInstanceCapability("mcp.unset",{name:s}),this.transport.sendResult(e.id,{ok:!0,restarting:!1})}async dispatchLegacyConversationCapability(e,t,s){const i=await this.runtimeLeases.claim(this.createOperationId());let n=!1;try{const r={name:e,params:s,context:{...this.canonicalContextBase(s,i.operationId,i.runtimeEpoch),scope:"conversation",conversation:{runtimeConversationUid:t.sessionId,runtimeSessionKey:t.gatewaySessionKey}}},o=this.runtimeCommands.dispatch(r,this.acpExecutionAttempt(r));return n=!0,await o.completion}finally{n||await this.runtimeLeases.release(i)}}async dispatchLegacyTerminalCapability(e,t,s,i){const n=await this.runtimeLeases.claim(this.createOperationId());let r=!1;try{const o={name:e,params:i,context:{...this.canonicalContextBase(i,n.operationId,n.runtimeEpoch),scope:"terminal",terminal:{terminalId:t,clientId:s}}},a=this.runtimeCommands.dispatch(o,this.acpExecutionAttempt(o));return r=!0,await a.completion}finally{r||await this.runtimeLeases.release(n)}}async dispatchLegacyCanvasNotification(e,t){const s=t&&"object"==typeof t?t:{},i=e.replace("/","."),n="canvas.toggle"===i?{visible:!0===s.visible||!0===s.enabled}:"canvas.reference"===i?{surfaceId:"string"==typeof s.surfaceId?s.surfaceId:""}:"canvas.dimensions"===i?{width:Number(s.width),height:Number(s.height),..."number"==typeof s.devicePixelRatio?{devicePixelRatio:s.devicePixelRatio}:{}}:{},r="string"==typeof s.sessionId?s.sessionId:"acp",o="string"==typeof s.canvasId?s.canvasId:r,a=await this.runtimeLeases.claim(this.createOperationId());let l=!1;try{const e={name:i,params:n,context:{...this.canonicalContextBase(n,a.operationId,a.runtimeEpoch),scope:"canvas",canvas:{canvasId:o,sessionId:r}}},t=this.runtimeCommands.dispatch(e,this.acpExecutionAttempt(e));l=!0,await t.completion}finally{l||await this.runtimeLeases.release(a)}}async applyCanonicalCanvasControl(e,t){if("canvas/reference"===e){const e=this.state.resolveSessionFromParams(t);if(!e)throw new RuntimeCommandError("INVALID_PARAMS","canvas session not found");const s="string"==typeof t.surfaceId?t.surfaceId:void 0;return void(e.referencedSurfaceId=s||void 0)}if(!this.handleCanvasNotification)throw new RuntimeCommandError("INVALID_PARAMS","canvas control delegate is not configured");await this.handleCanvasNotification(e,t)}async dispatchLegacyCronCapability(e,t){const s=normalizeRuntimeAgentLocalKey(this.config.gateway.agentId),i=await this.runtimeLeases.claim(this.createOperationId());let n=!1;try{const r="cron.add"===e?{...t,runtimeCronJobUid:`runtime-cron:${i.operationId}`}:"cron.run"===e?{...t,runToken:`runtime-run:${i.operationId}`}:t,o={name:e,params:r,context:{...this.canonicalContextBase(r,i.operationId,i.runtimeEpoch),scope:"agent",agent:{runtimeLocalKey:s,runtimeAgentUid:await this.runtimeAgentIdentities.resolveOrCreate(s)}}},a=this.runtimeCommands.dispatch(o,this.acpExecutionAttempt(o));return n=!0,await a.completion}finally{n||await this.runtimeLeases.release(i)}}validateConnectedGateway(){if(!this.getGateway()?.isConnected)throw new RuntimeCommandError("GATEWAY_NOT_CONNECTED","Gateway not connected")}async finishClaimedLegacyAgentMutation(e,t){let s=!1;try{const e=await t(),i=this.runtimeCommands.dispatch(e,this.acpExecutionAttempt(e));s=!0;const n=await i.completion;return queueMicrotask(()=>{this.observeAgentProjection()}),n}finally{s||await this.runtimeLeases.release(e)}}async observeAgentProjection(){await(async(e,t)=>{if(!t)return;let s;try{await Promise.race([Promise.resolve().then(t),new Promise((t,i)=>{s=setTimeout(()=>i(new Error(`${e} timed out`)),this.projectionObservationTimeoutMs)})])}catch(t){this.logger.warn?.(`[acp] ${e} failed: ${t instanceof Error?t.message:String(t)}`)}finally{s&&clearTimeout(s)}})("agent projection sync",this.triggerAgentSync)}async handleAgentCreate(e){try{const t=e.params?.name?.trim()??"";if(!t)throw new RuntimeCommandError("INVALID_PARAMS","Missing agent name");this.validateConnectedGateway();const s=this.createOperationId(),i=await this.runtimeLeases.claim(s),n=await this.finishClaimedLegacyAgentMutation(i,async()=>{const s=await this.runtimeAgentIdentities.allocateCreate(i,"agent.create"),n=Object.entries(e.params?.files??{}).filter(e=>"string"==typeof e[1]).map(([e,t])=>({name:e,contentRef:this.runtimeCommandResources.registerContent(t)}));return this.instanceCommand("agent.create",{runtimeAgentUid:s.runtimeAgentUid,name:t,...e.params?.identity?{identity:e.params.identity}:{},...e.params?.model?{defaultModelId:e.params.model}:{},...n.length?{bootstrapFiles:n}:{}},i)});this.transport.sendResult(e.id,{agentId:n.runtimeLocalKey,platformAgentId:this.resolvePlatformAgentId(n.runtimeLocalKey)??"",workspace:n.workspacePath})}catch(t){this.sendRuntimeCommandError(e.id,t)}}async handleApplyTemplate(e){try{const t=e.params?.name?.trim()??"";if(!t)throw new RuntimeCommandError("INVALID_PARAMS","Missing agent name");const s=e.params?.packageUrl?.trim()??"";if(!s)throw new RuntimeCommandError("MISSING_PARAM","Missing packageUrl","packageUrl");this.validateConnectedGateway();const i=await this.runtimeCommandResources.registerArtifact(s,e.params?.sha256),n=this.createOperationId(),r=await this.runtimeLeases.claim(n),o=await this.finishClaimedLegacyAgentMutation(r,async()=>{const s=await this.runtimeAgentIdentities.allocateCreate(r,"agent.applyTemplate");return this.instanceCommand("agent.applyTemplate",{runtimeAgentUid:s.runtimeAgentUid,name:t,artifact:i,...e.params?.identity?{identity:e.params.identity}:{},...e.params?.model?{defaultModelId:e.params.model}:{}},r)});this.transport.sendResult(e.id,{agentId:o.runtimeLocalKey,platformAgentId:this.resolvePlatformAgentId(o.runtimeLocalKey)??"",workspace:o.workspacePath})}catch(t){this.sendRuntimeCommandError(e.id,t)}}async handleAgentUpdate(e){try{const t=e.params?.agentId?.trim()??"";if(!t)throw new RuntimeCommandError("MISSING_PARAM","Missing agentId","agentId");const s={...void 0!==e.params?.name?{name:e.params.name}:{},...void 0!==e.params?.model?{defaultModelId:e.params.model}:{},...void 0!==e.params?.identity?{identity:e.params.identity}:{}};if(0===Object.keys(s).length)throw new RuntimeCommandError("INVALID_PARAMS","No updatable fields provided (name/model/identity)");this.validateConnectedGateway();const i=await this.runtimeLeases.claim(this.createOperationId()),n=await this.finishClaimedLegacyAgentMutation(i,()=>this.agentCommand("agent.update",t,s,i));this.transport.sendResult(e.id,{agentId:n.runtimeLocalKey})}catch(t){this.sendRuntimeCommandError(e.id,t)}}async handleAgentDelete(e){try{const t=e.params?.agentId?.trim()??"";if(!t)throw new RuntimeCommandError("MISSING_PARAM","Missing agentId","agentId");if("main"===normalizeRuntimeAgentLocalKey(t))throw new RuntimeCommandError("INVALID_PARAMS",'"main" cannot be deleted; delete the instance instead');this.validateConnectedGateway();const s=await this.runtimeLeases.claim(this.createOperationId()),i=await this.finishClaimedLegacyAgentMutation(s,()=>this.agentCommand("agent.delete",t,void 0===e.params?.deleteFiles?{}:{deleteFiles:e.params.deleteFiles},s));this.transport.sendResult(e.id,{agentId:i.runtimeLocalKey,...void 0===i.removedBindings?{}:{removedBindings:i.removedBindings}})}catch(t){this.sendRuntimeCommandError(e.id,t)}}async handleAgentList(e){try{const t=await this.dispatchLegacyInstanceCapability("agent.listProjection",{}),s=t.agents.map(e=>({agentId:e.runtimeLocalKey,name:e.name,...e.emoji?{emoji:e.emoji}:{},...e.avatarUrl?{avatarUrl:e.avatarUrl}:{}})),i={...t.defaultRuntimeLocalKey?{defaultId:t.defaultRuntimeLocalKey}:{},agents:s};this.transport.sendResult(e.id,i)}catch(t){this.sendRuntimeCommandError(e.id,t)}}async handleModelsList(e){try{this.transport.sendResult(e.id,await this.dispatchLegacyInstanceCapability("models.list",{}))}catch(t){this.sendRuntimeCommandError(e.id,t)}}async handleSkillsList(e){try{const t=await this.dispatchLegacyAgentCapability("skills.list",e.params?.agentId,{});this.transport.sendResult(e.id,{skills:t.skills.map(e=>({name:e.name,description:e.description??"",...e.emoji?{emoji:e.emoji}:{},...e.always?{always:!0}:{},...e.bundled?{bundled:!0}:{},...e.enabled?{}:{disabled:!0},skillKey:e.skillKey,...e.iconUrl?{iconUrl:e.iconUrl}:{}}))})}catch(t){this.sendRuntimeCommandError(e.id,t)}}async fetchSimplifiedSkills(e){const t=this.getGateway();if(!t?.isConnected)return[];try{const s=await t.skillsStatus(e);if(!s?.skills)return[];const i=s.skills.filter(e=>!1!==e.eligible||!0===e.disabled).sort((e,t)=>e.always&&!t.always?-1:!e.always&&t.always?1:e.name.localeCompare(t.name)).map(e=>({name:e.name,description:e.description,emoji:e.emoji,always:e.always||void 0,bundled:e.bundled||void 0,disabled:e.disabled||void 0,skillKey:e.skillKey||void 0,iconUrl:void 0})),n=await this.getSkillsDir(e);for(const e of i){const t=e.skillKey??e.name;try{const s=await readFile(join(n,t,".beeos-meta.json"),"utf8"),i=JSON.parse(s);i?.iconUrl&&(e.iconUrl=i.iconUrl)}catch{}}return i}catch(e){return this.logger.warn?.(`[bridge-core] Failed to fetch skills: ${e instanceof Error?e.message:e}`),[]}}async pushSkillsList(e){const t=await this.fetchSimplifiedSkills(e);this.transport.sendNotification("session/update",{sessionId:"_system",update:{sessionUpdate:"available_commands_update",commands:t}}),this.writeObs({component:"bridge-core",domain:"lifecycle",name:"skills.pushed",severity:"debug",payload:{count:t.length}})}getOpenclawHome(){return process.env.OPENCLAW_HOME||join(homedir(),".openclaw")}async getSkillsDir(e){const t=this.getOpenclawHome();if(!e||"main"===e)return join(t,"skills");const s=await this.resolveAgentWorkspaceDir(e);return join(s??join(t,`workspace-${e}`),"skills")}async resolveAgentWorkspaceDir(e){const t=this.getGateway();if(!t?.isConnected)return null;try{const s=await t.request("agents.list",{}),i=normalizeAgentId(e),n=s?.agents?.find(e=>normalizeAgentId(e.id)===i);return n?.workspace??null}catch(t){return this.logger.warn?.(`[bridge-core] resolveAgentWorkspaceDir("${e}") failed: ${t instanceof Error?t.message:t}`),null}}async handleSkillsInstall(e){const t=e.params,s=t?.zipUrl,i=t?.files,n=t?.agentId;let r;try{r=validateSkillSlug(t?.slug||t?.name||"")}catch{return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Invalid or missing skill slug"})}if(i?.length||s)try{let o;if(s){o=parseSkillZip(await fetchWithRetry(s,{maxRetries:4,logger:this.logger}))}else{if(!i?.length)throw new RuntimeCommandError("INVALID_PARAMS","Missing skill files or zipUrl");o=new Map;for(const e of i){const t=normalizeSkillArtifactPath(e.path),s=await fetchWithRetry(e.downloadUrl,{maxRetries:4,logger:this.logger});o.set(t,new Uint8Array(s))}}if(t?.iconUrl&&o.set(".beeos-meta.json",(new TextEncoder).encode(JSON.stringify({iconUrl:t.iconUrl}))),!this.runtimeCommandResources.registerParsedArtifact)throw new RuntimeCommandError("EXECUTION_FAILED","ACP skill artifact ingress is not configured");const a=this.runtimeCommandResources.registerParsedArtifact({manifest:{slug:r,version:"0.0.0"},workspaceFiles:o});await this.dispatchLegacyAgentCapability("skills.install",n,{artifact:a}),this.transport.sendResult(e.id,{success:!0}),this.onSkillInstalled?.(r,resolveSkillInstallDir(await this.getSkillsDir(n),r)),await this.pushSkillsList(n)}catch(t){this.logger.error?.(`[bridge-core] Failed to install skill "${r}": ${t instanceof Error?t.message:t}`),this.transport.sendAcpError(e.id,Errors.InternalError,{message:`Install failed: ${t instanceof Error?t.message:String(t)}`})}else this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Missing skill files or zipUrl"})}async handleSkillsUninstall(e){const t=e.params,s=t?.agentId;let i;try{i=validateSkillSlug(t?.slug||t?.name||"")}catch{return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Invalid or missing skill name"})}try{await this.dispatchLegacyAgentCapability("skills.uninstall",s,{skillKey:i}),this.transport.sendResult(e.id,{success:!0}),await this.pushSkillsList(s)}catch(t){this.logger.error?.(`[bridge-core] Failed to uninstall skill "${i}": ${t instanceof Error?t.message:t}`),this.transport.sendAcpError(e.id,Errors.InternalError,{message:`Uninstall failed: ${t instanceof Error?t.message:String(t)}`})}}async handleSkillsUpdate(e){const t=e.params,s=t?.skillKey,i=t?.enabled,n=t?.agentId;if(s&&"boolean"==typeof i)try{await this.dispatchLegacyAgentCapability("skills.setEnabled",n,{skillKey:s,enabled:i}),this.logger.info?.(`[bridge-core] Updated skill "${s}" enabled=${i}${n?` for agent "${n}"`:""}`),this.transport.sendResult(e.id,{ok:!0,skillKey:s,enabled:i}),await this.pushSkillsList(n)}catch(t){this.logger.error?.(`[bridge-core] Failed to update skill "${s}": ${t instanceof Error?t.message:t}`),this.transport.sendAcpError(e.id,Errors.InternalError,{message:`Update failed: ${t instanceof Error?t.message:String(t)}`})}else this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Missing skillKey or enabled"})}async handleSessionPrompt(e){const t=e.params?.sessionId,s=e.params?.prompt;if(!t||!s)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId, prompt"});const{session:i,created:n}=await this.resolveOrCreateSession(t);n&&this.onSessionLoaded?.(i.sessionId,i.gatewaySessionKey,i.platformAgentId);const r=i.sessionId;this.state.lastActiveSessionId=r,this.onPromptStart?.();const o=this.getGateway();if(!o?.isConnected)return void this.transport.sendAcpError(e.id,Errors.GatewayNotConnected);if(this.hasActiveRun(i)){const t=this.sessionMutationCoordinator.gateSnapshot(i.gatewaySessionKey);return void this.sendSessionBusy(i,e.id,"active_run",t.queueDepth)}try{await this.ensureVerboseFull(i)}catch(t){return this.releaseSessionWriteGate(i),void this.transport.sendAcpError(e.id,Errors.InternalError,{message:`Failed to prepare agent context: ${t instanceof Error?t.message:String(t)}`})}let a=extractPromptBlocks(sanitizePromptPayload(s));const l=a.filter(e=>"text"===e.type&&"text"in e&&"string"==typeof e.text).map(e=>e.text).join("\n");if(i.fileArtifactDisplayMode=prefersChatFileArtifacts(l)?"chat":"auto",!i.title||isPlaceholderTitle(i.title)){const e=a.find(e=>"text"===e.type&&e.text);if(e&&"text"in e&&e.text){const t=stripTransportMetadata(e.text).trim();if(this.logger.info?.(`[bridge-core] title-gen sid=${r} existing="${i.title}" cleanText="${t.slice(0,80)}" isPlaceholder=${isPlaceholderTitle(t)}`),t&&!isPlaceholderTitle(t)){const e=t.slice(0,64).replace(/\n/g," ").trim();i.title=e,i.titleSource="truncated",o?.isConnected&&e&&o.sessionsPatch(i.gatewaySessionKey,{label:e}).catch(e=>{this.logger.debug?.(`[bridge-core] sessionsPatch (title) failed: ${e instanceof Error?e.message:e}`)}),this.transport.sendSessionUpdate(r,{sessionUpdate:"title_update",title:e})}}}const c=buildResolutionPlan(a);if(c.refs.length>0)try{const e=await resolveResources(c,this.writeObs);a=applyResolutions(a,e)}catch(e){this.logger.warn?.(`[bridge-core] Resource pre-resolution failed: ${e instanceof Error?e.message:e}`)}let d;if(this.beeosFileResolver){const e=this.beeosFileResolver.buildResolutionPlan(a);if(e.refs.length>0)try{d=await this.beeosFileResolver.resolveMetadataForPrompt(e)}catch(e){this.logger.warn?.(`[bridge-core] BeeOS file resolution failed: ${e instanceof Error?e.message:e}`)}}const m=toGatewayPrompt(a,{beeosFileResolutionsByUri:d});if("error"in m)return this.releaseSessionWriteGate(i),void this.transport.sendAcpError(e.id,Errors.PromptConvertFailed,{message:m.error});const{message:u,attachments:p}=m,h=resolveStandaloneSlashCommandName(a,u)??resolveSlashCmd(a,u),g="string"==typeof h;if(h&&this.handleSlashCommand){const t=this;if(await(async()=>{try{return await t.handleSlashCommand(h)}catch(e){return t.logger.warn?.(`[bridge-core] /${h} handler failed: ${e instanceof Error?e.message:e}`),!1}})())return this.emitPromptAsUserSessionUpdates(i,a,resolveTurnId(i)),this.transport.sendSessionUpdate(r,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Loading ${h}...`},timestamp:(new Date).toISOString()},{turnId:resolveTurnId(i)}),this.transport.sendResult(e.id,{stopReason:"end_turn"}),void this.releaseSessionWriteGate(i)}const y="chat.send";let f=g?u:withUserMessagePrefix(u);const w=this.config.canvasEnabled&&!g&&!0===i.canvasActive&&!i.channelType;if(w){const e=i.promptsSinceCanvasInjection??0;!i.canvasPromptInjected||e>=10?(f=`${CANVAS_TERM_MAPPING}\n\n${f}`,i.canvasPromptInjected=!0,i.promptsSinceCanvasInjection=0,this.logger.debug?.("[bridge-core] Canvas term mapping injected (re-inject cycle)")):i.promptsSinceCanvasInjection=e+1}if(w){const e=this.getCanvasState?.();if(e){const t=e.resolveCanvasForSession(i.gatewaySessionKey);f=`${buildActiveSurfacesContext(e,t)??"[Canvas] Canvas panel is available. Use render_ui for structured/visual content."}\n\n${f}`}const t=i.referencedSurfaceId;t&&(f=`${CANVAS_UPDATE_HINT}\n[IMPORTANT: The user selected canvas surface "${t}" for editing. You MUST call render_ui with id="${t}" to UPDATE this existing surface. Do NOT create a new surface with a different id.]\n${f}`,i.referencedSurfaceId=void 0)}if(!g){const t=parseMentionsParam(e.params?.mentions);if(t.length>0){i.activeMentions=t;f=`${buildMentionInstruction(t)}\n${f}`,this.logger.debug?.(`[bridge-core] delegation mention instruction injected for ${t.length} agent(s)`)}else i.activeMentions=void 0}if(g&&this.logger.info?.(`[bridge-core] slash command passthrough sessionId=${r} command=/${h}`),this.hasActiveRun(i)){const t=this.sessionMutationCoordinator.gateSnapshot(i.gatewaySessionKey);return void this.sendSessionBusy(i,e.id,"active_run_after_prepare",t.queueDepth)}const v=this.sessionMutationCoordinator.tryStartInteractive({sessionKey:i.gatewaySessionKey,label:"session/prompt"},"acp");if(!v.ok)return void this.sendSessionBusy(i,e.id,v.reason,v.queueDepth);i.writeGateToken=v.token,this.state.resetForNewRun(i,r,this.transport),i.pendingPromptId=e.id,i.gatewayMethod=y;const I=resolveTurnId(i);this.emitPromptAsUserSessionUpdates(i,a,I),this.transport.sendSessionUpdate(r,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:""},timestamp:(new Date).toISOString()},I?{turnId:I}:void 0);const S=extractCronJobId(u);S&&(i.cronJobId=S),this.schedulePromptTimeout(i);const C=p.length>0?p.map(e=>({type:e.type,content:e.content,...e.mimeType?{mimeType:e.mimeType}:{},...e.fileName?{fileName:e.fileName}:{}})):void 0,R=`req_${randomUUID().replace(/-/g,"")}`,A={sessionKey:i.gatewaySessionKey,message:f,deliver:!1,idempotencyKey:randomUUID()};C?.length&&(A.attachments=C);if(!o.sendFrame({type:"req",id:R,method:y,params:A}))return this.state.clearPromptTimeout(i),i.pendingPromptId=void 0,i.assistantMq?.close(),i.assistantMq=void 0,i.pendingUserTurnUpdates=void 0,this.releaseSessionWriteGate(i),void this.transport.sendAcpError(e.id,Errors.SendFailed,{message:"failed to send prompt to gateway"});i.gatewayRequestId=R,this.state.promptsByGatewayRequestId.set(R,i)}replayUserTurnAsChunks(e,t,s,i,n,r,o){const a=splitUserReplayBlocks(s),l=r||void 0!==o?{...r?{turnId:r}:{},...void 0!==o?{seq:o}:{}}:void 0;for(const s of a){let r;if("text"===s.type){if(!s.text)continue;r={type:"text",text:s.text}}else r="resource_link"===s.type?{type:"resource_link",uri:s.uri??"",...s.fileName?{name:s.fileName}:{},...s.mimeType?{mimeType:s.mimeType}:{}}:{type:s.type,...s.mimeType?{mimeType:s.mimeType}:{},...s.fileName?{fileName:s.fileName}:{}};e.sendSessionUpdate(t,{sessionUpdate:"user_message_chunk",content:r,...i?{metadata:i}:{},...n?{timestamp:n}:{}},l)}}async replayAssistantTurnAsStream(e,t,s,i){const n=e=>{if(i||void 0!==e)return{...i?{turnId:i}:{},...void 0!==e?{seq:e}:{}}},r=new Set,o=(s,i,o)=>{if(!s?.length)return;const a=n(o);for(const n of s)n.uri&&!r.has(n.uri)&&(r.add(n.uri),e.sendSessionUpdate(t,{sessionUpdate:"agent_message_chunk",content:{type:"resource_link",uri:n.uri,name:n.name??"file",...n.mimeType?{mimeType:n.mimeType}:{}},...i?{timestamp:i}:{}},a))},a=n(s._seq);if(!s.sourceMessages?.length){const i={sessionUpdate:"history_turn",role:s.role,content:s.content,reasoning:s.reasoning,toolCalls:s.toolCalls,...s.timestamp?{timestamp:s.timestamp}:{}};return s.metadata&&(i.metadata=s.metadata),e.sendSessionUpdate(t,i,a),void o(s.files,s.timestamp,s._seq)}for(const i of s.sourceMessages){const r=i.updateType??"agent_message_chunk",a=n(i._seq);switch(r){case"agent_message_chunk":e.sendSessionUpdate(t,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:i.content},...i.timestamp?{timestamp:i.timestamp}:{},...i.metadata?{metadata:i.metadata}:{}},a);break;case"agent_thought_chunk":e.sendSessionUpdate(t,{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:i.content},...i.timestamp?{timestamp:i.timestamp}:{}},a);break;case"tool_call":{const n=i.toolCallId??"",r=s.toolCalls?.find(e=>e.id===n),o=i.toolName??"tool",l=i.content??"";let c={};if(l)try{c=JSON.parse(l)}catch{}e.sendSessionUpdate(t,buildToolCallPayload({toolCallId:n,toolName:o,args:c,kind:r?.kind,status:r?.status??"in_progress",timestamp:i.timestamp}),a);break}case"tool_call_update":{const n=i.toolCallId??"",r=s.toolCalls?.find(e=>e.id===n),l=i.toolName??r?.name??"tool",c=i.content??r?.output??"",d=await this.resolveReplayResourceLinks(n,l,i.files);e.sendSessionUpdate(t,buildToolCallUpdatePayload({toolCallId:n,toolName:l,outputText:c,kind:r?.kind,status:r?.status??"completed",resourceLinks:d,timestamp:i.timestamp}),a),o(d,i.timestamp,i._seq);break}}}o(s.files,s.timestamp,s._seq)}async resolveReplayResourceLinks(e,t,s){let i=s?.map(e=>({uri:e.uri,name:e.name??"file",...e.mimeType?{mimeType:e.mimeType}:{}}));if(i?.length)return i;if(i=await readEnrichmentCache(e).catch(()=>{}),i?.length)return i;if("beeos_upload_file"!==t)return;const n=await readUploadToolResult(e).catch(()=>{});if(!n)return;const r=buildToolResultSessionContentBlocks(t,n).filter(e=>"resource_link"===e.content?.type&&e.content.uri).map(e=>({uri:e.content.uri,name:e.content.name??"file",...e.content.mimeType?{mimeType:e.content.mimeType}:{}}));return r.length>0?r:void 0}emitPromptAsUserSessionUpdates(e,t,s){const i=(new Date).toISOString(),n=s?{turnId:s}:void 0;for(const r of t){const t=this.toUserSessionUpdateContent(r);if(!t)continue;const o={sessionUpdate:"user_message_chunk",content:t,timestamp:i};s&&void 0===o._turnId&&(o._turnId=s),this.transport.sendSessionUpdate(e.sessionId,o,n),e.pendingUserTurnUpdates?.push(o)}}toUserSessionUpdateContent(e){if("text"===e.type){if(!e.text)return;return{type:"text",text:e.text}}if("image"===e.type){const t=e.mimeType??e.mime_type??"application/octet-stream",s=e.fileName??e.file_name??e.name;if(!e.data&&!e.uri)return;return{type:"image",...e.data?{data:e.data}:{},...e.uri?{uri:e.uri}:{},...t?{mimeType:t}:{},...s?{fileName:s}:{}}}if("resource_link"===e.type){if(!e.uri)return;return{type:"resource_link",uri:e.uri,...e.title?{title:e.title}:{},...e.name?{name:e.name}:{},...e.mimeType??e.mime_type?{mimeType:e.mimeType??e.mime_type}:{}}}if("file"===e.type){const t=e.mimeType??e.mime_type??"application/octet-stream",s=e.fileName??e.file_name??e.filename??e.name;if(!e.data&&!e.text&&!e.uri)return;return{type:"file",...e.data?{data:e.data}:{},...e.text?{text:e.text}:{},...e.uri?{uri:e.uri}:{},...t?{mimeType:t}:{},...s?{fileName:s}:{}}}if("resource"===e.type){const t=e.resource??{},s=t.uri??e.uri,i=t.mimeType??t.mime_type??e.mimeType??e.mime_type,n=t.text??e.text,r=t.data??e.data,o=t.fileName??t.file_name??t.filename??t.name??e.fileName??e.file_name??e.filename??e.name;if(!s&&!n&&!r)return;return{type:"resource",resource:{...s?{uri:s}:{},...i?{mimeType:i}:{},...n?{text:n}:{},...r?{data:r}:{},...o?{fileName:o}:{}}}}}async handleSessionCancel(e,t){const s=t&&"object"==typeof t&&"sessionId"in t?t.sessionId:void 0;if(!s)return void(void 0!==e&&this.transport.sendAcpError(e,Errors.MissingParam,{param:"sessionId"}));const i=this.state.sessions.get(s);if(!i)return void(void 0!==e&&this.transport.sendAcpError(e,Errors.SessionNotFound));const n=i.activeRunBinding??this.observeActiveRun(i);if(!n){const t=this.sessionMutationCoordinator.snapshot(i.gatewaySessionKey);if("exclusive"===t?.attachmentPolicy&&void 0!==e){const t=this.sessionMutationCoordinator.gateSnapshot(i.gatewaySessionKey);return void this.sendSessionBusy(i,e,"exclusive_session_mutation",t.queueDepth)}return void(void 0!==e&&this.transport.sendResult(e,{}))}const r=await this.runtimeLeases.claim(this.createOperationId());let o=!1;try{const s=t&&"object"==typeof t&&"reason"in t&&"string"==typeof t.reason?t.reason:void 0,i={targetMessageId:n.targetMessageId,...s?{reason:s}:{}},a={name:"session.cancel",params:i,context:{...this.canonicalContextBase(i,r.operationId,r.runtimeEpoch),scope:"conversation",historyGeneration:n.historyGeneration,conversation:{runtimeConversationUid:n.runtimeConversationUid,runtimeSessionKey:n.runtimeSessionKey}}},l=this.runtimeCommands.dispatch(a,this.acpExecutionAttempt(a));o=!0,await l.completion,void 0!==e&&this.transport.sendResult(e,{})}catch(t){void 0!==e&&this.sendRuntimeCommandError(e,t)}finally{o||await this.runtimeLeases.release(r)}}hasActiveRun(e){return!e.promptDone&&(void 0!==e.pendingPromptId||void 0!==e.currentRunId||void 0!==e.gatewayRequestId)}observeLifecycle(e,t,s){observeLifecyclePromise(e,this.logger,{component:"bridge-core",action:t,...s?{sessionId:s.sessionId,gatewaySessionKey:s.gatewaySessionKey}:{}})}async handleCancellationResult(e,t){return t.ok?(this.observeLifecycle(t.terminalObservation.then(t=>{if(!t.ok)return this.publishCancellationRecovery(e)}),"cancel_terminal_observation",e),"accepted"):"recovery"in t?(await this.publishCancellationRecovery(e),"recovery_required"):"terminal_already_observed"}async publishCancellationRecovery(e){await this.endRun(e,{kind:"interrupted",stopReason:"interrupted",message:SESSION_RECOVERY_REQUIRED_MESSAGE,errorCode:SESSION_RECOVERY_REQUIRED_CODE})}releaseSessionWriteGate(e){if(!e.writeGateToken)return;const t=e.writeGateToken;e.writeGateToken=void 0,this.sessionMutationCoordinator.releaseBeforeRuntime(t)}logRuntimeFailure(e,t){this.logger.warn?.(`[bridge-core] runtime_failure_classified session_id=${e.sessionId} gateway_session_key=${e.gatewaySessionKey} run_id=${e.currentRunId??""} gateway_request_id=${e.gatewayRequestId??""} error_code=${t.errorCode} stop_reason=${t.stopReason} source=${t.source} runtime=${t.runtimeKind}`)}sendSessionBusy(e,t,s,i){this.logger.warn?.(`[bridge-core] session_write_gate_busy session_id=${e.sessionId} gateway_session_key=${e.gatewaySessionKey} reason=${s} queue_depth=${i}`),this.transport.sendError(t,Errors.AgentError.rpcCode,"Agent is busy",{code:"session_busy",reason:s,queueDepth:i}),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:"interrupted",error:INTERRUPTED_PUBLIC_MESSAGE,errorCode:"session_busy"},{turnId:`req:${String(t)}`})}async endRun(e,t){if(e.promptDone||e.mutationTerminalCommitting)return this.logger.debug?.(`[bridge-core] endRun skipped (promptDone=true) sessionId=${e.sessionId} outcome=${t.kind}`),!1;if(void 0===e.pendingPromptId&&void 0===e.currentRunId&&void 0===e.gatewayRequestId)return this.logger.debug?.(`[bridge-core] endRun skipped (no pendingPromptId and no currentRunId) sessionId=${e.sessionId} outcome=${t.kind}`),!1;e.mutationTerminalCommitting=!0,this.state.clearPromptTimeout(e),this.state.clearStreamIdleTimer(e);const s=e.writeGateToken,i=e.activeRunBinding;let n,r,o,a,l="timeout"===e.mutationTerminalOverride?{kind:"interrupted",stopReason:"timeout",message:"The agent did not finish before the session timeout.",errorCode:"gateway_timeout"}:t;if(s){const e="complete"===l.kind?"cancelled"===l.stopReason?"cancelled":"completed":"interrupted"===l.kind&&"timeout"===l.stopReason?"timeout":"error",t=await this.sessionMutationCoordinator.converge(s,e);t.ok?n=t.permit:l={kind:"interrupted",stopReason:"interrupted",message:SESSION_RECOVERY_REQUIRED_MESSAGE,errorCode:SESSION_RECOVERY_REQUIRED_CODE}}try{const t=resolveTurnId(e),s=t?{turnId:t}:void 0;e.promptDone=!0;const i=e.currentRunId;if("complete"===l.kind){if(i&&this.onRunComplete){const t=e.agentAssistantTextSoFar??e.chatAssistantTextSoFar??"";this.onRunComplete(i,t,l.stopReason)}void 0!==e.pendingPromptId&&this.transport.sendResult(e.pendingPromptId,{stopReason:l.stopReason}),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:l.stopReason},s),this.tryGenerateTitleFromHistory(e,e.sessionId)}else"interrupted"===l.kind?(i&&this.onRunFailed&&this.onRunFailed(i,l.message),void 0!==e.pendingPromptId&&this.transport.sendError(e.pendingPromptId,Errors.AgentError.rpcCode,l.message,{code:l.errorCode??"interrupted",stopReason:l.stopReason}),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:l.stopReason,error:l.message,...l.errorCode?{errorCode:l.errorCode}:{}},s)):(i&&this.onRunFailed&&this.onRunFailed(i,l.message),void 0!==e.pendingPromptId&&this.transport.sendError(e.pendingPromptId,l.code,l.message),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:"error",error:l.message},s))}catch(e){r=e}try{this.cleanupPrompt(e)}catch(e){o=e}finally{e.writeGateToken=void 0,e.activeRunBinding=void 0,n&&this.sessionMutationCoordinator.release(n)}if(i){const e="complete"===l.kind?"cancelled"===l.stopReason?"cancelled":"completed":"interrupted"===l.kind&&"cancelled"===l.stopReason?"cancelled":"failed";this.activeRuns.markTerminal(i,e)}try{this.onRunEnded?.(e,l)}catch(e){a=e}if(r)throw r;if(o)throw o;if(a)throw a;return!0}schedulePromptTimeout(e){let t;if(this.state.clearPromptTimeout(e),e.cronJobId){if(!this.cronOverrides.isInitialized())return void this.cronReady.then(()=>{!e.cronJobId||void 0===e.pendingPromptId&&void 0===e.currentRunId||this.schedulePromptTimeout(e)}).catch(e=>this.logger.error?.(`[bridge-core] cron overrides readiness failed: ${e instanceof Error?e.message:e}`));const s=this.cronOverrides.get(e.cronJobId)??this.config.cronMaxDurationDefaultMs;t=Math.max(CRON_DURATION_FLOOR_MS,Math.min(this.config.cronMaxDurationCapMs,s))}else t=this.config.promptTimeoutMs??DEFAULT_PROMPT_TIMEOUT_MS;t<=0||(e.promptTimeoutTimer=setTimeout(()=>{if(e.mutationTerminalCommitting)return;if(void 0===e.pendingPromptId&&void 0===e.currentRunId)return;this.logger.warn?.(`[bridge-core] Prompt timed out sessionId=${e.sessionId} after ${t}ms`),e.mutationTerminalOverride="timeout";const s=this.getGateway(),i=e.writeGateToken;s?.isConnected&&i?this.observeLifecycle(this.sessionMutationCoordinator.requestCancel(i,s).then(t=>this.handleCancellationResult(e,t)),"prompt_timeout_cancel",e):s?.isConnected?this.observeLifecycle(s.chatAbort(e.gatewaySessionKey,e.currentRunId).then(()=>this.interruptPrompt(e,classifyAgentRuntimeFailure({raw:`Prompt timed out after ${t}ms`,source:"live_gateway",runtimeKind:"openclaw"}))),"prompt_timeout_unowned_cancel",e):i&&(this.sessionMutationCoordinator.requireRecovery(i,"gateway_disconnected","disconnect"),this.observeLifecycle(this.endRun(e,{kind:"interrupted",stopReason:"interrupted",message:SESSION_RECOVERY_REQUIRED_MESSAGE,errorCode:SESSION_RECOVERY_REQUIRED_CODE}),"prompt_timeout_disconnected",e))},t),"object"==typeof e.promptTimeoutTimer&&"unref"in e.promptTimeoutTimer&&e.promptTimeoutTimer.unref())}adoptBackgroundMutation(e,t){const s=this.sessionMutationCoordinator.attachOrStartExternal({sessionKey:e.gatewaySessionKey,label:"background_run"},"acp",t);return s.ok?("owner"===s.ownership&&(e.writeGateToken=s.token),s):(this.logger.error?.(`[bridge-core] background mutation rejected sessionKey=${e.gatewaySessionKey} runId=${t} reason=${s.reason}`),s)}cleanupPrompt(e){this.state.clearPromptTimeout(e),this.state.clearStreamIdleTimer(e);const t=e.currentRunId;if(t){this.state.promptsByRunId.delete(t),this.state.runIdToCronJobId.delete(t),this.state.markRunCompleted(t);const e=`tc_${t}_`;for(const[t,s]of this.state.toolCallIdMap)s.startsWith(e)&&this.state.toolCallIdMap.delete(t)}e.gatewayRequestId&&this.state.promptsByGatewayRequestId.delete(e.gatewayRequestId),e.pendingPromptId=void 0,e.promptDone=void 0,e.currentRunId=void 0,e.gatewayRequestId=void 0,e.assistantStreamStartedAt=void 0,e.gatewayMethod=void 0,e.mutationTerminalOverride=void 0,e.mutationTerminalCommitting=void 0,e.assistantMq?.close(),e.assistantMq=void 0,e.pendingUserTurnUpdates=void 0}async completePrompt(e,t){await this.endRun(e,{kind:"complete",stopReason:t})}async interruptPrompt(e,t){this.logRuntimeFailure(e,t),await this.endRun(e,{kind:"interrupted",stopReason:t.stopReason,message:t.publicMessage,errorCode:t.errorCode})}async failPrompt(e,t,s){await this.endRun(e,{kind:"error",code:t,message:s})}cleanupAllPendingPrompts(){for(const e of this.state.sessions.values())e.writeGateToken?(this.sessionMutationCoordinator.requireRecovery(e.writeGateToken,"gateway_disconnected","disconnect"),this.observeLifecycle(this.endRun(e,{kind:"interrupted",stopReason:"interrupted",message:SESSION_RECOVERY_REQUIRED_MESSAGE,errorCode:SESSION_RECOVERY_REQUIRED_CODE}),"gateway_disconnect_recovery",e)):this.observeLifecycle(this.interruptPrompt(e,classifyAgentRuntimeFailure({raw:Errors.GatewayDisconnected.message,source:"live_gateway",runtimeKind:"openclaw"})),"gateway_disconnect_interrupt",e)}handleGatewayResponse(e){const t=e.id;if(!t)return;const s=this.state.promptsByGatewayRequestId.get(t);if(!s||s.promptDone)return;if(!e.ok){const i=e.error,n=i?.message??"gateway returned error";this.logger.warn?.(`[bridge-core] handleGatewayResponse: gateway rejected prompt gatewayRequestId=${t} error=${n}`);const r=classifyAgentRuntimeFailure({raw:n,source:"live_gateway",runtimeKind:"openclaw"});return void("interrupted"===r.kind?this.observeLifecycle(this.interruptPrompt(s,r),"gateway_response_interrupt",s):(this.logRuntimeFailure(s,r),this.observeLifecycle(this.failPrompt(s,Errors.SendFailed.rpcCode,r.publicMessage),"gateway_response_failure",s)))}const i=e.payload,n=i?.runId;n?(s.currentRunId=n,this.sessionMutationCoordinator.bindRun(s.writeGateToken,n),this.observeActiveRun(s),s.assistantStreamStartedAt=Date.now(),this.state.promptsByRunId.set(n,s),this.logger.debug?.(`[bridge-core] handleGatewayResponse: bound runId=${n} gatewayRequestId=${t} sessionId=${s.sessionId}`)):this.logger.debug?.(`[bridge-core] handleGatewayResponse: no runId in payload gatewayRequestId=${t} sessionId=${s.sessionId}`)}maybeCompletePromptFromChatState(e,t){if(e.promptDone||"chat.send"!==e.gatewayMethod)return;const s="string"==typeof t.state?t.state.toLowerCase():void 0;if(s)if("final"===s){const s="string"==typeof t.stopReason?t.stopReason:void 0;this.observeLifecycle(this.completePrompt(e,s||"end_turn"),"chat_state_final",e)}else if("aborted"===s||"cancelled"===s||"cancel"===s)this.observeLifecycle(this.completePrompt(e,"cancelled"),"chat_state_cancelled",e);else if("error"===s){const s=("string"==typeof t.summary?t.summary:void 0)??("string"==typeof t.message?t.message:void 0)??"gateway chat error",i=classifyAgentRuntimeFailure({raw:s,source:"chat_state",runtimeKind:"openclaw"});"interrupted"===i.kind?this.observeLifecycle(this.interruptPrompt(e,i),"chat_state_interrupt",e):(this.logRuntimeFailure(e,i),this.observeLifecycle(this.failPrompt(e,Errors.AgentError.rpcCode,i.publicMessage),"chat_state_failure",e))}}async handleCronRequest(e){const t=this.getGateway();if(!t?.isConnected)return void this.transport.sendAcpError(e.id,Errors.GatewayNotConnected);const s=e.method.replace("/","."),i={...e.params??{}};["cron.add","cron.update","cron.remove","cron.run","cron.runs"].includes(s)&&(i.__beeosCronIngress="acp"),"cron.update"===s&&(i.patch=i.patch&&"object"==typeof i.patch?{...i.patch}:{});try{const t=await this.dispatchLegacyCronCapability(s,i),n=await this.mapCronResultForAcp(s,t);this.transport.sendResult(e.id,n??{}),"cron.add"!==s&&"cron.update"!==s&&"cron.remove"!==s||this.refreshCronIsolatedSessionKeys()}catch(t){const i=t instanceof Error?t.message:"cron request failed";this.logger.warn?.(`[bridge-core] ${s} failed: ${i}`),this.transport.sendAcpError(e.id,Errors.SendFailed,{message:i})}}async mapCronResultForAcp(e,t){if(!t||"object"!=typeof t)return t;const s=t;await this.cronOverrides.snapshot();const i="cron.list"===e||"cron.status"===e,n=e=>{if(!e||"object"!=typeof e)return e;const t=e,s=t.id;if("string"!=typeof s)return e;const n=this.cronOverrides.localId(s)??s,r=this.cronChannelCache.get(n),o=r?encodeBeeosChannelTag("string"==typeof t.description?t.description:void 0,r):t.description,a=this.cronOverrides.get(n);return{...t,id:n,...void 0===o?{}:{description:o},...i&&"number"==typeof a?{_beeos_meta:{maxDurationMs:a}}:{}}};if(Array.isArray(s.jobs))return{...s,jobs:s.jobs.map(n)};if(s.jobs&&"object"==typeof s.jobs){const e=s.jobs,t={};for(const[s,i]of Object.entries(e))t[s]=n(i);return{...s,jobs:t}}return Array.isArray(s.runs)?{...s,runs:s.runs.map(e=>{if(!e||"object"!=typeof e)return e;const t=e,s="string"==typeof t.jobId?this.cronOverrides.localId(t.jobId)??t.jobId:t.jobId;return{...t,jobId:s}})}:"cron.add"===e||"cron.update"===e?n(t):t}async allocateCronChannel(e){if(!this.agentFetch||!this.agentGatewayUrl)return void this.logger.debug?.("[bridge-core] agentFetch/agentGatewayUrl unavailable, skip channel alloc");const t=this.getAuthoritativeInstanceId?.()?.trim();if(!t?.startsWith("inst_"))return void this.logger.warn?.("[bridge-core] no authoritative inst_* instance id resolved yet, skip channel alloc");const s=this.config.gateway.agentId||this.getDefaultAgentId(),i=this.resolvePlatformAgentId(s)?.trim();if(!i)return void this.logger.warn?.(`[bridge-core] no platform agent id for localAgentId=${s}, skip channel alloc`);const n={source:"cron",job_name:e,protocol:"beeos-conversation",target_agent_id:i,title:e};try{const e=`${this.agentGatewayUrl}/api/v1/channels`,s=await this.agentFetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({participants:[t,"service:cron"],metadata:n})});if(!s.ok)return void this.logger.warn?.(`[bridge-core] channel alloc failed: ${s.status}`);return(await s.json()).id}catch(e){return void this.logger.warn?.(`[bridge-core] channel alloc error: ${e instanceof Error?e.message:e}`)}}setCronChannelCache(e,t){if(this.cronChannelCache.size>=AcpGatewayBridgeCore.CRON_CHANNEL_CACHE_MAX){const e=this.cronChannelCache.keys().next().value;void 0!==e&&this.cronChannelCache.delete(e)}this.cronChannelCache.set(e,t)}async refreshCronIsolatedSessionKeys(){const e=this.getGateway();if(e?.isConnected)try{const t=await e.request("cron.list",{}),s=t?.jobs;if(!Array.isArray(s))return;const i=new Set,n=[];for(const e of s){if(!e||"object"!=typeof e)continue;const t=e;if("string"==typeof t.id&&n.push(t.id),"isolated"!==t.sessionTarget)continue;const s=t.sessionKey;"string"==typeof s&&s.length>0&&i.add(s)}this.cronIsolatedSessionKeys=i,await this.cronOverrides.reconcile(n)}catch(e){this.logger.debug?.(`[bridge-core] refreshCronIsolatedSessionKeys failed: ${e instanceof Error?e.message:e}`)}}}async function fetchWithRetry(e,t={}){const s=t.maxRetries??3;let i;for(let n=0;n<=s;n++){const r=await fetch(e,{signal:AbortSignal.timeout(12e4),redirect:"follow"});if(r.ok)return Buffer.from(await r.arrayBuffer());if(429===r.status||r.status>=500){const o=Number(r.headers.get("retry-after"))||0,a=1e3*Math.max(o,2**n);if(i=new Error(`HTTP ${r.status} from ${e}`),n<s){t.logger?.info?.(`[bridge-core] Download ${r.status}, retry ${n+1}/${s} in ${(a/1e3).toFixed(0)}s`),await new Promise(e=>setTimeout(e,a));continue}}throw new Error(`Failed to download ${e}: HTTP ${r.status}`)}throw i??new Error(`Download failed after retries: ${e}`)}const SKILL_ROOT_MARKERS=["SKILL.md","skill.md","SKILL.MD"];function normalizeSkillArtifactPath(e){const t=e.replaceAll("\\","/").replace(/^\.\//,"");if(!t||t.startsWith("/")||t.split("/").includes(".."))throw new RuntimeCommandError("INVALID_PARAMS",`Invalid skill artifact path: ${e}`);return t}function parseSkillZip(e){if(e.byteLength>MAX_ZIP_BYTES)throw new RuntimeCommandError("INVALID_PARAMS","Skill archive too large");const t=new AdmZip(e).getEntries().filter(e=>!e.isDirectory).map(e=>({name:normalizeSkillArtifactPath(e.entryName),bytes:e.getData()})).filter(e=>!e.name.split("/").includes("__MACOSX"));if(0===t.length)throw new RuntimeCommandError("INVALID_PARAMS","Skill archive is empty");const s=1===new Set(t.map(e=>e.name.split("/")[0])).size&&t.every(e=>e.name.includes("/")),i=new Map;for(const e of t){const t=s?e.name.slice(e.name.indexOf("/")+1):e.name;if(!t||i.has(t))throw new RuntimeCommandError("INVALID_PARAMS",`Duplicate skill path: ${t}`);i.set(t,e.bytes)}return i}async function resolveSkillRoot(e){for(const t of SKILL_ROOT_MARKERS)try{return await stat(join(e,t)),e}catch{}const t=(await readdir(e,{withFileTypes:!0})).filter(e=>e.isDirectory()&&!e.name.startsWith(".")&&"__MACOSX"!==e.name);if(1===t.length){const s=join(e,t[0].name);for(const e of SKILL_ROOT_MARKERS)try{return await stat(join(s,e)),s}catch{}return s}return e}async function extractZipToDir(e,t){const s=new AdmZip(e),i=join(t,".beeos-extract-tmp-"+Date.now());try{await mkdir(i,{recursive:!0}),s.extractAllTo(i,!0);const e=await resolveSkillRoot(i),n=await readdir(e,{withFileTypes:!0});let r=0;for(const s of n){if(s.name.startsWith(".beeos-extract-tmp")||"__MACOSX"===s.name)continue;const i=join(e,s.name),n=join(t,s.name);await rename(i,n).catch(async()=>{await cp(i,n,{recursive:!0})}),r++}if(0===r)throw new Error("Zip archive contained no extractable files")}finally{await rm(i,{recursive:!0,force:!0}).catch(()=>{})}}const VALID_SLUG_PATTERN=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,NON_ASCII_PATTERN=/[^\x00-\x7F]/;function validateSkillSlug(e){const t=e.trim();if(!t||t.includes("/")||t.includes("\\")||t.includes(".."))throw new Error(`Invalid skill slug: ${e}`);if(NON_ASCII_PATTERN.test(t)||!VALID_SLUG_PATTERN.test(t))throw new Error(`Invalid skill slug: ${e}`);return t}function safeDirName(e){const t=e.trim();return t?t.replaceAll("/","__").replaceAll("\\","__"):t}function extractMcpCredentialMaterial(e){const t=mcpStringMap(e.headers,"MCP headers"),s=mcpStringMap(e.env,"MCP environment");if(!(t&&0!==Object.keys(t).length||s&&0!==Object.keys(s).length))return;const i=e.transport??("string"==typeof e.command?"stdio":"string"==typeof e.url?"streamable-http":void 0);if("stdio"===i&&t&&Object.keys(t).length)throw new Error("MCP stdio config cannot include headers");if("stdio"!==i&&s&&Object.keys(s).length)throw new Error("MCP HTTP config cannot include env");return{...t&&Object.keys(t).length?{headers:t}:{},...s&&Object.keys(s).length?{env:s}:{}}}function mcpStringMap(e,t){if(void 0!==e){if(!e||"object"!=typeof e||Array.isArray(e)||Object.entries(e).some(([e,t])=>!e||/[\u0000-\u001f\u007f]/.test(e)||"string"!=typeof t))throw new Error(`${t} invalid`);return{...e}}}function requireCredentialReferencePort(e){if(!e)throw new Error("MCP credential reference vault is unavailable");return e}function resolveSkillInstallDir(e,t){const s=safeDirName(t),i=join(e,s),n=resolve(e),r=resolve(i),o=relative(n,r);if(!o||".."===o||o.startsWith(`..${sep}`)||path.isAbsolute(o))throw new Error("Invalid skill target path");return i}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID}from"node:crypto";import WebSocket from"ws";import{agentAuthHeaders}from"../agent-auth.js";import{MSG_SYNC,MSG_AWARENESS}from"./constants.js";const RECONNECT_BASE_MS=1e3,RECONNECT_MAX_MS=3e4,MAX_PENDING_DATA=500;export class CanvasRelayClient{ws=null;opts;reconnectAttempts=0;reconnectTimer=null;closed=!1;hasConnectedOnce=!1;canvasHandlers=new Map;joinedCanvases=new Set;pendingJoins=new Map;pendingData=[];actionHandler=null;pendingRequests=new Map;constructor(e){this.opts=e}connect(){this.closed=!1,this.reconnectAttempts=0,this.doConnect()}doConnect(){this.closed||this.doConnectAsync().catch(e=>{this.opts.logger?.warn?.(`[canvas-relay] Connect failed: ${e}`),this.scheduleReconnect()})}async doConnectAsync(){if(this.closed)return;const e="/ws/agent";let t,n={};if(this.opts.tokenProvider){const s=await this.opts.tokenProvider();t=`${(s.relay_url||this.opts.canvasRelayUrl).replace(/^http/,"ws")}${e}`,this.opts.agentId&&(t+=`?agentId=${encodeURIComponent(this.opts.agentId)}`),t+=`${t.includes("?")?"&":"?"}token=${encodeURIComponent(s.token)}`,n=agentAuthHeaders("GET",e,this.opts.agentKeys)}else t=`${this.opts.canvasRelayUrl.replace(/^http/,"ws")}${e}`,this.opts.agentId&&(t+=`?agentId=${encodeURIComponent(this.opts.agentId)}`),n=agentAuthHeaders("GET",e,this.opts.agentKeys);this.opts.logger?.info?.(`[canvas-relay] Connecting to ${t}`);const s=new WebSocket(t,{headers:n});s.binaryType="arraybuffer",s.on("open",()=>{this.opts.logger?.info?.("[canvas-relay] Connected (multiplexed)"),this.reconnectAttempts=0,this.ws=s,(this.opts.displayName||this.opts.avatarUrl)&&this.sendControlMessage({type:"profile",displayName:this.opts.displayName,avatarUrl:this.opts.avatarUrl});for(const e of this.joinedCanvases)this.sendJoinCommand(e);for(const e of this.pendingData)this.sendTagged(e.canvasId,e.data);this.pendingData=[],this.hasConnectedOnce?(this.opts.logger?.info?.("[canvas-relay] Reconnected — notifying upper layer"),this.opts.onReconnect?.()):this.hasConnectedOnce=!0}),s.on("message",(e,t)=>{if(!t&&"string"!=typeof e){const t=e instanceof Buffer?e.toString("utf8"):(new TextDecoder).decode(e);return void this.handleTextMessage(t)}if("string"==typeof e)return void this.handleTextMessage(e);const n=new Uint8Array(e instanceof ArrayBuffer?e:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength));this.handleBinaryMessage(n)}),s.on("close",()=>{this.opts.logger?.info?.("[canvas-relay] Disconnected"),this.ws=null;for(const[,e]of this.pendingJoins)e.reject(new Error("WebSocket disconnected"));this.pendingJoins.clear();for(const[,e]of this.pendingRequests)clearTimeout(e.timer),e.reject(new Error("WebSocket disconnected"));this.pendingRequests.clear(),this.scheduleReconnect()}),s.on("error",e=>{this.opts.logger?.warn?.("[canvas-relay] Error:",e.message),s.close()})}scheduleReconnect(){if(this.closed)return;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.opts.logger?.debug?.(`[canvas-relay] Reconnecting in ${e}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimer=setTimeout(()=>this.doConnect(),e),"object"==typeof this.reconnectTimer&&"unref"in this.reconnectTimer&&this.reconnectTimer.unref()}async joinCanvas(e,t){if(this.canvasHandlers.set(e,t),!this.joinedCanvases.has(e)&&(this.joinedCanvases.add(e),this.connected))return new Promise((t,n)=>{this.pendingJoins.set(e,{resolve:t,reject:n}),this.sendJoinCommand(e);const s=setTimeout(()=>{const t=this.pendingJoins.get(e);t&&(this.pendingJoins.delete(e),this.opts.logger?.warn?.(`[canvas-relay] joinCanvas timed out for canvas=${e}, resolving optimistically`),t.resolve())},5e3),o=this.pendingJoins.get(e);this.pendingJoins.set(e,{resolve:()=>{clearTimeout(s),o.resolve()},reject:e=>{clearTimeout(s),o.reject(e)}})})}leaveCanvas(e){this.canvasHandlers.delete(e),this.joinedCanvases.delete(e),this.connected&&this.sendControlMessage({type:"leave",canvasId:e})}sendUpdate(e,t){this.sendTagged(e,t)}sendAwareness(e,t){this.sendTagged(e,t)}async ensureCanvas(e,t){return(await this.sendRequest({type:"ensureCanvas",sessionId:e,agentId:t?.agentId,title:t?.title,linkSessionId:t?.linkSessionId})).canvasId}async deleteCanvas(e){await this.sendRequest({type:"deleteCanvas",canvasId:e})}async createSnapshot(e,t){return(await this.sendRequest({type:"createSnapshot",canvasId:e,description:t})).snapshotId??null}onAction(e){this.actionHandler=e}sendActionResult(e){this.sendControlMessage({type:"action:result",...e})}sendActionError(e){this.sendControlMessage({type:"action:error",...e})}sendRequest(e){if(!this.connected)return Promise.reject(new Error(`WebSocket not connected (request: ${e.type})`));const t=randomUUID();return e.reqId=t,new Promise((n,s)=>{const o=setTimeout(()=>{this.pendingRequests.delete(t),s(new Error(`WSS request ${e.type} timed out`))},1e4);this.pendingRequests.set(t,{resolve:n,reject:s,timer:o}),this.sendControlMessage(e)})}sendTagged(e,t){if(!this.connected)return this.pendingData.length>=500&&(this.opts.logger?.warn?.("[canvas-relay] Pending data buffer full (500), dropping oldest entry"),this.pendingData.shift()),void this.pendingData.push({canvasId:e,data:t});const n=(new TextEncoder).encode(e),s=new Uint8Array(1+n.length+t.length);s[0]=n.length,s.set(n,1),s.set(t,1+n.length),this.ws.send(s)}handleTextMessage(e){try{const t=JSON.parse(e),n=t.type;if(n?.endsWith(":result")&&t.reqId){const e=this.pendingRequests.get(t.reqId);return void(e&&(this.pendingRequests.delete(t.reqId),clearTimeout(e.timer),t.error?e.reject(new Error(t.error)):e.resolve(t)))}switch(n){case"joined":{const e=this.pendingJoins.get(t.canvasId??"");e&&(this.pendingJoins.delete(t.canvasId),e.resolve()),this.opts.logger?.info?.(`[canvas-relay] Joined canvas ${t.canvasId}`);break}case"left":this.opts.logger?.info?.(`[canvas-relay] Left canvas ${t.canvasId}`);break;case"error":this.opts.logger?.warn?.(`[canvas-relay] Error for canvas ${t.canvasId}: ${t.message}`);break;case"action":this.opts.logger?.info?.(`[canvas-relay] Received action: canvasId=${t.canvasId} surfaceId=${t.surfaceId} requestId=${t.requestId} senderClientId=${t.senderClientId}`),this.actionHandler?this.actionHandler(t):this.opts.logger?.warn?.("[canvas-relay] Action received but no handler registered");break;default:this.opts.logger?.debug?.(`[canvas-relay] Unknown control: ${n}`)}}catch{this.opts.logger?.warn?.(
|
|
1
|
+
import{randomUUID}from"node:crypto";import WebSocket from"ws";import{agentAuthHeaders}from"../agent-auth.js";import{MSG_SYNC,MSG_AWARENESS}from"./constants.js";const RECONNECT_BASE_MS=1e3,RECONNECT_MAX_MS=3e4,MAX_PENDING_DATA=500;export class CanvasRelayClient{ws=null;opts;reconnectAttempts=0;reconnectTimer=null;closed=!1;hasConnectedOnce=!1;canvasHandlers=new Map;joinedCanvases=new Set;pendingJoins=new Map;pendingData=[];actionHandler=null;controlHandler=null;pendingRequests=new Map;constructor(e){this.opts=e}connect(){this.closed=!1,this.reconnectAttempts=0,this.doConnect()}doConnect(){this.closed||this.doConnectAsync().catch(e=>{this.opts.logger?.warn?.(`[canvas-relay] Connect failed: ${e}`),this.scheduleReconnect()})}async doConnectAsync(){if(this.closed)return;const e="/ws/agent";let t,n={};if(this.opts.tokenProvider){const s=await this.opts.tokenProvider();t=`${(s.relay_url||this.opts.canvasRelayUrl).replace(/^http/,"ws")}${e}`,this.opts.agentId&&(t+=`?agentId=${encodeURIComponent(this.opts.agentId)}`),t+=`${t.includes("?")?"&":"?"}token=${encodeURIComponent(s.token)}`,n=agentAuthHeaders("GET",e,this.opts.agentKeys)}else t=`${this.opts.canvasRelayUrl.replace(/^http/,"ws")}${e}`,this.opts.agentId&&(t+=`?agentId=${encodeURIComponent(this.opts.agentId)}`),n=agentAuthHeaders("GET",e,this.opts.agentKeys);this.opts.logger?.info?.(`[canvas-relay] Connecting to ${t}`);const s=new WebSocket(t,{headers:n});s.binaryType="arraybuffer",s.on("open",()=>{this.opts.logger?.info?.("[canvas-relay] Connected (multiplexed)"),this.reconnectAttempts=0,this.ws=s,(this.opts.displayName||this.opts.avatarUrl)&&this.sendControlMessage({type:"profile",displayName:this.opts.displayName,avatarUrl:this.opts.avatarUrl});for(const e of this.joinedCanvases)this.sendJoinCommand(e);for(const e of this.pendingData)this.sendTagged(e.canvasId,e.data);this.pendingData=[],this.hasConnectedOnce?(this.opts.logger?.info?.("[canvas-relay] Reconnected — notifying upper layer"),this.opts.onReconnect?.()):this.hasConnectedOnce=!0}),s.on("message",(e,t)=>{if(!t&&"string"!=typeof e){const t=e instanceof Buffer?e.toString("utf8"):(new TextDecoder).decode(e);return void this.handleTextMessage(t)}if("string"==typeof e)return void this.handleTextMessage(e);const n=new Uint8Array(e instanceof ArrayBuffer?e:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength));this.handleBinaryMessage(n)}),s.on("close",()=>{this.opts.logger?.info?.("[canvas-relay] Disconnected"),this.ws=null;for(const[,e]of this.pendingJoins)e.reject(new Error("WebSocket disconnected"));this.pendingJoins.clear();for(const[,e]of this.pendingRequests)clearTimeout(e.timer),e.reject(new Error("WebSocket disconnected"));this.pendingRequests.clear(),this.scheduleReconnect()}),s.on("error",e=>{this.opts.logger?.warn?.("[canvas-relay] Error:",e.message),s.close()})}scheduleReconnect(){if(this.closed)return;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.opts.logger?.debug?.(`[canvas-relay] Reconnecting in ${e}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimer=setTimeout(()=>this.doConnect(),e),"object"==typeof this.reconnectTimer&&"unref"in this.reconnectTimer&&this.reconnectTimer.unref()}async joinCanvas(e,t){if(this.canvasHandlers.set(e,t),!this.joinedCanvases.has(e)&&(this.joinedCanvases.add(e),this.connected))return new Promise((t,n)=>{this.pendingJoins.set(e,{resolve:t,reject:n}),this.sendJoinCommand(e);const s=setTimeout(()=>{const t=this.pendingJoins.get(e);t&&(this.pendingJoins.delete(e),this.opts.logger?.warn?.(`[canvas-relay] joinCanvas timed out for canvas=${e}, resolving optimistically`),t.resolve())},5e3),o=this.pendingJoins.get(e);this.pendingJoins.set(e,{resolve:()=>{clearTimeout(s),o.resolve()},reject:e=>{clearTimeout(s),o.reject(e)}})})}leaveCanvas(e){this.canvasHandlers.delete(e),this.joinedCanvases.delete(e),this.connected&&this.sendControlMessage({type:"leave",canvasId:e})}sendUpdate(e,t){this.sendTagged(e,t)}sendAwareness(e,t){this.sendTagged(e,t)}async ensureCanvas(e,t){return(await this.sendRequest({type:"ensureCanvas",sessionId:e,agentId:t?.agentId,title:t?.title,linkSessionId:t?.linkSessionId})).canvasId}async deleteCanvas(e){await this.sendRequest({type:"deleteCanvas",canvasId:e})}async createSnapshot(e,t){return(await this.sendRequest({type:"createSnapshot",canvasId:e,description:t})).snapshotId??null}onAction(e){this.actionHandler=e}onCanvasControl(e){this.controlHandler=e}sendActionResult(e){this.sendControlMessage({type:"action:result",...e})}sendActionError(e){this.sendControlMessage({type:"action:error",...e})}sendRequest(e){if(!this.connected)return Promise.reject(new Error(`WebSocket not connected (request: ${e.type})`));const t=randomUUID();return e.reqId=t,new Promise((n,s)=>{const o=setTimeout(()=>{this.pendingRequests.delete(t),s(new Error(`WSS request ${e.type} timed out`))},1e4);this.pendingRequests.set(t,{resolve:n,reject:s,timer:o}),this.sendControlMessage(e)})}sendTagged(e,t){if(!this.connected)return this.pendingData.length>=500&&(this.opts.logger?.warn?.("[canvas-relay] Pending data buffer full (500), dropping oldest entry"),this.pendingData.shift()),void this.pendingData.push({canvasId:e,data:t});const n=(new TextEncoder).encode(e),s=new Uint8Array(1+n.length+t.length);s[0]=n.length,s.set(n,1),s.set(t,1+n.length),this.ws.send(s)}handleTextMessage(e){try{const t=JSON.parse(e),n=t.type;if(n?.endsWith(":result")&&t.reqId){const e=this.pendingRequests.get(t.reqId);return void(e&&(this.pendingRequests.delete(t.reqId),clearTimeout(e.timer),t.error?e.reject(new Error(t.error)):e.resolve(t)))}switch(n){case"joined":{const e=this.pendingJoins.get(t.canvasId??"");e&&(this.pendingJoins.delete(t.canvasId),e.resolve()),this.opts.logger?.info?.(`[canvas-relay] Joined canvas ${t.canvasId}`);break}case"left":this.opts.logger?.info?.(`[canvas-relay] Left canvas ${t.canvasId}`);break;case"error":this.opts.logger?.warn?.(`[canvas-relay] Error for canvas ${t.canvasId}: ${t.message}`);break;case"action":this.opts.logger?.info?.(`[canvas-relay] Received action: canvasId=${t.canvasId} surfaceId=${t.surfaceId} requestId=${t.requestId} senderClientId=${t.senderClientId}`),this.actionHandler?this.actionHandler(t):this.opts.logger?.warn?.("[canvas-relay] Action received but no handler registered");break;case"canvas.toggle":case"canvas.dimensions":case"canvas.reference":case"canvas.clear":this.opts.logger?.info?.(`[canvas-relay] Received control frame type=${n} canvasId=${t.canvasId} sessionId=${t.sessionId??""}`),this.controlHandler?this.controlHandler(t):this.opts.logger?.warn?.(`[canvas-relay] Control frame ${n} received but no handler registered`);break;default:this.opts.logger?.debug?.(`[canvas-relay] Unknown control: ${n}`)}}catch(e){this.opts.logger?.warn?.(`[canvas-relay] Failed to parse control message: ${e instanceof Error?e.message:String(e)}`)}}handleBinaryMessage(e){if(e.length<2)return;const t=e[0];if(e.length<1+t+1)return;const n=(new TextDecoder).decode(e.slice(1,1+t)),s=e.slice(1+t),o=this.canvasHandlers.get(n);if(!o)return;const a=s[0];a===MSG_SYNC&&o.onUpdate?o.onUpdate(s):a===MSG_AWARENESS&&o.onAwareness&&o.onAwareness(s)}sendJoinCommand(e){this.sendControlMessage({type:"join",canvasId:e})}sendControlMessage(e){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(e))}disconnect(){this.closed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.close(),this.ws=null),this.pendingData=[];for(const[,e]of this.pendingJoins)e.reject(new Error("Client disconnected"));this.pendingJoins.clear();for(const[,e]of this.pendingRequests)clearTimeout(e.timer),e.reject(new Error("Client disconnected"));this.pendingRequests.clear()}get connected(){return null!==this.ws&&this.ws.readyState===WebSocket.OPEN}}
|
package/dist/canvas/tools.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const A2UI_TYPE_NAMES=new Set(["Text","Image","Icon","Video","AudioPlayer","Row","Column","List","Card","Tabs","Divider","Modal","Button","CheckBox","TextField","DateTimeInput","MultipleChoice","Slider","Chart","WebEmbed","FilePreview","MapView"]);function normalizeComponents(e){return e.map(e=>{if(!e||"object"!=typeof e)return e;const t=e;if(t.component&&"object"==typeof t.component)return t;for(const e of Object.keys(t))if(A2UI_TYPE_NAMES.has(e)&&"object"==typeof t[e])return{id:t.id,component:{[e]:t[e]}};return t})}export const RENDER_UI_TOOL_NAME="render_ui";export const CLOSE_UI_TOOL_NAME="close_ui";export const RENDER_UI_TOOL_DESCRIPTION="Render a Google A2UI v0.8 component tree to the Canvas panel. Output a flat array of ComponentInstance objects with id references. ALWAYS prefer this over the canvas tool for displaying structured UI.";export const RENDER_UI_TOOL_SCHEMA={type:"object",required:["id","root","components"],properties:{id:{type:"string",description:"Surface ID (e.g. 'sales-report'). Reuse same id to update an existing surface."},root:{type:"string",description:"ID of the root component (must reference one of the components below)."},components:{type:"array",description:"Flat array of A2UI ComponentInstance objects. Each has a unique id and exactly one component type key.",items:{type:"object",required:["id"],properties:{id:{type:"string",description:"Unique component ID referenced by parent via child/children."},component:{type:"object",description:"Exactly ONE key = component type (Text, Image, Icon, Video, AudioPlayer, Row, Column, List, Card, Tabs, Divider, Modal, Button, CheckBox, TextField, DateTimeInput, MultipleChoice, Slider, Chart). Value = that component's properties object."}}}},data:{type:"object",description:"Optional data model for two-way binding. Keys are paths (e.g. '/name'), values are defaults."}}};export const CLOSE_UI_TOOL_DESCRIPTION="Close and remove a UI surface that was previously rendered.";export const CLOSE_UI_TOOL_SCHEMA={type:"object",required:["id"],properties:{id:{type:"string",description:"The UI identifier to close"}}};const SESSION_READY_POLL_ATTEMPTS=3,SESSION_READY_POLL_INTERVAL_MS=400,delay=e=>new Promise(t=>setTimeout(t,e));async function ensureRelayConnected(e,t,n,a){const{stateManager:o,logger:i}=e,r=a??e.getGatewaySessionKey?.(n),s=r??t,l=o.resolveCanvasForSession(s);if(l&&o.isCanvasJoined(l))return l;let c=o.getRelayClient();if(c||(c=await o.waitForRelayClient(),c))try{e.waitForAgentSync&&await e.waitForAgentSync();const a=e.getPlatformAgentId?.(n),l=r??t,d=r&&r!==t?t:void 0,p=await c.ensureCanvas(l,{agentId:a,linkSessionId:d});return await o.joinCanvas(p,s),i.info?.(`[canvas] Joined canvas=${p} session=${t} gatewayKey=${r??"none"} agentId=${a??"none"}`),p}catch(e){return void i.warn?.(`[canvas] Failed to join canvas relay: ${e}`)}}export function createRenderUiHandler(e){const{stateManager:t,logger:n,writeObs:a,isCanvasActive:o,getGatewaySessionKey:i}=e;let r=0;return async(s,l)=>{if(o){const e=i?.(s);if(!o(e))return{success:!1,error:"Canvas is disabled by user. Respond with plain text instead."}}const c=l,d=c.id,p=c.root,u="panel";let m=c.components;if("string"==typeof m)try{m=JSON.parse(m)}catch{}if(!(d&&p&&Array.isArray(m)&&m.length))return{success:!1,error:"id, root, and components (array) are required"};const h=normalizeComponents(m);if(!t.validateComponentCount(h))return{success:!1,error:"Too many components (max 500)"};if(!t.checkRateLimit(d))return n.warn?.(`[canvas] Rate limited surfaceId=${d}`),a({component:"canvas",domain:"canvas",name:"canvas.rate_limited",severity:"warn",payload:{surfaceId:d}}),{success:!1,error:"Rate limited — too many updates per second"};const g=c.data;let y=e.getActiveSessionId?.(s);for(let t=0;!y&&t<3;t++)await delay(400),y=e.getActiveSessionId?.(s);if(!y&&e.waitForAgentSync){try{await e.waitForAgentSync()}catch{}y=e.getActiveSessionId?.(s)}if(!y)return n.warn?.(`[canvas] No active session for toolCallId=${s} after 3 polls, render_ui not ready`),{success:!1,retryable:!0,error:"Canvas session not ready yet (agent just connected) — retry render_ui shortly; do NOT fall back to plain text."};const f=e.getGatewaySessionKey?.(s),v=await ensureRelayConnected(e,y,s,f),x=t.has(d,v??void 0),b=Date.now(),C=t.getRelayClient();v&&C&&b-r>6e4&&C.createSnapshot(v,"Pre-agent edit").then(()=>{r=Date.now(),n.debug?.("[canvas] Pre-edit checkpoint created")}).catch(e=>n.warn?.(`[canvas] Pre-edit checkpoint failed: ${e}`)),x?t.update(d,h,v,p,g):t.create(v??`_fallback_${Date.now()}`,d,u,h,{origin:{kind:"agent"},rootComponentId:p,dataModel:g});const S=h.map(e=>e.component&&"object"==typeof e.component?Object.keys(e.component)[0]??"unknown":"unknown");a({component:"canvas",domain:"canvas",name:x?"canvas.update_sent":"canvas.surface_created",severity:"info",payload:{surfaceId:d,presentation:u,componentCount:h.length,componentTypes:S}}),n.debug?.(`[canvas] ${x?"Updated":"Created"} surface=${d} components=${h.length}`);const T={success:!0,surfaceId:d,presentation:u,isUpdate:x,activeSurfaces:v?t.getAllActive(v).map(e=>e.surfaceId):[d]};return g&&(T.dataModel=g),T}}export function createCloseUiHandler(e){const{stateManager:t,logger:n,writeObs:a}=e;return async(o,i)=>{const r=i.id;if(!r)return{success:!1,error:"id is required"};const s=t.get(r),l=s?Date.now()-s.createdAt:0,c=e.getGatewaySessionKey?.(o),d=c?t.resolveCanvasForSession(c):void 0;return t.delete(r,d),a({component:"canvas",domain:"canvas",name:"canvas.surface_closed",severity:"info",payload:{surfaceId:r,lifetime_ms:l}}),n.debug?.(`[canvas] Closed surface=${r}`),{success:!0,surfaceId:r,message:"UI closed"}}}export const CANVAS_SYSTEM_PROMPT='## Canvas UI — Google A2UI v0.8\n\n**IMPORTANT: Always use `render_ui` (not the built-in `canvas` tool) to display visual/structured content.**\n\n### How render_ui works\n\nYou output a **flat array of components** with unique IDs. Components reference each other by ID.\n\nParameters:\n- `id`: Surface ID (e.g. "sales-report"). Reuse same id to update.\n- `root`: The ID of the top-level component (usually a Column).\n- `components`: Flat array of objects. **Each object MUST have `id` and `component`**:\n `{"id": "myId", "component": {"Text": {"text": {"literalString": "Hello"}, "usageHint": "body"}}}`\n The `component` key wraps exactly ONE type key (Text, Card, Row, etc.) and its properties.\n- `data` (optional): Data model object for form two-way binding.\n\n### Rules\n- Keep chat reply to ONE short sentence when using render_ui. Do NOT repeat data shown in canvas.\n- Use render_ui for structured data, visualizations, forms, dashboards. Use plain text for explanations.\n- Canvas renders in a narrow sidebar (~400px).\n- Prefer fewer, larger components. One table is better than many small cards.\n- Use descriptive surface IDs (e.g. "sales-report", not "ui1").\n- Same `id` updates existing surface; different `id` creates new one.\n- When asked to modify existing content, reuse the original surface id from [Canvas State].\n\n### StringValue\n\nText properties use StringValue — an object with exactly one key:\n- Static text: `{"literalString": "Hello"}`\n- Data binding: `{"path": "/fieldName"}` (reads from the `data` model)\n\nShorthand: `sv("text")` means `{"literalString": "text"}` in examples below.\n\n### Component Reference\n\n**Text** — Display text with semantic sizing.\n`{Text: {text: sv("Title"), usageHint: "h2"}}`\nusageHint: "h1" | "h2" | "h3" | "h4" | "h5" | "caption" | "body"\ntext also renders Markdown (bold, italic, lists, code blocks, links).\n\n**Image** — Display an image.\n`{Image: {url: sv("https://..."), usageHint: "mediumFeature"}}`\nImage.url may be `beeos-file://<fileId>`; the renderer resolves it. Do not convert it to a signed URL.\nusageHint: "icon" | "avatar" | "smallFeature" | "mediumFeature" | "largeFeature" | "header"\nfit (optional): "contain" | "cover" | "fill" | "none" | "scale-down"\n\n**Icon** — Material icon.\n`{Icon: {name: sv("check")}}`\n\n**Video** — Embed a video.\n`{Video: {url: sv("https://youtube.com/...")}}`\n\n**AudioPlayer** — Audio playback.\n`{AudioPlayer: {url: sv("https://..."), description: sv("Episode 1")}}`\n\n**Row** — Horizontal layout. Children referenced by ID.\n`{Row: {children: {explicitList: ["child1", "child2"]}, distribution: "spaceBetween"}}`\ndistribution: "start" | "center" | "end" | "spaceBetween" | "spaceAround" | "spaceEvenly"\nalignment: "start" | "center" | "end" | "stretch"\n\n**Column** — Vertical layout. Children referenced by ID.\n`{Column: {children: {explicitList: ["child1", "child2"]}}}`\nSame distribution/alignment options as Row.\n\n**List** — Vertical or horizontal list.\n`{List: {children: {explicitList: ["item1", "item2"]}, direction: "vertical"}}`\n\n**Card** — Container with a single child.\n`{Card: {child: "contentColumnId"}}`\n\n**Tabs** — Tabbed container.\n`{Tabs: {tabItems: [{title: sv("Tab 1"), child: "panel1"}, {title: sv("Tab 2"), child: "panel2"}]}}`\n\n**Divider** — Horizontal or vertical separator.\n`{Divider: {axis: "horizontal"}}`\n\n**Modal** — Dialog with trigger.\n`{Modal: {entryPointChild: "triggerBtnId", contentChild: "dialogContentId"}}`\n\n**Button** — Clickable with action.\n`{Button: {child: "labelTextId", action: {name: "onClick", context: [{key: "id", value: {literalString: "item-1"}}]}}}`\n\n**TextField** — Text input with data binding.\n`{TextField: {label: sv("Name"), text: {path: "/name"}, type: "shortText"}}`\ntype: "shortText" | "number" | "date" | "longText"\n\n**CheckBox** — Boolean toggle.\n`{CheckBox: {label: sv("Agree"), value: {path: "/agree"}}}`\n\n**DateTimeInput** — Date/time picker.\n`{DateTimeInput: {value: {path: "/date"}, enableDate: true, enableTime: false}}`\n\n**MultipleChoice** — Selection from options.\n`{MultipleChoice: {selections: {path: "/country"}, options: [{label: sv("US"), value: "US"}, {label: sv("CN"), value: "CN"}]}}`\n\n**Slider** — Numeric range input.\n`{Slider: {value: {path: "/volume"}, minValue: 0, maxValue: 100}}`\n\n**Chart** (BeeOS extension) — Data visualization.\n`{Chart: {chartType: sv("bar"), title: sv("Sales"), labels: ["Q1","Q2","Q3"], datasets: [{label: "Revenue", data: [100,200,150]}]}}`\nchartType: bar, horizontal_bar, line, area, scatter, pie, doughnut, radar, gauge, candlestick, funnel, sparkline\ngauge uses value + max instead of labels/datasets.\ncandlestick data: [{open,high,low,close}] (full field names, NOT o/h/l/c).\n\n### Composition Patterns\n\n**Simple text display:**\n```json\n{"id":"s1","root":"r","components":[\n {"id":"t","component":{"Text":{"text":{"literalString":"Hello World"},"usageHint":"h2"}}},\n {"id":"r","component":{"Column":{"children":{"explicitList":["t"]}}}}\n]}\n```\n\n**Dashboard with KPI cards:**\n```json\n{"id":"dashboard","root":"root","components":[\n {"id":"title","component":{"Text":{"text":{"literalString":"Dashboard"},"usageHint":"h2"}}},\n {"id":"rev-val","component":{"Text":{"text":{"literalString":"$1.2M"},"usageHint":"h2"}}},\n {"id":"rev-lbl","component":{"Text":{"text":{"literalString":"Revenue"},"usageHint":"caption"}}},\n {"id":"rev-col","component":{"Column":{"children":{"explicitList":["rev-lbl","rev-val"]},"alignment":"center"}}},\n {"id":"rev-card","component":{"Card":{"child":"rev-col"}}},\n {"id":"users-val","component":{"Text":{"text":{"literalString":"8,432"},"usageHint":"h2"}}},\n {"id":"users-lbl","component":{"Text":{"text":{"literalString":"Users"},"usageHint":"caption"}}},\n {"id":"users-col","component":{"Column":{"children":{"explicitList":["users-lbl","users-val"]},"alignment":"center"}}},\n {"id":"users-card","component":{"Card":{"child":"users-col"}}},\n {"id":"kpi-row","component":{"Row":{"children":{"explicitList":["rev-card","users-card"]}}}},\n {"id":"root","component":{"Column":{"children":{"explicitList":["title","kpi-row"]}}}}\n]}\n```\n\n**Table layout (Column + Row + Text):**\n```json\n{"id":"users-table","root":"root","components":[\n {"id":"h-name","component":{"Text":{"text":{"literalString":"Name"},"usageHint":"caption"}}},\n {"id":"h-role","component":{"Text":{"text":{"literalString":"Role"},"usageHint":"caption"}}},\n {"id":"header","component":{"Row":{"children":{"explicitList":["h-name","h-role"]}}}},\n {"id":"div","component":{"Divider":{"axis":"horizontal"}}},\n {"id":"r1-name","component":{"Text":{"text":{"literalString":"Alice"},"usageHint":"body"}}},\n {"id":"r1-role","component":{"Text":{"text":{"literalString":"Engineer"},"usageHint":"body"}}},\n {"id":"row1","component":{"Row":{"children":{"explicitList":["r1-name","r1-role"]}}}},\n {"id":"r2-name","component":{"Text":{"text":{"literalString":"Bob"},"usageHint":"body"}}},\n {"id":"r2-role","component":{"Text":{"text":{"literalString":"Designer"},"usageHint":"body"}}},\n {"id":"row2","component":{"Row":{"children":{"explicitList":["r2-name","r2-role"]}}}},\n {"id":"table-col","component":{"Column":{"children":{"explicitList":["header","div","row1","row2"]}}}},\n {"id":"root","component":{"Card":{"child":"table-col"}}}\n]}\n```\n\n**Form with data binding:**\n```json\n{"id":"settings","root":"root","data":{"/name":"","/email":"","/notify":false},"components":[\n {"id":"title","component":{"Text":{"text":{"literalString":"Settings"},"usageHint":"h3"}}},\n {"id":"f-name","component":{"TextField":{"label":{"literalString":"Name"},"text":{"path":"/name"},"type":"shortText"}}},\n {"id":"f-email","component":{"TextField":{"label":{"literalString":"Email"},"text":{"path":"/email"},"type":"shortText"}}},\n {"id":"f-notify","component":{"CheckBox":{"label":{"literalString":"Email notifications"},"value":{"path":"/notify"}}}},\n {"id":"btn-text","component":{"Text":{"text":{"literalString":"Save"},"usageHint":"body"}}},\n {"id":"btn","component":{"Button":{"child":"btn-text","action":{"name":"save_settings","context":[{"key":"name","value":{"path":"/name"}},{"key":"email","value":{"path":"/email"}},{"key":"notify","value":{"path":"/notify"}}]}}}},\n {"id":"root","component":{"Column":{"children":{"explicitList":["title","f-name","f-email","f-notify","btn"]}}}}\n]}\n```\n\n**Chart:**\n```json\n{"id":"sales-chart","root":"root","components":[\n {"id":"chart","component":{"Chart":{"chartType":{"literalString":"bar"},"title":{"literalString":"Monthly Sales"},"labels":["Jan","Feb","Mar"],"datasets":[{"label":"Revenue","data":[100,200,150]}]}}},\n {"id":"root","component":{"Column":{"children":{"explicitList":["chart"]}}}}\n]}\n```\n\n### render_form\nUse `render_form` for schema-driven forms when a domain schema exists.\nParameters: `domain`, `operation`, `data`, `entityId`.\n\n### close_ui\nCloses a UI surface. Use when user moves to a new topic or explicitly dismisses.\n';export const CANVAS_TERM_MAPPING='[System Note] Always use `render_ui` (not the canvas tool) for visual/structured content. Each component in the array MUST be: {"id":"x","component":{"TypeName":{props}}} — the "component" wrapper key is required. render_ui uses Google A2UI v0.8 format: flat component array with id references. Components: Text (usageHint: h1-h5/caption/body), Image, Icon, Video, AudioPlayer, Row (horizontal layout, children.explicitList), Column (vertical layout, children.explicitList), List, Card (single child), Tabs (tabItems), Divider, Modal, Button (child + action), TextField, CheckBox, MultipleChoice, Slider, DateTimeInput, Chart (BeeOS extension: chartType, labels, datasets). StringValue: {"literalString":"text"} or {"path":"/binding"}. root param = top-level component ID. Tables: Card > Column > Row > Text. Forms: TextField/CheckBox/Slider + Button with action.context paths. Chart: chartType(bar/line/pie/area/scatter/doughnut/radar/funnel/gauge/candlestick/sparkline), labels, datasets:[{label,data,color?}]. Candlestick: [{open,high,low,close}]. Gauge: value+max. Keep chat brief when canvas is used. Use `close_ui` to dismiss. Reuse same id to update; new id for new content.';export const CANVAS_UPDATE_HINT="[Canvas Rule] Same id in render_ui = update existing surface. Different id = new surface. When a surface is referenced for editing, you MUST reuse its exact id and provide the full updated component tree.";const MAX_CONTEXT_SURFACES=8,MAX_CONTEXT_CHARS=500;export function buildActiveSurfacesContext(e,t){let n;if(!t)return null;if(n=e.getAllActive(t),0===n.length)return null;const a=[...n].sort((e,t)=>t.updatedAt-e.updatedAt).slice(0,8),o=n.length-a.length;let i=`[Canvas State] Active surfaces: ${a.map(t=>{const n=e.summarize(t.surfaceId);if(!n)return`"${t.surfaceId}"`;const a=n.types.slice(0,3).join(", "),o=n.title?`: "${n.title}"`:"";return`"${t.surfaceId}" (${a}${o})`}).join("; ")}.`;return o>0&&(i+=` ...and ${o} more.`),i+=" To modify existing content, reuse its id in render_ui.",i.length>500&&(i=i.slice(0,497)+"..."),i}
|
|
1
|
+
import{extractBeeosConversationIdFromSessionKey}from"../runtime/openclaw-session-key-resolution.js";const A2UI_TYPE_NAMES=new Set(["Text","Image","Icon","Video","AudioPlayer","Row","Column","List","Card","Tabs","Divider","Modal","Button","CheckBox","TextField","DateTimeInput","MultipleChoice","Slider","Chart","WebEmbed","FilePreview","MapView"]);function normalizeComponents(e){return e.map(e=>{if(!e||"object"!=typeof e)return e;const t=e;if(t.component&&"object"==typeof t.component)return t;for(const e of Object.keys(t))if(A2UI_TYPE_NAMES.has(e)&&"object"==typeof t[e])return{id:t.id,component:{[e]:t[e]}};return t})}export const RENDER_UI_TOOL_NAME="render_ui";export const CLOSE_UI_TOOL_NAME="close_ui";export const RENDER_UI_TOOL_DESCRIPTION="Render a Google A2UI v0.8 component tree to the Canvas panel. Output a flat array of ComponentInstance objects with id references. ALWAYS prefer this over the canvas tool for displaying structured UI.";export const RENDER_UI_TOOL_SCHEMA={type:"object",required:["id","root","components"],properties:{id:{type:"string",description:"Surface ID (e.g. 'sales-report'). Reuse same id to update an existing surface."},root:{type:"string",description:"ID of the root component (must reference one of the components below)."},components:{type:"array",description:"Flat array of A2UI ComponentInstance objects. Each has a unique id and exactly one component type key.",items:{type:"object",required:["id"],properties:{id:{type:"string",description:"Unique component ID referenced by parent via child/children."},component:{type:"object",description:"Exactly ONE key = component type (Text, Image, Icon, Video, AudioPlayer, Row, Column, List, Card, Tabs, Divider, Modal, Button, CheckBox, TextField, DateTimeInput, MultipleChoice, Slider, Chart). Value = that component's properties object."}}}},data:{type:"object",description:"Optional data model for two-way binding. Keys are paths (e.g. '/name'), values are defaults."}}};export const CLOSE_UI_TOOL_DESCRIPTION="Close and remove a UI surface that was previously rendered.";export const CLOSE_UI_TOOL_SCHEMA={type:"object",required:["id"],properties:{id:{type:"string",description:"The UI identifier to close"}}};const SESSION_READY_POLL_ATTEMPTS=3,SESSION_READY_POLL_INTERVAL_MS=400,delay=e=>new Promise(t=>setTimeout(t,e));async function ensureRelayConnected(e,t,n,a){const{stateManager:o,logger:i}=e,r=a??e.getGatewaySessionKey?.(n),s=r??t,l=o.resolveCanvasForSession(s);if(l&&o.isCanvasJoined(l))return l;let c=o.getRelayClient();if(c||(c=await o.waitForRelayClient(),c))try{e.waitForAgentSync&&await e.waitForAgentSync();const a=e.getPlatformAgentId?.(n),l=r??t,d=(r?extractBeeosConversationIdFromSessionKey(r):void 0)??(r&&r!==t?t:void 0),p=await c.ensureCanvas(l,{agentId:a,linkSessionId:d});return await o.joinCanvas(p,s),i.info?.(`[canvas] Joined canvas=${p} session=${t} gatewayKey=${r??"none"} agentId=${a??"none"}`),p}catch(e){return void i.warn?.(`[canvas] Failed to join canvas relay: ${e}`)}}export function createRenderUiHandler(e){const{stateManager:t,logger:n,writeObs:a,isCanvasActive:o,getGatewaySessionKey:i}=e;let r=0;return async(s,l)=>{if(o){const e=i?.(s);if(!o(e))return{success:!1,error:"Canvas is disabled by user. Respond with plain text instead."}}const c=l,d=c.id,p=c.root,u="panel";let m=c.components;if("string"==typeof m)try{m=JSON.parse(m)}catch{}if(!(d&&p&&Array.isArray(m)&&m.length))return{success:!1,error:"id, root, and components (array) are required"};const h=normalizeComponents(m);if(!t.validateComponentCount(h))return{success:!1,error:"Too many components (max 500)"};if(!t.checkRateLimit(d))return n.warn?.(`[canvas] Rate limited surfaceId=${d}`),a({component:"canvas",domain:"canvas",name:"canvas.rate_limited",severity:"warn",payload:{surfaceId:d}}),{success:!1,error:"Rate limited — too many updates per second"};const g=c.data;let y=e.getActiveSessionId?.(s);for(let t=0;!y&&t<3;t++)await delay(400),y=e.getActiveSessionId?.(s);if(!y&&e.waitForAgentSync){try{await e.waitForAgentSync()}catch{}y=e.getActiveSessionId?.(s)}if(!y)return n.warn?.(`[canvas] No active session for toolCallId=${s} after 3 polls, render_ui not ready`),{success:!1,retryable:!0,error:"Canvas session not ready yet (agent just connected) — retry render_ui shortly; do NOT fall back to plain text."};const f=e.getGatewaySessionKey?.(s),v=await ensureRelayConnected(e,y,s,f),x=t.has(d,v??void 0),b=Date.now(),C=t.getRelayClient();v&&C&&b-r>6e4&&C.createSnapshot(v,"Pre-agent edit").then(()=>{r=Date.now(),n.debug?.("[canvas] Pre-edit checkpoint created")}).catch(e=>n.warn?.(`[canvas] Pre-edit checkpoint failed: ${e}`)),x?t.update(d,h,v,p,g):t.create(v??`_fallback_${Date.now()}`,d,u,h,{origin:{kind:"agent"},rootComponentId:p,dataModel:g});const S=h.map(e=>e.component&&"object"==typeof e.component?Object.keys(e.component)[0]??"unknown":"unknown");a({component:"canvas",domain:"canvas",name:x?"canvas.update_sent":"canvas.surface_created",severity:"info",payload:{surfaceId:d,presentation:u,componentCount:h.length,componentTypes:S}}),n.debug?.(`[canvas] ${x?"Updated":"Created"} surface=${d} components=${h.length}`);const T={success:!0,surfaceId:d,presentation:u,isUpdate:x,activeSurfaces:v?t.getAllActive(v).map(e=>e.surfaceId):[d]};return g&&(T.dataModel=g),T}}export function createCloseUiHandler(e){const{stateManager:t,logger:n,writeObs:a}=e;return async(o,i)=>{const r=i.id;if(!r)return{success:!1,error:"id is required"};const s=t.get(r),l=s?Date.now()-s.createdAt:0,c=e.getGatewaySessionKey?.(o),d=c?t.resolveCanvasForSession(c):void 0;return t.delete(r,d),a({component:"canvas",domain:"canvas",name:"canvas.surface_closed",severity:"info",payload:{surfaceId:r,lifetime_ms:l}}),n.debug?.(`[canvas] Closed surface=${r}`),{success:!0,surfaceId:r,message:"UI closed"}}}export const CANVAS_SYSTEM_PROMPT='## Canvas UI — Google A2UI v0.8\n\n**IMPORTANT: Always use `render_ui` (not the built-in `canvas` tool) to display visual/structured content.**\n\n### How render_ui works\n\nYou output a **flat array of components** with unique IDs. Components reference each other by ID.\n\nParameters:\n- `id`: Surface ID (e.g. "sales-report"). Reuse same id to update.\n- `root`: The ID of the top-level component (usually a Column).\n- `components`: Flat array of objects. **Each object MUST have `id` and `component`**:\n `{"id": "myId", "component": {"Text": {"text": {"literalString": "Hello"}, "usageHint": "body"}}}`\n The `component` key wraps exactly ONE type key (Text, Card, Row, etc.) and its properties.\n- `data` (optional): Data model object for form two-way binding.\n\n### Rules\n- Keep chat reply to ONE short sentence when using render_ui. Do NOT repeat data shown in canvas.\n- Use render_ui for structured data, visualizations, forms, dashboards. Use plain text for explanations.\n- Canvas renders in a narrow sidebar (~400px).\n- Prefer fewer, larger components. One table is better than many small cards.\n- Use descriptive surface IDs (e.g. "sales-report", not "ui1").\n- Same `id` updates existing surface; different `id` creates new one.\n- When asked to modify existing content, reuse the original surface id from [Canvas State].\n\n### StringValue\n\nText properties use StringValue — an object with exactly one key:\n- Static text: `{"literalString": "Hello"}`\n- Data binding: `{"path": "/fieldName"}` (reads from the `data` model)\n\nShorthand: `sv("text")` means `{"literalString": "text"}` in examples below.\n\n### Component Reference\n\n**Text** — Display text with semantic sizing.\n`{Text: {text: sv("Title"), usageHint: "h2"}}`\nusageHint: "h1" | "h2" | "h3" | "h4" | "h5" | "caption" | "body"\ntext also renders Markdown (bold, italic, lists, code blocks, links).\n\n**Image** — Display an image.\n`{Image: {url: sv("https://..."), usageHint: "mediumFeature"}}`\nImage.url may be `beeos-file://<fileId>`; the renderer resolves it. Do not convert it to a signed URL.\nusageHint: "icon" | "avatar" | "smallFeature" | "mediumFeature" | "largeFeature" | "header"\nfit (optional): "contain" | "cover" | "fill" | "none" | "scale-down"\n\n**Icon** — Material icon.\n`{Icon: {name: sv("check")}}`\n\n**Video** — Embed a video.\n`{Video: {url: sv("https://youtube.com/...")}}`\n\n**AudioPlayer** — Audio playback.\n`{AudioPlayer: {url: sv("https://..."), description: sv("Episode 1")}}`\n\n**Row** — Horizontal layout. Children referenced by ID.\n`{Row: {children: {explicitList: ["child1", "child2"]}, distribution: "spaceBetween"}}`\ndistribution: "start" | "center" | "end" | "spaceBetween" | "spaceAround" | "spaceEvenly"\nalignment: "start" | "center" | "end" | "stretch"\n\n**Column** — Vertical layout. Children referenced by ID.\n`{Column: {children: {explicitList: ["child1", "child2"]}}}`\nSame distribution/alignment options as Row.\n\n**List** — Vertical or horizontal list.\n`{List: {children: {explicitList: ["item1", "item2"]}, direction: "vertical"}}`\n\n**Card** — Container with a single child.\n`{Card: {child: "contentColumnId"}}`\n\n**Tabs** — Tabbed container.\n`{Tabs: {tabItems: [{title: sv("Tab 1"), child: "panel1"}, {title: sv("Tab 2"), child: "panel2"}]}}`\n\n**Divider** — Horizontal or vertical separator.\n`{Divider: {axis: "horizontal"}}`\n\n**Modal** — Dialog with trigger.\n`{Modal: {entryPointChild: "triggerBtnId", contentChild: "dialogContentId"}}`\n\n**Button** — Clickable with action.\n`{Button: {child: "labelTextId", action: {name: "onClick", context: [{key: "id", value: {literalString: "item-1"}}]}}}`\n\n**TextField** — Text input with data binding.\n`{TextField: {label: sv("Name"), text: {path: "/name"}, type: "shortText"}}`\ntype: "shortText" | "number" | "date" | "longText"\n\n**CheckBox** — Boolean toggle.\n`{CheckBox: {label: sv("Agree"), value: {path: "/agree"}}}`\n\n**DateTimeInput** — Date/time picker.\n`{DateTimeInput: {value: {path: "/date"}, enableDate: true, enableTime: false}}`\n\n**MultipleChoice** — Selection from options.\n`{MultipleChoice: {selections: {path: "/country"}, options: [{label: sv("US"), value: "US"}, {label: sv("CN"), value: "CN"}]}}`\n\n**Slider** — Numeric range input.\n`{Slider: {value: {path: "/volume"}, minValue: 0, maxValue: 100}}`\n\n**Chart** (BeeOS extension) — Data visualization.\n`{Chart: {chartType: sv("bar"), title: sv("Sales"), labels: ["Q1","Q2","Q3"], datasets: [{label: "Revenue", data: [100,200,150]}]}}`\nchartType: bar, horizontal_bar, line, area, scatter, pie, doughnut, radar, gauge, candlestick, funnel, sparkline\ngauge uses value + max instead of labels/datasets.\ncandlestick data: [{open,high,low,close}] (full field names, NOT o/h/l/c).\n\n### Composition Patterns\n\n**Simple text display:**\n```json\n{"id":"s1","root":"r","components":[\n {"id":"t","component":{"Text":{"text":{"literalString":"Hello World"},"usageHint":"h2"}}},\n {"id":"r","component":{"Column":{"children":{"explicitList":["t"]}}}}\n]}\n```\n\n**Dashboard with KPI cards:**\n```json\n{"id":"dashboard","root":"root","components":[\n {"id":"title","component":{"Text":{"text":{"literalString":"Dashboard"},"usageHint":"h2"}}},\n {"id":"rev-val","component":{"Text":{"text":{"literalString":"$1.2M"},"usageHint":"h2"}}},\n {"id":"rev-lbl","component":{"Text":{"text":{"literalString":"Revenue"},"usageHint":"caption"}}},\n {"id":"rev-col","component":{"Column":{"children":{"explicitList":["rev-lbl","rev-val"]},"alignment":"center"}}},\n {"id":"rev-card","component":{"Card":{"child":"rev-col"}}},\n {"id":"users-val","component":{"Text":{"text":{"literalString":"8,432"},"usageHint":"h2"}}},\n {"id":"users-lbl","component":{"Text":{"text":{"literalString":"Users"},"usageHint":"caption"}}},\n {"id":"users-col","component":{"Column":{"children":{"explicitList":["users-lbl","users-val"]},"alignment":"center"}}},\n {"id":"users-card","component":{"Card":{"child":"users-col"}}},\n {"id":"kpi-row","component":{"Row":{"children":{"explicitList":["rev-card","users-card"]}}}},\n {"id":"root","component":{"Column":{"children":{"explicitList":["title","kpi-row"]}}}}\n]}\n```\n\n**Table layout (Column + Row + Text):**\n```json\n{"id":"users-table","root":"root","components":[\n {"id":"h-name","component":{"Text":{"text":{"literalString":"Name"},"usageHint":"caption"}}},\n {"id":"h-role","component":{"Text":{"text":{"literalString":"Role"},"usageHint":"caption"}}},\n {"id":"header","component":{"Row":{"children":{"explicitList":["h-name","h-role"]}}}},\n {"id":"div","component":{"Divider":{"axis":"horizontal"}}},\n {"id":"r1-name","component":{"Text":{"text":{"literalString":"Alice"},"usageHint":"body"}}},\n {"id":"r1-role","component":{"Text":{"text":{"literalString":"Engineer"},"usageHint":"body"}}},\n {"id":"row1","component":{"Row":{"children":{"explicitList":["r1-name","r1-role"]}}}},\n {"id":"r2-name","component":{"Text":{"text":{"literalString":"Bob"},"usageHint":"body"}}},\n {"id":"r2-role","component":{"Text":{"text":{"literalString":"Designer"},"usageHint":"body"}}},\n {"id":"row2","component":{"Row":{"children":{"explicitList":["r2-name","r2-role"]}}}},\n {"id":"table-col","component":{"Column":{"children":{"explicitList":["header","div","row1","row2"]}}}},\n {"id":"root","component":{"Card":{"child":"table-col"}}}\n]}\n```\n\n**Form with data binding:**\n```json\n{"id":"settings","root":"root","data":{"/name":"","/email":"","/notify":false},"components":[\n {"id":"title","component":{"Text":{"text":{"literalString":"Settings"},"usageHint":"h3"}}},\n {"id":"f-name","component":{"TextField":{"label":{"literalString":"Name"},"text":{"path":"/name"},"type":"shortText"}}},\n {"id":"f-email","component":{"TextField":{"label":{"literalString":"Email"},"text":{"path":"/email"},"type":"shortText"}}},\n {"id":"f-notify","component":{"CheckBox":{"label":{"literalString":"Email notifications"},"value":{"path":"/notify"}}}},\n {"id":"btn-text","component":{"Text":{"text":{"literalString":"Save"},"usageHint":"body"}}},\n {"id":"btn","component":{"Button":{"child":"btn-text","action":{"name":"save_settings","context":[{"key":"name","value":{"path":"/name"}},{"key":"email","value":{"path":"/email"}},{"key":"notify","value":{"path":"/notify"}}]}}}},\n {"id":"root","component":{"Column":{"children":{"explicitList":["title","f-name","f-email","f-notify","btn"]}}}}\n]}\n```\n\n**Chart:**\n```json\n{"id":"sales-chart","root":"root","components":[\n {"id":"chart","component":{"Chart":{"chartType":{"literalString":"bar"},"title":{"literalString":"Monthly Sales"},"labels":["Jan","Feb","Mar"],"datasets":[{"label":"Revenue","data":[100,200,150]}]}}},\n {"id":"root","component":{"Column":{"children":{"explicitList":["chart"]}}}}\n]}\n```\n\n### render_form\nUse `render_form` for schema-driven forms when a domain schema exists.\nParameters: `domain`, `operation`, `data`, `entityId`.\n\n### close_ui\nCloses a UI surface. Use when user moves to a new topic or explicitly dismisses.\n';export const CANVAS_TERM_MAPPING='[System Note] Always use `render_ui` (not the canvas tool) for visual/structured content. Each component in the array MUST be: {"id":"x","component":{"TypeName":{props}}} — the "component" wrapper key is required. render_ui uses Google A2UI v0.8 format: flat component array with id references. Components: Text (usageHint: h1-h5/caption/body), Image, Icon, Video, AudioPlayer, Row (horizontal layout, children.explicitList), Column (vertical layout, children.explicitList), List, Card (single child), Tabs (tabItems), Divider, Modal, Button (child + action), TextField, CheckBox, MultipleChoice, Slider, DateTimeInput, Chart (BeeOS extension: chartType, labels, datasets). StringValue: {"literalString":"text"} or {"path":"/binding"}. root param = top-level component ID. Tables: Card > Column > Row > Text. Forms: TextField/CheckBox/Slider + Button with action.context paths. Chart: chartType(bar/line/pie/area/scatter/doughnut/radar/funnel/gauge/candlestick/sparkline), labels, datasets:[{label,data,color?}]. Candlestick: [{open,high,low,close}]. Gauge: value+max. Keep chat brief when canvas is used. Use `close_ui` to dismiss. Reuse same id to update; new id for new content.';export const CANVAS_UPDATE_HINT="[Canvas Rule] Same id in render_ui = update existing surface. Different id = new surface. When a surface is referenced for editing, you MUST reuse its exact id and provide the full updated component tree.";const MAX_CONTEXT_SURFACES=8,MAX_CONTEXT_CHARS=500;export function buildActiveSurfacesContext(e,t){let n;if(!t)return null;if(n=e.getAllActive(t),0===n.length)return null;const a=[...n].sort((e,t)=>t.updatedAt-e.updatedAt).slice(0,8),o=n.length-a.length;let i=`[Canvas State] Active surfaces: ${a.map(t=>{const n=e.summarize(t.surfaceId);if(!n)return`"${t.surfaceId}"`;const a=n.types.slice(0,3).join(", "),o=n.title?`: "${n.title}"`:"";return`"${t.surfaceId}" (${a}${o})`}).join("; ")}.`;return o>0&&(i+=` ...and ${o} more.`),i+=" To modify existing content, reuse its id in render_ui.",i.length>500&&(i=i.slice(0,497)+"..."),i}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CanvasActionRouter,formatActionForAgent}from"./canvas/action-router.js";import{FormSchemaRegistry}from"./surface/form-schema-registry.js";import{FormSurfaceBuilder}from"./surface/form-surface-builder.js";import{ResourceSurfaceRenderer}from"./surface/resource-surface-renderer.js";import{CANVAS_TERM_MAPPING}from"./canvas/tools.js";let _oclSeq=0;function nextOclId(e){return`${e}-${Date.now()}-${++_oclSeq}`}const STRING_PROPS=new Set(["text","url","label","name","title","description","placeholder","icon","src","alt","value","hint","caption"]);function toPascalCase(e){return e?e[0]>="A"&&e[0]<="Z"?e:e.charAt(0).toUpperCase()+e.slice(1):"Text"}function sanitizeA2UIComponents(e){return Array.isArray(e)?e.map(e=>{if("object"!=typeof e||null===e)return e;const s=e;if("component"in s&&"object"==typeof s.component&&null!==s.component){const e=s.component;for(const[s,t]of Object.entries(e)){if("object"==typeof t&&null!==t){const n=t;for(const[e,s]of Object.entries(n))"string"==typeof s&&STRING_PROPS.has(e)&&(n[e]={literalString:s});e[s]=n}if(s[0]>="a"&&s[0]<="z"){e[toPascalCase(s)]=e[s],delete e[s]}}s.component=e}return s}):e}export class CanvasOrchestrator{canvasState=null;resourceRenderer=null;descriptorRegistry=null;actionRouter=null;formBuilder=null;schemaRegistry=null;pendingCanvasLinks=[];deps;constructor(e){this.deps=e}updateDeps(e){Object.assign(this.deps,e)}setCanvasState(e,s){this.canvasState=e;const t=async(e,s)=>{if(!this.deps.gateway?.isConnected)throw new Error("Gateway not connected");return this.deps.gateway.request(e,s)},n=()=>{const s=this.deps.getSessionIdForToolCall();if(!s)return;const t=this.deps.state.sessions.get(s),n=t?.gatewaySessionKey;return n?e.resolveCanvasForSession(n):void 0},a=s?.schemaRegistry??new FormSchemaRegistry,i=new FormSurfaceBuilder({canvasState:e,gatewayRequest:t,resolveCanvasId:n,logger:this.deps.logger});this.formBuilder=i,this.schemaRegistry=a,this.descriptorRegistry=s?.descriptorRegistry??null,this.resourceRenderer=new ResourceSurfaceRenderer({canvasState:e,gatewayRequest:t,schemaRegistry:a,formBuilder:i,resolveCanvasId:n,logger:this.deps.logger}),this.actionRouter=new CanvasActionRouter({stateManager:e,logger:this.deps.logger,writeObs:e=>this.deps.writeObs(e),forwardToAgent:e=>this.forwardActionToAgent(e),emitActionAsUserMessage:e=>{const s=this.deps.state.resolveSessionFromParams(e);s?this.emitCanvasActionAsUserMessage(s.sessionId,e):this.deps.logger.warn?.("[canvas-orch] emitActionAsUserMessage: session not found, pill skipped",{surfaceId:e.surfaceId,sessionId:e.sessionId})}})}wireRelayActionHandler(){const e=this.canvasState?.getRelayClient();e?(e.onAction(e=>{this.handleRelayAction(e)}),this.deps.logger.debug?.("[canvas-orch] Canvas Relay action handler wired")):this.deps.logger.warn?.("[canvas-orch] wireRelayActionHandler called but no relay client available")}isCanvasActive(e){if(!e)return!1;const s=this.deps.state.sessions.get(e);return!0===s?.canvasActive}isCanvasActiveForGatewayKey(e){const s=this.deps.state.sessionsByGatewayKey.get(e);return!0===s?.canvasActive}onSessionLoaded(e,s,t){if(!this.deps.config.canvasEnabled)return;const n=this.canvasState?.getRelayClient();if(!n)return this.pendingCanvasLinks.push({acpSessionId:e,gatewaySessionKey:s}),void this.deps.logger.info?.(`[canvas-orch] Relay not ready, queued canvas link: acpSid=${e} gwKey=${s}`);this.ensureCanvasForSession(e,s)}onSessionDeleted(e){this.canvasState?.removeSession(e)}onSessionCleared(e,s){const t=this.canvasState?.resolveCanvasForSession(s);t&&(this.canvasState.clear(t),this.actionRouter?.reset())}onPromptStart(){this.actionRouter?.clearPending()}async onPromptComplete(e){try{await(this.actionRouter?.drainPending())}catch(e){this.deps.logger.warn?.(`[canvas-orch] Drain pending canvas actions failed: ${e instanceof Error?e.message:e}`)}}onPromptFailed(){this.actionRouter?.clearPending()}flushPendingCanvasLinks(){const e=this.pendingCanvasLinks.splice(0);if(0===e.length)return;const s=new Set,t=e.filter(({gatewaySessionKey:e})=>!s.has(e)&&(s.add(e),!this.canvasState?.resolveCanvasForSession(e)));if(0!==t.length){this.deps.logger.info?.(`[canvas-orch] Flushing ${t.length} pending canvas link(s)`);for(const{acpSessionId:e,gatewaySessionKey:s}of t)this.ensureCanvasForSession(e,s)}}onRelayReconnected(){this.deps.logger.info?.("[canvas-orch] Relay reconnected — retrying pending canvas links"),this.flushPendingCanvasLinks()}async handleSlashCommand(e){const s=this.descriptorRegistry?.getBySlashCommand(e);return!(!s||!this.resourceRenderer)&&(await this.resourceRenderer.render(s,"inline"),!0)}async enrichMessageWithCanvasContext(e,s,t){if(!this.canvasState)return e;if(t.has(s.split(":").slice(0,2).join(":"))||t.has(s))return e;try{let t=this.canvasState.resolveCanvasForSession(s);if(!t){const e=this.canvasState.getRelayClient();if(e)try{t=await e.ensureCanvas(s),this.canvasState.registerSession(s,t)}catch{}}if(t){let s=this.canvasState.buildContextForCanvas(t);s||(await this.canvasState.lazyLoadCanvas(t),s=this.canvasState.buildContextForCanvas(t));return`${CANVAS_TERM_MAPPING}\n\n${s??"[Canvas] Canvas panel is available. Use render_ui for structured/visual content."}\n\n${e}`}}catch(e){this.deps.logger.warn?.(`[canvas-orch] Canvas context injection failed: ${e instanceof Error?e.message:String(e)}`)}return e}handleCanvasNotification(e,s){if(this.canvasState){if("canvas/toggle"===e){const e=s,t=!1!==e.enabled,n=this.deps.state.resolveSessionFromParams(e);if(n&&(n.canvasActive=t,t&&(n.canvasPromptInjected=!1,n.sessionId))){const e=n.sessionId,s=n.gatewaySessionKey,t=n.agentId,a=this.canvasState?.getRelayClient();if(a){const i=this.deps.resolvePlatformAgentId(t??"")??n.platformAgentId,o=s&&s!==e?e:void 0;a.ensureCanvas(s??e,{agentId:i,linkSessionId:o}).catch(e=>{this.deps.logger.warn?.(`[canvas-orch] Failed to pre-create canvas on toggle: ${e}`)})}}this.deps.logger.info?.(`[canvas-orch] Canvas toggled: ${t}`),this.deps.writeObs({component:"canvas",domain:"canvas",name:"canvas.toggle",severity:"info",payload:{enabled:t}})}else if("canvas/clear"===e){const e=s,t=this.deps.state.resolveSessionFromParams(e),n=t?this.canvasState.resolveCanvasForSession(t.gatewaySessionKey):void 0,a=n?this.canvasState.getAllActive(n).length:0;n&&this.canvasState.clear(n),this.actionRouter?.reset(),this.deps.logger.info?.(`[canvas-orch] Canvas cleared (${a} surfaces removed)`),this.deps.writeObs({component:"canvas",domain:"canvas",name:"canvas.cleared",severity:"info"})}}else this.deps.logger.warn?.(`[canvas-orch] Canvas notification ${e} ignored — canvasState not initialized`)}handleOpenClawCanvasEvent(e){if(!this.canvasState||!e)return;const s=e,t=s.action;if("a2ui_push"===t||"surface_update"===t){const e=String(s.surfaceId??nextOclId("openclaw")),t=s.components;if(t&&Array.isArray(t)){const n=sanitizeA2UIComponents(t),a=s.canvasId?String(s.canvasId):void 0;this.canvasState.has(e,a)?this.canvasState.update(e,n,a):this.canvasState.create(a??nextOclId("_openclaw"),e,"inline",n,{origin:{kind:"openclaw"}}),this.deps.logger.debug?.(`[canvas-orch] OpenClaw canvas → state + relay (surfaceId=${e})`)}}else if("navigate"===t||"url_open"===t){const e=String(s.url??"");if(e){const t=nextOclId("openclaw-nav"),n=String(s.canvasId??nextOclId("_openclaw_nav")),a=[{id:`${t}-embed`,component:{WebEmbed:{url:{literalString:e},title:{literalString:String(s.title??e)}}}}];this.canvasState.create(n,t,"inline",a,{origin:{kind:"openclaw"}})}}else this.deps.logger.debug?.(`[canvas-orch] Unhandled OpenClaw canvas action: ${t}`)}ensureCanvasForSession(e,s){const t=this.canvasState?.getRelayClient();if(!t)return;const n=e!==s?e:void 0;t.ensureCanvas(s,{linkSessionId:n}).then(async t=>{this.canvasState?.registerSession(s,t),await(this.canvasState?.joinCanvas(t,s)),this.deps.logger.info?.(`[canvas-orch] Canvas ensured: canvas=${t} acpSid=${e} gwKey=${s}`)}).catch(t=>{this.deps.logger.warn?.(`[canvas-orch] Failed to ensure canvas: acpSid=${e} gwKey=${s} err=${t}`),this.pendingCanvasLinks.push({acpSessionId:e,gatewaySessionKey:s})})}async forwardActionToAgent(e){const s=this.deps.state.resolveSessionFromParams(e);if(!s)return void this.deps.logger.warn?.("[canvas-orch] forwardActionToAgent dropped — no session resolved");if(this.emitCanvasActionAsUserMessage(s.sessionId,e),!this.deps.gateway?.isConnected)return void this.deps.logger.warn?.("[canvas-orch] forwardActionToAgent: gateway not connected, pill sent but agent forward skipped");if(s.currentRunId&&!s.promptDone)return this.actionRouter?.enqueue(e),void this.deps.logger.info?.(`[canvas-orch] Agent busy, canvas action queued (runId=${s.currentRunId})`);this.deps.state.resetForNewRun(s,s.sessionId,this.deps.transport);const t=this.canvasState?.summarize(e.surfaceId??""),n=formatActionForAgent(e,t??void 0);try{const e=await this.deps.gateway.agentSend(s.gatewaySessionKey,n,this.deps.config.gateway.agentId||this.deps.getDefaultAgentId());s.currentRunId=e.runId,s.assistantStreamStartedAt=Date.now(),this.deps.state.promptsByRunId.set(e.runId,s)}catch(t){this.deps.logger.warn?.(`[canvas-orch] Agent forward failed: ${t instanceof Error?t.message:t}`),this.deps.transport.sendSessionUpdate(s.sessionId,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`> _User interacted with "${e.userAction?.name??"unknown"}" on canvas._`}})}}emitCanvasActionAsUserMessage(e,s){const t=s.userAction?.name??"unknown",n=`Clicked "${t}"`;this.deps.transport.sendSessionUpdate(e,{sessionUpdate:"user_message_chunk",content:{type:"text",text:n},metadata:{type:"canvas_action",surfaceId:s.surfaceId,actionName:t,sourceComponentId:s.userAction?.sourceComponentId,actionPayload:s.userAction?.context,actionTimestamp:s.userAction?.timestamp}}),this.deps.logger.info?.(`[canvas-orch] Emitted canvas action pill: session=${e} action=${t} surface=${s.surfaceId}`)}handleRelayAction(e){if(!this.canvasState||!this.actionRouter)return void this.deps.logger.warn?.("[canvas-orch] Relay action ignored — canvas not initialized");const{canvasId:s,surfaceId:t,userAction:n,requestId:a,senderClientId:i}=e,o=this.canvasState.resolveSessionForCanvas(s);if(!o)return this.deps.logger.warn?.(`[canvas-orch] Relay action ignored — no session for canvas=${s}`),void this.sendRelayActionError(s,a,i,"no_session");const r=this.deps.state.findSessionByKey(o);if(!r)return this.deps.logger.warn?.(`[canvas-orch] Relay action ignored — session not found for gatewayKey=${o}`),void this.sendRelayActionError(s,a,i,"no_session");const c={surfaceId:t,userAction:{name:n.name,sourceComponentId:n.sourceComponentId,timestamp:n.timestamp,context:n.context},sessionId:r.sessionId};this.actionRouter.route(c,s).then(()=>{this.deps.logger.info?.(`[canvas-orch] Relay action routed: surface=${t} request=${a}`),this.sendRelayActionResult(s,a,i,"ok")}).catch(e=>{this.deps.logger.warn?.(`[canvas-orch] Relay action routing failed: ${e instanceof Error?e.message:e}`),this.sendRelayActionError(s,a,i,"processing_failed")})}sendRelayActionResult(e,s,t,n){this.canvasState?.getRelayClient()?.sendActionResult({canvasId:e,requestId:s,targetClientId:t,status:n})}sendRelayActionError(e,s,t,n){this.canvasState?.getRelayClient()?.sendActionError({canvasId:e,requestId:s,targetClientId:t,error:n})}destroy(){this.canvasState?.destroy(),this.actionRouter?.reset(),this.pendingCanvasLinks.length=0,this.canvasState=null,this.actionRouter=null,this.resourceRenderer=null,this.descriptorRegistry=null,this.formBuilder=null,this.schemaRegistry=null}}
|
|
1
|
+
import{CanvasActionRouter,formatActionForAgent}from"./canvas/action-router.js";import{FormSchemaRegistry}from"./surface/form-schema-registry.js";import{FormSurfaceBuilder}from"./surface/form-surface-builder.js";import{ResourceSurfaceRenderer}from"./surface/resource-surface-renderer.js";import{CANVAS_TERM_MAPPING}from"./canvas/tools.js";import{extractBeeosConversationIdFromSessionKey}from"./runtime/openclaw-session-key-resolution.js";let _oclSeq=0;function nextOclId(e){return`${e}-${Date.now()}-${++_oclSeq}`}const STRING_PROPS=new Set(["text","url","label","name","title","description","placeholder","icon","src","alt","value","hint","caption"]);function toPascalCase(e){return e?e[0]>="A"&&e[0]<="Z"?e:e.charAt(0).toUpperCase()+e.slice(1):"Text"}function sanitizeA2UIComponents(e){return Array.isArray(e)?e.map(e=>{if("object"!=typeof e||null===e)return e;const s=e;if("component"in s&&"object"==typeof s.component&&null!==s.component){const e=s.component;for(const[s,n]of Object.entries(e)){if("object"==typeof n&&null!==n){const a=n;for(const[e,s]of Object.entries(a))"string"==typeof s&&STRING_PROPS.has(e)&&(a[e]={literalString:s});e[s]=a}if(s[0]>="a"&&s[0]<="z"){e[toPascalCase(s)]=e[s],delete e[s]}}s.component=e}return s}):e}export class CanvasOrchestrator{canvasState=null;resourceRenderer=null;descriptorRegistry=null;actionRouter=null;formBuilder=null;schemaRegistry=null;pendingCanvasLinks=[];deps;constructor(e){this.deps=e}updateDeps(e){Object.assign(this.deps,e)}setCanvasState(e,s){this.canvasState=e;const n=async(e,s)=>{if(!this.deps.gateway?.isConnected)throw new Error("Gateway not connected");return this.deps.gateway.request(e,s)},a=()=>{const s=this.deps.getSessionIdForToolCall();if(!s)return;const n=this.deps.state.sessions.get(s),a=n?.gatewaySessionKey;return a?e.resolveCanvasForSession(a):void 0},t=s?.schemaRegistry??new FormSchemaRegistry,o=new FormSurfaceBuilder({canvasState:e,gatewayRequest:n,resolveCanvasId:a,logger:this.deps.logger});this.formBuilder=o,this.schemaRegistry=t,this.descriptorRegistry=s?.descriptorRegistry??null,this.resourceRenderer=new ResourceSurfaceRenderer({canvasState:e,gatewayRequest:n,schemaRegistry:t,formBuilder:o,resolveCanvasId:a,logger:this.deps.logger}),this.actionRouter=new CanvasActionRouter({stateManager:e,logger:this.deps.logger,writeObs:e=>this.deps.writeObs(e),forwardToAgent:e=>this.forwardActionToAgent(e),emitActionAsUserMessage:e=>{const s=this.deps.state.resolveSessionFromParams(e);s?this.emitCanvasActionAsUserMessage(s.sessionId,e):this.deps.logger.warn?.("[canvas-orch] emitActionAsUserMessage: session not found, pill skipped",{surfaceId:e.surfaceId,sessionId:e.sessionId})}})}wireRelayActionHandler(){const e=this.canvasState?.getRelayClient();e?(e.onAction(e=>{this.handleRelayAction(e)}),e.onCanvasControl(e=>{this.handleRelayCanvasControl(e)}),this.deps.logger.debug?.("[canvas-orch] Canvas Relay action+control handlers wired")):this.deps.logger.warn?.("[canvas-orch] wireRelayActionHandler called but no relay client available")}handleRelayCanvasControl(e){if("canvas.toggle"===e.type){const s=!0===e.visible||!0===e.enabled,n={enabled:s,canvasId:e.canvasId,...e.sessionId?{sessionId:e.sessionId}:{}};if(e.sessionId?this.deps.state.resolveSessionFromParams(n):void 0)return void this.handleCanvasNotification("canvas/toggle",n);let a=0;for(const e of this.deps.state.sessionsByGatewayKey.values())e.canvasActive=s,s&&(e.canvasPromptInjected=!1),a++;for(const e of this.deps.state.sessions.values())e.canvasActive=s,s&&(e.canvasPromptInjected=!1),a++;if(s&&e.sessionId){const s=e.sessionId;for(const e of this.deps.state.sessionsByGatewayKey.values()){if(extractBeeosConversationIdFromSessionKey(e.gatewaySessionKey)===s||e.sessionId===s){this.ensureCanvasForSession(s,e.gatewaySessionKey);break}}}return void this.deps.logger.info?.(`[canvas-orch] Relay canvas.toggle enabled=${s} fan-out sessions≈${a} canvasId=${e.canvasId}`)}"canvas.dimensions"!==e.type?"canvas.reference"!==e.type?"canvas.clear"===e.type&&this.handleCanvasNotification("canvas/clear",{canvasId:e.canvasId,...e.sessionId?{sessionId:e.sessionId}:{}}):this.handleCanvasNotification("canvas/reference",{canvasId:e.canvasId,...e.sessionId?{sessionId:e.sessionId}:{},surfaceId:e.surfaceId??null}):this.handleCanvasNotification("canvas/dimensions",{canvasId:e.canvasId,...e.sessionId?{sessionId:e.sessionId}:{},width:e.width,height:e.height,...void 0===e.devicePixelRatio?{}:{devicePixelRatio:e.devicePixelRatio}})}isCanvasActive(e){if(!e)return!1;const s=this.deps.state.sessions.get(e);return!0===s?.canvasActive}isCanvasActiveForGatewayKey(e){const s=this.deps.state.sessionsByGatewayKey.get(e);return!0===s?.canvasActive}onSessionLoaded(e,s,n){if(!this.deps.config.canvasEnabled)return;const a=this.canvasState?.getRelayClient();if(!a)return this.pendingCanvasLinks.push({acpSessionId:e,gatewaySessionKey:s}),void this.deps.logger.info?.(`[canvas-orch] Relay not ready, queued canvas link: acpSid=${e} gwKey=${s}`);this.ensureCanvasForSession(e,s)}onSessionDeleted(e){this.canvasState?.removeSession(e)}onSessionCleared(e,s){const n=this.canvasState?.resolveCanvasForSession(s);n&&(this.canvasState.clear(n),this.actionRouter?.reset())}onPromptStart(){this.actionRouter?.clearPending()}async onPromptComplete(e){try{await(this.actionRouter?.drainPending())}catch(e){this.deps.logger.warn?.(`[canvas-orch] Drain pending canvas actions failed: ${e instanceof Error?e.message:e}`)}}onPromptFailed(){this.actionRouter?.clearPending()}flushPendingCanvasLinks(){const e=this.pendingCanvasLinks.splice(0);if(0===e.length)return;const s=new Set,n=e.filter(({gatewaySessionKey:e})=>!s.has(e)&&(s.add(e),!this.canvasState?.resolveCanvasForSession(e)));if(0!==n.length){this.deps.logger.info?.(`[canvas-orch] Flushing ${n.length} pending canvas link(s)`);for(const{acpSessionId:e,gatewaySessionKey:s}of n)this.ensureCanvasForSession(e,s)}}onRelayReconnected(){this.deps.logger.info?.("[canvas-orch] Relay reconnected — retrying pending canvas links"),this.flushPendingCanvasLinks()}async handleSlashCommand(e){const s=this.descriptorRegistry?.getBySlashCommand(e);return!(!s||!this.resourceRenderer)&&(await this.resourceRenderer.render(s,"inline"),!0)}async enrichMessageWithCanvasContext(e,s,n){if(!this.canvasState)return e;if(n.has(s.split(":").slice(0,2).join(":"))||n.has(s))return e;try{let n=this.canvasState.resolveCanvasForSession(s);if(!n){const e=this.canvasState.getRelayClient();if(e)try{const a=extractBeeosConversationIdFromSessionKey(s);n=await e.ensureCanvas(s,{...a?{linkSessionId:a}:{}}),this.canvasState.registerSession(s,n)}catch(e){this.deps.logger.warn?.(`[canvas-orch] ensureCanvas for prompt inject failed (session may not be linked yet): ${e instanceof Error?e.message:String(e)}`)}}if(n){let s=this.canvasState.buildContextForCanvas(n);s||(await this.canvasState.lazyLoadCanvas(n),s=this.canvasState.buildContextForCanvas(n));return`${CANVAS_TERM_MAPPING}\n\n${s??"[Canvas] Canvas panel is available. Use render_ui for structured/visual content."}\n\n${e}`}}catch(e){this.deps.logger.warn?.(`[canvas-orch] Canvas context injection failed: ${e instanceof Error?e.message:String(e)}`)}return e}handleCanvasNotification(e,s){if(this.canvasState){if("canvas/toggle"===e){const e=s,n=!1!==e.enabled,a=this.deps.state.resolveSessionFromParams(e);if(a&&(a.canvasActive=n,n&&(a.canvasPromptInjected=!1,a.sessionId))){const e=a.sessionId,s=a.gatewaySessionKey,n=a.agentId,t=this.canvasState?.getRelayClient();if(t){const o=this.deps.resolvePlatformAgentId(n??"")??a.platformAgentId,i=s&&s!==e?e:void 0;t.ensureCanvas(s??e,{agentId:o,linkSessionId:i}).catch(e=>{this.deps.logger.warn?.(`[canvas-orch] Failed to pre-create canvas on toggle: ${e}`)})}}this.deps.logger.info?.(`[canvas-orch] Canvas toggled: ${n}`),this.deps.writeObs({component:"canvas",domain:"canvas",name:"canvas.toggle",severity:"info",payload:{enabled:n}})}else if("canvas/clear"===e){const e=s,n=this.deps.state.resolveSessionFromParams(e),a=n?this.canvasState.resolveCanvasForSession(n.gatewaySessionKey):void 0,t=a?this.canvasState.getAllActive(a).length:0;a&&this.canvasState.clear(a),this.actionRouter?.reset(),this.deps.logger.info?.(`[canvas-orch] Canvas cleared (${t} surfaces removed)`),this.deps.writeObs({component:"canvas",domain:"canvas",name:"canvas.cleared",severity:"info"})}}else this.deps.logger.warn?.(`[canvas-orch] Canvas notification ${e} ignored — canvasState not initialized`)}handleOpenClawCanvasEvent(e){if(!this.canvasState||!e)return;const s=e,n=s.action;if("a2ui_push"===n||"surface_update"===n){const e=String(s.surfaceId??nextOclId("openclaw")),n=s.components;if(n&&Array.isArray(n)){const a=sanitizeA2UIComponents(n),t=s.canvasId?String(s.canvasId):void 0;this.canvasState.has(e,t)?this.canvasState.update(e,a,t):this.canvasState.create(t??nextOclId("_openclaw"),e,"inline",a,{origin:{kind:"openclaw"}}),this.deps.logger.debug?.(`[canvas-orch] OpenClaw canvas → state + relay (surfaceId=${e})`)}}else if("navigate"===n||"url_open"===n){const e=String(s.url??"");if(e){const n=nextOclId("openclaw-nav"),a=String(s.canvasId??nextOclId("_openclaw_nav")),t=[{id:`${n}-embed`,component:{WebEmbed:{url:{literalString:e},title:{literalString:String(s.title??e)}}}}];this.canvasState.create(a,n,"inline",t,{origin:{kind:"openclaw"}})}}else this.deps.logger.debug?.(`[canvas-orch] Unhandled OpenClaw canvas action: ${n}`)}ensureCanvasForSession(e,s){const n=this.canvasState?.getRelayClient();if(!n)return;const a=extractBeeosConversationIdFromSessionKey(s)??(e!==s?e:void 0);n.ensureCanvas(s,{linkSessionId:a}).then(async n=>{this.canvasState?.registerSession(s,n),await(this.canvasState?.joinCanvas(n,s)),this.deps.logger.info?.(`[canvas-orch] Canvas ensured: canvas=${n} acpSid=${e} gwKey=${s} linkSessionId=${a??"none"}`)}).catch(n=>{this.deps.logger.warn?.(`[canvas-orch] Failed to ensure canvas: acpSid=${e} gwKey=${s} linkSessionId=${a??"none"} err=${n}`),this.pendingCanvasLinks.push({acpSessionId:e,gatewaySessionKey:s})})}async forwardActionToAgent(e){const s=this.deps.state.resolveSessionFromParams(e);if(!s)return void this.deps.logger.warn?.("[canvas-orch] forwardActionToAgent dropped — no session resolved");if(this.emitCanvasActionAsUserMessage(s.sessionId,e),!this.deps.gateway?.isConnected)return void this.deps.logger.warn?.("[canvas-orch] forwardActionToAgent: gateway not connected, pill sent but agent forward skipped");if(s.currentRunId&&!s.promptDone)return this.actionRouter?.enqueue(e),void this.deps.logger.info?.(`[canvas-orch] Agent busy, canvas action queued (runId=${s.currentRunId})`);this.deps.state.resetForNewRun(s,s.sessionId,this.deps.transport);const n=this.canvasState?.summarize(e.surfaceId??""),a=formatActionForAgent(e,n??void 0);try{const e=await this.deps.gateway.agentSend(s.gatewaySessionKey,a,this.deps.config.gateway.agentId||this.deps.getDefaultAgentId());s.currentRunId=e.runId,s.assistantStreamStartedAt=Date.now(),this.deps.state.promptsByRunId.set(e.runId,s)}catch(n){this.deps.logger.warn?.(`[canvas-orch] Agent forward failed: ${n instanceof Error?n.message:n}`),this.deps.transport.sendSessionUpdate(s.sessionId,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`> _User interacted with "${e.userAction?.name??"unknown"}" on canvas._`}})}}emitCanvasActionAsUserMessage(e,s){const n=s.userAction?.name??"unknown",a=`Clicked "${n}"`;this.deps.transport.sendSessionUpdate(e,{sessionUpdate:"user_message_chunk",content:{type:"text",text:a},metadata:{type:"canvas_action",surfaceId:s.surfaceId,actionName:n,sourceComponentId:s.userAction?.sourceComponentId,actionPayload:s.userAction?.context,actionTimestamp:s.userAction?.timestamp}}),this.deps.logger.info?.(`[canvas-orch] Emitted canvas action pill: session=${e} action=${n} surface=${s.surfaceId}`)}handleRelayAction(e){if(!this.canvasState||!this.actionRouter)return void this.deps.logger.warn?.("[canvas-orch] Relay action ignored — canvas not initialized");const{canvasId:s,surfaceId:n,userAction:a,requestId:t,senderClientId:o}=e,i=this.canvasState.resolveSessionForCanvas(s);if(!i)return this.deps.logger.warn?.(`[canvas-orch] Relay action ignored — no session for canvas=${s}`),void this.sendRelayActionError(s,t,o,"no_session");const r=this.deps.state.findSessionByKey(i);if(!r)return this.deps.logger.warn?.(`[canvas-orch] Relay action ignored — session not found for gatewayKey=${i}`),void this.sendRelayActionError(s,t,o,"no_session");const c={surfaceId:n,userAction:{name:a.name,sourceComponentId:a.sourceComponentId,timestamp:a.timestamp,context:a.context},sessionId:r.sessionId};this.actionRouter.route(c,s).then(()=>{this.deps.logger.info?.(`[canvas-orch] Relay action routed: surface=${n} request=${t}`),this.sendRelayActionResult(s,t,o,"ok")}).catch(e=>{this.deps.logger.warn?.(`[canvas-orch] Relay action routing failed: ${e instanceof Error?e.message:e}`),this.sendRelayActionError(s,t,o,"processing_failed")})}sendRelayActionResult(e,s,n,a){this.canvasState?.getRelayClient()?.sendActionResult({canvasId:e,requestId:s,targetClientId:n,status:a})}sendRelayActionError(e,s,n,a){this.canvasState?.getRelayClient()?.sendActionError({canvasId:e,requestId:s,targetClientId:n,error:a})}destroy(){this.canvasState?.destroy(),this.actionRouter?.reset(),this.pendingCanvasLinks.length=0,this.canvasState=null,this.actionRouter=null,this.resourceRenderer=null,this.descriptorRegistry=null,this.formBuilder=null,this.schemaRegistry=null}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{RuntimeCommandError}from"./runtime-command-dispatcher.js";export function openClawKeyMatchesConversation(e,n){return!(!n||!e)&&(e===n||(e.endsWith(`:ctx-${n}`)||e.endsWith(`:ch-${n}`)||e.endsWith(`:${n}`)))}export function preferInteractiveOpenClawSessionKey(e){if(0===e.length)return;if(1===e.length)return e[0];const n=e.filter(e=>e.includes(":beeos-conversation:"));return 1===n.length?n[0]:void 0}export function resolveLiveOpenClawSessionKey(e,n){if(!e.trim()||e.trim()!==e)throw new RuntimeCommandError("INVALID_PARAMS","runtimeSessionKey must be a non-empty trimmed string");const t=[],
|
|
1
|
+
import{RuntimeCommandError}from"./runtime-command-dispatcher.js";export function openClawKeyMatchesConversation(e,n){return!(!n||!e)&&(e===n||(e.endsWith(`:ctx-${n}`)||e.endsWith(`:ch-${n}`)||e.endsWith(`:${n}`)))}export function extractBeeosConversationIdFromSessionKey(e){if(!e)return;const n="[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}",t=e.match(new RegExp(`:(?:ctx|ch)-(${n})$`));if(t?.[1])return t[1];const r=e.match(new RegExp(`^agent:[^:]+:(${n})$`));return r?.[1]?r[1]:new RegExp(`^${n}$`).test(e)?e:void 0}export function preferInteractiveOpenClawSessionKey(e){if(0===e.length)return;if(1===e.length)return e[0];const n=e.filter(e=>e.includes(":beeos-conversation:"));return 1===n.length?n[0]:void 0}export function resolveLiveOpenClawSessionKey(e,n){if(!e.trim()||e.trim()!==e)throw new RuntimeCommandError("INVALID_PARAMS","runtimeSessionKey must be a non-empty trimmed string");const t=[],r=[],s=[];for(const o of n)o.gatewaySessionKey===e&&e.startsWith("agent:")&&t.push(o.gatewaySessionKey),o.channelId===e?r.push(o.gatewaySessionKey):o.gatewaySessionKey!==e&&openClawKeyMatchesConversation(o.gatewaySessionKey,e)&&s.push(o.gatewaySessionKey);const o=(n,t)=>{const r=[...new Set(n)],s=preferInteractiveOpenClawSessionKey(r);if(s)return s;if(0===r.length)throw new RuntimeCommandError("INVALID_PARAMS",`no live local session for runtimeSessionKey=${e}; refusing OpenClaw sessions.patch upsert`);throw new RuntimeCommandError("INVALID_PARAMS",`ambiguous live OpenClaw sessions for runtimeSessionKey=${e} (${t}): ${r.join(",")}`)};return t.length>0?o(t,"gatewaySessionKey"):r.length>0?o(r,"channelId"):o(s,"key-pattern")}export function openClawSessionKeysFromList(e){if(!e||"object"!=typeof e||Array.isArray(e))return new Set;const n=e.sessions;if(!Array.isArray(n))return new Set;const t=new Set;for(const e of n){if(!e||"object"!=typeof e||Array.isArray(e))continue;const n=e,r=n.sessionKey??n.key??n.id??n.name;"string"==typeof r&&r.trim()&&r.trim()===r&&t.add(r)}return t}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "beeos-claw",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.42",
|
|
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>",
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
"dist/",
|
|
21
21
|
"scripts/runtime-blackbox-worker.mjs",
|
|
22
22
|
"scripts/runtime-blackbox-worker-main.mjs",
|
|
23
|
+
"scripts/runtime-blackbox-worker-lease.mjs",
|
|
23
24
|
"scripts/runtime-blackbox-worker-lifecycle.mjs",
|
|
24
25
|
"scripts/runtime-poison-blackbox.mjs",
|
|
25
26
|
"scripts/runtime-poison-blackbox-lib.mjs",
|
|
@@ -43,7 +44,7 @@
|
|
|
43
44
|
"verify:release-types-pin": "node ./scripts/verify-release-types-pin.mjs",
|
|
44
45
|
"verify:release-package": "npm run build:release && node ./scripts/verify-release-package.mjs",
|
|
45
46
|
"test:release-workflows": "node ./scripts/test-release-workflows.mjs && node --test ./scripts/verify-tag-release-request.test.mjs ./scripts/openclaw-release-authority.test.mjs ./scripts/openclaw-release-dispatch.test.mjs ./scripts/openclaw-release-finalizer.test.mjs ./scripts/openclaw-release-completion.test.mjs ./scripts/openclaw-release-recovery.test.mjs ./scripts/verify-openclaw-dispatch-contract.test.mjs ./scripts/verify-promotion-evidence.test.mjs ./scripts/verify-package-equivalence.test.mjs ./scripts/verify-package-equivalence.e2e.test.mjs",
|
|
46
|
-
"check:runtime-blackbox-worker": "node --check ./scripts/runtime-blackbox-worker.mjs && node --check ./scripts/runtime-blackbox-worker-main.mjs && node --check ./scripts/runtime-blackbox-worker-lifecycle.mjs && node --test ./scripts/runtime-blackbox-worker-lifecycle.test.mjs ./scripts/runtime-blackbox-worker-launcher.test.mjs",
|
|
47
|
+
"check:runtime-blackbox-worker": "node --check ./scripts/runtime-blackbox-worker.mjs && node --check ./scripts/runtime-blackbox-worker-main.mjs && node --check ./scripts/runtime-blackbox-worker-lease.mjs && node --check ./scripts/runtime-blackbox-worker-lifecycle.mjs && node --test ./scripts/runtime-blackbox-worker-lease.test.mjs ./scripts/runtime-blackbox-worker-lifecycle.test.mjs ./scripts/runtime-blackbox-worker-launcher.test.mjs",
|
|
47
48
|
"prepublishOnly": "npm run verify:release-types-pin",
|
|
48
49
|
"prepack": "npm run check:runtime-blackbox-worker && npm run build:release && node ./scripts/mcp-state-blackbox.mjs && node ./scripts/verify-release-package.mjs",
|
|
49
50
|
"runtime:blackbox-worker": "npm run build && node ./scripts/runtime-blackbox-worker.mjs",
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bind the SDK delivery lease to the same durable journal lineage that the
|
|
3
|
+
* runtime consumer factory was created with. The Message SDK treats lineage
|
|
4
|
+
* as part of the lease fence; omitting it makes every valid delivery appear
|
|
5
|
+
* to come from a changed lease.
|
|
6
|
+
*/
|
|
7
|
+
export function bindRuntimeBlackboxLease(input) {
|
|
8
|
+
return {
|
|
9
|
+
instanceId: input.instanceId,
|
|
10
|
+
leaseId: input.leaseId,
|
|
11
|
+
handlerIdentity: input.handlerIdentity,
|
|
12
|
+
runtimeEpoch: input.runtimeEpoch,
|
|
13
|
+
runtimeLeaseCredential: input.runtimeLeaseCredential,
|
|
14
|
+
leaseExpiresAt: input.leaseExpiresAt,
|
|
15
|
+
journalStoreId: input.journalStoreId,
|
|
16
|
+
journalGeneration: input.journalGeneration,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
@@ -21,6 +21,7 @@ import { createRuntimeBlackboxReceipt } from "./runtime-security.mjs";
|
|
|
21
21
|
import { runRuntimePoisonBlackbox } from "./runtime-poison-blackbox-lib.mjs";
|
|
22
22
|
import { closeRuntimeResources, createRuntimeBlackboxCompletionGate, selectRuntimeError, startGatewayWithinDeadline, withinDeadline } from
|
|
23
23
|
"./runtime-blackbox-worker-lifecycle.mjs";
|
|
24
|
+
import { bindRuntimeBlackboxLease } from "./runtime-blackbox-worker-lease.mjs";
|
|
24
25
|
|
|
25
26
|
export async function main() {
|
|
26
27
|
const contractPath = requiredEnvironment("RUNTIME_BLACKBOX_CONTRACT_FILE");
|
|
@@ -129,11 +130,14 @@ export async function main() {
|
|
|
129
130
|
let consumer;
|
|
130
131
|
let primaryError;
|
|
131
132
|
let releaseGatewayTransportObserver;
|
|
132
|
-
const runtimeLease = () => ({
|
|
133
|
+
const runtimeLease = () => bindRuntimeBlackboxLease({
|
|
134
|
+
instanceId, leaseId: nonempty(authority.leaseId, "authority.leaseId"),
|
|
133
135
|
handlerIdentity: nonempty(authority.handlerIdentity, "authority.handlerIdentity"),
|
|
134
136
|
runtimeEpoch: decimal(authority.runtimeEpoch, "authority.runtimeEpoch"),
|
|
135
137
|
runtimeLeaseCredential: nonempty(authority.runtimeLeaseCredential, "authority.runtimeLeaseCredential"),
|
|
136
|
-
leaseExpiresAt: new Date(Number(leaseClaims.exp) * 1_000).toISOString()
|
|
138
|
+
leaseExpiresAt: new Date(Number(leaseClaims.exp) * 1_000).toISOString(),
|
|
139
|
+
journalStoreId, journalGeneration,
|
|
140
|
+
});
|
|
137
141
|
try {
|
|
138
142
|
releaseGatewayTransportObserver = await startGatewayWithinDeadline(gateway, deadline);
|
|
139
143
|
const identities = new FileRuntimeAgentIdentityRegistry(`${statePrefix}-identities.json`);
|