beeos-claw 0.2.11 → 0.2.13
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{resolveAgentIdFromMentions}from"./mention-resolver.js";async function a2aFetch(e,t,n){const
|
|
1
|
+
import{agentFetch}from"../agent-auth.js";import{resolveAgentIdFromMentions}from"./mention-resolver.js";async function a2aFetch(e,t,n){const a=`${e.agentGatewayUrl}${t}`;return e.agentKeys?agentFetch(a,e.agentKeys,n):fetch(a,n)}export{a2aFetch};export class TaskHandleRegistry{seq=0;handles=new Map;taskIdToHandle=new Map;create(e,t,n,a){const s="bth_"+ ++this.seq;return this.handles.set(s,{taskId:e,agentId:t,contextId:n,sessionKey:a}),this.taskIdToHandle.set(e,s),s}resolveTaskId(e){const t=this.handles.get(e);return t?t.taskId:e}}const defaultRegistry=new TaskHandleRegistry;export function registerA2ATools(e,t,n=defaultRegistry,a,s,r){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,a){const{query:s}=n;try{const e=await a2aFetch(t,`/api/v1/a2a/discover?query=${encodeURIComponent(s)}&limit=20`,{signal:a});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(a?.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:g,contextId:l,timeoutMs:u,taskId:f}=o;const p=a?.(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=s?.(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(),a=n?.data??[],s=c.toLowerCase(),r=a.find(e=>e.name.toLowerCase()===s)??a.find(e=>e.name.toLowerCase().includes(s));if(!r)return{content:JSON.stringify({error:`Could not resolve agent name "${c}". Available agents: ${a.map(e=>`${e.name} (${e.id})`).join(", ")||"none"}`})};t.logger.info?.(`beeos_call_agent: resolved "${c}" → ${r.id} (${r.name}) via discover`),c=r.id}}catch{}}const h=l||(p?`session:${p}`:""),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}:{},...f?{taskId:f}:{}},configuration:{timeoutMs:y}}},a=`/api/v1/a2a/${encodeURIComponent(c)}`,s=AbortSignal.timeout(y+1e4),o=i?AbortSignal.any([i,s]):s,g=await a2aFetch(t,a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:o}),u=await g.text();let m;try{m=JSON.parse(u)}catch{m={}}if(!g.ok||m.error){if(401===g.status||403===g.status){const e=m.error??{};-32600===e.code&&r&&r("_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: ${g.status} ${e}`})}}const k=m.result,v=k?.id,I=k?.status?.state;if(v&&n.create(v,c,l,p),"completed"===I){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"===I){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)})}}}})}
|
|
@@ -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}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
|
+
import{randomUUID,createHash}from"node:crypto";import{mkdir,writeFile,rm,lstat,readlink}from"node:fs/promises";import{join}from"node:path";import{homedir}from"node:os";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 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"skills/install":await this.handleSkillsInstall(e);break;case"skills/uninstall":await this.handleSkillsUninstall(e);break;case"skills/update":await this.handleSkillsUpdate(e);break;case"models/list":await this.handleModelsList(e);break;case"session/cancel":this.handleSessionCancel(e.id,e.params);break;case"cron/list":case"cron/status":case"cron/add":case"cron/update":case"cron/remove":case"cron/run":case"cron/runs":await this.handleCronRequest(e);break;default:e.method.startsWith("terminal/")&&this.handleTerminalRequest?await this.handleTerminalRequest(e):this.transport.sendAcpError(e.id,Errors.MethodNotFound,{message:`Method not found: ${e.method}`})}}catch(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 i=[];try{const e=this.getGateway(),s=await loadHistory(e,t.gatewaySessionKey,50);i=groupIntoTurns(s);const o=i.filter(e=>"user"===e.role).length,r=i.filter(e=>"assistant"===e.role).length,a=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=${r} turnsWithToolCalls=${a} 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 o=new Set;for(const e of i)if(e.toolCalls)for(const s of e.toolCalls)s.id&&o.add(s.id),s.callId&&s.callId!==s.id&&o.add(s.callId);if(void 0!==t.pendingPromptId&&!t.promptDone&&t.assistantMq&&!t.assistantMq.closed)try{this.replayCurrentAssistantStream(t,o)}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,i=0;for(const o of t)s?.size&&o.toolCallId&&s.has(o.toolCallId)&&("tool_call"===o.sessionUpdate||"tool_call_update"===o.sessionUpdate)?i++:(this.transport.sendSessionUpdate(e.sessionId,o),n++);i>0&&this.logger.debug?.(`[bridge-core] replayCurrentAssistantStream skipped ${i} 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)isBackgroundSessionKey(e.gatewaySessionKey)||s.push({sessionId:e.sessionId,title:e.title||"New chat",cwd:e.cwd,updatedAt:e.lastStreamActivityTs??e.createdAt,agentId:e.agentId,platformAgentId:e.platformAgentId,deletable:!isSystemDefaultSessionKey(e.gatewaySessionKey)});const 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),r=t.label||cleanGatewayDerivedTitle(t.derivedTitle)||t.title||void 0,a=t.model,d=t.modelProvider;if(o){if(!o.title||"New chat"===o.title){const e=r||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),a&&(o.model=a),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:r||"New chat"});this.registerSession(e),s.push({sessionId:e.sessionId,title:r||"New chat",cwd:t.cwd,updatedAt:t.updatedAt,agentId:e.agentId,platformAgentId:e.platformAgentId,deletable:!isSystemDefaultSessionKey(n),model:a,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,r=this.getGateway();r?.isConnected&&r.sessionsPatch(o,{label:n}).catch(e=>{this.logger.debug?.(`[bridge-core] sessionsPatch (rename) failed: ${e instanceof Error?e.message:e}`)}),this.transport.sendResult(e.id,{sessionId: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 r=new Set;for(const[e,t]of this.state.toolCallToSessionMap)t===s&&(this.state.toolCallToSessionMap.delete(e),r.add(e));for(const[e,s]of this.state.toolCallIdMap)r.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,r=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&&(r=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:r})}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,disabled:e.disabled||void 0,skillKey:e.skillKey||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}})}getSkillsDir(){const e=process.env.OPENCLAW_HOME||join(homedir(),".openclaw");return join(e,"skills")}async handleSkillsInstall(e){const s=e.params,t=s?.name||s?.slug,n=s?.files;if(!t||!n?.length)return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Missing skill name or files"});const i=join(this.getSkillsDir(),t);try{await mkdir(i,{recursive:!0});for(const e of n){const s=join(i,e.path);await mkdir(join(s,".."),{recursive:!0});const t=await fetch(e.downloadUrl,{signal:AbortSignal.timeout(12e4)});if(!t.ok)throw new Error(`Failed to download ${e.path}: ${t.status}`);const n=Buffer.from(await t.arrayBuffer());await writeFile(s,n)}this.logger.info?.(`[bridge-core] Installed skill "${t}" (${n.length} files)`),this.transport.sendResult(e.id,{success:!0}),await this.pushSkillsList()}catch(s){this.logger.error?.(`[bridge-core] Failed to install skill "${t}": ${s instanceof Error?s.message:s}`),this.transport.sendAcpError(e.id,Errors.InternalError,{message:`Install failed: ${s instanceof Error?s.message:String(s)}`})}}async handleSkillsUninstall(e){const s=e.params,t=s?.name;if(!t)return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Missing skill name"});const n=join(this.getSkillsDir(),t),i=join(homedir(),".agents","skills",t);try{let s=!1;try{const e=await lstat(n);if(e.isSymbolicLink()){const e=await readlink(n);await rm(n,{force:!0}),await rm(e,{recursive:!0,force:!0}),s=!0}else e.isDirectory()&&(await rm(n,{recursive:!0,force:!0}),s=!0)}catch{}try{const e=await lstat(i);(e.isDirectory()||e.isSymbolicLink())&&(await rm(i,{recursive:!0,force:!0}),s=!0)}catch{}s||this.logger.warn?.(`[bridge-core] Skill "${t}" not found in any known location`),this.logger.info?.(`[bridge-core] Uninstalled skill "${t}"`),this.transport.sendResult(e.id,{success:!0}),await this.pushSkillsList()}catch(s){this.logger.error?.(`[bridge-core] Failed to uninstall skill "${t}": ${s instanceof Error?s.message:s}`),this.transport.sendAcpError(e.id,Errors.InternalError,{message:`Uninstall failed: ${s instanceof Error?s.message:String(s)}`})}}async handleSkillsUpdate(e){const s=e.params,t=s?.skillKey,n=s?.enabled;if(!t||"boolean"!=typeof n)return void this.transport.sendAcpError(e.id,Errors.InvalidParams,{message:"Missing skillKey or enabled"});const i=this.getGateway();if(i?.isConnected)try{const s=await i.skillsUpdate(t,n);this.logger.info?.(`[bridge-core] Updated skill "${t}" enabled=${n}`),this.transport.sendResult(e.id,{ok:s?.ok??!0,skillKey:t,enabled:n}),await this.pushSkillsList()}catch(s){this.logger.error?.(`[bridge-core] Failed to update skill "${t}": ${s instanceof Error?s.message:s}`),this.transport.sendAcpError(e.id,Errors.InternalError,{message:`Update failed: ${s instanceof Error?s.message:String(s)}`})}else this.transport.sendAcpError(e.id,Errors.InternalError,{message:"Gateway not connected"})}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 r=this.getGateway();if(!r?.isConnected)return void this.transport.sendAcpError(e.id,Errors.GatewayNotConnected);let a=extractPromptBlocks(sanitizePromptPayload(t));if(!n.title){const e=a.find(e=>"text"===e.type&&e.text);e&&"text"in e&&e.text&&(n.title=e.text.slice(0,64).replace(/\n/g," ").trim(),r?.isConnected&&n.title&&r.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(a);if(d.refs.length>0)try{const e=await resolveResources(d,this.writeObs);a=applyResolutions(a,e)}catch(e){this.logger.warn?.(`[bridge-core] Resource pre-resolution failed: ${e instanceof Error?e.message:e}`)}let l;if(this.beeosFileResolver){const e=this.beeosFileResolver.buildResolutionPlan(a);if(e.refs.length>0)try{l=await this.beeosFileResolver.resolveMetadataForPrompt(e)}catch(e){this.logger.warn?.(`[bridge-core] BeeOS file resolution failed: ${e instanceof Error?e.message:e}`)}}const c=toGatewayPrompt(a,{beeosFileResolutionsByUri:l});if("error"in c)return void this.transport.sendAcpError(e.id,Errors.PromptConvertFailed,{message:c.error});const{message:p,attachments:h}=c,g=resolveStandaloneSlashCommandName(a,p)??resolveSlashCmd(a,p),m="string"==typeof g;if(g&&this.handleSlashCommand){const s=this;if(await(async()=>{try{return await s.handleSlashCommand(g)}catch(e){return s.logger.warn?.(`[bridge-core] /${g} handler failed: ${e instanceof Error?e.message:e}`),!1}})())return this.emitPromptAsUserSessionUpdates(n.sessionId,a),this.transport.sendSessionUpdate(o,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Loading ${g}...`}}),void this.transport.sendResult(e.id,{stopReason:"end_turn"})}const u="chat.send";let y=m?p:withUserMessagePrefix(p);const f=this.config.canvasEnabled&&!m&&!1!==n.canvasActive&&!n.channelType;if(f){const e=n.promptsSinceCanvasInjection??0;!n.canvasPromptInjected||e>=10?(y=`${CANVAS_TERM_MAPPING}\n\n${y}`,n.canvasPromptInjected=!0,n.promptsSinceCanvasInjection=0,this.logger.debug?.("[bridge-core] Canvas term mapping injected (re-inject cycle)")):n.promptsSinceCanvasInjection=e+1}if(f){const e=this.getCanvasState?.();if(e){const 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(!m){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}m&&this.logger.info?.(`[bridge-core] slash command passthrough sessionId=${o} command=/${g}`),n.promptDone||void 0===n.pendingPromptId&&void 0===n.currentRunId||(this.logger.warn?.(`[bridge-core] handleSessionPrompt: force-ending stale run sid=${o} oldRunId=${n.currentRunId} oldPromptId=${n.pendingPromptId}`),(n.currentRunId||n.gatewayRequestId)&&r.agentCancel(n.gatewaySessionKey,{runId:n.currentRunId,requestId:n.gatewayRequestId}),this.endRun(n,{kind:"complete",stopReason:"cancelled"})),this.state.resetForNewRun(n,o,this.transport),n.pendingPromptId=e.id,n.gatewayMethod=u,this.emitPromptAsUserSessionUpdates(o,a),this.transport.sendSessionUpdate(o,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:""}}),this.schedulePromptTimeout(n);const S=h.length>0?h.map(e=>({type:e.type,content:e.content,...e.mimeType?{mimeType:e.mimeType}:{},...e.fileName?{fileName:e.fileName}:{}})):void 0,I=`req_${randomUUID().replace(/-/g,"")}`,w={sessionKey:n.gatewaySessionKey,message:y,deliver:!1,idempotencyKey:randomUUID()};S?.length&&(w.attachments=S);if(!r.sendFrame({type:"req",id:I,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=I,this.state.promptsByGatewayRequestId.set(I,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,i=s.text??e.text,o=s.data??e.data,r=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}:{},...r?{fileName:r}:{}}}}}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(),o=i?.isConnected,r=!(!n.currentRunId&&!n.gatewayRequestId);if(o&&r){i.agentCancel(n.gatewaySessionKey,{runId:n.currentRunId,requestId:n.gatewayRequestId})}this.endRun(n,{kind:"complete",stopReason:"cancelled"})||this.transport.sendSessionUpdate(n.sessionId,{sessionUpdate:"stream_complete",stopReason:"cancelled"}),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,i=n?.message??"gateway returned error";return this.logger.warn?.(`[bridge-core] handleGatewayResponse: gateway rejected prompt gatewayRequestId=${s} error=${i}`),void this.failPrompt(t,Errors.SendFailed.rpcCode,i)}const n=e.payload,i=n?.runId;i?(t.currentRunId=i,t.assistantStreamStartedAt=Date.now(),this.state.promptsByRunId.set(i,t),this.logger.debug?.(`[bridge-core] handleGatewayResponse: bound runId=${i} 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 i=n?this.state.promptsByRunId.get(n):void 0;if(!i)return void this.logger.warn?.(`[bridge-core] pushToolResultContent dropped — no session for runId=${n??"(none)"}`);const o=i.sessionId;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})}}}
|
package/dist/acp-server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{WebSocketServer,WebSocket}from"ws";import{randomUUID}from"node:crypto";let BridgeClientCtor;import{GatewayClient}from"./gateway-client.js";import{TerminalManager}from"./terminal/session-manager.js";import{AcpTransport}from"./acp-gateway/transport.js";import{AcpGatewaySessionState}from"./acp-gateway/session-state.js";import{AcpGatewayBridgeCore}from"./acp-gateway/bridge-core.js";import{BeeosFileResolver}from"./acp-gateway/beeos-file-resolver.js";import{AcpGatewayEvents}from"./acp-gateway/gateway-events.js";import{TerminalBridgeHandler}from"./terminal/bridge-handler.js";import{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
|
+
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}`):(r=this.core.ensureSessionForKey(o),this.logger.info?.(`[acp-server] agentSend: created session for key=${s} sid=${r.sessionId}`))):(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()}getLocalAgentId(){return this.config.gateway.agentId||this.core.getDefaultAgentId()}getDefaultPlatformAgentId(){return this.getDefaultPlatformAgent()?.id}getDefaultPlatformAgent(){const e=this.core.agentMapping;if(e&&0!==e.size)return e.values().next().value??void 0}getPlatformAgentIdForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return this.core.resolvePlatformAgentId(s?.agentId??"")??s?.platformAgentId}getGatewaySessionKeyForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return s?.gatewaySessionKey}getMentionsForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return s?.activeMentions}getResourceRenderer(){return this.canvasOrch.resourceRenderer}getDescriptorRegistry(){return this.canvasOrch.descriptorRegistry}getFormBuilder(){return this.canvasOrch.formBuilder}getSchemaRegistry(){return this.canvasOrch.schemaRegistry}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{CanvasActionRouter,formatActionForAgent}from"./canvas/action-router.js";import{FormSchemaRegistry}from"./surface/form-schema-registry.js";import{FormSurfaceBuilder}from"./surface/form-surface-builder.js";import{ResourceSurfaceRenderer}from"./surface/resource-surface-renderer.js";import{CANVAS_TERM_MAPPING}from"./canvas/tools.js";let _oclSeq=0;function nextOclId(e){return`${e}-${Date.now()}-${++_oclSeq}`}const STRING_PROPS=new Set(["text","url","label","name","title","description","placeholder","icon","src","alt","value","hint","caption"]);function toPascalCase(e){return e?e[0]>="A"&&e[0]<="Z"?e:e.charAt(0).toUpperCase()+e.slice(1):"Text"}function sanitizeA2UIComponents(e){return Array.isArray(e)?e.map(e=>{if("object"!=typeof e||null===e)return e;const s=e;if("component"in s&&"object"==typeof s.component&&null!==s.component){const e=s.component;for(const[s,t]of Object.entries(e)){if("object"==typeof t&&null!==t){const n=t;for(const[e,s]of Object.entries(n))"string"==typeof s&&STRING_PROPS.has(e)&&(n[e]={literalString:s});e[s]=n}if(s[0]>="a"&&s[0]<="z"){e[toPascalCase(s)]=e[s],delete e[s]}}s.component=e}return s}):e}export class CanvasOrchestrator{canvasState=null;resourceRenderer=null;descriptorRegistry=null;actionRouter=null;formBuilder=null;schemaRegistry=null;pendingCanvasLinks=[];deps;constructor(e){this.deps=e}updateDeps(e){Object.assign(this.deps,e)}setCanvasState(e,s){this.canvasState=e;const t=async(e,s)=>{if(!this.deps.gateway?.isConnected)throw new Error("Gateway not connected");return this.deps.gateway.request(e,s)},n=()=>{const s=this.deps.getSessionIdForToolCall();if(!s)return;const t=this.deps.state.sessions.get(s),n=t?.gatewaySessionKey;return n?e.resolveCanvasForSession(n):void 0},a=s?.schemaRegistry??new FormSchemaRegistry,i=new FormSurfaceBuilder({canvasState:e,gatewayRequest:t,resolveCanvasId:n,logger:this.deps.logger});this.formBuilder=i,this.schemaRegistry=a,this.descriptorRegistry=s?.descriptorRegistry??null,this.resourceRenderer=new ResourceSurfaceRenderer({canvasState:e,gatewayRequest:t,schemaRegistry:a,formBuilder:i,resolveCanvasId:n,logger:this.deps.logger}),this.actionRouter=new CanvasActionRouter({stateManager:e,logger:this.deps.logger,writeObs:e=>this.deps.writeObs(e),forwardToAgent:e=>this.forwardActionToAgent(e),emitActionAsUserMessage:e=>{const s=this.deps.state.resolveSessionFromParams(e);s?this.emitCanvasActionAsUserMessage(s.sessionId,e):this.deps.logger.warn?.("[canvas-orch] emitActionAsUserMessage: session not found, pill skipped",{surfaceId:e.surfaceId,sessionId:e.sessionId})}})}wireRelayActionHandler(){const e=this.canvasState?.getRelayClient();e?(e.onAction(e=>{this.handleRelayAction(e)}),this.deps.logger.debug?.("[canvas-orch] Canvas Relay action handler wired")):this.deps.logger.warn?.("[canvas-orch] wireRelayActionHandler called but no relay client available")}isCanvasActive(e){const s=e??this.deps.state.lastActiveSessionId,t=s?this.deps.state.sessions.get(s):void 0;return!1!==t?.canvasActive}isCanvasActiveForGatewayKey(e){const s=this.deps.state.sessionsByGatewayKey.get(e);return!1!==s?.canvasActive}onSessionLoaded(e,s,t){if(!this.deps.config.canvasEnabled)return;const n=this.canvasState?.getRelayClient();if(!n)return this.pendingCanvasLinks.push({acpSessionId:e,gatewaySessionKey:s}),void this.deps.logger.info?.(`[canvas-orch] Relay not ready, queued canvas link: acpSid=${e} gwKey=${s}`);this.ensureCanvasForSession(e,s)}onSessionDeleted(e){this.canvasState?.removeSession(e)}onSessionCleared(e,s){const t=this.canvasState?.resolveCanvasForSession(s);t&&(this.canvasState.clear(t),this.actionRouter?.reset())}onPromptStart(){this.actionRouter?.clearPending()}async onPromptComplete(e){try{await(this.actionRouter?.drainPending())}catch(e){this.deps.logger.warn?.(`[canvas-orch] Drain pending canvas actions failed: ${e instanceof Error?e.message:e}`)}}onPromptFailed(){this.actionRouter?.clearPending()}flushPendingCanvasLinks(){const e=this.pendingCanvasLinks.splice(0);if(0===e.length)return;const s=new Set,t=e.filter(({gatewaySessionKey:e})=>!s.has(e)&&(s.add(e),!this.canvasState?.resolveCanvasForSession(e)));if(0!==t.length){this.deps.logger.info?.(`[canvas-orch] Flushing ${t.length} pending canvas link(s)`);for(const{acpSessionId:e,gatewaySessionKey:s}of t)this.ensureCanvasForSession(e,s)}}onRelayReconnected(){this.deps.logger.info?.("[canvas-orch] Relay reconnected — retrying pending canvas links"),this.flushPendingCanvasLinks()}async handleSlashCommand(e){const s=this.descriptorRegistry?.getBySlashCommand(e);return!(!s||!this.resourceRenderer)&&(await this.resourceRenderer.render(s,"inline"),!0)}async enrichMessageWithCanvasContext(e,s,t){if(!this.canvasState)return e;if(t.has(s.split(":").slice(0,2).join(":"))||t.has(s))return e;try{let t=this.canvasState.resolveCanvasForSession(s);if(!t){const e=this.canvasState.getRelayClient();if(e)try{t=await e.ensureCanvas(s),this.canvasState.registerSession(s,t)}catch{}}if(t){let s=this.canvasState.buildContextForCanvas(t);s||(await this.canvasState.lazyLoadCanvas(t),s=this.canvasState.buildContextForCanvas(t));return`${CANVAS_TERM_MAPPING}\n\n${s??"[Canvas] Canvas panel is available. Use render_ui for structured/visual content."}\n\n${e}`}}catch(e){this.deps.logger.warn?.("[canvas-orch] Canvas context injection failed: %s",e)}return e}handleCanvasNotification(e,s){if(this.canvasState){if("canvas/toggle"===e){const e=s,t=!1!==e.enabled,n=this.deps.state.resolveSessionFromParams(e);if(n&&(n.canvasActive=t,t&&(n.canvasPromptInjected=!1,n.sessionId))){const e=n.sessionId,s=n.gatewaySessionKey,t=n.agentId,a=this.canvasState?.getRelayClient();if(a){const i=this.deps.resolvePlatformAgentId(t??"")??n.platformAgentId,o=s&&s!==e?e:void 0;a.ensureCanvas(s??e,{agentId:i,linkSessionId:o}).catch(e=>{this.deps.logger.warn?.(`[canvas-orch] Failed to pre-create canvas on toggle: ${e}`)})}}this.deps.logger.info?.(`[canvas-orch] Canvas toggled: ${t}`),this.deps.writeObs({component:"canvas",domain:"canvas",name:"canvas.toggle",severity:"info",payload:{enabled:t}})}else if("canvas/clear"===e){const e=s,t=this.deps.state.resolveSessionFromParams(e),n=t?this.canvasState.resolveCanvasForSession(t.gatewaySessionKey):void 0,a=n?this.canvasState.getAllActive(n).length:0;n&&this.canvasState.clear(n),this.actionRouter?.reset(),this.deps.logger.info?.(`[canvas-orch] Canvas cleared (${a} surfaces removed)`),this.deps.writeObs({component:"canvas",domain:"canvas",name:"canvas.cleared",severity:"info"})}}else this.deps.logger.warn?.(`[canvas-orch] Canvas notification ${e} ignored — canvasState not initialized`)}handleOpenClawCanvasEvent(e){if(!this.canvasState||!e)return;const s=e,t=s.action;if("a2ui_push"===t||"surface_update"===t){const e=String(s.surfaceId??nextOclId("openclaw")),t=s.components;if(t&&Array.isArray(t)){const n=sanitizeA2UIComponents(t),a=s.canvasId?String(s.canvasId):void 0;this.canvasState.has(e,a)?this.canvasState.update(e,n,a):this.canvasState.create(a??nextOclId("_openclaw"),e,"inline",n,{origin:{kind:"openclaw"}}),this.deps.logger.debug?.(`[canvas-orch] OpenClaw canvas → state + relay (surfaceId=${e})`)}}else if("navigate"===t||"url_open"===t){const e=String(s.url??"");if(e){const t=nextOclId("openclaw-nav"),n=String(s.canvasId??nextOclId("_openclaw_nav")),a=[{id:`${t}-embed`,component:{WebEmbed:{url:{literalString:e},title:{literalString:String(s.title??e)}}}}];this.canvasState.create(n,t,"inline",a,{origin:{kind:"openclaw"}})}}else this.deps.logger.debug?.(`[canvas-orch] Unhandled OpenClaw canvas action: ${t}`)}ensureCanvasForSession(e,s){const t=this.canvasState?.getRelayClient();if(!t)return;const n=e!==s?e:void 0;t.ensureCanvas(s,{linkSessionId:n}).then(async t=>{this.canvasState?.registerSession(s,t),await(this.canvasState?.joinCanvas(t,s)),this.deps.logger.info?.(`[canvas-orch] Canvas ensured: canvas=${t} acpSid=${e} gwKey=${s}`)}).catch(t=>{this.deps.logger.warn?.(`[canvas-orch] Failed to ensure canvas: acpSid=${e} gwKey=${s} err=${t}`),this.pendingCanvasLinks.push({acpSessionId:e,gatewaySessionKey:s})})}async forwardActionToAgent(e){const s=this.deps.state.resolveSessionFromParams(e);if(!s)return void this.deps.logger.warn?.("[canvas-orch] forwardActionToAgent dropped — no session resolved");if(this.emitCanvasActionAsUserMessage(s.sessionId,e),!this.deps.gateway?.isConnected)return void this.deps.logger.warn?.("[canvas-orch] forwardActionToAgent: gateway not connected, pill sent but agent forward skipped");if(s.currentRunId&&!s.promptDone)return this.actionRouter?.enqueue(e),void this.deps.logger.info?.(`[canvas-orch] Agent busy, canvas action queued (runId=${s.currentRunId})`);this.deps.state.resetForNewRun(s,s.sessionId,this.deps.transport);const t=this.canvasState?.summarize(e.surfaceId??""),n=formatActionForAgent(e,t??void 0);try{const e=await this.deps.gateway.agentSend(s.gatewaySessionKey,n,this.deps.config.gateway.agentId||this.deps.getDefaultAgentId());s.currentRunId=e.runId,s.assistantStreamStartedAt=Date.now(),this.deps.state.promptsByRunId.set(e.runId,s)}catch(t){this.deps.logger.warn?.(`[canvas-orch] Agent forward failed: ${t instanceof Error?t.message:t}`),this.deps.transport.sendSessionUpdate(s.sessionId,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`> _User interacted with "${e.userAction?.name??"unknown"}" on canvas._`}})}}emitCanvasActionAsUserMessage(e,s){const t=s.userAction?.name??"unknown",n=`Clicked "${t}"`;this.deps.transport.sendSessionUpdate(e,{sessionUpdate:"user_message_chunk",content:{type:"text",text:n},metadata:{type:"canvas_action",surfaceId:s.surfaceId,actionName:t,sourceComponentId:s.userAction?.sourceComponentId,actionPayload:s.userAction?.context,actionTimestamp:s.userAction?.timestamp}}),this.deps.logger.info?.(`[canvas-orch] Emitted canvas action pill: session=${e} action=${t} surface=${s.surfaceId}`)}handleRelayAction(e){if(!this.canvasState||!this.actionRouter)return void this.deps.logger.warn?.("[canvas-orch] Relay action ignored — canvas not initialized");const{canvasId:s,surfaceId:t,userAction:n,requestId:a,senderClientId:i}=e,o=this.canvasState.resolveSessionForCanvas(s);if(!o)return this.deps.logger.warn?.(`[canvas-orch] Relay action ignored — no session for canvas=${s}`),void this.sendRelayActionError(s,a,i,"no_session");const r=this.deps.state.findSessionByKey(o);if(!r)return this.deps.logger.warn?.(`[canvas-orch] Relay action ignored — session not found for gatewayKey=${o}`),void this.sendRelayActionError(s,a,i,"no_session");const c={surfaceId:t,userAction:{name:n.name,sourceComponentId:n.sourceComponentId,timestamp:n.timestamp,context:n.context},sessionId:r.sessionId};this.actionRouter.route(c,s).then(()=>{this.deps.logger.info?.(`[canvas-orch] Relay action routed: surface=${t} request=${a}`),this.sendRelayActionResult(s,a,i,"ok")}).catch(e=>{this.deps.logger.warn?.(`[canvas-orch] Relay action routing failed: ${e instanceof Error?e.message:e}`),this.sendRelayActionError(s,a,i,"processing_failed")})}sendRelayActionResult(e,s,t,n){this.canvasState?.getRelayClient()?.sendActionResult({canvasId:e,requestId:s,targetClientId:t,status:n})}sendRelayActionError(e,s,t,n){this.canvasState?.getRelayClient()?.sendActionError({canvasId:e,requestId:s,targetClientId:t,error:n})}destroy(){this.canvasState?.destroy(),this.actionRouter?.reset(),this.pendingCanvasLinks.length=0,this.canvasState=null,this.actionRouter=null,this.resourceRenderer=null,this.descriptorRegistry=null,this.formBuilder=null,this.schemaRegistry=null}}
|
|
1
|
+
import{CanvasActionRouter,formatActionForAgent}from"./canvas/action-router.js";import{FormSchemaRegistry}from"./surface/form-schema-registry.js";import{FormSurfaceBuilder}from"./surface/form-surface-builder.js";import{ResourceSurfaceRenderer}from"./surface/resource-surface-renderer.js";import{CANVAS_TERM_MAPPING}from"./canvas/tools.js";let _oclSeq=0;function nextOclId(e){return`${e}-${Date.now()}-${++_oclSeq}`}const STRING_PROPS=new Set(["text","url","label","name","title","description","placeholder","icon","src","alt","value","hint","caption"]);function toPascalCase(e){return e?e[0]>="A"&&e[0]<="Z"?e:e.charAt(0).toUpperCase()+e.slice(1):"Text"}function sanitizeA2UIComponents(e){return Array.isArray(e)?e.map(e=>{if("object"!=typeof e||null===e)return e;const s=e;if("component"in s&&"object"==typeof s.component&&null!==s.component){const e=s.component;for(const[s,t]of Object.entries(e)){if("object"==typeof t&&null!==t){const n=t;for(const[e,s]of Object.entries(n))"string"==typeof s&&STRING_PROPS.has(e)&&(n[e]={literalString:s});e[s]=n}if(s[0]>="a"&&s[0]<="z"){e[toPascalCase(s)]=e[s],delete e[s]}}s.component=e}return s}):e}export class CanvasOrchestrator{canvasState=null;resourceRenderer=null;descriptorRegistry=null;actionRouter=null;formBuilder=null;schemaRegistry=null;pendingCanvasLinks=[];deps;constructor(e){this.deps=e}updateDeps(e){Object.assign(this.deps,e)}setCanvasState(e,s){this.canvasState=e;const t=async(e,s)=>{if(!this.deps.gateway?.isConnected)throw new Error("Gateway not connected");return this.deps.gateway.request(e,s)},n=()=>{const s=this.deps.getSessionIdForToolCall();if(!s)return;const t=this.deps.state.sessions.get(s),n=t?.gatewaySessionKey;return n?e.resolveCanvasForSession(n):void 0},a=s?.schemaRegistry??new FormSchemaRegistry,i=new FormSurfaceBuilder({canvasState:e,gatewayRequest:t,resolveCanvasId:n,logger:this.deps.logger});this.formBuilder=i,this.schemaRegistry=a,this.descriptorRegistry=s?.descriptorRegistry??null,this.resourceRenderer=new ResourceSurfaceRenderer({canvasState:e,gatewayRequest:t,schemaRegistry:a,formBuilder:i,resolveCanvasId:n,logger:this.deps.logger}),this.actionRouter=new CanvasActionRouter({stateManager:e,logger:this.deps.logger,writeObs:e=>this.deps.writeObs(e),forwardToAgent:e=>this.forwardActionToAgent(e),emitActionAsUserMessage:e=>{const s=this.deps.state.resolveSessionFromParams(e);s?this.emitCanvasActionAsUserMessage(s.sessionId,e):this.deps.logger.warn?.("[canvas-orch] emitActionAsUserMessage: session not found, pill skipped",{surfaceId:e.surfaceId,sessionId:e.sessionId})}})}wireRelayActionHandler(){const e=this.canvasState?.getRelayClient();e?(e.onAction(e=>{this.handleRelayAction(e)}),this.deps.logger.debug?.("[canvas-orch] Canvas Relay action handler wired")):this.deps.logger.warn?.("[canvas-orch] wireRelayActionHandler called but no relay client available")}isCanvasActive(e){if(!e)return!1;const s=this.deps.state.sessions.get(e);return!1!==s?.canvasActive}isCanvasActiveForGatewayKey(e){const s=this.deps.state.sessionsByGatewayKey.get(e);return!1!==s?.canvasActive}onSessionLoaded(e,s,t){if(!this.deps.config.canvasEnabled)return;const n=this.canvasState?.getRelayClient();if(!n)return this.pendingCanvasLinks.push({acpSessionId:e,gatewaySessionKey:s}),void this.deps.logger.info?.(`[canvas-orch] Relay not ready, queued canvas link: acpSid=${e} gwKey=${s}`);this.ensureCanvasForSession(e,s)}onSessionDeleted(e){this.canvasState?.removeSession(e)}onSessionCleared(e,s){const t=this.canvasState?.resolveCanvasForSession(s);t&&(this.canvasState.clear(t),this.actionRouter?.reset())}onPromptStart(){this.actionRouter?.clearPending()}async onPromptComplete(e){try{await(this.actionRouter?.drainPending())}catch(e){this.deps.logger.warn?.(`[canvas-orch] Drain pending canvas actions failed: ${e instanceof Error?e.message:e}`)}}onPromptFailed(){this.actionRouter?.clearPending()}flushPendingCanvasLinks(){const e=this.pendingCanvasLinks.splice(0);if(0===e.length)return;const s=new Set,t=e.filter(({gatewaySessionKey:e})=>!s.has(e)&&(s.add(e),!this.canvasState?.resolveCanvasForSession(e)));if(0!==t.length){this.deps.logger.info?.(`[canvas-orch] Flushing ${t.length} pending canvas link(s)`);for(const{acpSessionId:e,gatewaySessionKey:s}of t)this.ensureCanvasForSession(e,s)}}onRelayReconnected(){this.deps.logger.info?.("[canvas-orch] Relay reconnected — retrying pending canvas links"),this.flushPendingCanvasLinks()}async handleSlashCommand(e){const s=this.descriptorRegistry?.getBySlashCommand(e);return!(!s||!this.resourceRenderer)&&(await this.resourceRenderer.render(s,"inline"),!0)}async enrichMessageWithCanvasContext(e,s,t){if(!this.canvasState)return e;if(t.has(s.split(":").slice(0,2).join(":"))||t.has(s))return e;try{let t=this.canvasState.resolveCanvasForSession(s);if(!t){const e=this.canvasState.getRelayClient();if(e)try{t=await e.ensureCanvas(s),this.canvasState.registerSession(s,t)}catch{}}if(t){let s=this.canvasState.buildContextForCanvas(t);s||(await this.canvasState.lazyLoadCanvas(t),s=this.canvasState.buildContextForCanvas(t));return`${CANVAS_TERM_MAPPING}\n\n${s??"[Canvas] Canvas panel is available. Use render_ui for structured/visual content."}\n\n${e}`}}catch(e){this.deps.logger.warn?.("[canvas-orch] Canvas context injection failed: %s",e)}return e}handleCanvasNotification(e,s){if(this.canvasState){if("canvas/toggle"===e){const e=s,t=!1!==e.enabled,n=this.deps.state.resolveSessionFromParams(e);if(n&&(n.canvasActive=t,t&&(n.canvasPromptInjected=!1,n.sessionId))){const e=n.sessionId,s=n.gatewaySessionKey,t=n.agentId,a=this.canvasState?.getRelayClient();if(a){const i=this.deps.resolvePlatformAgentId(t??"")??n.platformAgentId,o=s&&s!==e?e:void 0;a.ensureCanvas(s??e,{agentId:i,linkSessionId:o}).catch(e=>{this.deps.logger.warn?.(`[canvas-orch] Failed to pre-create canvas on toggle: ${e}`)})}}this.deps.logger.info?.(`[canvas-orch] Canvas toggled: ${t}`),this.deps.writeObs({component:"canvas",domain:"canvas",name:"canvas.toggle",severity:"info",payload:{enabled:t}})}else if("canvas/clear"===e){const e=s,t=this.deps.state.resolveSessionFromParams(e),n=t?this.canvasState.resolveCanvasForSession(t.gatewaySessionKey):void 0,a=n?this.canvasState.getAllActive(n).length:0;n&&this.canvasState.clear(n),this.actionRouter?.reset(),this.deps.logger.info?.(`[canvas-orch] Canvas cleared (${a} surfaces removed)`),this.deps.writeObs({component:"canvas",domain:"canvas",name:"canvas.cleared",severity:"info"})}}else this.deps.logger.warn?.(`[canvas-orch] Canvas notification ${e} ignored — canvasState not initialized`)}handleOpenClawCanvasEvent(e){if(!this.canvasState||!e)return;const s=e,t=s.action;if("a2ui_push"===t||"surface_update"===t){const e=String(s.surfaceId??nextOclId("openclaw")),t=s.components;if(t&&Array.isArray(t)){const n=sanitizeA2UIComponents(t),a=s.canvasId?String(s.canvasId):void 0;this.canvasState.has(e,a)?this.canvasState.update(e,n,a):this.canvasState.create(a??nextOclId("_openclaw"),e,"inline",n,{origin:{kind:"openclaw"}}),this.deps.logger.debug?.(`[canvas-orch] OpenClaw canvas → state + relay (surfaceId=${e})`)}}else if("navigate"===t||"url_open"===t){const e=String(s.url??"");if(e){const t=nextOclId("openclaw-nav"),n=String(s.canvasId??nextOclId("_openclaw_nav")),a=[{id:`${t}-embed`,component:{WebEmbed:{url:{literalString:e},title:{literalString:String(s.title??e)}}}}];this.canvasState.create(n,t,"inline",a,{origin:{kind:"openclaw"}})}}else this.deps.logger.debug?.(`[canvas-orch] Unhandled OpenClaw canvas action: ${t}`)}ensureCanvasForSession(e,s){const t=this.canvasState?.getRelayClient();if(!t)return;const n=e!==s?e:void 0;t.ensureCanvas(s,{linkSessionId:n}).then(async t=>{this.canvasState?.registerSession(s,t),await(this.canvasState?.joinCanvas(t,s)),this.deps.logger.info?.(`[canvas-orch] Canvas ensured: canvas=${t} acpSid=${e} gwKey=${s}`)}).catch(t=>{this.deps.logger.warn?.(`[canvas-orch] Failed to ensure canvas: acpSid=${e} gwKey=${s} err=${t}`),this.pendingCanvasLinks.push({acpSessionId:e,gatewaySessionKey:s})})}async forwardActionToAgent(e){const s=this.deps.state.resolveSessionFromParams(e);if(!s)return void this.deps.logger.warn?.("[canvas-orch] forwardActionToAgent dropped — no session resolved");if(this.emitCanvasActionAsUserMessage(s.sessionId,e),!this.deps.gateway?.isConnected)return void this.deps.logger.warn?.("[canvas-orch] forwardActionToAgent: gateway not connected, pill sent but agent forward skipped");if(s.currentRunId&&!s.promptDone)return this.actionRouter?.enqueue(e),void this.deps.logger.info?.(`[canvas-orch] Agent busy, canvas action queued (runId=${s.currentRunId})`);this.deps.state.resetForNewRun(s,s.sessionId,this.deps.transport);const t=this.canvasState?.summarize(e.surfaceId??""),n=formatActionForAgent(e,t??void 0);try{const e=await this.deps.gateway.agentSend(s.gatewaySessionKey,n,this.deps.config.gateway.agentId||this.deps.getDefaultAgentId());s.currentRunId=e.runId,s.assistantStreamStartedAt=Date.now(),this.deps.state.promptsByRunId.set(e.runId,s)}catch(t){this.deps.logger.warn?.(`[canvas-orch] Agent forward failed: ${t instanceof Error?t.message:t}`),this.deps.transport.sendSessionUpdate(s.sessionId,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`> _User interacted with "${e.userAction?.name??"unknown"}" on canvas._`}})}}emitCanvasActionAsUserMessage(e,s){const t=s.userAction?.name??"unknown",n=`Clicked "${t}"`;this.deps.transport.sendSessionUpdate(e,{sessionUpdate:"user_message_chunk",content:{type:"text",text:n},metadata:{type:"canvas_action",surfaceId:s.surfaceId,actionName:t,sourceComponentId:s.userAction?.sourceComponentId,actionPayload:s.userAction?.context,actionTimestamp:s.userAction?.timestamp}}),this.deps.logger.info?.(`[canvas-orch] Emitted canvas action pill: session=${e} action=${t} surface=${s.surfaceId}`)}handleRelayAction(e){if(!this.canvasState||!this.actionRouter)return void this.deps.logger.warn?.("[canvas-orch] Relay action ignored — canvas not initialized");const{canvasId:s,surfaceId:t,userAction:n,requestId:a,senderClientId:i}=e,o=this.canvasState.resolveSessionForCanvas(s);if(!o)return this.deps.logger.warn?.(`[canvas-orch] Relay action ignored — no session for canvas=${s}`),void this.sendRelayActionError(s,a,i,"no_session");const r=this.deps.state.findSessionByKey(o);if(!r)return this.deps.logger.warn?.(`[canvas-orch] Relay action ignored — session not found for gatewayKey=${o}`),void this.sendRelayActionError(s,a,i,"no_session");const c={surfaceId:t,userAction:{name:n.name,sourceComponentId:n.sourceComponentId,timestamp:n.timestamp,context:n.context},sessionId:r.sessionId};this.actionRouter.route(c,s).then(()=>{this.deps.logger.info?.(`[canvas-orch] Relay action routed: surface=${t} request=${a}`),this.sendRelayActionResult(s,a,i,"ok")}).catch(e=>{this.deps.logger.warn?.(`[canvas-orch] Relay action routing failed: ${e instanceof Error?e.message:e}`),this.sendRelayActionError(s,a,i,"processing_failed")})}sendRelayActionResult(e,s,t,n){this.canvasState?.getRelayClient()?.sendActionResult({canvasId:e,requestId:s,targetClientId:t,status:n})}sendRelayActionError(e,s,t,n){this.canvasState?.getRelayClient()?.sendActionError({canvasId:e,requestId:s,targetClientId:t,error:n})}destroy(){this.canvasState?.destroy(),this.actionRouter?.reset(),this.pendingCanvasLinks.length=0,this.canvasState=null,this.actionRouter=null,this.resourceRenderer=null,this.descriptorRegistry=null,this.formBuilder=null,this.schemaRegistry=null}}
|
package/dist/gateway-client.js
CHANGED
|
@@ -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 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}}
|
|
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 skillsUpdate(e,t){return this.request("skills.update",{skillKey:e,enabled:t})}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,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
|
+
import{randomUUID}from"node:crypto";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,_initializing=!1;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,t=buildThirdPartyChannelSet(o);t.size>0&&e.logger.info?.(`[beeos-claw] Third-party channels detected: ${[...t].join(", ")}`);const n=r.log.enabled?createObsEventWriter({dir:r.log.dir,redaction:{gatewayToken:r.gateway.token},logger:e.logger}):()=>{};n({component:"plugin",domain:"lifecycle",name:"lifecycle.startup",severity:"info",payload:{pluginVersion:PLUGIN_VERSION,pid:process.pid,nodeVersion:process.version,cwd:process.cwd()}}),n({component:"plugin",domain:"config",name:"config.resolved",severity:"info",payload:{config:r,sources:a.sources,openclawConfigPath:a.openclawConfigPath}});for(const o of a.validation)n({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:n,thirdPartyChannels:t,openclawConfig:o}}function registerUploadTools(e,o,a){const{cfg:r,writeObs:t}=o;cleanupUploadToolResultCache().catch(o=>{e.logger.warn?.(`[beeos_upload_file] cache cleanup failed on startup: ${String(o)}`)}),e.registerTool({name:BEEOS_UPLOAD_TOOL_NAME,description:BEEOS_UPLOAD_TOOL_DESCRIPTION,parameters:BEEOS_UPLOAD_TOOL_SCHEMA,async execute(o,n,s){e.logger.debug?.(`[beeos_upload_file] toolCallId=${o} params=${JSON.stringify(n)}`);const i=await executeUpload(n,r,agentKeys,s);return e.logger.debug?.(`[beeos_upload_file] toolCallId=${o} ok=${i.ok}`),t({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:t,thirdPartyChannels:n}=o,s=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,t,s,i,n);a.current=l,e.registerService({id:"beeos-acp",async start(){if(!r.bridge.url&&r.agentGatewayUrl&&s){const o=await discoverBridgeFromGW(r.agentGatewayUrl,s);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=>{c.onceConnected(()=>{l.setMessageSdk(c,o),e.logger.info?.("[beeos-claw] Message SDK connected (principalId=%s, via=%s)",o,u?"gateway":"direct")}),await c.connect(o,{centrifugoUrl:p,tokenProvider:u})};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,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;if(!a)return;let s="string"==typeof o?.session_key?o.session_key:void 0;if(!s){const e="string"==typeof o?.channel?o.channel:"a2a";s=`agent:${l.getLocalAgentId()}:${e}:${randomUUID()}`}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),t=(e,o)=>{l.broadcastNotification(e,o)};registerA2ATools(e,{agentGatewayUrl:r.agentGatewayUrl,agentKeys:agentKeys,logger:e.logger},g,o,a,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 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 t=l.getDefaultPlatformAgent();if(!t?.id)return void e.logger.info?.("[beeos-claw] Canvas Relay skipped: no agentId after sync");const n=new CanvasRelayClient({canvasRelayUrl:r.canvasRelayUrl,agentKeys:agentKeys,agentId:t.id,displayName:t.displayName,avatarUrl:t.avatarUrl,tokenProvider:a,onReconnect:()=>l.onRelayReconnected(),logger:e.logger});n.connect(),o.setRelayClient(n),o.setAgentId(t.id),l.wireRelayActionHandler(),l.flushPendingCanvasLinks(),e.logger.info?.(`[beeos-claw] Canvas Relay multiplexed client connected (agentId=${t.id}, name=${t.name??"none"})`)}catch(o){e.logger.warn?.(`[beeos-claw] Failed to start Canvas Relay client: ${o}`)}},stop(){o.getRelayClient()?.disconnect()}}),e.logger.info?.("[beeos-claw] Canvas Relay configured")}else e.logger.warn?.("[beeos-claw] Canvas Relay unavailable: agentGatewayUrl or agentKeys missing");const a={stateManager:o,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()},s=new FormSchemaRegistry;s.register(CRON_CREATE_SCHEMA),s.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:s,descriptorRegistry:i});const c=l.getFormBuilder();c&&e.registerTool({name:RENDER_FORM_TOOL_NAME,description:buildRenderFormDescription(s),parameters:RENDER_FORM_TOOL_SCHEMA,execute:g(createRenderFormHandler({registry:s,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(n,{sessionKey:o?.sessionKey,channelId:o?.channelId}))return;if(!o?.sessionKey)return;return l.isCanvasActiveForGatewayKey(o.sessionKey)?{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;return isThirdPartyChannel(n,{sessionKey:o?.sessionKey})?{block:!0,blockReason:"Canvas tools are not available in this channel. Respond with plain text only."}:o?.sessionKey?l.isCanvasActiveForGatewayKey(o.sessionKey)?void 0:{block:!0,blockReason:"Canvas is closed by user. Respond with plain text instead."}:{block:!0,blockReason:"Canvas session unknown. Respond with plain text instead."}}),e.logger.debug?.("[beeos-claw] Canvas tool guard registered: before_tool_call")}catch{e.logger.debug?.("[beeos-claw] before_tool_call hook not supported")}}e.logger.info?.("[beeos-claw] Canvas tools registered (render_ui, close_ui, render_form + auto-action tools)")}else e.logger.info?.("[beeos-claw] Canvas disabled by config (canvasEnabled=false)");const m=new TerminalManager,b=createTerminalWebSocketService({config:{port: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)"),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(!_initializing)if(e.registrationMode&&"full"!==e.registrationMode)e.logger.debug?.(`[beeos-claw] Skipping registration (mode=${e.registrationMode})`);else{_initializing=!0;try{const o=initializePlugin(e);if(!o)return;const a={current:null};registerUploadTools(e,o,a),registerServices(e,o,a),e.logger.info?.("[beeos-claw] Plugin registered successfully")}finally{_initializing=!1}}}};export default plugin;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Centrifuge}from"centrifuge";import WebSocket from"ws";export class MessageSDK{config;client=null;personalSub=null;principalId="";handlers=new Map;
|
|
1
|
+
import{Centrifuge}from"centrifuge";import WebSocket from"ws";export class MessageSDK{config;client=null;personalSub=null;principalId="";handlers=new Map;_resubscribeTimer=null;_resubscribeAttempts=0;static MAX_RESUBSCRIBE_ATTEMPTS=5;_reconnectCount=0;_lastDisconnectTs=0;_tokenRefreshCount=0;_onConnectedCallback=null;logger;constructor(e,t){this.config=e,this.logger=t}async getToken(e,t,n){const s={principal_id:e};return t&&(s.claims=t),n&&(s.ttl_seconds=n),this.restRequest("POST","/api/v1/tokens",s)}async send(e,t,n){await this.restRequest("POST","/api/v1/messages/send",{target_id:e,message_type:t,payload:n})}async isOnline(e){return(await this.restRequest("GET",`/api/v1/connections/${encodeURIComponent(e)}/online`)).online}async registerWebhook(e,t,n){const s={url:e,events:t};return n&&(s.secret=n),this.restRequest("POST","/api/v1/webhooks",s)}async removeWebhook(e){await this.restRequest("DELETE",`/api/v1/webhooks/${encodeURIComponent(e)}`)}async connect(e,t){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 n=t?.tokenProvider??(e=>this.getToken(e));let s=t?.centrifugoUrl||this.config.centrifugoUrl;if(!s)try{s=(await n(e)).centrifugo_url}catch(e){this.logger.warn?.(`[message-sdk] Token probe failed, cannot discover Centrifugo URL: ${e instanceof Error?e.message:String(e)}`)}if(!s)throw new Error("No Centrifugo URL available. Set centrifugoUrl in config, ConnectOptions, or ensure the token provider is reachable at startup.");const i=`personal:${e}`;this.logger.info?.(`[message-sdk] Connecting as principal=${e} url=${s}`);this.client=new Centrifuge(s,{getToken:async()=>{this._tokenRefreshCount++,this.logger.info?.(`[message-sdk] Token fetch #${this._tokenRefreshCount} for principal=${e}`);return(await n(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 t=this._lastDisconnectTs>0?Date.now()-this._lastDisconnectTs:0;this.logger.info?.(`[message-sdk] Reconnected (client=${e.client}) reconnects=${this._reconnectCount} downtime=${t}ms`)}else this.logger.info?.(`[message-sdk] Connected (client=${e.client})`);if(this._onConnectedCallback){try{this._onConnectedCallback()}catch{}this._onConnectedCallback=null}}),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)}),this.client.on("subscribed",e=>{e.channel===i&&this.logger.info?.(`[message-sdk] Subscribed channel=${i} recoverable=${e.recoverable} recovered=${e.recovered}`)}),this.client.on("subscribing",e=>{e.channel===i&&this.logger.info?.(`[message-sdk] Subscribing channel=${i}`)}),this.client.on("unsubscribed",e=>{e.channel===i&&this.logger.warn?.(`[message-sdk] Unsubscribed channel=${i}`)}),this.client.on("publication",e=>{e.channel===i&&this.dispatch(e.data).catch(e=>{this.logger.error?.("[message-sdk] dispatch error:",e)})}),this.client.connect()}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,t){this.handlers.set(e,t)}onceConnected(e){this._onConnectedCallback=e}async joinGroup(e,t){if(!this.client)throw new Error("Not connected");const n=this.client.newSubscription(`group:${e}`);return n.on("publication",n=>{t(n.data).catch(t=>{this.logger.error?.(`[message-sdk] group handler error (${e}):`,t)})}),n.subscribe(),n}async publishToGroup(e,t){if(!this.client)throw new Error("Not connected");await this.client.publish(`group:${e}`,{from:this.principalId,content:t,timestamp:Date.now()})}async sendToChannel(e,t,n){const s=`ch:${e}`,i={type:t,payload:n,channel_id:e,metadata:{from:this.principalId,channel_id:e,timestamp:String(Date.now())}};if("connected"===this.client?.state)return await this.client.publish(s,i),void this.logger.debug?.(`[message-sdk] Published type=${t} to ${s}`);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:t,payload:n});throw new Error(`Cannot send to channel ${e}: no Centrifugo connection and no serviceUrl`)}async sendToPersonal(e,t,n){if(!this.client)throw new Error("Not connected");const s=`personal:${e}`,i={type:t,payload:n,metadata:{from:this.principalId,timestamp:String(Date.now())}};try{await this.client.publish(s,i),this.logger.debug?.(`[message-sdk] Published type=${t} to ${s}`)}catch(e){throw this.logger.warn?.(`[message-sdk] Publish failed type=${t} channel=${s}: ${e instanceof Error?e.message:String(e)}`),e}}get isConnected(){return"connected"===this.client?.state}get currentPrincipalId(){return this.principalId}async dispatch(e){const t=this.handlers.get(e.type);t?await t(e):this.logger.debug?.(`[message-sdk] No handler for type=${e.type}`)}async restRequest(e,t,n){if(!this.config.serviceUrl)throw new Error("Message Service REST API requires serviceUrl in config");const s=`${this.config.serviceUrl}${t}`,i={},o={method:e,headers:i};void 0!==n&&(i["Content-Type"]="application/json",o.body=JSON.stringify(n));const r=await fetch(s,o);if(!r.ok){const n=await r.text().catch(()=>"");throw new Error(`Message Service ${e} ${t} returned ${r.status}: ${n}`)}if(204!==r.status)return await r.json()}}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "beeos-claw",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.13",
|
|
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>",
|