beeos-claw 0.2.40 → 0.3.0

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.
@@ -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()},t=new AcpGatewaySessionState(e),s={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}}},n={isConnected:!0,sessionsPatch:vi.fn().mockResolvedValue(void 0),chatHistory:vi.fn().mockResolvedValue(null),sessionsMessagesSubscribe:vi.fn().mockResolvedValue(void 0),sessionsList:vi.fn().mockResolvedValue({sessions:[]})};return{bridge:new AcpGatewayBridgeCore({state:t,transport:s,config:{gateway:{agentId:"main"}},logger:e,writeObs:vi.fn(),getGateway:()=>n,instanceId:"test-instance",thirdPartyChannels:new Set}),state:t,transport:s,gateway:n,logger:e}}describe("handleRequest — ping keep-alive (Bug-X)",()=>{let e;async function t(t){await e.bridge.handleRequest(t),await Promise.resolve()}beforeEach(()=>{e=makeBridge()}),it("responds to ping with a successful result, NOT a MethodNotFound error",async()=>{await t({jsonrpc:"2.0",id:42,method:"ping",params:{}}),expect(e.transport.sendAcpError).not.toHaveBeenCalled(),expect(e.transport.sendResult).toHaveBeenCalledTimes(1);const[s,n]=e.transport.sendResult.mock.calls[0];expect(s).toBe(42),expect(n).toEqual({pong:!0})}),it("accepts ping with no params (SDK sends empty object, but also absent)",async()=>{await t({jsonrpc:"2.0",id:"ka-1",method:"ping"}),expect(e.transport.sendAcpError).not.toHaveBeenCalled(),expect(e.transport.sendResult).toHaveBeenCalledTimes(1),expect(e.transport.sendResult.mock.calls[0]?.[1]).toEqual({pong:!0})}),it("is stateless — does not touch session state or gateway",async()=>{const s=e.transport.setSessionUpdateObserver.mock.calls.length,n=e.transport.sendNotification.mock.calls.length;await t({jsonrpc:"2.0",id:1,method:"ping",params:{}}),expect(e.state.sessions.size).toBe(0),expect(e.gateway.sessionsPatch).not.toHaveBeenCalled(),expect(e.gateway.sessionsMessagesSubscribe).not.toHaveBeenCalled(),expect(e.gateway.sessionsList).not.toHaveBeenCalled(),expect(e.gateway.chatHistory).not.toHaveBeenCalled(),expect(e.transport.setSessionUpdateObserver.mock.calls.length).toBe(s),expect(e.transport.sendNotification.mock.calls.length).toBe(n)}),it("handles high-frequency pings (SDK fires every 30s; simulate a burst)",async()=>{for(let e=0;e<10;e++)await t({jsonrpc:"2.0",id:e,method:"ping",params:{}});expect(e.transport.sendAcpError).not.toHaveBeenCalled(),expect(e.transport.sendResult).toHaveBeenCalledTimes(10);for(let t=0;t<10;t++){const[s,n]=e.transport.sendResult.mock.calls[t];expect(s).toBe(t),expect(n).toEqual({pong:!0})}}),it("unknown methods still emit MethodNotFound (guardrail for the switch default)",async()=>{await t({jsonrpc:"2.0",id:"unknown",method:"definitely/not/real",params:{}}),expect(e.transport.sendResult).not.toHaveBeenCalled(),expect(e.transport.sendAcpError).toHaveBeenCalledTimes(1);const[s,n]=e.transport.sendAcpError.mock.calls[0];expect(s).toBe("unknown"),expect(n).toMatchObject({rpcCode:-32601})})});
@@ -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()},s=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}}},n={isConnected:!0,sessionsPatch:vi.fn().mockResolvedValue(void 0),chatHistory:vi.fn().mockResolvedValue(null),sessionsMessagesSubscribe:vi.fn().mockResolvedValue(void 0),sessionsList:vi.fn().mockResolvedValue({sessions:[]})};return{bridge:new AcpGatewayBridgeCore({state:s,transport:t,config:{gateway:{agentId:"main"}},logger:e,writeObs:vi.fn(),getGateway:()=>n,instanceId:"test-instance",thirdPartyChannels:new Set}),state:s,transport:t,gateway:n,logger:e}}describe("handleSessionNew — lazy verbose patch (stub prevention)",()=>{let e;async function s(s={}){const t={jsonrpc:"2.0",id:1,method:"session/new",params:s};await e.bridge.handleSessionNew(t),await Promise.resolve(),await Promise.resolve();const n=e.transport.sendResult.mock.calls[0]?.[1];if(!n?.sessionId)throw new Error("session/new did not call sendResult with a sessionId");return n.sessionId}beforeEach(()=>{e=makeBridge()}),it("registers the new session in both lookup maps",async()=>{const t=await s();expect(e.state.sessions.has(t)).toBe(!0);const n=e.state.sessions.get(t);expect(n.gatewaySessionKey).toMatch(/^agent:main:/),expect(e.state.sessionsByGatewayKey.get(n.gatewaySessionKey)).toBe(n)}),it("responds to the RPC with the derived sessionId and sessionKey meta",async()=>{await s(),expect(e.transport.sendResult).toHaveBeenCalledTimes(1);const[t,n]=e.transport.sendResult.mock.calls[0];expect(t).toBe(1),expect(n).toMatchObject({sessionId:expect.stringMatching(/^session:/),_meta:{sessionKey:expect.stringMatching(/^agent:main:/),agentId:"main"}})}),it("does NOT eagerly call sessions.patch — this is the regression we fixed",async()=>{await s(),expect(e.gateway.sessionsPatch).not.toHaveBeenCalled()}),it("still subscribes to session.message events (needed for future prompts)",async()=>{await s(),expect(e.gateway.sessionsMessagesSubscribe).toHaveBeenCalledTimes(1);const[t]=e.gateway.sessionsMessagesSubscribe.mock.calls[0];expect(t).toMatch(/^agent:main:/)}),it("each session/new produces a unique gatewaySessionKey",async()=>{const t=await s(),n=e.state.sessions.get(t).gatewaySessionKey;e.transport.sendResult.mockClear();await e.bridge.handleSessionNew({jsonrpc:"2.0",id:2,method:"session/new"}),await Promise.resolve(),await Promise.resolve();const a=e.transport.sendResult.mock.calls[0]?.[1],o=e.state.sessions.get(a.sessionId).gatewaySessionKey;expect(o).not.toBe(n),expect(e.gateway.sessionsPatch).not.toHaveBeenCalled()})});
@@ -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,isHeartbeatOnlyText,isCronPromptText}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{ACP_PROTOCOL_VERSION,DEFAULT_PROMPT_TIMEOUT_MS,DEFAULT_LOAD_REPLAY_IDLE_TIMEOUT_MS,DEFAULT_LOAD_REPLAY_HARD_TIMEOUT_MS,DEFAULT_ASSISTANTMQ_LATECLOSE_TIMEOUT_MS}from"./types.js";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 i=s.match(/^\/([^\s:]+)(?::|\s|$)/)?.[1]?.trim();return i&&!i.includes("/")&&SLASH_COMMAND_NAME_RE.test(i)?i.toLowerCase():void 0}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;localSessionHistory;initialized=!1;agentMapping=null;_syncResolvers=[];_mappingReadyCallbacks=[];_loadSessionLock=new Map;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.localSessionHistory=new LocalSessionHistory({logger:this.logger}),this.transport.setSessionUpdateObserver((e,t,s)=>{const i=s?.turnId;if(!i)return;const n=this.state.sessions.get(e);n&&recordTurnIdForRole(n,t,i)})}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){this.state.sessions.set(e.sessionId,e),this.state.sessionsByGatewayKey.set(e.gatewaySessionKey,e),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 i=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 n=t.label||t.derivedTitle||t.title||void 0,o=n&&!isPlaceholderTitle(n)?n:void 0,r=createSessionObject({gatewayKey:s,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,title:o});this.registerSession(r),i++}i>0&&this.logger.info?.(`[bridge-core] preloadSessions: loaded ${i} 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}});try{switch(e.method){case"initialize":this.handleInitialize(e);break;case"session/new":await this.handleSessionNew(e);break;case"session/load":await this.handleSessionLoad(e);break;case"session/list":await this.handleSessionList(e);break;case"session/rename":this.handleSessionRename(e);break;case"session/delete":await this.handleSessionDelete(e);break;case"session/clear":await this.handleSessionClear(e);break;case"session/prompt":await this.handleSessionPrompt(e);break;case"session/set_mode":await this.handleSessionSetMode(e);break;case"session/set_model":await this.handleSessionSetModel(e);break;case"skills/list":await this.handleSkillsList(e);break;case"skills/install":await this.handleSkillsInstall(e);break;case"skills/uninstall":await this.handleSkillsUninstall(e);break;case"skills/update":await this.handleSkillsUpdate(e);break;case"models/list":await this.handleModelsList(e);break;case"session/cancel":this.handleSessionCancel(e.id,e.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(e);break;default: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,i=this.state.resolveSessionFromParams(t);if(!i){this.logger.warn?.(`[bridge-core] canvas/reference ignored — no session found for sessionId=${t?.sessionId}`);break}i.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:".",i=createSessionObject({gatewayKey:t,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,cwd:s});this.registerSession(i),this.transport.sendResult(e.id,{sessionId:i.sessionId,modes:{availableModes:[{...DEFAULT_MODE}],currentModeId:DEFAULT_MODE.id},_meta:{sessionKey:t,agentId:i.agentId,platformAgentId:i.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 i=this.state.sessionsByGatewayKey.get(t);if(!i)return;const n=e.message?.role,o="user"===n?"user":"system"===n?"system":"assistant",r=i.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="number"==typeof e.messageSeq?{seq:e.messageSeq}:void 0;let c;if(this.transport.sendSessionUpdate(i.sessionId,{sessionUpdate:"message_id_bind",turnId:r,role:o,messageId:s,...l?{timestamp:l}:{}},d),i.lastTurnIdByRole&&(i.lastTurnIdByRole[o]=void 0),"assistant"===o&&i.assistantMq&&!i.assistantMq.closed&&void 0!==i.assistantMqAwaitingRunId){c=i.assistantMqAwaitingRunId;const e=void 0!==i.assistantMqArmedAt?Date.now()-i.assistantMqArmedAt:0;this.clearAssistantMqCloseTimer(i),i.assistantMq.close(),this.logger.info?.(`[bridge-core] assistantMq late-close settled sessionId=${i.sessionId} runId=${c??"n/a"} messageId=${s} awaitedMs=${e}`),this.writeObs({component:"bridge-core",domain:"lifecycle",name:"assistantMq.lateclose.settled",severity:"info",payload:{sessionId:i.sessionId,runId:c,messageId:s,awaitedMs:e}})}"assistant"===o&&reconcileMissingArtifacts({localHistory:this.localSessionHistory,transport:this.transport,logger:this.logger,writeObs:this.writeObs,isSessionAlive:e=>this.state.sessions.has(e)},{session:i,turnId:r,messageId:s,runId:c})}async recoverSessionFromGateway(e){const t=this.getGateway();if(t?.isConnected)try{const s=await t.sessionsList();if(!s||"object"!=typeof s)return;const i=s.sessions;if(!Array.isArray(i))return;for(const t of i){const s=t,i=s.sessionKey??s.key??s.id??s.name;if(i&&"string"==typeof i&&deriveSessionId(i,this.instanceId)===e){const e=s.label||s.derivedTitle||s.title||void 0,t=e&&!isPlaceholderTitle(e)?e:void 0,n=createSessionObject({gatewayKey:i,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,title:t});return this.registerSession(n),n}}}catch(e){this.logger.debug?.("[bridge-core] recoverSessionFromGateway failed:",e)}}async resolveOrCreateSession(e){let t=this.state.sessions.get(e);if(!t&&e.startsWith("agent:")&&(t=this.state.findSessionByKey(e)),t||e.startsWith("agent:")||(t=await this.recoverSessionFromGateway(e)),t)return{session:t,created:!1};const s=e.startsWith("agent:"),i=this.config.gateway.agentId||this.getDefaultAgentId();return t=createSessionObject({gatewayKey:s?e:`agent:${i}:${e}`,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels}),this.registerSession(t),{session:t,created:!0}}async handleSessionLoad(e){const t=e.params?.sessionId;if(!t)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const s=this._loadSessionLock.get(t);if(s)try{await s}catch{}const i=this._doSessionLoad(e,t);this._loadSessionLock.set(t,i);try{await i}finally{this._loadSessionLock.get(t)===i&&this._loadSessionLock.delete(t)}}async _doSessionLoad(e,t){const{session:s}=await this.resolveOrCreateSession(t),i=s.sessionId;this.state.lastActiveSessionId=i,s.chatReplayDedupKeys.clear();let n=[];try{const e=this.getGateway(),t=await loadHistory(e,s.gatewaySessionKey,100,{localHistory:this.localSessionHistory,agentId:s.agentId,sessionId:s.sessionId,logger:this.logger,emitObs:e=>{this.writeObs({component:"history-replay",domain:"lifecycle",name:e.name,severity:e.severity,payload:e.payload})}});n=groupIntoTurns(t);const o=n.filter(e=>"user"===e.role).length,r=n.filter(e=>"assistant"===e.role).length,a=n.filter(e=>e.toolCalls?.length).length,l=n.reduce((e,t)=>e+(t.toolCalls?.length??0),0);if(this.logger.debug?.(`[bridge-core] handleSessionLoad sid=${i} messages=${t.length} turns=${n.length} userTurns=${o} asstTurns=${r} turnsWithToolCalls=${a} totalToolCalls=${l}`),n.length>0&&isPlaceholderTitle(s.title)&&"manual"!==s.titleSource){const e=n.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(e?.content){const t=stripTransportMetadata(e.content).trim().slice(0,64).replace(/\n/g," ").trim();if(t){s.title=t,s.titleSource="truncated";const e=this.getGateway();e?.isConnected&&e.sessionsPatch(s.gatewaySessionKey,{label:t}).catch(()=>{}),this.transport.sendSessionUpdate(i,{sessionUpdate:"title_update",title:t}),this.tryGenerateTitleFromHistory(s,i,n)}}}const d=e=>`history:${s.gatewaySessionKey}:${e}`;for(let e=0;e<n.length;e++){const t=n[e];"user"!==t.role||"internal_system"!==t.provenance?.kind?"user"===t.role&&/^\s*system\s*\(untrusted[^)]*\)/i.test(t.content)?this.logger.debug?.(`[bridge-core] SKIP history_turn[${e}] system-injected user message`):"user"===t.role&&isHeartbeatPromptText(t.content)?this.logger.debug?.(`[bridge-core] SKIP history_turn[${e}] heartbeat cron prompt`):"user"===t.role&&isCronPromptText(t.content)?this.logger.debug?.(`[bridge-core] SKIP history_turn[${e}] cron-triggered user message`):"assistant"===t.role&&isHeartbeatOnlyText(t.content)?this.logger.debug?.(`[bridge-core] SKIP history_turn[${e}] heartbeat assistant reply`):"system"!==t.role?(this.logger.debug?.(`[bridge-core] SENDING history_turn[${e}] role=${t.role} contentLen=${t.content.length} content=${JSON.stringify(t.content.slice(0,80))} tcCount=${t.toolCalls?.length??0}`),"user"===t.role?this.replayUserTurnAsChunks(i,t.content,t.metadata,t.timestamp,d(e),t.messageId,t._seq):await this.replayAssistantTurnAsStream(i,t,d(e))):(this.logger.debug?.(`[bridge-core] SENDING system_message[${e}] contentLen=${t.content.length}`),this.transport.sendSessionUpdate(i,{sessionUpdate:"system_message_chunk",content:{type:"text",text:t.content},metadata:t.metadata,...t.timestamp?{timestamp:t.timestamp}:{}},{turnId:d(e),...t.messageId?{messageId:t.messageId}:{},...void 0!==t._seq?{seq:t._seq}:{}})):this.logger.debug?.(`[bridge-core] SKIP history_turn[${e}] internal_system user message`)}}catch(e){this.logger.warn?.("[bridge-core] Failed to load session history:",e)}const o=new Set;for(const e of n)if(e.toolCalls)for(const t of e.toolCalls)t.id&&o.add(t.id),t.callId&&t.callId!==t.id&&o.add(t.callId);let r="",a="";for(let e=n.length-1;e>=0;e--)if("assistant"===n[e].role){r=n[e].content.slice(-200),a=(n[e].reasoning??"").slice(-200);break}const l=void 0!==s.assistantMq&&!s.assistantMq.closed,d=()=>{this.transport.sendResult(e.id,{sessionId:i}),this.onSessionLoaded?.(i,s.gatewaySessionKey,s.platformAgentId),this.pushSkillsList().catch(e=>{this.logger.warn?.(`[bridge-core] pushSkillsList failed: ${e instanceof Error?e.message:e}`)})};l?this.replayCurrentAssistantStream(s,o,r,a).catch(e=>{this.logger.warn?.(`[bridge-core] replayCurrentAssistantStream failed: ${e instanceof Error?e.message:e}`)}).finally(()=>d()):d()}async replayCurrentAssistantStream(e,t,s="",i=""){if(!e.assistantMq||e.assistantMq.closed)return;const n=this.config.loadReplayIdleTimeoutMs??DEFAULT_LOAD_REPLAY_IDLE_TIMEOUT_MS,o=DEFAULT_LOAD_REPLAY_HARD_TIMEOUT_MS,r=e.assistantMq.peek(0).length;this.writeObs({component:"bridge-core",domain:"lifecycle",name:"session.load.replay_start",severity:"debug",payload:{sessionId:e.sessionId,mqPendingCount:r}});let a=0,l=Date.now();const d={sent:0,skipped:0,cumulativeText:"",cumulativeReasoning:""};for(;e.assistantMq;){const r=e.assistantMq.peek(a);if(r.length>0){l=Date.now();a+=(await this.flushMqItems(e,r,a,t,s,i,d)).total;continue}if(e.assistantMq.closed)break;const c=Date.now()-l;if(c>=o){this.logger.warn?.(`[bridge-core] replayCurrentAssistantStream hard-idle-timeout sessionId=${e.sessionId} idleMs=${c} offset=${a}`),this.writeObs({component:"bridge-core",domain:"lifecycle",name:"session.load.replay_hardtimeout",severity:"warn",payload:{sessionId:e.sessionId,idleMs:c,offset:a}});break}if(c>=n){if(e.promptDone||void 0===e.pendingPromptId){this.logger.info?.(`[bridge-core] replayCurrentAssistantStream soft-idle-stop sessionId=${e.sessionId} idleMs=${c} offset=${a} promptDone=${!!e.promptDone}`),this.writeObs({component:"bridge-core",domain:"lifecycle",name:"session.load.replay_softidle_stop",severity:"info",payload:{sessionId:e.sessionId,idleMs:c,offset:a,promptDone:!!e.promptDone}});break}this.logger.debug?.(`[bridge-core] replayCurrentAssistantStream soft-idle-continue sessionId=${e.sessionId} idleMs=${c} offset=${a}`),this.writeObs({component:"bridge-core",domain:"lifecycle",name:"session.load.replay_softidle_continue",severity:"debug",payload:{sessionId:e.sessionId,idleMs:c,offset:a}})}await new Promise(e=>{const t=setTimeout(e,200);"object"==typeof t&&"unref"in t&&t.unref()})}d.skipped>0&&this.logger.debug?.(`[bridge-core] replayCurrentAssistantStream skipped ${d.skipped} duplicate tool events (already in history)`),(d.sent>0||d.skipped>0)&&this.writeObs({component:"bridge-core",domain:"lifecycle",name:"session.load.replay_complete",severity:"debug",payload:{sessionId:e.sessionId,replayed:d.sent,skipped:d.skipped}})}async flushMqItems(e,t,s,i,n,o,r){const a=r??{sent:0,skipped:0,cumulativeText:"",cumulativeReasoning:""};let l=0;for(const s of t)if(l++,i?.size&&s.toolCallId&&i.has(s.toolCallId)&&("tool_call"===s.sessionUpdate||"tool_call_update"===s.sessionUpdate))a.skipped++;else{if(n.length>0&&"agent_message_chunk"===s.sessionUpdate){const e=s.content?.text;if("string"==typeof e&&(a.cumulativeText+=e,a.cumulativeText.length<=n.length)){a.skipped++;continue}}if(o.length>0&&"agent_thought_chunk"===s.sessionUpdate){const e=s.content?.text;if("string"==typeof e&&(a.cumulativeReasoning+=e,a.cumulativeReasoning.length<=o.length)){a.skipped++;continue}}this.transport.sendSessionUpdate(e.sessionId,s),a.sent++}return{total:l}}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,i=s.sessionKey??s.key??s.id??s.name;if(!i||"string"!=typeof i)continue;if(isBackgroundSessionKey(i))continue;if(this.cronIsolatedSessionKeys.has(i))continue;const n=deriveSessionId(i,this.instanceId),o=t.find(e=>e.sessionId===i||e.sessionId===n||this.state.sessions.get(e.sessionId)?.gatewaySessionKey===i),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:i,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,cwd:s.cwd,title:a});this.registerSession(e),t.push({sessionId:e.sessionId,title:a||"",cwd:s.cwd,updatedAt:s.updatedAt,agentId:e.agentId,platformAgentId:e.platformAgentId,deletable:!isSystemDefaultSessionKey(i),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 i=s.slice(0,64),n=this.state.sessions.get(t);if(!n)return void this.transport.sendAcpError(e.id,Errors.SessionNotFound);n.title=i,n.titleSource="manual";const o=n.gatewaySessionKey,r=this.getGateway();r?.isConnected&&r.sessionsPatch(o,{label:i}).catch(e=>{this.logger.debug?.(`[bridge-core] sessionsPatch (rename) failed: ${e instanceof Error?e.message:e}`)}),this.transport.sendResult(e.id,{sessionId:t,title:i})}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,i){if(this.isGuardMessage(s))return void this.logger.info?.(`[bridge-core] title-gen SKIP guard message sid=${t}`);const n=this.matchTitleTemplate(s);if(n){e.title=n,e.titleSource="template";const s=this.getGateway();return s?.isConnected&&s.sessionsPatch(e.gatewaySessionKey,{label:n}).catch(()=>{}),void this.transport.sendSessionUpdate(t,{sessionUpdate:"title_update",title:n})}const 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(i)}`;this.logger.info?.(`[bridge-core] title-gen CALLING LLM sid=${t} q="${s.slice(0,60)}" aLen=${i.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 i=await s.json(),n=i.choices?.[0]?.message?.content?.trim();if(!n)return;const o=n.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 i=this.getGateway();if(!i?.isConnected)return;let n=s;if(!n)try{const t=await loadHistory(i,e.gatewaySessionKey);n=groupIntoTurns(t)}catch(e){return void this.logger.debug?.(`[bridge-core] title-gen loadHistory failed sid=${t}: ${e instanceof Error?e.message:e}`)}const o=n.find(e=>{if("user"!==e.role)return!1;if(!e.content?.trim())return!1;if("internal_system"===e.provenance?.kind)return!1;if(isCronPromptText(e.content))return!1;const t=stripTransportMetadata(e.content).trim();return!!t&&!/^Sender\s*\(untrusted/i.test(t)});if(!o)return;const r=n.indexOf(o),a=n.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 i=s.gatewaySessionKey;this.logger.info?.(`[bridge-core] session/delete sessionId=${t} gatewayKey=${i} gwConnected=${!!this.getGateway()?.isConnected}`);let n=!1;const o=this.getGateway();if(o?.isConnected&&i)try{await o.sessionsDelete(i),n=!0,this.logger.info?.(`[bridge-core] Gateway sessions.delete SUCCESS for key=${i}`)}catch(t){const s=t instanceof Error?t.message:String(t);if(this.logger.info?.(`[bridge-core] Gateway sessions.delete FAILED for key=${i}: ${s}`),!s.includes("Cannot delete the main session"))return void this.transport.sendResult(e.id,{deleted:!1});try{await o.sessionsReset(i),n=!0,this.logger.info?.(`[bridge-core] Gateway sessions.reset SUCCESS for key=${i}`)}catch(t){return this.logger.warn?.(`[bridge-core] Gateway sessions.reset also failed for key=${i}: ${t instanceof Error?t.message:t}`),void this.transport.sendResult(e.id,{deleted:!1})}}else i&&this.logger.warn?.(`[bridge-core] Gateway not connected, proceeding with local-only delete for key=${i}`);void 0!==s.pendingPromptId&&this.failPrompt(s,Errors.SessionDeleted.rpcCode,Errors.SessionDeleted.message),this.state.clearPromptTimeout(s),this.state.clearStreamIdleTimer(s),this.clearAssistantMqCloseTimer(s),s.assistantMq?.close(),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(i),this.transport.resetSessionUpdateCount(t),n&&this.onSessionDeleted?.(i),this.logger.info?.(`[bridge-core] session/delete DONE sessionId=${t} gatewayKey=${i} deleted=true`),this.transport.sendResult(e.id,{deleted:!0})}async handleSessionClear(e){this.logger.info?.(`[bridge-core] handleSessionClear called, params=${JSON.stringify(e.params)}`);const t=e.params?.sessionId;if(!t)return this.logger.warn?.("[bridge-core] session/clear missing sessionId"),void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const s=this.state.sessions.get(t);if(!s)return this.logger.warn?.(`[bridge-core] session/clear sessionId=${t} not found in state`),void this.transport.sendAcpError(e.id,Errors.SessionNotFound);this.logger.info?.(`[bridge-core] session/clear sessionId=${t} gatewayKey=${s.gatewaySessionKey}`);const i=this.getGateway(),n=i?.isConnected;if(s.promptDone||void 0===s.pendingPromptId&&void 0===s.currentRunId||(this.logger.info?.(`[bridge-core] session/clear: cancelling active run sid=${t} runId=${s.currentRunId}`),n&&(s.currentRunId||s.gatewayRequestId)&&i.agentCancel(s.gatewaySessionKey,{runId:s.currentRunId,requestId:s.gatewayRequestId}),this.endRun(s,{kind:"complete",stopReason:"cancelled"})),n&&s.gatewaySessionKey)try{await i.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=${n}, 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,i=t?this.state.sessions.get(t):void 0,n=this.getGateway();if(i&&n?.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 n.sessionsPatch(i.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,i=t?this.state.sessions.get(t):void 0,n=this.getGateway();let o=s??null,r=null;if(i&&n?.isConnected&&s)try{const e=await n.sessionsPatch(i.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})),i=this.getSkillsDir();for(const e of s){const t=e.skillKey??e.name;try{const s=await readFile(join(i,t,".beeos-meta.json"),"utf8"),n=JSON.parse(s);n?.iconUrl&&(e.iconUrl=n.iconUrl)}catch{}}return 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,i=t?.files;let n;try{n=validateSkillSlug(t?.slug||t?.name||"")}catch{return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Invalid or missing skill slug"})}if(!i?.length&&!s)return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Missing skill files or zipUrl"});const o=resolveSkillInstallDir(this.getSkillsDir(),n);try{if(await mkdir(o,{recursive:!0}),s){const e=await fetchWithRetry(s,{maxRetries:4,logger:this.logger});await extractZipToDir(e,o)}else if(i?.length){const e=resolve(o);for(const t of i){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 i=await fetch(t.downloadUrl,{signal:AbortSignal.timeout(12e4)});if(!i.ok)throw new Error(`Failed to download ${t.path}: ${i.status}`);const n=Buffer.from(await i.arrayBuffer());await writeFile(s,n)}}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 "${n}" via ${s?"zip":"files"}`),this.transport.sendResult(e.id,{success:!0}),this.onSkillInstalled?.(n,o),await this.pushSkillsList()}catch(t){this.logger.error?.(`[bridge-core] Failed to install skill "${n}": ${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 i=resolveSkillInstallDir(this.getSkillsDir(),s),n=resolveSkillInstallDir(join(homedir(),".agents","skills"),s);try{let t=!1;try{const e=await lstat(i);if(e.isSymbolicLink()){const e=await readlink(i);await rm(i,{force:!0}),await rm(e,{recursive:!0,force:!0}),t=!0}else e.isDirectory()&&(await rm(i,{recursive:!0,force:!0}),t=!0)}catch{}try{const e=await lstat(n);(e.isDirectory()||e.isSymbolicLink())&&(await rm(n,{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,i=t?.enabled;if(!s||"boolean"!=typeof i)return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Missing skillKey or enabled"});const n=this.getGateway();if(n?.isConnected)try{const t=await n.skillsUpdate(s,i);this.logger.info?.(`[bridge-core] Updated skill "${s}" enabled=${i}`),this.transport.sendResult(e.id,{ok:t?.ok??!0,skillKey:s,enabled:i}),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:i,created:n}=await this.resolveOrCreateSession(t);n&&this.onSessionLoaded?.(i.sessionId,i.gatewaySessionKey,i.platformAgentId);const o=i.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(i);let a=extractPromptBlocks(sanitizePromptPayload(s));if(!i.title||isPlaceholderTitle(i.title)){const e=a.find(e=>"text"===e.type&&e.text);if(e&&"text"in e&&e.text){const t=stripTransportMetadata(e.text).trim();if(this.logger.info?.(`[bridge-core] title-gen sid=${o} existing="${i.title}" cleanText="${t.slice(0,80)}" isPlaceholder=${isPlaceholderTitle(t)}`),t&&!isPlaceholderTitle(t)){const e=t.slice(0,64).replace(/\n/g," ").trim();i.title=e,i.titleSource="truncated",r?.isConnected&&e&&r.sessionsPatch(i.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:m,attachments:g}=c,h=resolveStandaloneSlashCommandName(a,m)??resolveSlashCmd(a,m),p="string"==typeof h;if(h&&this.handleSlashCommand){const t=this;if(await(async()=>{try{return await t.handleSlashCommand(h)}catch(e){return t.logger.warn?.(`[bridge-core] /${h} handler failed: ${e instanceof Error?e.message:e}`),!1}})())return this.emitPromptAsUserSessionUpdates(i.sessionId,a,resolveTurnId(i)),this.transport.sendSessionUpdate(o,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Loading ${h}...`},timestamp:(new Date).toISOString()},{turnId:resolveTurnId(i)}),void this.transport.sendResult(e.id,{stopReason:"end_turn"})}const u="chat.send";let y=p?m:withUserMessagePrefix(m);const f=this.config.canvasEnabled&&!p&&!1!==i.canvasActive&&!i.channelType;if(f){const e=i.promptsSinceCanvasInjection??0;!i.canvasPromptInjected||e>=10?(y=`${CANVAS_TERM_MAPPING}\n\n${y}`,i.canvasPromptInjected=!0,i.promptsSinceCanvasInjection=0,this.logger.debug?.("[bridge-core] Canvas term mapping injected (re-inject cycle)")):i.promptsSinceCanvasInjection=e+1}if(f){const e=this.getCanvasState?.();if(e){const t=e.resolveCanvasForSession(i.gatewaySessionKey);y=`${buildActiveSurfacesContext(e,t)??"[Canvas] Canvas panel is available. Use render_ui for structured/visual content."}\n\n${y}`}const t=i.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}`,i.referencedSurfaceId=void 0)}if(!p){const t=parseMentionsParam(e.params?.mentions);if(t.length>0){i.activeMentions=t;y=`${buildMentionInstruction(t)}\n${y}`,this.logger.debug?.(`[bridge-core] A2A mention instruction injected for ${t.length} agent(s)`)}else i.activeMentions=void 0}p&&this.logger.info?.(`[bridge-core] slash command passthrough sessionId=${o} command=/${h}`),i.promptDone||void 0===i.pendingPromptId&&void 0===i.currentRunId||(this.logger.warn?.(`[bridge-core] handleSessionPrompt: force-ending stale run sid=${o} oldRunId=${i.currentRunId} oldPromptId=${i.pendingPromptId}`),(i.currentRunId||i.gatewayRequestId)&&r.agentCancel(i.gatewaySessionKey,{runId:i.currentRunId,requestId:i.gatewayRequestId}),this.endRun(i,{kind:"complete",stopReason:"cancelled"})),this.state.resetForNewRun(i,o,this.transport),i.pendingPromptId=e.id,i.gatewayMethod=u;const I=resolveTurnId(i);this.emitPromptAsUserSessionUpdates(o,a,I),this.transport.sendSessionUpdate(o,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:""},timestamp:(new Date).toISOString()},I?{turnId:I}:void 0),this.schedulePromptTimeout(i);const S=g.length>0?g.map(e=>({type:e.type,content:e.content,...e.mimeType?{mimeType:e.mimeType}:{},...e.fileName?{fileName:e.fileName}:{}})):void 0,w=`req_${randomUUID().replace(/-/g,"")}`,b={sessionKey:i.gatewaySessionKey,message:y,deliver:!1,idempotencyKey:randomUUID()};S?.length&&(b.attachments=S);if(!r.sendFrame({type:"req",id:w,method:u,params:b}))return this.state.clearPromptTimeout(i),i.pendingPromptId=void 0,this.clearAssistantMqCloseTimer(i),i.assistantMq?.close(),void this.transport.sendAcpError(e.id,Errors.SendFailed,{message:"failed to send prompt to gateway"});i.gatewayRequestId=w,this.state.promptsByGatewayRequestId.set(w,i)}replayUserTurnAsChunks(e,t,s,i,n,o,r){const a=splitUserReplayBlocks(t),l=n||o||void 0!==r?{...n?{turnId:n}:{},...o?{messageId:o}:{},...void 0!==r?{seq:r}:{}}:void 0;for(const t of a){let n;if("text"===t.type){if(!t.text)continue;n={type:"text",text:t.text}}else n="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:n,...s?{metadata:s}:{},...i?{timestamp:i}:{}},l)}}async replayAssistantTurnAsStream(e,t,s){const i=(e,t)=>{if(s||e||void 0!==t)return{...s?{turnId:s}:{},...e?{messageId:e}:{},...void 0!==t?{seq:t}:{}}},n=i(t.messageId,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,n)}for(const s of t.sourceMessages){const n=s.updateType??"agent_message_chunk",o=i(s.messageId,s._seq);switch(n){case"agent_message_chunk":this.transport.sendSessionUpdate(e,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:s.content},...s.timestamp?{timestamp:s.timestamp}:{}},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 i=s.toolCallId??"",n=t.toolCalls?.find(e=>e.id===i),r=s.toolName??"tool",a=s.content??"";let l={};if(a)try{l=JSON.parse(a)}catch{}this.transport.sendSessionUpdate(e,buildToolCallPayload({toolCallId:i,toolName:r,args:l,kind:n?.kind,status:n?.status??"in_progress",timestamp:s.timestamp}),o);break}case"tool_call_update":{const i=s.toolCallId??"",n=t.toolCalls?.find(e=>e.id===i),r=s.toolName??n?.name??"tool",a=s.content??n?.output??"";let l=await readEnrichmentCache(i).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(i).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:i,toolName:r,outputText:a,kind:n?.kind,status:n?.status??"completed",resourceLinks:l,timestamp:s.timestamp}),o);break}}}}emitPromptAsUserSessionUpdates(e,t,s){const i=(new Date).toISOString(),n=s?{turnId:s}:void 0;for(const s of t){const t=this.toUserSessionUpdateContent(s);t&&this.transport.sendSessionUpdate(e,{sessionUpdate:"user_message_chunk",content:t,timestamp:i},n)}}toUserSessionUpdateContent(e){if("text"===e.type){if(!e.text)return;return{type:"text",text:e.text}}if("image"===e.type){const t=e.mimeType??e.mime_type??"application/octet-stream",s=e.fileName??e.file_name??e.name;if(!e.data&&!e.uri)return;return{type:"image",...e.data?{data:e.data}:{},...e.uri?{uri:e.uri}:{},...t?{mimeType:t}:{},...s?{fileName:s}:{}}}if("resource_link"===e.type){if(!e.uri)return;return{type:"resource_link",uri:e.uri,...e.title?{title:e.title}:{},...e.name?{name:e.name}:{},...e.mimeType??e.mime_type?{mimeType:e.mimeType??e.mime_type}:{}}}if("file"===e.type){const t=e.mimeType??e.mime_type??"application/octet-stream",s=e.fileName??e.file_name??e.filename??e.name;if(!e.data&&!e.text&&!e.uri)return;return{type:"file",...e.data?{data:e.data}:{},...e.text?{text:e.text}:{},...e.uri?{uri:e.uri}:{},...t?{mimeType:t}:{},...s?{fileName:s}:{}}}if("resource"===e.type){const t=e.resource??{},s=t.uri??e.uri,i=t.mimeType??t.mime_type??e.mimeType??e.mime_type,n=t.text??e.text,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&&!n&&!o)return;return{type:"resource",resource:{...s?{uri:s}:{},...i?{mimeType:i}:{},...n?{text:n}:{},...o?{data:o}:{},...r?{fileName:r}:{}}}}}handleSessionCancel(e,t){const s=t?.sessionId;if(!s)return void(void 0!==e&&this.transport.sendAcpError(e,Errors.MissingParam,{param:"sessionId"}));const i=this.state.sessions.get(s);if(!i)return void(void 0!==e&&this.transport.sendAcpError(e,Errors.SessionNotFound));const n=this.getGateway(),o=n?.isConnected,r=!(!i.currentRunId&&!i.gatewayRequestId);if(o&&r){n.agentCancel(i.gatewaySessionKey,{runId:i.currentRunId,requestId:i.gatewayRequestId})}this.endRun(i,{kind:"complete",stopReason:"cancelled"})||this.transport.sendSessionUpdate(i.sessionId,{sessionUpdate:"stream_complete",stopReason:"cancelled"},{turnId:resolveTurnId(i)}),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),i=s?{turnId:s}:void 0;e.promptDone=!0;const n=e.currentRunId;if("complete"===t.kind){if(n&&this.onRunComplete){const t=e.agentAssistantTextSoFar??e.chatAssistantTextSoFar??"";this.onRunComplete(n,t)}void 0!==e.pendingPromptId&&this.transport.sendResult(e.pendingPromptId,{stopReason:t.stopReason}),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:t.stopReason},i),this.tryGenerateTitleFromHistory(e,e.sessionId)}else n&&this.onRunFailed&&this.onRunFailed(n,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},i);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);const s=e.currentRunId;e.pendingPromptId=void 0,e.promptDone=void 0,e.currentRunId=void 0,e.gatewayRequestId=void 0,e.assistantStreamStartedAt=void 0,e.gatewayMethod=void 0,this.armAssistantMqLateClose(e,s)}armAssistantMqLateClose(e,t){if(!e.assistantMq||e.assistantMq.closed)return;this.clearAssistantMqCloseTimer(e),e.assistantMqAwaitingRunId=t,e.assistantMqArmedAt=Date.now();const s=DEFAULT_ASSISTANTMQ_LATECLOSE_TIMEOUT_MS;this.writeObs({component:"bridge-core",domain:"lifecycle",name:"assistantMq.lateclose.armed",severity:"debug",payload:{sessionId:e.sessionId,runId:t,timeoutMs:s}}),e.assistantMqCloseTimer=setTimeout(()=>{e.assistantMq&&!e.assistantMq.closed&&(this.logger.warn?.(`[bridge-core] assistantMq late-close timeout sessionId=${e.sessionId} runId=${t??"n/a"} timeoutMs=${s}`),this.writeObs({component:"bridge-core",domain:"lifecycle",name:"assistantMq.lateclose.timeout",severity:"warn",payload:{sessionId:e.sessionId,runId:t,timeoutMs:s}}),e.assistantMq.close()),e.assistantMqCloseTimer=void 0,e.assistantMqAwaitingRunId=void 0,e.assistantMqArmedAt=void 0},s),"object"==typeof e.assistantMqCloseTimer&&"unref"in e.assistantMqCloseTimer&&e.assistantMqCloseTimer.unref()}clearAssistantMqCloseTimer(e){e.assistantMqCloseTimer&&(clearTimeout(e.assistantMqCloseTimer),e.assistantMqCloseTimer=void 0),e.assistantMqAwaitingRunId=void 0,e.assistantMqArmedAt=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 i=e.error,n=i?.message??"gateway returned error";return this.logger.warn?.(`[bridge-core] handleGatewayResponse: gateway rejected prompt gatewayRequestId=${t} error=${n}`),void this.failPrompt(s,Errors.SendFailed.rpcCode,n)}const i=e.payload,n=i?.runId;n?(s.currentRunId=n,s.assistantStreamStartedAt=Date.now(),this.state.promptsByRunId.set(n,s),this.logger.debug?.(`[bridge-core] handleGatewayResponse: bound runId=${n} gatewayRequestId=${t} sessionId=${s.sessionId}`)):this.logger.debug?.(`[bridge-core] handleGatewayResponse: no runId in payload gatewayRequestId=${t} sessionId=${s.sessionId}`)}maybeCompletePromptFromChatState(e,t){if(e.promptDone||"chat.send"!==e.gatewayMethod)return;const s="string"==typeof t.state?t.state.toLowerCase():void 0;if(s)if("final"===s)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,i){if(0===s.length)return;const n=i?this.state.promptsByRunId.get(i):void 0;if(!n)return void this.logger.warn?.(`[bridge-core] pushToolResultContent dropped — no session for runId=${i??"(none)"}`);const o=n.sessionId,r=(new Date).toISOString(),a={turnId:resolveTurnId(n)};for(const e of s){const t={sessionUpdate:"agent_message_chunk",content:e,timestamp:r};this.transport.sendSessionUpdate(o,t,a),n.assistantMq?.push(t)}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("/",".");try{const i=await t.request(s,e.params??{});this.transport.sendResult(e.id,i??{}),"cron.add"!==s&&"cron.update"!==s&&"cron.remove"!==s||this.refreshCronIsolatedSessionKeys()}catch(t){const i=t instanceof Error?t.message:"cron request failed";this.logger.warn?.(`[bridge-core] ${s} failed: ${i}`),this.transport.sendAcpError(e.id,Errors.SendFailed,{message:i})}}async refreshCronIsolatedSessionKeys(){const e=this.getGateway();if(e?.isConnected)try{const t=await e.request("cron.list",{}),s=t?.jobs;if(!Array.isArray(s))return;const i=new Set;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&&i.add(s)}this.cronIsolatedSessionKeys=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 i;for(let n=0;n<=s;n++){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**n);if(i=new Error(`HTTP ${o.status} from ${e}`),n<s){t.logger?.info?.(`[bridge-core] Download ${o.status}, retry ${n+1}/${s} in ${(a/1e3).toFixed(0)}s`),await new Promise(e=>setTimeout(e,a));continue}}throw new Error(`Failed to download zip: ${o.status}`)}throw i??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),i=join(t,".beeos-extract-tmp-"+Date.now());try{await mkdir(i,{recursive:!0}),s.extractAllTo(i,!0);const e=await resolveSkillRoot(i),n=await readdir(e,{withFileTypes:!0});let o=0;for(const s of n){if(s.name.startsWith(".beeos-extract-tmp")||"__MACOSX"===s.name)continue;const i=join(e,s.name),n=join(t,s.name);await rename(i,n).catch(async()=>{await cp(i,n,{recursive:!0})}),o++}if(0===o)throw new Error("Zip archive contained no extractable files")}finally{await rm(i,{recursive:!0,force:!0}).catch(()=>{})}}const VALID_SLUG_PATTERN=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,NON_ASCII_PATTERN=/[^\x00-\x7F]/;function validateSkillSlug(e){const t=e.trim();if(!t||t.includes("/")||t.includes("\\")||t.includes(".."))throw new Error(`Invalid skill slug: ${e}`);if(NON_ASCII_PATTERN.test(t)||!VALID_SLUG_PATTERN.test(t))throw new Error(`Invalid skill slug: ${e}`);return t}function safeDirName(e){const t=e.trim();return t?t.replaceAll("/","__").replaceAll("\\","__"):t}function resolveSkillInstallDir(e,t){const s=safeDirName(t),i=join(e,s),n=resolve(e),o=resolve(i),r=relative(n,o);if(!r||".."===r||r.startsWith(`..${sep}`)||path.isAbsolute(r))throw new Error("Invalid skill target path");return i}
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,isHeartbeatOnlyText,isCronPromptText}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{ACP_PROTOCOL_VERSION,DEFAULT_PROMPT_TIMEOUT_MS,DEFAULT_LOAD_REPLAY_IDLE_TIMEOUT_MS,DEFAULT_LOAD_REPLAY_HARD_TIMEOUT_MS,DEFAULT_ASSISTANTMQ_LATECLOSE_TIMEOUT_MS}from"./types.js";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 i=s.match(/^\/([^\s:]+)(?::|\s|$)/)?.[1]?.trim();return i&&!i.includes("/")&&SLASH_COMMAND_NAME_RE.test(i)?i.toLowerCase():void 0}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;localSessionHistory;initialized=!1;agentMapping=null;_syncResolvers=[];_mappingReadyCallbacks=[];_loadSessionLock=new Map;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.localSessionHistory=new LocalSessionHistory({logger:this.logger}),this.transport.setSessionUpdateObserver((e,t,s)=>{const i=s?.turnId;if(!i)return;const n=this.state.sessions.get(e);n&&recordTurnIdForRole(n,t,i)})}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,i=this.state.sessions.has(e.sessionId);if(this.state.sessions.set(e.sessionId,e),this.state.sessionsByGatewayKey.set(e.gatewaySessionKey,e),!i){const t=(new Error).stack?.split("\n")[2]?.trim()??"(unknown)";this.logger.info?.(`[new-chat-stampede] registerSession sid=${e.sessionId.slice(0,12)} title="${(e.title??"").slice(0,24)}" ensureVerbose=${s} stateSize=${this.state.sessions.size} from: ${t}`)}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 i=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 n=t.label||t.derivedTitle||t.title||void 0,o=n&&!isPlaceholderTitle(n)?n:void 0,r=createSessionObject({gatewayKey:s,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,title:o});this.registerSession(r,{ensureVerbose:!1}),i++}i>0&&this.logger.info?.(`[bridge-core] preloadSessions: loaded ${i} 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: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,i=this.state.resolveSessionFromParams(t);if(!i){this.logger.warn?.(`[bridge-core] canvas/reference ignored — no session found for sessionId=${t?.sessionId}`);break}i.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:".",i=createSessionObject({gatewayKey:t,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,cwd:s}),n=this.state.sessions.size;this.registerSession(i,{ensureVerbose:!1}),this.logger.info?.(`[new-chat-stampede] session/new sid=${i.sessionId.slice(0,12)} gwKey=${t.slice(0,40)} stateSize ${n}→${this.state.sessions.size}`),this.transport.sendResult(e.id,{sessionId:i.sessionId,modes:{availableModes:[{...DEFAULT_MODE}],currentModeId:DEFAULT_MODE.id},_meta:{sessionKey:t,agentId:i.agentId,platformAgentId:i.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 i=this.state.sessionsByGatewayKey.get(t);if(!i)return;const n=e.message?.role,o="user"===n?"user":"system"===n?"system":"assistant",r=i.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};let c;if("number"==typeof e.messageSeq&&(d.seq=e.messageSeq),this.transport.sendSessionUpdate(i.sessionId,{sessionUpdate:"message_id_bind",role:o,messageId:s,...l?{timestamp:l}:{}},d),i.lastTurnIdByRole&&(i.lastTurnIdByRole[o]=void 0),"assistant"===o&&i.assistantMq&&!i.assistantMq.closed&&void 0!==i.assistantMqAwaitingRunId){c=i.assistantMqAwaitingRunId;const e=void 0!==i.assistantMqArmedAt?Date.now()-i.assistantMqArmedAt:0;this.clearAssistantMqCloseTimer(i),i.assistantMq.close(),this.logger.info?.(`[bridge-core] assistantMq late-close settled sessionId=${i.sessionId} runId=${c??"n/a"} messageId=${s} awaitedMs=${e}`),this.writeObs({component:"bridge-core",domain:"lifecycle",name:"assistantMq.lateclose.settled",severity:"info",payload:{sessionId:i.sessionId,runId:c,messageId:s,awaitedMs:e}})}"assistant"===o&&reconcileMissingArtifacts({localHistory:this.localSessionHistory,transport:this.transport,logger:this.logger,writeObs:this.writeObs,isSessionAlive:e=>this.state.sessions.has(e)},{session:i,turnId:r,messageId:s,runId:c})}async recoverSessionFromGateway(e){const t=this.getGateway();if(t?.isConnected)try{const s=await t.sessionsList();if(!s||"object"!=typeof s)return;const i=s.sessions;if(!Array.isArray(i))return;for(const t of i){const s=t,i=s.sessionKey??s.key??s.id??s.name;if(i&&"string"==typeof i&&deriveSessionId(i,this.instanceId)===e){const e=s.label||s.derivedTitle||s.title||void 0,t=e&&!isPlaceholderTitle(e)?e:void 0,n=createSessionObject({gatewayKey:i,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,title:t});return this.registerSession(n),n}}}catch(e){this.logger.debug?.("[bridge-core] recoverSessionFromGateway failed:",e)}}async resolveOrCreateSession(e){let t=this.state.sessions.get(e);if(!t&&e.startsWith("agent:")&&(t=this.state.findSessionByKey(e)),t||e.startsWith("agent:")||(t=await this.recoverSessionFromGateway(e)),t)return{session:t,created:!1};const s=e.startsWith("agent:"),i=this.config.gateway.agentId||this.getDefaultAgentId();return t=createSessionObject({gatewayKey:s?e:`agent:${i}:${e}`,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels}),this.registerSession(t),{session:t,created:!0}}async handleSessionLoad(e){const t=e.params?.sessionId;if(!t)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const s=this._loadSessionLock.get(t);if(s)try{await s}catch{}const i=this._doSessionLoad(e,t);this._loadSessionLock.set(t,i);try{await i}finally{this._loadSessionLock.get(t)===i&&this._loadSessionLock.delete(t)}}async _doSessionLoad(e,t){const{session:s}=await this.resolveOrCreateSession(t),i=s.sessionId;this.state.lastActiveSessionId=i,s.chatReplayDedupKeys.clear();let n=[];try{const e=this.getGateway(),t=await loadHistory(e,s.gatewaySessionKey,100,{localHistory:this.localSessionHistory,agentId:s.agentId,sessionId:s.sessionId,logger:this.logger,emitObs:e=>{this.writeObs({component:"history-replay",domain:"lifecycle",name:e.name,severity:e.severity,payload:e.payload})}});n=groupIntoTurns(t);const o=n.filter(e=>"user"===e.role).length,r=n.filter(e=>"assistant"===e.role).length,a=n.filter(e=>e.toolCalls?.length).length,l=n.reduce((e,t)=>e+(t.toolCalls?.length??0),0);if(this.logger.debug?.(`[bridge-core] handleSessionLoad sid=${i} messages=${t.length} turns=${n.length} userTurns=${o} asstTurns=${r} turnsWithToolCalls=${a} totalToolCalls=${l}`),n.length>0&&isPlaceholderTitle(s.title)&&"manual"!==s.titleSource){const e=n.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(e?.content){const t=stripTransportMetadata(e.content).trim().slice(0,64).replace(/\n/g," ").trim();if(t){s.title=t,s.titleSource="truncated";const e=this.getGateway();e?.isConnected&&e.sessionsPatch(s.gatewaySessionKey,{label:t}).catch(()=>{}),this.transport.sendSessionUpdate(i,{sessionUpdate:"title_update",title:t}),this.tryGenerateTitleFromHistory(s,i,n)}}}const d=e=>`history:${s.gatewaySessionKey}:${e}`;for(let e=0;e<n.length;e++){const t=n[e];"user"!==t.role||"internal_system"!==t.provenance?.kind?"user"===t.role&&/^\s*system\s*\(untrusted[^)]*\)/i.test(t.content)?this.logger.debug?.(`[bridge-core] SKIP history_turn[${e}] system-injected user message`):"user"===t.role&&isHeartbeatPromptText(t.content)?this.logger.debug?.(`[bridge-core] SKIP history_turn[${e}] heartbeat cron prompt`):"user"===t.role&&isCronPromptText(t.content)?this.logger.debug?.(`[bridge-core] SKIP history_turn[${e}] cron-triggered user message`):"assistant"===t.role&&isHeartbeatOnlyText(t.content)?this.logger.debug?.(`[bridge-core] SKIP history_turn[${e}] heartbeat assistant reply`):"system"!==t.role?(this.logger.debug?.(`[bridge-core] SENDING history_turn[${e}] role=${t.role} contentLen=${t.content.length} content=${JSON.stringify(t.content.slice(0,80))} tcCount=${t.toolCalls?.length??0}`),"user"===t.role?this.replayUserTurnAsChunks(i,t.content,t.metadata,t.timestamp,d(e),t.messageId,t._seq):await this.replayAssistantTurnAsStream(i,t,d(e))):(this.logger.debug?.(`[bridge-core] SENDING system_message[${e}] contentLen=${t.content.length}`),this.transport.sendSessionUpdate(i,{sessionUpdate:"system_message_chunk",content:{type:"text",text:t.content},metadata:t.metadata,...t.timestamp?{timestamp:t.timestamp}:{}},{turnId:d(e),...t.messageId?{messageId:t.messageId}:{},...void 0!==t._seq?{seq:t._seq}:{}})):this.logger.debug?.(`[bridge-core] SKIP history_turn[${e}] internal_system user message`)}}catch(e){this.logger.warn?.("[bridge-core] Failed to load session history:",e)}const o=new Set;for(const e of n)if(e.toolCalls)for(const t of e.toolCalls)t.id&&o.add(t.id),t.callId&&t.callId!==t.id&&o.add(t.callId);let r="",a="";for(let e=n.length-1;e>=0;e--)if("assistant"===n[e].role){r=n[e].content.slice(-200),a=(n[e].reasoning??"").slice(-200);break}const l=void 0!==s.assistantMq&&!s.assistantMq.closed,d=()=>{this.transport.sendResult(e.id,{sessionId:i}),this.onSessionLoaded?.(i,s.gatewaySessionKey,s.platformAgentId),this.pushSkillsList().catch(e=>{this.logger.warn?.(`[bridge-core] pushSkillsList failed: ${e instanceof Error?e.message:e}`)})};if(l)return this.replayCurrentAssistantStream(s,o,r,a).catch(e=>{this.logger.warn?.(`[bridge-core] replayCurrentAssistantStream failed: ${e instanceof Error?e.message:e}`)}).finally(()=>d());d()}async replayCurrentAssistantStream(e,t,s="",i=""){if(!e.assistantMq||e.assistantMq.closed)return;const n=this.config.loadReplayIdleTimeoutMs??DEFAULT_LOAD_REPLAY_IDLE_TIMEOUT_MS,o=DEFAULT_LOAD_REPLAY_HARD_TIMEOUT_MS,r=e.assistantMq.peek(0).length;this.writeObs({component:"bridge-core",domain:"lifecycle",name:"session.load.replay_start",severity:"debug",payload:{sessionId:e.sessionId,mqPendingCount:r}});let a=0,l=Date.now();const d={sent:0,skipped:0,cumulativeText:"",cumulativeReasoning:""};for(;e.assistantMq;){const r=e.assistantMq.peek(a);if(r.length>0){l=Date.now();a+=(await this.flushMqItems(e,r,a,t,s,i,d)).total;continue}if(e.assistantMq.closed)break;const c=Date.now()-l;if(c>=o){this.logger.warn?.(`[bridge-core] replayCurrentAssistantStream hard-idle-timeout sessionId=${e.sessionId} idleMs=${c} offset=${a}`),this.writeObs({component:"bridge-core",domain:"lifecycle",name:"session.load.replay_hardtimeout",severity:"warn",payload:{sessionId:e.sessionId,idleMs:c,offset:a}});break}if(c>=n){if(e.promptDone||void 0===e.pendingPromptId){this.logger.info?.(`[bridge-core] replayCurrentAssistantStream soft-idle-stop sessionId=${e.sessionId} idleMs=${c} offset=${a} promptDone=${!!e.promptDone}`),this.writeObs({component:"bridge-core",domain:"lifecycle",name:"session.load.replay_softidle_stop",severity:"info",payload:{sessionId:e.sessionId,idleMs:c,offset:a,promptDone:!!e.promptDone}});break}this.logger.debug?.(`[bridge-core] replayCurrentAssistantStream soft-idle-continue sessionId=${e.sessionId} idleMs=${c} offset=${a}`),this.writeObs({component:"bridge-core",domain:"lifecycle",name:"session.load.replay_softidle_continue",severity:"debug",payload:{sessionId:e.sessionId,idleMs:c,offset:a}})}await new Promise(e=>{const t=setTimeout(e,200);"object"==typeof t&&"unref"in t&&t.unref()})}d.skipped>0&&this.logger.debug?.(`[bridge-core] replayCurrentAssistantStream skipped ${d.skipped} duplicate tool events (already in history)`),(d.sent>0||d.skipped>0)&&this.writeObs({component:"bridge-core",domain:"lifecycle",name:"session.load.replay_complete",severity:"debug",payload:{sessionId:e.sessionId,replayed:d.sent,skipped:d.skipped}})}async flushMqItems(e,t,s,i,n,o,r){const a=r??{sent:0,skipped:0,cumulativeText:"",cumulativeReasoning:""};let l=0;for(const s of t)if(l++,!i?.size||"tool_call"!==s.sessionUpdate&&"tool_call_update"!==s.sessionUpdate||!i.has(s.toolCallId)){if(n.length>0&&"agent_message_chunk"===s.sessionUpdate){const e="text"===s.content.type?s.content.text:void 0;if("string"==typeof e&&(a.cumulativeText+=e,a.cumulativeText.length<=n.length)){a.skipped++;continue}}if(o.length>0&&"agent_thought_chunk"===s.sessionUpdate){const e="text"===s.content.type?s.content.text:void 0;if("string"==typeof e&&(a.cumulativeReasoning+=e,a.cumulativeReasoning.length<=o.length)){a.skipped++;continue}}this.transport.sendSessionUpdate(e.sessionId,s),a.sent++}else a.skipped++;return{total:l}}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,i=s.sessionKey??s.key??s.id??s.name;if(!i||"string"!=typeof i)continue;if(isBackgroundSessionKey(i))continue;if(this.cronIsolatedSessionKeys.has(i))continue;const n=deriveSessionId(i,this.instanceId),o=t.find(e=>e.sessionId===i||e.sessionId===n||this.state.sessions.get(e.sessionId)?.gatewaySessionKey===i),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:i,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(i),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));try{const e=t.map(e=>{const t=this.state.sessions.get(e.sessionId);return{sid:e.sessionId.slice(0,12),title:(e.title||"").slice(0,24),titleSource:t?.titleSource??"(none)",hasActivity:!!t?.lastStreamActivityTs,createdAt:t?.createdAt,updatedAt:e.updatedAt,gwKey:t?.gatewaySessionKey?.slice(0,40)}});this.logger.info?.(`[new-chat-stampede] session/list n=${t.length} total_state=${this.state.sessions.size} entries=${JSON.stringify(e)}`)}catch{}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 i=s.slice(0,64),n=this.state.sessions.get(t);if(!n)return void this.transport.sendAcpError(e.id,Errors.SessionNotFound);n.title=i,n.titleSource="manual";const o=n.gatewaySessionKey,r=this.getGateway();r?.isConnected&&r.sessionsPatch(o,{label:i}).catch(e=>{this.logger.debug?.(`[bridge-core] sessionsPatch (rename) failed: ${e instanceof Error?e.message:e}`)}),this.transport.sendResult(e.id,{sessionId:t,title:i})}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,i){if(this.isGuardMessage(s))return void this.logger.info?.(`[bridge-core] title-gen SKIP guard message sid=${t}`);const n=this.matchTitleTemplate(s);if(n){e.title=n,e.titleSource="template";const s=this.getGateway();return s?.isConnected&&s.sessionsPatch(e.gatewaySessionKey,{label:n}).catch(()=>{}),void this.transport.sendSessionUpdate(t,{sessionUpdate:"title_update",title:n})}const 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(i)}`;this.logger.info?.(`[bridge-core] title-gen CALLING LLM sid=${t} q="${s.slice(0,60)}" aLen=${i.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 i=await s.json(),n=i.choices?.[0]?.message?.content?.trim();if(!n)return;const o=n.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 i=this.getGateway();if(!i?.isConnected)return;let n=s;if(!n)try{const t=await loadHistory(i,e.gatewaySessionKey);n=groupIntoTurns(t)}catch(e){return void this.logger.debug?.(`[bridge-core] title-gen loadHistory failed sid=${t}: ${e instanceof Error?e.message:e}`)}const o=n.find(e=>{if("user"!==e.role)return!1;if(!e.content?.trim())return!1;if("internal_system"===e.provenance?.kind)return!1;if(isCronPromptText(e.content))return!1;const t=stripTransportMetadata(e.content).trim();return!!t&&!/^Sender\s*\(untrusted/i.test(t)});if(!o)return;const r=n.indexOf(o),a=n.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 i=s.gatewaySessionKey;this.logger.info?.(`[bridge-core] session/delete sessionId=${t} gatewayKey=${i} gwConnected=${!!this.getGateway()?.isConnected}`);let n=!1;const o=this.getGateway();if(o?.isConnected&&i)try{await o.sessionsDelete(i),n=!0,this.logger.info?.(`[bridge-core] Gateway sessions.delete SUCCESS for key=${i}`)}catch(t){const s=t instanceof Error?t.message:String(t);if(this.logger.info?.(`[bridge-core] Gateway sessions.delete FAILED for key=${i}: ${s}`),!s.includes("Cannot delete the main session"))return void this.transport.sendResult(e.id,{deleted:!1});try{await o.sessionsReset(i),n=!0,this.logger.info?.(`[bridge-core] Gateway sessions.reset SUCCESS for key=${i}`)}catch(t){return this.logger.warn?.(`[bridge-core] Gateway sessions.reset also failed for key=${i}: ${t instanceof Error?t.message:t}`),void this.transport.sendResult(e.id,{deleted:!1})}}else i&&this.logger.warn?.(`[bridge-core] Gateway not connected, proceeding with local-only delete for key=${i}`);void 0!==s.pendingPromptId&&this.failPrompt(s,Errors.SessionDeleted.rpcCode,Errors.SessionDeleted.message),this.state.clearPromptTimeout(s),this.state.clearStreamIdleTimer(s),this.clearAssistantMqCloseTimer(s),s.assistantMq?.close(),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(i),this.transport.resetSessionUpdateCount(t),n&&this.onSessionDeleted?.(i),this.logger.info?.(`[bridge-core] session/delete DONE sessionId=${t} gatewayKey=${i} deleted=true`),this.transport.sendResult(e.id,{deleted:!0})}async handleSessionClear(e){this.logger.info?.(`[bridge-core] handleSessionClear called, params=${JSON.stringify(e.params)}`);const t=e.params?.sessionId;if(!t)return this.logger.warn?.("[bridge-core] session/clear missing sessionId"),void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const s=this.state.sessions.get(t);if(!s)return this.logger.warn?.(`[bridge-core] session/clear sessionId=${t} not found in state`),void this.transport.sendAcpError(e.id,Errors.SessionNotFound);this.logger.info?.(`[bridge-core] session/clear sessionId=${t} gatewayKey=${s.gatewaySessionKey}`);const i=this.getGateway(),n=i?.isConnected;if(s.promptDone||void 0===s.pendingPromptId&&void 0===s.currentRunId||(this.logger.info?.(`[bridge-core] session/clear: cancelling active run sid=${t} runId=${s.currentRunId}`),n&&(s.currentRunId||s.gatewayRequestId)&&i.agentCancel(s.gatewaySessionKey,{runId:s.currentRunId,requestId:s.gatewayRequestId}),this.endRun(s,{kind:"complete",stopReason:"cancelled"})),n&&s.gatewaySessionKey)try{await i.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=${n}, 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,i=t?this.state.sessions.get(t):void 0,n=this.getGateway();if(i&&n?.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 n.sessionsPatch(i.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,i=t?this.state.sessions.get(t):void 0,n=this.getGateway();let o=s??null,r=null;if(i&&n?.isConnected&&s)try{const e=await n.sessionsPatch(i.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})),i=this.getSkillsDir();for(const e of s){const t=e.skillKey??e.name;try{const s=await readFile(join(i,t,".beeos-meta.json"),"utf8"),n=JSON.parse(s);n?.iconUrl&&(e.iconUrl=n.iconUrl)}catch{}}return 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,i=t?.files;let n;try{n=validateSkillSlug(t?.slug||t?.name||"")}catch{return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Invalid or missing skill slug"})}if(!i?.length&&!s)return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Missing skill files or zipUrl"});const o=resolveSkillInstallDir(this.getSkillsDir(),n);try{if(await mkdir(o,{recursive:!0}),s){const e=await fetchWithRetry(s,{maxRetries:4,logger:this.logger});await extractZipToDir(e,o)}else if(i?.length){const e=resolve(o);for(const t of i){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 i=await fetch(t.downloadUrl,{signal:AbortSignal.timeout(12e4)});if(!i.ok)throw new Error(`Failed to download ${t.path}: ${i.status}`);const n=Buffer.from(await i.arrayBuffer());await writeFile(s,n)}}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 "${n}" via ${s?"zip":"files"}`),this.transport.sendResult(e.id,{success:!0}),this.onSkillInstalled?.(n,o),await this.pushSkillsList()}catch(t){this.logger.error?.(`[bridge-core] Failed to install skill "${n}": ${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 i=resolveSkillInstallDir(this.getSkillsDir(),s),n=resolveSkillInstallDir(join(homedir(),".agents","skills"),s);try{let t=!1;try{const e=await lstat(i);if(e.isSymbolicLink()){const e=await readlink(i);await rm(i,{force:!0}),await rm(e,{recursive:!0,force:!0}),t=!0}else e.isDirectory()&&(await rm(i,{recursive:!0,force:!0}),t=!0)}catch{}try{const e=await lstat(n);(e.isDirectory()||e.isSymbolicLink())&&(await rm(n,{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,i=t?.enabled;if(!s||"boolean"!=typeof i)return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Missing skillKey or enabled"});const n=this.getGateway();if(n?.isConnected)try{const t=await n.skillsUpdate(s,i);this.logger.info?.(`[bridge-core] Updated skill "${s}" enabled=${i}`),this.transport.sendResult(e.id,{ok:t?.ok??!0,skillKey:s,enabled:i}),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:i,created:n}=await this.resolveOrCreateSession(t);n&&this.onSessionLoaded?.(i.sessionId,i.gatewaySessionKey,i.platformAgentId);const o=i.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(i);let a=extractPromptBlocks(sanitizePromptPayload(s));if(!i.title||isPlaceholderTitle(i.title)){const e=a.find(e=>"text"===e.type&&e.text);if(e&&"text"in e&&e.text){const t=stripTransportMetadata(e.text).trim();if(this.logger.info?.(`[bridge-core] title-gen sid=${o} existing="${i.title}" cleanText="${t.slice(0,80)}" isPlaceholder=${isPlaceholderTitle(t)}`),t&&!isPlaceholderTitle(t)){const e=t.slice(0,64).replace(/\n/g," ").trim();i.title=e,i.titleSource="truncated",r?.isConnected&&e&&r.sessionsPatch(i.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:m,attachments:g}=c,h=resolveStandaloneSlashCommandName(a,m)??resolveSlashCmd(a,m),p="string"==typeof h;if(h&&this.handleSlashCommand){const t=this;if(await(async()=>{try{return await t.handleSlashCommand(h)}catch(e){return t.logger.warn?.(`[bridge-core] /${h} handler failed: ${e instanceof Error?e.message:e}`),!1}})())return this.emitPromptAsUserSessionUpdates(i.sessionId,a,resolveTurnId(i)),this.transport.sendSessionUpdate(o,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Loading ${h}...`},timestamp:(new Date).toISOString()},{turnId:resolveTurnId(i)}),void this.transport.sendResult(e.id,{stopReason:"end_turn"})}const u="chat.send";let y=p?m:withUserMessagePrefix(m);const f=this.config.canvasEnabled&&!p&&!1!==i.canvasActive&&!i.channelType;if(f){const e=i.promptsSinceCanvasInjection??0;!i.canvasPromptInjected||e>=10?(y=`${CANVAS_TERM_MAPPING}\n\n${y}`,i.canvasPromptInjected=!0,i.promptsSinceCanvasInjection=0,this.logger.debug?.("[bridge-core] Canvas term mapping injected (re-inject cycle)")):i.promptsSinceCanvasInjection=e+1}if(f){const e=this.getCanvasState?.();if(e){const t=e.resolveCanvasForSession(i.gatewaySessionKey);y=`${buildActiveSurfacesContext(e,t)??"[Canvas] Canvas panel is available. Use render_ui for structured/visual content."}\n\n${y}`}const t=i.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}`,i.referencedSurfaceId=void 0)}if(!p){const t=parseMentionsParam(e.params?.mentions);if(t.length>0){i.activeMentions=t;y=`${buildMentionInstruction(t)}\n${y}`,this.logger.debug?.(`[bridge-core] A2A mention instruction injected for ${t.length} agent(s)`)}else i.activeMentions=void 0}p&&this.logger.info?.(`[bridge-core] slash command passthrough sessionId=${o} command=/${h}`),i.promptDone||void 0===i.pendingPromptId&&void 0===i.currentRunId||(this.logger.warn?.(`[bridge-core] handleSessionPrompt: force-ending stale run sid=${o} oldRunId=${i.currentRunId} oldPromptId=${i.pendingPromptId}`),(i.currentRunId||i.gatewayRequestId)&&r.agentCancel(i.gatewaySessionKey,{runId:i.currentRunId,requestId:i.gatewayRequestId}),this.endRun(i,{kind:"complete",stopReason:"cancelled"})),this.state.resetForNewRun(i,o,this.transport),i.pendingPromptId=e.id,i.gatewayMethod=u;const I=resolveTurnId(i);this.emitPromptAsUserSessionUpdates(o,a,I),this.transport.sendSessionUpdate(o,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:""},timestamp:(new Date).toISOString()},I?{turnId:I}:void 0),this.schedulePromptTimeout(i);const S=g.length>0?g.map(e=>({type:e.type,content:e.content,...e.mimeType?{mimeType:e.mimeType}:{},...e.fileName?{fileName:e.fileName}:{}})):void 0,w=`req_${randomUUID().replace(/-/g,"")}`,b={sessionKey:i.gatewaySessionKey,message:y,deliver:!1,idempotencyKey:randomUUID()};S?.length&&(b.attachments=S);if(!r.sendFrame({type:"req",id:w,method:u,params:b}))return this.state.clearPromptTimeout(i),i.pendingPromptId=void 0,this.clearAssistantMqCloseTimer(i),i.assistantMq?.close(),void this.transport.sendAcpError(e.id,Errors.SendFailed,{message:"failed to send prompt to gateway"});i.gatewayRequestId=w,this.state.promptsByGatewayRequestId.set(w,i)}replayUserTurnAsChunks(e,t,s,i,n,o,r){const a=splitUserReplayBlocks(t),l=n||o||void 0!==r?{...n?{turnId:n}:{},...o?{messageId:o}:{},...void 0!==r?{seq:r}:{}}:void 0;for(const t of a){let n;if("text"===t.type){if(!t.text)continue;n={type:"text",text:t.text}}else n="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:n,...s?{metadata:s}:{},...i?{timestamp:i}:{}},l)}}async replayAssistantTurnAsStream(e,t,s){const i=(e,t)=>{if(s||e||void 0!==t)return{...s?{turnId:s}:{},...e?{messageId:e}:{},...void 0!==t?{seq:t}:{}}},n=i(t.messageId,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,n)}for(const s of t.sourceMessages){const n=s.updateType??"agent_message_chunk",o=i(s.messageId,s._seq);switch(n){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 i=s.toolCallId??"",n=t.toolCalls?.find(e=>e.id===i),r=s.toolName??"tool",a=s.content??"";let l={};if(a)try{l=JSON.parse(a)}catch{}this.transport.sendSessionUpdate(e,buildToolCallPayload({toolCallId:i,toolName:r,args:l,kind:n?.kind,status:n?.status??"in_progress",timestamp:s.timestamp}),o);break}case"tool_call_update":{const i=s.toolCallId??"",n=t.toolCalls?.find(e=>e.id===i),r=s.toolName??n?.name??"tool",a=s.content??n?.output??"";let l=await readEnrichmentCache(i).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(i).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:i,toolName:r,outputText:a,kind:n?.kind,status:n?.status??"completed",resourceLinks:l,timestamp:s.timestamp}),o);break}}}}emitPromptAsUserSessionUpdates(e,t,s){const i=(new Date).toISOString(),n=s?{turnId:s}:void 0;for(const s of t){const t=this.toUserSessionUpdateContent(s);t&&this.transport.sendSessionUpdate(e,{sessionUpdate:"user_message_chunk",content:t,timestamp:i},n)}}toUserSessionUpdateContent(e){if("text"===e.type){if(!e.text)return;return{type:"text",text:e.text}}if("image"===e.type){const t=e.mimeType??e.mime_type??"application/octet-stream",s=e.fileName??e.file_name??e.name;if(!e.data&&!e.uri)return;return{type:"image",...e.data?{data:e.data}:{},...e.uri?{uri:e.uri}:{},...t?{mimeType:t}:{},...s?{fileName:s}:{}}}if("resource_link"===e.type){if(!e.uri)return;return{type:"resource_link",uri:e.uri,...e.title?{title:e.title}:{},...e.name?{name:e.name}:{},...e.mimeType??e.mime_type?{mimeType:e.mimeType??e.mime_type}:{}}}if("file"===e.type){const t=e.mimeType??e.mime_type??"application/octet-stream",s=e.fileName??e.file_name??e.filename??e.name;if(!e.data&&!e.text&&!e.uri)return;return{type:"file",...e.data?{data:e.data}:{},...e.text?{text:e.text}:{},...e.uri?{uri:e.uri}:{},...t?{mimeType:t}:{},...s?{fileName:s}:{}}}if("resource"===e.type){const t=e.resource??{},s=t.uri??e.uri,i=t.mimeType??t.mime_type??e.mimeType??e.mime_type,n=t.text??e.text,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&&!n&&!o)return;return{type:"resource",resource:{...s?{uri:s}:{},...i?{mimeType:i}:{},...n?{text:n}:{},...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 i=this.state.sessions.get(s);if(!i)return void(void 0!==e&&this.transport.sendAcpError(e,Errors.SessionNotFound));const n=this.getGateway(),o=n?.isConnected,r=!(!i.currentRunId&&!i.gatewayRequestId);if(o&&r){n.agentCancel(i.gatewaySessionKey,{runId:i.currentRunId,requestId:i.gatewayRequestId})}this.endRun(i,{kind:"complete",stopReason:"cancelled"})||this.transport.sendSessionUpdate(i.sessionId,{sessionUpdate:"stream_complete",stopReason:"cancelled"},{turnId:resolveTurnId(i)}),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),i=s?{turnId:s}:void 0;e.promptDone=!0;const n=e.currentRunId;if("complete"===t.kind){if(n&&this.onRunComplete){const t=e.agentAssistantTextSoFar??e.chatAssistantTextSoFar??"";this.onRunComplete(n,t)}void 0!==e.pendingPromptId&&this.transport.sendResult(e.pendingPromptId,{stopReason:t.stopReason}),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:t.stopReason},i),this.tryGenerateTitleFromHistory(e,e.sessionId)}else n&&this.onRunFailed&&this.onRunFailed(n,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},i);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);const s=e.currentRunId;e.pendingPromptId=void 0,e.promptDone=void 0,e.currentRunId=void 0,e.gatewayRequestId=void 0,e.assistantStreamStartedAt=void 0,e.gatewayMethod=void 0,this.armAssistantMqLateClose(e,s)}armAssistantMqLateClose(e,t){if(!e.assistantMq||e.assistantMq.closed)return;this.clearAssistantMqCloseTimer(e),e.assistantMqAwaitingRunId=t,e.assistantMqArmedAt=Date.now();const s=DEFAULT_ASSISTANTMQ_LATECLOSE_TIMEOUT_MS;this.writeObs({component:"bridge-core",domain:"lifecycle",name:"assistantMq.lateclose.armed",severity:"debug",payload:{sessionId:e.sessionId,runId:t,timeoutMs:s}}),e.assistantMqCloseTimer=setTimeout(()=>{e.assistantMq&&!e.assistantMq.closed&&(this.logger.warn?.(`[bridge-core] assistantMq late-close timeout sessionId=${e.sessionId} runId=${t??"n/a"} timeoutMs=${s}`),this.writeObs({component:"bridge-core",domain:"lifecycle",name:"assistantMq.lateclose.timeout",severity:"warn",payload:{sessionId:e.sessionId,runId:t,timeoutMs:s}}),e.assistantMq.close()),e.assistantMqCloseTimer=void 0,e.assistantMqAwaitingRunId=void 0,e.assistantMqArmedAt=void 0},s),"object"==typeof e.assistantMqCloseTimer&&"unref"in e.assistantMqCloseTimer&&e.assistantMqCloseTimer.unref()}clearAssistantMqCloseTimer(e){e.assistantMqCloseTimer&&(clearTimeout(e.assistantMqCloseTimer),e.assistantMqCloseTimer=void 0),e.assistantMqAwaitingRunId=void 0,e.assistantMqArmedAt=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 i=e.error,n=i?.message??"gateway returned error";return this.logger.warn?.(`[bridge-core] handleGatewayResponse: gateway rejected prompt gatewayRequestId=${t} error=${n}`),void this.failPrompt(s,Errors.SendFailed.rpcCode,n)}const i=e.payload,n=i?.runId;n?(s.currentRunId=n,s.assistantStreamStartedAt=Date.now(),this.state.promptsByRunId.set(n,s),this.logger.debug?.(`[bridge-core] handleGatewayResponse: bound runId=${n} gatewayRequestId=${t} sessionId=${s.sessionId}`)):this.logger.debug?.(`[bridge-core] handleGatewayResponse: no runId in payload gatewayRequestId=${t} sessionId=${s.sessionId}`)}maybeCompletePromptFromChatState(e,t){if(e.promptDone||"chat.send"!==e.gatewayMethod)return;const s="string"==typeof t.state?t.state.toLowerCase():void 0;if(s)if("final"===s)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,i){if(0===s.length)return;const n=i?this.state.promptsByRunId.get(i):void 0;if(!n)return void this.logger.warn?.(`[bridge-core] pushToolResultContent dropped — no session for runId=${i??"(none)"}`);const o=n.sessionId,r=(new Date).toISOString(),a={turnId:resolveTurnId(n)};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),n.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("/",".");try{const i=await t.request(s,e.params??{});this.transport.sendResult(e.id,i??{}),"cron.add"!==s&&"cron.update"!==s&&"cron.remove"!==s||this.refreshCronIsolatedSessionKeys()}catch(t){const i=t instanceof Error?t.message:"cron request failed";this.logger.warn?.(`[bridge-core] ${s} failed: ${i}`),this.transport.sendAcpError(e.id,Errors.SendFailed,{message:i})}}async refreshCronIsolatedSessionKeys(){const e=this.getGateway();if(e?.isConnected)try{const t=await e.request("cron.list",{}),s=t?.jobs;if(!Array.isArray(s))return;const i=new Set;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&&i.add(s)}this.cronIsolatedSessionKeys=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 i;for(let n=0;n<=s;n++){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**n);if(i=new Error(`HTTP ${o.status} from ${e}`),n<s){t.logger?.info?.(`[bridge-core] Download ${o.status}, retry ${n+1}/${s} in ${(a/1e3).toFixed(0)}s`),await new Promise(e=>setTimeout(e,a));continue}}throw new Error(`Failed to download zip: ${o.status}`)}throw i??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),i=join(t,".beeos-extract-tmp-"+Date.now());try{await mkdir(i,{recursive:!0}),s.extractAllTo(i,!0);const e=await resolveSkillRoot(i),n=await readdir(e,{withFileTypes:!0});let o=0;for(const s of n){if(s.name.startsWith(".beeos-extract-tmp")||"__MACOSX"===s.name)continue;const i=join(e,s.name),n=join(t,s.name);await rename(i,n).catch(async()=>{await cp(i,n,{recursive:!0})}),o++}if(0===o)throw new Error("Zip archive contained no extractable files")}finally{await rm(i,{recursive:!0,force:!0}).catch(()=>{})}}const VALID_SLUG_PATTERN=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,NON_ASCII_PATTERN=/[^\x00-\x7F]/;function validateSkillSlug(e){const t=e.trim();if(!t||t.includes("/")||t.includes("\\")||t.includes(".."))throw new Error(`Invalid skill slug: ${e}`);if(NON_ASCII_PATTERN.test(t)||!VALID_SLUG_PATTERN.test(t))throw new Error(`Invalid skill slug: ${e}`);return t}function safeDirName(e){const t=e.trim();return t?t.replaceAll("/","__").replaceAll("\\","__"):t}function resolveSkillInstallDir(e,t){const s=safeDirName(t),i=join(e,s),n=resolve(e),o=resolve(i),r=relative(n,o);if(!r||".."===r||r.startsWith(`..${sep}`)||path.isAbsolute(r))throw new Error("Invalid skill target path");return i}
@@ -0,0 +1 @@
1
+ const MAX_CONTENT_LEN=400,HTML_BODY_RE=/<\s*(?:html|!doctype|body|head|h1)\b/i,HTTP_STATUS_PREFIX_RE=/^\s*(\d{3})\b/,RATE_LIMIT_RE=/(\brate[_ -]?limit|\btoo[_ -]?many[_ -]?requests\b|\b429\b)/i,TIMEOUT_RE=/\b(timeout|timed[_ -]?out|504|gateway[_ -]?timeout)\b/i;function extractStatus(t){const r=HTTP_STATUS_PREFIX_RE.exec(t);return r?Number(r[1]):void 0}function clamp(t){const r=t.trim();return r.length<=400?r:`${r.slice(0,400)}…`}const parseStructuredJson=({raw:t})=>{const r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let e;try{e=JSON.parse(r)}catch{return null}if(!e||"object"!=typeof e)return null;const n=e,o=n.error&&"object"==typeof n.error?n.error:n,a="string"==typeof o.message?o.message:"string"==typeof o.detail?o.detail:"string"==typeof o.error?o.error:void 0;if(!a)return null;const s="string"==typeof o.code?o.code:"string"==typeof o.type?o.type:void 0,u="number"==typeof o.status?o.status:"number"==typeof o.httpStatus?o.httpStatus:void 0;return{content:clamp(`${s?`${s}: `:""}${a}`),category:"structured",httpStatus:u}},parseHtmlErrorPage=({raw:t})=>{if(!HTML_BODY_RE.test(t))return null;const r=extractStatus(t);return{content:r?`The provider returned an HTTP ${r} error page (likely a gateway/CDN failure). Retry in a moment.`:"The provider returned an HTML error page instead of an API response. Retry in a moment.",category:"gateway",httpStatus:r}},parseRateLimit=({raw:t})=>{if(!RATE_LIMIT_RE.test(t))return null;const r=extractStatus(t);return{content:clamp(t),category:"rate_limit",httpStatus:r}},parseTimeout=({raw:t})=>{if(!TIMEOUT_RE.test(t))return null;const r=extractStatus(t);return{content:clamp(t),category:"timeout",httpStatus:r}},fallback=({raw:t})=>{const r=extractStatus(t),e=t.trim();return e?{content:clamp(e),category:"unknown",httpStatus:r}:{content:r?`The provider returned HTTP ${r}.`:"The provider returned an error.",category:"unknown",httpStatus:r}},STRATEGIES=[parseStructuredJson,parseHtmlErrorPage,parseRateLimit,parseTimeout,fallback];export function formatProviderError(t){for(const r of STRATEGIES){const e=r(t);if(e)return e}return{content:"The provider returned an error.",category:"unknown"}}
@@ -0,0 +1 @@
1
+ import{describe,expect,it}from"vitest";import{formatProviderError}from"./error-message-formatter.js";describe("formatProviderError",()=>{describe("HTML error pages (gateway category)",()=>{it("summarises Cloudflare 502 HTML with extracted status",()=>{const t=formatProviderError({raw:"502 <!DOCTYPE html><html><head><title>Bad gateway</title></head><body><h1>Bad gateway</h1></body></html>"});expect(t.category).toBe("gateway"),expect(t.httpStatus).toBe(502),expect(t.content).toContain("HTTP 502"),expect(t.content).not.toContain("<!DOCTYPE"),expect(t.content).not.toContain("<html"),expect(t.content).not.toContain("ACP error")}),it("handles HTML without a leading status code",()=>{const t=formatProviderError({raw:"<html><body>Service Unavailable</body></html>"});expect(t.category).toBe("gateway"),expect(t.httpStatus).toBeUndefined(),expect(t.content).not.toContain("<"),expect(t.content).not.toContain("ACP error")}),it("matches nginx-style bare <h1> pages",()=>{const t=formatProviderError({raw:"503 <h1>Service Unavailable</h1>"});expect(t.category).toBe("gateway"),expect(t.httpStatus).toBe(503),expect(t.content).not.toContain("ACP error")})}),describe("structured JSON envelopes",()=>{it("parses OpenAI-style {error:{message,code}}",()=>{const t=JSON.stringify({error:{message:"The model has been deprecated.",code:"model_not_found",type:"invalid_request_error"}}),e=formatProviderError({raw:t});expect(e.category).toBe("structured"),expect(e.content).toContain("model_not_found"),expect(e.content).toContain("deprecated")}),it("parses bare {message,code} envelopes",()=>{const t=JSON.stringify({message:"quota exceeded",code:"quota"}),e=formatProviderError({raw:t});expect(e.category).toBe("structured"),expect(e.content).toContain("quota")}),it("extracts httpStatus when JSON includes it",()=>{const t=JSON.stringify({error:{message:"context too long",code:"context_length",status:400}}),e=formatProviderError({raw:t});expect(e.httpStatus).toBe(400)}),it("falls through to plain-text when JSON has no recognisable fields",()=>{const t=JSON.stringify({foo:"bar"}),e=formatProviderError({raw:t});expect(e.category).toBe("unknown")}),it("falls through to plain-text when JSON is malformed",()=>{const t=formatProviderError({raw:"{malformed json"});expect(t.category).toBe("unknown"),expect(t.content).toBe("{malformed json")})}),describe("rate limit",()=>{it("recognises '429 too many requests'",()=>{const t=formatProviderError({raw:"429 Too Many Requests"});expect(t.category).toBe("rate_limit"),expect(t.httpStatus).toBe(429)}),it("recognises 'rate_limit_exceeded' without status prefix",()=>{const t=formatProviderError({raw:"rate_limit_exceeded: slow down"});expect(t.category).toBe("rate_limit"),expect(t.httpStatus).toBeUndefined()}),it("HTML takes precedence over rate-limit keyword",()=>{const t=formatProviderError({raw:"429 <html><body>rate limit</body></html>"});expect(t.category).toBe("gateway")})}),describe("timeout",()=>{it("recognises 'gateway timeout'",()=>{const t=formatProviderError({raw:"504 gateway timeout"});expect(t.category).toBe("timeout"),expect(t.httpStatus).toBe(504)}),it("recognises 'request timed out'",()=>{const t=formatProviderError({raw:"request timed out after 30s"});expect(t.category).toBe("timeout")})}),describe("plain-text fallback",()=>{it("returns content verbatim for short messages",()=>{const t=formatProviderError({raw:"something went wrong"});expect(t.category).toBe("unknown"),expect(t.content).toBe("something went wrong")}),it("clamps oversized messages with ellipsis",()=>{const t="x".repeat(2e3),e=formatProviderError({raw:t});expect(e.content.length).toBeLessThan(t.length),expect(e.content.endsWith("…")).toBe(!0)}),it("handles an empty raw string with a generic default",()=>{const t=formatProviderError({raw:""});expect(t.category).toBe("unknown"),expect(t.content).toMatch(/provider returned an error/i)}),it("handles a bare status code with no body",()=>{const t=formatProviderError({raw:"500"});expect(t.httpStatus).toBe(500),expect(t.content).toContain("500")})}),describe("stopReason passthrough",()=>{it("ignores stopReason (reserved for future use) but does not crash",()=>{const t=formatProviderError({raw:"x",stopReason:"refusal"});expect(t.content).toBe("x")})})});
@@ -0,0 +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),s=vi.fn().mockReturnValue(!0),n={sendSessionUpdate:s,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();return{events:new AcpGatewayEvents({state:t,transport:n,config:{gateway:{agentId:"main"}},logger:e,writeObs:vi.fn(),completePrompt:a,failPrompt:o,maybeCompletePromptFromChatState:i,onStreamDelta:r}),state:t,transport:n,sendSessionUpdate:s,onStreamDelta:r,logger:e}}function makeSession(e,t){const s={sessionId:"s1",gatewaySessionKey:"main/s1",agentId:"main",currentRunId:t,pendingPromptId:1,promptDone:!1,createdAt:Date.now(),chatReplayDedupKeys:new Set};return e.sessions.set(s.sessionId,s),e.promptsByRunId.set(t,s),s}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 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 heartbeat ack across split deltas ("HEART" + "BEAT_OK")',()=>{const t={stream:"assistant",runId:"run-heartbeat-1",sessionKey:"main/s1",seq:1,ts:Date.now(),data:{delta:"HEART"}},s={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(s);const n=e.sendSessionUpdate.mock.calls.map(e=>e[1]).filter(e=>"agent_message_chunk"===e.sessionUpdate).map(e=>e.content?.text).filter(Boolean);expect(n).not.toContain("BEAT_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 s=e.sendSessionUpdate.mock.calls.map(e=>e[1]).filter(e=>"agent_message_chunk"===e.sessionUpdate);expect(s).toHaveLength(1),expect(s[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 s=e.sendSessionUpdate.mock.calls.map(e=>e[1]).filter(e=>"agent_message_chunk"===e.sessionUpdate);expect(s).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 s=e.sendSessionUpdate.mock.calls.map(e=>e[1]).filter(e=>"agent_message_chunk"===e.sessionUpdate);expect(s).toHaveLength(1)})});
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";import{Errors}from"../errors/index.js";import{formatFriendlyError}from"../errors/classify.js";import{stripTransportMetadata,normalizeTransportText}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";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 o=roleFromSessionUpdate(e);o&&(t.lastTurnIdByRole||(t.lastTurnIdByRole={}),t.lastTurnIdByRole[o]=s)}export class AcpGatewayEvents{state;transport;config;logger;writeObs;completePrompt;failPrompt;maybeCompletePromptFromChatState;agentFetchFn;onStreamDelta;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}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),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 o=asString(e.toolCallId)??asString(e.tool_call_id)??asString(e.callId)??asString(e.id);if(o){const e=this.state.toolCallIdMap.get(o);return e?(t.sessionId&&this.state.toolCallToSessionMap.set(e,t.sessionId),e):(this.state.toolCallIdMap.set(o,o),t.sessionId&&this.state.toolCallToSessionMap.set(o,t.sessionId),o)}const n=`tc_${t.currentRunId??"unknown"}_${this.state.nextToolCallSeq++}`;return t.sessionId&&this.state.toolCallToSessionMap.set(n,t.sessionId),n}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 o of s.content){const n=o;if(!isRecord(n))continue;const a=asString(n.type);if(!a)continue;const r=toISO(s.timestamp);if("thinking"===a){if(e.hasAgentThinkingStream)continue;const t=normalizeText(n.thinking)??normalizeText(n.text);if(!t)continue;const s=dedupKey("chat:thinking",t);if(e.chatReplayDedupKeys.has(s))continue;e.chatReplayDedupKeys.add(s);const o={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:t},...r?{timestamp:r}:{}};this.sendTurnUpdate(e,o)&&(e.assistantMq?.push(o),this.onStreamDelta?.(e,o));continue}if("toolCall"===a){if(this.sendToolCallSpacer(e,r),e.hasAgentToolStartStream)continue;const t=this.resolveToolCallId(e,n,"start"),s=asString(n.name)??asString(n.toolName)??asString(n.tool_name)??"tool",o=resolveToolArgs(n),a=dedupKey("chat:tool_start",t,JSON.stringify(o));if(e.chatReplayDedupKeys.has(a))continue;e.chatReplayDedupKeys.add(a);const i=buildToolCallPayload({toolCallId:t,toolName:s,args:o,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,n,"result"),s=asString(n.name)??asString(n.toolName)??asString(n.tool_name)??"tool",o=n.result,a=normalizeText(n.text)??normalizeText(n.result)??(isRecord(o)||Array.isArray(o)?JSON.stringify(o,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:o,resourceLinks:extractResourceLinksFromRawResult(o),timestamp:r});this.sendTurnUpdate(e,l)&&(e.assistantMq?.push(l),this.onStreamDelta?.(e,l));continue}if("text"===a&&n.text){if(e.hasAgentAssistantStream||e.agentAssistantTextSoFar)continue;const s=stripTransportMetadata(n.text);if(!s)continue;const o=dedupKey("chat:text",s);if(e.chatReplayDedupKeys.has(o))continue;e.chatReplayDedupKeys.add(o);const a=e.chatAssistantTextSoFar??"";let i;if(e.chatAssistantTextSoFar=s,s.startsWith(a))i=s.slice(a.length);else{if(a.startsWith(s))continue;i=s}if(!i)continue;this.logger.debug?.(`[gateway-events] chat.text delta seq=${t.seq} runId=${t.runId} len=${i.length} prevLen=${a.length}`);const l={sessionUpdate:"agent_message_chunk",content:{type:"text",text:i},...r?{timestamp:r}:{}};this.sendTurnUpdate(e,l),e.assistantMq?.push(l),this.onStreamDelta?.(e,l)}}}}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),o=t=>{this.sendTurnUpdate(e,t),e.assistantMq?.push(t),this.onStreamDelta?.(e,t)};if("assistant"===t.stream){e.hasAgentAssistantStream=!0;const n=this.state.extractAgentAssistantDelta(e,t.data??{});if(n){const e=normalizeTransportText(n);e&&(this.logger.debug?.(`[gateway-events] agent.assistant delta seq=${t.seq} runId=${t.runId} len=${e.length} source=${t.data?.delta?"delta":"cumulative"}`),o({sessionUpdate:"agent_message_chunk",content:{type:"text",text:e},...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 n=asString(t.type);if("thinking"===n){e.hasAgentThinkingStream=!0;const o=normalizeText(t.thinking)??normalizeText(t.text);if(o){const t={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:o},...s?{timestamp:s}:{}};this.sendTurnUpdate(e,t)&&(e.assistantMq?.push(t),this.onStreamDelta?.(e,t))}continue}if("toolCall"===n){this.sendToolCallSpacer(e,s),e.hasAgentToolStartStream=!0;const n=this.resolveToolCallId(e,t,"start"),a=asString(t.name)??asString(t.toolName)??asString(t.tool_name)??"tool",r=resolveToolArgs(t);o(buildToolCallPayload({toolCallId:n,toolName:a,args:r,timestamp:s}));continue}if("toolResult"===n){this.sendToolCallSpacer(e,s),e.hasAgentToolResultStream=!0;const n=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&&o(buildToolCallUpdatePayload({toolCallId:n,toolName:a,outputText:i,rawOutput:r,resourceLinks:extractResourceLinksFromRawResult(r),timestamp:s}));continue}}}else if("thinking"===t.stream){e.hasAgentThinkingStream=!0;const o=normalizeText(t.data?.delta)??normalizeText(t.data?.text);if(o){const t={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:o},...s?{timestamp:s}:{}};this.sendTurnUpdate(e,t)&&(e.assistantMq?.push(t),this.onStreamDelta?.(e,t))}}else if("tool"===t.stream){const n=t.data,a="string"==typeof n?.phase?n.phase:void 0;if("start"===a){this.sendToolCallSpacer(e,s),e.hasAgentToolStartStream=!0;const t=this.resolveToolCallId(e,n,"start"),a=asString(n?.name)??asString(n?.toolName)??asString(n?.tool_name)??"tool",r=resolveToolArgs(n);o(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=n?.toolCall;if(t){this.sendToolCallSpacer(e,s),e.hasAgentToolStartStream=!0;const a=asString(t?.name)??asString(n?.name)??asString(n?.toolName)??"tool",r={...n,...t},i=this.resolveToolCallId(e,r,"start"),l=resolveToolArgs(r);o(buildToolCallPayload({toolCallId:i,toolName:a,args:l,timestamp:s}))}}}else if("lifecycle"===t.stream){const s=t.data,o="string"==typeof s?.phase?s.phase:void 0;if("end"===o)this.completePrompt(e,"end_turn");else if("cancelled"===o||"cancel"===o)this.completePrompt(e,"cancelled");else if("error"===o){const o=s?.error,n=o&&"object"==typeof o?o:void 0,a=("string"==typeof s?.message?s.message:void 0)??("string"==typeof o?o:void 0)??("string"==typeof n?.message?n.message:void 0)??("string"==typeof s?.reason?s.reason:void 0)??(n?JSON.stringify(n):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 o=e.data,n=o?.toolCall,a=("string"==typeof n?.id?n.id:void 0)??("string"==typeof o?.toolCallId?o.toolCallId:void 0),r=(a?this.state.toolCallIdMap.get(a):void 0)??a??`tc_${e.runId}_${e.seq}`,i=("string"==typeof n?.name?n.name:void 0)??("string"==typeof o?.name?o.name:void 0)??"tool",l="string"==typeof o?.text?o.text:void 0,d=a??r,c=o?.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 m=[],p=[];for(const t of u)t.content&&("resource_link"===t.content.type&&t.content.uri?p.push({uri:t.content.uri,name:t.content.name??"file",...t.content.mimeType?{mimeType:t.content.mimeType}:{}}):t.content.text&&m.push(t.content.text));const h=buildToolCallUpdatePayload({toolCallId:r,toolName:i,outputText:m.join("\n"),rawOutput:c,resourceLinks:p,timestamp:s});this.sendTurnUpdate(t,h)&&(t.assistantMq?.push(h),this.onStreamDelta?.(t,h))}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()}handleCronEvent(t){if(this.transport.sendNotification("_beeos/cron_event",{payload:t}),!this.config.agentGatewayUrl||!this.agentFetchFn)return;const e=t??{},s="string"==typeof e.sessionKey?e.sessionKey:void 0,o=s?this.state.findSessionByKey(s)?.sessionId:void 0,n={...e};s&&null==n.sessionKey&&(n.sessionKey=s),o&&(n.sessionId=o);const a=`${this.config.agentGatewayUrl}/api/v1/agent/events`;this.agentFetchFn(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"cron",data:n})}).catch(t=>{this.logger.warn?.(`[gateway-events] event report failed: ${t instanceof Error?t.message:t}`)})}}
1
+ import{createHash}from"node:crypto";import{Errors}from"../errors/index.js";import{formatFriendlyError}from"../errors/classify.js";import{stripTransportMetadata,normalizeTransportText,isHeartbeatOnlyText}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";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 o=roleFromSessionUpdate(e);o&&(t.lastTurnIdByRole||(t.lastTurnIdByRole={}),t.lastTurnIdByRole[o]=s)}export class AcpGatewayEvents{state;transport;config;logger;writeObs;completePrompt;failPrompt;maybeCompletePromptFromChatState;agentFetchFn;onStreamDelta;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}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),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 o=asString(e.toolCallId)??asString(e.tool_call_id)??asString(e.callId)??asString(e.id);if(o){const e=this.state.toolCallIdMap.get(o);return e?(t.sessionId&&this.state.toolCallToSessionMap.set(e,t.sessionId),e):(this.state.toolCallIdMap.set(o,o),t.sessionId&&this.state.toolCallToSessionMap.set(o,t.sessionId),o)}const n=`tc_${t.currentRunId??"unknown"}_${this.state.nextToolCallSeq++}`;return t.sessionId&&this.state.toolCallToSessionMap.set(n,t.sessionId),n}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 o of s.content){const n=o;if(!isRecord(n))continue;const a=asString(n.type);if(!a)continue;const r=toISO(s.timestamp);if("thinking"===a){if(e.hasAgentThinkingStream)continue;const t=normalizeText(n.thinking)??normalizeText(n.text);if(!t)continue;const s=dedupKey("chat:thinking",t);if(e.chatReplayDedupKeys.has(s))continue;e.chatReplayDedupKeys.add(s);const o={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:t},...r?{timestamp:r}:{}};this.sendTurnUpdate(e,o)&&(e.assistantMq?.push(o),this.onStreamDelta?.(e,o));continue}if("toolCall"===a){if(this.sendToolCallSpacer(e,r),e.hasAgentToolStartStream)continue;const t=this.resolveToolCallId(e,n,"start"),s=asString(n.name)??asString(n.toolName)??asString(n.tool_name)??"tool",o=resolveToolArgs(n),a=dedupKey("chat:tool_start",t,JSON.stringify(o));if(e.chatReplayDedupKeys.has(a))continue;e.chatReplayDedupKeys.add(a);const i=buildToolCallPayload({toolCallId:t,toolName:s,args:o,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,n,"result"),s=asString(n.name)??asString(n.toolName)??asString(n.tool_name)??"tool",o=n.result,a=normalizeText(n.text)??normalizeText(n.result)??(isRecord(o)||Array.isArray(o)?JSON.stringify(o,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:o,resourceLinks:extractResourceLinksFromRawResult(o),timestamp:r});this.sendTurnUpdate(e,l)&&(e.assistantMq?.push(l),this.onStreamDelta?.(e,l));continue}if("text"===a&&n.text){if(e.hasAgentAssistantStream||e.agentAssistantTextSoFar)continue;const s=stripTransportMetadata(n.text);if(!s)continue;if(isHeartbeatOnlyText(s)){this.logger.debug?.(`[gateway-events] SKIP heartbeat chat.text runId=${t.runId} len=${s.length}`);continue}const o=dedupKey("chat:text",s);if(e.chatReplayDedupKeys.has(o))continue;e.chatReplayDedupKeys.add(o);const a=e.chatAssistantTextSoFar??"";let i;if(e.chatAssistantTextSoFar=s,s.startsWith(a))i=s.slice(a.length);else{if(a.startsWith(s))continue;i=s}if(!i)continue;this.logger.debug?.(`[gateway-events] chat.text delta seq=${t.seq} runId=${t.runId} len=${i.length} prevLen=${a.length}`);const l={sessionUpdate:"agent_message_chunk",content:{type:"text",text:i},...r?{timestamp:r}:{}};this.sendTurnUpdate(e,l),e.assistantMq?.push(l),this.onStreamDelta?.(e,l)}}}}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),o=t=>{this.sendTurnUpdate(e,t),e.assistantMq?.push(t),this.onStreamDelta?.(e,t)};if("assistant"===t.stream){e.hasAgentAssistantStream=!0;const n=this.state.extractAgentAssistantDelta(e,t.data??{});if(n){const a=normalizeTransportText(n);if(a){const n=e.agentAssistantTextSoFar??a;isHeartbeatOnlyText(n)?this.logger.debug?.(`[gateway-events] SKIP heartbeat assistant delta runId=${t.runId} len=${a.length}`):(this.logger.debug?.(`[gateway-events] agent.assistant delta seq=${t.seq} runId=${t.runId} len=${a.length} source=${t.data?.delta?"delta":"cumulative"}`),o({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 n=asString(t.type);if("thinking"===n){e.hasAgentThinkingStream=!0;const o=normalizeText(t.thinking)??normalizeText(t.text);if(o){const t={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:o},...s?{timestamp:s}:{}};this.sendTurnUpdate(e,t)&&(e.assistantMq?.push(t),this.onStreamDelta?.(e,t))}continue}if("toolCall"===n){this.sendToolCallSpacer(e,s),e.hasAgentToolStartStream=!0;const n=this.resolveToolCallId(e,t,"start"),a=asString(t.name)??asString(t.toolName)??asString(t.tool_name)??"tool",r=resolveToolArgs(t);o(buildToolCallPayload({toolCallId:n,toolName:a,args:r,timestamp:s}));continue}if("toolResult"===n){this.sendToolCallSpacer(e,s),e.hasAgentToolResultStream=!0;const n=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&&o(buildToolCallUpdatePayload({toolCallId:n,toolName:a,outputText:i,rawOutput:r,resourceLinks:extractResourceLinksFromRawResult(r),timestamp:s}));continue}}}else if("thinking"===t.stream){e.hasAgentThinkingStream=!0;const o=normalizeText(t.data?.delta)??normalizeText(t.data?.text);if(o){const t={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:o},...s?{timestamp:s}:{}};this.sendTurnUpdate(e,t)&&(e.assistantMq?.push(t),this.onStreamDelta?.(e,t))}}else if("tool"===t.stream){const n=t.data,a="string"==typeof n?.phase?n.phase:void 0;if("start"===a){this.sendToolCallSpacer(e,s),e.hasAgentToolStartStream=!0;const t=this.resolveToolCallId(e,n,"start"),a=asString(n?.name)??asString(n?.toolName)??asString(n?.tool_name)??"tool",r=resolveToolArgs(n);o(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=n?.toolCall;if(t){this.sendToolCallSpacer(e,s),e.hasAgentToolStartStream=!0;const a=asString(t?.name)??asString(n?.name)??asString(n?.toolName)??"tool",r={...n,...t},i=this.resolveToolCallId(e,r,"start"),l=resolveToolArgs(r);o(buildToolCallPayload({toolCallId:i,toolName:a,args:l,timestamp:s}))}}}else if("lifecycle"===t.stream){const s=t.data,o="string"==typeof s?.phase?s.phase:void 0;if("end"===o)this.completePrompt(e,"end_turn");else if("cancelled"===o||"cancel"===o)this.completePrompt(e,"cancelled");else if("error"===o){const o=s?.error,n=o&&"object"==typeof o?o:void 0,a=("string"==typeof s?.message?s.message:void 0)??("string"==typeof o?o:void 0)??("string"==typeof n?.message?n.message:void 0)??("string"==typeof s?.reason?s.reason:void 0)??(n?JSON.stringify(n):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 o=e.data,n=o?.toolCall,a=("string"==typeof n?.id?n.id:void 0)??("string"==typeof o?.toolCallId?o.toolCallId:void 0),r=(a?this.state.toolCallIdMap.get(a):void 0)??a??`tc_${e.runId}_${e.seq}`,i=("string"==typeof n?.name?n.name:void 0)??("string"==typeof o?.name?o.name:void 0)??"tool",l="string"==typeof o?.text?o.text:void 0,d=a??r,c=o?.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 m=[],p=[];for(const t of u)t.content&&("resource_link"===t.content.type&&t.content.uri?p.push({uri:t.content.uri,name:t.content.name??"file",...t.content.mimeType?{mimeType:t.content.mimeType}:{}}):t.content.text&&m.push(t.content.text));const h=buildToolCallUpdatePayload({toolCallId:r,toolName:i,outputText:m.join("\n"),rawOutput:c,resourceLinks:p,timestamp:s});this.sendTurnUpdate(t,h)&&(t.assistantMq?.push(h),this.onStreamDelta?.(t,h))}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()}handleCronEvent(t){if(this.transport.sendNotification("_beeos/cron_event",{payload:t}),!this.config.agentGatewayUrl||!this.agentFetchFn)return;const e=t??{},s="string"==typeof e.sessionKey?e.sessionKey:void 0,o=s?this.state.findSessionByKey(s)?.sessionId:void 0,n={...e};s&&null==n.sessionKey&&(n.sessionKey=s),o&&(n.sessionId=o);const a=`${this.config.agentGatewayUrl}/api/v1/agent/events`;this.agentFetchFn(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"cron",data:n})}).catch(t=>{this.logger.warn?.(`[gateway-events] event report failed: ${t instanceof Error?t.message:t}`)})}}
@@ -1 +1 @@
1
- import{stripTransportMetadata}from"../message-filter.js";const DEFAULT_CHAT_HISTORY_RPC_TIMEOUT_MS=3e3;function toISO(t){if(null!=t){if("string"==typeof t){if(!t)return;const e=new Date(t),o=e.getTime();return Number.isFinite(o)?e.toISOString():void 0}if(!(t<=0))try{return new Date(t).toISOString()}catch{return}}}function inferToolKindFromName(t){if(!t)return;const e=t.toLowerCase();return e.includes("read")?"read":e.includes("write")||e.includes("edit")?"edit":e.includes("delete")||e.includes("remove")?"delete":e.includes("move")||e.includes("rename")?"move":e.includes("search")||e.includes("find")?"search":e.includes("exec")||e.includes("run")||e.includes("bash")?"execute":e.includes("fetch")||e.includes("http")?"fetch":"other"}const BEEOS_USER_MSG_MARKER_RE=/(?:^|\n)\s*User Message From \w+:\s*\n/i,CANVAS_STATE_RE=/^\[Canvas State\][^\n]*/,SYSTEM_NOTE_RE=/^\[System Note\][^\n]*/,CANVAS_INTERACTION_RE=/^\[Canvas Interaction\] The user clicked "([^"]*)" on surface "([^"]*)"/,ACTION_CONTEXT_RE=/\nAction context: (.+?)(?:\n|$)/s;function stripBeeosUserEnvelope(t){const e=BEEOS_USER_MSG_MARKER_RE.exec(t);if(e){return t.slice(e.index+e[0].length).trim()}let o=t;return o=o.replace(CANVAS_STATE_RE,"").trimStart(),o=o.replace(SYSTEM_NOTE_RE,"").trimStart(),stripTransportMetadata(o).trim()}export async function loadHistory(t,e,o=100,s){const n=Date.now(),i=s?.rpcTimeoutMs??3e3,a=s?.logger,l=s?.emitObs,r=t=>{a?.info&&a.info(t)};let c,u=null;if(t?.isConnected)try{u=await Promise.race([t.chatHistory(e,o),new Promise(t=>{const e=setTimeout(()=>t(null),i);"object"==typeof e&&"unref"in e&&e.unref()})])}catch(t){c=t}const p=u?parseGatewayHistory(u):[];if(p.length>0){const t=Date.now()-n,o=p.filter(t=>"user"===t.role).length,s=p.filter(t=>"assistant"===t.role).length;return r(`[loadHistory] source=chat.history sid=${e} messages=${p.length} (user=${o} asst=${s}) elapsedMs=${t}`),l?.({name:"history.source",severity:"info",payload:{sessionKey:e,source:"chat.history",messages:p.length,userCount:o,asstCount:s,elapsedMs:t}}),p}const{localHistory:m,agentId:f,sessionId:d}=s??{},g=t?.isConnected?null===u?c?"rpc-error":"rpc-timeout":"rpc-empty":"gateway-disconnected";if(!m||!f){const t=Date.now()-n;return r(`[loadHistory] source=none sid=${e} reason=${g} elapsedMs=${t}`),c&&(a?.warn??console.debug)?.(`[loadHistory] chat.history error: ${c instanceof Error?c.message:String(c)}`),l?.({name:"history.none",severity:"warn",payload:{sessionKey:e,reason:g,fallbackAvailable:!1,elapsedMs:t}}),[]}let y=[];try{y=m.readEntries({agentId:f,sessionKey:e,sessionId:d})}catch(t){(a?.warn??console.debug)?.(`[loadHistory] local jsonl read failed: ${t instanceof Error?t.message:String(t)}`)}if(0===y.length){const t=Date.now()-n;return r(`[loadHistory] source=none sid=${e} reason=${g},local-empty elapsedMs=${t}`),l?.({name:"history.none",severity:"warn",payload:{sessionKey:e,reason:`${g},local-empty`,fallbackAvailable:!0,elapsedMs:t}}),[]}const _=parseGatewayHistory({messages:y}),h=Date.now()-n;return r(`[loadHistory] source=local-jsonl sid=${e} reason=${g} messages=${_.length} localLines=${y.length} elapsedMs=${h}`),l?.({name:"history.local_fallback",severity:"info",payload:{sessionKey:e,reason:g,localLines:y.length,messages:_.length,elapsedMs:h}}),_}export function groupIntoTurns(t){const e=[];let o=null;const s=()=>{o&&(e.push(o),o=null)};for(const n of t){if("assistant"===n.role&&(n.reasoning||n.toolCalls?.length)){s(),o={role:"assistant",content:n.content,reasoning:n.reasoning,files:n.files,sourceMessages:[n],...n.timestamp?{timestamp:n.timestamp}:{},...n.messageId?{messageId:n.messageId}:{},...void 0!==n._seq?{_seq:n._seq}:{}},n.toolCalls?.length&&(o.toolCalls=n.toolCalls.map(t=>({id:t.id,callId:t.id,name:t.name,arguments:t.arguments??"",status:t.status??"in_progress",output:t.output,isError:"error"===t.status||"failed"===t.status,kind:inferToolKindFromName(t.name)})));continue}if("system"===n.role){s();const t={role:"system",content:n.content};n.metadata&&(t.metadata=n.metadata),n.timestamp&&(t.timestamp=n.timestamp),n.messageId&&(t.messageId=n.messageId),void 0!==n._seq&&(t._seq=n._seq),e.push(t);continue}if("user"===n.role){s();const t={role:"user",content:n.content};n.provenance&&(t.provenance=n.provenance),n.metadata&&(t.metadata=n.metadata),n.timestamp&&(t.timestamp=n.timestamp),n.messageId&&(t.messageId=n.messageId),void 0!==n._seq&&(t._seq=n._seq),e.push(t);continue}o||(o={role:"assistant",content:"",sourceMessages:[]}),o.sourceMessages||(o.sourceMessages=[]),o.sourceMessages.push(n),!o.timestamp&&n.timestamp&&(o.timestamp=n.timestamp),!o.messageId&&n.messageId&&(o.messageId=n.messageId),void 0===o._seq&&void 0!==n._seq&&(o._seq=n._seq);switch(n.updateType??"agent_message_chunk"){case"agent_thought_chunk":o.reasoning=(o.reasoning??"")+n.content;break;case"tool_call":o.toolCalls||(o.toolCalls=[]),o.toolCalls.push({id:n.toolCallId??`tc_${o.toolCalls.length}`,callId:n.toolCallId??`tc_${o.toolCalls.length}`,name:n.toolName??"tool",arguments:n.content||"",status:"in_progress",kind:inferToolKindFromName(n.toolName)});break;case"tool_call_update":{o.toolCalls||(o.toolCalls=[]);const t=n.toolCallId?o.toolCalls.find(t=>t.id===n.toolCallId):void 0;t?(t.output=n.content,t.status="completed"):o.toolCalls.push({id:n.toolCallId??`tc_${o.toolCalls.length}`,callId:n.toolCallId??`tc_${o.toolCalls.length}`,name:n.toolName??"tool",arguments:"",status:"completed",output:n.content,kind:inferToolKindFromName(n.toolName)});break}default:o.content+=n.content,n.files?.length&&(o.files=[...o.files??[],...n.files])}}return s(),e}const TOOL_CALL_BLOCK_TYPES=new Set(["toolCall","toolUse","functionCall","tool_use","tool_call","toolcall"]),TOOL_RESULT_BLOCK_TYPES=new Set(["tool_result","tool_result_error","toolResult"]);function readOpenClawMeta(t){const e=t.__openclaw;if(!e||"object"!=typeof e)return{};const o={},s=e.id,n=e.seq;return"string"==typeof s&&s.length>0&&(o.id=s),"number"==typeof n&&Number.isFinite(n)&&(o.seq=n),o}function extractBlockText(t){if("string"==typeof t)return t;if(!Array.isArray(t))return"";let e="";for(const o of t)"string"!=typeof o?o&&"object"==typeof o&&"string"==typeof o.text&&(e+=o.text):e+=o;return e}function parseGatewayHistory(t){if(!t||"object"!=typeof t)return[];const e=t.messages;if(!Array.isArray(e))return[];const o=[];let s=null;for(const t of e){if(!t||"object"!=typeof t)continue;const e=t,n="string"==typeof e.role?e.role:"assistant",i=readOpenClawMeta(e),a=i.id,l=i.seq,r=e.message?.timestamp,c=toISO("number"==typeof e.timestamp||"string"==typeof e.timestamp?e.timestamp:"number"==typeof r||"string"==typeof r?r:void 0),u=t=>(a&&(t.messageId=a),void 0!==l&&(t._seq=l),c&&!t.timestamp&&(t.timestamp=c),t);if("toolResult"===n||"tool"===n){const t=String(e.toolCallId??e.tool_call_id??e.toolUseId??e.tool_use_id??""),n=extractBlockText(e.content),i=!0===e.is_error||!0===e.isError;if(s?.toolCalls?.length){const e=(t?s.toolCalls.find(e=>e.id===t):void 0)??s.toolCalls.find(t=>void 0===t.output);e&&(e.output=n,e.status=i?"failed":"completed")}else o.push(u({role:"assistant",content:n,updateType:"tool_call_update",toolCallId:t||void 0}));continue}if("user"===n&&Array.isArray(e.content)){let t=!1,n=!1;for(const o of e.content){if(!o||"object"!=typeof o)continue;const e=o,s="string"==typeof e.type?e.type:"";TOOL_RESULT_BLOCK_TYPES.has(s)?t=!0:"text"===s&&"string"==typeof e.text&&e.text.trim()&&(n=!0)}if(t&&!n){for(const t of e.content){if(!t||"object"!=typeof t)continue;const e=t,n="string"==typeof e.type?e.type:"";if(!TOOL_RESULT_BLOCK_TYPES.has(n))continue;const i=String(e.toolUseId??e.tool_use_id??e.toolCallId??e.tool_call_id??""),a="string"==typeof e.output?e.output:extractBlockText(e.content),l=!0===e.is_error||!0===e.isError;if(s?.toolCalls?.length){const t=(i?s.toolCalls.find(t=>t.id===i):void 0)??s.toolCalls.find(t=>void 0===t.output);t&&(t.output=a,t.status=l?"failed":"completed")}else o.push(u({role:"assistant",content:a,updateType:"tool_call_update",toolCallId:i||void 0}))}continue}}const p="user"===n?"user":"assistant";let m,f,d,g,y,_="";if("string"==typeof e.content)_=e.content;else if(Array.isArray(e.content)){if("assistant"===p&&e.content.some(t=>{if(!t||"object"!=typeof t)return!1;const e="string"==typeof t.type?t.type:"";return TOOL_CALL_BLOCK_TYPES.has(e)||TOOL_RESULT_BLOCK_TYPES.has(e)})&&"assistant"===p){const t=new Map;for(const s of e.content){if("string"==typeof s){s&&o.push(u({role:"assistant",content:s,updateType:"agent_message_chunk"}));continue}if(!s||"object"!=typeof s)continue;const e=s,n="string"==typeof e.type?e.type:"";if("text"===n&&"string"==typeof e.text&&e.text)o.push(u({role:"assistant",content:e.text,updateType:"agent_message_chunk"}));else if("thinking"===n&&"string"==typeof e.thinking)o.push(u({role:"assistant",content:e.thinking,updateType:"agent_thought_chunk"}));else if("resource_link"===n&&"string"==typeof e.uri&&e.uri)d||(d=[]),d.push({uri:e.uri,..."string"==typeof e.name&&e.name?{name:e.name}:{},..."string"==typeof e.mimeType&&e.mimeType?{mimeType:e.mimeType}:{}});else if(TOOL_CALL_BLOCK_TYPES.has(n)){const s=e.arguments??e.input,n="string"==typeof s?s:null!=s?JSON.stringify(s):"",i=String(e.id??e.toolCallId??e.tool_call_id??""),a=u({role:"assistant",content:n,updateType:"tool_call",toolCallId:i,toolName:String(e.name??"tool")});o.push(a),i&&t.set(i,a)}else if(TOOL_RESULT_BLOCK_TYPES.has(n)){const s=String(e.toolUseId??e.tool_use_id??e.toolCallId??e.tool_call_id??""),n="string"==typeof e.output?e.output:extractBlockText(e.content),i=!0===e.is_error||!0===e.isError;if(o.push(u({role:"assistant",content:n,updateType:"tool_call_update",toolCallId:s||void 0,toolName:t.get(s)?.toolName})),s&&t.has(s)){const e=t.get(s);e.toolCalls||(e.toolCalls=[{id:s,name:e.toolName??"tool",arguments:e.content,status:i?"failed":"completed",output:n}])}}}d?.length&&o.push(u({role:"assistant",content:"",files:d})),"string"==typeof e.reasoning&&e.reasoning?o.push(u({role:"assistant",content:e.reasoning,updateType:"agent_thought_chunk"})):"string"==typeof e.thinking&&e.thinking&&o.push(u({role:"assistant",content:e.thinking,updateType:"agent_thought_chunk"})),o.length>0&&"assistant"===o[o.length-1].role&&(s=o[o.length-1]);continue}for(const t of e.content){if("string"==typeof t){_+=t;continue}if(!t||"object"!=typeof t)continue;const e=t,o="string"==typeof e.type?e.type:"";"text"===o&&"string"==typeof e.text?_+=e.text:"thinking"===o&&"string"==typeof e.thinking?f=(f??"")+e.thinking:"resource_link"===o&&"string"==typeof e.uri&&e.uri&&(d||(d=[]),d.push({uri:e.uri,..."string"==typeof e.name&&e.name?{name:e.name}:{},..."string"==typeof e.mimeType&&e.mimeType?{mimeType:e.mimeType}:{}}))}}if(f||("string"==typeof e.reasoning&&e.reasoning?f=e.reasoning:"string"==typeof e.thinking&&e.thinking&&(f=e.thinking)),!m?.length){const t=e.tool_calls??e.toolCalls;if(Array.isArray(t)){m=[];for(const e of t){if(!e||"object"!=typeof e)continue;const t=e,o=t.function;m.push({id:String(t.id??t.toolCallId??""),name:String(o?.name??t.name??t.toolName??"tool"),arguments:"string"==typeof t.arguments?t.arguments:"string"==typeof o?.arguments?o.arguments:"",status:String(t.status??"in_progress"),output:"string"==typeof t.output?t.output:void 0})}0===m.length&&(m=void 0)}}if("user"===p&&_){_=stripBeeosUserEnvelope(_);const t=CANVAS_INTERACTION_RE.exec(_);if(t){const e=t[1];g={kind:"canvas_action"};const o={type:"canvas_action",actionName:e,surfaceId:t[2]},s=ACTION_CONTEXT_RE.exec(_);if(s)try{o.actionPayload=JSON.parse(s[1])}catch{}y=o,_=`Clicked "${e}"`}}if(!(_||f||m?.length||d?.length))continue;if(!g&&"user"===p&&e.provenance&&"object"==typeof e.provenance){const t=e.provenance;"string"==typeof t.kind&&(g={kind:t.kind},"string"==typeof t.sourceTool&&(g.sourceTool=t.sourceTool))}const h=u({role:p,content:_,reasoning:f,toolCalls:m,provenance:g,metadata:y,files:d});o.push(h),"assistant"===p&&(s=h)}o.filter(t=>t.toolCalls?.length),o.reduce((t,e)=>t+(e.toolCalls?.length??0),0),o.reduce((t,e)=>t+(e.toolCalls?.filter(t=>void 0!==t.output).length??0),0);return o}const BEEOS_FILE_URI_RE=/beeos-file:\/\/([a-zA-Z0-9_-]+)/g;export function extractBeeosFileUrisFromOutput(t){if(!t)return[];const e=[];for(const o of t.matchAll(BEEOS_FILE_URI_RE))e.push(o[0]);return[...new Set(e)]}const BEEOS_REF_RE=/<BEEOS_REF\s+((?:[^"]|"[^"]*")*?)\s*\/>/g;function parseBeeosRefAttrs(t){const e=new Map,o=/(\w+)="([^"]*)"/g;for(const s of t.matchAll(o))e.set(s[1],s[2]);return e}function guessMimeFromName(t){if(!t)return;const e=t.split(".").pop()?.toLowerCase();return e?{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",webm:"video/webm",txt:"text/plain",json:"application/json",csv:"text/csv"}[e]:void 0}export function splitBeeosRefReplayText(t){if(!t)return[];if(!t.includes("<BEEOS_REF "))return[{type:"text",text:t}];const e=[];let o=0;for(const s of t.matchAll(BEEOS_REF_RE)){const n=t.slice(o,s.index).trim();n&&e.push({type:"text",text:n});const i=parseBeeosRefAttrs(s[1]),a=i.get("id"),l=i.get("name"),r=i.get("status");a&&"download_failed"!==r?e.push({type:"resource_link",uri:`beeos-file://${a}`,fileName:l,mimeType:guessMimeFromName(l)??"application/octet-stream"}):a&&e.push({type:"resource_link",uri:`beeos-file://${a}`,fileName:l??"file",mimeType:guessMimeFromName(l)??"application/octet-stream"}),o=(s.index??0)+s[0].length}const s=t.slice(o).trim();return s&&e.push({type:"text",text:s}),e}const ATTACHMENT_MARKER_RE=/\[(image|file)\s+([^\]]*)\]/g;export function splitUserAttachmentMarkers(t){if(!t)return[];if(!t.includes("[image ")&&!t.includes("[file "))return[{type:"text",text:t}];const e=[];let o=0;for(const s of t.matchAll(ATTACHMENT_MARKER_RE)){const n=t.slice(o,s.index).trim();n&&e.push({type:"text",text:n});const i=s[1],a=s[2],l=new Map;for(const t of a.split(/\s+/)){const e=t.indexOf("=");e>0&&l.set(t.slice(0,e),t.slice(e+1))}e.push({type:i,mimeType:l.get("mime"),fileName:l.get("name")||("image"===i?"Image":"File")}),o=(s.index??0)+s[0].length}const s=t.slice(o).trim();return s&&e.push({type:"text",text:s}),e}export function splitUserReplayBlocks(t){return t?t.includes("<BEEOS_REF ")?splitBeeosRefReplayText(t):t.includes("[image ")||t.includes("[file ")?splitUserAttachmentMarkers(t):[{type:"text",text:t}]:[]}
1
+ import{stripTransportMetadata}from"../message-filter.js";import{formatProviderError}from"./error-message-formatter.js";const DEFAULT_CHAT_HISTORY_RPC_TIMEOUT_MS=3e3;function toISO(t){if(null!=t){if("string"==typeof t){if(!t)return;const e=new Date(t),o=e.getTime();return Number.isFinite(o)?e.toISOString():void 0}if(!(t<=0))try{return new Date(t).toISOString()}catch{return}}}function inferToolKindFromName(t){if(!t)return;const e=t.toLowerCase();return e.includes("read")?"read":e.includes("write")||e.includes("edit")?"edit":e.includes("delete")||e.includes("remove")?"delete":e.includes("move")||e.includes("rename")?"move":e.includes("search")||e.includes("find")?"search":e.includes("exec")||e.includes("run")||e.includes("bash")?"execute":e.includes("fetch")||e.includes("http")?"fetch":"other"}const BEEOS_USER_MSG_MARKER_RE=/(?:^|\n)\s*User Message From \w+:\s*\n/i,CANVAS_STATE_RE=/^\[Canvas State\][^\n]*/,SYSTEM_NOTE_RE=/^\[System Note\][^\n]*/,CANVAS_INTERACTION_RE=/^\[Canvas Interaction\] The user clicked "([^"]*)" on surface "([^"]*)"/,ACTION_CONTEXT_RE=/\nAction context: (.+?)(?:\n|$)/s;function stripBeeosUserEnvelope(t){const e=BEEOS_USER_MSG_MARKER_RE.exec(t);if(e){return t.slice(e.index+e[0].length).trim()}let o=t;return o=o.replace(CANVAS_STATE_RE,"").trimStart(),o=o.replace(SYSTEM_NOTE_RE,"").trimStart(),stripTransportMetadata(o).trim()}export async function loadHistory(t,e,o=100,s){const n=Date.now(),i=s?.rpcTimeoutMs??3e3,a=s?.logger,r=s?.emitObs,l=t=>{a?.info&&a.info(t)};let c,p=null;if(t?.isConnected)try{p=await Promise.race([t.chatHistory(e,o),new Promise(t=>{const e=setTimeout(()=>t(null),i);"object"==typeof e&&"unref"in e&&e.unref()})])}catch(t){c=t}const u=p?parseGatewayHistory(p):[];if(u.length>0){const t=Date.now()-n,o=u.filter(t=>"user"===t.role).length,s=u.filter(t=>"assistant"===t.role).length;return l(`[loadHistory] source=chat.history sid=${e} messages=${u.length} (user=${o} asst=${s}) elapsedMs=${t}`),r?.({name:"history.source",severity:"info",payload:{sessionKey:e,source:"chat.history",messages:u.length,userCount:o,asstCount:s,elapsedMs:t}}),u}const{localHistory:f,agentId:m,sessionId:d}=s??{},g=t?.isConnected?null===p?c?"rpc-error":"rpc-timeout":"rpc-empty":"gateway-disconnected";if(!f||!m){const t=Date.now()-n;return l(`[loadHistory] source=none sid=${e} reason=${g} elapsedMs=${t}`),c&&(a?.warn??console.debug)?.(`[loadHistory] chat.history error: ${c instanceof Error?c.message:String(c)}`),r?.({name:"history.none",severity:"warn",payload:{sessionKey:e,reason:g,fallbackAvailable:!1,elapsedMs:t}}),[]}let y=[];try{y=f.readEntries({agentId:m,sessionKey:e,sessionId:d})}catch(t){(a?.warn??console.debug)?.(`[loadHistory] local jsonl read failed: ${t instanceof Error?t.message:String(t)}`)}if(0===y.length){const t=Date.now()-n;return l(`[loadHistory] source=none sid=${e} reason=${g},local-empty elapsedMs=${t}`),r?.({name:"history.none",severity:"warn",payload:{sessionKey:e,reason:`${g},local-empty`,fallbackAvailable:!0,elapsedMs:t}}),[]}const _=parseGatewayHistory({messages:y}),h=Date.now()-n;return l(`[loadHistory] source=local-jsonl sid=${e} reason=${g} messages=${_.length} localLines=${y.length} elapsedMs=${h}`),r?.({name:"history.local_fallback",severity:"info",payload:{sessionKey:e,reason:g,localLines:y.length,messages:_.length,elapsedMs:h}}),_}export function groupIntoTurns(t){const e=[];let o=null;const s=()=>{o&&(e.push(o),o=null)};for(const n of t){if("assistant"===n.role&&(n.reasoning||n.toolCalls?.length)){s(),o={role:"assistant",content:n.content,reasoning:n.reasoning,files:n.files,sourceMessages:[n],...n.timestamp?{timestamp:n.timestamp}:{},...n.messageId?{messageId:n.messageId}:{},...void 0!==n._seq?{_seq:n._seq}:{}},n.toolCalls?.length&&(o.toolCalls=n.toolCalls.map(t=>({id:t.id,callId:t.id,name:t.name,arguments:t.arguments??"",status:t.status??"in_progress",output:t.output,isError:"error"===t.status||"failed"===t.status,kind:inferToolKindFromName(t.name)})));continue}if("assistant"===n.role&&"string"==typeof n.metadata?.status&&"error"===n.metadata.status){s();const t={role:"assistant",content:n.content,files:n.files,sourceMessages:[n],...n.timestamp?{timestamp:n.timestamp}:{},...n.messageId?{messageId:n.messageId}:{},...void 0!==n._seq?{_seq:n._seq}:{}};n.metadata&&(t.metadata=n.metadata),e.push(t);continue}if("system"===n.role){s();const t={role:"system",content:n.content};n.metadata&&(t.metadata=n.metadata),n.timestamp&&(t.timestamp=n.timestamp),n.messageId&&(t.messageId=n.messageId),void 0!==n._seq&&(t._seq=n._seq),e.push(t);continue}if("user"===n.role){s();const t={role:"user",content:n.content};n.provenance&&(t.provenance=n.provenance),n.metadata&&(t.metadata=n.metadata),n.timestamp&&(t.timestamp=n.timestamp),n.messageId&&(t.messageId=n.messageId),void 0!==n._seq&&(t._seq=n._seq),e.push(t);continue}o||(o={role:"assistant",content:"",sourceMessages:[]}),o.sourceMessages||(o.sourceMessages=[]),o.sourceMessages.push(n),!o.timestamp&&n.timestamp&&(o.timestamp=n.timestamp),!o.messageId&&n.messageId&&(o.messageId=n.messageId),void 0===o._seq&&void 0!==n._seq&&(o._seq=n._seq);switch(n.updateType??"agent_message_chunk"){case"agent_thought_chunk":o.reasoning=(o.reasoning??"")+n.content;break;case"tool_call":o.toolCalls||(o.toolCalls=[]),o.toolCalls.push({id:n.toolCallId??`tc_${o.toolCalls.length}`,callId:n.toolCallId??`tc_${o.toolCalls.length}`,name:n.toolName??"tool",arguments:n.content||"",status:"in_progress",kind:inferToolKindFromName(n.toolName)});break;case"tool_call_update":{o.toolCalls||(o.toolCalls=[]);const t=n.toolCallId?o.toolCalls.find(t=>t.id===n.toolCallId):void 0;t?(t.output=n.content,t.status="completed"):o.toolCalls.push({id:n.toolCallId??`tc_${o.toolCalls.length}`,callId:n.toolCallId??`tc_${o.toolCalls.length}`,name:n.toolName??"tool",arguments:"",status:"completed",output:n.content,kind:inferToolKindFromName(n.toolName)});break}default:o.content+=n.content,n.files?.length&&(o.files=[...o.files??[],...n.files])}}return s(),e}const TOOL_CALL_BLOCK_TYPES=new Set(["toolCall","toolUse","functionCall","tool_use","tool_call","toolcall"]),TOOL_RESULT_BLOCK_TYPES=new Set(["tool_result","tool_result_error","toolResult"]);function readOpenClawMeta(t){const e=t.__openclaw;if(!e||"object"!=typeof e)return{};const o={},s=e.id,n=e.seq;return"string"==typeof s&&s.length>0&&(o.id=s),"number"==typeof n&&Number.isFinite(n)&&(o.seq=n),o}function rawSeqOf(t){if(!t||"object"!=typeof t)return;const e=t.__openclaw;if(!e||"object"!=typeof e)return;const o=e.seq;return"number"==typeof o&&Number.isFinite(o)?o:void 0}function sortBySeqWhenComplete(t){if(t.length<2)return t;for(const e of t)if(void 0===rawSeqOf(e))return t;const e=t.slice();return e.sort((t,e)=>rawSeqOf(t)-rawSeqOf(e)),e}function collapseErrorRetryChains(t){const e=new Set,o=new Set;for(const s of t){if(!s||"object"!=typeof s)continue;const t=s;if("assistant"!==t.role)continue;if("error"!==t.stopReason)continue;const n=t.__openclaw&&"object"==typeof t.__openclaw?t.__openclaw:void 0,i="string"==typeof n?.id?n.id:"string"==typeof t.id?t.id:void 0,a="string"==typeof t.parentId?t.parentId:void 0;i&&e.add(i),a&&o.add(a)}const s=[];let n=null;for(const i of t){if(!i||"object"!=typeof i){s.push(i),n=null;continue}const t=i;if(!("assistant"===t.role&&"error"===t.stopReason)){s.push(i),n=null;continue}const a=t.__openclaw&&"object"==typeof t.__openclaw?t.__openclaw:void 0,r="string"==typeof a?.id?a.id:"string"==typeof t.id?t.id:void 0;r&&o.has(r)&&e.has(r)||(null===n?(n=s.length,s.push(i)):s[n]=i)}return s}function extractBlockText(t){if("string"==typeof t)return t;if(!Array.isArray(t))return"";let e="";for(const o of t)"string"!=typeof o?o&&"object"==typeof o&&"string"==typeof o.text&&(e+=o.text):e+=o;return e}export function parseGatewayHistory(t){if(!t||"object"!=typeof t)return[];const e=t.messages;if(!Array.isArray(e))return[];const o=collapseErrorRetryChains(sortBySeqWhenComplete(e)),s=[];let n=null;for(const t of o){if(!t||"object"!=typeof t)continue;const e=t,o="string"==typeof e.role?e.role:"assistant",i=readOpenClawMeta(e),a=i.id,r=i.seq,l=e.message?.timestamp,c=toISO("number"==typeof e.timestamp||"string"==typeof e.timestamp?e.timestamp:"number"==typeof l||"string"==typeof l?l:void 0),p=t=>(a&&(t.messageId=a),void 0!==r&&(t._seq=r),c&&!t.timestamp&&(t.timestamp=c),t);if("toolResult"===o||"tool"===o){const t=String(e.toolCallId??e.tool_call_id??e.toolUseId??e.tool_use_id??""),o=extractBlockText(e.content),i=!0===e.is_error||!0===e.isError;if(n?.toolCalls?.length){const e=(t?n.toolCalls.find(e=>e.id===t):void 0)??n.toolCalls.find(t=>void 0===t.output);e&&(e.output=o,e.status=i?"failed":"completed")}else s.push(p({role:"assistant",content:o,updateType:"tool_call_update",toolCallId:t||void 0}));continue}if("user"===o&&Array.isArray(e.content)){let t=!1,o=!1;for(const s of e.content){if(!s||"object"!=typeof s)continue;const e=s,n="string"==typeof e.type?e.type:"";TOOL_RESULT_BLOCK_TYPES.has(n)?t=!0:"text"===n&&"string"==typeof e.text&&e.text.trim()&&(o=!0)}if(t&&!o){for(const t of e.content){if(!t||"object"!=typeof t)continue;const e=t,o="string"==typeof e.type?e.type:"";if(!TOOL_RESULT_BLOCK_TYPES.has(o))continue;const i=String(e.toolUseId??e.tool_use_id??e.toolCallId??e.tool_call_id??""),a="string"==typeof e.output?e.output:extractBlockText(e.content),r=!0===e.is_error||!0===e.isError;if(n?.toolCalls?.length){const t=(i?n.toolCalls.find(t=>t.id===i):void 0)??n.toolCalls.find(t=>void 0===t.output);t&&(t.output=a,t.status=r?"failed":"completed")}else s.push(p({role:"assistant",content:a,updateType:"tool_call_update",toolCallId:i||void 0}))}continue}}const u="user"===o?"user":"assistant";let f,m,d,g,y,_="";if("string"==typeof e.content)_=e.content;else if(Array.isArray(e.content)){if("assistant"===u&&e.content.some(t=>{if(!t||"object"!=typeof t)return!1;const e="string"==typeof t.type?t.type:"";return TOOL_CALL_BLOCK_TYPES.has(e)||TOOL_RESULT_BLOCK_TYPES.has(e)})&&"assistant"===u){const t=new Map;for(const o of e.content){if("string"==typeof o){o&&s.push(p({role:"assistant",content:o,updateType:"agent_message_chunk"}));continue}if(!o||"object"!=typeof o)continue;const e=o,n="string"==typeof e.type?e.type:"";if("text"===n&&"string"==typeof e.text&&e.text)s.push(p({role:"assistant",content:e.text,updateType:"agent_message_chunk"}));else if("thinking"===n&&"string"==typeof e.thinking)s.push(p({role:"assistant",content:e.thinking,updateType:"agent_thought_chunk"}));else if("resource_link"===n&&"string"==typeof e.uri&&e.uri)d||(d=[]),d.push({uri:e.uri,..."string"==typeof e.name&&e.name?{name:e.name}:{},..."string"==typeof e.mimeType&&e.mimeType?{mimeType:e.mimeType}:{}});else if(TOOL_CALL_BLOCK_TYPES.has(n)){const o=e.arguments??e.input,n="string"==typeof o?o:null!=o?JSON.stringify(o):"",i=String(e.id??e.toolCallId??e.tool_call_id??""),a=p({role:"assistant",content:n,updateType:"tool_call",toolCallId:i,toolName:String(e.name??"tool")});s.push(a),i&&t.set(i,a)}else if(TOOL_RESULT_BLOCK_TYPES.has(n)){const o=String(e.toolUseId??e.tool_use_id??e.toolCallId??e.tool_call_id??""),n="string"==typeof e.output?e.output:extractBlockText(e.content),i=!0===e.is_error||!0===e.isError;if(s.push(p({role:"assistant",content:n,updateType:"tool_call_update",toolCallId:o||void 0,toolName:t.get(o)?.toolName})),o&&t.has(o)){const e=t.get(o);e.toolCalls||(e.toolCalls=[{id:o,name:e.toolName??"tool",arguments:e.content,status:i?"failed":"completed",output:n}])}}}d?.length&&s.push(p({role:"assistant",content:"",files:d})),"string"==typeof e.reasoning&&e.reasoning?s.push(p({role:"assistant",content:e.reasoning,updateType:"agent_thought_chunk"})):"string"==typeof e.thinking&&e.thinking&&s.push(p({role:"assistant",content:e.thinking,updateType:"agent_thought_chunk"})),s.length>0&&"assistant"===s[s.length-1].role&&(n=s[s.length-1]);continue}for(const t of e.content){if("string"==typeof t){_+=t;continue}if(!t||"object"!=typeof t)continue;const e=t,o="string"==typeof e.type?e.type:"";"text"===o&&"string"==typeof e.text?_+=e.text:"thinking"===o&&"string"==typeof e.thinking?m=(m??"")+e.thinking:"resource_link"===o&&"string"==typeof e.uri&&e.uri&&(d||(d=[]),d.push({uri:e.uri,..."string"==typeof e.name&&e.name?{name:e.name}:{},..."string"==typeof e.mimeType&&e.mimeType?{mimeType:e.mimeType}:{}}))}}if(m||("string"==typeof e.reasoning&&e.reasoning?m=e.reasoning:"string"==typeof e.thinking&&e.thinking&&(m=e.thinking)),!f?.length){const t=e.tool_calls??e.toolCalls;if(Array.isArray(t)){f=[];for(const e of t){if(!e||"object"!=typeof e)continue;const t=e,o=t.function;f.push({id:String(t.id??t.toolCallId??""),name:String(o?.name??t.name??t.toolName??"tool"),arguments:"string"==typeof t.arguments?t.arguments:"string"==typeof o?.arguments?o.arguments:"",status:String(t.status??"in_progress"),output:"string"==typeof t.output?t.output:void 0})}0===f.length&&(f=void 0)}}if("user"===u&&_){_=stripBeeosUserEnvelope(_);const t=CANVAS_INTERACTION_RE.exec(_);if(t){const e=t[1];g={kind:"canvas_action"};const o={type:"canvas_action",actionName:e,surfaceId:t[2]},s=ACTION_CONTEXT_RE.exec(_);if(s)try{o.actionPayload=JSON.parse(s[1])}catch{}y=o,_=`Clicked "${e}"`}}if(!_&&!m&&!f?.length&&!d?.length&&"assistant"===u&&"string"==typeof e.errorMessage&&e.errorMessage){const t=e.errorMessage,o="string"==typeof e.stopReason?e.stopReason:void 0,s=formatProviderError({raw:t,stopReason:o});_=s.content,y={...y??{},status:"error",errorSource:"provider",errorCategory:s.category,...void 0!==s.httpStatus?{httpStatus:s.httpStatus}:{},...o?{stopReason:o}:{},rawError:t}}if(!(_||m||f?.length||d?.length))continue;if(!g&&"user"===u&&e.provenance&&"object"==typeof e.provenance){const t=e.provenance;"string"==typeof t.kind&&(g={kind:t.kind},"string"==typeof t.sourceTool&&(g.sourceTool=t.sourceTool))}const h=p({role:u,content:_,reasoning:m,toolCalls:f,provenance:g,metadata:y,files:d});s.push(h),"assistant"===u&&(n=h)}s.filter(t=>t.toolCalls?.length),s.reduce((t,e)=>t+(e.toolCalls?.length??0),0),s.reduce((t,e)=>t+(e.toolCalls?.filter(t=>void 0!==t.output).length??0),0);return s}const BEEOS_FILE_URI_RE=/beeos-file:\/\/([a-zA-Z0-9_-]+)/g;export function extractBeeosFileUrisFromOutput(t){if(!t)return[];const e=[];for(const o of t.matchAll(BEEOS_FILE_URI_RE))e.push(o[0]);return[...new Set(e)]}const BEEOS_REF_RE=/<BEEOS_REF\s+((?:[^"]|"[^"]*")*?)\s*\/>/g;function parseBeeosRefAttrs(t){const e=new Map,o=/(\w+)="([^"]*)"/g;for(const s of t.matchAll(o))e.set(s[1],s[2]);return e}function guessMimeFromName(t){if(!t)return;const e=t.split(".").pop()?.toLowerCase();return e?{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",webm:"video/webm",txt:"text/plain",json:"application/json",csv:"text/csv"}[e]:void 0}export function splitBeeosRefReplayText(t){if(!t)return[];if(!t.includes("<BEEOS_REF "))return[{type:"text",text:t}];const e=[];let o=0;for(const s of t.matchAll(BEEOS_REF_RE)){const n=t.slice(o,s.index).trim();n&&e.push({type:"text",text:n});const i=parseBeeosRefAttrs(s[1]),a=i.get("id"),r=i.get("name"),l=i.get("status");a&&"download_failed"!==l?e.push({type:"resource_link",uri:`beeos-file://${a}`,fileName:r,mimeType:guessMimeFromName(r)??"application/octet-stream"}):a&&e.push({type:"resource_link",uri:`beeos-file://${a}`,fileName:r??"file",mimeType:guessMimeFromName(r)??"application/octet-stream"}),o=(s.index??0)+s[0].length}const s=t.slice(o).trim();return s&&e.push({type:"text",text:s}),e}const ATTACHMENT_MARKER_RE=/\[(image|file)\s+([^\]]*)\]/g;export function splitUserAttachmentMarkers(t){if(!t)return[];if(!t.includes("[image ")&&!t.includes("[file "))return[{type:"text",text:t}];const e=[];let o=0;for(const s of t.matchAll(ATTACHMENT_MARKER_RE)){const n=t.slice(o,s.index).trim();n&&e.push({type:"text",text:n});const i=s[1],a=s[2],r=new Map;for(const t of a.split(/\s+/)){const e=t.indexOf("=");e>0&&r.set(t.slice(0,e),t.slice(e+1))}e.push({type:i,mimeType:r.get("mime"),fileName:r.get("name")||("image"===i?"Image":"File")}),o=(s.index??0)+s[0].length}const s=t.slice(o).trim();return s&&e.push({type:"text",text:s}),e}export function splitUserReplayBlocks(t){return t?t.includes("<BEEOS_REF ")?splitBeeosRefReplayText(t):t.includes("[image ")||t.includes("[file ")?splitUserAttachmentMarkers(t):[{type:"text",text:t}]:[]}
@@ -1 +1 @@
1
- import{describe,expect,it,vi,beforeEach,afterEach}from"vitest";import{mkdtempSync,mkdirSync,rmSync,writeFileSync}from"node:fs";import os from"node:os";import path from"node:path";import{loadHistory}from"./history-replay.js";import{LocalSessionHistory}from"./local-session-history.js";function makeGateway(e={}){const{connected:t=!0,delayMs:o=0,response:a={messages:[]},reject:n=!1}=e;return{get isConnected(){return t},chatHistory:vi.fn(async()=>{if(o>0&&await new Promise(e=>setTimeout(e,o)),n)throw new Error("rpc-failed");return a})}}describe("loadHistory",()=>{const e={info:vi.fn(),warn:vi.fn(),debug:vi.fn()};let t;function o(e,o,a){const n=path.join(t,"agents",e,"sessions");mkdirSync(n,{recursive:!0});const s=path.join(n,`${o}.jsonl`),i=a.map(e=>JSON.stringify({id:e.id,type:"message",timestamp:(new Date).toISOString(),message:{role:e.role,content:[{type:"text",text:e.text}],timestamp:Date.now()}}));writeFileSync(s,i.join("\n")+"\n")}beforeEach(()=>{t=mkdtempSync(path.join(os.tmpdir(),"beeos-claw-lh-")),e.info.mockClear(),e.warn.mockClear(),e.debug.mockClear()}),afterEach(()=>{rmSync(t,{recursive:!0,force:!0})}),it("returns gateway messages when chat.history has content",async()=>{const t=makeGateway({response:{messages:[{id:"m1",role:"user",content:[{type:"text",text:"hi"}]},{id:"m2",role:"assistant",content:[{type:"text",text:"hello"}]}]}}),o=vi.fn(),a=await loadHistory(t,"agent:main:s1",100,{logger:e,emitObs:o});expect(a.length).toBeGreaterThan(0),expect(t.chatHistory).toHaveBeenCalledOnce(),expect(e.info).toHaveBeenCalledWith(expect.stringContaining("source=chat.history")),expect(o).toHaveBeenCalledOnce(),expect(o).toHaveBeenCalledWith(expect.objectContaining({name:"history.source",severity:"info",payload:expect.objectContaining({source:"chat.history",messages:a.length})}))}),it("falls back to local jsonl when gateway is disconnected",async()=>{o("main","s1",[{id:"m1",role:"user",text:"hi"},{id:"m2",role:"assistant",text:"hello"}]);const a=makeGateway({connected:!1}),n=new LocalSessionHistory({logger:e,openclawHome:t}),s=vi.fn(),i=await loadHistory(a,"agent:main:s1",100,{logger:e,localHistory:n,agentId:"main",sessionId:"s1",emitObs:s});expect(i.length).toBeGreaterThan(0),expect(a.chatHistory).not.toHaveBeenCalled(),expect(e.info).toHaveBeenCalledWith(expect.stringContaining("source=local-jsonl")),expect(s).toHaveBeenCalledWith(expect.objectContaining({name:"history.local_fallback",severity:"info",payload:expect.objectContaining({reason:"gateway-disconnected"})}))}),it("falls back to local jsonl when chat.history times out",async()=>{o("main","s1",[{id:"m1",role:"user",text:"hi"}]);const a=makeGateway({delayMs:500}),n=new LocalSessionHistory({logger:e,openclawHome:t}),s=await loadHistory(a,"agent:main:s1",100,{logger:e,localHistory:n,agentId:"main",sessionId:"s1",rpcTimeoutMs:50});expect(s.length).toBeGreaterThan(0),expect(e.info).toHaveBeenCalledWith(expect.stringContaining("reason=rpc-timeout"))}),it("falls back to local jsonl when chat.history returns empty",async()=>{o("main","s1",[{id:"m1",role:"user",text:"hi"}]);const a=makeGateway({response:{messages:[]}}),n=new LocalSessionHistory({logger:e,openclawHome:t}),s=await loadHistory(a,"agent:main:s1",100,{logger:e,localHistory:n,agentId:"main",sessionId:"s1"});expect(s.length).toBeGreaterThan(0),expect(e.info).toHaveBeenCalledWith(expect.stringContaining("reason=rpc-empty"))}),it("returns [] when both gateway and local are empty",async()=>{const o=makeGateway({response:{messages:[]}}),a=new LocalSessionHistory({logger:e,openclawHome:t}),n=vi.fn(),s=await loadHistory(o,"agent:main:s1",100,{logger:e,localHistory:a,agentId:"main",sessionId:"missing",emitObs:n});expect(s).toEqual([]),expect(e.info).toHaveBeenCalledWith(expect.stringContaining("local-empty")),expect(n).toHaveBeenCalledWith(expect.objectContaining({name:"history.none",severity:"warn",payload:expect.objectContaining({fallbackAvailable:!0})}))}),it("falls back to local on rpc error",async()=>{o("main","s1",[{id:"m1",role:"user",text:"hi"}]);const a=makeGateway({reject:!0}),n=new LocalSessionHistory({logger:e,openclawHome:t}),s=await loadHistory(a,"agent:main:s1",100,{logger:e,localHistory:n,agentId:"main",sessionId:"s1"});expect(s.length).toBeGreaterThan(0),expect(e.info).toHaveBeenCalledWith(expect.stringContaining("reason=rpc-error"))})});
1
+ import{describe,expect,it,vi,beforeEach,afterEach}from"vitest";import{mkdtempSync,mkdirSync,rmSync,writeFileSync}from"node:fs";import os from"node:os";import path from"node:path";import{loadHistory,parseGatewayHistory}from"./history-replay.js";import{LocalSessionHistory}from"./local-session-history.js";function makeGateway(e={}){const{connected:t=!0,delayMs:a=0,response:s={messages:[]},reject:o=!1}=e;return{get isConnected(){return t},chatHistory:vi.fn(async()=>{if(a>0&&await new Promise(e=>setTimeout(e,a)),o)throw new Error("rpc-failed");return s})}}describe("loadHistory",()=>{const e={info:vi.fn(),warn:vi.fn(),debug:vi.fn()};let t;function a(e,a,s){const o=path.join(t,"agents",e,"sessions");mkdirSync(o,{recursive:!0});const n=path.join(o,`${a}.jsonl`),r=s.map(e=>JSON.stringify({id:e.id,type:"message",timestamp:(new Date).toISOString(),message:{role:e.role,content:[{type:"text",text:e.text}],timestamp:Date.now()}}));writeFileSync(n,r.join("\n")+"\n")}beforeEach(()=>{t=mkdtempSync(path.join(os.tmpdir(),"beeos-claw-lh-")),e.info.mockClear(),e.warn.mockClear(),e.debug.mockClear()}),afterEach(()=>{rmSync(t,{recursive:!0,force:!0})}),it("returns gateway messages when chat.history has content",async()=>{const t=makeGateway({response:{messages:[{id:"m1",role:"user",content:[{type:"text",text:"hi"}]},{id:"m2",role:"assistant",content:[{type:"text",text:"hello"}]}]}}),a=vi.fn(),s=await loadHistory(t,"agent:main:s1",100,{logger:e,emitObs:a});expect(s.length).toBeGreaterThan(0),expect(t.chatHistory).toHaveBeenCalledOnce(),expect(e.info).toHaveBeenCalledWith(expect.stringContaining("source=chat.history")),expect(a).toHaveBeenCalledOnce(),expect(a).toHaveBeenCalledWith(expect.objectContaining({name:"history.source",severity:"info",payload:expect.objectContaining({source:"chat.history",messages:s.length})}))}),it("falls back to local jsonl when gateway is disconnected",async()=>{a("main","s1",[{id:"m1",role:"user",text:"hi"},{id:"m2",role:"assistant",text:"hello"}]);const s=makeGateway({connected:!1}),o=new LocalSessionHistory({logger:e,openclawHome:t}),n=vi.fn(),r=await loadHistory(s,"agent:main:s1",100,{logger:e,localHistory:o,agentId:"main",sessionId:"s1",emitObs:n});expect(r.length).toBeGreaterThan(0),expect(s.chatHistory).not.toHaveBeenCalled(),expect(e.info).toHaveBeenCalledWith(expect.stringContaining("source=local-jsonl")),expect(n).toHaveBeenCalledWith(expect.objectContaining({name:"history.local_fallback",severity:"info",payload:expect.objectContaining({reason:"gateway-disconnected"})}))}),it("falls back to local jsonl when chat.history times out",async()=>{a("main","s1",[{id:"m1",role:"user",text:"hi"}]);const s=makeGateway({delayMs:500}),o=new LocalSessionHistory({logger:e,openclawHome:t}),n=await loadHistory(s,"agent:main:s1",100,{logger:e,localHistory:o,agentId:"main",sessionId:"s1",rpcTimeoutMs:50});expect(n.length).toBeGreaterThan(0),expect(e.info).toHaveBeenCalledWith(expect.stringContaining("reason=rpc-timeout"))}),it("falls back to local jsonl when chat.history returns empty",async()=>{a("main","s1",[{id:"m1",role:"user",text:"hi"}]);const s=makeGateway({response:{messages:[]}}),o=new LocalSessionHistory({logger:e,openclawHome:t}),n=await loadHistory(s,"agent:main:s1",100,{logger:e,localHistory:o,agentId:"main",sessionId:"s1"});expect(n.length).toBeGreaterThan(0),expect(e.info).toHaveBeenCalledWith(expect.stringContaining("reason=rpc-empty"))}),it("returns [] when both gateway and local are empty",async()=>{const a=makeGateway({response:{messages:[]}}),s=new LocalSessionHistory({logger:e,openclawHome:t}),o=vi.fn(),n=await loadHistory(a,"agent:main:s1",100,{logger:e,localHistory:s,agentId:"main",sessionId:"missing",emitObs:o});expect(n).toEqual([]),expect(e.info).toHaveBeenCalledWith(expect.stringContaining("local-empty")),expect(o).toHaveBeenCalledWith(expect.objectContaining({name:"history.none",severity:"warn",payload:expect.objectContaining({fallbackAvailable:!0})}))}),it("falls back to local on rpc error",async()=>{a("main","s1",[{id:"m1",role:"user",text:"hi"}]);const s=makeGateway({reject:!0}),o=new LocalSessionHistory({logger:e,openclawHome:t}),n=await loadHistory(s,"agent:main:s1",100,{logger:e,localHistory:o,agentId:"main",sessionId:"s1"});expect(n.length).toBeGreaterThan(0),expect(e.info).toHaveBeenCalledWith(expect.stringContaining("reason=rpc-error"))})}),describe("parseGatewayHistory provider error replay",()=>{it("converts assistant stopReason=error + errorMessage (HTML) into a summarised bubble",()=>{const e=parseGatewayHistory({messages:[{role:"user",content:[{type:"text",text:"你好"}],timestamp:17767039e5,__openclaw:{id:"u1",seq:1}},{role:"assistant",content:[],stopReason:"error",errorMessage:"502 <!DOCTYPE html><html><head><title>Bad gateway</title></head><body><h1>Bad gateway</h1><p>Cloudflare</p></body></html>",timestamp:1776703955154,__openclaw:{id:"a1",seq:2}}]});expect(e).toHaveLength(2);const t=e[1];expect(t.role).toBe("assistant"),expect(t.content).toContain("HTTP 502"),expect(t.content).not.toContain("<!DOCTYPE"),expect(t.content).not.toContain("<html"),expect(t.metadata).toMatchObject({status:"error",errorSource:"provider",errorCategory:"gateway",httpStatus:502,stopReason:"error"}),expect(t.metadata?.rawError).toContain("<!DOCTYPE"),expect(t.messageId).toBe("a1")}),it("passes through short plain-text error messages verbatim",()=>{const e=parseGatewayHistory({messages:[{role:"assistant",content:[],stopReason:"error",errorMessage:"rate_limit_exceeded: please slow down",timestamp:1776703955154,__openclaw:{id:"a2",seq:1}}]});expect(e).toHaveLength(1),expect(e[0].content).toBe("rate_limit_exceeded: please slow down"),expect(e[0].metadata).toMatchObject({status:"error",errorSource:"provider",errorCategory:"rate_limit"})}),it("truncates oversized plain-text error bodies",()=>{const e="x".repeat(2e3),t=parseGatewayHistory({messages:[{role:"assistant",content:[],stopReason:"error",errorMessage:e,__openclaw:{id:"a3",seq:1}}]});expect(t).toHaveLength(1),expect(t[0].content.length).toBeLessThan(e.length),expect(t[0].content.endsWith("…")).toBe(!0)}),it("does NOT reformat assistant messages whose normal content happens to contain HTML",()=>{const e="Sure, here is the snippet: <html><body><h1>Hello</h1></body></html>. The <h1> tag is a top-level heading.",t=parseGatewayHistory({messages:[{role:"assistant",content:[{type:"text",text:e}],errorMessage:"502 <html>should be ignored</html>",stopReason:"error",__openclaw:{id:"a5",seq:1}}]});expect(t).toHaveLength(1),expect(t[0].content).toBe(e),expect(t[0].content).toContain("<html>"),expect(t[0].metadata?.status).toBeUndefined(),expect(t[0].metadata?.errorCategory).toBeUndefined()}),it("collapses provider retry chains to a single terminal error entry (parentId linked)",()=>{const e=parseGatewayHistory({messages:[{role:"user",content:[{type:"text",text:"hi"}],__openclaw:{id:"u1",seq:1}},{role:"assistant",content:[],stopReason:"error",errorMessage:"502 <!DOCTYPE html>bad gateway</html>",parentId:"u1",__openclaw:{id:"a1",seq:2}},{role:"assistant",content:[],stopReason:"error",errorMessage:"502 <!DOCTYPE html>bad gateway</html>",parentId:"a1",__openclaw:{id:"a2",seq:3}},{role:"assistant",content:[],stopReason:"error",errorMessage:"502 <!DOCTYPE html>bad gateway</html>",parentId:"a2",__openclaw:{id:"a3",seq:4}},{role:"assistant",content:[],stopReason:"error",errorMessage:"502 <!DOCTYPE html>bad gateway</html>",parentId:"a3",__openclaw:{id:"a4",seq:5}}]});expect(e).toHaveLength(2),expect(e[0].role).toBe("user"),expect(e[1].role).toBe("assistant"),expect(e[1].messageId).toBe("a4"),expect(e[1].content).toContain("HTTP 502");const t=e[1].content.split("HTTP 502").length-1;expect(t).toBe(1)}),it("collapse fallback: missing __openclaw metadata still keeps only the last error in a contiguous run",()=>{const e=parseGatewayHistory({messages:[{role:"user",content:[{type:"text",text:"hi"}]},{role:"assistant",content:[],stopReason:"error",errorMessage:"502 attempt 1"},{role:"assistant",content:[],stopReason:"error",errorMessage:"502 attempt 2 final"}]});expect(e).toHaveLength(2),expect(e[1].content).toBe("502 attempt 2 final")}),it("collapses sibling-style retries where every retry's parent is the same user (not a prior error)",()=>{const e=parseGatewayHistory({messages:[{role:"user",content:[{type:"text",text:"hi"}],__openclaw:{id:"u1",seq:1}},{role:"assistant",content:[],stopReason:"error",errorMessage:"502 attempt 1",parentId:"u1",__openclaw:{id:"a1",seq:2}},{role:"assistant",content:[],stopReason:"error",errorMessage:"502 attempt 2",parentId:"u1",__openclaw:{id:"a2",seq:3}},{role:"assistant",content:[],stopReason:"error",errorMessage:"502 attempt 3",parentId:"u1",__openclaw:{id:"a3",seq:4}},{role:"assistant",content:[],stopReason:"error",errorMessage:"502 attempt 4 final",parentId:"u1",__openclaw:{id:"a4",seq:5}}]}).filter(e=>"error"===e.metadata?.status);expect(e).toHaveLength(1),expect(e[0].messageId).toBe("a4"),expect(e[0].metadata?.rawError).toBe("502 attempt 4 final")}),it("does NOT collapse error chains that are separated by a successful reply",()=>{const e=parseGatewayHistory({messages:[{role:"user",content:[{type:"text",text:"q1"}],__openclaw:{id:"u1",seq:1}},{role:"assistant",content:[],stopReason:"error",errorMessage:"502 first turn",parentId:"u1",__openclaw:{id:"a1",seq:2}},{role:"user",content:[{type:"text",text:"q2"}],parentId:"a1",__openclaw:{id:"u2",seq:3}},{role:"assistant",content:[],stopReason:"error",errorMessage:"503 second turn",parentId:"u2",__openclaw:{id:"a2",seq:4}}]});expect(e).toHaveLength(4),expect(e[1].role).toBe("assistant"),expect(e[1].metadata?.status).toBe("error"),expect(e[3].role).toBe("assistant"),expect(e[3].metadata?.status).toBe("error")}),it("still drops genuinely empty assistant messages (no errorMessage, no content)",()=>{const e=parseGatewayHistory({messages:[{role:"assistant",content:[],__openclaw:{id:"a4",seq:1}}]});expect(e).toHaveLength(0)})}),describe("parseGatewayHistory deterministic ordering (Bug-W)",()=>{const e=[{role:"user",content:[{type:"text",text:"hi"}],timestamp:1776704e6,__openclaw:{id:"u1",seq:1}},{role:"assistant",content:[{type:"text",text:"hello"}],timestamp:1776704001e3,__openclaw:{id:"a1",seq:2}},{role:"user",content:[{type:"text",text:"what time is it"}],timestamp:1776704002e3,__openclaw:{id:"u2",seq:3}},{role:"assistant",content:[{type:"text",text:"3pm"}],timestamp:1776704003e3,__openclaw:{id:"a2",seq:4}}];it("produces the same sequence regardless of input order (shuffled inputs)",()=>{const t=parseGatewayHistory({messages:e}),a=parseGatewayHistory({messages:[...e].reverse()}),s=parseGatewayHistory({messages:[e[2],e[0],e[3],e[1]]});expect(t).toHaveLength(4),expect(a).toEqual(t),expect(s).toEqual(t);for(let e=1;e<t.length;e++)expect(t[e]._seq).toBeGreaterThan(t[e-1]._seq)}),it("preserves original order when any entry is missing __openclaw.seq",()=>{const t=parseGatewayHistory({messages:[e[0],e[1],{role:"assistant",content:[{type:"text",text:"oops"}]},e[2],e[3]]}),a=t.findIndex(e=>"assistant"===e.role&&e.content.includes("oops")),s=t.findIndex(e=>"user"===e.role&&e.content.includes("what time"));expect(a).toBeGreaterThan(-1),expect(s).toBeGreaterThan(a)}),it("sorts within a single turn that was split into multiple JSONL rows",()=>{const e=parseGatewayHistory({messages:[{role:"toolResult",content:[{type:"tool_result",tool_use_id:"tc_1",content:"42"}],timestamp:1776704011e3,__openclaw:{id:"tr1",seq:13}},{role:"user",content:[{type:"text",text:"go"}],timestamp:1776704009e3,__openclaw:{id:"u9",seq:10}},{role:"assistant",content:[{type:"tool_use",id:"tc_1",name:"calc",input:{a:6,b:7}}],timestamp:177670401e4,__openclaw:{id:"a9",seq:12}},{role:"assistant",content:[{type:"text",text:"let me compute"}],timestamp:177670401e4,__openclaw:{id:"a9",seq:11}}]}).map(e=>e._seq);for(let t=1;t<e.length;t++)expect(e[t]).toBeGreaterThanOrEqual(e[t-1])}),it("does not reorder when all seqs are already ascending (no-op path)",()=>{const t=parseGatewayHistory({messages:e}).map(e=>e._seq);expect(t).toEqual([1,2,3,4])})});
@@ -0,0 +1 @@
1
+ import{describe,it,expect,vi,beforeEach}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,loadReplayIdleTimeoutMs:10,cronFlushTimeoutMs:5e3,cronSignalWindowMs:5e3,canvasRelayUrl:"",canvasEnabled:!1,openclawCanvasCompat:!1,messageBus:{enabled:!1,serviceUrl:"",url:"",principalId:"",a2aEnabled:!1}}}function buildCore(){const e=makeLogger(),s=vi.fn(),o=new AcpGatewaySessionState(e),t=vi.fn(),a=new AcpTransport(t,s);return{core:new AcpGatewayBridgeCore({state:o,transport:a,config:makeConfig(),logger:e,writeObs:s,getGateway:()=>null,instanceId:"test-instance"}),state:o,transport:a,logger:e,writeObs:s,sendBridgeMessage:t}}function registerOpenMqSession(e,s,o="session:test-1"){const t={sessionId:o,gatewaySessionKey:`agent:main:${o}`,agentId:"main",createdAt:Date.now(),chatReplayDedupKeys:new Set,assistantMq:new MessageQueue,promptDone:!0};return s.sessions.set(t.sessionId,t),s.sessionsByGatewayKey.set(t.gatewaySessionKey,t),t}async function callSessionLoad(e,s,o){const t={jsonrpc:"2.0",id:s,method:"session/load",params:{sessionId:o}};await e.handleSessionLoad(t)}describe("handleSessionLoad — concurrent load serialization (Bug-AW)",()=>{let e;beforeEach(()=>{e=buildCore()}),it("holds the per-session lock across the full replay lifecycle (no overlap)",async()=>{const s=registerOpenMqSession(e.core,e.state),o=e.core._loadSessionLock,t=vi.spyOn(e.core,"replayCurrentAssistantStream"),a=callSessionLoad(e.core,1,s.sessionId),n=callSessionLoad(e.core,2,s.sessionId);await Promise.resolve(),expect(o.has(s.sessionId)).toBe(!0),await a,await n;const i=e.sendBridgeMessage.mock.calls.filter(e=>void 0!==e[0]?.result);expect(i).toHaveLength(2),expect(i.map(e=>e[0].id).sort()).toEqual([1,2]),expect(t).toHaveBeenCalledTimes(2);const r=[],c=[];t.mockRestore(),vi.spyOn(e.core,"replayCurrentAssistantStream").mockImplementation(async function(...e){const s=Date.now();r.push(s),await new Promise(e=>setTimeout(e,30)),c.push(Date.now())}),e.sendBridgeMessage.mockClear();const l=callSessionLoad(e.core,3,s.sessionId),d=callSessionLoad(e.core,4,s.sessionId);await Promise.all([l,d]),expect(r).toHaveLength(2),expect(c).toHaveLength(2),expect(r[1]).toBeGreaterThanOrEqual(c[0])}),it("releases the lock once replay has finished so later loads can proceed",async()=>{const s=registerOpenMqSession(e.core,e.state),o=e.core._loadSessionLock;await callSessionLoad(e.core,1,s.sessionId),expect(o.has(s.sessionId)).toBe(!1),e.sendBridgeMessage.mockClear(),await callSessionLoad(e.core,2,s.sessionId);const t=e.sendBridgeMessage.mock.calls.filter(e=>void 0!==e[0]?.result);expect(t).toHaveLength(1),expect(t[0][0].id).toBe(2),expect(o.has(s.sessionId)).toBe(!1)}),it("does not deadlock when assistantMq is closed (no replay branch)",async()=>{const s=registerOpenMqSession(e.core,e.state,"session:closed");s.assistantMq.close(),await callSessionLoad(e.core,1,s.sessionId);const o=e.core._loadSessionLock;expect(o.has(s.sessionId)).toBe(!1);const t=e.sendBridgeMessage.mock.calls.filter(e=>void 0!==e[0]?.result);expect(t).toHaveLength(1)})});
@@ -1 +1 @@
1
- export function inferToolKind(t){if(!t)return"other";const e=t.toLowerCase();return e.includes("read")?"read":e.includes("write")||e.includes("edit")?"edit":e.includes("delete")||e.includes("remove")?"delete":e.includes("move")||e.includes("rename")?"move":e.includes("search")||e.includes("find")?"search":e.includes("exec")||e.includes("run")||e.includes("bash")?"execute":e.includes("fetch")||e.includes("http")?"fetch":"other"}export function formatToolTitle(t,e){const n=t??"tool";if(!e||0===Object.keys(e).length)return n;return`${n}: ${Object.entries(e).map(([t,e])=>{const n="string"==typeof e?e:JSON.stringify(e);return`${t}: ${n.length>100?`${n.slice(0,100)}...`:n}`}).join(", ")}`}function serializeArgs(t){return Object.keys(t).length>0?JSON.stringify(t,null,2):""}export function buildToolCallPayload(t){const e=serializeArgs(t.args);return{sessionUpdate:"tool_call",toolCallId:t.toolCallId,name:t.toolName,title:t.title??formatToolTitle(t.toolName,t.args),kind:t.kind??inferToolKind(t.toolName),status:t.status??"in_progress",rawInput:t.args,arguments:e,content:e?[{type:"content",content:{type:"text",text:e}}]:void 0,...t.timestamp?{timestamp:t.timestamp}:{}}}export function buildToolCallUpdatePayload(t){const e=[];t.outputText&&e.push({type:"content",content:{type:"text",text:t.outputText}});for(const n of t.resourceLinks??[])e.push({type:"content",content:{type:"resource_link",uri:n.uri,name:n.name,...n.mimeType?{mimeType:n.mimeType}:{}}});return{sessionUpdate:"tool_call_update",toolCallId:t.toolCallId,name:t.toolName,title:t.toolName,kind:t.kind??inferToolKind(t.toolName),status:t.status??"completed",...void 0!==t.rawOutput?{rawOutput:t.rawOutput}:{},...e.length>0?{content:e}:{},...t.timestamp?{timestamp:t.timestamp}:{}}}
1
+ import{toWireRawOutput}from"./tool-call-raw-output.js";export function inferToolKind(t){if(!t)return"other";const e=t.toLowerCase();return e.includes("read")?"read":e.includes("write")||e.includes("edit")?"edit":e.includes("delete")||e.includes("remove")?"delete":e.includes("move")||e.includes("rename")?"move":e.includes("search")||e.includes("find")?"search":e.includes("exec")||e.includes("run")||e.includes("bash")?"execute":e.includes("fetch")||e.includes("http")?"fetch":"other"}export function formatToolTitle(t,e){const o=t??"tool";if(!e||0===Object.keys(e).length)return o;return`${o}: ${Object.entries(e).map(([t,e])=>{const o="string"==typeof e?e:JSON.stringify(e);return`${t}: ${o.length>100?`${o.slice(0,100)}...`:o}`}).join(", ")}`}function serializeArgs(t){return Object.keys(t).length>0?JSON.stringify(t,null,2):""}export function buildToolCallPayload(t){const e=serializeArgs(t.args),o=e?[{type:"content",content:{type:"text",text:e}}]:void 0;return{sessionUpdate:"tool_call",toolCallId:t.toolCallId,name:t.toolName,title:t.title??formatToolTitle(t.toolName,t.args),kind:t.kind??inferToolKind(t.toolName),status:t.status??"in_progress",rawInput:t.args,arguments:e,...void 0!==o?{content:o}:{},...t.timestamp?{timestamp:t.timestamp}:{}}}export function buildToolCallUpdatePayload(t){const e=[];t.outputText&&e.push({type:"content",content:{type:"text",text:t.outputText}});for(const o of t.resourceLinks??[])e.push({type:"content",content:{type:"resource_link",uri:o.uri,name:o.name,...o.mimeType?{mimeType:o.mimeType}:{}}});const o=toWireRawOutput(t.rawOutput);return{sessionUpdate:"tool_call_update",toolCallId:t.toolCallId,name:t.toolName,title:t.toolName,kind:t.kind??inferToolKind(t.toolName),status:t.status??"completed",...void 0!==o?{rawOutput:o}:{},...e.length>0?{content:e}:{},...t.timestamp?{timestamp:t.timestamp}:{}}}
@@ -0,0 +1 @@
1
+ function isPlainObject(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)&&Object.getPrototypeOf(t)===Object.prototype}export function toWireRawOutput(t){if(!isPlainObject(t))return;const e={...t},r=t.details;if(isPlainObject(r)){const t=r.url;e.details="string"==typeof t?{...r,url:t}:{...r}}return e}
@@ -1 +1 @@
1
- import{acpError}from"../errors/index.js";function normalizeOpts(e){if(null!=e)return"string"==typeof e?{turnId:e}:e}export class AcpTransport{debugIndex=0;sendBridgeMessage;obs;forward;sessionUpdateCounts=new Map;_isReady;sessionUpdateObserver;constructor(e,s,t,r){this.sendBridgeMessage=e,this.obs=s??(()=>{}),this.forward=t??{forwardThinking:!0,forwardToolCalls:!0},this._isReady=r}setSessionUpdateObserver(e){this.sessionUpdateObserver=e}isReady(){return!this._isReady||this._isReady()}get forwardControl(){return this.forward}nextMeta(){return{_debug_index:this.debugIndex++,_ts:Date.now()}}sendResult(e,s){const t=this.nextMeta();this.detectProtocolError(e,s,t._debug_index);const r={jsonrpc:"2.0",id:e,result:this.attachMeta(s,t),_debug_index:t._debug_index,_ts:t._ts};this.sendBridgeMessage(r),this.obs({component:"acp-transport",domain:"reply",name:"rpc.result",severity:"debug",payload:{id:e,_debug_index:t._debug_index}})}sendError(e,s,t,r){const n=this.nextMeta(),o={code:s,message:t};o.data=void 0!==r?this.attachMeta(r,n):{_meta:n};const d={jsonrpc:"2.0",id:e,error:o,_debug_index:n._debug_index,_ts:n._ts};this.sendBridgeMessage(d),this.obs({component:"acp-transport",domain:"reply",name:"rpc.error",severity:"warn",payload:{id:e,code:s,message:t,_debug_index:n._debug_index}})}sendAcpError(e,s,t){const r=acpError(s,t);this.sendError(e,r.code,r.message,r.data)}sendNotification(e,s){const t=this.nextMeta(),r={jsonrpc:"2.0",method:e,params:s,_debug_index:t._debug_index,_ts:t._ts};this.sendBridgeMessage(r)}enrich(e,s){if(!s||!s.turnId&&!s.messageId&&void 0===s.seq)return e;const t={...e};return s.turnId&&(t._turnId=s.turnId),s.messageId&&(t.messageId=s.messageId),void 0!==s.seq&&(t._seq=s.seq),t}sendSessionUpdate(e,s,t){const r=normalizeOpts(t),n=s,o=n?.sessionUpdate;if("agent_thought_chunk"===o&&!this.forward.forwardThinking)return!1;if(("tool_call"===o||"tool_call_update"===o)&&!this.forward.forwardToolCalls)return!1;const d=(this.sessionUpdateCounts.get(e)??0)+1;this.sessionUpdateCounts.set(e,d),d%50==0&&this.obs({component:"acp-transport",domain:"session-update",name:"send.rate",severity:"debug",payload:{sessionId:e,totalSent:d,lastType:o,_debug_index:this.debugIndex}}),this.sendNotification("session/update",{sessionId:e,update:this.enrich(s,r)});try{this.sessionUpdateObserver?.(e,s,r)}catch{}return!0}resetSessionUpdateCount(e){this.sessionUpdateCounts.delete(e)}sendCronSessionUpdate(e,s,t){const r={turnId:t.requestId,messageId:t.messageId,seq:t.seq};this.sendNotification("session/update",{sessionId:e,update:this.enrich(s,r),_meta:{...this.nextMeta(),...t}});try{this.sessionUpdateObserver?.(e,s,r)}catch{}return!0}detectProtocolError(e,s,t){if(!s||"object"!=typeof s)return;const r=s,n="error"in r&&null!=r.error,o="ok"in r&&!1===r.ok;(n||o)&&this.obs({component:"acp-transport",domain:"reply",name:"protocol.error_in_result",severity:"warn",payload:{id:e,_debug_index:t,hasError:n,notOk:o,errorSummary:n?"string"==typeof r.error?r.error.slice(0,200):JSON.stringify(r.error).slice(0,200):void 0}})}attachMeta(e,s){return!e||"object"!=typeof e||Array.isArray(e)?e:{...e,_meta:s}}}
1
+ import{acpError}from"../errors/index.js";function normalizeOpts(e){if(null!=e)return"string"==typeof e?{turnId:e}:e}export class AcpTransport{debugIndex=0;sendBridgeMessage;obs;forward;sessionUpdateCounts=new Map;_isReady;sessionUpdateObserver;constructor(e,s,t,r){this.sendBridgeMessage=e,this.obs=s??(()=>{}),this.forward=t??{forwardThinking:!0,forwardToolCalls:!0},this._isReady=r}setSessionUpdateObserver(e){this.sessionUpdateObserver=e}isReady(){return!this._isReady||this._isReady()}get forwardControl(){return this.forward}nextMeta(){return{_debug_index:this.debugIndex++,_ts:Date.now()}}sendResult(e,s){const t=this.nextMeta();this.detectProtocolError(e,s,t._debug_index);const r={jsonrpc:"2.0",id:e,result:this.attachMeta(s,t),_debug_index:t._debug_index,_ts:t._ts};this.sendBridgeMessage(r),this.obs({component:"acp-transport",domain:"reply",name:"rpc.result",severity:"debug",payload:{id:e,_debug_index:t._debug_index}})}sendError(e,s,t,r){const n=this.nextMeta(),o={code:s,message:t};o.data=void 0!==r?this.attachMeta(r,n):{_meta:n};const d={jsonrpc:"2.0",id:e,error:o,_debug_index:n._debug_index,_ts:n._ts};this.sendBridgeMessage(d),this.obs({component:"acp-transport",domain:"reply",name:"rpc.error",severity:"warn",payload:{id:e,code:s,message:t,_debug_index:n._debug_index}})}sendAcpError(e,s,t){const r=acpError(s,t);this.sendError(e,r.code,r.message,r.data)}sendNotification(e,s){const t=this.nextMeta(),r={jsonrpc:"2.0",method:e,params:s,_debug_index:t._debug_index,_ts:t._ts};this.sendBridgeMessage(r)}enrich(e,s){if(!s||!s.turnId&&!s.messageId&&void 0===s.seq)return e;const t={...e};return s.turnId&&(t._turnId=s.turnId),s.messageId&&(t.messageId=s.messageId),void 0!==s.seq&&(t._seq=s.seq),t}sendSessionUpdate(e,s,t){const r=normalizeOpts(t),n=s,o=n?.sessionUpdate;if("agent_thought_chunk"===o&&!this.forward.forwardThinking)return!1;if(("tool_call"===o||"tool_call_update"===o)&&!this.forward.forwardToolCalls)return!1;const d=(this.sessionUpdateCounts.get(e)??0)+1;this.sessionUpdateCounts.set(e,d),d%50==0&&this.obs({component:"acp-transport",domain:"session-update",name:"send.rate",severity:"debug",payload:{sessionId:e,totalSent:d,lastType:o,_debug_index:this.debugIndex}}),this.sendNotification("session/update",{sessionId:e,update:this.enrich(s,r)});try{this.sessionUpdateObserver?.(e,s,r)}catch{}return!0}sendSessionUpdateStrict(e,s,t){return this.sendSessionUpdate(e,s,t)}resetSessionUpdateCount(e){this.sessionUpdateCounts.delete(e)}sendCronSessionUpdate(e,s,t){const r={turnId:t.requestId,messageId:t.messageId,seq:t.seq};this.sendNotification("session/update",{sessionId:e,update:this.enrich(s,r),_meta:{...this.nextMeta(),...t}});try{this.sessionUpdateObserver?.(e,s,r)}catch{}return!0}detectProtocolError(e,s,t){if(!s||"object"!=typeof s)return;const r=s,n="error"in r&&null!=r.error,o="ok"in r&&!1===r.ok;(n||o)&&this.obs({component:"acp-transport",domain:"reply",name:"protocol.error_in_result",severity:"warn",payload:{id:e,_debug_index:t,hasError:n,notOk:o,errorSummary:n?"string"==typeof r.error?r.error.slice(0,200):JSON.stringify(r.error).slice(0,200):void 0}})}attachMeta(e,s){return!e||"object"!=typeof e||Array.isArray(e)?e:{...e,_meta:s}}}
@@ -1 +1 @@
1
- import{describe,expect,it}from"vitest";import{resolveTurnId}from"./gateway-events.js";function freezeTurnId(e,n){return n&&void 0===e._turnId&&(e._turnId=n),e}describe("resolveTurnId (turnId binding helper)",()=>{it("prefers the gateway runId when present",()=>{expect(resolveTurnId({currentRunId:"run-42",pendingPromptId:"acp-req-1"})).toBe("run-42")}),it("falls back to req:<pendingPromptId> when runId is not yet assigned",()=>{expect(resolveTurnId({pendingPromptId:"acp-req-1"})).toBe("req:acp-req-1"),expect(resolveTurnId({pendingPromptId:7})).toBe("req:7")}),it("returns undefined when neither runId nor pendingPromptId are known",()=>{expect(resolveTurnId({})).toBeUndefined()})}),describe("sendTurnUpdate _turnId freeze (pure replica)",()=>{it("sets _turnId when absent",()=>{const e={sessionUpdate:"agent_message_chunk"};freezeTurnId(e,"run-1"),expect(e._turnId).toBe("run-1")}),it("is idempotent and non-destructive — does not overwrite existing _turnId",()=>{const e={sessionUpdate:"agent_message_chunk",_turnId:"req:acp-3"};freezeTurnId(e,"run-9"),expect(e._turnId).toBe("req:acp-3")}),it("is a no-op when turnId is undefined",()=>{const e={sessionUpdate:"agent_message_chunk"};freezeTurnId(e,void 0),expect(e._turnId).toBeUndefined()})});
1
+ import{describe,expect,it}from"vitest";import{resolveTurnId}from"./gateway-events.js";function freezeTurnId(e,n){return n&&void 0===e._turnId&&(e._turnId=n),e}describe("resolveTurnId (turnId binding helper)",()=>{it("prefers the gateway runId when present",()=>{expect(resolveTurnId({currentRunId:"run-42",pendingPromptId:"acp-req-1"})).toBe("run-42")}),it("falls back to req:<pendingPromptId> when runId is not yet assigned",()=>{expect(resolveTurnId({pendingPromptId:"acp-req-1"})).toBe("req:acp-req-1"),expect(resolveTurnId({pendingPromptId:7})).toBe("req:7")}),it("returns undefined when neither runId nor pendingPromptId are known",()=>{expect(resolveTurnId({})).toBeUndefined()})}),describe("sendTurnUpdate _turnId freeze (pure replica)",()=>{it("sets _turnId when absent",()=>{const e={sessionUpdate:"agent_message_chunk",content:{type:"text",text:""}};freezeTurnId(e,"run-1"),expect(e._turnId).toBe("run-1")}),it("is idempotent and non-destructive — does not overwrite existing _turnId",()=>{const e={sessionUpdate:"agent_message_chunk",content:{type:"text",text:""},_turnId:"req:acp-3"};freezeTurnId(e,"run-9"),expect(e._turnId).toBe("req:acp-3")}),it("is a no-op when turnId is undefined",()=>{const e={sessionUpdate:"agent_message_chunk",content:{type:"text",text:""}};freezeTurnId(e,void 0),expect(e._turnId).toBeUndefined()})});
@@ -1 +1 @@
1
- export const ACP_PROTOCOL_VERSION=1;export const DEFAULT_PROMPT_TIMEOUT_MS=18e5;export const DEFAULT_STREAM_IDLE_TIMEOUT_MS=15e3;export const DEFAULT_STREAM_STALE_TIMEOUT_MS=6e5;export const DEFAULT_LOAD_REPLAY_IDLE_TIMEOUT_MS=15e3;export const DEFAULT_LOAD_REPLAY_HARD_TIMEOUT_MS=6e5;export const DEFAULT_ASSISTANTMQ_LATECLOSE_TIMEOUT_MS=6e4;
1
+ export{ACP_PROTOCOL_VERSION}from"@beeos-ai/beeos-types";export const DEFAULT_PROMPT_TIMEOUT_MS=18e5;export const DEFAULT_STREAM_IDLE_TIMEOUT_MS=15e3;export const DEFAULT_STREAM_STALE_TIMEOUT_MS=6e5;export const DEFAULT_LOAD_REPLAY_IDLE_TIMEOUT_MS=15e3;export const DEFAULT_LOAD_REPLAY_HARD_TIMEOUT_MS=6e5;export const DEFAULT_ASSISTANTMQ_LATECLOSE_TIMEOUT_MS=6e4;
@@ -1 +1 @@
1
- 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_OK",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(t){let e=t,r=!1,n=!0;for(;n;){n=!1;for(const t of METADATA_PREFIX_PATTERNS)t.test(e)&&(e=e.replace(t,""),r=!0,n=!0)}return{line:e,changed:r}}export function stripTransportMetadata(t){const e=t.includes(UNTRUSTED_BLOCK_MARKER),r=t.includes(SENDER_UNTRUSTED_MARKER);if(!(t.includes("[")||t.includes("HEARTBEAT_OK")||t.includes("User Message From")||e||r))return t;if(r){const e=t.replace(SENDER_UNTRUSTED_BLOCK_RE,"").replace(/^\n+/,"").trim();if(e!==t)return e?stripTransportMetadata(e):"";const r=t.indexOf(SENDER_UNTRUSTED_MARKER),n=t.indexOf("\n\n",r),s=-1===n?t.length:n,i=t.slice(s).replace(/^\n+/,"").trim();return i?stripTransportMetadata(i):""}if(e){const e=t.indexOf(UNTRUSTED_BLOCK_MARKER),r=/\nCurrent time:[^\n]*/i.exec(t.slice(e));if(r){const n=e+r.index+r[0].length,s=t.slice(n).replace(/^\n+/,"").trim();return s?stripTransportMetadata(s):""}const n=t.indexOf("\n\n",e),s=-1===n?t.length:n,i=t.slice(s).replace(/^\n+/,"").trim();return i?stripTransportMetadata(i):""}const n=t.split(/\r?\n/),s=[];let i=!1;for(const t of n){const e=stripMetadataPrefixesFromLine(t);HEARTBEAT_OK_LINE_RE.test(e.line.trim())?i=!0:e.changed&&(i=!0,!e.line.trim())||s.push(e.line)}return i?s.join("\n").replace(/^\n+/,"").replace(/\n+$/,""):t}export function normalizeTransportText(t){if(!t)return;const e=stripTransportMetadata(t);return e.length>0?e:void 0}export function isHeartbeatOnlyText(t){const e=stripTransportMetadata(t).trim();return!!e&&HEARTBEAT_OK_LINE_RE.test(e)}const HEARTBEAT_PROMPT_PREFIX="read heartbeat.md if it exists";export function isHeartbeatPromptText(t){return t.slice(0,80).toLowerCase().startsWith(HEARTBEAT_PROMPT_PREFIX)}const CRON_PROMPT_PREFIX_RE=/^\[cron:[0-9a-f-]{8,}\s/i;export function isCronPromptText(t){return CRON_PROMPT_PREFIX_RE.test(t.trimStart())}function isRecord(t){return!!t&&"object"==typeof t&&!Array.isArray(t)}function sanitizeNode(t){if("string"==typeof t){const e=stripTransportMetadata(t);return{value:e,changed:e!==t}}if(Array.isArray(t)){let e=!1;const r=t.map(t=>{const r=sanitizeNode(t);return r.changed&&(e=!0),r.value});return{value:e?r:t,changed:e}}if(!isRecord(t))return{value:t,changed:!1};let e=!1,r=t;if("string"==typeof t.type&&"text"===t.type&&"string"==typeof t.text){const n=stripTransportMetadata(t.text);n!==t.text&&(r={...r,text:n},e=!0)}if(Array.isArray(t.content)){const n=sanitizeNode(t.content);n.changed&&(e||(r={...r}),r.content=n.value,e=!0)}return{value:e?r:t,changed:e}}export function sanitizePromptPayload(t){return sanitizeNode(t).value}
1
+ 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_OK",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(t){let e=t,r=!1,n=!0;for(;n;){n=!1;for(const t of METADATA_PREFIX_PATTERNS)t.test(e)&&(e=e.replace(t,""),r=!0,n=!0)}return{line:e,changed:r}}export function stripTransportMetadata(t){const e=t.includes(UNTRUSTED_BLOCK_MARKER),r=t.includes(SENDER_UNTRUSTED_MARKER);if(!(t.includes("[")||t.includes("HEARTBEAT_OK")||t.includes("User Message From")||e||r))return t;if(r){const e=t.replace(SENDER_UNTRUSTED_BLOCK_RE,"").replace(/^\n+/,"").trim();if(e!==t)return e?stripTransportMetadata(e):"";const r=t.indexOf(SENDER_UNTRUSTED_MARKER),n=t.indexOf("\n\n",r),s=-1===n?t.length:n,i=t.slice(s).replace(/^\n+/,"").trim();return i?stripTransportMetadata(i):""}if(e){const e=t.indexOf(UNTRUSTED_BLOCK_MARKER),r=/\nCurrent time:[^\n]*/i.exec(t.slice(e));if(r){const n=e+r.index+r[0].length,s=t.slice(n).replace(/^\n+/,"").trim();return s?stripTransportMetadata(s):""}const n=t.indexOf("\n\n",e),s=-1===n?t.length:n,i=t.slice(s).replace(/^\n+/,"").trim();return i?stripTransportMetadata(i):""}const n=t.split(/\r?\n/),s=[];let i=!1;for(const t of n){const e=stripMetadataPrefixesFromLine(t);HEARTBEAT_OK_LINE_RE.test(e.line.trim())?i=!0:e.changed&&(i=!0,!e.line.trim())||s.push(e.line)}return i?s.join("\n").replace(/^\n+/,"").replace(/\n+$/,""):t}export function normalizeTransportText(t){if(!t)return;const e=stripTransportMetadata(t);return e.length>0?e:void 0}export function isHeartbeatOnlyText(t){const e=t.trim();if(!e)return!1;if(HEARTBEAT_OK_LINE_RE.test(e))return!0;if(!e.includes("HEARTBEAT_OK"))return!1;return 0===stripTransportMetadata(e).trim().length}const HEARTBEAT_PROMPT_PREFIX="read heartbeat.md if it exists";export function isHeartbeatPromptText(t){return t.slice(0,80).toLowerCase().startsWith(HEARTBEAT_PROMPT_PREFIX)}const CRON_PROMPT_PREFIX_RE=/^\[cron:[0-9a-f-]{8,}\s/i;export function isCronPromptText(t){return CRON_PROMPT_PREFIX_RE.test(t.trimStart())}function isRecord(t){return!!t&&"object"==typeof t&&!Array.isArray(t)}function sanitizeNode(t){if("string"==typeof t){const e=stripTransportMetadata(t);return{value:e,changed:e!==t}}if(Array.isArray(t)){let e=!1;const r=t.map(t=>{const r=sanitizeNode(t);return r.changed&&(e=!0),r.value});return{value:e?r:t,changed:e}}if(!isRecord(t))return{value:t,changed:!1};let e=!1,r=t;if("string"==typeof t.type&&"text"===t.type&&"string"==typeof t.text){const n=stripTransportMetadata(t.text);n!==t.text&&(r={...r,text:n},e=!0)}if(Array.isArray(t.content)){const n=sanitizeNode(t.content);n.changed&&(e||(r={...r}),r.content=n.value,e=!0)}return{value:e?r:t,changed:e}}export function sanitizePromptPayload(t){return sanitizeNode(t).value}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "beeos-claw",
3
- "version": "0.2.40",
3
+ "version": "0.3.0",
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>",
@@ -38,6 +38,7 @@
38
38
  "test:watch": "vitest"
39
39
  },
40
40
  "dependencies": {
41
+ "@beeos-ai/beeos-types": "^0.1.0-beta.4",
41
42
  "@beeos-ai/bridge-client": "^0.1.0",
42
43
  "adm-zip": "^0.5.17",
43
44
  "centrifuge": "^5.5.3",