beeos-claw 0.2.9 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/a2a/tools.js CHANGED
@@ -1 +1 @@
1
- import{agentFetch}from"../agent-auth.js";import{TaskHandleRegistry}from"./task-handle.js";import{resolveAgentIdFromMentions}from"./mention-resolver.js";async function a2aFetch(e,t,r){const a=`${e.agentGatewayUrl}${t}`;return e.agentKeys?agentFetch(a,e.agentKeys,r):fetch(a,r)}export{a2aFetch};const defaultRegistry=new TaskHandleRegistry;export function registerA2ATools(e,t,r=defaultRegistry,a,n,s){e.registerTool({name:"beeos_discover_agents",description:"Find other agents that can help with a task. Returns a list of agents matching the query. Results include your own agents and publicly available agents.",parameters:{type:"object",properties:{query:{type:"string",description:"What capability or skill you are looking for"}},required:["query"]},async execute(e,r){const{query:a}=r;try{const e=await a2aFetch(t,`/api/v1/a2a/discover?query=${encodeURIComponent(a)}&limit=20`);if(!e.ok)return{content:JSON.stringify({error:`discover failed: ${e.status}`})};const r=await e.json();return{content:JSON.stringify(r,null,2)}}catch(e){return{content:JSON.stringify({error:e instanceof Error?e.message:String(e)})}}}}),e.registerTool({name:"beeos_call_agent",description:"Ask another agent to perform a task. The task is sent asynchronously — returns a task ID immediately, and the result will be delivered via a2a_result message on your personal channel when ready.",parameters:{type:"object",properties:{agentId:{type:"string",description:"The target agent UUID (e.g. d04080d1-...) or display name. Prefer the UUID from discover results or @mention metadata when available."},message:{type:"string",description:"The task description or message to send to the agent"},taskId:{type:"string",description:"Optional existing task ID to continue a multi-turn conversation. When provided, the message is appended to the existing task instead of creating a new one."},files:{type:"array",items:{type:"string"},description:"Optional file URLs to include with the request"},contextId:{type:"string",description:"Optional context ID for multi-turn conversations with the same agent"},timeoutMs:{type:"number",description:"Task timeout in milliseconds. Defaults to 600000 (10 minutes). Set higher for long-running tasks."}},required:["agentId","message"]},async execute(e,o){let{agentId:i,message:c,files:l,contextId:d,timeoutMs:g,taskId:p}=o;const u=a?.(e),y=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(!y.test(i)){const r=n?.(e);if(r?.length){const e=resolveAgentIdFromMentions(r,i);e&&(t.logger.info?.(`beeos_call_agent: resolved "${i}" → ${e} via mention context`),i=e)}if(!y.test(i))try{const e=await a2aFetch(t,`/api/v1/a2a/discover?query=${encodeURIComponent(i)}&limit=10`);if(e.ok){const r=await e.json(),a=r?.data??[],n=i.toLowerCase(),s=a.find(e=>e.name.toLowerCase()===n)??a.find(e=>e.name.toLowerCase().includes(n));if(!s)return{content:JSON.stringify({error:`Could not resolve agent name "${i}". Available agents: ${a.map(e=>`${e.name} (${e.id})`).join(", ")||"none"}`})};t.logger.info?.(`beeos_call_agent: resolved "${i}" → ${s.id} (${s.name}) via discover`),i=s.id}}catch{}}const h=d||(u?`session:${u}`:"");try{const e={jsonrpc:"2.0",id:`claw-${Date.now()}`,method:"SendMessage",params:{message:{role:"user",parts:[{text:c}],...h?{contextId:h}:{},...p?{taskId:p}:{}},configuration:{returnImmediately:!0}}},a=`/api/v1/a2a/${encodeURIComponent(i)}`,n=await a2aFetch(t,a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),o=await n.text();let l;try{l=JSON.parse(o)}catch{l={}}if(!n.ok||l.error){if(401===n.status||403===n.status){const e=l.error??{};-32600===e.code&&s&&s("_beeos/auth_required",{type:"auth_required",target_agent_id:i,target_agent_name:i,title:"Authentication Required",content:`Agent **${i}** requires authentication.`})}const e=l.error?JSON.stringify(l.error):o;return{content:JSON.stringify({error:`send task failed: ${n.status} ${e}`})}}const g=l.result,y=g?.id;let f;return y&&(f=r.create(y,i,d,u)),{content:JSON.stringify({result:g,task_handle:f},null,2)}}catch(e){return{content:JSON.stringify({error:e instanceof Error?e.message:String(e)})}}}}),e.registerTool({name:"beeos_complete_task",description:"Complete an A2A task and send the result back to the caller agent. Use this when you have finished processing a task received from another agent.",parameters:{type:"object",properties:{taskId:{type:"string",description:"The task ID to complete"},result:{type:"string",description:"The result text to send back to the caller"},error:{type:"string",description:"If the task failed, provide an error message instead of result"}},required:["taskId"]},async execute(e,r){const{taskId:a,result:n,error:s}=r;try{const e={jsonrpc:"2.0",id:`claw-complete-${Date.now()}`,method:"CompleteTask",params:{task_id:a,result:n??"",error:s??""}},r=await a2aFetch(t,"/api/v1/a2a/_self",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),o=await r.text();let i;try{i=JSON.parse(o)}catch{i={}}if(!r.ok||i.error){const e=i.error?JSON.stringify(i.error):o;return{content:JSON.stringify({error:`complete task failed: ${r.status} ${e}`})}}return{content:JSON.stringify(i.result,null,2)}}catch(e){return{content:JSON.stringify({error:e instanceof Error?e.message:String(e)})}}}}),e.registerTool({name:"beeos_task_status",description:"Check the current status and result of an A2A task you previously sent. Accepts either a task_handle (e.g. bth_1) or a raw task ID.",parameters:{type:"object",properties:{taskId:{type:"string",description:"The task handle or task ID to check"}},required:["taskId"]},async execute(e,a){const{taskId:n}=a,s=r.resolveTaskId(n);try{const e={jsonrpc:"2.0",id:`claw-get-${Date.now()}`,method:"GetTask",params:{id:s}},r=await a2aFetch(t,"/api/v1/a2a/_self",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),a=await r.text();let n;try{n=JSON.parse(a)}catch{n={}}if(!r.ok||n.error){const e=n.error?JSON.stringify(n.error):a;return{content:JSON.stringify({error:`get task failed: ${r.status} ${e}`})}}return{content:JSON.stringify(n.result,null,2)}}catch(e){return{content:JSON.stringify({error:e instanceof Error?e.message:String(e)})}}}}),e.registerTool({name:"beeos_task_cancel",description:"Cancel an A2A task you previously sent. Only the caller can cancel a task. Accepts either a task_handle (e.g. bth_1) or a raw task ID.",parameters:{type:"object",properties:{taskId:{type:"string",description:"The task handle or task ID to cancel"}},required:["taskId"]},async execute(e,a){const{taskId:n}=a,s=r.resolveTaskId(n);try{const e={jsonrpc:"2.0",id:`claw-cancel-${Date.now()}`,method:"CancelTask",params:{id:s}},r=await a2aFetch(t,"/api/v1/a2a/_self",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),a=await r.text();let n;try{n=JSON.parse(a)}catch{n={}}if(!r.ok||n.error){const e=n.error?JSON.stringify(n.error):a;return{content:JSON.stringify({error:`cancel task failed: ${r.status} ${e}`})}}return{content:JSON.stringify(n.result,null,2)}}catch(e){return{content:JSON.stringify({error:e instanceof Error?e.message:String(e)})}}}})}
1
+ import{agentFetch}from"../agent-auth.js";import{resolveAgentIdFromMentions}from"./mention-resolver.js";async function a2aFetch(e,t,n){const r=`${e.agentGatewayUrl}${t}`;return e.agentKeys?agentFetch(r,e.agentKeys,n):fetch(r,n)}export{a2aFetch};export class TaskHandleRegistry{seq=0;handles=new Map;taskIdToHandle=new Map;create(e,t,n,r){const a="bth_"+ ++this.seq;return this.handles.set(a,{taskId:e,agentId:t,contextId:n,sessionKey:r}),this.taskIdToHandle.set(e,a),a}resolveTaskId(e){const t=this.handles.get(e);return t?t.taskId:e}}const defaultRegistry=new TaskHandleRegistry;export function registerA2ATools(e,t,n=defaultRegistry,r,a,s){e.registerTool({name:"beeos_discover_agents",description:"Find other agents that can help with a task. Returns a list of agents matching the query. Results include your own agents and publicly available agents.",parameters:{type:"object",properties:{query:{type:"string",description:"What capability or skill you are looking for"}},required:["query"]},async execute(e,n,r){const{query:a}=n;try{const e=await a2aFetch(t,`/api/v1/a2a/discover?query=${encodeURIComponent(a)}&limit=20`,{signal:r});if(!e.ok)return{content:JSON.stringify({error:`discover failed: ${e.status}`})};const n=await e.json();return{content:JSON.stringify(n,null,2)}}catch(e){if(r?.aborted)throw e;return{content:JSON.stringify({error:e instanceof Error?e.message:String(e)})}}}}),e.registerTool({name:"beeos_call_agent",description:"Ask another agent to perform a task. Waits for the agent to complete the task and returns the result. Timeout defaults to 10 minutes (configurable via timeoutMs).",parameters:{type:"object",properties:{agentId:{type:"string",description:"The target agent UUID (e.g. d04080d1-...) or display name. Prefer the UUID from discover results or @mention metadata when available."},message:{type:"string",description:"The task description or message to send to the agent"},taskId:{type:"string",description:"Optional existing task ID to continue a multi-turn conversation. When provided, the message is appended to the existing task instead of creating a new one."},files:{type:"array",items:{type:"string"},description:"Optional file URLs to include with the request"},contextId:{type:"string",description:"Optional context ID for multi-turn conversations with the same agent"},timeoutMs:{type:"number",description:"Task timeout in milliseconds. Defaults to 600000 (10 minutes). Set higher for long-running tasks."}},required:["agentId","message"]},async execute(e,o,i){let{agentId:c,message:d,files:l,contextId:g,timeoutMs:u,taskId:p}=o;const f=r?.(e),m=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(!m.test(c)){const n=a?.(e);if(n?.length){const e=resolveAgentIdFromMentions(n,c);e&&(t.logger.info?.(`beeos_call_agent: resolved "${c}" → ${e} via mention context`),c=e)}if(!m.test(c))try{const e=await a2aFetch(t,`/api/v1/a2a/discover?query=${encodeURIComponent(c)}&limit=10`,{signal:i});if(e.ok){const n=await e.json(),r=n?.data??[],a=c.toLowerCase(),s=r.find(e=>e.name.toLowerCase()===a)??r.find(e=>e.name.toLowerCase().includes(a));if(!s)return{content:JSON.stringify({error:`Could not resolve agent name "${c}". Available agents: ${r.map(e=>`${e.name} (${e.id})`).join(", ")||"none"}`})};t.logger.info?.(`beeos_call_agent: resolved "${c}" → ${s.id} (${s.name}) via discover`),c=s.id}}catch{}}const h=g||(f?`session:${f}`:""),y=u||6e5;try{const e={jsonrpc:"2.0",id:`claw-${Date.now()}`,method:"SendMessage",params:{message:{role:"user",parts:[{text:d}],...h?{contextId:h}:{},...p?{taskId:p}:{}},configuration:{timeoutMs:y}}},r=`/api/v1/a2a/${encodeURIComponent(c)}`,a=AbortSignal.timeout(y+1e4),o=i?AbortSignal.any([i,a]):a,l=await a2aFetch(t,r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:o}),u=await l.text();let m;try{m=JSON.parse(u)}catch{m={}}if(!l.ok||m.error){if(401===l.status||403===l.status){const e=m.error??{};-32600===e.code&&s&&s("_beeos/auth_required",{type:"auth_required",target_agent_id:c,target_agent_name:c,title:"Authentication Required",content:`Agent **${c}** requires authentication.`})}const e=m.error?JSON.stringify(m.error):u;return{content:JSON.stringify({error:`send task failed: ${l.status} ${e}`})}}const k=m.result,I=k?.id,v=k?.status?.state;if(I&&n.create(I,c,g,f),"completed"===v){const e=k?.artifacts,t=e?.flatMap(e=>e.parts??[]).filter(e=>"text"===e.kind).map(e=>e.text).join("\n");if(t)return{content:t}}if("failed"===v){const e=k?.status,t=e?.message?.parts,n=t?.[0]?.text??"task failed";return{content:JSON.stringify({error:n})}}return{content:JSON.stringify(k,null,2)}}catch(e){if(i?.aborted)throw e;return e instanceof DOMException&&"TimeoutError"===e.name?{content:JSON.stringify({error:`task timed out after ${y}ms`,agent:c})}:{content:JSON.stringify({error:e instanceof Error?e.message:String(e)})}}}}),e.registerTool({name:"beeos_complete_task",description:"Complete an A2A task and send the result back to the caller agent. Use this when you have finished processing a task received from another agent.",parameters:{type:"object",properties:{taskId:{type:"string",description:"The task ID to complete"},result:{type:"string",description:"The result text to send back to the caller"},error:{type:"string",description:"If the task failed, provide an error message instead of result"}},required:["taskId"]},async execute(e,n,r){const{taskId:a,result:s,error:o}=n;try{const e={jsonrpc:"2.0",id:`claw-complete-${Date.now()}`,method:"CompleteTask",params:{task_id:a,result:s??"",error:o??""}},n=await a2aFetch(t,"/api/v1/a2a/_self",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:r}),i=await n.text();let c;try{c=JSON.parse(i)}catch{c={}}if(!n.ok||c.error){const e=c.error?JSON.stringify(c.error):i;return{content:JSON.stringify({error:`complete task failed: ${n.status} ${e}`})}}return{content:JSON.stringify(c.result,null,2)}}catch(e){if(r?.aborted)throw e;return{content:JSON.stringify({error:e instanceof Error?e.message:String(e)})}}}})}
@@ -1 +1 @@
1
- import{randomUUID,createHash}from"node:crypto";import{sanitizePromptPayload,stripTransportMetadata}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{buildResolutionPlan,resolveResources,applyResolutions}from"./prompt-resource-resolver.js";import{readUploadToolResult}from"../upload/result-cache.js";import{BEEOS_UPLOAD_TOOL_NAME}from"../upload/tool.js";import{buildToolResultSessionContentBlocks}from"./tool-result-payload-strategies.js";import{Errors}from"../errors/index.js";import{formatFriendlyError}from"../errors/classify.js";import{resolveChannelFromSessionKey}from"../channel-detection.js";import{ACP_PROTOCOL_VERSION,DEFAULT_PROMPT_TIMEOUT_MS,DEFAULT_LOAD_REPLAY_IDLE_TIMEOUT_MS,DEFAULT_LOAD_REPLAY_HARD_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-"];function isBackgroundSessionKey(e){return BACKGROUND_SESSION_PATTERNS.some(s=>e.includes(s))}function isSystemDefaultSessionKey(e){const s=e.split(":");if(s.length<3||"agent"!==s[0])return!1;const t=s.slice(2).join(":");return"main"===t||t===s[1]}function cleanGatewayDerivedTitle(e){if(!e)return;let s=stripTransportMetadata(e);return/^\[System\b/.test(s)?void 0:(s=s.trim(),s||void 0)}function resolveStandaloneSlashCommandName(e,s){if(0===e.length)return;if(e.some(e=>"text"!==e.type))return;const t=s.trim();if(!t||t.includes("\n")||!t.startsWith("/"))return;const n=t.match(/^\/([^\s:]+)(?::|\s|$)/)?.[1]?.trim();return n&&!n.includes("/")&&SLASH_COMMAND_NAME_RE.test(n)?n.toLowerCase():void 0}function deriveSessionId(e,s){const t=createHash("sha256").update(`${s}:${e}`).digest("hex").substring(0,32);return`session:${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`}function parseAgentIdFromKey(e){const s=e.split(":");return(s.length>=3&&"agent"===s[0]?s[1]:"")||"main"}function createSessionObject(e){const s=parseAgentIdFromKey(e.gatewayKey);return{sessionId:deriveSessionId(e.gatewayKey,e.instanceId),gatewaySessionKey:e.gatewayKey,agentId:s,platformAgentId:e.resolvePlatformAgentId?.(s),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;initialized=!1;agentMapping=null;_syncResolvers=[];_mappingReadyCallbacks=[];setAgentMapping(e){this.agentMapping=e;for(const s of this.state.sessions.values())!s.platformAgentId&&s.agentId&&(s.platformAgentId=e.get(s.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(s=>{this._syncResolvers.push(s);const t=setTimeout(()=>{const e=this._syncResolvers.indexOf(s);-1!==e&&this._syncResolvers.splice(e,1),s()},e);"object"==typeof t&&"unref"in t&&t.unref()})}handleTerminalRequest=null;handleTerminalNotification=null;onRunComplete=null;onRunFailed=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}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)}ensureSessionForKey(e){const s=this.state.findSessionByKey(e);if(s)return s;const t=createSessionObject({gatewayKey:e,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels});return this.registerSession(t),this.logger.debug?.(`[bridge-core] ensureSessionForKey: lazily created session sid=${t.sessionId} key=${e}`),t}async preloadSessionsFromGateway(){const e=this.getGateway();if(e?.isConnected)try{const s=await e.sessionsList();if(!s||"object"!=typeof s)return;const t=s.sessions;if(!Array.isArray(t))return;let n=0;for(const e of t){const s=e,t=s.sessionKey??s.key??s.id??s.name;if(!t||"string"!=typeof t)continue;if(this.state.findSessionByKey(t))continue;const i=s.label||s.derivedTitle||s.title||void 0,o=createSessionObject({gatewayKey:t,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,title:i||"New chat"});this.registerSession(o),n++}n>0&&this.logger.info?.(`[bridge-core] preloadSessions: loaded ${n} session(s) from gateway`)}catch(e){this.logger.debug?.("[bridge-core] preloadSessions failed:",e)}else this.logger.debug?.("[bridge-core] preloadSessions skipped: gateway not connected")}async handleRequest(e){this.writeObs({component:"bridge-core",domain:"forward",name:`rpc.request.${e.method}`,severity:"debug",payload:{id:e.id,method:e.method}});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"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(s){this.transport.sendAcpError(e.id,Errors.InternalError,{message:s instanceof Error?s.message:"Internal error"})}}handleCanvasNotification=null;getCanvasState=null;onSessionLoaded=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 s=e.params,t=s?.surfaceId,n=this.state.resolveSessionFromParams(s);if(!n){this.logger.warn?.(`[bridge-core] canvas/reference ignored — no session found for sessionId=${s?.sessionId}`);break}n.referencedSurfaceId=t||void 0,this.logger.debug?.(`[bridge-core] Canvas reference ${t?"set":"cleared"}: ${t??"(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 s=this.transport.forwardControl;!1===e.params?.forwardThinking&&(s.forwardThinking=!1),!1===e.params?.forwardToolCalls&&(s.forwardToolCalls=!1),this.transport.sendResult(e.id,{protocolVersion:ACP_PROTOCOL_VERSION,agentCapabilities:{loadSession:!0,skills:!0,promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},sessionCapabilities:{list:{},"web-ssh":!!this.config.bridge.shell.enabled,canvas:!!this.config.canvasEnabled,cron:!0},mcp:{}},agentInfo:{name:"beeos-claw",title:"BeeOS Agent Bridge",version:"0.1.0"},_meta:{},authMethods:[]})}async handleSessionNew(e){const s=`agent:${"string"==typeof e.params?.agentId&&e.params.agentId||this.config.gateway.agentId||this.getDefaultAgentId()}:${randomUUID()}`,t="string"==typeof e.params?.cwd?e.params.cwd:".",n=createSessionObject({gatewayKey:s,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,cwd:t});this.registerSession(n),this.transport.sendResult(e.id,{sessionId:n.sessionId,modes:{availableModes:[{...DEFAULT_MODE}],currentModeId:DEFAULT_MODE.id},_meta:{sessionKey:s,agentId:n.agentId,platformAgentId:n.platformAgentId??null}}),this.fetchHistoryInBackground(s)}fetchHistoryInBackground(e){const s=this.getGateway();s?.isConnected&&loadHistory(s,e,50).catch(e=>{this.logger.debug?.(`[bridge-core] Background history fetch failed: ${e instanceof Error?e.message:e}`)})}async recoverSessionFromGateway(e){const s=this.getGateway();if(s?.isConnected)try{const t=await s.sessionsList();if(!t||"object"!=typeof t)return;const n=t.sessions;if(!Array.isArray(n))return;for(const s of n){const t=s,n=t.sessionKey??t.key??t.id??t.name;if(n&&"string"==typeof n&&deriveSessionId(n,this.instanceId)===e){const e=createSessionObject({gatewayKey:n,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels});return this.registerSession(e),e}}}catch(e){this.logger.debug?.("[bridge-core] recoverSessionFromGateway failed:",e)}}async resolveOrCreateSession(e){let s=this.state.sessions.get(e);if(!s&&e.startsWith("agent:")&&(s=this.state.findSessionByKey(e)),s||e.startsWith("agent:")||(s=await this.recoverSessionFromGateway(e)),s)return{session:s,created:!1};const t=e.startsWith("agent:"),n=this.config.gateway.agentId||this.getDefaultAgentId();return s=createSessionObject({gatewayKey:t?e:`agent:${n}:${e}`,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels}),this.registerSession(s),{session:s,created:!0}}async handleSessionLoad(e){const s=e.params?.sessionId;if(!s)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const{session:t}=await this.resolveOrCreateSession(s),n=t.sessionId;this.state.lastActiveSessionId=n,t.chatReplayDedupKeys.clear();try{const e=this.getGateway(),s=await loadHistory(e,t.gatewaySessionKey,50),i=groupIntoTurns(s),o=i.filter(e=>"user"===e.role).length,a=i.filter(e=>"assistant"===e.role).length,r=i.filter(e=>e.toolCalls?.length).length,d=i.reduce((e,s)=>e+(s.toolCalls?.length??0),0);this.logger.debug?.(`[bridge-core] handleSessionLoad sid=${n} messages=${s.length} turns=${i.length} userTurns=${o} asstTurns=${a} turnsWithToolCalls=${r} totalToolCalls=${d}`);for(let e=0;e<i.length;e++){const s=i[e];if("user"!==s.role||"internal_system"!==s.provenance?.kind)if("system"!==s.role){if(this.logger.debug?.(`[bridge-core] SENDING history_turn[${e}] role=${s.role} contentLen=${s.content.length} content=${JSON.stringify(s.content.slice(0,80))} tcCount=${s.toolCalls?.length??0}`),"user"===s.role)this.replayUserTurnAsChunks(n,s.content,s.metadata);else{const e={sessionUpdate:"history_turn",role:s.role,content:s.content,reasoning:s.reasoning,toolCalls:s.toolCalls};s.metadata&&(e.metadata=s.metadata),this.transport.sendSessionUpdate(n,e)}if("assistant"===s.role){if(s.files?.length)for(const e of s.files)this.transport.sendSessionUpdate(n,{sessionUpdate:"agent_message_chunk",content:{type:"resource_link",uri:e.uri,...e.name?{name:e.name}:{},...e.mimeType?{mimeType:e.mimeType}:{}}});s.toolCalls?.length&&await this.replayUploadFileBlocks(n,s.toolCalls)}}else this.logger.debug?.(`[bridge-core] SENDING system_message[${e}] contentLen=${s.content.length}`),this.transport.sendSessionUpdate(n,{sessionUpdate:"system_message_chunk",content:{type:"text",text:s.content},metadata:s.metadata});else 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 i=()=>{this.transport.sendResult(e.id,{sessionId:n}),this.onSessionLoaded?.(n,t.gatewaySessionKey,t.platformAgentId),this.pushSkillsList().catch(e=>{this.logger.warn?.(`[bridge-core] pushSkillsList failed: ${e instanceof Error?e.message:e}`)})};void 0!==t.pendingPromptId&&!t.promptDone&&t.assistantMq&&!t.assistantMq.closed?this.replayCurrentAssistantStream(t).catch(e=>{this.logger.warn?.(`[bridge-core] replayCurrentAssistantStream failed: ${e instanceof Error?e.message:e}`)}).finally(i):i()}async replayUploadFileBlocks(e,s){for(const t of s){if(t.name!==BEEOS_UPLOAD_TOOL_NAME)continue;let s=[];try{const e=await readUploadToolResult(t.id);e&&(s=buildToolResultSessionContentBlocks(t.name,e))}catch{}if(0===s.length){const e=extractBeeosFileUrisFromOutput(t.output);for(const t of e)s.push({type:"content",content:{type:"resource_link",uri:t,name:"file"}})}const n=s.filter(e=>"resource_link"===e.content?.type);for(const s of n)this.transport.sendSessionUpdate(e,{sessionUpdate:"agent_message_chunk",content:s.content});n.length>0&&this.logger.debug?.(`[bridge-core] replayUploadFileBlocks tcId=${t.id} sent ${n.length} resource_link block(s)`)}}async replayCurrentAssistantStream(e){if(!e.assistantMq||e.assistantMq.closed)return;const s=this.config.loadReplayIdleTimeoutMs??DEFAULT_LOAD_REPLAY_IDLE_TIMEOUT_MS,t=Date.now()+DEFAULT_LOAD_REPLAY_HARD_TIMEOUT_MS;let n=0;for(;Date.now()<t&&(e.currentRunId||e.pendingPromptId)&&!e.assistantMq.closed;){const t=await Promise.race([e.assistantMq.read(n),new Promise(e=>setTimeout(()=>e(null),s))]);if(!t||0===t.length){if(void 0!==e.pendingPromptId&&!e.promptDone)continue;break}for(const s of t)this.transport.sendSessionUpdate(e.sessionId,s),n++}n>0&&this.writeObs({component:"bridge-core",domain:"lifecycle",name:"session.load.replay_complete",severity:"debug",payload:{sessionId:e.sessionId,replayed:n}})}async handleSessionList(e){const s=[];for(const[,e]of this.state.sessions)s.push({sessionId:e.sessionId,title:e.title||"New chat",cwd:e.cwd,updatedAt:e.lastStreamActivityTs??e.createdAt,agentId:e.agentId,platformAgentId:e.platformAgentId,deletable:!isSystemDefaultSessionKey(e.gatewaySessionKey)});const t=this.getGateway();if(t?.isConnected)try{const e=await t.sessionsList();if(e&&"object"==typeof e&&Array.isArray(e.sessions)){const t=e.sessions;for(const e of t){const t=e,n=t.sessionKey??t.key??t.id??t.name;if(!n||"string"!=typeof n)continue;if(isBackgroundSessionKey(n))continue;const i=deriveSessionId(n,this.instanceId),o=s.find(e=>e.sessionId===n||e.sessionId===i||this.state.sessions.get(e.sessionId)?.gatewaySessionKey===n),a=t.label||cleanGatewayDerivedTitle(t.derivedTitle)||t.title||void 0,r=t.model,d=t.modelProvider;if(o){if(!o.title||"New chat"===o.title){const e=a||o.sessionId;o.title=e;const s=this.state.sessions.get(o.sessionId);s&&!s.title&&(s.title=e)}const e=t.updatedAt;e&&(o.updatedAt=e),r&&(o.model=r),d&&(o.modelProvider=d)}else{const e=createSessionObject({gatewayKey:n,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,cwd:t.cwd,title:a||"New chat"});this.registerSession(e),s.push({sessionId:e.sessionId,title:a||"New chat",cwd:t.cwd,updatedAt:t.updatedAt,agentId:e.agentId,platformAgentId:e.platformAgentId,deletable:!isSystemDefaultSessionKey(n),model:r,modelProvider:d})}}}}catch(e){this.logger.debug?.("[bridge-core] sessions.list enrichment failed:",e)}s.sort((e,s)=>(s.updatedAt??0)-(e.updatedAt??0)||e.sessionId.localeCompare(s.sessionId)),this.transport.sendResult(e.id,{sessions:s})}handleSessionRename(e){const s=e.params?.sessionId,t=e.params?.title;if(!s||!t)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId, title"});const n=t.slice(0,64),i=this.state.sessions.get(s);if(!i)return void this.transport.sendAcpError(e.id,Errors.SessionNotFound);i.title=n;const o=i.gatewaySessionKey,a=this.getGateway();a?.isConnected&&a.sessionsPatch(o,{label:n}).catch(e=>{this.logger.debug?.(`[bridge-core] sessionsPatch (rename) failed: ${e instanceof Error?e.message:e}`)}),this.transport.sendResult(e.id,{sessionId:s,title:n})}async handleSessionDelete(e){const s=e.params?.sessionId;if(!s)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const t=this.state.sessions.get(s);if(!t)return this.logger.info?.(`[bridge-core] session/delete sessionId=${s} NOT FOUND in local state`),void this.transport.sendAcpError(e.id,Errors.SessionNotFound);const n=t.gatewaySessionKey;this.logger.info?.(`[bridge-core] session/delete sessionId=${s} gatewayKey=${n} gwConnected=${!!this.getGateway()?.isConnected}`);let i=!1;const o=this.getGateway();if(o?.isConnected&&n)try{await o.sessionsDelete(n),i=!0,this.logger.info?.(`[bridge-core] Gateway sessions.delete SUCCESS for key=${n}`)}catch(s){const t=s instanceof Error?s.message:String(s);if(this.logger.info?.(`[bridge-core] Gateway sessions.delete FAILED for key=${n}: ${t}`),!t.includes("Cannot delete the main session"))return void this.transport.sendResult(e.id,{deleted:!1});try{await o.sessionsReset(n),i=!0,this.logger.info?.(`[bridge-core] Gateway sessions.reset SUCCESS for key=${n}`)}catch(s){return this.logger.warn?.(`[bridge-core] Gateway sessions.reset also failed for key=${n}: ${s instanceof Error?s.message:s}`),void this.transport.sendResult(e.id,{deleted:!1})}}else n&&this.logger.warn?.(`[bridge-core] Gateway not connected, proceeding with local-only delete for key=${n}`);void 0!==t.pendingPromptId&&this.failPrompt(t,Errors.SessionDeleted.rpcCode,Errors.SessionDeleted.message),this.state.clearPromptTimeout(t),this.state.clearStreamIdleTimer(t),t.assistantMq?.close(),t.currentRunId&&this.state.promptsByRunId.delete(t.currentRunId);const a=new Set;for(const[e,t]of this.state.toolCallToSessionMap)t===s&&(this.state.toolCallToSessionMap.delete(e),a.add(e));for(const[e,s]of this.state.toolCallIdMap)a.has(s)&&this.state.toolCallIdMap.delete(e);this.state.sessions.delete(s),this.state.sessionsByGatewayKey.delete(n),this.transport.resetSessionUpdateCount(s),i&&this.onSessionDeleted?.(n),this.logger.info?.(`[bridge-core] session/delete DONE sessionId=${s} gatewayKey=${n} deleted=true`),this.transport.sendResult(e.id,{deleted:!0})}async handleSessionClear(e){this.logger.info?.(`[bridge-core] handleSessionClear called, params=${JSON.stringify(e.params)}`);const s=e.params?.sessionId;if(!s)return this.logger.warn?.("[bridge-core] session/clear missing sessionId"),void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const t=this.state.sessions.get(s);if(!t)return this.logger.warn?.(`[bridge-core] session/clear sessionId=${s} not found in state`),void this.transport.sendAcpError(e.id,Errors.SessionNotFound);this.logger.info?.(`[bridge-core] session/clear sessionId=${s} gatewayKey=${t.gatewaySessionKey}`);const n=this.getGateway();if(n?.isConnected&&t.gatewaySessionKey)try{await n.sessionsReset(t.gatewaySessionKey),this.logger.info?.(`[bridge-core] Gateway sessions.reset SUCCESS for key=${t.gatewaySessionKey}`)}catch(e){this.logger.warn?.(`[bridge-core] Gateway sessions.reset FAILED for key=${t.gatewaySessionKey}: ${e instanceof Error?e.message:e}`)}else this.logger.warn?.(`[bridge-core] session/clear skipped gateway reset: connected=${n?.isConnected}, key=${t.gatewaySessionKey}`);t.chatReplayDedupKeys.clear(),this.logger.info?.("[bridge-core] session/clear dedupKeys cleared, calling onSessionCleared"),this.onSessionCleared?.(s,t.gatewaySessionKey),this.transport.sendResult(e.id,{cleared:!0}),this.logger.info?.("[bridge-core] session/clear DONE, sent cleared=true")}async handleSessionSetMode(e){const s=e.params?.sessionId,t=e.params?.mode,n=s?this.state.sessions.get(s):void 0,i=this.getGateway();if(n&&i?.isConnected&&t){const e={};if("verbose"===t||"detailed"===t?e.verboseLevel="full":"concise"!==t&&"default"!==t||(e.verboseLevel="default"),"reasoning"!==t&&"thinking"!==t||(e.reasoningLevel="stream"),Object.keys(e).length>0)try{await i.sessionsPatch(n.gatewaySessionKey,e)}catch(e){this.logger.warn?.(`[bridge-core] sessions.patch failed: ${e instanceof Error?e.message:e}`)}}this.transport.sendResult(e.id,{mode:t??"default"})}async handleSessionSetModel(e){const s=e.params?.sessionId,t=e.params?.model,n=s?this.state.sessions.get(s):void 0,i=this.getGateway();let o=t??null,a=null;if(n&&i?.isConnected&&t)try{const e=await i.sessionsPatch(n.gatewaySessionKey,{model:t}),s=e?.resolved;s?.model&&(o=s.model),s?.modelProvider&&(a=s.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:a})}async handleModelsList(e){const s=this.getGateway();if(s?.isConnected)try{const t=await s.request("models.list",{});this.transport.sendResult(e.id,t??{models:[]})}catch(s){this.transport.sendAcpError(e.id,Errors.InternalError,{message:`Failed to list models: ${s instanceof Error?s.message:s}`})}else this.transport.sendAcpError(e.id,Errors.GatewayNotConnected)}async handleSkillsList(e){const s=await this.fetchSimplifiedSkills();this.transport.sendResult(e.id,{skills:s})}async fetchSimplifiedSkills(){const e=this.getGateway();if(!e?.isConnected)return[];try{const s=await e.skillsStatus();return s?.skills?s.skills.filter(e=>!1!==e.eligible&&!0!==e.disabled).sort((e,s)=>e.always&&!s.always?-1:!e.always&&s.always?1:e.name.localeCompare(s.name)).map(e=>({name:e.name,description:e.description,emoji:e.emoji,always:e.always||void 0,bundled:e.bundled||void 0})):[]}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}})}async handleSessionPrompt(e){const s=e.params?.sessionId,t=e.params?.prompt;if(!s||!t)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId, prompt"});const{session:n,created:i}=await this.resolveOrCreateSession(s);i&&this.onSessionLoaded?.(n.sessionId,n.gatewaySessionKey,n.platformAgentId);const o=n.sessionId;this.state.lastActiveSessionId=o,this.onPromptStart?.();const a=this.getGateway();if(!a?.isConnected)return void this.transport.sendAcpError(e.id,Errors.GatewayNotConnected);let r=extractPromptBlocks(sanitizePromptPayload(t));if(!n.title){const e=r.find(e=>"text"===e.type&&e.text);e&&"text"in e&&e.text&&(n.title=e.text.slice(0,64).replace(/\n/g," ").trim(),a?.isConnected&&n.title&&a.sessionsPatch(n.gatewaySessionKey,{label:n.title}).catch(e=>{this.logger.debug?.(`[bridge-core] sessionsPatch (title) failed: ${e instanceof Error?e.message:e}`)}))}const d=buildResolutionPlan(r);if(d.refs.length>0)try{const e=await resolveResources(d,this.writeObs);r=applyResolutions(r,e)}catch(e){this.logger.warn?.(`[bridge-core] Resource pre-resolution failed: ${e instanceof Error?e.message:e}`)}let l;if(this.beeosFileResolver){const e=this.beeosFileResolver.buildResolutionPlan(r);if(e.refs.length>0)try{l=await this.beeosFileResolver.resolveMetadataForPrompt(e)}catch(e){this.logger.warn?.(`[bridge-core] BeeOS file resolution failed: ${e instanceof Error?e.message:e}`)}}const c=toGatewayPrompt(r,{beeosFileResolutionsByUri:l});if("error"in c)return void this.transport.sendAcpError(e.id,Errors.PromptConvertFailed,{message:c.error});const{message:h,attachments:g}=c,m=resolveStandaloneSlashCommandName(r,h)??resolveSlashCmd(r,h),p="string"==typeof m;if(m&&this.handleSlashCommand){const s=this;if(await(async()=>{try{return await s.handleSlashCommand(m)}catch(e){return s.logger.warn?.(`[bridge-core] /${m} handler failed: ${e instanceof Error?e.message:e}`),!1}})())return this.emitPromptAsUserSessionUpdates(n.sessionId,r),this.transport.sendSessionUpdate(o,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Loading ${m}...`}}),void this.transport.sendResult(e.id,{stopReason:"end_turn"})}const u=p?"chat.send":"agent";let f=p?h:withUserMessagePrefix(h);const y=this.config.canvasEnabled&&!p&&!1!==n.canvasActive&&!n.channelType;if(y){const e=n.promptsSinceCanvasInjection??0;!n.canvasPromptInjected||e>=10?(f=`${CANVAS_TERM_MAPPING}\n\n${f}`,n.canvasPromptInjected=!0,n.promptsSinceCanvasInjection=0,this.logger.debug?.("[bridge-core] Canvas term mapping injected (re-inject cycle)")):n.promptsSinceCanvasInjection=e+1}if(y){const e=this.getCanvasState?.();if(e){const s=e.resolveCanvasForSession(n.gatewaySessionKey);f=`${buildActiveSurfacesContext(e,s)??"[Canvas] Canvas panel is available. Use render_ui for structured/visual content."}\n\n${f}`}const s=n.referencedSurfaceId;s&&(f=`${CANVAS_UPDATE_HINT}\n[IMPORTANT: The user selected canvas surface "${s}" for editing. You MUST call render_ui with id="${s}" to UPDATE this existing surface. Do NOT create a new surface with a different id.]\n${f}`,n.referencedSurfaceId=void 0)}if(!p){const s=parseMentionsParam(e.params?.mentions);if(s.length>0){n.activeMentions=s;f=`${buildMentionInstruction(s)}\n${f}`,this.logger.debug?.(`[bridge-core] A2A mention instruction injected for ${s.length} agent(s)`)}else n.activeMentions=void 0}p&&this.logger.info?.(`[bridge-core] slash command passthrough sessionId=${o} command=/${m}`),this.state.resetForNewRun(n,o,this.transport),n.pendingPromptId=e.id,n.gatewayMethod=u,this.emitPromptAsUserSessionUpdates(o,r),this.transport.sendSessionUpdate(o,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:""}}),this.schedulePromptTimeout(n);try{const e=g.length>0?g.map(e=>({type:e.type,content:e.content,...e.mimeType?{mimeType:e.mimeType}:{},...e.fileName?{fileName:e.fileName}:{}})):void 0;let s;s=p?await a.chatSend(n.gatewaySessionKey,f,e):await a.agentSend(n.gatewaySessionKey,f,n.agentId||this.config.gateway.agentId||this.getDefaultAgentId(),e),n.currentRunId=s.runId,n.assistantStreamStartedAt=Date.now(),this.state.promptsByRunId.set(s.runId,n)}catch(s){this.state.clearPromptTimeout(n),void 0!==n.pendingPromptId&&(n.pendingPromptId=void 0,n.assistantMq?.close(),this.transport.sendAcpError(e.id,Errors.SendFailed,{message:s instanceof Error?s.message:"failed to send prompt to gateway"})),n.pendingAgentSends?.length&&(this.logger.warn?.("[bridge-core] Discarding %d deferred agentSends after prompt send failure",n.pendingAgentSends.length),n.pendingAgentSends=void 0)}}replayUserTurnAsChunks(e,s,t){const n=splitUserReplayBlocks(s);for(const s of n){let n;if("text"===s.type){if(!s.text)continue;n={type:"text",text:s.text}}else n="resource_link"===s.type?{type:"resource_link",uri:s.uri??"",...s.fileName?{name:s.fileName}:{},...s.mimeType?{mimeType:s.mimeType}:{}}:{type:s.type,...s.mimeType?{mimeType:s.mimeType}:{},...s.fileName?{fileName:s.fileName}:{}};this.transport.sendSessionUpdate(e,{sessionUpdate:"user_message_chunk",content:n,...t?{metadata:t}:{}})}}emitPromptAsUserSessionUpdates(e,s){for(const t of s){const s=this.toUserSessionUpdateContent(t);s&&this.transport.sendSessionUpdate(e,{sessionUpdate:"user_message_chunk",content:s})}}toUserSessionUpdateContent(e){if("text"===e.type){if(!e.text)return;return{type:"text",text:e.text}}if("image"===e.type){const s=e.mimeType??e.mime_type??"application/octet-stream",t=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}:{},...s?{mimeType:s}:{},...t?{fileName:t}:{}}}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 s=e.mimeType??e.mime_type??"application/octet-stream",t=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}:{},...s?{mimeType:s}:{},...t?{fileName:t}:{}}}if("resource"===e.type){const s=e.resource??{},t=s.uri??e.uri,n=s.mimeType??s.mime_type??e.mimeType??e.mime_type,i=s.text??e.text,o=s.data??e.data,a=s.fileName??s.file_name??s.filename??s.name??e.fileName??e.file_name??e.filename??e.name;if(!t&&!i&&!o)return;return{type:"resource",resource:{...t?{uri:t}:{},...n?{mimeType:n}:{},...i?{text:i}:{},...o?{data:o}:{},...a?{fileName:a}:{}}}}}handleSessionCancel(e,s){const t=s?.sessionId;if(!t)return void(void 0!==e&&this.transport.sendAcpError(e,Errors.MissingParam,{param:"sessionId"}));const n=this.state.sessions.get(t);if(!n)return void(void 0!==e&&this.transport.sendAcpError(e,Errors.SessionNotFound));const i=this.getGateway();i?.isConnected&&n.currentRunId&&i.chatAbort(n.gatewaySessionKey,n.currentRunId).catch(e=>{this.logger.debug?.(`[bridge-core] chatAbort failed: ${e instanceof Error?e.message:e}`)}),this.completePrompt(n,"cancelled"),void 0!==e&&this.transport.sendResult(e,{})}schedulePromptTimeout(e){this.state.clearPromptTimeout(e);const s=this.config.promptTimeoutMs??DEFAULT_PROMPT_TIMEOUT_MS;s<=0||(e.promptTimeoutTimer=setTimeout(()=>{void 0!==e.pendingPromptId&&(this.logger.warn?.(`[bridge-core] Prompt timed out sessionId=${e.sessionId} after ${s}ms`),this.failPrompt(e,Errors.PromptTimeout.rpcCode,`Prompt timed out after ${s}ms`))},s),"object"==typeof e.promptTimeoutTimer&&"unref"in e.promptTimeoutTimer&&e.promptTimeoutTimer.unref())}cleanupPrompt(e){this.state.clearPromptTimeout(e),this.state.clearStreamIdleTimer(e);const s=e.currentRunId;if(s){this.state.promptsByRunId.delete(s);const e=`tc_${s}_`;for(const[s,t]of this.state.toolCallIdMap)t.startsWith(e)&&this.state.toolCallIdMap.delete(s)}e.pendingPromptId=void 0,e.promptDone=void 0,e.currentRunId=void 0,e.assistantStreamStartedAt=void 0,e.gatewayMethod=void 0,e.assistantMq?.close()}completePrompt(e,s){if(e.promptDone)return;if(void 0===e.pendingPromptId&&void 0===e.currentRunId)return;e.promptDone=!0;const t=e.currentRunId;if(t&&this.onRunComplete){const s=e.agentAssistantTextSoFar??e.chatAssistantTextSoFar??"";this.onRunComplete(t,s)}void 0!==e.pendingPromptId&&this.transport.sendResult(e.pendingPromptId,{stopReason:s}),this.cleanupPrompt(e)}failPrompt(e,s,t){if(e.promptDone)return;if(void 0===e.pendingPromptId&&void 0===e.currentRunId)return;e.promptDone=!0;const n=e.currentRunId;n&&this.onRunFailed&&this.onRunFailed(n,t),void 0!==e.pendingPromptId&&this.transport.sendError(e.pendingPromptId,s,t),this.cleanupPrompt(e)}cleanupAllPendingPrompts(){for(const e of this.state.sessions.values())this.failPrompt(e,Errors.GatewayDisconnected.rpcCode,Errors.GatewayDisconnected.message)}maybeCompletePromptFromChatState(e,s){if(e.promptDone||"chat.send"!==e.gatewayMethod)return;const t="string"==typeof s.state?s.state.toLowerCase():void 0;if(t)if("final"===t)this.completePrompt(e,"end_turn");else if("aborted"===t||"cancelled"===t||"cancel"===t)this.completePrompt(e,"cancelled");else if("error"===t){const t=("string"==typeof s.summary?s.summary:void 0)??("string"==typeof s.message?s.message:void 0)??"gateway chat error";this.failPrompt(e,Errors.AgentError.rpcCode,formatFriendlyError(t))}}pushToolResultContent(e,s,t,n){if(0===t.length)return;const i=(n?this.state.promptsByRunId.get(n):void 0)??(this.state.lastActiveSessionId?this.state.sessions.get(this.state.lastActiveSessionId):void 0);if(!i)return void this.logger.warn?.(`[bridge-core] pushToolResultContent dropped — no session (runId=${n})`);const o=i.sessionId;for(const e of t){const s={sessionUpdate:"agent_message_chunk",content:e};this.transport.sendSessionUpdate(o,s),i.assistantMq?.push(s)}this.writeObs({component:"bridge-core",domain:"tool",name:"tool_result.direct_push",severity:"info",payload:{toolCallId:e,toolName:s,blockCount:t.length,sessionId:o}})}async handleCronRequest(e){const s=this.getGateway();if(!s?.isConnected)return void this.transport.sendAcpError(e.id,Errors.GatewayNotConnected);const t=e.method.replace("/",".");try{const n=await s.request(t,e.params??{});this.transport.sendResult(e.id,n??{})}catch(s){const n=s instanceof Error?s.message:"cron request failed";this.logger.warn?.(`[bridge-core] ${t} failed: ${n}`),this.transport.sendAcpError(e.id,Errors.SendFailed,{message:n})}}}
1
+ import{randomUUID,createHash}from"node:crypto";import{sanitizePromptPayload,stripTransportMetadata}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{buildResolutionPlan,resolveResources,applyResolutions}from"./prompt-resource-resolver.js";import{readUploadToolResult}from"../upload/result-cache.js";import{BEEOS_UPLOAD_TOOL_NAME}from"../upload/tool.js";import{buildToolResultSessionContentBlocks}from"./tool-result-payload-strategies.js";import{Errors}from"../errors/index.js";import{formatFriendlyError}from"../errors/classify.js";import{resolveChannelFromSessionKey}from"../channel-detection.js";import{ACP_PROTOCOL_VERSION,DEFAULT_PROMPT_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(s=>e.includes(s))}function isSystemDefaultSessionKey(e){const s=e.split(":");if(s.length<3||"agent"!==s[0])return!1;const t=s.slice(2).join(":");return"main"===t||t===s[1]}function cleanGatewayDerivedTitle(e){if(!e)return;let s=stripTransportMetadata(e);return/^\[System\b/.test(s)?void 0:(s=s.trim(),s||void 0)}function resolveStandaloneSlashCommandName(e,s){if(0===e.length)return;if(e.some(e=>"text"!==e.type))return;const t=s.trim();if(!t||t.includes("\n")||!t.startsWith("/"))return;const n=t.match(/^\/([^\s:]+)(?::|\s|$)/)?.[1]?.trim();return n&&!n.includes("/")&&SLASH_COMMAND_NAME_RE.test(n)?n.toLowerCase():void 0}function deriveSessionId(e,s){const t=createHash("sha256").update(`${s}:${e}`).digest("hex").substring(0,32);return`session:${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`}function parseAgentIdFromKey(e){const s=e.split(":");return(s.length>=3&&"agent"===s[0]?s[1]:"")||"main"}function createSessionObject(e){const s=parseAgentIdFromKey(e.gatewayKey);return{sessionId:deriveSessionId(e.gatewayKey,e.instanceId),gatewaySessionKey:e.gatewayKey,agentId:s,platformAgentId:e.resolvePlatformAgentId?.(s),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;initialized=!1;agentMapping=null;_syncResolvers=[];_mappingReadyCallbacks=[];setAgentMapping(e){this.agentMapping=e;for(const s of this.state.sessions.values())!s.platformAgentId&&s.agentId&&(s.platformAgentId=e.get(s.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(s=>{this._syncResolvers.push(s);const t=setTimeout(()=>{const e=this._syncResolvers.indexOf(s);-1!==e&&this._syncResolvers.splice(e,1),s()},e);"object"==typeof t&&"unref"in t&&t.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}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)}ensureSessionForKey(e){const s=this.state.findSessionByKey(e);if(s)return s;const t=createSessionObject({gatewayKey:e,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels});return this.registerSession(t),this.logger.debug?.(`[bridge-core] ensureSessionForKey: lazily created session sid=${t.sessionId} key=${e}`),t}async preloadSessionsFromGateway(){const e=this.getGateway();if(e?.isConnected)try{const s=await e.sessionsList();if(!s||"object"!=typeof s)return;const t=s.sessions;if(!Array.isArray(t))return;let n=0;for(const e of t){const s=e,t=s.sessionKey??s.key??s.id??s.name;if(!t||"string"!=typeof t)continue;if(this.state.findSessionByKey(t))continue;const o=s.label||s.derivedTitle||s.title||void 0,i=createSessionObject({gatewayKey:t,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,title:o||"New chat"});this.registerSession(i),n++}n>0&&this.logger.info?.(`[bridge-core] preloadSessions: loaded ${n} session(s) from gateway`)}catch(e){this.logger.debug?.("[bridge-core] preloadSessions failed:",e)}else this.logger.debug?.("[bridge-core] preloadSessions skipped: gateway not connected")}async handleRequest(e){this.writeObs({component:"bridge-core",domain:"forward",name:`rpc.request.${e.method}`,severity:"debug",payload:{id:e.id,method:e.method}});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"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(s){this.transport.sendAcpError(e.id,Errors.InternalError,{message:s instanceof Error?s.message:"Internal error"})}}handleCanvasNotification=null;getCanvasState=null;onSessionLoaded=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 s=e.params,t=s?.surfaceId,n=this.state.resolveSessionFromParams(s);if(!n){this.logger.warn?.(`[bridge-core] canvas/reference ignored — no session found for sessionId=${s?.sessionId}`);break}n.referencedSurfaceId=t||void 0,this.logger.debug?.(`[bridge-core] Canvas reference ${t?"set":"cleared"}: ${t??"(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 s=this.transport.forwardControl;!1===e.params?.forwardThinking&&(s.forwardThinking=!1),!1===e.params?.forwardToolCalls&&(s.forwardToolCalls=!1),this.transport.sendResult(e.id,{protocolVersion:ACP_PROTOCOL_VERSION,agentCapabilities:{loadSession:!0,skills:!0,promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},sessionCapabilities:{list:{},"web-ssh":!!this.config.bridge.shell.enabled,canvas:!!this.config.canvasEnabled,cron:!0},mcp:{}},agentInfo:{name:"beeos-claw",title:"BeeOS Agent Bridge",version:"0.1.0"},_meta:{},authMethods:[]})}async handleSessionNew(e){const s=`agent:${"string"==typeof e.params?.agentId&&e.params.agentId||this.config.gateway.agentId||this.getDefaultAgentId()}:${randomUUID()}`,t="string"==typeof e.params?.cwd?e.params.cwd:".",n=createSessionObject({gatewayKey:s,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,cwd:t});this.registerSession(n),this.transport.sendResult(e.id,{sessionId:n.sessionId,modes:{availableModes:[{...DEFAULT_MODE}],currentModeId:DEFAULT_MODE.id},_meta:{sessionKey:s,agentId:n.agentId,platformAgentId:n.platformAgentId??null}}),this.fetchHistoryInBackground(s)}fetchHistoryInBackground(e){const s=this.getGateway();s?.isConnected&&loadHistory(s,e,50).catch(e=>{this.logger.debug?.(`[bridge-core] Background history fetch failed: ${e instanceof Error?e.message:e}`)})}async recoverSessionFromGateway(e){const s=this.getGateway();if(s?.isConnected)try{const t=await s.sessionsList();if(!t||"object"!=typeof t)return;const n=t.sessions;if(!Array.isArray(n))return;for(const s of n){const t=s,n=t.sessionKey??t.key??t.id??t.name;if(n&&"string"==typeof n&&deriveSessionId(n,this.instanceId)===e){const e=createSessionObject({gatewayKey:n,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels});return this.registerSession(e),e}}}catch(e){this.logger.debug?.("[bridge-core] recoverSessionFromGateway failed:",e)}}async resolveOrCreateSession(e){let s=this.state.sessions.get(e);if(!s&&e.startsWith("agent:")&&(s=this.state.findSessionByKey(e)),s||e.startsWith("agent:")||(s=await this.recoverSessionFromGateway(e)),s)return{session:s,created:!1};const t=e.startsWith("agent:"),n=this.config.gateway.agentId||this.getDefaultAgentId();return s=createSessionObject({gatewayKey:t?e:`agent:${n}:${e}`,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels}),this.registerSession(s),{session:s,created:!0}}async handleSessionLoad(e){const s=e.params?.sessionId;if(!s)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const{session:t}=await this.resolveOrCreateSession(s),n=t.sessionId;this.state.lastActiveSessionId=n,t.chatReplayDedupKeys.clear();let o=[];try{const e=this.getGateway(),s=await loadHistory(e,t.gatewaySessionKey,50);o=groupIntoTurns(s);const i=o.filter(e=>"user"===e.role).length,a=o.filter(e=>"assistant"===e.role).length,r=o.filter(e=>e.toolCalls?.length).length,d=o.reduce((e,s)=>e+(s.toolCalls?.length??0),0);this.logger.debug?.(`[bridge-core] handleSessionLoad sid=${n} messages=${s.length} turns=${o.length} userTurns=${i} asstTurns=${a} turnsWithToolCalls=${r} totalToolCalls=${d}`);for(let e=0;e<o.length;e++){const s=o[e];if("user"!==s.role||"internal_system"!==s.provenance?.kind)if("system"!==s.role){if(this.logger.debug?.(`[bridge-core] SENDING history_turn[${e}] role=${s.role} contentLen=${s.content.length} content=${JSON.stringify(s.content.slice(0,80))} tcCount=${s.toolCalls?.length??0}`),"user"===s.role)this.replayUserTurnAsChunks(n,s.content,s.metadata);else{const e={sessionUpdate:"history_turn",role:s.role,content:s.content,reasoning:s.reasoning,toolCalls:s.toolCalls};s.metadata&&(e.metadata=s.metadata),this.transport.sendSessionUpdate(n,e)}if("assistant"===s.role){if(s.files?.length)for(const e of s.files)this.transport.sendSessionUpdate(n,{sessionUpdate:"agent_message_chunk",content:{type:"resource_link",uri:e.uri,...e.name?{name:e.name}:{},...e.mimeType?{mimeType:e.mimeType}:{}}});s.toolCalls?.length&&await this.replayUploadFileBlocks(n,s.toolCalls)}}else this.logger.debug?.(`[bridge-core] SENDING system_message[${e}] contentLen=${s.content.length}`),this.transport.sendSessionUpdate(n,{sessionUpdate:"system_message_chunk",content:{type:"text",text:s.content},metadata:s.metadata});else 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 i=new Set;for(const e of o)if(e.toolCalls)for(const s of e.toolCalls)s.id&&i.add(s.id),s.callId&&s.callId!==s.id&&i.add(s.callId);if(void 0!==t.pendingPromptId&&!t.promptDone&&t.assistantMq&&!t.assistantMq.closed)try{this.replayCurrentAssistantStream(t,i)}catch(e){this.logger.warn?.(`[bridge-core] replayCurrentAssistantStream failed: ${e instanceof Error?e.message:e}`)}(()=>{this.transport.sendResult(e.id,{sessionId:n}),this.onSessionLoaded?.(n,t.gatewaySessionKey,t.platformAgentId),this.pushSkillsList().catch(e=>{this.logger.warn?.(`[bridge-core] pushSkillsList failed: ${e instanceof Error?e.message:e}`)})})()}async replayUploadFileBlocks(e,s){for(const t of s){if(t.name!==BEEOS_UPLOAD_TOOL_NAME)continue;let s=[];try{const e=await readUploadToolResult(t.id);e&&(s=buildToolResultSessionContentBlocks(t.name,e))}catch{}if(0===s.length){const e=extractBeeosFileUrisFromOutput(t.output);for(const t of e)s.push({type:"content",content:{type:"resource_link",uri:t,name:"file"}})}const n=s.filter(e=>"resource_link"===e.content?.type);for(const s of n)this.transport.sendSessionUpdate(e,{sessionUpdate:"agent_message_chunk",content:s.content});n.length>0&&this.logger.debug?.(`[bridge-core] replayUploadFileBlocks tcId=${t.id} sent ${n.length} resource_link block(s)`)}}replayCurrentAssistantStream(e,s){if(!e.assistantMq||e.assistantMq.closed)return;const t=e.assistantMq.peek(0);if(0===t.length)return;let n=0,o=0;for(const i of t)s?.size&&i.toolCallId&&s.has(i.toolCallId)&&("tool_call"===i.sessionUpdate||"tool_call_update"===i.sessionUpdate)?o++:(this.transport.sendSessionUpdate(e.sessionId,i),n++);o>0&&this.logger.debug?.(`[bridge-core] replayCurrentAssistantStream skipped ${o} duplicate tool events (already in history)`),n>0&&this.writeObs({component:"bridge-core",domain:"lifecycle",name:"session.load.replay_complete",severity:"debug",payload:{sessionId:e.sessionId,replayed:n}})}async handleSessionList(e){const s=[];for(const[,e]of this.state.sessions)s.push({sessionId:e.sessionId,title:e.title||"New chat",cwd:e.cwd,updatedAt:e.lastStreamActivityTs??e.createdAt,agentId:e.agentId,platformAgentId:e.platformAgentId,deletable:!isSystemDefaultSessionKey(e.gatewaySessionKey)});const t=this.getGateway();if(t?.isConnected)try{const e=await t.sessionsList();if(e&&"object"==typeof e&&Array.isArray(e.sessions)){const t=e.sessions;for(const e of t){const t=e,n=t.sessionKey??t.key??t.id??t.name;if(!n||"string"!=typeof n)continue;if(isBackgroundSessionKey(n))continue;const o=deriveSessionId(n,this.instanceId),i=s.find(e=>e.sessionId===n||e.sessionId===o||this.state.sessions.get(e.sessionId)?.gatewaySessionKey===n),a=t.label||cleanGatewayDerivedTitle(t.derivedTitle)||t.title||void 0,r=t.model,d=t.modelProvider;if(i){if(!i.title||"New chat"===i.title){const e=a||i.sessionId;i.title=e;const s=this.state.sessions.get(i.sessionId);s&&!s.title&&(s.title=e)}const e=t.updatedAt;e&&(i.updatedAt=e),r&&(i.model=r),d&&(i.modelProvider=d)}else{const e=createSessionObject({gatewayKey:n,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,cwd:t.cwd,title:a||"New chat"});this.registerSession(e),s.push({sessionId:e.sessionId,title:a||"New chat",cwd:t.cwd,updatedAt:t.updatedAt,agentId:e.agentId,platformAgentId:e.platformAgentId,deletable:!isSystemDefaultSessionKey(n),model:r,modelProvider:d})}}}}catch(e){this.logger.debug?.("[bridge-core] sessions.list enrichment failed:",e)}s.sort((e,s)=>(s.updatedAt??0)-(e.updatedAt??0)||e.sessionId.localeCompare(s.sessionId)),this.transport.sendResult(e.id,{sessions:s})}handleSessionRename(e){const s=e.params?.sessionId,t=e.params?.title;if(!s||!t)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId, title"});const n=t.slice(0,64),o=this.state.sessions.get(s);if(!o)return void this.transport.sendAcpError(e.id,Errors.SessionNotFound);o.title=n;const i=o.gatewaySessionKey,a=this.getGateway();a?.isConnected&&a.sessionsPatch(i,{label:n}).catch(e=>{this.logger.debug?.(`[bridge-core] sessionsPatch (rename) failed: ${e instanceof Error?e.message:e}`)}),this.transport.sendResult(e.id,{sessionId:s,title:n})}async handleSessionDelete(e){const s=e.params?.sessionId;if(!s)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const t=this.state.sessions.get(s);if(!t)return this.logger.info?.(`[bridge-core] session/delete sessionId=${s} NOT FOUND in local state`),void this.transport.sendAcpError(e.id,Errors.SessionNotFound);const n=t.gatewaySessionKey;this.logger.info?.(`[bridge-core] session/delete sessionId=${s} gatewayKey=${n} gwConnected=${!!this.getGateway()?.isConnected}`);let o=!1;const i=this.getGateway();if(i?.isConnected&&n)try{await i.sessionsDelete(n),o=!0,this.logger.info?.(`[bridge-core] Gateway sessions.delete SUCCESS for key=${n}`)}catch(s){const t=s instanceof Error?s.message:String(s);if(this.logger.info?.(`[bridge-core] Gateway sessions.delete FAILED for key=${n}: ${t}`),!t.includes("Cannot delete the main session"))return void this.transport.sendResult(e.id,{deleted:!1});try{await i.sessionsReset(n),o=!0,this.logger.info?.(`[bridge-core] Gateway sessions.reset SUCCESS for key=${n}`)}catch(s){return this.logger.warn?.(`[bridge-core] Gateway sessions.reset also failed for key=${n}: ${s instanceof Error?s.message:s}`),void this.transport.sendResult(e.id,{deleted:!1})}}else n&&this.logger.warn?.(`[bridge-core] Gateway not connected, proceeding with local-only delete for key=${n}`);void 0!==t.pendingPromptId&&this.failPrompt(t,Errors.SessionDeleted.rpcCode,Errors.SessionDeleted.message),this.state.clearPromptTimeout(t),this.state.clearStreamIdleTimer(t),t.assistantMq?.close(),t.currentRunId&&this.state.promptsByRunId.delete(t.currentRunId);const a=new Set;for(const[e,t]of this.state.toolCallToSessionMap)t===s&&(this.state.toolCallToSessionMap.delete(e),a.add(e));for(const[e,s]of this.state.toolCallIdMap)a.has(s)&&this.state.toolCallIdMap.delete(e);this.state.sessions.delete(s),this.state.sessionsByGatewayKey.delete(n),this.transport.resetSessionUpdateCount(s),o&&this.onSessionDeleted?.(n),this.logger.info?.(`[bridge-core] session/delete DONE sessionId=${s} gatewayKey=${n} deleted=true`),this.transport.sendResult(e.id,{deleted:!0})}async handleSessionClear(e){this.logger.info?.(`[bridge-core] handleSessionClear called, params=${JSON.stringify(e.params)}`);const s=e.params?.sessionId;if(!s)return this.logger.warn?.("[bridge-core] session/clear missing sessionId"),void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const t=this.state.sessions.get(s);if(!t)return this.logger.warn?.(`[bridge-core] session/clear sessionId=${s} not found in state`),void this.transport.sendAcpError(e.id,Errors.SessionNotFound);this.logger.info?.(`[bridge-core] session/clear sessionId=${s} gatewayKey=${t.gatewaySessionKey}`);const n=this.getGateway();if(n?.isConnected&&t.gatewaySessionKey)try{await n.sessionsReset(t.gatewaySessionKey),this.logger.info?.(`[bridge-core] Gateway sessions.reset SUCCESS for key=${t.gatewaySessionKey}`)}catch(e){this.logger.warn?.(`[bridge-core] Gateway sessions.reset FAILED for key=${t.gatewaySessionKey}: ${e instanceof Error?e.message:e}`)}else this.logger.warn?.(`[bridge-core] session/clear skipped gateway reset: connected=${n?.isConnected}, key=${t.gatewaySessionKey}`);t.chatReplayDedupKeys.clear(),this.logger.info?.("[bridge-core] session/clear dedupKeys cleared, calling onSessionCleared"),this.onSessionCleared?.(s,t.gatewaySessionKey),this.transport.sendResult(e.id,{cleared:!0}),this.logger.info?.("[bridge-core] session/clear DONE, sent cleared=true")}async handleSessionSetMode(e){const s=e.params?.sessionId,t=e.params?.mode,n=s?this.state.sessions.get(s):void 0,o=this.getGateway();if(n&&o?.isConnected&&t){const e={};if("verbose"===t||"detailed"===t?e.verboseLevel="full":"concise"!==t&&"default"!==t||(e.verboseLevel="default"),"reasoning"!==t&&"thinking"!==t||(e.reasoningLevel="stream"),Object.keys(e).length>0)try{await o.sessionsPatch(n.gatewaySessionKey,e)}catch(e){this.logger.warn?.(`[bridge-core] sessions.patch failed: ${e instanceof Error?e.message:e}`)}}this.transport.sendResult(e.id,{mode:t??"default"})}async handleSessionSetModel(e){const s=e.params?.sessionId,t=e.params?.model,n=s?this.state.sessions.get(s):void 0,o=this.getGateway();let i=t??null,a=null;if(n&&o?.isConnected&&t)try{const e=await o.sessionsPatch(n.gatewaySessionKey,{model:t}),s=e?.resolved;s?.model&&(i=s.model),s?.modelProvider&&(a=s.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:i,modelProvider:a})}async handleModelsList(e){const s=this.getGateway();if(s?.isConnected)try{const t=await s.request("models.list",{});this.transport.sendResult(e.id,t??{models:[]})}catch(s){this.transport.sendAcpError(e.id,Errors.InternalError,{message:`Failed to list models: ${s instanceof Error?s.message:s}`})}else this.transport.sendAcpError(e.id,Errors.GatewayNotConnected)}async handleSkillsList(e){const s=await this.fetchSimplifiedSkills();this.transport.sendResult(e.id,{skills:s})}async fetchSimplifiedSkills(){const e=this.getGateway();if(!e?.isConnected)return[];try{const s=await e.skillsStatus();return s?.skills?s.skills.filter(e=>!1!==e.eligible&&!0!==e.disabled).sort((e,s)=>e.always&&!s.always?-1:!e.always&&s.always?1:e.name.localeCompare(s.name)).map(e=>({name:e.name,description:e.description,emoji:e.emoji,always:e.always||void 0,bundled:e.bundled||void 0})):[]}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}})}async handleSessionPrompt(e){const s=e.params?.sessionId,t=e.params?.prompt;if(!s||!t)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId, prompt"});const{session:n,created:o}=await this.resolveOrCreateSession(s);o&&this.onSessionLoaded?.(n.sessionId,n.gatewaySessionKey,n.platformAgentId);const i=n.sessionId;this.state.lastActiveSessionId=i,this.onPromptStart?.();const a=this.getGateway();if(!a?.isConnected)return void this.transport.sendAcpError(e.id,Errors.GatewayNotConnected);let r=extractPromptBlocks(sanitizePromptPayload(t));if(!n.title){const e=r.find(e=>"text"===e.type&&e.text);e&&"text"in e&&e.text&&(n.title=e.text.slice(0,64).replace(/\n/g," ").trim(),a?.isConnected&&n.title&&a.sessionsPatch(n.gatewaySessionKey,{label:n.title}).catch(e=>{this.logger.debug?.(`[bridge-core] sessionsPatch (title) failed: ${e instanceof Error?e.message:e}`)}))}const d=buildResolutionPlan(r);if(d.refs.length>0)try{const e=await resolveResources(d,this.writeObs);r=applyResolutions(r,e)}catch(e){this.logger.warn?.(`[bridge-core] Resource pre-resolution failed: ${e instanceof Error?e.message:e}`)}let l;if(this.beeosFileResolver){const e=this.beeosFileResolver.buildResolutionPlan(r);if(e.refs.length>0)try{l=await this.beeosFileResolver.resolveMetadataForPrompt(e)}catch(e){this.logger.warn?.(`[bridge-core] BeeOS file resolution failed: ${e instanceof Error?e.message:e}`)}}const c=toGatewayPrompt(r,{beeosFileResolutionsByUri:l});if("error"in c)return void this.transport.sendAcpError(e.id,Errors.PromptConvertFailed,{message:c.error});const{message:p,attachments:h}=c,m=resolveStandaloneSlashCommandName(r,p)??resolveSlashCmd(r,p),g="string"==typeof m;if(m&&this.handleSlashCommand){const s=this;if(await(async()=>{try{return await s.handleSlashCommand(m)}catch(e){return s.logger.warn?.(`[bridge-core] /${m} handler failed: ${e instanceof Error?e.message:e}`),!1}})())return this.emitPromptAsUserSessionUpdates(n.sessionId,r),this.transport.sendSessionUpdate(i,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Loading ${m}...`}}),void this.transport.sendResult(e.id,{stopReason:"end_turn"})}const u="chat.send";let y=g?p:withUserMessagePrefix(p);const f=this.config.canvasEnabled&&!g&&!1!==n.canvasActive&&!n.channelType;if(f){const e=n.promptsSinceCanvasInjection??0;!n.canvasPromptInjected||e>=10?(y=`${CANVAS_TERM_MAPPING}\n\n${y}`,n.canvasPromptInjected=!0,n.promptsSinceCanvasInjection=0,this.logger.debug?.("[bridge-core] Canvas term mapping injected (re-inject cycle)")):n.promptsSinceCanvasInjection=e+1}if(f){const e=this.getCanvasState?.();if(e){const s=e.resolveCanvasForSession(n.gatewaySessionKey);y=`${buildActiveSurfacesContext(e,s)??"[Canvas] Canvas panel is available. Use render_ui for structured/visual content."}\n\n${y}`}const s=n.referencedSurfaceId;s&&(y=`${CANVAS_UPDATE_HINT}\n[IMPORTANT: The user selected canvas surface "${s}" for editing. You MUST call render_ui with id="${s}" to UPDATE this existing surface. Do NOT create a new surface with a different id.]\n${y}`,n.referencedSurfaceId=void 0)}if(!g){const s=parseMentionsParam(e.params?.mentions);if(s.length>0){n.activeMentions=s;y=`${buildMentionInstruction(s)}\n${y}`,this.logger.debug?.(`[bridge-core] A2A mention instruction injected for ${s.length} agent(s)`)}else n.activeMentions=void 0}g&&this.logger.info?.(`[bridge-core] slash command passthrough sessionId=${i} command=/${m}`),n.promptDone||void 0===n.pendingPromptId&&void 0===n.currentRunId||(this.logger.warn?.(`[bridge-core] handleSessionPrompt: force-ending stale run sid=${i} oldRunId=${n.currentRunId} oldPromptId=${n.pendingPromptId}`),(n.currentRunId||n.gatewayRequestId)&&a.agentCancel(n.gatewaySessionKey,{runId:n.currentRunId,requestId:n.gatewayRequestId}),this.endRun(n,{kind:"complete",stopReason:"cancelled"})),this.state.resetForNewRun(n,i,this.transport),n.pendingPromptId=e.id,n.gatewayMethod=u,this.emitPromptAsUserSessionUpdates(i,r),this.transport.sendSessionUpdate(i,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:""}}),this.schedulePromptTimeout(n);const I=h.length>0?h.map(e=>({type:e.type,content:e.content,...e.mimeType?{mimeType:e.mimeType}:{},...e.fileName?{fileName:e.fileName}:{}})):void 0,S=`req_${randomUUID().replace(/-/g,"")}`,w={sessionKey:n.gatewaySessionKey,message:y,deliver:!1,idempotencyKey:randomUUID()};I?.length&&(w.attachments=I);if(!a.sendFrame({type:"req",id:S,method:u,params:w}))return this.state.clearPromptTimeout(n),n.pendingPromptId=void 0,n.assistantMq?.close(),void this.transport.sendAcpError(e.id,Errors.SendFailed,{message:"failed to send prompt to gateway"});n.gatewayRequestId=S,this.state.promptsByGatewayRequestId.set(S,n)}replayUserTurnAsChunks(e,s,t){const n=splitUserReplayBlocks(s);for(const s of n){let n;if("text"===s.type){if(!s.text)continue;n={type:"text",text:s.text}}else n="resource_link"===s.type?{type:"resource_link",uri:s.uri??"",...s.fileName?{name:s.fileName}:{},...s.mimeType?{mimeType:s.mimeType}:{}}:{type:s.type,...s.mimeType?{mimeType:s.mimeType}:{},...s.fileName?{fileName:s.fileName}:{}};this.transport.sendSessionUpdate(e,{sessionUpdate:"user_message_chunk",content:n,...t?{metadata:t}:{}})}}emitPromptAsUserSessionUpdates(e,s){for(const t of s){const s=this.toUserSessionUpdateContent(t);s&&this.transport.sendSessionUpdate(e,{sessionUpdate:"user_message_chunk",content:s})}}toUserSessionUpdateContent(e){if("text"===e.type){if(!e.text)return;return{type:"text",text:e.text}}if("image"===e.type){const s=e.mimeType??e.mime_type??"application/octet-stream",t=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}:{},...s?{mimeType:s}:{},...t?{fileName:t}:{}}}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 s=e.mimeType??e.mime_type??"application/octet-stream",t=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}:{},...s?{mimeType:s}:{},...t?{fileName:t}:{}}}if("resource"===e.type){const s=e.resource??{},t=s.uri??e.uri,n=s.mimeType??s.mime_type??e.mimeType??e.mime_type,o=s.text??e.text,i=s.data??e.data,a=s.fileName??s.file_name??s.filename??s.name??e.fileName??e.file_name??e.filename??e.name;if(!t&&!o&&!i)return;return{type:"resource",resource:{...t?{uri:t}:{},...n?{mimeType:n}:{},...o?{text:o}:{},...i?{data:i}:{},...a?{fileName:a}:{}}}}}handleSessionCancel(e,s){const t=s?.sessionId;if(!t)return void(void 0!==e&&this.transport.sendAcpError(e,Errors.MissingParam,{param:"sessionId"}));const n=this.state.sessions.get(t);if(!n)return void(void 0!==e&&this.transport.sendAcpError(e,Errors.SessionNotFound));const o=this.getGateway(),i=o?.isConnected,a=!(!n.currentRunId&&!n.gatewayRequestId);if(i&&a){o.agentCancel(n.gatewaySessionKey,{runId:n.currentRunId,requestId:n.gatewayRequestId})}this.endRun(n,{kind:"complete",stopReason:"cancelled"})||this.transport.sendSessionUpdate(n.sessionId,{sessionUpdate:"stream_complete",stopReason:"cancelled"}),void 0!==e&&this.transport.sendResult(e,{})}endRun(e,s){if(e.promptDone)return this.logger.debug?.(`[bridge-core] endRun skipped (promptDone=true) sessionId=${e.sessionId} outcome=${s.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=${s.kind}`),!1;e.promptDone=!0;const t=e.currentRunId;if("complete"===s.kind){if(t&&this.onRunComplete){const s=e.agentAssistantTextSoFar??e.chatAssistantTextSoFar??"";this.onRunComplete(t,s)}void 0!==e.pendingPromptId&&this.transport.sendResult(e.pendingPromptId,{stopReason:s.stopReason}),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:s.stopReason})}else t&&this.onRunFailed&&this.onRunFailed(t,s.message),void 0!==e.pendingPromptId&&this.transport.sendError(e.pendingPromptId,s.code,s.message),this.transport.sendSessionUpdate(e.sessionId,{sessionUpdate:"stream_complete",stopReason:"error",error:s.message});return this.cleanupPrompt(e),this.onRunEnded?.(e,s),!0}schedulePromptTimeout(e){this.state.clearPromptTimeout(e);const s=this.config.promptTimeoutMs??DEFAULT_PROMPT_TIMEOUT_MS;s<=0||(e.promptTimeoutTimer=setTimeout(()=>{void 0!==e.pendingPromptId&&(this.logger.warn?.(`[bridge-core] Prompt timed out sessionId=${e.sessionId} after ${s}ms`),this.failPrompt(e,Errors.PromptTimeout.rpcCode,`Prompt timed out after ${s}ms`))},s),"object"==typeof e.promptTimeoutTimer&&"unref"in e.promptTimeoutTimer&&e.promptTimeoutTimer.unref())}cleanupPrompt(e){this.state.clearPromptTimeout(e),this.state.clearStreamIdleTimer(e);const s=e.currentRunId;if(s){this.state.promptsByRunId.delete(s),this.state.markRunCompleted(s);const e=`tc_${s}_`;for(const[s,t]of this.state.toolCallIdMap)t.startsWith(e)&&this.state.toolCallIdMap.delete(s)}e.gatewayRequestId&&this.state.promptsByGatewayRequestId.delete(e.gatewayRequestId),e.pendingPromptId=void 0,e.promptDone=void 0,e.currentRunId=void 0,e.gatewayRequestId=void 0,e.assistantStreamStartedAt=void 0,e.gatewayMethod=void 0,e.assistantMq?.close()}completePrompt(e,s){this.endRun(e,{kind:"complete",stopReason:s})}failPrompt(e,s,t){this.endRun(e,{kind:"error",code:s,message:t})}cleanupAllPendingPrompts(){for(const e of this.state.sessions.values())this.failPrompt(e,Errors.GatewayDisconnected.rpcCode,Errors.GatewayDisconnected.message)}handleGatewayResponse(e){const s=e.id;if(!s)return;const t=this.state.promptsByGatewayRequestId.get(s);if(!t||t.promptDone)return;if(!e.ok){const n=e.error,o=n?.message??"gateway returned error";return this.logger.warn?.(`[bridge-core] handleGatewayResponse: gateway rejected prompt gatewayRequestId=${s} error=${o}`),void this.failPrompt(t,Errors.SendFailed.rpcCode,o)}const n=e.payload,o=n?.runId;o?(t.currentRunId=o,t.assistantStreamStartedAt=Date.now(),this.state.promptsByRunId.set(o,t),this.logger.debug?.(`[bridge-core] handleGatewayResponse: bound runId=${o} gatewayRequestId=${s} sessionId=${t.sessionId}`)):this.logger.debug?.(`[bridge-core] handleGatewayResponse: no runId in payload gatewayRequestId=${s} sessionId=${t.sessionId}`)}maybeCompletePromptFromChatState(e,s){if(e.promptDone||"chat.send"!==e.gatewayMethod)return;const t="string"==typeof s.state?s.state.toLowerCase():void 0;if(t)if("final"===t)this.completePrompt(e,"end_turn");else if("aborted"===t||"cancelled"===t||"cancel"===t)this.completePrompt(e,"cancelled");else if("error"===t){const t=("string"==typeof s.summary?s.summary:void 0)??("string"==typeof s.message?s.message:void 0)??"gateway chat error";this.failPrompt(e,Errors.AgentError.rpcCode,formatFriendlyError(t))}}pushToolResultContent(e,s,t,n){if(0===t.length)return;const o=(n?this.state.promptsByRunId.get(n):void 0)??(this.state.lastActiveSessionId?this.state.sessions.get(this.state.lastActiveSessionId):void 0);if(!o)return void this.logger.warn?.(`[bridge-core] pushToolResultContent dropped — no session (runId=${n})`);const i=o.sessionId;for(const e of t){const s={sessionUpdate:"agent_message_chunk",content:e};this.transport.sendSessionUpdate(i,s),o.assistantMq?.push(s)}this.writeObs({component:"bridge-core",domain:"tool",name:"tool_result.direct_push",severity:"info",payload:{toolCallId:e,toolName:s,blockCount:t.length,sessionId:i}})}async handleCronRequest(e){const s=this.getGateway();if(!s?.isConnected)return void this.transport.sendAcpError(e.id,Errors.GatewayNotConnected);const t=e.method.replace("/",".");try{const n=await s.request(t,e.params??{});this.transport.sendResult(e.id,n??{})}catch(s){const n=s instanceof Error?s.message:"cron request failed";this.logger.warn?.(`[bridge-core] ${t} failed: ${n}`),this.transport.sendAcpError(e.id,Errors.SendFailed,{message:n})}}}
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";import{Errors}from"../errors/index.js";import{formatFriendlyError}from"../errors/classify.js";import{stripTransportMetadata}from"../message-filter.js";import{resolveToolResultBlocks}from"./tool-result-payload-strategies.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;return t.replace(/\r\n/g,"\n").replace(/\r/g,"\n")||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 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{}}function serializeArgs(t){return Object.keys(t).length>0?JSON.stringify(t,null,2):""}function formatToolTitle(t,e){const s=t??"tool";if(!e||0===Object.keys(e).length)return s;return`${s}: ${Object.entries(e).map(([t,e])=>{const s="string"==typeof e?e:JSON.stringify(e);return`${t}: ${s.length>100?`${s.slice(0,100)}...`:s}`}).join(", ")}`}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"}function buildToolCallUpdate(t,e,s){const n=serializeArgs(s);return{sessionUpdate:"tool_call",toolCallId:t,title:formatToolTitle(e,s),kind:inferToolKind(e),status:"in_progress",rawInput:s,arguments:n,content:n?[{type:"content",content:{type:"text",text:n}}]:void 0}}export class AcpGatewayEvents{state;transport;config;logger;writeObs;completePrompt;failPrompt;maybeCompletePromptFromChatState;agentFetchFn;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}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()}sendToolCallSpacer(t){const e={sessionUpdate:"agent_message_chunk",content:{type:"text",text:"\n"}};this.transport.sendSessionUpdate(t.sessionId,e),t.assistantMq?.push(e)}resolveToolCallId(t,e,s){const n=asString(e.toolCallId)??asString(e.tool_call_id)??asString(e.callId)??asString(e.id);if(n){const e=this.state.toolCallIdMap.get(n);return e?(t.sessionId&&this.state.toolCallToSessionMap.set(e,t.sessionId),e):(this.state.toolCallIdMap.set(n,n),t.sessionId&&this.state.toolCallToSessionMap.set(n,t.sessionId),n)}const o=`tc_${t.currentRunId??"unknown"}_${this.state.nextToolCallSeq++}`;return t.sessionId&&this.state.toolCallToSessionMap.set(o,t.sessionId),o}handleChatEvent(t){const e=(t.runId?this.state.promptsByRunId.get(t.runId):void 0)??this.state.findSessionByKey(t.sessionKey);if(!e)return;if(!this.state.isCurrentStreamOwner(e,t.runId)){if(!t.runId||!1===e.promptDone)return;this.adoptBackgroundRun(e,t.runId)}const s=e.sessionId,n=t.message;if(n){this.touchStreamActivity(e);if("assistant"===n.role){if(!Array.isArray(n.content))return;for(const o of n.content){const n=o;if(!isRecord(n))continue;const a=asString(n.type);if(a){if("thinking"===a){if(e.hasAgentThinkingStream)continue;const t=normalizeText(n.thinking)??normalizeText(n.text);if(!t)continue;const o=dedupKey("chat:thinking",t);if(e.chatReplayDedupKeys.has(o))continue;e.chatReplayDedupKeys.add(o);const a={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:t}};this.transport.sendSessionUpdate(s,a)&&e.assistantMq?.push(a);continue}if("toolCall"===a){if(this.sendToolCallSpacer(e),e.hasAgentToolStartStream)continue;const t=this.resolveToolCallId(e,n,"start"),o=asString(n.name)??asString(n.toolName)??asString(n.tool_name)??"tool",a=resolveToolArgs(n),r=dedupKey("chat:tool_start",t,JSON.stringify(a));if(e.chatReplayDedupKeys.has(r))continue;e.chatReplayDedupKeys.add(r);const i=buildToolCallUpdate(t,o,a);this.transport.sendSessionUpdate(s,i)&&e.assistantMq?.push(i);continue}if("toolResult"===a){if(this.sendToolCallSpacer(e),e.hasAgentToolResultStream)continue;const t=this.resolveToolCallId(e,n,"result"),o=asString(n.name)??asString(n.toolName)??asString(n.tool_name)??"tool",a=n.result,r=normalizeText(n.text)??normalizeText(n.result)??(isRecord(a)||Array.isArray(a)?JSON.stringify(a,null,2):void 0);if(!r)continue;const i=dedupKey("chat:tool_result",t,r);if(e.chatReplayDedupKeys.has(i))continue;e.chatReplayDedupKeys.add(i);const l={sessionUpdate:"tool_call_update",toolCallId:t,title:o,status:"completed",rawOutput:a,content:[{type:"content",content:{type:"text",text:r}}]};this.transport.sendSessionUpdate(s,l)&&e.assistantMq?.push(l);continue}if("text"===a&&n.text){if(e.hasAgentAssistantStream||e.agentAssistantTextSoFar)continue;const o=stripTransportMetadata(n.text);if(!o)continue;const a=dedupKey("chat:text",o);if(e.chatReplayDedupKeys.has(a))continue;e.chatReplayDedupKeys.add(a);const r=e.chatAssistantTextSoFar??"";let i;if(e.chatAssistantTextSoFar=o,o.startsWith(r))i=o.slice(r.length);else{if(r.startsWith(o))continue;i=o}if(!i)continue;this.logger.debug?.(`[gateway-events] chat.text delta seq=${t.seq} runId=${t.runId} len=${i.length} prevLen=${r.length}`);const l={sessionUpdate:"agent_message_chunk",content:{type:"text",text:i}};this.transport.sendSessionUpdate(s,l),e.assistantMq?.push(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)){if(!t.runId||!1===e.promptDone)return;this.adoptBackgroundRun(e,t.runId)}const s=e.sessionId;this.touchStreamActivity(e);const n=t=>{this.transport.sendSessionUpdate(s,t),e.assistantMq?.push(t)};if("assistant"===t.stream){e.hasAgentAssistantStream=!0;const o=this.state.extractAgentAssistantDelta(e,t.data??{});o&&(this.logger.debug?.(`[gateway-events] agent.assistant delta seq=${t.seq} runId=${t.runId} len=${o.length} source=${t.data?.delta?"delta":"cumulative"}`),n({sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}}));const a=[],r=t.data;r&&(Array.isArray(r.content)?a.push(...r.content):isRecord(r.content)?a.push(r.content):"string"==typeof r.type&&a.push(r));for(const t of a){if(!isRecord(t))continue;const o=asString(t.type);if("thinking"===o){e.hasAgentThinkingStream=!0;const n=normalizeText(t.thinking)??normalizeText(t.text);if(n){const t={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n}};this.transport.sendSessionUpdate(s,t)&&e.assistantMq?.push(t)}continue}if("toolCall"===o){this.sendToolCallSpacer(e),e.hasAgentToolStartStream=!0;n(buildToolCallUpdate(this.resolveToolCallId(e,t,"start"),asString(t.name)??asString(t.toolName)??asString(t.tool_name)??"tool",resolveToolArgs(t)));continue}if("toolResult"===o){this.sendToolCallSpacer(e),e.hasAgentToolResultStream=!0;const s=this.resolveToolCallId(e,t,"result"),o=asString(t.name)??asString(t.toolName)??asString(t.tool_name)??"tool",a=t.result,r=normalizeText(t.text)??normalizeText(t.result)??(isRecord(a)||Array.isArray(a)?JSON.stringify(a,null,2):void 0);r&&n({sessionUpdate:"tool_call_update",toolCallId:s,title:o,status:"completed",rawOutput:a,content:[{type:"content",content:{type:"text",text:r}}]});continue}}}else if("thinking"===t.stream){e.hasAgentThinkingStream=!0;const n=normalizeText(t.data?.delta)??normalizeText(t.data?.text);if(n){const t={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n}};this.transport.sendSessionUpdate(s,t)&&e.assistantMq?.push(t)}}else if("tool"===t.stream){const s=t.data,o="string"==typeof s?.phase?s.phase:void 0;if("start"===o){this.sendToolCallSpacer(e),e.hasAgentToolStartStream=!0;n(buildToolCallUpdate(this.resolveToolCallId(e,s,"start"),asString(s?.name)??asString(s?.toolName)??asString(s?.tool_name)??"tool",resolveToolArgs(s)))}else if("result"===o)this.sendToolCallSpacer(e),e.hasAgentToolResultStream=!0,this.handleToolResult(e,t).catch(t=>{this.logger.warn?.(`[gateway-events] Tool result handling failed: ${t instanceof Error?t.message:t}`)});else{const t=s?.toolCall;if(t){this.sendToolCallSpacer(e),e.hasAgentToolStartStream=!0;const o=asString(t?.name)??asString(s?.name)??asString(s?.toolName)??"tool",a={...s,...t};n(buildToolCallUpdate(this.resolveToolCallId(e,a,"start"),o,resolveToolArgs(a)))}}}else if("lifecycle"===t.stream){const s=t.data,n="string"==typeof s?.phase?s.phase:void 0;if("end"===n)this.completePrompt(e,"end_turn");else if("cancelled"===n||"cancel"===n)this.completePrompt(e,"cancelled");else if("error"===n){const n=s?.error,o=n&&"object"==typeof n?n:void 0,a=("string"==typeof s?.message?s.message:void 0)??("string"==typeof n?n:void 0)??("string"==typeof o?.message?o.message:void 0)??("string"==typeof s?.reason?s.reason:void 0)??(o?JSON.stringify(o):void 0)??"gateway lifecycle error",r=formatFriendlyError(a);this.logger.warn?.(`[gateway-events] lifecycle error runId=${t.runId} sessionKey=${t.sessionKey} message=${a} data=${JSON.stringify(s)}`),this.failPrompt(e,Errors.AgentError.rpcCode,r)}}}async handleToolResult(t,e){const s=e.data,n=s?.toolCall,o=("string"==typeof n?.id?n.id:void 0)??("string"==typeof s?.toolCallId?s.toolCallId:void 0),a=(o?this.state.toolCallIdMap.get(o):void 0)??o??`tc_${e.runId}_${e.seq}`,r=("string"==typeof n?.name?n.name:void 0)??("string"==typeof s?.name?s.name:void 0)??"tool",i="string"==typeof s?.text?s.text:void 0,l=o??a;let c;try{c=await resolveToolResultBlocks({toolCallId:l,toolName:r,rawText:i,rawResult:e.data})}catch{c=i?[{type:"content",content:{type:"text",text:i}}]:[]}if(0===c.length&&i&&(c=[{type:"content",content:{type:"text",text:i}}]),c.length>0){const s=c.filter(t=>t.content&&(t.content.text||t.content.uri||t.content.data)).map(t=>({type:"content",content:t.content})),n={sessionUpdate:"tool_call_update",toolCallId:a,title:r,kind:inferToolKind(r),status:"completed",rawOutput:e.data,...s.length>0?{content:s}:{}};this.transport.sendSessionUpdate(t.sessionId,n)&&t.assistantMq?.push(n)}}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){const e=`${this.config.agentGatewayUrl}/api/v1/agent/events`;this.agentFetchFn(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"cron",data:t})}).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}from"../message-filter.js";import{resolveToolResultBlocks}from"./tool-result-payload-strategies.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"))}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 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{}}function serializeArgs(t){return Object.keys(t).length>0?JSON.stringify(t,null,2):""}function formatToolTitle(t,e){const s=t??"tool";if(!e||0===Object.keys(e).length)return s;return`${s}: ${Object.entries(e).map(([t,e])=>{const s="string"==typeof e?e:JSON.stringify(e);return`${t}: ${s.length>100?`${s.slice(0,100)}...`:s}`}).join(", ")}`}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"}function buildToolCallUpdate(t,e,s){const n=serializeArgs(s);return{sessionUpdate:"tool_call",toolCallId:t,title:formatToolTitle(e,s),kind:inferToolKind(e),status:"in_progress",rawInput:s,arguments:n,content:n?[{type:"content",content:{type:"text",text:n}}]:void 0}}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()}sendToolCallSpacer(t){const e={sessionUpdate:"agent_message_chunk",content:{type:"text",text:"\n"}};this.transport.sendSessionUpdate(t.sessionId,e),t.assistantMq?.push(e),this.onStreamDelta?.(t,e)}resolveToolCallId(t,e,s){const n=asString(e.toolCallId)??asString(e.tool_call_id)??asString(e.callId)??asString(e.id);if(n){const e=this.state.toolCallIdMap.get(n);return e?(t.sessionId&&this.state.toolCallToSessionMap.set(e,t.sessionId),e):(this.state.toolCallIdMap.set(n,n),t.sessionId&&this.state.toolCallToSessionMap.set(n,t.sessionId),n)}const o=`tc_${t.currentRunId??"unknown"}_${this.state.nextToolCallSeq++}`;return t.sessionId&&this.state.toolCallToSessionMap.set(o,t.sessionId),o}handleChatEvent(t){const e=(t.runId?this.state.promptsByRunId.get(t.runId):void 0)??this.state.findSessionByKey(t.sessionKey);if(!e)return;if(!this.state.isCurrentStreamOwner(e,t.runId)){const s=!e.currentRunId&&void 0===e.pendingPromptId;if(!t.runId||!s||this.state.isRunCompleted(t.runId))return;this.adoptBackgroundRun(e,t.runId)}const s=e.sessionId,n=t.message;if(n){this.touchStreamActivity(e);if("assistant"===n.role){if(!Array.isArray(n.content))return;for(const o of n.content){const n=o;if(!isRecord(n))continue;const a=asString(n.type);if(a){if("thinking"===a){if(e.hasAgentThinkingStream)continue;const t=normalizeText(n.thinking)??normalizeText(n.text);if(!t)continue;const o=dedupKey("chat:thinking",t);if(e.chatReplayDedupKeys.has(o))continue;e.chatReplayDedupKeys.add(o);const a={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:t}};this.transport.sendSessionUpdate(s,a)&&(e.assistantMq?.push(a),this.onStreamDelta?.(e,a));continue}if("toolCall"===a){if(this.sendToolCallSpacer(e),e.hasAgentToolStartStream)continue;const t=this.resolveToolCallId(e,n,"start"),o=asString(n.name)??asString(n.toolName)??asString(n.tool_name)??"tool",a=resolveToolArgs(n),r=dedupKey("chat:tool_start",t,JSON.stringify(a));if(e.chatReplayDedupKeys.has(r))continue;e.chatReplayDedupKeys.add(r);const i=buildToolCallUpdate(t,o,a);this.transport.sendSessionUpdate(s,i)&&(e.assistantMq?.push(i),this.onStreamDelta?.(e,i));continue}if("toolResult"===a){if(this.sendToolCallSpacer(e),e.hasAgentToolResultStream)continue;const t=this.resolveToolCallId(e,n,"result"),o=asString(n.name)??asString(n.toolName)??asString(n.tool_name)??"tool",a=n.result,r=normalizeText(n.text)??normalizeText(n.result)??(isRecord(a)||Array.isArray(a)?JSON.stringify(a,null,2):void 0);if(!r)continue;const i=dedupKey("chat:tool_result",t,r);if(e.chatReplayDedupKeys.has(i))continue;e.chatReplayDedupKeys.add(i);const l={sessionUpdate:"tool_call_update",toolCallId:t,title:o,status:"completed",rawOutput:a,content:[{type:"content",content:{type:"text",text:r}}]};this.transport.sendSessionUpdate(s,l)&&(e.assistantMq?.push(l),this.onStreamDelta?.(e,l));continue}if("text"===a&&n.text){if(e.hasAgentAssistantStream||e.agentAssistantTextSoFar)continue;const o=stripTransportMetadata(n.text);if(!o)continue;const a=dedupKey("chat:text",o);if(e.chatReplayDedupKeys.has(a))continue;e.chatReplayDedupKeys.add(a);const r=e.chatAssistantTextSoFar??"";let i;if(e.chatAssistantTextSoFar=o,o.startsWith(r))i=o.slice(r.length);else{if(r.startsWith(o))continue;i=o}if(!i)continue;this.logger.debug?.(`[gateway-events] chat.text delta seq=${t.seq} runId=${t.runId} len=${i.length} prevLen=${r.length}`);const l={sessionUpdate:"agent_message_chunk",content:{type:"text",text:i}};this.transport.sendSessionUpdate(s,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)}const s=e.sessionId;this.touchStreamActivity(e);const n=t=>{this.transport.sendSessionUpdate(s,t),e.assistantMq?.push(t),this.onStreamDelta?.(e,t)};if("assistant"===t.stream){e.hasAgentAssistantStream=!0;const o=this.state.extractAgentAssistantDelta(e,t.data??{});if(o){const e=normalizeTransportText(o);e&&(this.logger.debug?.(`[gateway-events] agent.assistant delta seq=${t.seq} runId=${t.runId} len=${e.length} source=${t.data?.delta?"delta":"cumulative"}`),n({sessionUpdate:"agent_message_chunk",content:{type:"text",text:e}}))}const a=[],r=t.data;r&&(Array.isArray(r.content)?a.push(...r.content):isRecord(r.content)?a.push(r.content):"string"==typeof r.type&&a.push(r));for(const t of a){if(!isRecord(t))continue;const o=asString(t.type);if("thinking"===o){e.hasAgentThinkingStream=!0;const n=normalizeText(t.thinking)??normalizeText(t.text);if(n){const t={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n}};this.transport.sendSessionUpdate(s,t)&&(e.assistantMq?.push(t),this.onStreamDelta?.(e,t))}continue}if("toolCall"===o){this.sendToolCallSpacer(e),e.hasAgentToolStartStream=!0;n(buildToolCallUpdate(this.resolveToolCallId(e,t,"start"),asString(t.name)??asString(t.toolName)??asString(t.tool_name)??"tool",resolveToolArgs(t)));continue}if("toolResult"===o){this.sendToolCallSpacer(e),e.hasAgentToolResultStream=!0;const s=this.resolveToolCallId(e,t,"result"),o=asString(t.name)??asString(t.toolName)??asString(t.tool_name)??"tool",a=t.result,r=normalizeText(t.text)??normalizeText(t.result)??(isRecord(a)||Array.isArray(a)?JSON.stringify(a,null,2):void 0);r&&n({sessionUpdate:"tool_call_update",toolCallId:s,title:o,status:"completed",rawOutput:a,content:[{type:"content",content:{type:"text",text:r}}]});continue}}}else if("thinking"===t.stream){e.hasAgentThinkingStream=!0;const n=normalizeText(t.data?.delta)??normalizeText(t.data?.text);if(n){const t={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n}};this.transport.sendSessionUpdate(s,t)&&(e.assistantMq?.push(t),this.onStreamDelta?.(e,t))}}else if("tool"===t.stream){const s=t.data,o="string"==typeof s?.phase?s.phase:void 0;if("start"===o){this.sendToolCallSpacer(e),e.hasAgentToolStartStream=!0;n(buildToolCallUpdate(this.resolveToolCallId(e,s,"start"),asString(s?.name)??asString(s?.toolName)??asString(s?.tool_name)??"tool",resolveToolArgs(s)))}else if("result"===o)this.sendToolCallSpacer(e),e.hasAgentToolResultStream=!0,this.handleToolResult(e,t).catch(t=>{this.logger.warn?.(`[gateway-events] Tool result handling failed: ${t instanceof Error?t.message:t}`)});else{const t=s?.toolCall;if(t){this.sendToolCallSpacer(e),e.hasAgentToolStartStream=!0;const o=asString(t?.name)??asString(s?.name)??asString(s?.toolName)??"tool",a={...s,...t};n(buildToolCallUpdate(this.resolveToolCallId(e,a,"start"),o,resolveToolArgs(a)))}}}else if("lifecycle"===t.stream){const s=t.data,n="string"==typeof s?.phase?s.phase:void 0;if("end"===n)this.completePrompt(e,"end_turn");else if("cancelled"===n||"cancel"===n)this.completePrompt(e,"cancelled");else if("error"===n){const n=s?.error,o=n&&"object"==typeof n?n:void 0,a=("string"==typeof s?.message?s.message:void 0)??("string"==typeof n?n:void 0)??("string"==typeof o?.message?o.message:void 0)??("string"==typeof s?.reason?s.reason:void 0)??(o?JSON.stringify(o):void 0)??"gateway lifecycle error",r=formatFriendlyError(a);this.logger.warn?.(`[gateway-events] lifecycle error runId=${t.runId} sessionKey=${t.sessionKey} message=${a} data=${JSON.stringify(s)}`),this.failPrompt(e,Errors.AgentError.rpcCode,r)}}}async handleToolResult(t,e){const s=e.data,n=s?.toolCall,o=("string"==typeof n?.id?n.id:void 0)??("string"==typeof s?.toolCallId?s.toolCallId:void 0),a=(o?this.state.toolCallIdMap.get(o):void 0)??o??`tc_${e.runId}_${e.seq}`,r=("string"==typeof n?.name?n.name:void 0)??("string"==typeof s?.name?s.name:void 0)??"tool",i="string"==typeof s?.text?s.text:void 0,l=o??a;let c;try{c=await resolveToolResultBlocks({toolCallId:l,toolName:r,rawText:i,rawResult:e.data})}catch{c=i?[{type:"content",content:{type:"text",text:i}}]:[]}if(0===c.length&&i&&(c=[{type:"content",content:{type:"text",text:i}}]),c.length>0){const s=c.filter(t=>t.content&&(t.content.text||t.content.uri||t.content.data)).map(t=>({type:"content",content:t.content})),n={sessionUpdate:"tool_call_update",toolCallId:a,title:r,kind:inferToolKind(r),status:"completed",rawOutput:e.data,...s.length>0?{content:s}:{}};this.transport.sendSessionUpdate(t.sessionId,n)&&(t.assistantMq?.push(n),this.onStreamDelta?.(t,n))}}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){const e=`${this.config.agentGatewayUrl}/api/v1/agent/events`;this.agentFetchFn(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"cron",data:t})}).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";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=50){if(!t?.isConnected)return[];try{const n=parseGatewayHistory(await t.chatHistory(e,o));if(n.length>0){n.filter(t=>"user"===t.role).length,n.filter(t=>"assistant"===t.role).length}return n}catch(t){return[]}}export function groupIntoTurns(t){const e=[];let o=null;const n=()=>{o&&(e.push(o),o=null)};for(const s of t){if("assistant"===s.role&&(s.reasoning||s.toolCalls?.length)){n(),o={role:"assistant",content:s.content,reasoning:s.reasoning,files:s.files},s.toolCalls?.length&&(o.toolCalls=s.toolCalls.map(t=>({id:t.id,callId:t.id,name:t.name,arguments:t.arguments??"",status:t.status??"completed",output:t.output,isError:"error"===t.status||"failed"===t.status,kind:inferToolKindFromName(t.name)})));continue}if("system"===s.role){n();const t={role:"system",content:s.content};s.metadata&&(t.metadata=s.metadata),e.push(t);continue}if("user"===s.role){n();const t={role:"user",content:s.content};s.provenance&&(t.provenance=s.provenance),s.metadata&&(t.metadata=s.metadata),e.push(t);continue}o||(o={role:"assistant",content:""});switch(s.updateType??"agent_message_chunk"){case"agent_thought_chunk":o.reasoning=(o.reasoning??"")+s.content;break;case"tool_call":o.toolCalls||(o.toolCalls=[]),o.toolCalls.push({id:s.toolCallId??`tc_${o.toolCalls.length}`,callId:s.toolCallId??`tc_${o.toolCalls.length}`,name:s.toolName??"tool",arguments:s.content||"",status:"completed",kind:inferToolKindFromName(s.toolName)});break;case"tool_call_update":{o.toolCalls||(o.toolCalls=[]);const t=s.toolCallId?o.toolCalls.find(t=>t.id===s.toolCallId):void 0;t?(t.output=s.content,t.status="completed"):o.toolCalls.push({id:s.toolCallId??`tc_${o.toolCalls.length}`,callId:s.toolCallId??`tc_${o.toolCalls.length}`,name:s.toolName??"tool",arguments:"",status:"completed",output:s.content,kind:inferToolKindFromName(s.toolName)});break}default:o.content+=s.content,s.files?.length&&(o.files=[...o.files??[],...s.files])}}return n(),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 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 n=null;for(const t of e){if(!t||"object"!=typeof t)continue;const e=t,s="string"==typeof e.role?e.role:"assistant";if("toolResult"===s||"tool"===s){if(!n?.toolCalls?.length)continue;const t=String(e.toolCallId??e.tool_call_id??e.toolUseId??e.tool_use_id??""),o=extractBlockText(e.content);if(t){const s=n.toolCalls.find(e=>e.id===t);if(s)s.output=o,!0!==e.is_error&&!0!==e.isError||(s.status="error");else{const t=n.toolCalls.find(t=>void 0===t.output);t&&(t.output=o,!0!==e.is_error&&!0!==e.isError||(t.status="error"))}}else{const t=n.toolCalls.find(t=>void 0===t.output);t&&(t.output=o,!0!==e.is_error&&!0!==e.isError||(t.status="error"))}continue}if("user"===s&&n?.toolCalls?.length&&Array.isArray(e.content)){let t=!1,o=!1;for(const n of e.content){if(!n||"object"!=typeof n)continue;const e=n,s="string"==typeof e.type?e.type:"";TOOL_RESULT_BLOCK_TYPES.has(s)?t=!0:"text"===s&&"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 s=String(e.toolUseId??e.tool_use_id??e.toolCallId??e.tool_call_id??""),i="string"==typeof e.output?e.output:extractBlockText(e.content);if(s){const t=n.toolCalls.find(t=>t.id===s);if(t)t.output=i,!0!==e.is_error&&!0!==e.isError||(t.status="error");else{const t=n.toolCalls.find(t=>void 0===t.output);t&&(t.output=i,!0!==e.is_error&&!0!==e.isError||(t.status="error"))}}else{const t=n.toolCalls.find(t=>void 0===t.output);t&&(t.output=i,!0!==e.is_error&&!0!==e.isError||(t.status="error"))}}continue}}const i="user"===s?"user":"assistant";let r,l,a,c,u,p="";if("string"==typeof e.content)p=e.content;else if(Array.isArray(e.content))for(const t of e.content){if("string"==typeof t){p+=t;continue}if(!t||"object"!=typeof t)continue;const e=t,o="string"==typeof e.type?e.type:"";if("text"===o&&"string"==typeof e.text)p+=e.text;else if("thinking"===o&&"string"==typeof e.thinking)l=(l??"")+e.thinking;else if("resource_link"===o&&"string"==typeof e.uri&&e.uri)a||(a=[]),a.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(o)){r||(r=[]);const t=e.arguments??e.input,o="string"==typeof t?t:null!=t?JSON.stringify(t):"";r.push({id:String(e.id??e.toolCallId??e.tool_call_id??""),name:String(e.name??"tool"),arguments:o,status:"completed"})}else if(TOOL_RESULT_BLOCK_TYPES.has(o)){const t=String(e.toolUseId??e.tool_use_id??e.toolCallId??e.tool_call_id??""),o="string"==typeof e.output?e.output:extractBlockText(e.content),n=!0===e.is_error||!0===e.isError;if(r){const e=t?r.find(e=>e.id===t):void 0;if(e)e.output=o,n&&(e.status="error");else{const t=r.find(t=>void 0===t.output);t&&(t.output=o,n&&(t.status="error"))}}}}if(l||("string"==typeof e.reasoning&&e.reasoning?l=e.reasoning:"string"==typeof e.thinking&&e.thinking&&(l=e.thinking)),!r?.length){const t=e.tool_calls??e.toolCalls;if(Array.isArray(t)){r=[];for(const e of t){if(!e||"object"!=typeof e)continue;const t=e,o=t.function;r.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??"completed"),output:"string"==typeof t.output?t.output:void 0})}0===r.length&&(r=void 0)}}if("user"===i&&p){p=stripBeeosUserEnvelope(p);const t=CANVAS_INTERACTION_RE.exec(p);if(t){const e=t[1];c={kind:"canvas_action"};const o={type:"canvas_action",actionName:e,surfaceId:t[2]},n=ACTION_CONTEXT_RE.exec(p);if(n)try{o.actionPayload=JSON.parse(n[1])}catch{}u=o,p=`Clicked "${e}"`}}if(!(p||l||r?.length||a?.length))continue;if(!c&&"user"===i&&e.provenance&&"object"==typeof e.provenance){const t=e.provenance;"string"==typeof t.kind&&(c={kind:t.kind},"string"==typeof t.sourceTool&&(c.sourceTool=t.sourceTool))}const f={role:i,content:p,reasoning:l,toolCalls:r,provenance:c,metadata:u,files:a};o.push(f),"assistant"===i&&(n=f)}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 n of t.matchAll(o))e.set(n[1],n[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 n of t.matchAll(BEEOS_REF_RE)){const s=t.slice(o,n.index).trim();s&&e.push({type:"text",text:s});const i=parseBeeosRefAttrs(n[1]),r=i.get("id"),l=i.get("name"),a=i.get("status");r&&"download_failed"!==a?e.push({type:"resource_link",uri:`beeos-file://${r}`,fileName:l,mimeType:guessMimeFromName(l)??"application/octet-stream"}):r&&e.push({type:"resource_link",uri:`beeos-file://${r}`,fileName:l??"file",mimeType:guessMimeFromName(l)??"application/octet-stream"}),o=(n.index??0)+n[0].length}const n=t.slice(o).trim();return n&&e.push({type:"text",text:n}),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 n of t.matchAll(ATTACHMENT_MARKER_RE)){const s=t.slice(o,n.index).trim();s&&e.push({type:"text",text:s});const i=n[1],r=n[2],l=new Map;for(const t of r.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=(n.index??0)+n[0].length}const n=t.slice(o).trim();return n&&e.push({type:"text",text:n}),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";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=50){if(!t?.isConnected)return[];try{const n=parseGatewayHistory(await t.chatHistory(e,o));if(n.length>0){n.filter(t=>"user"===t.role).length,n.filter(t=>"assistant"===t.role).length}return n}catch(t){return[]}}export function groupIntoTurns(t){const e=[];let o=null;const n=()=>{o&&(e.push(o),o=null)};for(const s of t){if("assistant"===s.role&&(s.reasoning||s.toolCalls?.length)){n(),o={role:"assistant",content:s.content,reasoning:s.reasoning,files:s.files},s.toolCalls?.length&&(o.toolCalls=s.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"===s.role){n();const t={role:"system",content:s.content};s.metadata&&(t.metadata=s.metadata),e.push(t);continue}if("user"===s.role){n();const t={role:"user",content:s.content};s.provenance&&(t.provenance=s.provenance),s.metadata&&(t.metadata=s.metadata),e.push(t);continue}o||(o={role:"assistant",content:""});switch(s.updateType??"agent_message_chunk"){case"agent_thought_chunk":o.reasoning=(o.reasoning??"")+s.content;break;case"tool_call":o.toolCalls||(o.toolCalls=[]),o.toolCalls.push({id:s.toolCallId??`tc_${o.toolCalls.length}`,callId:s.toolCallId??`tc_${o.toolCalls.length}`,name:s.toolName??"tool",arguments:s.content||"",status:"in_progress",kind:inferToolKindFromName(s.toolName)});break;case"tool_call_update":{o.toolCalls||(o.toolCalls=[]);const t=s.toolCallId?o.toolCalls.find(t=>t.id===s.toolCallId):void 0;t?(t.output=s.content,t.status="completed"):o.toolCalls.push({id:s.toolCallId??`tc_${o.toolCalls.length}`,callId:s.toolCallId??`tc_${o.toolCalls.length}`,name:s.toolName??"tool",arguments:"",status:"completed",output:s.content,kind:inferToolKindFromName(s.toolName)});break}default:o.content+=s.content,s.files?.length&&(o.files=[...o.files??[],...s.files])}}return n(),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 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 n=null;for(const t of e){if(!t||"object"!=typeof t)continue;const e=t,s="string"==typeof e.role?e.role:"assistant";if("toolResult"===s||"tool"===s){if(!n?.toolCalls?.length)continue;const t=String(e.toolCallId??e.tool_call_id??e.toolUseId??e.tool_use_id??""),o=extractBlockText(e.content);if(t){const s=n.toolCalls.find(e=>e.id===t);if(s)s.output=o,s.status=!0===e.is_error||!0===e.isError?"error":"completed";else{const t=n.toolCalls.find(t=>void 0===t.output);t&&(t.output=o,t.status=!0===e.is_error||!0===e.isError?"error":"completed")}}else{const t=n.toolCalls.find(t=>void 0===t.output);t&&(t.output=o,t.status=!0===e.is_error||!0===e.isError?"error":"completed")}continue}if("user"===s&&n?.toolCalls?.length&&Array.isArray(e.content)){let t=!1,o=!1;for(const n of e.content){if(!n||"object"!=typeof n)continue;const e=n,s="string"==typeof e.type?e.type:"";TOOL_RESULT_BLOCK_TYPES.has(s)?t=!0:"text"===s&&"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 s=String(e.toolUseId??e.tool_use_id??e.toolCallId??e.tool_call_id??""),i="string"==typeof e.output?e.output:extractBlockText(e.content),l=!0===e.is_error||!0===e.isError;if(s){const t=n.toolCalls.find(t=>t.id===s);if(t)t.output=i,t.status=l?"error":"completed";else{const t=n.toolCalls.find(t=>void 0===t.output);t&&(t.output=i,t.status=l?"error":"completed")}}else{const t=n.toolCalls.find(t=>void 0===t.output);t&&(t.output=i,t.status=l?"error":"completed")}}continue}}const i="user"===s?"user":"assistant";let l,r,a,c,u,p="";if("string"==typeof e.content)p=e.content;else if(Array.isArray(e.content))for(const t of e.content){if("string"==typeof t){p+=t;continue}if(!t||"object"!=typeof t)continue;const e=t,o="string"==typeof e.type?e.type:"";if("text"===o&&"string"==typeof e.text)p+=e.text;else if("thinking"===o&&"string"==typeof e.thinking)r=(r??"")+e.thinking;else if("resource_link"===o&&"string"==typeof e.uri&&e.uri)a||(a=[]),a.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(o)){l||(l=[]);const t=e.arguments??e.input,o="string"==typeof t?t:null!=t?JSON.stringify(t):"";l.push({id:String(e.id??e.toolCallId??e.tool_call_id??""),name:String(e.name??"tool"),arguments:o,status:"in_progress"})}else if(TOOL_RESULT_BLOCK_TYPES.has(o)){const t=String(e.toolUseId??e.tool_use_id??e.toolCallId??e.tool_call_id??""),o="string"==typeof e.output?e.output:extractBlockText(e.content),n=!0===e.is_error||!0===e.isError;if(l){const e=t?l.find(e=>e.id===t):void 0;if(e)e.output=o,e.status=n?"error":"completed";else{const t=l.find(t=>void 0===t.output);t&&(t.output=o,t.status=n?"error":"completed")}}}}if(r||("string"==typeof e.reasoning&&e.reasoning?r=e.reasoning:"string"==typeof e.thinking&&e.thinking&&(r=e.thinking)),!l?.length){const t=e.tool_calls??e.toolCalls;if(Array.isArray(t)){l=[];for(const e of t){if(!e||"object"!=typeof e)continue;const t=e,o=t.function;l.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===l.length&&(l=void 0)}}if("user"===i&&p){p=stripBeeosUserEnvelope(p);const t=CANVAS_INTERACTION_RE.exec(p);if(t){const e=t[1];c={kind:"canvas_action"};const o={type:"canvas_action",actionName:e,surfaceId:t[2]},n=ACTION_CONTEXT_RE.exec(p);if(n)try{o.actionPayload=JSON.parse(n[1])}catch{}u=o,p=`Clicked "${e}"`}}if(!(p||r||l?.length||a?.length))continue;if(!c&&"user"===i&&e.provenance&&"object"==typeof e.provenance){const t=e.provenance;"string"==typeof t.kind&&(c={kind:t.kind},"string"==typeof t.sourceTool&&(c.sourceTool=t.sourceTool))}const f={role:i,content:p,reasoning:r,toolCalls:l,provenance:c,metadata:u,files:a};o.push(f),"assistant"===i&&(n=f)}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 n of t.matchAll(o))e.set(n[1],n[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 n of t.matchAll(BEEOS_REF_RE)){const s=t.slice(o,n.index).trim();s&&e.push({type:"text",text:s});const i=parseBeeosRefAttrs(n[1]),l=i.get("id"),r=i.get("name"),a=i.get("status");l&&"download_failed"!==a?e.push({type:"resource_link",uri:`beeos-file://${l}`,fileName:r,mimeType:guessMimeFromName(r)??"application/octet-stream"}):l&&e.push({type:"resource_link",uri:`beeos-file://${l}`,fileName:r??"file",mimeType:guessMimeFromName(r)??"application/octet-stream"}),o=(n.index??0)+n[0].length}const n=t.slice(o).trim();return n&&e.push({type:"text",text:n}),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 n of t.matchAll(ATTACHMENT_MARKER_RE)){const s=t.slice(o,n.index).trim();s&&e.push({type:"text",text:s});const i=n[1],l=n[2],r=new Map;for(const t of l.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=(n.index??0)+n[0].length}const n=t.slice(o).trim();return n&&e.push({type:"text",text:n}),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{MessageQueue}from"../utils/mq.js";const MAX_TOOL_CALL_MAP_ENTRIES=5e3;export class AcpGatewaySessionState{sessions=new Map;promptsByRunId=new Map;sessionsByGatewayKey=new Map;toolCallIdMap=new Map;toolCallToSessionMap=new Map;nextToolCallSeq=0;lastActiveSessionId;sessionGcTimer=null;MAX_IDLE_SESSION_MS=864e5;SESSION_GC_INTERVAL_MS=3e5;logger;constructor(s){this.logger=s}findSessionByKey(s){return this.sessionsByGatewayKey.get(s)}resolveSessionFromParams(s){const e="string"==typeof s?.sessionId?s.sessionId:void 0;if(e)return this.sessions.get(e)}isCurrentStreamOwner(s,e){return!e||!!s.currentRunId&&e===s.currentRunId}clearPromptTimeout(s){s.promptTimeoutTimer&&(clearTimeout(s.promptTimeoutTimer),s.promptTimeoutTimer=void 0)}clearStreamIdleTimer(s){s.streamIdleTimer&&(clearTimeout(s.streamIdleTimer),s.streamIdleTimer=void 0)}resetForNewRun(s,e,t){this.clearStreamIdleTimer(s),s.currentRunId&&this.promptsByRunId.delete(s.currentRunId),s.currentRunId=void 0,s.assistantMq?.close(),s.assistantMq=new MessageQueue,s.chatReplayDedupKeys.clear(),s.hasAgentAssistantStream=!1,s.hasAgentThinkingStream=!1,s.hasAgentToolStartStream=!1,s.hasAgentToolResultStream=!1,s.chatAssistantTextSoFar=void 0,s.agentAssistantTextSoFar=void 0,s.promptDone=!1,t.resetSessionUpdateCount(e),this.enforceToolCallMapLimits()}enforceToolCallMapLimits(){if(this.toolCallIdMap.size>5e3){const s=this.toolCallIdMap.size-5e3;let e=0;for(const t of this.toolCallIdMap.keys()){if(e>=s)break;this.toolCallToSessionMap.delete(this.toolCallIdMap.get(t)),this.toolCallIdMap.delete(t),e++}}if(this.toolCallToSessionMap.size>5e3){const s=this.toolCallToSessionMap.size-5e3;let e=0;for(const t of this.toolCallToSessionMap.keys()){if(e>=s)break;this.toolCallToSessionMap.delete(t),e++}}}extractAgentAssistantDelta(s,e){const t=(s.chatAssistantTextSoFar??"").length;if(e.delta){const o=s.agentAssistantTextSoFar??"",i=o+e.delta;if(s.agentAssistantTextSoFar=i,t>0&&o.length<t){if(i.length<=t)return;return i.slice(t)}return e.delta}const o=e.text;if(!o)return;const i=s.agentAssistantTextSoFar??"";s.agentAssistantTextSoFar=o;const a=Math.max(i.length,t);if(!(o.length<=a)){if(o.startsWith(i)||0===a)return o.slice(a)||void 0;if(!i.startsWith(o))return o}}startSessionGc(s,e){this.sessionGcTimer=setInterval(()=>this.gcSessions(s,e),this.SESSION_GC_INTERVAL_MS),"object"==typeof this.sessionGcTimer&&"unref"in this.sessionGcTimer&&this.sessionGcTimer.unref()}gcSessions(s,e){const t=Date.now()-this.MAX_IDLE_SESSION_MS;let o=0;for(const[i,a]of this.sessions){if(void 0!==a.pendingPromptId)continue;(a.lastStreamActivityTs??a.createdAt)<t&&(s(a),e?.(a),this.sessions.delete(i),this.sessionsByGatewayKey.delete(a.gatewaySessionKey),o++)}const i=new Set(Array.from(this.sessions.values()).map(s=>s.sessionId));for(const[s,e]of this.toolCallToSessionMap)i.has(e)||this.toolCallToSessionMap.delete(s);for(const[s,e]of this.toolCallIdMap)this.toolCallToSessionMap.has(e)||this.toolCallIdMap.delete(s);o>0&&(this.lastActiveSessionId&&!this.sessions.has(this.lastActiveSessionId)&&(this.lastActiveSessionId=void 0),this.logger.debug?.(`[session-state] GC evicted ${o} idle sessions, remaining=${this.sessions.size}`))}destroy(){this.sessionGcTimer&&(clearInterval(this.sessionGcTimer),this.sessionGcTimer=null);for(const s of this.sessions.values())this.clearPromptTimeout(s),this.clearStreamIdleTimer(s),s.assistantMq?.close();this.promptsByRunId.clear(),this.toolCallIdMap.clear(),this.toolCallToSessionMap.clear(),this.sessionsByGatewayKey.clear(),this.sessions.clear(),this.lastActiveSessionId=void 0}}
1
+ import{MessageQueue}from"../utils/mq.js";const MAX_TOOL_CALL_MAP_ENTRIES=5e3,MAX_COMPLETED_RUN_IDS=200;export class AcpGatewaySessionState{sessions=new Map;promptsByRunId=new Map;promptsByGatewayRequestId=new Map;sessionsByGatewayKey=new Map;toolCallIdMap=new Map;toolCallToSessionMap=new Map;nextToolCallSeq=0;completedRunIds=new Set;lastActiveSessionId;sessionGcTimer=null;MAX_IDLE_SESSION_MS=864e5;A2A_SESSION_IDLE_MS=3e5;SESSION_GC_INTERVAL_MS=3e5;logger;constructor(s){this.logger=s}findSessionByKey(s){return this.sessionsByGatewayKey.get(s)}resolveSessionFromParams(s){const e="string"==typeof s?.sessionId?s.sessionId:void 0;if(e)return this.sessions.get(e)}isCurrentStreamOwner(s,e){return!e||!!s.currentRunId&&e===s.currentRunId}markRunCompleted(s){if(this.completedRunIds.add(s),this.completedRunIds.size>200){const s=this.completedRunIds.values().next().value;s&&this.completedRunIds.delete(s)}}isRunCompleted(s){return this.completedRunIds.has(s)}clearPromptTimeout(s){s.promptTimeoutTimer&&(clearTimeout(s.promptTimeoutTimer),s.promptTimeoutTimer=void 0)}clearStreamIdleTimer(s){s.streamIdleTimer&&(clearTimeout(s.streamIdleTimer),s.streamIdleTimer=void 0)}resetForNewRun(s,e,t){this.clearStreamIdleTimer(s),s.currentRunId&&this.promptsByRunId.delete(s.currentRunId),s.gatewayRequestId&&this.promptsByGatewayRequestId.delete(s.gatewayRequestId),s.currentRunId=void 0,s.gatewayRequestId=void 0,s.assistantMq?.close(),s.assistantMq=new MessageQueue,s.chatReplayDedupKeys.clear(),s.hasAgentAssistantStream=!1,s.hasAgentThinkingStream=!1,s.hasAgentToolStartStream=!1,s.hasAgentToolResultStream=!1,s.chatAssistantTextSoFar=void 0,s.agentAssistantTextSoFar=void 0,s.promptDone=!1,t.resetSessionUpdateCount(e),this.enforceToolCallMapLimits()}enforceToolCallMapLimits(){if(this.toolCallIdMap.size>5e3){const s=this.toolCallIdMap.size-5e3;let e=0;for(const t of this.toolCallIdMap.keys()){if(e>=s)break;this.toolCallToSessionMap.delete(this.toolCallIdMap.get(t)),this.toolCallIdMap.delete(t),e++}}if(this.toolCallToSessionMap.size>5e3){const s=this.toolCallToSessionMap.size-5e3;let e=0;for(const t of this.toolCallToSessionMap.keys()){if(e>=s)break;this.toolCallToSessionMap.delete(t),e++}}}extractAgentAssistantDelta(s,e){const t=(s.chatAssistantTextSoFar??"").length;if(e.delta){const o=s.agentAssistantTextSoFar??"",i=o+e.delta;if(s.agentAssistantTextSoFar=i,t>0&&o.length<t){if(i.length<=t)return;return i.slice(t)}return e.delta}const o=e.text;if(!o)return;const i=s.agentAssistantTextSoFar??"";s.agentAssistantTextSoFar=o;const a=Math.max(i.length,t);if(!(o.length<=a)){if(o.startsWith(i)||0===a)return o.slice(a)||void 0;if(!i.startsWith(o))return o}}startSessionGc(s,e){this.sessionGcTimer=setInterval(()=>this.gcSessions(s,e),this.SESSION_GC_INTERVAL_MS),"object"==typeof this.sessionGcTimer&&"unref"in this.sessionGcTimer&&this.sessionGcTimer.unref()}gcSessions(s,e){const t=Date.now();let o=0;for(const[i,a]of this.sessions){if(void 0!==a.pendingPromptId)continue;(a.lastStreamActivityTs??a.createdAt)<t-(a.gatewaySessionKey.includes(":a2a:")?this.A2A_SESSION_IDLE_MS:this.MAX_IDLE_SESSION_MS)&&(s(a),e?.(a),this.sessions.delete(i),this.sessionsByGatewayKey.delete(a.gatewaySessionKey),o++)}const i=new Set(Array.from(this.sessions.values()).map(s=>s.sessionId));for(const[s,e]of this.toolCallToSessionMap)i.has(e)||this.toolCallToSessionMap.delete(s);for(const[s,e]of this.toolCallIdMap)this.toolCallToSessionMap.has(e)||this.toolCallIdMap.delete(s);o>0&&(this.lastActiveSessionId&&!this.sessions.has(this.lastActiveSessionId)&&(this.lastActiveSessionId=void 0),this.logger.debug?.(`[session-state] GC evicted ${o} idle sessions, remaining=${this.sessions.size}`))}destroy(){this.sessionGcTimer&&(clearInterval(this.sessionGcTimer),this.sessionGcTimer=null);for(const s of this.sessions.values())this.clearPromptTimeout(s),this.clearStreamIdleTimer(s),s.assistantMq?.close();this.promptsByRunId.clear(),this.promptsByGatewayRequestId.clear(),this.completedRunIds.clear(),this.toolCallIdMap.clear(),this.toolCallToSessionMap.clear(),this.sessionsByGatewayKey.clear(),this.sessions.clear(),this.lastActiveSessionId=void 0}}
@@ -1 +1 @@
1
- import{acpError}from"../errors/index.js";export class AcpTransport{debugIndex=0;sendBridgeMessage;obs;forward;sessionUpdateCounts=new Map;constructor(e,t,s){this.sendBridgeMessage=e,this.obs=t??(()=>{}),this.forward=s??{forwardThinking:!0,forwardToolCalls:!0}}get forwardControl(){return this.forward}nextMeta(){return{_debug_index:this.debugIndex++,_ts:Date.now()}}sendResult(e,t){const s=this.nextMeta();this.detectProtocolError(e,t,s._debug_index);const r={jsonrpc:"2.0",id:e,result:this.attachMeta(t,s),_debug_index:s._debug_index,_ts:s._ts};this.sendBridgeMessage(r),this.obs({component:"acp-transport",domain:"reply",name:"rpc.result",severity:"debug",payload:{id:e,_debug_index:s._debug_index}})}sendError(e,t,s,r){const o=this.nextMeta(),n={code:t,message:s};n.data=void 0!==r?this.attachMeta(r,o):{_meta:o};const d={jsonrpc:"2.0",id:e,error:n,_debug_index:o._debug_index,_ts:o._ts};this.sendBridgeMessage(d),this.obs({component:"acp-transport",domain:"reply",name:"rpc.error",severity:"warn",payload:{id:e,code:t,message:s,_debug_index:o._debug_index}})}sendAcpError(e,t,s){const r=acpError(t,s);this.sendError(e,r.code,r.message,r.data)}sendNotification(e,t){const s=this.nextMeta(),r={jsonrpc:"2.0",method:e,params:t,_debug_index:s._debug_index,_ts:s._ts};this.sendBridgeMessage(r)}enrichWithTurnId(e,t){return t?{...e,_turnId:t}:e}sendSessionUpdate(e,t,s){const r=t,o=r?.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 n=(this.sessionUpdateCounts.get(e)??0)+1;return this.sessionUpdateCounts.set(e,n),n%50==0&&this.obs({component:"acp-transport",domain:"session-update",name:"send.rate",severity:"debug",payload:{sessionId:e,totalSent:n,lastType:o,_debug_index:this.debugIndex}}),this.sendNotification("session/update",{sessionId:e,update:this.enrichWithTurnId(t,s)}),!0}resetSessionUpdateCount(e){this.sessionUpdateCounts.delete(e)}sendCronSessionUpdate(e,t,s){return this.sendNotification("session/update",{sessionId:e,update:this.enrichWithTurnId(t,s.requestId),_meta:{...this.nextMeta(),...s}}),!0}detectProtocolError(e,t,s){if(!t||"object"!=typeof t)return;const r=t,o="error"in r&&null!=r.error,n="ok"in r&&!1===r.ok;(o||n)&&this.obs({component:"acp-transport",domain:"reply",name:"protocol.error_in_result",severity:"warn",payload:{id:e,_debug_index:s,hasError:o,notOk:n,errorSummary:o?"string"==typeof r.error?r.error.slice(0,200):JSON.stringify(r.error).slice(0,200):void 0}})}attachMeta(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:{...e,_meta:t}}}
1
+ import{acpError}from"../errors/index.js";export class AcpTransport{debugIndex=0;sendBridgeMessage;obs;forward;sessionUpdateCounts=new Map;_isReady;constructor(e,t,s,r){this.sendBridgeMessage=e,this.obs=t??(()=>{}),this.forward=s??{forwardThinking:!0,forwardToolCalls:!0},this._isReady=r}isReady(){return!this._isReady||this._isReady()}get forwardControl(){return this.forward}nextMeta(){return{_debug_index:this.debugIndex++,_ts:Date.now()}}sendResult(e,t){const s=this.nextMeta();this.detectProtocolError(e,t,s._debug_index);const r={jsonrpc:"2.0",id:e,result:this.attachMeta(t,s),_debug_index:s._debug_index,_ts:s._ts};this.sendBridgeMessage(r),this.obs({component:"acp-transport",domain:"reply",name:"rpc.result",severity:"debug",payload:{id:e,_debug_index:s._debug_index}})}sendError(e,t,s,r){const o=this.nextMeta(),n={code:t,message:s};n.data=void 0!==r?this.attachMeta(r,o):{_meta:o};const i={jsonrpc:"2.0",id:e,error:n,_debug_index:o._debug_index,_ts:o._ts};this.sendBridgeMessage(i),this.obs({component:"acp-transport",domain:"reply",name:"rpc.error",severity:"warn",payload:{id:e,code:t,message:s,_debug_index:o._debug_index}})}sendAcpError(e,t,s){const r=acpError(t,s);this.sendError(e,r.code,r.message,r.data)}sendNotification(e,t){const s=this.nextMeta(),r={jsonrpc:"2.0",method:e,params:t,_debug_index:s._debug_index,_ts:s._ts};this.sendBridgeMessage(r)}enrichWithTurnId(e,t){return t?{...e,_turnId:t}:e}sendSessionUpdate(e,t,s){const r=t,o=r?.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 n=(this.sessionUpdateCounts.get(e)??0)+1;return this.sessionUpdateCounts.set(e,n),n%50==0&&this.obs({component:"acp-transport",domain:"session-update",name:"send.rate",severity:"debug",payload:{sessionId:e,totalSent:n,lastType:o,_debug_index:this.debugIndex}}),this.sendNotification("session/update",{sessionId:e,update:this.enrichWithTurnId(t,s)}),!0}resetSessionUpdateCount(e){this.sessionUpdateCounts.delete(e)}sendCronSessionUpdate(e,t,s){return this.sendNotification("session/update",{sessionId:e,update:this.enrichWithTurnId(t,s.requestId),_meta:{...this.nextMeta(),...s}}),!0}detectProtocolError(e,t,s){if(!t||"object"!=typeof t)return;const r=t,o="error"in r&&null!=r.error,n="ok"in r&&!1===r.ok;(o||n)&&this.obs({component:"acp-transport",domain:"reply",name:"protocol.error_in_result",severity:"warn",payload:{id:e,_debug_index:s,hasError:o,notOk:n,errorSummary:o?"string"==typeof r.error?r.error.slice(0,200):JSON.stringify(r.error).slice(0,200):void 0}})}attachMeta(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:{...e,_meta:t}}}
@@ -1 +1 @@
1
- import{WebSocketServer,WebSocket}from"ws";let BridgeClientCtor;import{GatewayClient}from"./gateway-client.js";import{TerminalManager}from"./terminal/session-manager.js";import{AcpTransport}from"./acp-gateway/transport.js";import{AcpGatewaySessionState}from"./acp-gateway/session-state.js";import{AcpGatewayBridgeCore}from"./acp-gateway/bridge-core.js";import{BeeosFileResolver}from"./acp-gateway/beeos-file-resolver.js";import{AcpGatewayEvents}from"./acp-gateway/gateway-events.js";import{TerminalBridgeHandler}from"./terminal/bridge-handler.js";import{syncAgentsToPlatform}from"./agent-sync.js";import{CanvasOrchestrator}from"./canvas-orchestrator.js";import{A2AOrchestrator}from"./a2a-orchestrator.js";import{discoverBridgeFromGW}from"./bridge-discovery.js";import{writeDiscoveryCache}from"./discovery-cache.js";export class ACPServer{agentFetchFn;instanceId;wss=null;gateway=null;client=null;config;logger;writeObs;transport;state;core;events;terminalMgr;terminalHandler;canvasOrch;a2aOrch;pendingToolCallSessionKeys=[];thirdPartyChannels;agentSyncRetryTimer=null;bridgeInstance=null;bridgeConsecutiveFailures=0;static RE_DISCOVER_THRESHOLD=5;drainNextDeferredSend(e){this.a2aOrch.drainNextDeferredSend(e,(e,t,s,n)=>this.agentSend(e,t,s,n))}async gatewayRequest(e,t){if(!this.gateway?.isConnected)throw new Error("Gateway not connected");return this.gateway.request(e,t)}async agentSend(e,t,s,n){if(!this.gateway?.isConnected)throw new Error("Gateway not connected");const i=this.config.gateway.agentId||this.core.getDefaultAgentId();let a,r;if(s){if(a=this.state.findSessionByKey(s),!a)return void this.logger.warn?.("[acp-server] A2A result target session expired, discarding targetSessionKey=%s (known keys: %s)",s,[...this.state.sessionsByGatewayKey.keys()].join(", "));r=s,this.logger.info?.(`[acp-server] agentSend: resolved session for key=${s} sid=${a.sessionId}`)}else{const e=this.state.lastActiveSessionId;a=e?this.state.sessions.get(e):void 0,r=a?.gatewaySessionKey??`agent:${i}:a2a`,this.logger.info?.(`[acp-server] agentSend: no targetSessionKey, using fallback key=${r}`)}if(a&&!a.promptDone&&(void 0!==a.pendingPromptId||void 0!==a.currentRunId))return(a.pendingAgentSends??=[]).push({message:e,attachments:t,inputProvenance:n}),void this.logger.info?.("[acp-server] Session has active run, deferred message (queue=%d)",a.pendingAgentSends.length);const o=await this.canvasOrch.enrichMessageWithCanvasContext(e,r,this.thirdPartyChannels),c=await this.gateway.agentSend(r,o,i,t,n);return a&&c?.runId&&(this.state.resetForNewRun(a,a.sessionId,this.transport),a.currentRunId=c.runId,a.assistantStreamStartedAt=Date.now(),this.state.promptsByRunId.set(c.runId,a)),c}trackA2ARun(e,t,s){this.a2aOrch.trackA2ARun(e,t,s)}cancelA2ARunByTaskId(e){return this.a2aOrch.cancelA2ARunByTaskId(e)}emitA2ASystemNotification(e){this.a2aOrch.emitA2ASystemNotification(e)}sendBridgeMessage=e=>{const t=this.client;if(t&&t.readyState===WebSocket.OPEN)try{t.send(JSON.stringify(e))}catch(e){this.logger.debug?.("[acp-server] bridge send failed (socket may be closing):",e)}else this.logger.debug?.("[acp-server] bridge not ready, dropping message")};constructor(e,t,s,n,i,a){this.agentFetchFn=n,this.instanceId=i,this.config=e,this.logger=t,this.writeObs=s??(()=>{}),this.thirdPartyChannels=a??new Set,this.transport=new AcpTransport(this.sendBridgeMessage,this.writeObs),this.state=new AcpGatewaySessionState(this.logger);const r=this.agentFetchFn&&this.config.agentGatewayUrl?new BeeosFileResolver({agentGatewayUrl:this.config.agentGatewayUrl,agentFetch:this.agentFetchFn,writeObs:this.writeObs}):void 0;this.core=new AcpGatewayBridgeCore({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,getGateway:()=>this.gateway,instanceId:this.instanceId,thirdPartyChannels:this.thirdPartyChannels,beeosFileResolver:r}),this.canvasOrch=new CanvasOrchestrator({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,getSessionIdForToolCall:e=>this.getSessionIdForToolCall(e),gateway:null,getDefaultAgentId:()=>this.core.getDefaultAgentId(),resolvePlatformAgentId:e=>this.core.resolvePlatformAgentId(e)??""}),this.a2aOrch=new A2AOrchestrator({state:this.state,transport:this.transport,logger:this.logger}),this.events=new AcpGatewayEvents({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,completePrompt:(e,t)=>{this.core.completePrompt(e,t),this.canvasOrch.onPromptComplete(e),this.drainNextDeferredSend(e)},failPrompt:(e,t,s)=>{this.core.failPrompt(e,t,s),this.canvasOrch.onPromptFailed(),this.drainNextDeferredSend(e)},maybeCompletePromptFromChatState:(e,t)=>this.core.maybeCompletePromptFromChatState(e,t),agentFetch:this.agentFetchFn}),this.terminalMgr=new TerminalManager,this.terminalHandler=new TerminalBridgeHandler({terminalMgr:this.terminalMgr,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs}),this.terminalHandler.setupListeners(),this.core.handleTerminalRequest=e=>this.terminalHandler.handleRequest(e),this.core.handleTerminalNotification=(e,t)=>this.terminalHandler.handleNotification(e,t),this.core.onRunComplete=(e,t)=>{this.a2aOrch.onRunComplete(e,t)},this.core.onRunFailed=(e,t)=>{this.a2aOrch.onRunFailed(e,t)},this.core.handleCanvasNotification=(e,t)=>{this.canvasOrch.handleCanvasNotification(e,t)},this.core.getCanvasState=()=>this.canvasOrch.canvasState,this.core.onSessionLoaded=(e,t,s)=>{this.canvasOrch.onSessionLoaded(e,t,s)},this.core.onSessionDeleted=e=>{this.canvasOrch.onSessionDeleted(e)},this.core.onSessionCleared=(e,t)=>{this.canvasOrch.onSessionCleared(e,t)},this.core.handleSlashCommand=async e=>this.canvasOrch.handleSlashCommand(e),this.core.onPromptStart=()=>{this.canvasOrch.onPromptStart()},this.state.startSessionGc(e=>this.core.cleanupPrompt(e),e=>{this.canvasOrch.canvasState?.removeSession(e.gatewaySessionKey),this.transport.resetSessionUpdateCount(e.sessionId)})}async start(e){e&&(this.config.bridge.url=e);const t=this.config.bridge.url,s=this.config.keyFile;if(t&&!BridgeClientCtor)try{const e=await import("@beeos-ai/bridge-client");BridgeClientCtor=e.BridgeClient}catch(e){this.logger.warn?.("[acp-server] Bridge SDK not available")}await this.connectGateway(),t&&s&&BridgeClientCtor?await this.startBridgeMode(t,s):(this.logger.warn?.("[acp-server] Bridge not configured; running in standby (no ACP listener). Use handleUpgrade() for noServer mode."),this.core.markAgentSyncDone())}async startBridgeMode(e,t){if(!BridgeClientCtor)throw new Error("@beeos-ai/bridge-client not available");const s=new BridgeClientCtor({bridgeUrl:e,service:this.config.bridge.service||"acp",keyFile:t});this.bridgeInstance=s,s.on("connected",()=>{this.bridgeConsecutiveFailures=0,this.logger.info?.("[acp-server] Connected to Bridge (publicKey auth)"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"bridge.connected",severity:"info"}),this.tryAgentSync()}),s.on("disconnected",(...e)=>{const n=String(e[0]??"unknown");if(this.logger.warn?.(`[acp-server] Bridge disconnected: ${n}`),this.core.initialized=!1,this.bridgeConsecutiveFailures++,this.bridgeConsecutiveFailures>=ACPServer.RE_DISCOVER_THRESHOLD&&this.agentFetchFn&&this.config.agentGatewayUrl){this.bridgeConsecutiveFailures=0;const e=this.config.bridge.url;discoverBridgeFromGW(this.config.agentGatewayUrl,this.agentFetchFn).then(async n=>{n&&n.url!==e&&(this.logger.info?.(`[acp-server] Bridge re-discovery: URL changed ${e} → ${n.url}, switching`),this.config.bridge.url=n.url,writeDiscoveryCache({bridge:{url:n.url,discoveredAt:Date.now()}}),await s.close(!1),await this.startBridgeMode(n.url,t))}).catch(()=>{})}}),s.on("message",(...e)=>{const t=e[0],s="string"==typeof t?t:Buffer.from(t).toString("utf-8");try{const e=JSON.parse(s);"id"in e&&void 0!==e.id?this.core.handleRequest(e):this.core.handleNotification(e)}catch{this.logger.error?.("[acp-server] Invalid JSON-RPC message from Bridge")}}),s.on("error",(...e)=>{const t=e[0];this.logger.error?.("[acp-server] Bridge error:",t?.message)});const n={readyState:WebSocket.OPEN,send:(e,t)=>{try{s.send(e),t?.()}catch(e){t?.(e)}},close:()=>s.close(),terminate:()=>s.close(!1),on:()=>n,once:()=>n,removeListener:()=>n,removeAllListeners:()=>n,ping:()=>{}};Object.defineProperty(n,"readyState",{get:()=>"connected"===s.state?WebSocket.OPEN:WebSocket.CLOSED}),this.client=n;try{await s.connect()}catch(e){this.logger.warn?.(`[acp-server] Initial bridge connect failed (will retry in background): ${e?.message}`)}this.core.initialized=!1,this.logger.info?.("[acp-server] Running in Bridge mode (WS client)")}handleUpgrade(e,t,s){this.wss||(this.wss=new WebSocketServer({noServer:!0}),this.wss.on("connection",(e,t)=>this.handleConnection(e,t))),this.wss.handleUpgrade(e,t,s,t=>{this.wss.emit("connection",t,e)})}async tryAgentSync(e=0){if(this.agentSyncRetryTimer&&(clearTimeout(this.agentSyncRetryTimer),this.agentSyncRetryTimer=null),!this.client||this.client.readyState!==WebSocket.OPEN)return;if(!this.gateway||!this.agentFetchFn||!this.config.agentGatewayUrl)return void this.core.markAgentSyncDone();const t=()=>{if(e+1>=6)return this.logger.warn?.("[acp-server] agent sync exhausted 6 attempts — giving up"),void this.core.markAgentSyncDone();const t=Math.min(5e3*2**e,12e4);this.logger.info?.(`[acp-server] agent sync retry #${e+1} in ${Math.round(t/1e3)}s`),this.agentSyncRetryTimer=setTimeout(()=>this.tryAgentSync(e+1),t)};try{const e=await syncAgentsToPlatform({gateway:this.gateway,agentGatewayUrl:this.config.agentGatewayUrl,capabilities:{canvas:this.config.canvasEnabled,terminal:!0,fileSystem:!0,cron:!0},agentFetch:this.agentFetchFn,logger:this.logger});e?(this.core.setAgentMapping(e),this.logger.info?.(`[acp-server] agent mapping loaded: ${[...e.keys()].join(", ")}`)):t()}catch(e){this.logger.warn?.(`[acp-server] agent sync failed: ${e}`),t()}}async connectGateway(){this.gateway&&(this.gateway.stop(),this.gateway=null);const e=this.config.gateway;this.gateway=new GatewayClient({url:e.url,token:e.token||"",clientId:e.clientId,openclawCanvasCompat:!!this.config.openclawCanvasCompat,retry:{baseMs:this.config.retry.baseMs,maxMs:this.config.retry.maxMs,maxAttempts:this.config.retry.maxAttempts}}),this.gateway.on("chat",e=>this.events.handleChatEvent(e)),this.gateway.on("agent",e=>this.events.handleAgentEvent(e)),this.gateway.on("cron",e=>this.events.handleCronEvent(e));const t=this.gateway;this.canvasOrch.updateDeps({gateway:t?{get isConnected(){return t.isConnected},request:(e,t)=>this.gateway.request(e,t),agentSend:(e,t,s)=>this.gateway.agentSend(e,t,s)}:null}),this.config.openclawCanvasCompat&&(this.gateway.on("canvas",e=>this.canvasOrch.handleOpenClawCanvasEvent(e)),this.logger.info?.("[acp-server] OpenClaw native canvas compat enabled — listening for canvas events")),this.gateway.on("connected",()=>{this.logger.info?.("[acp-server] Connected to OpenClaw Gateway"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"gateway.connected",severity:"info"})}),this.gateway.on("disconnected",()=>{this.logger.warn?.("[acp-server] Gateway disconnected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"gateway.disconnected",severity:"warn"}),this.core.cleanupAllPendingPrompts()}),this.gateway.on("reconnecting",e=>{this.logger.info?.(`[acp-server] Reconnecting to Gateway attempt=${e.attempt} delay=${Math.round(e.delayMs)}ms`)}),this.gateway.on("reconnect-exhausted",e=>{this.logger.error?.(`[acp-server] Gateway reconnect exhausted after ${e} attempts`)}),this.gateway.on("error",e=>{this.logger.error?.("[acp-server] Gateway error:",e.message)}),this.gateway.on("transport",e=>{this.writeObs({component:"gateway-client",domain:"lifecycle",name:`transport.${e.event}`,severity:"connect_fail"===e.event||"error"===e.event?"warn":"debug",payload:e})}),this.gateway.on("reconnect-notify-scheduled",e=>{this.logger.info?.(`[acp-server] Server-initiated reconnect scheduled in ${e.delayMs}ms`)}),this.gateway.on("reconnect-notify-fired",()=>{this.logger.info?.("[acp-server] Server-initiated reconnect firing")});try{await this.gateway.start()}catch(e){this.logger.error?.("[acp-server] Initial Gateway connect failed:",e)}}handleConnection(e,t){if(this.client){this.logger.warn?.("[acp-server] Replacing existing ACP client with new connection (takeover)");const e=this.client;this.client=null;try{e.close(1008,"replaced by new client")}catch{e.terminate()}}this.client=e,this.core.initialized=!1,this.logger.info?.("[acp-server] ACP client connected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"client.connected",severity:"info"}),e.on("message",e=>{const t="string"==typeof e?e:e.toString("utf-8");try{const e=JSON.parse(t);"id"in e&&void 0!==e.id?this.core.handleRequest(e):this.core.handleNotification(e)}catch{this.logger.error?.("[acp-server] Invalid JSON-RPC message")}}),e.on("close",()=>{this.client===e&&(this.client=null,this.core.initialized=!1),this.logger.info?.("[acp-server] ACP client disconnected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"client.disconnected",severity:"info"})})}pushToolResultContent(e,t,s,n){this.core.pushToolResultContent(e,t,s,n)}setCanvasState(e,t){this.canvasOrch.setCanvasState(e,t)}wireRelayActionHandler(){this.canvasOrch.wireRelayActionHandler()}isCanvasActive(e){return this.canvasOrch.isCanvasActive(e)}isCanvasActiveForGatewayKey(e){return this.canvasOrch.isCanvasActiveForGatewayKey(e)}broadcastNotification(e,t){this.transport.sendNotification(e,t)}getActiveSessionId(){return this.state.lastActiveSessionId}getSessionIdForToolCall(e){const t=this.pendingToolCallSessionKeys.length>0?this.pendingToolCallSessionKeys[this.pendingToolCallSessionKeys.length-1]:void 0;if(t){const s=this.state.findSessionByKey(t)??this.core.ensureSessionForKey(t);if(s?.sessionId)return e&&this.state.toolCallToSessionMap.set(e,s.sessionId),s.sessionId}if(e){const t=this.state.toolCallToSessionMap.get(e);if(t)return t;const s=this.state.toolCallIdMap.get(e);if(s&&s!==e){const e=this.state.toolCallToSessionMap.get(s);if(e)return e}const n=e.split("_");if(n.length>=3&&"tc"===n[0]){const e=n[1],t=this.state.promptsByRunId.get(e);if(t?.sessionId)return t.sessionId}}this.logger.warn?.(`[acp-server] getSessionIdForToolCall MISS: toolCallId=${e??"(none)"}, sessions=${this.state.sessions.size}, pendingKey=${t??"none"}`)}getSessionIdForActivePrompt(){return this.getSessionIdForToolCall()}setPendingToolCallSessionKey(e){e&&(this.pendingToolCallSessionKeys.push(e),this.pendingToolCallSessionKeys.length>16&&this.pendingToolCallSessionKeys.shift())}preMapToolCallSession(e){const t=this.pendingToolCallSessionKeys.length>0?this.pendingToolCallSessionKeys[this.pendingToolCallSessionKeys.length-1]:void 0;if(!t||!e)return;if(this.state.toolCallToSessionMap.has(e))return;const s=this.state.findSessionByKey(t)??this.core.ensureSessionForKey(t);s?.sessionId&&this.state.toolCallToSessionMap.set(e,s.sessionId)}waitForAgentMapping(){return this.core.waitForAgentMapping()}onceAgentMappingReady(e){this.core.onceAgentMappingReady(e)}flushPendingCanvasLinks(){this.canvasOrch.flushPendingCanvasLinks()}onRelayReconnected(){this.canvasOrch.onRelayReconnected()}getDefaultPlatformAgentId(){return this.getDefaultPlatformAgent()?.id}getDefaultPlatformAgent(){const e=this.core.agentMapping;if(e&&0!==e.size)return e.values().next().value??void 0}getPlatformAgentIdForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return this.core.resolvePlatformAgentId(s?.agentId??"")??s?.platformAgentId}getGatewaySessionKeyForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return s?.gatewaySessionKey}getMentionsForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return s?.activeMentions}getResourceRenderer(){return this.canvasOrch.resourceRenderer}getDescriptorRegistry(){return this.canvasOrch.descriptorRegistry}getFormBuilder(){return this.canvasOrch.formBuilder}getSchemaRegistry(){return this.canvasOrch.schemaRegistry}emitCanvasActionAsUserMessage(e,t){this.canvasOrch.emitCanvasActionAsUserMessage(e,t)}async stop(){this.agentSyncRetryTimer&&(clearTimeout(this.agentSyncRetryTimer),this.agentSyncRetryTimer=null),this.state.destroy(),this.a2aOrch.destroy(),this.canvasOrch.destroy(),this.gateway&&(this.gateway.removeAllListeners(),this.gateway.stop(),this.gateway=null),this.client&&(this.client.removeAllListeners(),this.client.close(),this.client=null),this.bridgeInstance=null,this.bridgeConsecutiveFailures=0,this.terminalHandler.destroy(),this.terminalMgr.destroy(),this.wss&&(this.wss.removeAllListeners(),this.wss.close(),this.wss=null),this.logger.info?.("[acp-server] Stopped"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"lifecycle.shutdown",severity:"info"})}}
1
+ import{WebSocketServer,WebSocket}from"ws";import{randomUUID}from"node:crypto";let BridgeClientCtor;import{GatewayClient}from"./gateway-client.js";import{TerminalManager}from"./terminal/session-manager.js";import{AcpTransport}from"./acp-gateway/transport.js";import{AcpGatewaySessionState}from"./acp-gateway/session-state.js";import{AcpGatewayBridgeCore}from"./acp-gateway/bridge-core.js";import{BeeosFileResolver}from"./acp-gateway/beeos-file-resolver.js";import{AcpGatewayEvents}from"./acp-gateway/gateway-events.js";import{TerminalBridgeHandler}from"./terminal/bridge-handler.js";import{syncAgentsToPlatform}from"./agent-sync.js";import{CanvasOrchestrator}from"./canvas-orchestrator.js";import{discoverBridgeFromGW}from"./bridge-discovery.js";import{writeDiscoveryCache}from"./discovery-cache.js";export class ACPServer{agentFetchFn;instanceId;wss=null;gateway=null;client=null;config;logger;writeObs;transport;state;core;events;terminalMgr;terminalHandler;canvasOrch;messageSdk=null;msgPrincipalId=null;pendingToolCallSessionKeys=[];thirdPartyChannels;agentSyncRetryTimer=null;bridgeInstance=null;bridgeConsecutiveFailures=0;static RE_DISCOVER_THRESHOLD=5;drainNextDeferredSend(e){const t=e.pendingAgentSends?.shift();t&&(e.pendingAgentSends?.length||(e.pendingAgentSends=void 0),this.agentSend(t.message,t.attachments,e.gatewaySessionKey,t.inputProvenance).catch(e=>this.logger.warn?.("[acp-server] Deferred agentSend failed: %s",e)))}async gatewayRequest(e,t){if(!this.gateway?.isConnected)throw new Error("Gateway not connected");return this.gateway.request(e,t)}async agentSend(e,t,s,n,i){if(!this.gateway?.isConnected)throw new Error("Gateway not connected");const a=this.config.gateway.agentId||this.core.getDefaultAgentId();let r,o;if(s?(r=this.state.findSessionByKey(s),o=s,r?this.logger.info?.(`[acp-server] agentSend: resolved session for key=${s} sid=${r.sessionId}`):this.logger.info?.(`[acp-server] agentSend: no existing session for key=${s}, gateway will create one`)):(o=`agent:${a}:a2a:${randomUUID()}`,r=this.core.ensureSessionForKey(o),this.logger.info?.(`[acp-server] agentSend: no targetSessionKey, created A2A session key=${o}`)),i&&r&&(r.channelId=i),r&&!r.promptDone&&(void 0!==r.pendingPromptId||void 0!==r.currentRunId||void 0!==r.gatewayRequestId))return(r.pendingAgentSends??=[]).push({message:e,attachments:t,inputProvenance:n}),void this.logger.info?.("[acp-server] Session has active run, deferred message (queue=%d)",r.pendingAgentSends.length);const c=await this.canvasOrch.enrichMessageWithCanvasContext(e,o,this.thirdPartyChannels),l=await this.gateway.agentSend(o,c,a,t,n);return l?.runId&&(r?(this.state.resetForNewRun(r,r.sessionId,this.transport),r.currentRunId=l.runId,r.assistantStreamStartedAt=Date.now(),this.state.promptsByRunId.set(l.runId,r)):this.state.promptsByRunId.set(l.runId,{gatewaySessionKey:o,channelId:i})),l}setMessageSdk(e,t){this.messageSdk=e,this.msgPrincipalId=t}sendBridgeMessage=e=>{const t=this.client;if(t&&t.readyState===WebSocket.OPEN)try{t.send(JSON.stringify(e))}catch(e){this.logger.debug?.("[acp-server] bridge send failed (socket may be closing):",e)}else this.logger.debug?.("[acp-server] bridge not ready, dropping message")};constructor(e,t,s,n,i,a){this.agentFetchFn=n,this.instanceId=i,this.config=e,this.logger=t,this.writeObs=s??(()=>{}),this.thirdPartyChannels=a??new Set,this.transport=new AcpTransport(this.sendBridgeMessage,this.writeObs,void 0,()=>{const e=this.client;return!!e&&e.readyState===WebSocket.OPEN}),this.state=new AcpGatewaySessionState(this.logger);const r=this.agentFetchFn&&this.config.agentGatewayUrl?new BeeosFileResolver({agentGatewayUrl:this.config.agentGatewayUrl,agentFetch:this.agentFetchFn,writeObs:this.writeObs}):void 0;this.core=new AcpGatewayBridgeCore({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,getGateway:()=>this.gateway,instanceId:this.instanceId,thirdPartyChannels:this.thirdPartyChannels,beeosFileResolver:r}),this.canvasOrch=new CanvasOrchestrator({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,getSessionIdForToolCall:e=>this.getSessionIdForToolCall(e),gateway:null,getDefaultAgentId:()=>this.core.getDefaultAgentId(),resolvePlatformAgentId:e=>this.core.resolvePlatformAgentId(e)??""}),this.events=new AcpGatewayEvents({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,completePrompt:(e,t)=>this.core.completePrompt(e,t),failPrompt:(e,t,s)=>this.core.failPrompt(e,t,s),maybeCompletePromptFromChatState:(e,t)=>this.core.maybeCompletePromptFromChatState(e,t),agentFetch:this.agentFetchFn,onStreamDelta:(e,t)=>{if(!this.messageSdk||!this.msgPrincipalId)return;const s=e.gatewaySessionKey;if(!s)return;const n=e.channelId,i={session_key:s,update:t};(n&&this.messageSdk.sendToChannel?this.messageSdk.sendToChannel(n,"agent_reply_delta",i):this.messageSdk.sendToPersonal(this.msgPrincipalId,"agent_reply_delta",i)).catch(e=>this.logger.debug?.(`[acp-server] agent_reply_delta publish failed: ${e}`))}}),this.core.onRunEnded=(e,t)=>{"complete"===t.kind?this.canvasOrch.onPromptComplete(e):this.canvasOrch.onPromptFailed(),this.drainNextDeferredSend(e)},this.terminalMgr=new TerminalManager,this.terminalHandler=new TerminalBridgeHandler({terminalMgr:this.terminalMgr,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs}),this.terminalHandler.setupListeners(),this.core.handleTerminalRequest=e=>this.terminalHandler.handleRequest(e),this.core.handleTerminalNotification=(e,t)=>this.terminalHandler.handleNotification(e,t),this.core.onRunComplete=(e,t)=>{const s=this.state.promptsByRunId.get(e),n=s?.gatewaySessionKey,i=s?.channelId;if(this.logger.info?.(`[acp-server] onRunComplete runId=${e} session_key=${n} channel=${i} principal=${this.msgPrincipalId} hasSDK=${!!this.messageSdk}`),this.messageSdk&&this.msgPrincipalId&&n){const e={session_key:n,text:t};(i&&this.messageSdk.sendToChannel?this.messageSdk.sendToChannel(i,"agent_reply",e):this.messageSdk.sendToPersonal(this.msgPrincipalId,"agent_reply",e)).then(()=>{this.logger.info?.(`[acp-server] agent_reply published ok session_key=${n} channel=${i??"personal"}`)}).catch(e=>this.logger.warn?.(`[acp-server] agent_reply publish failed: ${e instanceof Error?e.message:JSON.stringify(e)}`))}else n||this.logger.warn?.(`[acp-server] onRunComplete: no session_key for runId=${e}, cannot publish reply`)},this.core.onRunFailed=(e,t)=>{const s=this.state.promptsByRunId.get(e),n=s?.gatewaySessionKey,i=s?.channelId;if(this.logger.info?.(`[acp-server] onRunFailed runId=${e} session_key=${n} channel=${i}`),this.messageSdk&&this.msgPrincipalId&&n){const e={session_key:n,error:t||"execution failed"};(i&&this.messageSdk.sendToChannel?this.messageSdk.sendToChannel(i,"agent_reply",e):this.messageSdk.sendToPersonal(this.msgPrincipalId,"agent_reply",e)).catch(e=>this.logger.warn?.(`[acp-server] agent_reply error publish failed: ${e instanceof Error?e.message:String(e)}`))}},this.core.handleCanvasNotification=(e,t)=>{this.canvasOrch.handleCanvasNotification(e,t)},this.core.getCanvasState=()=>this.canvasOrch.canvasState,this.core.onSessionLoaded=(e,t,s)=>{this.canvasOrch.onSessionLoaded(e,t,s)},this.core.onSessionDeleted=e=>{this.canvasOrch.onSessionDeleted(e)},this.core.onSessionCleared=(e,t)=>{this.canvasOrch.onSessionCleared(e,t)},this.core.handleSlashCommand=async e=>this.canvasOrch.handleSlashCommand(e),this.core.onPromptStart=()=>{this.canvasOrch.onPromptStart()},this.state.startSessionGc(e=>this.core.cleanupPrompt(e),e=>{this.canvasOrch.canvasState?.removeSession(e.gatewaySessionKey),this.transport.resetSessionUpdateCount(e.sessionId)})}async start(e){e&&(this.config.bridge.url=e);const t=this.config.bridge.url,s=this.config.keyFile;if(t&&!BridgeClientCtor)try{const e=await import("@beeos-ai/bridge-client");BridgeClientCtor=e.BridgeClient}catch(e){this.logger.warn?.("[acp-server] Bridge SDK not available")}await this.connectGateway(),t&&s&&BridgeClientCtor?await this.startBridgeMode(t,s):(this.logger.warn?.("[acp-server] Bridge not configured; running in standby (no ACP listener). Use handleUpgrade() for noServer mode."),this.core.markAgentSyncDone())}async startBridgeMode(e,t){if(!BridgeClientCtor)throw new Error("@beeos-ai/bridge-client not available");const s=new BridgeClientCtor({bridgeUrl:e,service:this.config.bridge.service||"acp",keyFile:t});this.bridgeInstance=s,s.on("connected",()=>{this.bridgeConsecutiveFailures=0,this.logger.info?.("[acp-server] Connected to Bridge (publicKey auth)"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"bridge.connected",severity:"info"}),this.tryAgentSync()}),s.on("disconnected",(...e)=>{const n=String(e[0]??"unknown");if(this.logger.warn?.(`[acp-server] Bridge disconnected: ${n}`),this.core.initialized=!1,this.bridgeConsecutiveFailures++,this.bridgeConsecutiveFailures>=ACPServer.RE_DISCOVER_THRESHOLD&&this.agentFetchFn&&this.config.agentGatewayUrl){this.bridgeConsecutiveFailures=0;const e=this.config.bridge.url;discoverBridgeFromGW(this.config.agentGatewayUrl,this.agentFetchFn).then(async n=>{n&&n.url!==e&&(this.logger.info?.(`[acp-server] Bridge re-discovery: URL changed ${e} → ${n.url}, switching`),this.config.bridge.url=n.url,writeDiscoveryCache({bridge:{url:n.url,discoveredAt:Date.now()}}),await s.close(!1),await this.startBridgeMode(n.url,t))}).catch(()=>{})}}),s.on("message",(...e)=>{const t=e[0],s="string"==typeof t?t:Buffer.from(t).toString("utf-8");try{const e=JSON.parse(s);"id"in e&&void 0!==e.id?this.core.handleRequest(e):this.core.handleNotification(e)}catch{this.logger.error?.("[acp-server] Invalid JSON-RPC message from Bridge")}}),s.on("error",(...e)=>{const t=e[0];this.logger.error?.("[acp-server] Bridge error:",t?.message)});const n={readyState:WebSocket.OPEN,send:(e,t)=>{try{s.send(e),t?.()}catch(e){t?.(e)}},close:()=>s.close(),terminate:()=>s.close(!1),on:()=>n,once:()=>n,removeListener:()=>n,removeAllListeners:()=>n,ping:()=>{}};Object.defineProperty(n,"readyState",{get:()=>"connected"===s.state?WebSocket.OPEN:WebSocket.CLOSED}),this.client=n;try{await s.connect()}catch(e){this.logger.warn?.(`[acp-server] Initial bridge connect failed (will retry in background): ${e?.message}`)}this.core.initialized=!1,this.logger.info?.("[acp-server] Running in Bridge mode (WS client)")}handleUpgrade(e,t,s){this.wss||(this.wss=new WebSocketServer({noServer:!0}),this.wss.on("connection",(e,t)=>this.handleConnection(e,t))),this.wss.handleUpgrade(e,t,s,t=>{this.wss.emit("connection",t,e)})}async tryAgentSync(e=0){if(this.agentSyncRetryTimer&&(clearTimeout(this.agentSyncRetryTimer),this.agentSyncRetryTimer=null),!this.client||this.client.readyState!==WebSocket.OPEN)return;if(!this.gateway||!this.agentFetchFn||!this.config.agentGatewayUrl)return void this.core.markAgentSyncDone();const t=()=>{if(e+1>=6)return this.logger.warn?.("[acp-server] agent sync exhausted 6 attempts — giving up"),void this.core.markAgentSyncDone();const t=Math.min(5e3*2**e,12e4);this.logger.info?.(`[acp-server] agent sync retry #${e+1} in ${Math.round(t/1e3)}s`),this.agentSyncRetryTimer=setTimeout(()=>this.tryAgentSync(e+1),t)};try{const e=await syncAgentsToPlatform({gateway:this.gateway,agentGatewayUrl:this.config.agentGatewayUrl,capabilities:{canvas:this.config.canvasEnabled,terminal:!0,fileSystem:!0,cron:!0,streaming:!0},agentFetch:this.agentFetchFn,logger:this.logger});e?(this.core.setAgentMapping(e),this.logger.info?.(`[acp-server] agent mapping loaded: ${[...e.keys()].join(", ")}`)):t()}catch(e){this.logger.warn?.(`[acp-server] agent sync failed: ${e}`),t()}}async connectGateway(){this.gateway&&(this.gateway.stop(),this.gateway=null);const e=this.config.gateway;this.gateway=new GatewayClient({url:e.url,token:e.token||"",clientId:e.clientId,openclawCanvasCompat:!!this.config.openclawCanvasCompat,retry:{baseMs:this.config.retry.baseMs,maxMs:this.config.retry.maxMs,maxAttempts:this.config.retry.maxAttempts}}),this.gateway.on("chat",e=>this.events.handleChatEvent(e)),this.gateway.on("agent",e=>this.events.handleAgentEvent(e)),this.gateway.on("cron",e=>this.events.handleCronEvent(e)),this.gateway.on("response",e=>this.core.handleGatewayResponse(e));const t=this.gateway;this.canvasOrch.updateDeps({gateway:t?{get isConnected(){return t.isConnected},request:(e,t)=>this.gateway.request(e,t),agentSend:(e,t,s)=>this.gateway.agentSend(e,t,s)}:null}),this.config.openclawCanvasCompat&&(this.gateway.on("canvas",e=>this.canvasOrch.handleOpenClawCanvasEvent(e)),this.logger.info?.("[acp-server] OpenClaw native canvas compat enabled — listening for canvas events")),this.gateway.on("connected",()=>{this.logger.info?.("[acp-server] Connected to OpenClaw Gateway"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"gateway.connected",severity:"info"})}),this.gateway.on("disconnected",()=>{this.logger.warn?.("[acp-server] Gateway disconnected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"gateway.disconnected",severity:"warn"}),this.core.cleanupAllPendingPrompts()}),this.gateway.on("reconnecting",e=>{this.logger.info?.(`[acp-server] Reconnecting to Gateway attempt=${e.attempt} delay=${Math.round(e.delayMs)}ms`)}),this.gateway.on("reconnect-exhausted",e=>{this.logger.error?.(`[acp-server] Gateway reconnect exhausted after ${e} attempts`)}),this.gateway.on("error",e=>{this.logger.error?.("[acp-server] Gateway error:",e.message)}),this.gateway.on("transport",e=>{this.writeObs({component:"gateway-client",domain:"lifecycle",name:`transport.${e.event}`,severity:"connect_fail"===e.event||"error"===e.event?"warn":"debug",payload:e})}),this.gateway.on("reconnect-notify-scheduled",e=>{this.logger.info?.(`[acp-server] Server-initiated reconnect scheduled in ${e.delayMs}ms`)}),this.gateway.on("reconnect-notify-fired",()=>{this.logger.info?.("[acp-server] Server-initiated reconnect firing")});try{await this.gateway.start()}catch(e){this.logger.error?.("[acp-server] Initial Gateway connect failed:",e)}}handleConnection(e,t){if(this.client){this.logger.warn?.("[acp-server] Replacing existing ACP client with new connection (takeover)");const e=this.client;this.client=null;try{e.close(1008,"replaced by new client")}catch{e.terminate()}}this.client=e,this.core.initialized=!1,this.logger.info?.("[acp-server] ACP client connected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"client.connected",severity:"info"}),e.on("message",e=>{const t="string"==typeof e?e:e.toString("utf-8");try{const e=JSON.parse(t);"id"in e&&void 0!==e.id?this.core.handleRequest(e):this.core.handleNotification(e)}catch{this.logger.error?.("[acp-server] Invalid JSON-RPC message")}}),e.on("close",()=>{this.client===e&&(this.client=null,this.core.initialized=!1),this.logger.info?.("[acp-server] ACP client disconnected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"client.disconnected",severity:"info"})})}pushToolResultContent(e,t,s,n){this.core.pushToolResultContent(e,t,s,n)}setCanvasState(e,t){this.canvasOrch.setCanvasState(e,t)}wireRelayActionHandler(){this.canvasOrch.wireRelayActionHandler()}isCanvasActive(e){return this.canvasOrch.isCanvasActive(e)}isCanvasActiveForGatewayKey(e){return this.canvasOrch.isCanvasActiveForGatewayKey(e)}broadcastNotification(e,t){this.transport.sendNotification(e,t)}getActiveSessionId(){return this.state.lastActiveSessionId}getSessionIdForToolCall(e){const t=this.pendingToolCallSessionKeys.length>0?this.pendingToolCallSessionKeys[this.pendingToolCallSessionKeys.length-1]:void 0;if(t){const s=this.state.findSessionByKey(t)??this.core.ensureSessionForKey(t);if(s?.sessionId)return e&&this.state.toolCallToSessionMap.set(e,s.sessionId),s.sessionId}if(e){const t=this.state.toolCallToSessionMap.get(e);if(t)return t;const s=this.state.toolCallIdMap.get(e);if(s&&s!==e){const e=this.state.toolCallToSessionMap.get(s);if(e)return e}const n=e.split("_");if(n.length>=3&&"tc"===n[0]){const e=n[1],t=this.state.promptsByRunId.get(e);if(t?.sessionId)return t.sessionId}}this.logger.warn?.(`[acp-server] getSessionIdForToolCall MISS: toolCallId=${e??"(none)"}, sessions=${this.state.sessions.size}, pendingKey=${t??"none"}`)}getSessionIdForActivePrompt(){return this.getSessionIdForToolCall()}setPendingToolCallSessionKey(e){e&&(this.pendingToolCallSessionKeys.push(e),this.pendingToolCallSessionKeys.length>16&&this.pendingToolCallSessionKeys.shift())}preMapToolCallSession(e){const t=this.pendingToolCallSessionKeys.length>0?this.pendingToolCallSessionKeys[this.pendingToolCallSessionKeys.length-1]:void 0;if(!t||!e)return;if(this.state.toolCallToSessionMap.has(e))return;const s=this.state.findSessionByKey(t)??this.core.ensureSessionForKey(t);s?.sessionId&&this.state.toolCallToSessionMap.set(e,s.sessionId)}waitForAgentMapping(){return this.core.waitForAgentMapping()}onceAgentMappingReady(e){this.core.onceAgentMappingReady(e)}flushPendingCanvasLinks(){this.canvasOrch.flushPendingCanvasLinks()}onRelayReconnected(){this.canvasOrch.onRelayReconnected()}getDefaultPlatformAgentId(){return this.getDefaultPlatformAgent()?.id}getDefaultPlatformAgent(){const e=this.core.agentMapping;if(e&&0!==e.size)return e.values().next().value??void 0}getPlatformAgentIdForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return this.core.resolvePlatformAgentId(s?.agentId??"")??s?.platformAgentId}getGatewaySessionKeyForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return s?.gatewaySessionKey}getMentionsForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return s?.activeMentions}getResourceRenderer(){return this.canvasOrch.resourceRenderer}getDescriptorRegistry(){return this.canvasOrch.descriptorRegistry}getFormBuilder(){return this.canvasOrch.formBuilder}getSchemaRegistry(){return this.canvasOrch.schemaRegistry}emitCanvasActionAsUserMessage(e,t){this.canvasOrch.emitCanvasActionAsUserMessage(e,t)}async stop(){this.agentSyncRetryTimer&&(clearTimeout(this.agentSyncRetryTimer),this.agentSyncRetryTimer=null),this.state.destroy(),this.canvasOrch.destroy(),this.gateway&&(this.gateway.removeAllListeners(),this.gateway.stop(),this.gateway=null),this.client&&(this.client.removeAllListeners(),this.client.close(),this.client=null),this.bridgeInstance=null,this.bridgeConsecutiveFailures=0,this.terminalHandler.destroy(),this.terminalMgr.destroy(),this.wss&&(this.wss.removeAllListeners(),this.wss.close(),this.wss=null),this.logger.info?.("[acp-server] Stopped"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"lifecycle.shutdown",severity:"info"})}}
@@ -1 +1 @@
1
- import{sv,findRootIds,nextComponentId}from"./a2ui-helpers.js";function nextCid(){return nextComponentId("c")}function textNode(e,t,n="body"){return{id:e,component:{Text:{text:sv(t),usageHint:n}}}}function imageNode(e,t,n="mediumFeature",s,a){const i={url:sv(t),usageHint:n};return s&&(i.fit=s),a&&(i.altText=sv(a)),{id:e,component:{Image:i}}}function iconNode(e,t){return{id:e,component:{Icon:{name:sv(t)}}}}function dividerNode(e,t="horizontal"){return{id:e,component:{Divider:{axis:t}}}}function buttonNode(e,t,n,s){const a={name:n};return s&&(a.context=s),{id:e,component:{Button:{child:t,action:a}}}}function columnNode(e,t,n,s){const a={children:{explicitList:t}};return n&&(a.distribution=n),s&&(a.alignment=s),{id:e,component:{Column:a}}}function rowNode(e,t,n,s){const a={children:{explicitList:t}};return n&&(a.distribution=n),s&&(a.alignment=s),{id:e,component:{Row:a}}}function cardNode(e,t){return{id:e,component:{Card:{child:t}}}}function tabsNode(e,t){return{id:e,component:{Tabs:{tabItems:t.map(e=>({title:sv(e.title),child:e.childId}))}}}}function textFieldNode(e,t,n="shortText",s){const a={label:sv(t),type:n};return s&&(a.text={path:s}),{id:e,component:{TextField:a}}}function checkboxNode(e,t,n){return{id:e,component:{CheckBox:{label:sv(t),value:n?{path:n}:{literalBoolean:!1}}}}}function multipleChoiceNode(e,t,n,s,a){const i={label:sv(t),options:n.map(e=>({label:sv(e.label),value:e.value})),selections:{path:s}};return a&&(i.description=sv(a)),{id:e,component:{MultipleChoice:i}}}function translateComponentsWithDataModel(e){const t={},n=[];for(const s of e){if(!s||"object"!=typeof s){const e=nextCid();n.push(textNode(e,"[invalid component]"));continue}if("form"===("string"==typeof s.type?s.type.toLowerCase():"text")){const e=buildFormWithDataModel(s);n.push(...e.nodes),Object.assign(t,e.dataModel)}else n.push(...translateComponent(s))}return{components:n,dataModel:t}}function translateComponent(e){if(!e||"object"!=typeof e){return[textNode(nextCid(),"[invalid component]")]}const t="string"==typeof e.type?e.type.toLowerCase():"text";switch(t){case"text":return buildText(e);case"card":return buildCard(e);case"table":return buildTable(e);case"form":return buildForm(e);case"image":return buildImage(e);case"button":return buildButton(e);case"grid":return buildGrid(e);case"stat":return buildStat(e);case"key_value":return buildKeyValue(e);case"list":return buildList(e);case"alert":case"callout":return buildAlert(e);case"code":return buildCode(e);case"markdown":return buildMarkdown(e);case"chart":return buildChart(e);case"divider":return buildDivider(e);case"tabs":return buildTabs(e);case"link":return buildLink(e);case"web_embed":case"video":case"audio":case"map":case"file_preview":return buildEmbed(e);case"badge":return buildBadge(e);case"progress":return buildProgress(e);case"timeline":return buildTimeline(e);case"accordion":return buildAccordion(e);case"row":case"column":{const n=(Array.isArray(e.children)?e.children:[]).flatMap(e=>translateComponent(e)),s=findRootIds(n),a=nextCid(),i="row"===t?rowNode(a,s):columnNode(a,s);return[...n,i]}default:return[textNode(nextCid(),`[Unsupported: ${t}]`)]}}function s(e){if(null==e)return"";if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return String(e);try{return JSON.stringify(e)}catch{return"[Object]"}}function buildText(e){return[textNode(nextCid(),s(e.content??e.text??""))]}function buildCard(e){const t=[],n=[];if(e.image){const a=nextCid();t.push(imageNode(a,s(e.image),"mediumFeature","cover")),n.push(a)}if(e.title){const a=nextCid();t.push(textNode(a,s(e.title),"h3")),n.push(a)}if(e.subtitle){const a=nextCid();t.push(textNode(a,s(e.subtitle),"caption")),n.push(a)}if(e.description){const a=nextCid();t.push(textNode(a,s(e.description),"body")),n.push(a)}const a=Array.isArray(e.fields)?e.fields:[];for(const e of a){if(!e||"object"!=typeof e)continue;const a=e,i=nextCid(),o=nextCid(),r=nextCid();t.push(textNode(o,s(a.label??a.key),"caption")),t.push(textNode(r,s(a.value))),t.push(rowNode(i,[o,r],"spaceBetween")),n.push(i)}const i=Array.isArray(e.actions)?e.actions:[];if(i.length>0){const e=[];for(const n of i){if(!n||"object"!=typeof n)continue;const a=n,i=nextCid(),o=nextCid(),r=s(a.label??"Action"),l=s(a.actionId??a.id??nextCid());t.push(textNode(o,r)),t.push(buttonNode(i,o,l,[{key:"actionId",value:{literalString:l}},{key:"label",value:{literalString:r}}])),e.push(i)}if(e.length>0){const s=nextCid();t.push(rowNode(s,e)),n.push(s)}}if(e.footer){const a=nextCid();t.push(textNode(a,s(e.footer),"caption")),n.push(a)}const o=nextCid();t.push(columnNode(o,n));const r=nextCid();return t.push(cardNode(r,o)),t}function buildTable(e){const t=[],n=[],a=Array.isArray(e.columns)?e.columns:[],i=Array.isArray(e.rows)?e.rows:[];if(e.title){const a=nextCid();t.push(textNode(a,s(e.title),"h4")),n.push(a)}const o=[],r=[];for(const e of a)if("string"==typeof e)o.push(e),r.push(e);else if(e&&"object"==typeof e){const t=e,n=s(t.key??t.id??t.field??t.name??t.label??"");o.push(s(t.label??t.title??t.header??t.name??n)),r.push(n)}else{const t=s(e);o.push(t),r.push(t)}if(o.length>0){const e=[];for(const n of o){const s=nextCid();t.push(textNode(s,n,"caption")),e.push(s)}const s=nextCid();t.push(rowNode(s,e)),n.push(s);const a=nextCid();t.push(dividerNode(a)),n.push(a)}for(const e of i){let a;if(Array.isArray(e))a=e;else if(e&&"object"==typeof e&&r.length>0){const t=e;a=r.map(e=>{const n=Object.keys(t).find(t=>t===e||t.toLowerCase()===e.toLowerCase());return null!=n?t[n]:""})}else a=[e];const i=[];for(const e of a){const n=nextCid();t.push(textNode(n,s(e))),i.push(n)}const o=nextCid();t.push(rowNode(o,i)),n.push(o)}const l=nextCid();t.push(columnNode(l,n));const c=nextCid();return t.push(cardNode(c,l)),t}function buildForm(e){return buildFormWithDataModel(e).nodes}function buildFormWithDataModel(e){const t=[],n=[],a=Array.isArray(e.fields)?e.fields:[],i={};if(e.title){const a=nextCid();t.push(textNode(a,s(e.title),"h3")),n.push(a)}if(e.description){const a=nextCid();t.push(textNode(a,s(e.description),"body")),n.push(a)}const o=[];for(const e of a){if(!e||"object"!=typeof e)continue;const a=e,r=nextCid(),l=s(a.name??a.label??r),c=s(a.inputType??a.type??"text"),d=`/${l}`;o.push(l);const u=a.defaultValue??a.default??a.value;if("checkbox"===c||"boolean"===c||"toggle"===c)i[l]=null!=u&&!!u,t.push(checkboxNode(r,s(a.label??a.name??""),d));else if("select"===c||"multi_select"===c||"dropdown"===c||"radio"===c){const e=Array.isArray(a.options)?a.options:[],n=e.map(e=>{if("string"==typeof e)return{label:e,value:e};const t=e;return{label:s(t.label??t.value??""),value:s(t.value??t.label??"")}});if(null!=u)i[l]=String(u);else if(e.length>0){const t=e[0];i[l]="string"==typeof t?t:s(t.value??"")}else i[l]="";t.push(multipleChoiceNode(r,s(a.label??a.name??""),n,d))}else if("datetime"===c||"time"===c){i[l]=null!=u?String(u):"";const e="datetime"===c;t.push({id:r,component:{DateTimeInput:{value:{path:d},enableDate:e,enableTime:!0}}})}else if("range"===c){const e="number"==typeof a.min?a.min:0,n="number"==typeof a.max?a.max:100;i[l]=null!=u?Number(u):e,t.push({id:r,component:{Slider:{label:sv(s(a.label??a.name??"")),value:{path:d},minValue:e,maxValue:n}}})}else{i[l]=null!=u?String(u):"";const e="number"===c?"number":"date"===c?"date":"textarea"===c||"longText"===c?"longText":"shortText";t.push(textFieldNode(r,s(a.label??a.name??""),e,d))}n.push(r)}const r=o.map(e=>({key:e,value:{path:`/${e}`}})),l=nextCid(),c=nextCid();t.push(textNode(l,s(e.submitLabel??"Submit"))),t.push(buttonNode(c,l,s(e.submitActionId??"form_submit"),r)),n.push(c);const d=nextCid();return t.push(columnNode(d,n)),{nodes:t,dataModel:i}}function buildImage(e){const t=nextCid(),n=e.alt??e.altText;return[imageNode(t,s(e.url??e.src??""),"mediumFeature",void 0,n?s(n):void 0)]}function buildButton(e){const t=nextCid(),n=nextCid(),a=s(e.label??"Button"),i=s(e.actionId??n);return[textNode(t,a),buttonNode(n,t,i,[{key:"actionId",value:{literalString:i}},{key:"label",value:{literalString:a}}])]}function buildGrid(e){const t=(Array.isArray(e.children)?e.children:Array.isArray(e.components)?e.components:[]).flatMap(e=>translateComponent(e)),n=Number(e.columns??2),s=findRootIds(t),a=[],i=[];for(let e=0;e<s.length;e+=n){const t=s.slice(e,e+n),o=nextCid();a.push(rowNode(o,t)),i.push(o)}const o=nextCid();return[...t,...a,columnNode(o,i)]}function buildStat(e){const t=[],n=[];if(e.icon){const a=nextCid();t.push(iconNode(a,s(e.icon))),n.push(a)}if(e.label){const a=nextCid();t.push(textNode(a,s(e.label),"caption")),n.push(a)}const a=nextCid();if(t.push(textNode(a,s(e.value??"0"),"h2")),n.push(a),e.change){const a=nextCid(),i="positive"===e.changeType?"↑ ":"negative"===e.changeType?"↓ ":"";t.push(textNode(a,`${i}${s(e.change)}`,"caption")),n.push(a)}if(e.description){const a=nextCid();t.push(textNode(a,s(e.description),"caption")),n.push(a)}const i=nextCid();t.push(columnNode(i,n,void 0,"center"));const o=nextCid();return t.push(cardNode(o,i)),t}function buildKeyValue(e){const t=[],n=[],a=Array.isArray(e.items)?e.items:[];if(e.title){const a=nextCid();t.push(textNode(a,s(e.title),"h4")),n.push(a)}for(const e of a){if(!e||"object"!=typeof e)continue;const a=e,i=nextCid(),o=nextCid(),r=nextCid();t.push(textNode(o,s(a.key??a.label??""),"caption")),t.push(textNode(r,s(a.value??""))),t.push(rowNode(i,[o,r],"spaceBetween")),n.push(i)}const i=nextCid();t.push(columnNode(i,n));const o=nextCid();return t.push(cardNode(o,i)),t}function buildList(e){const t=[],n=[],a=Array.isArray(e.items)?e.items:[];if(e.title){const a=nextCid();t.push(textNode(a,s(e.title),"h4")),n.push(a)}for(const e of a){if(!e||"object"!=typeof e)continue;const a=e,i=[];if(a.image){const e=nextCid();t.push(imageNode(e,s(a.image),"avatar")),i.push(e)}if(a.icon){const e=nextCid();t.push(iconNode(e,s(a.icon))),i.push(e)}const o=[];if(a.title||a.name){const e=nextCid();t.push(textNode(e,s(a.title??a.name),"body")),o.push(e)}if(a.subtitle||a.description){const e=nextCid();t.push(textNode(e,s(a.subtitle??a.description),"caption")),o.push(e)}if(o.length>0){const e=nextCid();t.push(columnNode(e,o)),i.push(e)}if(a.badge||a.value){const e=nextCid();t.push(textNode(e,s(a.badge??a.value),"caption")),i.push(e)}const r=nextCid();t.push(rowNode(r,i,"start","center")),n.push(r)}const i=nextCid();return t.push(columnNode(i,n)),t}function buildAlert(e){const t=[],n=[],a=s(e.variant??"info"),i=nextCid();t.push(iconNode(i,{info:"info",success:"check",warning:"error",error:"error",tip:"info",caution:"error",important:"error",note:"info"}[a]??"info")),n.push(i);const o=[];if(e.title){const n=nextCid();t.push(textNode(n,s(e.title),"h5")),o.push(n)}if(e.message||e.content){const n=nextCid();t.push(textNode(n,s(e.message??e.content))),o.push(n)}if(0===o.length){const n=nextCid();t.push(textNode(n,s(e.type??"Alert"))),o.push(n)}const r=nextCid();t.push(columnNode(r,o)),n.push(r);const l=nextCid();t.push(rowNode(l,n,"start","start"));const c=nextCid();return t.push(cardNode(c,l)),t}function buildCode(e){const t=s(e.code??""),n=s(e.language??""),a=n?`\`\`\`${n}\n${t}\n\`\`\``:`\`\`\`\n${t}\n\`\`\``;return[textNode(nextCid(),a)]}function buildMarkdown(e){return[textNode(nextCid(),s(e.content??""))]}function normalizeDatasets(e){return e.map(e=>{if(!e||"object"!=typeof e)return e;const t={label:e.label??e.name??"",data:Array.isArray(e.data)?e.data.map(e=>e&&"object"==typeof e&&("o"in e||"h"in e||"l"in e||"c"in e)?{open:e.o??e.open,high:e.h??e.high,low:e.l??e.low,close:e.c??e.close}:e):e.data};return e.color&&(t.color=e.color),t})}function buildChart(e){const t=nextCid(),n=s(e.chartType??"bar"),a={chartType:sv(n)};e.title&&(a.title=sv(s(e.title))),Array.isArray(e.labels)&&(a.labels=e.labels.map(e=>"string"==typeof e?e:String(e??"")));const i=Array.isArray(e.datasets)?e.datasets:Array.isArray(e.stages)?e.stages:null;return i&&(a.datasets=normalizeDatasets(i)),void 0!==e.value&&(a.value="number"==typeof e.value?e.value:Number(e.value)||0),void 0!==e.max&&(a.max="number"==typeof e.max?e.max:Number(e.max)||100),[{id:t,component:{Chart:a}}]}function buildDivider(e){return[dividerNode(nextCid())]}function buildTabs(e){const t=Array.isArray(e.tabs)?e.tabs:Array.isArray(e.children)?e.children:Array.isArray(e.items)?e.items:[];if(0===t.length){return[textNode(nextCid(),s(e.title??""))]}const n=[],a=[];for(const e of t){const t=s(e.label??e.title??e.id??"Tab"),i=(Array.isArray(e.children)?e.children:[]).flatMap(e=>translateComponent(e));n.push(...i);const o=findRootIds(i),r=nextCid();n.push(columnNode(r,o)),a.push({title:t,childId:r})}const i=nextCid();return n.push(tabsNode(i,a)),n}function buildLink(e){const t=nextCid(),n=nextCid();return[textNode(t,s(e.text??e.label??e.url??"Link")),buttonNode(n,t,"navigate",[{key:"url",value:{literalString:s(e.url??"")}}])]}function buildEmbed(e){const t=s(e.url??"");if(/youtube|youtu\.be|vimeo/i.test(t)){return[{id:nextCid(),component:{Video:{url:sv(t)}}}]}return buildLink({text:s(e.title??t),url:t})}function buildBadge(e){return[textNode(nextCid(),s(e.text??e.label??""),"caption")]}function buildProgress(e){const t=Number(e.value??0),n=Number(e.max??100),a=n>0?Math.round(t/n*100):0;return[textNode(nextCid(),`${s(e.label)||"Progress"}: ${a}% (${t}/${n})`)]}function buildTimeline(e){const t=(Array.isArray(e.items)?e.items:[]).filter(e=>null!=e&&"object"==typeof e).map(e=>`${s(e.time??e.date??"")} — ${s(e.title??"")}${e.description?`: ${s(e.description)}`:""}`),n=e.title?`**${s(e.title)}**\n`:"";return[textNode(nextCid(),n+(t.length>0?t.join("\n"):"(empty timeline)"))]}function buildAccordion(e){const t=Array.isArray(e.items)?e.items:Array.isArray(e.children)?e.children:[];if(0===t.length){return[textNode(nextCid(),s(e.title??""))]}const n=[];for(const e of t){const t=nextCid();n.push(textNode(t,s(e.title??e.label??""),"h5"));const a=Array.isArray(e.children)?e.children.flatMap(e=>translateComponent(e)):[];n.push(...a)}return n}export const RENDER_UI_TOOL_NAME="render_ui";export const CLOSE_UI_TOOL_NAME="close_ui";export const RENDER_UI_TOOL_DESCRIPTION="Render structured visual content to the Canvas panel. ALWAYS prefer this tool over the canvas tool for displaying UI. Use for charts, tables, stats, key-value pairs, lists, cards, forms, alerts, code, markdown, images, links, web embeds — NOT for text paragraphs. When you call this tool, keep your text reply brief.";export const CLOSE_UI_TOOL_DESCRIPTION="Close and remove a UI surface that was previously rendered.";export const RENDER_UI_TOOL_SCHEMA={type:"object",required:["id","components"],properties:{id:{type:"string",description:"Descriptive, human-readable identifier (e.g., 'sales-report', 'user-dashboard'). Reuse same id to update an existing surface."},components:{type:["array","string"],description:"UI components to render",items:{type:"object",required:["type"],properties:{type:{type:"string",enum:["card","table","stat","key_value","list","grid","chart","markdown","code","text","image","web_embed","alert","form","button","link"]},title:{type:"string"},content:{type:"string"},label:{type:"string"},description:{type:"string"},url:{type:"string"},image:{type:"string"},subtitle:{type:"string"},badge:{type:"string"},badgeVariant:{type:"string",enum:["default","success","warning","error","info"]},footer:{type:"string"},layout:{type:"string",enum:["vertical","horizontal"]},actions:{type:"array",description:"Card action buttons: [{label, actionId, variant?}]"},fields:{type:"array",description:"For card: [{label,value}]. For form: [{name,label,inputType,options,...}]"},children:{type:"array",description:"For grid: nested child components (card, stat, image, etc.)"},gap:{type:"string",enum:["sm","md","lg"]},columns:{type:"array",description:"Column headers or grid column count"},rows:{type:"array",description:"Row data as arrays matching column order"},submitLabel:{type:"string"},submitActionId:{type:"string"},actionId:{type:"string"},alt:{type:"string"},aspectRatio:{type:"string",enum:["16:9","4:3","1:1"]},chartType:{type:"string",enum:["bar","horizontal_bar","line","area","scatter","pie","doughnut","radar","gauge","candlestick","funnel","sparkline"]},stages:{type:"array"},labels:{type:"array"},datasets:{type:"array"},language:{type:"string"},code:{type:"string"},items:{type:"array"},variant:{type:"string"},message:{type:"string"},value:{type:"number"},max:{type:"number"},change:{type:"string"},changeType:{type:"string",enum:["positive","negative","neutral"]},icon:{type:"string"},text:{type:"string"}}}}}};export const CLOSE_UI_TOOL_SCHEMA={type:"object",required:["id"],properties:{id:{type:"string",description:"The UI identifier to close"}}};async function ensureRelayConnected(e,t,n,s){const{stateManager:a,logger:i}=e,o=s??e.getGatewaySessionKey?.(n),r=o??t,l=a.resolveCanvasForSession(r);if(l&&a.isCanvasJoined(l))return l;let c=a.getRelayClient();if(c||(c=await a.waitForRelayClient(),c))try{e.waitForAgentSync&&await e.waitForAgentSync();const s=e.getPlatformAgentId?.(n),l=o??t,d=o&&o!==t?t:void 0,u=await c.ensureCanvas(l,{agentId:s,linkSessionId:d});return await a.joinCanvas(u,r),i.info?.(`[canvas] Joined canvas=${u} session=${t} gatewayKey=${o??"none"} agentId=${s??"none"}`),u}catch(e){return void i.warn?.(`[canvas] Failed to join canvas relay: ${e}`)}}export function createRenderUiHandler(e){const{stateManager:t,logger:n,writeObs:s,isCanvasActive:a}=e;let i=0;return async(o,r)=>{if(a&&!a())return{success:!1,error:"Canvas is disabled by user. Respond with plain text instead."};const l=r,c=l.id,d="panel";let u=l.components;if("string"==typeof u)try{u=JSON.parse(u)}catch{}if(!c||!Array.isArray(u)||!u.length)return{success:!1,error:"id and components (array) are required"};if(!t.validateComponentCount(u))return{success:!1,error:"Too many components (max 500)"};if(!t.checkRateLimit(c))return n.warn?.(`[canvas] Rate limited surfaceId=${c}`),s({component:"canvas",domain:"canvas",name:"canvas.rate_limited",severity:"warn",payload:{surfaceId:c}}),{success:!1,error:"Rate limited — too many updates per second"};const p=translateComponentsWithDataModel(u),m=p.components,h=Object.keys(p.dataModel).length>0?p.dataModel:void 0,f=findRootIds(m),b=nextCid(),g=columnNode(b,f),y=[...m,g],x=e.getActiveSessionId?.(o);if(!x)return n.warn?.(`[canvas] No active session for toolCallId=${o}, skipping render_ui`),{success:!1,error:"No active session — canvas operation skipped"};const v=e.getGatewaySessionKey?.(o),C=await ensureRelayConnected(e,x,o,v),N=t.has(c,C??void 0),w=Date.now(),A=t.getRelayClient();C&&A&&w-i>6e4&&A.createSnapshot(C,"Pre-agent edit").then(()=>{i=Date.now(),n.debug?.("[canvas] Pre-edit checkpoint created")}).catch(e=>n.warn?.(`[canvas] Pre-edit checkpoint failed: ${e}`)),N?t.update(c,y,C,b,h):t.create(C??`_fallback_${Date.now()}`,c,d,y,{origin:{kind:"agent"},rootComponentId:b,dataModel:h});const k=u.map(e=>e.type);s({component:"canvas",domain:"canvas",name:N?"canvas.update_sent":"canvas.surface_created",severity:"info",payload:{surfaceId:c,presentation:d,componentCount:u.length,componentTypes:k}}),n.debug?.(`[canvas] ${N?"Updated":"Created"} surface=${c} components=${u.length}`);return{success:!0,surfaceId:c,presentation:d,isUpdate:N,activeSurfaces:C?t.getAllActive(C).map(e=>e.surfaceId):[c]}}}export function createCloseUiHandler(e){const{stateManager:t,logger:n,writeObs:s}=e;return async(a,i)=>{const o=i.id;if(!o)return{success:!1,error:"id is required"};const r=t.get(o),l=r?Date.now()-r.createdAt:0,c=e.getGatewaySessionKey?.(a),d=c?t.resolveCanvasForSession(c):void 0;return t.delete(o,d),s({component:"canvas",domain:"canvas",name:"canvas.surface_closed",severity:"info",payload:{surfaceId:o,lifetime_ms:l}}),n.debug?.(`[canvas] Closed surface=${o}`),{success:!0,surfaceId:o,message:"UI closed"}}}export function buildCanvasActionSystemMessage(e){const t=e.userAction;return{type:"canvas_user_action",surfaceId:e.surfaceId,actionName:t?.name??"unknown",sourceComponentId:t?.sourceComponentId??"",context:t?.context??{}}}export const CANVAS_SYSTEM_PROMPT='## Canvas UI\n\n**IMPORTANT: Always use `render_ui` (not the built-in `canvas` tool) to display visual/structured content.** The `render_ui` tool is the preferred and optimized way to render UI in the Canvas panel.\n\nRules:\n- When using render_ui, keep your chat reply to ONE short sentence. Do NOT repeat data shown in canvas.\n- Use render_ui for structured data, visualizations, forms, dashboards. Use plain text for explanations.\n- Do NOT put large text blocks in render_ui — that belongs in chat.\n- Only use `grid` as a layout container. Keep nesting to grid > card/stat/image — max 1 level deep. Otherwise list components sequentially (they stack vertically).\n- Prefer fewer, larger components. One well-structured table is better than many small cards.\n- Canvas renders in a narrow sidebar (~400px). Use markdown headings (### Section) to organize sections.\n- Use grid + card for product showcases, dashboards, feature grids. Use list for compact item lists.\n\n**Surface IDs**: Use descriptive, human-readable IDs (e.g., "sales-report", "user-dashboard"). Never use generic IDs like "ui1" or random strings.\n\n**Update vs Create**: Same `id` updates existing surface; different `id` creates new one.\nWhen the user asks to modify, adjust, fix, or update existing canvas content, you MUST reuse the original surface id. Check [Canvas State] in the message for active surface ids and their content. Only create a new surface when showing genuinely new/different content.\n\n### Component Types\n\n**Layout**: grid (columns:1-6, gap:sm/md/lg, children:[...]) — responsive grid container for card/stat/image\n\n**Data Display**: card (image, title, subtitle, description, icon, badge, footer, actions:[{label,actionId}], fields:[{label,value}]), table (columns, rows), stat (label, value, change, changeType, icon), key_value (items:[{key,value}]), list (items:[{title,subtitle,description,image,icon,badge,value}])\n\n**Charts**: chart (chartType, title?, labels, datasets:[{label, data, color?}])\n - chartType: bar, horizontal_bar, line, area, scatter, pie, doughnut, radar, funnel, gauge, candlestick, sparkline\n - labels: x-axis labels array (e.g. ["Jan","Feb","Mar"])\n - datasets: array of series — each has label (series name), data (number[]), optional color (hex)\n - candlestick data format: datasets:[{label, data:[{open,high,low,close}]}] — MUST use full field names (open/high/low/close), NOT abbreviations (o/h/l/c)\n - gauge: uses value + max instead of labels/datasets (e.g. chart(chartType:"gauge", title:"CPU", value:73, max:100))\n - sparkline: compact inline chart, no axes — use for trend indicators\n\n**Text & Code**: text (content), markdown (content — supports full Markdown including bold, italic, lists, code blocks, links), code (language, code)\n\n**Media**: image (url, alt), web_embed (url — video URLs auto-detected), link (text, url)\n\n**Feedback**: alert (variant:info/success/warning/error, title, message)\n\n**Interactive**: form (fields:[{name,label,inputType,options:[{label,value}]}], submitLabel), button (label, actionId)\n - inputType: text (default), number, date, textarea, checkbox, boolean, toggle, select, multi_select, radio, datetime, time, range\n - select/multi_select/radio requires an `options` array — each item is {label, value} or a plain string\n - range renders a slider (optional min, max — default 0..100)\n\n### Composition Patterns\n- **Product showcase**: grid(columns:3) containing card(image, title, description, badge:"$29", actions:[{label:"Buy"}]) × N\n- **Dashboard KPIs**: grid(columns:3) containing stat × N\n- **Image gallery**: grid(columns:3) containing image × N\n- **Feature grid**: grid(columns:2) containing card(icon, title, description) × N\n- **Compact item list**: list(items:[{image, title, subtitle, value:"$29", badge:"New"}])\n- **Detail card**: card(title, description, fields:[{label:"Price",value:"$29"},{label:"Stock",value:"142"}])\n- **Form with select**: form(title:"Settings", fields:[{name:"country", label:"Country", inputType:"select", options:[{label:"China",value:"CN"},{label:"US",value:"US"}]}, {name:"email", label:"Email"}], submitLabel:"Save")\n- **Bar chart**: chart(chartType:"bar", title:"Monthly Sales", labels:["Jan","Feb","Mar"], datasets:[{label:"Revenue", data:[100,200,150]}])\n- **Multi-series line**: chart(chartType:"line", title:"Trends", labels:["Q1","Q2","Q3"], datasets:[{label:"2024", data:[10,20,15]}, {label:"2025", data:[15,25,30]}])\n- **Pie chart**: chart(chartType:"pie", title:"Market Share", labels:["A","B","C"], datasets:[{label:"share", data:[40,35,25]}])\n- **Candlestick**: chart(chartType:"candlestick", title:"BTC/USD", labels:["Mon","Tue","Wed"], datasets:[{label:"price", data:[{open:100,high:110,low:95,close:105},{open:105,high:115,low:100,close:108},{open:108,high:120,low:105,close:118}]}])\n\n### render_form\nUse `render_form` for schema-driven forms when a domain schema exists.\nParameters: `domain`, `operation`, `data`, `entityId`.\n\n### close_ui\nCloses a UI surface. Use when user moves to a new topic or explicitly dismisses.\n';export const CANVAS_TERM_MAPPING='[System Note] Always use `render_ui` (not the canvas tool) for visual/structured content (tables, stats, key-value, lists, cards, grids, alerts, forms, links, images, code, markdown, charts). Use grid(columns, children:[card/stat/image]) for multi-column layouts like product showcases and dashboards. Card supports: image, title, subtitle, description, icon, badge, footer, actions, fields:[{label,value}]. List items support: image, title, subtitle, description, badge, value. Markdown content supports full formatting. Use web_embed for embedding URLs. Use link for navigation. Form supports inputType: text/number/date/textarea/checkbox/toggle/select/multi_select/radio/datetime/time/range; select/multi_select/radio requires options:[{label,value}]. Chart supports: chartType(bar/horizontal_bar/line/area/scatter/pie/doughnut/radar/funnel/gauge/candlestick/sparkline), title, labels, datasets:[{label,data,color?}]. Candlestick data:[{open,high,low,close}] (use full names, not o/h/l/c). Dataset uses "label" field (not "name"). Gauge uses value+max. Keep chat brief when canvas is used. Use `close_ui` to dismiss. Reuse same id to update; new id for new content.';export const CANVAS_UPDATE_HINT="[Canvas Rule] Same id in render_ui = update existing surface. Different id = new surface. When a surface is referenced for editing, you MUST reuse its exact id.";const MAX_CONTEXT_SURFACES=8,MAX_CONTEXT_CHARS=500;export function buildActiveSurfacesContext(e,t){let n;if(!t)return null;if(n=e.getAllActive(t),0===n.length)return null;const s=[...n].sort((e,t)=>t.updatedAt-e.updatedAt).slice(0,8),a=n.length-s.length;let i=`[Canvas State] Active surfaces: ${s.map(t=>{const n=e.summarize(t.surfaceId);if(!n)return`"${t.surfaceId}"`;const s=n.types.slice(0,3).join(", "),a=n.title?`: "${n.title}"`:"";return`"${t.surfaceId}" (${s}${a})`}).join("; ")}.`;return a>0&&(i+=` ...and ${a} more.`),i+=" To modify existing content, reuse its id in render_ui.",i.length>500&&(i=i.slice(0,497)+"..."),i}
1
+ import{sv,findRootIds,nextComponentId}from"./a2ui-helpers.js";function nextCid(){return nextComponentId("c")}function textNode(e,t,n="body"){return{id:e,component:{Text:{text:sv(t),usageHint:n}}}}function imageNode(e,t,n="mediumFeature",s,a){const o={url:sv(t),usageHint:n};return s&&(o.fit=s),a&&(o.altText=sv(a)),{id:e,component:{Image:o}}}function iconNode(e,t){return{id:e,component:{Icon:{name:sv(t)}}}}function dividerNode(e,t="horizontal"){return{id:e,component:{Divider:{axis:t}}}}function buttonNode(e,t,n,s){const a={name:n};return s&&(a.context=s),{id:e,component:{Button:{child:t,action:a}}}}function columnNode(e,t,n,s){const a={children:{explicitList:t}};return n&&(a.distribution=n),s&&(a.alignment=s),{id:e,component:{Column:a}}}function rowNode(e,t,n,s){const a={children:{explicitList:t}};return n&&(a.distribution=n),s&&(a.alignment=s),{id:e,component:{Row:a}}}function cardNode(e,t){return{id:e,component:{Card:{child:t}}}}function tabsNode(e,t){return{id:e,component:{Tabs:{tabItems:t.map(e=>({title:sv(e.title),child:e.childId}))}}}}function textFieldNode(e,t,n="shortText",s){const a={label:sv(t),type:n};return s&&(a.text={path:s}),{id:e,component:{TextField:a}}}function checkboxNode(e,t,n){return{id:e,component:{CheckBox:{label:sv(t),value:n?{path:n}:{literalBoolean:!1}}}}}function multipleChoiceNode(e,t,n,s,a){const o={label:sv(t),options:n.map(e=>({label:sv(e.label),value:e.value})),selections:{path:s}};return a&&(o.description=sv(a)),{id:e,component:{MultipleChoice:o}}}function translateComponentsWithDataModel(e){const t={},n=[];for(const s of e){if(!s||"object"!=typeof s){const e=nextCid();n.push(textNode(e,"[invalid component]"));continue}if("form"===("string"==typeof s.type?s.type.toLowerCase():"text")){const e=buildFormWithDataModel(s);n.push(...e.nodes),Object.assign(t,e.dataModel)}else n.push(...translateComponent(s))}return{components:n,dataModel:t}}function translateComponent(e){if(!e||"object"!=typeof e){return[textNode(nextCid(),"[invalid component]")]}const t="string"==typeof e.type?e.type.toLowerCase():"text";switch(t){case"text":return buildText(e);case"card":return buildCard(e);case"table":return buildTable(e);case"form":return buildForm(e);case"image":return buildImage(e);case"button":return buildButton(e);case"grid":return buildGrid(e);case"stat":return buildStat(e);case"key_value":return buildKeyValue(e);case"list":return buildList(e);case"alert":case"callout":return buildAlert(e);case"code":return buildCode(e);case"markdown":return buildMarkdown(e);case"chart":return buildChart(e);case"divider":return buildDivider(e);case"tabs":return buildTabs(e);case"link":return buildLink(e);case"web_embed":case"video":case"audio":case"map":case"file_preview":return buildEmbed(e);case"badge":return buildBadge(e);case"progress":return buildProgress(e);case"timeline":return buildTimeline(e);case"accordion":return buildAccordion(e);case"row":case"column":{const n=(Array.isArray(e.children)?e.children:[]).flatMap(e=>translateComponent(e)),s=findRootIds(n),a=nextCid(),o="row"===t?rowNode(a,s):columnNode(a,s);return[...n,o]}default:return[textNode(nextCid(),`[Unsupported: ${t}]`)]}}function s(e){if(null==e)return"";if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return String(e);try{return JSON.stringify(e)}catch{return"[Object]"}}function buildText(e){return[textNode(nextCid(),s(e.content??e.text??""))]}function buildCard(e){const t=[],n=[];if(e.image){const a=nextCid();t.push(imageNode(a,s(e.image),"mediumFeature","cover")),n.push(a)}if(e.title){const a=nextCid();t.push(textNode(a,s(e.title),"h3")),n.push(a)}if(e.subtitle){const a=nextCid();t.push(textNode(a,s(e.subtitle),"caption")),n.push(a)}if(e.description){const a=nextCid();t.push(textNode(a,s(e.description),"body")),n.push(a)}const a=Array.isArray(e.fields)?e.fields:[];for(const e of a){if(!e||"object"!=typeof e)continue;const a=e,o=nextCid(),i=nextCid(),r=nextCid();t.push(textNode(i,s(a.label??a.key),"caption")),t.push(textNode(r,s(a.value))),t.push(rowNode(o,[i,r],"spaceBetween")),n.push(o)}const o=Array.isArray(e.actions)?e.actions:[];if(o.length>0){const e=[];for(const n of o){if(!n||"object"!=typeof n)continue;const a=n,o=nextCid(),i=nextCid(),r=s(a.label??"Action"),l=s(a.actionId??a.id??nextCid());t.push(textNode(i,r)),t.push(buttonNode(o,i,l,[{key:"actionId",value:{literalString:l}},{key:"label",value:{literalString:r}}])),e.push(o)}if(e.length>0){const s=nextCid();t.push(rowNode(s,e)),n.push(s)}}const i=Array.isArray(e.children)?e.children:[];for(const e of i){if(!e||"object"!=typeof e)continue;const s=translateComponent(e);t.push(...s);const a=findRootIds(s);n.push(...a)}if(e.footer){const a=nextCid();t.push(textNode(a,s(e.footer),"caption")),n.push(a)}const r=nextCid();t.push(columnNode(r,n));const l=nextCid();return t.push(cardNode(l,r)),t}function buildTable(e){const t=[],n=[],a=Array.isArray(e.columns)?e.columns:[],o=Array.isArray(e.rows)?e.rows:[];if(e.title){const a=nextCid();t.push(textNode(a,s(e.title),"h4")),n.push(a)}const i=[],r=[];for(const e of a)if("string"==typeof e)i.push(e),r.push(e);else if(e&&"object"==typeof e){const t=e,n=s(t.key??t.id??t.field??t.name??t.label??"");i.push(s(t.label??t.title??t.header??t.name??n)),r.push(n)}else{const t=s(e);i.push(t),r.push(t)}if(i.length>0){const e=[];for(const n of i){const s=nextCid();t.push(textNode(s,n,"caption")),e.push(s)}const s=nextCid();t.push(rowNode(s,e)),n.push(s);const a=nextCid();t.push(dividerNode(a)),n.push(a)}for(const e of o){let a;if(Array.isArray(e))a=e;else if(e&&"object"==typeof e&&r.length>0){const t=e;a=r.map(e=>{const n=Object.keys(t).find(t=>t===e||t.toLowerCase()===e.toLowerCase());return null!=n?t[n]:""})}else a=[e];const o=[];for(const e of a){const n=nextCid();t.push(textNode(n,s(e))),o.push(n)}const i=nextCid();t.push(rowNode(i,o)),n.push(i)}const l=nextCid();t.push(columnNode(l,n));const c=nextCid();return t.push(cardNode(c,l)),t}function buildForm(e){return buildFormWithDataModel(e).nodes}function buildFormWithDataModel(e){const t=[],n=[],a=Array.isArray(e.fields)?e.fields:[],o={};if(e.title){const a=nextCid();t.push(textNode(a,s(e.title),"h3")),n.push(a)}if(e.description){const a=nextCid();t.push(textNode(a,s(e.description),"body")),n.push(a)}const i=[];for(const e of a){if(!e||"object"!=typeof e)continue;const a=e,r=nextCid(),l=s(a.name??a.label??r),c=s(a.inputType??a.type??"text"),d=`/${l}`;i.push(l);const u=a.defaultValue??a.default??a.value;if("checkbox"===c||"boolean"===c||"toggle"===c)o[l]=null!=u&&!!u,t.push(checkboxNode(r,s(a.label??a.name??""),d));else if("select"===c||"multi_select"===c||"dropdown"===c||"radio"===c){const e=Array.isArray(a.options)?a.options:[],n=e.map(e=>{if("string"==typeof e)return{label:e,value:e};const t=e;return{label:s(t.label??t.value??""),value:s(t.value??t.label??"")}});if(null!=u)o[l]=String(u);else if(e.length>0){const t=e[0];o[l]="string"==typeof t?t:s(t.value??"")}else o[l]="";t.push(multipleChoiceNode(r,s(a.label??a.name??""),n,d))}else if("datetime"===c||"time"===c){o[l]=null!=u?String(u):"";const e="datetime"===c;t.push({id:r,component:{DateTimeInput:{value:{path:d},enableDate:e,enableTime:!0}}})}else if("range"===c){const e="number"==typeof a.min?a.min:0,n="number"==typeof a.max?a.max:100;o[l]=null!=u?Number(u):e,t.push({id:r,component:{Slider:{label:sv(s(a.label??a.name??"")),value:{path:d},minValue:e,maxValue:n}}})}else{o[l]=null!=u?String(u):"";const e="number"===c?"number":"date"===c?"date":"textarea"===c||"longText"===c?"longText":"shortText";t.push(textFieldNode(r,s(a.label??a.name??""),e,d))}n.push(r)}const r=i.map(e=>({key:e,value:{path:`/${e}`}})),l=nextCid(),c=nextCid();t.push(textNode(l,s(e.submitLabel??"Submit"))),t.push(buttonNode(c,l,s(e.submitActionId??"form_submit"),r)),n.push(c);const d=nextCid();return t.push(columnNode(d,n)),{nodes:t,dataModel:o}}function buildImage(e){const t=nextCid(),n=e.alt??e.altText;return[imageNode(t,s(e.url??e.src??""),"mediumFeature",void 0,n?s(n):void 0)]}function buildButton(e){const t=nextCid(),n=nextCid(),a=s(e.label??"Button"),o=s(e.actionId??n);return[textNode(t,a),buttonNode(n,t,o,[{key:"actionId",value:{literalString:o}},{key:"label",value:{literalString:a}}])]}function buildGrid(e){const t=(Array.isArray(e.children)?e.children:Array.isArray(e.components)?e.components:[]).flatMap(e=>translateComponent(e)),n=Number(e.columns??2),s=findRootIds(t),a=[],o=[];for(let e=0;e<s.length;e+=n){const t=s.slice(e,e+n),i=nextCid();a.push(rowNode(i,t)),o.push(i)}const i=nextCid();return[...t,...a,columnNode(i,o)]}function buildStat(e){const t=[],n=[];if(e.icon){const a=nextCid();t.push(iconNode(a,s(e.icon))),n.push(a)}if(e.label){const a=nextCid();t.push(textNode(a,s(e.label),"caption")),n.push(a)}const a=nextCid();if(t.push(textNode(a,s(e.value??"0"),"h2")),n.push(a),e.change){const a=nextCid(),o="positive"===e.changeType?"↑ ":"negative"===e.changeType?"↓ ":"";t.push(textNode(a,`${o}${s(e.change)}`,"caption")),n.push(a)}if(e.description){const a=nextCid();t.push(textNode(a,s(e.description),"caption")),n.push(a)}const o=nextCid();t.push(columnNode(o,n,void 0,"center"));const i=nextCid();return t.push(cardNode(i,o)),t}function buildKeyValue(e){const t=[],n=[],a=Array.isArray(e.items)?e.items:[];if(e.title){const a=nextCid();t.push(textNode(a,s(e.title),"h4")),n.push(a)}for(const e of a){if(!e||"object"!=typeof e)continue;const a=e,o=nextCid(),i=nextCid(),r=nextCid();t.push(textNode(i,s(a.key??a.label??""),"caption")),t.push(textNode(r,s(a.value??""))),t.push(rowNode(o,[i,r],"spaceBetween")),n.push(o)}const o=nextCid();t.push(columnNode(o,n));const i=nextCid();return t.push(cardNode(i,o)),t}function buildList(e){const t=[],n=[],a=Array.isArray(e.items)?e.items:[];if(e.title){const a=nextCid();t.push(textNode(a,s(e.title),"h4")),n.push(a)}for(const e of a){if(!e||"object"!=typeof e)continue;const a=e,o=[];if(a.image){const e=nextCid();t.push(imageNode(e,s(a.image),"avatar")),o.push(e)}if(a.icon){const e=nextCid();t.push(iconNode(e,s(a.icon))),o.push(e)}const i=[];if(a.title||a.name){const e=nextCid();t.push(textNode(e,s(a.title??a.name),"body")),i.push(e)}if(a.subtitle||a.description){const e=nextCid();t.push(textNode(e,s(a.subtitle??a.description),"caption")),i.push(e)}if(i.length>0){const e=nextCid();t.push(columnNode(e,i)),o.push(e)}if(a.badge||a.value){const e=nextCid();t.push(textNode(e,s(a.badge??a.value),"caption")),o.push(e)}const r=nextCid();t.push(rowNode(r,o,"start","center")),n.push(r)}const o=nextCid();return t.push(columnNode(o,n)),t}function buildAlert(e){const t=[],n=[],a=s(e.variant??"info"),o=nextCid();t.push(iconNode(o,{info:"info",success:"check",warning:"error",error:"error",tip:"info",caution:"error",important:"error",note:"info"}[a]??"info")),n.push(o);const i=[];if(e.title){const n=nextCid();t.push(textNode(n,s(e.title),"h5")),i.push(n)}if(e.message||e.content){const n=nextCid();t.push(textNode(n,s(e.message??e.content))),i.push(n)}if(0===i.length){const n=nextCid();t.push(textNode(n,s(e.type??"Alert"))),i.push(n)}const r=nextCid();t.push(columnNode(r,i)),n.push(r);const l=nextCid();t.push(rowNode(l,n,"start","start"));const c=nextCid();return t.push(cardNode(c,l)),t}function buildCode(e){const t=s(e.code??""),n=s(e.language??""),a=n?`\`\`\`${n}\n${t}\n\`\`\``:`\`\`\`\n${t}\n\`\`\``;return[textNode(nextCid(),a)]}function buildMarkdown(e){return[textNode(nextCid(),s(e.content??""))]}function normalizeDatasets(e){return e.map(e=>{if(!e||"object"!=typeof e)return e;const t={label:e.label??e.name??"",data:Array.isArray(e.data)?e.data.map(e=>e&&"object"==typeof e&&("o"in e||"h"in e||"l"in e||"c"in e)?{open:e.o??e.open,high:e.h??e.high,low:e.l??e.low,close:e.c??e.close}:e):e.data};return e.color&&(t.color=e.color),t})}function buildChart(e){const t=nextCid(),n=s(e.chartType??"bar"),a={chartType:sv(n)};e.title&&(a.title=sv(s(e.title))),Array.isArray(e.labels)&&(a.labels=e.labels.map(e=>"string"==typeof e?e:String(e??"")));const o=Array.isArray(e.datasets)?e.datasets:Array.isArray(e.stages)?e.stages:null;return o&&(a.datasets=normalizeDatasets(o)),void 0!==e.value&&(a.value="number"==typeof e.value?e.value:Number(e.value)||0),void 0!==e.max&&(a.max="number"==typeof e.max?e.max:Number(e.max)||100),[{id:t,component:{Chart:a}}]}function buildDivider(e){return[dividerNode(nextCid())]}function buildTabs(e){const t=Array.isArray(e.tabs)?e.tabs:Array.isArray(e.children)?e.children:Array.isArray(e.items)?e.items:[];if(0===t.length){return[textNode(nextCid(),s(e.title??""))]}const n=[],a=[];for(const e of t){const t=s(e.label??e.title??e.id??"Tab"),o=(Array.isArray(e.children)?e.children:[]).flatMap(e=>translateComponent(e));n.push(...o);const i=findRootIds(o),r=nextCid();n.push(columnNode(r,i)),a.push({title:t,childId:r})}const o=nextCid();return n.push(tabsNode(o,a)),n}function buildLink(e){const t=nextCid(),n=nextCid();return[textNode(t,s(e.text??e.label??e.url??"Link")),buttonNode(n,t,"navigate",[{key:"url",value:{literalString:s(e.url??"")}}])]}function buildEmbed(e){const t=s(e.url??"");if(/youtube|youtu\.be|vimeo/i.test(t)){return[{id:nextCid(),component:{Video:{url:sv(t)}}}]}return buildLink({text:s(e.title??t),url:t})}function buildBadge(e){return[textNode(nextCid(),s(e.text??e.label??""),"caption")]}function buildProgress(e){const t=Number(e.value??0),n=Number(e.max??100),a=n>0?Math.round(t/n*100):0;return[textNode(nextCid(),`${s(e.label)||"Progress"}: ${a}% (${t}/${n})`)]}function buildTimeline(e){const t=(Array.isArray(e.items)?e.items:[]).filter(e=>null!=e&&"object"==typeof e).map(e=>`${s(e.time??e.date??"")} — ${s(e.title??"")}${e.description?`: ${s(e.description)}`:""}`),n=e.title?`**${s(e.title)}**\n`:"";return[textNode(nextCid(),n+(t.length>0?t.join("\n"):"(empty timeline)"))]}function buildAccordion(e){const t=Array.isArray(e.items)?e.items:Array.isArray(e.children)?e.children:[];if(0===t.length){return[textNode(nextCid(),s(e.title??""))]}const n=[];for(const e of t){const t=nextCid();n.push(textNode(t,s(e.title??e.label??""),"h5"));const a=Array.isArray(e.children)?e.children.flatMap(e=>translateComponent(e)):[];n.push(...a)}return n}export const RENDER_UI_TOOL_NAME="render_ui";export const CLOSE_UI_TOOL_NAME="close_ui";export const RENDER_UI_TOOL_DESCRIPTION="Render structured visual content to the Canvas panel. ALWAYS prefer this tool over the canvas tool for displaying UI. Use for charts, tables, stats, key-value pairs, lists, cards, forms, alerts, code, markdown, images, links, web embeds — NOT for text paragraphs. When you call this tool, keep your text reply brief.";export const CLOSE_UI_TOOL_DESCRIPTION="Close and remove a UI surface that was previously rendered.";export const RENDER_UI_TOOL_SCHEMA={type:"object",required:["id","components"],properties:{id:{type:"string",description:"Descriptive, human-readable identifier (e.g., 'sales-report', 'user-dashboard'). Reuse same id to update an existing surface."},components:{type:["array","string"],description:"UI components to render",items:{type:"object",required:["type"],properties:{type:{type:"string",enum:["card","table","stat","key_value","list","grid","chart","markdown","code","text","image","web_embed","alert","form","button","link"]},title:{type:"string"},content:{type:"string"},label:{type:"string"},description:{type:"string"},url:{type:"string"},image:{type:"string"},subtitle:{type:"string"},badge:{type:"string"},badgeVariant:{type:"string",enum:["default","success","warning","error","info"]},footer:{type:"string"},layout:{type:"string",enum:["vertical","horizontal"]},actions:{type:"array",description:"Card action buttons: [{label, actionId, variant?}]"},fields:{type:"array",description:"For card: [{label,value}]. For form: [{name,label,inputType,options,...}]"},children:{type:"array",description:"For grid: nested child components (card, stat, image, etc.)"},gap:{type:"string",enum:["sm","md","lg"]},columns:{type:"array",description:"Column headers or grid column count"},rows:{type:"array",description:"Row data as arrays matching column order"},submitLabel:{type:"string"},submitActionId:{type:"string"},actionId:{type:"string"},alt:{type:"string"},aspectRatio:{type:"string",enum:["16:9","4:3","1:1"]},chartType:{type:"string",enum:["bar","horizontal_bar","line","area","scatter","pie","doughnut","radar","gauge","candlestick","funnel","sparkline"]},stages:{type:"array"},labels:{type:"array"},datasets:{type:"array"},language:{type:"string"},code:{type:"string"},items:{type:"array"},variant:{type:"string"},message:{type:"string"},value:{type:"number"},max:{type:"number"},change:{type:"string"},changeType:{type:"string",enum:["positive","negative","neutral"]},icon:{type:"string"},text:{type:"string"}}}}}};export const CLOSE_UI_TOOL_SCHEMA={type:"object",required:["id"],properties:{id:{type:"string",description:"The UI identifier to close"}}};async function ensureRelayConnected(e,t,n,s){const{stateManager:a,logger:o}=e,i=s??e.getGatewaySessionKey?.(n),r=i??t,l=a.resolveCanvasForSession(r);if(l&&a.isCanvasJoined(l))return l;let c=a.getRelayClient();if(c||(c=await a.waitForRelayClient(),c))try{e.waitForAgentSync&&await e.waitForAgentSync();const s=e.getPlatformAgentId?.(n),l=i??t,d=i&&i!==t?t:void 0,u=await c.ensureCanvas(l,{agentId:s,linkSessionId:d});return await a.joinCanvas(u,r),o.info?.(`[canvas] Joined canvas=${u} session=${t} gatewayKey=${i??"none"} agentId=${s??"none"}`),u}catch(e){return void o.warn?.(`[canvas] Failed to join canvas relay: ${e}`)}}export function createRenderUiHandler(e){const{stateManager:t,logger:n,writeObs:s,isCanvasActive:a}=e;let o=0;return async(i,r)=>{if(a&&!a())return{success:!1,error:"Canvas is disabled by user. Respond with plain text instead."};const l=r,c=l.id,d="panel";let u=l.components;if("string"==typeof u)try{u=JSON.parse(u)}catch{}if(!c||!Array.isArray(u)||!u.length)return{success:!1,error:"id and components (array) are required"};if(!t.validateComponentCount(u))return{success:!1,error:"Too many components (max 500)"};if(!t.checkRateLimit(c))return n.warn?.(`[canvas] Rate limited surfaceId=${c}`),s({component:"canvas",domain:"canvas",name:"canvas.rate_limited",severity:"warn",payload:{surfaceId:c}}),{success:!1,error:"Rate limited — too many updates per second"};const p=translateComponentsWithDataModel(u),m=p.components,h=Object.keys(p.dataModel).length>0?p.dataModel:void 0,f=findRootIds(m),b=nextCid(),g=columnNode(b,f),y=[...m,g],x=e.getActiveSessionId?.(i);if(!x)return n.warn?.(`[canvas] No active session for toolCallId=${i}, skipping render_ui`),{success:!1,error:"No active session — canvas operation skipped"};const v=e.getGatewaySessionKey?.(i),C=await ensureRelayConnected(e,x,i,v),N=t.has(c,C??void 0),w=Date.now(),A=t.getRelayClient();C&&A&&w-o>6e4&&A.createSnapshot(C,"Pre-agent edit").then(()=>{o=Date.now(),n.debug?.("[canvas] Pre-edit checkpoint created")}).catch(e=>n.warn?.(`[canvas] Pre-edit checkpoint failed: ${e}`)),N?t.update(c,y,C,b,h):t.create(C??`_fallback_${Date.now()}`,c,d,y,{origin:{kind:"agent"},rootComponentId:b,dataModel:h});const k=u.map(e=>e.type);s({component:"canvas",domain:"canvas",name:N?"canvas.update_sent":"canvas.surface_created",severity:"info",payload:{surfaceId:c,presentation:d,componentCount:u.length,componentTypes:k}}),n.debug?.(`[canvas] ${N?"Updated":"Created"} surface=${c} components=${u.length}`);return{success:!0,surfaceId:c,presentation:d,isUpdate:N,activeSurfaces:C?t.getAllActive(C).map(e=>e.surfaceId):[c]}}}export function createCloseUiHandler(e){const{stateManager:t,logger:n,writeObs:s}=e;return async(a,o)=>{const i=o.id;if(!i)return{success:!1,error:"id is required"};const r=t.get(i),l=r?Date.now()-r.createdAt:0,c=e.getGatewaySessionKey?.(a),d=c?t.resolveCanvasForSession(c):void 0;return t.delete(i,d),s({component:"canvas",domain:"canvas",name:"canvas.surface_closed",severity:"info",payload:{surfaceId:i,lifetime_ms:l}}),n.debug?.(`[canvas] Closed surface=${i}`),{success:!0,surfaceId:i,message:"UI closed"}}}export function buildCanvasActionSystemMessage(e){const t=e.userAction;return{type:"canvas_user_action",surfaceId:e.surfaceId,actionName:t?.name??"unknown",sourceComponentId:t?.sourceComponentId??"",context:t?.context??{}}}export const CANVAS_SYSTEM_PROMPT='## Canvas UI\n\n**IMPORTANT: Always use `render_ui` (not the built-in `canvas` tool) to display visual/structured content.** The `render_ui` tool is the preferred and optimized way to render UI in the Canvas panel.\n\nRules:\n- When using render_ui, keep your chat reply to ONE short sentence. Do NOT repeat data shown in canvas.\n- Use render_ui for structured data, visualizations, forms, dashboards. Use plain text for explanations.\n- Do NOT put large text blocks in render_ui — that belongs in chat.\n- Only use `grid` as a layout container. Keep nesting to grid > card/stat/image — max 1 level deep. Otherwise list components sequentially (they stack vertically).\n- Prefer fewer, larger components. One well-structured table is better than many small cards.\n- Canvas renders in a narrow sidebar (~400px). Use markdown headings (### Section) to organize sections.\n- Use grid + card for product showcases, dashboards, feature grids. Use list for compact item lists.\n\n**Surface IDs**: Use descriptive, human-readable IDs (e.g., "sales-report", "user-dashboard"). Never use generic IDs like "ui1" or random strings.\n\n**Update vs Create**: Same `id` updates existing surface; different `id` creates new one.\nWhen the user asks to modify, adjust, fix, or update existing canvas content, you MUST reuse the original surface id. Check [Canvas State] in the message for active surface ids and their content. Only create a new surface when showing genuinely new/different content.\n\n### Component Types\n\n**Layout**: grid (columns:1-6, gap:sm/md/lg, children:[...]) — responsive grid container for card/stat/image\n\n**Data Display**: card (image, title, subtitle, description, icon, badge, footer, actions:[{label,actionId}], fields:[{label,value}]), table (columns, rows), stat (label, value, change, changeType, icon), key_value (items:[{key,value}]), list (items:[{title,subtitle,description,image,icon,badge,value}])\n\n**Charts**: chart (chartType, title?, labels, datasets:[{label, data, color?}])\n - chartType: bar, horizontal_bar, line, area, scatter, pie, doughnut, radar, funnel, gauge, candlestick, sparkline\n - labels: x-axis labels array (e.g. ["Jan","Feb","Mar"])\n - datasets: array of series — each has label (series name), data (number[]), optional color (hex)\n - candlestick data format: datasets:[{label, data:[{open,high,low,close}]}] — MUST use full field names (open/high/low/close), NOT abbreviations (o/h/l/c)\n - gauge: uses value + max instead of labels/datasets (e.g. chart(chartType:"gauge", title:"CPU", value:73, max:100))\n - sparkline: compact inline chart, no axes — use for trend indicators\n\n**Text & Code**: text (content), markdown (content — supports full Markdown including bold, italic, lists, code blocks, links), code (language, code)\n\n**Media**: image (url, alt), web_embed (url — video URLs auto-detected), link (text, url)\n\n**Feedback**: alert (variant:info/success/warning/error, title, message)\n\n**Interactive**: form (fields:[{name,label,inputType,options:[{label,value}]}], submitLabel), button (label, actionId)\n - inputType: text (default), number, date, textarea, checkbox, boolean, toggle, select, multi_select, radio, datetime, time, range\n - select/multi_select/radio requires an `options` array — each item is {label, value} or a plain string\n - range renders a slider (optional min, max — default 0..100)\n\n### Composition Patterns\n- **Product showcase**: grid(columns:3) containing card(image, title, description, badge:"$29", actions:[{label:"Buy"}]) × N\n- **Dashboard KPIs**: grid(columns:3) containing stat × N\n- **Image gallery**: grid(columns:3) containing image × N\n- **Feature grid**: grid(columns:2) containing card(icon, title, description) × N\n- **Compact item list**: list(items:[{image, title, subtitle, value:"$29", badge:"New"}])\n- **Detail card**: card(title, description, fields:[{label:"Price",value:"$29"},{label:"Stock",value:"142"}])\n- **Form with select**: form(title:"Settings", fields:[{name:"country", label:"Country", inputType:"select", options:[{label:"China",value:"CN"},{label:"US",value:"US"}]}, {name:"email", label:"Email"}], submitLabel:"Save")\n- **Bar chart**: chart(chartType:"bar", title:"Monthly Sales", labels:["Jan","Feb","Mar"], datasets:[{label:"Revenue", data:[100,200,150]}])\n- **Multi-series line**: chart(chartType:"line", title:"Trends", labels:["Q1","Q2","Q3"], datasets:[{label:"2024", data:[10,20,15]}, {label:"2025", data:[15,25,30]}])\n- **Pie chart**: chart(chartType:"pie", title:"Market Share", labels:["A","B","C"], datasets:[{label:"share", data:[40,35,25]}])\n- **Candlestick**: chart(chartType:"candlestick", title:"BTC/USD", labels:["Mon","Tue","Wed"], datasets:[{label:"price", data:[{open:100,high:110,low:95,close:105},{open:105,high:115,low:100,close:108},{open:108,high:120,low:105,close:118}]}])\n\n### render_form\nUse `render_form` for schema-driven forms when a domain schema exists.\nParameters: `domain`, `operation`, `data`, `entityId`.\n\n### close_ui\nCloses a UI surface. Use when user moves to a new topic or explicitly dismisses.\n';export const CANVAS_TERM_MAPPING='[System Note] Always use `render_ui` (not the canvas tool) for visual/structured content (tables, stats, key-value, lists, cards, grids, alerts, forms, links, images, code, markdown, charts). Use grid(columns, children:[card/stat/image]) for multi-column layouts like product showcases and dashboards. Card supports: image, title, subtitle, description, icon, badge, footer, actions, fields:[{label,value}]. List items support: image, title, subtitle, description, badge, value. Markdown content supports full formatting. Use web_embed for embedding URLs. Use link for navigation. Form supports inputType: text/number/date/textarea/checkbox/toggle/select/multi_select/radio/datetime/time/range; select/multi_select/radio requires options:[{label,value}]. Chart supports: chartType(bar/horizontal_bar/line/area/scatter/pie/doughnut/radar/funnel/gauge/candlestick/sparkline), title, labels, datasets:[{label,data,color?}]. Candlestick data:[{open,high,low,close}] (use full names, not o/h/l/c). Dataset uses "label" field (not "name"). Gauge uses value+max. Keep chat brief when canvas is used. Use `close_ui` to dismiss. Reuse same id to update; new id for new content.';export const CANVAS_UPDATE_HINT="[Canvas Rule] Same id in render_ui = update existing surface. Different id = new surface. When a surface is referenced for editing, you MUST reuse its exact id.";const MAX_CONTEXT_SURFACES=8,MAX_CONTEXT_CHARS=500;export function buildActiveSurfacesContext(e,t){let n;if(!t)return null;if(n=e.getAllActive(t),0===n.length)return null;const s=[...n].sort((e,t)=>t.updatedAt-e.updatedAt).slice(0,8),a=n.length-s.length;let o=`[Canvas State] Active surfaces: ${s.map(t=>{const n=e.summarize(t.surfaceId);if(!n)return`"${t.surfaceId}"`;const s=n.types.slice(0,3).join(", "),a=n.title?`: "${n.title}"`:"";return`"${t.surfaceId}" (${s}${a})`}).join("; ")}.`;return a>0&&(o+=` ...and ${a} more.`),o+=" To modify existing content, reuse its id in render_ui.",o.length>500&&(o=o.slice(0,497)+"..."),o}
@@ -1 +1 @@
1
- import{WebSocket}from"ws";import{EventEmitter}from"node:events";import{randomUUID,createHash}from"node:crypto";import{loadOrCreateDeviceIdentity,buildDeviceAuthPayload,signDeviceAuth,ensureDevicePaired}from"./device-identity.js";const PROTOCOL_VERSION=3,CONNECT_TIMEOUT_MS=3e4,HEARTBEAT_INTERVAL_MS=15e3,LIVENESS_TIMEOUT_MS=6e4,AUTH_FAILURE_CLOSE_CODE=4001,CONNECT_DELAY_MS=750,RECONNECT_NOTIFY_MIN_MS=6e4,RECONNECT_NOTIFY_MAX_MS=18e4,RECONNECT_NOTIFY_METHOD="server/reconnect",MANUAL_RECONNECT_SIGNAL="SIGUSR1";function registerReconnectSignal(e,t,n){detachReconnectSignal(e),e.handler=t;try{process.on("SIGUSR1",t),n?.info?.("[gateway] manual reconnect enabled signal=SIGUSR1")}catch{n?.warn?.("[gateway] manual reconnect signal not supported")}}function detachReconnectSignal(e){if(e.handler){try{process.off("SIGUSR1",e.handler)}catch{}e.handler=null}}export class GatewayClient extends EventEmitter{ws=null;config;pending=new Map;connected=!1;stopped=!1;authFailed=!1;connectPromise=null;reconnectTimer=null;reconnectAttempt=0;signalState={handler:null};deviceIdentity;heartbeatTimer=null;lastPongTs=0;_connectionSeq=0;_currentConnectionId=null;_lastReadyAt=0;reconnectNotifyTimer=null;constructor(e){super(),this.config=e,this.deviceIdentity=loadOrCreateDeviceIdentity();try{ensureDevicePaired(this.deviceIdentity)}catch(e){}}async start(){this.stopped=!1,this.reconnectAttempt=0,registerReconnectSignal(this.signalState,()=>{this.stopped||(this.emit("manual-reconnect"),this.reconnectNow())}),await this.connect()}stop(){this.stopped=!0,this.stopHeartbeat(),this.clearReconnectNotify(),detachReconnectSignal(this.signalState),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.close()}async connect(){if(this.connectPromise)return this.connectPromise;this.connectPromise=this._connect();try{await this.connectPromise}finally{this.connectPromise=null}}_connect(){return new Promise((e,t)=>{if(this.authFailed)return void t(new Error("Authentication failed — not retrying"));const n=Date.now();this.emit("transport",{event:"connect_start",url:this.config.url,attempt:this.reconnectAttempt});const i=new WebSocket(this.config.url);this.ws=i;let s=null;const o=setTimeout(()=>{this.emit("transport",{event:"connect_fail",reason:"timeout",durationMs:Date.now()-n}),i.close(),t(new Error("Gateway connection timeout"))},3e4),c=t=>{clearTimeout(o),this.connected=!0,this.reconnectAttempt=0,this.authFailed=!1,this._connectionSeq++,this._currentConnectionId=randomUUID(),this._lastReadyAt=Date.now(),this.startHeartbeat(),this.emit("transport",{event:"connect_ok",connectionSeq:this._connectionSeq,connectionId:this._currentConnectionId,durationMs:Date.now()-n}),this.emit("connected",{...t,connectionSeq:this._connectionSeq,connectionId:this._currentConnectionId}),e()},r=e=>{clearTimeout(o),this.authFailed=!0,this.emit("transport",{event:"connect_fail",reason:e,durationMs:Date.now()-n}),this.emit("auth-failed",{reason:e}),i.close(),t(new Error(e))};i.on("open",()=>{this.emit("transport",{event:"ws_open",durationMs:Date.now()-n})}),i.on("message",e=>{const t="string"==typeof e?e:e.toString("utf-8");if("pong"===t)return void(this.lastPongTs=Date.now());let i;this.emitMessageHash(t);try{i=JSON.parse(t)}catch{return}const o=i.method;o&&!i.id&&(this.isReconnectNotification(o)?this.scheduleReconnectNotify():this.reconnectNotifyTimer&&this.clearReconnectNotify(),this.emit("notification",o,i.params));const a=i.type;if("event"===a&&this.reconnectNotifyTimer&&this.clearReconnectNotify(),"event"===a){const e=i.event,t=i.payload;if("connect.challenge"===e){this.emit("transport",{event:"handshake.challenge_recv",durationMs:Date.now()-n});const e=t?.nonce;setTimeout(()=>{s=this._sendConnect(e),this.emit("transport",{event:"handshake.connect_sent",durationMs:Date.now()-n})},750)}else"chat"===e?this.emit("chat",t):"agent"===e?this.emit("agent",t):"cron"===e?this.emit("cron",t):"canvas"===e?this.emit("canvas",t):this.emit("gateway-event",e,t)}else if("hello-ok"===a)c(i);else if("hello-error"===a||"connect-error"===a)r("Authentication rejected by Gateway");else if("res"===a){const e=i.id;if(e&&e===s){if(i.ok){const e=i.payload;c(e??i)}else{const e=i.error;r(e?.message||"Gateway connect rejected")}return}const t=this.pending.get(e);if(t)if(this.pending.delete(e),clearTimeout(t.timer),i.ok)t.resolve(i.payload);else{const e=i.error;t.reject(new Error(e?.message||"Gateway request failed"))}}}),i.on("pong",()=>{this.lastPongTs=Date.now()}),i.on("close",e=>{const i=this.connected;this.stopHeartbeat(),this.clearReconnectNotify(),this.emit("transport",{event:"close",code:e,durationMs:Date.now()-n}),this.connected=!1,this.connectPromise=null;for(const[,e]of this.pending)clearTimeout(e.timer),e.reject(new Error("Connection closed"));this.pending.clear(),i||(clearTimeout(o),t(new Error(`Connection closed during handshake (code=${e})`))),4001===e&&(this.authFailed=!0,this.emit("auth-failed",{code:e})),this.emit("disconnected"),this.stopped||this.authFailed||this.scheduleReconnect()}),i.on("error",e=>{this.emit("transport",{event:"error",message:e.message,durationMs:Date.now()-n}),this.connected||(clearTimeout(o),t(e)),this.emit("error",e)})})}emitMessageHash(e){if(e.length<32)return;const t=createHash("sha256").update(e).digest("hex").slice(0,16);this.emit("transport",{event:"message_recv",hash:t,size:e.length})}startHeartbeat(){this.stopHeartbeat(),this.lastPongTs=Date.now(),this.heartbeatTimer=setInterval(()=>{if(!this.ws||!this.connected)return;try{this.ws.ping()}catch{}const e=Date.now()-this.lastPongTs;e>6e4&&(this.emit("liveness-timeout",{elapsed:e}),this.ws.close())},15e3),"object"==typeof this.heartbeatTimer&&"unref"in this.heartbeatTimer&&this.heartbeatTimer.unref()}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}isReconnectNotification(e){return"server/reconnect"===e||e.endsWith("/reconnect")}scheduleReconnectNotify(){this.clearReconnectNotify();const e=6e4+12e4*Math.random();this.emit("reconnect-notify-scheduled",{delayMs:Math.round(e)}),this.reconnectNotifyTimer=setTimeout(()=>{this.reconnectNotifyTimer=null,!this.stopped&&this.connected&&(this.emit("reconnect-notify-fired"),this.reconnectNow())},e),"object"==typeof this.reconnectNotifyTimer&&"unref"in this.reconnectNotifyTimer&&this.reconnectNotifyTimer.unref()}clearReconnectNotify(){this.reconnectNotifyTimer&&(clearTimeout(this.reconnectNotifyTimer),this.reconnectNotifyTimer=null)}scheduleReconnect(){if(this.stopped)return;if(this.reconnectTimer)return;const e=this.config.retry??{baseMs:1e3,maxMs:6e5,maxAttempts:0};if(e.maxAttempts>0&&this.reconnectAttempt>=e.maxAttempts)return void this.emit("reconnect-exhausted",this.reconnectAttempt);const t=Math.min(e.baseMs*Math.pow(2,this.reconnectAttempt)+500*Math.random(),e.maxMs);this.reconnectAttempt++,this.emit("reconnecting",{attempt:this.reconnectAttempt,delayMs:t}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.stopped||this.connect().catch(e=>{this.emit("error",e instanceof Error?e:new Error(String(e)))})},t),"object"==typeof this.reconnectTimer&&"unref"in this.reconnectTimer&&this.reconnectTimer.unref()}reconnectNow(){this.stopped||(this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.close(),this.reconnectAttempt=0,this.connect().catch(e=>{this.emit("error",e instanceof Error?e:new Error(String(e)))}))}_sendConnect(e){const t=Date.now(),n="operator",i=["operator.admin","operator.approvals","operator.pairing"],s={id:this.deviceIdentity.deviceId,publicKey:this.deviceIdentity.publicKeyB64url,signedAt:t};if(e){const o=buildDeviceAuthPayload({deviceId:this.deviceIdentity.deviceId,clientId:"cli",clientMode:"cli",role:n,scopes:i,signedAtMs:t,token:this.config.token,nonce:e});s.nonce=e,s.signature=signDeviceAuth(this.deviceIdentity,o)}const o=randomUUID(),c={type:"req",id:o,method:"connect",params:{minProtocol:3,maxProtocol:3,client:{id:"cli",displayName:"BeeOS Platform Bridge",version:"0.1.0",platform:"beeos",mode:"cli"},caps:this.config.openclawCanvasCompat?["tool-events","canvas"]:["tool-events"],role:n,scopes:i,auth:{token:this.config.token},device:s}};return this.ws?.send(JSON.stringify(c)),o}async request(e,t,n=6e4){if(!this.ws||!this.connected)throw new Error("Not connected to Gateway");const i=randomUUID(),s={type:"req",id:i,method:e,params:t};return new Promise((t,o)=>{const c=setTimeout(()=>{this.pending.delete(i),o(new Error(`Gateway request timeout: ${e}`))},n);this.pending.set(i,{resolve:t,reject:o,timer:c}),this.ws.send(JSON.stringify(s))})}async agentSend(e,t,n,i,s){const o={agentId:n,sessionKey:e,message:t,deliver:!1,idempotencyKey:randomUUID()};i?.length&&(o.attachments=i),s&&(o.inputProvenance=s);return await this.request("agent",o,12e4)}async chatSend(e,t,n){const i={sessionKey:e,message:t,deliver:!1,idempotencyKey:randomUUID()};n?.length&&(i.attachments=n);return await this.request("chat.send",i,12e4)}async chatAbort(e,t){await this.request("chat.abort",{sessionKey:e,runId:t})}async chatHistory(e,t){return this.request("chat.history",{sessionKey:e,limit:t})}async skillsStatus(){return this.request("skills.status",{})}async sessionsList(){return this.request("sessions.list",{includeDerivedTitles:!0})}async sessionsResolve(e){return this.request("sessions.resolve",{sessionKey:e})}async sessionsPatch(e,t){return this.request("sessions.patch",{key:e,...t})}async sessionsDelete(e){return this.request("sessions.delete",{key:e})}async sessionsReset(e){return this.request("sessions.reset",{key:e,reason:"new"})}close(){if(this.ws)try{this.ws.close()}catch{}this.ws=null,this.connected=!1,this.connectPromise=null,this._currentConnectionId=null}get isConnected(){return this.connected}get connectionSeq(){return this._connectionSeq}get currentConnectionId(){return this._currentConnectionId}get lastReadyAt(){return this._lastReadyAt}}
1
+ import{WebSocket}from"ws";import{EventEmitter}from"node:events";import{randomUUID,createHash}from"node:crypto";import{loadOrCreateDeviceIdentity,buildDeviceAuthPayload,signDeviceAuth,ensureDevicePaired}from"./device-identity.js";const PROTOCOL_VERSION=3,CONNECT_TIMEOUT_MS=3e4,HEARTBEAT_INTERVAL_MS=15e3,LIVENESS_TIMEOUT_MS=6e4,AUTH_FAILURE_CLOSE_CODE=4001,CONNECT_DELAY_MS=750,RECONNECT_NOTIFY_MIN_MS=6e4,RECONNECT_NOTIFY_MAX_MS=18e4,RECONNECT_NOTIFY_METHOD="server/reconnect",MANUAL_RECONNECT_SIGNAL="SIGUSR1";function registerReconnectSignal(e,t,n){detachReconnectSignal(e),e.handler=t;try{process.on("SIGUSR1",t),n?.info?.("[gateway] manual reconnect enabled signal=SIGUSR1")}catch{n?.warn?.("[gateway] manual reconnect signal not supported")}}function detachReconnectSignal(e){if(e.handler){try{process.off("SIGUSR1",e.handler)}catch{}e.handler=null}}export class GatewayClient extends EventEmitter{ws=null;config;pending=new Map;connected=!1;stopped=!1;authFailed=!1;connectPromise=null;reconnectTimer=null;reconnectAttempt=0;signalState={handler:null};deviceIdentity;heartbeatTimer=null;lastPongTs=0;_connectionSeq=0;_currentConnectionId=null;_lastReadyAt=0;reconnectNotifyTimer=null;constructor(e){super(),this.config=e,this.deviceIdentity=loadOrCreateDeviceIdentity();try{ensureDevicePaired(this.deviceIdentity)}catch(e){}}async start(){this.stopped=!1,this.reconnectAttempt=0,registerReconnectSignal(this.signalState,()=>{this.stopped||(this.emit("manual-reconnect"),this.reconnectNow())}),await this.connect()}stop(){this.stopped=!0,this.stopHeartbeat(),this.clearReconnectNotify(),detachReconnectSignal(this.signalState),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.close()}async connect(){if(this.connectPromise)return this.connectPromise;this.connectPromise=this._connect();try{await this.connectPromise}finally{this.connectPromise=null}}_connect(){return new Promise((e,t)=>{if(this.authFailed)return void t(new Error("Authentication failed — not retrying"));const n=Date.now();this.emit("transport",{event:"connect_start",url:this.config.url,attempt:this.reconnectAttempt});const s=new WebSocket(this.config.url);this.ws=s;let i=null;const o=setTimeout(()=>{this.emit("transport",{event:"connect_fail",reason:"timeout",durationMs:Date.now()-n}),s.close(),t(new Error("Gateway connection timeout"))},3e4),r=t=>{clearTimeout(o),this.connected=!0,this.reconnectAttempt=0,this.authFailed=!1,this._connectionSeq++,this._currentConnectionId=randomUUID(),this._lastReadyAt=Date.now(),this.startHeartbeat(),this.emit("transport",{event:"connect_ok",connectionSeq:this._connectionSeq,connectionId:this._currentConnectionId,durationMs:Date.now()-n}),this.emit("connected",{...t,connectionSeq:this._connectionSeq,connectionId:this._currentConnectionId}),e()},c=e=>{clearTimeout(o),this.authFailed=!0,this.emit("transport",{event:"connect_fail",reason:e,durationMs:Date.now()-n}),this.emit("auth-failed",{reason:e}),s.close(),t(new Error(e))};s.on("open",()=>{this.emit("transport",{event:"ws_open",durationMs:Date.now()-n})}),s.on("message",e=>{const t="string"==typeof e?e:e.toString("utf-8");if("pong"===t)return void(this.lastPongTs=Date.now());let s;this.emitMessageHash(t);try{s=JSON.parse(t)}catch{return}const o=s.method;o&&!s.id&&(this.isReconnectNotification(o)?this.scheduleReconnectNotify():this.reconnectNotifyTimer&&this.clearReconnectNotify(),this.emit("notification",o,s.params));const a=s.type;if("event"===a&&this.reconnectNotifyTimer&&this.clearReconnectNotify(),"event"===a){const e=s.event,t=s.payload;if("connect.challenge"===e){this.emit("transport",{event:"handshake.challenge_recv",durationMs:Date.now()-n});const e=t?.nonce;setTimeout(()=>{i=this._sendConnect(e),this.emit("transport",{event:"handshake.connect_sent",durationMs:Date.now()-n})},750)}else"chat"===e?this.emit("chat",t):"agent"===e?this.emit("agent",t):"cron"===e?this.emit("cron",t):"canvas"===e?this.emit("canvas",t):this.emit("gateway-event",e,t)}else if("hello-ok"===a)r(s);else if("hello-error"===a||"connect-error"===a)c("Authentication rejected by Gateway");else if("res"===a){const e=s.id;if(e&&e===i){if(s.ok){const e=s.payload;r(e??s)}else{const e=s.error;c(e?.message||"Gateway connect rejected")}return}const t=this.pending.get(e);if(t)if(this.pending.delete(e),clearTimeout(t.timer),s.ok)t.resolve(s.payload);else{const e=s.error;t.reject(new Error(e?.message||"Gateway request failed"))}else this.emit("response",s)}}),s.on("pong",()=>{this.lastPongTs=Date.now()}),s.on("close",e=>{const s=this.connected;this.stopHeartbeat(),this.clearReconnectNotify(),this.emit("transport",{event:"close",code:e,durationMs:Date.now()-n}),this.connected=!1,this.connectPromise=null;for(const[,e]of this.pending)clearTimeout(e.timer),e.reject(new Error("Connection closed"));this.pending.clear(),s||(clearTimeout(o),t(new Error(`Connection closed during handshake (code=${e})`))),4001===e&&(this.authFailed=!0,this.emit("auth-failed",{code:e})),this.emit("disconnected"),this.stopped||this.authFailed||this.scheduleReconnect()}),s.on("error",e=>{this.emit("transport",{event:"error",message:e.message,durationMs:Date.now()-n}),this.connected||(clearTimeout(o),t(e)),this.emit("error",e)})})}emitMessageHash(e){if(e.length<32)return;const t=createHash("sha256").update(e).digest("hex").slice(0,16);this.emit("transport",{event:"message_recv",hash:t,size:e.length})}startHeartbeat(){this.stopHeartbeat(),this.lastPongTs=Date.now(),this.heartbeatTimer=setInterval(()=>{if(!this.ws||!this.connected)return;try{this.ws.ping()}catch{}const e=Date.now()-this.lastPongTs;e>6e4&&(this.emit("liveness-timeout",{elapsed:e}),this.ws.close())},15e3),"object"==typeof this.heartbeatTimer&&"unref"in this.heartbeatTimer&&this.heartbeatTimer.unref()}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}isReconnectNotification(e){return"server/reconnect"===e||e.endsWith("/reconnect")}scheduleReconnectNotify(){this.clearReconnectNotify();const e=6e4+12e4*Math.random();this.emit("reconnect-notify-scheduled",{delayMs:Math.round(e)}),this.reconnectNotifyTimer=setTimeout(()=>{this.reconnectNotifyTimer=null,!this.stopped&&this.connected&&(this.emit("reconnect-notify-fired"),this.reconnectNow())},e),"object"==typeof this.reconnectNotifyTimer&&"unref"in this.reconnectNotifyTimer&&this.reconnectNotifyTimer.unref()}clearReconnectNotify(){this.reconnectNotifyTimer&&(clearTimeout(this.reconnectNotifyTimer),this.reconnectNotifyTimer=null)}scheduleReconnect(){if(this.stopped)return;if(this.reconnectTimer)return;const e=this.config.retry??{baseMs:1e3,maxMs:6e5,maxAttempts:0};if(e.maxAttempts>0&&this.reconnectAttempt>=e.maxAttempts)return void this.emit("reconnect-exhausted",this.reconnectAttempt);const t=Math.min(e.baseMs*Math.pow(2,this.reconnectAttempt)+500*Math.random(),e.maxMs);this.reconnectAttempt++,this.emit("reconnecting",{attempt:this.reconnectAttempt,delayMs:t}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.stopped||this.connect().catch(e=>{this.emit("error",e instanceof Error?e:new Error(String(e)))})},t),"object"==typeof this.reconnectTimer&&"unref"in this.reconnectTimer&&this.reconnectTimer.unref()}reconnectNow(){this.stopped||(this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.close(),this.reconnectAttempt=0,this.connect().catch(e=>{this.emit("error",e instanceof Error?e:new Error(String(e)))}))}_sendConnect(e){const t=Date.now(),n="operator",s=["operator.admin","operator.approvals","operator.pairing"],i={id:this.deviceIdentity.deviceId,publicKey:this.deviceIdentity.publicKeyB64url,signedAt:t};if(e){const o=buildDeviceAuthPayload({deviceId:this.deviceIdentity.deviceId,clientId:"cli",clientMode:"cli",role:n,scopes:s,signedAtMs:t,token:this.config.token,nonce:e});i.nonce=e,i.signature=signDeviceAuth(this.deviceIdentity,o)}const o=randomUUID(),r={type:"req",id:o,method:"connect",params:{minProtocol:3,maxProtocol:3,client:{id:"cli",displayName:"BeeOS Platform Bridge",version:"0.1.0",platform:"beeos",mode:"cli"},caps:this.config.openclawCanvasCompat?["tool-events","canvas"]:["tool-events"],role:n,scopes:s,auth:{token:this.config.token},device:i}};return this.ws?.send(JSON.stringify(r)),o}async request(e,t,n=6e4){if(!this.ws||!this.connected)throw new Error("Not connected to Gateway");const s=randomUUID(),i={type:"req",id:s,method:e,params:t};return new Promise((t,o)=>{const r=setTimeout(()=>{this.pending.delete(s),o(new Error(`Gateway request timeout: ${e}`))},n);this.pending.set(s,{resolve:t,reject:o,timer:r}),this.ws.send(JSON.stringify(i))})}async agentSend(e,t,n,s,i){const o={agentId:n,sessionKey:e,message:t,deliver:!1,idempotencyKey:randomUUID()};s?.length&&(o.attachments=s),i&&(o.inputProvenance=i);return await this.request("agent",o,12e4)}async chatSend(e,t,n){const s={sessionKey:e,message:t,deliver:!1,idempotencyKey:randomUUID()};n?.length&&(s.attachments=n);return await this.request("chat.send",s,12e4)}async chatAbort(e,t){await this.request("chat.abort",{sessionKey:e,runId:t})}sendFrame(e){if(!this.ws||!this.connected)return!1;try{return this.ws.send(JSON.stringify(e)),!0}catch{return!1}}agentCancel(e,t){const n={sessionKey:e};t?.runId&&(n.runId=t.runId);const s=`abort_${t?.runId??t?.requestId??e}`;return this.sendFrame({type:"req",id:s,method:"chat.abort",params:n})}async chatHistory(e,t){return this.request("chat.history",{sessionKey:e,limit:t})}async skillsStatus(){return this.request("skills.status",{})}async sessionsList(){return this.request("sessions.list",{includeDerivedTitles:!0})}async sessionsResolve(e){return this.request("sessions.resolve",{sessionKey:e})}async sessionsPatch(e,t){return this.request("sessions.patch",{key:e,...t})}async sessionsDelete(e){return this.request("sessions.delete",{key:e})}async sessionsReset(e){return this.request("sessions.reset",{key:e,reason:"new"})}close(){if(this.ws)try{this.ws.close()}catch{}this.ws=null,this.connected=!1,this.connectPromise=null,this._currentConnectionId=null}get isConnected(){return this.connected}get connectionSeq(){return this._connectionSeq}get currentConnectionId(){return this._currentConnectionId}get lastReadyAt(){return this._lastReadyAt}}
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{resolveConfigWithMeta,mirrorOpenClawConfig}from"./config.js";import{MessageSDK}from"./messaging/message-sdk.js";import{registerA2ATools}from"./a2a/tools.js";import{createA2ATaskHandler}from"./a2a/task-handler.js";import{createA2AResultHandler}from"./a2a/result-handler.js";import{createA2ATaskCancelHandler}from"./a2a/cancel-handler.js";import{TaskHandleRegistry}from"./a2a/task-handle.js";import{pollPendingTasks}from"./a2a/poll-pending.js";import{BEEOS_UPLOAD_TOOL_NAME,BEEOS_UPLOAD_TOOL_SCHEMA,BEEOS_UPLOAD_TOOL_DESCRIPTION,executeUpload}from"./upload/tool.js";import{writeUploadToolResult,cleanupUploadToolResultCache}from"./upload/result-cache.js";import{handleFileStage}from"./upload/file-stage.js";import{ACPServer}from"./acp-server.js";import{createObsEventWriter}from"./observability.js";import{resolvePluginVersion}from"./plugin-version.js";import{createTerminalWebSocketService}from"./terminal/websocket.js";import{TerminalManager}from"./terminal/session-manager.js";import{loadAgentKeyPair,agentFetch}from"./agent-auth.js";import{readDiscoveryCache,writeDiscoveryCache}from"./discovery-cache.js";import{discoverBridgeFromGW}from"./bridge-discovery.js";import{CanvasStateManager}from"./canvas/state.js";import{CanvasRelayClient}from"./canvas/relay-client.js";import{RENDER_UI_TOOL_NAME,RENDER_UI_TOOL_DESCRIPTION,RENDER_UI_TOOL_SCHEMA,CLOSE_UI_TOOL_NAME,CLOSE_UI_TOOL_DESCRIPTION,CLOSE_UI_TOOL_SCHEMA,createRenderUiHandler,createCloseUiHandler,CANVAS_SYSTEM_PROMPT}from"./canvas/tools.js";import{FormSchemaRegistry}from"./surface/form-schema-registry.js";import{CRON_CREATE_SCHEMA,CRON_UPDATE_SCHEMA}from"./surface/cron-schemas.js";import{RENDER_FORM_TOOL_NAME,RENDER_FORM_TOOL_SCHEMA,buildRenderFormDescription,createRenderFormHandler}from"./surface/render-form-tool.js";import{ResourceDescriptorRegistry}from"./surface/resource-descriptor-registry.js";import{CRON_RESOURCE}from"./surface/cron-resource.js";import{generateActionTools}from"./surface/action-tool-generator.js";import{buildThirdPartyChannelSet,isThirdPartyChannel}from"./channel-detection.js";const PLUGIN_VERSION=resolvePluginVersion();let agentKeys=null,sharedCanvasState=null;function initializePlugin(e){let a,o;try{a=e.runtime?.config?.loadConfig?.()}catch{}try{o=resolveConfigWithMeta({pluginConfig:e.pluginConfig??{},openclawConfig:a})}catch(a){return e.logger.error?.("[beeos-claw] Failed to resolve config:",a),null}const r=o.config,t=buildThirdPartyChannelSet(a);t.size>0&&e.logger.info?.(`[beeos-claw] Third-party channels detected: ${[...t].join(", ")}`);const s=r.log.enabled?createObsEventWriter({dir:r.log.dir,redaction:{gatewayToken:r.gateway.token},logger:e.logger}):()=>{};s({component:"plugin",domain:"lifecycle",name:"lifecycle.startup",severity:"info",payload:{pluginVersion:PLUGIN_VERSION,pid:process.pid,nodeVersion:process.version,cwd:process.cwd()}}),s({component:"plugin",domain:"config",name:"config.resolved",severity:"info",payload:{config:r,sources:o.sources,openclawConfigPath:o.openclawConfigPath}});for(const a of o.validation)s({component:"plugin",domain:"config",name:"config.validation",severity:a.severity,summary:a.message,error:{code:a.code,message:a.message,nextSteps:a.nextSteps}}),"error"===a.severity?e.logger.error?.(`[beeos-claw] ${a.message}`):e.logger.warn?.(`[beeos-claw] ${a.message}`);if(o.validation.some(e=>"error"===e.severity)&&e.logger.error?.("[beeos-claw] Plugin has configuration errors — some features may not work."),r.keyFile)try{agentKeys=loadAgentKeyPair(r.keyFile);const a=Buffer.from(agentKeys.publicKey).toString("base64");e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (publicKey: ${a})`)}catch(a){e.logger.warn?.(`[beeos-claw] Failed to load agent key pair: ${a}`),e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (no key pair — signed requests disabled)`)}else e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (no keyFile configured)`);return{cfg:r,writeObs:s,thirdPartyChannels:t,openclawConfig:a}}function registerUploadTools(e,a,o){const{cfg:r,writeObs:t}=a;cleanupUploadToolResultCache().catch(a=>{e.logger.warn?.(`[beeos_upload_file] cache cleanup failed on startup: ${String(a)}`)}),e.registerTool({name:BEEOS_UPLOAD_TOOL_NAME,description:BEEOS_UPLOAD_TOOL_DESCRIPTION,parameters:BEEOS_UPLOAD_TOOL_SCHEMA,async execute(a,s){e.logger.debug?.(`[beeos_upload_file] toolCallId=${a} params=${JSON.stringify(s)}`);const n=await executeUpload(s,r,agentKeys);return e.logger.debug?.(`[beeos_upload_file] toolCallId=${a} ok=${n.ok}`),t({component:"upload-tool",domain:"tool",name:n.ok?"upload.success":"upload.failure",severity:n.ok?"info":"warn",payload:{toolCallId:a,ok:n.ok,fileCount:n.files?.length??0,error:n.error}}),n.ok&&n.content&&o.current&&o.current.pushToolResultContent(a,BEEOS_UPLOAD_TOOL_NAME,n.content),(async o=>{try{await writeUploadToolResult(a,BEEOS_UPLOAD_TOOL_NAME,o),await cleanupUploadToolResultCache()}catch(o){e.logger.warn?.(`[beeos_upload_file] persist cache failed toolCallId=${a}: ${String(o)}`)}return o})(n)}}),e.registerHttpRoute({path:"/beeos/files/stage",auth:"gateway",async handler(e,o){await handleFileStage(e,o,a.cfg)}})}function registerServices(e,a,o){const{cfg:r,writeObs:t,thirdPartyChannels:s}=a,n=agentKeys?(e,a)=>agentFetch(e,agentKeys,a):void 0,i=agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):void 0,l=new ACPServer(r,e.logger,t,n,i,s);o.current=l,e.registerService({id:"beeos-acp",async start(){if(!r.bridge.url&&r.agentGatewayUrl&&n){const a=await discoverBridgeFromGW(r.agentGatewayUrl,n);if(a)r.bridge.url=a.url,writeDiscoveryCache({bridge:{url:a.url,discoveredAt:Date.now()}}),e.logger.info?.(`[beeos-claw] Bridge URL discovered from Agent Gateway: ${a.url}`);else{const a=readDiscoveryCache();a?.bridge?.url?(r.bridge.url=a.bridge.url,e.logger.info?.(`[beeos-claw] Bridge URL from cache (GW unreachable): ${a.bridge.url}`)):e.logger.debug?.("[beeos-claw] Bridge URL not available (no GW, no cache) — bridge disabled")}}await l.start(r.bridge.url||void 0),e.logger.info?.("[beeos-claw] ACP Server started")},async stop(){await l.stop(),e.logger.info?.("[beeos-claw] ACP Server stopped")}});const g=new TaskHandleRegistry;let c=null;const{enabled:d,url:p,principalId:f,a2aEnabled:u}=r.messageBus;let y;if(r.agentGatewayUrl&&agentKeys){const e=r.agentGatewayUrl,a=agentKeys;y=async o=>{const r=await agentFetch(`${e}/api/v1/messaging/token`,a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({principal_id:o})});if(!r.ok){const e=await r.text().catch(()=>"");throw new Error(`Gateway messaging token returned ${r.status}: ${e}`)}return r.json()}}if(d&&(y||r.messageBus.serviceUrl)){c=new MessageSDK({serviceUrl:y?void 0:r.messageBus.serviceUrl,centrifugoUrl:p},e.logger);const a=f,o=async a=>{await c.connect(a,{centrifugoUrl:p,tokenProvider:y}),e.logger.info?.("[beeos-claw] Message SDK connected (principalId=%s, via=%s)",a,y?"gateway":"direct")};e.registerService({id:"beeos-message-bus",async start(){let r=a;if(r||(r=process.env.BEEOS_PRINCIPAL_ID||""),!r&&l)try{await l.waitForAgentMapping(),r=l.getDefaultPlatformAgentId()||""}catch(a){e.logger.warn?.("[beeos-claw] Failed to resolve principalId from agent sync:",a)}r?await o(r):l?(e.logger.info?.("[beeos-claw] Message bus deferred: waiting for late agent sync..."),l.onceAgentMappingReady(()=>{const a=l.getDefaultPlatformAgentId();a?o(a).catch(a=>{e.logger.error?.("[beeos-claw] Deferred message bus connect failed:",a)}):e.logger.warn?.("[beeos-claw] Agent mapping ready but no principalId, message bus stays disabled")})):e.logger.warn?.("[beeos-claw] No principalId resolved, message bus disabled")},async stop(){await(c?.disconnect()),e.logger.info?.("[beeos-claw] Message SDK disconnected")}});const t=(e,a,o,r)=>l.agentSend(e,a,o,r),s=(e,a,o)=>l.trackA2ARun(e,a,o),n=e=>l.emitA2ASystemNotification(e),i=r.agentGatewayUrl?{agentGatewayUrl:r.agentGatewayUrl,agentKeys:agentKeys,logger:e.logger}:void 0;c.onMessage("a2a_task",createA2ATaskHandler(t,i,s,n)),c.onMessage("a2a_result",createA2AResultHandler(t,g,n)),c.onMessage("a2a_task_cancel",createA2ATaskCancelHandler(t,e=>l.cancelA2ARunByTaskId(e))),i&&e.registerService({id:"beeos-a2a-poll",async start(){await l.waitForAgentMapping();const a=await pollPendingTasks(i,t,s);a>0&&e.logger.info?.("[beeos-claw] Dispatched %d pending A2A tasks on startup",a)}})}else d?e.logger.warn?.("[beeos-claw] Message bus enabled but MESSAGE_SERVICE_URL not set — disabled"):e.logger.info?.("[beeos-claw] Message bus disabled (enabled=%s)",d);if(!1!==u&&r.agentGatewayUrl){const a=e=>l.getGatewaySessionKeyForToolCall(e),o=e=>l.getMentionsForToolCall(e),t=(e,a)=>{l.broadcastNotification(e,a)};registerA2ATools(e,{agentGatewayUrl:r.agentGatewayUrl,agentKeys:agentKeys,logger:e.logger},g,a,o,t),e.logger.info?.("[beeos-claw] A2A tools registered (beeos_discover_agents, beeos_call_agent) via REST")}if(r.canvasEnabled){sharedCanvasState||(sharedCanvasState=new CanvasStateManager);const a=sharedCanvasState;if(r.agentGatewayUrl&&agentKeys){let o;a.setLogger(e.logger);{const e=r.agentGatewayUrl,a=agentKeys;o=async()=>{const o=await agentFetch(`${e}/api/v1/canvas/token`,a,{method:"POST"});if(!o.ok){const e=await o.text().catch(()=>"");throw new Error(`Canvas token returned ${o.status}: ${e}`)}return o.json()}}e.registerService({id:"beeos-canvas-relay",async start(){try{await l.waitForAgentMapping();const t=l.getDefaultPlatformAgent();if(!t?.id)return void e.logger.info?.("[beeos-claw] Canvas Relay skipped: no agentId after sync");const s=new CanvasRelayClient({canvasRelayUrl:r.canvasRelayUrl,agentKeys:agentKeys,agentId:t.id,displayName:t.displayName,avatarUrl:t.avatarUrl,tokenProvider:o,onReconnect:()=>l.onRelayReconnected(),logger:e.logger});s.connect(),a.setRelayClient(s),a.setAgentId(t.id),l.wireRelayActionHandler(),l.flushPendingCanvasLinks(),e.logger.info?.(`[beeos-claw] Canvas Relay multiplexed client connected (agentId=${t.id}, name=${t.name??"none"})`)}catch(a){e.logger.warn?.(`[beeos-claw] Failed to start Canvas Relay client: ${a}`)}},stop(){a.getRelayClient()?.disconnect()}}),e.logger.info?.("[beeos-claw] Canvas Relay configured")}else e.logger.warn?.("[beeos-claw] Canvas Relay unavailable: agentGatewayUrl or agentKeys missing");const o={stateManager:a,logger:e.logger,writeObs:e=>t(e),isCanvasActive:()=>l.isCanvasActive(),getActiveSessionId:e=>l.getSessionIdForToolCall(e),getPlatformAgentId:e=>l.getPlatformAgentIdForToolCall(e),getGatewaySessionKey:e=>l.getGatewaySessionKeyForToolCall(e),waitForAgentSync:()=>l.waitForAgentMapping()},n=new FormSchemaRegistry;n.register(CRON_CREATE_SCHEMA),n.register(CRON_UPDATE_SCHEMA);const i=new ResourceDescriptorRegistry;i.register(CRON_RESOURCE);const g=e=>async(a,o)=>(l.preMapToolCallSession(a),e(a,o));e.registerTool({name:RENDER_UI_TOOL_NAME,description:RENDER_UI_TOOL_DESCRIPTION,parameters:RENDER_UI_TOOL_SCHEMA,execute:g(createRenderUiHandler(o))}),e.registerTool({name:CLOSE_UI_TOOL_NAME,description:CLOSE_UI_TOOL_DESCRIPTION,parameters:CLOSE_UI_TOOL_SCHEMA,execute:g(createCloseUiHandler(o))}),l.setCanvasState(a,{schemaRegistry:n,descriptorRegistry:i});const c=l.getFormBuilder();c&&e.registerTool({name:RENDER_FORM_TOOL_NAME,description:buildRenderFormDescription(n),parameters:RENDER_FORM_TOOL_SCHEMA,execute:g(createRenderFormHandler({registry:n,builder:c,logger:e.logger}))});const d=l.getResourceRenderer();if(d){generateActionTools(i,e,async(e,a)=>l.gatewayRequest(e,a),d,e.logger)}const p=new Set([RENDER_UI_TOOL_NAME,CLOSE_UI_TOOL_NAME,RENDER_FORM_TOOL_NAME]),f=256,u=new Map;if("function"==typeof e.on){try{e.on("before_prompt_build",(e,a)=>{if(a?.sessionKey){if(u.size>=f&&!u.has(a.sessionKey)){const e=u.keys().next().value;void 0!==e&&u.delete(e)}u.set(a.sessionKey,a.channelId)}if(isThirdPartyChannel(s,{sessionKey:a?.sessionKey,channelId:a?.channelId}))return;return(a?.sessionKey?l.isCanvasActiveForGatewayKey(a.sessionKey):l.isCanvasActive())?{appendSystemContext:CANVAS_SYSTEM_PROMPT}:{appendSystemContext:"Canvas is closed by user. Do NOT use render_ui, close_ui, or render_form. Respond with plain text only."}}),e.logger.debug?.("[beeos-claw] Canvas system prompt hook registered: before_prompt_build")}catch{e.logger.debug?.("[beeos-claw] before_prompt_build hook not supported")}try{e.on("before_tool_call",(e,a)=>{if(a?.sessionKey&&l.setPendingToolCallSessionKey(a.sessionKey),!p.has(e.toolName))return;if(isThirdPartyChannel(s,{sessionKey:a?.sessionKey}))return{block:!0,blockReason:"Canvas tools are not available in this channel. Respond with plain text only."};return(a?.sessionKey?l.isCanvasActiveForGatewayKey(a.sessionKey):l.isCanvasActive())?void 0:{block:!0,blockReason:"Canvas is closed by user. Respond with plain text instead."}}),e.logger.debug?.("[beeos-claw] Canvas tool guard registered: before_tool_call")}catch{e.logger.debug?.("[beeos-claw] before_tool_call hook not supported")}}e.logger.info?.("[beeos-claw] Canvas tools registered (render_ui, close_ui, render_form + auto-action tools)")}else e.logger.info?.("[beeos-claw] Canvas disabled by config (canvasEnabled=false)");const m=new TerminalManager,b=createTerminalWebSocketService({config:{port:r.terminalWsPort,token:agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):"",allowedOrigins:r.terminalWsAllowedOrigins},terminalMgr:m,logger:e.logger,writeObs:t});if(r.bridge.shell.enabled?e.registerService({id:"beeos-terminal-ws",start(){b.start(),e.logger.info?.(`[beeos-claw] Terminal WS started on port ${r.terminalWsPort}`)},stop(){b.stop(),m.destroy(),e.logger.info?.("[beeos-claw] Terminal WS stopped")}}):e.logger.info?.("[beeos-claw] Terminal/shell disabled by config (bridge.shell.enabled=false)"),a.openclawConfig){const o=mirrorOpenClawConfig(a.openclawConfig);o.copied?e.logger.info?.(`[beeos-claw] mirrored openclaw config to ${o.destinationPath}`):e.logger.debug?.(`[beeos-claw] openclaw config mirror skipped: ${o.reason}`)}}const plugin={id:"beeos-claw",name:"beeos-claw",description:"BeeOS platform bridge plugin for OpenClaw. Provides file upload/download, ACP bridge, and observability.",version:PLUGIN_VERSION,register(e){if(e.registrationMode&&"full"!==e.registrationMode)return void e.logger.debug?.(`[beeos-claw] Skipping registration (mode=${e.registrationMode})`);const a=initializePlugin(e);if(!a)return;const o={current:null};registerUploadTools(e,a,o),registerServices(e,a,o),e.logger.info?.("[beeos-claw] Plugin registered successfully")}};export default plugin;
1
+ import{resolveConfigWithMeta,mirrorOpenClawConfig}from"./config.js";import{MessageSDK}from"./messaging/message-sdk.js";import{registerA2ATools,TaskHandleRegistry}from"./a2a/tools.js";import{BEEOS_UPLOAD_TOOL_NAME,BEEOS_UPLOAD_TOOL_SCHEMA,BEEOS_UPLOAD_TOOL_DESCRIPTION,executeUpload}from"./upload/tool.js";import{writeUploadToolResult,cleanupUploadToolResultCache}from"./upload/result-cache.js";import{handleFileStage}from"./upload/file-stage.js";import{ACPServer}from"./acp-server.js";import{createObsEventWriter}from"./observability.js";import{resolvePluginVersion}from"./plugin-version.js";import{createTerminalWebSocketService}from"./terminal/websocket.js";import{TerminalManager}from"./terminal/session-manager.js";import{loadAgentKeyPair,agentFetch}from"./agent-auth.js";import{readDiscoveryCache,writeDiscoveryCache}from"./discovery-cache.js";import{discoverBridgeFromGW}from"./bridge-discovery.js";import{CanvasStateManager}from"./canvas/state.js";import{CanvasRelayClient}from"./canvas/relay-client.js";import{RENDER_UI_TOOL_NAME,RENDER_UI_TOOL_DESCRIPTION,RENDER_UI_TOOL_SCHEMA,CLOSE_UI_TOOL_NAME,CLOSE_UI_TOOL_DESCRIPTION,CLOSE_UI_TOOL_SCHEMA,createRenderUiHandler,createCloseUiHandler,CANVAS_SYSTEM_PROMPT}from"./canvas/tools.js";import{FormSchemaRegistry}from"./surface/form-schema-registry.js";import{CRON_CREATE_SCHEMA,CRON_UPDATE_SCHEMA}from"./surface/cron-schemas.js";import{RENDER_FORM_TOOL_NAME,RENDER_FORM_TOOL_SCHEMA,buildRenderFormDescription,createRenderFormHandler}from"./surface/render-form-tool.js";import{ResourceDescriptorRegistry}from"./surface/resource-descriptor-registry.js";import{CRON_RESOURCE}from"./surface/cron-resource.js";import{generateActionTools}from"./surface/action-tool-generator.js";import{buildThirdPartyChannelSet,isThirdPartyChannel}from"./channel-detection.js";const PLUGIN_VERSION=resolvePluginVersion();let agentKeys=null,sharedCanvasState=null;function initializePlugin(e){let o,a;try{o=e.runtime?.config?.loadConfig?.()}catch{}try{a=resolveConfigWithMeta({pluginConfig:e.pluginConfig??{},openclawConfig:o})}catch(o){return e.logger.error?.("[beeos-claw] Failed to resolve config:",o),null}const r=a.config,s=buildThirdPartyChannelSet(o);s.size>0&&e.logger.info?.(`[beeos-claw] Third-party channels detected: ${[...s].join(", ")}`);const t=r.log.enabled?createObsEventWriter({dir:r.log.dir,redaction:{gatewayToken:r.gateway.token},logger:e.logger}):()=>{};t({component:"plugin",domain:"lifecycle",name:"lifecycle.startup",severity:"info",payload:{pluginVersion:PLUGIN_VERSION,pid:process.pid,nodeVersion:process.version,cwd:process.cwd()}}),t({component:"plugin",domain:"config",name:"config.resolved",severity:"info",payload:{config:r,sources:a.sources,openclawConfigPath:a.openclawConfigPath}});for(const o of a.validation)t({component:"plugin",domain:"config",name:"config.validation",severity:o.severity,summary:o.message,error:{code:o.code,message:o.message,nextSteps:o.nextSteps}}),"error"===o.severity?e.logger.error?.(`[beeos-claw] ${o.message}`):e.logger.warn?.(`[beeos-claw] ${o.message}`);if(a.validation.some(e=>"error"===e.severity)&&e.logger.error?.("[beeos-claw] Plugin has configuration errors — some features may not work."),r.keyFile)try{agentKeys=loadAgentKeyPair(r.keyFile);const o=Buffer.from(agentKeys.publicKey).toString("base64");e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (publicKey: ${o})`)}catch(o){e.logger.warn?.(`[beeos-claw] Failed to load agent key pair: ${o}`),e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (no key pair — signed requests disabled)`)}else e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (no keyFile configured)`);return{cfg:r,writeObs:t,thirdPartyChannels:s,openclawConfig:o}}function registerUploadTools(e,o,a){const{cfg:r,writeObs:s}=o;cleanupUploadToolResultCache().catch(o=>{e.logger.warn?.(`[beeos_upload_file] cache cleanup failed on startup: ${String(o)}`)}),e.registerTool({name:BEEOS_UPLOAD_TOOL_NAME,description:BEEOS_UPLOAD_TOOL_DESCRIPTION,parameters:BEEOS_UPLOAD_TOOL_SCHEMA,async execute(o,t,n){e.logger.debug?.(`[beeos_upload_file] toolCallId=${o} params=${JSON.stringify(t)}`);const i=await executeUpload(t,r,agentKeys,n);return e.logger.debug?.(`[beeos_upload_file] toolCallId=${o} ok=${i.ok}`),s({component:"upload-tool",domain:"tool",name:i.ok?"upload.success":"upload.failure",severity:i.ok?"info":"warn",payload:{toolCallId:o,ok:i.ok,fileCount:i.files?.length??0,error:i.error}}),i.ok&&i.content&&a.current&&a.current.pushToolResultContent(o,BEEOS_UPLOAD_TOOL_NAME,i.content),(async a=>{try{await writeUploadToolResult(o,BEEOS_UPLOAD_TOOL_NAME,a),await cleanupUploadToolResultCache()}catch(a){e.logger.warn?.(`[beeos_upload_file] persist cache failed toolCallId=${o}: ${String(a)}`)}return a})(i)}}),e.registerHttpRoute({path:"/beeos/files/stage",auth:"gateway",async handler(e,a){await handleFileStage(e,a,o.cfg)}})}function registerServices(e,o,a){const{cfg:r,writeObs:s,thirdPartyChannels:t}=o,n=agentKeys?(e,o)=>agentFetch(e,agentKeys,o):void 0,i=agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):void 0,l=new ACPServer(r,e.logger,s,n,i,t);a.current=l,e.registerService({id:"beeos-acp",async start(){if(!r.bridge.url&&r.agentGatewayUrl&&n){const o=await discoverBridgeFromGW(r.agentGatewayUrl,n);if(o)r.bridge.url=o.url,writeDiscoveryCache({bridge:{url:o.url,discoveredAt:Date.now()}}),e.logger.info?.(`[beeos-claw] Bridge URL discovered from Agent Gateway: ${o.url}`);else{const o=readDiscoveryCache();o?.bridge?.url?(r.bridge.url=o.bridge.url,e.logger.info?.(`[beeos-claw] Bridge URL from cache (GW unreachable): ${o.bridge.url}`)):e.logger.debug?.("[beeos-claw] Bridge URL not available (no GW, no cache) — bridge disabled")}}await l.start(r.bridge.url||void 0),e.logger.info?.("[beeos-claw] ACP Server started")},async stop(){await l.stop(),e.logger.info?.("[beeos-claw] ACP Server stopped")}});const g=new TaskHandleRegistry;let c=null;const{enabled:d,url:p,principalId:f,a2aEnabled:y}=r.messageBus;let u;if(r.agentGatewayUrl&&agentKeys){const e=r.agentGatewayUrl,o=agentKeys;u=async a=>{const r=await agentFetch(`${e}/api/v1/messaging/token`,o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({principal_id:a})});if(!r.ok){const e=await r.text().catch(()=>"");throw new Error(`Gateway messaging token returned ${r.status}: ${e}`)}return r.json()}}if(d&&(u||r.messageBus.serviceUrl)){c=new MessageSDK({serviceUrl:u?void 0:r.messageBus.serviceUrl,centrifugoUrl:p},e.logger);const o=f,a=async o=>{await c.connect(o,{centrifugoUrl:p,tokenProvider:u}),l.setMessageSdk(c,o),e.logger.info?.("[beeos-claw] Message SDK connected (principalId=%s, via=%s)",o,u?"gateway":"direct")};e.registerService({id:"beeos-message-bus",async start(){let r=o;if(r||(r=process.env.BEEOS_PRINCIPAL_ID||""),!r&&l)try{await l.waitForAgentMapping(),r=l.getDefaultPlatformAgentId()||""}catch(o){e.logger.warn?.("[beeos-claw] Failed to resolve principalId from agent sync:",o)}r?await a(r):l?(e.logger.info?.("[beeos-claw] Message bus deferred: waiting for late agent sync..."),l.onceAgentMappingReady(()=>{const o=l.getDefaultPlatformAgentId();o?a(o).catch(o=>{e.logger.error?.("[beeos-claw] Deferred message bus connect failed:",o)}):e.logger.warn?.("[beeos-claw] Agent mapping ready but no principalId, message bus stays disabled")})):e.logger.warn?.("[beeos-claw] No principalId resolved, message bus disabled")},async stop(){await(c?.disconnect()),e.logger.info?.("[beeos-claw] Message SDK disconnected")}}),c.onMessage("agent_request",async e=>{const o=e.payload,a="string"==typeof o?.message?o.message:"",r=Array.isArray(o?.files)?o.files:void 0,s="string"==typeof o?.session_key?o.session_key:void 0,t=e.channel_id??e.metadata?.channel_id??("string"==typeof o?.channel_id?o.channel_id:void 0),n=t&&t.length>0?t:void 0;a&&await l.agentSend(a,r,s,void 0,n)})}else d?e.logger.warn?.("[beeos-claw] Message bus enabled but MESSAGE_SERVICE_URL not set — disabled"):e.logger.info?.("[beeos-claw] Message bus disabled (enabled=%s)",d);if(!1!==y&&r.agentGatewayUrl){const o=e=>l.getGatewaySessionKeyForToolCall(e),a=e=>l.getMentionsForToolCall(e),s=(e,o)=>{l.broadcastNotification(e,o)};registerA2ATools(e,{agentGatewayUrl:r.agentGatewayUrl,agentKeys:agentKeys,logger:e.logger},g,o,a,s),e.logger.info?.("[beeos-claw] A2A tools registered (beeos_discover_agents, beeos_call_agent) via REST")}if(r.canvasEnabled){sharedCanvasState||(sharedCanvasState=new CanvasStateManager);const o=sharedCanvasState;if(r.agentGatewayUrl&&agentKeys){let a;o.setLogger(e.logger);{const e=r.agentGatewayUrl,o=agentKeys;a=async()=>{const a=await agentFetch(`${e}/api/v1/canvas/token`,o,{method:"POST"});if(!a.ok){const e=await a.text().catch(()=>"");throw new Error(`Canvas token returned ${a.status}: ${e}`)}return a.json()}}e.registerService({id:"beeos-canvas-relay",async start(){try{await l.waitForAgentMapping();const s=l.getDefaultPlatformAgent();if(!s?.id)return void e.logger.info?.("[beeos-claw] Canvas Relay skipped: no agentId after sync");const t=new CanvasRelayClient({canvasRelayUrl:r.canvasRelayUrl,agentKeys:agentKeys,agentId:s.id,displayName:s.displayName,avatarUrl:s.avatarUrl,tokenProvider:a,onReconnect:()=>l.onRelayReconnected(),logger:e.logger});t.connect(),o.setRelayClient(t),o.setAgentId(s.id),l.wireRelayActionHandler(),l.flushPendingCanvasLinks(),e.logger.info?.(`[beeos-claw] Canvas Relay multiplexed client connected (agentId=${s.id}, name=${s.name??"none"})`)}catch(o){e.logger.warn?.(`[beeos-claw] Failed to start Canvas Relay client: ${o}`)}},stop(){o.getRelayClient()?.disconnect()}}),e.logger.info?.("[beeos-claw] Canvas Relay configured")}else e.logger.warn?.("[beeos-claw] Canvas Relay unavailable: agentGatewayUrl or agentKeys missing");const a={stateManager:o,logger:e.logger,writeObs:e=>s(e),isCanvasActive:()=>l.isCanvasActive(),getActiveSessionId:e=>l.getSessionIdForToolCall(e),getPlatformAgentId:e=>l.getPlatformAgentIdForToolCall(e),getGatewaySessionKey:e=>l.getGatewaySessionKeyForToolCall(e),waitForAgentSync:()=>l.waitForAgentMapping()},n=new FormSchemaRegistry;n.register(CRON_CREATE_SCHEMA),n.register(CRON_UPDATE_SCHEMA);const i=new ResourceDescriptorRegistry;i.register(CRON_RESOURCE);const g=e=>async(o,a,r)=>(l.preMapToolCallSession(o),e(o,a));e.registerTool({name:RENDER_UI_TOOL_NAME,description:RENDER_UI_TOOL_DESCRIPTION,parameters:RENDER_UI_TOOL_SCHEMA,execute:g(createRenderUiHandler(a))}),e.registerTool({name:CLOSE_UI_TOOL_NAME,description:CLOSE_UI_TOOL_DESCRIPTION,parameters:CLOSE_UI_TOOL_SCHEMA,execute:g(createCloseUiHandler(a))}),l.setCanvasState(o,{schemaRegistry:n,descriptorRegistry:i});const c=l.getFormBuilder();c&&e.registerTool({name:RENDER_FORM_TOOL_NAME,description:buildRenderFormDescription(n),parameters:RENDER_FORM_TOOL_SCHEMA,execute:g(createRenderFormHandler({registry:n,builder:c,logger:e.logger}))});const d=l.getResourceRenderer();if(d){generateActionTools(i,e,async(e,o)=>l.gatewayRequest(e,o),d,e.logger)}const p=new Set([RENDER_UI_TOOL_NAME,CLOSE_UI_TOOL_NAME,RENDER_FORM_TOOL_NAME]),f=256,y=new Map;if("function"==typeof e.on){try{e.on("before_prompt_build",(e,o)=>{if(o?.sessionKey){if(y.size>=f&&!y.has(o.sessionKey)){const e=y.keys().next().value;void 0!==e&&y.delete(e)}y.set(o.sessionKey,o.channelId)}if(isThirdPartyChannel(t,{sessionKey:o?.sessionKey,channelId:o?.channelId}))return;return(o?.sessionKey?l.isCanvasActiveForGatewayKey(o.sessionKey):l.isCanvasActive())?{appendSystemContext:CANVAS_SYSTEM_PROMPT}:{appendSystemContext:"Canvas is closed by user. Do NOT use render_ui, close_ui, or render_form. Respond with plain text only."}}),e.logger.debug?.("[beeos-claw] Canvas system prompt hook registered: before_prompt_build")}catch{e.logger.debug?.("[beeos-claw] before_prompt_build hook not supported")}try{e.on("before_tool_call",(e,o)=>{if(o?.sessionKey&&l.setPendingToolCallSessionKey(o.sessionKey),!p.has(e.toolName))return;if(isThirdPartyChannel(t,{sessionKey:o?.sessionKey}))return{block:!0,blockReason:"Canvas tools are not available in this channel. Respond with plain text only."};return(o?.sessionKey?l.isCanvasActiveForGatewayKey(o.sessionKey):l.isCanvasActive())?void 0:{block:!0,blockReason:"Canvas is closed by user. Respond with plain text instead."}}),e.logger.debug?.("[beeos-claw] Canvas tool guard registered: before_tool_call")}catch{e.logger.debug?.("[beeos-claw] before_tool_call hook not supported")}}e.logger.info?.("[beeos-claw] Canvas tools registered (render_ui, close_ui, render_form + auto-action tools)")}else e.logger.info?.("[beeos-claw] Canvas disabled by config (canvasEnabled=false)");const m=new TerminalManager,b=createTerminalWebSocketService({config:{port:r.terminalWsPort,token:agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):"",allowedOrigins:r.terminalWsAllowedOrigins},terminalMgr:m,logger:e.logger,writeObs:s});if(r.bridge.shell.enabled?e.registerService({id:"beeos-terminal-ws",start(){b.start(),e.logger.info?.(`[beeos-claw] Terminal WS started on port ${r.terminalWsPort}`)},stop(){b.stop(),m.destroy(),e.logger.info?.("[beeos-claw] Terminal WS stopped")}}):e.logger.info?.("[beeos-claw] Terminal/shell disabled by config (bridge.shell.enabled=false)"),o.openclawConfig){const a=mirrorOpenClawConfig(o.openclawConfig);a.copied?e.logger.info?.(`[beeos-claw] mirrored openclaw config to ${a.destinationPath}`):e.logger.debug?.(`[beeos-claw] openclaw config mirror skipped: ${a.reason}`)}}const plugin={id:"beeos-claw",name:"beeos-claw",description:"BeeOS platform bridge plugin for OpenClaw. Provides file upload/download, ACP bridge, and observability.",version:PLUGIN_VERSION,register(e){if(e.registrationMode&&"full"!==e.registrationMode)return void e.logger.debug?.(`[beeos-claw] Skipping registration (mode=${e.registrationMode})`);const o=initializePlugin(e);if(!o)return;const a={current:null};registerUploadTools(e,o,a),registerServices(e,o,a),e.logger.info?.("[beeos-claw] Plugin registered successfully")}};export default plugin;
@@ -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",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;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){if(!(t.includes("[")||t.includes("HEARTBEAT_OK")||t.includes("User Message From")||UNTRUSTED_METADATA_BLOCK_RE.test(t.trim())))return t;if(UNTRUSTED_METADATA_BLOCK_RE.test(t.trim()))return"";const e=t.split(/\r?\n/),r=[];let n=!1;for(const t of e){const e=stripMetadataPrefixesFromLine(t);"HEARTBEAT_OK"!==e.line.trim()?e.changed&&(n=!0,!e.line.trim())||r.push(e.line):n=!0}return n?r.join("\n").replace(/^\n+/,"").replace(/\n+$/,""):t}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;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){if(!(t.includes("[")||t.includes("HEARTBEAT_OK")||t.includes("User Message From")||UNTRUSTED_METADATA_BLOCK_RE.test(t.trim())))return t;if(UNTRUSTED_METADATA_BLOCK_RE.test(t.trim()))return"";const e=t.split(/\r?\n/),r=[];let n=!1;for(const t of e){const e=stripMetadataPrefixesFromLine(t);HEARTBEAT_OK_LINE_RE.test(e.line.trim())?n=!0:e.changed&&(n=!0,!e.line.trim())||r.push(e.line)}return n?r.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)}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 +1 @@
1
- import{Centrifuge}from"centrifuge";import WebSocket from"ws";export class MessageSDK{config;client=null;personalSub=null;principalId="";handlers=new Map;connectLock=null;_resubscribeTimer=null;_resubscribeAttempts=0;static MAX_RESUBSCRIBE_ATTEMPTS=5;logger;constructor(e,s){this.config=e,this.logger=s}async getToken(e,s,t){const i={principal_id:e};return s&&(i.claims=s),t&&(i.ttl_seconds=t),this.restRequest("POST","/api/v1/tokens",i)}async send(e,s,t){await this.restRequest("POST","/api/v1/messages/send",{target_id:e,message_type:s,payload:t})}async isOnline(e){return(await this.restRequest("GET",`/api/v1/connections/${encodeURIComponent(e)}/online`)).online}async registerWebhook(e,s,t){const i={url:e,events:s};return t&&(i.secret=t),this.restRequest("POST","/api/v1/webhooks",i)}async removeWebhook(e){await this.restRequest("DELETE",`/api/v1/webhooks/${encodeURIComponent(e)}`)}async connect(e,s){let t;this.connectLock&&await this.connectLock,this.connectLock=new Promise(e=>{t=e});try{await this._doConnect(e,s)}finally{this.connectLock=null,t()}}async _doConnect(e,s){this.client&&(this.logger.info?.("[message-sdk] Disconnecting previous client before reconnect"),await this.disconnect()),this.principalId=e;const t=s?.tokenProvider??(e=>this.getToken(e)),i=await t(e),r=s?.centrifugoUrl||this.config.centrifugoUrl||i.centrifugo_url;if(!r)throw new Error("No Centrifugo URL available");const n=`personal:${e}`,o=Array.isArray(i.channels)&&i.channels.includes(n);this.logger.info?.(`[message-sdk] Connecting as principal=${e} url=${r} serverSideSub=${o}`);this.client=new Centrifuge(r,{token:i.token,getToken:async()=>(await t(e)).token,websocket:WebSocket}),this.client.on("connecting",e=>{this.logger.info?.(`[message-sdk] Connecting: code=${e.code} reason=${e.reason}`)}),this.client.on("connected",e=>{this.logger.info?.(`[message-sdk] Connected (client=${e.client})`)}),this.client.on("disconnected",e=>{this.logger.warn?.(`[message-sdk] Disconnected: code=${e.code} reason=${e.reason}`)}),this.client.on("error",e=>{this.logger.error?.("[message-sdk] Error:",e.error)}),o&&(this.client.on("subscribed",e=>{e.channel===n&&this.logger.info?.(`[message-sdk] Server-sub subscribed: channel=${n} recoverable=${e.recoverable} recovered=${e.recovered}`)}),this.client.on("subscribing",e=>{e.channel===n&&this.logger.info?.(`[message-sdk] Server-sub subscribing: channel=${n}`)}),this.client.on("unsubscribed",e=>{e.channel===n&&this.logger.warn?.(`[message-sdk] Server-sub unsubscribed: channel=${n}`)}),this.client.on("publication",e=>{e.channel===n&&this.dispatch(e.data).catch(e=>{this.logger.error?.("[message-sdk] dispatch error:",e)})})),this.client.connect(),o||(this.personalSub=this.client.newSubscription(n),this.personalSub.on("subscribing",e=>{this.logger.info?.(`[message-sdk] Subscription subscribing: code=${e.code} reason=${e.reason} channel=${n}`)}),this.personalSub.on("subscribed",e=>{this._resubscribeAttempts=0,this.logger.info?.(`[message-sdk] Subscription subscribed: channel=${n} recoverable=${e.recoverable} recovered=${e.recovered}`)}),this.personalSub.on("unsubscribed",e=>{this.logger.warn?.(`[message-sdk] Subscription unsubscribed: code=${e.code} reason=${e.reason} channel=${n}`),this._scheduleResubscribe(n,e.code)}),this.personalSub.on("error",e=>{this.logger.error?.(`[message-sdk] Subscription error: type=${e.type} channel=${n}`,e.error)}),this.personalSub.on("publication",e=>{this.dispatch(e.data).catch(e=>{this.logger.error?.("[message-sdk] dispatch error:",e)})}),this.personalSub.subscribe())}async disconnect(){this._resubscribeTimer&&(clearTimeout(this._resubscribeTimer),this._resubscribeTimer=null),this._resubscribeAttempts=0,this.personalSub&&(this.personalSub.unsubscribe(),this.personalSub=null),this.client?.disconnect(),this.client=null}onMessage(e,s){this.handlers.set(e,s)}async joinGroup(e,s){if(!this.client)throw new Error("Not connected");const t=this.client.newSubscription(`group:${e}`);return t.on("publication",t=>{s(t.data).catch(s=>{this.logger.error?.(`[message-sdk] group handler error (${e}):`,s)})}),t.subscribe(),t}async publishToGroup(e,s){if(!this.client)throw new Error("Not connected");await this.client.publish(`group:${e}`,{from:this.principalId,content:s,timestamp:Date.now()})}get isConnected(){return"connected"===this.client?.state}get currentPrincipalId(){return this.principalId}_scheduleResubscribe(e,s){if(0===s)return;if(this._resubscribeAttempts>=MessageSDK.MAX_RESUBSCRIBE_ATTEMPTS)return void this.logger.error?.(`[message-sdk] Resubscribe exhausted after ${this._resubscribeAttempts} attempts, channel=${e}`);this._resubscribeTimer&&clearTimeout(this._resubscribeTimer);const t=Math.min(1e3*Math.pow(2,this._resubscribeAttempts),3e4);this._resubscribeAttempts++,this.logger.info?.(`[message-sdk] Scheduling resubscribe in ${t}ms (attempt ${this._resubscribeAttempts}/${MessageSDK.MAX_RESUBSCRIBE_ATTEMPTS}) channel=${e}`),this._resubscribeTimer=setTimeout(()=>{this._resubscribeTimer=null,this.personalSub&&this.client&&"unsubscribed"===this.personalSub.state&&(this.logger.info?.(`[message-sdk] Attempting resubscribe channel=${e}`),this.personalSub.subscribe())},t)}async dispatch(e){const s=this.handlers.get(e.type);s?await s(e):this.logger.debug?.(`[message-sdk] No handler for type=${e.type}`)}async restRequest(e,s,t){if(!this.config.serviceUrl)throw new Error("Message Service REST API requires serviceUrl in config");const i=`${this.config.serviceUrl}${s}`,r={},n={method:e,headers:r};void 0!==t&&(r["Content-Type"]="application/json",n.body=JSON.stringify(t));const o=await fetch(i,n);if(!o.ok){const t=await o.text().catch(()=>"");throw new Error(`Message Service ${e} ${s} returned ${o.status}: ${t}`)}if(204!==o.status)return await o.json()}}
1
+ import{Centrifuge}from"centrifuge";import WebSocket from"ws";export class MessageSDK{config;client=null;personalSub=null;principalId="";handlers=new Map;connectLock=null;_resubscribeTimer=null;_resubscribeAttempts=0;static MAX_RESUBSCRIBE_ATTEMPTS=5;_reconnectCount=0;_lastDisconnectTs=0;_tokenRefreshCount=0;logger;constructor(e,s){this.config=e,this.logger=s}async getToken(e,s,t){const n={principal_id:e};return s&&(n.claims=s),t&&(n.ttl_seconds=t),this.restRequest("POST","/api/v1/tokens",n)}async send(e,s,t){await this.restRequest("POST","/api/v1/messages/send",{target_id:e,message_type:s,payload:t})}async isOnline(e){return(await this.restRequest("GET",`/api/v1/connections/${encodeURIComponent(e)}/online`)).online}async registerWebhook(e,s,t){const n={url:e,events:s};return t&&(n.secret=t),this.restRequest("POST","/api/v1/webhooks",n)}async removeWebhook(e){await this.restRequest("DELETE",`/api/v1/webhooks/${encodeURIComponent(e)}`)}async connect(e,s){let t;this.connectLock&&await this.connectLock,this.connectLock=new Promise(e=>{t=e});try{await this._doConnect(e,s)}finally{this.connectLock=null,t()}}async _doConnect(e,s){this.client&&(this.logger.info?.("[message-sdk] Disconnecting previous client before reconnect"),await this.disconnect()),this.principalId=e,this._reconnectCount=0,this._lastDisconnectTs=0,this._tokenRefreshCount=0;const t=s?.tokenProvider??(e=>this.getToken(e)),n=await t(e),i=s?.centrifugoUrl||this.config.centrifugoUrl||n.centrifugo_url;if(!i)throw new Error("No Centrifugo URL available");const r=`personal:${e}`,o=Array.isArray(n.channels)&&n.channels.includes(r);this.logger.info?.(`[message-sdk] Connecting as principal=${e} url=${i} serverSideSub=${o}`);this.client=new Centrifuge(i,{token:n.token,getToken:async()=>{this._tokenRefreshCount++,this.logger.info?.(`[message-sdk] Token refresh #${this._tokenRefreshCount} for principal=${e}`);return(await t(e)).token},websocket:WebSocket}),this.client.on("connecting",e=>{this.logger.info?.(`[message-sdk] Connecting: code=${e.code} reason=${e.reason}`)}),this.client.on("connected",e=>{if(this._reconnectCount>0){const s=this._lastDisconnectTs>0?Date.now()-this._lastDisconnectTs:0;this.logger.info?.(`[message-sdk] Reconnected (client=${e.client}) reconnects=${this._reconnectCount} downtime=${s}ms`)}else this.logger.info?.(`[message-sdk] Connected (client=${e.client})`)}),this.client.on("disconnected",e=>{this._reconnectCount++,this._lastDisconnectTs=Date.now(),this.logger.warn?.(`[message-sdk] Disconnected: code=${e.code} reason=${e.reason} totalDisconnects=${this._reconnectCount}`)}),this.client.on("error",e=>{this.logger.error?.("[message-sdk] Error:",e.error)}),o&&(this.client.on("subscribed",e=>{e.channel===r&&this.logger.info?.(`[message-sdk] Server-sub subscribed: channel=${r} recoverable=${e.recoverable} recovered=${e.recovered}`)}),this.client.on("subscribing",e=>{e.channel===r&&this.logger.info?.(`[message-sdk] Server-sub subscribing: channel=${r}`)}),this.client.on("unsubscribed",e=>{e.channel===r&&this.logger.warn?.(`[message-sdk] Server-sub unsubscribed: channel=${r}`)}),this.client.on("publication",e=>{e.channel===r&&this.dispatch(e.data).catch(e=>{this.logger.error?.("[message-sdk] dispatch error:",e)})})),this.client.connect(),o||(this.personalSub=this.client.newSubscription(r),this.personalSub.on("subscribing",e=>{this.logger.info?.(`[message-sdk] Subscription subscribing: code=${e.code} reason=${e.reason} channel=${r}`)}),this.personalSub.on("subscribed",e=>{this._resubscribeAttempts=0,this.logger.info?.(`[message-sdk] Subscription subscribed: channel=${r} recoverable=${e.recoverable} recovered=${e.recovered}`)}),this.personalSub.on("unsubscribed",e=>{this.logger.warn?.(`[message-sdk] Subscription unsubscribed: code=${e.code} reason=${e.reason} channel=${r}`),this._scheduleResubscribe(r,e.code)}),this.personalSub.on("error",e=>{this.logger.error?.(`[message-sdk] Subscription error: type=${e.type} channel=${r}`,e.error)}),this.personalSub.on("publication",e=>{this.dispatch(e.data).catch(e=>{this.logger.error?.("[message-sdk] dispatch error:",e)})}),this.personalSub.subscribe())}async disconnect(){this._resubscribeTimer&&(clearTimeout(this._resubscribeTimer),this._resubscribeTimer=null),this._resubscribeAttempts=0,this.personalSub&&(this.personalSub.unsubscribe(),this.personalSub=null),this.client?.disconnect(),this.client=null}onMessage(e,s){this.handlers.set(e,s)}async joinGroup(e,s){if(!this.client)throw new Error("Not connected");const t=this.client.newSubscription(`group:${e}`);return t.on("publication",t=>{s(t.data).catch(s=>{this.logger.error?.(`[message-sdk] group handler error (${e}):`,s)})}),t.subscribe(),t}async publishToGroup(e,s){if(!this.client)throw new Error("Not connected");await this.client.publish(`group:${e}`,{from:this.principalId,content:s,timestamp:Date.now()})}async sendToChannel(e,s,t){const n=`ch:${e}`,i={type:s,payload:t,channel_id:e,metadata:{from:this.principalId,channel_id:e,timestamp:String(Date.now())}};if("connected"===this.client?.state)return await this.client.publish(n,i),void this.logger.debug?.(`[message-sdk] Published type=${s} to ${n}`);if(this.config.serviceUrl)return this.logger.warn?.(`[message-sdk] Centrifugo not connected, falling back to REST for ch:${e}`),void await this.restRequest("POST",`/api/v1/channels/${encodeURIComponent(e)}/messages`,{sender_id:this.principalId,type:s,payload:t});throw new Error(`Cannot send to channel ${e}: no Centrifugo connection and no serviceUrl`)}async sendToPersonal(e,s,t){if(!this.client)throw new Error("Not connected");const n=`personal:${e}`,i={type:s,payload:t,metadata:{from:this.principalId,timestamp:String(Date.now())}};try{await this.client.publish(n,i),this.logger.debug?.(`[message-sdk] Published type=${s} to ${n}`)}catch(e){throw this.logger.warn?.(`[message-sdk] Publish failed type=${s} channel=${n}: ${e instanceof Error?e.message:String(e)}`),e}}get isConnected(){return"connected"===this.client?.state}get currentPrincipalId(){return this.principalId}_scheduleResubscribe(e,s){if(0===s)return;if(this._resubscribeAttempts>=MessageSDK.MAX_RESUBSCRIBE_ATTEMPTS)return void this.logger.error?.(`[message-sdk] Resubscribe exhausted after ${this._resubscribeAttempts} attempts, channel=${e}`);this._resubscribeTimer&&clearTimeout(this._resubscribeTimer);const t=Math.min(1e3*Math.pow(2,this._resubscribeAttempts),3e4);this._resubscribeAttempts++,this.logger.info?.(`[message-sdk] Scheduling resubscribe in ${t}ms (attempt ${this._resubscribeAttempts}/${MessageSDK.MAX_RESUBSCRIBE_ATTEMPTS}) channel=${e}`),this._resubscribeTimer=setTimeout(()=>{this._resubscribeTimer=null,this.personalSub&&this.client&&"unsubscribed"===this.personalSub.state&&(this.logger.info?.(`[message-sdk] Attempting resubscribe channel=${e}`),this.personalSub.subscribe())},t)}async dispatch(e){const s=this.handlers.get(e.type);s?await s(e):this.logger.debug?.(`[message-sdk] No handler for type=${e.type}`)}async restRequest(e,s,t){if(!this.config.serviceUrl)throw new Error("Message Service REST API requires serviceUrl in config");const n=`${this.config.serviceUrl}${s}`,i={},r={method:e,headers:i};void 0!==t&&(i["Content-Type"]="application/json",r.body=JSON.stringify(t));const o=await fetch(n,r);if(!o.ok){const t=await o.text().catch(()=>"");throw new Error(`Message Service ${e} ${s} returned ${o.status}: ${t}`)}if(204!==o.status)return await o.json()}}
@@ -1 +1 @@
1
- export function generateActionTools(e,t,o,r,s){const c=e.list();let n=0;for(const e of c)for(const s of e.itemActions){if("rpc"!==s.type)continue;const c=`${e.domain}_${s.id}`,i=s.description??`${s.id} a ${e.domain} item`;t.registerTool({name:c,description:i,parameters:{type:"object",required:["params"],properties:{params:{type:"object",description:`Parameters for ${s.rpc}. Pass the exact object to send to the RPC.`}}},async execute(t,c){const n=c,i=n.params??n;try{const t=await o(s.rpc,i);return await r.render(e),{success:!0,result:t}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}),n++}s.info?.(`[action-tool-gen] Registered ${n} action tools from ${c.length} descriptor(s)`)}
1
+ export function generateActionTools(e,t,o,r,s){const c=e.list();let n=0;for(const e of c)for(const s of e.itemActions){if("rpc"!==s.type)continue;const c=`${e.domain}_${s.id}`,i=s.description??`${s.id} a ${e.domain} item`;t.registerTool({name:c,description:i,parameters:{type:"object",required:["params"],properties:{params:{type:"object",description:`Parameters for ${s.rpc}. Pass the exact object to send to the RPC.`}}},async execute(t,c,n){const i=c,a=i.params??i;try{const t=await o(s.rpc,a);return await r.render(e),{success:!0,result:t}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}),n++}s.info?.(`[action-tool-gen] Registered ${n} action tools from ${c.length} descriptor(s)`)}
@@ -1 +1 @@
1
- import{constants}from"node:fs";import{access,readFile,stat}from"node:fs/promises";import{basename,extname}from"node:path";import{agentFetch}from"../agent-auth.js";export const BEEOS_UPLOAD_TOOL_NAME="beeos_upload_file";export const BEEOS_UPLOAD_TOOL_DESCRIPTION="Upload 1-5 local files from this machine to the user via the BeeOS platform. If the call succeeds, the files are already delivered to the user — do not use any other tool to send them again. Any file type is accepted: text, images, documents, PDFs, archives, binaries.";export const BEEOS_UPLOAD_TOOL_SCHEMA={title:"BeeOS file upload",type:"object",description:BEEOS_UPLOAD_TOOL_DESCRIPTION,additionalProperties:!1,required:["paths"],properties:{paths:{type:"array",minItems:1,maxItems:5,description:"Local filesystem paths (1-5). Absolute or workspace-relative.",items:{type:"string",minLength:1,description:"Single local filesystem path"}}}};const MAX_PATHS=5,REQUEST_TIMEOUT_MS=12e4,MAX_CONCURRENCY=3;async function runWithConcurrency(e,t){const r=new Array(e.length);let a=0;async function n(){for(;a<e.length;){const t=a++;r[t]=await e[t]()}}const s=[];for(let r=0;r<Math.min(t,e.length);r++)s.push(n());return await Promise.all(s),r}async function validateFiles(e){return Promise.all(e.map(async e=>{try{await access(e,constants.R_OK);return(await stat(e)).isFile()?{path:e,ok:!0}:{path:e,ok:!1,error:"not a regular file"}}catch(t){const r=t.code;let a;return a="ENOENT"===r?"file not found":"ENOTDIR"===r?"path component is not a directory":"EACCES"===r?"permission denied":t instanceof Error?t.message:String(t),{path:e,ok:!1,error:a}}}))}export async function executeUpload(e,t,r){const a=parseParams(e);if(!a.ok)return errorResult(a.error);if(!t.agentGatewayUrl)return errorResult("agentGatewayUrl not configured — file upload requires Agent Gateway access");if(!r)return errorResult("agent key pair not available — cannot sign upload requests");const n=`${t.agentGatewayUrl}/api/v1/agent/files`,s=a.paths,i=(await validateFiles(s)).find(e=>!e.ok);if(i)return errorResult(`${i.path}: ${i.error}`);const o=[],l=s.map(e=>async()=>{try{return await uploadSingleFile(e,n,r)}catch(t){return o.push(`${e}: ${t instanceof Error?t.message:String(t)}`),null}}),c=(await runWithConcurrency(l,3)).filter(e=>null!==e);if(0===c.length)return errorResult(`All uploads failed: ${o.join("; ")}`);const p=c.map(e=>({uri:`beeos-file://${e.fileId}`,name:e.fileName,mimeType:e.mimeType,fileId:e.fileId})),u=c.length===s.length?`Uploaded ${c.length} file(s): ${p.map(e=>e.name).join(", ")}`:`Uploaded ${c.length}/${s.length} file(s): ${p.map(e=>e.name).join(", ")}. Failed: ${o.join("; ")}`,m={ok:!0,files:p};return{...m,content:[{type:"text",text:u},...p.map(e=>({type:"resource_link",uri:e.uri,name:e.name,mimeType:e.mimeType}))],output:m,result:m,details:m,isError:!1}}async function uploadSingleFile(e,t,r){await access(e,constants.R_OK);if(!(await stat(e)).isFile())throw new Error("not a regular file");const a=basename(e),n=inferMimeType(a),s=await readFile(e),i=new AbortController,o=setTimeout(()=>i.abort(),12e4);"object"==typeof o&&"unref"in o&&o.unref();try{const e=await agentFetch(t+"/presign",r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileName:a,mimeType:n}),signal:i.signal});if(!e.ok){const t=await e.text().catch(()=>e.statusText);throw new Error(`presign ${e.status}: ${t}`)}const o=await e.json(),l=await fetch(o.uploadUrl,{method:"PUT",headers:{"Content-Type":n},body:new Blob([s],{type:n}),signal:i.signal});if(!l.ok)throw new Error(`S3 PUT failed: ${l.status}`);const c=await agentFetch(t+"/confirm",r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileId:o.fileId}),signal:i.signal});if(!c.ok){const e=await c.text().catch(()=>c.statusText);throw new Error(`confirm ${c.status}: ${e}`)}const p=await c.json();return{fileId:p.fileId,downloadUrl:p.downloadUrl,fileName:p.fileName||a,mimeType:p.mimeType||n,size:p.size||s.byteLength}}finally{clearTimeout(o)}}function parseParams(e){if(!e||"object"!=typeof e)return{ok:!1,error:"params must be an object"};const t=e;if(Object.keys(t).filter(e=>"paths"!==e).length>0)return{ok:!1,error:"only paths is allowed"};if(!Array.isArray(t.paths))return{ok:!1,error:"paths must be an array"};if(t.paths.length<1)return{ok:!1,error:"paths must contain at least 1 item"};if(t.paths.length>5)return{ok:!1,error:"paths must contain no more than 5 items"};const r=[];for(let e=0;e<t.paths.length;e++){const a=t.paths[e];if("string"!=typeof a||""===a.trim())return{ok:!1,error:`paths[${e}] must be a non-empty string`};r.push(a.trim())}return{ok:!0,paths:r}}function errorResult(e){const t={ok:!1,error:e};return{...t,content:[{type:"text",text:e}],output:t,result:t,details:t,isError:!0}}function inferMimeType(e){switch(extname(e).toLowerCase()){case".txt":return"text/plain";case".md":return"text/markdown";case".json":return"application/json";case".html":return"text/html";case".css":return"text/css";case".js":case".mjs":case".cjs":return"text/javascript";case".ts":return"text/x.typescript";case".tsx":case".jsx":return"text/jsx";case".xml":return"application/xml";case".yaml":case".yml":return"application/yaml";case".toml":return"application/toml";case".pdf":return"application/pdf";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";case".csv":return"text/csv";case".zip":return"application/zip";case".tar":return"application/x-tar";case".gz":case".tgz":return"application/gzip";default:return"application/octet-stream"}}
1
+ import{constants}from"node:fs";import{access,readFile,stat}from"node:fs/promises";import{basename,extname}from"node:path";import{agentFetch}from"../agent-auth.js";export const BEEOS_UPLOAD_TOOL_NAME="beeos_upload_file";export const BEEOS_UPLOAD_TOOL_DESCRIPTION="Upload 1-5 local files from this machine to the user via the BeeOS platform. If the call succeeds, the files are already delivered to the user — do not use any other tool to send them again. Any file type is accepted: text, images, documents, PDFs, archives, binaries.";export const BEEOS_UPLOAD_TOOL_SCHEMA={title:"BeeOS file upload",type:"object",description:BEEOS_UPLOAD_TOOL_DESCRIPTION,additionalProperties:!1,required:["paths"],properties:{paths:{type:"array",minItems:1,maxItems:5,description:"Local filesystem paths (1-5). Absolute or workspace-relative.",items:{type:"string",minLength:1,description:"Single local filesystem path"}}}};const MAX_PATHS=5,REQUEST_TIMEOUT_MS=12e4,MAX_CONCURRENCY=3;async function runWithConcurrency(e,t){const r=new Array(e.length);let a=0;async function n(){for(;a<e.length;){const t=a++;r[t]=await e[t]()}}const s=[];for(let r=0;r<Math.min(t,e.length);r++)s.push(n());return await Promise.all(s),r}async function validateFiles(e){return Promise.all(e.map(async e=>{try{await access(e,constants.R_OK);return(await stat(e)).isFile()?{path:e,ok:!0}:{path:e,ok:!1,error:"not a regular file"}}catch(t){const r=t.code;let a;return a="ENOENT"===r?"file not found":"ENOTDIR"===r?"path component is not a directory":"EACCES"===r?"permission denied":t instanceof Error?t.message:String(t),{path:e,ok:!1,error:a}}}))}export async function executeUpload(e,t,r,a){const n=parseParams(e);if(!n.ok)return errorResult(n.error);if(!t.agentGatewayUrl)return errorResult("agentGatewayUrl not configured — file upload requires Agent Gateway access");if(!r)return errorResult("agent key pair not available — cannot sign upload requests");const s=`${t.agentGatewayUrl}/api/v1/agent/files`,i=n.paths,o=(await validateFiles(i)).find(e=>!e.ok);if(o)return errorResult(`${o.path}: ${o.error}`);const l=[],c=i.map(e=>async()=>{try{return await uploadSingleFile(e,s,r,a)}catch(t){if(a?.aborted)throw t;return l.push(`${e}: ${t instanceof Error?t.message:String(t)}`),null}}),p=(await runWithConcurrency(c,3)).filter(e=>null!==e);if(0===p.length)return errorResult(`All uploads failed: ${l.join("; ")}`);const u=p.map(e=>({uri:`beeos-file://${e.fileId}`,name:e.fileName,mimeType:e.mimeType,fileId:e.fileId})),m=p.length===i.length?`Uploaded ${p.length} file(s): ${u.map(e=>e.name).join(", ")}`:`Uploaded ${p.length}/${i.length} file(s): ${u.map(e=>e.name).join(", ")}. Failed: ${l.join("; ")}`,f={ok:!0,files:u};return{...f,content:[{type:"text",text:m},...u.map(e=>({type:"resource_link",uri:e.uri,name:e.name,mimeType:e.mimeType}))],output:f,result:f,details:f,isError:!1}}async function uploadSingleFile(e,t,r,a){await access(e,constants.R_OK);if(!(await stat(e)).isFile())throw new Error("not a regular file");const n=basename(e),s=inferMimeType(n),i=await readFile(e),o=AbortSignal.timeout(12e4),l=a?AbortSignal.any([a,o]):o;try{const e=await agentFetch(t+"/presign",r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileName:n,mimeType:s}),signal:l});if(!e.ok){const t=await e.text().catch(()=>e.statusText);throw new Error(`presign ${e.status}: ${t}`)}const a=await e.json(),o=await fetch(a.uploadUrl,{method:"PUT",headers:{"Content-Type":s},body:new Blob([i],{type:s}),signal:l});if(!o.ok)throw new Error(`S3 PUT failed: ${o.status}`);const c=await agentFetch(t+"/confirm",r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileId:a.fileId}),signal:l});if(!c.ok){const e=await c.text().catch(()=>c.statusText);throw new Error(`confirm ${c.status}: ${e}`)}const p=await c.json();return{fileId:p.fileId,downloadUrl:p.downloadUrl,fileName:p.fileName||n,mimeType:p.mimeType||s,size:p.size||i.byteLength}}finally{}}function parseParams(e){if(!e||"object"!=typeof e)return{ok:!1,error:"params must be an object"};const t=e;if(Object.keys(t).filter(e=>"paths"!==e).length>0)return{ok:!1,error:"only paths is allowed"};if(!Array.isArray(t.paths))return{ok:!1,error:"paths must be an array"};if(t.paths.length<1)return{ok:!1,error:"paths must contain at least 1 item"};if(t.paths.length>5)return{ok:!1,error:"paths must contain no more than 5 items"};const r=[];for(let e=0;e<t.paths.length;e++){const a=t.paths[e];if("string"!=typeof a||""===a.trim())return{ok:!1,error:`paths[${e}] must be a non-empty string`};r.push(a.trim())}return{ok:!0,paths:r}}function errorResult(e){const t={ok:!1,error:e};return{...t,content:[{type:"text",text:e}],output:t,result:t,details:t,isError:!0}}function inferMimeType(e){switch(extname(e).toLowerCase()){case".txt":return"text/plain";case".md":return"text/markdown";case".json":return"application/json";case".html":return"text/html";case".css":return"text/css";case".js":case".mjs":case".cjs":return"text/javascript";case".ts":return"text/x.typescript";case".tsx":case".jsx":return"text/jsx";case".xml":return"application/xml";case".yaml":case".yml":return"application/yaml";case".toml":return"application/toml";case".pdf":return"application/pdf";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";case".csv":return"text/csv";case".zip":return"application/zip";case".tar":return"application/x-tar";case".gz":case".tgz":return"application/gzip";default:return"application/octet-stream"}}
package/dist/utils/mq.js CHANGED
@@ -1 +1 @@
1
- export class MessageQueue{messages=[];waiters=[];_closed=!1;get closed(){return this._closed}push(s){if(this._closed)return;this.messages.push(s);const e=this.waiters;this.waiters=[],e.forEach(s=>s())}async read(s){return this._closed?null:s<this.messages.length?this.messages.slice(s):new Promise(e=>{this.waiters.push(()=>{this._closed?e(null):e(this.messages.slice(s))})})}close(){this._closed=!0;const s=this.waiters;this.waiters=[],s.forEach(s=>s())}}
1
+ export class MessageQueue{messages=[];waiters=[];_closed=!1;get closed(){return this._closed}push(s){if(this._closed)return;this.messages.push(s);const e=this.waiters;this.waiters=[],e.forEach(s=>s())}async read(s){return this._closed?null:s<this.messages.length?this.messages.slice(s):new Promise(e=>{this.waiters.push(()=>{this._closed?e(null):e(this.messages.slice(s))})})}peek(s){return this._closed||s>=this.messages.length?[]:this.messages.slice(s)}close(){this._closed=!0;const s=this.waiters;this.waiters=[],s.forEach(s=>s())}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "beeos-claw",
3
- "version": "0.2.9",
3
+ "version": "0.2.11",
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>",
@@ -1 +0,0 @@
1
- export function createA2ATaskCancelHandler(a,t){return async e=>{let n=e.payload;"a2a_task_cancel"===n?.type&&n?.payload&&"object"==typeof n.payload&&(n=n.payload);const o="string"==typeof n?.task_id?n.task_id:void 0,s="string"==typeof n?.reason?n.reason:"unknown";if(!o)return{ok:!1,error:"missing task_id"};const r=t(o),c="timeout"===s?`A2A task ${o} was terminated — the caller's timeout expired.`:`A2A task ${o} was cancelled by the caller.`;try{await a(`[A2A Task Cancelled]\n\n${c}\n\nYou may stop working on this task.`,void 0,void 0,{kind:"internal_system",sourceTool:"a2a_task_cancel"})}catch(a){}return{ok:!0,cancelled:r}}}
@@ -1 +0,0 @@
1
- import{a2aFetch}from"./tools.js";import{dispatchA2ATask}from"./task-executor.js";export async function pollPendingTasks(a,e,t){let s=0;try{const o=await a2aFetch(a,"/api/v1/a2a/tasks/pending");if(!o.ok)return a.logger.warn?.("[beeos-claw] Failed to poll pending tasks: %d %s",o.status,await o.text()),0;const n=await o.json(),i=Array.isArray(n.data)?n.data:[];if(0===i.length)return a.logger.debug?.("[beeos-claw] No pending A2A tasks found on startup"),0;a.logger.info?.("[beeos-claw] Found %d pending A2A tasks to process",i.length);for(const o of i)try{await dispatchA2ATask(a,e,t,o.id,o.message,o.caller_principal_id,o.files),s++,a.logger.info?.("[beeos-claw] Dispatched pending task %s",o.id)}catch(e){a.logger.error?.("[beeos-claw] Failed to dispatch pending task %s:",o.id,e)}}catch(e){a.logger.warn?.("[beeos-claw] Pending task poll failed:",e)}return s}
@@ -1 +0,0 @@
1
- function extractResultText(t){if(!t)return"";if("string"==typeof t)return t;if("object"==typeof t){const e=t;if("string"==typeof e.text)return e.text;if("object"==typeof e.data&&e.data)try{return JSON.stringify(e.data,null,2)}catch{}if("string"==typeof e.result)return e.result;const a=Object.keys(e);if(1===a.length&&"status"===a[0])return"";try{return JSON.stringify(e,null,2)}catch{}}return String(t)}export function createA2AResultHandler(t,e,a){return async n=>{let s=n.payload;"a2a_result"===s?.type&&s?.payload&&"object"==typeof s.payload&&(s=s.payload);const r="string"==typeof s?.task_id?s.task_id:void 0,i="string"==typeof s?.status?s.status:void 0,o=s?.result,l="string"==typeof s?.context_id?s.context_id:void 0,u="string"==typeof s?.target_name?s.target_name:void 0;if(!r)return{ok:!1,error:"missing task_id"};let c,d,y=e?.resolveSessionKey(r);if(!y&&l?.startsWith("session:")&&(y=l.slice(8)),c="completed"===i?`A2A task ${r} completed successfully.`:"failed"===i?`A2A task ${r} failed.`:"cancelled"===i?`A2A task ${r} was cancelled.`:"timeout"===i?`A2A task ${r} timed out — the target agent did not complete in time.`:`A2A task ${r} finished with status: ${i??"unknown"}.`,a){a({type:"a2a_result_notification",taskId:r,callerName:u??r,message:c,targetSessionKey:y})}try{d="string"==typeof o?o:JSON.stringify(o,null,2)}catch{d=String(o)}const f=extractResultText(o),p=`[A2A Result]\n\n${c}\n\nResult:\n${f||d}${f.length>20?"\n\n[INSTRUCTION] The task returned data. You MUST call render_ui to display this data visually on the canvas as a card or table. Do NOT repeat the data in chat text — put it all in render_ui. Keep your chat reply to one brief sentence.":""}`;try{await t(p,void 0,y,{kind:"internal_system",sourceTool:"a2a_result"})}catch(t){}return{ok:!0}}}
@@ -1 +0,0 @@
1
- import{a2aFetch}from"./tools.js";export function extractTextResult(t){if("string"==typeof t)return t;if(t&&"object"==typeof t){const e=t;if("string"==typeof e.content)return e.content;if("string"==typeof e.text)return e.text;if("string"==typeof e.message)return e.message}try{return JSON.stringify(t)}catch{return String(t)}}export async function completeA2ATask(t,e,a,s){await a2aFetch(t,`/api/v1/a2a/tasks/${encodeURIComponent(e)}/complete`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({result:s?"":a,error:s})})}export async function updateTaskStatus(t,e,a,s){try{const n=await a2aFetch(t,`/api/v1/a2a/tasks/${encodeURIComponent(e)}/status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:a,message:s})});n.ok||t.logger.warn?.("[beeos-claw] updateTaskStatus %s -> %s failed: %d",e,a,n.status)}catch(s){t.logger.warn?.("[beeos-claw] updateTaskStatus %s -> %s error: %s",e,a,s instanceof Error?s.message:String(s))}}export async function dispatchA2ATask(t,e,a,s,n,o,r){try{await updateTaskStatus(t,s,"working");const i=`[A2A Task #${s}${o?` from ${o}`:""}]\n\n${n}`,c=await e(i,r),p=c?.runId;p?a(p,s,(e,a)=>completeA2ATask(t,s,e,a)):t.logger.warn?.("[beeos-claw] agentSend returned no runId for A2A task %s, task will rely on manual completion or timeout",s)}catch(e){const a=e instanceof Error?e.message:String(e);t.logger.warn?.("[beeos-claw] Failed to dispatch A2A task %s: %s",s,a);try{await completeA2ATask(t,s,"",a)}catch{}}}
@@ -1 +0,0 @@
1
- const MAX_HANDLES=200;export class TaskHandleRegistry{handles=new Map;counter=0;create(e,t,s,n){const r=`bth_${(++this.counter).toString(36)}`;return this.handles.set(r,{taskId:e,targetAgentId:t,contextId:s,gatewaySessionKey:n,createdAt:Date.now()}),this.evict(),r}resolve(e){if(this.handles.has(e))return this.handles.get(e);for(const t of this.handles.values())if(t.taskId===e)return t}resolveTaskId(e){const t=this.resolve(e);return t?.taskId??e}resolveSessionKey(e){const t=this.resolve(e);return t?.gatewaySessionKey}evict(){if(this.handles.size<=200)return;const e=[...this.handles.entries()].sort((e,t)=>e[1].createdAt-t[1].createdAt),t=e.length-200;for(let s=0;s<t;s++)this.handles.delete(e[s][0])}}
@@ -1 +0,0 @@
1
- import{dispatchA2ATask}from"./task-executor.js";export function createA2ATaskHandler(t,e,s,a){return async i=>{const n=i.payload,r="string"==typeof n?.message?n.message:void 0;if(!r)return{ok:!1,error:"missing message"};const o=Array.isArray(n?.files)?n.files:void 0,f="string"==typeof n?.task_id?n.task_id:void 0,l="string"==typeof n?.caller?n.caller:void 0,c="string"==typeof n?.caller_name?n.caller_name:l??"Unknown Agent",d="string"==typeof n?.context_id?n.context_id:void 0,p=Array.isArray(n?.parts)?n.parts:void 0;if(f&&a){const t="a2a_task"===i.type&&d,e=r.length>100?r.slice(0,100)+"...":r;a({type:"a2a_task_notification",taskId:f,callerName:c,message:t?`Continued A2A task from ${c}: ${e}`:`Received A2A task from ${c}: ${e}`})}let A=r;if(p&&p.length>0){const t=[];for(const e of p)if("string"==typeof e.text&&e.text!==r)t.push(e.text);else if(e.file&&"object"==typeof e.file){const s=e.file;"string"==typeof s.url&&t.push(`[File: ${s.name||s.url}]`)}t.length>0&&(A=r+"\n\n"+t.join("\n"))}if(!f||!e||!s){return t(`[A2A Task${f?` #${f}`:""}${l?` from ${l}`:""}]\n\n${A}`,o)}return await dispatchA2ATask(e,t,s,f,A,l,o),{ok:!0,taskId:f,contextId:d}}}
@@ -1 +0,0 @@
1
- export class A2AOrchestrator{pendingA2ARuns=new Map;deps;constructor(e){this.deps=e}trackA2ARun(e,s,t){this.pendingA2ARuns.set(e,{taskId:s,completeFn:t})}cancelA2ARunByTaskId(e){for(const[s,t]of this.pendingA2ARuns)if(t.taskId===e)return this.pendingA2ARuns.delete(s),this.deps.logger.info?.("[a2a-orch] Removed pending A2A run %s for cancelled task %s",s,e),!0;return!1}onRunComplete(e,s){const t=this.pendingA2ARuns.get(e);t&&(this.pendingA2ARuns.delete(e),t.completeFn(s,"").catch(e=>this.deps.logger.warn?.("[a2a-orch] A2A CompleteTask failed for task %s: %s",t.taskId,e)))}onRunFailed(e,s){const t=this.pendingA2ARuns.get(e);t&&(this.pendingA2ARuns.delete(e),t.completeFn("",s).catch(e=>this.deps.logger.warn?.("[a2a-orch] A2A CompleteTask (error) failed for task %s: %s",t.taskId,e)))}emitA2ASystemNotification(e){let s;if(e.targetSessionKey){const t=this.deps.state.findSessionByKey(e.targetSessionKey);s=t?.sessionId,s||this.deps.logger.debug?.("[a2a-orch] emitA2ASystemNotification: targetSessionKey=%s not found, falling back",e.targetSessionKey)}if(!s){const e=this.deps.state.lastActiveSessionId,t=e?this.deps.state.sessions.get(e):void 0;s=t?.sessionId??e}if(!s)return void this.deps.logger.debug?.("[a2a-orch] emitA2ASystemNotification: no active session, dropping");const t={type:e.type,taskId:e.taskId,callerName:e.callerName,taskLink:`/a2a/tasks/${e.taskId}`};this.deps.transport.sendSessionUpdate(s,{sessionUpdate:"system_message_chunk",content:{type:"text",text:e.message},metadata:t})}drainNextDeferredSend(e,s){const t=e.pendingAgentSends?.shift();t&&(e.pendingAgentSends?.length||(e.pendingAgentSends=void 0),s(t.message,t.attachments,e.gatewaySessionKey,t.inputProvenance).catch(e=>this.deps.logger.warn?.("[a2a-orch] Deferred agentSend failed: %s",e)))}destroy(){this.pendingA2ARuns.clear()}}
@@ -1 +0,0 @@
1
- import{describe,it,expect,beforeEach,vi}from"vitest";import{A2AOrchestrator}from"./a2a-orchestrator.js";import{AcpGatewaySessionState}from"./acp-gateway/session-state.js";describe("A2AOrchestrator",()=>{let e,t;const n={info:vi.fn(),warn:vi.fn(),debug:vi.fn()},o={sendSessionUpdate:vi.fn().mockReturnValue(!0),sendResult:vi.fn(),sendAcpError:vi.fn(),sendNotification:vi.fn(),resetSessionUpdateCount:vi.fn()};beforeEach(()=>{t=new AcpGatewaySessionState(n),e=new A2AOrchestrator({state:t,transport:o,logger:n}),vi.clearAllMocks()}),describe("trackA2ARun / onRunComplete",()=>{it("should call completeFn on run completion",async()=>{const t=vi.fn().mockResolvedValue(void 0);e.trackA2ARun("run-1","task-1",t),e.onRunComplete("run-1","Hello, result"),expect(t).toHaveBeenCalledWith("Hello, result","")}),it("should not call completeFn for unknown runId",()=>{const t=vi.fn().mockResolvedValue(void 0);e.trackA2ARun("run-1","task-1",t),e.onRunComplete("unknown-run","text"),expect(t).not.toHaveBeenCalled()})}),describe("onRunFailed",()=>{it("should call completeFn with error",async()=>{const t=vi.fn().mockResolvedValue(void 0);e.trackA2ARun("run-2","task-2",t),e.onRunFailed("run-2","Something went wrong"),expect(t).toHaveBeenCalledWith("","Something went wrong")})}),describe("cancelA2ARunByTaskId",()=>{it("should remove the run and return true",()=>{const t=vi.fn().mockResolvedValue(void 0);e.trackA2ARun("run-3","task-3",t),expect(e.cancelA2ARunByTaskId("task-3")).toBe(!0),e.onRunComplete("run-3","late result"),expect(t).not.toHaveBeenCalled()}),it("should return false for unknown task",()=>{expect(e.cancelA2ARunByTaskId("unknown")).toBe(!1)})}),describe("emitA2ASystemNotification",()=>{it("should send to targeted session",()=>{const n={sessionId:"s1",gatewaySessionKey:"agent:main:s1",agentId:"main",createdAt:Date.now(),chatReplayDedupKeys:new Set};t.sessions.set("s1",n),t.sessionsByGatewayKey.set("agent:main:s1",n),e.emitA2ASystemNotification({type:"a2a_task_notification",taskId:"t1",callerName:"Agent X",message:"New task from Agent X",targetSessionKey:"agent:main:s1"}),expect(o.sendSessionUpdate).toHaveBeenCalledWith("s1",expect.objectContaining({sessionUpdate:"system_message_chunk"}))}),it("should drop when no session available",()=>{e.emitA2ASystemNotification({type:"a2a_task_notification",taskId:"t1",callerName:"Agent X",message:"Dropped"}),expect(o.sendSessionUpdate).not.toHaveBeenCalled()})}),describe("destroy",()=>{it("should clear all pending runs",()=>{e.trackA2ARun("r1","t1",vi.fn().mockResolvedValue(void 0)),e.trackA2ARun("r2","t2",vi.fn().mockResolvedValue(void 0)),e.destroy(),expect(e.cancelA2ARunByTaskId("t1")).toBe(!1),expect(e.cancelA2ARunByTaskId("t2")).toBe(!1)})})});