beeos-claw 0.4.4 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acp-gateway/assistant-mq-lifecycle.test.js +1 -1
- package/dist/acp-gateway/bridge-core-cron-internal-delivery.test.js +1 -0
- package/dist/acp-gateway/bridge-core.js +1 -1
- package/dist/acp-gateway/gateway-events-cron-backfill.test.js +1 -1
- package/dist/acp-gateway/gateway-events-cron-name.test.js +1 -1
- package/dist/acp-gateway/gateway-events-heartbeat.test.js +1 -1
- package/dist/acp-gateway/gateway-events.js +1 -1
- package/dist/acp-gateway/session-load-inflight-user.test.js +1 -1
- package/dist/acp-gateway/session-load.test.js +1 -1
- package/dist/acp-gateway/session-state.js +1 -1
- package/dist/acp-gateway/session-state.test.js +1 -1
- package/dist/acp-server-agent-sync.test.js +1 -1
- package/dist/acp-server-bridge-shim.test.js +1 -1
- package/dist/acp-server.js +1 -1
- package/dist/agent-sync.js +1 -1
- package/dist/config.js +1 -1
- package/dist/cron-overrides.js +1 -0
- package/dist/index.js +1 -1
- package/dist/message-filter.js +1 -1
- package/dist/surface/cron-schemas.js +1 -1
- package/package.json +2 -2
- package/dist/messaging/chat-envelope.js +0 -1
- package/dist/messaging/chat-envelope.test.js +0 -1
- package/dist/messaging/message-sdk.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describe,it,expect,vi}from"vitest";import{AcpGatewayBridgeCore}from"./bridge-core.js";import{AcpGatewaySessionState}from"./session-state.js";import{AcpTransport}from"./transport.js";import{MessageQueue}from"../utils/mq.js";function makeLogger(){return{info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()}}function makeConfig(){return{agentGatewayUrl:"http://localhost:0",keyFile:"/tmp/key",bridge:{url:"",service:"bridge",shell:{enabled:!1}},gateway:{url:"",token:"",protocol:1,clientId:"c",agentId:"a"},retry:{baseMs:100,maxMs:1e3,maxAttempts:0},log:{enabled:!1,verbose:!1,dir:"/tmp"},promptTimeoutMs:6e4,terminalWsPort:0,terminalWsAllowedOrigins:[],streamIdleTimeoutMs:6e4,streamStaleTimeoutMs:6e4,cronSignalWindowMs:5e3,canvasRelayUrl:"",canvasEnabled:!1,openclawCanvasCompat:!1,messageBus:{enabled:!1,serviceUrl:"",url:"",principalId:"",a2aEnabled:!1}}}function makeSession(e,s){return{sessionId:e,gatewaySessionKey:s,agentId:"main",createdAt:Date.now(),chatReplayDedupKeys:new Set}}function buildCore(){const e=makeLogger(),s=vi.fn(),t=new AcpGatewaySessionState(e),
|
|
1
|
+
import{describe,it,expect,vi}from"vitest";import{AcpGatewayBridgeCore}from"./bridge-core.js";import{AcpGatewaySessionState}from"./session-state.js";import{AcpTransport}from"./transport.js";import{MessageQueue}from"../utils/mq.js";function makeLogger(){return{info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()}}function makeConfig(){return{agentGatewayUrl:"http://localhost:0",keyFile:"/tmp/key",bridge:{url:"",service:"bridge",shell:{enabled:!1}},gateway:{url:"",token:"",protocol:1,clientId:"c",agentId:"a"},retry:{baseMs:100,maxMs:1e3,maxAttempts:0},log:{enabled:!1,verbose:!1,dir:"/tmp"},promptTimeoutMs:6e4,terminalWsPort:0,terminalWsAllowedOrigins:[],streamIdleTimeoutMs:6e4,streamStaleTimeoutMs:6e4,cronSignalWindowMs:5e3,cronMaxDurationDefaultMs:3e5,cronMaxDurationCapMs:18e5,canvasRelayUrl:"",canvasEnabled:!1,openclawCanvasCompat:!1,messageBus:{enabled:!1,serviceUrl:"",url:"",principalId:"",a2aEnabled:!1}}}function makeSession(e,s){return{sessionId:e,gatewaySessionKey:s,agentId:"main",createdAt:Date.now(),chatReplayDedupKeys:new Set}}function buildCore(){const e=makeLogger(),s=vi.fn(),t=new AcpGatewaySessionState(e),a=vi.fn(),n=new AcpTransport(a,s);return{core:new AcpGatewayBridgeCore({state:t,transport:n,config:makeConfig(),logger:e,writeObs:s,getGateway:()=>null,instanceId:"test-instance"}),state:t,transport:n,logger:e,writeObs:s,sendBridgeMessage:a}}describe("assistantMq lifecycle — endRun closes mq immediately",()=>{it("cleanupPrompt closes and clears assistantMq synchronously (no late-close timer)",()=>{const{core:e,state:s}=buildCore(),t=makeSession("s1","agent:main:s1");t.assistantMq=new MessageQueue,t.currentRunId="run-1",s.sessions.set(t.sessionId,t),s.sessionsByGatewayKey.set(t.gatewaySessionKey,t);const a=t.assistantMq;expect(a.closed).toBe(!1),e.cleanupPrompt(t),expect(a.closed).toBe(!0),expect(t.assistantMq).toBeUndefined(),expect(t.currentRunId).toBeUndefined(),expect(t.pendingPromptId).toBeUndefined()}),it("handleSessionMessage does NOT touch the mq (mq lifecycle is decoupled from persistence signal)",()=>{const{core:e,state:s}=buildCore(),t=makeSession("s1","agent:main:s1");t.assistantMq=new MessageQueue,t.lastTurnIdByRole={assistant:"turn-1"},s.sessions.set(t.sessionId,t),s.sessionsByGatewayKey.set(t.gatewaySessionKey,t);const a=t.assistantMq;e.handleSessionMessage({sessionKey:t.gatewaySessionKey,messageId:"msg-1",message:{role:"assistant",timestamp:Date.now()}}),expect(a.closed).toBe(!1),expect(t.assistantMq).toBe(a)})});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{describe,it,expect,beforeEach,vi}from"vitest";import{AcpGatewayBridgeCore}from"./bridge-core.js";import{AcpGatewaySessionState}from"./session-state.js";function makeBridge(){const e={info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()},n=new AcpGatewaySessionState(e),t={sendResult:vi.fn(),sendAcpError:vi.fn(),sendSessionUpdate:vi.fn(),sendNotification:vi.fn(),resetSessionUpdateCount:vi.fn(),setSessionUpdateObserver:vi.fn(),isReady:()=>!0,get forwardControl(){return{forwardThinking:!0,forwardToolCalls:!0}}},o={isConnected:!0,request:vi.fn().mockResolvedValue({id:"job_test_123"})};return{bridge:new AcpGatewayBridgeCore({state:n,transport:t,config:{gateway:{agentId:"main"},cronMaxDurationDefaultMs:3e5,cronMaxDurationCapMs:72e5},logger:e,writeObs:vi.fn(),getGateway:()=>o,instanceId:"test-instance",thirdPartyChannels:new Set}),state:n,transport:t,gateway:o,logger:e}}function cronAddRequest(e,n){return{jsonrpc:"2.0",id:e,method:"cron/add",params:n}}describe("handleCronRequest — _beeos_internal delivery contract (Bug-A)",()=>{let e;beforeEach(()=>{e=makeBridge()}),it("forces delivery={mode:'none'} when _beeos_internal=true (no delivery from client)",async()=>{await e.bridge.handleRequest(cronAddRequest(1,{name:"daily-summary",schedule:{kind:"cron",expression:"0 9 * * *"},sessionTarget:"isolated",payload:{kind:"agentTurn",message:"hi"},_beeos_internal:!0})),expect(e.transport.sendAcpError).not.toHaveBeenCalled();const n=e.gateway.request.mock.calls.find(e=>"cron.add"===e[0]);expect(n,"expected a cron.add forward").toBeDefined();const[t,o]=n;expect(t).toBe("cron.add"),expect(o).not.toHaveProperty("_beeos_internal"),expect(o.delivery).toEqual({mode:"none"})}),it("normalizes delivery to {mode:'none'} even when client sent a conflicting delivery",async()=>{await e.bridge.handleRequest(cronAddRequest(2,{name:"daily-summary",schedule:{kind:"cron",expression:"0 9 * * *"},sessionTarget:"isolated",payload:{kind:"agentTurn",message:"hi"},_beeos_internal:!0,delivery:{mode:"announce",channel:"lark:c_123"}}));const n=e.gateway.request.mock.calls.find(e=>"cron.add"===e[0]),[,t]=n;expect(t.delivery).toEqual({mode:"none"})}),it("leaves delivery untouched when _beeos_internal is not set",async()=>{await e.bridge.handleRequest(cronAddRequest(3,{name:"announce-job",schedule:{kind:"cron",expression:"0 9 * * *"},sessionTarget:"isolated",payload:{kind:"agentTurn",message:"hi"},delivery:{mode:"announce",channel:"lark:c_123"}}));const n=e.gateway.request.mock.calls.find(e=>"cron.add"===e[0]),[,t]=n;expect(t.delivery).toEqual({mode:"announce",channel:"lark:c_123"}),expect(t).not.toHaveProperty("_beeos_internal")}),it("also applies to cron.update (not just cron.add)",async()=>{await e.bridge.handleRequest({jsonrpc:"2.0",id:4,method:"cron/update",params:{id:"job_test_123",name:"renamed",_beeos_internal:!0}});const n=e.gateway.request.mock.calls.find(e=>"cron.update"===e[0]),[t,o]=n;expect(t).toBe("cron.update"),expect(o).not.toHaveProperty("_beeos_internal"),expect(o.delivery).toEqual({mode:"none"})}),it("strips _beeos_internal=false without synthesizing delivery",async()=>{await e.bridge.handleRequest(cronAddRequest(5,{name:"neutral-job",schedule:{kind:"cron",expression:"0 9 * * *"},sessionTarget:"isolated",payload:{kind:"agentTurn",message:"hi"},delivery:{mode:"webhook",to:"https://example.com/hook"},_beeos_internal:!1}));const n=e.gateway.request.mock.calls.find(e=>"cron.add"===e[0]),[,t]=n;expect(t).not.toHaveProperty("_beeos_internal"),expect(t.delivery).toEqual({mode:"webhook",to:"https://example.com/hook"})})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID,createHash}from"node:crypto";import{mkdir,writeFile,readFile,rm,lstat,readlink,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,stripTransportMetadata,isHeartbeatPromptText,isCronPromptText,classifyHeartbeatFilter,previewFilteredText}from"../message-filter.js";import{CANVAS_TERM_MAPPING,CANVAS_UPDATE_HINT,buildActiveSurfacesContext}from"../canvas/tools.js";import{parseMentionsParam,buildMentionInstruction}from"../a2a/mention-resolver.js";import{extractPromptBlocks,toGatewayPrompt,resolveSlashCommandName as resolveSlashCmd}from"./prompt-converter.js";import{loadHistory,groupIntoTurns,extractBeeosFileUrisFromOutput,splitUserReplayBlocks}from"./history-replay.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-payload-strategies.js";import{buildToolCallPayload,buildToolCallUpdatePayload}from"./tool-call-payload-builder.js";import{Errors}from"../errors/index.js";import{formatFriendlyError}from"../errors/classify.js";import{resolveChannelFromSessionKey}from"../channel-detection.js";import{resolveTurnId,recordTurnIdForRole}from"./gateway-events.js";import{McpService}from"./mcp-service.js";import{DEFAULT_PROMPT_TIMEOUT_MS}from"./types.js";import{ACP_PROTOCOL_VERSION}from"@beeos-ai/beeos-types/acp";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;function withUserMessagePrefix(e){return e.startsWith(USER_MESSAGE_PREFIX)?e:`${USER_MESSAGE_PREFIX_WITH_NEWLINE}${e}`}const BACKGROUND_SESSION_PATTERNS=[":cron:",":hook:","node-",":a2a:"];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){return!e||"New chat"===e||(!!/^[0-9a-f]{6,12}\s*\(20\d{2}/i.test(e)||(!!/^Sender\s*\(untrusted/i.test(e)||!!/^Conversation\s+info\s*\(untrusted/i.test(e)))}function cleanGatewayDerivedTitle(e){if(!e)return;let t=stripTransportMetadata(e);return/^\[System\b/.test(t)?void 0:(t=t.trim(),t||void 0)}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}export const BEEOS_CHANNEL_TAG_RE=/<!-- beeos:channel=(.+?) -->/;export function encodeBeeosChannelTag(e,t){const s=`\x3c!-- beeos:channel=${t} --\x3e`;return e?`${e}\n${s}`:s}export function decodeBeeosChannelId(e){if(!e)return;const t=BEEOS_CHANNEL_TAG_RE.exec(e);return t?.[1]}export function stripBeeosChannelTag(e){return e?e.replace(/\n?<!-- beeos:channel=.+? -->/,"").trim():""}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)}}export class AcpGatewayBridgeCore{state;transport;config;logger;writeObs;getGateway;thirdPartyChannels;beeosFileResolver;agentFetch;agentGatewayUrl;cronChannelCache=new Map;static CRON_CHANNEL_CACHE_MAX=256;localSessionHistory;mcp;initialized=!1;agentMapping=null;_syncResolvers=[];_mappingReadyCallbacks=[];cronIsolatedSessionKeys=new Set;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=[]}onceAgentMappingReady(e){this.agentMapping&&this.agentMapping.size>0?e():this._mappingReadyCallbacks.push(e)}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;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.thirdPartyChannels=e.thirdPartyChannels??new Set,this.beeosFileResolver=e.beeosFileResolver,this.agentFetch=e.agentFetch,this.agentGatewayUrl=e.agentGatewayUrl,this.localSessionHistory=new LocalSessionHistory({logger:this.logger}),this.mcp=new McpService({transport:this.transport,logger:this.logger,state:this.state}),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)})}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,o=i&&!isPlaceholderTitle(i)?i:void 0,r=createSessionObject({gatewayKey:s,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,title:o});this.registerSession(r,{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":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":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"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":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:"mcp/list"===e.method?await this.mcp.handleList(e):"mcp/set"===e.method?await this.mcp.handleSet(e):"mcp/unset"===e.method?await this.mcp.handleUnset(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.handleSessionCancel(void 0,e.params);break;case"canvas/toggle":case"canvas/clear":this.handleCanvasNotification?this.handleCanvasNotification(e.method,e.params):this.logger.debug?.(`[bridge-core] Canvas notification ignored (canvas disabled): ${e.method}`);break;case"canvas/reference":{const t=e.params,s=t?.surfaceId,n=this.state.resolveSessionFromParams(t);if(!n){this.logger.warn?.(`[bridge-core] canvas/reference ignored — no session found for sessionId=${t?.sessionId}`);break}n.referencedSurfaceId=s||void 0,this.logger.debug?.(`[bridge-core] Canvas reference ${s?"set":"cleared"}: ${s??"(none)"}`);break}default:e.method.startsWith("terminal/")&&this.handleTerminalNotification?this.handleTerminalNotification(e.method,e.params):this.logger.debug?.(`[bridge-core] Unknown notification: ${e.method}`)}}handleInitialize(e){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,o="user"===i?"user":"system"===i?"system":"assistant",r=n.lastTurnIdByRole?.[o];if(!r)return void this.logger.debug?.(`[bridge-core] session.message skipped: no lastTurnId role=${o} sessionKey=${t} messageId=${s}`);const a=e.message?.timestamp,l="number"==typeof a&&a>0?new Date(a).toISOString():void 0,d={turnId:r};"number"==typeof e.messageSeq&&(d.seq=e.messageSeq),this.transport.sendSessionUpdate(n.sessionId,{sessionUpdate:"message_id_bind",role:o,messageId:s,...l?{timestamp:l}:{}},d),n.lastTurnIdByRole&&(n.lastTurnIdByRole[o]=void 0),"assistant"===o&&reconcileMissingArtifacts({localHistory:this.localSessionHistory,transport:this.transport,logger:this.logger,writeObs:this.writeObs,isSessionAlive:e=>this.state.sessions.has(e)},{session:n,turnId:r,messageId:s,runId:void 0})}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,o=i?null:n,r=await loadHistory(o,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(r),l=a.filter(e=>"user"===e.role).length,d=a.filter(e=>"assistant"===e.role).length,c=a.filter(e=>e.toolCalls?.length).length,h=a.reduce((e,t)=>e+(t.toolCalls?.length??0),0);if(this.logger.debug?.(`[bridge-core] handleSessionLoad sid=${s} messages=${r.length} turns=${a.length} userTurns=${l} asstTurns=${d} turnsWithToolCalls=${c} totalToolCalls=${h}`),l>0&&e.pendingUserTurnUpdates&&e.pendingUserTurnUpdates.length>0&&(e.pendingUserTurnUpdates=[]),a.length>0&&isPlaceholderTitle(e.title)&&"manual"!==e.titleSource){const t=a.find(e=>{if("user"!==e.role)return!1;if("internal_system"===e.provenance?.kind)return!1;if(isCronPromptText(e.content))return!1;const t=stripTransportMetadata(e.content).trim();return t.length>0&&!/^Sender\s*\(untrusted/i.test(t)});if(t?.content){const n=stripTransportMetadata(t.content).trim().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 g=t=>`history:${e.gatewaySessionKey}:${t}`;let p=0,m=-1;if(i)for(let e=a.length-1;e>=0;e--)if("assistant"===a[e].role){m=e;break}for(let n=0;n<a.length;n++){const o=a[n];if(i&&n===m)this.logger.debug?.(`[bridge-core] SKIP history_turn[${n}] assistant — mq active, deferring to emitCurrentStreamSnapshot`);else if("user"!==o.role||"internal_system"!==o.provenance?.kind)if("user"===o.role&&/^\s*system\s*\(untrusted[^)]*\)/i.test(o.content))this.logger.debug?.(`[bridge-core] SKIP history_turn[${n}] system-injected user message`);else if("user"===o.role&&isHeartbeatPromptText(o.content))this.logger.info?.(`[bridge-core] SKIP history_turn[${n}] heartbeat cron prompt sessionId=${e.sessionId} contentLen=${o.content.length} preview="${previewFilteredText(o.content)}"`);else if("user"===o.role&&isCronPromptText(o.content))this.logger.info?.(`[bridge-core] SKIP history_turn[${n}] cron-triggered user message sessionId=${e.sessionId} contentLen=${o.content.length} preview="${previewFilteredText(o.content)}"`);else{if("assistant"===o.role){const t=classifyHeartbeatFilter(o.content);if(t.filtered){this.logger.info?.(`[bridge-core] SKIP history_turn[${n}] heartbeat assistant reply reason=${t.reason} sessionId=${e.sessionId} contentLen=${o.content.length} preview="${previewFilteredText(o.content)}"`);continue}}if("system"!==o.role)if(this.logger.debug?.(`[bridge-core] SENDING history_turn[${n}] role=${o.role} contentLen=${o.content.length} content=${JSON.stringify(o.content.slice(0,80))} tcCount=${o.toolCalls?.length??0}`),"user"===o.role)this.replayUserTurnAsChunks(s,o.content,o.metadata,o.timestamp,g(n),o._seq);else{if(await this.replayAssistantTurnAsStream(s,o,g(n)),o.toolCalls)for(const e of o.toolCalls)e.id&&t.add(e.id);this.transport.sendSessionUpdate(s,{sessionUpdate:"stream_complete",stopReason:"end_turn"},{turnId:g(n)}),p+=1}else this.logger.debug?.(`[bridge-core] SENDING system_message[${n}] contentLen=${o.content.length}`),this.transport.sendSessionUpdate(s,{sessionUpdate:"system_message_chunk",content:{type:"text",text:o.content},metadata:o.metadata,...o.timestamp?{timestamp:o.timestamp}:{}},{turnId:g(n),...void 0!==o._seq?{seq:o._seq}:{}})}else this.logger.debug?.(`[bridge-core] SKIP history_turn[${n}] internal_system user message`)}this.logger.debug?.(`[bridge-core] emitHistoryTurns DONE sid=${s} historyStreamCompleteEmitted=${p} replayedToolCallIds=${t.size}`)}catch(e){this.logger.warn?.("[bridge-core] Failed to load session history:",e)}return t}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],o=n.sessionUpdate,r=n.toolCallId;if("tool_call"!==o&&"tool_call_update"!==o||!r||!t.has(r)){if("agent_message_chunk"===o){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 o=resolveTurnId(e),r=o?{turnId:o}:void 0;for(let t=i;t<s.length;t++)this.transport.sendSessionUpdate(e.sessionId,s[t],r)}}async handleSessionList(e){const t=[];for(const[,e]of this.state.sessions)isBackgroundSessionKey(e.gatewaySessionKey)||this.cronIsolatedSessionKeys.has(e.gatewaySessionKey)||t.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 s=this.getGateway();if(s?.isConnected)try{const e=await s.sessionsList();if(e&&"object"==typeof e&&Array.isArray(e.sessions)){const s=e.sessions;for(const e of s){const s=e,n=s.sessionKey??s.key??s.id??s.name;if(!n||"string"!=typeof n)continue;if(isBackgroundSessionKey(n))continue;if(this.cronIsolatedSessionKeys.has(n))continue;const i=deriveSessionId(n,this.instanceId),o=t.find(e=>e.sessionId===n||e.sessionId===i||this.state.sessions.get(e.sessionId)?.gatewaySessionKey===n),r=s.label||cleanGatewayDerivedTitle(s.derivedTitle)||s.title||void 0,a=r&&!isPlaceholderTitle(r)?r:void 0,l=s.model,d=s.modelProvider;if(o){if(a&&isPlaceholderTitle(o.title)){o.title=a;const e=this.state.sessions.get(o.sessionId);e&&isPlaceholderTitle(e.title)&&(e.title=a)}const e=s.updatedAt;e&&(o.updatedAt=e),l&&(o.model=l),d&&(o.modelProvider=d)}else{const e=createSessionObject({gatewayKey:n,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,cwd:s.cwd,title:a});this.registerSession(e,{ensureVerbose:!1}),t.push({sessionId:e.sessionId,title:a||"",cwd:s.cwd,updatedAt:s.updatedAt,agentId:e.agentId,platformAgentId:e.platformAgentId,deletable:!isSystemDefaultSessionKey(n),model:l,modelProvider:d})}}}}catch(e){this.logger.debug?.("[bridge-core] sessions.list enrichment failed:",e)}t.sort((e,t)=>(t.updatedAt??0)-(e.updatedAt??0)||e.sessionId.localeCompare(t.sessionId)),this.transport.sendResult(e.id,{sessions:t})}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)return void this.transport.sendAcpError(e.id,Errors.SessionNotFound);i.title=n,i.titleSource="manual";const o=i.gatewaySessionKey,r=this.getGateway();r?.isConnected&&r.sessionsPatch(o,{label:n}).catch(e=>{this.logger.debug?.(`[bridge-core] sessionsPatch (rename) failed: ${e instanceof Error?e.message:e}`)}),this.transport.sendResult(e.id,{sessionId:t,title:n})}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"},{match:["新会话","new chat","new conversation"],zh:"新会话",en:"New Conversation"}];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 (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.\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- If both the question and answer are too vague to summarize, return "新会话" (for zh) or "New Conversation" (for en).\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]\nhi\n\n[Assistant Answer]\nHello! How can I help you today?\nOutput: {"title": "New Conversation"}';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 o=(process.env.AROUTER_BASE_URL||"").replace(/\/$/,""),r=process.env.AROUTER_API_KEY||"";if(!o||!r)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(`${o}/v1/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},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 o=i.replace(/^```json\s*/,"").replace(/```$/,"").trim();let r;try{r=JSON.parse(o).title?.trim()??""}catch{return void this.logger.debug?.(`[bridge-core] title-gen JSON parse failed: ${o}`)}if(!r)return;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="${r}"`),e.title=r,e.titleSource="auto";const a=this.getGateway();a?.isConnected&&a.sessionsPatch(e.gatewaySessionKey,{label:r}).catch(()=>{}),this.transport.sendSessionUpdate(t,{sessionUpdate:"title_update",title:r})}).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 o=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=stripTransportMetadata(e.content).trim();return!!t&&!/^Sender\s*\(untrusted/i.test(t)});if(!o)return;const r=i.indexOf(o),a=i.slice(r+1).find(e=>"assistant"===e.role&&!!e.content?.trim());if(!a)return;const l=stripTransportMetadata(o.content).trim(),d=a.content.trim();l&&d&&this.generateTitleFromQA(e,t,l,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;this.logger.info?.(`[bridge-core] session/delete sessionId=${t} gatewayKey=${n} gwConnected=${!!this.getGateway()?.isConnected}`);let i=!1;const o=this.getGateway();if(o?.isConnected&&n)try{await o.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 o.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}`);void 0!==s.pendingPromptId&&this.failPrompt(s,Errors.SessionDeleted.rpcCode,Errors.SessionDeleted.message),this.state.clearPromptTimeout(s),this.state.clearStreamIdleTimer(s),s.assistantMq?.close(),s.assistantMq=void 0,s.currentRunId&&this.state.promptsByRunId.delete(s.currentRunId);const r=new Set;for(const[e,s]of this.state.toolCallToSessionMap)s===t&&(this.state.toolCallToSessionMap.delete(e),r.add(e));for(const[e,t]of this.state.toolCallIdMap)r.has(t)&&this.state.toolCallIdMap.delete(e);this.state.sessions.delete(t),this.state.sessionsByGatewayKey.delete(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})}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}`),i&&(s.currentRunId||s.gatewayRequestId)&&n.agentCancel(s.gatewaySessionKey,{runId:s.currentRunId,requestId:s.gatewayRequestId}),this.endRun(s,{kind:"complete",stopReason:"cancelled"})),i&&s.gatewaySessionKey)try{await n.sessionsReset(s.gatewaySessionKey),this.logger.info?.(`[bridge-core] Gateway sessions.reset SUCCESS for key=${s.gatewaySessionKey}`)}catch(e){this.logger.warn?.(`[bridge-core] Gateway sessions.reset FAILED for key=${s.gatewaySessionKey}: ${e instanceof Error?e.message:e}`)}else this.logger.warn?.(`[bridge-core] session/clear skipped gateway reset: connected=${i}, key=${s.gatewaySessionKey}`);s.chatReplayDedupKeys.clear(),this.logger.info?.("[bridge-core] session/clear dedupKeys cleared, calling onSessionCleared"),this.onSessionCleared?.(t,s.gatewaySessionKey),this.transport.sendResult(e.id,{cleared:!0}),this.logger.info?.("[bridge-core] session/clear DONE, sent cleared=true")}async handleSessionSetMode(e){const t=e.params?.sessionId,s=e.params?.mode,n=t?this.state.sessions.get(t):void 0,i=this.getGateway();if(n&&i?.isConnected&&s){const e={};if("verbose"===s||"detailed"===s?e.verboseLevel="full":"concise"!==s&&"default"!==s||(e.verboseLevel="default"),"reasoning"!==s&&"thinking"!==s||(e.reasoningLevel="stream"),Object.keys(e).length>0)try{await i.sessionsPatch(n.gatewaySessionKey,e)}catch(e){this.logger.warn?.(`[bridge-core] sessions.patch failed: ${e instanceof Error?e.message:e}`)}}this.transport.sendResult(e.id,{mode:s??"default"})}async handleSessionSetModel(e){const t=e.params?.sessionId,s=e.params?.model,n=t?this.state.sessions.get(t):void 0,i=this.getGateway();let o=s??null,r=null;if(n&&i?.isConnected&&s)try{const e=await i.sessionsPatch(n.gatewaySessionKey,{model:s}),t=e?.resolved;t?.model&&(o=t.model),t?.modelProvider&&(r=t.modelProvider)}catch(e){this.logger.warn?.(`[bridge-core] sessions.patch for model failed: ${e instanceof Error?e.message:e}`)}this.transport.sendResult(e.id,{model:o,modelProvider:r})}async handleModelsList(e){const t=this.getGateway();if(t?.isConnected)try{const s=await t.request("models.list",{});this.transport.sendResult(e.id,s??{models:[]})}catch(t){this.transport.sendAcpError(e.id,Errors.InternalError,{message:`Failed to list models: ${t instanceof Error?t.message:t}`})}else this.transport.sendAcpError(e.id,Errors.GatewayNotConnected)}async handleSkillsList(e){const t=await this.fetchSimplifiedSkills();this.transport.sendResult(e.id,{skills:t})}async fetchSimplifiedSkills(){const e=this.getGateway();if(!e?.isConnected)return[];try{const t=await e.skillsStatus();if(!t?.skills)return[];const s=t.skills.filter(e=>!1!==e.eligible||!0===e.disabled).sort((e,t)=>e.always&&!t.always?-1:!e.always&&t.always?1:e.name.localeCompare(t.name)).map(e=>({name:e.name,description:e.description,emoji:e.emoji,always:e.always||void 0,bundled:e.bundled||void 0,disabled:e.disabled||void 0,skillKey:e.skillKey||void 0,iconUrl:void 0})),n=this.getSkillsDir();for(const e of s){const t=e.skillKey??e.name;try{const s=await readFile(join(n,t,".beeos-meta.json"),"utf8"),i=JSON.parse(s);i?.iconUrl&&(e.iconUrl=i.iconUrl)}catch{}}return s}catch(e){return this.logger.warn?.(`[bridge-core] Failed to fetch skills: ${e instanceof Error?e.message:e}`),[]}}async pushSkillsList(){const e=await this.fetchSimplifiedSkills();this.transport.sendNotification("session/update",{sessionId:"_system",update:{sessionUpdate:"available_commands_update",commands:e}}),this.writeObs({component:"bridge-core",domain:"lifecycle",name:"skills.pushed",severity:"debug",payload:{count:e.length}})}getSkillsDir(){const e=process.env.OPENCLAW_HOME||join(homedir(),".openclaw");return join(e,"skills")}async handleSkillsInstall(e){const t=e.params,s=t?.zipUrl,n=t?.files;let i;try{i=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)return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Missing skill files or zipUrl"});const o=resolveSkillInstallDir(this.getSkillsDir(),i);try{if(await mkdir(o,{recursive:!0}),s){const e=await fetchWithRetry(s,{maxRetries:4,logger:this.logger});await extractZipToDir(e,o)}else if(n?.length){const e=resolve(o);for(const t of n){const s=join(o,t.path);if(!resolve(s).startsWith(e+sep))throw new Error(`File path escapes skill directory: ${t.path}`);await mkdir(join(s,".."),{recursive:!0});const n=await fetch(t.downloadUrl,{signal:AbortSignal.timeout(12e4)});if(!n.ok)throw new Error(`Failed to download ${t.path}: ${n.status}`);const i=Buffer.from(await n.arrayBuffer());await writeFile(s,i)}}if(t?.iconUrl)try{await writeFile(join(o,".beeos-meta.json"),JSON.stringify({iconUrl:t.iconUrl}),"utf8")}catch{}this.logger.info?.(`[bridge-core] Installed skill "${i}" via ${s?"zip":"files"}`),this.transport.sendResult(e.id,{success:!0}),this.onSkillInstalled?.(i,o),await this.pushSkillsList()}catch(t){this.logger.error?.(`[bridge-core] Failed to install skill "${i}": ${t instanceof Error?t.message:t}`),this.transport.sendAcpError(e.id,Errors.InternalError,{message:`Install failed: ${t instanceof Error?t.message:String(t)}`})}}async handleSkillsUninstall(e){const t=e.params;let s;try{s=validateSkillSlug(t?.slug||t?.name||"")}catch{return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Invalid or missing skill name"})}const n=resolveSkillInstallDir(this.getSkillsDir(),s),i=resolveSkillInstallDir(join(homedir(),".agents","skills"),s);try{let t=!1;try{const e=await lstat(n);if(e.isSymbolicLink()){const e=await readlink(n);await rm(n,{force:!0}),await rm(e,{recursive:!0,force:!0}),t=!0}else e.isDirectory()&&(await rm(n,{recursive:!0,force:!0}),t=!0)}catch{}try{const e=await lstat(i);(e.isDirectory()||e.isSymbolicLink())&&(await rm(i,{recursive:!0,force:!0}),t=!0)}catch{}t||this.logger.warn?.(`[bridge-core] Skill "${s}" not found in any known location`),this.logger.info?.(`[bridge-core] Uninstalled skill "${s}"`),this.transport.sendResult(e.id,{success:!0}),await this.pushSkillsList()}catch(t){this.logger.error?.(`[bridge-core] Failed to uninstall skill "${s}": ${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;if(!s||"boolean"!=typeof n)return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Missing skillKey or enabled"});const i=this.getGateway();if(i?.isConnected)try{const t=await i.skillsUpdate(s,n);this.logger.info?.(`[bridge-core] Updated skill "${s}" enabled=${n}`),this.transport.sendResult(e.id,{ok:t?.ok??!0,skillKey:s,enabled:n}),await this.pushSkillsList()}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.InternalError,{message:"Gateway not connected"})}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 o=n.sessionId;this.state.lastActiveSessionId=o,this.onPromptStart?.();const r=this.getGateway();if(!r?.isConnected)return void this.transport.sendAcpError(e.id,Errors.GatewayNotConnected);await this.ensureVerboseFull(n);let a=extractPromptBlocks(sanitizePromptPayload(s));if(!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=${o} 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",r?.isConnected&&e&&r.sessionsPatch(n.gatewaySessionKey,{label:e}).catch(e=>{this.logger.debug?.(`[bridge-core] sessionsPatch (title) failed: ${e instanceof Error?e.message:e}`)}),this.transport.sendSessionUpdate(o,{sessionUpdate:"title_update",title:e})}}}const l=buildResolutionPlan(a);if(l.refs.length>0)try{const e=await resolveResources(l,this.writeObs);a=applyResolutions(a,e)}catch(e){this.logger.warn?.(`[bridge-core] Resource pre-resolution failed: ${e instanceof Error?e.message:e}`)}let d;if(this.beeosFileResolver){const e=this.beeosFileResolver.buildResolutionPlan(a);if(e.refs.length>0)try{d=await this.beeosFileResolver.resolveMetadataForPrompt(e)}catch(e){this.logger.warn?.(`[bridge-core] BeeOS file resolution failed: ${e instanceof Error?e.message:e}`)}}const c=toGatewayPrompt(a,{beeosFileResolutionsByUri:d});if("error"in c)return void this.transport.sendAcpError(e.id,Errors.PromptConvertFailed,{message:c.error});const{message:h,attachments:g}=c,p=resolveStandaloneSlashCommandName(a,h)??resolveSlashCmd(a,h),m="string"==typeof p;if(p&&this.handleSlashCommand){const t=this;if(await(async()=>{try{return await t.handleSlashCommand(p)}catch(e){return t.logger.warn?.(`[bridge-core] /${p} handler failed: ${e instanceof Error?e.message:e}`),!1}})())return this.emitPromptAsUserSessionUpdates(n,a,resolveTurnId(n)),this.transport.sendSessionUpdate(o,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Loading ${p}...`},timestamp:(new Date).toISOString()},{turnId:resolveTurnId(n)}),void this.transport.sendResult(e.id,{stopReason:"end_turn"})}const u="chat.send";let y=m?h:withUserMessagePrefix(h);const f=this.config.canvasEnabled&&!m&&!1!==n.canvasActive&&!n.channelType;if(f){const e=n.promptsSinceCanvasInjection??0;!n.canvasPromptInjected||e>=10?(y=`${CANVAS_TERM_MAPPING}\n\n${y}`,n.canvasPromptInjected=!0,n.promptsSinceCanvasInjection=0,this.logger.debug?.("[bridge-core] Canvas term mapping injected (re-inject cycle)")):n.promptsSinceCanvasInjection=e+1}if(f){const e=this.getCanvasState?.();if(e){const t=e.resolveCanvasForSession(n.gatewaySessionKey);y=`${buildActiveSurfacesContext(e,t)??"[Canvas] Canvas panel is available. Use render_ui for structured/visual content."}\n\n${y}`}const t=n.referencedSurfaceId;t&&(y=`${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${y}`,n.referencedSurfaceId=void 0)}if(!m){const t=parseMentionsParam(e.params?.mentions);if(t.length>0){n.activeMentions=t;y=`${buildMentionInstruction(t)}\n${y}`,this.logger.debug?.(`[bridge-core] A2A mention instruction injected for ${t.length} agent(s)`)}else n.activeMentions=void 0}m&&this.logger.info?.(`[bridge-core] slash command passthrough sessionId=${o} command=/${p}`),n.promptDone||void 0===n.pendingPromptId&&void 0===n.currentRunId||(this.logger.warn?.(`[bridge-core] handleSessionPrompt: force-ending stale run sid=${o} oldRunId=${n.currentRunId} oldPromptId=${n.pendingPromptId}`),(n.currentRunId||n.gatewayRequestId)&&r.agentCancel(n.gatewaySessionKey,{runId:n.currentRunId,requestId:n.gatewayRequestId}),this.endRun(n,{kind:"complete",stopReason:"cancelled"})),this.state.resetForNewRun(n,o,this.transport),n.pendingPromptId=e.id,n.gatewayMethod=u;const S=resolveTurnId(n);this.emitPromptAsUserSessionUpdates(n,a,S),this.transport.sendSessionUpdate(o,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:""},timestamp:(new Date).toISOString()},S?{turnId:S}:void 0),this.schedulePromptTimeout(n);const w=g.length>0?g.map(e=>({type:e.type,content:e.content,...e.mimeType?{mimeType:e.mimeType}:{},...e.fileName?{fileName:e.fileName}:{}})):void 0,I=`req_${randomUUID().replace(/-/g,"")}`,v={sessionKey:n.gatewaySessionKey,message:y,deliver:!1,idempotencyKey:randomUUID()};w?.length&&(v.attachments=w);if(!r.sendFrame({type:"req",id:I,method:u,params:v}))return this.state.clearPromptTimeout(n),n.pendingPromptId=void 0,n.assistantMq?.close(),n.assistantMq=void 0,n.pendingUserTurnUpdates=void 0,void this.transport.sendAcpError(e.id,Errors.SendFailed,{message:"failed to send prompt to gateway"});n.gatewayRequestId=I,this.state.promptsByGatewayRequestId.set(I,n)}replayUserTurnAsChunks(e,t,s,n,i,o){const r=splitUserReplayBlocks(t),a=i||void 0!==o?{...i?{turnId:i}:{},...void 0!==o?{seq:o}:{}}:void 0;for(const t of r){let i;if("text"===t.type){if(!t.text)continue;i={type:"text",text:t.text}}else i="resource_link"===t.type?{type:"resource_link",uri:t.uri??"",...t.fileName?{name:t.fileName}:{},...t.mimeType?{mimeType:t.mimeType}:{}}:{type:t.type,...t.mimeType?{mimeType:t.mimeType}:{},...t.fileName?{fileName:t.fileName}:{}};this.transport.sendSessionUpdate(e,{sessionUpdate:"user_message_chunk",content:i,...s?{metadata:s}:{},...n?{timestamp:n}:{}},a)}}async replayAssistantTurnAsStream(e,t,s){const n=e=>{if(s||void 0!==e)return{...s?{turnId:s}:{},...void 0!==e?{seq:e}:{}}},i=n(t._seq);if(!t.sourceMessages?.length){const s={sessionUpdate:"history_turn",role:t.role,content:t.content,reasoning:t.reasoning,toolCalls:t.toolCalls,...t.timestamp?{timestamp:t.timestamp}:{}};return t.metadata&&(s.metadata=t.metadata),void this.transport.sendSessionUpdate(e,s,i)}for(const s of t.sourceMessages){const i=s.updateType??"agent_message_chunk",o=n(s._seq);switch(i){case"agent_message_chunk":this.transport.sendSessionUpdate(e,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:s.content},...s.timestamp?{timestamp:s.timestamp}:{},...s.metadata?{metadata:s.metadata}:{}},o);break;case"agent_thought_chunk":this.transport.sendSessionUpdate(e,{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:s.content},...s.timestamp?{timestamp:s.timestamp}:{}},o);break;case"tool_call":{const n=s.toolCallId??"",i=t.toolCalls?.find(e=>e.id===n),r=s.toolName??"tool",a=s.content??"";let l={};if(a)try{l=JSON.parse(a)}catch{}this.transport.sendSessionUpdate(e,buildToolCallPayload({toolCallId:n,toolName:r,args:l,kind:i?.kind,status:i?.status??"in_progress",timestamp:s.timestamp}),o);break}case"tool_call_update":{const n=s.toolCallId??"",i=t.toolCalls?.find(e=>e.id===n),r=s.toolName??i?.name??"tool",a=s.content??i?.output??"";let l=await readEnrichmentCache(n).catch(()=>{});if(!l){const e=extractBeeosFileUrisFromOutput(a);e.length>0&&(l=e.map(e=>({uri:e,name:"file"})))}if(!l&&"beeos_upload_file"===r){const e=await readUploadToolResult(n).catch(()=>{});if(e){const t=buildToolResultSessionContentBlocks(r,e).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}:{}}));t.length>0&&(l=t)}}this.transport.sendSessionUpdate(e,buildToolCallUpdatePayload({toolCallId:n,toolName:r,outputText:a,kind:i?.kind,status:i?.status??"completed",resourceLinks:l,timestamp:s.timestamp}),o);break}}}}emitPromptAsUserSessionUpdates(e,t,s){const n=(new Date).toISOString(),i=s?{turnId:s}:void 0;for(const o of t){const t=this.toUserSessionUpdateContent(o);if(!t)continue;const r={sessionUpdate:"user_message_chunk",content:t,timestamp:n};s&&void 0===r._turnId&&(r._turnId=s),this.transport.sendSessionUpdate(e.sessionId,r,i),e.pendingUserTurnUpdates?.push(r)}}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,o=t.data??e.data,r=t.fileName??t.file_name??t.filename??t.name??e.fileName??e.file_name??e.filename??e.name;if(!s&&!i&&!o)return;return{type:"resource",resource:{...s?{uri:s}:{},...n?{mimeType:n}:{},...i?{text:i}:{},...o?{data:o}:{},...r?{fileName:r}:{}}}}}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=this.getGateway(),o=i?.isConnected,r=!(!n.currentRunId&&!n.gatewayRequestId);if(o&&r){i.agentCancel(n.gatewaySessionKey,{runId:n.currentRunId,requestId:n.gatewayRequestId})}this.endRun(n,{kind:"complete",stopReason:"cancelled"})||this.transport.sendSessionUpdate(n.sessionId,{sessionUpdate:"stream_complete",stopReason:"cancelled"},{turnId:resolveTurnId(n)}),void 0!==e&&this.transport.sendResult(e,{})}endRun(e,t){if(e.promptDone)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)return this.logger.debug?.(`[bridge-core] endRun skipped (no pendingPromptId and no currentRunId) sessionId=${e.sessionId} outcome=${t.kind}`),!1;const s=resolveTurnId(e),n=s?{turnId:s}:void 0;e.promptDone=!0;const i=e.currentRunId;if("complete"===t.kind){if(i&&this.onRunComplete){const t=e.agentAssistantTextSoFar??e.chatAssistantTextSoFar??"";this.onRunComplete(i,t)}void 0!==e.pendingPromptId&&this.transport.sendResult(e.pendingPromptId,{stopReason:t.stopReason}),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:t.stopReason},n),this.tryGenerateTitleFromHistory(e,e.sessionId)}else i&&this.onRunFailed&&this.onRunFailed(i,t.message),void 0!==e.pendingPromptId&&this.transport.sendError(e.pendingPromptId,t.code,t.message),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:"error",error:t.message},n);return this.cleanupPrompt(e),this.onRunEnded?.(e,t),!0}schedulePromptTimeout(e){this.state.clearPromptTimeout(e);const t=this.config.promptTimeoutMs??DEFAULT_PROMPT_TIMEOUT_MS;t<=0||(e.promptTimeoutTimer=setTimeout(()=>{void 0!==e.pendingPromptId&&(this.logger.warn?.(`[bridge-core] Prompt timed out sessionId=${e.sessionId} after ${t}ms`),this.failPrompt(e,Errors.PromptTimeout.rpcCode,`Prompt timed out after ${t}ms`))},t),"object"==typeof e.promptTimeoutTimer&&"unref"in e.promptTimeoutTimer&&e.promptTimeoutTimer.unref())}cleanupPrompt(e){this.state.clearPromptTimeout(e),this.state.clearStreamIdleTimer(e);const t=e.currentRunId;if(t){this.state.promptsByRunId.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.assistantMq?.close(),e.assistantMq=void 0,e.pendingUserTurnUpdates=void 0}completePrompt(e,t){this.endRun(e,{kind:"complete",stopReason:t})}failPrompt(e,t,s){this.endRun(e,{kind:"error",code:t,message:s})}cleanupAllPendingPrompts(){for(const e of this.state.sessions.values())this.failPrompt(e,Errors.GatewayDisconnected.rpcCode,Errors.GatewayDisconnected.message)}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";return this.logger.warn?.(`[bridge-core] handleGatewayResponse: gateway rejected prompt gatewayRequestId=${t} error=${i}`),void this.failPrompt(s,Errors.SendFailed.rpcCode,i)}const n=e.payload,i=n?.runId;i?(s.currentRunId=i,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)this.completePrompt(e,"end_turn");else if("aborted"===s||"cancelled"===s||"cancel"===s)this.completePrompt(e,"cancelled");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";this.failPrompt(e,Errors.AgentError.rpcCode,formatFriendlyError(s))}}pushToolResultContent(e,t,s,n){if(0===s.length)return;const i=n?this.state.promptsByRunId.get(n):void 0;if(!i)return void this.logger.warn?.(`[bridge-core] pushToolResultContent dropped — no session for runId=${n??"(none)"}`);const o=i.sessionId,r=(new Date).toISOString(),a={turnId:resolveTurnId(i)};for(const e of s){const t=narrowContentBlock(e);if(!t)continue;const s={sessionUpdate:"agent_message_chunk",content:t,timestamp:r};this.transport.sendSessionUpdate(o,s,a),i.assistantMq?.push(s)}this.writeObs({component:"bridge-core",domain:"tool",name:"tool_result.direct_push",severity:"info",payload:{toolCallId:e,toolName:t,blockCount:s.length,sessionId:o}})}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??{}};if("cron.add"!==s&&"cron.update"!==s||!0!==n._beeos_internal)void 0!==n._beeos_internal&&delete n._beeos_internal;else{delete n._beeos_internal;const e=await this.allocateCronChannel(n.name??"cron");e&&(n.description=encodeBeeosChannelTag(n.description,e))}try{const i=await t.request(s,n);if(this.transport.sendResult(e.id,i??{}),("cron.add"===s||"cron.update"===s)&&i&&"object"==typeof i){const e=i.id,t=decodeBeeosChannelId(n.description);e&&t&&this.setCronChannelCache(e,t)}"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 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;for(const e of s){if(!e||"object"!=typeof e)continue;const t=e;if("isolated"!==t.sessionTarget)continue;const s=t.sessionKey;"string"==typeof s&&s.length>0&&n.add(s)}this.cronIsolatedSessionKeys=n}catch(e){this.logger.debug?.(`[bridge-core] refreshCronIsolatedSessionKeys failed: ${e instanceof Error?e.message:e}`)}}}async function fetchWithRetry(e,t={}){const s=t.maxRetries??3;let n;for(let i=0;i<=s;i++){const o=await fetch(e,{signal:AbortSignal.timeout(12e4),redirect:"follow"});if(o.ok)return Buffer.from(await o.arrayBuffer());if(429===o.status||o.status>=500){const r=Number(o.headers.get("retry-after"))||0,a=1e3*Math.max(r,2**i);if(n=new Error(`HTTP ${o.status} from ${e}`),i<s){t.logger?.info?.(`[bridge-core] Download ${o.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: ${o.status}`)}throw n??new Error("Download failed after retries")}const SKILL_ROOT_MARKERS=["SKILL.md","skill.md","SKILL.MD"];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 o=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})}),o++}if(0===o)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 resolveSkillInstallDir(e,t){const s=safeDirName(t),n=join(e,s),i=resolve(e),o=resolve(n),r=relative(i,o);if(!r||".."===r||r.startsWith(`..${sep}`)||path.isAbsolute(r))throw new Error("Invalid skill target path");return n}
|
|
1
|
+
import{randomUUID,createHash}from"node:crypto";import{mkdir,writeFile,readFile,rm,lstat,readlink,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,stripTransportMetadata,isHeartbeatPromptText,isCronPromptText,extractCronJobId,classifyHeartbeatFilter,previewFilteredText}from"../message-filter.js";import{createCronOverridesStore}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"../a2a/mention-resolver.js";import{extractPromptBlocks,toGatewayPrompt,resolveSlashCommandName as resolveSlashCmd}from"./prompt-converter.js";import{loadHistory,groupIntoTurns,extractBeeosFileUrisFromOutput,splitUserReplayBlocks}from"./history-replay.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-payload-strategies.js";import{buildToolCallPayload,buildToolCallUpdatePayload}from"./tool-call-payload-builder.js";import{Errors}from"../errors/index.js";import{formatFriendlyError}from"../errors/classify.js";import{resolveChannelFromSessionKey}from"../channel-detection.js";import{resolveTurnId,recordTurnIdForRole}from"./gateway-events.js";import{McpService}from"./mcp-service.js";import{DEFAULT_PROMPT_TIMEOUT_MS}from"./types.js";import{ACP_PROTOCOL_VERSION}from"@beeos-ai/beeos-types/acp";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;function withUserMessagePrefix(e){return e.startsWith(USER_MESSAGE_PREFIX)?e:`${USER_MESSAGE_PREFIX_WITH_NEWLINE}${e}`}const BACKGROUND_SESSION_PATTERNS=[":cron:",":hook:","node-",":a2a:",":mcp:",":openapi:"];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){return!e||"New chat"===e||(!!/^[0-9a-f]{6,12}\s*\(20\d{2}/i.test(e)||(!!/^Sender\s*\(untrusted/i.test(e)||!!/^Conversation\s+info\s*\(untrusted/i.test(e)))}function cleanGatewayDerivedTitle(e){if(!e)return;let t=stripTransportMetadata(e);return/^\[System\b/.test(t)?void 0:(t=t.trim(),t||void 0)}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}export const BEEOS_CHANNEL_TAG_RE=/<!-- beeos:channel=(.+?) -->/;export function encodeBeeosChannelTag(e,t){const s=`\x3c!-- beeos:channel=${t} --\x3e`;return e?`${e}\n${s}`:s}export function decodeBeeosChannelId(e){if(!e)return;const t=BEEOS_CHANNEL_TAG_RE.exec(e);return t?.[1]}export function stripBeeosChannelTag(e){return e?e.replace(/\n?<!-- beeos:channel=.+? -->/,"").trim():""}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)}}export class AcpGatewayBridgeCore{state;transport;config;logger;writeObs;getGateway;thirdPartyChannels;beeosFileResolver;agentFetch;agentGatewayUrl;cronChannelCache=new Map;static CRON_CHANNEL_CACHE_MAX=256;localSessionHistory;mcp;initialized=!1;agentMapping=null;_syncResolvers=[];_mappingReadyCallbacks=[];cronIsolatedSessionKeys=new Set;cronOverrides;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=[]}onceAgentMappingReady(e){this.agentMapping&&this.agentMapping.size>0?e():this._mappingReadyCallbacks.push(e)}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;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.thirdPartyChannels=e.thirdPartyChannels??new Set,this.beeosFileResolver=e.beeosFileResolver,this.agentFetch=e.agentFetch,this.agentGatewayUrl=e.agentGatewayUrl,this.localSessionHistory=new LocalSessionHistory({logger:this.logger}),this.cronOverrides=createCronOverridesStore(this.logger),this.mcp=new McpService({transport:this.transport,logger:this.logger,state:this.state}),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)})}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,o=i&&!isPlaceholderTitle(i)?i:void 0,r=createSessionObject({gatewayKey:s,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,title:o});this.registerSession(r,{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":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":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"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":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:"mcp/list"===e.method?await this.mcp.handleList(e):"mcp/set"===e.method?await this.mcp.handleSet(e):"mcp/unset"===e.method?await this.mcp.handleUnset(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.handleSessionCancel(void 0,e.params);break;case"canvas/toggle":case"canvas/clear":this.handleCanvasNotification?this.handleCanvasNotification(e.method,e.params):this.logger.debug?.(`[bridge-core] Canvas notification ignored (canvas disabled): ${e.method}`);break;case"canvas/reference":{const t=e.params,s=t?.surfaceId,n=this.state.resolveSessionFromParams(t);if(!n){this.logger.warn?.(`[bridge-core] canvas/reference ignored — no session found for sessionId=${t?.sessionId}`);break}n.referencedSurfaceId=s||void 0,this.logger.debug?.(`[bridge-core] Canvas reference ${s?"set":"cleared"}: ${s??"(none)"}`);break}default:e.method.startsWith("terminal/")&&this.handleTerminalNotification?this.handleTerminalNotification(e.method,e.params):this.logger.debug?.(`[bridge-core] Unknown notification: ${e.method}`)}}handleInitialize(e){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,o="user"===i?"user":"system"===i?"system":"assistant",r=n.lastTurnIdByRole?.[o];if(!r)return void this.logger.debug?.(`[bridge-core] session.message skipped: no lastTurnId role=${o} sessionKey=${t} messageId=${s}`);const a=e.message?.timestamp,l="number"==typeof a&&a>0?new Date(a).toISOString():void 0,d={turnId:r};"number"==typeof e.messageSeq&&(d.seq=e.messageSeq),this.transport.sendSessionUpdate(n.sessionId,{sessionUpdate:"message_id_bind",role:o,messageId:s,...l?{timestamp:l}:{}},d),n.lastTurnIdByRole&&(n.lastTurnIdByRole[o]=void 0),"assistant"===o&&reconcileMissingArtifacts({localHistory:this.localSessionHistory,transport:this.transport,logger:this.logger,writeObs:this.writeObs,isSessionAlive:e=>this.state.sessions.has(e)},{session:n,turnId:r,messageId:s,runId:void 0})}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,o=i?null:n,r=await loadHistory(o,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(r),l=a.filter(e=>"user"===e.role).length,d=a.filter(e=>"assistant"===e.role).length,c=a.filter(e=>e.toolCalls?.length).length,h=a.reduce((e,t)=>e+(t.toolCalls?.length??0),0);if(this.logger.debug?.(`[bridge-core] handleSessionLoad sid=${s} messages=${r.length} turns=${a.length} userTurns=${l} asstTurns=${d} turnsWithToolCalls=${c} totalToolCalls=${h}`),l>0&&e.pendingUserTurnUpdates&&e.pendingUserTurnUpdates.length>0&&(e.pendingUserTurnUpdates=[]),a.length>0&&isPlaceholderTitle(e.title)&&"manual"!==e.titleSource){const t=a.find(e=>{if("user"!==e.role)return!1;if("internal_system"===e.provenance?.kind)return!1;if(isCronPromptText(e.content))return!1;const t=stripTransportMetadata(e.content).trim();return t.length>0&&!/^Sender\s*\(untrusted/i.test(t)});if(t?.content){const n=stripTransportMetadata(t.content).trim().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 g=t=>`history:${e.gatewaySessionKey}:${t}`;let p=0,m=-1;if(i)for(let e=a.length-1;e>=0;e--)if("assistant"===a[e].role){m=e;break}for(let n=0;n<a.length;n++){const o=a[n];if(i&&n===m)this.logger.debug?.(`[bridge-core] SKIP history_turn[${n}] assistant — mq active, deferring to emitCurrentStreamSnapshot`);else if("user"!==o.role||"internal_system"!==o.provenance?.kind)if("user"===o.role&&/^\s*system\s*\(untrusted[^)]*\)/i.test(o.content))this.logger.debug?.(`[bridge-core] SKIP history_turn[${n}] system-injected user message`);else if("user"===o.role&&isHeartbeatPromptText(o.content))this.logger.info?.(`[bridge-core] SKIP history_turn[${n}] heartbeat cron prompt sessionId=${e.sessionId} contentLen=${o.content.length} preview="${previewFilteredText(o.content)}"`);else if("user"===o.role&&isCronPromptText(o.content))this.logger.info?.(`[bridge-core] SKIP history_turn[${n}] cron-triggered user message sessionId=${e.sessionId} contentLen=${o.content.length} preview="${previewFilteredText(o.content)}"`);else{if("assistant"===o.role){const t=classifyHeartbeatFilter(o.content);if(t.filtered){this.logger.info?.(`[bridge-core] SKIP history_turn[${n}] heartbeat assistant reply reason=${t.reason} sessionId=${e.sessionId} contentLen=${o.content.length} preview="${previewFilteredText(o.content)}"`);continue}}if("system"!==o.role)if(this.logger.debug?.(`[bridge-core] SENDING history_turn[${n}] role=${o.role} contentLen=${o.content.length} content=${JSON.stringify(o.content.slice(0,80))} tcCount=${o.toolCalls?.length??0}`),"user"===o.role)this.replayUserTurnAsChunks(s,o.content,o.metadata,o.timestamp,g(n),o._seq);else{if(await this.replayAssistantTurnAsStream(s,o,g(n)),o.toolCalls)for(const e of o.toolCalls)e.id&&t.add(e.id);this.transport.sendSessionUpdate(s,{sessionUpdate:"stream_complete",stopReason:"end_turn"},{turnId:g(n)}),p+=1}else this.logger.debug?.(`[bridge-core] SENDING system_message[${n}] contentLen=${o.content.length}`),this.transport.sendSessionUpdate(s,{sessionUpdate:"system_message_chunk",content:{type:"text",text:o.content},metadata:o.metadata,...o.timestamp?{timestamp:o.timestamp}:{}},{turnId:g(n),...void 0!==o._seq?{seq:o._seq}:{}})}else this.logger.debug?.(`[bridge-core] SKIP history_turn[${n}] internal_system user message`)}this.logger.debug?.(`[bridge-core] emitHistoryTurns DONE sid=${s} historyStreamCompleteEmitted=${p} replayedToolCallIds=${t.size}`)}catch(e){this.logger.warn?.("[bridge-core] Failed to load session history:",e)}return t}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],o=n.sessionUpdate,r=n.toolCallId;if("tool_call"!==o&&"tool_call_update"!==o||!r||!t.has(r)){if("agent_message_chunk"===o){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 o=resolveTurnId(e),r=o?{turnId:o}:void 0;for(let t=i;t<s.length;t++)this.transport.sendSessionUpdate(e.sessionId,s[t],r)}}async handleSessionList(e){const t=[];for(const[,e]of this.state.sessions)isBackgroundSessionKey(e.gatewaySessionKey)||this.cronIsolatedSessionKeys.has(e.gatewaySessionKey)||t.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 s=this.getGateway();if(s?.isConnected)try{const e=await s.sessionsList();if(e&&"object"==typeof e&&Array.isArray(e.sessions)){const s=e.sessions;for(const e of s){const s=e,n=s.sessionKey??s.key??s.id??s.name;if(!n||"string"!=typeof n)continue;if(isBackgroundSessionKey(n))continue;if(this.cronIsolatedSessionKeys.has(n))continue;const i=deriveSessionId(n,this.instanceId),o=t.find(e=>e.sessionId===n||e.sessionId===i||this.state.sessions.get(e.sessionId)?.gatewaySessionKey===n),r=s.label||cleanGatewayDerivedTitle(s.derivedTitle)||s.title||void 0,a=r&&!isPlaceholderTitle(r)?r:void 0,l=s.model,d=s.modelProvider;if(o){if(a&&isPlaceholderTitle(o.title)){o.title=a;const e=this.state.sessions.get(o.sessionId);e&&isPlaceholderTitle(e.title)&&(e.title=a)}const e=s.updatedAt;e&&(o.updatedAt=e),l&&(o.model=l),d&&(o.modelProvider=d)}else{const e=createSessionObject({gatewayKey:n,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,cwd:s.cwd,title:a});this.registerSession(e,{ensureVerbose:!1}),t.push({sessionId:e.sessionId,title:a||"",cwd:s.cwd,updatedAt:s.updatedAt,agentId:e.agentId,platformAgentId:e.platformAgentId,deletable:!isSystemDefaultSessionKey(n),model:l,modelProvider:d})}}}}catch(e){this.logger.debug?.("[bridge-core] sessions.list enrichment failed:",e)}t.sort((e,t)=>(t.updatedAt??0)-(e.updatedAt??0)||e.sessionId.localeCompare(t.sessionId)),this.transport.sendResult(e.id,{sessions:t})}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)return void this.transport.sendAcpError(e.id,Errors.SessionNotFound);i.title=n,i.titleSource="manual";const o=i.gatewaySessionKey,r=this.getGateway();r?.isConnected&&r.sessionsPatch(o,{label:n}).catch(e=>{this.logger.debug?.(`[bridge-core] sessionsPatch (rename) failed: ${e instanceof Error?e.message:e}`)}),this.transport.sendResult(e.id,{sessionId:t,title:n})}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"},{match:["新会话","new chat","new conversation"],zh:"新会话",en:"New Conversation"}];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 (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.\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- If both the question and answer are too vague to summarize, return "新会话" (for zh) or "New Conversation" (for en).\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]\nhi\n\n[Assistant Answer]\nHello! How can I help you today?\nOutput: {"title": "New Conversation"}';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 o=(process.env.AROUTER_BASE_URL||"").replace(/\/$/,""),r=process.env.AROUTER_API_KEY||"";if(!o||!r)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(`${o}/v1/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},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 o=i.replace(/^```json\s*/,"").replace(/```$/,"").trim();let r;try{r=JSON.parse(o).title?.trim()??""}catch{return void this.logger.debug?.(`[bridge-core] title-gen JSON parse failed: ${o}`)}if(!r)return;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="${r}"`),e.title=r,e.titleSource="auto";const a=this.getGateway();a?.isConnected&&a.sessionsPatch(e.gatewaySessionKey,{label:r}).catch(()=>{}),this.transport.sendSessionUpdate(t,{sessionUpdate:"title_update",title:r})}).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 o=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=stripTransportMetadata(e.content).trim();return!!t&&!/^Sender\s*\(untrusted/i.test(t)});if(!o)return;const r=i.indexOf(o),a=i.slice(r+1).find(e=>"assistant"===e.role&&!!e.content?.trim());if(!a)return;const l=stripTransportMetadata(o.content).trim(),d=a.content.trim();l&&d&&this.generateTitleFromQA(e,t,l,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;this.logger.info?.(`[bridge-core] session/delete sessionId=${t} gatewayKey=${n} gwConnected=${!!this.getGateway()?.isConnected}`);let i=!1;const o=this.getGateway();if(o?.isConnected&&n)try{await o.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 o.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}`);void 0!==s.pendingPromptId&&this.failPrompt(s,Errors.SessionDeleted.rpcCode,Errors.SessionDeleted.message),this.state.clearPromptTimeout(s),this.state.clearStreamIdleTimer(s),s.assistantMq?.close(),s.assistantMq=void 0,s.currentRunId&&this.state.promptsByRunId.delete(s.currentRunId);const r=new Set;for(const[e,s]of this.state.toolCallToSessionMap)s===t&&(this.state.toolCallToSessionMap.delete(e),r.add(e));for(const[e,t]of this.state.toolCallIdMap)r.has(t)&&this.state.toolCallIdMap.delete(e);this.state.sessions.delete(t),this.state.sessionsByGatewayKey.delete(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})}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}`),i&&(s.currentRunId||s.gatewayRequestId)&&n.agentCancel(s.gatewaySessionKey,{runId:s.currentRunId,requestId:s.gatewayRequestId}),this.endRun(s,{kind:"complete",stopReason:"cancelled"})),i&&s.gatewaySessionKey)try{await n.sessionsReset(s.gatewaySessionKey),this.logger.info?.(`[bridge-core] Gateway sessions.reset SUCCESS for key=${s.gatewaySessionKey}`)}catch(e){this.logger.warn?.(`[bridge-core] Gateway sessions.reset FAILED for key=${s.gatewaySessionKey}: ${e instanceof Error?e.message:e}`)}else this.logger.warn?.(`[bridge-core] session/clear skipped gateway reset: connected=${i}, key=${s.gatewaySessionKey}`);s.chatReplayDedupKeys.clear(),this.logger.info?.("[bridge-core] session/clear dedupKeys cleared, calling onSessionCleared"),this.onSessionCleared?.(t,s.gatewaySessionKey),this.transport.sendResult(e.id,{cleared:!0}),this.logger.info?.("[bridge-core] session/clear DONE, sent cleared=true")}async handleSessionSetMode(e){const t=e.params?.sessionId,s=e.params?.mode,n=t?this.state.sessions.get(t):void 0,i=this.getGateway();if(n&&i?.isConnected&&s){const e={};if("verbose"===s||"detailed"===s?e.verboseLevel="full":"concise"!==s&&"default"!==s||(e.verboseLevel="default"),"reasoning"!==s&&"thinking"!==s||(e.reasoningLevel="stream"),Object.keys(e).length>0)try{await i.sessionsPatch(n.gatewaySessionKey,e)}catch(e){this.logger.warn?.(`[bridge-core] sessions.patch failed: ${e instanceof Error?e.message:e}`)}}this.transport.sendResult(e.id,{mode:s??"default"})}async handleSessionSetModel(e){const t=e.params?.sessionId,s=e.params?.model,n=t?this.state.sessions.get(t):void 0,i=this.getGateway();let o=s??null,r=null;if(n&&i?.isConnected&&s)try{const e=await i.sessionsPatch(n.gatewaySessionKey,{model:s}),t=e?.resolved;t?.model&&(o=t.model),t?.modelProvider&&(r=t.modelProvider)}catch(e){this.logger.warn?.(`[bridge-core] sessions.patch for model failed: ${e instanceof Error?e.message:e}`)}this.transport.sendResult(e.id,{model:o,modelProvider:r})}async handleModelsList(e){const t=this.getGateway();if(t?.isConnected)try{const s=await t.request("models.list",{});this.transport.sendResult(e.id,s??{models:[]})}catch(t){this.transport.sendAcpError(e.id,Errors.InternalError,{message:`Failed to list models: ${t instanceof Error?t.message:t}`})}else this.transport.sendAcpError(e.id,Errors.GatewayNotConnected)}async handleSkillsList(e){const t=await this.fetchSimplifiedSkills();this.transport.sendResult(e.id,{skills:t})}async fetchSimplifiedSkills(){const e=this.getGateway();if(!e?.isConnected)return[];try{const t=await e.skillsStatus();if(!t?.skills)return[];const s=t.skills.filter(e=>!1!==e.eligible||!0===e.disabled).sort((e,t)=>e.always&&!t.always?-1:!e.always&&t.always?1:e.name.localeCompare(t.name)).map(e=>({name:e.name,description:e.description,emoji:e.emoji,always:e.always||void 0,bundled:e.bundled||void 0,disabled:e.disabled||void 0,skillKey:e.skillKey||void 0,iconUrl:void 0})),n=this.getSkillsDir();for(const e of s){const t=e.skillKey??e.name;try{const s=await readFile(join(n,t,".beeos-meta.json"),"utf8"),i=JSON.parse(s);i?.iconUrl&&(e.iconUrl=i.iconUrl)}catch{}}return s}catch(e){return this.logger.warn?.(`[bridge-core] Failed to fetch skills: ${e instanceof Error?e.message:e}`),[]}}async pushSkillsList(){const e=await this.fetchSimplifiedSkills();this.transport.sendNotification("session/update",{sessionId:"_system",update:{sessionUpdate:"available_commands_update",commands:e}}),this.writeObs({component:"bridge-core",domain:"lifecycle",name:"skills.pushed",severity:"debug",payload:{count:e.length}})}getSkillsDir(){const e=process.env.OPENCLAW_HOME||join(homedir(),".openclaw");return join(e,"skills")}async handleSkillsInstall(e){const t=e.params,s=t?.zipUrl,n=t?.files;let i;try{i=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)return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Missing skill files or zipUrl"});const o=resolveSkillInstallDir(this.getSkillsDir(),i);try{if(await mkdir(o,{recursive:!0}),s){const e=await fetchWithRetry(s,{maxRetries:4,logger:this.logger});await extractZipToDir(e,o)}else if(n?.length){const e=resolve(o);for(const t of n){const s=join(o,t.path);if(!resolve(s).startsWith(e+sep))throw new Error(`File path escapes skill directory: ${t.path}`);await mkdir(join(s,".."),{recursive:!0});const n=await fetch(t.downloadUrl,{signal:AbortSignal.timeout(12e4)});if(!n.ok)throw new Error(`Failed to download ${t.path}: ${n.status}`);const i=Buffer.from(await n.arrayBuffer());await writeFile(s,i)}}if(t?.iconUrl)try{await writeFile(join(o,".beeos-meta.json"),JSON.stringify({iconUrl:t.iconUrl}),"utf8")}catch{}this.logger.info?.(`[bridge-core] Installed skill "${i}" via ${s?"zip":"files"}`),this.transport.sendResult(e.id,{success:!0}),this.onSkillInstalled?.(i,o),await this.pushSkillsList()}catch(t){this.logger.error?.(`[bridge-core] Failed to install skill "${i}": ${t instanceof Error?t.message:t}`),this.transport.sendAcpError(e.id,Errors.InternalError,{message:`Install failed: ${t instanceof Error?t.message:String(t)}`})}}async handleSkillsUninstall(e){const t=e.params;let s;try{s=validateSkillSlug(t?.slug||t?.name||"")}catch{return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Invalid or missing skill name"})}const n=resolveSkillInstallDir(this.getSkillsDir(),s),i=resolveSkillInstallDir(join(homedir(),".agents","skills"),s);try{let t=!1;try{const e=await lstat(n);if(e.isSymbolicLink()){const e=await readlink(n);await rm(n,{force:!0}),await rm(e,{recursive:!0,force:!0}),t=!0}else e.isDirectory()&&(await rm(n,{recursive:!0,force:!0}),t=!0)}catch{}try{const e=await lstat(i);(e.isDirectory()||e.isSymbolicLink())&&(await rm(i,{recursive:!0,force:!0}),t=!0)}catch{}t||this.logger.warn?.(`[bridge-core] Skill "${s}" not found in any known location`),this.logger.info?.(`[bridge-core] Uninstalled skill "${s}"`),this.transport.sendResult(e.id,{success:!0}),await this.pushSkillsList()}catch(t){this.logger.error?.(`[bridge-core] Failed to uninstall skill "${s}": ${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;if(!s||"boolean"!=typeof n)return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Missing skillKey or enabled"});const i=this.getGateway();if(i?.isConnected)try{const t=await i.skillsUpdate(s,n);this.logger.info?.(`[bridge-core] Updated skill "${s}" enabled=${n}`),this.transport.sendResult(e.id,{ok:t?.ok??!0,skillKey:s,enabled:n}),await this.pushSkillsList()}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.InternalError,{message:"Gateway not connected"})}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 o=n.sessionId;this.state.lastActiveSessionId=o,this.onPromptStart?.();const r=this.getGateway();if(!r?.isConnected)return void this.transport.sendAcpError(e.id,Errors.GatewayNotConnected);await this.ensureVerboseFull(n);let a=extractPromptBlocks(sanitizePromptPayload(s));if(!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=${o} 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",r?.isConnected&&e&&r.sessionsPatch(n.gatewaySessionKey,{label:e}).catch(e=>{this.logger.debug?.(`[bridge-core] sessionsPatch (title) failed: ${e instanceof Error?e.message:e}`)}),this.transport.sendSessionUpdate(o,{sessionUpdate:"title_update",title:e})}}}const l=buildResolutionPlan(a);if(l.refs.length>0)try{const e=await resolveResources(l,this.writeObs);a=applyResolutions(a,e)}catch(e){this.logger.warn?.(`[bridge-core] Resource pre-resolution failed: ${e instanceof Error?e.message:e}`)}let d;if(this.beeosFileResolver){const e=this.beeosFileResolver.buildResolutionPlan(a);if(e.refs.length>0)try{d=await this.beeosFileResolver.resolveMetadataForPrompt(e)}catch(e){this.logger.warn?.(`[bridge-core] BeeOS file resolution failed: ${e instanceof Error?e.message:e}`)}}const c=toGatewayPrompt(a,{beeosFileResolutionsByUri:d});if("error"in c)return void this.transport.sendAcpError(e.id,Errors.PromptConvertFailed,{message:c.error});const{message:h,attachments:g}=c,p=resolveStandaloneSlashCommandName(a,h)??resolveSlashCmd(a,h),m="string"==typeof p;if(p&&this.handleSlashCommand){const t=this;if(await(async()=>{try{return await t.handleSlashCommand(p)}catch(e){return t.logger.warn?.(`[bridge-core] /${p} handler failed: ${e instanceof Error?e.message:e}`),!1}})())return this.emitPromptAsUserSessionUpdates(n,a,resolveTurnId(n)),this.transport.sendSessionUpdate(o,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Loading ${p}...`},timestamp:(new Date).toISOString()},{turnId:resolveTurnId(n)}),void this.transport.sendResult(e.id,{stopReason:"end_turn"})}const u="chat.send";let f=m?h:withUserMessagePrefix(h);const y=this.config.canvasEnabled&&!m&&!1!==n.canvasActive&&!n.channelType;if(y){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(y){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(!m){const t=parseMentionsParam(e.params?.mentions);if(t.length>0){n.activeMentions=t;f=`${buildMentionInstruction(t)}\n${f}`,this.logger.debug?.(`[bridge-core] A2A mention instruction injected for ${t.length} agent(s)`)}else n.activeMentions=void 0}m&&this.logger.info?.(`[bridge-core] slash command passthrough sessionId=${o} command=/${p}`),n.promptDone||void 0===n.pendingPromptId&&void 0===n.currentRunId||(this.logger.warn?.(`[bridge-core] handleSessionPrompt: force-ending stale run sid=${o} oldRunId=${n.currentRunId} oldPromptId=${n.pendingPromptId}`),(n.currentRunId||n.gatewayRequestId)&&r.agentCancel(n.gatewaySessionKey,{runId:n.currentRunId,requestId:n.gatewayRequestId}),this.endRun(n,{kind:"complete",stopReason:"cancelled"})),this.state.resetForNewRun(n,o,this.transport),n.pendingPromptId=e.id,n.gatewayMethod=u;const S=resolveTurnId(n);this.emitPromptAsUserSessionUpdates(n,a,S),this.transport.sendSessionUpdate(o,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:""},timestamp:(new Date).toISOString()},S?{turnId:S}:void 0);const w=extractCronJobId(h);w&&(n.cronJobId=w),this.schedulePromptTimeout(n);const I=g.length>0?g.map(e=>({type:e.type,content:e.content,...e.mimeType?{mimeType:e.mimeType}:{},...e.fileName?{fileName:e.fileName}:{}})):void 0,v=`req_${randomUUID().replace(/-/g,"")}`,b={sessionKey:n.gatewaySessionKey,message:f,deliver:!1,idempotencyKey:randomUUID()};I?.length&&(b.attachments=I);if(!r.sendFrame({type:"req",id:v,method:u,params:b}))return this.state.clearPromptTimeout(n),n.pendingPromptId=void 0,n.assistantMq?.close(),n.assistantMq=void 0,n.pendingUserTurnUpdates=void 0,void this.transport.sendAcpError(e.id,Errors.SendFailed,{message:"failed to send prompt to gateway"});n.gatewayRequestId=v,this.state.promptsByGatewayRequestId.set(v,n)}replayUserTurnAsChunks(e,t,s,n,i,o){const r=splitUserReplayBlocks(t),a=i||void 0!==o?{...i?{turnId:i}:{},...void 0!==o?{seq:o}:{}}:void 0;for(const t of r){let i;if("text"===t.type){if(!t.text)continue;i={type:"text",text:t.text}}else i="resource_link"===t.type?{type:"resource_link",uri:t.uri??"",...t.fileName?{name:t.fileName}:{},...t.mimeType?{mimeType:t.mimeType}:{}}:{type:t.type,...t.mimeType?{mimeType:t.mimeType}:{},...t.fileName?{fileName:t.fileName}:{}};this.transport.sendSessionUpdate(e,{sessionUpdate:"user_message_chunk",content:i,...s?{metadata:s}:{},...n?{timestamp:n}:{}},a)}}async replayAssistantTurnAsStream(e,t,s){const n=e=>{if(s||void 0!==e)return{...s?{turnId:s}:{},...void 0!==e?{seq:e}:{}}},i=n(t._seq);if(!t.sourceMessages?.length){const s={sessionUpdate:"history_turn",role:t.role,content:t.content,reasoning:t.reasoning,toolCalls:t.toolCalls,...t.timestamp?{timestamp:t.timestamp}:{}};return t.metadata&&(s.metadata=t.metadata),void this.transport.sendSessionUpdate(e,s,i)}for(const s of t.sourceMessages){const i=s.updateType??"agent_message_chunk",o=n(s._seq);switch(i){case"agent_message_chunk":this.transport.sendSessionUpdate(e,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:s.content},...s.timestamp?{timestamp:s.timestamp}:{},...s.metadata?{metadata:s.metadata}:{}},o);break;case"agent_thought_chunk":this.transport.sendSessionUpdate(e,{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:s.content},...s.timestamp?{timestamp:s.timestamp}:{}},o);break;case"tool_call":{const n=s.toolCallId??"",i=t.toolCalls?.find(e=>e.id===n),r=s.toolName??"tool",a=s.content??"";let l={};if(a)try{l=JSON.parse(a)}catch{}this.transport.sendSessionUpdate(e,buildToolCallPayload({toolCallId:n,toolName:r,args:l,kind:i?.kind,status:i?.status??"in_progress",timestamp:s.timestamp}),o);break}case"tool_call_update":{const n=s.toolCallId??"",i=t.toolCalls?.find(e=>e.id===n),r=s.toolName??i?.name??"tool",a=s.content??i?.output??"";let l=await readEnrichmentCache(n).catch(()=>{});if(!l){const e=extractBeeosFileUrisFromOutput(a);e.length>0&&(l=e.map(e=>({uri:e,name:"file"})))}if(!l&&"beeos_upload_file"===r){const e=await readUploadToolResult(n).catch(()=>{});if(e){const t=buildToolResultSessionContentBlocks(r,e).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}:{}}));t.length>0&&(l=t)}}this.transport.sendSessionUpdate(e,buildToolCallUpdatePayload({toolCallId:n,toolName:r,outputText:a,kind:i?.kind,status:i?.status??"completed",resourceLinks:l,timestamp:s.timestamp}),o);break}}}}emitPromptAsUserSessionUpdates(e,t,s){const n=(new Date).toISOString(),i=s?{turnId:s}:void 0;for(const o of t){const t=this.toUserSessionUpdateContent(o);if(!t)continue;const r={sessionUpdate:"user_message_chunk",content:t,timestamp:n};s&&void 0===r._turnId&&(r._turnId=s),this.transport.sendSessionUpdate(e.sessionId,r,i),e.pendingUserTurnUpdates?.push(r)}}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,o=t.data??e.data,r=t.fileName??t.file_name??t.filename??t.name??e.fileName??e.file_name??e.filename??e.name;if(!s&&!i&&!o)return;return{type:"resource",resource:{...s?{uri:s}:{},...n?{mimeType:n}:{},...i?{text:i}:{},...o?{data:o}:{},...r?{fileName:r}:{}}}}}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=this.getGateway(),o=i?.isConnected,r=!(!n.currentRunId&&!n.gatewayRequestId);if(o&&r){i.agentCancel(n.gatewaySessionKey,{runId:n.currentRunId,requestId:n.gatewayRequestId})}this.endRun(n,{kind:"complete",stopReason:"cancelled"})||this.transport.sendSessionUpdate(n.sessionId,{sessionUpdate:"stream_complete",stopReason:"cancelled"},{turnId:resolveTurnId(n)}),void 0!==e&&this.transport.sendResult(e,{})}endRun(e,t){if(e.promptDone)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)return this.logger.debug?.(`[bridge-core] endRun skipped (no pendingPromptId and no currentRunId) sessionId=${e.sessionId} outcome=${t.kind}`),!1;const s=resolveTurnId(e),n=s?{turnId:s}:void 0;e.promptDone=!0;const i=e.currentRunId;if("complete"===t.kind){if(i&&this.onRunComplete){const t=e.agentAssistantTextSoFar??e.chatAssistantTextSoFar??"";this.onRunComplete(i,t)}void 0!==e.pendingPromptId&&this.transport.sendResult(e.pendingPromptId,{stopReason:t.stopReason}),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:t.stopReason},n),this.tryGenerateTitleFromHistory(e,e.sessionId)}else i&&this.onRunFailed&&this.onRunFailed(i,t.message),void 0!==e.pendingPromptId&&this.transport.sendError(e.pendingPromptId,t.code,t.message),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:"error",error:t.message},n);return this.cleanupPrompt(e),this.onRunEnded?.(e,t),!0}schedulePromptTimeout(e){let t;if(this.state.clearPromptTimeout(e),e.cronJobId){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(()=>{void 0!==e.pendingPromptId&&((e.currentRunId||e.gatewayRequestId)&&this.getGateway()?.agentCancel(e.gatewaySessionKey,{runId:e.currentRunId,requestId:e.gatewayRequestId}),this.logger.warn?.(`[bridge-core] Prompt timed out sessionId=${e.sessionId} after ${t}ms`),this.failPrompt(e,Errors.PromptTimeout.rpcCode,`Prompt timed out after ${t}ms`))},t),"object"==typeof e.promptTimeoutTimer&&"unref"in e.promptTimeoutTimer&&e.promptTimeoutTimer.unref())}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.assistantMq?.close(),e.assistantMq=void 0,e.pendingUserTurnUpdates=void 0}completePrompt(e,t){this.endRun(e,{kind:"complete",stopReason:t})}failPrompt(e,t,s){this.endRun(e,{kind:"error",code:t,message:s})}cleanupAllPendingPrompts(){for(const e of this.state.sessions.values())this.failPrompt(e,Errors.GatewayDisconnected.rpcCode,Errors.GatewayDisconnected.message)}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";return this.logger.warn?.(`[bridge-core] handleGatewayResponse: gateway rejected prompt gatewayRequestId=${t} error=${i}`),void this.failPrompt(s,Errors.SendFailed.rpcCode,i)}const n=e.payload,i=n?.runId;i?(s.currentRunId=i,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)this.completePrompt(e,"end_turn");else if("aborted"===s||"cancelled"===s||"cancel"===s)this.completePrompt(e,"cancelled");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";this.failPrompt(e,Errors.AgentError.rpcCode,formatFriendlyError(s))}}pushToolResultContent(e,t,s,n){if(0===s.length)return;const i=n?this.state.promptsByRunId.get(n):void 0;if(!i)return void this.logger.warn?.(`[bridge-core] pushToolResultContent dropped — no session for runId=${n??"(none)"}`);const o=i.sessionId,r=(new Date).toISOString(),a={turnId:resolveTurnId(i)};for(const e of s){const t=narrowContentBlock(e);if(!t)continue;const s={sessionUpdate:"agent_message_chunk",content:t,timestamp:r};this.transport.sendSessionUpdate(o,s,a),i.assistantMq?.push(s)}this.writeObs({component:"bridge-core",domain:"tool",name:"tool_result.direct_push",severity:"info",payload:{toolCallId:e,toolName:t,blockCount:s.length,sessionId:o}})}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??{}},i=n._beeos_meta;if(delete n._beeos_meta,"cron.add"!==s&&"cron.update"!==s||!0!==n._beeos_internal)void 0!==n._beeos_internal&&delete n._beeos_internal;else{delete n._beeos_internal,n.delivery={mode:"none"};const e=await this.allocateCronChannel(n.name??"cron");e&&(n.description=encodeBeeosChannelTag(n.description,e))}try{const o=await t.request(s,n);if(this.transport.sendResult(e.id,o??{}),("cron.add"===s||"cron.update"===s)&&o&&"object"==typeof o){const e=o.id;if(e&&void 0!==i?.maxDurationMs){const t=Math.max(CRON_DURATION_FLOOR_MS,Math.min(this.config.cronMaxDurationCapMs,i.maxDurationMs));this.cronOverrides.set(e,t)}}if("cron.remove"===s){const t=e.params?.id;t&&this.cronOverrides.delete(t)}if(("cron.add"===s||"cron.update"===s)&&o&&"object"==typeof o){const e=o.id,t=decodeBeeosChannelId(n.description);e&&t&&this.setCronChannelCache(e,t)}"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 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,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 o=await fetch(e,{signal:AbortSignal.timeout(12e4),redirect:"follow"});if(o.ok)return Buffer.from(await o.arrayBuffer());if(429===o.status||o.status>=500){const r=Number(o.headers.get("retry-after"))||0,a=1e3*Math.max(r,2**i);if(n=new Error(`HTTP ${o.status} from ${e}`),i<s){t.logger?.info?.(`[bridge-core] Download ${o.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: ${o.status}`)}throw n??new Error("Download failed after retries")}const SKILL_ROOT_MARKERS=["SKILL.md","skill.md","SKILL.MD"];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 o=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})}),o++}if(0===o)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 resolveSkillInstallDir(e,t){const s=safeDirName(t),n=join(e,s),i=resolve(e),o=resolve(n),r=relative(i,o);if(!r||".."===r||r.startsWith(`..${sep}`)||path.isAbsolute(r))throw new Error("Invalid skill target path");return n}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describe,it,expect,vi}from"vitest";import{AcpGatewayEvents,isChannelGoneError}from"./gateway-events.js";import{AcpGatewaySessionState}from"./session-state.js";function makeHarness(){const e={info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()},n=new AcpGatewaySessionState(e),a={sendSessionUpdate:vi.fn().mockReturnValue(!0),sendResult:vi.fn(),sendAcpError:vi.fn(),sendNotification:vi.fn(),resetSessionUpdateCount:vi.fn(),setSessionUpdateObserver:vi.fn(),isReady:()=>!0,get forwardControl(){return{forwardThinking:!0,forwardToolCalls:!0}}},t=vi.fn(),s=new Map;return{events:new AcpGatewayEvents({state:n,transport:a,config:{gateway:{agentId:"main"}},logger:e,writeObs:vi.fn(),completePrompt:vi.fn(),failPrompt:vi.fn(),maybeCompletePromptFromChatState:vi.fn(),gatewayRequest:t,cronChannelCache:s}),state:n,gatewayRequest:t,cronChannelCache:s,logger:e}}function installSession(e,n,a){const t={sessionId:`sid-${n}`,gatewaySessionKey:n,agentId:"main",createdAt:Date.now(),chatReplayDedupKeys:new Set,channelId:a};e.sessions.set(t.sessionId,t),e.sessionsByGatewayKey.set(n,t)}describe("isChannelGoneError",()=>{it("returns true for 'not found' text",()=>{expect(isChannelGoneError(new Error("channel not found"),"channel not found")).toBe(!0)}),it("returns true for 'no such channel' / 'channel does not exist'",()=>{expect(isChannelGoneError(new Error("no such channel"),"no such channel")).toBe(!0),expect(isChannelGoneError(new Error("channel does not exist"),"channel does not exist")).toBe(!0)}),it("returns true for HTTP 404 / 410 in message",()=>{expect(isChannelGoneError(new Error("HTTP 404"),"HTTP 404")).toBe(!0),expect(isChannelGoneError(new Error("status 410"),"status 410")).toBe(!0)}),it("returns true when err carries a status=404 or 410 field",()=>{const e=Object.assign(new Error("nope"),{status:404}),n=Object.assign(new Error("nope"),{statusCode:410});expect(isChannelGoneError(e,"nope")).toBe(!0),expect(isChannelGoneError(n,"nope")).toBe(!0)}),it("returns false for unrelated errors",()=>{expect(isChannelGoneError(new Error("ECONNRESET"),"ECONNRESET")).toBe(!1),expect(isChannelGoneError(new Error("timeout"),"timeout")).toBe(!1),expect(isChannelGoneError(new Error("500 server error"),"500 server error")).toBe(!1)})}),describe("maybeBackfillBeeosChannel",()=>{it("short-circuits when cronChannelCache already holds the jobId",async()=>{const e=makeHarness();e.cronChannelCache.set("job-1","chan-cached"),await e.events.maybeBackfillBeeosChannel({jobId:"job-1",action:"added"}),expect(e.gatewayRequest).not.toHaveBeenCalled()}),it("skips and backfills cache when description already has the beeos tag",async()=>{const e=makeHarness();e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"job-2",description:"Daily backup\n\x3c!-- beeos:channel=chan-existing --\x3e",sessionKey:"agent:main:main",sessionTarget:"session:agent:main:main",payload:{kind:"agentTurn"}}]}),await e.events.maybeBackfillBeeosChannel({jobId:"job-2",action:"added"}),expect(e.gatewayRequest).toHaveBeenCalledTimes(1),expect(e.gatewayRequest).toHaveBeenCalledWith("cron.list",{}),expect(e.cronChannelCache.get("job-2")).toBe("chan-existing")}),it("skips when sessionTarget === 'main'",async()=>{const e=makeHarness();installSession(e.state,"agent:main:main","chan-origin"),e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"job-3",description:"",sessionKey:"agent:main:main",sessionTarget:"main",payload:{kind:"agentTurn"}}]}),await e.events.maybeBackfillBeeosChannel({jobId:"job-3",action:"added"}),expect(e.gatewayRequest).toHaveBeenCalledTimes(1),expect(e.cronChannelCache.has("job-3")).toBe(!1)}),it("skips when payload.kind === 'systemEvent'",async()=>{const e=makeHarness();installSession(e.state,"agent:main:main","chan-origin"),e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"job-4",description:"",sessionKey:"agent:main:main",sessionTarget:"session:agent:main:main",payload:{kind:"systemEvent",text:"heartbeat"}}]}),await e.events.maybeBackfillBeeosChannel({jobId:"job-4",action:"added"}),expect(e.gatewayRequest).toHaveBeenCalledTimes(1),expect(e.cronChannelCache.has("job-4")).toBe(!1)}),it("skips when delivery.mode === 'none' (explicit opt-out)",async()=>{const e=makeHarness();installSession(e.state,"agent:main:main","chan-origin"),e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"job-5",description:"Silent backup",sessionKey:"agent:main:main",sessionTarget:"session:agent:main:main",payload:{kind:"agentTurn"},delivery:{mode:"none"}}]}),await e.events.maybeBackfillBeeosChannel({jobId:"job-5",action:"added"}),expect(e.gatewayRequest).toHaveBeenCalledTimes(1),expect(e.cronChannelCache.has("job-5")).toBe(!1)}),it("skips when job has no sessionKey",async()=>{const e=makeHarness();e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"job-6",description:"",sessionTarget:"session:agent:main:main",payload:{kind:"agentTurn"}}]}),await e.events.maybeBackfillBeeosChannel({jobId:"job-6",action:"added"}),expect(e.gatewayRequest).toHaveBeenCalledTimes(1),expect(e.cronChannelCache.has("job-6")).toBe(!1)}),it("skips when ACPSession has no channelId",async()=>{const e=makeHarness();installSession(e.state,"agent:main:main",void 0),e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"job-7",description:"",sessionKey:"agent:main:main",sessionTarget:"session:agent:main:main",payload:{kind:"agentTurn"}}]}),await e.events.maybeBackfillBeeosChannel({jobId:"job-7",action:"added"}),expect(e.gatewayRequest).toHaveBeenCalledTimes(1),expect(e.cronChannelCache.has("job-7")).toBe(!1)}),it("happy path: emits cron.update with beeos tag and populates cache",async()=>{const e=makeHarness();installSession(e.state,"agent:main:main","chan-origin"),e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"job-8",description:"Remind me to pee",sessionKey:"agent:main:main",sessionTarget:"session:agent:main:main",payload:{kind:"agentTurn"},delivery:{mode:"announce",channel:"last"}}]}).mockResolvedValueOnce({ok:!0}),await e.events.maybeBackfillBeeosChannel({jobId:"job-8",action:"added"}),expect(e.gatewayRequest).toHaveBeenCalledTimes(2),expect(e.gatewayRequest).toHaveBeenNthCalledWith(1,"cron.list",{});const[n,a]=e.gatewayRequest.mock.calls[1];expect(n).toBe("cron.update"),expect(a.id).toBe("job-8"),expect(a.patch.description).toBe("Remind me to pee\n\x3c!-- beeos:channel=chan-origin --\x3e"),expect(e.cronChannelCache.get("job-8")).toBe("chan-origin")}),it("gracefully degrades (warn) when cron.update rejects",async()=>{const e=makeHarness();installSession(e.state,"agent:main:main","chan-origin"),e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"job-9",description:"Reminder",sessionKey:"agent:main:main",sessionTarget:"session:agent:main:main",payload:{kind:"agentTurn"}}]}).mockRejectedValueOnce(new Error("boom")),await expect(e.events.maybeBackfillBeeosChannel({jobId:"job-9",action:"added"})).resolves.toBeUndefined(),expect(e.logger.warn).toHaveBeenCalledWith(expect.stringContaining("maybeBackfillBeeosChannel cron.update failed")),expect(e.cronChannelCache.has("job-9")).toBe(!1)})});
|
|
1
|
+
import{describe,it,expect,vi}from"vitest";import{AcpGatewayEvents,isChannelGoneError}from"./gateway-events.js";import{AcpGatewaySessionState}from"./session-state.js";function makeHarness(){const e={info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()},n=new AcpGatewaySessionState(e),a={sendSessionUpdate:vi.fn().mockReturnValue(!0),sendResult:vi.fn(),sendAcpError:vi.fn(),sendNotification:vi.fn(),resetSessionUpdateCount:vi.fn(),setSessionUpdateObserver:vi.fn(),isReady:()=>!0,get forwardControl(){return{forwardThinking:!0,forwardToolCalls:!0}}},t=vi.fn(),s=new Map;return{events:new AcpGatewayEvents({state:n,transport:a,config:{gateway:{agentId:"main"}},logger:e,writeObs:vi.fn(),completePrompt:vi.fn(),failPrompt:vi.fn(),schedulePromptTimeout:vi.fn(),maybeCompletePromptFromChatState:vi.fn(),gatewayRequest:t,cronChannelCache:s}),state:n,gatewayRequest:t,cronChannelCache:s,logger:e}}function installSession(e,n,a){const t={sessionId:`sid-${n}`,gatewaySessionKey:n,agentId:"main",createdAt:Date.now(),chatReplayDedupKeys:new Set,channelId:a};e.sessions.set(t.sessionId,t),e.sessionsByGatewayKey.set(n,t)}describe("isChannelGoneError",()=>{it("returns true for 'not found' text",()=>{expect(isChannelGoneError(new Error("channel not found"),"channel not found")).toBe(!0)}),it("returns true for 'no such channel' / 'channel does not exist'",()=>{expect(isChannelGoneError(new Error("no such channel"),"no such channel")).toBe(!0),expect(isChannelGoneError(new Error("channel does not exist"),"channel does not exist")).toBe(!0)}),it("returns true for HTTP 404 / 410 in message",()=>{expect(isChannelGoneError(new Error("HTTP 404"),"HTTP 404")).toBe(!0),expect(isChannelGoneError(new Error("status 410"),"status 410")).toBe(!0)}),it("returns true when err carries a status=404 or 410 field",()=>{const e=Object.assign(new Error("nope"),{status:404}),n=Object.assign(new Error("nope"),{statusCode:410});expect(isChannelGoneError(e,"nope")).toBe(!0),expect(isChannelGoneError(n,"nope")).toBe(!0)}),it("returns false for unrelated errors",()=>{expect(isChannelGoneError(new Error("ECONNRESET"),"ECONNRESET")).toBe(!1),expect(isChannelGoneError(new Error("timeout"),"timeout")).toBe(!1),expect(isChannelGoneError(new Error("500 server error"),"500 server error")).toBe(!1)})}),describe("maybeBackfillBeeosChannel",()=>{it("short-circuits when cronChannelCache already holds the jobId",async()=>{const e=makeHarness();e.cronChannelCache.set("job-1","chan-cached"),await e.events.maybeBackfillBeeosChannel({jobId:"job-1",action:"added"}),expect(e.gatewayRequest).not.toHaveBeenCalled()}),it("skips and backfills cache when description already has the beeos tag",async()=>{const e=makeHarness();e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"job-2",description:"Daily backup\n\x3c!-- beeos:channel=chan-existing --\x3e",sessionKey:"agent:main:main",sessionTarget:"session:agent:main:main",payload:{kind:"agentTurn"}}]}),await e.events.maybeBackfillBeeosChannel({jobId:"job-2",action:"added"}),expect(e.gatewayRequest).toHaveBeenCalledTimes(1),expect(e.gatewayRequest).toHaveBeenCalledWith("cron.list",{}),expect(e.cronChannelCache.get("job-2")).toBe("chan-existing")}),it("skips when sessionTarget === 'main'",async()=>{const e=makeHarness();installSession(e.state,"agent:main:main","chan-origin"),e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"job-3",description:"",sessionKey:"agent:main:main",sessionTarget:"main",payload:{kind:"agentTurn"}}]}),await e.events.maybeBackfillBeeosChannel({jobId:"job-3",action:"added"}),expect(e.gatewayRequest).toHaveBeenCalledTimes(1),expect(e.cronChannelCache.has("job-3")).toBe(!1)}),it("skips when payload.kind === 'systemEvent'",async()=>{const e=makeHarness();installSession(e.state,"agent:main:main","chan-origin"),e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"job-4",description:"",sessionKey:"agent:main:main",sessionTarget:"session:agent:main:main",payload:{kind:"systemEvent",text:"heartbeat"}}]}),await e.events.maybeBackfillBeeosChannel({jobId:"job-4",action:"added"}),expect(e.gatewayRequest).toHaveBeenCalledTimes(1),expect(e.cronChannelCache.has("job-4")).toBe(!1)}),it("skips when delivery.mode === 'none' (explicit opt-out)",async()=>{const e=makeHarness();installSession(e.state,"agent:main:main","chan-origin"),e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"job-5",description:"Silent backup",sessionKey:"agent:main:main",sessionTarget:"session:agent:main:main",payload:{kind:"agentTurn"},delivery:{mode:"none"}}]}),await e.events.maybeBackfillBeeosChannel({jobId:"job-5",action:"added"}),expect(e.gatewayRequest).toHaveBeenCalledTimes(1),expect(e.cronChannelCache.has("job-5")).toBe(!1)}),it("skips when job has no sessionKey",async()=>{const e=makeHarness();e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"job-6",description:"",sessionTarget:"session:agent:main:main",payload:{kind:"agentTurn"}}]}),await e.events.maybeBackfillBeeosChannel({jobId:"job-6",action:"added"}),expect(e.gatewayRequest).toHaveBeenCalledTimes(1),expect(e.cronChannelCache.has("job-6")).toBe(!1)}),it("skips when ACPSession has no channelId",async()=>{const e=makeHarness();installSession(e.state,"agent:main:main",void 0),e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"job-7",description:"",sessionKey:"agent:main:main",sessionTarget:"session:agent:main:main",payload:{kind:"agentTurn"}}]}),await e.events.maybeBackfillBeeosChannel({jobId:"job-7",action:"added"}),expect(e.gatewayRequest).toHaveBeenCalledTimes(1),expect(e.cronChannelCache.has("job-7")).toBe(!1)}),it("happy path: emits cron.update with beeos tag and populates cache",async()=>{const e=makeHarness();installSession(e.state,"agent:main:main","chan-origin"),e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"job-8",description:"Remind me to pee",sessionKey:"agent:main:main",sessionTarget:"session:agent:main:main",payload:{kind:"agentTurn"},delivery:{mode:"announce",channel:"last"}}]}).mockResolvedValueOnce({ok:!0}),await e.events.maybeBackfillBeeosChannel({jobId:"job-8",action:"added"}),expect(e.gatewayRequest).toHaveBeenCalledTimes(2),expect(e.gatewayRequest).toHaveBeenNthCalledWith(1,"cron.list",{});const[n,a]=e.gatewayRequest.mock.calls[1];expect(n).toBe("cron.update"),expect(a.id).toBe("job-8"),expect(a.patch.description).toBe("Remind me to pee\n\x3c!-- beeos:channel=chan-origin --\x3e"),expect(e.cronChannelCache.get("job-8")).toBe("chan-origin")}),it("gracefully degrades (warn) when cron.update rejects",async()=>{const e=makeHarness();installSession(e.state,"agent:main:main","chan-origin"),e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"job-9",description:"Reminder",sessionKey:"agent:main:main",sessionTarget:"session:agent:main:main",payload:{kind:"agentTurn"}}]}).mockRejectedValueOnce(new Error("boom")),await expect(e.events.maybeBackfillBeeosChannel({jobId:"job-9",action:"added"})).resolves.toBeUndefined(),expect(e.logger.warn).toHaveBeenCalledWith(expect.stringContaining("maybeBackfillBeeosChannel cron.update failed")),expect(e.cronChannelCache.has("job-9")).toBe(!1)})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describe,it,expect,vi}from"vitest";import{AcpGatewayEvents}from"./gateway-events.js";import{AcpGatewaySessionState}from"./session-state.js";function makeHarness(){const e={info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()},t=new AcpGatewaySessionState(e),n={sendSessionUpdate:vi.fn().mockReturnValue(!0),sendResult:vi.fn(),sendAcpError:vi.fn(),sendNotification:vi.fn(),resetSessionUpdateCount:vi.fn(),setSessionUpdateObserver:vi.fn(),isReady:()=>!0,get forwardControl(){return{forwardThinking:!0,forwardToolCalls:!0}}},a=vi.fn(),o=vi.fn().mockResolvedValue(new Response("{}",{status:200})),s=new Map;return{events:new AcpGatewayEvents({state:t,transport:n,config:{gateway:{agentId:"main"},agentGatewayUrl:"https://agent-gw.example.com"},logger:e,writeObs:vi.fn(),completePrompt:vi.fn(),failPrompt:vi.fn(),maybeCompletePromptFromChatState:vi.fn(),agentFetch:o,gatewayRequest:a,cronChannelCache:s}),state:t,gatewayRequest:a,agentFetch:o,logger:e}}function postedCronData(e){expect(e).toHaveBeenCalledTimes(1);const[t,n]=e.mock.calls[0];expect(t).toBe("https://agent-gw.example.com/api/v1/agent/events");const a=JSON.parse(n.body);return expect(a.type).toBe("cron"),a.data}describe("reportCronEventToAgentGateway — cron job name back-fill",()=>{it("uses payload.name verbatim when present, skipping cron.list",async()=>{const e=makeHarness();await e.events.reportCronEventToAgentGateway({jobId:"job-1",action:"finished",summary:"ok",name:"preset-name"}),expect(e.gatewayRequest).not.toHaveBeenCalled(),expect(postedCronData(e.agentFetch).name).toBe("preset-name")}),it("queries cron.list and posts the resolved name when payload lacks one",async()=>{const e=makeHarness();e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"other-job",name:"other-name"},{id:"job-2",name:"daily-report"}]}),await e.events.reportCronEventToAgentGateway({jobId:"job-2",action:"finished",summary:"all done"}),expect(e.gatewayRequest).toHaveBeenCalledTimes(1),expect(e.gatewayRequest).toHaveBeenCalledWith("cron.list",{}),expect(postedCronData(e.agentFetch).name).toBe("daily-report")}),it("posts without name (and does not throw) when cron.list rejects",async()=>{const e=makeHarness();e.gatewayRequest.mockRejectedValueOnce(new Error("gateway gone")),await e.events.reportCronEventToAgentGateway({jobId:"job-3",action:"finished"}),expect(e.agentFetch).toHaveBeenCalledTimes(1),expect(postedCronData(e.agentFetch).name).toBeUndefined()}),it("posts without name when cron.list returns but jobId is not in the list",async()=>{const e=makeHarness();e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"different-job",name:"irrelevant"}]}),await e.events.reportCronEventToAgentGateway({jobId:"job-4",action:"finished"}),expect(e.gatewayRequest).toHaveBeenCalledTimes(1),expect(postedCronData(e.agentFetch).name).toBeUndefined()}),it("skips cron.list lookup entirely when payload has no jobId",async()=>{const e=makeHarness();await e.events.reportCronEventToAgentGateway({action:"added",nextRunAtMs:0}),expect(e.gatewayRequest).not.toHaveBeenCalled(),expect(postedCronData(e.agentFetch).name).toBeUndefined()}),it("does not throw when agentFetch rejects (warn logged)",async()=>{const e=makeHarness();e.agentFetch.mockRejectedValueOnce(new Error("network down")),await expect(e.events.reportCronEventToAgentGateway({jobId:"job-5",action:"finished",name:"n"})).resolves.toBeUndefined(),expect(e.logger.warn).toHaveBeenCalledWith(expect.stringContaining("event report failed"))})}),describe("handleCronEvent — end-to-end happy path",()=>{it("forwards the upstream payload (with name resolved) without dropping existing fields",async()=>{const e=makeHarness();e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"job-e2e",name:"e2e-name"}]}),e.events.handleCronEvent({jobId:"job-e2e",action:"finished",status:"ok",summary:"Run complete",sessionKey:"agent:main:cron:job-e2e:run:r1",runAtMs:17e11}),await new Promise(e=>setImmediate(e));const t=postedCronData(e.agentFetch);expect(t.jobId).toBe("job-e2e"),expect(t.action).toBe("finished"),expect(t.summary).toBe("Run complete"),expect(t.sessionKey).toBe("agent:main:cron:job-e2e:run:r1"),expect(t.name).toBe("e2e-name")})});
|
|
1
|
+
import{describe,it,expect,vi}from"vitest";import{AcpGatewayEvents}from"./gateway-events.js";import{AcpGatewaySessionState}from"./session-state.js";function makeHarness(){const e={info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()},t=new AcpGatewaySessionState(e),n={sendSessionUpdate:vi.fn().mockReturnValue(!0),sendResult:vi.fn(),sendAcpError:vi.fn(),sendNotification:vi.fn(),resetSessionUpdateCount:vi.fn(),setSessionUpdateObserver:vi.fn(),isReady:()=>!0,get forwardControl(){return{forwardThinking:!0,forwardToolCalls:!0}}},a=vi.fn(),o=vi.fn().mockResolvedValue(new Response("{}",{status:200})),s=new Map;return{events:new AcpGatewayEvents({state:t,transport:n,config:{gateway:{agentId:"main"},agentGatewayUrl:"https://agent-gw.example.com"},logger:e,writeObs:vi.fn(),completePrompt:vi.fn(),failPrompt:vi.fn(),schedulePromptTimeout:vi.fn(),maybeCompletePromptFromChatState:vi.fn(),agentFetch:o,gatewayRequest:a,cronChannelCache:s}),state:t,gatewayRequest:a,agentFetch:o,logger:e}}function postedCronData(e){expect(e).toHaveBeenCalledTimes(1);const[t,n]=e.mock.calls[0];expect(t).toBe("https://agent-gw.example.com/api/v1/agent/events");const a=JSON.parse(n.body);return expect(a.type).toBe("cron"),a.data}describe("reportCronEventToAgentGateway — cron job name back-fill",()=>{it("uses payload.name verbatim when present, skipping cron.list",async()=>{const e=makeHarness();await e.events.reportCronEventToAgentGateway({jobId:"job-1",action:"finished",summary:"ok",name:"preset-name"}),expect(e.gatewayRequest).not.toHaveBeenCalled(),expect(postedCronData(e.agentFetch).name).toBe("preset-name")}),it("queries cron.list and posts the resolved name when payload lacks one",async()=>{const e=makeHarness();e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"other-job",name:"other-name"},{id:"job-2",name:"daily-report"}]}),await e.events.reportCronEventToAgentGateway({jobId:"job-2",action:"finished",summary:"all done"}),expect(e.gatewayRequest).toHaveBeenCalledTimes(1),expect(e.gatewayRequest).toHaveBeenCalledWith("cron.list",{}),expect(postedCronData(e.agentFetch).name).toBe("daily-report")}),it("posts without name (and does not throw) when cron.list rejects",async()=>{const e=makeHarness();e.gatewayRequest.mockRejectedValueOnce(new Error("gateway gone")),await e.events.reportCronEventToAgentGateway({jobId:"job-3",action:"finished"}),expect(e.agentFetch).toHaveBeenCalledTimes(1),expect(postedCronData(e.agentFetch).name).toBeUndefined()}),it("posts without name when cron.list returns but jobId is not in the list",async()=>{const e=makeHarness();e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"different-job",name:"irrelevant"}]}),await e.events.reportCronEventToAgentGateway({jobId:"job-4",action:"finished"}),expect(e.gatewayRequest).toHaveBeenCalledTimes(1),expect(postedCronData(e.agentFetch).name).toBeUndefined()}),it("skips cron.list lookup entirely when payload has no jobId",async()=>{const e=makeHarness();await e.events.reportCronEventToAgentGateway({action:"added",nextRunAtMs:0}),expect(e.gatewayRequest).not.toHaveBeenCalled(),expect(postedCronData(e.agentFetch).name).toBeUndefined()}),it("does not throw when agentFetch rejects (warn logged)",async()=>{const e=makeHarness();e.agentFetch.mockRejectedValueOnce(new Error("network down")),await expect(e.events.reportCronEventToAgentGateway({jobId:"job-5",action:"finished",name:"n"})).resolves.toBeUndefined(),expect(e.logger.warn).toHaveBeenCalledWith(expect.stringContaining("event report failed"))})}),describe("handleCronEvent — end-to-end happy path",()=>{it("forwards the upstream payload (with name resolved) without dropping existing fields",async()=>{const e=makeHarness();e.gatewayRequest.mockResolvedValueOnce({jobs:[{id:"job-e2e",name:"e2e-name"}]}),e.events.handleCronEvent({jobId:"job-e2e",action:"finished",status:"ok",summary:"Run complete",sessionKey:"agent:main:cron:job-e2e:run:r1",runAtMs:17e11}),await new Promise(e=>setImmediate(e));const t=postedCronData(e.agentFetch);expect(t.jobId).toBe("job-e2e"),expect(t.action).toBe("finished"),expect(t.summary).toBe("Run complete"),expect(t.sessionKey).toBe("agent:main:cron:job-e2e:run:r1"),expect(t.name).toBe("e2e-name")})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describe,it,expect,beforeEach,vi}from"vitest";import{AcpGatewayEvents}from"./gateway-events.js";import{AcpGatewaySessionState}from"./session-state.js";function makeDeps(){const e={info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()},t=new AcpGatewaySessionState(e),n=vi.fn().mockReturnValue(!0),s={sendSessionUpdate:n,sendResult:vi.fn(),sendAcpError:vi.fn(),sendNotification:vi.fn(),resetSessionUpdateCount:vi.fn(),setSessionUpdateObserver:vi.fn(),isReady:()=>!0,get forwardControl(){return{forwardThinking:!0,forwardToolCalls:!0}}},a=vi.fn(),o=vi.fn(),i=vi.fn(),r=vi.fn(),d=vi.fn();return{events:new AcpGatewayEvents({state:t,transport:s,config:{gateway:{agentId:"main"}},logger:e,writeObs:d,completePrompt:a,failPrompt:o,maybeCompletePromptFromChatState:i,onStreamDelta:r}),state:t,transport:s,sendSessionUpdate:n,onStreamDelta:r,logger:e,writeObs:d}}function makeSession(e,t){const n={sessionId:"s1",gatewaySessionKey:"main/s1",agentId:"main",currentRunId:t,pendingPromptId:1,promptDone:!1,createdAt:Date.now(),chatReplayDedupKeys:new Set};return e.sessions.set(n.sessionId,n),e.promptsByRunId.set(t,n),n}describe("Bug-Z: heartbeat live-path filtering",()=>{let e,t;beforeEach(()=>{e=makeDeps(),t=makeSession(e.state,"run-heartbeat-1")}),it("drops agent.assistant delta whose cumulative text is HEARTBEAT_OK",()=>{const t={stream:"assistant",runId:"run-heartbeat-1",sessionKey:"main/s1",seq:1,ts:Date.now(),data:{delta:"HEARTBEAT_OK"}};e.events.handleAgentEvent(t);const n=e.sendSessionUpdate.mock.calls.map(e=>e[1]).filter(e=>"agent_message_chunk"===e.sessionUpdate);expect(n).toHaveLength(0),expect(e.onStreamDelta).not.toHaveBeenCalled()}),it("emits a structured SKIP log + obs event with reason + preview on prefix drop",()=>{const t={stream:"assistant",runId:"run-heartbeat-1",sessionKey:"main/s1",seq:1,ts:Date.now(),data:{delta:"HEARTBEAT_"}};e.events.handleAgentEvent(t);const n=e.logger.info.mock.calls.map(e=>String(e[0])),s=n.find(e=>e.includes("SKIP heartbeat assistant-delta"));expect(s,`expected a SKIP log, got info=${JSON.stringify(n)}`).toBeDefined(),expect(s).toContain("reason=prefix"),expect(s).toContain("sessionId=s1"),expect(s).toContain("runId=run-heartbeat-1"),expect(s).toContain('cumulative="HEARTBEAT_"'),expect(s).toContain('delta="HEARTBEAT_"');const a=e.writeObs.mock.calls.map(e=>e[0]).find(e=>"heartbeat_filter_skip"===e.name);expect(a).toBeDefined(),expect(a.component).toBe("gateway-events"),expect(a.severity).toBe("info");const o=a.payload;expect(o.source).toBe("assistant-delta"),expect(o.reason).toBe("prefix"),expect(o.sessionId).toBe("s1"),expect(o.runId).toBe("run-heartbeat-1"),expect(o.cumulativePreview).toBe("HEARTBEAT_"),expect(o.deltaPreview).toBe("HEARTBEAT_")}),it('drops heartbeat ack across split deltas ("HEART" + "BEAT_OK") — no underscore or full token leaks',()=>{const t={stream:"assistant",runId:"run-heartbeat-1",sessionKey:"main/s1",seq:1,ts:Date.now(),data:{delta:"HEART"}},n={stream:"assistant",runId:"run-heartbeat-1",sessionKey:"main/s1",seq:2,ts:Date.now(),data:{delta:"BEAT_OK"}};e.events.handleAgentEvent(t),e.events.handleAgentEvent(n);const s=e.sendSessionUpdate.mock.calls.map(e=>e[1]).filter(e=>"agent_message_chunk"===e.sessionUpdate).map(e=>e.content?.text??"").join("");expect(s).not.toContain("_"),expect(s).not.toContain("HEARTBEAT_OK")}),it('drops real-world split ("HEARTBEAT_" + "OK") — the ghost bubble case',()=>{const t={stream:"assistant",runId:"run-heartbeat-1",sessionKey:"main/s1",seq:1,ts:Date.now(),data:{delta:"HEARTBEAT_"}},n={stream:"assistant",runId:"run-heartbeat-1",sessionKey:"main/s1",seq:2,ts:Date.now(),data:{delta:"OK"}};e.events.handleAgentEvent(t),e.events.handleAgentEvent(n);const s=e.sendSessionUpdate.mock.calls.map(e=>e[1]).filter(e=>"agent_message_chunk"===e.sessionUpdate);expect(s).toHaveLength(0),expect(e.onStreamDelta).not.toHaveBeenCalled()}),it('drops fine-grained split ("H" + "EARTBEAT" + "_OK") at least at the underscore boundary',()=>{const t=["H","EARTBEAT","_OK"];for(let n=0;n<t.length;n++)e.events.handleAgentEvent({stream:"assistant",runId:"run-heartbeat-1",sessionKey:"main/s1",seq:n+1,ts:Date.now(),data:{delta:t[n]}});const n=e.sendSessionUpdate.mock.calls.map(e=>e[1]).filter(e=>"agent_message_chunk"===e.sessionUpdate).map(e=>e.content?.text??"").join("");expect(n).not.toContain("_"),expect(n).not.toContain("HEARTBEAT_OK")}),it("does NOT drop normal assistant text that happens to contain HEARTBEAT as substring",()=>{const t={stream:"assistant",runId:"run-heartbeat-1",sessionKey:"main/s1",seq:1,ts:Date.now(),data:{delta:"Let's design a HEARTBEAT_OK-like ack for our API."}};e.events.handleAgentEvent(t);const n=e.sendSessionUpdate.mock.calls.map(e=>e[1]).filter(e=>"agent_message_chunk"===e.sessionUpdate);expect(n).toHaveLength(1),expect(n[0].content.text).toContain("HEARTBEAT_OK-like")}),it("drops chat.text heartbeat when no agent.assistant stream is active",()=>{const t={runId:"run-heartbeat-1",sessionKey:"main/s1",seq:1,message:{role:"assistant",content:[{type:"text",text:"HEARTBEAT_OK"}],timestamp:Date.now()}};e.events.handleChatEvent(t);const n=e.sendSessionUpdate.mock.calls.map(e=>e[1]).filter(e=>"agent_message_chunk"===e.sessionUpdate);expect(n).toHaveLength(0)}),it("does NOT drop a real chat.text that only mentions the token inline",()=>{const t={runId:"run-heartbeat-1",sessionKey:"main/s1",seq:1,message:{role:"assistant",content:[{type:"text",text:"Use the sentinel HEARTBEAT_OK in your ack handler."}],timestamp:Date.now()}};e.events.handleChatEvent(t);const n=e.sendSessionUpdate.mock.calls.map(e=>e[1]).filter(e=>"agent_message_chunk"===e.sessionUpdate);expect(n).toHaveLength(1)})});
|
|
1
|
+
import{describe,it,expect,beforeEach,vi}from"vitest";import{AcpGatewayEvents}from"./gateway-events.js";import{AcpGatewaySessionState}from"./session-state.js";function makeDeps(){const e={info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()},t=new AcpGatewaySessionState(e),n=vi.fn().mockReturnValue(!0),s={sendSessionUpdate:n,sendResult:vi.fn(),sendAcpError:vi.fn(),sendNotification:vi.fn(),resetSessionUpdateCount:vi.fn(),setSessionUpdateObserver:vi.fn(),isReady:()=>!0,get forwardControl(){return{forwardThinking:!0,forwardToolCalls:!0}}},a=vi.fn(),o=vi.fn(),i=vi.fn(),r=vi.fn(),d=vi.fn();return{events:new AcpGatewayEvents({state:t,transport:s,config:{gateway:{agentId:"main"}},logger:e,writeObs:d,completePrompt:a,failPrompt:o,schedulePromptTimeout:vi.fn(),maybeCompletePromptFromChatState:i,onStreamDelta:r}),state:t,transport:s,sendSessionUpdate:n,onStreamDelta:r,logger:e,writeObs:d}}function makeSession(e,t){const n={sessionId:"s1",gatewaySessionKey:"main/s1",agentId:"main",currentRunId:t,pendingPromptId:1,promptDone:!1,createdAt:Date.now(),chatReplayDedupKeys:new Set};return e.sessions.set(n.sessionId,n),e.promptsByRunId.set(t,n),n}describe("Bug-Z: heartbeat live-path filtering",()=>{let e,t;beforeEach(()=>{e=makeDeps(),t=makeSession(e.state,"run-heartbeat-1")}),it("drops agent.assistant delta whose cumulative text is HEARTBEAT_OK",()=>{const t={stream:"assistant",runId:"run-heartbeat-1",sessionKey:"main/s1",seq:1,ts:Date.now(),data:{delta:"HEARTBEAT_OK"}};e.events.handleAgentEvent(t);const n=e.sendSessionUpdate.mock.calls.map(e=>e[1]).filter(e=>"agent_message_chunk"===e.sessionUpdate);expect(n).toHaveLength(0),expect(e.onStreamDelta).not.toHaveBeenCalled()}),it("emits a structured SKIP log + obs event with reason + preview on prefix drop",()=>{const t={stream:"assistant",runId:"run-heartbeat-1",sessionKey:"main/s1",seq:1,ts:Date.now(),data:{delta:"HEARTBEAT_"}};e.events.handleAgentEvent(t);const n=e.logger.info.mock.calls.map(e=>String(e[0])),s=n.find(e=>e.includes("SKIP heartbeat assistant-delta"));expect(s,`expected a SKIP log, got info=${JSON.stringify(n)}`).toBeDefined(),expect(s).toContain("reason=prefix"),expect(s).toContain("sessionId=s1"),expect(s).toContain("runId=run-heartbeat-1"),expect(s).toContain('cumulative="HEARTBEAT_"'),expect(s).toContain('delta="HEARTBEAT_"');const a=e.writeObs.mock.calls.map(e=>e[0]).find(e=>"heartbeat_filter_skip"===e.name);expect(a).toBeDefined(),expect(a.component).toBe("gateway-events"),expect(a.severity).toBe("info");const o=a.payload;expect(o.source).toBe("assistant-delta"),expect(o.reason).toBe("prefix"),expect(o.sessionId).toBe("s1"),expect(o.runId).toBe("run-heartbeat-1"),expect(o.cumulativePreview).toBe("HEARTBEAT_"),expect(o.deltaPreview).toBe("HEARTBEAT_")}),it('drops heartbeat ack across split deltas ("HEART" + "BEAT_OK") — no underscore or full token leaks',()=>{const t={stream:"assistant",runId:"run-heartbeat-1",sessionKey:"main/s1",seq:1,ts:Date.now(),data:{delta:"HEART"}},n={stream:"assistant",runId:"run-heartbeat-1",sessionKey:"main/s1",seq:2,ts:Date.now(),data:{delta:"BEAT_OK"}};e.events.handleAgentEvent(t),e.events.handleAgentEvent(n);const s=e.sendSessionUpdate.mock.calls.map(e=>e[1]).filter(e=>"agent_message_chunk"===e.sessionUpdate).map(e=>e.content?.text??"").join("");expect(s).not.toContain("_"),expect(s).not.toContain("HEARTBEAT_OK")}),it('drops real-world split ("HEARTBEAT_" + "OK") — the ghost bubble case',()=>{const t={stream:"assistant",runId:"run-heartbeat-1",sessionKey:"main/s1",seq:1,ts:Date.now(),data:{delta:"HEARTBEAT_"}},n={stream:"assistant",runId:"run-heartbeat-1",sessionKey:"main/s1",seq:2,ts:Date.now(),data:{delta:"OK"}};e.events.handleAgentEvent(t),e.events.handleAgentEvent(n);const s=e.sendSessionUpdate.mock.calls.map(e=>e[1]).filter(e=>"agent_message_chunk"===e.sessionUpdate);expect(s).toHaveLength(0),expect(e.onStreamDelta).not.toHaveBeenCalled()}),it('drops fine-grained split ("H" + "EARTBEAT" + "_OK") at least at the underscore boundary',()=>{const t=["H","EARTBEAT","_OK"];for(let n=0;n<t.length;n++)e.events.handleAgentEvent({stream:"assistant",runId:"run-heartbeat-1",sessionKey:"main/s1",seq:n+1,ts:Date.now(),data:{delta:t[n]}});const n=e.sendSessionUpdate.mock.calls.map(e=>e[1]).filter(e=>"agent_message_chunk"===e.sessionUpdate).map(e=>e.content?.text??"").join("");expect(n).not.toContain("_"),expect(n).not.toContain("HEARTBEAT_OK")}),it("does NOT drop normal assistant text that happens to contain HEARTBEAT as substring",()=>{const t={stream:"assistant",runId:"run-heartbeat-1",sessionKey:"main/s1",seq:1,ts:Date.now(),data:{delta:"Let's design a HEARTBEAT_OK-like ack for our API."}};e.events.handleAgentEvent(t);const n=e.sendSessionUpdate.mock.calls.map(e=>e[1]).filter(e=>"agent_message_chunk"===e.sessionUpdate);expect(n).toHaveLength(1),expect(n[0].content.text).toContain("HEARTBEAT_OK-like")}),it("drops chat.text heartbeat when no agent.assistant stream is active",()=>{const t={runId:"run-heartbeat-1",sessionKey:"main/s1",seq:1,message:{role:"assistant",content:[{type:"text",text:"HEARTBEAT_OK"}],timestamp:Date.now()}};e.events.handleChatEvent(t);const n=e.sendSessionUpdate.mock.calls.map(e=>e[1]).filter(e=>"agent_message_chunk"===e.sessionUpdate);expect(n).toHaveLength(0)}),it("does NOT drop a real chat.text that only mentions the token inline",()=>{const t={runId:"run-heartbeat-1",sessionKey:"main/s1",seq:1,message:{role:"assistant",content:[{type:"text",text:"Use the sentinel HEARTBEAT_OK in your ack handler."}],timestamp:Date.now()}};e.events.handleChatEvent(t);const n=e.sendSessionUpdate.mock.calls.map(e=>e[1]).filter(e=>"agent_message_chunk"===e.sessionUpdate);expect(n).toHaveLength(1)})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash,randomUUID}from"node:crypto";import{Errors}from"../errors/index.js";import{BEEOS_CHANNEL_TAG_RE,decodeBeeosChannelId,encodeBeeosChannelTag}from"./bridge-core.js";import{formatFriendlyError}from"../errors/classify.js";import{stripTransportMetadata,normalizeTransportText,classifyHeartbeatFilter,previewFilteredText}from"../message-filter.js";import{resolveToolResultBlocks}from"./tool-result-payload-strategies.js";import{buildToolCallPayload,buildToolCallUpdatePayload}from"./tool-call-payload-builder.js";import{DEFAULT_STREAM_IDLE_TIMEOUT_MS,DEFAULT_STREAM_STALE_TIMEOUT_MS}from"./types.js";import{MessageQueue}from"../utils/mq.js";function asString(t){if("string"==typeof t){return t.trim()||void 0}}function isRecord(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function normalizeText(t){if("string"==typeof t)return normalizeTransportText(t.replace(/\r\n/g,"\n").replace(/\r/g,"\n"))}function extractResourceLinksFromRawResult(t){if(!isRecord(t)||!Array.isArray(t.files))return;const e=[];for(const s of t.files){if(!isRecord(s))continue;const t=asString(s.uri)??(asString(s.fileId)?`beeos-file://${s.fileId}`:void 0);t&&e.push({uri:t,name:asString(s.name)??"file",...asString(s.mimeType)?{mimeType:asString(s.mimeType)}:{}})}return e.length>0?e:void 0}const DEDUP_HASH_THRESHOLD=256;function dedupKey(t,...e){const s=`${t}:${e.join(":")}`;if(s.length<=256)return s;return`${t}:h:${createHash("sha256").update(s).digest("hex").slice(0,24)}`}function toISO(t){if(!(null==t||t<=0))try{return new Date(t).toISOString()}catch{return}}function resolveToolArgs(t){const e=t.arguments??t.args??t.input;if(isRecord(e))return e;if("string"==typeof e){const t=e.trim();if(t.startsWith("{")||t.startsWith("["))try{return JSON.parse(t)}catch{}}return{}}export function resolveTurnId(t){if(t.currentRunId)return t.currentRunId;const e=t.pendingPromptId;return void 0!==e?"string"==typeof e?`req:${e}`:`req:${String(e)}`:void 0}export function roleFromSessionUpdate(t){const e=t.sessionUpdate;if(e)return"user_message_chunk"===e?"user":"system_message_chunk"===e?"system":e.startsWith("agent_")||e.startsWith("tool_")?"assistant":"history_turn"===e?"user"===t.role?"user":"system"===t.role?"system":"assistant":void 0}export function recordTurnIdForRole(t,e,s){if(!s)return;const n=roleFromSessionUpdate(e);n&&(t.lastTurnIdByRole||(t.lastTurnIdByRole={}),t.lastTurnIdByRole[n]=s)}export class AcpGatewayEvents{state;transport;config;logger;writeObs;completePrompt;failPrompt;maybeCompletePromptFromChatState;agentFetchFn;onStreamDelta;getMessageSdk;getMsgPrincipalId;gatewayRequest;cronChannelCache;constructor(t){this.state=t.state,this.transport=t.transport,this.config=t.config,this.logger=t.logger,this.writeObs=t.writeObs,this.completePrompt=t.completePrompt,this.failPrompt=t.failPrompt,this.maybeCompletePromptFromChatState=t.maybeCompletePromptFromChatState,this.agentFetchFn=t.agentFetch,this.onStreamDelta=t.onStreamDelta,this.getMessageSdk=t.getMessageSdk,this.getMsgPrincipalId=t.getMsgPrincipalId,this.gatewayRequest=t.gatewayRequest,this.cronChannelCache=t.cronChannelCache}touchStreamActivity(t){t.lastStreamActivityTs=Date.now(),this.resetStreamIdleTimer(t)}resetStreamIdleTimer(t){this.state.clearStreamIdleTimer(t);const e=this.config.streamIdleTimeoutMs??DEFAULT_STREAM_IDLE_TIMEOUT_MS,s=this.config.streamStaleTimeoutMs??DEFAULT_STREAM_STALE_TIMEOUT_MS;t.streamIdleTimer=setTimeout(()=>{if(!t.lastStreamActivityTs)return;const e=Date.now()-t.lastStreamActivityTs;e>s&&(this.logger.warn?.(`[gateway-events] Stream stale timeout sessionId=${t.sessionId} stale=${e}ms`),this.completePrompt(t,"end_turn"))},e),"object"==typeof t.streamIdleTimer&&"unref"in t.streamIdleTimer&&t.streamIdleTimer.unref()}sendTurnUpdate(t,e){const s=resolveTurnId(t);return s&&void 0===e._turnId&&(e._turnId=s),recordTurnIdForRole(t,e,s),!!t.sessionLoadInProgress||this.transport.sendSessionUpdate(t.sessionId,e,{turnId:s})}sendToolCallSpacer(t,e){const s={sessionUpdate:"agent_message_chunk",content:{type:"text",text:"\n"},...e?{timestamp:e}:{}};this.sendTurnUpdate(t,s),t.assistantMq?.push(s),this.onStreamDelta?.(t,s)}resolveToolCallId(t,e,s){const n=asString(e.toolCallId)??asString(e.tool_call_id)??asString(e.callId)??asString(e.id);if(n){const e=this.state.toolCallIdMap.get(n);return e?(t.sessionId&&this.state.toolCallToSessionMap.set(e,t.sessionId),e):(this.state.toolCallIdMap.set(n,n),t.sessionId&&this.state.toolCallToSessionMap.set(n,t.sessionId),n)}const o=`tc_${t.currentRunId??"unknown"}_${this.state.nextToolCallSeq++}`;return t.sessionId&&this.state.toolCallToSessionMap.set(o,t.sessionId),o}handleChatEvent(t){const e=(t.runId?this.state.promptsByRunId.get(t.runId):void 0)??this.state.findSessionByKey(t.sessionKey);if(!e)return;if(!this.state.isCurrentStreamOwner(e,t.runId)){const s=!e.currentRunId&&void 0===e.pendingPromptId;if(!t.runId||!s||this.state.isRunCompleted(t.runId))return;this.adoptBackgroundRun(e,t.runId)}e.sessionId;const s=t.message;if(s){this.touchStreamActivity(e);if("assistant"===s.role){if(!Array.isArray(s.content))return;for(const n of s.content){const o=n;if(!isRecord(o))continue;const a=asString(o.type);if(!a)continue;const r=toISO(s.timestamp);if("thinking"===a){if(e.hasAgentThinkingStream)continue;const t=normalizeText(o.thinking)??normalizeText(o.text);if(!t)continue;const s=dedupKey("chat:thinking",t);if(e.chatReplayDedupKeys.has(s))continue;e.chatReplayDedupKeys.add(s);const n={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:t},...r?{timestamp:r}:{}};this.sendTurnUpdate(e,n)&&(e.assistantMq?.push(n),this.onStreamDelta?.(e,n));continue}if("toolCall"===a){if(this.sendToolCallSpacer(e,r),e.hasAgentToolStartStream)continue;const t=this.resolveToolCallId(e,o,"start"),s=asString(o.name)??asString(o.toolName)??asString(o.tool_name)??"tool",n=resolveToolArgs(o),a=dedupKey("chat:tool_start",t,JSON.stringify(n));if(e.chatReplayDedupKeys.has(a))continue;e.chatReplayDedupKeys.add(a);const i=buildToolCallPayload({toolCallId:t,toolName:s,args:n,timestamp:r});this.sendTurnUpdate(e,i)&&(e.assistantMq?.push(i),this.onStreamDelta?.(e,i));continue}if("toolResult"===a){if(this.sendToolCallSpacer(e,r),e.hasAgentToolResultStream)continue;const t=this.resolveToolCallId(e,o,"result"),s=asString(o.name)??asString(o.toolName)??asString(o.tool_name)??"tool",n=o.result,a=normalizeText(o.text)??normalizeText(o.result)??(isRecord(n)||Array.isArray(n)?JSON.stringify(n,null,2):void 0);if(!a)continue;const i=dedupKey("chat:tool_result",t,a);if(e.chatReplayDedupKeys.has(i))continue;e.chatReplayDedupKeys.add(i);const l=buildToolCallUpdatePayload({toolCallId:t,toolName:s,outputText:a,rawOutput:n,resourceLinks:extractResourceLinksFromRawResult(n),timestamp:r});this.sendTurnUpdate(e,l)&&(e.assistantMq?.push(l),this.onStreamDelta?.(e,l));continue}if("text"===a&&o.text){if(e.hasAgentAssistantStream||e.agentAssistantTextSoFar)continue;const s=stripTransportMetadata(o.text);if(!s)continue;const n=classifyHeartbeatFilter(s);if(n.filtered){this.logHeartbeatSkip({source:"chat-text",reason:n.reason,sessionId:e.sessionId,runId:t.runId,cumulative:s});continue}const a=dedupKey("chat:text",s);if(e.chatReplayDedupKeys.has(a))continue;e.chatReplayDedupKeys.add(a);const i=e.chatAssistantTextSoFar??"";let l;if(e.chatAssistantTextSoFar=s,s.startsWith(i))l=s.slice(i.length);else{if(i.startsWith(s))continue;l=s}if(!l)continue;this.logger.debug?.(`[gateway-events] chat.text delta seq=${t.seq} runId=${t.runId} len=${l.length} prevLen=${i.length}`);const c={sessionUpdate:"agent_message_chunk",content:{type:"text",text:l},...r?{timestamp:r}:{}};this.sendTurnUpdate(e,c),e.assistantMq?.push(c),this.onStreamDelta?.(e,c)}}}}else"delta"===t.state&&this.touchStreamActivity(e);if(this.maybeCompletePromptFromChatState(e,t),!e.promptDone)if("final"===t.state)this.completePrompt(e,t.stopReason||"end_turn");else if("aborted"===t.state||"cancelled"===t.state||"cancel"===t.state)this.completePrompt(e,"cancelled");else if("error"===t.state){const s=t.errorMessage||Errors.AgentError.message;this.failPrompt(e,Errors.AgentError.rpcCode,formatFriendlyError(s))}}handleAgentEvent(t){const e=(t.runId?this.state.promptsByRunId.get(t.runId):void 0)??(t.sessionKey?this.state.findSessionByKey(t.sessionKey):void 0);if(!e)return;if(!this.state.isCurrentStreamOwner(e,t.runId)){const s=!e.currentRunId&&void 0===e.pendingPromptId;if(!t.runId||!s||this.state.isRunCompleted(t.runId))return;this.adoptBackgroundRun(e,t.runId)}e.sessionId;this.touchStreamActivity(e);const s=toISO(t.ts),n=t=>{this.sendTurnUpdate(e,t),e.assistantMq?.push(t),this.onStreamDelta?.(e,t)};if("assistant"===t.stream){e.hasAgentAssistantStream=!0;const o=this.state.extractAgentAssistantDelta(e,t.data??{});if(o){const a=normalizeTransportText(o);if(a){const o=e.agentAssistantTextSoFar??a,r=classifyHeartbeatFilter(o);r.filtered?this.logHeartbeatSkip({source:"assistant-delta",reason:r.reason,sessionId:e.sessionId,runId:t.runId,cumulative:o,delta:a}):(this.logger.debug?.(`[gateway-events] agent.assistant delta seq=${t.seq} runId=${t.runId} len=${a.length} source=${t.data?.delta?"delta":"cumulative"}`),n({sessionUpdate:"agent_message_chunk",content:{type:"text",text:a},...s?{timestamp:s}:{}}))}}const a=[],r=t.data;r&&(Array.isArray(r.content)?a.push(...r.content):isRecord(r.content)?a.push(r.content):"string"==typeof r.type&&a.push(r));for(const t of a){if(!isRecord(t))continue;const o=asString(t.type);if("thinking"===o){e.hasAgentThinkingStream=!0;const n=normalizeText(t.thinking)??normalizeText(t.text);if(n){const t={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n},...s?{timestamp:s}:{}};this.sendTurnUpdate(e,t)&&(e.assistantMq?.push(t),this.onStreamDelta?.(e,t))}continue}if("toolCall"===o){this.sendToolCallSpacer(e,s),e.hasAgentToolStartStream=!0;const o=this.resolveToolCallId(e,t,"start"),a=asString(t.name)??asString(t.toolName)??asString(t.tool_name)??"tool",r=resolveToolArgs(t);n(buildToolCallPayload({toolCallId:o,toolName:a,args:r,timestamp:s}));continue}if("toolResult"===o){this.sendToolCallSpacer(e,s),e.hasAgentToolResultStream=!0;const o=this.resolveToolCallId(e,t,"result"),a=asString(t.name)??asString(t.toolName)??asString(t.tool_name)??"tool",r=t.result,i=normalizeText(t.text)??normalizeText(t.result)??(isRecord(r)||Array.isArray(r)?JSON.stringify(r,null,2):void 0);i&&n(buildToolCallUpdatePayload({toolCallId:o,toolName:a,outputText:i,rawOutput:r,resourceLinks:extractResourceLinksFromRawResult(r),timestamp:s}));continue}}}else if("thinking"===t.stream){e.hasAgentThinkingStream=!0;const n=normalizeText(t.data?.delta)??normalizeText(t.data?.text);if(n){const t={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n},...s?{timestamp:s}:{}};this.sendTurnUpdate(e,t)&&(e.assistantMq?.push(t),this.onStreamDelta?.(e,t))}}else if("tool"===t.stream){const o=t.data,a="string"==typeof o?.phase?o.phase:void 0;if("start"===a){this.sendToolCallSpacer(e,s),e.hasAgentToolStartStream=!0;const t=this.resolveToolCallId(e,o,"start"),a=asString(o?.name)??asString(o?.toolName)??asString(o?.tool_name)??"tool",r=resolveToolArgs(o);n(buildToolCallPayload({toolCallId:t,toolName:a,args:r,timestamp:s}))}else if("result"===a)this.sendToolCallSpacer(e,s),e.hasAgentToolResultStream=!0,this.handleToolResult(e,t,s).catch(t=>{this.logger.warn?.(`[gateway-events] Tool result handling failed: ${t instanceof Error?t.message:t}`)});else{const t=o?.toolCall;if(t){this.sendToolCallSpacer(e,s),e.hasAgentToolStartStream=!0;const a=asString(t?.name)??asString(o?.name)??asString(o?.toolName)??"tool",r={...o,...t},i=this.resolveToolCallId(e,r,"start"),l=resolveToolArgs(r);n(buildToolCallPayload({toolCallId:i,toolName:a,args:l,timestamp:s}))}}}else if("lifecycle"===t.stream){const s=t.data,n="string"==typeof s?.phase?s.phase:void 0;if("end"===n)this.completePrompt(e,"end_turn");else if("cancelled"===n||"cancel"===n)this.completePrompt(e,"cancelled");else if("error"===n){const n=s?.error,o=n&&"object"==typeof n?n:void 0,a=("string"==typeof s?.message?s.message:void 0)??("string"==typeof n?n:void 0)??("string"==typeof o?.message?o.message:void 0)??("string"==typeof s?.reason?s.reason:void 0)??(o?JSON.stringify(o):void 0)??"gateway lifecycle error",r=formatFriendlyError(a);this.logger.warn?.(`[gateway-events] lifecycle error runId=${t.runId} sessionKey=${t.sessionKey} message=${a} data=${JSON.stringify(s)}`),this.failPrompt(e,Errors.AgentError.rpcCode,r)}}}async handleToolResult(t,e,s){const n=e.data,o=n?.toolCall,a=("string"==typeof o?.id?o.id:void 0)??("string"==typeof n?.toolCallId?n.toolCallId:void 0),r=(a?this.state.toolCallIdMap.get(a):void 0)??a??`tc_${e.runId}_${e.seq}`,i=("string"==typeof o?.name?o.name:void 0)??("string"==typeof n?.name?n.name:void 0)??"tool",l="string"==typeof n?.text?n.text:void 0,c=a??r,d=n?.result;let u;try{u=await resolveToolResultBlocks({toolCallId:c,toolName:i,rawText:l,rawResult:d})}catch{u=l?[{type:"content",content:{type:"text",text:l}}]:[]}0===u.length&&l&&(u=[{type:"content",content:{type:"text",text:l}}]);const h=[],g=[];for(const t of u)t.content&&("resource_link"===t.content.type&&t.content.uri?g.push({uri:t.content.uri,name:t.content.name??"file",...t.content.mimeType?{mimeType:t.content.mimeType}:{}}):t.content.text&&h.push(t.content.text));const m=buildToolCallUpdatePayload({toolCallId:r,toolName:i,outputText:h.join("\n"),rawOutput:d,resourceLinks:g,timestamp:s});this.sendTurnUpdate(t,m)&&(t.assistantMq?.push(m),this.onStreamDelta?.(t,m))}adoptBackgroundRun(t,e){this.logger.debug?.(`[gateway-events] Adopting background run ${e} on session ${t.sessionId} (prev=${t.currentRunId})`),t.currentRunId=e,t.promptDone=!1,this.state.promptsByRunId.set(e,t),t.assistantStreamStartedAt=Date.now(),t.lastStreamActivityTs=Date.now(),t.hasAgentAssistantStream=void 0,t.hasAgentThinkingStream=void 0,t.hasAgentToolStartStream=void 0,t.hasAgentToolResultStream=void 0,t.chatAssistantTextSoFar=void 0,t.agentAssistantTextSoFar=void 0,t.chatReplayDedupKeys?.clear(),t.assistantMq&&!t.assistantMq.closed||(t.assistantMq=new MessageQueue)}handleCronEvent(t){this.transport.sendNotification("_beeos/cron_event",{payload:t});const e=t??{};this.config.agentGatewayUrl&&this.agentFetchFn&&this.reportCronEventToAgentGateway(e),"added"===e.action&&this.maybeBackfillBeeosChannel(e),"finished"===e.action&&"string"==typeof e.summary&&e.summary&&this.publishCronResult(e)}async reportCronEventToAgentGateway(t){if(!this.config.agentGatewayUrl||!this.agentFetchFn)return;const e={...t},s="string"==typeof t.sessionKey?t.sessionKey:void 0;s&&null==e.sessionKey&&(e.sessionKey=s);const n=s?this.state.findSessionByKey(s)?.sessionId:void 0;if(n&&(e.sessionId=n),("string"!=typeof e.name||!e.name)&&"string"==typeof t.jobId&&t.jobId&&this.gatewayRequest)try{const s=await this.gatewayRequest("cron.list",{}),n=s?.jobs;if(Array.isArray(n))for(const s of n)if(isRecord(s)&&s.id===t.jobId&&"string"==typeof s.name&&s.name){e.name=s.name;break}}catch(t){this.logger.debug?.(`[gateway-events] cron.list lookup failed: ${t instanceof Error?t.message:t}`)}const o=`${this.config.agentGatewayUrl}/api/v1/agent/events`;try{await this.agentFetchFn(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"cron",data:e})})}catch(t){this.logger.warn?.(`[gateway-events] event report failed: ${t instanceof Error?t.message:t}`)}}async maybeBackfillBeeosChannel(t){const e="string"==typeof t.jobId?t.jobId:void 0;if(!e)return;if(!this.gatewayRequest)return;if(this.cronChannelCache?.get(e))return;let s;try{const t=await this.gatewayRequest("cron.list",{}),n=t?.jobs;if(Array.isArray(n))for(const t of n){if(!t||"object"!=typeof t)continue;const n=t;if(n.id===e){s=n;break}}}catch(t){return void this.logger.debug?.(`[gateway-events] maybeBackfillBeeosChannel cron.list failed: ${t instanceof Error?t.message:t}`)}if(!s)return;const n="string"==typeof s.description?s.description:"";if(BEEOS_CHANNEL_TAG_RE.test(n)){const t=decodeBeeosChannelId(n);return void(t&&this.setCronChannelCacheLocal(e,t))}if("main"===("string"==typeof s.sessionTarget?s.sessionTarget:void 0))return;const o=isRecord(s.payload)?s.payload:void 0;if("systemEvent"===(o&&"string"==typeof o.kind?o.kind:void 0))return;const a=isRecord(s.delivery)?s.delivery:void 0;if(a&&"none"===a.mode)return;const r="string"==typeof s.sessionKey?s.sessionKey:void 0;if(!r)return void this.logger.debug?.(`[gateway-events] maybeBackfillBeeosChannel: job has no sessionKey job=${e}`);const i=this.state.findSessionByKey(r),l=i?.channelId;if(!l)return void this.logger.debug?.(`[gateway-events] maybeBackfillBeeosChannel: no channelId on ACPSession for sessionKey=${r} job=${e}`);const c=encodeBeeosChannelTag(n,l);try{await this.gatewayRequest("cron.update",{id:e,patch:{description:c}}),this.setCronChannelCacheLocal(e,l),this.logger.info?.(`[gateway-events] backfilled beeos:channel for LLM-created cron job=${e} channel=${l}`)}catch(t){this.logger.warn?.(`[gateway-events] maybeBackfillBeeosChannel cron.update failed: ${t instanceof Error?t.message:t}`)}}setCronChannelCacheLocal(t,e){this.cronChannelCache&&this.cronChannelCache.set(t,e)}async publishCronResult(t){const e=this.getMessageSdk?.();if(!e)return;const s=this.getMsgPrincipalId?.();if(!s)return;const n="string"==typeof t.jobId?t.jobId:void 0;if(!n)return;const o=t.summary;let a=this.cronChannelCache?.get(n);if(!a&&this.gatewayRequest)try{const t=await this.gatewayRequest("cron.list",{}),e=t?.jobs;if(Array.isArray(e))for(const t of e){if(!t||"object"!=typeof t)continue;const e=t;if(e.id===n){a=decodeBeeosChannelId(e.description);break}}}catch(t){this.logger.debug?.(`[gateway-events] cron.list fallback failed: ${t instanceof Error?t.message:t}`)}if(!a)return;const r=randomUUID();try{await e.sendToChannel(a,"agent_reply",{text:o,cron_job_id:n,session_key:t.sessionKey??void 0},{inReplyTo:r}),this.logger.info?.(`[gateway-events] published cron result to channel=${a} job=${n}`)}catch(t){const e=t instanceof Error?t.message:String(t);if(isChannelGoneError(t,e))return this.logger.info?.(`[gateway-events] origin channel gone (session likely deleted), skipping publish: channel=${a} job=${n} err=${e}`),void this.cronChannelCache?.delete(n);this.logger.warn?.(`[gateway-events] publishCronResult failed: ${e}`)}}logHeartbeatSkip(t){const e=previewFilteredText(t.cumulative),s=void 0!==t.delta?previewFilteredText(t.delta):void 0;this.logger.info?.(`[gateway-events] SKIP heartbeat ${t.source} reason=${t.reason} sessionId=${t.sessionId} runId=${t.runId??"n/a"} cumLen=${t.cumulative.length}`+(void 0!==t.delta?` deltaLen=${t.delta.length}`:"")+` cumulative="${e}"`+(void 0!==s?` delta="${s}"`:"")),this.writeObs({component:"gateway-events",domain:"lifecycle",name:"heartbeat_filter_skip",severity:"info",summary:`heartbeat ${t.source} drop (${t.reason})`,payload:{source:t.source,reason:t.reason,sessionId:t.sessionId,runId:t.runId,cumulativeLen:t.cumulative.length,cumulativePreview:e,...void 0!==t.delta?{deltaLen:t.delta.length,deltaPreview:s}:{}}})}}export function isChannelGoneError(t,e){const s=e.toLowerCase();if(s.includes("not found")||s.includes("no such channel")||s.includes("channel does not exist")||s.includes("channel gone")||s.includes("410")||/\b404\b/.test(s))return!0;if(isRecord(t)){const e=t.status??t.statusCode??t.code;if(404===e||410===e)return!0}return!1}
|
|
1
|
+
import{createHash,randomUUID}from"node:crypto";import{Errors}from"../errors/index.js";import{BEEOS_CHANNEL_TAG_RE,decodeBeeosChannelId,encodeBeeosChannelTag}from"./bridge-core.js";import{formatFriendlyError}from"../errors/classify.js";import{stripTransportMetadata,normalizeTransportText,classifyHeartbeatFilter,previewFilteredText}from"../message-filter.js";import{resolveToolResultBlocks}from"./tool-result-payload-strategies.js";import{buildToolCallPayload,buildToolCallUpdatePayload}from"./tool-call-payload-builder.js";import{DEFAULT_STREAM_IDLE_TIMEOUT_MS,DEFAULT_STREAM_STALE_TIMEOUT_MS}from"./types.js";import{MessageQueue}from"../utils/mq.js";function asString(t){if("string"==typeof t){return t.trim()||void 0}}function isRecord(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function normalizeText(t){if("string"==typeof t)return normalizeTransportText(t.replace(/\r\n/g,"\n").replace(/\r/g,"\n"))}function extractResourceLinksFromRawResult(t){if(!isRecord(t)||!Array.isArray(t.files))return;const e=[];for(const s of t.files){if(!isRecord(s))continue;const t=asString(s.uri)??(asString(s.fileId)?`beeos-file://${s.fileId}`:void 0);t&&e.push({uri:t,name:asString(s.name)??"file",...asString(s.mimeType)?{mimeType:asString(s.mimeType)}:{}})}return e.length>0?e:void 0}const DEDUP_HASH_THRESHOLD=256;function dedupKey(t,...e){const s=`${t}:${e.join(":")}`;if(s.length<=256)return s;return`${t}:h:${createHash("sha256").update(s).digest("hex").slice(0,24)}`}function toISO(t){if(!(null==t||t<=0))try{return new Date(t).toISOString()}catch{return}}function resolveToolArgs(t){const e=t.arguments??t.args??t.input;if(isRecord(e))return e;if("string"==typeof e){const t=e.trim();if(t.startsWith("{")||t.startsWith("["))try{return JSON.parse(t)}catch{}}return{}}export function resolveTurnId(t){if(t.currentRunId)return t.currentRunId;const e=t.pendingPromptId;return void 0!==e?"string"==typeof e?`req:${e}`:`req:${String(e)}`:void 0}export function roleFromSessionUpdate(t){const e=t.sessionUpdate;if(e)return"user_message_chunk"===e?"user":"system_message_chunk"===e?"system":e.startsWith("agent_")||e.startsWith("tool_")?"assistant":"history_turn"===e?"user"===t.role?"user":"system"===t.role?"system":"assistant":void 0}export function recordTurnIdForRole(t,e,s){if(!s)return;const n=roleFromSessionUpdate(e);n&&(t.lastTurnIdByRole||(t.lastTurnIdByRole={}),t.lastTurnIdByRole[n]=s)}export class AcpGatewayEvents{state;transport;config;logger;writeObs;completePrompt;failPrompt;schedulePromptTimeout;maybeCompletePromptFromChatState;agentFetchFn;onStreamDelta;getMessageClient;getMsgPrincipalId;gatewayRequest;cronChannelCache;constructor(t){this.state=t.state,this.transport=t.transport,this.config=t.config,this.logger=t.logger,this.writeObs=t.writeObs,this.completePrompt=t.completePrompt,this.failPrompt=t.failPrompt,this.schedulePromptTimeout=t.schedulePromptTimeout,this.maybeCompletePromptFromChatState=t.maybeCompletePromptFromChatState,this.agentFetchFn=t.agentFetch,this.onStreamDelta=t.onStreamDelta,this.getMessageClient=t.getMessageClient,this.getMsgPrincipalId=t.getMsgPrincipalId,this.gatewayRequest=t.gatewayRequest,this.cronChannelCache=t.cronChannelCache}touchStreamActivity(t){t.lastStreamActivityTs=Date.now(),this.resetStreamIdleTimer(t)}resetStreamIdleTimer(t){this.state.clearStreamIdleTimer(t);const e=this.config.streamIdleTimeoutMs??DEFAULT_STREAM_IDLE_TIMEOUT_MS,s=this.config.streamStaleTimeoutMs??DEFAULT_STREAM_STALE_TIMEOUT_MS;t.streamIdleTimer=setTimeout(()=>{if(!t.lastStreamActivityTs)return;const e=Date.now()-t.lastStreamActivityTs;e>s&&(this.logger.warn?.(`[gateway-events] Stream stale timeout sessionId=${t.sessionId} stale=${e}ms`),this.completePrompt(t,"end_turn"))},e),"object"==typeof t.streamIdleTimer&&"unref"in t.streamIdleTimer&&t.streamIdleTimer.unref()}sendTurnUpdate(t,e){const s=resolveTurnId(t);return s&&void 0===e._turnId&&(e._turnId=s),recordTurnIdForRole(t,e,s),!!t.sessionLoadInProgress||this.transport.sendSessionUpdate(t.sessionId,e,{turnId:s})}sendToolCallSpacer(t,e){const s={sessionUpdate:"agent_message_chunk",content:{type:"text",text:"\n"},...e?{timestamp:e}:{}};this.sendTurnUpdate(t,s),t.assistantMq?.push(s),this.onStreamDelta?.(t,s)}resolveToolCallId(t,e,s){const n=asString(e.toolCallId)??asString(e.tool_call_id)??asString(e.callId)??asString(e.id);if(n){const e=this.state.toolCallIdMap.get(n);return e?(t.sessionId&&this.state.toolCallToSessionMap.set(e,t.sessionId),e):(this.state.toolCallIdMap.set(n,n),t.sessionId&&this.state.toolCallToSessionMap.set(n,t.sessionId),n)}const o=`tc_${t.currentRunId??"unknown"}_${this.state.nextToolCallSeq++}`;return t.sessionId&&this.state.toolCallToSessionMap.set(o,t.sessionId),o}handleChatEvent(t){const e=(t.runId?this.state.promptsByRunId.get(t.runId):void 0)??this.state.findSessionByKey(t.sessionKey);if(!e)return;if(!this.state.isCurrentStreamOwner(e,t.runId)){const s=!e.currentRunId&&void 0===e.pendingPromptId;if(!t.runId||!s||this.state.isRunCompleted(t.runId))return;this.adoptBackgroundRun(e,t.runId)}e.sessionId;const s=t.message;if(s){this.touchStreamActivity(e);if("assistant"===s.role){if(!Array.isArray(s.content))return;for(const n of s.content){const o=n;if(!isRecord(o))continue;const a=asString(o.type);if(!a)continue;const r=toISO(s.timestamp);if("thinking"===a){if(e.hasAgentThinkingStream)continue;const t=normalizeText(o.thinking)??normalizeText(o.text);if(!t)continue;const s=dedupKey("chat:thinking",t);if(e.chatReplayDedupKeys.has(s))continue;e.chatReplayDedupKeys.add(s);const n={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:t},...r?{timestamp:r}:{}};this.sendTurnUpdate(e,n)&&(e.assistantMq?.push(n),this.onStreamDelta?.(e,n));continue}if("toolCall"===a){if(this.sendToolCallSpacer(e,r),e.hasAgentToolStartStream)continue;const t=this.resolveToolCallId(e,o,"start"),s=asString(o.name)??asString(o.toolName)??asString(o.tool_name)??"tool",n=resolveToolArgs(o),a=dedupKey("chat:tool_start",t,JSON.stringify(n));if(e.chatReplayDedupKeys.has(a))continue;e.chatReplayDedupKeys.add(a);const i=buildToolCallPayload({toolCallId:t,toolName:s,args:n,timestamp:r});this.sendTurnUpdate(e,i)&&(e.assistantMq?.push(i),this.onStreamDelta?.(e,i));continue}if("toolResult"===a){if(this.sendToolCallSpacer(e,r),e.hasAgentToolResultStream)continue;const t=this.resolveToolCallId(e,o,"result"),s=asString(o.name)??asString(o.toolName)??asString(o.tool_name)??"tool",n=o.result,a=normalizeText(o.text)??normalizeText(o.result)??(isRecord(n)||Array.isArray(n)?JSON.stringify(n,null,2):void 0);if(!a)continue;const i=dedupKey("chat:tool_result",t,a);if(e.chatReplayDedupKeys.has(i))continue;e.chatReplayDedupKeys.add(i);const l=buildToolCallUpdatePayload({toolCallId:t,toolName:s,outputText:a,rawOutput:n,resourceLinks:extractResourceLinksFromRawResult(n),timestamp:r});this.sendTurnUpdate(e,l)&&(e.assistantMq?.push(l),this.onStreamDelta?.(e,l));continue}if("text"===a&&o.text){if(e.hasAgentAssistantStream||e.agentAssistantTextSoFar)continue;const s=stripTransportMetadata(o.text);if(!s)continue;const n=classifyHeartbeatFilter(s);if(n.filtered){this.logHeartbeatSkip({source:"chat-text",reason:n.reason,sessionId:e.sessionId,runId:t.runId,cumulative:s});continue}const a=dedupKey("chat:text",s);if(e.chatReplayDedupKeys.has(a))continue;e.chatReplayDedupKeys.add(a);const i=e.chatAssistantTextSoFar??"";let l;if(e.chatAssistantTextSoFar=s,s.startsWith(i))l=s.slice(i.length);else{if(i.startsWith(s))continue;l=s}if(!l)continue;this.logger.debug?.(`[gateway-events] chat.text delta seq=${t.seq} runId=${t.runId} len=${l.length} prevLen=${i.length}`);const d={sessionUpdate:"agent_message_chunk",content:{type:"text",text:l},...r?{timestamp:r}:{}};this.sendTurnUpdate(e,d),e.assistantMq?.push(d),this.onStreamDelta?.(e,d)}}}}else"delta"===t.state&&this.touchStreamActivity(e);if(this.maybeCompletePromptFromChatState(e,t),!e.promptDone)if("final"===t.state)this.completePrompt(e,t.stopReason||"end_turn");else if("aborted"===t.state||"cancelled"===t.state||"cancel"===t.state)this.completePrompt(e,"cancelled");else if("error"===t.state){const s=t.errorMessage||Errors.AgentError.message;this.failPrompt(e,Errors.AgentError.rpcCode,formatFriendlyError(s))}}handleAgentEvent(t){const e=(t.runId?this.state.promptsByRunId.get(t.runId):void 0)??(t.sessionKey?this.state.findSessionByKey(t.sessionKey):void 0);if(!e)return;if(!this.state.isCurrentStreamOwner(e,t.runId)){const s=!e.currentRunId&&void 0===e.pendingPromptId;if(!t.runId||!s||this.state.isRunCompleted(t.runId))return;this.adoptBackgroundRun(e,t.runId)}t.runId&&e.cronJobId&&!this.state.runIdToCronJobId.has(t.runId)&&this.state.setRunCronJobId(t.runId,e.cronJobId);e.sessionId;this.touchStreamActivity(e);const s=toISO(t.ts),n=t=>{this.sendTurnUpdate(e,t),e.assistantMq?.push(t),this.onStreamDelta?.(e,t)};if("assistant"===t.stream){e.hasAgentAssistantStream=!0;const o=this.state.extractAgentAssistantDelta(e,t.data??{});if(o){const a=normalizeTransportText(o);if(a){const o=e.agentAssistantTextSoFar??a,r=classifyHeartbeatFilter(o);r.filtered?this.logHeartbeatSkip({source:"assistant-delta",reason:r.reason,sessionId:e.sessionId,runId:t.runId,cumulative:o,delta:a}):(this.logger.debug?.(`[gateway-events] agent.assistant delta seq=${t.seq} runId=${t.runId} len=${a.length} source=${t.data?.delta?"delta":"cumulative"}`),n({sessionUpdate:"agent_message_chunk",content:{type:"text",text:a},...s?{timestamp:s}:{}}))}}const a=[],r=t.data;r&&(Array.isArray(r.content)?a.push(...r.content):isRecord(r.content)?a.push(r.content):"string"==typeof r.type&&a.push(r));for(const t of a){if(!isRecord(t))continue;const o=asString(t.type);if("thinking"===o){e.hasAgentThinkingStream=!0;const n=normalizeText(t.thinking)??normalizeText(t.text);if(n){const t={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n},...s?{timestamp:s}:{}};this.sendTurnUpdate(e,t)&&(e.assistantMq?.push(t),this.onStreamDelta?.(e,t))}continue}if("toolCall"===o){this.sendToolCallSpacer(e,s),e.hasAgentToolStartStream=!0;const o=this.resolveToolCallId(e,t,"start"),a=asString(t.name)??asString(t.toolName)??asString(t.tool_name)??"tool",r=resolveToolArgs(t);n(buildToolCallPayload({toolCallId:o,toolName:a,args:r,timestamp:s}));continue}if("toolResult"===o){this.sendToolCallSpacer(e,s),e.hasAgentToolResultStream=!0;const o=this.resolveToolCallId(e,t,"result"),a=asString(t.name)??asString(t.toolName)??asString(t.tool_name)??"tool",r=t.result,i=normalizeText(t.text)??normalizeText(t.result)??(isRecord(r)||Array.isArray(r)?JSON.stringify(r,null,2):void 0);i&&n(buildToolCallUpdatePayload({toolCallId:o,toolName:a,outputText:i,rawOutput:r,resourceLinks:extractResourceLinksFromRawResult(r),timestamp:s}));continue}}}else if("thinking"===t.stream){e.hasAgentThinkingStream=!0;const n=normalizeText(t.data?.delta)??normalizeText(t.data?.text);if(n){const t={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n},...s?{timestamp:s}:{}};this.sendTurnUpdate(e,t)&&(e.assistantMq?.push(t),this.onStreamDelta?.(e,t))}}else if("tool"===t.stream){const o=t.data,a="string"==typeof o?.phase?o.phase:void 0;if("start"===a){this.sendToolCallSpacer(e,s),e.hasAgentToolStartStream=!0;const t=this.resolveToolCallId(e,o,"start"),a=asString(o?.name)??asString(o?.toolName)??asString(o?.tool_name)??"tool",r=resolveToolArgs(o);n(buildToolCallPayload({toolCallId:t,toolName:a,args:r,timestamp:s}))}else if("result"===a)this.sendToolCallSpacer(e,s),e.hasAgentToolResultStream=!0,this.handleToolResult(e,t,s).catch(t=>{this.logger.warn?.(`[gateway-events] Tool result handling failed: ${t instanceof Error?t.message:t}`)});else{const t=o?.toolCall;if(t){this.sendToolCallSpacer(e,s),e.hasAgentToolStartStream=!0;const a=asString(t?.name)??asString(o?.name)??asString(o?.toolName)??"tool",r={...o,...t},i=this.resolveToolCallId(e,r,"start"),l=resolveToolArgs(r);n(buildToolCallPayload({toolCallId:i,toolName:a,args:l,timestamp:s}))}}}else if("lifecycle"===t.stream){const s=t.data,n="string"==typeof s?.phase?s.phase:void 0;if("end"===n)this.completePrompt(e,"end_turn");else if("cancelled"===n||"cancel"===n)this.completePrompt(e,"cancelled");else if("error"===n){const n=s?.error,o=n&&"object"==typeof n?n:void 0,a=("string"==typeof s?.message?s.message:void 0)??("string"==typeof n?n:void 0)??("string"==typeof o?.message?o.message:void 0)??("string"==typeof s?.reason?s.reason:void 0)??(o?JSON.stringify(o):void 0)??"gateway lifecycle error",r=formatFriendlyError(a);this.logger.warn?.(`[gateway-events] lifecycle error runId=${t.runId} sessionKey=${t.sessionKey} message=${a} data=${JSON.stringify(s)}`),this.failPrompt(e,Errors.AgentError.rpcCode,r)}}}async handleToolResult(t,e,s){const n=e.data,o=n?.toolCall,a=("string"==typeof o?.id?o.id:void 0)??("string"==typeof n?.toolCallId?n.toolCallId:void 0),r=(a?this.state.toolCallIdMap.get(a):void 0)??a??`tc_${e.runId}_${e.seq}`,i=("string"==typeof o?.name?o.name:void 0)??("string"==typeof n?.name?n.name:void 0)??"tool",l="string"==typeof n?.text?n.text:void 0,d=a??r,c=n?.result;let u;try{u=await resolveToolResultBlocks({toolCallId:d,toolName:i,rawText:l,rawResult:c})}catch{u=l?[{type:"content",content:{type:"text",text:l}}]:[]}0===u.length&&l&&(u=[{type:"content",content:{type:"text",text:l}}]);const h=[],g=[];for(const t of u)t.content&&("resource_link"===t.content.type&&t.content.uri?g.push({uri:t.content.uri,name:t.content.name??"file",...t.content.mimeType?{mimeType:t.content.mimeType}:{}}):t.content.text&&h.push(t.content.text));const m=buildToolCallUpdatePayload({toolCallId:r,toolName:i,outputText:h.join("\n"),rawOutput:c,resourceLinks:g,timestamp:s});this.sendTurnUpdate(t,m)&&(t.assistantMq?.push(m),this.onStreamDelta?.(t,m))}adoptBackgroundRun(t,e){this.logger.debug?.(`[gateway-events] Adopting background run ${e} on session ${t.sessionId} (prev=${t.currentRunId})`),t.currentRunId=e,t.promptDone=!1,this.state.promptsByRunId.set(e,t);const s=this.state.runIdToCronJobId.get(e);s&&(t.cronJobId=s),t.assistantStreamStartedAt=Date.now(),t.lastStreamActivityTs=Date.now(),t.hasAgentAssistantStream=void 0,t.hasAgentThinkingStream=void 0,t.hasAgentToolStartStream=void 0,t.hasAgentToolResultStream=void 0,t.chatAssistantTextSoFar=void 0,t.agentAssistantTextSoFar=void 0,t.chatReplayDedupKeys?.clear(),t.assistantMq&&!t.assistantMq.closed||(t.assistantMq=new MessageQueue),this.schedulePromptTimeout(t)}handleCronEvent(t){this.transport.sendNotification("_beeos/cron_event",{payload:t});const e=t??{};"string"==typeof e.runId&&"string"==typeof e.jobId&&this.state.setRunCronJobId(e.runId,e.jobId),this.config.agentGatewayUrl&&this.agentFetchFn&&this.reportCronEventToAgentGateway(e),"added"===e.action&&this.maybeBackfillBeeosChannel(e),"finished"===e.action&&"string"==typeof e.summary&&e.summary&&this.publishCronResult(e)}async reportCronEventToAgentGateway(t){if(!this.config.agentGatewayUrl||!this.agentFetchFn)return;const e={...t},s="string"==typeof t.sessionKey?t.sessionKey:void 0;s&&null==e.sessionKey&&(e.sessionKey=s);const n=s?this.state.findSessionByKey(s)?.sessionId:void 0;if(n&&(e.sessionId=n),("string"!=typeof e.name||!e.name)&&"string"==typeof t.jobId&&t.jobId&&this.gatewayRequest)try{const s=await this.gatewayRequest("cron.list",{}),n=s?.jobs;if(Array.isArray(n))for(const s of n)if(isRecord(s)&&s.id===t.jobId&&"string"==typeof s.name&&s.name){e.name=s.name;break}}catch(t){this.logger.debug?.(`[gateway-events] cron.list lookup failed: ${t instanceof Error?t.message:t}`)}const o=`${this.config.agentGatewayUrl}/api/v1/agent/events`;try{await this.agentFetchFn(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"cron",data:e})})}catch(t){this.logger.warn?.(`[gateway-events] event report failed: ${t instanceof Error?t.message:t}`)}}async maybeBackfillBeeosChannel(t){const e="string"==typeof t.jobId?t.jobId:void 0;if(!e)return;if(!this.gatewayRequest)return;if(this.cronChannelCache?.get(e))return;let s;try{const t=await this.gatewayRequest("cron.list",{}),n=t?.jobs;if(Array.isArray(n))for(const t of n){if(!t||"object"!=typeof t)continue;const n=t;if(n.id===e){s=n;break}}}catch(t){return void this.logger.debug?.(`[gateway-events] maybeBackfillBeeosChannel cron.list failed: ${t instanceof Error?t.message:t}`)}if(!s)return;const n="string"==typeof s.description?s.description:"";if(BEEOS_CHANNEL_TAG_RE.test(n)){const t=decodeBeeosChannelId(n);return void(t&&this.setCronChannelCacheLocal(e,t))}if("main"===("string"==typeof s.sessionTarget?s.sessionTarget:void 0))return;const o=isRecord(s.payload)?s.payload:void 0;if("systemEvent"===(o&&"string"==typeof o.kind?o.kind:void 0))return;const a=isRecord(s.delivery)?s.delivery:void 0;if(a&&"none"===a.mode)return;const r="string"==typeof s.sessionKey?s.sessionKey:void 0;if(!r)return void this.logger.debug?.(`[gateway-events] maybeBackfillBeeosChannel: job has no sessionKey job=${e}`);const i=this.state.findSessionByKey(r),l=i?.channelId;if(!l)return void this.logger.debug?.(`[gateway-events] maybeBackfillBeeosChannel: no channelId on ACPSession for sessionKey=${r} job=${e}`);const d=encodeBeeosChannelTag(n,l);try{await this.gatewayRequest("cron.update",{id:e,patch:{description:d}}),this.setCronChannelCacheLocal(e,l),this.logger.info?.(`[gateway-events] backfilled beeos:channel for LLM-created cron job=${e} channel=${l}`)}catch(t){this.logger.warn?.(`[gateway-events] maybeBackfillBeeosChannel cron.update failed: ${t instanceof Error?t.message:t}`)}}setCronChannelCacheLocal(t,e){this.cronChannelCache&&this.cronChannelCache.set(t,e)}async publishCronResult(t){const e=this.getMessageClient?.();if(!e)return;const s=this.getMsgPrincipalId?.();if(!s)return;const n="string"==typeof t.jobId?t.jobId:void 0;if(!n)return;const o=t.summary;let a=this.cronChannelCache?.get(n);if(!a&&this.gatewayRequest)try{const t=await this.gatewayRequest("cron.list",{}),e=t?.jobs;if(Array.isArray(e))for(const t of e){if(!t||"object"!=typeof t)continue;const e=t;if(e.id===n){a=decodeBeeosChannelId(e.description);break}}}catch(t){this.logger.debug?.(`[gateway-events] cron.list fallback failed: ${t instanceof Error?t.message:t}`)}if(!a)return;const r=randomUUID();try{await e.messages.send({conversationId:a,id:r,type:"agent_reply",content:{text:o,cron_job_id:n,session_key:t.sessionKey??void 0}}),this.logger.info?.(`[gateway-events] published cron result to channel=${a} job=${n}`)}catch(t){const e=t instanceof Error?t.message:String(t);if(isChannelGoneError(t,e))return this.logger.info?.(`[gateway-events] origin channel gone (session likely deleted), skipping publish: channel=${a} job=${n} err=${e}`),void this.cronChannelCache?.delete(n);this.logger.warn?.(`[gateway-events] publishCronResult failed: ${e}`)}}logHeartbeatSkip(t){const e=previewFilteredText(t.cumulative),s=void 0!==t.delta?previewFilteredText(t.delta):void 0;this.logger.info?.(`[gateway-events] SKIP heartbeat ${t.source} reason=${t.reason} sessionId=${t.sessionId} runId=${t.runId??"n/a"} cumLen=${t.cumulative.length}`+(void 0!==t.delta?` deltaLen=${t.delta.length}`:"")+` cumulative="${e}"`+(void 0!==s?` delta="${s}"`:"")),this.writeObs({component:"gateway-events",domain:"lifecycle",name:"heartbeat_filter_skip",severity:"info",summary:`heartbeat ${t.source} drop (${t.reason})`,payload:{source:t.source,reason:t.reason,sessionId:t.sessionId,runId:t.runId,cumulativeLen:t.cumulative.length,cumulativePreview:e,...void 0!==t.delta?{deltaLen:t.delta.length,deltaPreview:s}:{}}})}}export function isChannelGoneError(t,e){const s=e.toLowerCase();if(s.includes("not found")||s.includes("no such channel")||s.includes("channel does not exist")||s.includes("channel gone")||s.includes("410")||/\b404\b/.test(s))return!0;if(isRecord(t)){const e=t.status??t.statusCode??t.code;if(404===e||410===e)return!0}return!1}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describe,it,expect,vi}from"vitest";import{AcpGatewayBridgeCore}from"./bridge-core.js";import{AcpGatewaySessionState}from"./session-state.js";import{AcpTransport}from"./transport.js";function makeLogger(){return{info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()}}function makeConfig(){return{agentGatewayUrl:"http://localhost:0",keyFile:"/tmp/key",bridge:{url:"",service:"bridge",shell:{enabled:!1}},gateway:{url:"",token:"",protocol:1,clientId:"c",agentId:"main"},retry:{baseMs:100,maxMs:1e3,maxAttempts:0},log:{enabled:!1,verbose:!1,dir:"/tmp"},promptTimeoutMs:6e4,terminalWsPort:0,terminalWsAllowedOrigins:[],streamIdleTimeoutMs:6e4,streamStaleTimeoutMs:6e4,cronSignalWindowMs:5e3,canvasRelayUrl:"",canvasEnabled:!1,openclawCanvasCompat:!1,messageBus:{enabled:!1,serviceUrl:"",url:"",principalId:"",a2aEnabled:!1}}}function buildCore(){const e=makeLogger(),s=vi.fn(),t=new AcpGatewaySessionState(e),n=vi.fn(),a=new AcpTransport(n,s);return{core:new AcpGatewayBridgeCore({state:t,transport:a,config:makeConfig(),logger:e,writeObs:s,getGateway:()=>null,instanceId:"test-instance"}),state:t,transport:a,logger:e,writeObs:s,sendBridgeMessage:n}}function registerSession(e,s,t={}){const n={sessionId:s,gatewaySessionKey:`agent:main:${s}`,agentId:"main",createdAt:Date.now(),chatReplayDedupKeys:new Set,...t};return e.sessions.set(n.sessionId,n),e.sessionsByGatewayKey.set(n.gatewaySessionKey,n),n}async function callSessionLoad(e,s,t){const n={jsonrpc:"2.0",id:s,method:"session/load",params:{sessionId:t}};await e.handleSessionLoad(n)}function collectEmittedUpdates(e){return e.mock.calls.map(e=>e[0]).filter(e=>"session/update"===e?.method).map(e=>e.params?.update).filter(e=>!!e)}function userChunkTexts(e){return e.filter(e=>"user_message_chunk"===e.sessionUpdate).map(e=>{const s=e.content;return"text"===s?.type?s.text??"":""})}describe("session/load — in-flight user buffer (Plan B)",()=>{it("replays pendingUserTurnUpdates when history has nothing yet (mirrors: prompt sent, OpenClaw not yet persisted)",async()=>{const e=buildCore(),s=registerSession(e.state,"session:inflight-user");s.pendingUserTurnUpdates=[{sessionUpdate:"user_message_chunk",content:{type:"text",text:"hello"},timestamp:(new Date).toISOString()}],await callSessionLoad(e.core,1,s.sessionId);const t=collectEmittedUpdates(e.sendBridgeMessage);expect(userChunkTexts(t)).toEqual(["hello"])}),it("does NOT replay the buffer after handleSessionMessage(role=user) clears it (prevents double-emit with chat.history)",async()=>{const e=buildCore(),s=registerSession(e.state,"session:persisted-user",{lastTurnIdByRole:{user:"req:t1"}});s.pendingUserTurnUpdates=[{sessionUpdate:"user_message_chunk",content:{type:"text",text:"hello"},timestamp:(new Date).toISOString()}];const t={sessionKey:s.gatewaySessionKey,messageId:"a1b2c3d4",message:{role:"user",timestamp:Date.now()}};e.core.handleSessionMessage(t),expect(s.pendingUserTurnUpdates).toEqual([]),e.sendBridgeMessage.mockClear(),await callSessionLoad(e.core,2,s.sessionId);const n=collectEmittedUpdates(e.sendBridgeMessage);expect(userChunkTexts(n)).toEqual([])}),it("cleanupPrompt discards pendingUserTurnUpdates so a stale buffer never outlives the run",async()=>{const e=buildCore(),s=registerSession(e.state,"session:cleanup-buffer");s.pendingUserTurnUpdates=[{sessionUpdate:"user_message_chunk",content:{type:"text",text:"stale"},timestamp:(new Date).toISOString()}],e.core.cleanupPrompt(s),expect(s.pendingUserTurnUpdates).toBeUndefined()})});
|
|
1
|
+
import{describe,it,expect,vi}from"vitest";import{AcpGatewayBridgeCore}from"./bridge-core.js";import{AcpGatewaySessionState}from"./session-state.js";import{AcpTransport}from"./transport.js";function makeLogger(){return{info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()}}function makeConfig(){return{agentGatewayUrl:"http://localhost:0",keyFile:"/tmp/key",bridge:{url:"",service:"bridge",shell:{enabled:!1}},gateway:{url:"",token:"",protocol:1,clientId:"c",agentId:"main"},retry:{baseMs:100,maxMs:1e3,maxAttempts:0},log:{enabled:!1,verbose:!1,dir:"/tmp"},promptTimeoutMs:6e4,terminalWsPort:0,terminalWsAllowedOrigins:[],streamIdleTimeoutMs:6e4,streamStaleTimeoutMs:6e4,cronSignalWindowMs:5e3,cronMaxDurationDefaultMs:3e5,cronMaxDurationCapMs:18e5,canvasRelayUrl:"",canvasEnabled:!1,openclawCanvasCompat:!1,messageBus:{enabled:!1,serviceUrl:"",url:"",principalId:"",a2aEnabled:!1}}}function buildCore(){const e=makeLogger(),s=vi.fn(),t=new AcpGatewaySessionState(e),n=vi.fn(),a=new AcpTransport(n,s);return{core:new AcpGatewayBridgeCore({state:t,transport:a,config:makeConfig(),logger:e,writeObs:s,getGateway:()=>null,instanceId:"test-instance"}),state:t,transport:a,logger:e,writeObs:s,sendBridgeMessage:n}}function registerSession(e,s,t={}){const n={sessionId:s,gatewaySessionKey:`agent:main:${s}`,agentId:"main",createdAt:Date.now(),chatReplayDedupKeys:new Set,...t};return e.sessions.set(n.sessionId,n),e.sessionsByGatewayKey.set(n.gatewaySessionKey,n),n}async function callSessionLoad(e,s,t){const n={jsonrpc:"2.0",id:s,method:"session/load",params:{sessionId:t}};await e.handleSessionLoad(n)}function collectEmittedUpdates(e){return e.mock.calls.map(e=>e[0]).filter(e=>"session/update"===e?.method).map(e=>e.params?.update).filter(e=>!!e)}function userChunkTexts(e){return e.filter(e=>"user_message_chunk"===e.sessionUpdate).map(e=>{const s=e.content;return"text"===s?.type?s.text??"":""})}describe("session/load — in-flight user buffer (Plan B)",()=>{it("replays pendingUserTurnUpdates when history has nothing yet (mirrors: prompt sent, OpenClaw not yet persisted)",async()=>{const e=buildCore(),s=registerSession(e.state,"session:inflight-user");s.pendingUserTurnUpdates=[{sessionUpdate:"user_message_chunk",content:{type:"text",text:"hello"},timestamp:(new Date).toISOString()}],await callSessionLoad(e.core,1,s.sessionId);const t=collectEmittedUpdates(e.sendBridgeMessage);expect(userChunkTexts(t)).toEqual(["hello"])}),it("does NOT replay the buffer after handleSessionMessage(role=user) clears it (prevents double-emit with chat.history)",async()=>{const e=buildCore(),s=registerSession(e.state,"session:persisted-user",{lastTurnIdByRole:{user:"req:t1"}});s.pendingUserTurnUpdates=[{sessionUpdate:"user_message_chunk",content:{type:"text",text:"hello"},timestamp:(new Date).toISOString()}];const t={sessionKey:s.gatewaySessionKey,messageId:"a1b2c3d4",message:{role:"user",timestamp:Date.now()}};e.core.handleSessionMessage(t),expect(s.pendingUserTurnUpdates).toEqual([]),e.sendBridgeMessage.mockClear(),await callSessionLoad(e.core,2,s.sessionId);const n=collectEmittedUpdates(e.sendBridgeMessage);expect(userChunkTexts(n)).toEqual([])}),it("cleanupPrompt discards pendingUserTurnUpdates so a stale buffer never outlives the run",async()=>{const e=buildCore(),s=registerSession(e.state,"session:cleanup-buffer");s.pendingUserTurnUpdates=[{sessionUpdate:"user_message_chunk",content:{type:"text",text:"stale"},timestamp:(new Date).toISOString()}],e.core.cleanupPrompt(s),expect(s.pendingUserTurnUpdates).toBeUndefined()})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describe,it,expect,vi}from"vitest";import{AcpGatewayBridgeCore}from"./bridge-core.js";import{AcpGatewaySessionState}from"./session-state.js";import{AcpTransport}from"./transport.js";import{MessageQueue}from"../utils/mq.js";function makeLogger(){return{info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()}}function makeConfig(){return{agentGatewayUrl:"http://localhost:0",keyFile:"/tmp/key",bridge:{url:"",service:"bridge",shell:{enabled:!1}},gateway:{url:"",token:"",protocol:1,clientId:"c",agentId:"main"},retry:{baseMs:100,maxMs:1e3,maxAttempts:0},log:{enabled:!1,verbose:!1,dir:"/tmp"},promptTimeoutMs:6e4,terminalWsPort:0,terminalWsAllowedOrigins:[],streamIdleTimeoutMs:6e4,streamStaleTimeoutMs:6e4,cronSignalWindowMs:5e3,canvasRelayUrl:"",canvasEnabled:!1,openclawCanvasCompat:!1,messageBus:{enabled:!1,serviceUrl:"",url:"",principalId:"",a2aEnabled:!1}}}function buildCore(){const e=makeLogger(),s=vi.fn(),t=new AcpGatewaySessionState(e),
|
|
1
|
+
import{describe,it,expect,vi}from"vitest";import{AcpGatewayBridgeCore}from"./bridge-core.js";import{AcpGatewaySessionState}from"./session-state.js";import{AcpTransport}from"./transport.js";import{MessageQueue}from"../utils/mq.js";function makeLogger(){return{info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()}}function makeConfig(){return{agentGatewayUrl:"http://localhost:0",keyFile:"/tmp/key",bridge:{url:"",service:"bridge",shell:{enabled:!1}},gateway:{url:"",token:"",protocol:1,clientId:"c",agentId:"main"},retry:{baseMs:100,maxMs:1e3,maxAttempts:0},log:{enabled:!1,verbose:!1,dir:"/tmp"},promptTimeoutMs:6e4,terminalWsPort:0,terminalWsAllowedOrigins:[],streamIdleTimeoutMs:6e4,streamStaleTimeoutMs:6e4,cronSignalWindowMs:5e3,cronMaxDurationDefaultMs:3e5,cronMaxDurationCapMs:18e5,canvasRelayUrl:"",canvasEnabled:!1,openclawCanvasCompat:!1,messageBus:{enabled:!1,serviceUrl:"",url:"",principalId:"",a2aEnabled:!1}}}function buildCore(){const e=makeLogger(),s=vi.fn(),t=new AcpGatewaySessionState(e),a=vi.fn(),n=new AcpTransport(a,s);return{core:new AcpGatewayBridgeCore({state:t,transport:n,config:makeConfig(),logger:e,writeObs:s,getGateway:()=>null,instanceId:"test-instance"}),state:t,transport:n,logger:e,writeObs:s,sendBridgeMessage:a}}function registerSession(e,s,t={}){const a={sessionId:s,gatewaySessionKey:`agent:main:${s}`,agentId:"main",createdAt:Date.now(),chatReplayDedupKeys:new Set,...t};return e.sessions.set(a.sessionId,a),e.sessionsByGatewayKey.set(a.gatewaySessionKey,a),a}async function callSessionLoad(e,s,t){const a={jsonrpc:"2.0",id:s,method:"session/load",params:{sessionId:t}};await e.handleSessionLoad(a)}function collectEmittedUpdates(e){return e.mock.calls.map(e=>e[0]).filter(e=>"session/update"===e?.method).map(e=>e.params?.update)}function collectResults(e){return e.mock.calls.map(e=>e[0]).filter(e=>void 0!==e?.result)}describe("session/load — KISS contract",()=>{it("ACKs immediately (< 50ms) even when assistantMq has buffered chunks (regression: Bug-AW hang)",async()=>{const e=buildCore(),s=registerSession(e.state,"session:fast-ack"),t=new MessageQueue;for(let e=0;e<5;e++)t.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`chunk-${e}`}});s.assistantMq=t;const a=Date.now();await callSessionLoad(e.core,1,s.sessionId);const n=Date.now()-a;expect(n).toBeLessThan(50);const o=collectResults(e.sendBridgeMessage);expect(o).toHaveLength(1),expect(o[0].result).toMatchObject({sessionId:s.sessionId})}),it("emits mq snapshot exactly once — subsequent pushes are NOT replayed as part of this load",async()=>{const e=buildCore(),s=registerSession(e.state,"session:snapshot-once"),t=new MessageQueue;t.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"first"}}),t.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"second"}}),s.assistantMq=t,await callSessionLoad(e.core,1,s.sessionId),t.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"post-load"}});const a=collectEmittedUpdates(e.sendBridgeMessage).filter(e=>"agent_message_chunk"===e?.sessionUpdate).map(e=>e.content.text);expect(a).toEqual(["first","second"])}),it("emits no stream updates when assistantMq is undefined — just ACKs",async()=>{const e=buildCore(),s=registerSession(e.state,"session:no-mq");s.assistantMq=void 0,await callSessionLoad(e.core,1,s.sessionId);const t=collectEmittedUpdates(e.sendBridgeMessage);expect(t.filter(e=>"agent_message_chunk"===e?.sessionUpdate)).toHaveLength(0);const a=collectResults(e.sendBridgeMessage);expect(a).toHaveLength(1)}),it("skips snapshot when assistantMq is closed — closed mq means history already covers the turn",async()=>{const e=buildCore(),s=registerSession(e.state,"session:closed-mq"),t=new MessageQueue;t.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"should-be-skipped"}}),t.close(),s.assistantMq=t,await callSessionLoad(e.core,1,s.sessionId);const a=collectEmittedUpdates(e.sendBridgeMessage);expect(a.filter(e=>"agent_message_chunk"===e?.sessionUpdate)).toHaveLength(0);const n=collectResults(e.sendBridgeMessage);expect(n).toHaveLength(1)}),it("rejects a load with missing sessionId via sendAcpError (no session touch)",async()=>{const e=buildCore();await e.core.handleSessionLoad({jsonrpc:"2.0",id:1,method:"session/load",params:{}});const s=e.sendBridgeMessage.mock.calls.map(e=>e[0]).filter(e=>void 0!==e?.error);expect(s).toHaveLength(1),expect(s[0].error.data?.param).toBe("sessionId")})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{MessageQueue}from"../utils/mq.js";const MAX_TOOL_CALL_MAP_ENTRIES=5e3,MAX_COMPLETED_RUN_IDS=200;export class AcpGatewaySessionState{sessions=new Map;promptsByRunId=new Map;promptsByGatewayRequestId=new Map;sessionsByGatewayKey=new Map;toolCallIdMap=new Map;toolCallToSessionMap=new Map;nextToolCallSeq=0;completedRunIds=new Set;lastActiveSessionId;sessionGcTimer=null;MAX_IDLE_SESSION_MS=864e5;
|
|
1
|
+
import{MessageQueue}from"../utils/mq.js";const MAX_TOOL_CALL_MAP_ENTRIES=5e3,MAX_COMPLETED_RUN_IDS=200;export class AcpGatewaySessionState{sessions=new Map;promptsByRunId=new Map;promptsByGatewayRequestId=new Map;sessionsByGatewayKey=new Map;toolCallIdMap=new Map;toolCallToSessionMap=new Map;runIdToCronJobId=new Map;nextToolCallSeq=0;completedRunIds=new Set;lastActiveSessionId;sessionGcTimer=null;MAX_IDLE_SESSION_MS=864e5;EXTERNAL_SESSION_IDLE_MS=3e5;SESSION_GC_INTERVAL_MS=3e5;logger;constructor(s){this.logger=s}findSessionByKey(s){return this.sessionsByGatewayKey.get(s)}resolveSessionFromParams(s){const e="string"==typeof s?.sessionId?s.sessionId:void 0;if(e)return this.sessions.get(e)}isCurrentStreamOwner(s,e){return!e||!!s.currentRunId&&e===s.currentRunId}markRunCompleted(s){if(this.completedRunIds.add(s),this.completedRunIds.size>200){const s=this.completedRunIds.values().next().value;s&&this.completedRunIds.delete(s)}}isRunCompleted(s){return this.completedRunIds.has(s)}setRunCronJobId(s,e){if(this.runIdToCronJobId.set(s,e),this.runIdToCronJobId.size>400){const s=this.runIdToCronJobId.keys().next().value;void 0!==s&&this.runIdToCronJobId.delete(s)}}clearPromptTimeout(s){s.promptTimeoutTimer&&(clearTimeout(s.promptTimeoutTimer),s.promptTimeoutTimer=void 0)}clearStreamIdleTimer(s){s.streamIdleTimer&&(clearTimeout(s.streamIdleTimer),s.streamIdleTimer=void 0)}resetForNewRun(s,e,t){this.clearStreamIdleTimer(s),s.currentRunId&&(this.promptsByRunId.delete(s.currentRunId),this.runIdToCronJobId.delete(s.currentRunId)),s.gatewayRequestId&&this.promptsByGatewayRequestId.delete(s.gatewayRequestId),s.currentRunId=void 0,s.gatewayRequestId=void 0,s.assistantMq&&!s.assistantMq.closed&&(this.logger.warn?.(`[session-state] resetForNewRun discarding stale assistantMq sessionId=${e}`),s.assistantMq.close()),s.assistantMq=new MessageQueue,s.pendingUserTurnUpdates=[],s.chatReplayDedupKeys.clear(),s.hasAgentAssistantStream=!1,s.hasAgentThinkingStream=!1,s.hasAgentToolStartStream=!1,s.hasAgentToolResultStream=!1,s.chatAssistantTextSoFar=void 0,s.agentAssistantTextSoFar=void 0,s.cronJobId=void 0,s.promptDone=!1,t.resetSessionUpdateCount(e),this.enforceToolCallMapLimits()}enforceToolCallMapLimits(){if(this.toolCallIdMap.size>5e3){const s=this.toolCallIdMap.size-5e3;let e=0;for(const t of this.toolCallIdMap.keys()){if(e>=s)break;this.toolCallToSessionMap.delete(this.toolCallIdMap.get(t)),this.toolCallIdMap.delete(t),e++}}if(this.toolCallToSessionMap.size>5e3){const s=this.toolCallToSessionMap.size-5e3;let e=0;for(const t of this.toolCallToSessionMap.keys()){if(e>=s)break;this.toolCallToSessionMap.delete(t),e++}}}extractAgentAssistantDelta(s,e){const t=(s.chatAssistantTextSoFar??"").length;if(e.delta){const o=s.agentAssistantTextSoFar??"",i=o+e.delta;if(s.agentAssistantTextSoFar=i,t>0&&o.length<t){if(i.length<=t)return;return i.slice(t)}return e.delta}const o=e.text;if(!o)return;const i=s.agentAssistantTextSoFar??"";s.agentAssistantTextSoFar=o;const n=Math.max(i.length,t);if(!(o.length<=n)){if(o.startsWith(i)||0===n)return o.slice(n)||void 0;if(!i.startsWith(o))return o}}startSessionGc(s,e){this.sessionGcTimer=setInterval(()=>this.gcSessions(s,e),this.SESSION_GC_INTERVAL_MS),"object"==typeof this.sessionGcTimer&&"unref"in this.sessionGcTimer&&this.sessionGcTimer.unref()}gcSessions(s,e){const t=Date.now();let o=0;for(const[i,n]of this.sessions){if(void 0!==n.pendingPromptId)continue;const a=n.lastStreamActivityTs??n.createdAt,r=n.gatewaySessionKey;a<t-(r.includes(":a2a:")||r.includes(":mcp:")||r.includes(":openapi:")?this.EXTERNAL_SESSION_IDLE_MS:this.MAX_IDLE_SESSION_MS)&&(s(n),e?.(n),this.sessions.delete(i),this.sessionsByGatewayKey.delete(n.gatewaySessionKey),o++)}const i=new Set(Array.from(this.sessions.values()).map(s=>s.sessionId));for(const[s,e]of this.toolCallToSessionMap)i.has(e)||this.toolCallToSessionMap.delete(s);for(const[s,e]of this.toolCallIdMap)this.toolCallToSessionMap.has(e)||this.toolCallIdMap.delete(s);o>0&&(this.lastActiveSessionId&&!this.sessions.has(this.lastActiveSessionId)&&(this.lastActiveSessionId=void 0),this.logger.debug?.(`[session-state] GC evicted ${o} idle sessions, remaining=${this.sessions.size}`))}destroy(){this.sessionGcTimer&&(clearInterval(this.sessionGcTimer),this.sessionGcTimer=null);for(const s of this.sessions.values())this.clearPromptTimeout(s),this.clearStreamIdleTimer(s),s.assistantMq?.close();this.promptsByRunId.clear(),this.promptsByGatewayRequestId.clear(),this.runIdToCronJobId.clear(),this.completedRunIds.clear(),this.toolCallIdMap.clear(),this.toolCallToSessionMap.clear(),this.sessionsByGatewayKey.clear(),this.sessions.clear(),this.lastActiveSessionId=void 0}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describe,it,expect,beforeEach,vi}from"vitest";import{AcpGatewaySessionState}from"./session-state.js";import{MessageQueue}from"../utils/mq.js";function makeSession(e,s){return{sessionId:e,gatewaySessionKey:s??`agent:main:${e}`,agentId:"main",createdAt:Date.now(),chatReplayDedupKeys:new Set}}describe("AcpGatewaySessionState",()=>{let e;const s={info:vi.fn(),warn:vi.fn(),debug:vi.fn()};beforeEach(()=>{s.info.mockClear(),s.warn.mockClear(),s.debug.mockClear(),e=new AcpGatewaySessionState(s)}),it("should store and find sessions by key",()=>{const s=makeSession("s1","agent:main:abc");e.sessions.set("s1",s),e.sessionsByGatewayKey.set("agent:main:abc",s),expect(e.findSessionByKey("agent:main:abc")).toBe(s),expect(e.findSessionByKey("nonexistent")).toBeUndefined()}),describe("enforceToolCallMapLimits",()=>{it("should evict oldest entries when exceeding hard cap",()=>{for(let s=0;s<5010;s++)e.toolCallIdMap.set(`gw-${s}`,`acp-${s}`);expect(e.toolCallIdMap.size).toBe(5010),e.enforceToolCallMapLimits(),expect(e.toolCallIdMap.size).toBe(5e3),expect(e.toolCallIdMap.has("gw-0")).toBe(!1),expect(e.toolCallIdMap.has("gw-9")).toBe(!1),expect(e.toolCallIdMap.has("gw-5009")).toBe(!0)}),it("should not evict when under limit",()=>{e.toolCallIdMap.set("a","b"),e.enforceToolCallMapLimits(),expect(e.toolCallIdMap.size).toBe(1)})}),describe("resetForNewRun",()=>{it("should clear run-specific state and enforce limits",()=>{const s=makeSession("s1");s.currentRunId="old-run",s.promptDone=!0,s.chatReplayDedupKeys.add("old"),e.sessions.set("s1",s);const t={resetSessionUpdateCount:vi.fn(),sendSessionUpdate:vi.fn(),sendResult:vi.fn(),sendAcpError:vi.fn(),sendNotification:vi.fn()};e.resetForNewRun(s,"s1",t),expect(s.currentRunId).toBeUndefined(),expect(s.chatReplayDedupKeys.size).toBe(0),expect(s.promptDone).toBe(!1),expect(t.resetSessionUpdateCount).toHaveBeenCalledWith("s1")}),it("should warn and discard a stale open assistantMq left behind by a prior run",()=>{const t=makeSession("s1"),a=new MessageQueue;a.push({sessionUpdate:"agent_message_chunk"}),t.assistantMq=a;const n={resetSessionUpdateCount:vi.fn()};e.resetForNewRun(t,"s1",n),expect(s.warn).toHaveBeenCalledWith(expect.stringContaining("discarding stale assistantMq")),expect(a.closed).toBe(!0),expect(t.assistantMq).toBeDefined(),expect(t.assistantMq).not.toBe(a),expect(t.assistantMq?.closed).toBe(!1),expect(t.assistantMq?.peek(0).length).toBe(0)}),it("should not warn when assistantMq was already closed by session.message",()=>{const t=makeSession("s1"),a=new MessageQueue;a.close(),t.assistantMq=a;const n={resetSessionUpdateCount:vi.fn()};e.resetForNewRun(t,"s1",n),expect(s.warn).not.toHaveBeenCalled(),expect(t.assistantMq).not.toBe(a),expect(t.assistantMq?.closed).toBe(!1)}),it("should reset hasAgent*Stream flags so the next run starts clean",()=>{const s=makeSession("s1");s.hasAgentAssistantStream=!0,s.hasAgentThinkingStream=!0,s.hasAgentToolStartStream=!0,s.hasAgentToolResultStream=!0,s.chatAssistantTextSoFar="stale",s.agentAssistantTextSoFar="stale";const t={resetSessionUpdateCount:vi.fn()};e.resetForNewRun(s,"s1",t),expect(s.hasAgentAssistantStream).toBe(!1),expect(s.hasAgentThinkingStream).toBe(!1),expect(s.hasAgentToolStartStream).toBe(!1),expect(s.hasAgentToolResultStream).toBe(!1),expect(s.chatAssistantTextSoFar).toBeUndefined(),expect(s.agentAssistantTextSoFar).toBeUndefined()})}),describe("session GC",()=>{it("should clean up expired sessions",()=>{vi.useFakeTimers();const s=makeSession("expired");s.createdAt=Date.now()-9e7,e.sessions.set("expired",s),e.sessionsByGatewayKey.set(s.gatewaySessionKey,s);const t=vi.fn(),a=vi.fn();e.startSessionGc(t,a),vi.advanceTimersByTime(300100),expect(e.sessions.has("expired")).toBe(!1),expect(t).toHaveBeenCalled(),expect(a).toHaveBeenCalled(),e.destroy(),vi.useRealTimers()})})});
|
|
1
|
+
import{describe,it,expect,beforeEach,vi}from"vitest";import{AcpGatewaySessionState}from"./session-state.js";import{MessageQueue}from"../utils/mq.js";function makeSession(e,s){return{sessionId:e,gatewaySessionKey:s??`agent:main:${e}`,agentId:"main",createdAt:Date.now(),chatReplayDedupKeys:new Set}}describe("AcpGatewaySessionState",()=>{let e;const s={info:vi.fn(),warn:vi.fn(),debug:vi.fn()};beforeEach(()=>{s.info.mockClear(),s.warn.mockClear(),s.debug.mockClear(),e=new AcpGatewaySessionState(s)}),it("should store and find sessions by key",()=>{const s=makeSession("s1","agent:main:abc");e.sessions.set("s1",s),e.sessionsByGatewayKey.set("agent:main:abc",s),expect(e.findSessionByKey("agent:main:abc")).toBe(s),expect(e.findSessionByKey("nonexistent")).toBeUndefined()}),describe("enforceToolCallMapLimits",()=>{it("should evict oldest entries when exceeding hard cap",()=>{for(let s=0;s<5010;s++)e.toolCallIdMap.set(`gw-${s}`,`acp-${s}`);expect(e.toolCallIdMap.size).toBe(5010),e.enforceToolCallMapLimits(),expect(e.toolCallIdMap.size).toBe(5e3),expect(e.toolCallIdMap.has("gw-0")).toBe(!1),expect(e.toolCallIdMap.has("gw-9")).toBe(!1),expect(e.toolCallIdMap.has("gw-5009")).toBe(!0)}),it("should not evict when under limit",()=>{e.toolCallIdMap.set("a","b"),e.enforceToolCallMapLimits(),expect(e.toolCallIdMap.size).toBe(1)})}),describe("resetForNewRun",()=>{it("should clear run-specific state and enforce limits",()=>{const s=makeSession("s1");s.currentRunId="old-run",s.promptDone=!0,s.chatReplayDedupKeys.add("old"),e.sessions.set("s1",s);const t={resetSessionUpdateCount:vi.fn(),sendSessionUpdate:vi.fn(),sendResult:vi.fn(),sendAcpError:vi.fn(),sendNotification:vi.fn()};e.resetForNewRun(s,"s1",t),expect(s.currentRunId).toBeUndefined(),expect(s.chatReplayDedupKeys.size).toBe(0),expect(s.promptDone).toBe(!1),expect(t.resetSessionUpdateCount).toHaveBeenCalledWith("s1")}),it("should warn and discard a stale open assistantMq left behind by a prior run",()=>{const t=makeSession("s1"),a=new MessageQueue;a.push({sessionUpdate:"agent_message_chunk"}),t.assistantMq=a;const n={resetSessionUpdateCount:vi.fn()};e.resetForNewRun(t,"s1",n),expect(s.warn).toHaveBeenCalledWith(expect.stringContaining("discarding stale assistantMq")),expect(a.closed).toBe(!0),expect(t.assistantMq).toBeDefined(),expect(t.assistantMq).not.toBe(a),expect(t.assistantMq?.closed).toBe(!1),expect(t.assistantMq?.peek(0).length).toBe(0)}),it("should not warn when assistantMq was already closed by session.message",()=>{const t=makeSession("s1"),a=new MessageQueue;a.close(),t.assistantMq=a;const n={resetSessionUpdateCount:vi.fn()};e.resetForNewRun(t,"s1",n),expect(s.warn).not.toHaveBeenCalled(),expect(t.assistantMq).not.toBe(a),expect(t.assistantMq?.closed).toBe(!1)}),it("should reset hasAgent*Stream flags so the next run starts clean",()=>{const s=makeSession("s1");s.hasAgentAssistantStream=!0,s.hasAgentThinkingStream=!0,s.hasAgentToolStartStream=!0,s.hasAgentToolResultStream=!0,s.chatAssistantTextSoFar="stale",s.agentAssistantTextSoFar="stale";const t={resetSessionUpdateCount:vi.fn()};e.resetForNewRun(s,"s1",t),expect(s.hasAgentAssistantStream).toBe(!1),expect(s.hasAgentThinkingStream).toBe(!1),expect(s.hasAgentToolStartStream).toBe(!1),expect(s.hasAgentToolResultStream).toBe(!1),expect(s.chatAssistantTextSoFar).toBeUndefined(),expect(s.agentAssistantTextSoFar).toBeUndefined()})}),describe("session GC",()=>{it("should clean up expired sessions",()=>{vi.useFakeTimers();const s=makeSession("expired");s.createdAt=Date.now()-9e7,e.sessions.set("expired",s),e.sessionsByGatewayKey.set(s.gatewaySessionKey,s);const t=vi.fn(),a=vi.fn();e.startSessionGc(t,a),vi.advanceTimersByTime(300100),expect(e.sessions.has("expired")).toBe(!1),expect(t).toHaveBeenCalled(),expect(a).toHaveBeenCalled(),e.destroy(),vi.useRealTimers()}),it.each([["a2a","agent:bot:a2a:ch-X"],["mcp","agent:bot:mcp:ch-X"],["openapi","agent:bot:openapi:ch-X"]])("should evict %s session after EXTERNAL_SESSION_IDLE_MS (5min)",(s,t)=>{vi.useFakeTimers();const a=makeSession("ext",t);a.createdAt=Date.now()-36e4,e.sessions.set("ext",a),e.sessionsByGatewayKey.set(t,a);const n=vi.fn();e.startSessionGc(n),vi.advanceTimersByTime(e.SESSION_GC_INTERVAL_MS+100),expect(e.sessions.has("ext")).toBe(!1),expect(n).toHaveBeenCalled(),e.destroy(),vi.useRealTimers()}),it("should KEEP an interactive session past the external TTL window",()=>{vi.useFakeTimers();const s=makeSession("interactive","agent:bot:s-user-1");s.createdAt=Date.now()-36e4,e.sessions.set("interactive",s),e.sessionsByGatewayKey.set(s.gatewaySessionKey,s);const t=vi.fn();e.startSessionGc(t),vi.advanceTimersByTime(e.SESSION_GC_INTERVAL_MS+100),expect(e.sessions.has("interactive")).toBe(!0),expect(t).not.toHaveBeenCalled(),e.destroy(),vi.useRealTimers()})})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describe,expect,it,vi}from"vitest";import{ACPServer}from"./acp-server.js";const gatewayMock=vi.hoisted(()=>({instances:[]}));function makeConfig(){return{agentGatewayUrl:"https://agent-gw.example.test",keyFile:"/tmp/test.key",bridge:{url:"wss://bridge.example.test",service:"acp",shell:{enabled:!1}},gateway:{url:"ws://127.0.0.1:18789",token:"test-token",protocol:3,clientId:"test-client",agentId:"main"},retry:{baseMs:1,maxMs:10,maxAttempts:0},log:{enabled:!1,verbose:!1,dir:"/tmp"},promptTimeoutMs:1e3,terminalWsPort:0,terminalWsAllowedOrigins:[],streamIdleTimeoutMs:1e3,streamStaleTimeoutMs:1e3,cronSignalWindowMs:1e3,canvasRelayUrl:"",canvasEnabled:!1,openclawCanvasCompat:!1,messageBus:{enabled:!1,serviceUrl:"",url:"",principalId:"",a2aEnabled:!1}}}vi.mock("./gateway-client.js",()=>({GatewayClient:class{connected=!1;request=vi.fn();handlers=new Map;constructor(){gatewayMock.instances.push(this)}get isConnected(){return this.connected}on(e,t){const n=this.handlers.get(e)??[];return n.push(t),this.handlers.set(e,n),this}async start(){}stop(){this.connected=!1}emit(e,t){for(const n of this.handlers.get(e)??[])n(t)}}})),describe("ACPServer agent sync recovery",()=>{it("retries agent sync when OpenClaw Gateway reconnects after initial wait-gateway failure",async()=>{gatewayMock.instances.length=0;let e=!1;const t=vi.fn(async()=>new Response(JSON.stringify({created:1,updated:0,deactivated:0,data:[{id:"platform-main",instanceId:"inst_test",name:"main",displayName:"main",description:"Main",version:"0.1.0",avatarUrl:"",status:"active"}]}),{status:200,headers:{"Content-Type":"application/json"}})),n={info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()},a=new ACPServer(makeConfig(),n,void 0,t,"inst_test");await a.connectGateway();const s=gatewayMock.instances[0];s.request.mockImplementation(async t=>{if(!e)throw new Error("Not connected to Gateway");if("agents.list"===t)return{defaultId:"main",mainKey:"main",scope:"test",agents:[{id:"main",name:"Main"}]};if("skills.status"===t)return{skills:[]};if("cron.list"===t)return{jobs:[]};throw new Error(`unexpected method: ${t}`)}),a.client={readyState:1},await a.tryAgentSync(),expect(t).not.toHaveBeenCalled(),expect(n.info).toHaveBeenCalledWith("[acp-server] agent sync waiting for OpenClaw Gateway connection"),e=!0,s.connected=!0,s.emit("connected"),await vi.waitFor(()=>expect(t).toHaveBeenCalledTimes(1)),expect(t).toHaveBeenCalledWith(new URL("/api/v1/agents/sync","https://agent-gw.example.test"),expect.objectContaining({method:"POST"})),expect(n.info).toHaveBeenCalledWith(expect.stringContaining("[acp-server] agent mapping loaded: main"))})});
|
|
1
|
+
import{describe,expect,it,vi}from"vitest";import{ACPServer}from"./acp-server.js";const gatewayMock=vi.hoisted(()=>({instances:[]}));function makeConfig(){return{agentGatewayUrl:"https://agent-gw.example.test",keyFile:"/tmp/test.key",bridge:{url:"wss://bridge.example.test",service:"acp",shell:{enabled:!1}},gateway:{url:"ws://127.0.0.1:18789",token:"test-token",protocol:3,clientId:"test-client",agentId:"main"},retry:{baseMs:1,maxMs:10,maxAttempts:0},log:{enabled:!1,verbose:!1,dir:"/tmp"},promptTimeoutMs:1e3,terminalWsPort:0,terminalWsAllowedOrigins:[],streamIdleTimeoutMs:1e3,streamStaleTimeoutMs:1e3,cronSignalWindowMs:1e3,cronMaxDurationDefaultMs:3e5,cronMaxDurationCapMs:18e5,canvasRelayUrl:"",canvasEnabled:!1,openclawCanvasCompat:!1,messageBus:{enabled:!1,serviceUrl:"",url:"",principalId:"",a2aEnabled:!1}}}vi.mock("./gateway-client.js",()=>({GatewayClient:class{connected=!1;request=vi.fn();handlers=new Map;constructor(){gatewayMock.instances.push(this)}get isConnected(){return this.connected}on(e,t){const n=this.handlers.get(e)??[];return n.push(t),this.handlers.set(e,n),this}async start(){}stop(){this.connected=!1}emit(e,t){for(const n of this.handlers.get(e)??[])n(t)}}})),describe("ACPServer agent sync recovery",()=>{it("retries agent sync when OpenClaw Gateway reconnects after initial wait-gateway failure",async()=>{gatewayMock.instances.length=0;let e=!1;const t=vi.fn(async()=>new Response(JSON.stringify({created:1,updated:0,deactivated:0,data:[{id:"platform-main",instanceId:"inst_test",name:"main",displayName:"main",description:"Main",version:"0.1.0",avatarUrl:"",status:"active"}]}),{status:200,headers:{"Content-Type":"application/json"}})),n={info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()},a=new ACPServer(makeConfig(),n,void 0,t,"inst_test");await a.connectGateway();const s=gatewayMock.instances[0];s.request.mockImplementation(async t=>{if(!e)throw new Error("Not connected to Gateway");if("agents.list"===t)return{defaultId:"main",mainKey:"main",scope:"test",agents:[{id:"main",name:"Main"}]};if("skills.status"===t)return{skills:[]};if("cron.list"===t)return{jobs:[]};throw new Error(`unexpected method: ${t}`)}),a.client={readyState:1},await a.tryAgentSync(),expect(t).not.toHaveBeenCalled(),expect(n.info).toHaveBeenCalledWith("[acp-server] agent sync waiting for OpenClaw Gateway connection"),e=!0,s.connected=!0,s.emit("connected"),await vi.waitFor(()=>expect(t).toHaveBeenCalledTimes(1)),expect(t).toHaveBeenCalledWith(new URL("/api/v1/agents/sync","https://agent-gw.example.test"),expect.objectContaining({method:"POST"})),expect(n.info).toHaveBeenCalledWith(expect.stringContaining("[acp-server] agent mapping loaded: main"))})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describe,expect,it,vi}from"vitest";import{ACPServer}from"./acp-server.js";const bridgeMock=vi.hoisted(()=>({instances:[],closeImpl:vi.fn(async e=>{})}));function makeConfig(){return{agentGatewayUrl:"https://agent-gw.example.test",keyFile:"/tmp/test.key",bridge:{url:"wss://bridge.example.test",service:"acp",shell:{enabled:!1}},gateway:{url:"ws://127.0.0.1:18789",token:"test-token",protocol:3,clientId:"test-client",agentId:"main"},retry:{baseMs:1,maxMs:10,maxAttempts:0},log:{enabled:!1,verbose:!1,dir:"/tmp"},promptTimeoutMs:1e3,terminalWsPort:0,terminalWsAllowedOrigins:[],streamIdleTimeoutMs:1e3,streamStaleTimeoutMs:1e3,cronSignalWindowMs:1e3,canvasRelayUrl:"",canvasEnabled:!1,openclawCanvasCompat:!1,messageBus:{enabled:!1,serviceUrl:"",url:"",principalId:"",a2aEnabled:!1}}}function makeLogger(){return{info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()}}vi.mock("@beeos-ai/bridge-client",()=>({BridgeClient:class{state="connected";send=vi.fn(()=>Promise.reject(new Error("ws closing")));connect=vi.fn(async()=>{});close=vi.fn(e=>bridgeMock.closeImpl(e));listeners=new Map;constructor(){bridgeMock.instances.push(this)}on(e,t){const n=this.listeners.get(e)??[];return n.push(t),this.listeners.set(e,n),this}emit(e,...t){for(const n of this.listeners.get(e)??[])n(...t)}}})),vi.mock("./gateway-client.js",()=>({GatewayClient:class{get isConnected(){return!0}on(e,t){return this}removeAllListeners(){return this}async start(){}stop(){}request(){return Promise.resolve({})}agentSend(){return Promise.resolve({})}}})),describe("ACPServer bridge shim",()=>{it("handles BridgeClient.send rejection without creating an unhandled rejection",async()=>{bridgeMock.instances.length=0,bridgeMock.closeImpl.mockReset(),bridgeMock.closeImpl.mockImplementation(async()=>{});const e=vi.fn();process.once("unhandledRejection",e);const t=makeLogger(),n=new ACPServer(makeConfig(),t);await n.start(),n.sendBridgeMessage({jsonrpc:"2.0",method:"session/update",params:{}}),await new Promise(e=>setImmediate(e)),process.removeListener("unhandledRejection",e),expect(bridgeMock.instances[0]?.send).toHaveBeenCalledTimes(1),expect(t.warn).toHaveBeenCalledWith("[acp-server] bridge.send failed: ws closing"),expect(e).not.toHaveBeenCalled()})}),describe("ACPServer.stop() bridge teardown",()=>{it("closes the bridge instance even when the ACP-proxy client has already disconnected",async()=>{bridgeMock.instances.length=0,bridgeMock.closeImpl.mockReset(),bridgeMock.closeImpl.mockImplementation(async()=>{});const e=makeLogger(),t=new ACPServer(makeConfig(),e);await t.start(),t.client=null,expect(t.bridgeInstance).not.toBeNull(),await t.stop(),expect(bridgeMock.instances[0]?.close).toHaveBeenCalledTimes(1),expect(t.bridgeInstance).toBeNull()}),it("clears bridgeInstance even when bridge.close() rejects",async()=>{bridgeMock.instances.length=0,bridgeMock.closeImpl.mockReset(),bridgeMock.closeImpl.mockImplementation(async()=>{throw new Error("simulated SDK close failure")});const e=makeLogger(),t=new ACPServer(makeConfig(),e);await t.start(),await expect(t.stop()).resolves.toBeUndefined(),expect(t.bridgeInstance).toBeNull(),expect(e.debug).toHaveBeenCalledWith(expect.stringContaining("bridge.close failed during stop"))}),it("ignores events from a stale BridgeClient after stop()",async()=>{bridgeMock.instances.length=0,bridgeMock.closeImpl.mockReset(),bridgeMock.closeImpl.mockImplementation(async()=>{});const e=makeLogger(),t=new ACPServer(makeConfig(),e);await t.start();const n=bridgeMock.instances[0];expect(n).toBeDefined(),await t.stop(),e.warn.mockClear(),n.emit("disconnected","code=1006"),expect(e.warn).not.toHaveBeenCalled(),expect(bridgeMock.instances).toHaveLength(1)})});
|
|
1
|
+
import{describe,expect,it,vi}from"vitest";import{ACPServer}from"./acp-server.js";const bridgeMock=vi.hoisted(()=>({instances:[],closeImpl:vi.fn(async e=>{})}));function makeConfig(){return{agentGatewayUrl:"https://agent-gw.example.test",keyFile:"/tmp/test.key",bridge:{url:"wss://bridge.example.test",service:"acp",shell:{enabled:!1}},gateway:{url:"ws://127.0.0.1:18789",token:"test-token",protocol:3,clientId:"test-client",agentId:"main"},retry:{baseMs:1,maxMs:10,maxAttempts:0},log:{enabled:!1,verbose:!1,dir:"/tmp"},promptTimeoutMs:1e3,terminalWsPort:0,terminalWsAllowedOrigins:[],streamIdleTimeoutMs:1e3,streamStaleTimeoutMs:1e3,cronSignalWindowMs:1e3,cronMaxDurationDefaultMs:3e5,cronMaxDurationCapMs:18e5,canvasRelayUrl:"",canvasEnabled:!1,openclawCanvasCompat:!1,messageBus:{enabled:!1,serviceUrl:"",url:"",principalId:"",a2aEnabled:!1}}}function makeLogger(){return{info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()}}vi.mock("@beeos-ai/bridge-client",()=>({BridgeClient:class{state="connected";send=vi.fn(()=>Promise.reject(new Error("ws closing")));connect=vi.fn(async()=>{});close=vi.fn(e=>bridgeMock.closeImpl(e));listeners=new Map;constructor(){bridgeMock.instances.push(this)}on(e,t){const n=this.listeners.get(e)??[];return n.push(t),this.listeners.set(e,n),this}emit(e,...t){for(const n of this.listeners.get(e)??[])n(...t)}}})),vi.mock("./gateway-client.js",()=>({GatewayClient:class{get isConnected(){return!0}on(e,t){return this}removeAllListeners(){return this}async start(){}stop(){}request(){return Promise.resolve({})}agentSend(){return Promise.resolve({})}}})),describe("ACPServer bridge shim",()=>{it("handles BridgeClient.send rejection without creating an unhandled rejection",async()=>{bridgeMock.instances.length=0,bridgeMock.closeImpl.mockReset(),bridgeMock.closeImpl.mockImplementation(async()=>{});const e=vi.fn();process.once("unhandledRejection",e);const t=makeLogger(),n=new ACPServer(makeConfig(),t);await n.start(),n.sendBridgeMessage({jsonrpc:"2.0",method:"session/update",params:{}}),await new Promise(e=>setImmediate(e)),process.removeListener("unhandledRejection",e),expect(bridgeMock.instances[0]?.send).toHaveBeenCalledTimes(1),expect(t.warn).toHaveBeenCalledWith("[acp-server] bridge.send failed: ws closing"),expect(e).not.toHaveBeenCalled()})}),describe("ACPServer.stop() bridge teardown",()=>{it("closes the bridge instance even when the ACP-proxy client has already disconnected",async()=>{bridgeMock.instances.length=0,bridgeMock.closeImpl.mockReset(),bridgeMock.closeImpl.mockImplementation(async()=>{});const e=makeLogger(),t=new ACPServer(makeConfig(),e);await t.start(),t.client=null,expect(t.bridgeInstance).not.toBeNull(),await t.stop(),expect(bridgeMock.instances[0]?.close).toHaveBeenCalledTimes(1),expect(t.bridgeInstance).toBeNull()}),it("clears bridgeInstance even when bridge.close() rejects",async()=>{bridgeMock.instances.length=0,bridgeMock.closeImpl.mockReset(),bridgeMock.closeImpl.mockImplementation(async()=>{throw new Error("simulated SDK close failure")});const e=makeLogger(),t=new ACPServer(makeConfig(),e);await t.start(),await expect(t.stop()).resolves.toBeUndefined(),expect(t.bridgeInstance).toBeNull(),expect(e.debug).toHaveBeenCalledWith(expect.stringContaining("bridge.close failed during stop"))}),it("ignores events from a stale BridgeClient after stop()",async()=>{bridgeMock.instances.length=0,bridgeMock.closeImpl.mockReset(),bridgeMock.closeImpl.mockImplementation(async()=>{});const e=makeLogger(),t=new ACPServer(makeConfig(),e);await t.start();const n=bridgeMock.instances[0];expect(n).toBeDefined(),await t.stop(),e.warn.mockClear(),n.emit("disconnected","code=1006"),expect(e.warn).not.toHaveBeenCalled(),expect(bridgeMock.instances).toHaveLength(1)})});
|
package/dist/acp-server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{WebSocketServer,WebSocket}from"ws";import{randomUUID}from"node:crypto";let BridgeClientCtor;import{GatewayClient}from"./gateway-client.js";import{TerminalManager}from"./terminal/session-manager.js";import{AcpTransport}from"./acp-gateway/transport.js";import{AcpGatewaySessionState}from"./acp-gateway/session-state.js";import{AcpGatewayBridgeCore}from"./acp-gateway/bridge-core.js";import{BeeosFileResolver}from"./acp-gateway/beeos-file-resolver.js";import{AcpGatewayEvents}from"./acp-gateway/gateway-events.js";import{TerminalBridgeHandler}from"./terminal/bridge-handler.js";import{isAgentSyncWaitForGateway,syncAgentsToPlatform}from"./agent-sync.js";import{CanvasOrchestrator}from"./canvas-orchestrator.js";import{discoverBridgeFromGW}from"./bridge-discovery.js";import{writeDiscoveryCache}from"./discovery-cache.js";function formatBridgeEventArgs(e){return 0===e.length?"(no args)":e.map((e,t)=>`arg${t}=${formatBridgeEventValue(e)}`).join(" ")}function formatBridgeEventValue(e){if(void 0===e)return"undefined";if(null===e)return"null";if(e instanceof Error){const t=e.stack?e.stack.split("\n").slice(0,4).join(" | "):"";return`Error(name=${e.name},message=${e.message}${t?`,stack=${t}`:""})`}if("object"==typeof e)try{return JSON.stringify(e,jsonReplacerForLogs)}catch{return String(e)}return String(e)}function jsonReplacerForLogs(e,t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t}export class ACPServer{agentFetchFn;instanceId;wss=null;gateway=null;client=null;config;logger;writeObs;transport;state;core;events;terminalMgr;terminalHandler;canvasOrch;messageSdk=null;msgPrincipalId=null;pendingToolCallSessionKeys=[];thirdPartyChannels;agentSyncRetryTimer=null;agentSyncInFlight=!1;bridgeInstance=null;bridgeConsecutiveFailures=0;static RE_DISCOVER_THRESHOLD=2;drainNextDeferredSend(e){const t=e.pendingAgentSends?.shift();t&&(e.pendingAgentSends?.length||(e.pendingAgentSends=void 0),this.agentSend(t.message,t.attachments,e.gatewaySessionKey,t.inputProvenance,t.channelId,t.inboundMessageId).catch(e=>this.logger.warn?.("[acp-server] Deferred agentSend failed: %s",e)))}async gatewayRequest(e,t){if(!this.gateway?.isConnected)throw new Error("Gateway not connected");return this.gateway.request(e,t)}async agentSend(e,t,s,n,i,r){if(!this.gateway?.isConnected)throw new Error("Gateway not connected");const a=this.config.gateway.agentId||this.core.getDefaultAgentId();let o,c;if(s?(o=this.state.findSessionByKey(s),c=s,o?this.logger.info?.(`[acp-server] agentSend: resolved session for key=${s} sid=${o.sessionId}`):(o=this.core.ensureSessionForKey(c),this.logger.info?.(`[acp-server] agentSend: created session for key=${s} sid=${o.sessionId}`))):(c=`agent:${a}:a2a:${randomUUID()}`,o=this.core.ensureSessionForKey(c),this.logger.info?.(`[acp-server] agentSend: no targetSessionKey, created A2A session key=${c}`)),i&&o&&(o.channelId=i),r&&o&&(o.inboundMessageId=r),o&&!o.promptDone&&(void 0!==o.pendingPromptId||void 0!==o.currentRunId||void 0!==o.gatewayRequestId))return(o.pendingAgentSends??=[]).push({message:e,attachments:t,inputProvenance:n,channelId:i,inboundMessageId:r}),void this.logger.info?.("[acp-server] Session has active run, deferred message (queue=%d)",o.pendingAgentSends.length);const g=await this.gateway.agentSend(c,e,a,t,n);return g?.runId&&(o?(this.state.resetForNewRun(o,o.sessionId,this.transport),o.currentRunId=g.runId,o.assistantStreamStartedAt=Date.now(),this.state.promptsByRunId.set(g.runId,o)):this.state.promptsByRunId.set(g.runId,{gatewaySessionKey:c,channelId:i,inboundMessageId:r})),g}setMessageSdk(e,t){this.messageSdk=e,this.msgPrincipalId=t}async publishAgentReply(e,t,s,n){const i=this.messageSdk,r=this.msgPrincipalId;if(i&&r){if(e&&i.sendToChannel)try{return await i.sendToChannel(e,s,n,{inReplyTo:t}),void this.logger.info?.(`[acp-server] ${s} published channel=${e} in_reply_to=${t??"-"}`)}catch(t){this.logger.warn?.(`[acp-server] sendToChannel failed channel=${e}: ${t instanceof Error?t.message:String(t)}; attempting persistent fallback`)}if(e&&i.sendChannelMessage)try{return await i.sendChannelMessage(e,{type:s,payload:n,inReplyTo:t,senderId:r}),void this.logger.info?.(`[acp-server] ${s} persisted channel=${e} in_reply_to=${t??"-"}`)}catch(t){this.logger.warn?.(`[acp-server] sendChannelMessage failed channel=${e}: ${t instanceof Error?t.message:String(t)}; falling back to personal channel`)}await i.sendToPersonal(r,s,n)}}sendBridgeMessage=e=>{const t=this.client;if(t&&t.readyState===WebSocket.OPEN)try{t.send(JSON.stringify(e))}catch(e){this.logger.debug?.("[acp-server] bridge send failed (socket may be closing):",e)}else this.logger.debug?.("[acp-server] bridge not ready, dropping message")};constructor(e,t,s,n,i,r){this.agentFetchFn=n,this.instanceId=i,this.config=e,this.logger=t,this.writeObs=s??(()=>{}),this.thirdPartyChannels=r??new Set,this.transport=new AcpTransport(this.sendBridgeMessage,this.writeObs,void 0,()=>{const e=this.client;return!!e&&e.readyState===WebSocket.OPEN}),this.state=new AcpGatewaySessionState(this.logger);const a=this.agentFetchFn&&this.config.agentGatewayUrl?new BeeosFileResolver({agentGatewayUrl:this.config.agentGatewayUrl,agentFetch:this.agentFetchFn,writeObs:this.writeObs}):void 0;this.core=new AcpGatewayBridgeCore({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,getGateway:()=>this.gateway,instanceId:this.instanceId,thirdPartyChannels:this.thirdPartyChannels,beeosFileResolver:a,agentFetch:this.agentFetchFn,agentGatewayUrl:this.config.agentGatewayUrl}),this.canvasOrch=new CanvasOrchestrator({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,getSessionIdForToolCall:e=>this.getSessionIdForToolCall(e),gateway:null,getDefaultAgentId:()=>this.core.getDefaultAgentId(),resolvePlatformAgentId:e=>this.core.resolvePlatformAgentId(e)??""}),this.events=new AcpGatewayEvents({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,completePrompt:(e,t)=>this.core.completePrompt(e,t),failPrompt:(e,t,s)=>this.core.failPrompt(e,t,s),maybeCompletePromptFromChatState:(e,t)=>this.core.maybeCompletePromptFromChatState(e,t),agentFetch:this.agentFetchFn,getMessageSdk:()=>{const e=this.messageSdk;return e?.sendToChannel?{sendToChannel:e.sendToChannel.bind(e)}:null},getMsgPrincipalId:()=>this.msgPrincipalId??null,gatewayRequest:(e,t)=>{const s=this.gateway;return s?.isConnected?s.request(e,t):Promise.reject(new Error("gateway not connected"))},cronChannelCache:this.core.cronChannelCache,onStreamDelta:(e,t)=>{if(!this.messageSdk||!this.msgPrincipalId)return;const s=e.gatewaySessionKey;if(!s)return;const n=e.channelId,i={session_key:s,update:t};(n&&this.messageSdk.sendToChannel?this.messageSdk.sendToChannel(n,"agent_reply_delta",i):this.messageSdk.sendToPersonal(this.msgPrincipalId,"agent_reply_delta",i)).catch(e=>this.logger.debug?.(`[acp-server] agent_reply_delta publish failed: ${e}`))}}),this.core.onRunEnded=(e,t)=>{"complete"===t.kind?this.canvasOrch.onPromptComplete(e):this.canvasOrch.onPromptFailed(),this.drainNextDeferredSend(e)},this.terminalMgr=new TerminalManager,this.terminalHandler=new TerminalBridgeHandler({terminalMgr:this.terminalMgr,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs}),this.terminalHandler.setupListeners(),this.core.handleTerminalRequest=e=>this.terminalHandler.handleRequest(e),this.core.handleTerminalNotification=(e,t)=>this.terminalHandler.handleNotification(e,t),this.core.onRunComplete=(e,t)=>{const s=this.state.promptsByRunId.get(e),n=s?.gatewaySessionKey,i=s?.channelId,r=s?.inboundMessageId;if(this.logger.info?.(`[acp-server] onRunComplete runId=${e} session_key=${n} channel=${i} in_reply_to=${r??"-"} principal=${this.msgPrincipalId} hasSDK=${!!this.messageSdk}`),!n)return void this.logger.warn?.(`[acp-server] onRunComplete: no session_key for runId=${e}, cannot publish reply`);const a={session_key:n,text:t};this.publishAgentReply(i,r,"agent_reply",a).catch(e=>this.logger.warn?.(`[acp-server] agent_reply publish failed: ${e instanceof Error?e.message:JSON.stringify(e)}`))},this.core.onRunFailed=(e,t)=>{const s=this.state.promptsByRunId.get(e),n=s?.gatewaySessionKey,i=s?.channelId,r=s?.inboundMessageId;if(this.logger.info?.(`[acp-server] onRunFailed runId=${e} session_key=${n} channel=${i} in_reply_to=${r??"-"}`),!n)return;const a={session_key:n,error:t||"execution failed"};this.publishAgentReply(i,r,"agent_reply",a).catch(e=>this.logger.warn?.(`[acp-server] agent_reply error publish failed: ${e instanceof Error?e.message:String(e)}`))},this.core.handleCanvasNotification=(e,t)=>{this.canvasOrch.handleCanvasNotification(e,t)},this.core.getCanvasState=()=>this.canvasOrch.canvasState,this.core.onSessionLoaded=(e,t,s)=>{this.canvasOrch.onSessionLoaded(e,t,s)},this.core.onSkillInstalled=(e,t)=>{this.registerSkillFormSchemas(e,t)},this.core.onSessionDeleted=e=>{this.canvasOrch.onSessionDeleted(e)},this.core.onSessionCleared=(e,t)=>{this.canvasOrch.onSessionCleared(e,t)},this.core.handleSlashCommand=async e=>this.canvasOrch.handleSlashCommand(e),this.core.onPromptStart=()=>{this.canvasOrch.onPromptStart()},this.state.startSessionGc(e=>this.core.cleanupPrompt(e),e=>{this.canvasOrch.canvasState?.removeSession(e.gatewaySessionKey),this.transport.resetSessionUpdateCount(e.sessionId)})}async start(e){const t=Date.now();this.logger.info?.("[acp-server] start() begin"),e&&(this.config.bridge.url=e);const s=this.config.bridge.url,n=this.config.keyFile;if(s&&!BridgeClientCtor)try{const e=Date.now(),t=await import("@beeos-ai/bridge-client");BridgeClientCtor=t.BridgeClient,this.logger.info?.(`[acp-server] bridge-client import took ${Date.now()-e}ms`)}catch(e){this.logger.warn?.("[acp-server] Bridge SDK not available")}const i=Date.now();if(await this.connectGateway(),this.logger.info?.(`[acp-server] connectGateway() took ${Date.now()-i}ms`),s&&n&&BridgeClientCtor){Date.now();await this.startBridgeMode(s,n)}else this.logger.warn?.("[acp-server] Bridge not configured; running in standby (no ACP listener). Use handleUpgrade() for noServer mode."),this.core.markAgentSyncDone();this.logger.info?.(`[acp-server] start() total ${Date.now()-t}ms`)}async startBridgeMode(e,t){if(!BridgeClientCtor)throw new Error("@beeos-ai/bridge-client not available");const s=new BridgeClientCtor({bridgeUrl:e,service:this.config.bridge.service||"acp",keyFile:t});this.bridgeInstance=s;const n=()=>this.bridgeInstance===s;s.on("connected",()=>{n()&&(this.bridgeConsecutiveFailures=0,this.logger.info?.("[acp-server] Connected to Bridge (publicKey auth)"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"bridge.connected",severity:"info"}),this.tryAgentSync())}),s.on("disconnected",(...e)=>{if(!n())return;const i=String(e[0]??"unknown"),r=formatBridgeEventArgs(e);if(this.logger.warn?.(`[acp-server] Bridge disconnected: ${i} (detail=${r})`),this.core.initialized=!1,this.bridgeConsecutiveFailures++,this.bridgeConsecutiveFailures>=ACPServer.RE_DISCOVER_THRESHOLD&&this.agentFetchFn&&this.config.agentGatewayUrl){this.bridgeConsecutiveFailures=0;const e=this.config.bridge.url;discoverBridgeFromGW(this.config.agentGatewayUrl,this.agentFetchFn).then(async n=>{n&&n.url!==e&&(this.logger.info?.(`[acp-server] Bridge re-discovery: URL changed ${e} → ${n.url}, switching`),this.config.bridge.url=n.url,writeDiscoveryCache({bridge:{url:n.url,discoveredAt:Date.now()}}),await s.close(!1),await this.startBridgeMode(n.url,t))}).catch(()=>{})}}),s.on("message",(...e)=>{if(!n())return;const t=e[0],s="string"==typeof t?t:Buffer.from(t).toString("utf-8");try{const e=JSON.parse(s);"id"in e&&void 0!==e.id?this.core.handleRequest(e).catch(e=>{this.logger.error?.(`[acp-server] Bridge request failed: ${e instanceof Error?e.message:String(e)}`)}):this.core.handleNotification(e)}catch{this.logger.error?.("[acp-server] Invalid JSON-RPC message from Bridge")}}),s.on("error",(...e)=>{if(!n())return;const t=formatBridgeEventArgs(e);this.logger.error?.(`[acp-server] Bridge error: ${t}`)});const i={readyState:WebSocket.OPEN,send:(e,t)=>{s.send(e).then(()=>t?.(),e=>{const s=e instanceof Error?e:new Error(String(e));this.logger.warn?.(`[acp-server] bridge.send failed: ${s.message}`),t?.(s)})},close:()=>{s.close().catch(e=>{this.logger.debug?.(`[acp-server] bridge.close failed: ${e instanceof Error?e.message:String(e)}`)})},terminate:()=>{s.close(!1).catch(e=>{this.logger.debug?.(`[acp-server] bridge.terminate failed: ${e instanceof Error?e.message:String(e)}`)})},on:()=>i,once:()=>i,removeListener:()=>i,removeAllListeners:()=>i,ping:()=>{}};Object.defineProperty(i,"readyState",{get:()=>"connected"===s.state?WebSocket.OPEN:WebSocket.CLOSED}),this.client=i;const r=Date.now();try{await s.connect(),this.logger.info?.(`[acp-server] bridge.connect() took ${Date.now()-r}ms`)}catch(e){this.logger.warn?.(`[acp-server] Initial bridge connect failed after ${Date.now()-r}ms (will retry in background): ${e?.message}`)}this.core.initialized=!1,this.logger.info?.("[acp-server] Running in Bridge mode (WS client)")}handleUpgrade(e,t,s){this.wss||(this.wss=new WebSocketServer({noServer:!0}),this.wss.on("connection",(e,t)=>this.handleConnection(e,t))),this.wss.handleUpgrade(e,t,s,t=>{this.wss.emit("connection",t,e)})}async tryAgentSync(e=0){if(this.agentSyncRetryTimer&&(clearTimeout(this.agentSyncRetryTimer),this.agentSyncRetryTimer=null),!this.client||this.client.readyState!==WebSocket.OPEN)return;if(!this.gateway||!this.agentFetchFn||!this.config.agentGatewayUrl)return void this.core.markAgentSyncDone();if(this.agentSyncInFlight)return;const t=()=>{if(e+1>=6)return void this.logger.warn?.("[acp-server] agent sync exhausted 6 attempts — waiting for Gateway reconnect");const t=e<2?1e3*(e+1):Math.min(5e3*2**(e-2),12e4);this.logger.info?.(`[acp-server] agent sync retry #${e+1} in ${Math.round(t/1e3)}s`),this.agentSyncRetryTimer=setTimeout(()=>{this.tryAgentSync(e+1)},t)},s=Date.now();this.agentSyncInFlight=!0;try{const e=await syncAgentsToPlatform({gateway:this.gateway,agentGatewayUrl:this.config.agentGatewayUrl,capabilities:{canvas:this.config.canvasEnabled,terminal:!0,fileSystem:!0,cron:!0,streaming:!0},agentFetch:this.agentFetchFn,logger:this.logger});isAgentSyncWaitForGateway(e)?this.logger.info?.("[acp-server] agent sync waiting for OpenClaw Gateway connection"):e?(this.core.setAgentMapping(e),this.logger.info?.(`[acp-server] agent mapping loaded: ${[...e.keys()].join(", ")} (sync took ${Date.now()-s}ms)`)):t()}catch(e){this.logger.warn?.(`[acp-server] agent sync failed: ${e}`),t()}finally{this.agentSyncInFlight=!1}}async connectGateway(){this.gateway&&(this.gateway.stop(),this.gateway=null);const e=this.config.gateway;this.gateway=new GatewayClient({url:e.url,token:e.token||"",clientId:e.clientId,openclawCanvasCompat:!!this.config.openclawCanvasCompat,retry:{baseMs:this.config.retry.baseMs,maxMs:this.config.retry.maxMs,maxAttempts:this.config.retry.maxAttempts}}),this.gateway.on("chat",e=>this.events.handleChatEvent(e)),this.gateway.on("agent",e=>this.events.handleAgentEvent(e)),this.gateway.on("cron",e=>this.events.handleCronEvent(e)),this.gateway.on("sessionMessage",e=>this.core.handleSessionMessage(e)),this.gateway.on("response",e=>this.core.handleGatewayResponse(e));const t=this.gateway;this.canvasOrch.updateDeps({gateway:t?{get isConnected(){return t.isConnected},request:(e,t)=>this.gateway.request(e,t),agentSend:(e,t,s)=>this.gateway.agentSend(e,t,s)}:null}),this.config.openclawCanvasCompat&&(this.gateway.on("canvas",e=>this.canvasOrch.handleOpenClawCanvasEvent(e)),this.logger.info?.("[acp-server] OpenClaw native canvas compat enabled — listening for canvas events")),this.gateway.on("connected",()=>{this.logger.info?.("[acp-server] Connected to OpenClaw Gateway"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"gateway.connected",severity:"info"}),this.core.resubscribeAllSessionMessages(),this.core.refreshCronIsolatedSessionKeys(),this.tryAgentSync()}),this.gateway.on("disconnected",()=>{this.logger.warn?.("[acp-server] Gateway disconnected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"gateway.disconnected",severity:"warn"}),this.core.cleanupAllPendingPrompts()}),this.gateway.on("reconnecting",e=>{this.logger.info?.(`[acp-server] Reconnecting to Gateway attempt=${e.attempt} delay=${Math.round(e.delayMs)}ms`)}),this.gateway.on("reconnect-exhausted",e=>{this.logger.error?.(`[acp-server] Gateway reconnect exhausted after ${e} attempts`)}),this.gateway.on("error",e=>{this.logger.error?.("[acp-server] Gateway error:",e.message)}),this.gateway.on("transport",e=>{this.logger.info?.(`[acp-server] transport.${e.event} durationMs=${e.durationMs??"?"}`),this.writeObs({component:"gateway-client",domain:"lifecycle",name:`transport.${e.event}`,severity:"connect_fail"===e.event||"error"===e.event?"warn":"debug",payload:e})}),this.gateway.on("reconnect-notify-scheduled",e=>{this.logger.info?.(`[acp-server] Server-initiated reconnect scheduled in ${e.delayMs}ms`)}),this.gateway.on("reconnect-notify-fired",()=>{this.logger.info?.("[acp-server] Server-initiated reconnect firing")});try{await this.gateway.start()}catch(e){this.logger.error?.("[acp-server] Initial Gateway connect failed:",e)}}handleConnection(e,t){if(this.client){this.logger.warn?.("[acp-server] Replacing existing ACP client with new connection (takeover)");const e=this.client;this.client=null;try{e.close(1008,"replaced by new client")}catch{e.terminate()}}this.client=e,this.core.initialized=!1,this.logger.info?.("[acp-server] ACP client connected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"client.connected",severity:"info"}),e.on("message",e=>{const t="string"==typeof e?e:e.toString("utf-8");try{const e=JSON.parse(t);"id"in e&&void 0!==e.id?this.core.handleRequest(e).catch(e=>{this.logger.error?.(`[acp-server] request failed: ${e instanceof Error?e.message:String(e)}`)}):this.core.handleNotification(e)}catch{this.logger.error?.("[acp-server] Invalid JSON-RPC message")}}),e.on("close",()=>{this.client===e&&(this.client=null,this.core.initialized=!1),this.logger.info?.("[acp-server] ACP client disconnected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"client.disconnected",severity:"info"})})}pushToolResultContent(e,t,s,n){this.core.pushToolResultContent(e,t,s,n)}setCanvasState(e,t){this.canvasOrch.setCanvasState(e,t)}wireRelayActionHandler(){this.canvasOrch.wireRelayActionHandler()}isCanvasActive(e){return this.canvasOrch.isCanvasActive(e)}isCanvasActiveForGatewayKey(e){return this.canvasOrch.isCanvasActiveForGatewayKey(e)}broadcastNotification(e,t){this.transport.sendNotification(e,t)}getActiveSessionId(){return this.state.lastActiveSessionId}getSessionIdForToolCall(e){const t=this.pendingToolCallSessionKeys.length>0?this.pendingToolCallSessionKeys[this.pendingToolCallSessionKeys.length-1]:void 0;if(t){const s=this.state.findSessionByKey(t)??this.core.ensureSessionForKey(t);if(s?.sessionId)return e&&this.state.toolCallToSessionMap.set(e,s.sessionId),s.sessionId}if(e){const t=this.state.toolCallToSessionMap.get(e);if(t)return t;const s=this.state.toolCallIdMap.get(e);if(s&&s!==e){const e=this.state.toolCallToSessionMap.get(s);if(e)return e}const n=e.split("_");if(n.length>=3&&"tc"===n[0]){const e=n[1],t=this.state.promptsByRunId.get(e);if(t?.sessionId)return t.sessionId}}this.logger.warn?.(`[acp-server] getSessionIdForToolCall MISS: toolCallId=${e??"(none)"}, sessions=${this.state.sessions.size}, pendingKey=${t??"none"}`)}getSessionIdForActivePrompt(){return this.getSessionIdForToolCall()}setPendingToolCallSessionKey(e){e&&(this.pendingToolCallSessionKeys.push(e),this.pendingToolCallSessionKeys.length>16&&this.pendingToolCallSessionKeys.shift())}preMapToolCallSession(e){const t=this.pendingToolCallSessionKeys.length>0?this.pendingToolCallSessionKeys[this.pendingToolCallSessionKeys.length-1]:void 0;if(!t||!e)return;if(this.state.toolCallToSessionMap.has(e))return;const s=this.state.findSessionByKey(t)??this.core.ensureSessionForKey(t);s?.sessionId&&this.state.toolCallToSessionMap.set(e,s.sessionId)}waitForAgentMapping(){return this.core.waitForAgentMapping()}onceAgentMappingReady(e){this.core.onceAgentMappingReady(e)}flushPendingCanvasLinks(){this.canvasOrch.flushPendingCanvasLinks()}onRelayReconnected(){this.canvasOrch.onRelayReconnected()}getLocalAgentId(){return this.config.gateway.agentId||this.core.getDefaultAgentId()}getDefaultPlatformAgentId(){return this.getDefaultPlatformAgent()?.id}getDefaultPlatformAgent(){const e=this.core.agentMapping;if(e&&0!==e.size)return e.values().next().value??void 0}getPlatformAgentIdForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return this.core.resolvePlatformAgentId(s?.agentId??"")??s?.platformAgentId}getGatewaySessionKeyForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return s?.gatewaySessionKey}getMentionsForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return s?.activeMentions}getResourceRenderer(){return this.canvasOrch.resourceRenderer}getDescriptorRegistry(){return this.canvasOrch.descriptorRegistry}getFormBuilder(){return this.canvasOrch.formBuilder}getSchemaRegistry(){return this.canvasOrch.schemaRegistry}registerSkillFormSchemas(e,t){const s=this.canvasOrch.schemaRegistry;s&&import("node:fs/promises").then(async({readFile:n})=>{try{const i=`${t}/skill.json`,r=await n(i,"utf-8"),a=JSON.parse(r);if(a.formSchemas?.length){for(const e of a.formSchemas)s.register({...e,submitLabel:e.submitLabel||"Submit",fields:e.fields});this.logger.info?.(`[acp-server] Registered ${a.formSchemas.length} form schema(s) from skill "${e}"`)}}catch{}}).catch(e=>{this.logger.debug?.(`[acp-server] skill form schema import failed: ${e instanceof Error?e.message:String(e)}`)})}emitCanvasActionAsUserMessage(e,t){this.canvasOrch.emitCanvasActionAsUserMessage(e,t)}async stop(){if(this.agentSyncRetryTimer&&(clearTimeout(this.agentSyncRetryTimer),this.agentSyncRetryTimer=null),this.state.destroy(),this.canvasOrch.destroy(),this.gateway&&(this.gateway.removeAllListeners(),this.gateway.stop(),this.gateway=null),this.client&&(this.client.removeAllListeners(),this.client.close(),this.client=null),this.bridgeInstance){try{await this.bridgeInstance.close()}catch(e){this.logger.debug?.(`[acp-server] bridge.close failed during stop: ${e instanceof Error?e.message:String(e)}`)}this.bridgeInstance=null}this.bridgeConsecutiveFailures=0,this.terminalHandler.destroy(),this.terminalMgr.destroy(),this.wss&&(this.wss.removeAllListeners(),this.wss.close(),this.wss=null),this.logger.info?.("[acp-server] Stopped"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"lifecycle.shutdown",severity:"info"})}}
|
|
1
|
+
import{WebSocketServer,WebSocket}from"ws";import{randomUUID}from"node:crypto";let BridgeClientCtor;import{GatewayClient}from"./gateway-client.js";import{TerminalManager}from"./terminal/session-manager.js";import{AcpTransport}from"./acp-gateway/transport.js";import{AcpGatewaySessionState}from"./acp-gateway/session-state.js";import{AcpGatewayBridgeCore}from"./acp-gateway/bridge-core.js";import{BeeosFileResolver}from"./acp-gateway/beeos-file-resolver.js";import{AcpGatewayEvents}from"./acp-gateway/gateway-events.js";import{TerminalBridgeHandler}from"./terminal/bridge-handler.js";import{isAgentSyncWaitForGateway,syncAgentsToPlatform}from"./agent-sync.js";import{CanvasOrchestrator}from"./canvas-orchestrator.js";import{discoverBridgeFromGW}from"./bridge-discovery.js";import{writeDiscoveryCache}from"./discovery-cache.js";function formatBridgeEventArgs(e){return 0===e.length?"(no args)":e.map((e,t)=>`arg${t}=${formatBridgeEventValue(e)}`).join(" ")}function formatBridgeEventValue(e){if(void 0===e)return"undefined";if(null===e)return"null";if(e instanceof Error){const t=e.stack?e.stack.split("\n").slice(0,4).join(" | "):"";return`Error(name=${e.name},message=${e.message}${t?`,stack=${t}`:""})`}if("object"==typeof e)try{return JSON.stringify(e,jsonReplacerForLogs)}catch{return String(e)}return String(e)}function jsonReplacerForLogs(e,t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t}export class ACPServer{agentFetchFn;instanceId;wss=null;gateway=null;client=null;config;logger;writeObs;transport;state;core;events;terminalMgr;terminalHandler;canvasOrch;messageClient=null;msgPrincipalId=null;pendingToolCallSessionKeys=[];thirdPartyChannels;agentSyncRetryTimer=null;agentSyncInFlight=!1;bridgeInstance=null;bridgeConsecutiveFailures=0;static RE_DISCOVER_THRESHOLD=2;drainNextDeferredSend(e){const t=e.pendingAgentSends?.shift();t&&(e.pendingAgentSends?.length||(e.pendingAgentSends=void 0),this.agentSend(t.message,t.attachments,e.gatewaySessionKey,t.inputProvenance,t.channelId,t.inboundMessageId).catch(e=>this.logger.warn?.("[acp-server] Deferred agentSend failed: %s",e)))}async gatewayRequest(e,t){if(!this.gateway?.isConnected)throw new Error("Gateway not connected");return this.gateway.request(e,t)}async agentSend(e,t,s,n,i,r){if(!this.gateway?.isConnected)throw new Error("Gateway not connected");const a=this.config.gateway.agentId||this.core.getDefaultAgentId();let o,c;if(s?(o=this.state.findSessionByKey(s),c=s,o?this.logger.info?.(`[acp-server] agentSend: resolved session for key=${s} sid=${o.sessionId}`):(o=this.core.ensureSessionForKey(c),this.logger.info?.(`[acp-server] agentSend: created session for key=${s} sid=${o.sessionId}`))):(c=`agent:${a}:a2a:${randomUUID()}`,o=this.core.ensureSessionForKey(c),this.logger.info?.(`[acp-server] agentSend: no targetSessionKey, created A2A session key=${c}`)),i&&o&&(o.channelId=i),r&&o&&(o.inboundMessageId=r),o&&!o.promptDone&&(void 0!==o.pendingPromptId||void 0!==o.currentRunId||void 0!==o.gatewayRequestId))return(o.pendingAgentSends??=[]).push({message:e,attachments:t,inputProvenance:n,channelId:i,inboundMessageId:r}),void this.logger.info?.("[acp-server] Session has active run, deferred message (queue=%d)",o.pendingAgentSends.length);const g=await this.gateway.agentSend(c,e,a,t,n);return g?.runId&&(o?(this.state.resetForNewRun(o,o.sessionId,this.transport),o.currentRunId=g.runId,o.assistantStreamStartedAt=Date.now(),this.state.promptsByRunId.set(g.runId,o)):this.state.promptsByRunId.set(g.runId,{gatewaySessionKey:c,channelId:i,inboundMessageId:r})),g}setMessageClient(e,t){this.messageClient=e,this.msgPrincipalId=t}async publishAgentReply(e,t,s,n){const i=this.messageClient,r=this.msgPrincipalId;if(i&&r){if(e)try{return await i.messages.send({conversationId:e,type:s,content:n,replyTo:t}),void this.logger.info?.(`[acp-server] ${s} persisted channel=${e} in_reply_to=${t??"-"}`)}catch(t){this.logger.warn?.(`[acp-server] messages.send failed channel=${e}: ${t instanceof Error?t.message:String(t)}; falling back to personal channel`)}await i.identities.send({identityId:r,type:s,content:n})}}sendBridgeMessage=e=>{const t=this.client;if(t&&t.readyState===WebSocket.OPEN)try{t.send(JSON.stringify(e))}catch(e){this.logger.debug?.("[acp-server] bridge send failed (socket may be closing):",e)}else this.logger.debug?.("[acp-server] bridge not ready, dropping message")};constructor(e,t,s,n,i,r){this.agentFetchFn=n,this.instanceId=i,this.config=e,this.logger=t,this.writeObs=s??(()=>{}),this.thirdPartyChannels=r??new Set,this.transport=new AcpTransport(this.sendBridgeMessage,this.writeObs,void 0,()=>{const e=this.client;return!!e&&e.readyState===WebSocket.OPEN}),this.state=new AcpGatewaySessionState(this.logger);const a=this.agentFetchFn&&this.config.agentGatewayUrl?new BeeosFileResolver({agentGatewayUrl:this.config.agentGatewayUrl,agentFetch:this.agentFetchFn,writeObs:this.writeObs}):void 0;this.core=new AcpGatewayBridgeCore({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,getGateway:()=>this.gateway,instanceId:this.instanceId,thirdPartyChannels:this.thirdPartyChannels,beeosFileResolver:a,agentFetch:this.agentFetchFn,agentGatewayUrl:this.config.agentGatewayUrl}),this.canvasOrch=new CanvasOrchestrator({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,getSessionIdForToolCall:e=>this.getSessionIdForToolCall(e),gateway:null,getDefaultAgentId:()=>this.core.getDefaultAgentId(),resolvePlatformAgentId:e=>this.core.resolvePlatformAgentId(e)??""}),this.events=new AcpGatewayEvents({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,completePrompt:(e,t)=>this.core.completePrompt(e,t),failPrompt:(e,t,s)=>this.core.failPrompt(e,t,s),schedulePromptTimeout:e=>this.core.schedulePromptTimeout(e),maybeCompletePromptFromChatState:(e,t)=>this.core.maybeCompletePromptFromChatState(e,t),agentFetch:this.agentFetchFn,getMessageClient:()=>this.messageClient,getMsgPrincipalId:()=>this.msgPrincipalId??null,gatewayRequest:(e,t)=>{const s=this.gateway;return s?.isConnected?s.request(e,t):Promise.reject(new Error("gateway not connected"))},cronChannelCache:this.core.cronChannelCache,onStreamDelta:(e,t)=>{if(!this.messageClient||!this.msgPrincipalId)return;const s=e.gatewaySessionKey;if(!s)return;const n=e.channelId,i={session_key:s,update:t};(n?this.messageClient.messages.send({conversationId:n,type:"agent_reply_delta",content:i}):this.messageClient.identities.send({identityId:this.msgPrincipalId,type:"agent_reply_delta",content:i})).catch(e=>this.logger.debug?.(`[acp-server] agent_reply_delta publish failed: ${e}`))}}),this.core.onRunEnded=(e,t)=>{"complete"===t.kind?this.canvasOrch.onPromptComplete(e):this.canvasOrch.onPromptFailed(),this.drainNextDeferredSend(e)},this.terminalMgr=new TerminalManager,this.terminalHandler=new TerminalBridgeHandler({terminalMgr:this.terminalMgr,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs}),this.terminalHandler.setupListeners(),this.core.handleTerminalRequest=e=>this.terminalHandler.handleRequest(e),this.core.handleTerminalNotification=(e,t)=>this.terminalHandler.handleNotification(e,t),this.core.onRunComplete=(e,t)=>{const s=this.state.promptsByRunId.get(e),n=s?.gatewaySessionKey,i=s?.channelId,r=s?.inboundMessageId;if(this.logger.info?.(`[acp-server] onRunComplete runId=${e} session_key=${n} channel=${i} in_reply_to=${r??"-"} principal=${this.msgPrincipalId} hasClient=${!!this.messageClient}`),!n)return void this.logger.warn?.(`[acp-server] onRunComplete: no session_key for runId=${e}, cannot publish reply`);const a={session_key:n,text:t};this.publishAgentReply(i,r,"agent_reply",a).catch(e=>this.logger.warn?.(`[acp-server] agent_reply publish failed: ${e instanceof Error?e.message:JSON.stringify(e)}`))},this.core.onRunFailed=(e,t)=>{const s=this.state.promptsByRunId.get(e),n=s?.gatewaySessionKey,i=s?.channelId,r=s?.inboundMessageId;if(this.logger.info?.(`[acp-server] onRunFailed runId=${e} session_key=${n} channel=${i} in_reply_to=${r??"-"}`),!n)return;const a={session_key:n,error:t||"execution failed"};this.publishAgentReply(i,r,"agent_reply",a).catch(e=>this.logger.warn?.(`[acp-server] agent_reply error publish failed: ${e instanceof Error?e.message:String(e)}`))},this.core.handleCanvasNotification=(e,t)=>{this.canvasOrch.handleCanvasNotification(e,t)},this.core.getCanvasState=()=>this.canvasOrch.canvasState,this.core.onSessionLoaded=(e,t,s)=>{this.canvasOrch.onSessionLoaded(e,t,s)},this.core.onSkillInstalled=(e,t)=>{this.registerSkillFormSchemas(e,t)},this.core.onSessionDeleted=e=>{this.canvasOrch.onSessionDeleted(e)},this.core.onSessionCleared=(e,t)=>{this.canvasOrch.onSessionCleared(e,t)},this.core.handleSlashCommand=async e=>this.canvasOrch.handleSlashCommand(e),this.core.onPromptStart=()=>{this.canvasOrch.onPromptStart()},this.state.startSessionGc(e=>this.core.cleanupPrompt(e),e=>{this.canvasOrch.canvasState?.removeSession(e.gatewaySessionKey),this.transport.resetSessionUpdateCount(e.sessionId)})}async start(e){const t=Date.now();this.logger.info?.("[acp-server] start() begin"),e&&(this.config.bridge.url=e);const s=this.config.bridge.url,n=this.config.keyFile;if(s&&!BridgeClientCtor)try{const e=Date.now(),t=await import("@beeos-ai/bridge-client");BridgeClientCtor=t.BridgeClient,this.logger.info?.(`[acp-server] bridge-client import took ${Date.now()-e}ms`)}catch(e){this.logger.warn?.("[acp-server] Bridge SDK not available")}const i=Date.now();if(await this.connectGateway(),this.logger.info?.(`[acp-server] connectGateway() took ${Date.now()-i}ms`),s&&n&&BridgeClientCtor){Date.now();await this.startBridgeMode(s,n)}else this.logger.warn?.("[acp-server] Bridge not configured; running in standby (no ACP listener). Use handleUpgrade() for noServer mode."),this.core.markAgentSyncDone();this.logger.info?.(`[acp-server] start() total ${Date.now()-t}ms`)}async startBridgeMode(e,t){if(!BridgeClientCtor)throw new Error("@beeos-ai/bridge-client not available");const s=new BridgeClientCtor({bridgeUrl:e,service:this.config.bridge.service||"acp",keyFile:t});this.bridgeInstance=s;const n=()=>this.bridgeInstance===s;s.on("connected",()=>{n()&&(this.bridgeConsecutiveFailures=0,this.logger.info?.("[acp-server] Connected to Bridge (publicKey auth)"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"bridge.connected",severity:"info"}),this.tryAgentSync())}),s.on("disconnected",(...e)=>{if(!n())return;const i=String(e[0]??"unknown"),r=formatBridgeEventArgs(e);if(this.logger.warn?.(`[acp-server] Bridge disconnected: ${i} (detail=${r})`),this.core.initialized=!1,this.bridgeConsecutiveFailures++,this.bridgeConsecutiveFailures>=ACPServer.RE_DISCOVER_THRESHOLD&&this.agentFetchFn&&this.config.agentGatewayUrl){this.bridgeConsecutiveFailures=0;const e=this.config.bridge.url;discoverBridgeFromGW(this.config.agentGatewayUrl,this.agentFetchFn).then(async n=>{n&&n.url!==e&&(this.logger.info?.(`[acp-server] Bridge re-discovery: URL changed ${e} → ${n.url}, switching`),this.config.bridge.url=n.url,writeDiscoveryCache({bridge:{url:n.url,discoveredAt:Date.now()}}),await s.close(!1),await this.startBridgeMode(n.url,t))}).catch(()=>{})}}),s.on("message",(...e)=>{if(!n())return;const t=e[0],s="string"==typeof t?t:Buffer.from(t).toString("utf-8");try{const e=JSON.parse(s);"id"in e&&void 0!==e.id?this.core.handleRequest(e).catch(e=>{this.logger.error?.(`[acp-server] Bridge request failed: ${e instanceof Error?e.message:String(e)}`)}):this.core.handleNotification(e)}catch{this.logger.error?.("[acp-server] Invalid JSON-RPC message from Bridge")}}),s.on("error",(...e)=>{if(!n())return;const t=formatBridgeEventArgs(e);this.logger.error?.(`[acp-server] Bridge error: ${t}`)});const i={readyState:WebSocket.OPEN,send:(e,t)=>{s.send(e).then(()=>t?.(),e=>{const s=e instanceof Error?e:new Error(String(e));this.logger.warn?.(`[acp-server] bridge.send failed: ${s.message}`),t?.(s)})},close:()=>{s.close().catch(e=>{this.logger.debug?.(`[acp-server] bridge.close failed: ${e instanceof Error?e.message:String(e)}`)})},terminate:()=>{s.close(!1).catch(e=>{this.logger.debug?.(`[acp-server] bridge.terminate failed: ${e instanceof Error?e.message:String(e)}`)})},on:()=>i,once:()=>i,removeListener:()=>i,removeAllListeners:()=>i,ping:()=>{}};Object.defineProperty(i,"readyState",{get:()=>"connected"===s.state?WebSocket.OPEN:WebSocket.CLOSED}),this.client=i;const r=Date.now();try{await s.connect(),this.logger.info?.(`[acp-server] bridge.connect() took ${Date.now()-r}ms`)}catch(e){this.logger.warn?.(`[acp-server] Initial bridge connect failed after ${Date.now()-r}ms (will retry in background): ${e?.message}`)}this.core.initialized=!1,this.logger.info?.("[acp-server] Running in Bridge mode (WS client)")}handleUpgrade(e,t,s){this.wss||(this.wss=new WebSocketServer({noServer:!0}),this.wss.on("connection",(e,t)=>this.handleConnection(e,t))),this.wss.handleUpgrade(e,t,s,t=>{this.wss.emit("connection",t,e)})}async tryAgentSync(e=0){if(this.agentSyncRetryTimer&&(clearTimeout(this.agentSyncRetryTimer),this.agentSyncRetryTimer=null),!this.client||this.client.readyState!==WebSocket.OPEN)return;if(!this.gateway||!this.agentFetchFn||!this.config.agentGatewayUrl)return void this.core.markAgentSyncDone();if(this.agentSyncInFlight)return;const t=()=>{if(e+1>=6)return void this.logger.warn?.("[acp-server] agent sync exhausted 6 attempts — waiting for Gateway reconnect");const t=e<2?1e3*(e+1):Math.min(5e3*2**(e-2),12e4);this.logger.info?.(`[acp-server] agent sync retry #${e+1} in ${Math.round(t/1e3)}s`),this.agentSyncRetryTimer=setTimeout(()=>{this.tryAgentSync(e+1)},t)},s=Date.now();this.agentSyncInFlight=!0;try{const e=await syncAgentsToPlatform({gateway:this.gateway,agentGatewayUrl:this.config.agentGatewayUrl,capabilities:{canvas:this.config.canvasEnabled,terminal:!0,fileSystem:!0,cron:!0,streaming:!0},agentFetch:this.agentFetchFn,logger:this.logger});isAgentSyncWaitForGateway(e)?this.logger.info?.("[acp-server] agent sync waiting for OpenClaw Gateway connection"):e?(this.core.setAgentMapping(e),this.logger.info?.(`[acp-server] agent mapping loaded: ${[...e.keys()].join(", ")} (sync took ${Date.now()-s}ms)`)):t()}catch(e){this.logger.warn?.(`[acp-server] agent sync failed: ${e}`),t()}finally{this.agentSyncInFlight=!1}}async connectGateway(){this.gateway&&(this.gateway.stop(),this.gateway=null);const e=this.config.gateway;this.gateway=new GatewayClient({url:e.url,token:e.token||"",clientId:e.clientId,openclawCanvasCompat:!!this.config.openclawCanvasCompat,retry:{baseMs:this.config.retry.baseMs,maxMs:this.config.retry.maxMs,maxAttempts:this.config.retry.maxAttempts}}),this.gateway.on("chat",e=>this.events.handleChatEvent(e)),this.gateway.on("agent",e=>this.events.handleAgentEvent(e)),this.gateway.on("cron",e=>this.events.handleCronEvent(e)),this.gateway.on("sessionMessage",e=>this.core.handleSessionMessage(e)),this.gateway.on("response",e=>this.core.handleGatewayResponse(e));const t=this.gateway;this.canvasOrch.updateDeps({gateway:t?{get isConnected(){return t.isConnected},request:(e,t)=>this.gateway.request(e,t),agentSend:(e,t,s)=>this.gateway.agentSend(e,t,s)}:null}),this.config.openclawCanvasCompat&&(this.gateway.on("canvas",e=>this.canvasOrch.handleOpenClawCanvasEvent(e)),this.logger.info?.("[acp-server] OpenClaw native canvas compat enabled — listening for canvas events")),this.gateway.on("connected",()=>{this.logger.info?.("[acp-server] Connected to OpenClaw Gateway"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"gateway.connected",severity:"info"}),this.core.resubscribeAllSessionMessages(),this.core.refreshCronIsolatedSessionKeys(),this.tryAgentSync()}),this.gateway.on("disconnected",()=>{this.logger.warn?.("[acp-server] Gateway disconnected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"gateway.disconnected",severity:"warn"}),this.core.cleanupAllPendingPrompts()}),this.gateway.on("reconnecting",e=>{this.logger.info?.(`[acp-server] Reconnecting to Gateway attempt=${e.attempt} delay=${Math.round(e.delayMs)}ms`)}),this.gateway.on("reconnect-exhausted",e=>{this.logger.error?.(`[acp-server] Gateway reconnect exhausted after ${e} attempts`)}),this.gateway.on("error",e=>{this.logger.error?.("[acp-server] Gateway error:",e.message)}),this.gateway.on("transport",e=>{this.logger.info?.(`[acp-server] transport.${e.event} durationMs=${e.durationMs??"?"}`),this.writeObs({component:"gateway-client",domain:"lifecycle",name:`transport.${e.event}`,severity:"connect_fail"===e.event||"error"===e.event?"warn":"debug",payload:e})}),this.gateway.on("reconnect-notify-scheduled",e=>{this.logger.info?.(`[acp-server] Server-initiated reconnect scheduled in ${e.delayMs}ms`)}),this.gateway.on("reconnect-notify-fired",()=>{this.logger.info?.("[acp-server] Server-initiated reconnect firing")});try{await this.gateway.start()}catch(e){this.logger.error?.("[acp-server] Initial Gateway connect failed:",e)}}handleConnection(e,t){if(this.client){this.logger.warn?.("[acp-server] Replacing existing ACP client with new connection (takeover)");const e=this.client;this.client=null;try{e.close(1008,"replaced by new client")}catch{e.terminate()}}this.client=e,this.core.initialized=!1,this.logger.info?.("[acp-server] ACP client connected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"client.connected",severity:"info"}),e.on("message",e=>{const t="string"==typeof e?e:e.toString("utf-8");try{const e=JSON.parse(t);"id"in e&&void 0!==e.id?this.core.handleRequest(e).catch(e=>{this.logger.error?.(`[acp-server] request failed: ${e instanceof Error?e.message:String(e)}`)}):this.core.handleNotification(e)}catch{this.logger.error?.("[acp-server] Invalid JSON-RPC message")}}),e.on("close",()=>{this.client===e&&(this.client=null,this.core.initialized=!1),this.logger.info?.("[acp-server] ACP client disconnected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"client.disconnected",severity:"info"})})}pushToolResultContent(e,t,s,n){this.core.pushToolResultContent(e,t,s,n)}setCanvasState(e,t){this.canvasOrch.setCanvasState(e,t)}wireRelayActionHandler(){this.canvasOrch.wireRelayActionHandler()}isCanvasActive(e){return this.canvasOrch.isCanvasActive(e)}isCanvasActiveForGatewayKey(e){return this.canvasOrch.isCanvasActiveForGatewayKey(e)}broadcastNotification(e,t){this.transport.sendNotification(e,t)}getActiveSessionId(){return this.state.lastActiveSessionId}getSessionIdForToolCall(e){const t=this.pendingToolCallSessionKeys.length>0?this.pendingToolCallSessionKeys[this.pendingToolCallSessionKeys.length-1]:void 0;if(t){const s=this.state.findSessionByKey(t)??this.core.ensureSessionForKey(t);if(s?.sessionId)return e&&this.state.toolCallToSessionMap.set(e,s.sessionId),s.sessionId}if(e){const t=this.state.toolCallToSessionMap.get(e);if(t)return t;const s=this.state.toolCallIdMap.get(e);if(s&&s!==e){const e=this.state.toolCallToSessionMap.get(s);if(e)return e}const n=e.split("_");if(n.length>=3&&"tc"===n[0]){const e=n[1],t=this.state.promptsByRunId.get(e);if(t?.sessionId)return t.sessionId}}this.logger.warn?.(`[acp-server] getSessionIdForToolCall MISS: toolCallId=${e??"(none)"}, sessions=${this.state.sessions.size}, pendingKey=${t??"none"}`)}getSessionIdForActivePrompt(){return this.getSessionIdForToolCall()}setPendingToolCallSessionKey(e){e&&(this.pendingToolCallSessionKeys.push(e),this.pendingToolCallSessionKeys.length>16&&this.pendingToolCallSessionKeys.shift())}preMapToolCallSession(e){const t=this.pendingToolCallSessionKeys.length>0?this.pendingToolCallSessionKeys[this.pendingToolCallSessionKeys.length-1]:void 0;if(!t||!e)return;if(this.state.toolCallToSessionMap.has(e))return;const s=this.state.findSessionByKey(t)??this.core.ensureSessionForKey(t);s?.sessionId&&this.state.toolCallToSessionMap.set(e,s.sessionId)}waitForAgentMapping(){return this.core.waitForAgentMapping()}onceAgentMappingReady(e){this.core.onceAgentMappingReady(e)}flushPendingCanvasLinks(){this.canvasOrch.flushPendingCanvasLinks()}onRelayReconnected(){this.canvasOrch.onRelayReconnected()}getLocalAgentId(){return this.config.gateway.agentId||this.core.getDefaultAgentId()}getDefaultPlatformAgentId(){return this.getDefaultPlatformAgent()?.id}getDefaultPlatformAgent(){const e=this.core.agentMapping;if(e&&0!==e.size)return e.values().next().value??void 0}getPlatformAgentIdForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return this.core.resolvePlatformAgentId(s?.agentId??"")??s?.platformAgentId}getGatewaySessionKeyForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return s?.gatewaySessionKey}getMentionsForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return s?.activeMentions}getResourceRenderer(){return this.canvasOrch.resourceRenderer}getDescriptorRegistry(){return this.canvasOrch.descriptorRegistry}getFormBuilder(){return this.canvasOrch.formBuilder}getSchemaRegistry(){return this.canvasOrch.schemaRegistry}registerSkillFormSchemas(e,t){const s=this.canvasOrch.schemaRegistry;s&&import("node:fs/promises").then(async({readFile:n})=>{try{const i=`${t}/skill.json`,r=await n(i,"utf-8"),a=JSON.parse(r);if(a.formSchemas?.length){for(const e of a.formSchemas)s.register({...e,submitLabel:e.submitLabel||"Submit",fields:e.fields});this.logger.info?.(`[acp-server] Registered ${a.formSchemas.length} form schema(s) from skill "${e}"`)}}catch{}}).catch(e=>{this.logger.debug?.(`[acp-server] skill form schema import failed: ${e instanceof Error?e.message:String(e)}`)})}emitCanvasActionAsUserMessage(e,t){this.canvasOrch.emitCanvasActionAsUserMessage(e,t)}async stop(){if(this.agentSyncRetryTimer&&(clearTimeout(this.agentSyncRetryTimer),this.agentSyncRetryTimer=null),this.state.destroy(),this.canvasOrch.destroy(),this.gateway&&(this.gateway.removeAllListeners(),this.gateway.stop(),this.gateway=null),this.client&&(this.client.removeAllListeners(),this.client.close(),this.client=null),this.bridgeInstance){try{await this.bridgeInstance.close()}catch(e){this.logger.debug?.(`[acp-server] bridge.close failed during stop: ${e instanceof Error?e.message:String(e)}`)}this.bridgeInstance=null}this.bridgeConsecutiveFailures=0,this.terminalHandler.destroy(),this.terminalMgr.destroy(),this.wss&&(this.wss.removeAllListeners(),this.wss.close(),this.wss=null),this.logger.info?.("[acp-server] Stopped"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"lifecycle.shutdown",severity:"info"})}}
|
package/dist/agent-sync.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function isAgentSyncWaitForGateway(t){return!(!t||t instanceof Map||"wait_gateway"!==t.status)}export async function syncAgentsToPlatform(t){const{gateway:e,agentGatewayUrl:n,capabilities:a,agentFetch:s,logger:i}=t;if(!s)return i?.debug?.("[agent-sync] no agentFetch — skipping sync (no key pair)"),null;if(!n)return i?.debug?.("[agent-sync] no agentGatewayUrl — skipping sync"),null;try{const t=await e.request("agents.list",{}),r=t?.agents??[];if(0===r.length)return i?.debug?.("[agent-sync] no agents from Gateway — skipping sync"),null;const o=[];for(const t of r){let n=[];try{const a=await e.request("skills.status",{agentId:t.id});n=(a?.skills??[]).filter(t=>t.eligible&&!t.disabled).map(t=>({name:t.name,description:t.description,...t.emoji?{emoji:t.emoji}:{}}))}catch{i?.debug?.(`[agent-sync] skills.status failed for agent ${t.id} — continuing without skills`)}const s={};if(a)for(const[t,e]of Object.entries(a))e&&(s[t]=!0);o.push({name:t.id,description:t.name||t.identity?.name||t.id,version:"0.1.0",capabilities:s,skills:n,avatarUrl:t.identity?.avatarUrl||"",homepage:""})}const c=new URL("/api/v1/agents/sync",n),
|
|
1
|
+
export function isAgentSyncWaitForGateway(t){return!(!t||t instanceof Map||"wait_gateway"!==t.status)}export async function syncAgentsToPlatform(t){const{gateway:e,agentGatewayUrl:n,capabilities:a,agentFetch:s,logger:i}=t;if(!s)return i?.debug?.("[agent-sync] no agentFetch — skipping sync (no key pair)"),null;if(!n)return i?.debug?.("[agent-sync] no agentGatewayUrl — skipping sync"),null;try{const t=await e.request("agents.list",{}),r=t?.agents??[];if(0===r.length)return i?.debug?.("[agent-sync] no agents from Gateway — skipping sync"),null;const o=[];for(const t of r){let n=[];try{const a=await e.request("skills.status",{agentId:t.id});n=(a?.skills??[]).filter(t=>t.eligible&&!t.disabled).map(t=>({name:t.name,description:t.description,...t.emoji?{emoji:t.emoji}:{}}))}catch{i?.debug?.(`[agent-sync] skills.status failed for agent ${t.id} — continuing without skills`)}const s={};if(a)for(const[t,e]of Object.entries(a))e&&(s[t]=!0);const r=t.identity?.name||t.name||t.id;o.push({name:t.id,displayName:r,description:t.name||t.identity?.name||t.id,version:"0.1.0",capabilities:s,skills:n,avatarUrl:t.identity?.avatarUrl||"",homepage:""})}const c=new URL("/api/v1/agents/sync",n),d=await s(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agents:o})});if(d.ok){const t=await d.json();i?.info?.(`[agent-sync] synced ${o.length} agent(s) — created=${t.created??0} updated=${t.updated??0} deactivated=${t.deactivated??0}`);const e=new Map,n=Array.isArray(t.data)?t.data:[];for(const t of n)t&&"string"==typeof t.name&&"string"==typeof t.id&&e.set(t.name,{id:t.id,instanceId:t.instanceId??"",name:t.name,displayName:t.displayName??t.name,description:t.description??"",version:t.version??"",avatarUrl:t.avatarUrl??"",status:t.status??"active"});return e.size>0?e:null}{const t=await d.text().catch(()=>"");return i?.warn?.(`[agent-sync] sync failed: HTTP ${d.status} — ${t.slice(0,200)}`),null}}catch(t){const e=t instanceof Error?t.message:String(t);return i?.warn?.(`[agent-sync] sync error: ${e}`),"Not connected to Gateway"===e?{status:"wait_gateway",reason:e}:null}}
|
package/dist/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdirSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,join}from"node:path";function trimStr(e){if("string"==typeof e){const r=e.trim();return r.length>0?r:void 0}}function readInt(e){if("number"==typeof e&&Number.isFinite(e))return Math.trunc(e);if("string"==typeof e){const r=parseInt(e,10);return Number.isFinite(r)?r:void 0}}function readBool(e){return"boolean"==typeof e?e:"true"===e||"false"!==e&&void 0}function pick(e,r){for(const r of e)if(void 0!==r.value)return{value:r.value,source:r.source};return r}const CURRENT_CONFIG_PROTOCOL=1;function shouldTrustOperationalConfig(e){const r=e._generator;if(!r)return!1;return("number"==typeof r.configProtocol?r.configProtocol:0)>=1}const DEFAULT_GATEWAY_URL="ws://127.0.0.1:18789",DEFAULT_LOG_DIR=join(process.env.OPENCLAW_HOME||join(homedir(),".openclaw"),"beeos-logs"),DEFAULT_OPENCLAW_CONFIG_PATH=join(homedir(),".openclaw","openclaw.json");export function resolveConfigWithMeta(e){const r=e.pluginConfig??{},
|
|
1
|
+
import{mkdirSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,join}from"node:path";export const CRON_DURATION_FLOOR_MS=3e4;export const CRON_DURATION_CAP_DEFAULT_MS=72e5;function trimStr(e){if("string"==typeof e){const r=e.trim();return r.length>0?r:void 0}}function readInt(e){if("number"==typeof e&&Number.isFinite(e))return Math.trunc(e);if("string"==typeof e){const r=parseInt(e,10);return Number.isFinite(r)?r:void 0}}function readBool(e){return"boolean"==typeof e?e:"true"===e||"false"!==e&&void 0}function pick(e,r){for(const r of e)if(void 0!==r.value)return{value:r.value,source:r.source};return r}const CURRENT_CONFIG_PROTOCOL=1;function shouldTrustOperationalConfig(e){const r=e._generator;if(!r)return!1;return("number"==typeof r.configProtocol?r.configProtocol:0)>=1}const DEFAULT_GATEWAY_URL="ws://127.0.0.1:18789",DEFAULT_LOG_DIR=join(process.env.OPENCLAW_HOME||join(homedir(),".openclaw"),"beeos-logs"),DEFAULT_OPENCLAW_CONFIG_PATH=join(homedir(),".openclaw","openclaw.json");export function resolveConfigWithMeta(e){const r=e.pluginConfig??{},a=e.openclawConfig??{},o=e.openclawConfigPath??DEFAULT_OPENCLAW_CONFIG_PATH,u=shouldTrustOperationalConfig(r),n=pick([{source:"pluginConfig",value:trimStr(r.agentGatewayUrl)},{source:"pluginConfig",value:trimStr(r.platformUrl)},{source:"env",value:trimStr(process.env.AGENT_GATEWAY_URL)}],{source:"default",value:""}),l=r.gateway??{},t=(a.gateway??{}).auth??{},s=pick([...u?[{source:"pluginConfig",value:trimStr(l.url)}]:[],{source:"env",value:trimStr(process.env.BEEOS_GATEWAY_URL)}],{source:"default",value:DEFAULT_GATEWAY_URL}),i=pick([{source:"openclawConfig",value:trimStr(t.token)},{source:"pluginConfig",value:trimStr(l.token)},{source:"env",value:trimStr(process.env.BEEOS_GATEWAY_TOKEN)}],{source:"default",value:""}),c=pick([...u?[{source:"pluginConfig",value:readInt(l.protocol)}]:[]],{source:"default",value:3}),v=pick([...u?[{source:"pluginConfig",value:trimStr(l.clientId)}]:[]],{source:"default",value:`beeos-claw-${process.pid}`}),p=pick([...u?[{source:"pluginConfig",value:trimStr(l.agentId)}]:[]],{source:"default",value:""}),d=r.bridge??{},g=pick([{source:"pluginConfig",value:trimStr(r.keyFile)},{source:"pluginConfig",value:trimStr(d.keyFile)},{source:"env",value:trimStr(process.env.BRIDGE_KEY_FILE)}],{source:"default",value:""}),f=pick([{source:"env",value:trimStr(process.env.BRIDGE_URL)}],{source:"default",value:""}),m=pick([...u?[{source:"pluginConfig",value:trimStr(d.service)}]:[],{source:"env",value:trimStr(process.env.BRIDGE_SERVICE)}],{source:"default",value:"acp"}),E=d.shell??{},_=pick([...u?[{source:"pluginConfig",value:readBool(E.enabled)}]:[],{source:"env",value:readBool(process.env.BEEOS_SHELL_ENABLED)}],{source:"default",value:!0}),S=r.retry??{},A=pick([...u?[{source:"pluginConfig",value:readInt(S.baseMs)}]:[]],{source:"default",value:1e3}),C=pick([...u?[{source:"pluginConfig",value:readInt(S.maxMs)}]:[]],{source:"default",value:6e5}),I=pick([...u?[{source:"pluginConfig",value:readInt(S.maxAttempts)}]:[]],{source:"default",value:0}),M=r.log??{},O=pick([...u?[{source:"pluginConfig",value:readBool(M.enabled)}]:[],{source:"env",value:readBool(process.env.BEEOS_LOG_ENABLED)}],{source:"default",value:!0}),T=pick([...u?[{source:"pluginConfig",value:readBool(M.verbose)}]:[]],{source:"default",value:!1}),R=pick([{source:"pluginConfig",value:trimStr(M.dir)}],{source:"default",value:DEFAULT_LOG_DIR}),k=pick([...u?[{source:"pluginConfig",value:readInt(d.promptTimeoutMs)}]:[],{source:"env",value:readInt(process.env.BEEOS_PROMPT_TIMEOUT_MS)}],{source:"default",value:6e5}),w=pick([...u?[{source:"pluginConfig",value:readInt(r.terminalWsPort)}]:[],{source:"env",value:readInt(process.env.BEEOS_TERMINAL_WS_PORT)}],{source:"default",value:18801}),y=(u?trimStr(r.terminalWsAllowedOrigins):void 0)??trimStr(process.env.BEEOS_TERMINAL_WS_ALLOWED_ORIGINS),L=y?y.split(",").map(e=>e.trim()).filter(Boolean):void 0,N=pick([{source:y?"pluginConfig":"default",value:L?.length?L:void 0}],{source:"default",value:["localhost","127.0.0.1","::1"]}),B=pick([...u?[{source:"pluginConfig",value:readInt(r.streamIdleTimeoutMs)}]:[],{source:"env",value:readInt(process.env.BEEOS_STREAM_IDLE_TIMEOUT_MS)}],{source:"default",value:15e3}),U=pick([...u?[{source:"pluginConfig",value:readInt(r.streamStaleTimeoutMs)}]:[],{source:"env",value:readInt(process.env.BEEOS_STREAM_STALE_TIMEOUT_MS)}],{source:"default",value:6e5}),b=pick([...u?[{source:"pluginConfig",value:readInt(r.cronSignalWindowMs)}]:[],{source:"env",value:readInt(process.env.BEEOS_CRON_SIGNAL_WINDOW_MS)}],{source:"default",value:6e4}),h=pick([{source:"pluginConfig",value:readInt(r.cronMaxDurationDefaultMs)},{source:"env",value:readInt(process.env.BEEOS_CRON_MAX_DURATION_DEFAULT_MS)}],{source:"default",value:6e5}),G=pick([{source:"pluginConfig",value:readInt(r.cronMaxDurationCapMs)},{source:"env",value:readInt(process.env.BEEOS_CRON_MAX_DURATION_CAP_MS)}],{source:"default",value:72e5}),D=pick([{source:"env",value:trimStr(process.env.CANVAS_RELAY_URL)},{source:"pluginConfig",value:trimStr(r.canvasRelayUrl)}],{source:"default",value:"https://canvas-relay.beeos.ai"}),P=pick([...u?[{source:"pluginConfig",value:readBool(r.canvasEnabled)}]:[],{source:"env",value:readBool(process.env.BEEOS_CANVAS_ENABLED)}],{source:"default",value:!0}),W=pick([...u?[{source:"pluginConfig",value:readBool(r.openclawCanvasCompat)}]:[],{source:"env",value:readBool(process.env.BEEOS_OPENCLAW_CANVAS_COMPAT)}],{source:"default",value:!1}),x=r.messageBus??{},F=pick([{source:"pluginConfig",value:trimStr(x.serviceUrl)},{source:"env",value:trimStr(process.env.MESSAGE_SERVICE_URL)}],{source:"default",value:""}),H=pick([{source:"pluginConfig",value:trimStr(x.url)},{source:"env",value:trimStr(process.env.CENTRIFUGO_URL)}],{source:"default",value:""}),Y=pick([{source:"pluginConfig",value:trimStr(x.principalId)},{source:"env",value:trimStr(process.env.BEEOS_PRINCIPAL_ID)}],{source:"default",value:""}),j=pick([{source:"pluginConfig",value:readBool(x.a2aEnabled)},{source:"env",value:readBool(process.env.BEEOS_A2A_ENABLED)}],{source:"default",value:!0}),$=pick([{source:"pluginConfig",value:readBool(x.enabled)},{source:"env",value:readBool(process.env.BEEOS_MESSAGE_BUS_ENABLED)}],{source:"default",value:!(!F.value&&!n.value)}),V={agentGatewayUrl:n.value.replace(/\/+$/,""),keyFile:g.value,bridge:{url:f.value,service:m.value,mode:trimStr(d.mode),shell:{enabled:_.value},promptTimeoutMs:k.value},gateway:{url:s.value,token:i.value,protocol:c.value,clientId:v.value,agentId:p.value},retry:{baseMs:Math.max(0,A.value),maxMs:Math.max(0,C.value),maxAttempts:Math.max(0,I.value)},log:{enabled:O.value,verbose:T.value,dir:R.value},promptTimeoutMs:k.value,terminalWsPort:w.value,terminalWsAllowedOrigins:N.value,streamIdleTimeoutMs:Math.max(0,B.value),streamStaleTimeoutMs:Math.max(0,U.value),cronSignalWindowMs:Math.max(0,b.value),cronMaxDurationDefaultMs:Math.max(3e4,h.value),cronMaxDurationCapMs:Math.max(6e4,G.value),canvasRelayUrl:D.value.replace(/\/+$/,""),canvasEnabled:P.value,openclawCanvasCompat:W.value,messageBus:{enabled:$.value,serviceUrl:F.value,url:H.value,principalId:Y.value,a2aEnabled:j.value}},K={agentGatewayUrl:n.source,keyFile:g.source,bridge:{url:f.source,service:m.source,shell:{enabled:_.source}},gateway:{url:s.source,token:i.source,protocol:c.source,clientId:v.source,agentId:p.source},retry:{baseMs:A.source,maxMs:C.source,maxAttempts:I.source},log:{enabled:O.source,verbose:T.source,dir:R.source},promptTimeoutMs:k.source,terminalWsPort:w.source,terminalWsAllowedOrigins:N.source,streamIdleTimeoutMs:B.source,streamStaleTimeoutMs:U.source,cronSignalWindowMs:b.source,cronMaxDurationDefaultMs:h.source,cronMaxDurationCapMs:G.source,canvasRelayUrl:D.source,canvasEnabled:P.source,openclawCanvasCompat:W.source,messageBus:{enabled:$.source,serviceUrl:F.source,url:H.source,principalId:Y.source,a2aEnabled:j.source}},X=[];return V.agentGatewayUrl||X.push({code:"CONFIG_AGENT_GATEWAY_URL_MISSING",severity:"error",message:"agentGatewayUrl is required for file uploads and Agent Gateway callbacks",nextSteps:[`Set plugins.entries.beeos-claw.config.agentGatewayUrl in ${o}`,"Or set the AGENT_GATEWAY_URL environment variable"]}),V.gateway.token||X.push({code:"CONFIG_GATEWAY_TOKEN_MISSING",severity:"warn",message:"gateway.token is empty; Gateway auth may fail if authentication is enabled",nextSteps:[`Set gateway.auth.token in ${o}`,`Or set plugins.entries.beeos-claw.config.gateway.token in ${o}`]}),{config:V,sources:K,validation:X,openclawConfigPath:o}}export function resolveConfig(e){const{config:r,validation:a}=resolveConfigWithMeta({pluginConfig:e}),o=a.find(e=>"error"===e.severity);if(o)throw new Error(`[beeos-claw] ${o.message}`);return r}const MIRROR_PATH=join(process.env.OPENCLAW_HOME||join(homedir(),".openclaw"),"beeos-claw","openclaw.json");export function mirrorOpenClawConfig(e){if(!e||"object"!=typeof e||Array.isArray(e))return{copied:!1,destinationPath:MIRROR_PATH,reason:"config_invalid"};try{return mkdirSync(dirname(MIRROR_PATH),{recursive:!0}),writeFileSync(MIRROR_PATH,JSON.stringify(e,null,2)+"\n",{encoding:"utf8",mode:384}),{copied:!0,destinationPath:MIRROR_PATH}}catch(e){return{copied:!1,destinationPath:MIRROR_PATH,reason:e instanceof Error?e.message:"write_failed"}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{mkdir,readFile,writeFile}from"node:fs/promises";import{dirname,join}from"node:path";import{homedir}from"node:os";const OVERRIDES_DIR=join(process.env.OPENCLAW_HOME||join(homedir(),".openclaw"),"beeos-claw"),OVERRIDES_PATH=join(OVERRIDES_DIR,"cron-overrides.json"),MAX_CACHE_SIZE=512;class LruCache{_map=new Map;get(e){const t=this._map.get(e);return void 0!==t&&(this._map.delete(e),this._map.set(e,t)),t}set(e,t){if(this._map.delete(e),this._map.set(e,t),this._map.size>512){const e=this._map.keys().next().value;void 0!==e&&this._map.delete(e)}}delete(e){return this._map.delete(e)}entries(){return this._map.entries()}get size(){return this._map.size}clear(){this._map.clear()}}export function createCronOverridesStore(e){const t=new LruCache;let r=!1;async function i(){if(r)return;const i=await async function(){try{const t=await readFile(OVERRIDES_PATH,"utf-8"),r=JSON.parse(t);return r&&"object"==typeof r&&r.jobs&&"object"==typeof r.jobs?r:(e?.warn?.("[cron-overrides] invalid file format, resetting"),{jobs:{}})}catch(t){const r=t?.code;return"ENOENT"===r||e?.warn?.(`[cron-overrides] failed to load: ${t instanceof Error?t.message:t}`),{jobs:{}}}}();for(const[e,r]of Object.entries(i.jobs))"number"==typeof r&&Number.isFinite(r)&&r>0&&t.set(e,r);r=!0}async function s(){const r={};for(const[e,i]of t.entries())r[e]=i;const i={jobs:r};try{await mkdir(dirname(OVERRIDES_PATH),{recursive:!0}),await writeFile(OVERRIDES_PATH,JSON.stringify(i,null,2)+"\n",{encoding:"utf-8",mode:384})}catch(t){e?.warn?.(`[cron-overrides] failed to persist: ${t instanceof Error?t.message:t}`)}}return{get:e=>t.get(e),async set(e,r){await i(),t.set(e,Math.max(1,Math.trunc(r))),await s()},async delete(e){await i(),t.delete(e)&&await s()},async reconcile(r){await i();const n=new Set(r);let o=!1;for(const[e]of t.entries())n.has(e)||(t.delete(e),o=!0);o&&(e?.debug?.(`[cron-overrides] reconcile removed stale entries, remaining=${t.size}`),await s())}}}
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveConfigWithMeta,mirrorOpenClawConfig}from"./config.js";import{MessageSDK,createMessagingTokenProvider,extractChatPrompt}from"@beeos-ai/message-sdk";import{registerA2ATools,TaskHandleRegistry}from"./a2a/tools.js";import{BEEOS_UPLOAD_TOOL_NAME,BEEOS_UPLOAD_TOOL_SCHEMA,BEEOS_UPLOAD_TOOL_DESCRIPTION,executeUpload}from"./upload/tool.js";import{writeUploadToolResult,cleanupUploadToolResultCache}from"./upload/result-cache.js";import{handleFileStage}from"./upload/file-stage.js";import{handleStatusRequest}from"./status.js";import{ACPServer}from"./acp-server.js";import{createObsEventWriter}from"./observability.js";import{resolvePluginVersion}from"./plugin-version.js";import{createTerminalWebSocketService}from"./terminal/websocket.js";import{TerminalManager}from"./terminal/session-manager.js";import{loadAgentKeyPair,agentFetch}from"./agent-auth.js";import{readDiscoveryCache,writeDiscoveryCache}from"./discovery-cache.js";import{discoverBridgeFromGW}from"./bridge-discovery.js";import{setUploadDeps}from"./upload/upload-file.js";import{registerLocalFileExtractor}from"./upload/local-file-extractors.js";import{browserScreenshotExtractor}from"./browser/screenshot-extractor.js";import{CanvasStateManager}from"./canvas/state.js";import{CanvasRelayClient}from"./canvas/relay-client.js";import{RENDER_UI_TOOL_NAME,RENDER_UI_TOOL_DESCRIPTION,RENDER_UI_TOOL_SCHEMA,CLOSE_UI_TOOL_NAME,CLOSE_UI_TOOL_DESCRIPTION,CLOSE_UI_TOOL_SCHEMA,createRenderUiHandler,createCloseUiHandler,CANVAS_SYSTEM_PROMPT}from"./canvas/tools.js";import{FormSchemaRegistry}from"./surface/form-schema-registry.js";import{buildCronSchemas}from"./surface/cron-schemas.js";import{RENDER_FORM_TOOL_NAME,RENDER_FORM_TOOL_SCHEMA,buildRenderFormDescription,createRenderFormHandler}from"./surface/render-form-tool.js";import{ResourceDescriptorRegistry}from"./surface/resource-descriptor-registry.js";import{CRON_RESOURCE}from"./surface/cron-resource.js";import{generateActionTools}from"./surface/action-tool-generator.js";import{buildThirdPartyChannelSet,isThirdPartyChannel}from"./channel-detection.js";const PLUGIN_VERSION=resolvePluginVersion();let agentKeys=null,sharedCanvasState=null,_initializing=!1,_pluginRegisteredAt=0;const ED25519_PKCS8_PREFIX=Buffer.from("302e020100300506032b657004220420","hex");function agentKeyPairToMessagingIdentity(e){return{publicKeyBase64:()=>Buffer.from(e.publicKey).toString("base64"),sign:async o=>{const{createPrivateKey:r,sign:a}=await import("node:crypto"),t=r({key:32===e.privateKey.length?Buffer.concat([ED25519_PKCS8_PREFIX,Buffer.from(e.privateKey)]):Buffer.from(e.privateKey),format:"der",type:"pkcs8"});return new Uint8Array(a(null,Buffer.from(o),t))}}}let unhandledRejectionObserverInstalled=!1;function installUnhandledRejectionObserver(e,o){unhandledRejectionObserverInstalled||(unhandledRejectionObserverInstalled=!0,process.on("unhandledRejection",r=>{const a=r instanceof Error?r.message:String(r);e.logger.error?.("[beeos-claw] unhandledRejection:",r),o({component:"plugin",domain:"fatal",name:"unhandled_rejection",severity:"error",summary:a,error:{code:"unhandled_rejection",message:a}})}))}function initializePlugin(e){let o,r;try{o=e.runtime?.config?.loadConfig?.()}catch{}try{r=resolveConfigWithMeta({pluginConfig:e.pluginConfig??{},openclawConfig:o})}catch(o){return e.logger.error?.("[beeos-claw] Failed to resolve config:",o),null}const a=r.config,t=buildThirdPartyChannelSet(o);t.size>0&&e.logger.info?.(`[beeos-claw] Third-party channels detected: ${[...t].join(", ")}`);const s=a.log.enabled?createObsEventWriter({dir:a.log.dir,redaction:{gatewayToken:a.gateway.token},logger:e.logger}):()=>{};installUnhandledRejectionObserver(e,s),s({component:"plugin",domain:"lifecycle",name:"lifecycle.startup",severity:"info",payload:{pluginVersion:PLUGIN_VERSION,pid:process.pid,nodeVersion:process.version,cwd:process.cwd()}}),s({component:"plugin",domain:"config",name:"config.resolved",severity:"info",payload:{config:a,sources:r.sources,openclawConfigPath:r.openclawConfigPath}});for(const o of r.validation)s({component:"plugin",domain:"config",name:"config.validation",severity:o.severity,summary:o.message,error:{code:o.code,message:o.message,nextSteps:o.nextSteps}}),"error"===o.severity?e.logger.error?.(`[beeos-claw] ${o.message}`):e.logger.warn?.(`[beeos-claw] ${o.message}`);if(r.validation.some(e=>"error"===e.severity)&&e.logger.error?.("[beeos-claw] Plugin has configuration errors — some features may not work."),a.keyFile)try{agentKeys=loadAgentKeyPair(a.keyFile);const o=Buffer.from(agentKeys.publicKey).toString("base64");e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (publicKey: ${o})`)}catch(o){e.logger.warn?.(`[beeos-claw] Failed to load agent key pair: ${o}`),e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (no key pair — signed requests disabled)`)}else e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (no keyFile configured)`);return agentKeys&&a.agentGatewayUrl&&(setUploadDeps({gatewayUrl:a.agentGatewayUrl,keys:agentKeys,logger:e.logger}),registerLocalFileExtractor(browserScreenshotExtractor),e.logger.info?.("[beeos-claw] Upload deps + browser screenshot extractor registered")),{cfg:a,writeObs:s,thirdPartyChannels:t,openclawConfig:o}}function registerUploadTools(e,o,r){const{cfg:a,writeObs:t}=o;cleanupUploadToolResultCache().catch(o=>{e.logger.warn?.(`[beeos_upload_file] cache cleanup failed on startup: ${String(o)}`)}),e.registerTool({name:BEEOS_UPLOAD_TOOL_NAME,description:BEEOS_UPLOAD_TOOL_DESCRIPTION,parameters:BEEOS_UPLOAD_TOOL_SCHEMA,async execute(o,r,s){e.logger.debug?.(`[beeos_upload_file] toolCallId=${o} params=${JSON.stringify(r)}`);const n=await executeUpload(r,a,agentKeys,s);return e.logger.debug?.(`[beeos_upload_file] toolCallId=${o} ok=${n.ok}`),t({component:"upload-tool",domain:"tool",name:n.ok?"upload.success":"upload.failure",severity:n.ok?"info":"warn",payload:{toolCallId:o,ok:n.ok,fileCount:n.files?.length??0,error:n.error}}),(async r=>{try{await writeUploadToolResult(o,BEEOS_UPLOAD_TOOL_NAME,r),await cleanupUploadToolResultCache()}catch(r){e.logger.warn?.(`[beeos_upload_file] persist cache failed toolCallId=${o}: ${String(r)}`)}return r})(n)}}),e.registerHttpRoute({path:"/beeos/files/stage",auth:"gateway",async handler(e,r){await handleFileStage(e,r,o.cfg)}}),e.registerHttpRoute({path:"/beeos/status",auth:"plugin",handler(e,o){handleStatusRequest(e,o,{publicKey:agentKeys?.publicKey??null,pluginVersion:PLUGIN_VERSION})}})}function registerServices(e,o,r){const{cfg:a,writeObs:t,thirdPartyChannels:s}=o,n=agentKeys?(e,o)=>agentFetch(e,agentKeys,o):void 0,i=agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):void 0,l=new ACPServer(a,e.logger,t,n,i,s);r.current=l,e.registerService({id:"beeos-acp",async start(){const o=Date.now(),r=_pluginRegisteredAt?o-_pluginRegisteredAt:-1;if(e.logger.info?.(`[beeos-claw] beeos-acp service start() begin, sincePluginRegister=${r}ms, bridge.url=${a.bridge.url||"(empty)"}`),!a.bridge.url&&a.agentGatewayUrl&&n){const o=Date.now(),r=await discoverBridgeFromGW(a.agentGatewayUrl,n);if(e.logger.info?.(`[beeos-claw] bridge discovery took ${Date.now()-o}ms result=${r?.url??"null"}`),r)a.bridge.url=r.url,writeDiscoveryCache({bridge:{url:r.url,discoveredAt:Date.now()}}),e.logger.info?.(`[beeos-claw] Bridge URL discovered from Agent Gateway: ${r.url}`);else{const o=readDiscoveryCache();o?.bridge?.url?(a.bridge.url=o.bridge.url,e.logger.info?.(`[beeos-claw] Bridge URL from cache (GW unreachable): ${o.bridge.url}`)):e.logger.debug?.("[beeos-claw] Bridge URL not available (no GW, no cache) — bridge disabled")}}await l.start(a.bridge.url||void 0),e.logger.info?.(`[beeos-claw] ACP Server started (total service start: ${Date.now()-o}ms)`)},async stop(){await l.stop(),e.logger.info?.("[beeos-claw] ACP Server stopped")}});const g=new TaskHandleRegistry;let c=null;const{enabled:d,url:p,principalId:u,a2aEnabled:f}=a.messageBus;let y;if(a.agentGatewayUrl&&agentKeys){const e=agentKeyPairToMessagingIdentity(agentKeys);y=createMessagingTokenProvider({agentGatewayUrl:a.agentGatewayUrl,identity:e})}if(d&&(y||a.messageBus.serviceUrl)){c=new MessageSDK({serviceUrl:y?void 0:a.messageBus.serviceUrl,centrifugoUrl:p},e.logger);const o=u,r=async o=>{c.onceConnected(()=>{l.setMessageSdk(c,o),e.logger.info?.("[beeos-claw] Message SDK connected (principalId=%s, via=%s)",o,y?"gateway":"direct")}),await c.connect(o,{centrifugoUrl:p,tokenProvider:y})};e.registerService({id:"beeos-message-bus",async start(){let a=o;if(a||(a=process.env.BEEOS_PRINCIPAL_ID||""),!a&&l)try{await l.waitForAgentMapping(),a=l.getDefaultPlatformAgent()?.instanceId||""}catch(o){e.logger.warn?.("[beeos-claw] Failed to resolve principalId from agent sync:",o)}a?await r(a):l?(e.logger.info?.("[beeos-claw] Message bus deferred: waiting for late agent sync..."),l.onceAgentMappingReady(()=>{const o=l.getDefaultPlatformAgent()?.instanceId;o?r(o).catch(o=>{e.logger.error?.("[beeos-claw] Deferred message bus connect failed:",o)}):e.logger.warn?.("[beeos-claw] Agent mapping ready but no principalId, message bus stays disabled")})):e.logger.warn?.("[beeos-claw] No principalId resolved, message bus disabled")},async stop(){await(c?.disconnect()),e.logger.info?.("[beeos-claw] Message SDK disconnected")}});const t=async(o,r)=>{const a=extractChatPrompt(r,{source:o,localAgentId:l.getLocalAgentId()});a&&(e.logger.debug?.(`[beeos-claw] ${o} received (sessionKey=%s, contextId=%s)`,a.sessionKey,a.contextId??"-"),await l.agentSend(a.message,a.files,a.sessionKey,void 0,a.channelId,a.messageId))};c.onMessage("chat_message",async e=>{await t("chat_message",e)});let s=!1;c.onMessage("agent_request",async o=>{s||(e.logger.warn?.("[beeos-claw] Received legacy 'agent_request' envelope — this path is deprecated and will be removed once all upstreams migrate to 'chat_message' (L0 AgentInvocationService)."),s=!0),await t("agent_request",o)})}else d?e.logger.warn?.("[beeos-claw] Message bus enabled but MESSAGE_SERVICE_URL not set — disabled"):e.logger.info?.("[beeos-claw] Message bus disabled (enabled=%s)",d);if(!1!==f&&a.agentGatewayUrl){const o=e=>l.getGatewaySessionKeyForToolCall(e),r=e=>l.getMentionsForToolCall(e),t=(e,o)=>{l.broadcastNotification(e,o)};registerA2ATools(e,{agentGatewayUrl:a.agentGatewayUrl,agentKeys:agentKeys,logger:e.logger},g,o,r,t),e.logger.info?.("[beeos-claw] A2A tools registered (beeos_discover_agents, beeos_call_agent) via REST")}if(a.canvasEnabled){sharedCanvasState||(sharedCanvasState=new CanvasStateManager);const o=sharedCanvasState;if(a.agentGatewayUrl&&agentKeys){let r;o.setLogger(e.logger);{const e=a.agentGatewayUrl,o=agentKeys;r=async()=>{const r=await agentFetch(`${e}/api/v1/canvas/token`,o,{method:"POST"});if(!r.ok){const e=await r.text().catch(()=>"");throw new Error(`Canvas token returned ${r.status}: ${e}`)}return r.json()}}e.registerService({id:"beeos-canvas-relay",async start(){try{await l.waitForAgentMapping();const t=l.getDefaultPlatformAgent();if(!t?.id)return void e.logger.info?.("[beeos-claw] Canvas Relay skipped: no agentId after sync");const s=new CanvasRelayClient({canvasRelayUrl:a.canvasRelayUrl,agentKeys:agentKeys,agentId:t.id,displayName:t.displayName,avatarUrl:t.avatarUrl,tokenProvider:r,onReconnect:()=>l.onRelayReconnected(),logger:e.logger});s.connect(),o.setRelayClient(s),o.setAgentId(t.id),l.wireRelayActionHandler(),l.flushPendingCanvasLinks(),e.logger.info?.(`[beeos-claw] Canvas Relay multiplexed client connected (agentId=${t.id}, name=${t.name??"none"})`)}catch(o){e.logger.warn?.(`[beeos-claw] Failed to start Canvas Relay client: ${o}`)}},stop(){o.getRelayClient()?.disconnect()}}),e.logger.info?.("[beeos-claw] Canvas Relay configured")}else e.logger.warn?.("[beeos-claw] Canvas Relay unavailable: agentGatewayUrl or agentKeys missing");const r={stateManager:o,logger:e.logger,writeObs:e=>t(e),isCanvasActive:e=>!e||l.isCanvasActiveForGatewayKey(e),getActiveSessionId:e=>l.getSessionIdForToolCall(e),getPlatformAgentId:e=>l.getPlatformAgentIdForToolCall(e),getGatewaySessionKey:e=>l.getGatewaySessionKeyForToolCall(e),waitForAgentSync:()=>l.waitForAgentMapping()},n=new FormSchemaRegistry,i=buildCronSchemas(s);n.register(i.create),n.register(i.update);const g=new ResourceDescriptorRegistry;g.register(CRON_RESOURCE);const c=e=>async(o,r,a)=>(l.preMapToolCallSession(o),e(o,r));e.registerTool({name:RENDER_UI_TOOL_NAME,description:RENDER_UI_TOOL_DESCRIPTION,parameters:RENDER_UI_TOOL_SCHEMA,execute:c(createRenderUiHandler(r))}),e.registerTool({name:CLOSE_UI_TOOL_NAME,description:CLOSE_UI_TOOL_DESCRIPTION,parameters:CLOSE_UI_TOOL_SCHEMA,execute:c(createCloseUiHandler(r))}),l.setCanvasState(o,{schemaRegistry:n,descriptorRegistry:g});const d=l.getFormBuilder();d&&e.registerTool({name:RENDER_FORM_TOOL_NAME,description:buildRenderFormDescription(n),parameters:RENDER_FORM_TOOL_SCHEMA,execute:c(createRenderFormHandler({registry:n,builder:d,logger:e.logger}))});const p=l.getResourceRenderer();if(p){generateActionTools(g,e,async(e,o)=>l.gatewayRequest(e,o),p,e.logger)}const u='\n\nTool selection guidance:\n- browser tool: Use when the user wants to OPEN, VISIT, NAVIGATE to a webpage, take SCREENSHOTS, interact with elements (click, type), or visually inspect pages.\n- beeos_search: Use ONLY for text-based information retrieval (fact-finding, research queries). Never for page interaction or screenshots.\n- beeos_fetch: Use ONLY to extract article text from a known URL. Never for visual content or screenshots.\nWhen the user says "open", "visit", "go to", "screenshot", or mentions seeing/viewing a webpage, ALWAYS prefer the browser tool.',f=new Set([RENDER_UI_TOOL_NAME,CLOSE_UI_TOOL_NAME,RENDER_FORM_TOOL_NAME]),y=256,m=new Map;if("function"==typeof e.on){try{e.on("before_prompt_build",(e,o)=>{if(o?.sessionKey){if(m.size>=y&&!m.has(o.sessionKey)){const e=m.keys().next().value;void 0!==e&&m.delete(e)}m.set(o.sessionKey,o.channelId)}if(isThirdPartyChannel(s,{sessionKey:o?.sessionKey,channelId:o?.channelId}))return;if(!o?.sessionKey)return{appendSystemContext:u};return l.isCanvasActiveForGatewayKey(o.sessionKey)?{appendSystemContext:CANVAS_SYSTEM_PROMPT+u}:{appendSystemContext:"Canvas is closed by user. Do NOT use render_ui, close_ui, or render_form. Respond with plain text only."+u}}),e.logger.debug?.("[beeos-claw] Canvas system prompt hook registered: before_prompt_build")}catch{e.logger.debug?.("[beeos-claw] before_prompt_build hook not supported")}try{e.on("before_tool_call",(e,o)=>{if(o?.sessionKey&&l.setPendingToolCallSessionKey(o.sessionKey),!f.has(e.toolName))return;return isThirdPartyChannel(s,{sessionKey:o?.sessionKey})?{block:!0,blockReason:"Canvas tools are not available in this channel. Respond with plain text only."}:o?.sessionKey?l.isCanvasActiveForGatewayKey(o.sessionKey)?void 0:{block:!0,blockReason:"Canvas is closed by user. Respond with plain text instead."}:{block:!0,blockReason:"Canvas session unknown. Respond with plain text instead."}}),e.logger.debug?.("[beeos-claw] Canvas tool guard registered: before_tool_call")}catch{e.logger.debug?.("[beeos-claw] before_tool_call hook not supported")}}e.logger.info?.("[beeos-claw] Canvas tools registered (render_ui, close_ui, render_form + auto-action tools)")}else e.logger.info?.("[beeos-claw] Canvas disabled by config (canvasEnabled=false)");const m=new TerminalManager,b=createTerminalWebSocketService({config:{port:a.terminalWsPort,token:agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):"",allowedOrigins:a.terminalWsAllowedOrigins},terminalMgr:m,logger:e.logger,writeObs:t});if(a.bridge.shell.enabled?e.registerService({id:"beeos-terminal-ws",start(){b.start(),e.logger.info?.(`[beeos-claw] Terminal WS started on port ${a.terminalWsPort}`)},stop(){b.stop(),m.destroy(),e.logger.info?.("[beeos-claw] Terminal WS stopped")}}):e.logger.info?.("[beeos-claw] Terminal/shell disabled by config (bridge.shell.enabled=false)"),o.openclawConfig){const r=mirrorOpenClawConfig(o.openclawConfig);r.copied?e.logger.info?.(`[beeos-claw] mirrored openclaw config to ${r.destinationPath}`):e.logger.debug?.(`[beeos-claw] openclaw config mirror skipped: ${r.reason}`)}}const plugin={id:"beeos-claw",name:"beeos-claw",description:"BeeOS platform bridge plugin for OpenClaw. Provides file upload/download, ACP bridge, and observability.",version:PLUGIN_VERSION,register(e){if(!_initializing)if(e.registrationMode&&"full"!==e.registrationMode)e.logger.debug?.(`[beeos-claw] Skipping registration (mode=${e.registrationMode})`);else{_initializing=!0;try{const o=initializePlugin(e);if(!o)return;const r={current:null};registerUploadTools(e,o,r),registerServices(e,o,r),_pluginRegisteredAt=Date.now(),e.logger.info?.("[beeos-claw] Plugin registered successfully")}finally{_initializing=!1}}}};export default plugin;
|
|
1
|
+
import{resolveConfigWithMeta,mirrorOpenClawConfig}from"./config.js";import{MessageClient}from"@beeos-ai/message-sdk";import{extractChatPrompt}from"@beeos-ai/message-sdk/chat-envelope";import{createTokenProvider}from"@beeos-ai/message-sdk/auth";import{registerA2ATools,TaskHandleRegistry}from"./a2a/tools.js";import{BEEOS_UPLOAD_TOOL_NAME,BEEOS_UPLOAD_TOOL_SCHEMA,BEEOS_UPLOAD_TOOL_DESCRIPTION,executeUpload}from"./upload/tool.js";import{writeUploadToolResult,cleanupUploadToolResultCache}from"./upload/result-cache.js";import{handleFileStage}from"./upload/file-stage.js";import{handleStatusRequest}from"./status.js";import{ACPServer}from"./acp-server.js";import{createObsEventWriter}from"./observability.js";import{resolvePluginVersion}from"./plugin-version.js";import{createTerminalWebSocketService}from"./terminal/websocket.js";import{TerminalManager}from"./terminal/session-manager.js";import{loadAgentKeyPair,agentFetch}from"./agent-auth.js";import{readDiscoveryCache,writeDiscoveryCache}from"./discovery-cache.js";import{discoverBridgeFromGW}from"./bridge-discovery.js";import{setUploadDeps}from"./upload/upload-file.js";import{registerLocalFileExtractor}from"./upload/local-file-extractors.js";import{browserScreenshotExtractor}from"./browser/screenshot-extractor.js";import{CanvasStateManager}from"./canvas/state.js";import{CanvasRelayClient}from"./canvas/relay-client.js";import{RENDER_UI_TOOL_NAME,RENDER_UI_TOOL_DESCRIPTION,RENDER_UI_TOOL_SCHEMA,CLOSE_UI_TOOL_NAME,CLOSE_UI_TOOL_DESCRIPTION,CLOSE_UI_TOOL_SCHEMA,createRenderUiHandler,createCloseUiHandler,CANVAS_SYSTEM_PROMPT}from"./canvas/tools.js";import{FormSchemaRegistry}from"./surface/form-schema-registry.js";import{buildCronSchemas}from"./surface/cron-schemas.js";import{RENDER_FORM_TOOL_NAME,RENDER_FORM_TOOL_SCHEMA,buildRenderFormDescription,createRenderFormHandler}from"./surface/render-form-tool.js";import{ResourceDescriptorRegistry}from"./surface/resource-descriptor-registry.js";import{CRON_RESOURCE}from"./surface/cron-resource.js";import{generateActionTools}from"./surface/action-tool-generator.js";import{buildThirdPartyChannelSet,isThirdPartyChannel}from"./channel-detection.js";const PLUGIN_VERSION=resolvePluginVersion();let agentKeys=null,sharedCanvasState=null,_initializing=!1,_pluginRegisteredAt=0;const ED25519_PKCS8_PREFIX=Buffer.from("302e020100300506032b657004220420","hex");function agentKeyPairToIdentity(e){return{publicKeyBase64:()=>Buffer.from(e.publicKey).toString("base64"),sign:async o=>{const{createPrivateKey:r,sign:a}=await import("node:crypto"),t=r({key:32===e.privateKey.length?Buffer.concat([ED25519_PKCS8_PREFIX,Buffer.from(e.privateKey)]):Buffer.from(e.privateKey),format:"der",type:"pkcs8"});return new Uint8Array(a(null,Buffer.from(o),t))}}}let unhandledRejectionObserverInstalled=!1;function installUnhandledRejectionObserver(e,o){unhandledRejectionObserverInstalled||(unhandledRejectionObserverInstalled=!0,process.on("unhandledRejection",r=>{const a=r instanceof Error?r.message:String(r);e.logger.error?.("[beeos-claw] unhandledRejection:",r),o({component:"plugin",domain:"fatal",name:"unhandled_rejection",severity:"error",summary:a,error:{code:"unhandled_rejection",message:a}})}))}function initializePlugin(e){let o,r;try{o=e.runtime?.config?.loadConfig?.()}catch{}try{r=resolveConfigWithMeta({pluginConfig:e.pluginConfig??{},openclawConfig:o})}catch(o){return e.logger.error?.("[beeos-claw] Failed to resolve config:",o),null}const a=r.config,t=buildThirdPartyChannelSet(o);t.size>0&&e.logger.info?.(`[beeos-claw] Third-party channels detected: ${[...t].join(", ")}`);const s=a.log.enabled?createObsEventWriter({dir:a.log.dir,redaction:{gatewayToken:a.gateway.token},logger:e.logger}):()=>{};installUnhandledRejectionObserver(e,s),s({component:"plugin",domain:"lifecycle",name:"lifecycle.startup",severity:"info",payload:{pluginVersion:PLUGIN_VERSION,pid:process.pid,nodeVersion:process.version,cwd:process.cwd()}}),s({component:"plugin",domain:"config",name:"config.resolved",severity:"info",payload:{config:a,sources:r.sources,openclawConfigPath:r.openclawConfigPath}});for(const o of r.validation)s({component:"plugin",domain:"config",name:"config.validation",severity:o.severity,summary:o.message,error:{code:o.code,message:o.message,nextSteps:o.nextSteps}}),"error"===o.severity?e.logger.error?.(`[beeos-claw] ${o.message}`):e.logger.warn?.(`[beeos-claw] ${o.message}`);if(r.validation.some(e=>"error"===e.severity)&&e.logger.error?.("[beeos-claw] Plugin has configuration errors — some features may not work."),a.keyFile)try{agentKeys=loadAgentKeyPair(a.keyFile);const o=Buffer.from(agentKeys.publicKey).toString("base64");e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (publicKey: ${o})`)}catch(o){e.logger.warn?.(`[beeos-claw] Failed to load agent key pair: ${o}`),e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (no key pair — signed requests disabled)`)}else e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (no keyFile configured)`);return agentKeys&&a.agentGatewayUrl&&(setUploadDeps({gatewayUrl:a.agentGatewayUrl,keys:agentKeys,logger:e.logger}),registerLocalFileExtractor(browserScreenshotExtractor),e.logger.info?.("[beeos-claw] Upload deps + browser screenshot extractor registered")),{cfg:a,writeObs:s,thirdPartyChannels:t,openclawConfig:o}}function registerUploadTools(e,o,r){const{cfg:a,writeObs:t}=o;cleanupUploadToolResultCache().catch(o=>{e.logger.warn?.(`[beeos_upload_file] cache cleanup failed on startup: ${String(o)}`)}),e.registerTool({name:BEEOS_UPLOAD_TOOL_NAME,description:BEEOS_UPLOAD_TOOL_DESCRIPTION,parameters:BEEOS_UPLOAD_TOOL_SCHEMA,async execute(o,r,s){e.logger.debug?.(`[beeos_upload_file] toolCallId=${o} params=${JSON.stringify(r)}`);const n=await executeUpload(r,a,agentKeys,s);return e.logger.debug?.(`[beeos_upload_file] toolCallId=${o} ok=${n.ok}`),t({component:"upload-tool",domain:"tool",name:n.ok?"upload.success":"upload.failure",severity:n.ok?"info":"warn",payload:{toolCallId:o,ok:n.ok,fileCount:n.files?.length??0,error:n.error}}),(async r=>{try{await writeUploadToolResult(o,BEEOS_UPLOAD_TOOL_NAME,r),await cleanupUploadToolResultCache()}catch(r){e.logger.warn?.(`[beeos_upload_file] persist cache failed toolCallId=${o}: ${String(r)}`)}return r})(n)}}),e.registerHttpRoute({path:"/beeos/files/stage",auth:"gateway",async handler(e,r){await handleFileStage(e,r,o.cfg)}}),e.registerHttpRoute({path:"/beeos/status",auth:"plugin",handler(e,o){handleStatusRequest(e,o,{publicKey:agentKeys?.publicKey??null,pluginVersion:PLUGIN_VERSION})}})}function registerServices(e,o,r){const{cfg:a,writeObs:t,thirdPartyChannels:s}=o,n=agentKeys?(e,o)=>agentFetch(e,agentKeys,o):void 0,i=agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):void 0,l=new ACPServer(a,e.logger,t,n,i,s);r.current=l,e.registerService({id:"beeos-acp",async start(){const o=Date.now(),r=_pluginRegisteredAt?o-_pluginRegisteredAt:-1;if(e.logger.info?.(`[beeos-claw] beeos-acp service start() begin, sincePluginRegister=${r}ms, bridge.url=${a.bridge.url||"(empty)"}`),!a.bridge.url&&a.agentGatewayUrl&&n){const o=Date.now(),r=await discoverBridgeFromGW(a.agentGatewayUrl,n);if(e.logger.info?.(`[beeos-claw] bridge discovery took ${Date.now()-o}ms result=${r?.url??"null"}`),r)a.bridge.url=r.url,writeDiscoveryCache({bridge:{url:r.url,discoveredAt:Date.now()}}),e.logger.info?.(`[beeos-claw] Bridge URL discovered from Agent Gateway: ${r.url}`);else{const o=readDiscoveryCache();o?.bridge?.url?(a.bridge.url=o.bridge.url,e.logger.info?.(`[beeos-claw] Bridge URL from cache (GW unreachable): ${o.bridge.url}`)):e.logger.debug?.("[beeos-claw] Bridge URL not available (no GW, no cache) — bridge disabled")}}await l.start(a.bridge.url||void 0),e.logger.info?.(`[beeos-claw] ACP Server started (total service start: ${Date.now()-o}ms)`)},async stop(){await l.stop(),e.logger.info?.("[beeos-claw] ACP Server stopped")}});const g=new TaskHandleRegistry;let c=null;const{enabled:d,url:p,principalId:u,a2aEnabled:f}=a.messageBus;let y;if(a.agentGatewayUrl&&agentKeys){const e=agentKeyPairToIdentity(agentKeys);y=createTokenProvider({agentGatewayUrl:a.agentGatewayUrl,identity:e})}if(d&&(y||a.messageBus.serviceUrl)){c=new MessageClient({serviceUrl:a.messageBus.serviceUrl||"https://msg.invalid",centrifugoUrl:p,tokenProvider:y,logger:e.logger});const o=u,r=async o=>{c.once("connect",()=>{l.setMessageClient(c,o),e.logger.info?.("[beeos-claw] MessageClient connected (principalId=%s, via=%s)",o,y?"gateway":"direct")}),await c.connect({identityId:o})};e.registerService({id:"beeos-message-bus",async start(){let a=o;if(a||(a=process.env.BEEOS_PRINCIPAL_ID||""),!a&&l)try{await l.waitForAgentMapping(),a=l.getDefaultPlatformAgent()?.instanceId||""}catch(o){e.logger.warn?.("[beeos-claw] Failed to resolve principalId from agent sync:",o)}a?await r(a):l?(e.logger.info?.("[beeos-claw] Message bus deferred: waiting for late agent sync..."),l.onceAgentMappingReady(()=>{const o=l.getDefaultPlatformAgent()?.instanceId;o?r(o).catch(o=>{e.logger.error?.("[beeos-claw] Deferred message bus connect failed:",o)}):e.logger.warn?.("[beeos-claw] Agent mapping ready but no principalId, message bus stays disabled")})):e.logger.warn?.("[beeos-claw] No principalId resolved, message bus disabled")},async stop(){await(c?.disconnect()),e.logger.info?.("[beeos-claw] MessageClient disconnected")}});const t=async(o,r)=>{const a=extractChatPrompt(r,{source:o,localAgentId:l.getLocalAgentId()});a&&(e.logger.debug?.(`[beeos-claw] ${o} received (sessionKey=%s, contextId=%s)`,a.sessionKey,a.contextId??"-"),await l.agentSend(a.message,a.files,a.sessionKey,void 0,a.channelId,a.messageId))};let s=!1;c.on("message",async o=>{"chat_message"===o.type?await t("chat_message",o):"agent_request"===o.type&&(s||(e.logger.warn?.("[beeos-claw] Received legacy 'agent_request' message — this path is deprecated and will be removed once all upstreams migrate to 'chat_message' (L0 AgentInvocationService)."),s=!0),await t("agent_request",o))})}else d?e.logger.warn?.("[beeos-claw] Message bus enabled but MESSAGE_SERVICE_URL not set — disabled"):e.logger.info?.("[beeos-claw] Message bus disabled (enabled=%s)",d);if(!1!==f&&a.agentGatewayUrl){const o=e=>l.getGatewaySessionKeyForToolCall(e),r=e=>l.getMentionsForToolCall(e),t=(e,o)=>{l.broadcastNotification(e,o)};registerA2ATools(e,{agentGatewayUrl:a.agentGatewayUrl,agentKeys:agentKeys,logger:e.logger},g,o,r,t),e.logger.info?.("[beeos-claw] A2A tools registered (beeos_discover_agents, beeos_call_agent) via REST")}if(a.canvasEnabled){sharedCanvasState||(sharedCanvasState=new CanvasStateManager);const o=sharedCanvasState;if(a.agentGatewayUrl&&agentKeys){let r;o.setLogger(e.logger);{const e=a.agentGatewayUrl,o=agentKeys;r=async()=>{const r=await agentFetch(`${e}/api/v1/canvas/token`,o,{method:"POST"});if(!r.ok){const e=await r.text().catch(()=>"");throw new Error(`Canvas token returned ${r.status}: ${e}`)}return r.json()}}e.registerService({id:"beeos-canvas-relay",async start(){try{await l.waitForAgentMapping();const t=l.getDefaultPlatformAgent();if(!t?.id)return void e.logger.info?.("[beeos-claw] Canvas Relay skipped: no agentId after sync");const s=new CanvasRelayClient({canvasRelayUrl:a.canvasRelayUrl,agentKeys:agentKeys,agentId:t.id,displayName:t.displayName,avatarUrl:t.avatarUrl,tokenProvider:r,onReconnect:()=>l.onRelayReconnected(),logger:e.logger});s.connect(),o.setRelayClient(s),o.setAgentId(t.id),l.wireRelayActionHandler(),l.flushPendingCanvasLinks(),e.logger.info?.(`[beeos-claw] Canvas Relay multiplexed client connected (agentId=${t.id}, name=${t.name??"none"})`)}catch(o){e.logger.warn?.(`[beeos-claw] Failed to start Canvas Relay client: ${o}`)}},stop(){o.getRelayClient()?.disconnect()}}),e.logger.info?.("[beeos-claw] Canvas Relay configured")}else e.logger.warn?.("[beeos-claw] Canvas Relay unavailable: agentGatewayUrl or agentKeys missing");const r={stateManager:o,logger:e.logger,writeObs:e=>t(e),isCanvasActive:e=>!e||l.isCanvasActiveForGatewayKey(e),getActiveSessionId:e=>l.getSessionIdForToolCall(e),getPlatformAgentId:e=>l.getPlatformAgentIdForToolCall(e),getGatewaySessionKey:e=>l.getGatewaySessionKeyForToolCall(e),waitForAgentSync:()=>l.waitForAgentMapping()},n=new FormSchemaRegistry,i=buildCronSchemas(s,{capMs:a.cronMaxDurationCapMs});n.register(i.create),n.register(i.update);const g=new ResourceDescriptorRegistry;g.register(CRON_RESOURCE);const c=e=>async(o,r,a)=>(l.preMapToolCallSession(o),e(o,r));e.registerTool({name:RENDER_UI_TOOL_NAME,description:RENDER_UI_TOOL_DESCRIPTION,parameters:RENDER_UI_TOOL_SCHEMA,execute:c(createRenderUiHandler(r))}),e.registerTool({name:CLOSE_UI_TOOL_NAME,description:CLOSE_UI_TOOL_DESCRIPTION,parameters:CLOSE_UI_TOOL_SCHEMA,execute:c(createCloseUiHandler(r))}),l.setCanvasState(o,{schemaRegistry:n,descriptorRegistry:g});const d=l.getFormBuilder();d&&e.registerTool({name:RENDER_FORM_TOOL_NAME,description:buildRenderFormDescription(n),parameters:RENDER_FORM_TOOL_SCHEMA,execute:c(createRenderFormHandler({registry:n,builder:d,logger:e.logger}))});const p=l.getResourceRenderer();if(p){generateActionTools(g,e,async(e,o)=>l.gatewayRequest(e,o),p,e.logger)}const u='\n\nTool selection guidance:\n- browser tool: Use when the user wants to OPEN, VISIT, NAVIGATE to a webpage, take SCREENSHOTS, interact with elements (click, type), or visually inspect pages.\n- beeos_search: Use ONLY for text-based information retrieval (fact-finding, research queries). Never for page interaction or screenshots.\n- beeos_fetch: Use ONLY to extract article text from a known URL. Never for visual content or screenshots.\nWhen the user says "open", "visit", "go to", "screenshot", or mentions seeing/viewing a webpage, ALWAYS prefer the browser tool.',f=new Set([RENDER_UI_TOOL_NAME,CLOSE_UI_TOOL_NAME,RENDER_FORM_TOOL_NAME]),y=256,m=new Map;if("function"==typeof e.on){try{e.on("before_prompt_build",(e,o)=>{if(o?.sessionKey){if(m.size>=y&&!m.has(o.sessionKey)){const e=m.keys().next().value;void 0!==e&&m.delete(e)}m.set(o.sessionKey,o.channelId)}if(isThirdPartyChannel(s,{sessionKey:o?.sessionKey,channelId:o?.channelId}))return{appendSystemContext:'This conversation is in a third-party channel (Lark/Telegram/Discord/Slack); Canvas surfaces are not visible here. Do NOT use render_ui, close_ui, or render_form. Use built-in tools directly (e.g. the `cron` tool with `action:"add"` for scheduled tasks) and respond with plain text.'};if(!o?.sessionKey)return{appendSystemContext:u};return l.isCanvasActiveForGatewayKey(o.sessionKey)?{appendSystemContext:CANVAS_SYSTEM_PROMPT+u}:{appendSystemContext:"Canvas is closed by user. Do NOT use render_ui, close_ui, or render_form. Respond with plain text only."+u}}),e.logger.debug?.("[beeos-claw] Canvas system prompt hook registered: before_prompt_build")}catch{e.logger.debug?.("[beeos-claw] before_prompt_build hook not supported")}try{e.on("before_tool_call",(e,o)=>{if(o?.sessionKey&&l.setPendingToolCallSessionKey(o.sessionKey),!f.has(e.toolName))return;const r=o?.sessionKey?m.get(o.sessionKey):void 0;return isThirdPartyChannel(s,{sessionKey:o?.sessionKey,channelId:r})?{block:!0,blockReason:"Canvas tools are not available in this channel. Respond with plain text only."}:o?.sessionKey?l.isCanvasActiveForGatewayKey(o.sessionKey)?void 0:{block:!0,blockReason:"Canvas is closed by user. Respond with plain text instead."}:{block:!0,blockReason:"Canvas session unknown. Respond with plain text instead."}}),e.logger.debug?.("[beeos-claw] Canvas tool guard registered: before_tool_call")}catch{e.logger.debug?.("[beeos-claw] before_tool_call hook not supported")}}e.logger.info?.("[beeos-claw] Canvas tools registered (render_ui, close_ui, render_form + auto-action tools)")}else e.logger.info?.("[beeos-claw] Canvas disabled by config (canvasEnabled=false)");const m=new TerminalManager,b=createTerminalWebSocketService({config:{port:a.terminalWsPort,token:agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):"",allowedOrigins:a.terminalWsAllowedOrigins},terminalMgr:m,logger:e.logger,writeObs:t});if(a.bridge.shell.enabled?e.registerService({id:"beeos-terminal-ws",start(){b.start(),e.logger.info?.(`[beeos-claw] Terminal WS started on port ${a.terminalWsPort}`)},stop(){b.stop(),m.destroy(),e.logger.info?.("[beeos-claw] Terminal WS stopped")}}):e.logger.info?.("[beeos-claw] Terminal/shell disabled by config (bridge.shell.enabled=false)"),o.openclawConfig){const r=mirrorOpenClawConfig(o.openclawConfig);r.copied?e.logger.info?.(`[beeos-claw] mirrored openclaw config to ${r.destinationPath}`):e.logger.debug?.(`[beeos-claw] openclaw config mirror skipped: ${r.reason}`)}}const plugin={id:"beeos-claw",name:"beeos-claw",description:"BeeOS platform bridge plugin for OpenClaw. Provides file upload/download, ACP bridge, and observability.",version:PLUGIN_VERSION,register(e){if(!_initializing)if(e.registrationMode&&"full"!==e.registrationMode)e.logger.debug?.(`[beeos-claw] Skipping registration (mode=${e.registrationMode})`);else{_initializing=!0;try{const o=initializePlugin(e);if(!o)return;const r={current:null};registerUploadTools(e,o,r),registerServices(e,o,r),_pluginRegisteredAt=Date.now(),e.logger.info?.("[beeos-claw] Plugin registered successfully")}finally{_initializing=!1}}}};export default plugin;
|
package/dist/message-filter.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{HEARTBEAT_TOKEN,isSilentReplyPrefixText,stripHeartbeatToken}from"./auto-reply-tokens.js";const TIMESTAMP_PREFIX_RE=/^\s*\[(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s+\d{4}-\d{2}-\d{2}\s+\d{1,2}:\d{2}(?::\d{2})?\s+GMT[+-]\d{1,2}(?::?\d{2})?]\s*/i,WORKDIR_PREFIX_RE=/^\s*\[working directory:[^\]]*]\s*/i,MESSAGE_ID_PREFIX_RE=/^\s*\[message_id:[^\]]*]\s*/i,USER_MSG_PREFIX_RE=/^\s*User Message From \w+:\s*/i,HEARTBEAT_OK_LINE=HEARTBEAT_TOKEN,HEARTBEAT_OK_LINE_RE=/^[\s\p{P}\p{S}]*HEARTBEAT_OK[\s\p{P}\p{S}]*$/u,METADATA_PREFIX_PATTERNS=[TIMESTAMP_PREFIX_RE,WORKDIR_PREFIX_RE,MESSAGE_ID_PREFIX_RE,USER_MSG_PREFIX_RE],UNTRUSTED_METADATA_BLOCK_RE=/^Conversation info \(untrusted metadata\):[\s\S]*?Current time:\s*.*?$/i,UNTRUSTED_BLOCK_MARKER="Conversation info (untrusted metadata):",SENDER_UNTRUSTED_MARKER="Sender (untrusted metadata):",SENDER_UNTRUSTED_BLOCK_RE=/Sender\s*\(untrusted[^)]*\)\s*:\s*```[a-z]*\s*[\s\S]*?```/i;function stripMetadataPrefixesFromLine(e){let t=e,r=!1,n=!0;for(;n;){n=!1;for(const e of METADATA_PREFIX_PATTERNS)e.test(t)&&(t=t.replace(e,""),r=!0,n=!0)}return{line:t,changed:r}}export function stripTransportMetadata(e){const t=e.includes(UNTRUSTED_BLOCK_MARKER),r=e.includes(SENDER_UNTRUSTED_MARKER);if(!(e.includes("[")||e.includes(HEARTBEAT_OK_LINE)||e.includes("User Message From")||t||r))return e;if(r){const t=e.replace(SENDER_UNTRUSTED_BLOCK_RE,"").replace(/^\n+/,"").trim();if(t!==e)return t?stripTransportMetadata(t):"";const r=e.indexOf(SENDER_UNTRUSTED_MARKER),n=e.indexOf("\n\n",r),i=-1===n?e.length:n,s=e.slice(i).replace(/^\n+/,"").trim();return s?stripTransportMetadata(s):""}if(t){const t=e.indexOf(UNTRUSTED_BLOCK_MARKER),r=/\nCurrent time:[^\n]*/i.exec(e.slice(t));if(r){const n=t+r.index+r[0].length,i=e.slice(n).replace(/^\n+/,"").trim();return i?stripTransportMetadata(i):""}const n=e.indexOf("\n\n",t),i=-1===n?e.length:n,s=e.slice(i).replace(/^\n+/,"").trim();return s?stripTransportMetadata(s):""}const n=e.split(/\r?\n/),i=[];let s=!1;for(const e of n){const t=stripMetadataPrefixesFromLine(e);HEARTBEAT_OK_LINE_RE.test(t.line.trim())?s=!0:t.changed&&(s=!0,!t.line.trim())||i.push(t.line)}return s?i.join("\n").replace(/^\n+/,"").replace(/\n+$/,""):e}export function normalizeTransportText(e){if(!e)return;const t=stripTransportMetadata(e);return t.length>0?t:void 0}export function isHeartbeatOnlyText(e){const t=e.trim();if(!t)return!1;if(HEARTBEAT_OK_LINE_RE.test(t))return!0;if(t.includes(HEARTBEAT_OK_LINE)){if(stripHeartbeatToken(t,{mode:"message"}).shouldSkip)return!0;if(0===stripTransportMetadata(t).trim().length)return!0}return!1}export function isHeartbeatPrefixText(e){if(!e)return!1;const t=e.trim();return!!t&&(!(t.length>=HEARTBEAT_OK_LINE.length)&&isSilentReplyPrefixText(t,HEARTBEAT_OK_LINE))}export function isHeartbeatFullOrPrefix(e){return"none"!==classifyHeartbeatFilter(e).reason}export function previewFilteredText(e,t=120){if(!e)return"";const r=e.replace(/\\/g,"\\\\").replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(/\s+/g," ").trim();if(r.length<=t)return r;const n=Math.floor((t-1)/2),i=t-1-n;return`${r.slice(0,n)}…${r.slice(-i)}`}export function classifyHeartbeatFilter(e){if(!e)return{reason:"none",filtered:!1};const t=e.trim();if(!t)return{reason:"none",filtered:!1};if(HEARTBEAT_OK_LINE_RE.test(t))return{reason:"full",filtered:!0};if(t.includes(HEARTBEAT_OK_LINE)){if(stripHeartbeatToken(t,{mode:"message"}).shouldSkip)return{reason:"full-stripped",filtered:!0};if(0===stripTransportMetadata(t).trim().length)return{reason:"full-metadata-residue",filtered:!0}}return isHeartbeatPrefixText(t)?{reason:"prefix",filtered:!0}:{reason:"none",filtered:!1}}const HEARTBEAT_PROMPT_PREFIX="read heartbeat.md if it exists";export function isHeartbeatPromptText(e){return e.slice(0,80).toLowerCase().startsWith(HEARTBEAT_PROMPT_PREFIX)}const CRON_PROMPT_PREFIX_RE=/^\[cron:[0-9a-f-]{8,}\s/i;export function isCronPromptText(e){return CRON_PROMPT_PREFIX_RE.test(e.trimStart())}function isRecord(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function sanitizeNode(e){if("string"==typeof e){const t=stripTransportMetadata(e);return{value:t,changed:t!==e}}if(Array.isArray(e)){let t=!1;const r=e.map(e=>{const r=sanitizeNode(e);return r.changed&&(t=!0),r.value});return{value:t?r:e,changed:t}}if(!isRecord(e))return{value:e,changed:!1};let t=!1,r=e;if("string"==typeof e.type&&"text"===e.type&&"string"==typeof e.text){const n=stripTransportMetadata(e.text);n!==e.text&&(r={...r,text:n},t=!0)}if(Array.isArray(e.content)){const n=sanitizeNode(e.content);n.changed&&(t||(r={...r}),r.content=n.value,t=!0)}return{value:t?r:e,changed:t}}export function sanitizePromptPayload(e){return sanitizeNode(e).value}
|
|
1
|
+
import{HEARTBEAT_TOKEN,isSilentReplyPrefixText,stripHeartbeatToken}from"./auto-reply-tokens.js";const TIMESTAMP_PREFIX_RE=/^\s*\[(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s+\d{4}-\d{2}-\d{2}\s+\d{1,2}:\d{2}(?::\d{2})?\s+GMT[+-]\d{1,2}(?::?\d{2})?]\s*/i,WORKDIR_PREFIX_RE=/^\s*\[working directory:[^\]]*]\s*/i,MESSAGE_ID_PREFIX_RE=/^\s*\[message_id:[^\]]*]\s*/i,USER_MSG_PREFIX_RE=/^\s*User Message From \w+:\s*/i,HEARTBEAT_OK_LINE=HEARTBEAT_TOKEN,HEARTBEAT_OK_LINE_RE=/^[\s\p{P}\p{S}]*HEARTBEAT_OK[\s\p{P}\p{S}]*$/u,METADATA_PREFIX_PATTERNS=[TIMESTAMP_PREFIX_RE,WORKDIR_PREFIX_RE,MESSAGE_ID_PREFIX_RE,USER_MSG_PREFIX_RE],UNTRUSTED_METADATA_BLOCK_RE=/^Conversation info \(untrusted metadata\):[\s\S]*?Current time:\s*.*?$/i,UNTRUSTED_BLOCK_MARKER="Conversation info (untrusted metadata):",SENDER_UNTRUSTED_MARKER="Sender (untrusted metadata):",SENDER_UNTRUSTED_BLOCK_RE=/Sender\s*\(untrusted[^)]*\)\s*:\s*```[a-z]*\s*[\s\S]*?```/i;function stripMetadataPrefixesFromLine(e){let t=e,r=!1,n=!0;for(;n;){n=!1;for(const e of METADATA_PREFIX_PATTERNS)e.test(t)&&(t=t.replace(e,""),r=!0,n=!0)}return{line:t,changed:r}}export function stripTransportMetadata(e){const t=e.includes(UNTRUSTED_BLOCK_MARKER),r=e.includes(SENDER_UNTRUSTED_MARKER);if(!(e.includes("[")||e.includes(HEARTBEAT_OK_LINE)||e.includes("User Message From")||t||r))return e;if(r){const t=e.replace(SENDER_UNTRUSTED_BLOCK_RE,"").replace(/^\n+/,"").trim();if(t!==e)return t?stripTransportMetadata(t):"";const r=e.indexOf(SENDER_UNTRUSTED_MARKER),n=e.indexOf("\n\n",r),i=-1===n?e.length:n,s=e.slice(i).replace(/^\n+/,"").trim();return s?stripTransportMetadata(s):""}if(t){const t=e.indexOf(UNTRUSTED_BLOCK_MARKER),r=/\nCurrent time:[^\n]*/i.exec(e.slice(t));if(r){const n=t+r.index+r[0].length,i=e.slice(n).replace(/^\n+/,"").trim();return i?stripTransportMetadata(i):""}const n=e.indexOf("\n\n",t),i=-1===n?e.length:n,s=e.slice(i).replace(/^\n+/,"").trim();return s?stripTransportMetadata(s):""}const n=e.split(/\r?\n/),i=[];let s=!1;for(const e of n){const t=stripMetadataPrefixesFromLine(e);HEARTBEAT_OK_LINE_RE.test(t.line.trim())?s=!0:t.changed&&(s=!0,!t.line.trim())||i.push(t.line)}return s?i.join("\n").replace(/^\n+/,"").replace(/\n+$/,""):e}export function normalizeTransportText(e){if(!e)return;const t=stripTransportMetadata(e);return t.length>0?t:void 0}export function isHeartbeatOnlyText(e){const t=e.trim();if(!t)return!1;if(HEARTBEAT_OK_LINE_RE.test(t))return!0;if(t.includes(HEARTBEAT_OK_LINE)){if(stripHeartbeatToken(t,{mode:"message"}).shouldSkip)return!0;if(0===stripTransportMetadata(t).trim().length)return!0}return!1}export function isHeartbeatPrefixText(e){if(!e)return!1;const t=e.trim();return!!t&&(!(t.length>=HEARTBEAT_OK_LINE.length)&&isSilentReplyPrefixText(t,HEARTBEAT_OK_LINE))}export function isHeartbeatFullOrPrefix(e){return"none"!==classifyHeartbeatFilter(e).reason}export function previewFilteredText(e,t=120){if(!e)return"";const r=e.replace(/\\/g,"\\\\").replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(/\s+/g," ").trim();if(r.length<=t)return r;const n=Math.floor((t-1)/2),i=t-1-n;return`${r.slice(0,n)}…${r.slice(-i)}`}export function classifyHeartbeatFilter(e){if(!e)return{reason:"none",filtered:!1};const t=e.trim();if(!t)return{reason:"none",filtered:!1};if(HEARTBEAT_OK_LINE_RE.test(t))return{reason:"full",filtered:!0};if(t.includes(HEARTBEAT_OK_LINE)){if(stripHeartbeatToken(t,{mode:"message"}).shouldSkip)return{reason:"full-stripped",filtered:!0};if(0===stripTransportMetadata(t).trim().length)return{reason:"full-metadata-residue",filtered:!0}}return isHeartbeatPrefixText(t)?{reason:"prefix",filtered:!0}:{reason:"none",filtered:!1}}const HEARTBEAT_PROMPT_PREFIX="read heartbeat.md if it exists";export function isHeartbeatPromptText(e){return e.slice(0,80).toLowerCase().startsWith(HEARTBEAT_PROMPT_PREFIX)}const CRON_PROMPT_PREFIX_RE=/^\[cron:([0-9a-f-]{8,})\s/i;export function isCronPromptText(e){return CRON_PROMPT_PREFIX_RE.test(e.trimStart())}export function extractCronJobId(e){return CRON_PROMPT_PREFIX_RE.exec(e.trimStart())?.[1]}function isRecord(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function sanitizeNode(e){if("string"==typeof e){const t=stripTransportMetadata(e);return{value:t,changed:t!==e}}if(Array.isArray(e)){let t=!1;const r=e.map(e=>{const r=sanitizeNode(e);return r.changed&&(t=!0),r.value});return{value:t?r:e,changed:t}}if(!isRecord(e))return{value:e,changed:!1};let t=!1,r=e;if("string"==typeof e.type&&"text"===e.type&&"string"==typeof e.text){const n=stripTransportMetadata(e.text);n!==e.text&&(r={...r,text:n},t=!0)}if(Array.isArray(e.content)){const n=sanitizeNode(e.content);n.changed&&(t||(r={...r}),r.content=n.value,t=!0)}return{value:t?r:e,changed:t}}export function sanitizePromptPayload(e){return sanitizeNode(e).value}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function buildSharedFields(e){const a=[{name:"name",label:"Task Name",inputType:"text",required:!0,placeholder:"e.g. daily-report",apiPath:"name"},{name:"description",label:"Description",inputType:"textarea",placeholder:"What does this task do?",apiPath:"description"},{name:"enabled",label:"Enabled",inputType:"toggle",defaultValue:!0,apiPath:"enabled"},{name:"sessionTarget",label:"Execution Mode",inputType:"select",required:!0,defaultValue:"isolated",options:[{label:"Independent (isolated)",value:"isolated"},{label:"Main session",value:"main"}]},{name:"deliveryMode",label:"Result Delivery",inputType:"select",required:!0,defaultValue:"internal",options:[{label:"Internal (BeeOS IM channel)",value:"internal"},...e.length>0?[{label:"Channel (Telegram/Discord/…)",value:"announce"}]:[],{label:"Webhook",value:"webhook"},{label:"None (log only)",value:"none"}]}];return e.length>0&&
|
|
1
|
+
import{CRON_DURATION_FLOOR_MS,CRON_DURATION_CAP_DEFAULT_MS}from"../config.js";function buildSharedFields(e,a){const n=a?.floorMs??CRON_DURATION_FLOOR_MS,t=a?.capMs??CRON_DURATION_CAP_DEFAULT_MS,l=[{name:"name",label:"Task Name",inputType:"text",required:!0,placeholder:"e.g. daily-report",apiPath:"name"},{name:"description",label:"Description",inputType:"textarea",placeholder:"What does this task do?",apiPath:"description"},{name:"enabled",label:"Enabled",inputType:"toggle",defaultValue:!0,apiPath:"enabled"},{name:"sessionTarget",label:"Execution Mode",inputType:"select",required:!0,defaultValue:"isolated",options:[{label:"Independent (isolated)",value:"isolated"},{label:"Main session",value:"main"}]},{name:"deliveryMode",label:"Result Delivery",inputType:"select",required:!0,defaultValue:"internal",options:[{label:"Internal (BeeOS IM channel)",value:"internal"},...e.length>0?[{label:"Channel (Telegram/Discord/…)",value:"announce"}]:[],{label:"Webhook",value:"webhook"},{label:"None (log only)",value:"none"}]}];return e.length>0&&l.push({name:"deliveryChannel",label:"Delivery Channel",inputType:"select",options:e}),l.push({name:"webhookUrl",label:"Webhook URL",inputType:"url",placeholder:"https://example.com/webhook"},{name:"scheduleKind",label:"Schedule Type",inputType:"select",required:!0,options:[{label:"Interval (every N ms)",value:"every"},{label:"Cron Expression",value:"cron"},{label:"Specific Time",value:"at"}],apiPath:"schedule.kind"},{name:"everyMs",label:"Interval (ms)",inputType:"number",placeholder:"3600000 = 1 hour",validation:{min:1e3},apiPath:"schedule.everyMs"},{name:"cronExpr",label:"Cron Expression",inputType:"text",placeholder:"e.g. 0 9 * * *",apiPath:"schedule.expr"},{name:"at",label:"Run At (ISO 8601)",inputType:"text",placeholder:"e.g. 2026-04-01T09:00:00Z",apiPath:"schedule.at"},{name:"tz",label:"Timezone",inputType:"text",placeholder:"e.g. Asia/Shanghai (optional)",apiPath:"schedule.tz"},{name:"message",label:"Agent Message",inputType:"textarea",required:!0,placeholder:"What should the agent do when this task fires?",apiPath:"payload.message"},{name:"maxDurationMs",label:"Max Execution Time (ms)",inputType:"number",placeholder:`optional, e.g. 600000 = 10min (max ${Math.round(t/6e4)}min)`,validation:{min:n,max:t},apiPath:"_beeos_meta.maxDurationMs"}),l}function cronTransformPayload(e){const a={};void 0!==e.name&&(a.name=e.name),void 0!==e.description&&(a.description=e.description),void 0!==e.enabled&&(a.enabled=e.enabled);const n=e.scheduleKind;if(n){const t={kind:n};"every"===n&&e.everyMs&&(t.everyMs=Number(e.everyMs)),"cron"===n&&e.cronExpr&&(t.expr=e.cronExpr),"at"===n&&e.at&&(t.at=e.at),e.tz&&(t.tz=e.tz),a.schedule=t}const t=e.deliveryMode??"internal",l=e.sessionTarget??"isolated",o=e.message;switch(t){case"internal":a.sessionTarget="isolated",a.delivery={mode:"none"},a._beeos_internal=!0,void 0!==o&&(a.payload={kind:"agentTurn",message:String(o)});break;case"announce":a.sessionTarget="isolated",a.delivery={mode:"announce",...e.deliveryChannel?{channel:e.deliveryChannel}:{}},void 0!==o&&(a.payload={kind:"agentTurn",message:String(o)});break;case"webhook":a.sessionTarget="isolated",a.delivery={mode:"webhook",...e.webhookUrl?{to:e.webhookUrl}:{}},void 0!==o&&(a.payload={kind:"agentTurn",message:String(o)});break;default:if(a.sessionTarget=l,a.delivery={mode:"none"},void 0!==o){const e="isolated"===l;a.payload=e?{kind:"agentTurn",message:String(o)}:{kind:"systemEvent",text:String(o)}}}const i=e.maxDurationMs;if(void 0!==i&&""!==i&&null!==i){const e=Number(i);Number.isFinite(e)&&e>0&&(a._beeos_meta={maxDurationMs:Math.trunc(e)})}return a}function cronCreateTransform(e){const a=cronTransformPayload(e);return a.name||(a.name="Untitled"),void 0===a.enabled&&(a.enabled=!0),a.schedule||(a.schedule={kind:"every",everyMs:36e5}),a.sessionTarget||(a.sessionTarget="isolated"),a.wakeMode="now",a.payload||(a.payload={kind:"agentTurn",message:""}),a.delivery||(a.delivery={mode:"none"}),void 0===a._beeos_internal&&(a._beeos_internal=!0),a}export function buildCronSchemas(e,a){const n=buildSharedFields([...e].map(e=>({label:e.charAt(0).toUpperCase()+e.slice(1),value:e})),a);return{create:{domain:"cron",operation:"create",title:"Create Scheduled Task",description:"Add a new recurring or one-time agent task.",fields:n,submitLabel:"Create",targetRpc:"cron.add",transformPayload:cronCreateTransform},update:{domain:"cron",operation:"update",title:"Edit Scheduled Task",description:"Modify an existing scheduled task.",fields:n,submitLabel:"Update",targetRpc:"cron.update",transformPayload:cronTransformPayload}}}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "beeos-claw",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
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>",
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"dependencies": {
|
|
42
42
|
"@beeos-ai/beeos-types": "^1.0.0",
|
|
43
43
|
"@beeos-ai/bridge-client": "^0.1.0",
|
|
44
|
-
"@beeos-ai/message-sdk": "^
|
|
44
|
+
"@beeos-ai/message-sdk": "^1.0.0",
|
|
45
45
|
"adm-zip": "^0.5.17",
|
|
46
46
|
"ws": "^8.18.0"
|
|
47
47
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{A2A_PROTOCOL_FIELDS,extractChatPrompt}from"@beeos-ai/message-sdk";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{describe,it,expect}from"vitest";import{extractChatPrompt,A2A_PROTOCOL_FIELDS}from"./chat-envelope.js";const LOCAL_AGENT_ID="agent-local-test",FIXED_SUFFIX=()=>"fixed-suffix";describe("extractChatPrompt — chat_message envelope",()=>{it("returns null when no message is present",()=>{const e=extractChatPrompt({type:"chat_message",payload:{parts:[]}},{source:"chat_message",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e).toBeNull()}),it("extracts message, channelId and contextId from a native envelope",()=>{const e=extractChatPrompt({type:"chat_message",channel_id:"ch-123",payload:{message:"hello",context_id:"ctx-42",parts:[{type:"text",text:"hello"},{type:"file",file_url:"https://cdn/a.png"}]}},{source:"chat_message",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e).not.toBeNull(),expect(e.message).toBe("hello"),expect(e.files).toEqual(["https://cdn/a.png"]),expect(e.channelId).toBe("ch-123"),expect(e.contextId).toBe("ctx-42"),expect(e.sessionKey).toBe(`agent:${LOCAL_AGENT_ID}:invoke:ctx-ctx-42`)}),it("generates a fresh session key when neither context_id nor channel_id is supplied",()=>{const e=extractChatPrompt({type:"chat_message",payload:{message:"hi"}},{source:"chat_message",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e.sessionKey).toBe(`agent:${LOCAL_AGENT_ID}:invoke:fixed-suffix`),expect(e.channelId).toBeUndefined()}),it("uses ch-{channelId} suffix when only channel_id is present",()=>{const e=extractChatPrompt({type:"chat_message",channel_id:"ch-stable",payload:{message:"hi"}},{source:"chat_message",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e.channelId).toBe("ch-stable"),expect(e.sessionKey).toBe(`agent:${LOCAL_AGENT_ID}:invoke:ch-ch-stable`),expect(e.sessionKey.includes("fixed-suffix")).toBe(!1)}),it("prefers ctx-{contextId} over ch-{channelId} when both are present",()=>{const e=extractChatPrompt({type:"chat_message",channel_id:"ch-stable",payload:{message:"hi",context_id:"ctx-pinned"}},{source:"chat_message",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e.sessionKey).toBe(`agent:${LOCAL_AGENT_ID}:invoke:ctx-ctx-pinned`),expect(e.channelId).toBe("ch-stable")}),it("does NOT surface any A2A protocol header even if upstream leaks one",()=>{const e={message:"hello"};for(const t of A2A_PROTOCOL_FIELDS)e[t]=`leaked:${t}`;const t=extractChatPrompt({type:"chat_message",payload:e,metadata:{task_id:"leaked-task",caller_protocol:"a2a",correlation_id:"leaked-corr"}},{source:"chat_message",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(t).not.toBeNull();const a=new Set(["message","files","channelId","contextId","sessionKey","messageId"]);for(const e of Object.keys(t))expect(a.has(e)).toBe(!0);for(const e of A2A_PROTOCOL_FIELDS)expect(t.sessionKey.includes(`leaked:${e}`)).toBe(!1),expect(t.message.includes(`leaked:${e}`)).toBe(!1)}),it("legacy agent_request envelopes still parse, but default channel stays `a2a`",()=>{const e=extractChatPrompt({type:"agent_request",payload:{message:"legacy",files:["/tmp/a.txt"]}},{source:"agent_request",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e.message).toBe("legacy"),expect(e.files).toEqual(["/tmp/a.txt"]),expect(e.sessionKey).toBe(`agent:${LOCAL_AGENT_ID}:a2a:fixed-suffix`)}),it("respects an explicit session_key from legacy callers",()=>{const e=extractChatPrompt({type:"agent_request",payload:{message:"legacy",session_key:"agent:legacy:pre-existing"}},{source:"agent_request",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e.sessionKey).toBe("agent:legacy:pre-existing")}),it("surfaces envelope.message_id as the generic IM request/response correlator",()=>{const e=extractChatPrompt({type:"chat_message",channel_id:"ch-1",message_id:"msg-envelope",payload:{message:"hi",message_id:"msg-payload"},metadata:{message_id:"msg-meta"}},{source:"chat_message",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e.messageId).toBe("msg-envelope")}),it("falls back to metadata.message_id when the envelope field is absent",()=>{const e=extractChatPrompt({type:"chat_message",channel_id:"ch-1",payload:{message:"hi"},metadata:{message_id:"msg-meta"}},{source:"chat_message",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e.messageId).toBe("msg-meta")}),it("normalizes empty string message_id to undefined",()=>{const e=extractChatPrompt({type:"chat_message",channel_id:"ch-1",message_id:"",payload:{message:"hi"}},{source:"chat_message",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e.messageId).toBeUndefined()}),it("prefers envelope.channel_id over metadata over payload",()=>{const e=extractChatPrompt({type:"chat_message",channel_id:"envelope-ch",payload:{message:"m",channel_id:"payload-ch"},metadata:{channel_id:"meta-ch"}},{source:"chat_message",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e.channelId).toBe("envelope-ch")})});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{MessageSDK}from"@beeos-ai/message-sdk";
|