beeos-claw 0.2.3 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acp-gateway/beeos-file-resolver.js +1 -0
- package/dist/acp-gateway/bridge-core.js +1 -1
- package/dist/acp-gateway/gateway-events.js +1 -1
- package/dist/acp-gateway/history-replay.js +1 -1
- package/dist/acp-gateway/prompt-converter.js +1 -1
- package/dist/acp-gateway/session-state.js +1 -1
- package/dist/acp-server.js +1 -1
- package/dist/canvas/tools.js +1 -1
- package/dist/index.js +1 -1
- package/dist/upload/tool.js +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync,mkdirSync,readdirSync,statSync,writeFileSync}from"node:fs";import{join,basename}from"node:path";const BEEOS_FILE_URI_PREFIX="beeos-file://",MAX_FILE_NAME_LENGTH=120,DOWNLOAD_TIMEOUT_MS=12e4,MAX_CONCURRENT_RESOLVES=3,OPENCLAW_HOME=process.env.OPENCLAW_HOME||join(process.env.HOME||"/home/node",".openclaw"),UPLOAD_DIR=join(OPENCLAW_HOME,"workspace","uploads"),RESOURCE_CACHE_DIR=join(OPENCLAW_HOME,"workspace","resource_cache");export function parseBeeosFileUri(e){if(!e.startsWith("beeos-file://"))return{};const t=e.slice(13).trim();return t?{fileId:t}:{error:"beeos-file uri requires file_id"}}export class BeeosFileResolver{agentGatewayUrl;agentFetch;writeObs;constructor(e){this.agentGatewayUrl=e.agentGatewayUrl,this.agentFetch=e.agentFetch,this.writeObs=e.writeObs}buildResolutionPlan(e){const t=[],a=new Map;for(let i=0;i<e.length;i++){const r=e[i];if("resource_link"!==r.type||!r.uri)continue;const o=parseBeeosFileUri(r.uri);o.fileId&&(t.push({blockIndex:i,uri:r.uri,fileId:o.fileId,name:r.title??r.name}),a.set(r.uri,o.fileId))}return{refs:t,fileIds:[...new Set(a.values())],fileIdByUri:a}}async resolveMetadataForPrompt(e){if(0===e.fileIds.length)return new Map;const t=new Map,a=e.fileIds.map(e=>async()=>{const a=await this.resolveOneFile(e);t.set(e,a)});await runWithConcurrency(a,3);const i=new Map;for(const[a,r]of e.fileIdByUri.entries()){const e=t.get(r);e&&i.set(a,e)}return i}async resolveOneFile(e){const t=Date.now(),a=this.findCachedFile(e);if(a)return this.writeObs?.({component:"beeos-file-resolver",domain:"file",name:"cache_hit",severity:"debug",payload:{fileId:e,localPath:a.localPath}}),{status:"resolved",fileId:e,name:a.localFileName,mimeType:"application/octet-stream",localPath:a.localPath,localFileName:a.localFileName,localSizeBytes:a.localSizeBytes,localCacheHit:!0,downloadUrl:""};const i=`${this.agentGatewayUrl}/api/v1/agent/files/${encodeURIComponent(e)}/resolve`;this.writeObs?.({component:"beeos-file-resolver",domain:"file",name:"metadata_request",severity:"info",payload:{fileId:e,url:i}});const r=new AbortController,o=setTimeout(()=>r.abort(),12e4);"object"==typeof o&&"unref"in o&&o.unref();try{const a=await this.agentFetch(i,{method:"GET",signal:r.signal});if(!a.ok){const i=a.status>=500?"http_5xx":"http_4xx",r=a.status>=500||429===a.status;return this.writeObs?.({component:"beeos-file-resolver",domain:"file",name:"metadata_failed",severity:"warn",payload:{fileId:e,httpStatus:a.status,code:i,durationMs:Date.now()-t}}),{status:"resolve_failed",fileId:e,code:i,message:`resolve request failed with status ${a.status}`,retriable:r,httpStatus:a.status}}let o;try{o=await a.json()}catch{return this.makeFailure(e,"invalid_response","resolve response is not valid json",!1)}const l=asString(o.fileName),s=asString(o.mimeType),n=asString(o.downloadUrl),c="number"==typeof o.size?o.size:void 0;if(!n)return this.makeFailure(e,"missing_download_url","resolve response missing downloadUrl",!1,l);this.writeObs?.({component:"beeos-file-resolver",domain:"file",name:"metadata_ok",severity:"debug",payload:{fileId:e,fileName:l,mimeType:s,size:c,durationMs:Date.now()-t}});const d=await this.ensureFileDownloaded({fileId:e,name:l||e,downloadUrl:n});return"resolve_failed"===d.status?d:{status:"resolved",fileId:e,name:l||d.localFileName,mimeType:s||"application/octet-stream",size:c,downloadUrl:n,localPath:d.localPath,localFileName:d.localFileName,localSizeBytes:d.localSizeBytes,localCacheHit:!1}}catch(t){const a=t instanceof Error&&"AbortError"===t.name,i=a?"timeout":"network_error",r=a?"resolve request timed out after 120000ms":`resolve request failed: ${t instanceof Error?t.message:String(t)}`;return this.makeFailure(e,i,r,!0)}finally{clearTimeout(o)}}findCachedFile(e){for(const t of[UPLOAD_DIR,RESOURCE_CACHE_DIR]){const a=this.findFileByPrefix(t,e);if(a)return a}}findFileByPrefix(e,t){if(!existsSync(e))return;const a=`${t}_`;let i;try{i=readdirSync(e).sort()}catch{return}for(const t of i){if(!t.startsWith(a))continue;const i=join(e,t);try{const e=statSync(i);if(e.isFile()&&e.size>0)return{localPath:i,localFileName:t,localSizeBytes:e.size}}catch{continue}}}async ensureFileDownloaded(e){const t=sanitizeFileName(e.name),a=`${e.fileId}_${t}`,i=join(RESOURCE_CACHE_DIR,a);try{mkdirSync(RESOURCE_CACHE_DIR,{recursive:!0})}catch(t){return this.makeFailure(e.fileId,"fs_error",`failed to create cache dir: ${String(t)}`,!1,e.name)}const r=this.findFileByPrefix(RESOURCE_CACHE_DIR,e.fileId);if(r)return{status:"resolved",fileId:e.fileId,name:e.name,mimeType:"application/octet-stream",downloadUrl:e.downloadUrl,localPath:r.localPath,localFileName:r.localFileName,localSizeBytes:r.localSizeBytes,localCacheHit:!0};const o=new AbortController,l=setTimeout(()=>o.abort(),12e4);"object"==typeof l&&"unref"in l&&l.unref();try{const t=await this.agentFetch(e.downloadUrl,{method:"GET",signal:o.signal});if(!t.ok){const a=t.status>=500?"http_5xx":"http_4xx";return this.makeFailure(e.fileId,a,`file download failed with status ${t.status}`,t.status>=500||429===t.status,e.name,t.status)}let r;try{r=Buffer.from(await t.arrayBuffer())}catch{return this.makeFailure(e.fileId,"network_error","failed to read download response body",!0,e.name)}if(0===r.byteLength)return this.makeFailure(e.fileId,"invalid_response","downloaded file is empty",!1,e.name);try{writeFileSync(i,r)}catch(t){return this.makeFailure(e.fileId,"fs_error",`failed to write file: ${String(t)}`,!1,e.name)}let l=r.byteLength;try{const e=statSync(i);e.isFile()&&e.size>0&&(l=e.size)}catch{}return this.writeObs?.({component:"beeos-file-resolver",domain:"file",name:"download_ok",severity:"info",payload:{fileId:e.fileId,localPath:i,localSizeBytes:l}}),{status:"resolved",fileId:e.fileId,name:e.name,mimeType:"application/octet-stream",downloadUrl:e.downloadUrl,localPath:i,localFileName:a,localSizeBytes:l,localCacheHit:!1}}catch(t){const a=t instanceof Error&&"AbortError"===t.name,i=a?"timeout":"network_error",r=a?"file download timed out after 120000ms":`file download failed: ${t instanceof Error?t.message:String(t)}`;return this.makeFailure(e.fileId,i,r,!0,e.name)}finally{clearTimeout(l)}}makeFailure(e,t,a,i,r,o){return this.writeObs?.({component:"beeos-file-resolver",domain:"file",name:"resolve_failed",severity:"warn",payload:{fileId:e,code:t,message:a,retriable:i,...void 0!==o?{httpStatus:o}:{}}}),{status:"resolve_failed",fileId:e,...r?{name:r}:{},code:t,message:a,retriable:i,...void 0!==o?{httpStatus:o}:{}}}}function sanitizeFileName(e){return basename(e).trim().replace(/[\u0000-\u001f\u007f]/g,"").replace(/[\\/]+/g,"_").replace(/[^\p{L}\p{N}._-]+/gu,"_").replace(/_+/g,"_").replace(/^\.+/,"").replace(/^_+|_+$/g,"").slice(0,120)||"file"}function asString(e){if("string"==typeof e&&e.trim())return e.trim()}async function runWithConcurrency(e,t){let a=0;async function i(){for(;a<e.length;){const t=a++;await e[t]()}}const r=[];for(let a=0;a<Math.min(t,e.length);a++)r.push(i());await Promise.all(r)}
|
|
@@ -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}from"./history-replay.js";import{buildResolutionPlan,resolveResources,applyResolutions}from"./prompt-resource-resolver.js";import{Errors}from"../errors/index.js";import{formatFriendlyError}from"../errors/classify.js";import{resolveChannelFromSessionKey}from"../channel-detection.js";import{ACP_PROTOCOL_VERSION,DEFAULT_PROMPT_TIMEOUT_MS,DEFAULT_LOAD_REPLAY_IDLE_TIMEOUT_MS,DEFAULT_LOAD_REPLAY_HARD_TIMEOUT_MS}from"./types.js";const DEFAULT_MODE={id:"default",name:"Default",description:"Default agent mode"},USER_MESSAGE_PREFIX="User Message From BeeOS:",USER_MESSAGE_PREFIX_WITH_NEWLINE=`${USER_MESSAGE_PREFIX}\n`,SLASH_COMMAND_NAME_RE=/^[a-z0-9_-]+$/i;function withUserMessagePrefix(e){return e.startsWith(USER_MESSAGE_PREFIX)?e:`${USER_MESSAGE_PREFIX_WITH_NEWLINE}${e}`}const BACKGROUND_SESSION_PATTERNS=[":cron:",":hook:","node-"];function isBackgroundSessionKey(e){return BACKGROUND_SESSION_PATTERNS.some(s=>e.includes(s))}function isSystemDefaultSessionKey(e){const s=e.split(":");if(s.length<3||"agent"!==s[0])return!1;const t=s.slice(2).join(":");return"main"===t||t===s[1]}function cleanGatewayDerivedTitle(e){if(!e)return;let s=stripTransportMetadata(e);return/^\[System\b/.test(s)?void 0:(s=s.trim(),s||void 0)}function resolveStandaloneSlashCommandName(e,s){if(0===e.length)return;if(e.some(e=>"text"!==e.type))return;const t=s.trim();if(!t||t.includes("\n")||!t.startsWith("/"))return;const n=t.match(/^\/([^\s:]+)(?::|\s|$)/)?.[1]?.trim();return n&&!n.includes("/")&&SLASH_COMMAND_NAME_RE.test(n)?n.toLowerCase():void 0}function deriveSessionId(e,s){const t=createHash("sha256").update(`${s}:${e}`).digest("hex").substring(0,32);return`session:${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`}function parseAgentIdFromKey(e){const s=e.split(":");return(s.length>=3&&"agent"===s[0]?s[1]:"")||"main"}function createSessionObject(e){const s=parseAgentIdFromKey(e.gatewayKey);return{sessionId:deriveSessionId(e.gatewayKey,e.instanceId),gatewaySessionKey:e.gatewayKey,agentId:s,platformAgentId:e.resolvePlatformAgentId?.(s),createdAt:Date.now(),chatReplayDedupKeys:new Set,cwd:e.cwd,title:e.title,channelType:resolveChannelFromSessionKey(e.gatewayKey,e.thirdPartyChannels)}}export class AcpGatewayBridgeCore{state;transport;config;logger;writeObs;getGateway;thirdPartyChannels;initialized=!1;agentMapping=null;_syncResolvers=[];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=[]}markAgentSyncDone(){for(const e of this._syncResolvers)e();this._syncResolvers=[]}waitForAgentMapping(e=15e3){return this.agentMapping?Promise.resolve():new Promise(s=>{this._syncResolvers.push(s);const t=setTimeout(()=>{const e=this._syncResolvers.indexOf(s);-1!==e&&this._syncResolvers.splice(e,1),s()},e);"object"==typeof t&&"unref"in t&&t.unref()})}handleTerminalRequest=null;handleTerminalNotification=null;onRunComplete=null;onRunFailed=null;handleSlashCommand=null;onPromptStart=null;instanceId;constructor(e){this.state=e.state,this.transport=e.transport,this.config=e.config,this.logger=e.logger,this.writeObs=e.writeObs,this.getGateway=e.getGateway,this.instanceId=e.instanceId||"unknown",this.thirdPartyChannels=e.thirdPartyChannels??new Set}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)}async handleRequest(e){this.writeObs({component:"bridge-core",domain:"forward",name:`rpc.request.${e.method}`,severity:"debug",payload:{id:e.id,method:e.method}});try{switch(e.method){case"initialize":this.handleInitialize(e);break;case"session/new":await this.handleSessionNew(e);break;case"session/load":await this.handleSessionLoad(e);break;case"session/list":await this.handleSessionList(e);break;case"session/rename":this.handleSessionRename(e);break;case"session/delete":await this.handleSessionDelete(e);break;case"session/clear":await this.handleSessionClear(e);break;case"session/prompt":await this.handleSessionPrompt(e);break;case"session/set_mode":await this.handleSessionSetMode(e);break;case"session/set_model":await this.handleSessionSetModel(e);break;case"skills/list":await this.handleSkillsList(e);break;case"models/list":await this.handleModelsList(e);break;case"session/cancel":this.handleSessionCancel(e.id,e.params);break;case"cron/list":case"cron/status":case"cron/add":case"cron/update":case"cron/remove":case"cron/run":case"cron/runs":await this.handleCronRequest(e);break;default:e.method.startsWith("terminal/")&&this.handleTerminalRequest?await this.handleTerminalRequest(e):this.transport.sendAcpError(e.id,Errors.MethodNotFound,{message:`Method not found: ${e.method}`})}}catch(s){this.transport.sendAcpError(e.id,Errors.InternalError,{message:s instanceof Error?s.message:"Internal error"})}}handleCanvasNotification=null;getCanvasState=null;onSessionLoaded=null;onSessionDeleted=null;onSessionCleared=null;handleNotification(e){switch(e.method){case"session/cancel":this.handleSessionCancel(void 0,e.params);break;case"canvas/toggle":case"canvas/clear":this.handleCanvasNotification?this.handleCanvasNotification(e.method,e.params):this.logger.debug?.(`[bridge-core] Canvas notification ignored (canvas disabled): ${e.method}`);break;case"canvas/reference":{const s=e.params,t=s?.surfaceId,n=this.state.resolveSessionFromParams(s);if(!n){this.logger.warn?.(`[bridge-core] canvas/reference ignored — no session found for sessionId=${s?.sessionId}`);break}n.referencedSurfaceId=t||void 0,this.logger.debug?.(`[bridge-core] Canvas reference ${t?"set":"cleared"}: ${t??"(none)"}`);break}default:e.method.startsWith("terminal/")&&this.handleTerminalNotification?this.handleTerminalNotification(e.method,e.params):this.logger.debug?.(`[bridge-core] Unknown notification: ${e.method}`)}}handleInitialize(e){this.initialized=!0;const s=this.transport.forwardControl;!1===e.params?.forwardThinking&&(s.forwardThinking=!1),!1===e.params?.forwardToolCalls&&(s.forwardToolCalls=!1),this.transport.sendResult(e.id,{protocolVersion:ACP_PROTOCOL_VERSION,agentCapabilities:{loadSession:!0,skills:!0,promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},sessionCapabilities:{list:{},"web-ssh":!!this.config.bridge.shell.enabled,canvas:!!this.config.canvasEnabled,cron:!0},mcp:{}},agentInfo:{name:"beeos-claw",title:"BeeOS Agent Bridge",version:"0.1.0"},_meta:{},authMethods:[]})}async handleSessionNew(e){const s=`agent:${"string"==typeof e.params?.agentId&&e.params.agentId||this.config.gateway.agentId||this.getDefaultAgentId()}:${randomUUID()}`,t="string"==typeof e.params?.cwd?e.params.cwd:".",n=createSessionObject({gatewayKey:s,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,cwd:t});this.registerSession(n),this.transport.sendResult(e.id,{sessionId:n.sessionId,modes:{availableModes:[{...DEFAULT_MODE}],currentModeId:DEFAULT_MODE.id},_meta:{sessionKey:s,agentId:n.agentId,platformAgentId:n.platformAgentId??null}}),this.fetchHistoryInBackground(s)}fetchHistoryInBackground(e){const s=this.getGateway();s?.isConnected&&loadHistory(s,e,50).catch(e=>{this.logger.debug?.(`[bridge-core] Background history fetch failed: ${e instanceof Error?e.message:e}`)})}async recoverSessionFromGateway(e){const s=this.getGateway();if(s?.isConnected)try{const t=await s.sessionsList();if(!t||"object"!=typeof t)return;const n=t.sessions;if(!Array.isArray(n))return;for(const s of n){const t=s,n=t.sessionKey??t.key??t.id??t.name;if(n&&"string"==typeof n&&deriveSessionId(n,this.instanceId)===e){const e=createSessionObject({gatewayKey:n,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels});return this.registerSession(e),e}}}catch(e){this.logger.debug?.("[bridge-core] recoverSessionFromGateway failed:",e)}}async resolveOrCreateSession(e){let s=this.state.sessions.get(e);if(!s&&e.startsWith("agent:")&&(s=this.state.findSessionByKey(e)),s||e.startsWith("agent:")||(s=await this.recoverSessionFromGateway(e)),s)return{session:s,created:!1};const t=e.startsWith("agent:"),n=this.config.gateway.agentId||this.getDefaultAgentId();return s=createSessionObject({gatewayKey:t?e:`agent:${n}:${e}`,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels}),this.registerSession(s),{session:s,created:!0}}async handleSessionLoad(e){const s=e.params?.sessionId;if(!s)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const{session:t}=await this.resolveOrCreateSession(s),n=t.sessionId;this.state.lastActiveSessionId=n,t.chatReplayDedupKeys.clear();try{const e=this.getGateway(),s=await loadHistory(e,t.gatewaySessionKey,50),i=groupIntoTurns(s),o=i.filter(e=>"user"===e.role).length,a=i.filter(e=>"assistant"===e.role).length,r=i.filter(e=>e.toolCalls?.length).length,d=i.reduce((e,s)=>e+(s.toolCalls?.length??0),0);this.logger.debug?.(`[bridge-core] handleSessionLoad sid=${n} messages=${s.length} turns=${i.length} userTurns=${o} asstTurns=${a} turnsWithToolCalls=${r} totalToolCalls=${d}`);for(let e=0;e<i.length;e++){const s=i[e];if("user"===s.role&&"internal_system"===s.provenance?.kind){this.logger.debug?.(`[bridge-core] SKIP history_turn[${e}] internal_system user message`);continue}if("system"===s.role){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});continue}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}`);const t={sessionUpdate:"history_turn",role:s.role,content:s.content,reasoning:s.reasoning,toolCalls:s.toolCalls};s.metadata&&(t.metadata=s.metadata),this.transport.sendSessionUpdate(n,t)}}catch(e){this.logger.warn?.("[bridge-core] Failed to load session history:",e)}this.transport.sendResult(e.id,{sessionId:n}),this.onSessionLoaded?.(n,t.gatewaySessionKey,t.platformAgentId);void 0!==t.pendingPromptId&&!t.promptDone&&t.assistantMq&&!t.assistantMq.closed&&this.replayCurrentAssistantStream(t).catch(e=>{this.logger.warn?.(`[bridge-core] replayCurrentAssistantStream failed: ${e instanceof Error?e.message:e}`)}),this.pushSkillsList().catch(e=>{this.logger.warn?.(`[bridge-core] pushSkillsList failed: ${e instanceof Error?e.message:e}`)})}async replayCurrentAssistantStream(e){if(!e.assistantMq||e.assistantMq.closed)return;const s=this.config.loadReplayIdleTimeoutMs??DEFAULT_LOAD_REPLAY_IDLE_TIMEOUT_MS,t=Date.now()+DEFAULT_LOAD_REPLAY_HARD_TIMEOUT_MS;let n=0;for(;Date.now()<t&&(e.currentRunId||e.pendingPromptId)&&!e.assistantMq.closed;){const t=await Promise.race([e.assistantMq.read(n),new Promise(e=>setTimeout(()=>e(null),s))]);if(!t||0===t.length){if(void 0!==e.pendingPromptId&&!e.promptDone)continue;break}for(const s of t)this.transport.sendSessionUpdate(e.sessionId,s),n++}n>0&&this.writeObs({component:"bridge-core",domain:"lifecycle",name:"session.load.replay_complete",severity:"debug",payload:{sessionId:e.sessionId,replayed:n}})}async handleSessionList(e){const s=[];for(const[,e]of this.state.sessions)s.push({sessionId:e.sessionId,title:e.title||"New chat",cwd:e.cwd,updatedAt:e.lastStreamActivityTs??e.createdAt,agentId:e.agentId,platformAgentId:e.platformAgentId,deletable:!isSystemDefaultSessionKey(e.gatewaySessionKey)});const t=this.getGateway();if(t?.isConnected)try{const e=await t.sessionsList();if(e&&"object"==typeof e&&Array.isArray(e.sessions)){const t=e.sessions;for(const e of t){const t=e,n=t.sessionKey??t.key??t.id??t.name;if(!n||"string"!=typeof n)continue;if(isBackgroundSessionKey(n))continue;const i=deriveSessionId(n,this.instanceId),o=s.find(e=>e.sessionId===n||e.sessionId===i||this.state.sessions.get(e.sessionId)?.gatewaySessionKey===n),a=t.label||cleanGatewayDerivedTitle(t.derivedTitle)||t.title||void 0,r=t.model,d=t.modelProvider;if(o){if(!o.title||"New chat"===o.title){const e=a||o.sessionId;o.title=e;const s=this.state.sessions.get(o.sessionId);s&&!s.title&&(s.title=e)}const e=t.updatedAt;e&&(o.updatedAt=e),r&&(o.model=r),d&&(o.modelProvider=d)}else{const e=createSessionObject({gatewayKey:n,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,cwd:t.cwd,title:a||"New chat"});this.registerSession(e),s.push({sessionId:e.sessionId,title:a||"New chat",cwd:t.cwd,updatedAt:t.updatedAt,agentId:e.agentId,platformAgentId:e.platformAgentId,deletable:!isSystemDefaultSessionKey(n),model:r,modelProvider:d})}}}}catch(e){this.logger.debug?.("[bridge-core] sessions.list enrichment failed:",e)}s.sort((e,s)=>(s.updatedAt??0)-(e.updatedAt??0)||e.sessionId.localeCompare(s.sessionId)),this.transport.sendResult(e.id,{sessions:s})}handleSessionRename(e){const s=e.params?.sessionId,t=e.params?.title;if(!s||!t)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId, title"});const n=t.slice(0,64),i=this.state.sessions.get(s);if(!i)return void this.transport.sendAcpError(e.id,Errors.SessionNotFound);i.title=n;const o=i.gatewaySessionKey,a=this.getGateway();a?.isConnected&&a.sessionsPatch(o,{label:n}).catch(e=>{this.logger.debug?.(`[bridge-core] sessionsPatch (rename) failed: ${e instanceof Error?e.message:e}`)}),this.transport.sendResult(e.id,{sessionId:s,title:n})}async handleSessionDelete(e){const s=e.params?.sessionId;if(!s)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const t=this.state.sessions.get(s);if(!t)return this.logger.info?.(`[bridge-core] session/delete sessionId=${s} NOT FOUND in local state`),void this.transport.sendAcpError(e.id,Errors.SessionNotFound);const n=t.gatewaySessionKey;this.logger.info?.(`[bridge-core] session/delete sessionId=${s} gatewayKey=${n} gwConnected=${!!this.getGateway()?.isConnected}`);let i=!1;const o=this.getGateway();if(o?.isConnected&&n)try{await o.sessionsDelete(n),i=!0,this.logger.info?.(`[bridge-core] Gateway sessions.delete SUCCESS for key=${n}`)}catch(s){const t=s instanceof Error?s.message:String(s);if(this.logger.info?.(`[bridge-core] Gateway sessions.delete FAILED for key=${n}: ${t}`),!t.includes("Cannot delete the main session"))return void this.transport.sendResult(e.id,{deleted:!1});try{await o.sessionsReset(n),i=!0,this.logger.info?.(`[bridge-core] Gateway sessions.reset SUCCESS for key=${n}`)}catch(s){return this.logger.warn?.(`[bridge-core] Gateway sessions.reset also failed for key=${n}: ${s instanceof Error?s.message:s}`),void this.transport.sendResult(e.id,{deleted:!1})}}else n&&this.logger.warn?.(`[bridge-core] Gateway not connected, proceeding with local-only delete for key=${n}`);void 0!==t.pendingPromptId&&this.failPrompt(t,Errors.SessionDeleted.rpcCode,Errors.SessionDeleted.message),this.state.clearPromptTimeout(t),this.state.clearStreamIdleTimer(t),t.assistantMq?.close(),t.currentRunId&&this.state.promptsByRunId.delete(t.currentRunId);const a=new Set;for(const[e,t]of this.state.toolCallToSessionMap)t===s&&(this.state.toolCallToSessionMap.delete(e),a.add(e));for(const[e,s]of this.state.toolCallIdMap)a.has(s)&&this.state.toolCallIdMap.delete(e);this.state.sessions.delete(s),this.state.sessionsByGatewayKey.delete(n),this.transport.resetSessionUpdateCount(s),i&&this.onSessionDeleted?.(n),this.logger.info?.(`[bridge-core] session/delete DONE sessionId=${s} gatewayKey=${n} deleted=true`),this.transport.sendResult(e.id,{deleted:!0})}async handleSessionClear(e){this.logger.info?.(`[bridge-core] handleSessionClear called, params=${JSON.stringify(e.params)}`);const s=e.params?.sessionId;if(!s)return this.logger.warn?.("[bridge-core] session/clear missing sessionId"),void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const t=this.state.sessions.get(s);if(!t)return this.logger.warn?.(`[bridge-core] session/clear sessionId=${s} not found in state`),void this.transport.sendAcpError(e.id,Errors.SessionNotFound);this.logger.info?.(`[bridge-core] session/clear sessionId=${s} gatewayKey=${t.gatewaySessionKey}`);const n=this.getGateway();if(n?.isConnected&&t.gatewaySessionKey)try{await n.sessionsReset(t.gatewaySessionKey),this.logger.info?.(`[bridge-core] Gateway sessions.reset SUCCESS for key=${t.gatewaySessionKey}`)}catch(e){this.logger.warn?.(`[bridge-core] Gateway sessions.reset FAILED for key=${t.gatewaySessionKey}: ${e instanceof Error?e.message:e}`)}else this.logger.warn?.(`[bridge-core] session/clear skipped gateway reset: connected=${n?.isConnected}, key=${t.gatewaySessionKey}`);t.chatReplayDedupKeys.clear(),this.logger.info?.("[bridge-core] session/clear dedupKeys cleared, calling onSessionCleared"),this.onSessionCleared?.(s,t.gatewaySessionKey),this.transport.sendResult(e.id,{cleared:!0}),this.logger.info?.("[bridge-core] session/clear DONE, sent cleared=true")}async handleSessionSetMode(e){const s=e.params?.sessionId,t=e.params?.mode,n=s?this.state.sessions.get(s):void 0,i=this.getGateway();if(n&&i?.isConnected&&t){const e={};if("verbose"===t||"detailed"===t?e.verboseLevel="full":"concise"!==t&&"default"!==t||(e.verboseLevel="default"),"reasoning"!==t&&"thinking"!==t||(e.reasoningLevel="stream"),Object.keys(e).length>0)try{await i.sessionsPatch(n.gatewaySessionKey,e)}catch(e){this.logger.warn?.(`[bridge-core] sessions.patch failed: ${e instanceof Error?e.message:e}`)}}this.transport.sendResult(e.id,{mode:t??"default"})}async handleSessionSetModel(e){const s=e.params?.sessionId,t=e.params?.model,n=s?this.state.sessions.get(s):void 0,i=this.getGateway();let o=t??null,a=null;if(n&&i?.isConnected&&t)try{const e=await i.sessionsPatch(n.gatewaySessionKey,{model:t}),s=e?.resolved;s?.model&&(o=s.model),s?.modelProvider&&(a=s.modelProvider)}catch(e){this.logger.warn?.(`[bridge-core] sessions.patch for model failed: ${e instanceof Error?e.message:e}`)}this.transport.sendResult(e.id,{model:o,modelProvider:a})}async handleModelsList(e){const s=this.getGateway();if(s?.isConnected)try{const t=await s.request("models.list",{});this.transport.sendResult(e.id,t??{models:[]})}catch(s){this.transport.sendAcpError(e.id,Errors.InternalError,{message:`Failed to list models: ${s instanceof Error?s.message:s}`})}else this.transport.sendAcpError(e.id,Errors.GatewayNotConnected)}async handleSkillsList(e){const s=await this.fetchSimplifiedSkills();this.transport.sendResult(e.id,{skills:s})}async fetchSimplifiedSkills(){const e=this.getGateway();if(!e?.isConnected)return[];try{const s=await e.skillsStatus();return s?.skills?s.skills.filter(e=>!1!==e.eligible&&!0!==e.disabled).sort((e,s)=>e.always&&!s.always?-1:!e.always&&s.always?1:e.name.localeCompare(s.name)).map(e=>({name:e.name,description:e.description,emoji:e.emoji,always:e.always||void 0,bundled:e.bundled||void 0})):[]}catch(e){return this.logger.warn?.(`[bridge-core] Failed to fetch skills: ${e instanceof Error?e.message:e}`),[]}}async pushSkillsList(){const e=await this.fetchSimplifiedSkills();this.transport.sendNotification("session/update",{sessionId:"_system",update:{sessionUpdate:"available_commands_update",commands:e}}),this.writeObs({component:"bridge-core",domain:"lifecycle",name:"skills.pushed",severity:"debug",payload:{count:e.length}})}async handleSessionPrompt(e){const s=e.params?.sessionId,t=e.params?.prompt;if(!s||!t)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId, prompt"});const{session:n,created:i}=await this.resolveOrCreateSession(s);i&&this.onSessionLoaded?.(n.sessionId,n.gatewaySessionKey,n.platformAgentId);const o=n.sessionId;this.state.lastActiveSessionId=o,this.onPromptStart?.();const a=this.getGateway();if(!a?.isConnected)return void this.transport.sendAcpError(e.id,Errors.GatewayNotConnected);let r=extractPromptBlocks(sanitizePromptPayload(t));if(!n.title){const e=r.find(e=>"text"===e.type&&e.text);e&&"text"in e&&e.text&&(n.title=e.text.slice(0,64).replace(/\n/g," ").trim(),a?.isConnected&&n.title&&a.sessionsPatch(n.gatewaySessionKey,{label:n.title}).catch(e=>{this.logger.debug?.(`[bridge-core] sessionsPatch (title) failed: ${e instanceof Error?e.message:e}`)}))}const d=buildResolutionPlan(r);if(d.refs.length>0)try{const e=await resolveResources(d,this.writeObs);r=applyResolutions(r,e)}catch(e){this.logger.warn?.(`[bridge-core] Resource pre-resolution failed: ${e instanceof Error?e.message:e}`)}const l=toGatewayPrompt(r);if("error"in l)return void this.transport.sendAcpError(e.id,Errors.PromptConvertFailed,{message:l.error});const{message:c,attachments:h}=l,m=resolveStandaloneSlashCommandName(r,c)??resolveSlashCmd(r,c),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(o,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Loading ${m}...`}}),void this.transport.sendResult(e.id,{stopReason:"end_turn"})}const p=g?"chat.send":"agent";let u=g?c:withUserMessagePrefix(c);const f=this.config.canvasEnabled&&!g&&!1!==n.canvasActive&&!n.channelType;if(f){const e=n.promptsSinceCanvasInjection??0;!n.canvasPromptInjected||e>=10?(u=`${CANVAS_TERM_MAPPING}\n\n${u}`,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);u=`${buildActiveSurfacesContext(e,s)??"[Canvas] Canvas panel is available. Use render_ui for structured/visual content."}\n\n${u}`}const s=n.referencedSurfaceId;s&&(u=`${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${u}`,n.referencedSurfaceId=void 0)}if(!g){const s=parseMentionsParam(e.params?.mentions);if(s.length>0){n.activeMentions=s;u=`${buildMentionInstruction(s)}\n${u}`,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=${o} command=/${m}`),this.state.resetForNewRun(n,o,this.transport),n.pendingPromptId=e.id,n.gatewayMethod=p,this.emitPromptAsUserSessionUpdates(o,r),this.transport.sendSessionUpdate(o,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:""}}),this.schedulePromptTimeout(n);try{const e=h.length>0?h.map(e=>({type:e.type,content:e.content,...e.mimeType?{mimeType:e.mimeType}:{},...e.fileName?{fileName:e.fileName}:{}})):void 0;let s;s=g?await a.chatSend(n.gatewaySessionKey,u,e):await a.agentSend(n.gatewaySessionKey,u,n.agentId||this.config.gateway.agentId||this.getDefaultAgentId(),e),n.currentRunId=s.runId,n.assistantStreamStartedAt=Date.now(),this.state.promptsByRunId.set(s.runId,n)}catch(s){this.state.clearPromptTimeout(n),void 0!==n.pendingPromptId&&(n.pendingPromptId=void 0,n.assistantMq?.close(),this.transport.sendAcpError(e.id,Errors.SendFailed,{message:s instanceof Error?s.message:"failed to send prompt to gateway"})),n.pendingAgentSends?.length&&(this.logger.warn?.("[bridge-core] Discarding %d deferred agentSends after prompt send failure",n.pendingAgentSends.length),n.pendingAgentSends=void 0)}}emitPromptAsUserSessionUpdates(e,s){for(const t of s){const s=this.toUserSessionUpdateContent(t);s&&this.transport.sendSessionUpdate(e,{sessionUpdate:"user_message_chunk",content:s})}}toUserSessionUpdateContent(e){if("text"===e.type){if(!e.text)return;return{type:"text",text:e.text}}if("image"===e.type){const s=e.mimeType??e.mime_type??"application/octet-stream",t=e.fileName??e.file_name??e.name;if(!e.data&&!e.uri)return;return{type:"image",...e.data?{data:e.data}:{},...e.uri?{uri:e.uri}:{},...s?{mimeType:s}:{},...t?{fileName:t}:{}}}if("resource_link"===e.type){if(!e.uri)return;return{type:"resource_link",uri:e.uri,...e.title?{title:e.title}:{},...e.name?{name:e.name}:{},...e.mimeType??e.mime_type?{mimeType:e.mimeType??e.mime_type}:{}}}if("file"===e.type){const s=e.mimeType??e.mime_type??"application/octet-stream",t=e.fileName??e.file_name??e.filename??e.name;if(!e.data&&!e.text&&!e.uri)return;return{type:"file",...e.data?{data:e.data}:{},...e.text?{text:e.text}:{},...e.uri?{uri:e.uri}:{},...s?{mimeType:s}:{},...t?{fileName:t}:{}}}if("resource"===e.type){const s=e.resource??{},t=s.uri??e.uri,n=s.mimeType??s.mime_type??e.mimeType??e.mime_type,i=s.text??e.text,o=s.data??e.data,a=s.fileName??s.file_name??s.filename??s.name??e.fileName??e.file_name??e.filename??e.name;if(!t&&!i&&!o)return;return{type:"resource",resource:{...t?{uri:t}:{},...n?{mimeType:n}:{},...i?{text:i}:{},...o?{data:o}:{},...a?{fileName:a}:{}}}}}handleSessionCancel(e,s){const t=s?.sessionId;if(!t)return void(void 0!==e&&this.transport.sendAcpError(e,Errors.MissingParam,{param:"sessionId"}));const n=this.state.sessions.get(t);if(!n)return void(void 0!==e&&this.transport.sendAcpError(e,Errors.SessionNotFound));const i=this.getGateway();i?.isConnected&&n.currentRunId&&i.chatAbort(n.gatewaySessionKey,n.currentRunId).catch(e=>{this.logger.debug?.(`[bridge-core] chatAbort failed: ${e instanceof Error?e.message:e}`)}),this.completePrompt(n,"cancelled"),void 0!==e&&this.transport.sendResult(e,{})}schedulePromptTimeout(e){this.state.clearPromptTimeout(e);const s=this.config.promptTimeoutMs??DEFAULT_PROMPT_TIMEOUT_MS;s<=0||(e.promptTimeoutTimer=setTimeout(()=>{void 0!==e.pendingPromptId&&(this.logger.warn?.(`[bridge-core] Prompt timed out sessionId=${e.sessionId} after ${s}ms`),this.failPrompt(e,Errors.PromptTimeout.rpcCode,`Prompt timed out after ${s}ms`))},s),"object"==typeof e.promptTimeoutTimer&&"unref"in e.promptTimeoutTimer&&e.promptTimeoutTimer.unref())}cleanupPrompt(e){this.state.clearPromptTimeout(e),this.state.clearStreamIdleTimer(e);const s=e.currentRunId;if(s){this.state.promptsByRunId.delete(s);const e=`tc_${s}_`;for(const[s,t]of this.state.toolCallIdMap)t.startsWith(e)&&this.state.toolCallIdMap.delete(s)}e.pendingPromptId=void 0,e.promptDone=void 0,e.currentRunId=void 0,e.assistantStreamStartedAt=void 0,e.gatewayMethod=void 0,e.assistantMq?.close()}completePrompt(e,s){if(e.promptDone)return;if(void 0===e.pendingPromptId&&void 0===e.currentRunId)return;e.promptDone=!0;const t=e.currentRunId;if(t&&this.onRunComplete){const s=e.agentAssistantTextSoFar??e.chatAssistantTextSoFar??"";this.onRunComplete(t,s)}void 0!==e.pendingPromptId&&this.transport.sendResult(e.pendingPromptId,{stopReason:s}),this.cleanupPrompt(e)}failPrompt(e,s,t){if(e.promptDone)return;if(void 0===e.pendingPromptId&&void 0===e.currentRunId)return;e.promptDone=!0;const n=e.currentRunId;n&&this.onRunFailed&&this.onRunFailed(n,t),void 0!==e.pendingPromptId&&this.transport.sendError(e.pendingPromptId,s,t),this.cleanupPrompt(e)}cleanupAllPendingPrompts(){for(const e of this.state.sessions.values())this.failPrompt(e,Errors.GatewayDisconnected.rpcCode,Errors.GatewayDisconnected.message)}maybeCompletePromptFromChatState(e,s){if(e.promptDone||"chat.send"!==e.gatewayMethod)return;const t="string"==typeof s.state?s.state.toLowerCase():void 0;if(t)if("final"===t)this.completePrompt(e,"end_turn");else if("aborted"===t||"cancelled"===t||"cancel"===t)this.completePrompt(e,"cancelled");else if("error"===t){const t=("string"==typeof s.summary?s.summary:void 0)??("string"==typeof s.message?s.message:void 0)??"gateway chat error";this.failPrompt(e,Errors.AgentError.rpcCode,formatFriendlyError(t))}}pushToolResultContent(e,s,t,n){if(0===t.length)return;const i=(n?this.state.promptsByRunId.get(n):void 0)??(this.state.lastActiveSessionId?this.state.sessions.get(this.state.lastActiveSessionId):void 0);if(!i)return void this.logger.warn?.(`[bridge-core] pushToolResultContent dropped — no session (runId=${n})`);const o=i.sessionId;for(const e of t){const s={sessionUpdate:"agent_message_chunk",content:e};this.transport.sendSessionUpdate(o,s),i.assistantMq?.push(s)}this.writeObs({component:"bridge-core",domain:"tool",name:"tool_result.direct_push",severity:"info",payload:{toolCallId:e,toolName:s,blockCount:t.length,sessionId:o}})}async handleCronRequest(e){const s=this.getGateway();if(!s?.isConnected)return void this.transport.sendAcpError(e.id,Errors.GatewayNotConnected);const t=e.method.replace("/",".");try{const n=await s.request(t,e.params??{});this.transport.sendResult(e.id,n??{})}catch(s){const n=s instanceof Error?s.message:"cron request failed";this.logger.warn?.(`[bridge-core] ${t} failed: ${n}`),this.transport.sendAcpError(e.id,Errors.SendFailed,{message:n})}}}
|
|
1
|
+
import{randomUUID,createHash}from"node:crypto";import{sanitizePromptPayload,stripTransportMetadata}from"../message-filter.js";import{CANVAS_TERM_MAPPING,CANVAS_UPDATE_HINT,buildActiveSurfacesContext}from"../canvas/tools.js";import{parseMentionsParam,buildMentionInstruction}from"../a2a/mention-resolver.js";import{extractPromptBlocks,toGatewayPrompt,resolveSlashCommandName as resolveSlashCmd}from"./prompt-converter.js";import{loadHistory,groupIntoTurns,extractBeeosFileUrisFromOutput,splitUserReplayBlocks}from"./history-replay.js";import{buildResolutionPlan,resolveResources,applyResolutions}from"./prompt-resource-resolver.js";import{readUploadToolResult}from"../upload/result-cache.js";import{BEEOS_UPLOAD_TOOL_NAME}from"../upload/tool.js";import{buildToolResultSessionContentBlocks}from"./tool-result-payload-strategies.js";import{Errors}from"../errors/index.js";import{formatFriendlyError}from"../errors/classify.js";import{resolveChannelFromSessionKey}from"../channel-detection.js";import{ACP_PROTOCOL_VERSION,DEFAULT_PROMPT_TIMEOUT_MS,DEFAULT_LOAD_REPLAY_IDLE_TIMEOUT_MS,DEFAULT_LOAD_REPLAY_HARD_TIMEOUT_MS}from"./types.js";const DEFAULT_MODE={id:"default",name:"Default",description:"Default agent mode"},USER_MESSAGE_PREFIX="User Message From BeeOS:",USER_MESSAGE_PREFIX_WITH_NEWLINE=`${USER_MESSAGE_PREFIX}\n`,SLASH_COMMAND_NAME_RE=/^[a-z0-9_-]+$/i;function withUserMessagePrefix(e){return e.startsWith(USER_MESSAGE_PREFIX)?e:`${USER_MESSAGE_PREFIX_WITH_NEWLINE}${e}`}const BACKGROUND_SESSION_PATTERNS=[":cron:",":hook:","node-"];function isBackgroundSessionKey(e){return BACKGROUND_SESSION_PATTERNS.some(s=>e.includes(s))}function isSystemDefaultSessionKey(e){const s=e.split(":");if(s.length<3||"agent"!==s[0])return!1;const t=s.slice(2).join(":");return"main"===t||t===s[1]}function cleanGatewayDerivedTitle(e){if(!e)return;let s=stripTransportMetadata(e);return/^\[System\b/.test(s)?void 0:(s=s.trim(),s||void 0)}function resolveStandaloneSlashCommandName(e,s){if(0===e.length)return;if(e.some(e=>"text"!==e.type))return;const t=s.trim();if(!t||t.includes("\n")||!t.startsWith("/"))return;const n=t.match(/^\/([^\s:]+)(?::|\s|$)/)?.[1]?.trim();return n&&!n.includes("/")&&SLASH_COMMAND_NAME_RE.test(n)?n.toLowerCase():void 0}function deriveSessionId(e,s){const t=createHash("sha256").update(`${s}:${e}`).digest("hex").substring(0,32);return`session:${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`}function parseAgentIdFromKey(e){const s=e.split(":");return(s.length>=3&&"agent"===s[0]?s[1]:"")||"main"}function createSessionObject(e){const s=parseAgentIdFromKey(e.gatewayKey);return{sessionId:deriveSessionId(e.gatewayKey,e.instanceId),gatewaySessionKey:e.gatewayKey,agentId:s,platformAgentId:e.resolvePlatformAgentId?.(s),createdAt:Date.now(),chatReplayDedupKeys:new Set,cwd:e.cwd,title:e.title,channelType:resolveChannelFromSessionKey(e.gatewayKey,e.thirdPartyChannels)}}export class AcpGatewayBridgeCore{state;transport;config;logger;writeObs;getGateway;thirdPartyChannels;beeosFileResolver;initialized=!1;agentMapping=null;_syncResolvers=[];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=[]}markAgentSyncDone(){for(const e of this._syncResolvers)e();this._syncResolvers=[]}waitForAgentMapping(e=15e3){return this.agentMapping?Promise.resolve():new Promise(s=>{this._syncResolvers.push(s);const t=setTimeout(()=>{const e=this._syncResolvers.indexOf(s);-1!==e&&this._syncResolvers.splice(e,1),s()},e);"object"==typeof t&&"unref"in t&&t.unref()})}handleTerminalRequest=null;handleTerminalNotification=null;onRunComplete=null;onRunFailed=null;handleSlashCommand=null;onPromptStart=null;instanceId;constructor(e){this.state=e.state,this.transport=e.transport,this.config=e.config,this.logger=e.logger,this.writeObs=e.writeObs,this.getGateway=e.getGateway,this.instanceId=e.instanceId||"unknown",this.thirdPartyChannels=e.thirdPartyChannels??new Set,this.beeosFileResolver=e.beeosFileResolver}resolvePlatformAgentId(e){return this.agentMapping?.get(e)?.id}getDefaultAgentId(){return this.agentMapping&&this.agentMapping.size>0?this.agentMapping.keys().next().value??"main":"main"}registerSession(e){this.state.sessions.set(e.sessionId,e),this.state.sessionsByGatewayKey.set(e.gatewaySessionKey,e)}async handleRequest(e){this.writeObs({component:"bridge-core",domain:"forward",name:`rpc.request.${e.method}`,severity:"debug",payload:{id:e.id,method:e.method}});try{switch(e.method){case"initialize":this.handleInitialize(e);break;case"session/new":await this.handleSessionNew(e);break;case"session/load":await this.handleSessionLoad(e);break;case"session/list":await this.handleSessionList(e);break;case"session/rename":this.handleSessionRename(e);break;case"session/delete":await this.handleSessionDelete(e);break;case"session/clear":await this.handleSessionClear(e);break;case"session/prompt":await this.handleSessionPrompt(e);break;case"session/set_mode":await this.handleSessionSetMode(e);break;case"session/set_model":await this.handleSessionSetModel(e);break;case"skills/list":await this.handleSkillsList(e);break;case"models/list":await this.handleModelsList(e);break;case"session/cancel":this.handleSessionCancel(e.id,e.params);break;case"cron/list":case"cron/status":case"cron/add":case"cron/update":case"cron/remove":case"cron/run":case"cron/runs":await this.handleCronRequest(e);break;default:e.method.startsWith("terminal/")&&this.handleTerminalRequest?await this.handleTerminalRequest(e):this.transport.sendAcpError(e.id,Errors.MethodNotFound,{message:`Method not found: ${e.method}`})}}catch(s){this.transport.sendAcpError(e.id,Errors.InternalError,{message:s instanceof Error?s.message:"Internal error"})}}handleCanvasNotification=null;getCanvasState=null;onSessionLoaded=null;onSessionDeleted=null;onSessionCleared=null;handleNotification(e){switch(e.method){case"session/cancel":this.handleSessionCancel(void 0,e.params);break;case"canvas/toggle":case"canvas/clear":this.handleCanvasNotification?this.handleCanvasNotification(e.method,e.params):this.logger.debug?.(`[bridge-core] Canvas notification ignored (canvas disabled): ${e.method}`);break;case"canvas/reference":{const s=e.params,t=s?.surfaceId,n=this.state.resolveSessionFromParams(s);if(!n){this.logger.warn?.(`[bridge-core] canvas/reference ignored — no session found for sessionId=${s?.sessionId}`);break}n.referencedSurfaceId=t||void 0,this.logger.debug?.(`[bridge-core] Canvas reference ${t?"set":"cleared"}: ${t??"(none)"}`);break}default:e.method.startsWith("terminal/")&&this.handleTerminalNotification?this.handleTerminalNotification(e.method,e.params):this.logger.debug?.(`[bridge-core] Unknown notification: ${e.method}`)}}handleInitialize(e){this.initialized=!0;const s=this.transport.forwardControl;!1===e.params?.forwardThinking&&(s.forwardThinking=!1),!1===e.params?.forwardToolCalls&&(s.forwardToolCalls=!1),this.transport.sendResult(e.id,{protocolVersion:ACP_PROTOCOL_VERSION,agentCapabilities:{loadSession:!0,skills:!0,promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},sessionCapabilities:{list:{},"web-ssh":!!this.config.bridge.shell.enabled,canvas:!!this.config.canvasEnabled,cron:!0},mcp:{}},agentInfo:{name:"beeos-claw",title:"BeeOS Agent Bridge",version:"0.1.0"},_meta:{},authMethods:[]})}async handleSessionNew(e){const s=`agent:${"string"==typeof e.params?.agentId&&e.params.agentId||this.config.gateway.agentId||this.getDefaultAgentId()}:${randomUUID()}`,t="string"==typeof e.params?.cwd?e.params.cwd:".",n=createSessionObject({gatewayKey:s,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels,cwd:t});this.registerSession(n),this.transport.sendResult(e.id,{sessionId:n.sessionId,modes:{availableModes:[{...DEFAULT_MODE}],currentModeId:DEFAULT_MODE.id},_meta:{sessionKey:s,agentId:n.agentId,platformAgentId:n.platformAgentId??null}}),this.fetchHistoryInBackground(s)}fetchHistoryInBackground(e){const s=this.getGateway();s?.isConnected&&loadHistory(s,e,50).catch(e=>{this.logger.debug?.(`[bridge-core] Background history fetch failed: ${e instanceof Error?e.message:e}`)})}async recoverSessionFromGateway(e){const s=this.getGateway();if(s?.isConnected)try{const t=await s.sessionsList();if(!t||"object"!=typeof t)return;const n=t.sessions;if(!Array.isArray(n))return;for(const s of n){const t=s,n=t.sessionKey??t.key??t.id??t.name;if(n&&"string"==typeof n&&deriveSessionId(n,this.instanceId)===e){const e=createSessionObject({gatewayKey:n,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels});return this.registerSession(e),e}}}catch(e){this.logger.debug?.("[bridge-core] recoverSessionFromGateway failed:",e)}}async resolveOrCreateSession(e){let s=this.state.sessions.get(e);if(!s&&e.startsWith("agent:")&&(s=this.state.findSessionByKey(e)),s||e.startsWith("agent:")||(s=await this.recoverSessionFromGateway(e)),s)return{session:s,created:!1};const t=e.startsWith("agent:"),n=this.config.gateway.agentId||this.getDefaultAgentId();return s=createSessionObject({gatewayKey:t?e:`agent:${n}:${e}`,instanceId:this.instanceId,resolvePlatformAgentId:e=>this.resolvePlatformAgentId(e),thirdPartyChannels:this.thirdPartyChannels}),this.registerSession(s),{session:s,created:!0}}async handleSessionLoad(e){const s=e.params?.sessionId;if(!s)return void this.transport.sendAcpError(e.id,Errors.MissingParam,{param:"sessionId"});const{session:t}=await this.resolveOrCreateSession(s),n=t.sessionId;this.state.lastActiveSessionId=n,t.chatReplayDedupKeys.clear();try{const e=this.getGateway(),s=await loadHistory(e,t.gatewaySessionKey,50),o=groupIntoTurns(s),i=o.filter(e=>"user"===e.role).length,r=o.filter(e=>"assistant"===e.role).length,a=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=${r} turnsWithToolCalls=${a} 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 o=()=>{this.transport.sendResult(e.id,{sessionId:n}),this.onSessionLoaded?.(n,t.gatewaySessionKey,t.platformAgentId),this.pushSkillsList().catch(e=>{this.logger.warn?.(`[bridge-core] pushSkillsList failed: ${e instanceof Error?e.message:e}`)})};void 0!==t.pendingPromptId&&!t.promptDone&&t.assistantMq&&!t.assistantMq.closed?this.replayCurrentAssistantStream(t).catch(e=>{this.logger.warn?.(`[bridge-core] replayCurrentAssistantStream failed: ${e instanceof Error?e.message:e}`)}).finally(o):o()}async replayUploadFileBlocks(e,s){for(const t of s){if(t.name!==BEEOS_UPLOAD_TOOL_NAME)continue;let s=[];try{const e=await readUploadToolResult(t.id);e&&(s=buildToolResultSessionContentBlocks(t.name,e))}catch{}if(0===s.length){const e=extractBeeosFileUrisFromOutput(t.output);for(const t of e)s.push({type:"content",content:{type:"resource_link",uri:t,name:"file"}})}const n=s.filter(e=>"resource_link"===e.content?.type);for(const s of n)this.transport.sendSessionUpdate(e,{sessionUpdate:"agent_message_chunk",content:s.content});n.length>0&&this.logger.debug?.(`[bridge-core] replayUploadFileBlocks tcId=${t.id} sent ${n.length} resource_link block(s)`)}}async replayCurrentAssistantStream(e){if(!e.assistantMq||e.assistantMq.closed)return;const s=this.config.loadReplayIdleTimeoutMs??DEFAULT_LOAD_REPLAY_IDLE_TIMEOUT_MS,t=Date.now()+DEFAULT_LOAD_REPLAY_HARD_TIMEOUT_MS;let n=0;for(;Date.now()<t&&(e.currentRunId||e.pendingPromptId)&&!e.assistantMq.closed;){const t=await Promise.race([e.assistantMq.read(n),new Promise(e=>setTimeout(()=>e(null),s))]);if(!t||0===t.length){if(void 0!==e.pendingPromptId&&!e.promptDone)continue;break}for(const s of t)this.transport.sendSessionUpdate(e.sessionId,s),n++}n>0&&this.writeObs({component:"bridge-core",domain:"lifecycle",name:"session.load.replay_complete",severity:"debug",payload:{sessionId:e.sessionId,replayed:n}})}async handleSessionList(e){const s=[];for(const[,e]of this.state.sessions)s.push({sessionId:e.sessionId,title:e.title||"New chat",cwd:e.cwd,updatedAt:e.lastStreamActivityTs??e.createdAt,agentId:e.agentId,platformAgentId:e.platformAgentId,deletable:!isSystemDefaultSessionKey(e.gatewaySessionKey)});const t=this.getGateway();if(t?.isConnected)try{const e=await t.sessionsList();if(e&&"object"==typeof e&&Array.isArray(e.sessions)){const t=e.sessions;for(const e of t){const t=e,n=t.sessionKey??t.key??t.id??t.name;if(!n||"string"!=typeof n)continue;if(isBackgroundSessionKey(n))continue;const o=deriveSessionId(n,this.instanceId),i=s.find(e=>e.sessionId===n||e.sessionId===o||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(i){if(!i.title||"New chat"===i.title){const e=r||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),a&&(i.model=a),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: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),o=this.state.sessions.get(s);if(!o)return void this.transport.sendAcpError(e.id,Errors.SessionNotFound);o.title=n;const i=o.gatewaySessionKey,r=this.getGateway();r?.isConnected&&r.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 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),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,r=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&&(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:i,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})):[]}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 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:m,attachments:h}=c,p=resolveStandaloneSlashCommandName(a,m)??resolveSlashCmd(a,m),g="string"==typeof p;if(p&&this.handleSlashCommand){const s=this;if(await(async()=>{try{return await s.handleSlashCommand(p)}catch(e){return s.logger.warn?.(`[bridge-core] /${p} handler failed: ${e instanceof Error?e.message:e}`),!1}})())return this.emitPromptAsUserSessionUpdates(n.sessionId,a),this.transport.sendSessionUpdate(i,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Loading ${p}...`}}),void this.transport.sendResult(e.id,{stopReason:"end_turn"})}const u=g?"chat.send":"agent";let f=g?m:withUserMessagePrefix(m);const y=this.config.canvasEnabled&&!g&&!1!==n.canvasActive&&!n.channelType;if(y){const e=n.promptsSinceCanvasInjection??0;!n.canvasPromptInjected||e>=10?(f=`${CANVAS_TERM_MAPPING}\n\n${f}`,n.canvasPromptInjected=!0,n.promptsSinceCanvasInjection=0,this.logger.debug?.("[bridge-core] Canvas term mapping injected (re-inject cycle)")):n.promptsSinceCanvasInjection=e+1}if(y){const e=this.getCanvasState?.();if(e){const s=e.resolveCanvasForSession(n.gatewaySessionKey);f=`${buildActiveSurfacesContext(e,s)??"[Canvas] Canvas panel is available. Use render_ui for structured/visual content."}\n\n${f}`}const s=n.referencedSurfaceId;s&&(f=`${CANVAS_UPDATE_HINT}\n[IMPORTANT: The user selected canvas surface "${s}" for editing. You MUST call render_ui with id="${s}" to UPDATE this existing surface. Do NOT create a new surface with a different id.]\n${f}`,n.referencedSurfaceId=void 0)}if(!g){const s=parseMentionsParam(e.params?.mentions);if(s.length>0){n.activeMentions=s;f=`${buildMentionInstruction(s)}\n${f}`,this.logger.debug?.(`[bridge-core] A2A mention instruction injected for ${s.length} agent(s)`)}else n.activeMentions=void 0}g&&this.logger.info?.(`[bridge-core] slash command passthrough sessionId=${i} command=/${p}`),this.state.resetForNewRun(n,i,this.transport),n.pendingPromptId=e.id,n.gatewayMethod=u,this.emitPromptAsUserSessionUpdates(i,a),this.transport.sendSessionUpdate(i,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:""}}),this.schedulePromptTimeout(n);try{const e=h.length>0?h.map(e=>({type:e.type,content:e.content,...e.mimeType?{mimeType:e.mimeType}:{},...e.fileName?{fileName:e.fileName}:{}})):void 0;let s;s=g?await r.chatSend(n.gatewaySessionKey,f,e):await r.agentSend(n.gatewaySessionKey,f,n.agentId||this.config.gateway.agentId||this.getDefaultAgentId(),e),n.currentRunId=s.runId,n.assistantStreamStartedAt=Date.now(),this.state.promptsByRunId.set(s.runId,n)}catch(s){this.state.clearPromptTimeout(n),void 0!==n.pendingPromptId&&(n.pendingPromptId=void 0,n.assistantMq?.close(),this.transport.sendAcpError(e.id,Errors.SendFailed,{message:s instanceof Error?s.message:"failed to send prompt to gateway"})),n.pendingAgentSends?.length&&(this.logger.warn?.("[bridge-core] Discarding %d deferred agentSends after prompt send failure",n.pendingAgentSends.length),n.pendingAgentSends=void 0)}}replayUserTurnAsChunks(e,s,t){const n=splitUserReplayBlocks(s);for(const s of n){let n;if("text"===s.type){if(!s.text)continue;n={type:"text",text:s.text}}else n="resource_link"===s.type?{type:"resource_link",uri:s.uri??"",...s.fileName?{name:s.fileName}:{},...s.mimeType?{mimeType:s.mimeType}:{}}:{type:s.type,...s.mimeType?{mimeType:s.mimeType}:{},...s.fileName?{fileName:s.fileName}:{}};this.transport.sendSessionUpdate(e,{sessionUpdate:"user_message_chunk",content:n,...t?{metadata:t}:{}})}}emitPromptAsUserSessionUpdates(e,s){for(const t of s){const s=this.toUserSessionUpdateContent(t);s&&this.transport.sendSessionUpdate(e,{sessionUpdate:"user_message_chunk",content:s})}}toUserSessionUpdateContent(e){if("text"===e.type){if(!e.text)return;return{type:"text",text:e.text}}if("image"===e.type){const s=e.mimeType??e.mime_type??"application/octet-stream",t=e.fileName??e.file_name??e.name;if(!e.data&&!e.uri)return;return{type:"image",...e.data?{data:e.data}:{},...e.uri?{uri:e.uri}:{},...s?{mimeType:s}:{},...t?{fileName:t}:{}}}if("resource_link"===e.type){if(!e.uri)return;return{type:"resource_link",uri:e.uri,...e.title?{title:e.title}:{},...e.name?{name:e.name}:{},...e.mimeType??e.mime_type?{mimeType:e.mimeType??e.mime_type}:{}}}if("file"===e.type){const s=e.mimeType??e.mime_type??"application/octet-stream",t=e.fileName??e.file_name??e.filename??e.name;if(!e.data&&!e.text&&!e.uri)return;return{type:"file",...e.data?{data:e.data}:{},...e.text?{text:e.text}:{},...e.uri?{uri:e.uri}:{},...s?{mimeType:s}:{},...t?{fileName:t}:{}}}if("resource"===e.type){const s=e.resource??{},t=s.uri??e.uri,n=s.mimeType??s.mime_type??e.mimeType??e.mime_type,o=s.text??e.text,i=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&&!o&&!i)return;return{type:"resource",resource:{...t?{uri:t}:{},...n?{mimeType:n}:{},...o?{text:o}:{},...i?{data:i}:{},...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 o=this.getGateway();o?.isConnected&&n.currentRunId&&o.chatAbort(n.gatewaySessionKey,n.currentRunId).catch(e=>{this.logger.debug?.(`[bridge-core] chatAbort failed: ${e instanceof Error?e.message:e}`)}),this.completePrompt(n,"cancelled"),void 0!==e&&this.transport.sendResult(e,{})}schedulePromptTimeout(e){this.state.clearPromptTimeout(e);const s=this.config.promptTimeoutMs??DEFAULT_PROMPT_TIMEOUT_MS;s<=0||(e.promptTimeoutTimer=setTimeout(()=>{void 0!==e.pendingPromptId&&(this.logger.warn?.(`[bridge-core] Prompt timed out sessionId=${e.sessionId} after ${s}ms`),this.failPrompt(e,Errors.PromptTimeout.rpcCode,`Prompt timed out after ${s}ms`))},s),"object"==typeof e.promptTimeoutTimer&&"unref"in e.promptTimeoutTimer&&e.promptTimeoutTimer.unref())}cleanupPrompt(e){this.state.clearPromptTimeout(e),this.state.clearStreamIdleTimer(e);const s=e.currentRunId;if(s){this.state.promptsByRunId.delete(s);const e=`tc_${s}_`;for(const[s,t]of this.state.toolCallIdMap)t.startsWith(e)&&this.state.toolCallIdMap.delete(s)}e.pendingPromptId=void 0,e.promptDone=void 0,e.currentRunId=void 0,e.assistantStreamStartedAt=void 0,e.gatewayMethod=void 0,e.assistantMq?.close()}completePrompt(e,s){if(e.promptDone)return;if(void 0===e.pendingPromptId&&void 0===e.currentRunId)return;e.promptDone=!0;const t=e.currentRunId;if(t&&this.onRunComplete){const s=e.agentAssistantTextSoFar??e.chatAssistantTextSoFar??"";this.onRunComplete(t,s)}void 0!==e.pendingPromptId&&this.transport.sendResult(e.pendingPromptId,{stopReason:s}),this.cleanupPrompt(e)}failPrompt(e,s,t){if(e.promptDone)return;if(void 0===e.pendingPromptId&&void 0===e.currentRunId)return;e.promptDone=!0;const n=e.currentRunId;n&&this.onRunFailed&&this.onRunFailed(n,t),void 0!==e.pendingPromptId&&this.transport.sendError(e.pendingPromptId,s,t),this.cleanupPrompt(e)}cleanupAllPendingPrompts(){for(const e of this.state.sessions.values())this.failPrompt(e,Errors.GatewayDisconnected.rpcCode,Errors.GatewayDisconnected.message)}maybeCompletePromptFromChatState(e,s){if(e.promptDone||"chat.send"!==e.gatewayMethod)return;const t="string"==typeof s.state?s.state.toLowerCase():void 0;if(t)if("final"===t)this.completePrompt(e,"end_turn");else if("aborted"===t||"cancelled"===t||"cancel"===t)this.completePrompt(e,"cancelled");else if("error"===t){const t=("string"==typeof s.summary?s.summary:void 0)??("string"==typeof s.message?s.message:void 0)??"gateway chat error";this.failPrompt(e,Errors.AgentError.rpcCode,formatFriendlyError(t))}}pushToolResultContent(e,s,t,n){if(0===t.length)return;const o=(n?this.state.promptsByRunId.get(n):void 0)??(this.state.lastActiveSessionId?this.state.sessions.get(this.state.lastActiveSessionId):void 0);if(!o)return void this.logger.warn?.(`[bridge-core] pushToolResultContent dropped — no session (runId=${n})`);const i=o.sessionId;for(const e of t){const s={sessionUpdate:"agent_message_chunk",content:e};this.transport.sendSessionUpdate(i,s),o.assistantMq?.push(s)}this.writeObs({component:"bridge-core",domain:"tool",name:"tool_result.direct_push",severity:"info",payload:{toolCallId:e,toolName:s,blockCount:t.length,sessionId:i}})}async handleCronRequest(e){const s=this.getGateway();if(!s?.isConnected)return void this.transport.sendAcpError(e.id,Errors.GatewayNotConnected);const t=e.method.replace("/",".");try{const n=await s.request(t,e.params??{});this.transport.sendResult(e.id,n??{})}catch(s){const n=s instanceof Error?s.message:"cron request failed";this.logger.warn?.(`[bridge-core] ${t} failed: ${n}`),this.transport.sendAcpError(e.id,Errors.SendFailed,{message:n})}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{Errors}from"../errors/index.js";import{formatFriendlyError}from"../errors/classify.js";import{stripTransportMetadata}from"../message-filter.js";import{resolveToolResultBlocks}from"./tool-result-payload-strategies.js";import{DEFAULT_STREAM_IDLE_TIMEOUT_MS,DEFAULT_STREAM_STALE_TIMEOUT_MS}from"./types.js";function asString(t){if("string"==typeof t){return t.trim()||void 0}}function isRecord(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function normalizeText(t){if("string"!=typeof t)return;return t.replace(/\r\n/g,"\n").replace(/\r/g,"\n")||void 0}const DEDUP_HASH_THRESHOLD=256;function dedupKey(t,...e){const s=`${t}:${e.join(":")}`;if(s.length<=256)return s;return`${t}:h:${createHash("sha256").update(s).digest("hex").slice(0,24)}`}export class AcpGatewayEvents{state;transport;config;logger;writeObs;completePrompt;failPrompt;maybeCompletePromptFromChatState;agentFetchFn;constructor(t){this.state=t.state,this.transport=t.transport,this.config=t.config,this.logger=t.logger,this.writeObs=t.writeObs,this.completePrompt=t.completePrompt,this.failPrompt=t.failPrompt,this.maybeCompletePromptFromChatState=t.maybeCompletePromptFromChatState,this.agentFetchFn=t.agentFetch}touchStreamActivity(t){t.lastStreamActivityTs=Date.now(),this.resetStreamIdleTimer(t)}resetStreamIdleTimer(t){this.state.clearStreamIdleTimer(t);const e=this.config.streamIdleTimeoutMs??DEFAULT_STREAM_IDLE_TIMEOUT_MS,s=this.config.streamStaleTimeoutMs??DEFAULT_STREAM_STALE_TIMEOUT_MS;t.streamIdleTimer=setTimeout(()=>{if(!t.lastStreamActivityTs)return;const e=Date.now()-t.lastStreamActivityTs;e>s&&(this.logger.warn?.(`[gateway-events] Stream stale timeout sessionId=${t.sessionId} stale=${e}ms`),this.completePrompt(t,"end_turn"))},e),"object"==typeof t.streamIdleTimer&&"unref"in t.streamIdleTimer&&t.streamIdleTimer.unref()}sendToolCallSpacer(t){const e={sessionUpdate:"agent_message_chunk",content:{type:"text",text:"\n"}};this.transport.sendSessionUpdate(t.sessionId,e),t.assistantMq?.push(e)}resolveToolCallId(t,e,s){const n=asString(e.toolCallId)??asString(e.tool_call_id)??asString(e.callId)??asString(e.id);if(n){const e=this.state.toolCallIdMap.get(n);return e?(t.sessionId&&this.state.toolCallToSessionMap.set(e,t.sessionId),e):(this.state.toolCallIdMap.set(n,n),t.sessionId&&this.state.toolCallToSessionMap.set(n,t.sessionId),n)}const o=`tc_${t.currentRunId??"unknown"}_${this.state.nextToolCallSeq++}`;return t.sessionId&&this.state.toolCallToSessionMap.set(o,t.sessionId),o}handleChatEvent(t){const e=(t.runId?this.state.promptsByRunId.get(t.runId):void 0)??this.state.findSessionByKey(t.sessionKey);if(!e)return;if(!this.state.isCurrentStreamOwner(e,t.runId)){if(!t.runId||!1===e.promptDone)return;this.adoptBackgroundRun(e,t.runId)}if("number"==typeof t.seq){if(t.seq<=(e.lastChatSeq??-1))return void this.logger.debug?.(`[gateway-events] Dropping duplicate chat event seq=${t.seq} (last=${e.lastChatSeq}) runId=${t.runId}`);e.lastChatSeq=t.seq}const s=e.sessionId,n=t.message;if(n){this.touchStreamActivity(e);if("assistant"===n.role){if(!Array.isArray(n.content))return;for(const o of n.content){const n=o;if(!isRecord(n))continue;const a=asString(n.type);if(a){if("thinking"===a){if(e.hasAgentThinkingStream)continue;const t=normalizeText(n.thinking)??normalizeText(n.text);if(!t)continue;const o=dedupKey("chat:thinking",t);if(e.chatReplayDedupKeys.has(o))continue;e.chatReplayDedupKeys.add(o);const a={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:t}};this.transport.sendSessionUpdate(s,a)&&e.assistantMq?.push(a);continue}if("toolCall"===a){if(this.sendToolCallSpacer(e),e.hasAgentToolStartStream)continue;const t=this.resolveToolCallId(e,n,"start"),o=asString(n.name)??asString(n.toolName)??asString(n.tool_name)??"tool",a=isRecord(n.arguments)?n.arguments:isRecord(n.args)?n.args:{},r=dedupKey("chat:tool_start",t,JSON.stringify(a));if(e.chatReplayDedupKeys.has(r))continue;e.chatReplayDedupKeys.add(r);const i={sessionUpdate:"tool_call",toolCallId:t,title:o,status:"in_progress",content:[{type:"content",content:{type:"text",text:JSON.stringify(a,null,2)}}]};this.transport.sendSessionUpdate(s,i)&&e.assistantMq?.push(i);continue}if("toolResult"===a){if(this.sendToolCallSpacer(e),e.hasAgentToolResultStream)continue;const t=this.resolveToolCallId(e,n,"result"),o=asString(n.name)??asString(n.toolName)??asString(n.tool_name)??"tool",a=normalizeText(n.text)??normalizeText(n.result)??(isRecord(n.result)||Array.isArray(n.result)?JSON.stringify(n.result,null,2):void 0);if(!a)continue;const r=dedupKey("chat:tool_result",t,a);if(e.chatReplayDedupKeys.has(r))continue;e.chatReplayDedupKeys.add(r);const i={sessionUpdate:"tool_call_update",toolCallId:t,title:o,status:"completed",content:[{type:"content",content:{type:"text",text:a}}]};this.transport.sendSessionUpdate(s,i)&&e.assistantMq?.push(i);continue}if("text"===a&&n.text){if(e.hasAgentAssistantStream||e.agentAssistantTextSoFar)continue;const o=stripTransportMetadata(n.text);if(!o)continue;const a=dedupKey("chat:text",o);if(e.chatReplayDedupKeys.has(a))continue;e.chatReplayDedupKeys.add(a);const r=e.chatAssistantTextSoFar??"";let i;if(e.chatAssistantTextSoFar=o,o.startsWith(r))i=o.slice(r.length);else{if(r.startsWith(o))continue;i=o}if(!i)continue;this.logger.debug?.(`[gateway-events] chat.text delta seq=${t.seq} runId=${t.runId} len=${i.length} prevLen=${r.length}`);const l={sessionUpdate:"agent_message_chunk",content:{type:"text",text:i}};this.transport.sendSessionUpdate(s,l),e.assistantMq?.push(l)}}}}}else"delta"===t.state&&this.touchStreamActivity(e);if(this.maybeCompletePromptFromChatState(e,t),!e.promptDone)if("final"===t.state)this.completePrompt(e,t.stopReason||"end_turn");else if("aborted"===t.state||"cancelled"===t.state||"cancel"===t.state)this.completePrompt(e,"cancelled");else if("error"===t.state){const s=t.errorMessage||Errors.AgentError.message;this.failPrompt(e,Errors.AgentError.rpcCode,formatFriendlyError(s))}}handleAgentEvent(t){const e=(t.runId?this.state.promptsByRunId.get(t.runId):void 0)??(t.sessionKey?this.state.findSessionByKey(t.sessionKey):void 0);if(!e)return;if(!this.state.isCurrentStreamOwner(e,t.runId)){if(!t.runId||!1===e.promptDone)return;this.adoptBackgroundRun(e,t.runId)}if("number"==typeof t.seq){if(t.seq<=(e.lastAgentSeq??-1))return void this.logger.debug?.(`[gateway-events] Dropping duplicate agent event seq=${t.seq} (last=${e.lastAgentSeq}) runId=${t.runId} stream=${t.stream}`);e.lastAgentSeq=t.seq}const s=e.sessionId;this.touchStreamActivity(e);const n=t=>{this.transport.sendSessionUpdate(s,t),e.assistantMq?.push(t)};if("assistant"===t.stream){e.hasAgentAssistantStream=!0;const o=this.state.extractAgentAssistantDelta(e,t.data??{});o&&(this.logger.debug?.(`[gateway-events] agent.assistant delta seq=${t.seq} runId=${t.runId} len=${o.length} source=${t.data?.delta?"delta":"cumulative"}`),n({sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}}));const a=[],r=t.data;r&&(Array.isArray(r.content)?a.push(...r.content):isRecord(r.content)?a.push(r.content):"string"==typeof r.type&&a.push(r));for(const t of a){if(!isRecord(t))continue;const o=asString(t.type);if("thinking"===o){e.hasAgentThinkingStream=!0;const n=normalizeText(t.thinking)??normalizeText(t.text);if(n){const t={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n}};this.transport.sendSessionUpdate(s,t)&&e.assistantMq?.push(t)}continue}if("toolCall"===o){this.sendToolCallSpacer(e),e.hasAgentToolStartStream=!0;const s=this.resolveToolCallId(e,t,"start"),o=asString(t.name)??asString(t.toolName)??asString(t.tool_name)??"tool",a=isRecord(t.arguments)?t.arguments:isRecord(t.args)?t.args:{};n({sessionUpdate:"tool_call",toolCallId:s,title:o,status:"in_progress",content:[{type:"content",content:{type:"text",text:JSON.stringify(a,null,2)}}]});continue}if("toolResult"===o){this.sendToolCallSpacer(e),e.hasAgentToolResultStream=!0;const s=this.resolveToolCallId(e,t,"result"),o=asString(t.name)??asString(t.toolName)??asString(t.tool_name)??"tool",a=normalizeText(t.text)??normalizeText(t.result)??(isRecord(t.result)||Array.isArray(t.result)?JSON.stringify(t.result,null,2):void 0);a&&n({sessionUpdate:"tool_call_update",toolCallId:s,title:o,status:"completed",content:[{type:"content",content:{type:"text",text:a}}]});continue}}}else if("thinking"===t.stream){e.hasAgentThinkingStream=!0;const n=normalizeText(t.data?.delta)??normalizeText(t.data?.text);if(n){const t={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n}};this.transport.sendSessionUpdate(s,t)&&e.assistantMq?.push(t)}}else if("tool"===t.stream){const s=t.data,o="string"==typeof s?.phase?s.phase:void 0;if("start"===o){this.sendToolCallSpacer(e),e.hasAgentToolStartStream=!0;const t=this.resolveToolCallId(e,s,"start"),o=asString(s?.name)??asString(s?.toolName)??asString(s?.tool_name)??"tool",a=isRecord(s?.arguments)?s.arguments:isRecord(s?.args)?s.args:{};n({sessionUpdate:"tool_call",toolCallId:t,title:o,kind:"other",status:"in_progress",content:[{type:"content",content:{type:"text",text:JSON.stringify(a,null,2)}}]})}else if("result"===o)this.sendToolCallSpacer(e),e.hasAgentToolResultStream=!0,this.handleToolResult(e,t).catch(t=>{this.logger.warn?.(`[gateway-events] Tool result handling failed: ${t instanceof Error?t.message:t}`)});else{const t=s?.toolCall;if(t){this.sendToolCallSpacer(e),e.hasAgentToolStartStream=!0;const o=asString(t?.name)??asString(s?.name)??asString(s?.toolName)??"tool";n({sessionUpdate:"tool_call",toolCallId:this.resolveToolCallId(e,{...s,...t},"start"),title:o,kind:"other",status:"in_progress"})}}}else if("lifecycle"===t.stream){const s=t.data,n="string"==typeof s?.phase?s.phase:void 0;if("end"===n)this.completePrompt(e,"end_turn");else if("cancelled"===n||"cancel"===n)this.completePrompt(e,"cancelled");else if("error"===n){const n=s?.error,o=n&&"object"==typeof n?n:void 0,a=("string"==typeof s?.message?s.message:void 0)??("string"==typeof n?n:void 0)??("string"==typeof o?.message?o.message:void 0)??("string"==typeof s?.reason?s.reason:void 0)??(o?JSON.stringify(o):void 0)??"gateway lifecycle error",r=formatFriendlyError(a);this.logger.warn?.(`[gateway-events] lifecycle error runId=${t.runId} sessionKey=${t.sessionKey} message=${a} data=${JSON.stringify(s)}`),this.failPrompt(e,Errors.AgentError.rpcCode,r)}}}async handleToolResult(t,e){const s=e.data,n=s?.toolCall,o=("string"==typeof n?.id?n.id:void 0)??("string"==typeof s?.toolCallId?s.toolCallId:void 0),a=(o?this.state.toolCallIdMap.get(o):void 0)??o??`tc_${e.runId}_${e.seq}`,r=("string"==typeof n?.name?n.name:void 0)??("string"==typeof s?.name?s.name:void 0)??"tool",i="string"==typeof s?.text?s.text:void 0,l=o??a;let c;try{c=await resolveToolResultBlocks({toolCallId:l,toolName:r,rawText:i,rawResult:e.data})}catch{c=i?[{type:"content",content:{type:"text",text:i}}]:[]}if(0===c.length&&i&&(c=[{type:"content",content:{type:"text",text:i}}]),c.length>0){const e=c.filter(t=>"text"===t.content?.type&&t.content?.text).map(t=>({type:"content",content:{type:"text",text:t.content.text}})),s={sessionUpdate:"tool_call_update",toolCallId:a,title:r,kind:"other",status:"completed",...e.length>0?{content:e}:{}};this.transport.sendSessionUpdate(t.sessionId,s)&&t.assistantMq?.push(s)}}adoptBackgroundRun(t,e){this.logger.debug?.(`[gateway-events] Adopting background run ${e} on session ${t.sessionId} (prev=${t.currentRunId})`),t.currentRunId=e,t.promptDone=!1,this.state.promptsByRunId.set(e,t),t.lastChatSeq=void 0,t.lastAgentSeq=void 0,t.assistantStreamStartedAt=Date.now(),t.lastStreamActivityTs=Date.now(),t.hasAgentAssistantStream=void 0,t.hasAgentThinkingStream=void 0,t.hasAgentToolStartStream=void 0,t.hasAgentToolResultStream=void 0,t.chatAssistantTextSoFar=void 0,t.agentAssistantTextSoFar=void 0,t.chatReplayDedupKeys?.clear()}handleCronEvent(t){if(this.transport.sendNotification("_beeos/cron_event",{payload:t}),this.config.agentGatewayUrl&&this.agentFetchFn){const e=`${this.config.agentGatewayUrl}/api/v1/agent/events`;this.agentFetchFn(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"cron",data:t})}).catch(t=>{this.logger.warn?.(`[gateway-events] event report failed: ${t instanceof Error?t.message:t}`)})}}}
|
|
1
|
+
import{createHash}from"node:crypto";import{Errors}from"../errors/index.js";import{formatFriendlyError}from"../errors/classify.js";import{stripTransportMetadata}from"../message-filter.js";import{resolveToolResultBlocks}from"./tool-result-payload-strategies.js";import{DEFAULT_STREAM_IDLE_TIMEOUT_MS,DEFAULT_STREAM_STALE_TIMEOUT_MS}from"./types.js";function asString(t){if("string"==typeof t){return t.trim()||void 0}}function isRecord(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function normalizeText(t){if("string"!=typeof t)return;return t.replace(/\r\n/g,"\n").replace(/\r/g,"\n")||void 0}const DEDUP_HASH_THRESHOLD=256;function dedupKey(t,...e){const s=`${t}:${e.join(":")}`;if(s.length<=256)return s;return`${t}:h:${createHash("sha256").update(s).digest("hex").slice(0,24)}`}export class AcpGatewayEvents{state;transport;config;logger;writeObs;completePrompt;failPrompt;maybeCompletePromptFromChatState;agentFetchFn;constructor(t){this.state=t.state,this.transport=t.transport,this.config=t.config,this.logger=t.logger,this.writeObs=t.writeObs,this.completePrompt=t.completePrompt,this.failPrompt=t.failPrompt,this.maybeCompletePromptFromChatState=t.maybeCompletePromptFromChatState,this.agentFetchFn=t.agentFetch}touchStreamActivity(t){t.lastStreamActivityTs=Date.now(),this.resetStreamIdleTimer(t)}resetStreamIdleTimer(t){this.state.clearStreamIdleTimer(t);const e=this.config.streamIdleTimeoutMs??DEFAULT_STREAM_IDLE_TIMEOUT_MS,s=this.config.streamStaleTimeoutMs??DEFAULT_STREAM_STALE_TIMEOUT_MS;t.streamIdleTimer=setTimeout(()=>{if(!t.lastStreamActivityTs)return;const e=Date.now()-t.lastStreamActivityTs;e>s&&(this.logger.warn?.(`[gateway-events] Stream stale timeout sessionId=${t.sessionId} stale=${e}ms`),this.completePrompt(t,"end_turn"))},e),"object"==typeof t.streamIdleTimer&&"unref"in t.streamIdleTimer&&t.streamIdleTimer.unref()}sendToolCallSpacer(t){const e={sessionUpdate:"agent_message_chunk",content:{type:"text",text:"\n"}};this.transport.sendSessionUpdate(t.sessionId,e),t.assistantMq?.push(e)}resolveToolCallId(t,e,s){const o=asString(e.toolCallId)??asString(e.tool_call_id)??asString(e.callId)??asString(e.id);if(o){const e=this.state.toolCallIdMap.get(o);return e?(t.sessionId&&this.state.toolCallToSessionMap.set(e,t.sessionId),e):(this.state.toolCallIdMap.set(o,o),t.sessionId&&this.state.toolCallToSessionMap.set(o,t.sessionId),o)}const n=`tc_${t.currentRunId??"unknown"}_${this.state.nextToolCallSeq++}`;return t.sessionId&&this.state.toolCallToSessionMap.set(n,t.sessionId),n}handleChatEvent(t){const e=(t.runId?this.state.promptsByRunId.get(t.runId):void 0)??this.state.findSessionByKey(t.sessionKey);if(!e)return;if(!this.state.isCurrentStreamOwner(e,t.runId)){if(!t.runId||!1===e.promptDone)return;this.adoptBackgroundRun(e,t.runId)}const s=e.sessionId,o=t.message;if(o){this.touchStreamActivity(e);if("assistant"===o.role){if(!Array.isArray(o.content))return;for(const n of o.content){const o=n;if(!isRecord(o))continue;const a=asString(o.type);if(a){if("thinking"===a){if(e.hasAgentThinkingStream)continue;const t=normalizeText(o.thinking)??normalizeText(o.text);if(!t)continue;const n=dedupKey("chat:thinking",t);if(e.chatReplayDedupKeys.has(n))continue;e.chatReplayDedupKeys.add(n);const a={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:t}};this.transport.sendSessionUpdate(s,a)&&e.assistantMq?.push(a);continue}if("toolCall"===a){if(this.sendToolCallSpacer(e),e.hasAgentToolStartStream)continue;const t=this.resolveToolCallId(e,o,"start"),n=asString(o.name)??asString(o.toolName)??asString(o.tool_name)??"tool",a=isRecord(o.arguments)?o.arguments:isRecord(o.args)?o.args:{},r=dedupKey("chat:tool_start",t,JSON.stringify(a));if(e.chatReplayDedupKeys.has(r))continue;e.chatReplayDedupKeys.add(r);const i={sessionUpdate:"tool_call",toolCallId:t,title:n,status:"in_progress",content:[{type:"content",content:{type:"text",text:JSON.stringify(a,null,2)}}]};this.transport.sendSessionUpdate(s,i)&&e.assistantMq?.push(i);continue}if("toolResult"===a){if(this.sendToolCallSpacer(e),e.hasAgentToolResultStream)continue;const t=this.resolveToolCallId(e,o,"result"),n=asString(o.name)??asString(o.toolName)??asString(o.tool_name)??"tool",a=normalizeText(o.text)??normalizeText(o.result)??(isRecord(o.result)||Array.isArray(o.result)?JSON.stringify(o.result,null,2):void 0);if(!a)continue;const r=dedupKey("chat:tool_result",t,a);if(e.chatReplayDedupKeys.has(r))continue;e.chatReplayDedupKeys.add(r);const i={sessionUpdate:"tool_call_update",toolCallId:t,title:n,status:"completed",content:[{type:"content",content:{type:"text",text:a}}]};this.transport.sendSessionUpdate(s,i)&&e.assistantMq?.push(i);continue}if("text"===a&&o.text){if(e.hasAgentAssistantStream||e.agentAssistantTextSoFar)continue;const n=stripTransportMetadata(o.text);if(!n)continue;const a=dedupKey("chat:text",n);if(e.chatReplayDedupKeys.has(a))continue;e.chatReplayDedupKeys.add(a);const r=e.chatAssistantTextSoFar??"";let i;if(e.chatAssistantTextSoFar=n,n.startsWith(r))i=n.slice(r.length);else{if(r.startsWith(n))continue;i=n}if(!i)continue;this.logger.debug?.(`[gateway-events] chat.text delta seq=${t.seq} runId=${t.runId} len=${i.length} prevLen=${r.length}`);const l={sessionUpdate:"agent_message_chunk",content:{type:"text",text:i}};this.transport.sendSessionUpdate(s,l),e.assistantMq?.push(l)}}}}}else"delta"===t.state&&this.touchStreamActivity(e);if(this.maybeCompletePromptFromChatState(e,t),!e.promptDone)if("final"===t.state)this.completePrompt(e,t.stopReason||"end_turn");else if("aborted"===t.state||"cancelled"===t.state||"cancel"===t.state)this.completePrompt(e,"cancelled");else if("error"===t.state){const s=t.errorMessage||Errors.AgentError.message;this.failPrompt(e,Errors.AgentError.rpcCode,formatFriendlyError(s))}}handleAgentEvent(t){const e=(t.runId?this.state.promptsByRunId.get(t.runId):void 0)??(t.sessionKey?this.state.findSessionByKey(t.sessionKey):void 0);if(!e)return;if(!this.state.isCurrentStreamOwner(e,t.runId)){if(!t.runId||!1===e.promptDone)return;this.adoptBackgroundRun(e,t.runId)}const s=e.sessionId;this.touchStreamActivity(e);const o=t=>{this.transport.sendSessionUpdate(s,t),e.assistantMq?.push(t)};if("assistant"===t.stream){e.hasAgentAssistantStream=!0;const n=this.state.extractAgentAssistantDelta(e,t.data??{});n&&(this.logger.debug?.(`[gateway-events] agent.assistant delta seq=${t.seq} runId=${t.runId} len=${n.length} source=${t.data?.delta?"delta":"cumulative"}`),o({sessionUpdate:"agent_message_chunk",content:{type:"text",text:n}}));const a=[],r=t.data;r&&(Array.isArray(r.content)?a.push(...r.content):isRecord(r.content)?a.push(r.content):"string"==typeof r.type&&a.push(r));for(const t of a){if(!isRecord(t))continue;const n=asString(t.type);if("thinking"===n){e.hasAgentThinkingStream=!0;const o=normalizeText(t.thinking)??normalizeText(t.text);if(o){const t={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:o}};this.transport.sendSessionUpdate(s,t)&&e.assistantMq?.push(t)}continue}if("toolCall"===n){this.sendToolCallSpacer(e),e.hasAgentToolStartStream=!0;const s=this.resolveToolCallId(e,t,"start"),n=asString(t.name)??asString(t.toolName)??asString(t.tool_name)??"tool",a=isRecord(t.arguments)?t.arguments:isRecord(t.args)?t.args:{};o({sessionUpdate:"tool_call",toolCallId:s,title:n,status:"in_progress",content:[{type:"content",content:{type:"text",text:JSON.stringify(a,null,2)}}]});continue}if("toolResult"===n){this.sendToolCallSpacer(e),e.hasAgentToolResultStream=!0;const s=this.resolveToolCallId(e,t,"result"),n=asString(t.name)??asString(t.toolName)??asString(t.tool_name)??"tool",a=normalizeText(t.text)??normalizeText(t.result)??(isRecord(t.result)||Array.isArray(t.result)?JSON.stringify(t.result,null,2):void 0);a&&o({sessionUpdate:"tool_call_update",toolCallId:s,title:n,status:"completed",content:[{type:"content",content:{type:"text",text:a}}]});continue}}}else if("thinking"===t.stream){e.hasAgentThinkingStream=!0;const o=normalizeText(t.data?.delta)??normalizeText(t.data?.text);if(o){const t={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:o}};this.transport.sendSessionUpdate(s,t)&&e.assistantMq?.push(t)}}else if("tool"===t.stream){const s=t.data,n="string"==typeof s?.phase?s.phase:void 0;if("start"===n){this.sendToolCallSpacer(e),e.hasAgentToolStartStream=!0;const t=this.resolveToolCallId(e,s,"start"),n=asString(s?.name)??asString(s?.toolName)??asString(s?.tool_name)??"tool",a=isRecord(s?.arguments)?s.arguments:isRecord(s?.args)?s.args:{};o({sessionUpdate:"tool_call",toolCallId:t,title:n,kind:"other",status:"in_progress",content:[{type:"content",content:{type:"text",text:JSON.stringify(a,null,2)}}]})}else if("result"===n)this.sendToolCallSpacer(e),e.hasAgentToolResultStream=!0,this.handleToolResult(e,t).catch(t=>{this.logger.warn?.(`[gateway-events] Tool result handling failed: ${t instanceof Error?t.message:t}`)});else{const t=s?.toolCall;if(t){this.sendToolCallSpacer(e),e.hasAgentToolStartStream=!0;const n=asString(t?.name)??asString(s?.name)??asString(s?.toolName)??"tool";o({sessionUpdate:"tool_call",toolCallId:this.resolveToolCallId(e,{...s,...t},"start"),title:n,kind:"other",status:"in_progress"})}}}else if("lifecycle"===t.stream){const s=t.data,o="string"==typeof s?.phase?s.phase:void 0;if("end"===o)this.completePrompt(e,"end_turn");else if("cancelled"===o||"cancel"===o)this.completePrompt(e,"cancelled");else if("error"===o){const o=s?.error,n=o&&"object"==typeof o?o:void 0,a=("string"==typeof s?.message?s.message:void 0)??("string"==typeof o?o:void 0)??("string"==typeof n?.message?n.message:void 0)??("string"==typeof s?.reason?s.reason:void 0)??(n?JSON.stringify(n):void 0)??"gateway lifecycle error",r=formatFriendlyError(a);this.logger.warn?.(`[gateway-events] lifecycle error runId=${t.runId} sessionKey=${t.sessionKey} message=${a} data=${JSON.stringify(s)}`),this.failPrompt(e,Errors.AgentError.rpcCode,r)}}}async handleToolResult(t,e){const s=e.data,o=s?.toolCall,n=("string"==typeof o?.id?o.id:void 0)??("string"==typeof s?.toolCallId?s.toolCallId:void 0),a=(n?this.state.toolCallIdMap.get(n):void 0)??n??`tc_${e.runId}_${e.seq}`,r=("string"==typeof o?.name?o.name:void 0)??("string"==typeof s?.name?s.name:void 0)??"tool",i="string"==typeof s?.text?s.text:void 0,l=n??a;let c;try{c=await resolveToolResultBlocks({toolCallId:l,toolName:r,rawText:i,rawResult:e.data})}catch{c=i?[{type:"content",content:{type:"text",text:i}}]:[]}if(0===c.length&&i&&(c=[{type:"content",content:{type:"text",text:i}}]),c.length>0){const e=c.filter(t=>"text"===t.content?.type&&t.content?.text).map(t=>({type:"content",content:{type:"text",text:t.content.text}})),s={sessionUpdate:"tool_call_update",toolCallId:a,title:r,kind:"other",status:"completed",...e.length>0?{content:e}:{}};this.transport.sendSessionUpdate(t.sessionId,s)&&t.assistantMq?.push(s)}}adoptBackgroundRun(t,e){this.logger.debug?.(`[gateway-events] Adopting background run ${e} on session ${t.sessionId} (prev=${t.currentRunId})`),t.currentRunId=e,t.promptDone=!1,this.state.promptsByRunId.set(e,t),t.assistantStreamStartedAt=Date.now(),t.lastStreamActivityTs=Date.now(),t.hasAgentAssistantStream=void 0,t.hasAgentThinkingStream=void 0,t.hasAgentToolStartStream=void 0,t.hasAgentToolResultStream=void 0,t.chatAssistantTextSoFar=void 0,t.agentAssistantTextSoFar=void 0,t.chatReplayDedupKeys?.clear()}handleCronEvent(t){if(this.transport.sendNotification("_beeos/cron_event",{payload:t}),this.config.agentGatewayUrl&&this.agentFetchFn){const e=`${this.config.agentGatewayUrl}/api/v1/agent/events`;this.agentFetchFn(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"cron",data:t})}).catch(t=>{this.logger.warn?.(`[gateway-events] event report failed: ${t instanceof Error?t.message:t}`)})}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stripTransportMetadata}from"../message-filter.js";const BEEOS_USER_MSG_MARKER_RE=/(?:^|\n)\s*User Message From \w+:\s*\n/i,CANVAS_STATE_RE=/^\[Canvas State\][^\n]*/,SYSTEM_NOTE_RE=/^\[System Note\][^\n]*/,CANVAS_INTERACTION_RE=/^\[Canvas Interaction\] The user clicked "([^"]*)" on surface "([^"]*)"/,ACTION_CONTEXT_RE=/\nAction context: (.+?)(?:\n|$)/s;function stripBeeosUserEnvelope(t){const
|
|
1
|
+
import{stripTransportMetadata}from"../message-filter.js";const BEEOS_USER_MSG_MARKER_RE=/(?:^|\n)\s*User Message From \w+:\s*\n/i,CANVAS_STATE_RE=/^\[Canvas State\][^\n]*/,SYSTEM_NOTE_RE=/^\[System Note\][^\n]*/,CANVAS_INTERACTION_RE=/^\[Canvas Interaction\] The user clicked "([^"]*)" on surface "([^"]*)"/,ACTION_CONTEXT_RE=/\nAction context: (.+?)(?:\n|$)/s;function stripBeeosUserEnvelope(t){const e=BEEOS_USER_MSG_MARKER_RE.exec(t);if(e){return t.slice(e.index+e[0].length).trim()}let o=t;return o=o.replace(CANVAS_STATE_RE,"").trimStart(),o=o.replace(SYSTEM_NOTE_RE,"").trimStart(),stripTransportMetadata(o).trim()}export async function loadHistory(t,e,o=50){if(!t?.isConnected)return[];try{const n=parseGatewayHistory(await t.chatHistory(e,o));if(n.length>0){n.filter(t=>"user"===t.role).length,n.filter(t=>"assistant"===t.role).length}return n}catch(t){return[]}}export function groupIntoTurns(t){const e=[];let o=null;const n=()=>{o&&(e.push(o),o=null)};for(const s of t){if("assistant"===s.role&&(s.reasoning||s.toolCalls?.length)){n(),o={role:"assistant",content:s.content,reasoning:s.reasoning,files:s.files},s.toolCalls?.length&&(o.toolCalls=s.toolCalls.map(t=>({id:t.id,callId:t.id,name:t.name,arguments:t.arguments??"",status:t.status??"completed",output:t.output,isError:"error"===t.status||"failed"===t.status})));continue}if("system"===s.role){n();const t={role:"system",content:s.content};s.metadata&&(t.metadata=s.metadata),e.push(t);continue}if("user"===s.role){n();const t={role:"user",content:s.content};s.provenance&&(t.provenance=s.provenance),s.metadata&&(t.metadata=s.metadata),e.push(t);continue}o||(o={role:"assistant",content:""});switch(s.updateType??"agent_message_chunk"){case"agent_thought_chunk":o.reasoning=(o.reasoning??"")+s.content;break;case"tool_call":o.toolCalls||(o.toolCalls=[]),o.toolCalls.push({id:s.toolCallId??`tc_${o.toolCalls.length}`,callId:s.toolCallId??`tc_${o.toolCalls.length}`,name:s.toolName??"tool",arguments:s.content||"",status:"completed"});break;case"tool_call_update":{o.toolCalls||(o.toolCalls=[]);const t=s.toolCallId?o.toolCalls.find(t=>t.id===s.toolCallId):void 0;t?(t.output=s.content,t.status="completed"):o.toolCalls.push({id:s.toolCallId??`tc_${o.toolCalls.length}`,callId:s.toolCallId??`tc_${o.toolCalls.length}`,name:s.toolName??"tool",arguments:"",status:"completed",output:s.content});break}default:o.content+=s.content,s.files?.length&&(o.files=[...o.files??[],...s.files])}}return n(),e}const TOOL_CALL_BLOCK_TYPES=new Set(["toolCall","toolUse","functionCall","tool_use","tool_call","toolcall"]),TOOL_RESULT_BLOCK_TYPES=new Set(["tool_result","tool_result_error","toolResult"]);function extractBlockText(t){if("string"==typeof t)return t;if(!Array.isArray(t))return"";let e="";for(const o of t)"string"!=typeof o?o&&"object"==typeof o&&"string"==typeof o.text&&(e+=o.text):e+=o;return e}function parseGatewayHistory(t){if(!t||"object"!=typeof t)return[];const e=t.messages;if(!Array.isArray(e))return[];const o=[];let n=null;for(const t of e){if(!t||"object"!=typeof t)continue;const e=t,s="string"==typeof e.role?e.role:"assistant";if("toolResult"===s||"tool"===s){if(!n?.toolCalls?.length)continue;const t=String(e.toolCallId??e.tool_call_id??e.toolUseId??e.tool_use_id??""),o=extractBlockText(e.content);if(t){const s=n.toolCalls.find(e=>e.id===t);if(s)s.output=o,!0!==e.is_error&&!0!==e.isError||(s.status="error");else{const t=n.toolCalls.find(t=>void 0===t.output);t&&(t.output=o,!0!==e.is_error&&!0!==e.isError||(t.status="error"))}}else{const t=n.toolCalls.find(t=>void 0===t.output);t&&(t.output=o,!0!==e.is_error&&!0!==e.isError||(t.status="error"))}continue}if("user"===s&&n?.toolCalls?.length&&Array.isArray(e.content)){let t=!1,o=!1;for(const n of e.content){if(!n||"object"!=typeof n)continue;const e=n,s="string"==typeof e.type?e.type:"";TOOL_RESULT_BLOCK_TYPES.has(s)?t=!0:"text"===s&&"string"==typeof e.text&&e.text.trim()&&(o=!0)}if(t&&!o){for(const t of e.content){if(!t||"object"!=typeof t)continue;const e=t,o="string"==typeof e.type?e.type:"";if(!TOOL_RESULT_BLOCK_TYPES.has(o))continue;const s=String(e.toolUseId??e.tool_use_id??e.toolCallId??e.tool_call_id??""),r="string"==typeof e.output?e.output:extractBlockText(e.content);if(s){const t=n.toolCalls.find(t=>t.id===s);if(t)t.output=r,!0!==e.is_error&&!0!==e.isError||(t.status="error");else{const t=n.toolCalls.find(t=>void 0===t.output);t&&(t.output=r,!0!==e.is_error&&!0!==e.isError||(t.status="error"))}}else{const t=n.toolCalls.find(t=>void 0===t.output);t&&(t.output=r,!0!==e.is_error&&!0!==e.isError||(t.status="error"))}}continue}}const r="user"===s?"user":"assistant";let i,l,a,c,u,p="";if("string"==typeof e.content)p=e.content;else if(Array.isArray(e.content))for(const t of e.content){if("string"==typeof t){p+=t;continue}if(!t||"object"!=typeof t)continue;const e=t,o="string"==typeof e.type?e.type:"";if("text"===o&&"string"==typeof e.text)p+=e.text;else if("thinking"===o&&"string"==typeof e.thinking)l=(l??"")+e.thinking;else if("resource_link"===o&&"string"==typeof e.uri&&e.uri)a||(a=[]),a.push({uri:e.uri,..."string"==typeof e.name&&e.name?{name:e.name}:{},..."string"==typeof e.mimeType&&e.mimeType?{mimeType:e.mimeType}:{}});else if(TOOL_CALL_BLOCK_TYPES.has(o)){i||(i=[]);const t=e.arguments??e.input,o="string"==typeof t?t:null!=t?JSON.stringify(t):"";i.push({id:String(e.id??e.toolCallId??e.tool_call_id??""),name:String(e.name??"tool"),arguments:o,status:"completed"})}else if(TOOL_RESULT_BLOCK_TYPES.has(o)){const t=String(e.toolUseId??e.tool_use_id??e.toolCallId??e.tool_call_id??""),o="string"==typeof e.output?e.output:extractBlockText(e.content),n=!0===e.is_error||!0===e.isError;if(i){const e=t?i.find(e=>e.id===t):void 0;if(e)e.output=o,n&&(e.status="error");else{const t=i.find(t=>void 0===t.output);t&&(t.output=o,n&&(t.status="error"))}}}}if(l||("string"==typeof e.reasoning&&e.reasoning?l=e.reasoning:"string"==typeof e.thinking&&e.thinking&&(l=e.thinking)),!i?.length){const t=e.tool_calls??e.toolCalls;if(Array.isArray(t)){i=[];for(const e of t){if(!e||"object"!=typeof e)continue;const t=e,o=t.function;i.push({id:String(t.id??t.toolCallId??""),name:String(o?.name??t.name??t.toolName??"tool"),arguments:"string"==typeof t.arguments?t.arguments:"string"==typeof o?.arguments?o.arguments:"",status:String(t.status??"completed"),output:"string"==typeof t.output?t.output:void 0})}0===i.length&&(i=void 0)}}if("user"===r&&p){p=stripBeeosUserEnvelope(p);const t=CANVAS_INTERACTION_RE.exec(p);if(t){const e=t[1];c={kind:"canvas_action"};const o={type:"canvas_action",actionName:e,surfaceId:t[2]},n=ACTION_CONTEXT_RE.exec(p);if(n)try{o.actionPayload=JSON.parse(n[1])}catch{}u=o,p=`Clicked "${e}"`}}if(!(p||l||i?.length||a?.length))continue;if(!c&&"user"===r&&e.provenance&&"object"==typeof e.provenance){const t=e.provenance;"string"==typeof t.kind&&(c={kind:t.kind},"string"==typeof t.sourceTool&&(c.sourceTool=t.sourceTool))}const f={role:r,content:p,reasoning:l,toolCalls:i,provenance:c,metadata:u,files:a};o.push(f),"assistant"===r&&(n=f)}o.filter(t=>t.toolCalls?.length),o.reduce((t,e)=>t+(e.toolCalls?.length??0),0),o.reduce((t,e)=>t+(e.toolCalls?.filter(t=>void 0!==t.output).length??0),0);return o}const BEEOS_FILE_URI_RE=/beeos-file:\/\/([a-zA-Z0-9_-]+)/g;export function extractBeeosFileUrisFromOutput(t){if(!t)return[];const e=[];for(const o of t.matchAll(BEEOS_FILE_URI_RE))e.push(o[0]);return[...new Set(e)]}const BEEOS_REF_RE=/<BEEOS_REF\s+([^/>]*)\s*\/>/g;function parseBeeosRefAttrs(t){const e=new Map,o=/(\w+)="([^"]*)"/g;for(const n of t.matchAll(o))e.set(n[1],n[2]);return e}function guessMimeFromName(t){if(!t)return;const e=t.split(".").pop()?.toLowerCase();return e?{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",webm:"video/webm",txt:"text/plain",json:"application/json",csv:"text/csv"}[e]:void 0}export function splitBeeosRefReplayText(t){if(!t)return[];if(!t.includes("<BEEOS_REF "))return[{type:"text",text:t}];const e=[];let o=0;for(const n of t.matchAll(BEEOS_REF_RE)){const s=t.slice(o,n.index).trim();s&&e.push({type:"text",text:s});const r=parseBeeosRefAttrs(n[1]),i=r.get("id"),l=r.get("name"),a=r.get("status");i&&"download_failed"!==a?e.push({type:"resource_link",uri:`beeos-file://${i}`,fileName:l,mimeType:guessMimeFromName(l)??"application/octet-stream"}):i&&e.push({type:"resource_link",uri:`beeos-file://${i}`,fileName:l??"file",mimeType:guessMimeFromName(l)??"application/octet-stream"}),o=(n.index??0)+n[0].length}const n=t.slice(o).trim();return n&&e.push({type:"text",text:n}),e}const ATTACHMENT_MARKER_RE=/\[(image|file)\s+([^\]]*)\]/g;export function splitUserAttachmentMarkers(t){if(!t)return[];if(!t.includes("[image ")&&!t.includes("[file "))return[{type:"text",text:t}];const e=[];let o=0;for(const n of t.matchAll(ATTACHMENT_MARKER_RE)){const s=t.slice(o,n.index).trim();s&&e.push({type:"text",text:s});const r=n[1],i=n[2],l=new Map;for(const t of i.split(/\s+/)){const e=t.indexOf("=");e>0&&l.set(t.slice(0,e),t.slice(e+1))}e.push({type:r,mimeType:l.get("mime"),fileName:l.get("name")||("image"===r?"Image":"File")}),o=(n.index??0)+n[0].length}const n=t.slice(o).trim();return n&&e.push({type:"text",text:n}),e}export function splitUserReplayBlocks(t){return t?t.includes("<BEEOS_REF ")?splitBeeosRefReplayText(t):t.includes("[image ")||t.includes("[file ")?splitUserAttachmentMarkers(t):[{type:"text",text:t}]:[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{basename}from"node:path";import{asTrimmedNonEmptyString as asStr,isPlainRecord as isRecord}from"../utils/text.js";const SLASH_COMMAND_RE=/^\/([a-z0-9_-]+)(?::|\s|$)/i;export function resolveSlashCommandName(e,t){if(0===e.length)return;if(e.some(e=>"text"!==e.type))return;const r=t.trim();if(!r||r.includes("\n")||!r.startsWith("/"))return;const i=r.match(SLASH_COMMAND_RE);return i?.[1]?.toLowerCase()}export function extractPromptBlocks(e){const t=[];if("string"==typeof e)t.push({type:"text",text:e});else if(Array.isArray(e))for(const r of e){const e=asBlock(r);e&&t.push(e)}else if(isRecord(e))if(Array.isArray(e.content))for(const r of e.content){const e=asBlock(r);e&&t.push(e)}else if("string"==typeof e.type){const r=asBlock(e);r&&t.push(r)}return t}export function toGatewayPrompt(e){const
|
|
1
|
+
import{basename}from"node:path";import{asTrimmedNonEmptyString as asStr,isPlainRecord as isRecord}from"../utils/text.js";import{parseBeeosFileUri}from"./beeos-file-resolver.js";const SLASH_COMMAND_RE=/^\/([a-z0-9_-]+)(?::|\s|$)/i;export function resolveSlashCommandName(e,t){if(0===e.length)return;if(e.some(e=>"text"!==e.type))return;const r=t.trim();if(!r||r.includes("\n")||!r.startsWith("/"))return;const i=r.match(SLASH_COMMAND_RE);return i?.[1]?.toLowerCase()}export function extractPromptBlocks(e){const t=[];if("string"==typeof e)t.push({type:"text",text:e});else if(Array.isArray(e))for(const r of e){const e=asBlock(r);e&&t.push(e)}else if(isRecord(e))if(Array.isArray(e.content))for(const r of e.content){const e=asBlock(r);e&&t.push(e)}else if("string"==typeof e.type){const r=asBlock(e);r&&t.push(r)}return t}export function toGatewayPrompt(e,t){const r=[],i=[],a=[],s=new Set;for(const o of e)switch(o.type){case"text":{const e=o.text?.trim();e&&r.push(e);break}case"image":{const e=o.mimeType??o.mime_type??"application/octet-stream",t=o.fileName??o.file_name??o.name??(o.uri?resolveUriFileName(o.uri):void 0);if(!o.data&&!o.uri)return{error:"image block requires data or uri"};const a=[`mime=${e}`];o.data&&(a.push(`size=${o.data.length}`),i.push({type:"image",content:o.data,mimeType:e,fileName:t})),o.uri&&a.push(`uri=${o.uri}`),r.push(`[image ${a.join(" ")}]`);break}case"file":{const e=o.mimeType??o.mime_type??"application/octet-stream",t=o.fileName??o.file_name??o.filename??o.name??(o.uri?resolveUriFileName(o.uri):void 0),a=o.text?.trim(),s=a?Buffer.from(a,"utf-8").toString("base64"):void 0;if(!o.data&&!s&&!o.uri)return{error:"file block requires data, text, or uri"};const n=[`mime=${e}`];t&&n.push(`name=${t}`),o.data?(n.push(`size=${o.data.length}`),i.push({type:"file",content:o.data,mimeType:e,fileName:t})):s&&(n.push(`text=${truncate(a,80)}`),i.push({type:"file",content:s,mimeType:e,fileName:t})),o.uri&&n.push(`uri=${o.uri}`),r.push(`[file ${n.join(" ")}]`);break}case"resource_link":{if(!o.uri)return{error:"resource_link block requires uri"};const e=parseBeeosFileUri(o.uri);if(e.fileId){const i=t?.beeosFileResolutionsByUri?.get(o.uri);if(i){const e="resolved"===i.status?`${i.fileId}:resolved`:`${i.fileId}:${i.code}`;s.has(e)||(s.add(e),a.push(i))}if("resolved"===i?.status){r.push(buildBeeosRefText({fileId:e.fileId,name:i.name,localPath:i.localPath}));break}if("resolve_failed"===i?.status){const t=i.name??o.name?.trim()??o.title?.trim()??e.fileId,a=void 0!==i.httpStatus?`http_${i.httpStatus}`:i.code;r.push(buildBeeosFailedRefText({fileId:e.fileId,name:t,reason:a}));break}}const i=o.title??o.name??"resource";r.push(`[resource_link title=${i} uri=${o.uri}]`);break}case"resource":{const e=o.resource??{},t=asStr(e.uri)??o.uri;if(!t)return{error:"resource block requires uri"};const a=asStr(e.mimeType)??asStr(e.mime_type)??o.mimeType??o.mime_type,s=asStr(e.text)??o.text,n=asStr(e.data)??o.data,l=asStr(e.fileName)??asStr(e.file_name)??asStr(e.name)??o.fileName??o.file_name??o.name??resolveUriFileName(t);n?i.push({type:"file",content:n,mimeType:a,fileName:l}):s&&i.push({type:"file",content:Buffer.from(s,"utf-8").toString("base64"),mimeType:a??"text/plain",fileName:l});const m=s?`text=${truncate(s,120)}`:n?`size=${n.length}`:"";r.push(`[resource uri=${t}${a?` mime=${a}`:""} ${m}]`.trim());break}}return 0===r.length?{message:"(empty prompt)",attachments:[]}:{message:r.join("\n"),attachments:i,...a.length>0?{beeosFileResolutions:a}:{}}}function asBlock(e){return isRecord(e)&&"string"==typeof e.type?e:null}function truncate(e,t){return e.length<=t?e:`${e.slice(0,t)}...`}export function resolveUriFileName(e){try{const t=new URL(e),r=basename(t.pathname);if(r&&"."!==r&&"/"!==r&&"\\"!==r)return decodeURIComponent(r)}catch{}const t=basename(e);if(t&&"."!==t&&"/"!==t&&"\\"!==t)return t}function escapeXmlAttr(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}function buildBeeosRefText(e){return`<BEEOS_REF type="file" path="${escapeXmlAttr(e.localPath)}" name="${escapeXmlAttr(e.name)}" id="${escapeXmlAttr(e.fileId)}" />`}function buildBeeosFailedRefText(e){return`<BEEOS_REF type="file" path="" name="${escapeXmlAttr(e.name)}" id="${escapeXmlAttr(e.fileId)}" status="download_failed" reason="${escapeXmlAttr(e.reason)}" />`}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{MessageQueue}from"../utils/mq.js";const MAX_TOOL_CALL_MAP_ENTRIES=5e3;export class AcpGatewaySessionState{sessions=new Map;promptsByRunId=new Map;sessionsByGatewayKey=new Map;toolCallIdMap=new Map;toolCallToSessionMap=new Map;nextToolCallSeq=0;lastActiveSessionId;sessionGcTimer=null;MAX_IDLE_SESSION_MS=864e5;SESSION_GC_INTERVAL_MS=3e5;logger;constructor(s){this.logger=s}findSessionByKey(s){return this.sessionsByGatewayKey.get(s)}resolveSessionFromParams(s){const e="string"==typeof s?.sessionId?s.sessionId:void 0;if(e)return this.sessions.get(e)}isCurrentStreamOwner(s,e){return!e||!!s.currentRunId&&e===s.currentRunId}clearPromptTimeout(s){s.promptTimeoutTimer&&(clearTimeout(s.promptTimeoutTimer),s.promptTimeoutTimer=void 0)}clearStreamIdleTimer(s){s.streamIdleTimer&&(clearTimeout(s.streamIdleTimer),s.streamIdleTimer=void 0)}resetForNewRun(s,e,t){this.clearStreamIdleTimer(s),s.currentRunId&&this.promptsByRunId.delete(s.currentRunId),s.currentRunId=void 0,s.assistantMq?.close(),s.assistantMq=new MessageQueue,s.chatReplayDedupKeys.clear(),s.hasAgentAssistantStream=!1,s.hasAgentThinkingStream=!1,s.hasAgentToolStartStream=!1,s.hasAgentToolResultStream=!1,s.chatAssistantTextSoFar=void 0,s.agentAssistantTextSoFar=void 0,s.
|
|
1
|
+
import{MessageQueue}from"../utils/mq.js";const MAX_TOOL_CALL_MAP_ENTRIES=5e3;export class AcpGatewaySessionState{sessions=new Map;promptsByRunId=new Map;sessionsByGatewayKey=new Map;toolCallIdMap=new Map;toolCallToSessionMap=new Map;nextToolCallSeq=0;lastActiveSessionId;sessionGcTimer=null;MAX_IDLE_SESSION_MS=864e5;SESSION_GC_INTERVAL_MS=3e5;logger;constructor(s){this.logger=s}findSessionByKey(s){return this.sessionsByGatewayKey.get(s)}resolveSessionFromParams(s){const e="string"==typeof s?.sessionId?s.sessionId:void 0;if(e)return this.sessions.get(e)}isCurrentStreamOwner(s,e){return!e||!!s.currentRunId&&e===s.currentRunId}clearPromptTimeout(s){s.promptTimeoutTimer&&(clearTimeout(s.promptTimeoutTimer),s.promptTimeoutTimer=void 0)}clearStreamIdleTimer(s){s.streamIdleTimer&&(clearTimeout(s.streamIdleTimer),s.streamIdleTimer=void 0)}resetForNewRun(s,e,t){this.clearStreamIdleTimer(s),s.currentRunId&&this.promptsByRunId.delete(s.currentRunId),s.currentRunId=void 0,s.assistantMq?.close(),s.assistantMq=new MessageQueue,s.chatReplayDedupKeys.clear(),s.hasAgentAssistantStream=!1,s.hasAgentThinkingStream=!1,s.hasAgentToolStartStream=!1,s.hasAgentToolResultStream=!1,s.chatAssistantTextSoFar=void 0,s.agentAssistantTextSoFar=void 0,s.promptDone=!1,t.resetSessionUpdateCount(e),this.enforceToolCallMapLimits()}enforceToolCallMapLimits(){if(this.toolCallIdMap.size>5e3){const s=this.toolCallIdMap.size-5e3;let e=0;for(const t of this.toolCallIdMap.keys()){if(e>=s)break;this.toolCallToSessionMap.delete(this.toolCallIdMap.get(t)),this.toolCallIdMap.delete(t),e++}}if(this.toolCallToSessionMap.size>5e3){const s=this.toolCallToSessionMap.size-5e3;let e=0;for(const t of this.toolCallToSessionMap.keys()){if(e>=s)break;this.toolCallToSessionMap.delete(t),e++}}}extractAgentAssistantDelta(s,e){const t=(s.chatAssistantTextSoFar??"").length;if(e.delta){const o=s.agentAssistantTextSoFar??"",i=o+e.delta;if(s.agentAssistantTextSoFar=i,t>0&&o.length<t){if(i.length<=t)return;return i.slice(t)}return e.delta}const o=e.text;if(!o)return;const i=s.agentAssistantTextSoFar??"";s.agentAssistantTextSoFar=o;const a=Math.max(i.length,t);if(!(o.length<=a)){if(o.startsWith(i)||0===a)return o.slice(a)||void 0;if(!i.startsWith(o))return o}}startSessionGc(s,e){this.sessionGcTimer=setInterval(()=>this.gcSessions(s,e),this.SESSION_GC_INTERVAL_MS),"object"==typeof this.sessionGcTimer&&"unref"in this.sessionGcTimer&&this.sessionGcTimer.unref()}gcSessions(s,e){const t=Date.now()-this.MAX_IDLE_SESSION_MS;let o=0;for(const[i,a]of this.sessions){if(void 0!==a.pendingPromptId)continue;(a.lastStreamActivityTs??a.createdAt)<t&&(s(a),e?.(a),this.sessions.delete(i),this.sessionsByGatewayKey.delete(a.gatewaySessionKey),o++)}const i=new Set(Array.from(this.sessions.values()).map(s=>s.sessionId));for(const[s,e]of this.toolCallToSessionMap)i.has(e)||this.toolCallToSessionMap.delete(s);for(const[s,e]of this.toolCallIdMap)this.toolCallToSessionMap.has(e)||this.toolCallIdMap.delete(s);o>0&&(this.lastActiveSessionId&&!this.sessions.has(this.lastActiveSessionId)&&(this.lastActiveSessionId=void 0),this.logger.debug?.(`[session-state] GC evicted ${o} idle sessions, remaining=${this.sessions.size}`))}destroy(){this.sessionGcTimer&&(clearInterval(this.sessionGcTimer),this.sessionGcTimer=null);for(const s of this.sessions.values())this.clearPromptTimeout(s),this.clearStreamIdleTimer(s),s.assistantMq?.close();this.promptsByRunId.clear(),this.toolCallIdMap.clear(),this.toolCallToSessionMap.clear(),this.sessionsByGatewayKey.clear(),this.sessions.clear(),this.lastActiveSessionId=void 0}}
|
package/dist/acp-server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{WebSocketServer,WebSocket}from"ws";let BridgeClientCtor;import{GatewayClient}from"./gateway-client.js";import{TerminalManager}from"./terminal/session-manager.js";import{AcpTransport}from"./acp-gateway/transport.js";import{AcpGatewaySessionState}from"./acp-gateway/session-state.js";import{AcpGatewayBridgeCore}from"./acp-gateway/bridge-core.js";import{AcpGatewayEvents}from"./acp-gateway/gateway-events.js";import{TerminalBridgeHandler}from"./terminal/bridge-handler.js";import{syncAgentsToPlatform}from"./agent-sync.js";import{CanvasOrchestrator}from"./canvas-orchestrator.js";import{A2AOrchestrator}from"./a2a-orchestrator.js";import{discoverBridgeFromGW}from"./bridge-discovery.js";import{writeDiscoveryCache}from"./discovery-cache.js";export class ACPServer{agentFetchFn;instanceId;wss=null;gateway=null;client=null;config;logger;writeObs;transport;state;core;events;terminalMgr;terminalHandler;canvasOrch;a2aOrch;pendingToolCallSessionKeys=[];thirdPartyChannels;agentSyncRetryTimer=null;bridgeInstance=null;bridgeConsecutiveFailures=0;static RE_DISCOVER_THRESHOLD=5;drainNextDeferredSend(e){this.a2aOrch.drainNextDeferredSend(e,(e,t,s,n)=>this.agentSend(e,t,s,n))}async gatewayRequest(e,t){if(!this.gateway?.isConnected)throw new Error("Gateway not connected");return this.gateway.request(e,t)}async agentSend(e,t,s,n){if(!this.gateway?.isConnected)throw new Error("Gateway not connected");const i=this.config.gateway.agentId||this.core.getDefaultAgentId();let a,r;if(s){if(a=this.state.findSessionByKey(s),!a)return void this.logger.warn?.("[acp-server] A2A result target session expired, discarding targetSessionKey=%s (known keys: %s)",s,[...this.state.sessionsByGatewayKey.keys()].join(", "));r=s,this.logger.info?.(`[acp-server] agentSend: resolved session for key=${s} sid=${a.sessionId}`)}else{const e=this.state.lastActiveSessionId;a=e?this.state.sessions.get(e):void 0,r=a?.gatewaySessionKey??`agent:${i}:a2a`,this.logger.info?.(`[acp-server] agentSend: no targetSessionKey, using fallback key=${r}`)}if(a&&!a.promptDone&&(void 0!==a.pendingPromptId||void 0!==a.currentRunId))return(a.pendingAgentSends??=[]).push({message:e,attachments:t,inputProvenance:n}),void this.logger.info?.("[acp-server] Session has active run, deferred message (queue=%d)",a.pendingAgentSends.length);const o=await this.canvasOrch.enrichMessageWithCanvasContext(e,r,this.thirdPartyChannels),c=await this.gateway.agentSend(r,o,i,t,n);return a&&c?.runId&&(this.state.resetForNewRun(a,a.sessionId,this.transport),a.currentRunId=c.runId,a.assistantStreamStartedAt=Date.now(),this.state.promptsByRunId.set(c.runId,a)),c}trackA2ARun(e,t,s){this.a2aOrch.trackA2ARun(e,t,s)}cancelA2ARunByTaskId(e){return this.a2aOrch.cancelA2ARunByTaskId(e)}emitA2ASystemNotification(e){this.a2aOrch.emitA2ASystemNotification(e)}sendBridgeMessage=e=>{const t=this.client;if(t&&t.readyState===WebSocket.OPEN)try{t.send(JSON.stringify(e))}catch(e){this.logger.debug?.("[acp-server] bridge send failed (socket may be closing):",e)}else this.logger.debug?.("[acp-server] bridge not ready, dropping message")};constructor(e,t,s,n,i,a){this.agentFetchFn=n,this.instanceId=i,this.config=e,this.logger=t,this.writeObs=s??(()=>{}),this.thirdPartyChannels=a??new Set,this.transport=new AcpTransport(this.sendBridgeMessage,this.writeObs),this.state=new AcpGatewaySessionState(this.logger),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}),this.canvasOrch=new CanvasOrchestrator({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,getSessionIdForToolCall:e=>this.getSessionIdForToolCall(e),gateway:null,getDefaultAgentId:()=>this.core.getDefaultAgentId(),resolvePlatformAgentId:e=>this.core.resolvePlatformAgentId(e)??""}),this.a2aOrch=new A2AOrchestrator({state:this.state,transport:this.transport,logger:this.logger}),this.events=new AcpGatewayEvents({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,completePrompt:(e,t)=>{this.core.completePrompt(e,t),this.canvasOrch.onPromptComplete(e),this.drainNextDeferredSend(e)},failPrompt:(e,t,s)=>{this.core.failPrompt(e,t,s),this.canvasOrch.onPromptFailed(),this.drainNextDeferredSend(e)},maybeCompletePromptFromChatState:(e,t)=>this.core.maybeCompletePromptFromChatState(e,t),agentFetch:this.agentFetchFn}),this.terminalMgr=new TerminalManager,this.terminalHandler=new TerminalBridgeHandler({terminalMgr:this.terminalMgr,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs}),this.terminalHandler.setupListeners(),this.core.handleTerminalRequest=e=>this.terminalHandler.handleRequest(e),this.core.handleTerminalNotification=(e,t)=>this.terminalHandler.handleNotification(e,t),this.core.onRunComplete=(e,t)=>{this.a2aOrch.onRunComplete(e,t)},this.core.onRunFailed=(e,t)=>{this.a2aOrch.onRunFailed(e,t)},this.core.handleCanvasNotification=(e,t)=>{this.canvasOrch.handleCanvasNotification(e,t)},this.core.getCanvasState=()=>this.canvasOrch.canvasState,this.core.onSessionLoaded=(e,t,s)=>{this.canvasOrch.onSessionLoaded(e,t,s)},this.core.onSessionDeleted=e=>{this.canvasOrch.onSessionDeleted(e)},this.core.onSessionCleared=(e,t)=>{this.canvasOrch.onSessionCleared(e,t)},this.core.handleSlashCommand=async e=>this.canvasOrch.handleSlashCommand(e),this.core.onPromptStart=()=>{this.canvasOrch.onPromptStart()},this.state.startSessionGc(e=>this.core.cleanupPrompt(e),e=>{this.canvasOrch.canvasState?.removeSession(e.gatewaySessionKey),this.transport.resetSessionUpdateCount(e.sessionId)})}async start(e){e&&(this.config.bridge.url=e);const t=this.config.bridge.url,s=this.config.keyFile;if(t&&!BridgeClientCtor)try{const e=await import("@beeos-ai/bridge-client");BridgeClientCtor=e.BridgeClient}catch(e){this.logger.warn?.("[acp-server] Bridge SDK not available")}await this.connectGateway(),t&&s&&BridgeClientCtor?await this.startBridgeMode(t,s):(this.logger.warn?.("[acp-server] Bridge not configured; running in standby (no ACP listener). Use handleUpgrade() for noServer mode."),this.core.markAgentSyncDone())}async startBridgeMode(e,t){if(!BridgeClientCtor)throw new Error("@beeos-ai/bridge-client not available");const s=new BridgeClientCtor({bridgeUrl:e,service:this.config.bridge.service||"acp",keyFile:t});this.bridgeInstance=s,s.on("connected",()=>{this.bridgeConsecutiveFailures=0,this.logger.info?.("[acp-server] Connected to Bridge (publicKey auth)"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"bridge.connected",severity:"info"}),this.tryAgentSync()}),s.on("disconnected",(...e)=>{const n=String(e[0]??"unknown");if(this.logger.warn?.(`[acp-server] Bridge disconnected: ${n}`),this.core.initialized=!1,this.bridgeConsecutiveFailures++,this.bridgeConsecutiveFailures>=ACPServer.RE_DISCOVER_THRESHOLD&&this.agentFetchFn&&this.config.agentGatewayUrl){this.bridgeConsecutiveFailures=0;const e=this.config.bridge.url;discoverBridgeFromGW(this.config.agentGatewayUrl,this.agentFetchFn).then(async n=>{n&&n!==e&&(this.logger.info?.(`[acp-server] Bridge re-discovery: URL changed ${e} → ${n}, switching`),this.config.bridge.url=n,writeDiscoveryCache({bridge:{url:n,discoveredAt:Date.now()}}),await s.close(!1),await this.startBridgeMode(n,t))}).catch(()=>{})}}),s.on("message",(...e)=>{const t=e[0],s="string"==typeof t?t:Buffer.from(t).toString("utf-8");try{const e=JSON.parse(s);"id"in e&&void 0!==e.id?this.core.handleRequest(e):this.core.handleNotification(e)}catch{this.logger.error?.("[acp-server] Invalid JSON-RPC message from Bridge")}}),s.on("error",(...e)=>{const t=e[0];this.logger.error?.("[acp-server] Bridge error:",t?.message)});const n={readyState:WebSocket.OPEN,send:(e,t)=>{try{s.send(e),t?.()}catch(e){t?.(e)}},close:()=>s.close(),terminate:()=>s.close(!1),on:()=>n,once:()=>n,removeListener:()=>n,removeAllListeners:()=>n,ping:()=>{}};Object.defineProperty(n,"readyState",{get:()=>"connected"===s.state?WebSocket.OPEN:WebSocket.CLOSED}),this.client=n;try{await s.connect()}catch(e){this.logger.warn?.(`[acp-server] Initial bridge connect failed (will retry in background): ${e?.message}`)}this.core.initialized=!1,this.logger.info?.("[acp-server] Running in Bridge mode (WS client)")}handleUpgrade(e,t,s){this.wss||(this.wss=new WebSocketServer({noServer:!0}),this.wss.on("connection",(e,t)=>this.handleConnection(e,t))),this.wss.handleUpgrade(e,t,s,t=>{this.wss.emit("connection",t,e)})}async tryAgentSync(e=0){if(this.agentSyncRetryTimer&&(clearTimeout(this.agentSyncRetryTimer),this.agentSyncRetryTimer=null),!this.client||this.client.readyState!==WebSocket.OPEN)return;if(!this.gateway||!this.agentFetchFn||!this.config.agentGatewayUrl)return void this.core.markAgentSyncDone();const t=()=>{if(e+1>=6)return this.logger.warn?.("[acp-server] agent sync exhausted 6 attempts — giving up"),void this.core.markAgentSyncDone();const t=Math.min(5e3*2**e,12e4);this.logger.info?.(`[acp-server] agent sync retry #${e+1} in ${Math.round(t/1e3)}s`),this.agentSyncRetryTimer=setTimeout(()=>this.tryAgentSync(e+1),t)};try{const e=await syncAgentsToPlatform({gateway:this.gateway,agentGatewayUrl:this.config.agentGatewayUrl,capabilities:{canvas:this.config.canvasEnabled,terminal:!0,fileSystem:!0,cron:!0},agentFetch:this.agentFetchFn,logger:this.logger});e?(this.core.setAgentMapping(e),this.logger.info?.(`[acp-server] agent mapping loaded: ${[...e.keys()].join(", ")}`)):t()}catch(e){this.logger.warn?.(`[acp-server] agent sync failed: ${e}`),t()}}async connectGateway(){const e=this.config.gateway;this.gateway=new GatewayClient({url:e.url,token:e.token||"",clientId:e.clientId,openclawCanvasCompat:!!this.config.openclawCanvasCompat,retry:{baseMs:this.config.retry.baseMs,maxMs:this.config.retry.maxMs,maxAttempts:this.config.retry.maxAttempts}}),this.gateway.on("chat",e=>this.events.handleChatEvent(e)),this.gateway.on("agent",e=>this.events.handleAgentEvent(e)),this.gateway.on("cron",e=>this.events.handleCronEvent(e));const t=this.gateway;this.canvasOrch.updateDeps({gateway:t?{get isConnected(){return t.isConnected},request:(e,t)=>this.gateway.request(e,t),agentSend:(e,t,s)=>this.gateway.agentSend(e,t,s)}:null}),this.config.openclawCanvasCompat&&(this.gateway.on("canvas",e=>this.canvasOrch.handleOpenClawCanvasEvent(e)),this.logger.info?.("[acp-server] OpenClaw native canvas compat enabled — listening for canvas events")),this.gateway.on("connected",()=>{this.logger.info?.("[acp-server] Connected to OpenClaw Gateway"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"gateway.connected",severity:"info"})}),this.gateway.on("disconnected",()=>{this.logger.warn?.("[acp-server] Gateway disconnected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"gateway.disconnected",severity:"warn"}),this.core.cleanupAllPendingPrompts()}),this.gateway.on("reconnecting",e=>{this.logger.info?.(`[acp-server] Reconnecting to Gateway attempt=${e.attempt} delay=${Math.round(e.delayMs)}ms`)}),this.gateway.on("reconnect-exhausted",e=>{this.logger.error?.(`[acp-server] Gateway reconnect exhausted after ${e} attempts`)}),this.gateway.on("error",e=>{this.logger.error?.("[acp-server] Gateway error:",e.message)}),this.gateway.on("transport",e=>{this.writeObs({component:"gateway-client",domain:"lifecycle",name:`transport.${e.event}`,severity:"connect_fail"===e.event||"error"===e.event?"warn":"debug",payload:e})}),this.gateway.on("reconnect-notify-scheduled",e=>{this.logger.info?.(`[acp-server] Server-initiated reconnect scheduled in ${e.delayMs}ms`)}),this.gateway.on("reconnect-notify-fired",()=>{this.logger.info?.("[acp-server] Server-initiated reconnect firing")});try{await this.gateway.start()}catch(e){this.logger.error?.("[acp-server] Initial Gateway connect failed:",e)}}handleConnection(e,t){if(this.client){this.logger.warn?.("[acp-server] Replacing existing ACP client with new connection (takeover)");const e=this.client;this.client=null;try{e.close(1008,"replaced by new client")}catch{e.terminate()}}this.client=e,this.core.initialized=!1,this.logger.info?.("[acp-server] ACP client connected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"client.connected",severity:"info"}),e.on("message",e=>{const t="string"==typeof e?e:e.toString("utf-8");try{const e=JSON.parse(t);"id"in e&&void 0!==e.id?this.core.handleRequest(e):this.core.handleNotification(e)}catch{this.logger.error?.("[acp-server] Invalid JSON-RPC message")}}),e.on("close",()=>{this.client===e&&(this.client=null,this.core.initialized=!1),this.logger.info?.("[acp-server] ACP client disconnected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"client.disconnected",severity:"info"})})}pushToolResultContent(e,t,s,n){this.core.pushToolResultContent(e,t,s,n)}setCanvasState(e,t){this.canvasOrch.setCanvasState(e,t)}wireRelayActionHandler(){this.canvasOrch.wireRelayActionHandler()}isCanvasActive(e){return this.canvasOrch.isCanvasActive(e)}isCanvasActiveForGatewayKey(e){return this.canvasOrch.isCanvasActiveForGatewayKey(e)}broadcastNotification(e,t){this.transport.sendNotification(e,t)}getActiveSessionId(){return this.state.lastActiveSessionId}getSessionIdForToolCall(e){const t=this.pendingToolCallSessionKeys.length>0?this.pendingToolCallSessionKeys[this.pendingToolCallSessionKeys.length-1]:void 0;if(t){const s=this.state.findSessionByKey(t);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);s?.sessionId&&this.state.toolCallToSessionMap.set(e,s.sessionId)}waitForAgentMapping(){return this.core.waitForAgentMapping()}flushPendingCanvasLinks(){this.canvasOrch.flushPendingCanvasLinks()}onRelayReconnected(){this.canvasOrch.onRelayReconnected()}getDefaultPlatformAgentId(){return this.getDefaultPlatformAgent()?.id}getDefaultPlatformAgent(){const e=this.core.agentMapping;if(e&&0!==e.size)return e.values().next().value??void 0}getPlatformAgentIdForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return this.core.resolvePlatformAgentId(s?.agentId??"")??s?.platformAgentId}getGatewaySessionKeyForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return s?.gatewaySessionKey}getMentionsForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return s?.activeMentions}getResourceRenderer(){return this.canvasOrch.resourceRenderer}getDescriptorRegistry(){return this.canvasOrch.descriptorRegistry}getFormBuilder(){return this.canvasOrch.formBuilder}getSchemaRegistry(){return this.canvasOrch.schemaRegistry}emitCanvasActionAsUserMessage(e,t){this.canvasOrch.emitCanvasActionAsUserMessage(e,t)}async stop(){this.agentSyncRetryTimer&&(clearTimeout(this.agentSyncRetryTimer),this.agentSyncRetryTimer=null),this.state.destroy(),this.a2aOrch.destroy(),this.canvasOrch.destroy(),this.gateway&&(this.gateway.removeAllListeners(),this.gateway.stop(),this.gateway=null),this.client&&(this.client.removeAllListeners(),this.client.close(),this.client=null),this.bridgeInstance=null,this.bridgeConsecutiveFailures=0,this.terminalHandler.destroy(),this.terminalMgr.destroy(),this.wss&&(this.wss.removeAllListeners(),this.wss.close(),this.wss=null),this.logger.info?.("[acp-server] Stopped"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"lifecycle.shutdown",severity:"info"})}}
|
|
1
|
+
import{WebSocketServer,WebSocket}from"ws";let BridgeClientCtor;import{GatewayClient}from"./gateway-client.js";import{TerminalManager}from"./terminal/session-manager.js";import{AcpTransport}from"./acp-gateway/transport.js";import{AcpGatewaySessionState}from"./acp-gateway/session-state.js";import{AcpGatewayBridgeCore}from"./acp-gateway/bridge-core.js";import{BeeosFileResolver}from"./acp-gateway/beeos-file-resolver.js";import{AcpGatewayEvents}from"./acp-gateway/gateway-events.js";import{TerminalBridgeHandler}from"./terminal/bridge-handler.js";import{syncAgentsToPlatform}from"./agent-sync.js";import{CanvasOrchestrator}from"./canvas-orchestrator.js";import{A2AOrchestrator}from"./a2a-orchestrator.js";import{discoverBridgeFromGW}from"./bridge-discovery.js";import{writeDiscoveryCache}from"./discovery-cache.js";export class ACPServer{agentFetchFn;instanceId;wss=null;gateway=null;client=null;config;logger;writeObs;transport;state;core;events;terminalMgr;terminalHandler;canvasOrch;a2aOrch;pendingToolCallSessionKeys=[];thirdPartyChannels;agentSyncRetryTimer=null;bridgeInstance=null;bridgeConsecutiveFailures=0;static RE_DISCOVER_THRESHOLD=5;drainNextDeferredSend(e){this.a2aOrch.drainNextDeferredSend(e,(e,t,s,n)=>this.agentSend(e,t,s,n))}async gatewayRequest(e,t){if(!this.gateway?.isConnected)throw new Error("Gateway not connected");return this.gateway.request(e,t)}async agentSend(e,t,s,n){if(!this.gateway?.isConnected)throw new Error("Gateway not connected");const i=this.config.gateway.agentId||this.core.getDefaultAgentId();let a,r;if(s){if(a=this.state.findSessionByKey(s),!a)return void this.logger.warn?.("[acp-server] A2A result target session expired, discarding targetSessionKey=%s (known keys: %s)",s,[...this.state.sessionsByGatewayKey.keys()].join(", "));r=s,this.logger.info?.(`[acp-server] agentSend: resolved session for key=${s} sid=${a.sessionId}`)}else{const e=this.state.lastActiveSessionId;a=e?this.state.sessions.get(e):void 0,r=a?.gatewaySessionKey??`agent:${i}:a2a`,this.logger.info?.(`[acp-server] agentSend: no targetSessionKey, using fallback key=${r}`)}if(a&&!a.promptDone&&(void 0!==a.pendingPromptId||void 0!==a.currentRunId))return(a.pendingAgentSends??=[]).push({message:e,attachments:t,inputProvenance:n}),void this.logger.info?.("[acp-server] Session has active run, deferred message (queue=%d)",a.pendingAgentSends.length);const o=await this.canvasOrch.enrichMessageWithCanvasContext(e,r,this.thirdPartyChannels),c=await this.gateway.agentSend(r,o,i,t,n);return a&&c?.runId&&(this.state.resetForNewRun(a,a.sessionId,this.transport),a.currentRunId=c.runId,a.assistantStreamStartedAt=Date.now(),this.state.promptsByRunId.set(c.runId,a)),c}trackA2ARun(e,t,s){this.a2aOrch.trackA2ARun(e,t,s)}cancelA2ARunByTaskId(e){return this.a2aOrch.cancelA2ARunByTaskId(e)}emitA2ASystemNotification(e){this.a2aOrch.emitA2ASystemNotification(e)}sendBridgeMessage=e=>{const t=this.client;if(t&&t.readyState===WebSocket.OPEN)try{t.send(JSON.stringify(e))}catch(e){this.logger.debug?.("[acp-server] bridge send failed (socket may be closing):",e)}else this.logger.debug?.("[acp-server] bridge not ready, dropping message")};constructor(e,t,s,n,i,a){this.agentFetchFn=n,this.instanceId=i,this.config=e,this.logger=t,this.writeObs=s??(()=>{}),this.thirdPartyChannels=a??new Set,this.transport=new AcpTransport(this.sendBridgeMessage,this.writeObs),this.state=new AcpGatewaySessionState(this.logger);const r=this.agentFetchFn&&this.config.agentGatewayUrl?new BeeosFileResolver({agentGatewayUrl:this.config.agentGatewayUrl,agentFetch:this.agentFetchFn,writeObs:this.writeObs}):void 0;this.core=new AcpGatewayBridgeCore({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,getGateway:()=>this.gateway,instanceId:this.instanceId,thirdPartyChannels:this.thirdPartyChannels,beeosFileResolver:r}),this.canvasOrch=new CanvasOrchestrator({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,getSessionIdForToolCall:e=>this.getSessionIdForToolCall(e),gateway:null,getDefaultAgentId:()=>this.core.getDefaultAgentId(),resolvePlatformAgentId:e=>this.core.resolvePlatformAgentId(e)??""}),this.a2aOrch=new A2AOrchestrator({state:this.state,transport:this.transport,logger:this.logger}),this.events=new AcpGatewayEvents({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,completePrompt:(e,t)=>{this.core.completePrompt(e,t),this.canvasOrch.onPromptComplete(e),this.drainNextDeferredSend(e)},failPrompt:(e,t,s)=>{this.core.failPrompt(e,t,s),this.canvasOrch.onPromptFailed(),this.drainNextDeferredSend(e)},maybeCompletePromptFromChatState:(e,t)=>this.core.maybeCompletePromptFromChatState(e,t),agentFetch:this.agentFetchFn}),this.terminalMgr=new TerminalManager,this.terminalHandler=new TerminalBridgeHandler({terminalMgr:this.terminalMgr,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs}),this.terminalHandler.setupListeners(),this.core.handleTerminalRequest=e=>this.terminalHandler.handleRequest(e),this.core.handleTerminalNotification=(e,t)=>this.terminalHandler.handleNotification(e,t),this.core.onRunComplete=(e,t)=>{this.a2aOrch.onRunComplete(e,t)},this.core.onRunFailed=(e,t)=>{this.a2aOrch.onRunFailed(e,t)},this.core.handleCanvasNotification=(e,t)=>{this.canvasOrch.handleCanvasNotification(e,t)},this.core.getCanvasState=()=>this.canvasOrch.canvasState,this.core.onSessionLoaded=(e,t,s)=>{this.canvasOrch.onSessionLoaded(e,t,s)},this.core.onSessionDeleted=e=>{this.canvasOrch.onSessionDeleted(e)},this.core.onSessionCleared=(e,t)=>{this.canvasOrch.onSessionCleared(e,t)},this.core.handleSlashCommand=async e=>this.canvasOrch.handleSlashCommand(e),this.core.onPromptStart=()=>{this.canvasOrch.onPromptStart()},this.state.startSessionGc(e=>this.core.cleanupPrompt(e),e=>{this.canvasOrch.canvasState?.removeSession(e.gatewaySessionKey),this.transport.resetSessionUpdateCount(e.sessionId)})}async start(e){e&&(this.config.bridge.url=e);const t=this.config.bridge.url,s=this.config.keyFile;if(t&&!BridgeClientCtor)try{const e=await import("@beeos-ai/bridge-client");BridgeClientCtor=e.BridgeClient}catch(e){this.logger.warn?.("[acp-server] Bridge SDK not available")}await this.connectGateway(),t&&s&&BridgeClientCtor?await this.startBridgeMode(t,s):(this.logger.warn?.("[acp-server] Bridge not configured; running in standby (no ACP listener). Use handleUpgrade() for noServer mode."),this.core.markAgentSyncDone())}async startBridgeMode(e,t){if(!BridgeClientCtor)throw new Error("@beeos-ai/bridge-client not available");const s=new BridgeClientCtor({bridgeUrl:e,service:this.config.bridge.service||"acp",keyFile:t});this.bridgeInstance=s,s.on("connected",()=>{this.bridgeConsecutiveFailures=0,this.logger.info?.("[acp-server] Connected to Bridge (publicKey auth)"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"bridge.connected",severity:"info"}),this.tryAgentSync()}),s.on("disconnected",(...e)=>{const n=String(e[0]??"unknown");if(this.logger.warn?.(`[acp-server] Bridge disconnected: ${n}`),this.core.initialized=!1,this.bridgeConsecutiveFailures++,this.bridgeConsecutiveFailures>=ACPServer.RE_DISCOVER_THRESHOLD&&this.agentFetchFn&&this.config.agentGatewayUrl){this.bridgeConsecutiveFailures=0;const e=this.config.bridge.url;discoverBridgeFromGW(this.config.agentGatewayUrl,this.agentFetchFn).then(async n=>{n&&n!==e&&(this.logger.info?.(`[acp-server] Bridge re-discovery: URL changed ${e} → ${n}, switching`),this.config.bridge.url=n,writeDiscoveryCache({bridge:{url:n,discoveredAt:Date.now()}}),await s.close(!1),await this.startBridgeMode(n,t))}).catch(()=>{})}}),s.on("message",(...e)=>{const t=e[0],s="string"==typeof t?t:Buffer.from(t).toString("utf-8");try{const e=JSON.parse(s);"id"in e&&void 0!==e.id?this.core.handleRequest(e):this.core.handleNotification(e)}catch{this.logger.error?.("[acp-server] Invalid JSON-RPC message from Bridge")}}),s.on("error",(...e)=>{const t=e[0];this.logger.error?.("[acp-server] Bridge error:",t?.message)});const n={readyState:WebSocket.OPEN,send:(e,t)=>{try{s.send(e),t?.()}catch(e){t?.(e)}},close:()=>s.close(),terminate:()=>s.close(!1),on:()=>n,once:()=>n,removeListener:()=>n,removeAllListeners:()=>n,ping:()=>{}};Object.defineProperty(n,"readyState",{get:()=>"connected"===s.state?WebSocket.OPEN:WebSocket.CLOSED}),this.client=n;try{await s.connect()}catch(e){this.logger.warn?.(`[acp-server] Initial bridge connect failed (will retry in background): ${e?.message}`)}this.core.initialized=!1,this.logger.info?.("[acp-server] Running in Bridge mode (WS client)")}handleUpgrade(e,t,s){this.wss||(this.wss=new WebSocketServer({noServer:!0}),this.wss.on("connection",(e,t)=>this.handleConnection(e,t))),this.wss.handleUpgrade(e,t,s,t=>{this.wss.emit("connection",t,e)})}async tryAgentSync(e=0){if(this.agentSyncRetryTimer&&(clearTimeout(this.agentSyncRetryTimer),this.agentSyncRetryTimer=null),!this.client||this.client.readyState!==WebSocket.OPEN)return;if(!this.gateway||!this.agentFetchFn||!this.config.agentGatewayUrl)return void this.core.markAgentSyncDone();const t=()=>{if(e+1>=6)return this.logger.warn?.("[acp-server] agent sync exhausted 6 attempts — giving up"),void this.core.markAgentSyncDone();const t=Math.min(5e3*2**e,12e4);this.logger.info?.(`[acp-server] agent sync retry #${e+1} in ${Math.round(t/1e3)}s`),this.agentSyncRetryTimer=setTimeout(()=>this.tryAgentSync(e+1),t)};try{const e=await syncAgentsToPlatform({gateway:this.gateway,agentGatewayUrl:this.config.agentGatewayUrl,capabilities:{canvas:this.config.canvasEnabled,terminal:!0,fileSystem:!0,cron:!0},agentFetch:this.agentFetchFn,logger:this.logger});e?(this.core.setAgentMapping(e),this.logger.info?.(`[acp-server] agent mapping loaded: ${[...e.keys()].join(", ")}`)):t()}catch(e){this.logger.warn?.(`[acp-server] agent sync failed: ${e}`),t()}}async connectGateway(){this.gateway&&(this.gateway.stop(),this.gateway=null);const e=this.config.gateway;this.gateway=new GatewayClient({url:e.url,token:e.token||"",clientId:e.clientId,openclawCanvasCompat:!!this.config.openclawCanvasCompat,retry:{baseMs:this.config.retry.baseMs,maxMs:this.config.retry.maxMs,maxAttempts:this.config.retry.maxAttempts}}),this.gateway.on("chat",e=>this.events.handleChatEvent(e)),this.gateway.on("agent",e=>this.events.handleAgentEvent(e)),this.gateway.on("cron",e=>this.events.handleCronEvent(e));const t=this.gateway;this.canvasOrch.updateDeps({gateway:t?{get isConnected(){return t.isConnected},request:(e,t)=>this.gateway.request(e,t),agentSend:(e,t,s)=>this.gateway.agentSend(e,t,s)}:null}),this.config.openclawCanvasCompat&&(this.gateway.on("canvas",e=>this.canvasOrch.handleOpenClawCanvasEvent(e)),this.logger.info?.("[acp-server] OpenClaw native canvas compat enabled — listening for canvas events")),this.gateway.on("connected",()=>{this.logger.info?.("[acp-server] Connected to OpenClaw Gateway"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"gateway.connected",severity:"info"})}),this.gateway.on("disconnected",()=>{this.logger.warn?.("[acp-server] Gateway disconnected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"gateway.disconnected",severity:"warn"}),this.core.cleanupAllPendingPrompts()}),this.gateway.on("reconnecting",e=>{this.logger.info?.(`[acp-server] Reconnecting to Gateway attempt=${e.attempt} delay=${Math.round(e.delayMs)}ms`)}),this.gateway.on("reconnect-exhausted",e=>{this.logger.error?.(`[acp-server] Gateway reconnect exhausted after ${e} attempts`)}),this.gateway.on("error",e=>{this.logger.error?.("[acp-server] Gateway error:",e.message)}),this.gateway.on("transport",e=>{this.writeObs({component:"gateway-client",domain:"lifecycle",name:`transport.${e.event}`,severity:"connect_fail"===e.event||"error"===e.event?"warn":"debug",payload:e})}),this.gateway.on("reconnect-notify-scheduled",e=>{this.logger.info?.(`[acp-server] Server-initiated reconnect scheduled in ${e.delayMs}ms`)}),this.gateway.on("reconnect-notify-fired",()=>{this.logger.info?.("[acp-server] Server-initiated reconnect firing")});try{await this.gateway.start()}catch(e){this.logger.error?.("[acp-server] Initial Gateway connect failed:",e)}}handleConnection(e,t){if(this.client){this.logger.warn?.("[acp-server] Replacing existing ACP client with new connection (takeover)");const e=this.client;this.client=null;try{e.close(1008,"replaced by new client")}catch{e.terminate()}}this.client=e,this.core.initialized=!1,this.logger.info?.("[acp-server] ACP client connected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"client.connected",severity:"info"}),e.on("message",e=>{const t="string"==typeof e?e:e.toString("utf-8");try{const e=JSON.parse(t);"id"in e&&void 0!==e.id?this.core.handleRequest(e):this.core.handleNotification(e)}catch{this.logger.error?.("[acp-server] Invalid JSON-RPC message")}}),e.on("close",()=>{this.client===e&&(this.client=null,this.core.initialized=!1),this.logger.info?.("[acp-server] ACP client disconnected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"client.disconnected",severity:"info"})})}pushToolResultContent(e,t,s,n){this.core.pushToolResultContent(e,t,s,n)}setCanvasState(e,t){this.canvasOrch.setCanvasState(e,t)}wireRelayActionHandler(){this.canvasOrch.wireRelayActionHandler()}isCanvasActive(e){return this.canvasOrch.isCanvasActive(e)}isCanvasActiveForGatewayKey(e){return this.canvasOrch.isCanvasActiveForGatewayKey(e)}broadcastNotification(e,t){this.transport.sendNotification(e,t)}getActiveSessionId(){return this.state.lastActiveSessionId}getSessionIdForToolCall(e){const t=this.pendingToolCallSessionKeys.length>0?this.pendingToolCallSessionKeys[this.pendingToolCallSessionKeys.length-1]:void 0;if(t){const s=this.state.findSessionByKey(t);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);s?.sessionId&&this.state.toolCallToSessionMap.set(e,s.sessionId)}waitForAgentMapping(){return this.core.waitForAgentMapping()}flushPendingCanvasLinks(){this.canvasOrch.flushPendingCanvasLinks()}onRelayReconnected(){this.canvasOrch.onRelayReconnected()}getDefaultPlatformAgentId(){return this.getDefaultPlatformAgent()?.id}getDefaultPlatformAgent(){const e=this.core.agentMapping;if(e&&0!==e.size)return e.values().next().value??void 0}getPlatformAgentIdForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return this.core.resolvePlatformAgentId(s?.agentId??"")??s?.platformAgentId}getGatewaySessionKeyForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return s?.gatewaySessionKey}getMentionsForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return s?.activeMentions}getResourceRenderer(){return this.canvasOrch.resourceRenderer}getDescriptorRegistry(){return this.canvasOrch.descriptorRegistry}getFormBuilder(){return this.canvasOrch.formBuilder}getSchemaRegistry(){return this.canvasOrch.schemaRegistry}emitCanvasActionAsUserMessage(e,t){this.canvasOrch.emitCanvasActionAsUserMessage(e,t)}async stop(){this.agentSyncRetryTimer&&(clearTimeout(this.agentSyncRetryTimer),this.agentSyncRetryTimer=null),this.state.destroy(),this.a2aOrch.destroy(),this.canvasOrch.destroy(),this.gateway&&(this.gateway.removeAllListeners(),this.gateway.stop(),this.gateway=null),this.client&&(this.client.removeAllListeners(),this.client.close(),this.client=null),this.bridgeInstance=null,this.bridgeConsecutiveFailures=0,this.terminalHandler.destroy(),this.terminalMgr.destroy(),this.wss&&(this.wss.removeAllListeners(),this.wss.close(),this.wss=null),this.logger.info?.("[acp-server] Stopped"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"lifecycle.shutdown",severity:"info"})}}
|
package/dist/canvas/tools.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sv,findRootIds,nextComponentId}from"./a2ui-helpers.js";function nextCid(){return nextComponentId("c")}function textNode(e,t,n="body"){return{id:e,component:{Text:{text:sv(t),usageHint:n}}}}function imageNode(e,t,n="mediumFeature",s,i){const o={url:sv(t),usageHint:n};return s&&(o.fit=s),i&&(o.altText=sv(i)),{id:e,component:{Image:o}}}function iconNode(e,t){return{id:e,component:{Icon:{name:sv(t)}}}}function dividerNode(e,t="horizontal"){return{id:e,component:{Divider:{axis:t}}}}function buttonNode(e,t,n,s){const i={name:n};return s&&(i.context=s),{id:e,component:{Button:{child:t,action:i}}}}function columnNode(e,t,n,s){const i={children:{explicitList:t}};return n&&(i.distribution=n),s&&(i.alignment=s),{id:e,component:{Column:i}}}function rowNode(e,t,n,s){const i={children:{explicitList:t}};return n&&(i.distribution=n),s&&(i.alignment=s),{id:e,component:{Row:i}}}function cardNode(e,t){return{id:e,component:{Card:{child:t}}}}function tabsNode(e,t){return{id:e,component:{Tabs:{tabItems:t.map(e=>({title:sv(e.title),child:e.childId}))}}}}function textFieldNode(e,t,n="shortText",s){const i={label:sv(t),type:n};return s&&(i.text={path:s}),{id:e,component:{TextField:i}}}function checkboxNode(e,t,n){return{id:e,component:{CheckBox:{label:sv(t),value:n?{path:n}:{literalBoolean:!1}}}}}function multipleChoiceNode(e,t,n,s,i){const o={label:sv(t),options:n.map(e=>({label:sv(e.label),value:e.value})),selections:{path:s}};return i&&(o.description=sv(i)),{id:e,component:{MultipleChoice:o}}}function translateComponentsWithDataModel(e){const t={},n=[];for(const s of e){if(!s||"object"!=typeof s){const e=nextCid();n.push(textNode(e,"[invalid component]"));continue}if("form"===("string"==typeof s.type?s.type.toLowerCase():"text")){const e=buildFormWithDataModel(s);n.push(...e.nodes),Object.assign(t,e.dataModel)}else n.push(...translateComponent(s))}return{components:n,dataModel:t}}function translateComponent(e){if(!e||"object"!=typeof e){return[textNode(nextCid(),"[invalid component]")]}const t="string"==typeof e.type?e.type.toLowerCase():"text";switch(t){case"text":return buildText(e);case"card":return buildCard(e);case"table":return buildTable(e);case"form":return buildForm(e);case"image":return buildImage(e);case"button":return buildButton(e);case"grid":return buildGrid(e);case"stat":return buildStat(e);case"key_value":return buildKeyValue(e);case"list":return buildList(e);case"alert":case"callout":return buildAlert(e);case"code":return buildCode(e);case"markdown":return buildMarkdown(e);case"chart":return buildChart(e);case"divider":return buildDivider(e);case"tabs":return buildTabs(e);case"link":return buildLink(e);case"web_embed":case"video":case"audio":case"map":case"file_preview":return buildEmbed(e);case"badge":return buildBadge(e);case"progress":return buildProgress(e);case"timeline":return buildTimeline(e);case"accordion":return buildAccordion(e);case"row":case"column":{const n=(Array.isArray(e.children)?e.children:[]).flatMap(e=>translateComponent(e)),s=findRootIds(n),i=nextCid(),o="row"===t?rowNode(i,s):columnNode(i,s);return[...n,o]}default:return[textNode(nextCid(),`[Unsupported: ${t}]`)]}}function s(e){if(null==e)return"";if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return String(e);try{return JSON.stringify(e)}catch{return"[Object]"}}function buildText(e){return[textNode(nextCid(),s(e.content??e.text??""))]}function buildCard(e){const t=[],n=[];if(e.image){const i=nextCid();t.push(imageNode(i,s(e.image),"mediumFeature","cover")),n.push(i)}if(e.title){const i=nextCid();t.push(textNode(i,s(e.title),"h3")),n.push(i)}if(e.subtitle){const i=nextCid();t.push(textNode(i,s(e.subtitle),"caption")),n.push(i)}if(e.description){const i=nextCid();t.push(textNode(i,s(e.description),"body")),n.push(i)}const i=Array.isArray(e.fields)?e.fields:[];for(const e of i){if(!e||"object"!=typeof e)continue;const i=e,o=nextCid(),a=nextCid(),r=nextCid();t.push(textNode(a,s(i.label??i.key),"caption")),t.push(textNode(r,s(i.value))),t.push(rowNode(o,[a,r],"spaceBetween")),n.push(o)}const o=Array.isArray(e.actions)?e.actions:[];if(o.length>0){const e=[];for(const n of o){if(!n||"object"!=typeof n)continue;const i=n,o=nextCid(),a=nextCid(),r=s(i.label??"Action"),c=s(i.actionId??i.id??nextCid());t.push(textNode(a,r)),t.push(buttonNode(o,a,c,[{key:"actionId",value:{literalString:c}},{key:"label",value:{literalString:r}}])),e.push(o)}if(e.length>0){const s=nextCid();t.push(rowNode(s,e)),n.push(s)}}if(e.footer){const i=nextCid();t.push(textNode(i,s(e.footer),"caption")),n.push(i)}const a=nextCid();t.push(columnNode(a,n));const r=nextCid();return t.push(cardNode(r,a)),t}function buildTable(e){const t=[],n=[],i=Array.isArray(e.columns)?e.columns:[],o=Array.isArray(e.rows)?e.rows:[];if(e.title){const i=nextCid();t.push(textNode(i,s(e.title),"h4")),n.push(i)}const a=[],r=[];for(const e of i)if("string"==typeof e)a.push(e),r.push(e);else if(e&&"object"==typeof e){const t=e,n=s(t.key??t.id??t.field??t.name??t.label??"");a.push(s(t.label??t.title??t.header??t.name??n)),r.push(n)}else{const t=s(e);a.push(t),r.push(t)}if(a.length>0){const e=[];for(const n of a){const s=nextCid();t.push(textNode(s,n,"caption")),e.push(s)}const s=nextCid();t.push(rowNode(s,e)),n.push(s);const i=nextCid();t.push(dividerNode(i)),n.push(i)}for(const e of o){let i;if(Array.isArray(e))i=e;else if(e&&"object"==typeof e&&r.length>0){const t=e;i=r.map(e=>{const n=Object.keys(t).find(t=>t===e||t.toLowerCase()===e.toLowerCase());return null!=n?t[n]:""})}else i=[e];const o=[];for(const e of i){const n=nextCid();t.push(textNode(n,s(e))),o.push(n)}const a=nextCid();t.push(rowNode(a,o)),n.push(a)}const c=nextCid();t.push(columnNode(c,n));const d=nextCid();return t.push(cardNode(d,c)),t}function buildForm(e){return buildFormWithDataModel(e).nodes}function buildFormWithDataModel(e){const t=[],n=[],i=Array.isArray(e.fields)?e.fields:[],o={};if(e.title){const i=nextCid();t.push(textNode(i,s(e.title),"h3")),n.push(i)}if(e.description){const i=nextCid();t.push(textNode(i,s(e.description),"body")),n.push(i)}const a=[];for(const e of i){if(!e||"object"!=typeof e)continue;const i=e,r=nextCid(),c=s(i.name??i.label??r),d=s(i.inputType??i.type??"text"),l=`/${c}`;a.push(c);const u=i.defaultValue??i.default??i.value;if("checkbox"===d||"boolean"===d||"toggle"===d)o[c]=null!=u&&!!u,t.push(checkboxNode(r,s(i.label??i.name??""),l));else if("select"===d||"multi_select"===d||"dropdown"===d||"radio"===d){const e=Array.isArray(i.options)?i.options:[],n=e.map(e=>{if("string"==typeof e)return{label:e,value:e};const t=e;return{label:s(t.label??t.value??""),value:s(t.value??t.label??"")}});if(null!=u)o[c]=String(u);else if(e.length>0){const t=e[0];o[c]="string"==typeof t?t:s(t.value??"")}else o[c]="";t.push(multipleChoiceNode(r,s(i.label??i.name??""),n,l))}else if("datetime"===d||"time"===d){o[c]=null!=u?String(u):"";const e="datetime"===d;t.push({id:r,component:{DateTimeInput:{value:{path:l},enableDate:e,enableTime:!0}}})}else if("range"===d){const e="number"==typeof i.min?i.min:0,n="number"==typeof i.max?i.max:100;o[c]=null!=u?Number(u):e,t.push({id:r,component:{Slider:{label:sv(s(i.label??i.name??"")),value:{path:l},minValue:e,maxValue:n}}})}else{o[c]=null!=u?String(u):"";const e="number"===d?"number":"date"===d?"date":"textarea"===d||"longText"===d?"longText":"shortText";t.push(textFieldNode(r,s(i.label??i.name??""),e,l))}n.push(r)}const r=a.map(e=>({key:e,value:{path:`/${e}`}})),c=nextCid(),d=nextCid();t.push(textNode(c,s(e.submitLabel??"Submit"))),t.push(buttonNode(d,c,s(e.submitActionId??"form_submit"),r)),n.push(d);const l=nextCid();return t.push(columnNode(l,n)),{nodes:t,dataModel:o}}function buildImage(e){const t=nextCid(),n=e.alt??e.altText;return[imageNode(t,s(e.url??e.src??""),"mediumFeature",void 0,n?s(n):void 0)]}function buildButton(e){const t=nextCid(),n=nextCid(),i=s(e.label??"Button"),o=s(e.actionId??n);return[textNode(t,i),buttonNode(n,t,o,[{key:"actionId",value:{literalString:o}},{key:"label",value:{literalString:i}}])]}function buildGrid(e){const t=(Array.isArray(e.children)?e.children:Array.isArray(e.components)?e.components:[]).flatMap(e=>translateComponent(e)),n=Number(e.columns??2),s=findRootIds(t),i=[],o=[];for(let e=0;e<s.length;e+=n){const t=s.slice(e,e+n),a=nextCid();i.push(rowNode(a,t)),o.push(a)}const a=nextCid();return[...t,...i,columnNode(a,o)]}function buildStat(e){const t=[],n=[];if(e.icon){const i=nextCid();t.push(iconNode(i,s(e.icon))),n.push(i)}if(e.label){const i=nextCid();t.push(textNode(i,s(e.label),"caption")),n.push(i)}const i=nextCid();if(t.push(textNode(i,s(e.value??"0"),"h2")),n.push(i),e.change){const i=nextCid(),o="positive"===e.changeType?"↑ ":"negative"===e.changeType?"↓ ":"";t.push(textNode(i,`${o}${s(e.change)}`,"caption")),n.push(i)}if(e.description){const i=nextCid();t.push(textNode(i,s(e.description),"caption")),n.push(i)}const o=nextCid();t.push(columnNode(o,n,void 0,"center"));const a=nextCid();return t.push(cardNode(a,o)),t}function buildKeyValue(e){const t=[],n=[],i=Array.isArray(e.items)?e.items:[];if(e.title){const i=nextCid();t.push(textNode(i,s(e.title),"h4")),n.push(i)}for(const e of i){if(!e||"object"!=typeof e)continue;const i=e,o=nextCid(),a=nextCid(),r=nextCid();t.push(textNode(a,s(i.key??i.label??""),"caption")),t.push(textNode(r,s(i.value??""))),t.push(rowNode(o,[a,r],"spaceBetween")),n.push(o)}const o=nextCid();t.push(columnNode(o,n));const a=nextCid();return t.push(cardNode(a,o)),t}function buildList(e){const t=[],n=[],i=Array.isArray(e.items)?e.items:[];if(e.title){const i=nextCid();t.push(textNode(i,s(e.title),"h4")),n.push(i)}for(const e of i){if(!e||"object"!=typeof e)continue;const i=e,o=[];if(i.image){const e=nextCid();t.push(imageNode(e,s(i.image),"avatar")),o.push(e)}if(i.icon){const e=nextCid();t.push(iconNode(e,s(i.icon))),o.push(e)}const a=[];if(i.title||i.name){const e=nextCid();t.push(textNode(e,s(i.title??i.name),"body")),a.push(e)}if(i.subtitle||i.description){const e=nextCid();t.push(textNode(e,s(i.subtitle??i.description),"caption")),a.push(e)}if(a.length>0){const e=nextCid();t.push(columnNode(e,a)),o.push(e)}if(i.badge||i.value){const e=nextCid();t.push(textNode(e,s(i.badge??i.value),"caption")),o.push(e)}const r=nextCid();t.push(rowNode(r,o,"start","center")),n.push(r)}const o=nextCid();return t.push(columnNode(o,n)),t}function buildAlert(e){const t=[],n=[],i=s(e.variant??"info"),o=nextCid();t.push(iconNode(o,{info:"info",success:"check",warning:"error",error:"error",tip:"info",caution:"error",important:"error",note:"info"}[i]??"info")),n.push(o);const a=[];if(e.title){const n=nextCid();t.push(textNode(n,s(e.title),"h5")),a.push(n)}if(e.message||e.content){const n=nextCid();t.push(textNode(n,s(e.message??e.content))),a.push(n)}if(0===a.length){const n=nextCid();t.push(textNode(n,s(e.type??"Alert"))),a.push(n)}const r=nextCid();t.push(columnNode(r,a)),n.push(r);const c=nextCid();t.push(rowNode(c,n,"start","start"));const d=nextCid();return t.push(cardNode(d,c)),t}function buildCode(e){const t=s(e.code??""),n=s(e.language??""),i=n?`\`\`\`${n}\n${t}\n\`\`\``:`\`\`\`\n${t}\n\`\`\``;return[textNode(nextCid(),i)]}function buildMarkdown(e){return[textNode(nextCid(),s(e.content??""))]}function buildChart(e){const t=nextCid(),n=s(e.chartType??"chart");return[textNode(t,`[${e.title?s(e.title):n} — chart visualization not available in standard catalog]`,"caption")]}function buildDivider(e){return[dividerNode(nextCid())]}function buildTabs(e){const t=Array.isArray(e.tabs)?e.tabs:Array.isArray(e.children)?e.children:Array.isArray(e.items)?e.items:[];if(0===t.length){return[textNode(nextCid(),s(e.title??""))]}const n=[],i=[];for(const e of t){const t=s(e.label??e.title??e.id??"Tab"),o=(Array.isArray(e.children)?e.children:[]).flatMap(e=>translateComponent(e));n.push(...o);const a=findRootIds(o),r=nextCid();n.push(columnNode(r,a)),i.push({title:t,childId:r})}const o=nextCid();return n.push(tabsNode(o,i)),n}function buildLink(e){const t=nextCid(),n=nextCid();return[textNode(t,s(e.text??e.label??e.url??"Link")),buttonNode(n,t,"navigate",[{key:"url",value:{literalString:s(e.url??"")}}])]}function buildEmbed(e){const t=s(e.url??"");if(/youtube|youtu\.be|vimeo/i.test(t)){return[{id:nextCid(),component:{Video:{url:sv(t)}}}]}return buildLink({text:s(e.title??t),url:t})}function buildBadge(e){return[textNode(nextCid(),s(e.text??e.label??""),"caption")]}function buildProgress(e){const t=Number(e.value??0),n=Number(e.max??100),i=n>0?Math.round(t/n*100):0;return[textNode(nextCid(),`${s(e.label)||"Progress"}: ${i}% (${t}/${n})`)]}function buildTimeline(e){const t=(Array.isArray(e.items)?e.items:[]).filter(e=>null!=e&&"object"==typeof e).map(e=>`${s(e.time??e.date??"")} — ${s(e.title??"")}${e.description?`: ${s(e.description)}`:""}`),n=e.title?`**${s(e.title)}**\n`:"";return[textNode(nextCid(),n+(t.length>0?t.join("\n"):"(empty timeline)"))]}function buildAccordion(e){const t=Array.isArray(e.items)?e.items:Array.isArray(e.children)?e.children:[];if(0===t.length){return[textNode(nextCid(),s(e.title??""))]}const n=[];for(const e of t){const t=nextCid();n.push(textNode(t,s(e.title??e.label??""),"h5"));const i=Array.isArray(e.children)?e.children.flatMap(e=>translateComponent(e)):[];n.push(...i)}return n}export const RENDER_UI_TOOL_NAME="render_ui";export const CLOSE_UI_TOOL_NAME="close_ui";export const RENDER_UI_TOOL_DESCRIPTION="Render structured visual content to the Canvas panel. ALWAYS prefer this tool over the canvas tool for displaying UI. Use for charts, tables, stats, key-value pairs, lists, cards, forms, alerts, code, markdown, images, links, web embeds — NOT for text paragraphs. When you call this tool, keep your text reply brief.";export const CLOSE_UI_TOOL_DESCRIPTION="Close and remove a UI surface that was previously rendered.";export const RENDER_UI_TOOL_SCHEMA={type:"object",required:["id","components"],properties:{id:{type:"string",description:"Descriptive, human-readable identifier (e.g., 'sales-report', 'user-dashboard'). Reuse same id to update an existing surface."},components:{type:["array","string"],description:"UI components to render",items:{type:"object",required:["type"],properties:{type:{type:"string",enum:["card","table","stat","key_value","list","grid","chart","markdown","code","text","image","web_embed","alert","form","button","link"]},title:{type:"string"},content:{type:"string"},label:{type:"string"},description:{type:"string"},url:{type:"string"},image:{type:"string"},subtitle:{type:"string"},badge:{type:"string"},badgeVariant:{type:"string",enum:["default","success","warning","error","info"]},footer:{type:"string"},layout:{type:"string",enum:["vertical","horizontal"]},actions:{type:"array",description:"Card action buttons: [{label, actionId, variant?}]"},fields:{type:"array",description:"For card: [{label,value}]. For form: [{name,label,inputType,options,...}]"},children:{type:"array",description:"For grid: nested child components (card, stat, image, etc.)"},gap:{type:"string",enum:["sm","md","lg"]},columns:{type:"array",description:"Column headers or grid column count"},rows:{type:"array",description:"Row data as arrays matching column order"},submitLabel:{type:"string"},submitActionId:{type:"string"},actionId:{type:"string"},alt:{type:"string"},aspectRatio:{type:"string",enum:["16:9","4:3","1:1"]},chartType:{type:"string",enum:["bar","horizontal_bar","line","area","scatter","pie","doughnut","radar","gauge","candlestick","funnel","sparkline"]},stages:{type:"array"},labels:{type:"array"},datasets:{type:"array"},language:{type:"string"},code:{type:"string"},items:{type:"array"},variant:{type:"string"},message:{type:"string"},value:{type:"number"},max:{type:"number"},change:{type:"string"},changeType:{type:"string",enum:["positive","negative","neutral"]},icon:{type:"string"},text:{type:"string"}}}}}};export const CLOSE_UI_TOOL_SCHEMA={type:"object",required:["id"],properties:{id:{type:"string",description:"The UI identifier to close"}}};async function ensureRelayConnected(e,t,n,s){const{stateManager:i,logger:o}=e,a=s??e.getGatewaySessionKey?.(n),r=a??t,c=i.resolveCanvasForSession(r);if(c&&i.isCanvasJoined(c))return c;const d=i.getRelayClient();if(d)try{e.waitForAgentSync&&await e.waitForAgentSync();const s=e.getPlatformAgentId?.(n),c=a??t,l=a&&a!==t?t:void 0,u=await d.ensureCanvas(c,{agentId:s,linkSessionId:l});return await i.joinCanvas(u,r),o.info?.(`[canvas] Joined canvas=${u} session=${t} gatewayKey=${a??"none"} agentId=${s??"none"}`),u}catch(e){return void o.warn?.(`[canvas] Failed to join canvas relay: ${e}`)}}export function createRenderUiHandler(e){const{stateManager:t,logger:n,writeObs:s,isCanvasActive:i}=e;let o=0;return async(a,r)=>{if(i&&!i())return{success:!1,error:"Canvas is disabled by user. Respond with plain text instead."};const c=r,d=c.id,l="panel";let u=c.components;if("string"==typeof u)try{u=JSON.parse(u)}catch{}if(!d||!Array.isArray(u)||!u.length)return{success:!1,error:"id and components (array) are required"};if(!t.validateComponentCount(u))return{success:!1,error:"Too many components (max 500)"};if(!t.checkRateLimit(d))return n.warn?.(`[canvas] Rate limited surfaceId=${d}`),s({component:"canvas",domain:"canvas",name:"canvas.rate_limited",severity:"warn",payload:{surfaceId:d}}),{success:!1,error:"Rate limited — too many updates per second"};const p=translateComponentsWithDataModel(u),m=p.components,f=Object.keys(p.dataModel).length>0?p.dataModel:void 0,h=findRootIds(m),b=nextCid(),g=columnNode(b,h),y=[...m,g],x=e.getActiveSessionId?.(a);if(!x)return n.warn?.(`[canvas] No active session for toolCallId=${a}, skipping render_ui`),{success:!1,error:"No active session — canvas operation skipped"};const v=e.getGatewaySessionKey?.(a),C=await ensureRelayConnected(e,x,a,v),N=t.has(d,C??void 0),w=Date.now(),A=t.getRelayClient();C&&A&&w-o>6e4&&A.createSnapshot(C,"Pre-agent edit").then(()=>{o=Date.now(),n.debug?.("[canvas] Pre-edit checkpoint created")}).catch(e=>n.warn?.(`[canvas] Pre-edit checkpoint failed: ${e}`)),N?t.update(d,y,C,b,f):t.create(C??`_fallback_${Date.now()}`,d,l,y,{origin:{kind:"agent"},rootComponentId:b,dataModel:f});const I=u.map(e=>e.type);s({component:"canvas",domain:"canvas",name:N?"canvas.update_sent":"canvas.surface_created",severity:"info",payload:{surfaceId:d,presentation:l,componentCount:u.length,componentTypes:I}}),n.debug?.(`[canvas] ${N?"Updated":"Created"} surface=${d} components=${u.length}`);return{success:!0,surfaceId:d,presentation:l,isUpdate:N,activeSurfaces:C?t.getAllActive(C).map(e=>e.surfaceId):[d]}}}export function createCloseUiHandler(e){const{stateManager:t,logger:n,writeObs:s}=e;return async(i,o)=>{const a=o.id;if(!a)return{success:!1,error:"id is required"};const r=t.get(a),c=r?Date.now()-r.createdAt:0,d=e.getGatewaySessionKey?.(i),l=d?t.resolveCanvasForSession(d):void 0;return t.delete(a,l),s({component:"canvas",domain:"canvas",name:"canvas.surface_closed",severity:"info",payload:{surfaceId:a,lifetime_ms:c}}),n.debug?.(`[canvas] Closed surface=${a}`),{success:!0,surfaceId:a,message:"UI closed"}}}export function buildCanvasActionSystemMessage(e){const t=e.userAction;return{type:"canvas_user_action",surfaceId:e.surfaceId,actionName:t?.name??"unknown",sourceComponentId:t?.sourceComponentId??"",context:t?.context??{}}}export const CANVAS_SYSTEM_PROMPT='## Canvas UI\n\n**IMPORTANT: Always use `render_ui` (not the built-in `canvas` tool) to display visual/structured content.** The `render_ui` tool is the preferred and optimized way to render UI in the Canvas panel.\n\nRules:\n- When using render_ui, keep your chat reply to ONE short sentence. Do NOT repeat data shown in canvas.\n- Use render_ui for structured data, visualizations, forms, dashboards. Use plain text for explanations.\n- Do NOT put large text blocks in render_ui — that belongs in chat.\n- Only use `grid` as a layout container. Keep nesting to grid > card/stat/image — max 1 level deep. Otherwise list components sequentially (they stack vertically).\n- Prefer fewer, larger components. One well-structured table is better than many small cards.\n- Canvas renders in a narrow sidebar (~400px). Use markdown headings (### Section) to organize sections.\n- Use grid + card for product showcases, dashboards, feature grids. Use list for compact item lists.\n\n**Surface IDs**: Use descriptive, human-readable IDs (e.g., "sales-report", "user-dashboard"). Never use generic IDs like "ui1" or random strings.\n\n**Update vs Create**: Same `id` updates existing surface; different `id` creates new one.\nWhen the user asks to modify, adjust, fix, or update existing canvas content, you MUST reuse the original surface id. Check [Canvas State] in the message for active surface ids and their content. Only create a new surface when showing genuinely new/different content.\n\n### Component Types\n\n**Layout**: grid (columns:1-6, gap:sm/md/lg, children:[...]) — responsive grid container for card/stat/image\n\n**Data Display**: card (image, title, subtitle, description, icon, badge, footer, actions:[{label,actionId}], fields:[{label,value}]), table (columns, rows), stat (label, value, change, changeType, icon), key_value (items:[{key,value}]), list (items:[{title,subtitle,description,image,icon,badge,value}])\n\n**Text & Code**: text (content), markdown (content — supports full Markdown including bold, italic, lists, code blocks, links), code (language, code)\n\n**Media**: image (url, alt), web_embed (url — video URLs auto-detected), link (text, url)\n\n**Feedback**: alert (variant:info/success/warning/error, title, message)\n\n**Interactive**: form (fields:[{name,label,inputType,options:[{label,value}]}], submitLabel), button (label, actionId)\n - inputType: text (default), number, date, textarea, checkbox, boolean, toggle, select, multi_select, radio, datetime, time, range\n - select/multi_select/radio requires an `options` array — each item is {label, value} or a plain string\n - range renders a slider (optional min, max — default 0..100)\n\n### Composition Patterns\n- **Product showcase**: grid(columns:3) containing card(image, title, description, badge:"$29", actions:[{label:"Buy"}]) × N\n- **Dashboard KPIs**: grid(columns:3) containing stat × N\n- **Image gallery**: grid(columns:3) containing image × N\n- **Feature grid**: grid(columns:2) containing card(icon, title, description) × N\n- **Compact item list**: list(items:[{image, title, subtitle, value:"$29", badge:"New"}])\n- **Detail card**: card(title, description, fields:[{label:"Price",value:"$29"},{label:"Stock",value:"142"}])\n- **Form with select**: form(title:"Settings", fields:[{name:"country", label:"Country", inputType:"select", options:[{label:"China",value:"CN"},{label:"US",value:"US"}]}, {name:"email", label:"Email"}], submitLabel:"Save")\n\n### render_form\nUse `render_form` for schema-driven forms when a domain schema exists.\nParameters: `domain`, `operation`, `data`, `entityId`.\n\n### close_ui\nCloses a UI surface. Use when user moves to a new topic or explicitly dismisses.\n';export const CANVAS_TERM_MAPPING="[System Note] Always use `render_ui` (not the canvas tool) for visual/structured content (tables, stats, key-value, lists, cards, grids, alerts, forms, links, images, code, markdown). Use grid(columns, children:[card/stat/image]) for multi-column layouts like product showcases and dashboards. Card supports: image, title, subtitle, description, icon, badge, footer, actions, fields:[{label,value}]. List items support: image, title, subtitle, description, badge, value. Markdown content supports full formatting. Use web_embed for embedding URLs. Use link for navigation. Form supports inputType: text/number/date/textarea/checkbox/toggle/select/multi_select/radio/datetime/time/range; select/multi_select/radio requires options:[{label,value}]. Keep chat brief when canvas is used. Use `close_ui` to dismiss. Reuse same id to update; new id for new content.";export const CANVAS_UPDATE_HINT="[Canvas Rule] Same id in render_ui = update existing surface. Different id = new surface. When a surface is referenced for editing, you MUST reuse its exact id.";const MAX_CONTEXT_SURFACES=8,MAX_CONTEXT_CHARS=500;export function buildActiveSurfacesContext(e,t){let n;if(!t)return null;if(n=e.getAllActive(t),0===n.length)return null;const s=[...n].sort((e,t)=>t.updatedAt-e.updatedAt).slice(0,8),i=n.length-s.length;let o=`[Canvas State] Active surfaces: ${s.map(t=>{const n=e.summarize(t.surfaceId);if(!n)return`"${t.surfaceId}"`;const s=n.types.slice(0,3).join(", "),i=n.title?`: "${n.title}"`:"";return`"${t.surfaceId}" (${s}${i})`}).join("; ")}.`;return i>0&&(o+=` ...and ${i} more.`),o+=" To modify existing content, reuse its id in render_ui.",o.length>500&&(o=o.slice(0,497)+"..."),o}
|
|
1
|
+
import{sv,findRootIds,nextComponentId}from"./a2ui-helpers.js";function nextCid(){return nextComponentId("c")}function textNode(e,t,n="body"){return{id:e,component:{Text:{text:sv(t),usageHint:n}}}}function imageNode(e,t,n="mediumFeature",s,a){const i={url:sv(t),usageHint:n};return s&&(i.fit=s),a&&(i.altText=sv(a)),{id:e,component:{Image:i}}}function iconNode(e,t){return{id:e,component:{Icon:{name:sv(t)}}}}function dividerNode(e,t="horizontal"){return{id:e,component:{Divider:{axis:t}}}}function buttonNode(e,t,n,s){const a={name:n};return s&&(a.context=s),{id:e,component:{Button:{child:t,action:a}}}}function columnNode(e,t,n,s){const a={children:{explicitList:t}};return n&&(a.distribution=n),s&&(a.alignment=s),{id:e,component:{Column:a}}}function rowNode(e,t,n,s){const a={children:{explicitList:t}};return n&&(a.distribution=n),s&&(a.alignment=s),{id:e,component:{Row:a}}}function cardNode(e,t){return{id:e,component:{Card:{child:t}}}}function tabsNode(e,t){return{id:e,component:{Tabs:{tabItems:t.map(e=>({title:sv(e.title),child:e.childId}))}}}}function textFieldNode(e,t,n="shortText",s){const a={label:sv(t),type:n};return s&&(a.text={path:s}),{id:e,component:{TextField:a}}}function checkboxNode(e,t,n){return{id:e,component:{CheckBox:{label:sv(t),value:n?{path:n}:{literalBoolean:!1}}}}}function multipleChoiceNode(e,t,n,s,a){const i={label:sv(t),options:n.map(e=>({label:sv(e.label),value:e.value})),selections:{path:s}};return a&&(i.description=sv(a)),{id:e,component:{MultipleChoice:i}}}function translateComponentsWithDataModel(e){const t={},n=[];for(const s of e){if(!s||"object"!=typeof s){const e=nextCid();n.push(textNode(e,"[invalid component]"));continue}if("form"===("string"==typeof s.type?s.type.toLowerCase():"text")){const e=buildFormWithDataModel(s);n.push(...e.nodes),Object.assign(t,e.dataModel)}else n.push(...translateComponent(s))}return{components:n,dataModel:t}}function translateComponent(e){if(!e||"object"!=typeof e){return[textNode(nextCid(),"[invalid component]")]}const t="string"==typeof e.type?e.type.toLowerCase():"text";switch(t){case"text":return buildText(e);case"card":return buildCard(e);case"table":return buildTable(e);case"form":return buildForm(e);case"image":return buildImage(e);case"button":return buildButton(e);case"grid":return buildGrid(e);case"stat":return buildStat(e);case"key_value":return buildKeyValue(e);case"list":return buildList(e);case"alert":case"callout":return buildAlert(e);case"code":return buildCode(e);case"markdown":return buildMarkdown(e);case"chart":return buildChart(e);case"divider":return buildDivider(e);case"tabs":return buildTabs(e);case"link":return buildLink(e);case"web_embed":case"video":case"audio":case"map":case"file_preview":return buildEmbed(e);case"badge":return buildBadge(e);case"progress":return buildProgress(e);case"timeline":return buildTimeline(e);case"accordion":return buildAccordion(e);case"row":case"column":{const n=(Array.isArray(e.children)?e.children:[]).flatMap(e=>translateComponent(e)),s=findRootIds(n),a=nextCid(),i="row"===t?rowNode(a,s):columnNode(a,s);return[...n,i]}default:return[textNode(nextCid(),`[Unsupported: ${t}]`)]}}function s(e){if(null==e)return"";if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return String(e);try{return JSON.stringify(e)}catch{return"[Object]"}}function buildText(e){return[textNode(nextCid(),s(e.content??e.text??""))]}function buildCard(e){const t=[],n=[];if(e.image){const a=nextCid();t.push(imageNode(a,s(e.image),"mediumFeature","cover")),n.push(a)}if(e.title){const a=nextCid();t.push(textNode(a,s(e.title),"h3")),n.push(a)}if(e.subtitle){const a=nextCid();t.push(textNode(a,s(e.subtitle),"caption")),n.push(a)}if(e.description){const a=nextCid();t.push(textNode(a,s(e.description),"body")),n.push(a)}const a=Array.isArray(e.fields)?e.fields:[];for(const e of a){if(!e||"object"!=typeof e)continue;const a=e,i=nextCid(),o=nextCid(),r=nextCid();t.push(textNode(o,s(a.label??a.key),"caption")),t.push(textNode(r,s(a.value))),t.push(rowNode(i,[o,r],"spaceBetween")),n.push(i)}const i=Array.isArray(e.actions)?e.actions:[];if(i.length>0){const e=[];for(const n of i){if(!n||"object"!=typeof n)continue;const a=n,i=nextCid(),o=nextCid(),r=s(a.label??"Action"),l=s(a.actionId??a.id??nextCid());t.push(textNode(o,r)),t.push(buttonNode(i,o,l,[{key:"actionId",value:{literalString:l}},{key:"label",value:{literalString:r}}])),e.push(i)}if(e.length>0){const s=nextCid();t.push(rowNode(s,e)),n.push(s)}}if(e.footer){const a=nextCid();t.push(textNode(a,s(e.footer),"caption")),n.push(a)}const o=nextCid();t.push(columnNode(o,n));const r=nextCid();return t.push(cardNode(r,o)),t}function buildTable(e){const t=[],n=[],a=Array.isArray(e.columns)?e.columns:[],i=Array.isArray(e.rows)?e.rows:[];if(e.title){const a=nextCid();t.push(textNode(a,s(e.title),"h4")),n.push(a)}const o=[],r=[];for(const e of a)if("string"==typeof e)o.push(e),r.push(e);else if(e&&"object"==typeof e){const t=e,n=s(t.key??t.id??t.field??t.name??t.label??"");o.push(s(t.label??t.title??t.header??t.name??n)),r.push(n)}else{const t=s(e);o.push(t),r.push(t)}if(o.length>0){const e=[];for(const n of o){const s=nextCid();t.push(textNode(s,n,"caption")),e.push(s)}const s=nextCid();t.push(rowNode(s,e)),n.push(s);const a=nextCid();t.push(dividerNode(a)),n.push(a)}for(const e of i){let a;if(Array.isArray(e))a=e;else if(e&&"object"==typeof e&&r.length>0){const t=e;a=r.map(e=>{const n=Object.keys(t).find(t=>t===e||t.toLowerCase()===e.toLowerCase());return null!=n?t[n]:""})}else a=[e];const i=[];for(const e of a){const n=nextCid();t.push(textNode(n,s(e))),i.push(n)}const o=nextCid();t.push(rowNode(o,i)),n.push(o)}const l=nextCid();t.push(columnNode(l,n));const c=nextCid();return t.push(cardNode(c,l)),t}function buildForm(e){return buildFormWithDataModel(e).nodes}function buildFormWithDataModel(e){const t=[],n=[],a=Array.isArray(e.fields)?e.fields:[],i={};if(e.title){const a=nextCid();t.push(textNode(a,s(e.title),"h3")),n.push(a)}if(e.description){const a=nextCid();t.push(textNode(a,s(e.description),"body")),n.push(a)}const o=[];for(const e of a){if(!e||"object"!=typeof e)continue;const a=e,r=nextCid(),l=s(a.name??a.label??r),c=s(a.inputType??a.type??"text"),d=`/${l}`;o.push(l);const u=a.defaultValue??a.default??a.value;if("checkbox"===c||"boolean"===c||"toggle"===c)i[l]=null!=u&&!!u,t.push(checkboxNode(r,s(a.label??a.name??""),d));else if("select"===c||"multi_select"===c||"dropdown"===c||"radio"===c){const e=Array.isArray(a.options)?a.options:[],n=e.map(e=>{if("string"==typeof e)return{label:e,value:e};const t=e;return{label:s(t.label??t.value??""),value:s(t.value??t.label??"")}});if(null!=u)i[l]=String(u);else if(e.length>0){const t=e[0];i[l]="string"==typeof t?t:s(t.value??"")}else i[l]="";t.push(multipleChoiceNode(r,s(a.label??a.name??""),n,d))}else if("datetime"===c||"time"===c){i[l]=null!=u?String(u):"";const e="datetime"===c;t.push({id:r,component:{DateTimeInput:{value:{path:d},enableDate:e,enableTime:!0}}})}else if("range"===c){const e="number"==typeof a.min?a.min:0,n="number"==typeof a.max?a.max:100;i[l]=null!=u?Number(u):e,t.push({id:r,component:{Slider:{label:sv(s(a.label??a.name??"")),value:{path:d},minValue:e,maxValue:n}}})}else{i[l]=null!=u?String(u):"";const e="number"===c?"number":"date"===c?"date":"textarea"===c||"longText"===c?"longText":"shortText";t.push(textFieldNode(r,s(a.label??a.name??""),e,d))}n.push(r)}const r=o.map(e=>({key:e,value:{path:`/${e}`}})),l=nextCid(),c=nextCid();t.push(textNode(l,s(e.submitLabel??"Submit"))),t.push(buttonNode(c,l,s(e.submitActionId??"form_submit"),r)),n.push(c);const d=nextCid();return t.push(columnNode(d,n)),{nodes:t,dataModel:i}}function buildImage(e){const t=nextCid(),n=e.alt??e.altText;return[imageNode(t,s(e.url??e.src??""),"mediumFeature",void 0,n?s(n):void 0)]}function buildButton(e){const t=nextCid(),n=nextCid(),a=s(e.label??"Button"),i=s(e.actionId??n);return[textNode(t,a),buttonNode(n,t,i,[{key:"actionId",value:{literalString:i}},{key:"label",value:{literalString:a}}])]}function buildGrid(e){const t=(Array.isArray(e.children)?e.children:Array.isArray(e.components)?e.components:[]).flatMap(e=>translateComponent(e)),n=Number(e.columns??2),s=findRootIds(t),a=[],i=[];for(let e=0;e<s.length;e+=n){const t=s.slice(e,e+n),o=nextCid();a.push(rowNode(o,t)),i.push(o)}const o=nextCid();return[...t,...a,columnNode(o,i)]}function buildStat(e){const t=[],n=[];if(e.icon){const a=nextCid();t.push(iconNode(a,s(e.icon))),n.push(a)}if(e.label){const a=nextCid();t.push(textNode(a,s(e.label),"caption")),n.push(a)}const a=nextCid();if(t.push(textNode(a,s(e.value??"0"),"h2")),n.push(a),e.change){const a=nextCid(),i="positive"===e.changeType?"↑ ":"negative"===e.changeType?"↓ ":"";t.push(textNode(a,`${i}${s(e.change)}`,"caption")),n.push(a)}if(e.description){const a=nextCid();t.push(textNode(a,s(e.description),"caption")),n.push(a)}const i=nextCid();t.push(columnNode(i,n,void 0,"center"));const o=nextCid();return t.push(cardNode(o,i)),t}function buildKeyValue(e){const t=[],n=[],a=Array.isArray(e.items)?e.items:[];if(e.title){const a=nextCid();t.push(textNode(a,s(e.title),"h4")),n.push(a)}for(const e of a){if(!e||"object"!=typeof e)continue;const a=e,i=nextCid(),o=nextCid(),r=nextCid();t.push(textNode(o,s(a.key??a.label??""),"caption")),t.push(textNode(r,s(a.value??""))),t.push(rowNode(i,[o,r],"spaceBetween")),n.push(i)}const i=nextCid();t.push(columnNode(i,n));const o=nextCid();return t.push(cardNode(o,i)),t}function buildList(e){const t=[],n=[],a=Array.isArray(e.items)?e.items:[];if(e.title){const a=nextCid();t.push(textNode(a,s(e.title),"h4")),n.push(a)}for(const e of a){if(!e||"object"!=typeof e)continue;const a=e,i=[];if(a.image){const e=nextCid();t.push(imageNode(e,s(a.image),"avatar")),i.push(e)}if(a.icon){const e=nextCid();t.push(iconNode(e,s(a.icon))),i.push(e)}const o=[];if(a.title||a.name){const e=nextCid();t.push(textNode(e,s(a.title??a.name),"body")),o.push(e)}if(a.subtitle||a.description){const e=nextCid();t.push(textNode(e,s(a.subtitle??a.description),"caption")),o.push(e)}if(o.length>0){const e=nextCid();t.push(columnNode(e,o)),i.push(e)}if(a.badge||a.value){const e=nextCid();t.push(textNode(e,s(a.badge??a.value),"caption")),i.push(e)}const r=nextCid();t.push(rowNode(r,i,"start","center")),n.push(r)}const i=nextCid();return t.push(columnNode(i,n)),t}function buildAlert(e){const t=[],n=[],a=s(e.variant??"info"),i=nextCid();t.push(iconNode(i,{info:"info",success:"check",warning:"error",error:"error",tip:"info",caution:"error",important:"error",note:"info"}[a]??"info")),n.push(i);const o=[];if(e.title){const n=nextCid();t.push(textNode(n,s(e.title),"h5")),o.push(n)}if(e.message||e.content){const n=nextCid();t.push(textNode(n,s(e.message??e.content))),o.push(n)}if(0===o.length){const n=nextCid();t.push(textNode(n,s(e.type??"Alert"))),o.push(n)}const r=nextCid();t.push(columnNode(r,o)),n.push(r);const l=nextCid();t.push(rowNode(l,n,"start","start"));const c=nextCid();return t.push(cardNode(c,l)),t}function buildCode(e){const t=s(e.code??""),n=s(e.language??""),a=n?`\`\`\`${n}\n${t}\n\`\`\``:`\`\`\`\n${t}\n\`\`\``;return[textNode(nextCid(),a)]}function buildMarkdown(e){return[textNode(nextCid(),s(e.content??""))]}function normalizeDatasets(e){return e.map(e=>{if(!e||"object"!=typeof e)return e;const t={label:e.label??e.name??"",data:Array.isArray(e.data)?e.data.map(e=>e&&"object"==typeof e&&("o"in e||"h"in e||"l"in e||"c"in e)?{open:e.o??e.open,high:e.h??e.high,low:e.l??e.low,close:e.c??e.close}:e):e.data};return e.color&&(t.color=e.color),t})}function buildChart(e){const t=nextCid(),n=s(e.chartType??"bar"),a={chartType:sv(n)};e.title&&(a.title=sv(s(e.title))),Array.isArray(e.labels)&&(a.labels=e.labels.map(e=>"string"==typeof e?e:String(e??"")));const i=Array.isArray(e.datasets)?e.datasets:Array.isArray(e.stages)?e.stages:null;return i&&(a.datasets=normalizeDatasets(i)),void 0!==e.value&&(a.value="number"==typeof e.value?e.value:Number(e.value)||0),void 0!==e.max&&(a.max="number"==typeof e.max?e.max:Number(e.max)||100),[{id:t,component:{Chart:a}}]}function buildDivider(e){return[dividerNode(nextCid())]}function buildTabs(e){const t=Array.isArray(e.tabs)?e.tabs:Array.isArray(e.children)?e.children:Array.isArray(e.items)?e.items:[];if(0===t.length){return[textNode(nextCid(),s(e.title??""))]}const n=[],a=[];for(const e of t){const t=s(e.label??e.title??e.id??"Tab"),i=(Array.isArray(e.children)?e.children:[]).flatMap(e=>translateComponent(e));n.push(...i);const o=findRootIds(i),r=nextCid();n.push(columnNode(r,o)),a.push({title:t,childId:r})}const i=nextCid();return n.push(tabsNode(i,a)),n}function buildLink(e){const t=nextCid(),n=nextCid();return[textNode(t,s(e.text??e.label??e.url??"Link")),buttonNode(n,t,"navigate",[{key:"url",value:{literalString:s(e.url??"")}}])]}function buildEmbed(e){const t=s(e.url??"");if(/youtube|youtu\.be|vimeo/i.test(t)){return[{id:nextCid(),component:{Video:{url:sv(t)}}}]}return buildLink({text:s(e.title??t),url:t})}function buildBadge(e){return[textNode(nextCid(),s(e.text??e.label??""),"caption")]}function buildProgress(e){const t=Number(e.value??0),n=Number(e.max??100),a=n>0?Math.round(t/n*100):0;return[textNode(nextCid(),`${s(e.label)||"Progress"}: ${a}% (${t}/${n})`)]}function buildTimeline(e){const t=(Array.isArray(e.items)?e.items:[]).filter(e=>null!=e&&"object"==typeof e).map(e=>`${s(e.time??e.date??"")} — ${s(e.title??"")}${e.description?`: ${s(e.description)}`:""}`),n=e.title?`**${s(e.title)}**\n`:"";return[textNode(nextCid(),n+(t.length>0?t.join("\n"):"(empty timeline)"))]}function buildAccordion(e){const t=Array.isArray(e.items)?e.items:Array.isArray(e.children)?e.children:[];if(0===t.length){return[textNode(nextCid(),s(e.title??""))]}const n=[];for(const e of t){const t=nextCid();n.push(textNode(t,s(e.title??e.label??""),"h5"));const a=Array.isArray(e.children)?e.children.flatMap(e=>translateComponent(e)):[];n.push(...a)}return n}export const RENDER_UI_TOOL_NAME="render_ui";export const CLOSE_UI_TOOL_NAME="close_ui";export const RENDER_UI_TOOL_DESCRIPTION="Render structured visual content to the Canvas panel. ALWAYS prefer this tool over the canvas tool for displaying UI. Use for charts, tables, stats, key-value pairs, lists, cards, forms, alerts, code, markdown, images, links, web embeds — NOT for text paragraphs. When you call this tool, keep your text reply brief.";export const CLOSE_UI_TOOL_DESCRIPTION="Close and remove a UI surface that was previously rendered.";export const RENDER_UI_TOOL_SCHEMA={type:"object",required:["id","components"],properties:{id:{type:"string",description:"Descriptive, human-readable identifier (e.g., 'sales-report', 'user-dashboard'). Reuse same id to update an existing surface."},components:{type:["array","string"],description:"UI components to render",items:{type:"object",required:["type"],properties:{type:{type:"string",enum:["card","table","stat","key_value","list","grid","chart","markdown","code","text","image","web_embed","alert","form","button","link"]},title:{type:"string"},content:{type:"string"},label:{type:"string"},description:{type:"string"},url:{type:"string"},image:{type:"string"},subtitle:{type:"string"},badge:{type:"string"},badgeVariant:{type:"string",enum:["default","success","warning","error","info"]},footer:{type:"string"},layout:{type:"string",enum:["vertical","horizontal"]},actions:{type:"array",description:"Card action buttons: [{label, actionId, variant?}]"},fields:{type:"array",description:"For card: [{label,value}]. For form: [{name,label,inputType,options,...}]"},children:{type:"array",description:"For grid: nested child components (card, stat, image, etc.)"},gap:{type:"string",enum:["sm","md","lg"]},columns:{type:"array",description:"Column headers or grid column count"},rows:{type:"array",description:"Row data as arrays matching column order"},submitLabel:{type:"string"},submitActionId:{type:"string"},actionId:{type:"string"},alt:{type:"string"},aspectRatio:{type:"string",enum:["16:9","4:3","1:1"]},chartType:{type:"string",enum:["bar","horizontal_bar","line","area","scatter","pie","doughnut","radar","gauge","candlestick","funnel","sparkline"]},stages:{type:"array"},labels:{type:"array"},datasets:{type:"array"},language:{type:"string"},code:{type:"string"},items:{type:"array"},variant:{type:"string"},message:{type:"string"},value:{type:"number"},max:{type:"number"},change:{type:"string"},changeType:{type:"string",enum:["positive","negative","neutral"]},icon:{type:"string"},text:{type:"string"}}}}}};export const CLOSE_UI_TOOL_SCHEMA={type:"object",required:["id"],properties:{id:{type:"string",description:"The UI identifier to close"}}};async function ensureRelayConnected(e,t,n,s){const{stateManager:a,logger:i}=e,o=s??e.getGatewaySessionKey?.(n),r=o??t,l=a.resolveCanvasForSession(r);if(l&&a.isCanvasJoined(l))return l;const c=a.getRelayClient();if(c)try{e.waitForAgentSync&&await e.waitForAgentSync();const s=e.getPlatformAgentId?.(n),l=o??t,d=o&&o!==t?t:void 0,u=await c.ensureCanvas(l,{agentId:s,linkSessionId:d});return await a.joinCanvas(u,r),i.info?.(`[canvas] Joined canvas=${u} session=${t} gatewayKey=${o??"none"} agentId=${s??"none"}`),u}catch(e){return void i.warn?.(`[canvas] Failed to join canvas relay: ${e}`)}}export function createRenderUiHandler(e){const{stateManager:t,logger:n,writeObs:s,isCanvasActive:a}=e;let i=0;return async(o,r)=>{if(a&&!a())return{success:!1,error:"Canvas is disabled by user. Respond with plain text instead."};const l=r,c=l.id,d="panel";let u=l.components;if("string"==typeof u)try{u=JSON.parse(u)}catch{}if(!c||!Array.isArray(u)||!u.length)return{success:!1,error:"id and components (array) are required"};if(!t.validateComponentCount(u))return{success:!1,error:"Too many components (max 500)"};if(!t.checkRateLimit(c))return n.warn?.(`[canvas] Rate limited surfaceId=${c}`),s({component:"canvas",domain:"canvas",name:"canvas.rate_limited",severity:"warn",payload:{surfaceId:c}}),{success:!1,error:"Rate limited — too many updates per second"};const p=translateComponentsWithDataModel(u),m=p.components,h=Object.keys(p.dataModel).length>0?p.dataModel:void 0,f=findRootIds(m),b=nextCid(),g=columnNode(b,f),y=[...m,g],x=e.getActiveSessionId?.(o);if(!x)return n.warn?.(`[canvas] No active session for toolCallId=${o}, skipping render_ui`),{success:!1,error:"No active session — canvas operation skipped"};const v=e.getGatewaySessionKey?.(o),C=await ensureRelayConnected(e,x,o,v),N=t.has(c,C??void 0),w=Date.now(),A=t.getRelayClient();C&&A&&w-i>6e4&&A.createSnapshot(C,"Pre-agent edit").then(()=>{i=Date.now(),n.debug?.("[canvas] Pre-edit checkpoint created")}).catch(e=>n.warn?.(`[canvas] Pre-edit checkpoint failed: ${e}`)),N?t.update(c,y,C,b,h):t.create(C??`_fallback_${Date.now()}`,c,d,y,{origin:{kind:"agent"},rootComponentId:b,dataModel:h});const k=u.map(e=>e.type);s({component:"canvas",domain:"canvas",name:N?"canvas.update_sent":"canvas.surface_created",severity:"info",payload:{surfaceId:c,presentation:d,componentCount:u.length,componentTypes:k}}),n.debug?.(`[canvas] ${N?"Updated":"Created"} surface=${c} components=${u.length}`);return{success:!0,surfaceId:c,presentation:d,isUpdate:N,activeSurfaces:C?t.getAllActive(C).map(e=>e.surfaceId):[c]}}}export function createCloseUiHandler(e){const{stateManager:t,logger:n,writeObs:s}=e;return async(a,i)=>{const o=i.id;if(!o)return{success:!1,error:"id is required"};const r=t.get(o),l=r?Date.now()-r.createdAt:0,c=e.getGatewaySessionKey?.(a),d=c?t.resolveCanvasForSession(c):void 0;return t.delete(o,d),s({component:"canvas",domain:"canvas",name:"canvas.surface_closed",severity:"info",payload:{surfaceId:o,lifetime_ms:l}}),n.debug?.(`[canvas] Closed surface=${o}`),{success:!0,surfaceId:o,message:"UI closed"}}}export function buildCanvasActionSystemMessage(e){const t=e.userAction;return{type:"canvas_user_action",surfaceId:e.surfaceId,actionName:t?.name??"unknown",sourceComponentId:t?.sourceComponentId??"",context:t?.context??{}}}export const CANVAS_SYSTEM_PROMPT='## Canvas UI\n\n**IMPORTANT: Always use `render_ui` (not the built-in `canvas` tool) to display visual/structured content.** The `render_ui` tool is the preferred and optimized way to render UI in the Canvas panel.\n\nRules:\n- When using render_ui, keep your chat reply to ONE short sentence. Do NOT repeat data shown in canvas.\n- Use render_ui for structured data, visualizations, forms, dashboards. Use plain text for explanations.\n- Do NOT put large text blocks in render_ui — that belongs in chat.\n- Only use `grid` as a layout container. Keep nesting to grid > card/stat/image — max 1 level deep. Otherwise list components sequentially (they stack vertically).\n- Prefer fewer, larger components. One well-structured table is better than many small cards.\n- Canvas renders in a narrow sidebar (~400px). Use markdown headings (### Section) to organize sections.\n- Use grid + card for product showcases, dashboards, feature grids. Use list for compact item lists.\n\n**Surface IDs**: Use descriptive, human-readable IDs (e.g., "sales-report", "user-dashboard"). Never use generic IDs like "ui1" or random strings.\n\n**Update vs Create**: Same `id` updates existing surface; different `id` creates new one.\nWhen the user asks to modify, adjust, fix, or update existing canvas content, you MUST reuse the original surface id. Check [Canvas State] in the message for active surface ids and their content. Only create a new surface when showing genuinely new/different content.\n\n### Component Types\n\n**Layout**: grid (columns:1-6, gap:sm/md/lg, children:[...]) — responsive grid container for card/stat/image\n\n**Data Display**: card (image, title, subtitle, description, icon, badge, footer, actions:[{label,actionId}], fields:[{label,value}]), table (columns, rows), stat (label, value, change, changeType, icon), key_value (items:[{key,value}]), list (items:[{title,subtitle,description,image,icon,badge,value}])\n\n**Charts**: chart (chartType, title?, labels, datasets:[{label, data, color?}])\n - chartType: bar, horizontal_bar, line, area, scatter, pie, doughnut, radar, funnel, gauge, candlestick, sparkline\n - labels: x-axis labels array (e.g. ["Jan","Feb","Mar"])\n - datasets: array of series — each has label (series name), data (number[]), optional color (hex)\n - candlestick data format: datasets:[{label, data:[{open,high,low,close}]}] — MUST use full field names (open/high/low/close), NOT abbreviations (o/h/l/c)\n - gauge: uses value + max instead of labels/datasets (e.g. chart(chartType:"gauge", title:"CPU", value:73, max:100))\n - sparkline: compact inline chart, no axes — use for trend indicators\n\n**Text & Code**: text (content), markdown (content — supports full Markdown including bold, italic, lists, code blocks, links), code (language, code)\n\n**Media**: image (url, alt), web_embed (url — video URLs auto-detected), link (text, url)\n\n**Feedback**: alert (variant:info/success/warning/error, title, message)\n\n**Interactive**: form (fields:[{name,label,inputType,options:[{label,value}]}], submitLabel), button (label, actionId)\n - inputType: text (default), number, date, textarea, checkbox, boolean, toggle, select, multi_select, radio, datetime, time, range\n - select/multi_select/radio requires an `options` array — each item is {label, value} or a plain string\n - range renders a slider (optional min, max — default 0..100)\n\n### Composition Patterns\n- **Product showcase**: grid(columns:3) containing card(image, title, description, badge:"$29", actions:[{label:"Buy"}]) × N\n- **Dashboard KPIs**: grid(columns:3) containing stat × N\n- **Image gallery**: grid(columns:3) containing image × N\n- **Feature grid**: grid(columns:2) containing card(icon, title, description) × N\n- **Compact item list**: list(items:[{image, title, subtitle, value:"$29", badge:"New"}])\n- **Detail card**: card(title, description, fields:[{label:"Price",value:"$29"},{label:"Stock",value:"142"}])\n- **Form with select**: form(title:"Settings", fields:[{name:"country", label:"Country", inputType:"select", options:[{label:"China",value:"CN"},{label:"US",value:"US"}]}, {name:"email", label:"Email"}], submitLabel:"Save")\n- **Bar chart**: chart(chartType:"bar", title:"Monthly Sales", labels:["Jan","Feb","Mar"], datasets:[{label:"Revenue", data:[100,200,150]}])\n- **Multi-series line**: chart(chartType:"line", title:"Trends", labels:["Q1","Q2","Q3"], datasets:[{label:"2024", data:[10,20,15]}, {label:"2025", data:[15,25,30]}])\n- **Pie chart**: chart(chartType:"pie", title:"Market Share", labels:["A","B","C"], datasets:[{label:"share", data:[40,35,25]}])\n- **Candlestick**: chart(chartType:"candlestick", title:"BTC/USD", labels:["Mon","Tue","Wed"], datasets:[{label:"price", data:[{open:100,high:110,low:95,close:105},{open:105,high:115,low:100,close:108},{open:108,high:120,low:105,close:118}]}])\n\n### render_form\nUse `render_form` for schema-driven forms when a domain schema exists.\nParameters: `domain`, `operation`, `data`, `entityId`.\n\n### close_ui\nCloses a UI surface. Use when user moves to a new topic or explicitly dismisses.\n';export const CANVAS_TERM_MAPPING='[System Note] Always use `render_ui` (not the canvas tool) for visual/structured content (tables, stats, key-value, lists, cards, grids, alerts, forms, links, images, code, markdown, charts). Use grid(columns, children:[card/stat/image]) for multi-column layouts like product showcases and dashboards. Card supports: image, title, subtitle, description, icon, badge, footer, actions, fields:[{label,value}]. List items support: image, title, subtitle, description, badge, value. Markdown content supports full formatting. Use web_embed for embedding URLs. Use link for navigation. Form supports inputType: text/number/date/textarea/checkbox/toggle/select/multi_select/radio/datetime/time/range; select/multi_select/radio requires options:[{label,value}]. Chart supports: chartType(bar/horizontal_bar/line/area/scatter/pie/doughnut/radar/funnel/gauge/candlestick/sparkline), title, labels, datasets:[{label,data,color?}]. Candlestick data:[{open,high,low,close}] (use full names, not o/h/l/c). Dataset uses "label" field (not "name"). Gauge uses value+max. Keep chat brief when canvas is used. Use `close_ui` to dismiss. Reuse same id to update; new id for new content.';export const CANVAS_UPDATE_HINT="[Canvas Rule] Same id in render_ui = update existing surface. Different id = new surface. When a surface is referenced for editing, you MUST reuse its exact id.";const MAX_CONTEXT_SURFACES=8,MAX_CONTEXT_CHARS=500;export function buildActiveSurfacesContext(e,t){let n;if(!t)return null;if(n=e.getAllActive(t),0===n.length)return null;const s=[...n].sort((e,t)=>t.updatedAt-e.updatedAt).slice(0,8),a=n.length-s.length;let i=`[Canvas State] Active surfaces: ${s.map(t=>{const n=e.summarize(t.surfaceId);if(!n)return`"${t.surfaceId}"`;const s=n.types.slice(0,3).join(", "),a=n.title?`: "${n.title}"`:"";return`"${t.surfaceId}" (${s}${a})`}).join("; ")}.`;return a>0&&(i+=` ...and ${a} more.`),i+=" To modify existing content, reuse its id in render_ui.",i.length>500&&(i=i.slice(0,497)+"..."),i}
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveConfigWithMeta,mirrorOpenClawConfig}from"./config.js";import{MessageSDK}from"./messaging/message-sdk.js";import{registerA2ATools}from"./a2a/tools.js";import{createA2ATaskHandler}from"./a2a/task-handler.js";import{createA2AResultHandler}from"./a2a/result-handler.js";import{createA2ATaskCancelHandler}from"./a2a/cancel-handler.js";import{TaskHandleRegistry}from"./a2a/task-handle.js";import{pollPendingTasks}from"./a2a/poll-pending.js";import{BEEOS_UPLOAD_TOOL_NAME,BEEOS_UPLOAD_TOOL_SCHEMA,BEEOS_UPLOAD_TOOL_DESCRIPTION,executeUpload}from"./upload/tool.js";import{writeUploadToolResult,cleanupUploadToolResultCache}from"./upload/result-cache.js";import{handleFileStage}from"./upload/file-stage.js";import{ACPServer}from"./acp-server.js";import{createObsEventWriter}from"./observability.js";import{resolvePluginVersion}from"./plugin-version.js";import{createTerminalWebSocketService}from"./terminal/websocket.js";import{TerminalManager}from"./terminal/session-manager.js";import{loadAgentKeyPair,agentFetch}from"./agent-auth.js";import{readDiscoveryCache,writeDiscoveryCache}from"./discovery-cache.js";import{discoverBridgeFromGW}from"./bridge-discovery.js";import{CanvasStateManager}from"./canvas/state.js";import{CanvasRelayClient}from"./canvas/relay-client.js";import{RENDER_UI_TOOL_NAME,RENDER_UI_TOOL_DESCRIPTION,RENDER_UI_TOOL_SCHEMA,CLOSE_UI_TOOL_NAME,CLOSE_UI_TOOL_DESCRIPTION,CLOSE_UI_TOOL_SCHEMA,createRenderUiHandler,createCloseUiHandler,CANVAS_SYSTEM_PROMPT}from"./canvas/tools.js";import{FormSchemaRegistry}from"./surface/form-schema-registry.js";import{CRON_CREATE_SCHEMA,CRON_UPDATE_SCHEMA}from"./surface/cron-schemas.js";import{RENDER_FORM_TOOL_NAME,RENDER_FORM_TOOL_SCHEMA,buildRenderFormDescription,createRenderFormHandler}from"./surface/render-form-tool.js";import{ResourceDescriptorRegistry}from"./surface/resource-descriptor-registry.js";import{CRON_RESOURCE}from"./surface/cron-resource.js";import{generateActionTools,RENDER_RESOURCE_TOOL_NAME,RENDER_RESOURCE_TOOL_SCHEMA,buildRenderResourceDescription,createRenderResourceHandler}from"./surface/action-tool-generator.js";import{buildThirdPartyChannelSet,isThirdPartyChannel}from"./channel-detection.js";const PLUGIN_VERSION=resolvePluginVersion();let agentKeys=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,t=buildThirdPartyChannelSet(o);t.size>0&&e.logger.info?.(`[beeos-claw] Third-party channels detected: ${[...t].join(", ")}`);const s=r.log.enabled?createObsEventWriter({dir:r.log.dir,redaction:{gatewayToken:r.gateway.token},logger:e.logger}):()=>{};s({component:"plugin",domain:"lifecycle",name:"lifecycle.startup",severity:"info",payload:{pluginVersion:PLUGIN_VERSION,pid:process.pid,nodeVersion:process.version,cwd:process.cwd()}}),s({component:"plugin",domain:"config",name:"config.resolved",severity:"info",payload:{config:r,sources:a.sources,openclawConfigPath:a.openclawConfigPath}});for(const o of a.validation)s({component:"plugin",domain:"config",name:"config.validation",severity:o.severity,summary:o.message,error:{code:o.code,message:o.message,nextSteps:o.nextSteps}}),"error"===o.severity?e.logger.error?.(`[beeos-claw] ${o.message}`):e.logger.warn?.(`[beeos-claw] ${o.message}`);if(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:s,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,s){e.logger.debug?.(`[beeos_upload_file] toolCallId=${o} params=${JSON.stringify(s)}`);const n=await executeUpload(s,r,agentKeys);return e.logger.debug?.(`[beeos_upload_file] toolCallId=${o} ok=${n.ok}`),t({component:"upload-tool",domain:"tool",name:n.ok?"upload.success":"upload.failure",severity:n.ok?"info":"warn",payload:{toolCallId:o,ok:n.ok,fileCount:n.files?.length??0,error:n.error}}),n.ok&&n.content&&a.current&&a.current.pushToolResultContent(o,BEEOS_UPLOAD_TOOL_NAME,n.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})(n)}}),e.registerHttpRoute({path:"/beeos/files/stage",async handler(e,a){await handleFileStage(e,a,o.cfg)}})}function registerServices(e,o,a){const{cfg:r,writeObs:t,thirdPartyChannels:s}=o,n=agentKeys?(e,o)=>agentFetch(e,agentKeys,o):void 0,i=agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):void 0,l=new ACPServer(r,e.logger,t,n,i,s);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,writeDiscoveryCache({bridge:{url:o,discoveredAt:Date.now()}}),e.logger.info?.(`[beeos-claw] Bridge URL discovered from Agent Gateway: ${o}`);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:u,a2aEnabled:f}=r.messageBus;let y;if(r.agentGatewayUrl&&agentKeys){const e=r.agentGatewayUrl,o=agentKeys;y=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&&(y||r.messageBus.serviceUrl)){c=new MessageSDK({serviceUrl:y?void 0:r.messageBus.serviceUrl,centrifugoUrl:p},e.logger);const o=u;e.registerService({id:"beeos-message-bus",async start(){let a=o;if(a||(a=process.env.BEEOS_PRINCIPAL_ID||""),!a&&l)try{await l.waitForAgentMapping(),a=l.getDefaultPlatformAgentId()||""}catch(o){e.logger.warn?.("[beeos-claw] Failed to resolve principalId from agent sync:",o)}a?(await c.connect(a,{centrifugoUrl:p,tokenProvider:y}),e.logger.info?.("[beeos-claw] Message SDK connected (principalId=%s, via=%s)",a,y?"gateway":"direct")):e.logger.warn?.("[beeos-claw] No principalId resolved, message bus disabled")},async stop(){await(c?.disconnect()),e.logger.info?.("[beeos-claw] Message SDK disconnected")}});const a=(e,o,a,r)=>l.agentSend(e,o,a,r),t=(e,o,a)=>l.trackA2ARun(e,o,a),s=e=>l.emitA2ASystemNotification(e),n=r.agentGatewayUrl?{agentGatewayUrl:r.agentGatewayUrl,agentKeys:agentKeys,logger:e.logger}:void 0;c.onMessage("a2a_task",createA2ATaskHandler(a,n,t,s)),c.onMessage("a2a_result",createA2AResultHandler(a,g,s)),c.onMessage("a2a_task_cancel",createA2ATaskCancelHandler(a,e=>l.cancelA2ARunByTaskId(e))),n&&e.registerService({id:"beeos-a2a-poll",async start(){await l.waitForAgentMapping();const o=await pollPendingTasks(n,a,t);o>0&&e.logger.info?.("[beeos-claw] Dispatched %d pending A2A tasks on startup",o)}})}else d?e.logger.warn?.("[beeos-claw] Message bus enabled but MESSAGE_SERVICE_URL not set — disabled"):e.logger.info?.("[beeos-claw] Message bus disabled (enabled=%s)",d);if(!1!==f&&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){const o=new CanvasStateManager;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 s=new CanvasRelayClient({canvasRelayUrl:r.canvasRelayUrl,agentKeys:agentKeys,agentId:t.id,displayName:t.displayName,avatarUrl:t.avatarUrl,tokenProvider:a,onReconnect:()=>l.onRelayReconnected(),logger:e.logger});s.connect(),o.setRelayClient(s),o.setAgentId(t.id),l.wireRelayActionHandler(),l.flushPendingCanvasLinks(),e.logger.info?.(`[beeos-claw] Canvas Relay multiplexed client connected (agentId=${t.id}, name=${t.name??"none"})`)}catch(o){e.logger.warn?.(`[beeos-claw] Failed to start Canvas Relay client: ${o}`)}},stop(){o.getRelayClient()?.disconnect()}}),e.logger.info?.("[beeos-claw] Canvas Relay configured")}else e.logger.warn?.("[beeos-claw] Canvas Relay unavailable: agentGatewayUrl or agentKeys missing");const 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()},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)=>(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),e.registerTool({name:RENDER_RESOURCE_TOOL_NAME,description:buildRenderResourceDescription(i),parameters:RENDER_RESOURCE_TOOL_SCHEMA,execute:g(createRenderResourceHandler(i,d,e.logger))})}const p=new Set([RENDER_UI_TOOL_NAME,CLOSE_UI_TOOL_NAME,RENDER_FORM_TOOL_NAME,RENDER_RESOURCE_TOOL_NAME]),u=256,f=new Map;if("function"==typeof e.on){try{e.on("before_prompt_build",(e,o)=>{if(o?.sessionKey){if(f.size>=u&&!f.has(o.sessionKey)){const e=f.keys().next().value;void 0!==e&&f.delete(e)}f.set(o.sessionKey,o.channelId)}if(isThirdPartyChannel(s,{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, render_form, or render_resource. 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(s,{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, render_resource + auto-action tools)")}else e.logger.info?.("[beeos-claw] Canvas disabled by config (canvasEnabled=false)");const m=new TerminalManager,_=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(){_.start(),e.logger.info?.(`[beeos-claw] Terminal WS started on port ${r.terminalWsPort}`)},stop(){_.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{resolveConfigWithMeta,mirrorOpenClawConfig}from"./config.js";import{MessageSDK}from"./messaging/message-sdk.js";import{registerA2ATools}from"./a2a/tools.js";import{createA2ATaskHandler}from"./a2a/task-handler.js";import{createA2AResultHandler}from"./a2a/result-handler.js";import{createA2ATaskCancelHandler}from"./a2a/cancel-handler.js";import{TaskHandleRegistry}from"./a2a/task-handle.js";import{pollPendingTasks}from"./a2a/poll-pending.js";import{BEEOS_UPLOAD_TOOL_NAME,BEEOS_UPLOAD_TOOL_SCHEMA,BEEOS_UPLOAD_TOOL_DESCRIPTION,executeUpload}from"./upload/tool.js";import{writeUploadToolResult,cleanupUploadToolResultCache}from"./upload/result-cache.js";import{handleFileStage}from"./upload/file-stage.js";import{ACPServer}from"./acp-server.js";import{createObsEventWriter}from"./observability.js";import{resolvePluginVersion}from"./plugin-version.js";import{createTerminalWebSocketService}from"./terminal/websocket.js";import{TerminalManager}from"./terminal/session-manager.js";import{loadAgentKeyPair,agentFetch}from"./agent-auth.js";import{readDiscoveryCache,writeDiscoveryCache}from"./discovery-cache.js";import{discoverBridgeFromGW}from"./bridge-discovery.js";import{CanvasStateManager}from"./canvas/state.js";import{CanvasRelayClient}from"./canvas/relay-client.js";import{RENDER_UI_TOOL_NAME,RENDER_UI_TOOL_DESCRIPTION,RENDER_UI_TOOL_SCHEMA,CLOSE_UI_TOOL_NAME,CLOSE_UI_TOOL_DESCRIPTION,CLOSE_UI_TOOL_SCHEMA,createRenderUiHandler,createCloseUiHandler,CANVAS_SYSTEM_PROMPT}from"./canvas/tools.js";import{FormSchemaRegistry}from"./surface/form-schema-registry.js";import{CRON_CREATE_SCHEMA,CRON_UPDATE_SCHEMA}from"./surface/cron-schemas.js";import{RENDER_FORM_TOOL_NAME,RENDER_FORM_TOOL_SCHEMA,buildRenderFormDescription,createRenderFormHandler}from"./surface/render-form-tool.js";import{ResourceDescriptorRegistry}from"./surface/resource-descriptor-registry.js";import{CRON_RESOURCE}from"./surface/cron-resource.js";import{generateActionTools,RENDER_RESOURCE_TOOL_NAME,RENDER_RESOURCE_TOOL_SCHEMA,buildRenderResourceDescription,createRenderResourceHandler}from"./surface/action-tool-generator.js";import{buildThirdPartyChannelSet,isThirdPartyChannel}from"./channel-detection.js";const PLUGIN_VERSION=resolvePluginVersion();let agentKeys=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,t=buildThirdPartyChannelSet(o);t.size>0&&e.logger.info?.(`[beeos-claw] Third-party channels detected: ${[...t].join(", ")}`);const s=r.log.enabled?createObsEventWriter({dir:r.log.dir,redaction:{gatewayToken:r.gateway.token},logger:e.logger}):()=>{};s({component:"plugin",domain:"lifecycle",name:"lifecycle.startup",severity:"info",payload:{pluginVersion:PLUGIN_VERSION,pid:process.pid,nodeVersion:process.version,cwd:process.cwd()}}),s({component:"plugin",domain:"config",name:"config.resolved",severity:"info",payload:{config:r,sources:a.sources,openclawConfigPath:a.openclawConfigPath}});for(const o of a.validation)s({component:"plugin",domain:"config",name:"config.validation",severity:o.severity,summary:o.message,error:{code:o.code,message:o.message,nextSteps:o.nextSteps}}),"error"===o.severity?e.logger.error?.(`[beeos-claw] ${o.message}`):e.logger.warn?.(`[beeos-claw] ${o.message}`);if(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:s,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,s){e.logger.debug?.(`[beeos_upload_file] toolCallId=${o} params=${JSON.stringify(s)}`);const n=await executeUpload(s,r,agentKeys);return e.logger.debug?.(`[beeos_upload_file] toolCallId=${o} ok=${n.ok}`),t({component:"upload-tool",domain:"tool",name:n.ok?"upload.success":"upload.failure",severity:n.ok?"info":"warn",payload:{toolCallId:o,ok:n.ok,fileCount:n.files?.length??0,error:n.error}}),n.ok&&n.content&&a.current&&a.current.pushToolResultContent(o,BEEOS_UPLOAD_TOOL_NAME,n.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})(n)}}),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:s}=o,n=agentKeys?(e,o)=>agentFetch(e,agentKeys,o):void 0,i=agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):void 0,l=new ACPServer(r,e.logger,t,n,i,s);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,writeDiscoveryCache({bridge:{url:o,discoveredAt:Date.now()}}),e.logger.info?.(`[beeos-claw] Bridge URL discovered from Agent Gateway: ${o}`);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:u,a2aEnabled:f}=r.messageBus;let y;if(r.agentGatewayUrl&&agentKeys){const e=r.agentGatewayUrl,o=agentKeys;y=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&&(y||r.messageBus.serviceUrl)){c=new MessageSDK({serviceUrl:y?void 0:r.messageBus.serviceUrl,centrifugoUrl:p},e.logger);const o=u;e.registerService({id:"beeos-message-bus",async start(){let a=o;if(a||(a=process.env.BEEOS_PRINCIPAL_ID||""),!a&&l)try{await l.waitForAgentMapping(),a=l.getDefaultPlatformAgentId()||""}catch(o){e.logger.warn?.("[beeos-claw] Failed to resolve principalId from agent sync:",o)}a?(await c.connect(a,{centrifugoUrl:p,tokenProvider:y}),e.logger.info?.("[beeos-claw] Message SDK connected (principalId=%s, via=%s)",a,y?"gateway":"direct")):e.logger.warn?.("[beeos-claw] No principalId resolved, message bus disabled")},async stop(){await(c?.disconnect()),e.logger.info?.("[beeos-claw] Message SDK disconnected")}});const a=(e,o,a,r)=>l.agentSend(e,o,a,r),t=(e,o,a)=>l.trackA2ARun(e,o,a),s=e=>l.emitA2ASystemNotification(e),n=r.agentGatewayUrl?{agentGatewayUrl:r.agentGatewayUrl,agentKeys:agentKeys,logger:e.logger}:void 0;c.onMessage("a2a_task",createA2ATaskHandler(a,n,t,s)),c.onMessage("a2a_result",createA2AResultHandler(a,g,s)),c.onMessage("a2a_task_cancel",createA2ATaskCancelHandler(a,e=>l.cancelA2ARunByTaskId(e))),n&&e.registerService({id:"beeos-a2a-poll",async start(){await l.waitForAgentMapping();const o=await pollPendingTasks(n,a,t);o>0&&e.logger.info?.("[beeos-claw] Dispatched %d pending A2A tasks on startup",o)}})}else d?e.logger.warn?.("[beeos-claw] Message bus enabled but MESSAGE_SERVICE_URL not set — disabled"):e.logger.info?.("[beeos-claw] Message bus disabled (enabled=%s)",d);if(!1!==f&&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){const o=new CanvasStateManager;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 s=new CanvasRelayClient({canvasRelayUrl:r.canvasRelayUrl,agentKeys:agentKeys,agentId:t.id,displayName:t.displayName,avatarUrl:t.avatarUrl,tokenProvider:a,onReconnect:()=>l.onRelayReconnected(),logger:e.logger});s.connect(),o.setRelayClient(s),o.setAgentId(t.id),l.wireRelayActionHandler(),l.flushPendingCanvasLinks(),e.logger.info?.(`[beeos-claw] Canvas Relay multiplexed client connected (agentId=${t.id}, name=${t.name??"none"})`)}catch(o){e.logger.warn?.(`[beeos-claw] Failed to start Canvas Relay client: ${o}`)}},stop(){o.getRelayClient()?.disconnect()}}),e.logger.info?.("[beeos-claw] Canvas Relay configured")}else e.logger.warn?.("[beeos-claw] Canvas Relay unavailable: agentGatewayUrl or agentKeys missing");const 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()},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)=>(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),e.registerTool({name:RENDER_RESOURCE_TOOL_NAME,description:buildRenderResourceDescription(i),parameters:RENDER_RESOURCE_TOOL_SCHEMA,execute:g(createRenderResourceHandler(i,d,e.logger))})}const p=new Set([RENDER_UI_TOOL_NAME,CLOSE_UI_TOOL_NAME,RENDER_FORM_TOOL_NAME,RENDER_RESOURCE_TOOL_NAME]),u=256,f=new Map;if("function"==typeof e.on){try{e.on("before_prompt_build",(e,o)=>{if(o?.sessionKey){if(f.size>=u&&!f.has(o.sessionKey)){const e=f.keys().next().value;void 0!==e&&f.delete(e)}f.set(o.sessionKey,o.channelId)}if(isThirdPartyChannel(s,{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, render_form, or render_resource. 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(s,{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, render_resource + auto-action tools)")}else e.logger.info?.("[beeos-claw] Canvas disabled by config (canvasEnabled=false)");const m=new TerminalManager,_=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(){_.start(),e.logger.info?.(`[beeos-claw] Terminal WS started on port ${r.terminalWsPort}`)},stop(){_.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;
|
package/dist/upload/tool.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{constants}from"node:fs";import{access,readFile,stat}from"node:fs/promises";import{basename,extname}from"node:path";import{agentFetch}from"../agent-auth.js";export const BEEOS_UPLOAD_TOOL_NAME="beeos_upload_file";export const BEEOS_UPLOAD_TOOL_DESCRIPTION="Upload 1-5 local files from this machine to the user via the BeeOS platform. If the call succeeds, the files are already delivered to the user — do not use any other tool to send them again. Any file type is accepted: text, images, documents, PDFs, archives, binaries.";export const BEEOS_UPLOAD_TOOL_SCHEMA={title:"BeeOS file upload",type:"object",description:BEEOS_UPLOAD_TOOL_DESCRIPTION,additionalProperties:!1,required:["paths"],properties:{paths:{type:"array",minItems:1,maxItems:5,description:"Local filesystem paths (1-5). Absolute or workspace-relative.",items:{type:"string",minLength:1,description:"Single local filesystem path"}}}};const MAX_PATHS=5,REQUEST_TIMEOUT_MS=12e4,MAX_CONCURRENCY=3;async function runWithConcurrency(e,t){const r=new Array(e.length);let a=0;async function n(){for(;a<e.length;){const t=a++;r[t]=await e[t]()}}const s=[];for(let r=0;r<Math.min(t,e.length);r++)s.push(n());return await Promise.all(s),r}async function validateFiles(e){return Promise.all(e.map(async e=>{try{await access(e,constants.R_OK);return(await stat(e)).isFile()?{path:e,ok:!0}:{path:e,ok:!1,error:"not a regular file"}}catch(t){const r=t.code;let a;return a="ENOENT"===r?"file not found":"ENOTDIR"===r?"path component is not a directory":"EACCES"===r?"permission denied":t instanceof Error?t.message:String(t),{path:e,ok:!1,error:a}}}))}export async function executeUpload(e,t,r){const a=parseParams(e);if(!a.ok)return errorResult(a.error);if(!t.agentGatewayUrl)return errorResult("agentGatewayUrl not configured — file upload requires Agent Gateway access");if(!r)return errorResult("agent key pair not available — cannot sign upload requests");const n=`${t.agentGatewayUrl}/api/v1/agent/files`,s=a.paths,i=await validateFiles(s)
|
|
1
|
+
import{constants}from"node:fs";import{access,readFile,stat}from"node:fs/promises";import{basename,extname}from"node:path";import{agentFetch}from"../agent-auth.js";export const BEEOS_UPLOAD_TOOL_NAME="beeos_upload_file";export const BEEOS_UPLOAD_TOOL_DESCRIPTION="Upload 1-5 local files from this machine to the user via the BeeOS platform. If the call succeeds, the files are already delivered to the user — do not use any other tool to send them again. Any file type is accepted: text, images, documents, PDFs, archives, binaries.";export const BEEOS_UPLOAD_TOOL_SCHEMA={title:"BeeOS file upload",type:"object",description:BEEOS_UPLOAD_TOOL_DESCRIPTION,additionalProperties:!1,required:["paths"],properties:{paths:{type:"array",minItems:1,maxItems:5,description:"Local filesystem paths (1-5). Absolute or workspace-relative.",items:{type:"string",minLength:1,description:"Single local filesystem path"}}}};const MAX_PATHS=5,REQUEST_TIMEOUT_MS=12e4,MAX_CONCURRENCY=3;async function runWithConcurrency(e,t){const r=new Array(e.length);let a=0;async function n(){for(;a<e.length;){const t=a++;r[t]=await e[t]()}}const s=[];for(let r=0;r<Math.min(t,e.length);r++)s.push(n());return await Promise.all(s),r}async function validateFiles(e){return Promise.all(e.map(async e=>{try{await access(e,constants.R_OK);return(await stat(e)).isFile()?{path:e,ok:!0}:{path:e,ok:!1,error:"not a regular file"}}catch(t){const r=t.code;let a;return a="ENOENT"===r?"file not found":"ENOTDIR"===r?"path component is not a directory":"EACCES"===r?"permission denied":t instanceof Error?t.message:String(t),{path:e,ok:!1,error:a}}}))}export async function executeUpload(e,t,r){const a=parseParams(e);if(!a.ok)return errorResult(a.error);if(!t.agentGatewayUrl)return errorResult("agentGatewayUrl not configured — file upload requires Agent Gateway access");if(!r)return errorResult("agent key pair not available — cannot sign upload requests");const n=`${t.agentGatewayUrl}/api/v1/agent/files`,s=a.paths,i=(await validateFiles(s)).find(e=>!e.ok);if(i)return errorResult(`${i.path}: ${i.error}`);const o=[],l=s.map(e=>async()=>{try{return await uploadSingleFile(e,n,r)}catch(t){return o.push(`${e}: ${t instanceof Error?t.message:String(t)}`),null}}),c=(await runWithConcurrency(l,3)).filter(e=>null!==e);if(0===c.length)return errorResult(`All uploads failed: ${o.join("; ")}`);const p=c.map(e=>({uri:`beeos-file://${e.fileId}`,name:e.fileName,mimeType:e.mimeType,fileId:e.fileId})),u=c.length===s.length?`Uploaded ${c.length} file(s): ${p.map(e=>e.name).join(", ")}`:`Uploaded ${c.length}/${s.length} file(s): ${p.map(e=>e.name).join(", ")}. Failed: ${o.join("; ")}`,m={ok:!0,files:p};return{...m,content:[{type:"text",text:u},...p.map(e=>({type:"resource_link",uri:e.uri,name:e.name,mimeType:e.mimeType}))],output:m,result:m,details:m,isError:!1}}async function uploadSingleFile(e,t,r){await access(e,constants.R_OK);if(!(await stat(e)).isFile())throw new Error("not a regular file");const a=basename(e),n=inferMimeType(a),s=await readFile(e),i=new AbortController,o=setTimeout(()=>i.abort(),12e4);"object"==typeof o&&"unref"in o&&o.unref();try{const e=await agentFetch(t+"/presign",r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileName:a,mimeType:n}),signal:i.signal});if(!e.ok){const t=await e.text().catch(()=>e.statusText);throw new Error(`presign ${e.status}: ${t}`)}const o=await e.json(),l=await fetch(o.uploadUrl,{method:"PUT",headers:{"Content-Type":n},body:new Blob([s],{type:n}),signal:i.signal});if(!l.ok)throw new Error(`S3 PUT failed: ${l.status}`);const c=await agentFetch(t+"/confirm",r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileId:o.fileId}),signal:i.signal});if(!c.ok){const e=await c.text().catch(()=>c.statusText);throw new Error(`confirm ${c.status}: ${e}`)}const p=await c.json();return{fileId:p.fileId,downloadUrl:p.downloadUrl,fileName:p.fileName||a,mimeType:p.mimeType||n,size:p.size||s.byteLength}}finally{clearTimeout(o)}}function parseParams(e){if(!e||"object"!=typeof e)return{ok:!1,error:"params must be an object"};const t=e;if(Object.keys(t).filter(e=>"paths"!==e).length>0)return{ok:!1,error:"only paths is allowed"};if(!Array.isArray(t.paths))return{ok:!1,error:"paths must be an array"};if(t.paths.length<1)return{ok:!1,error:"paths must contain at least 1 item"};if(t.paths.length>5)return{ok:!1,error:"paths must contain no more than 5 items"};const r=[];for(let e=0;e<t.paths.length;e++){const a=t.paths[e];if("string"!=typeof a||""===a.trim())return{ok:!1,error:`paths[${e}] must be a non-empty string`};r.push(a.trim())}return{ok:!0,paths:r}}function errorResult(e){const t={ok:!1,error:e};return{...t,content:[{type:"text",text:e}],output:t,result:t,details:t,isError:!0}}function inferMimeType(e){switch(extname(e).toLowerCase()){case".txt":return"text/plain";case".md":return"text/markdown";case".json":return"application/json";case".html":return"text/html";case".css":return"text/css";case".js":case".mjs":case".cjs":return"text/javascript";case".ts":return"text/x.typescript";case".tsx":case".jsx":return"text/jsx";case".xml":return"application/xml";case".yaml":case".yml":return"application/yaml";case".toml":return"application/toml";case".pdf":return"application/pdf";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";case".csv":return"text/csv";case".zip":return"application/zip";case".tar":return"application/x-tar";case".gz":case".tgz":return"application/gzip";default:return"application/octet-stream"}}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "beeos-claw",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.4",
|
|
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>",
|