beeos-claw 0.5.86 → 0.5.88

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- 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{SESSION_RECOVERY_REQUIRED_CODE,SESSION_RECOVERY_REQUIRED_MESSAGE}from"../runtime/session-mutation-coordinator.js";import{observeLifecyclePromise}from"../runtime/lifecycle-promise-observer.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{LocalConversationHistoryBoundary,OpenClawGatewaySessionMetadataPort,OpenClawSessionMetadataService,RuntimeSessionControlService}from"../runtime/runtime-session-control-service.js";import{pageRuntimeSessions,parseRuntimeSessionListPage}from"../runtime/runtime-session-list-policy.js";import{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{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 isPlaceholderTitle(e){if(!e)return!0;const t=e.trim();if(!t)return!0;const s=t.toLowerCase();return"new chat"===s||"new conversation"===s||"新会话"===t||(!!/^[0-9a-f]{6,12}\s*\(20\d{2}/i.test(t)||(!!/^Sender\s*\(untrusted/i.test(t)||!!/^Conversation\s+info\s*\(untrusted/i.test(t)))}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 n=s.match(/^\/([^\s:]+)(?::|\s|$)/)?.[1]?.trim();return n&&!n.includes("/")&&SLASH_COMMAND_NAME_RE.test(n)?n.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 n=Buffer.from(await s.arrayBuffer());if(n.length>MAX_ZIP_BYTES)throw new TemplatePackageError(`package too large: ${n.length} bytes (max ${MAX_ZIP_BYTES})`);const i=createHash("sha256").update(n).digest("hex");if(t?.trim()&&t.trim().toLowerCase()!==i)throw new TemplatePackageError("package sha256 mismatch");const r=this.parsePackage(n),o=`acp-artifact:sha256:${i}`;return this.artifacts.set(o,r),{artifactRef:o,version:r.manifest?.version??"0.0.0",sha256:i,sizeBytes:String(n.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,n]of[...e.workspaceFiles].sort(([e],[t])=>e.localeCompare(t)))t.update(s).update("\0").update(n).update("\0");const s=t.digest("hex"),n=`acp-artifact:sha256:${s}`;this.artifacts.set(n,e);const i=[...e.workspaceFiles.values()].reduce((e,t)=>e+t.byteLength,0);return{artifactRef:n,version:e.manifest?.version??"0.0.0",sha256:s,sizeBytes:String(i),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 n=this.transport.materializeSessionUpdate(t,s);return null!==n&&this.updates.push(n),!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;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)}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;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.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,n=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):void 0;this.mcp=new McpService({transport:this.transport,logger:this.logger,state:this.state,...n?{desiredState:n}:{}}),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 i=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 n=this.getGateway();if(!n?.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 i=t.currentRunId,r=await this.sessionMutationCoordinator.requestCancel(t.writeGateToken,n);if(!r.ok)return{state:"recovery_required",reason:"terminal_not_observed",runtimeRunId:i};const o=await r.terminalObservation;return o.ok?{state:"terminal_observed",runtimeRunId:i,abortObservation:r.acknowledged?{state:"target_acknowledged",aborted:!0,runIds:[i],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:i}},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);s?(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):this.logger.debug?.(`[bridge-core] setModel projection skipped: no live local session for key=${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}:{}});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:i})),this.transport.setSessionUpdateObserver((e,t,s)=>{const n=s?.turnId;if(!n)return;const i=this.state.sessions.get(e);i&&(recordTurnIdForRole(i,t,n),recordToolCallTurnForUpdate(i,t,n))})}setRuntimeTerminalService(e){this.runtimeTerminalService=e}setRuntimeReceiptHistoryPort(e){this.mcp.setRuntimeReceiptHistoryPort(e)}getRuntimeCommandDispatcher(){return this.runtimeCommands}async stopMcp(){await this.mcp.stop()}observeActiveRun(e){const t=e.currentRunId,s=e.writeGateToken,n=this.sessionMutationCoordinator.snapshot(e.gatewaySessionKey),i=void 0===e.pendingPromptId?e.gatewayRequestId??t:String(e.pendingPromptId);if(!t||!n||!i)return;const r={runtimeConversationUid:e.sessionId,runtimeSessionKey:e.gatewaySessionKey,historyGeneration:this.localHistoryBoundary.currentGeneration(e.sessionId),targetMessageId:i,runtimeRunId:t,activeRunRegistrationId:`acp:${n.operationId}`};return this.activeRuns.register(r,async()=>{const i=this.getGateway();if(!i?.isConnected||e.currentRunId!==t)return"recovery_required";const r=s?.operationId===n.operationId?await this.sessionMutationCoordinator.requestCancel(s,i):await this.sessionMutationCoordinator.requestCancelForSession(e.gatewaySessionKey,i);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}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.getGateway();if(e?.isConnected)try{const t=await e.sessionsList();if(!t||"object"!=typeof t)return;const s=t.sessions;if(!Array.isArray(s))return;let n=0;for(const e of s){const t=e,s=t.sessionKey??t.key??t.id??t.name;if(!s||"string"!=typeof s)continue;if(this.state.findSessionByKey(s))continue;const i=t.label||t.derivedTitle||t.title||void 0,r=i&&!isPlaceholderTitle(i)?i:void 0,o=createSessionObject({gatewayKey:s,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,title:r});this.registerSession(o,{ensureVerbose:!1}),n++}n>0&&this.logger.info?.(`[bridge-core] preloadSessions: loaded ${n} session(s) from gateway`)}catch(e){this.logger.debug?.("[bridge-core] preloadSessions failed:",e)}else this.logger.debug?.("[bridge-core] preloadSessions skipped: gateway not connected")}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 handleSessionNew(e){const t=`agent:${"string"==typeof e.params?.agentId&&e.params.agentId||this.config.gateway.agentId||this.getDefaultAgentId()}:${randomUUID()}`,s="string"==typeof e.params?.cwd?e.params.cwd:".",n=createSessionObject({gatewayKey:t,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,cwd:s});this.registerSession(n,{ensureVerbose:!1}),this.transport.sendResult(e.id,{sessionId:n.sessionId,modes:{availableModes:[{...DEFAULT_MODE}],currentModeId:DEFAULT_MODE.id},_meta:{sessionKey:t,agentId:n.agentId,platformAgentId:n.platformAgentId??null}}),this.fetchHistoryInBackground(t)}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 n=this.state.sessionsByGatewayKey.get(t);if(!n)return;const i=e.message?.role;if("toolResult"===i||"tool"===i)return void this.handlePersistedToolResultMessage(n,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"===i?"user":"system"===i?"system":"assistant",o=n.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,d="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(n.sessionId,{sessionUpdate:"message_id_bind",role:r,messageId:s,...d?{timestamp:d}:{}},c),n.lastTurnIdByRole&&(n.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:n,turnId:o,messageId:s,runId:void 0})}async handlePersistedToolResultMessage(e,t){const s=t.messageId;if(!s)return;const n=extractPersistedToolResultEnvelope(t.message),i=this.extractPersistedToolResultFromHistory(e,s),r=mergePersistedToolResultEnvelopes(i,n);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}});i&&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 d=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:d,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 n=s.sessions;if(!Array.isArray(n))return;for(const t of n){const s=t,n=s.sessionKey??s.key??s.id??s.name;if(n&&"string"==typeof n&&deriveSessionId(n,this.instanceId)===e){const e=s.label||s.derivedTitle||s.title||void 0,t=e&&!isPlaceholderTitle(e)?e:void 0,i=createSessionObject({gatewayKey:n,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,title:t});return this.registerSession(i),i}}}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:"),n=this.config.gateway.agentId||this.getDefaultAgentId();return t=createSessionObject({gatewayKey:s?e:`agent:${n}:${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),n=s.sessionId;this.state.lastActiveSessionId=n,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:n}),this.onSessionLoaded?.(n,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 n=this.getGateway(),i=e.assistantMq&&!e.assistantMq.closed,r=i?null:n,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),d=a.filter(e=>"user"===e.role).length,c=a.filter(e=>"assistant"===e.role).length,l=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=${d} asstTurns=${c} turnsWithToolCalls=${l} totalToolCalls=${m}`),d>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 n=cleanHistoryUserContent(t.content).slice(0,64).replace(/\n/g," ").trim();if(n){e.title=n,e.titleSource="truncated";const t=this.getGateway();t?.isConnected&&t.sessionsPatch(e.gatewaySessionKey,{label:n}).catch(()=>{}),this.transport.sendSessionUpdate(s,{sessionUpdate:"title_update",title:n}),this.tryGenerateTitleFromHistory(e,s,a)}}}const u=t=>`history:${e.gatewaySessionKey}:${t}`;let p=-1;if(i)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(i),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,n){const i=e.sessionId,r=new Set;let o=0;for(let a=0;a<t.length;a++){const d=t[a],c=n.turnIdFor(d,a);if(n.mqActive&&a===n.lastAsstIdx){const e=classifyHistoricalAssistantTurnCompletion(d,{mqActive:n.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"===d.role&&"internal_system"===d.provenance?.kind){this.logger.debug?.(`[bridge-core] SKIP history_turn[${a}] internal_system user message`);continue}if("user"===d.role&&/^\s*system\s*\(untrusted[^)]*\)/i.test(d.content)){this.logger.debug?.(`[bridge-core] SKIP history_turn[${a}] system-injected user message`);continue}if("user"===d.role&&isHeartbeatPromptText(d.content)){this.logger.info?.(`[bridge-core] SKIP history_turn[${a}] heartbeat cron prompt sessionId=${e.sessionId} contentLen=${d.content.length} preview="${previewSanitizedText(d.content)}"`);continue}if("user"===d.role&&isCronPromptText(d.content)){this.logger.info?.(`[bridge-core] SKIP history_turn[${a}] cron-triggered user message sessionId=${e.sessionId} contentLen=${d.content.length} preview="${previewSanitizedText(d.content)}"`);continue}if("assistant"===d.role){const t=classifyHeartbeatFilter(d.content);if(t.filtered){this.logger.info?.(`[bridge-core] SKIP history_turn[${a}] heartbeat assistant reply reason=${t.reason} sessionId=${e.sessionId} contentLen=${d.content.length} preview="${previewSanitizedText(d.content)}"`);continue}}const l="assistant"===d.role?classifyHistoricalAssistantTurnCompletion(d,{mqActive:n.mqActive,isSkippedForLiveMq:!1}):void 0;if("error"===l?.kind||"interrupted"===l?.kind&&l.failure)s.sendSessionUpdate(i,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:""},...d.timestamp?{timestamp:d.timestamp}:{}},{turnId:c,...void 0!==d._seq?{seq:d._seq}:{}}),s.sendSessionUpdate(i,{sessionUpdate:"stream_complete",stopReason:l.stopReason,error:l.message,errorCode:l.errorCode},{turnId:c}),this.logger.info?.(`[bridge-core] history_runtime_failure_terminalized session_id=${i} turn_id=${c} error_code=${l.errorCode} stop_reason=${l.stopReason} source=history_replay`),o+=1;else if("system"!==d.role)if(this.logger.debug?.(`[bridge-core] SENDING history_turn[${a}] role=${d.role} contentLen=${d.content.length} content=${JSON.stringify(d.content.slice(0,80))} tcCount=${d.toolCalls?.length??0}`),"user"===d.role)this.replayUserTurnAsChunks(s,i,d.content,d.metadata,d.timestamp,c,d._seq);else{if(await this.replayAssistantTurnAsStream(s,i,d,c),d.toolCalls)for(const e of d.toolCalls)e.id&&r.add(e.id);const e=l??classifyHistoricalAssistantTurnCompletion(d,{mqActive:n.mqActive,isSkippedForLiveMq:!1});if("interrupted"===e.kind){const t=new Set(e.incompleteToolCallIds);for(const n of d.toolCalls??[])t.has(n.id)&&s.sendSessionUpdate(i,buildToolCallUpdatePayload({toolCallId:n.id,toolName:n.name,outputText:e.message,kind:n.kind,status:"failed",timestamp:d.timestamp}),{turnId:c});this.logger.info?.(`[bridge-core] history_orphan_turn_terminalized session_id=${i} turn_id=${c} tool_call_ids=${e.incompleteToolCallIds.join(",")} stop_reason=${e.stopReason} source=history_replay`),s.sendSessionUpdate(i,{sessionUpdate:"stream_complete",stopReason:e.stopReason,error:e.message,errorCode:e.errorCode},{turnId:c}),o+=1;continue}if("completed"!==e.kind)continue;s.sendSessionUpdate(i,{sessionUpdate:"stream_complete",stopReason:e.stopReason},{turnId:c}),o+=1}else this.logger.debug?.(`[bridge-core] SENDING system_message[${a}] contentLen=${d.content.length}`),s.sendSessionUpdate(i,{sessionUpdate:"system_message_chunk",content:{type:"text",text:d.content},metadata:d.metadata,...d.timestamp?{timestamp:d.timestamp}:{}},{turnId:c,...void 0!==d._seq?{seq:d._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 n="string"==typeof t.cursor&&t.cursor.length>0?t.cursor:void 0,i="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,{...n?{cursor:n}:{},limit:i,logger:this.logger}),d=groupIntoTurns(a.messages),c=new HistoryUpdateRecorder(this.transport);await this.replayHistoryTurnsToSink(r,d,c,{mqActive:!1,lastAsstIdx:-1,turnIdFor:(e,t)=>void 0!==e._seq?`history:${r.gatewaySessionKey}:seq:${e._seq}`:`history:${r.gatewaySessionKey}:seq:none:${n??"head"}:${t}`}),this.logger.debug?.(`[bridge-core] _beeos/session/history sid=${r.sessionId} cursor=${n??"<head>"} limit=${i} turns=${d.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 n=e.assistantMq;if(n&&!n.closed){const s=n.peek(0);let i=0;if(t&&t.size>0)for(let e=0;e<s.length;e++){const n=s[e],r=n.sessionUpdate,o=n.toolCallId;if("tool_call"!==r&&"tool_call_update"!==r||!o||!t.has(o)){if("agent_message_chunk"===r){if(""===(n.content?.text??"").trim()&&e<s.length-1){const n=s[e+1];if(("tool_call"===n.sessionUpdate||"tool_call_update"===n.sessionUpdate)&&n.toolCallId&&t.has(n.toolCallId)){i=e+1;continue}}break}break}i=e+1}const r=resolveTurnId(e),o=r?{turnId:r}:void 0;for(let t=i;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 n=this.getGateway();if(n?.isConnected)try{const e=await n.sessionsList();if(e&&"object"==typeof e&&Array.isArray(e.sessions)){const n=e.sessions;for(const e of n){const n=e,i=n.sessionKey??n.key??n.id??n.name;if(!i||"string"!=typeof i)continue;if(isBackgroundSessionKey(i))continue;if(this.cronIsolatedSessionKeys.has(i))continue;const r=deriveSessionId(i,this.instanceId),o=s.find(e=>e.sessionId===i||e.sessionId===r||this.state.sessions.get(e.sessionId)?.gatewaySessionKey===i);if(!0===n.deleted){if(this.state.deletedGatewaySessionKeys.add(i),!t.includeDeleted)continue}else this.state.deletedGatewaySessionKeys.delete(i);const a=n.label||cleanGatewayDerivedTitle(n.derivedTitle)||n.title||void 0,d=a&&!isPlaceholderTitle(a)?a:void 0,c=n.model,l=n.modelProvider;if(o){if(d&&isPlaceholderTitle(o.title)){o.title=d;const e=this.state.sessions.get(o.sessionId);e&&isPlaceholderTitle(e.title)&&(e.title=d)}const e=n.updatedAt;e&&(o.updatedAt=e),c&&(o.model=c),l&&(o.modelProvider=l)}else{const e=createSessionObject({gatewayKey:i,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,cwd:n.cwd,title:d});this.registerSession(e,{ensureVerbose:!1}),s.push({sessionId:e.sessionId,title:d||"",cwd:n.cwd,updatedAt:n.updatedAt,agentId:e.agentId,platformAgentId:e.platformAgentId,deletable:!isSystemDefaultSessionKey(i),model:c,modelProvider:l})}}}}catch(e){this.logger.debug?.("[bridge-core] sessions.list enrichment failed:",e)}const i=t.includeDeleted?s:s.filter(e=>{const t=this.state.sessions.get(e.sessionId)?.gatewaySessionKey;return!t||!this.state.deletedGatewaySessionKeys.has(t)});i.sort((e,t)=>(t.updatedAt??0)-(e.updatedAt??0)||e.sessionId.localeCompare(t.sessionId)),this.transport.sendResult(e.id,{sessions:pageRuntimeSessions(i,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 n=s.slice(0,64),i=this.state.sessions.get(t);if(i)try{const s=await this.dispatchLegacyConversationCapability("session.rename",i,{title:n});i.title=s.title,i.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)}`),i.title=n,i.titleSource="manual",this.transport.sendResult(e.id,{sessionId:t,title:n})}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.\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,n){if(this.isGuardMessage(s))return void this.logger.info?.(`[bridge-core] title-gen SKIP guard message sid=${t}`);const i=this.matchTitleTemplate(s);if(i){e.title=i,e.titleSource="template";const s=this.getGateway();return s?.isConnected&&s.sessionsPatch(e.gatewaySessionKey,{label:i}).catch(()=>{}),void this.transport.sendSessionUpdate(t,{sessionUpdate:"title_update",title:i})}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(n)}`;this.logger.info?.(`[bridge-core] title-gen CALLING LLM sid=${t} q="${s.slice(0,60)}" aLen=${n.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 n=await s.json(),i=n.choices?.[0]?.message?.content?.trim();if(!i)return;const r=i.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 n=this.getGateway();if(!n?.isConnected)return;let i=s;if(!i)try{const t=await loadHistory(n,e.gatewaySessionKey);i=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=i.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=i.indexOf(r),a=i.slice(o+1).find(e=>"assistant"===e.role&&!!e.content?.trim());if(!a)return;const d=cleanHistoryUserContent(r.content),c=a.content.trim();d&&c&&this.generateTitleFromQA(e,t,d,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 n=s.gatewaySessionKey,i=this.sessionMutationCoordinator.tryStartExclusive({sessionKey:n,label:"session_delete"},"acp");if(!i.ok)return void this.sendSessionBusy(s,e.id,"active_session_mutation",i.queueDepth);const r=i.token;try{if(this.hasActiveRun(s)){const t=this.sessionMutationCoordinator.gateSnapshot(n);return void this.sendSessionBusy(s,e.id,"active_session_mutation",t.queueDepth)}this.logger.info?.(`[bridge-core] session/delete sessionId=${t} gatewayKey=${n} gwConnected=${!!this.getGateway()?.isConnected}`);let i=!1;const r=this.getGateway();if(r?.isConnected&&n)try{await r.sessionsDelete(n),i=!0,this.logger.info?.(`[bridge-core] Gateway sessions.delete SUCCESS for key=${n}`)}catch(t){const s=t instanceof Error?t.message:String(t);if(this.logger.info?.(`[bridge-core] Gateway sessions.delete FAILED for key=${n}: ${s}`),!s.includes("Cannot delete the main session"))return void this.transport.sendResult(e.id,{deleted:!1});try{await r.sessionsReset(n),i=!0,this.logger.info?.(`[bridge-core] Gateway sessions.reset SUCCESS for key=${n}`)}catch(t){return this.logger.warn?.(`[bridge-core] Gateway sessions.reset also failed for key=${n}: ${t instanceof Error?t.message:t}`),void this.transport.sendResult(e.id,{deleted:!1})}}else n&&this.logger.warn?.(`[bridge-core] Gateway not connected, proceeding with local-only delete for key=${n}`);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(n),this.state.deletedGatewaySessionKeys.add(n),this.transport.resetSessionUpdateCount(t),i&&this.onSessionDeleted?.(n),this.logger.info?.(`[bridge-core] session/delete DONE sessionId=${t} gatewayKey=${n} 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 n=this.getGateway(),i=n?.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(i&&r){const e=await this.sessionMutationCoordinator.requestCancel(r,n);o="recovery_required"===await this.handleCancellationResult(s,e)}else i&&await n.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,n=t?this.state.sessions.get(t):void 0;if(t&&s)if(n)try{const t=await this.dispatchLegacyConversationCapability("session.setMode",n,{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,n="string"==typeof s?.sessionId?s.sessionId:void 0;if(!n||!s||!Object.prototype.hasOwnProperty.call(s,"model"))return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId, model"});const i=s.model;if(null!==i&&("string"!=typeof i||0===i.length||i.trim()!==i))return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"model must be a non-empty string or null"});const r=n?this.state.sessions.get(n):void 0;if(r)try{const t=await this.dispatchLegacyConversationCapability("session.setModel",r,{modelOverrideId:i});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 n=Date.now(),i=createHash("sha256").update(JSON.stringify(e)).digest("hex");return{operationId:t,runtimeInstanceUid:this.instanceId,dispatchEpoch:s,paramsHash:i,idempotencyKeyHash:createHash("sha256").update(t).digest("hex"),claimDeadline:new Date(n+3e4).toISOString(),executionDeadline:new Date(n+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,n){return{name:e,params:s,context:{...this.canonicalContextBase(s,n.operationId,n.runtimeEpoch),scope:"agent",agent:{runtimeLocalKey:t,runtimeAgentUid:await this.runtimeAgentIdentities.resolveOrCreate(t)}}}}async dispatchLegacyAgentCapability(e,t,s){const n=normalizeRuntimeAgentLocalKey(t),i=await this.runtimeLeases.claim(this.createOperationId());let r=!1;try{const t={name:e,params:s,context:{...this.canonicalContextBase(s,i.operationId,i.runtimeEpoch),scope:"agent",agent:{runtimeLocalKey:n,runtimeAgentUid:await this.runtimeAgentIdentities.resolveOrCreate(n)}}},o=this.runtimeCommands.dispatch(t,this.acpExecutionAttempt(t));return r=!0,await o.completion}finally{r||await this.runtimeLeases.release(i)}}async dispatchLegacyInstanceCapability(e,t){const s=await this.runtimeLeases.claim(this.createOperationId());let n=!1;try{const i={name:e,params:t,context:{...this.canonicalContextBase(t,s.operationId,s.runtimeEpoch),scope:"instance"}},r=this.runtimeCommands.dispatch(i,this.acpExecutionAttempt(i));return n=!0,await r.completion}finally{n||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 n;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,i=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}),d=createHash("sha256").update(canonicalizeJcs(a)).digest("hex");n={definition:{definitionRef:`acp-mcp:sha256:${d}`,version:"local-v1",sha256:d,...i?{credentialRef:await requireCredentialReferencePort(this.mcpCredentialReferences).put({serverName:s,material:i})}:{}},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?.(n.definition,n.config);try{await this.dispatchLegacyInstanceCapability("mcp.set",{name:s,definition:n.definition})}catch(e){if(n.definition.credentialRef){!await this.mcp.removeCredentialIfUnreferenced(n.definition.credentialRef)&&this.mcpCredentialReferences?.owns(n.definition.credentialRef)&&await this.mcpCredentialReferences.remove(n.definition.credentialRef)}throw e}this.transport.sendResult(e.id,{ok:!0,restarting:!0})}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:!0})}async dispatchLegacyConversationCapability(e,t,s){const n=await this.runtimeLeases.claim(this.createOperationId());let i=!1;try{const r={name:e,params:s,context:{...this.canonicalContextBase(s,n.operationId,n.runtimeEpoch),scope:"conversation",conversation:{runtimeConversationUid:t.sessionId,runtimeSessionKey:t.gatewaySessionKey}}},o=this.runtimeCommands.dispatch(r,this.acpExecutionAttempt(r));return i=!0,await o.completion}finally{i||await this.runtimeLeases.release(n)}}async dispatchLegacyTerminalCapability(e,t,s,n){const i=await this.runtimeLeases.claim(this.createOperationId());let r=!1;try{const o={name:e,params:n,context:{...this.canonicalContextBase(n,i.operationId,i.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(i)}}async dispatchLegacyCanvasNotification(e,t){const s=t&&"object"==typeof t?t:{},n=e.replace("/","."),i="canvas.toggle"===n?{visible:!0===s.visible||!0===s.enabled}:"canvas.reference"===n?{surfaceId:"string"==typeof s.surfaceId?s.surfaceId:""}:"canvas.dimensions"===n?{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 d=!1;try{const e={name:n,params:i,context:{...this.canonicalContextBase(i,a.operationId,a.runtimeEpoch),scope:"canvas",canvas:{canvasId:o,sessionId:r}}},t=this.runtimeCommands.dispatch(e,this.acpExecutionAttempt(e));d=!0,await t.completion}finally{d||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),n=await this.runtimeLeases.claim(this.createOperationId());let i=!1;try{const r="cron.add"===e?{...t,runtimeCronJobUid:`runtime-cron:${n.operationId}`}:"cron.run"===e?{...t,runToken:`runtime-run:${n.operationId}`}:t,o={name:e,params:r,context:{...this.canonicalContextBase(r,n.operationId,n.runtimeEpoch),scope:"agent",agent:{runtimeLocalKey:s,runtimeAgentUid:await this.runtimeAgentIdentities.resolveOrCreate(s)}}},a=this.runtimeCommands.dispatch(o,this.acpExecutionAttempt(o));return i=!0,await a.completion}finally{i||await this.runtimeLeases.release(n)}}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(),n=this.runtimeCommands.dispatch(e,this.acpExecutionAttempt(e));s=!0;const i=await n.completion;return queueMicrotask(()=>{this.observeAgentProjection()}),i}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,n)=>{s=setTimeout(()=>n(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(),n=await this.runtimeLeases.claim(s),i=await this.finishClaimedLegacyAgentMutation(n,async()=>{const s=await this.runtimeAgentIdentities.allocateCreate(n,"agent.create"),i=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}:{},...i.length?{bootstrapFiles:i}:{}},n)});this.transport.sendResult(e.id,{agentId:i.runtimeLocalKey,platformAgentId:this.resolvePlatformAgentId(i.runtimeLocalKey)??"",workspace:i.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 n=await this.runtimeCommandResources.registerArtifact(s,e.params?.sha256),i=this.createOperationId(),r=await this.runtimeLeases.claim(i),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:n,...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 n=await this.runtimeLeases.claim(this.createOperationId()),i=await this.finishClaimedLegacyAgentMutation(n,()=>this.agentCommand("agent.update",t,s,n));this.transport.sendResult(e.id,{agentId:i.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()),n=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:n.runtimeLocalKey,...void 0===n.removedBindings?{}:{removedBindings:n.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}:{}})),n={...t.defaultRuntimeLocalKey?{defaultId:t.defaultRuntimeLocalKey}:{},agents:s};this.transport.sendResult(e.id,n)}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 n=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})),i=await this.getSkillsDir(e);for(const e of n){const t=e.skillKey??e.name;try{const s=await readFile(join(i,t,".beeos-meta.json"),"utf8"),n=JSON.parse(s);n?.iconUrl&&(e.iconUrl=n.iconUrl)}catch{}}return n}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",{}),n=normalizeAgentId(e),i=s?.agents?.find(e=>normalizeAgentId(e.id)===n);return i?.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,n=t?.files,i=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(n?.length||s)try{let o;if(s){o=parseSkillZip(await fetchWithRetry(s,{maxRetries:4,logger:this.logger}))}else{if(!n?.length)throw new RuntimeCommandError("INVALID_PARAMS","Missing skill files or zipUrl");o=new Map;for(const e of n){const t=normalizeSkillArtifactPath(e.path),s=await fetch(e.downloadUrl,{signal:AbortSignal.timeout(12e4)});if(!s.ok)throw new Error(`Failed to download ${e.path}: ${s.status}`);o.set(t,new Uint8Array(await s.arrayBuffer()))}}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",i,{artifact:a}),this.transport.sendResult(e.id,{success:!0}),this.onSkillInstalled?.(r,resolveSkillInstallDir(await this.getSkillsDir(i),r)),await this.pushSkillsList(i)}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 n;try{n=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:n}),this.transport.sendResult(e.id,{success:!0}),await this.pushSkillsList(s)}catch(t){this.logger.error?.(`[bridge-core] Failed to uninstall skill "${n}": ${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,n=t?.enabled,i=t?.agentId;if(s&&"boolean"==typeof n)try{await this.dispatchLegacyAgentCapability("skills.setEnabled",i,{skillKey:s,enabled:n}),this.logger.info?.(`[bridge-core] Updated skill "${s}" enabled=${n}${i?` for agent "${i}"`:""}`),this.transport.sendResult(e.id,{ok:!0,skillKey:s,enabled:n}),await this.pushSkillsList(i)}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:n,created:i}=await this.resolveOrCreateSession(t);i&&this.onSessionLoaded?.(n.sessionId,n.gatewaySessionKey,n.platformAgentId);const r=n.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(n)){const t=this.sessionMutationCoordinator.gateSnapshot(n.gatewaySessionKey);return void this.sendSessionBusy(n,e.id,"active_run",t.queueDepth)}try{await this.ensureVerboseFull(n)}catch(t){return this.releaseSessionWriteGate(n),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 d=a.filter(e=>"text"===e.type&&"text"in e&&"string"==typeof e.text).map(e=>e.text).join("\n");if(n.fileArtifactDisplayMode=prefersChatFileArtifacts(d)?"chat":"auto",!n.title||isPlaceholderTitle(n.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="${n.title}" cleanText="${t.slice(0,80)}" isPlaceholder=${isPlaceholderTitle(t)}`),t&&!isPlaceholderTitle(t)){const e=t.slice(0,64).replace(/\n/g," ").trim();n.title=e,n.titleSource="truncated",o?.isConnected&&e&&o.sessionsPatch(n.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 l;if(this.beeosFileResolver){const e=this.beeosFileResolver.buildResolutionPlan(a);if(e.refs.length>0)try{l=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:l});if("error"in m)return this.releaseSessionWriteGate(n),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(n,a,resolveTurnId(n)),this.transport.sendSessionUpdate(r,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Loading ${h}...`},timestamp:(new Date).toISOString()},{turnId:resolveTurnId(n)}),this.transport.sendResult(e.id,{stopReason:"end_turn"}),void this.releaseSessionWriteGate(n)}const y="chat.send";let f=g?u:withUserMessagePrefix(u);const w=this.config.canvasEnabled&&!g&&!0===n.canvasActive&&!n.channelType;if(w){const e=n.promptsSinceCanvasInjection??0;!n.canvasPromptInjected||e>=10?(f=`${CANVAS_TERM_MAPPING}\n\n${f}`,n.canvasPromptInjected=!0,n.promptsSinceCanvasInjection=0,this.logger.debug?.("[bridge-core] Canvas term mapping injected (re-inject cycle)")):n.promptsSinceCanvasInjection=e+1}if(w){const e=this.getCanvasState?.();if(e){const t=e.resolveCanvasForSession(n.gatewaySessionKey);f=`${buildActiveSurfacesContext(e,t)??"[Canvas] Canvas panel is available. Use render_ui for structured/visual content."}\n\n${f}`}const t=n.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}`,n.referencedSurfaceId=void 0)}if(!g){const t=parseMentionsParam(e.params?.mentions);if(t.length>0){n.activeMentions=t;f=`${buildMentionInstruction(t)}\n${f}`,this.logger.debug?.(`[bridge-core] delegation mention instruction injected for ${t.length} agent(s)`)}else n.activeMentions=void 0}if(g&&this.logger.info?.(`[bridge-core] slash command passthrough sessionId=${r} command=/${h}`),this.hasActiveRun(n)){const t=this.sessionMutationCoordinator.gateSnapshot(n.gatewaySessionKey);return void this.sendSessionBusy(n,e.id,"active_run_after_prepare",t.queueDepth)}const I=this.sessionMutationCoordinator.tryStartInteractive({sessionKey:n.gatewaySessionKey,label:"session/prompt"},"acp");if(!I.ok)return void this.sendSessionBusy(n,e.id,I.reason,I.queueDepth);n.writeGateToken=I.token,this.state.resetForNewRun(n,r,this.transport),n.pendingPromptId=e.id,n.gatewayMethod=y;const v=resolveTurnId(n);this.emitPromptAsUserSessionUpdates(n,a,v),this.transport.sendSessionUpdate(r,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:""},timestamp:(new Date).toISOString()},v?{turnId:v}:void 0);const S=extractCronJobId(u);S&&(n.cronJobId=S),this.schedulePromptTimeout(n);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,"")}`,b={sessionKey:n.gatewaySessionKey,message:f,deliver:!1,idempotencyKey:randomUUID()};C?.length&&(b.attachments=C);if(!o.sendFrame({type:"req",id:R,method:y,params:b}))return this.state.clearPromptTimeout(n),n.pendingPromptId=void 0,n.assistantMq?.close(),n.assistantMq=void 0,n.pendingUserTurnUpdates=void 0,this.releaseSessionWriteGate(n),void this.transport.sendAcpError(e.id,Errors.SendFailed,{message:"failed to send prompt to gateway"});n.gatewayRequestId=R,this.state.promptsByGatewayRequestId.set(R,n)}replayUserTurnAsChunks(e,t,s,n,i,r,o){const a=splitUserReplayBlocks(s),d=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,...n?{metadata:n}:{},...i?{timestamp:i}:{}},d)}}async replayAssistantTurnAsStream(e,t,s,n){const i=e=>{if(n||void 0!==e)return{...n?{turnId:n}:{},...void 0!==e?{seq:e}:{}}},r=new Set,o=(s,n,o)=>{if(!s?.length)return;const a=i(o);for(const i of s)i.uri&&!r.has(i.uri)&&(r.add(i.uri),e.sendSessionUpdate(t,{sessionUpdate:"agent_message_chunk",content:{type:"resource_link",uri:i.uri,name:i.name??"file",...i.mimeType?{mimeType:i.mimeType}:{}},...n?{timestamp:n}:{}},a))},a=i(s._seq);if(!s.sourceMessages?.length){const n={sessionUpdate:"history_turn",role:s.role,content:s.content,reasoning:s.reasoning,toolCalls:s.toolCalls,...s.timestamp?{timestamp:s.timestamp}:{}};return s.metadata&&(n.metadata=s.metadata),e.sendSessionUpdate(t,n,a),void o(s.files,s.timestamp,s._seq)}for(const n of s.sourceMessages){const r=n.updateType??"agent_message_chunk",a=i(n._seq);switch(r){case"agent_message_chunk":e.sendSessionUpdate(t,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:n.content},...n.timestamp?{timestamp:n.timestamp}:{},...n.metadata?{metadata:n.metadata}:{}},a);break;case"agent_thought_chunk":e.sendSessionUpdate(t,{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n.content},...n.timestamp?{timestamp:n.timestamp}:{}},a);break;case"tool_call":{const i=n.toolCallId??"",r=s.toolCalls?.find(e=>e.id===i),o=n.toolName??"tool",d=n.content??"";let c={};if(d)try{c=JSON.parse(d)}catch{}e.sendSessionUpdate(t,buildToolCallPayload({toolCallId:i,toolName:o,args:c,kind:r?.kind,status:r?.status??"in_progress",timestamp:n.timestamp}),a);break}case"tool_call_update":{const i=n.toolCallId??"",r=s.toolCalls?.find(e=>e.id===i),d=n.toolName??r?.name??"tool",c=n.content??r?.output??"",l=await this.resolveReplayResourceLinks(i,d,n.files);e.sendSessionUpdate(t,buildToolCallUpdatePayload({toolCallId:i,toolName:d,outputText:c,kind:r?.kind,status:r?.status??"completed",resourceLinks:l,timestamp:n.timestamp}),a),o(l,n.timestamp,n._seq);break}}}o(s.files,s.timestamp,s._seq)}async resolveReplayResourceLinks(e,t,s){let n=s?.map(e=>({uri:e.uri,name:e.name??"file",...e.mimeType?{mimeType:e.mimeType}:{}}));if(n?.length)return n;if(n=await readEnrichmentCache(e).catch(()=>{}),n?.length)return n;if("beeos_upload_file"!==t)return;const i=await readUploadToolResult(e).catch(()=>{});if(!i)return;const r=buildToolResultSessionContentBlocks(t,i).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 n=(new Date).toISOString(),i=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:n};s&&void 0===o._turnId&&(o._turnId=s),this.transport.sendSessionUpdate(e.sessionId,o,i),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,n=t.mimeType??t.mime_type??e.mimeType??e.mime_type,i=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&&!i&&!r)return;return{type:"resource",resource:{...s?{uri:s}:{},...n?{mimeType:n}:{},...i?{text:i}:{},...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 n=this.state.sessions.get(s);if(!n)return void(void 0!==e&&this.transport.sendAcpError(e,Errors.SessionNotFound));const i=n.activeRunBinding??this.observeActiveRun(n);if(!i){const t=this.sessionMutationCoordinator.snapshot(n.gatewaySessionKey);if("exclusive"===t?.attachmentPolicy&&void 0!==e){const t=this.sessionMutationCoordinator.gateSnapshot(n.gatewaySessionKey);return void this.sendSessionBusy(n,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,n={targetMessageId:i.targetMessageId,...s?{reason:s}:{}},a={name:"session.cancel",params:n,context:{...this.canonicalContextBase(n,r.operationId,r.runtimeEpoch),scope:"conversation",historyGeneration:i.historyGeneration,conversation:{runtimeConversationUid:i.runtimeConversationUid,runtimeSessionKey:i.runtimeSessionKey}}},d=this.runtimeCommands.dispatch(a,this.acpExecutionAttempt(a));o=!0,await d.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,n){this.logger.warn?.(`[bridge-core] session_write_gate_busy session_id=${e.sessionId} gateway_session_key=${e.gatewaySessionKey} reason=${s} queue_depth=${n}`),this.transport.sendError(t,Errors.AgentError.rpcCode,"Agent is busy",{code:"session_busy",reason:s,queueDepth:n}),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,n=e.activeRunBinding;let i,r,o,a,d="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"===d.kind?"cancelled"===d.stopReason?"cancelled":"completed":"interrupted"===d.kind&&"timeout"===d.stopReason?"timeout":"error",t=await this.sessionMutationCoordinator.converge(s,e);t.ok?i=t.permit:d={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 n=e.currentRunId;if("complete"===d.kind){if(n&&this.onRunComplete){const t=e.agentAssistantTextSoFar??e.chatAssistantTextSoFar??"";this.onRunComplete(n,t,d.stopReason)}void 0!==e.pendingPromptId&&this.transport.sendResult(e.pendingPromptId,{stopReason:d.stopReason}),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:d.stopReason},s),this.tryGenerateTitleFromHistory(e,e.sessionId)}else"interrupted"===d.kind?(n&&this.onRunFailed&&this.onRunFailed(n,d.message),void 0!==e.pendingPromptId&&this.transport.sendError(e.pendingPromptId,Errors.AgentError.rpcCode,d.message,{code:d.errorCode??"interrupted",stopReason:d.stopReason}),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:d.stopReason,error:d.message,...d.errorCode?{errorCode:d.errorCode}:{}},s)):(n&&this.onRunFailed&&this.onRunFailed(n,d.message),void 0!==e.pendingPromptId&&this.transport.sendError(e.pendingPromptId,d.code,d.message),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:"error",error:d.message},s))}catch(e){r=e}try{this.cleanupPrompt(e)}catch(e){o=e}finally{e.writeGateToken=void 0,e.activeRunBinding=void 0,i&&this.sessionMutationCoordinator.release(i)}if(n){const e="complete"===d.kind?"cancelled"===d.stopReason?"cancelled":"completed":"interrupted"===d.kind&&"cancelled"===d.stopReason?"cancelled":"failed";this.activeRuns.markTerminal(n,e)}try{this.onRunEnded?.(e,d)}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(),n=e.writeGateToken;s?.isConnected&&n?this.observeLifecycle(this.sessionMutationCoordinator.requestCancel(n,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):n&&(this.sessionMutationCoordinator.requireRecovery(n,"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 n=e.error,i=n?.message??"gateway returned error";this.logger.warn?.(`[bridge-core] handleGatewayResponse: gateway rejected prompt gatewayRequestId=${t} error=${i}`);const r=classifyAgentRuntimeFailure({raw:i,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 n=e.payload,i=n?.runId;i?(s.currentRunId=i,this.sessionMutationCoordinator.bindRun(s.writeGateToken,i),this.observeActiveRun(s),s.assistantStreamStartedAt=Date.now(),this.state.promptsByRunId.set(i,s),this.logger.debug?.(`[bridge-core] handleGatewayResponse: bound runId=${i} 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",n=classifyAgentRuntimeFailure({raw:s,source:"chat_state",runtimeKind:"openclaw"});"interrupted"===n.kind?this.observeLifecycle(this.interruptPrompt(e,n),"chat_state_interrupt",e):(this.logRuntimeFailure(e,n),this.observeLifecycle(this.failPrompt(e,Errors.AgentError.rpcCode,n.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("/","."),n={...e.params??{}};["cron.add","cron.update","cron.remove","cron.run","cron.runs"].includes(s)&&(n.__beeosCronIngress="acp"),"cron.update"===s&&(n.patch=n.patch&&"object"==typeof n.patch?{...n.patch}:{});try{const t=await this.dispatchLegacyCronCapability(s,n),i=await this.mapCronResultForAcp(s,t);this.transport.sendResult(e.id,i??{}),"cron.add"!==s&&"cron.update"!==s&&"cron.remove"!==s||this.refreshCronIsolatedSessionKeys()}catch(t){const n=t instanceof Error?t.message:"cron request failed";this.logger.warn?.(`[bridge-core] ${s} failed: ${n}`),this.transport.sendAcpError(e.id,Errors.SendFailed,{message:n})}}async mapCronResultForAcp(e,t){if(!t||"object"!=typeof t)return t;const s=t;await this.cronOverrides.snapshot();const n="cron.list"===e||"cron.status"===e,i=e=>{if(!e||"object"!=typeof e)return e;const t=e,s=t.id;if("string"!=typeof s)return e;const i=this.cronOverrides.localId(s)??s,r=this.cronChannelCache.get(i),o=r?encodeBeeosChannelTag("string"==typeof t.description?t.description:void 0,r):t.description,a=this.cronOverrides.get(i);return{...t,id:i,...void 0===o?{}:{description:o},...n&&"number"==typeof a?{_beeos_meta:{maxDurationMs:a}}:{}}};if(Array.isArray(s.jobs))return{...s,jobs:s.jobs.map(i)};if(s.jobs&&"object"==typeof s.jobs){const e=s.jobs,t={};for(const[s,n]of Object.entries(e))t[s]=i(n);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?i(t):t}async allocateCronChannel(e){if(this.agentFetch&&this.agentGatewayUrl)try{const t=`${this.agentGatewayUrl}/api/v1/channels`,s=await this.agentFetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({participants:[this.instanceId,"service:cron"],metadata:{source:"cron",job_name:e}})});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}`)}else this.logger.debug?.("[bridge-core] agentFetch/agentGatewayUrl unavailable, skip channel alloc")}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 n=new Set,i=[];for(const e of s){if(!e||"object"!=typeof e)continue;const t=e;if("string"==typeof t.id&&i.push(t.id),"isolated"!==t.sessionTarget)continue;const s=t.sessionKey;"string"==typeof s&&s.length>0&&n.add(s)}this.cronIsolatedSessionKeys=n,await this.cronOverrides.reconcile(i)}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 n;for(let i=0;i<=s;i++){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**i);if(n=new Error(`HTTP ${r.status} from ${e}`),i<s){t.logger?.info?.(`[bridge-core] Download ${r.status}, retry ${i+1}/${s} in ${(a/1e3).toFixed(0)}s`),await new Promise(e=>setTimeout(e,a));continue}}throw new Error(`Failed to download zip: ${r.status}`)}throw n??new Error("Download failed after retries")}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("/")),n=new Map;for(const e of t){const t=s?e.name.slice(e.name.indexOf("/")+1):e.name;if(!t||n.has(t))throw new RuntimeCommandError("INVALID_PARAMS",`Duplicate skill path: ${t}`);n.set(t,e.bytes)}return n}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),n=join(t,".beeos-extract-tmp-"+Date.now());try{await mkdir(n,{recursive:!0}),s.extractAllTo(n,!0);const e=await resolveSkillRoot(n),i=await readdir(e,{withFileTypes:!0});let r=0;for(const s of i){if(s.name.startsWith(".beeos-extract-tmp")||"__MACOSX"===s.name)continue;const n=join(e,s.name),i=join(t,s.name);await rename(n,i).catch(async()=>{await cp(n,i,{recursive:!0})}),r++}if(0===r)throw new Error("Zip archive contained no extractable files")}finally{await rm(n,{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 n=e.transport??("string"==typeof e.command?"stdio":"string"==typeof e.url?"streamable-http":void 0);if("stdio"===n&&t&&Object.keys(t).length)throw new Error("MCP stdio config cannot include headers");if("stdio"!==n&&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),n=join(e,s),i=resolve(e),r=resolve(n),o=relative(i,r);if(!o||".."===o||o.startsWith(`..${sep}`)||path.isAbsolute(o))throw new Error("Invalid skill target path");return n}
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{SESSION_RECOVERY_REQUIRED_CODE,SESSION_RECOVERY_REQUIRED_MESSAGE}from"../runtime/session-mutation-coordinator.js";import{observeLifecyclePromise}from"../runtime/lifecycle-promise-observer.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{LocalConversationHistoryBoundary,OpenClawGatewaySessionMetadataPort,OpenClawSessionMetadataService,RuntimeSessionControlService}from"../runtime/runtime-session-control-service.js";import{pageRuntimeSessions,parseRuntimeSessionListPage}from"../runtime/runtime-session-list-policy.js";import{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{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 isPlaceholderTitle(e){if(!e)return!0;const t=e.trim();if(!t)return!0;const s=t.toLowerCase();return"new chat"===s||"new conversation"===s||"新会话"===t||(!!/^[0-9a-f]{6,12}\s*\(20\d{2}/i.test(t)||(!!/^Sender\s*\(untrusted/i.test(t)||!!/^Conversation\s+info\s*\(untrusted/i.test(t)))}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 n=s.match(/^\/([^\s:]+)(?::|\s|$)/)?.[1]?.trim();return n&&!n.includes("/")&&SLASH_COMMAND_NAME_RE.test(n)?n.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 n=Buffer.from(await s.arrayBuffer());if(n.length>MAX_ZIP_BYTES)throw new TemplatePackageError(`package too large: ${n.length} bytes (max ${MAX_ZIP_BYTES})`);const i=createHash("sha256").update(n).digest("hex");if(t?.trim()&&t.trim().toLowerCase()!==i)throw new TemplatePackageError("package sha256 mismatch");const r=this.parsePackage(n),o=`acp-artifact:sha256:${i}`;return this.artifacts.set(o,r),{artifactRef:o,version:r.manifest?.version??"0.0.0",sha256:i,sizeBytes:String(n.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,n]of[...e.workspaceFiles].sort(([e],[t])=>e.localeCompare(t)))t.update(s).update("\0").update(n).update("\0");const s=t.digest("hex"),n=`acp-artifact:sha256:${s}`;this.artifacts.set(n,e);const i=[...e.workspaceFiles.values()].reduce((e,t)=>e+t.byteLength,0);return{artifactRef:n,version:e.manifest?.version??"0.0.0",sha256:s,sizeBytes:String(i),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 n=this.transport.materializeSessionUpdate(t,s);return null!==n&&this.updates.push(n),!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;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)}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;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.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,n=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):void 0;this.mcp=new McpService({transport:this.transport,logger:this.logger,state:this.state,...n?{desiredState:n}:{}}),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 i=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 n=this.getGateway();if(!n?.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 i=t.currentRunId,r=await this.sessionMutationCoordinator.requestCancel(t.writeGateToken,n);if(!r.ok)return{state:"recovery_required",reason:"terminal_not_observed",runtimeRunId:i};const o=await r.terminalObservation;return o.ok?{state:"terminal_observed",runtimeRunId:i,abortObservation:r.acknowledged?{state:"target_acknowledged",aborted:!0,runIds:[i],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:i}},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);s?(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):this.logger.debug?.(`[bridge-core] setModel projection skipped: no live local session for key=${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}:{}});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:i})),this.transport.setSessionUpdateObserver((e,t,s)=>{const n=s?.turnId;if(!n)return;const i=this.state.sessions.get(e);i&&(recordTurnIdForRole(i,t,n),recordToolCallTurnForUpdate(i,t,n))})}setRuntimeTerminalService(e){this.runtimeTerminalService=e}setRuntimeReceiptHistoryPort(e){this.mcp.setRuntimeReceiptHistoryPort(e)}getRuntimeCommandDispatcher(){return this.runtimeCommands}async stopMcp(){await this.mcp.stop()}observeActiveRun(e){const t=e.currentRunId,s=e.writeGateToken,n=this.sessionMutationCoordinator.snapshot(e.gatewaySessionKey),i=void 0===e.pendingPromptId?e.gatewayRequestId??t:String(e.pendingPromptId);if(!t||!n||!i)return;const r={runtimeConversationUid:e.sessionId,runtimeSessionKey:e.gatewaySessionKey,historyGeneration:this.localHistoryBoundary.currentGeneration(e.sessionId),targetMessageId:i,runtimeRunId:t,activeRunRegistrationId:`acp:${n.operationId}`};return this.activeRuns.register(r,async()=>{const i=this.getGateway();if(!i?.isConnected||e.currentRunId!==t)return"recovery_required";const r=s?.operationId===n.operationId?await this.sessionMutationCoordinator.requestCancel(s,i):await this.sessionMutationCoordinator.requestCancelForSession(e.gatewaySessionKey,i);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}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.getGateway();if(e?.isConnected)try{const t=await e.sessionsList();if(!t||"object"!=typeof t)return;const s=t.sessions;if(!Array.isArray(s))return;let n=0;for(const e of s){const t=e,s=t.sessionKey??t.key??t.id??t.name;if(!s||"string"!=typeof s)continue;if(this.state.findSessionByKey(s))continue;const i=t.label||t.derivedTitle||t.title||void 0,r=i&&!isPlaceholderTitle(i)?i:void 0,o=createSessionObject({gatewayKey:s,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,title:r});this.registerSession(o,{ensureVerbose:!1}),n++}n>0&&this.logger.info?.(`[bridge-core] preloadSessions: loaded ${n} session(s) from gateway`)}catch(e){this.logger.debug?.("[bridge-core] preloadSessions failed:",e)}else this.logger.debug?.("[bridge-core] preloadSessions skipped: gateway not connected")}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 handleSessionNew(e){const t=`agent:${"string"==typeof e.params?.agentId&&e.params.agentId||this.config.gateway.agentId||this.getDefaultAgentId()}:${randomUUID()}`,s="string"==typeof e.params?.cwd?e.params.cwd:".",n=createSessionObject({gatewayKey:t,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,cwd:s});this.registerSession(n,{ensureVerbose:!1}),this.transport.sendResult(e.id,{sessionId:n.sessionId,modes:{availableModes:[{...DEFAULT_MODE}],currentModeId:DEFAULT_MODE.id},_meta:{sessionKey:t,agentId:n.agentId,platformAgentId:n.platformAgentId??null}}),this.fetchHistoryInBackground(t)}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 n=this.state.sessionsByGatewayKey.get(t);if(!n)return;const i=e.message?.role;if("toolResult"===i||"tool"===i)return void this.handlePersistedToolResultMessage(n,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"===i?"user":"system"===i?"system":"assistant",o=n.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,c="number"==typeof a&&a>0?new Date(a).toISOString():void 0,d={turnId:o};"number"==typeof e.messageSeq&&(d.seq=e.messageSeq),this.transport.sendSessionUpdate(n.sessionId,{sessionUpdate:"message_id_bind",role:r,messageId:s,...c?{timestamp:c}:{}},d),n.lastTurnIdByRole&&(n.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:n,turnId:o,messageId:s,runId:void 0})}async handlePersistedToolResultMessage(e,t){const s=t.messageId;if(!s)return;const n=extractPersistedToolResultEnvelope(t.message),i=this.extractPersistedToolResultFromHistory(e,s),r=mergePersistedToolResultEnvelopes(i,n);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}});i&&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 c=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:c,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 n=s.sessions;if(!Array.isArray(n))return;for(const t of n){const s=t,n=s.sessionKey??s.key??s.id??s.name;if(n&&"string"==typeof n&&deriveSessionId(n,this.instanceId)===e){const e=s.label||s.derivedTitle||s.title||void 0,t=e&&!isPlaceholderTitle(e)?e:void 0,i=createSessionObject({gatewayKey:n,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,title:t});return this.registerSession(i),i}}}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:"),n=this.config.gateway.agentId||this.getDefaultAgentId();return t=createSessionObject({gatewayKey:s?e:`agent:${n}:${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),n=s.sessionId;this.state.lastActiveSessionId=n,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:n}),this.onSessionLoaded?.(n,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 n=this.getGateway(),i=e.assistantMq&&!e.assistantMq.closed,r=i?null:n,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),c=a.filter(e=>"user"===e.role).length,d=a.filter(e=>"assistant"===e.role).length,l=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=${c} asstTurns=${d} turnsWithToolCalls=${l} totalToolCalls=${m}`),c>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 n=cleanHistoryUserContent(t.content).slice(0,64).replace(/\n/g," ").trim();if(n){e.title=n,e.titleSource="truncated";const t=this.getGateway();t?.isConnected&&t.sessionsPatch(e.gatewaySessionKey,{label:n}).catch(()=>{}),this.transport.sendSessionUpdate(s,{sessionUpdate:"title_update",title:n}),this.tryGenerateTitleFromHistory(e,s,a)}}}const u=t=>`history:${e.gatewaySessionKey}:${t}`;let p=-1;if(i)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(i),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,n){const i=e.sessionId,r=new Set;let o=0;for(let a=0;a<t.length;a++){const c=t[a],d=n.turnIdFor(c,a);if(n.mqActive&&a===n.lastAsstIdx){const e=classifyHistoricalAssistantTurnCompletion(c,{mqActive:n.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"===c.role&&"internal_system"===c.provenance?.kind){this.logger.debug?.(`[bridge-core] SKIP history_turn[${a}] internal_system user message`);continue}if("user"===c.role&&/^\s*system\s*\(untrusted[^)]*\)/i.test(c.content)){this.logger.debug?.(`[bridge-core] SKIP history_turn[${a}] system-injected user message`);continue}if("user"===c.role&&isHeartbeatPromptText(c.content)){this.logger.info?.(`[bridge-core] SKIP history_turn[${a}] heartbeat cron prompt sessionId=${e.sessionId} contentLen=${c.content.length} preview="${previewSanitizedText(c.content)}"`);continue}if("user"===c.role&&isCronPromptText(c.content)){this.logger.info?.(`[bridge-core] SKIP history_turn[${a}] cron-triggered user message sessionId=${e.sessionId} contentLen=${c.content.length} preview="${previewSanitizedText(c.content)}"`);continue}if("assistant"===c.role){const t=classifyHeartbeatFilter(c.content);if(t.filtered){this.logger.info?.(`[bridge-core] SKIP history_turn[${a}] heartbeat assistant reply reason=${t.reason} sessionId=${e.sessionId} contentLen=${c.content.length} preview="${previewSanitizedText(c.content)}"`);continue}}const l="assistant"===c.role?classifyHistoricalAssistantTurnCompletion(c,{mqActive:n.mqActive,isSkippedForLiveMq:!1}):void 0;if("error"===l?.kind||"interrupted"===l?.kind&&l.failure)s.sendSessionUpdate(i,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:""},...c.timestamp?{timestamp:c.timestamp}:{}},{turnId:d,...void 0!==c._seq?{seq:c._seq}:{}}),s.sendSessionUpdate(i,{sessionUpdate:"stream_complete",stopReason:l.stopReason,error:l.message,errorCode:l.errorCode},{turnId:d}),this.logger.info?.(`[bridge-core] history_runtime_failure_terminalized session_id=${i} turn_id=${d} error_code=${l.errorCode} stop_reason=${l.stopReason} source=history_replay`),o+=1;else if("system"!==c.role)if(this.logger.debug?.(`[bridge-core] SENDING history_turn[${a}] role=${c.role} contentLen=${c.content.length} content=${JSON.stringify(c.content.slice(0,80))} tcCount=${c.toolCalls?.length??0}`),"user"===c.role)this.replayUserTurnAsChunks(s,i,c.content,c.metadata,c.timestamp,d,c._seq);else{if(await this.replayAssistantTurnAsStream(s,i,c,d),c.toolCalls)for(const e of c.toolCalls)e.id&&r.add(e.id);const e=l??classifyHistoricalAssistantTurnCompletion(c,{mqActive:n.mqActive,isSkippedForLiveMq:!1});if("interrupted"===e.kind){const t=new Set(e.incompleteToolCallIds);for(const n of c.toolCalls??[])t.has(n.id)&&s.sendSessionUpdate(i,buildToolCallUpdatePayload({toolCallId:n.id,toolName:n.name,outputText:e.message,kind:n.kind,status:"failed",timestamp:c.timestamp}),{turnId:d});this.logger.info?.(`[bridge-core] history_orphan_turn_terminalized session_id=${i} turn_id=${d} tool_call_ids=${e.incompleteToolCallIds.join(",")} stop_reason=${e.stopReason} source=history_replay`),s.sendSessionUpdate(i,{sessionUpdate:"stream_complete",stopReason:e.stopReason,error:e.message,errorCode:e.errorCode},{turnId:d}),o+=1;continue}if("completed"!==e.kind)continue;s.sendSessionUpdate(i,{sessionUpdate:"stream_complete",stopReason:e.stopReason},{turnId:d}),o+=1}else this.logger.debug?.(`[bridge-core] SENDING system_message[${a}] contentLen=${c.content.length}`),s.sendSessionUpdate(i,{sessionUpdate:"system_message_chunk",content:{type:"text",text:c.content},metadata:c.metadata,...c.timestamp?{timestamp:c.timestamp}:{}},{turnId:d,...void 0!==c._seq?{seq:c._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 n="string"==typeof t.cursor&&t.cursor.length>0?t.cursor:void 0,i="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,{...n?{cursor:n}:{},limit:i,logger:this.logger}),c=groupIntoTurns(a.messages),d=new HistoryUpdateRecorder(this.transport);await this.replayHistoryTurnsToSink(r,c,d,{mqActive:!1,lastAsstIdx:-1,turnIdFor:(e,t)=>void 0!==e._seq?`history:${r.gatewaySessionKey}:seq:${e._seq}`:`history:${r.gatewaySessionKey}:seq:none:${n??"head"}:${t}`}),this.logger.debug?.(`[bridge-core] _beeos/session/history sid=${r.sessionId} cursor=${n??"<head>"} limit=${i} turns=${c.length} updates=${d.updates.length} hasMore=${a.hasMore} nextCursor=${a.nextCursor??"<none>"}`),this.transport.sendResult(e.id,{updates:d.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 n=e.assistantMq;if(n&&!n.closed){const s=n.peek(0);let i=0;if(t&&t.size>0)for(let e=0;e<s.length;e++){const n=s[e],r=n.sessionUpdate,o=n.toolCallId;if("tool_call"!==r&&"tool_call_update"!==r||!o||!t.has(o)){if("agent_message_chunk"===r){if(""===(n.content?.text??"").trim()&&e<s.length-1){const n=s[e+1];if(("tool_call"===n.sessionUpdate||"tool_call_update"===n.sessionUpdate)&&n.toolCallId&&t.has(n.toolCallId)){i=e+1;continue}}break}break}i=e+1}const r=resolveTurnId(e),o=r?{turnId:r}:void 0;for(let t=i;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 n=this.getGateway();if(n?.isConnected)try{const e=await n.sessionsList();if(e&&"object"==typeof e&&Array.isArray(e.sessions)){const n=e.sessions;for(const e of n){const n=e,i=n.sessionKey??n.key??n.id??n.name;if(!i||"string"!=typeof i)continue;if(isBackgroundSessionKey(i))continue;if(this.cronIsolatedSessionKeys.has(i))continue;const r=deriveSessionId(i,this.instanceId),o=s.find(e=>e.sessionId===i||e.sessionId===r||this.state.sessions.get(e.sessionId)?.gatewaySessionKey===i);if(!0===n.deleted){if(this.state.deletedGatewaySessionKeys.add(i),!t.includeDeleted)continue}else this.state.deletedGatewaySessionKeys.delete(i);const a=n.label||cleanGatewayDerivedTitle(n.derivedTitle)||n.title||void 0,c=a&&!isPlaceholderTitle(a)?a:void 0,d=n.model,l=n.modelProvider;if(o){if(c&&isPlaceholderTitle(o.title)){o.title=c;const e=this.state.sessions.get(o.sessionId);e&&isPlaceholderTitle(e.title)&&(e.title=c)}const e=n.updatedAt;e&&(o.updatedAt=e),d&&(o.model=d),l&&(o.modelProvider=l)}else{const e=createSessionObject({gatewayKey:i,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,cwd:n.cwd,title:c});this.registerSession(e,{ensureVerbose:!1}),s.push({sessionId:e.sessionId,title:c||"",cwd:n.cwd,updatedAt:n.updatedAt,agentId:e.agentId,platformAgentId:e.platformAgentId,deletable:!isSystemDefaultSessionKey(i),model:d,modelProvider:l})}}}}catch(e){this.logger.debug?.("[bridge-core] sessions.list enrichment failed:",e)}const i=t.includeDeleted?s:s.filter(e=>{const t=this.state.sessions.get(e.sessionId)?.gatewaySessionKey;return!t||!this.state.deletedGatewaySessionKeys.has(t)});i.sort((e,t)=>(t.updatedAt??0)-(e.updatedAt??0)||e.sessionId.localeCompare(t.sessionId)),this.transport.sendResult(e.id,{sessions:pageRuntimeSessions(i,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 n=s.slice(0,64),i=this.state.sessions.get(t);if(i)try{const s=await this.dispatchLegacyConversationCapability("session.rename",i,{title:n});i.title=s.title,i.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)}`),i.title=n,i.titleSource="manual",this.transport.sendResult(e.id,{sessionId:t,title:n})}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,n){if(this.isGuardMessage(s))return void this.logger.info?.(`[bridge-core] title-gen SKIP guard message sid=${t}`);const i=this.matchTitleTemplate(s);if(i){e.title=i,e.titleSource="template";const s=this.getGateway();return s?.isConnected&&s.sessionsPatch(e.gatewaySessionKey,{label:i}).catch(()=>{}),void this.transport.sendSessionUpdate(t,{sessionUpdate:"title_update",title:i})}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(n)}`;this.logger.info?.(`[bridge-core] title-gen CALLING LLM sid=${t} q="${s.slice(0,60)}" aLen=${n.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 n=await s.json(),i=n.choices?.[0]?.message?.content?.trim();if(!i)return;const r=i.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 n=this.getGateway();if(!n?.isConnected)return;let i=s;if(!i)try{const t=await loadHistory(n,e.gatewaySessionKey);i=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=i.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=i.indexOf(r),a=i.slice(o+1).find(e=>"assistant"===e.role&&!!e.content?.trim());if(!a)return;const c=cleanHistoryUserContent(r.content),d=a.content.trim();c&&d&&this.generateTitleFromQA(e,t,c,d)}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 n=s.gatewaySessionKey,i=this.sessionMutationCoordinator.tryStartExclusive({sessionKey:n,label:"session_delete"},"acp");if(!i.ok)return void this.sendSessionBusy(s,e.id,"active_session_mutation",i.queueDepth);const r=i.token;try{if(this.hasActiveRun(s)){const t=this.sessionMutationCoordinator.gateSnapshot(n);return void this.sendSessionBusy(s,e.id,"active_session_mutation",t.queueDepth)}this.logger.info?.(`[bridge-core] session/delete sessionId=${t} gatewayKey=${n} gwConnected=${!!this.getGateway()?.isConnected}`);let i=!1;const r=this.getGateway();if(r?.isConnected&&n)try{await r.sessionsDelete(n),i=!0,this.logger.info?.(`[bridge-core] Gateway sessions.delete SUCCESS for key=${n}`)}catch(t){const s=t instanceof Error?t.message:String(t);if(this.logger.info?.(`[bridge-core] Gateway sessions.delete FAILED for key=${n}: ${s}`),!s.includes("Cannot delete the main session"))return void this.transport.sendResult(e.id,{deleted:!1});try{await r.sessionsReset(n),i=!0,this.logger.info?.(`[bridge-core] Gateway sessions.reset SUCCESS for key=${n}`)}catch(t){return this.logger.warn?.(`[bridge-core] Gateway sessions.reset also failed for key=${n}: ${t instanceof Error?t.message:t}`),void this.transport.sendResult(e.id,{deleted:!1})}}else n&&this.logger.warn?.(`[bridge-core] Gateway not connected, proceeding with local-only delete for key=${n}`);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(n),this.state.deletedGatewaySessionKeys.add(n),this.transport.resetSessionUpdateCount(t),i&&this.onSessionDeleted?.(n),this.logger.info?.(`[bridge-core] session/delete DONE sessionId=${t} gatewayKey=${n} 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 n=this.getGateway(),i=n?.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(i&&r){const e=await this.sessionMutationCoordinator.requestCancel(r,n);o="recovery_required"===await this.handleCancellationResult(s,e)}else i&&await n.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,n=t?this.state.sessions.get(t):void 0;if(t&&s)if(n)try{const t=await this.dispatchLegacyConversationCapability("session.setMode",n,{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,n="string"==typeof s?.sessionId?s.sessionId:void 0;if(!n||!s||!Object.prototype.hasOwnProperty.call(s,"model"))return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId, model"});const i=s.model;if(null!==i&&("string"!=typeof i||0===i.length||i.trim()!==i))return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"model must be a non-empty string or null"});const r=n?this.state.sessions.get(n):void 0;if(r)try{const t=await this.dispatchLegacyConversationCapability("session.setModel",r,{modelOverrideId:i});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 n=Date.now(),i=createHash("sha256").update(JSON.stringify(e)).digest("hex");return{operationId:t,runtimeInstanceUid:this.instanceId,dispatchEpoch:s,paramsHash:i,idempotencyKeyHash:createHash("sha256").update(t).digest("hex"),claimDeadline:new Date(n+3e4).toISOString(),executionDeadline:new Date(n+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,n){return{name:e,params:s,context:{...this.canonicalContextBase(s,n.operationId,n.runtimeEpoch),scope:"agent",agent:{runtimeLocalKey:t,runtimeAgentUid:await this.runtimeAgentIdentities.resolveOrCreate(t)}}}}async dispatchLegacyAgentCapability(e,t,s){const n=normalizeRuntimeAgentLocalKey(t),i=await this.runtimeLeases.claim(this.createOperationId());let r=!1;try{const t={name:e,params:s,context:{...this.canonicalContextBase(s,i.operationId,i.runtimeEpoch),scope:"agent",agent:{runtimeLocalKey:n,runtimeAgentUid:await this.runtimeAgentIdentities.resolveOrCreate(n)}}},o=this.runtimeCommands.dispatch(t,this.acpExecutionAttempt(t));return r=!0,await o.completion}finally{r||await this.runtimeLeases.release(i)}}async dispatchLegacyInstanceCapability(e,t){const s=await this.runtimeLeases.claim(this.createOperationId());let n=!1;try{const i={name:e,params:t,context:{...this.canonicalContextBase(t,s.operationId,s.runtimeEpoch),scope:"instance"}},r=this.runtimeCommands.dispatch(i,this.acpExecutionAttempt(i));return n=!0,await r.completion}finally{n||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 n;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,i=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}),c=createHash("sha256").update(canonicalizeJcs(a)).digest("hex");n={definition:{definitionRef:`acp-mcp:sha256:${c}`,version:"local-v1",sha256:c,...i?{credentialRef:await requireCredentialReferencePort(this.mcpCredentialReferences).put({serverName:s,material:i})}:{}},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?.(n.definition,n.config);try{await this.dispatchLegacyInstanceCapability("mcp.set",{name:s,definition:n.definition})}catch(e){if(n.definition.credentialRef){!await this.mcp.removeCredentialIfUnreferenced(n.definition.credentialRef)&&this.mcpCredentialReferences?.owns(n.definition.credentialRef)&&await this.mcpCredentialReferences.remove(n.definition.credentialRef)}throw e}this.transport.sendResult(e.id,{ok:!0,restarting:!0})}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:!0})}async dispatchLegacyConversationCapability(e,t,s){const n=await this.runtimeLeases.claim(this.createOperationId());let i=!1;try{const r={name:e,params:s,context:{...this.canonicalContextBase(s,n.operationId,n.runtimeEpoch),scope:"conversation",conversation:{runtimeConversationUid:t.sessionId,runtimeSessionKey:t.gatewaySessionKey}}},o=this.runtimeCommands.dispatch(r,this.acpExecutionAttempt(r));return i=!0,await o.completion}finally{i||await this.runtimeLeases.release(n)}}async dispatchLegacyTerminalCapability(e,t,s,n){const i=await this.runtimeLeases.claim(this.createOperationId());let r=!1;try{const o={name:e,params:n,context:{...this.canonicalContextBase(n,i.operationId,i.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(i)}}async dispatchLegacyCanvasNotification(e,t){const s=t&&"object"==typeof t?t:{},n=e.replace("/","."),i="canvas.toggle"===n?{visible:!0===s.visible||!0===s.enabled}:"canvas.reference"===n?{surfaceId:"string"==typeof s.surfaceId?s.surfaceId:""}:"canvas.dimensions"===n?{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 c=!1;try{const e={name:n,params:i,context:{...this.canonicalContextBase(i,a.operationId,a.runtimeEpoch),scope:"canvas",canvas:{canvasId:o,sessionId:r}}},t=this.runtimeCommands.dispatch(e,this.acpExecutionAttempt(e));c=!0,await t.completion}finally{c||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),n=await this.runtimeLeases.claim(this.createOperationId());let i=!1;try{const r="cron.add"===e?{...t,runtimeCronJobUid:`runtime-cron:${n.operationId}`}:"cron.run"===e?{...t,runToken:`runtime-run:${n.operationId}`}:t,o={name:e,params:r,context:{...this.canonicalContextBase(r,n.operationId,n.runtimeEpoch),scope:"agent",agent:{runtimeLocalKey:s,runtimeAgentUid:await this.runtimeAgentIdentities.resolveOrCreate(s)}}},a=this.runtimeCommands.dispatch(o,this.acpExecutionAttempt(o));return i=!0,await a.completion}finally{i||await this.runtimeLeases.release(n)}}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(),n=this.runtimeCommands.dispatch(e,this.acpExecutionAttempt(e));s=!0;const i=await n.completion;return queueMicrotask(()=>{this.observeAgentProjection()}),i}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,n)=>{s=setTimeout(()=>n(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(),n=await this.runtimeLeases.claim(s),i=await this.finishClaimedLegacyAgentMutation(n,async()=>{const s=await this.runtimeAgentIdentities.allocateCreate(n,"agent.create"),i=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}:{},...i.length?{bootstrapFiles:i}:{}},n)});this.transport.sendResult(e.id,{agentId:i.runtimeLocalKey,platformAgentId:this.resolvePlatformAgentId(i.runtimeLocalKey)??"",workspace:i.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 n=await this.runtimeCommandResources.registerArtifact(s,e.params?.sha256),i=this.createOperationId(),r=await this.runtimeLeases.claim(i),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:n,...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 n=await this.runtimeLeases.claim(this.createOperationId()),i=await this.finishClaimedLegacyAgentMutation(n,()=>this.agentCommand("agent.update",t,s,n));this.transport.sendResult(e.id,{agentId:i.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()),n=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:n.runtimeLocalKey,...void 0===n.removedBindings?{}:{removedBindings:n.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}:{}})),n={...t.defaultRuntimeLocalKey?{defaultId:t.defaultRuntimeLocalKey}:{},agents:s};this.transport.sendResult(e.id,n)}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 n=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})),i=await this.getSkillsDir(e);for(const e of n){const t=e.skillKey??e.name;try{const s=await readFile(join(i,t,".beeos-meta.json"),"utf8"),n=JSON.parse(s);n?.iconUrl&&(e.iconUrl=n.iconUrl)}catch{}}return n}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",{}),n=normalizeAgentId(e),i=s?.agents?.find(e=>normalizeAgentId(e.id)===n);return i?.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,n=t?.files,i=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(n?.length||s)try{let o;if(s){o=parseSkillZip(await fetchWithRetry(s,{maxRetries:4,logger:this.logger}))}else{if(!n?.length)throw new RuntimeCommandError("INVALID_PARAMS","Missing skill files or zipUrl");o=new Map;for(const e of n){const t=normalizeSkillArtifactPath(e.path),s=await fetch(e.downloadUrl,{signal:AbortSignal.timeout(12e4)});if(!s.ok)throw new Error(`Failed to download ${e.path}: ${s.status}`);o.set(t,new Uint8Array(await s.arrayBuffer()))}}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",i,{artifact:a}),this.transport.sendResult(e.id,{success:!0}),this.onSkillInstalled?.(r,resolveSkillInstallDir(await this.getSkillsDir(i),r)),await this.pushSkillsList(i)}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 n;try{n=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:n}),this.transport.sendResult(e.id,{success:!0}),await this.pushSkillsList(s)}catch(t){this.logger.error?.(`[bridge-core] Failed to uninstall skill "${n}": ${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,n=t?.enabled,i=t?.agentId;if(s&&"boolean"==typeof n)try{await this.dispatchLegacyAgentCapability("skills.setEnabled",i,{skillKey:s,enabled:n}),this.logger.info?.(`[bridge-core] Updated skill "${s}" enabled=${n}${i?` for agent "${i}"`:""}`),this.transport.sendResult(e.id,{ok:!0,skillKey:s,enabled:n}),await this.pushSkillsList(i)}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:n,created:i}=await this.resolveOrCreateSession(t);i&&this.onSessionLoaded?.(n.sessionId,n.gatewaySessionKey,n.platformAgentId);const r=n.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(n)){const t=this.sessionMutationCoordinator.gateSnapshot(n.gatewaySessionKey);return void this.sendSessionBusy(n,e.id,"active_run",t.queueDepth)}try{await this.ensureVerboseFull(n)}catch(t){return this.releaseSessionWriteGate(n),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 c=a.filter(e=>"text"===e.type&&"text"in e&&"string"==typeof e.text).map(e=>e.text).join("\n");if(n.fileArtifactDisplayMode=prefersChatFileArtifacts(c)?"chat":"auto",!n.title||isPlaceholderTitle(n.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="${n.title}" cleanText="${t.slice(0,80)}" isPlaceholder=${isPlaceholderTitle(t)}`),t&&!isPlaceholderTitle(t)){const e=t.slice(0,64).replace(/\n/g," ").trim();n.title=e,n.titleSource="truncated",o?.isConnected&&e&&o.sessionsPatch(n.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 d=buildResolutionPlan(a);if(d.refs.length>0)try{const e=await resolveResources(d,this.writeObs);a=applyResolutions(a,e)}catch(e){this.logger.warn?.(`[bridge-core] Resource pre-resolution failed: ${e instanceof Error?e.message:e}`)}let l;if(this.beeosFileResolver){const e=this.beeosFileResolver.buildResolutionPlan(a);if(e.refs.length>0)try{l=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:l});if("error"in m)return this.releaseSessionWriteGate(n),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(n,a,resolveTurnId(n)),this.transport.sendSessionUpdate(r,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Loading ${h}...`},timestamp:(new Date).toISOString()},{turnId:resolveTurnId(n)}),this.transport.sendResult(e.id,{stopReason:"end_turn"}),void this.releaseSessionWriteGate(n)}const y="chat.send";let f=g?u:withUserMessagePrefix(u);const w=this.config.canvasEnabled&&!g&&!0===n.canvasActive&&!n.channelType;if(w){const e=n.promptsSinceCanvasInjection??0;!n.canvasPromptInjected||e>=10?(f=`${CANVAS_TERM_MAPPING}\n\n${f}`,n.canvasPromptInjected=!0,n.promptsSinceCanvasInjection=0,this.logger.debug?.("[bridge-core] Canvas term mapping injected (re-inject cycle)")):n.promptsSinceCanvasInjection=e+1}if(w){const e=this.getCanvasState?.();if(e){const t=e.resolveCanvasForSession(n.gatewaySessionKey);f=`${buildActiveSurfacesContext(e,t)??"[Canvas] Canvas panel is available. Use render_ui for structured/visual content."}\n\n${f}`}const t=n.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}`,n.referencedSurfaceId=void 0)}if(!g){const t=parseMentionsParam(e.params?.mentions);if(t.length>0){n.activeMentions=t;f=`${buildMentionInstruction(t)}\n${f}`,this.logger.debug?.(`[bridge-core] delegation mention instruction injected for ${t.length} agent(s)`)}else n.activeMentions=void 0}if(g&&this.logger.info?.(`[bridge-core] slash command passthrough sessionId=${r} command=/${h}`),this.hasActiveRun(n)){const t=this.sessionMutationCoordinator.gateSnapshot(n.gatewaySessionKey);return void this.sendSessionBusy(n,e.id,"active_run_after_prepare",t.queueDepth)}const I=this.sessionMutationCoordinator.tryStartInteractive({sessionKey:n.gatewaySessionKey,label:"session/prompt"},"acp");if(!I.ok)return void this.sendSessionBusy(n,e.id,I.reason,I.queueDepth);n.writeGateToken=I.token,this.state.resetForNewRun(n,r,this.transport),n.pendingPromptId=e.id,n.gatewayMethod=y;const v=resolveTurnId(n);this.emitPromptAsUserSessionUpdates(n,a,v),this.transport.sendSessionUpdate(r,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:""},timestamp:(new Date).toISOString()},v?{turnId:v}:void 0);const S=extractCronJobId(u);S&&(n.cronJobId=S),this.schedulePromptTimeout(n);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,"")}`,b={sessionKey:n.gatewaySessionKey,message:f,deliver:!1,idempotencyKey:randomUUID()};C?.length&&(b.attachments=C);if(!o.sendFrame({type:"req",id:R,method:y,params:b}))return this.state.clearPromptTimeout(n),n.pendingPromptId=void 0,n.assistantMq?.close(),n.assistantMq=void 0,n.pendingUserTurnUpdates=void 0,this.releaseSessionWriteGate(n),void this.transport.sendAcpError(e.id,Errors.SendFailed,{message:"failed to send prompt to gateway"});n.gatewayRequestId=R,this.state.promptsByGatewayRequestId.set(R,n)}replayUserTurnAsChunks(e,t,s,n,i,r,o){const a=splitUserReplayBlocks(s),c=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,...n?{metadata:n}:{},...i?{timestamp:i}:{}},c)}}async replayAssistantTurnAsStream(e,t,s,n){const i=e=>{if(n||void 0!==e)return{...n?{turnId:n}:{},...void 0!==e?{seq:e}:{}}},r=new Set,o=(s,n,o)=>{if(!s?.length)return;const a=i(o);for(const i of s)i.uri&&!r.has(i.uri)&&(r.add(i.uri),e.sendSessionUpdate(t,{sessionUpdate:"agent_message_chunk",content:{type:"resource_link",uri:i.uri,name:i.name??"file",...i.mimeType?{mimeType:i.mimeType}:{}},...n?{timestamp:n}:{}},a))},a=i(s._seq);if(!s.sourceMessages?.length){const n={sessionUpdate:"history_turn",role:s.role,content:s.content,reasoning:s.reasoning,toolCalls:s.toolCalls,...s.timestamp?{timestamp:s.timestamp}:{}};return s.metadata&&(n.metadata=s.metadata),e.sendSessionUpdate(t,n,a),void o(s.files,s.timestamp,s._seq)}for(const n of s.sourceMessages){const r=n.updateType??"agent_message_chunk",a=i(n._seq);switch(r){case"agent_message_chunk":e.sendSessionUpdate(t,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:n.content},...n.timestamp?{timestamp:n.timestamp}:{},...n.metadata?{metadata:n.metadata}:{}},a);break;case"agent_thought_chunk":e.sendSessionUpdate(t,{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n.content},...n.timestamp?{timestamp:n.timestamp}:{}},a);break;case"tool_call":{const i=n.toolCallId??"",r=s.toolCalls?.find(e=>e.id===i),o=n.toolName??"tool",c=n.content??"";let d={};if(c)try{d=JSON.parse(c)}catch{}e.sendSessionUpdate(t,buildToolCallPayload({toolCallId:i,toolName:o,args:d,kind:r?.kind,status:r?.status??"in_progress",timestamp:n.timestamp}),a);break}case"tool_call_update":{const i=n.toolCallId??"",r=s.toolCalls?.find(e=>e.id===i),c=n.toolName??r?.name??"tool",d=n.content??r?.output??"",l=await this.resolveReplayResourceLinks(i,c,n.files);e.sendSessionUpdate(t,buildToolCallUpdatePayload({toolCallId:i,toolName:c,outputText:d,kind:r?.kind,status:r?.status??"completed",resourceLinks:l,timestamp:n.timestamp}),a),o(l,n.timestamp,n._seq);break}}}o(s.files,s.timestamp,s._seq)}async resolveReplayResourceLinks(e,t,s){let n=s?.map(e=>({uri:e.uri,name:e.name??"file",...e.mimeType?{mimeType:e.mimeType}:{}}));if(n?.length)return n;if(n=await readEnrichmentCache(e).catch(()=>{}),n?.length)return n;if("beeos_upload_file"!==t)return;const i=await readUploadToolResult(e).catch(()=>{});if(!i)return;const r=buildToolResultSessionContentBlocks(t,i).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 n=(new Date).toISOString(),i=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:n};s&&void 0===o._turnId&&(o._turnId=s),this.transport.sendSessionUpdate(e.sessionId,o,i),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,n=t.mimeType??t.mime_type??e.mimeType??e.mime_type,i=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&&!i&&!r)return;return{type:"resource",resource:{...s?{uri:s}:{},...n?{mimeType:n}:{},...i?{text:i}:{},...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 n=this.state.sessions.get(s);if(!n)return void(void 0!==e&&this.transport.sendAcpError(e,Errors.SessionNotFound));const i=n.activeRunBinding??this.observeActiveRun(n);if(!i){const t=this.sessionMutationCoordinator.snapshot(n.gatewaySessionKey);if("exclusive"===t?.attachmentPolicy&&void 0!==e){const t=this.sessionMutationCoordinator.gateSnapshot(n.gatewaySessionKey);return void this.sendSessionBusy(n,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,n={targetMessageId:i.targetMessageId,...s?{reason:s}:{}},a={name:"session.cancel",params:n,context:{...this.canonicalContextBase(n,r.operationId,r.runtimeEpoch),scope:"conversation",historyGeneration:i.historyGeneration,conversation:{runtimeConversationUid:i.runtimeConversationUid,runtimeSessionKey:i.runtimeSessionKey}}},c=this.runtimeCommands.dispatch(a,this.acpExecutionAttempt(a));o=!0,await c.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,n){this.logger.warn?.(`[bridge-core] session_write_gate_busy session_id=${e.sessionId} gateway_session_key=${e.gatewaySessionKey} reason=${s} queue_depth=${n}`),this.transport.sendError(t,Errors.AgentError.rpcCode,"Agent is busy",{code:"session_busy",reason:s,queueDepth:n}),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,n=e.activeRunBinding;let i,r,o,a,c="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"===c.kind?"cancelled"===c.stopReason?"cancelled":"completed":"interrupted"===c.kind&&"timeout"===c.stopReason?"timeout":"error",t=await this.sessionMutationCoordinator.converge(s,e);t.ok?i=t.permit:c={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 n=e.currentRunId;if("complete"===c.kind){if(n&&this.onRunComplete){const t=e.agentAssistantTextSoFar??e.chatAssistantTextSoFar??"";this.onRunComplete(n,t,c.stopReason)}void 0!==e.pendingPromptId&&this.transport.sendResult(e.pendingPromptId,{stopReason:c.stopReason}),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:c.stopReason},s),this.tryGenerateTitleFromHistory(e,e.sessionId)}else"interrupted"===c.kind?(n&&this.onRunFailed&&this.onRunFailed(n,c.message),void 0!==e.pendingPromptId&&this.transport.sendError(e.pendingPromptId,Errors.AgentError.rpcCode,c.message,{code:c.errorCode??"interrupted",stopReason:c.stopReason}),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:c.stopReason,error:c.message,...c.errorCode?{errorCode:c.errorCode}:{}},s)):(n&&this.onRunFailed&&this.onRunFailed(n,c.message),void 0!==e.pendingPromptId&&this.transport.sendError(e.pendingPromptId,c.code,c.message),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:"error",error:c.message},s))}catch(e){r=e}try{this.cleanupPrompt(e)}catch(e){o=e}finally{e.writeGateToken=void 0,e.activeRunBinding=void 0,i&&this.sessionMutationCoordinator.release(i)}if(n){const e="complete"===c.kind?"cancelled"===c.stopReason?"cancelled":"completed":"interrupted"===c.kind&&"cancelled"===c.stopReason?"cancelled":"failed";this.activeRuns.markTerminal(n,e)}try{this.onRunEnded?.(e,c)}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(),n=e.writeGateToken;s?.isConnected&&n?this.observeLifecycle(this.sessionMutationCoordinator.requestCancel(n,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):n&&(this.sessionMutationCoordinator.requireRecovery(n,"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 n=e.error,i=n?.message??"gateway returned error";this.logger.warn?.(`[bridge-core] handleGatewayResponse: gateway rejected prompt gatewayRequestId=${t} error=${i}`);const r=classifyAgentRuntimeFailure({raw:i,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 n=e.payload,i=n?.runId;i?(s.currentRunId=i,this.sessionMutationCoordinator.bindRun(s.writeGateToken,i),this.observeActiveRun(s),s.assistantStreamStartedAt=Date.now(),this.state.promptsByRunId.set(i,s),this.logger.debug?.(`[bridge-core] handleGatewayResponse: bound runId=${i} 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",n=classifyAgentRuntimeFailure({raw:s,source:"chat_state",runtimeKind:"openclaw"});"interrupted"===n.kind?this.observeLifecycle(this.interruptPrompt(e,n),"chat_state_interrupt",e):(this.logRuntimeFailure(e,n),this.observeLifecycle(this.failPrompt(e,Errors.AgentError.rpcCode,n.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("/","."),n={...e.params??{}};["cron.add","cron.update","cron.remove","cron.run","cron.runs"].includes(s)&&(n.__beeosCronIngress="acp"),"cron.update"===s&&(n.patch=n.patch&&"object"==typeof n.patch?{...n.patch}:{});try{const t=await this.dispatchLegacyCronCapability(s,n),i=await this.mapCronResultForAcp(s,t);this.transport.sendResult(e.id,i??{}),"cron.add"!==s&&"cron.update"!==s&&"cron.remove"!==s||this.refreshCronIsolatedSessionKeys()}catch(t){const n=t instanceof Error?t.message:"cron request failed";this.logger.warn?.(`[bridge-core] ${s} failed: ${n}`),this.transport.sendAcpError(e.id,Errors.SendFailed,{message:n})}}async mapCronResultForAcp(e,t){if(!t||"object"!=typeof t)return t;const s=t;await this.cronOverrides.snapshot();const n="cron.list"===e||"cron.status"===e,i=e=>{if(!e||"object"!=typeof e)return e;const t=e,s=t.id;if("string"!=typeof s)return e;const i=this.cronOverrides.localId(s)??s,r=this.cronChannelCache.get(i),o=r?encodeBeeosChannelTag("string"==typeof t.description?t.description:void 0,r):t.description,a=this.cronOverrides.get(i);return{...t,id:i,...void 0===o?{}:{description:o},...n&&"number"==typeof a?{_beeos_meta:{maxDurationMs:a}}:{}}};if(Array.isArray(s.jobs))return{...s,jobs:s.jobs.map(i)};if(s.jobs&&"object"==typeof s.jobs){const e=s.jobs,t={};for(const[s,n]of Object.entries(e))t[s]=i(n);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?i(t):t}async allocateCronChannel(e){if(this.agentFetch&&this.agentGatewayUrl)try{const t=`${this.agentGatewayUrl}/api/v1/channels`,s=await this.agentFetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({participants:[this.instanceId,"service:cron"],metadata:{source:"cron",job_name:e}})});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}`)}else this.logger.debug?.("[bridge-core] agentFetch/agentGatewayUrl unavailable, skip channel alloc")}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 n=new Set,i=[];for(const e of s){if(!e||"object"!=typeof e)continue;const t=e;if("string"==typeof t.id&&i.push(t.id),"isolated"!==t.sessionTarget)continue;const s=t.sessionKey;"string"==typeof s&&s.length>0&&n.add(s)}this.cronIsolatedSessionKeys=n,await this.cronOverrides.reconcile(i)}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 n;for(let i=0;i<=s;i++){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**i);if(n=new Error(`HTTP ${r.status} from ${e}`),i<s){t.logger?.info?.(`[bridge-core] Download ${r.status}, retry ${i+1}/${s} in ${(a/1e3).toFixed(0)}s`),await new Promise(e=>setTimeout(e,a));continue}}throw new Error(`Failed to download zip: ${r.status}`)}throw n??new Error("Download failed after retries")}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("/")),n=new Map;for(const e of t){const t=s?e.name.slice(e.name.indexOf("/")+1):e.name;if(!t||n.has(t))throw new RuntimeCommandError("INVALID_PARAMS",`Duplicate skill path: ${t}`);n.set(t,e.bytes)}return n}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),n=join(t,".beeos-extract-tmp-"+Date.now());try{await mkdir(n,{recursive:!0}),s.extractAllTo(n,!0);const e=await resolveSkillRoot(n),i=await readdir(e,{withFileTypes:!0});let r=0;for(const s of i){if(s.name.startsWith(".beeos-extract-tmp")||"__MACOSX"===s.name)continue;const n=join(e,s.name),i=join(t,s.name);await rename(n,i).catch(async()=>{await cp(n,i,{recursive:!0})}),r++}if(0===r)throw new Error("Zip archive contained no extractable files")}finally{await rm(n,{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 n=e.transport??("string"==typeof e.command?"stdio":"string"==typeof e.url?"streamable-http":void 0);if("stdio"===n&&t&&Object.keys(t).length)throw new Error("MCP stdio config cannot include headers");if("stdio"!==n&&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),n=join(e,s),i=resolve(e),r=resolve(n),o=relative(i,r);if(!o||".."===o||o.startsWith(`..${sep}`)||path.isAbsolute(o))throw new Error("Invalid skill target path");return n}
@@ -1 +1 @@
1
- import{listMcpServers,setMcpServer,unsetMcpServer,OpenClawCliError}from"../openclaw-cli.js";import{Errors}from"../errors/index.js";import{requireSecretFreeMcpServerName}from"./mcp-public-config-security.js";const RESTART_DEBOUNCE_MS=750;export class McpService{transport;logger;state;exit;restartTimer;list;set;unset;resolveDefinition;desiredState;desiredStateStarted=!1;constructor(e){this.transport=e.transport,this.logger=e.logger,this.state=e.state,this.exit=e.exit??(e=>process.exit(e)),this.list=e.list??listMcpServers,this.set=e.set??setMcpServer,this.unset=e.unset??unsetMcpServer,this.resolveDefinition=e.resolveDefinition,this.desiredState=e.desiredState}setRuntimeReceiptHistoryPort(e){this.desiredState?.setRuntimeReceiptHistoryPort(e)}async execute(e,t,r){const i=e;if("mcp.list"===i.name){if(this.desiredState){await this.ensureDesiredState();const e=await this.desiredState.list();if(e.servers.some(e=>void 0===e.config))throw new Error("Service MCP config is available only within its active operation");return{servers:e.servers.map(e=>({name:e.name,definitionRef:e.definitionRef,transport:e.config.transport,...e.config.url?{url:e.config.url}:{},...e.config.command?{command:e.config.command}:{},...e.config.args?{args:e.config.args}:{},...e.config.cwd?{cwd:e.config.cwd}:{},connected:e.connected,...e.config.connectionTimeoutMs?{connectionTimeoutMs:e.config.connectionTimeoutMs}:{}}))}}const e=await this.list();return{servers:Object.entries(e).map(([e,t])=>sanitizeMcpConfig(e,t))}}if(this.hasInFlightPrompts())throw new Error("PROMPT_IN_FLIGHT");if("service"===r.origin&&!this.desiredState)throw new Error("Service MCP mutations require the desired-state controller");if("mcp.set"===i.name){const e=i;requireSecretFreeMcpServerName(e.params.name);const t=r.resources.resolveMcpDefinition??("acp"===r.origin?this.resolveDefinition:void 0);if(!t)throw new Error("operation-scoped MCP definition resolver is not configured");const s=await t(e.params.definition);return this.desiredState?(await this.ensureDesiredState(),await this.desiredState.set(desiredServer(e.params.name,e.params.definition,publicConfig(s)),commitBinding(e,r)),{applied:!0,restartRequired:!1}):(await this.set(e.params.name,s),{applied:!0,restartRequired:!0})}const s=i.params.name;return requireSecretFreeMcpServerName(s),this.desiredState?(await this.ensureDesiredState(),await this.desiredState.unset(s,commitBinding(i,r)),{applied:!0,restartRequired:!1}):(await this.unset(s),{applied:!0,restartRequired:!0})}afterCommit(e){this.desiredState||"mcp.set"!==e.name&&"mcp.unset"!==e.name||this.scheduleRestart()}async projectCommitted(e,t,r){if(!this.desiredState||"mcp.set"!==e.name&&"mcp.unset"!==e.name)return;await this.ensureDesiredState();const i=e.params?.name;if("string"!=typeof i||!i)throw new Error("committed MCP projection lacks a server name");const s=r?"mcp.set"===e.name?{operationId:e.context.operationId,method:"mcp.set",source:"service"===r.origin?"service":"acp_local",paramsHash:e.context.paramsHash,runtimeEpoch:e.context.dispatchEpoch,expected:{name:i,definitionRef:e.params.definition.definitionRef,version:e.params.definition.version,sha256:e.params.definition.sha256,...e.params.definition.credentialRef?{credentialRef:e.params.definition.credentialRef}:{}}}:{operationId:e.context.operationId,method:"mcp.unset",source:"service"===r.origin?"service":"acp_local",paramsHash:e.context.paramsHash,runtimeEpoch:e.context.dispatchEpoch,expected:{name:i,absent:!0}}:void 0;let n;if("service"===r?.origin&&"mcp.set"===e.name){const t=e.params.definition,i=r.resources.resolveMcpDefinition;if(!i)throw new Error("operation-scoped MCP definition resolver is not configured");n={config:publicConfig(await i(t)),runtimeEpoch:r.runtimeEpoch,...r.resources.resolveMcpCredential?{credential:await r.resources.resolveMcpCredential(t)}:{}}}return n?await this.desiredState.project(i,r?.abortSignal,s,n):await this.desiredState.project(i,r?.abortSignal,s)}async removeCredentialIfUnreferenced(e){return!!this.desiredState&&(await this.desiredState.removeLocalCredentialIfUnreferenced(e),!0)}async handleList(e){try{if(this.desiredState){await this.ensureDesiredState();const t=await this.desiredState.list();return void this.transport.sendResult(e.id,{revision:t.revision,servers:t.servers})}const t=await this.list();this.transport.sendResult(e.id,{servers:t})}catch(t){this.logger.warn?.(`[mcp-service] list failed: ${t instanceof Error?t.message:t}`),this.sendMappedError(e,t,!0)}}async handleSet(e){const t=e.params,r=t?.name,i=t?.server;if(r&&i&&"object"==typeof i){if(!this.rejectIfInFlight(e))try{if(requireSecretFreeMcpServerName(r),this.desiredState){const t=asDesiredServer(r,i);return await this.ensureDesiredState(),await this.desiredState.set(t),await this.desiredState.project(r),this.logger.info?.(`[mcp-service] desired state applied name=${r}`),void this.transport.sendResult(e.id,{ok:!0,restarting:!1})}await this.set(r,i),this.logger.info?.(`[mcp-service] set applied name=${r}`),this.transport.sendResult(e.id,{ok:!0,restarting:!0}),this.scheduleRestart()}catch(t){this.logger.error?.(`[mcp-service] set failed name=${r}: ${t instanceof Error?t.message:t}`),this.sendMappedError(e,t,!1)}}else this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Missing 'name' or 'server' config"})}async handleUnset(e){const t=e.params,r=t?.name;if(r){if(!this.rejectIfInFlight(e))try{if(requireSecretFreeMcpServerName(r),this.desiredState)return await this.ensureDesiredState(),await this.desiredState.unset(r),await this.desiredState.project(r),void this.transport.sendResult(e.id,{ok:!0,restarting:!1});await this.unset(r),this.logger.info?.(`[mcp-service] unset applied name=${r}`),this.transport.sendResult(e.id,{ok:!0,restarting:!0}),this.scheduleRestart()}catch(t){this.logger.error?.(`[mcp-service] unset failed name=${r}: ${t instanceof Error?t.message:t}`),this.sendMappedError(e,t,!1)}}else this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Missing 'name'"})}hasInFlightPrompts(){for(const e of this.state.sessions.values())if(void 0!==e.pendingPromptId||void 0!==e.currentRunId)return!0;return!1}rejectIfInFlight(e){return!!this.hasInFlightPrompts()&&(this.transport.sendError(e.id,Errors.InvalidParams.rpcCode,"Agent is busy",{code:Errors.InvalidParams.code,reason:"PROMPT_IN_FLIGHT",message:"Agent is processing a message; please retry after it completes."}),!0)}scheduleRestart(){this.restartTimer&&clearTimeout(this.restartTimer),this.restartTimer=setTimeout(()=>{this.logger.info?.("[mcp-service] mcp change applied — exiting for container restart"),this.exit(0)},750)}async ensureDesiredState(){if(!this.desiredStateStarted){if(!this.desiredState)throw new Error("MCP desired-state controller is unavailable");await this.desiredState.start(),this.desiredStateStarted=!0}}async stop(){this.desiredState&&this.desiredStateStarted&&(this.desiredStateStarted=!1,await this.desiredState.stop())}sendMappedError(e,t,r){const i=cliErrToAcpError(t,r);this.transport.sendError(e.id,i.code,i.message,i.data)}}function desiredServer(e,t,r){return{name:e,definitionRef:t.definitionRef,version:t.version,sha256:t.sha256,...t.credentialRef?{credentialRef:t.credentialRef}:{},config:r}}function commitBinding(e,t){return{source:"service"===t.origin?"service":"acp_local",operationId:e.context.operationId,method:e.name,paramsHash:e.context.paramsHash,runtimeEpoch:e.context.dispatchEpoch}}function publicConfig(e){if(void 0!==e.headers||void 0!==e.env)throw new Error("resolved MCP secrets must not enter desired state");return{transport:e.transport??(e.command?"stdio":"streamable-http"),..."string"==typeof e.url?{url:e.url}:{},..."string"==typeof e.command?{command:e.command}:{},...Array.isArray(e.args)?{args:e.args}:{},..."string"==typeof e.cwd?{cwd:e.cwd}:{},..."number"==typeof e.connectionTimeoutMs?{connectionTimeoutMs:e.connectionTimeoutMs}:{}}}function asDesiredServer(e,t){const r=t;if("string"!=typeof r.definitionRef||"string"!=typeof r.version||"string"!=typeof r.sha256)throw new Error("ACP mcp/set requires a verified definitionRef, version and sha256");if(void 0!==r.headers||void 0!==r.env)throw new Error("ACP mcp/set accepts credentialRef, not resolved headers or env");return desiredServer(e,{definitionRef:r.definitionRef,version:r.version,sha256:r.sha256,..."string"==typeof r.credentialRef?{credentialRef:r.credentialRef}:{},..."number"==typeof r.connectionTimeoutMs?{connectionTimeoutMs:r.connectionTimeoutMs}:{}},publicConfig(t))}function sanitizeMcpConfig(e,t){const r=t.transport??(t.command?"stdio":"streamable-http");return{name:e,definitionRef:`runtime-mcp:${encodeURIComponent(e)}`,transport:r,..."number"==typeof t.connectionTimeoutMs?{connectionTimeoutMs:t.connectionTimeoutMs}:{},..."string"==typeof t.url?{url:t.url}:{},..."string"==typeof t.command?{command:t.command}:{},...Array.isArray(t.args)?{args:t.args}:{},..."string"==typeof t.cwd?{cwd:t.cwd}:{}}}export function cliErrToAcpError(e,t){if(e instanceof OpenClawCliError){const r=e.stderr??"";return null===e.exitCode||t?{code:Errors.InternalError.rpcCode,message:e.message,data:{code:Errors.InternalError.code}}:/No MCP server named/i.test(r)?{code:Errors.InvalidParams.rpcCode,message:e.message,data:{code:Errors.InvalidParams.code,reason:"NOT_FOUND"}}:{code:Errors.InvalidParams.rpcCode,message:e.message,data:{code:Errors.InvalidParams.code}}}return{code:Errors.InternalError.rpcCode,message:e instanceof Error?e.message:String(e),data:{code:Errors.InternalError.code}}}
1
+ import{listMcpServers,setMcpServer,unsetMcpServer,OpenClawCliError}from"../openclaw-cli.js";import{Errors}from"../errors/index.js";import{requireSecretFreeMcpServerName}from"./mcp-public-config-security.js";const RESTART_DEBOUNCE_MS=750;export class McpService{transport;logger;state;exit;restartTimer;list;set;unset;resolveDefinition;desiredState;desiredStateStarted=!1;constructor(e){this.transport=e.transport,this.logger=e.logger,this.state=e.state,this.exit=e.exit??(e=>process.exit(e)),this.list=e.list??listMcpServers,this.set=e.set??setMcpServer,this.unset=e.unset??unsetMcpServer,this.resolveDefinition=e.resolveDefinition,this.desiredState=e.desiredState}setRuntimeReceiptHistoryPort(e){this.desiredState?.setRuntimeReceiptHistoryPort(e)}async execute(e,t,r){const i=e;if("mcp.list"===i.name){if(this.desiredState){await this.ensureDesiredState();const e=await this.desiredState.list();if(e.servers.some(e=>void 0===e.config))throw new Error("Service MCP config is available only within its active operation");return{servers:e.servers.map(e=>({name:e.name,definitionRef:e.definitionRef,transport:e.config.transport,...e.config.url?{url:e.config.url}:{},...e.config.command?{command:e.config.command}:{},...e.config.args?{args:e.config.args}:{},...e.config.cwd?{cwd:e.config.cwd}:{},connected:e.connected,...e.config.connectionTimeoutMs?{connectionTimeoutMs:e.config.connectionTimeoutMs}:{}}))}}const e=await this.list();return{servers:Object.entries(e).map(([e,t])=>sanitizeMcpConfig(e,t))}}if(this.hasInFlightPrompts())throw new Error("PROMPT_IN_FLIGHT");if("service"===r.origin&&!this.desiredState)throw new Error("Service MCP mutations require the desired-state controller");if("mcp.set"===i.name){const e=i;requireSecretFreeMcpServerName(e.params.name);const t=r.resources.resolveMcpDefinition?.bind(r.resources)??("acp"===r.origin?this.resolveDefinition:void 0);if(!t)throw new Error("operation-scoped MCP definition resolver is not configured");const s=await t(e.params.definition);return this.desiredState?(await this.ensureDesiredState(),await this.desiredState.set(desiredServer(e.params.name,e.params.definition,publicConfig(s)),commitBinding(e,r)),{applied:!0,restartRequired:!1}):(await this.set(e.params.name,s),{applied:!0,restartRequired:!0})}const s=i.params.name;return requireSecretFreeMcpServerName(s),this.desiredState?(await this.ensureDesiredState(),await this.desiredState.unset(s,commitBinding(i,r)),{applied:!0,restartRequired:!1}):(await this.unset(s),{applied:!0,restartRequired:!0})}afterCommit(e){this.desiredState||"mcp.set"!==e.name&&"mcp.unset"!==e.name||this.scheduleRestart()}async projectCommitted(e,t,r){if(!this.desiredState||"mcp.set"!==e.name&&"mcp.unset"!==e.name)return;await this.ensureDesiredState();const i=e.params?.name;if("string"!=typeof i||!i)throw new Error("committed MCP projection lacks a server name");const s=r?"mcp.set"===e.name?{operationId:e.context.operationId,method:"mcp.set",source:"service"===r.origin?"service":"acp_local",paramsHash:e.context.paramsHash,runtimeEpoch:e.context.dispatchEpoch,expected:{name:i,definitionRef:e.params.definition.definitionRef,version:e.params.definition.version,sha256:e.params.definition.sha256,...e.params.definition.credentialRef?{credentialRef:e.params.definition.credentialRef}:{}}}:{operationId:e.context.operationId,method:"mcp.unset",source:"service"===r.origin?"service":"acp_local",paramsHash:e.context.paramsHash,runtimeEpoch:e.context.dispatchEpoch,expected:{name:i,absent:!0}}:void 0;let n;if("service"===r?.origin&&"mcp.set"===e.name){const t=e.params.definition,i=r.resources.resolveMcpDefinition?.bind(r.resources);if(!i)throw new Error("operation-scoped MCP definition resolver is not configured");n={config:publicConfig(await i(t)),runtimeEpoch:r.runtimeEpoch,...r.resources.resolveMcpCredential?{credential:await r.resources.resolveMcpCredential(t)}:{}}}return n?await this.desiredState.project(i,r?.abortSignal,s,n):await this.desiredState.project(i,r?.abortSignal,s)}async removeCredentialIfUnreferenced(e){return!!this.desiredState&&(await this.desiredState.removeLocalCredentialIfUnreferenced(e),!0)}async handleList(e){try{if(this.desiredState){await this.ensureDesiredState();const t=await this.desiredState.list();return void this.transport.sendResult(e.id,{revision:t.revision,servers:t.servers})}const t=await this.list();this.transport.sendResult(e.id,{servers:t})}catch(t){this.logger.warn?.(`[mcp-service] list failed: ${t instanceof Error?t.message:t}`),this.sendMappedError(e,t,!0)}}async handleSet(e){const t=e.params,r=t?.name,i=t?.server;if(r&&i&&"object"==typeof i){if(!this.rejectIfInFlight(e))try{if(requireSecretFreeMcpServerName(r),this.desiredState){const t=asDesiredServer(r,i);return await this.ensureDesiredState(),await this.desiredState.set(t),await this.desiredState.project(r),this.logger.info?.(`[mcp-service] desired state applied name=${r}`),void this.transport.sendResult(e.id,{ok:!0,restarting:!1})}await this.set(r,i),this.logger.info?.(`[mcp-service] set applied name=${r}`),this.transport.sendResult(e.id,{ok:!0,restarting:!0}),this.scheduleRestart()}catch(t){this.logger.error?.(`[mcp-service] set failed name=${r}: ${t instanceof Error?t.message:t}`),this.sendMappedError(e,t,!1)}}else this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Missing 'name' or 'server' config"})}async handleUnset(e){const t=e.params,r=t?.name;if(r){if(!this.rejectIfInFlight(e))try{if(requireSecretFreeMcpServerName(r),this.desiredState)return await this.ensureDesiredState(),await this.desiredState.unset(r),await this.desiredState.project(r),void this.transport.sendResult(e.id,{ok:!0,restarting:!1});await this.unset(r),this.logger.info?.(`[mcp-service] unset applied name=${r}`),this.transport.sendResult(e.id,{ok:!0,restarting:!0}),this.scheduleRestart()}catch(t){this.logger.error?.(`[mcp-service] unset failed name=${r}: ${t instanceof Error?t.message:t}`),this.sendMappedError(e,t,!1)}}else this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Missing 'name'"})}hasInFlightPrompts(){for(const e of this.state.sessions.values())if(void 0!==e.pendingPromptId||void 0!==e.currentRunId)return!0;return!1}rejectIfInFlight(e){return!!this.hasInFlightPrompts()&&(this.transport.sendError(e.id,Errors.InvalidParams.rpcCode,"Agent is busy",{code:Errors.InvalidParams.code,reason:"PROMPT_IN_FLIGHT",message:"Agent is processing a message; please retry after it completes."}),!0)}scheduleRestart(){this.restartTimer&&clearTimeout(this.restartTimer),this.restartTimer=setTimeout(()=>{this.logger.info?.("[mcp-service] mcp change applied — exiting for container restart"),this.exit(0)},750)}async ensureDesiredState(){if(!this.desiredStateStarted){if(!this.desiredState)throw new Error("MCP desired-state controller is unavailable");await this.desiredState.start(),this.desiredStateStarted=!0}}async stop(){this.desiredState&&this.desiredStateStarted&&(this.desiredStateStarted=!1,await this.desiredState.stop())}sendMappedError(e,t,r){const i=cliErrToAcpError(t,r);this.transport.sendError(e.id,i.code,i.message,i.data)}}function desiredServer(e,t,r){return{name:e,definitionRef:t.definitionRef,version:t.version,sha256:t.sha256,...t.credentialRef?{credentialRef:t.credentialRef}:{},config:r}}function commitBinding(e,t){return{source:"service"===t.origin?"service":"acp_local",operationId:e.context.operationId,method:e.name,paramsHash:e.context.paramsHash,runtimeEpoch:e.context.dispatchEpoch}}function publicConfig(e){if(void 0!==e.headers||void 0!==e.env)throw new Error("resolved MCP secrets must not enter desired state");return{transport:e.transport??(e.command?"stdio":"streamable-http"),..."string"==typeof e.url?{url:e.url}:{},..."string"==typeof e.command?{command:e.command}:{},...Array.isArray(e.args)?{args:e.args}:{},..."string"==typeof e.cwd?{cwd:e.cwd}:{},..."number"==typeof e.connectionTimeoutMs?{connectionTimeoutMs:e.connectionTimeoutMs}:{}}}function asDesiredServer(e,t){const r=t;if("string"!=typeof r.definitionRef||"string"!=typeof r.version||"string"!=typeof r.sha256)throw new Error("ACP mcp/set requires a verified definitionRef, version and sha256");if(void 0!==r.headers||void 0!==r.env)throw new Error("ACP mcp/set accepts credentialRef, not resolved headers or env");return desiredServer(e,{definitionRef:r.definitionRef,version:r.version,sha256:r.sha256,..."string"==typeof r.credentialRef?{credentialRef:r.credentialRef}:{},..."number"==typeof r.connectionTimeoutMs?{connectionTimeoutMs:r.connectionTimeoutMs}:{}},publicConfig(t))}function sanitizeMcpConfig(e,t){const r=t.transport??(t.command?"stdio":"streamable-http");return{name:e,definitionRef:`runtime-mcp:${encodeURIComponent(e)}`,transport:r,..."number"==typeof t.connectionTimeoutMs?{connectionTimeoutMs:t.connectionTimeoutMs}:{},..."string"==typeof t.url?{url:t.url}:{},..."string"==typeof t.command?{command:t.command}:{},...Array.isArray(t.args)?{args:t.args}:{},..."string"==typeof t.cwd?{cwd:t.cwd}:{}}}export function cliErrToAcpError(e,t){if(e instanceof OpenClawCliError){const r=e.stderr??"";return null===e.exitCode||t?{code:Errors.InternalError.rpcCode,message:e.message,data:{code:Errors.InternalError.code}}:/No MCP server named/i.test(r)?{code:Errors.InvalidParams.rpcCode,message:e.message,data:{code:Errors.InvalidParams.code,reason:"NOT_FOUND"}}:{code:Errors.InvalidParams.rpcCode,message:e.message,data:{code:Errors.InvalidParams.code}}}return{code:Errors.InternalError.rpcCode,message:e instanceof Error?e.message:String(e),data:{code:Errors.InternalError.code}}}
@@ -1 +1 @@
1
- const 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.\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"}',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"}],PLACEHOLDER_TITLES=new Set(["new chat","new conversation","新会话","新對話","新しいチャット","새 채팅","แชตใหม่"]);export function isPlaceholderTitle(e){if(!e)return!0;const t=e.trim();return!t||(!!PLACEHOLDER_TITLES.has(t.toLowerCase())||(!!/^[0-9a-f]{6,12}\s*\(20\d{2}/i.test(t)||(!!/^Sender\s*\(untrusted/i.test(t)||!!/^Conversation\s+info\s*\(untrusted/i.test(t))))}export function isGuardMessage(e){const t=e.trim();return[...t].length<3||[...t].every(e=>/[\p{P}\p{S}\s]/u.test(e))}export function matchTitleTemplate(e){const t=e.trim().toLowerCase();for(const n of TITLE_TEMPLATES)if(n.match.some(e=>e.toLowerCase()===t))return/[\u4e00-\u9fff]/.test(e)?n.zh:n.en}function truncateQuestionForTitle(e){return e.length>2e3?e.slice(0,1500):e}function truncateAnswerForTitle(e){return e.length<=1e3?e:`${e.slice(0,500)}\n...\n${e.slice(-500)}`}export function fallbackTitleFromQuestion(e){const t=e.replace(/[\r\n\t]+/g," ").replace(/[。!?.!?…]+$/u,"").trim();if(!t||isGuardMessage(t)||isPlaceholderTitle(t))return;const n=[...t];return n.length<=20?t:n.slice(0,18).join("")}export async function generateTitleFromQA(e,t,n,o="title-gen"){if(isGuardMessage(e))return void n?.info?.(`[${o}] SKIP guard message`);const i=matchTitleTemplate(e);if(i)return n?.info?.(`[${o}] template title="${i}"`),i;const r=(process.env.AROUTER_BASE_URL||"").replace(/\/$/,""),s=process.env.AROUTER_API_KEY||"";if(!r||!s)return void n?.info?.(`[${o}] SKIP: no AROUTER env vars`);const a=`[User Question]\n${truncateQuestionForTitle(e)}\n\n[Assistant Answer]\n${truncateAnswerForTitle(t)}`;n?.info?.(`[${o}] CALLING LLM q="${e.slice(0,60)}" aLen=${t.length}`);try{const t=await fetch(`${r}/v1/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:"openai/gpt-4o-mini",max_tokens:32,temperature:.3,messages:[{role:"system",content:TITLE_SYSTEM_PROMPT},{role:"user",content:a}]})});if(!t.ok){const e=await t.text().catch(()=>"");return void n?.info?.(`[${o}] FAILED status=${t.status} body=${e.slice(0,300)}`)}const i=await t.json(),c=i.choices?.[0]?.message?.content?.trim();if(!c)return;const u=c.replace(/^```json\s*/,"").replace(/```$/,"").trim();let l;try{l=JSON.parse(u).title?.trim()??""}catch{return void n?.debug?.(`[${o}] JSON parse failed: ${u}`)}if(!l||isPlaceholderTitle(l)){const t=fallbackTitleFromQuestion(e);return t?(n?.info?.(`[${o}] discarded placeholder/empty title="${l}"; fallback="${t}"`),t):void n?.info?.(`[${o}] discarded placeholder/empty title="${l}"`)}return n?.info?.(`[${o}] OK title="${l}"`),l}catch(e){return void n?.info?.(`[${o}] ERROR: ${e instanceof Error?e.message:e}`)}}function unwrapConversation(e){const t=e.data&&"object"==typeof e.data?e.data:e,n="string"==typeof t.owner_identity_id&&t.owner_identity_id||"string"==typeof t.ownerIdentityId&&t.ownerIdentityId||void 0;return{title:"string"==typeof t.title?t.title:void 0,ownerIdentityId:n}}export async function patchMsConversationTitle(e,t,n,o){await e.request("PATCH",`/api/v1/control/conversations/${encodeURIComponent(t)}`,{ownerIdentityId:n,title:o})}export async function maybeRenameImConversationTitle(e){const{client:t,conversationId:n,question:o,answer:i,logger:r}=e,s=`im-title-gen conv=${n}`;if(!n||!o.trim()||!i.trim())return void r?.debug?.(`[${s}] SKIP missing conversation/q/a`);let a,c;try{const e=unwrapConversation(await t.request("GET",`/api/v2/conversations/${encodeURIComponent(n)}`)??{});a=e.title,c=e.ownerIdentityId}catch(e){return void r?.info?.(`[${s}] GET conversation failed: ${e instanceof Error?e.message:e}`)}if(!isPlaceholderTitle(a))return void r?.debug?.(`[${s}] SKIP non-placeholder title="${a}"`);if(!c)return void r?.info?.(`[${s}] SKIP: no owner_identity_id on conversation`);const u=await generateTitleFromQA(o,i,r,s);if(u)try{return await patchMsConversationTitle(t,n,c,u),r?.info?.(`[${s}] PATCH MS title OK title="${u}"`),u}catch(e){return void r?.info?.(`[${s}] PATCH MS title FAILED: ${e instanceof Error?e.message:e}`)}}
1
+ const TITLE_SYSTEM_PROMPT_BASE='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/Thai (up to 24 if needed to keep all key domain terms intact).\n- Language: When a Client UI locale is provided below, write the title in THAT language even if the user wrote in a different language (translate the topic). Otherwise match the user\'s input language exactly. Mixed zh/en input → use the dominant language. Do NOT switch languages away from the required locale.\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 — never treat them as vague. Prefer the locale-native self-intro title from the Client UI locale section when present.\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"}',SELF_INTRO_BY_LOCALE={zh:"自我介绍","zh-TW":"自我介紹",ja:"自己紹介",ko:"자기소개",th:"แนะนำตัว",en:"Self Introduction"},SELF_INTRO_ALIASES=new Set(Object.values(SELF_INTRO_BY_LOCALE).map(e=>e.toLowerCase())),LOCALE_PROMPT_HINT={zh:'zh (简体中文) — write the title in Simplified Chinese. Self-intro → "自我介绍".',"zh-TW":'zh-TW (繁體中文) — write the title in Traditional Chinese. Self-intro → "自我介紹".',ja:'ja (日本語) — write the title in Japanese. Self-intro → "自己紹介". Never use Chinese "自我介绍".',ko:'ko (한국어) — write the title in Korean. Self-intro → "자기소개".',th:'th (ไทย) — write the title in Thai. Self-intro → "แนะนำตัว".',en:'en (English) — write the title in English. Self-intro → "Self Introduction".'},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"}],PLACEHOLDER_TITLES=new Set(["new chat","new conversation","新会话","新對話","新しいチャット","새 채팅","แชตใหม่"]),PLACEHOLDER_TO_LOCALE={"new chat":"en","new conversation":"en","新会话":"zh","新對話":"zh-TW","新しいチャット":"ja","새 채팅":"ko","แชตใหม่":"th"};export function inferTitleLocaleFromPlaceholder(e){if(!e)return;const t=e.trim().toLowerCase();return PLACEHOLDER_TO_LOCALE[t]??PLACEHOLDER_TO_LOCALE[e.trim()]}export function buildTitleSystemPrompt(e){return e?`${TITLE_SYSTEM_PROMPT_BASE}\n\n### Client UI locale\n${LOCALE_PROMPT_HINT[e]}\nCRITICAL: The title language MUST match this locale, even when [User Question] is in another language.`:TITLE_SYSTEM_PROMPT_BASE}export function alignTitleWithLocale(e,t){return t&&SELF_INTRO_ALIASES.has(e.trim().toLowerCase())?SELF_INTRO_BY_LOCALE[t]:e}export function isPlaceholderTitle(e){if(!e)return!0;const t=e.trim();return!t||(!!PLACEHOLDER_TITLES.has(t.toLowerCase())||(!!/^[0-9a-f]{6,12}\s*\(20\d{2}/i.test(t)||(!!/^Sender\s*\(untrusted/i.test(t)||!!/^Conversation\s+info\s*\(untrusted/i.test(t))))}export function isGuardMessage(e){const t=e.trim();return[...t].length<3||[...t].every(e=>/[\p{P}\p{S}\s]/u.test(e))}export function matchTitleTemplate(e){const t=e.trim().toLowerCase();for(const n of TITLE_TEMPLATES)if(n.match.some(e=>e.toLowerCase()===t))return/[\u4e00-\u9fff]/.test(e)?n.zh:n.en}function truncateQuestionForTitle(e){return e.length>2e3?e.slice(0,1500):e}function truncateAnswerForTitle(e){return e.length<=1e3?e:`${e.slice(0,500)}\n...\n${e.slice(-500)}`}export function fallbackTitleFromQuestion(e){const t=e.replace(/[\r\n\t]+/g," ").replace(/[。!?.!?…]+$/u,"").trim();if(!t||isGuardMessage(t)||isPlaceholderTitle(t))return;const n=[...t];return n.length<=20?t:n.slice(0,18).join("")}export async function generateTitleFromQA(e,t,n,i="title-gen"){let o,r,a=i;if(n&&("locale"in n||"logPrefix"in n||"logger"in n)){const e=n;o=e.logger,a=e.logPrefix??"title-gen",r=e.locale}else o=n;if(isGuardMessage(e))return void o?.info?.(`[${a}] SKIP guard message`);const s=matchTitleTemplate(e);if(s){const e=alignTitleWithLocale(s,r);return o?.info?.(`[${a}] template title="${e}"`),e}const l=(process.env.AROUTER_BASE_URL||"").replace(/\/$/,""),c=process.env.AROUTER_API_KEY||"";if(!l||!c)return void o?.info?.(`[${a}] SKIP: no AROUTER env vars`);const u=`[User Question]\n${truncateQuestionForTitle(e)}\n\n[Assistant Answer]\n${truncateAnswerForTitle(t)}`;o?.info?.(`[${a}] CALLING LLM q="${e.slice(0,60)}" aLen=${t.length}${r?` locale=${r}`:""}`);try{const t=await fetch(`${l}/v1/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`},body:JSON.stringify({model:"openai/gpt-4o-mini",max_tokens:32,temperature:.3,messages:[{role:"system",content:buildTitleSystemPrompt(r)},{role:"user",content:u}]})});if(!t.ok){const e=await t.text().catch(()=>"");return void o?.info?.(`[${a}] FAILED status=${t.status} body=${e.slice(0,300)}`)}const n=await t.json(),i=n.choices?.[0]?.message?.content?.trim();if(!i)return;const s=i.replace(/^```json\s*/,"").replace(/```$/,"").trim();let h;try{h=JSON.parse(s).title?.trim()??""}catch{return void o?.debug?.(`[${a}] JSON parse failed: ${s}`)}if(!h||isPlaceholderTitle(h)){const t=fallbackTitleFromQuestion(e);if(t){const n=alignTitleWithLocale(t,r),i=r&&n===t&&/介绍一下你自己|介紹一下你自己|introduce yourself|自己紹介|자기소개/i.test(e)?SELF_INTRO_BY_LOCALE[r]:n;return o?.info?.(`[${a}] discarded placeholder/empty title="${h}"; fallback="${i}"`),i}return void o?.info?.(`[${a}] discarded placeholder/empty title="${h}"`)}const d=alignTitleWithLocale(h,r);return o?.info?.(d!==h?`[${a}] OK title="${h}" → locale-aligned="${d}"`:`[${a}] OK title="${h}"`),d}catch(e){return void o?.info?.(`[${a}] ERROR: ${e instanceof Error?e.message:e}`)}}function unwrapConversation(e){const t=e.data&&"object"==typeof e.data?e.data:e,n="string"==typeof t.owner_identity_id&&t.owner_identity_id||"string"==typeof t.ownerIdentityId&&t.ownerIdentityId||void 0;return{title:"string"==typeof t.title?t.title:void 0,ownerIdentityId:n}}export async function patchMsConversationTitle(e,t,n,i){await e.request("PATCH",`/api/v1/control/conversations/${encodeURIComponent(t)}`,{ownerIdentityId:n,title:i})}export async function maybeRenameImConversationTitle(e){const{client:t,conversationId:n,question:i,answer:o,logger:r}=e,a=`im-title-gen conv=${n}`;if(!n||!i.trim()||!o.trim())return void r?.debug?.(`[${a}] SKIP missing conversation/q/a`);let s,l;try{const e=unwrapConversation(await t.request("GET",`/api/v2/conversations/${encodeURIComponent(n)}`)??{});s=e.title,l=e.ownerIdentityId}catch(e){return void r?.info?.(`[${a}] GET conversation failed: ${e instanceof Error?e.message:e}`)}if(!isPlaceholderTitle(s))return void r?.debug?.(`[${a}] SKIP non-placeholder title="${s}"`);if(!l)return void r?.info?.(`[${a}] SKIP: no owner_identity_id on conversation`);const c=inferTitleLocaleFromPlaceholder(s),u=await generateTitleFromQA(i,o,{logger:r,logPrefix:a,locale:c});if(u)try{return await patchMsConversationTitle(t,n,l,u),r?.info?.(`[${a}] PATCH MS title OK title="${u}"`),u}catch(e){return void r?.info?.(`[${a}] PATCH MS title FAILED: ${e instanceof Error?e.message:e}`)}}
@@ -1 +1 @@
1
- export class MessageServiceSessionModelHttpAuthority{options;constructor(e){this.options=e}async project(e){const o=new URL(`/api/v1/runtime/conversations/${encodeURIComponent(e.conversationId)}/metadata/model`,this.options.messageServiceUrl),r=await this.options.fetchAuthorized(o,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,requestHash:e.requestHash,modelOverrideId:e.modelOverrideId,runtimeLeaseCredential:e.runtimeLeaseCredential})}),t=await decodeRaw(r);if(!r.ok)throw new Error(`Message Service session model projection failed (${r.status})`);const s=record(t)&&record(t.data)?t.data:t;if(!record(s)||"projected"!==s.status||"created"!==s.disposition&&"reused"!==s.disposition||s.conversationId!==e.conversationId)throw new Error("Message Service session model projection receipt mismatch");const i=void 0===s.modelOverrideId||null===s.modelOverrideId?null:"string"==typeof s.modelOverrideId?s.modelOverrideId:void 0;if(void 0===i||i!==e.modelOverrideId)throw new Error("Message Service session model projection modelOverrideId mismatch");return{status:"projected",disposition:s.disposition,conversationId:e.conversationId,modelOverrideId:i}}}async function decodeRaw(e){try{return await e.json()}catch{return}}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}
1
+ export class MessageServiceSessionModelHttpAuthority{options;constructor(e){this.options=e}async project(e){const o=new URL(`/api/v1/runtime/conversations/${encodeURIComponent(e.conversationId)}/metadata/model`,this.options.messageServiceUrl),r=await this.options.fetchAuthorized(o,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({schemaVersion:1,operationId:e.operationId,requestMessageId:e.requestMessageId,requestHash:e.requestHash,modelOverrideId:e.modelOverrideId,runtimeLeaseCredential:e.runtimeLeaseCredential})}),s=await decodeRaw(r);if(!r.ok){const e=record(s)&&"string"==typeof s.message&&s.message?`: ${s.code??"error"}: ${s.message}`:"";throw new Error(`Message Service session model projection failed (${r.status})${e}`)}const t=record(s)&&record(s.data)?s.data:s;if(!record(t)||"projected"!==t.status||"created"!==t.disposition&&"reused"!==t.disposition||t.conversationId!==e.conversationId)throw new Error("Message Service session model projection receipt mismatch");const i=void 0===t.modelOverrideId||null===t.modelOverrideId?null:"string"==typeof t.modelOverrideId?t.modelOverrideId:void 0;if(void 0===i||i!==e.modelOverrideId)throw new Error("Message Service session model projection modelOverrideId mismatch");return{status:"projected",disposition:t.disposition,conversationId:e.conversationId,modelOverrideId:i}}}async function decodeRaw(e){try{return await e.json()}catch{return}}function record(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}
@@ -1 +1 @@
1
- import{RUNTIME_RESOURCE_BINDING_CONTRACT_REVISION}from"@beeos-ai/beeos-types/runtime";import{parseAndValidateTemplatePackage}from"../acp-gateway/agent-template-package.js";import{HttpRuntimeOperationResourceResolver,RuntimeResourceResolutionError}from"./runtime-operation-resource-resolver.js";import{MessageServiceRuntimeMessageChannel}from"./message-service-runtime-message-channel.js";import{MessageServiceConversationClearHttpAuthority}from"./message-service-conversation-clear-http-authority.js";import{MessageServiceConversationHistoryBoundary}from"./message-service-conversation-history-boundary.js";import{MessageServiceSessionModelHttpAuthority}from"./message-service-session-model-http-authority.js";import{MsRuntimeMessageChannelConsumerFactory}from"./ms-runtime-message-channel-consumer-factory.js";import{RuntimeJwksVerifier}from"./runtime-jwks-verifier.js";import{GatewayGrantJwksVerifier}from"./split-runtime-authorization-verifier.js";import{RUNTIME_MESSAGE_CHANNEL_REVISION,RUNTIME_PARITY_MANIFEST}from"./runtime-parity-manifest.js";import{intersectRuntimeServiceMethodsWithBackendCapabilities,loadRuntimeServiceContractIdentity,runtimeServiceContractRequirement}from"./runtime-service-contract-compatibility.js";const CONTRACT_ARTIFACT_BLOCKER=Object.freeze({id:"contract_artifact_mismatch",owner:"backend",requiredContract:"frozen Types manifest and Service wire artifacts"}),TRANSPORT_BLOCKER=Object.freeze({id:"message_channel_transport",owner:"backend",requiredContract:`${RUNTIME_MESSAGE_CHANNEL_REVISION} HTTP delivery/history/append authority`}),JWKS_BLOCKER=Object.freeze({id:"gateway_grant_jwks",owner:"backend",requiredContract:"Purpose-bound Gateway runtime execution-grant JWKS proxy"}),POISON_JOURNAL_BLOCKER=Object.freeze({id:"poison_journal",owner:"openclaw_runtime_client",requiredContract:"Durable bounded runtime poison-delivery journal"}),grantAdapterOptions=new WeakMap;export class AgentGatewayGrantJwksReadinessAdapter{constructor(e){grantAdapterOptions.set(this,{agentGatewayUrl:new URL(e.agentGatewayUrl).toString()})}}export class AgentGatewaySplitJwksReadinessAdapter extends AgentGatewayGrantJwksReadinessAdapter{}const transportOptions=new WeakMap;export class RuntimeServiceTransportReadinessAdapter{constructor(e){transportOptions.set(this,{messageService:e.messageService,scopedDeliveryKey:e.scopedDeliveryKey,agentGatewayUrl:new URL(e.agentGatewayUrl).toString(),boundAgentFetch:e.boundAgentFetch})}}const CAPABILITY_BLOCKERS=Object.freeze(RUNTIME_PARITY_MANIFEST.filter(e=>"blocked"===e.status).map(e=>Object.freeze({method:e.method,owner:e.blockerOwner,requiredContract:e.contractRevision})));export async function createRuntimeServiceProductionCandidate(e){try{loadRuntimeServiceContractIdentity()}catch{return{status:"unavailable",blockers:Object.freeze([{...CONTRACT_ARTIFACT_BLOCKER,requiredContract:contractArtifactRequirement()}])}}if(!e.poisonJournal)return{status:"unavailable",blockers:Object.freeze([POISON_JOURNAL_BLOCKER])};let t;if(e.authorizationAdapter)try{t=await probeGatewayGrantJwks(e.authorizationAdapter)}catch{}const r=e.transportAdapter?transportOptions.get(e.transportAdapter):void 0;if(!r)return{status:"unavailable",blockers:Object.freeze([TRANSPORT_BLOCKER,...t?[]:[JWKS_BLOCKER]])};if(!t)return{status:"unavailable",blockers:Object.freeze([JWKS_BLOCKER])};try{const n=await r.messageService.ready(),a=new MessageServiceRuntimeMessageChannel({serviceUrl:n.serviceUrl,transport:r.messageService,scopedDeliveryKey:r.scopedDeliveryKey}),i=runtimeMethods(),s=e.attemptPorts??runtimeMessageAttemptPorts(r,n.serviceUrl);return{status:"ready",blockers:[],capabilityBlockers:CAPABILITY_BLOCKERS,serviceMethods:i,factory:new MsRuntimeMessageChannelConsumerFactory({channel:a,verifier:t,ports:s,journal:e.commandJournal,allowedMethods:new Set(i),options:{poisonJournal:e.poisonJournal,...e.onConsumerDeliveryError?{onDeliveryError:e.onConsumerDeliveryError}:{},...e.onConsumerRequestTerminalAccepted?{onRequestTerminalAccepted:e.onConsumerRequestTerminalAccepted}:{},...e.onConsumerRequestAcknowledged?{onRequestAcknowledged:e.onConsumerRequestAcknowledged}:{}}}),...void 0===e.attemptPorts?{resourceBindingContractRevision:RUNTIME_RESOURCE_BINDING_CONTRACT_REVISION}:{}}}catch{return{status:"unavailable",blockers:Object.freeze([TRANSPORT_BLOCKER])}}}async function probeGatewayGrantJwks(e){const t=grantAdapterOptions.get(e);if(!t)throw new Error("untrusted Gateway grant readiness adapter");const r=t.agentGatewayUrl.replace(/\/+$/,""),n=new GatewayGrantJwksVerifier(new RuntimeJwksVerifier(`${r}/.well-known/runtime-execution-grant-jwks.json`));return await n.refresh(!0),n}export function runtimeMessageAttemptPorts(e,t){const r=new MessageServiceConversationClearHttpAuthority({messageServiceUrl:t,fetchAuthorized:async(t,r)=>await e.messageService.fetch(t,r)}),n=new MessageServiceSessionModelHttpAuthority({messageServiceUrl:t,fetchAuthorized:async(t,r)=>await e.messageService.fetch(t,r)});return{async resolve({request:t,command:a,executionGrant:i,getLease:s,journalRecord:o,abortSignal:c}){const u="skills.install"===a.name||"agent.applyTemplate"===a.name?a.params.artifact:void 0,d="mcp.set"===a.name?a.params.definition:void 0;if((u||d)&&(t.resourceBindingContractRevision!==RUNTIME_RESOURCE_BINDING_CONTRACT_REVISION||!t.resourceBindings))throw new RuntimeResourceResolutionError("resolution_rejected","resource-bound Service delivery requires the Types 4.1 binding carrier");const m=new HttpRuntimeOperationResourceResolver({gatewayUrl:e.agentGatewayUrl,operationId:t.operationId,requestMessageId:t.requestMessageId,instanceId:t.instanceId,paramsHash:t.paramsHash,bindings:t.resourceBindings??[],getAuthorization:()=>{const e=s();return{executionGrant:i,runtimeLeaseCredential:e.runtimeLeaseCredential,fence:deliveryFence(t,e)}},fetchAuthorized:async(t,r)=>await e.boundAgentFetch(t,r??{}),parseSkillArtifact:e=>parseAndValidateTemplatePackage(Buffer.from(e)),signal:c});if("prepared"!==o.phase&&"started"!==o.phase||(u&&await m.readVerifiedArtifact(u),d&&await m.resolveMcpDefinition(d)),"session.setModel"===a.name)return{resources:m,sessionModelProjection:{project:async({conversationId:e,modelOverrideId:r})=>{const a=s();return await n.project({conversationId:e,operationId:t.operationId,requestMessageId:t.requestMessageId,requestHash:t.requestHash,modelOverrideId:r,runtimeLeaseCredential:a.runtimeLeaseCredential})}}};if("session.clear"!==a.name)return{resources:m};const l=a.context.conversation,p=s();return{resources:m,historyBoundary:new MessageServiceConversationHistoryBoundary({operationId:t.operationId,requestMessageId:t.requestMessageId,expectedGeneration:await r.currentGeneration(l.runtimeConversationUid),fence:deliveryFence(t,p),authority:r})}}}}function runtimeMethods(){return[...intersectRuntimeServiceMethodsWithBackendCapabilities(RUNTIME_PARITY_MANIFEST.filter(e=>"ready"===e.status).map(e=>e.method))]}function contractArtifactRequirement(){try{return runtimeServiceContractRequirement()}catch{return CONTRACT_ARTIFACT_BLOCKER.requiredContract}}function deliveryFence(e,t){if(t.handlerIdentity!==e.runtimeHandlerIdentity||t.runtimeEpoch!==e.dispatchEpoch)throw new Error("runtime delivery fence does not match the retained request");return{claimId:e.requestMessageId,handlerIdentity:t.handlerIdentity,runtimeEpoch:t.runtimeEpoch,fencingToken:t.runtimeEpoch,journalStoreId:t.handlerIdentity,journalGeneration:t.runtimeEpoch}}
1
+ import{RUNTIME_RESOURCE_BINDING_CONTRACT_REVISION}from"@beeos-ai/beeos-types/runtime";import{parseAndValidateTemplatePackage}from"../acp-gateway/agent-template-package.js";import{HttpRuntimeOperationResourceResolver,RuntimeResourceResolutionError}from"./runtime-operation-resource-resolver.js";import{MessageServiceRuntimeMessageChannel}from"./message-service-runtime-message-channel.js";import{MessageServiceConversationClearHttpAuthority}from"./message-service-conversation-clear-http-authority.js";import{MessageServiceConversationHistoryBoundary}from"./message-service-conversation-history-boundary.js";import{MessageServiceSessionModelHttpAuthority}from"./message-service-session-model-http-authority.js";import{MsRuntimeMessageChannelConsumerFactory}from"./ms-runtime-message-channel-consumer-factory.js";import{RuntimeJwksVerifier}from"./runtime-jwks-verifier.js";import{GatewayGrantJwksVerifier}from"./split-runtime-authorization-verifier.js";import{RUNTIME_MESSAGE_CHANNEL_REVISION,RUNTIME_PARITY_MANIFEST}from"./runtime-parity-manifest.js";import{intersectRuntimeServiceMethodsWithBackendCapabilities,loadRuntimeServiceContractIdentity,runtimeServiceContractRequirement}from"./runtime-service-contract-compatibility.js";const CONTRACT_ARTIFACT_BLOCKER=Object.freeze({id:"contract_artifact_mismatch",owner:"backend",requiredContract:"frozen Types manifest and Service wire artifacts"}),TRANSPORT_BLOCKER=Object.freeze({id:"message_channel_transport",owner:"backend",requiredContract:`${RUNTIME_MESSAGE_CHANNEL_REVISION} HTTP delivery/history/append authority`}),JWKS_BLOCKER=Object.freeze({id:"gateway_grant_jwks",owner:"backend",requiredContract:"Purpose-bound Gateway runtime execution-grant JWKS proxy"}),POISON_JOURNAL_BLOCKER=Object.freeze({id:"poison_journal",owner:"openclaw_runtime_client",requiredContract:"Durable bounded runtime poison-delivery journal"}),grantAdapterOptions=new WeakMap;export class AgentGatewayGrantJwksReadinessAdapter{constructor(e){grantAdapterOptions.set(this,{agentGatewayUrl:new URL(e.agentGatewayUrl).toString()})}}export class AgentGatewaySplitJwksReadinessAdapter extends AgentGatewayGrantJwksReadinessAdapter{}const transportOptions=new WeakMap;export class RuntimeServiceTransportReadinessAdapter{constructor(e){transportOptions.set(this,{messageService:e.messageService,scopedDeliveryKey:e.scopedDeliveryKey,agentGatewayUrl:new URL(e.agentGatewayUrl).toString(),boundAgentFetch:e.boundAgentFetch})}}const CAPABILITY_BLOCKERS=Object.freeze(RUNTIME_PARITY_MANIFEST.filter(e=>"blocked"===e.status).map(e=>Object.freeze({method:e.method,owner:e.blockerOwner,requiredContract:e.contractRevision})));export async function createRuntimeServiceProductionCandidate(e){try{loadRuntimeServiceContractIdentity()}catch{return{status:"unavailable",blockers:Object.freeze([{...CONTRACT_ARTIFACT_BLOCKER,requiredContract:contractArtifactRequirement()}])}}if(!e.poisonJournal)return{status:"unavailable",blockers:Object.freeze([POISON_JOURNAL_BLOCKER])};let t;if(e.authorizationAdapter)try{t=await probeGatewayGrantJwks(e.authorizationAdapter)}catch{}const r=e.transportAdapter?transportOptions.get(e.transportAdapter):void 0;if(!r)return{status:"unavailable",blockers:Object.freeze([TRANSPORT_BLOCKER,...t?[]:[JWKS_BLOCKER]])};if(!t)return{status:"unavailable",blockers:Object.freeze([JWKS_BLOCKER])};try{const n=await r.messageService.ready(),a=new MessageServiceRuntimeMessageChannel({serviceUrl:n.serviceUrl,transport:r.messageService,scopedDeliveryKey:r.scopedDeliveryKey}),i=runtimeMethods(),s=e.attemptPorts??runtimeMessageAttemptPorts(r,n.serviceUrl);return{status:"ready",blockers:[],capabilityBlockers:CAPABILITY_BLOCKERS,serviceMethods:i,factory:new MsRuntimeMessageChannelConsumerFactory({channel:a,verifier:t,ports:s,journal:e.commandJournal,allowedMethods:new Set(i),options:{poisonJournal:e.poisonJournal,...e.onConsumerDeliveryError?{onDeliveryError:e.onConsumerDeliveryError}:{},...e.onConsumerRequestTerminalAccepted?{onRequestTerminalAccepted:e.onConsumerRequestTerminalAccepted}:{},...e.onConsumerRequestAcknowledged?{onRequestAcknowledged:e.onConsumerRequestAcknowledged}:{}}}),...void 0===e.attemptPorts?{resourceBindingContractRevision:RUNTIME_RESOURCE_BINDING_CONTRACT_REVISION}:{}}}catch{return{status:"unavailable",blockers:Object.freeze([TRANSPORT_BLOCKER])}}}async function probeGatewayGrantJwks(e){const t=grantAdapterOptions.get(e);if(!t)throw new Error("untrusted Gateway grant readiness adapter");const r=t.agentGatewayUrl.replace(/\/+$/,""),n=new GatewayGrantJwksVerifier(new RuntimeJwksVerifier(`${r}/.well-known/runtime-execution-grant-jwks.json`));return await n.refresh(!0),n}export function runtimeMessageAttemptPorts(e,t){const r=new MessageServiceConversationClearHttpAuthority({messageServiceUrl:t,fetchAuthorized:async(t,r)=>await e.messageService.fetch(t,r)});return{async resolve({request:n,command:a,executionGrant:i,getLease:s,journalRecord:o,abortSignal:c}){const u="skills.install"===a.name||"agent.applyTemplate"===a.name?a.params.artifact:void 0,d="mcp.set"===a.name?a.params.definition:void 0;if((u||d)&&(n.resourceBindingContractRevision!==RUNTIME_RESOURCE_BINDING_CONTRACT_REVISION||!n.resourceBindings))throw new RuntimeResourceResolutionError("resolution_rejected","resource-bound Service delivery requires the Types 4.1 binding carrier");const m=new HttpRuntimeOperationResourceResolver({gatewayUrl:e.agentGatewayUrl,operationId:n.operationId,requestMessageId:n.requestMessageId,instanceId:n.instanceId,paramsHash:n.paramsHash,bindings:n.resourceBindings??[],getAuthorization:()=>{const e=s();return{executionGrant:i,runtimeLeaseCredential:e.runtimeLeaseCredential,fence:deliveryFence(n,e)}},fetchAuthorized:async(t,r)=>await e.boundAgentFetch(t,r??{}),parseSkillArtifact:e=>parseAndValidateTemplatePackage(Buffer.from(e)),signal:c});if("prepared"!==o.phase&&"started"!==o.phase||(u&&await m.readVerifiedArtifact(u),d&&await m.resolveMcpDefinition(d)),"session.setModel"===a.name)return{resources:m,sessionModelProjection:{project:async({conversationId:r,modelOverrideId:a})=>{const i=s(),o=new MessageServiceSessionModelHttpAuthority({messageServiceUrl:t,fetchAuthorized:async(t,r)=>await e.messageService.fetchRuntimeChannel(t,{runtimeLeaseCredential:i.runtimeLeaseCredential,scopedDeliveryKey:e.scopedDeliveryKey},r)});return await o.project({conversationId:r,operationId:n.operationId,requestMessageId:n.requestMessageId,requestHash:n.requestHash,modelOverrideId:a,runtimeLeaseCredential:i.runtimeLeaseCredential})}}};if("session.clear"!==a.name)return{resources:m};const l=a.context.conversation,p=s();return{resources:m,historyBoundary:new MessageServiceConversationHistoryBoundary({operationId:n.operationId,requestMessageId:n.requestMessageId,expectedGeneration:await r.currentGeneration(l.runtimeConversationUid),fence:deliveryFence(n,p),authority:r})}}}}function runtimeMethods(){return[...intersectRuntimeServiceMethodsWithBackendCapabilities(RUNTIME_PARITY_MANIFEST.filter(e=>"ready"===e.status).map(e=>e.method))]}function contractArtifactRequirement(){try{return runtimeServiceContractRequirement()}catch{return CONTRACT_ARTIFACT_BLOCKER.requiredContract}}function deliveryFence(e,t){if(t.handlerIdentity!==e.runtimeHandlerIdentity||t.runtimeEpoch!==e.dispatchEpoch)throw new Error("runtime delivery fence does not match the retained request");return{claimId:e.requestMessageId,handlerIdentity:t.handlerIdentity,runtimeEpoch:t.runtimeEpoch,fencingToken:t.runtimeEpoch,journalStoreId:t.handlerIdentity,journalGeneration:t.runtimeEpoch}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "beeos-claw",
3
- "version": "0.5.86",
3
+ "version": "0.5.88",
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>",
@@ -78,5 +78,8 @@
78
78
  "terser": "^5.39.0",
79
79
  "typescript": "^5.6.3",
80
80
  "vitest": "^4.1.0"
81
+ },
82
+ "overrides": {
83
+ "fast-uri": ">=3.1.4"
81
84
  }
82
85
  }