beeos-claw 0.3.1 → 0.3.3-staging.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -5
- package/dist/acp-gateway/assistant-mq-lifecycle.test.js +1 -1
- package/dist/acp-gateway/bridge-core.js +1 -1
- package/dist/acp-gateway/gateway-events-cron-backfill.test.js +1 -0
- package/dist/acp-gateway/gateway-events-heartbeat.test.js +1 -1
- package/dist/acp-gateway/gateway-events.js +1 -1
- package/dist/acp-gateway/mcp-service.js +1 -0
- package/dist/acp-gateway/mcp-service.test.js +1 -0
- package/dist/acp-gateway/pending-user-turn-updates.test.js +1 -0
- package/dist/acp-gateway/session-load-inflight-user.test.js +1 -0
- package/dist/acp-gateway/session-load.test.js +1 -0
- package/dist/acp-gateway/session-state.js +1 -1
- package/dist/acp-gateway/session-state.test.js +1 -1
- package/dist/acp-gateway/transport.js +1 -1
- package/dist/acp-gateway/transport.test.js +1 -1
- package/dist/acp-gateway/types.js +1 -1
- package/dist/acp-server.js +1 -1
- package/dist/auto-reply-tokens.js +1 -0
- package/dist/auto-reply-tokens.test.js +1 -0
- package/dist/config.js +1 -1
- package/dist/index.js +1 -1
- package/dist/message-filter.js +1 -1
- package/dist/message-filter.test.js +1 -1
- package/dist/messaging/chat-envelope.js +1 -0
- package/dist/messaging/chat-envelope.test.js +1 -0
- package/dist/messaging/message-sdk.js +1 -1
- package/dist/openclaw-cli.js +1 -0
- package/dist/status.js +1 -0
- package/dist/surface/cron-resource.js +1 -1
- package/dist/surface/cron-schemas.js +1 -1
- package/dist/surface/index.js +1 -1
- package/dist/utils/mq.js +1 -1
- package/openclaw.plugin.json +0 -4
- package/package.json +2 -2
- package/dist/acp-gateway/session-load-concurrency.test.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{describe,it,expect,vi}from"vitest";import{AcpGatewayBridgeCore}from"./bridge-core.js";import{AcpGatewaySessionState}from"./session-state.js";import{AcpTransport}from"./transport.js";function makeLogger(){return{info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()}}function makeConfig(){return{agentGatewayUrl:"http://localhost:0",keyFile:"/tmp/key",bridge:{url:"",service:"bridge",shell:{enabled:!1}},gateway:{url:"",token:"",protocol:1,clientId:"c",agentId:"main"},retry:{baseMs:100,maxMs:1e3,maxAttempts:0},log:{enabled:!1,verbose:!1,dir:"/tmp"},promptTimeoutMs:6e4,terminalWsPort:0,terminalWsAllowedOrigins:[],streamIdleTimeoutMs:6e4,streamStaleTimeoutMs:6e4,cronSignalWindowMs:5e3,canvasRelayUrl:"",canvasEnabled:!1,openclawCanvasCompat:!1,messageBus:{enabled:!1,serviceUrl:"",url:"",principalId:"",a2aEnabled:!1}}}function buildCore(){const e=makeLogger(),s=vi.fn(),t=new AcpGatewaySessionState(e),n=vi.fn(),a=new AcpTransport(n,s);return{core:new AcpGatewayBridgeCore({state:t,transport:a,config:makeConfig(),logger:e,writeObs:s,getGateway:()=>null,instanceId:"test-instance"}),state:t,transport:a,logger:e,writeObs:s,sendBridgeMessage:n}}function registerSession(e,s,t={}){const n={sessionId:s,gatewaySessionKey:`agent:main:${s}`,agentId:"main",createdAt:Date.now(),chatReplayDedupKeys:new Set,...t};return e.sessions.set(n.sessionId,n),e.sessionsByGatewayKey.set(n.gatewaySessionKey,n),n}async function callSessionLoad(e,s,t){const n={jsonrpc:"2.0",id:s,method:"session/load",params:{sessionId:t}};await e.handleSessionLoad(n)}function collectEmittedUpdates(e){return e.mock.calls.map(e=>e[0]).filter(e=>"session/update"===e?.method).map(e=>e.params?.update).filter(e=>!!e)}function userChunkTexts(e){return e.filter(e=>"user_message_chunk"===e.sessionUpdate).map(e=>{const s=e.content;return"text"===s?.type?s.text??"":""})}describe("session/load — in-flight user buffer (Plan B)",()=>{it("replays pendingUserTurnUpdates when history has nothing yet (mirrors: prompt sent, OpenClaw not yet persisted)",async()=>{const e=buildCore(),s=registerSession(e.state,"session:inflight-user");s.pendingUserTurnUpdates=[{sessionUpdate:"user_message_chunk",content:{type:"text",text:"hello"},timestamp:(new Date).toISOString()}],await callSessionLoad(e.core,1,s.sessionId);const t=collectEmittedUpdates(e.sendBridgeMessage);expect(userChunkTexts(t)).toEqual(["hello"])}),it("does NOT replay the buffer after handleSessionMessage(role=user) clears it (prevents double-emit with chat.history)",async()=>{const e=buildCore(),s=registerSession(e.state,"session:persisted-user",{lastTurnIdByRole:{user:"req:t1"}});s.pendingUserTurnUpdates=[{sessionUpdate:"user_message_chunk",content:{type:"text",text:"hello"},timestamp:(new Date).toISOString()}];const t={sessionKey:s.gatewaySessionKey,messageId:"a1b2c3d4",message:{role:"user",timestamp:Date.now()}};e.core.handleSessionMessage(t),expect(s.pendingUserTurnUpdates).toEqual([]),e.sendBridgeMessage.mockClear(),await callSessionLoad(e.core,2,s.sessionId);const n=collectEmittedUpdates(e.sendBridgeMessage);expect(userChunkTexts(n)).toEqual([])}),it("cleanupPrompt discards pendingUserTurnUpdates so a stale buffer never outlives the run",async()=>{const e=buildCore(),s=registerSession(e.state,"session:cleanup-buffer");s.pendingUserTurnUpdates=[{sessionUpdate:"user_message_chunk",content:{type:"text",text:"stale"},timestamp:(new Date).toISOString()}],e.core.cleanupPrompt(s),expect(s.pendingUserTurnUpdates).toBeUndefined()})});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{describe,it,expect,vi}from"vitest";import{AcpGatewayBridgeCore}from"./bridge-core.js";import{AcpGatewaySessionState}from"./session-state.js";import{AcpTransport}from"./transport.js";import{MessageQueue}from"../utils/mq.js";function makeLogger(){return{info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()}}function makeConfig(){return{agentGatewayUrl:"http://localhost:0",keyFile:"/tmp/key",bridge:{url:"",service:"bridge",shell:{enabled:!1}},gateway:{url:"",token:"",protocol:1,clientId:"c",agentId:"main"},retry:{baseMs:100,maxMs:1e3,maxAttempts:0},log:{enabled:!1,verbose:!1,dir:"/tmp"},promptTimeoutMs:6e4,terminalWsPort:0,terminalWsAllowedOrigins:[],streamIdleTimeoutMs:6e4,streamStaleTimeoutMs:6e4,cronSignalWindowMs:5e3,canvasRelayUrl:"",canvasEnabled:!1,openclawCanvasCompat:!1,messageBus:{enabled:!1,serviceUrl:"",url:"",principalId:"",a2aEnabled:!1}}}function buildCore(){const e=makeLogger(),s=vi.fn(),t=new AcpGatewaySessionState(e),n=vi.fn(),a=new AcpTransport(n,s);return{core:new AcpGatewayBridgeCore({state:t,transport:a,config:makeConfig(),logger:e,writeObs:s,getGateway:()=>null,instanceId:"test-instance"}),state:t,transport:a,logger:e,writeObs:s,sendBridgeMessage:n}}function registerSession(e,s,t={}){const n={sessionId:s,gatewaySessionKey:`agent:main:${s}`,agentId:"main",createdAt:Date.now(),chatReplayDedupKeys:new Set,...t};return e.sessions.set(n.sessionId,n),e.sessionsByGatewayKey.set(n.gatewaySessionKey,n),n}async function callSessionLoad(e,s,t){const n={jsonrpc:"2.0",id:s,method:"session/load",params:{sessionId:t}};await e.handleSessionLoad(n)}function collectEmittedUpdates(e){return e.mock.calls.map(e=>e[0]).filter(e=>"session/update"===e?.method).map(e=>e.params?.update)}function collectResults(e){return e.mock.calls.map(e=>e[0]).filter(e=>void 0!==e?.result)}describe("session/load — KISS contract",()=>{it("ACKs immediately (< 50ms) even when assistantMq has buffered chunks (regression: Bug-AW hang)",async()=>{const e=buildCore(),s=registerSession(e.state,"session:fast-ack"),t=new MessageQueue;for(let e=0;e<5;e++)t.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`chunk-${e}`}});s.assistantMq=t;const n=Date.now();await callSessionLoad(e.core,1,s.sessionId);const a=Date.now()-n;expect(a).toBeLessThan(50);const o=collectResults(e.sendBridgeMessage);expect(o).toHaveLength(1),expect(o[0].result).toMatchObject({sessionId:s.sessionId})}),it("emits mq snapshot exactly once — subsequent pushes are NOT replayed as part of this load",async()=>{const e=buildCore(),s=registerSession(e.state,"session:snapshot-once"),t=new MessageQueue;t.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"first"}}),t.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"second"}}),s.assistantMq=t,await callSessionLoad(e.core,1,s.sessionId),t.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"post-load"}});const n=collectEmittedUpdates(e.sendBridgeMessage).filter(e=>"agent_message_chunk"===e?.sessionUpdate).map(e=>e.content.text);expect(n).toEqual(["first","second"])}),it("emits no stream updates when assistantMq is undefined — just ACKs",async()=>{const e=buildCore(),s=registerSession(e.state,"session:no-mq");s.assistantMq=void 0,await callSessionLoad(e.core,1,s.sessionId);const t=collectEmittedUpdates(e.sendBridgeMessage);expect(t.filter(e=>"agent_message_chunk"===e?.sessionUpdate)).toHaveLength(0);const n=collectResults(e.sendBridgeMessage);expect(n).toHaveLength(1)}),it("skips snapshot when assistantMq is closed — closed mq means history already covers the turn",async()=>{const e=buildCore(),s=registerSession(e.state,"session:closed-mq"),t=new MessageQueue;t.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"should-be-skipped"}}),t.close(),s.assistantMq=t,await callSessionLoad(e.core,1,s.sessionId);const n=collectEmittedUpdates(e.sendBridgeMessage);expect(n.filter(e=>"agent_message_chunk"===e?.sessionUpdate)).toHaveLength(0);const a=collectResults(e.sendBridgeMessage);expect(a).toHaveLength(1)}),it("rejects a load with missing sessionId via sendAcpError (no session touch)",async()=>{const e=buildCore();await e.core.handleSessionLoad({jsonrpc:"2.0",id:1,method:"session/load",params:{}});const s=e.sendBridgeMessage.mock.calls.map(e=>e[0]).filter(e=>void 0!==e?.error);expect(s).toHaveLength(1),expect(s[0].error.data?.param).toBe("sessionId")})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{MessageQueue}from"../utils/mq.js";const MAX_TOOL_CALL_MAP_ENTRIES=5e3,MAX_COMPLETED_RUN_IDS=200;export class AcpGatewaySessionState{sessions=new Map;promptsByRunId=new Map;promptsByGatewayRequestId=new Map;sessionsByGatewayKey=new Map;toolCallIdMap=new Map;toolCallToSessionMap=new Map;nextToolCallSeq=0;completedRunIds=new Set;lastActiveSessionId;sessionGcTimer=null;MAX_IDLE_SESSION_MS=864e5;A2A_SESSION_IDLE_MS=3e5;SESSION_GC_INTERVAL_MS=3e5;logger;constructor(s){this.logger=s}findSessionByKey(s){return this.sessionsByGatewayKey.get(s)}resolveSessionFromParams(s){const e="string"==typeof s?.sessionId?s.sessionId:void 0;if(e)return this.sessions.get(e)}isCurrentStreamOwner(s,e){return!e||!!s.currentRunId&&e===s.currentRunId}markRunCompleted(s){if(this.completedRunIds.add(s),this.completedRunIds.size>200){const s=this.completedRunIds.values().next().value;s&&this.completedRunIds.delete(s)}}isRunCompleted(s){return this.completedRunIds.has(s)}clearPromptTimeout(s){s.promptTimeoutTimer&&(clearTimeout(s.promptTimeoutTimer),s.promptTimeoutTimer=void 0)}clearStreamIdleTimer(s){s.streamIdleTimer&&(clearTimeout(s.streamIdleTimer),s.streamIdleTimer=void 0)}resetForNewRun(s,e,t){this.clearStreamIdleTimer(s),s.currentRunId&&this.promptsByRunId.delete(s.currentRunId),s.gatewayRequestId&&this.promptsByGatewayRequestId.delete(s.gatewayRequestId),s.currentRunId=void 0,s.gatewayRequestId=void 0,s.assistantMq&&!s.assistantMq.closed&&(
|
|
1
|
+
import{MessageQueue}from"../utils/mq.js";const MAX_TOOL_CALL_MAP_ENTRIES=5e3,MAX_COMPLETED_RUN_IDS=200;export class AcpGatewaySessionState{sessions=new Map;promptsByRunId=new Map;promptsByGatewayRequestId=new Map;sessionsByGatewayKey=new Map;toolCallIdMap=new Map;toolCallToSessionMap=new Map;nextToolCallSeq=0;completedRunIds=new Set;lastActiveSessionId;sessionGcTimer=null;MAX_IDLE_SESSION_MS=864e5;A2A_SESSION_IDLE_MS=3e5;SESSION_GC_INTERVAL_MS=3e5;logger;constructor(s){this.logger=s}findSessionByKey(s){return this.sessionsByGatewayKey.get(s)}resolveSessionFromParams(s){const e="string"==typeof s?.sessionId?s.sessionId:void 0;if(e)return this.sessions.get(e)}isCurrentStreamOwner(s,e){return!e||!!s.currentRunId&&e===s.currentRunId}markRunCompleted(s){if(this.completedRunIds.add(s),this.completedRunIds.size>200){const s=this.completedRunIds.values().next().value;s&&this.completedRunIds.delete(s)}}isRunCompleted(s){return this.completedRunIds.has(s)}clearPromptTimeout(s){s.promptTimeoutTimer&&(clearTimeout(s.promptTimeoutTimer),s.promptTimeoutTimer=void 0)}clearStreamIdleTimer(s){s.streamIdleTimer&&(clearTimeout(s.streamIdleTimer),s.streamIdleTimer=void 0)}resetForNewRun(s,e,t){this.clearStreamIdleTimer(s),s.currentRunId&&this.promptsByRunId.delete(s.currentRunId),s.gatewayRequestId&&this.promptsByGatewayRequestId.delete(s.gatewayRequestId),s.currentRunId=void 0,s.gatewayRequestId=void 0,s.assistantMq&&!s.assistantMq.closed&&(this.logger.warn?.(`[session-state] resetForNewRun discarding stale assistantMq sessionId=${e}`),s.assistantMq.close()),s.assistantMq=new MessageQueue,s.pendingUserTurnUpdates=[],s.chatReplayDedupKeys.clear(),s.hasAgentAssistantStream=!1,s.hasAgentThinkingStream=!1,s.hasAgentToolStartStream=!1,s.hasAgentToolResultStream=!1,s.chatAssistantTextSoFar=void 0,s.agentAssistantTextSoFar=void 0,s.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 i=s.agentAssistantTextSoFar??"",o=i+e.delta;if(s.agentAssistantTextSoFar=o,t>0&&i.length<t){if(o.length<=t)return;return o.slice(t)}return e.delta}const i=e.text;if(!i)return;const o=s.agentAssistantTextSoFar??"";s.agentAssistantTextSoFar=i;const a=Math.max(o.length,t);if(!(i.length<=a)){if(i.startsWith(o)||0===a)return i.slice(a)||void 0;if(!o.startsWith(i))return i}}startSessionGc(s,e){this.sessionGcTimer=setInterval(()=>this.gcSessions(s,e),this.SESSION_GC_INTERVAL_MS),"object"==typeof this.sessionGcTimer&&"unref"in this.sessionGcTimer&&this.sessionGcTimer.unref()}gcSessions(s,e){const t=Date.now();let i=0;for(const[o,a]of this.sessions){if(void 0!==a.pendingPromptId)continue;(a.lastStreamActivityTs??a.createdAt)<t-(a.gatewaySessionKey.includes(":a2a:")?this.A2A_SESSION_IDLE_MS:this.MAX_IDLE_SESSION_MS)&&(s(a),e?.(a),this.sessions.delete(o),this.sessionsByGatewayKey.delete(a.gatewaySessionKey),i++)}const o=new Set(Array.from(this.sessions.values()).map(s=>s.sessionId));for(const[s,e]of this.toolCallToSessionMap)o.has(e)||this.toolCallToSessionMap.delete(s);for(const[s,e]of this.toolCallIdMap)this.toolCallToSessionMap.has(e)||this.toolCallIdMap.delete(s);i>0&&(this.lastActiveSessionId&&!this.sessions.has(this.lastActiveSessionId)&&(this.lastActiveSessionId=void 0),this.logger.debug?.(`[session-state] GC evicted ${i} idle sessions, remaining=${this.sessions.size}`))}destroy(){this.sessionGcTimer&&(clearInterval(this.sessionGcTimer),this.sessionGcTimer=null);for(const s of this.sessions.values())this.clearPromptTimeout(s),this.clearStreamIdleTimer(s),s.assistantMq?.close();this.promptsByRunId.clear(),this.promptsByGatewayRequestId.clear(),this.completedRunIds.clear(),this.toolCallIdMap.clear(),this.toolCallToSessionMap.clear(),this.sessionsByGatewayKey.clear(),this.sessions.clear(),this.lastActiveSessionId=void 0}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describe,it,expect,beforeEach,vi}from"vitest";import{AcpGatewaySessionState}from"./session-state.js";import{MessageQueue}from"../utils/mq.js";function makeSession(e,s){return{sessionId:e,gatewaySessionKey:s??`agent:main:${e}`,agentId:"main",createdAt:Date.now(),chatReplayDedupKeys:new Set}}describe("AcpGatewaySessionState",()=>{let e;const s={info:vi.fn(),warn:vi.fn(),debug:vi.fn()};beforeEach(()=>{s.info.mockClear(),s.warn.mockClear(),s.debug.mockClear(),e=new AcpGatewaySessionState(s)}),it("should store and find sessions by key",()=>{const s=makeSession("s1","agent:main:abc");e.sessions.set("s1",s),e.sessionsByGatewayKey.set("agent:main:abc",s),expect(e.findSessionByKey("agent:main:abc")).toBe(s),expect(e.findSessionByKey("nonexistent")).toBeUndefined()}),describe("enforceToolCallMapLimits",()=>{it("should evict oldest entries when exceeding hard cap",()=>{for(let s=0;s<5010;s++)e.toolCallIdMap.set(`gw-${s}`,`acp-${s}`);expect(e.toolCallIdMap.size).toBe(5010),e.enforceToolCallMapLimits(),expect(e.toolCallIdMap.size).toBe(5e3),expect(e.toolCallIdMap.has("gw-0")).toBe(!1),expect(e.toolCallIdMap.has("gw-9")).toBe(!1),expect(e.toolCallIdMap.has("gw-5009")).toBe(!0)}),it("should not evict when under limit",()=>{e.toolCallIdMap.set("a","b"),e.enforceToolCallMapLimits(),expect(e.toolCallIdMap.size).toBe(1)})}),describe("resetForNewRun",()=>{it("should clear run-specific state and enforce limits",()=>{const s=makeSession("s1");s.currentRunId="old-run",s.promptDone=!0,s.chatReplayDedupKeys.add("old"),e.sessions.set("s1",s);const t={resetSessionUpdateCount:vi.fn(),sendSessionUpdate:vi.fn(),sendResult:vi.fn(),sendAcpError:vi.fn(),sendNotification:vi.fn()};e.resetForNewRun(s,"s1",t),expect(s.currentRunId).toBeUndefined(),expect(s.chatReplayDedupKeys.size).toBe(0),expect(s.promptDone).toBe(!1),expect(t.resetSessionUpdateCount).toHaveBeenCalledWith("s1")}),it("should warn and discard a stale open assistantMq left behind by a prior run",()=>{const t=makeSession("s1")
|
|
1
|
+
import{describe,it,expect,beforeEach,vi}from"vitest";import{AcpGatewaySessionState}from"./session-state.js";import{MessageQueue}from"../utils/mq.js";function makeSession(e,s){return{sessionId:e,gatewaySessionKey:s??`agent:main:${e}`,agentId:"main",createdAt:Date.now(),chatReplayDedupKeys:new Set}}describe("AcpGatewaySessionState",()=>{let e;const s={info:vi.fn(),warn:vi.fn(),debug:vi.fn()};beforeEach(()=>{s.info.mockClear(),s.warn.mockClear(),s.debug.mockClear(),e=new AcpGatewaySessionState(s)}),it("should store and find sessions by key",()=>{const s=makeSession("s1","agent:main:abc");e.sessions.set("s1",s),e.sessionsByGatewayKey.set("agent:main:abc",s),expect(e.findSessionByKey("agent:main:abc")).toBe(s),expect(e.findSessionByKey("nonexistent")).toBeUndefined()}),describe("enforceToolCallMapLimits",()=>{it("should evict oldest entries when exceeding hard cap",()=>{for(let s=0;s<5010;s++)e.toolCallIdMap.set(`gw-${s}`,`acp-${s}`);expect(e.toolCallIdMap.size).toBe(5010),e.enforceToolCallMapLimits(),expect(e.toolCallIdMap.size).toBe(5e3),expect(e.toolCallIdMap.has("gw-0")).toBe(!1),expect(e.toolCallIdMap.has("gw-9")).toBe(!1),expect(e.toolCallIdMap.has("gw-5009")).toBe(!0)}),it("should not evict when under limit",()=>{e.toolCallIdMap.set("a","b"),e.enforceToolCallMapLimits(),expect(e.toolCallIdMap.size).toBe(1)})}),describe("resetForNewRun",()=>{it("should clear run-specific state and enforce limits",()=>{const s=makeSession("s1");s.currentRunId="old-run",s.promptDone=!0,s.chatReplayDedupKeys.add("old"),e.sessions.set("s1",s);const t={resetSessionUpdateCount:vi.fn(),sendSessionUpdate:vi.fn(),sendResult:vi.fn(),sendAcpError:vi.fn(),sendNotification:vi.fn()};e.resetForNewRun(s,"s1",t),expect(s.currentRunId).toBeUndefined(),expect(s.chatReplayDedupKeys.size).toBe(0),expect(s.promptDone).toBe(!1),expect(t.resetSessionUpdateCount).toHaveBeenCalledWith("s1")}),it("should warn and discard a stale open assistantMq left behind by a prior run",()=>{const t=makeSession("s1"),a=new MessageQueue;a.push({sessionUpdate:"agent_message_chunk"}),t.assistantMq=a;const n={resetSessionUpdateCount:vi.fn()};e.resetForNewRun(t,"s1",n),expect(s.warn).toHaveBeenCalledWith(expect.stringContaining("discarding stale assistantMq")),expect(a.closed).toBe(!0),expect(t.assistantMq).toBeDefined(),expect(t.assistantMq).not.toBe(a),expect(t.assistantMq?.closed).toBe(!1),expect(t.assistantMq?.peek(0).length).toBe(0)}),it("should not warn when assistantMq was already closed by session.message",()=>{const t=makeSession("s1"),a=new MessageQueue;a.close(),t.assistantMq=a;const n={resetSessionUpdateCount:vi.fn()};e.resetForNewRun(t,"s1",n),expect(s.warn).not.toHaveBeenCalled(),expect(t.assistantMq).not.toBe(a),expect(t.assistantMq?.closed).toBe(!1)}),it("should reset hasAgent*Stream flags so the next run starts clean",()=>{const s=makeSession("s1");s.hasAgentAssistantStream=!0,s.hasAgentThinkingStream=!0,s.hasAgentToolStartStream=!0,s.hasAgentToolResultStream=!0,s.chatAssistantTextSoFar="stale",s.agentAssistantTextSoFar="stale";const t={resetSessionUpdateCount:vi.fn()};e.resetForNewRun(s,"s1",t),expect(s.hasAgentAssistantStream).toBe(!1),expect(s.hasAgentThinkingStream).toBe(!1),expect(s.hasAgentToolStartStream).toBe(!1),expect(s.hasAgentToolResultStream).toBe(!1),expect(s.chatAssistantTextSoFar).toBeUndefined(),expect(s.agentAssistantTextSoFar).toBeUndefined()})}),describe("session GC",()=>{it("should clean up expired sessions",()=>{vi.useFakeTimers();const s=makeSession("expired");s.createdAt=Date.now()-9e7,e.sessions.set("expired",s),e.sessionsByGatewayKey.set(s.gatewaySessionKey,s);const t=vi.fn(),a=vi.fn();e.startSessionGc(t,a),vi.advanceTimersByTime(300100),expect(e.sessions.has("expired")).toBe(!1),expect(t).toHaveBeenCalled(),expect(a).toHaveBeenCalled(),e.destroy(),vi.useRealTimers()})})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{acpError}from"../errors/index.js";function normalizeOpts(e){if(null!=e)return"string"==typeof e?{turnId:e}:e}export class AcpTransport{debugIndex=0;sendBridgeMessage;obs;forward;sessionUpdateCounts=new Map;_isReady;sessionUpdateObserver;constructor(e,s,t,r){this.sendBridgeMessage=e,this.obs=s??(()=>{}),this.forward=t??{forwardThinking:!0,forwardToolCalls:!0},this._isReady=r}setSessionUpdateObserver(e){this.sessionUpdateObserver=e}isReady(){return!this._isReady||this._isReady()}get forwardControl(){return this.forward}nextMeta(){return{_debug_index:this.debugIndex++,_ts:Date.now()}}sendResult(e,s){const t=this.nextMeta();this.detectProtocolError(e,s,t._debug_index);const r={jsonrpc:"2.0",id:e,result:this.attachMeta(s,t),_debug_index:t._debug_index,_ts:t._ts};this.sendBridgeMessage(r),this.obs({component:"acp-transport",domain:"reply",name:"rpc.result",severity:"debug",payload:{id:e,_debug_index:t._debug_index}})}sendError(e,s,t,r){const
|
|
1
|
+
import{acpError}from"../errors/index.js";function normalizeOpts(e){if(null!=e)return"string"==typeof e?{turnId:e}:e}export class AcpTransport{debugIndex=0;sendBridgeMessage;obs;forward;sessionUpdateCounts=new Map;_isReady;sessionUpdateObserver;constructor(e,s,t,r){this.sendBridgeMessage=e,this.obs=s??(()=>{}),this.forward=t??{forwardThinking:!0,forwardToolCalls:!0},this._isReady=r}setSessionUpdateObserver(e){this.sessionUpdateObserver=e}isReady(){return!this._isReady||this._isReady()}get forwardControl(){return this.forward}nextMeta(){return{_debug_index:this.debugIndex++,_ts:Date.now()}}sendResult(e,s){const t=this.nextMeta();this.detectProtocolError(e,s,t._debug_index);const r={jsonrpc:"2.0",id:e,result:this.attachMeta(s,t),_debug_index:t._debug_index,_ts:t._ts};this.sendBridgeMessage(r),this.obs({component:"acp-transport",domain:"reply",name:"rpc.result",severity:"debug",payload:{id:e,_debug_index:t._debug_index}})}sendError(e,s,t,r){const o=this.nextMeta(),n={code:s,message:t};n.data=void 0!==r?this.attachMeta(r,o):{_meta:o};const d={jsonrpc:"2.0",id:e,error:n,_debug_index:o._debug_index,_ts:o._ts};this.sendBridgeMessage(d),this.obs({component:"acp-transport",domain:"reply",name:"rpc.error",severity:"warn",payload:{id:e,code:s,message:t,_debug_index:o._debug_index}})}sendAcpError(e,s,t){const r=acpError(s,t);this.sendError(e,r.code,r.message,r.data)}sendNotification(e,s){const t=this.nextMeta(),r={jsonrpc:"2.0",method:e,params:s,_debug_index:t._debug_index,_ts:t._ts};this.sendBridgeMessage(r)}enrich(e,s){if(!s||!s.turnId&&!s.messageId&&void 0===s.seq)return e;const t={...e};return s.turnId&&(t._turnId=s.turnId),s.messageId&&(t.messageId=s.messageId),void 0!==s.seq&&(t._seq=s.seq),t}sendSessionUpdate(e,s,t){const r=normalizeOpts(t),o=s,n=o?.sessionUpdate;if("agent_thought_chunk"===n&&!this.forward.forwardThinking)return!1;if(("tool_call"===n||"tool_call_update"===n)&&!this.forward.forwardToolCalls)return!1;const d=(this.sessionUpdateCounts.get(e)??0)+1;this.sessionUpdateCounts.set(e,d),d%50==0&&this.obs({component:"acp-transport",domain:"session-update",name:"send.rate",severity:"debug",payload:{sessionId:e,totalSent:d,lastType:n,_debug_index:this.debugIndex}}),this.sendNotification("session/update",{sessionId:e,update:this.enrich(s,r)});try{this.sessionUpdateObserver?.(e,s,r)}catch{}return!0}sendSessionUpdateStrict(e,s,t){return this.sendSessionUpdate(e,s,t)}resetSessionUpdateCount(e){this.sessionUpdateCounts.delete(e)}detectProtocolError(e,s,t){if(!s||"object"!=typeof s)return;const r=s,o="error"in r&&null!=r.error,n="ok"in r&&!1===r.ok;(o||n)&&this.obs({component:"acp-transport",domain:"reply",name:"protocol.error_in_result",severity:"warn",payload:{id:e,_debug_index:t,hasError:o,notOk:n,errorSummary:o?"string"==typeof r.error?r.error.slice(0,200):JSON.stringify(r.error).slice(0,200):void 0}})}attachMeta(e,s){return!e||"object"!=typeof e||Array.isArray(e)?e:{...e,_meta:s}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describe,it,expect,beforeEach,vi}from"vitest";import{AcpTransport}from"./transport.js";function makeTransport(){const e=[];return{tx:new AcpTransport(t=>{e.push(t)}),sent:e}}function getUpdate(e){expect(e.length).toBe(1);return e[0].params.update}describe("AcpTransport session/update _seq injection",()=>{let e,t;beforeEach(()=>{const s=makeTransport();e=s.tx,t=s.sent}),it("injects _seq from opts.seq when provided",()=>{e.sendSessionUpdate("s1",{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"hi"}},{turnId:"t1",messageId:"m1",seq:42});const s=getUpdate(t);expect(s._seq).toBe(42),expect(s._turnId).toBe("t1"),expect(s.messageId).toBe("m1")}),it("omits _seq when opts.seq is undefined",()=>{e.sendSessionUpdate("s1",{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"hi"}},{turnId:"t1",messageId:"m1"});const s=getUpdate(t);expect("_seq"in s).toBe(!1)}),it("preserves seq=0 (not treated as missing)",()=>{e.sendSessionUpdate("s1",{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"hi"}},{seq:0});const s=getUpdate(t);expect(s._seq).toBe(0)}),it("does not enrich when opts omits all identifiers",()=>{const s={sessionUpdate:"agent_message_chunk",content:{type:"text",text:"hi"}};e.sendSessionUpdate("s1",s);const n=getUpdate(t);expect(n).toEqual(s),expect("_seq"in n).toBe(!1),expect("_turnId"in n).toBe(!1),expect("messageId"in n).toBe(!1)}),it("multiple splits sharing the same seq all emit _seq (client dedups)",()=>{e.sendSessionUpdate("s1",{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"text"}},{turnId:"t1",messageId:"m1",seq:7}),e.sendSessionUpdate("s1",{sessionUpdate:"tool_call",toolCallId:"T1"},{turnId:"t1",messageId:"m1",seq:7}),e.sendSessionUpdate("s1",{sessionUpdate:"tool_call_update",toolCallId:"T1"},{turnId:"t1",messageId:"m1",seq:7}),expect(t.length).toBe(3);for(const e of t){const t=e.params.update;expect(t._seq).toBe(7),expect(t.messageId).toBe("m1"),expect(t._turnId).toBe("t1")}}),it("
|
|
1
|
+
import{describe,it,expect,beforeEach,vi}from"vitest";import{AcpTransport}from"./transport.js";function makeTransport(){const e=[];return{tx:new AcpTransport(t=>{e.push(t)}),sent:e}}function getUpdate(e){expect(e.length).toBe(1);return e[0].params.update}describe("AcpTransport session/update _seq injection",()=>{let e,t;beforeEach(()=>{const s=makeTransport();e=s.tx,t=s.sent}),it("injects _seq from opts.seq when provided",()=>{e.sendSessionUpdate("s1",{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"hi"}},{turnId:"t1",messageId:"m1",seq:42});const s=getUpdate(t);expect(s._seq).toBe(42),expect(s._turnId).toBe("t1"),expect(s.messageId).toBe("m1")}),it("omits _seq when opts.seq is undefined",()=>{e.sendSessionUpdate("s1",{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"hi"}},{turnId:"t1",messageId:"m1"});const s=getUpdate(t);expect("_seq"in s).toBe(!1)}),it("preserves seq=0 (not treated as missing)",()=>{e.sendSessionUpdate("s1",{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"hi"}},{seq:0});const s=getUpdate(t);expect(s._seq).toBe(0)}),it("does not enrich when opts omits all identifiers",()=>{const s={sessionUpdate:"agent_message_chunk",content:{type:"text",text:"hi"}};e.sendSessionUpdate("s1",s);const n=getUpdate(t);expect(n).toEqual(s),expect("_seq"in n).toBe(!1),expect("_turnId"in n).toBe(!1),expect("messageId"in n).toBe(!1)}),it("multiple splits sharing the same seq all emit _seq (client dedups)",()=>{e.sendSessionUpdate("s1",{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"text"}},{turnId:"t1",messageId:"m1",seq:7}),e.sendSessionUpdate("s1",{sessionUpdate:"tool_call",toolCallId:"T1"},{turnId:"t1",messageId:"m1",seq:7}),e.sendSessionUpdate("s1",{sessionUpdate:"tool_call_update",toolCallId:"T1"},{turnId:"t1",messageId:"m1",seq:7}),expect(t.length).toBe(3);for(const e of t){const t=e.params.update;expect(t._seq).toBe(7),expect(t.messageId).toBe("m1"),expect(t._turnId).toBe("t1")}}),it("legacy positional turnId signature still works and omits _seq",()=>{e.sendSessionUpdate("s1",{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"hi"}},"t1");const s=getUpdate(t);expect(s._turnId).toBe("t1"),expect("_seq"in s).toBe(!1)}),it("forwardThinking=false still suppresses agent_thought_chunk regardless of seq",()=>{const e=[],t=new AcpTransport(t=>e.push(t),void 0,{forwardThinking:!1,forwardToolCalls:!0}).sendSessionUpdate("s1",{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:"thinking"}},{seq:1});expect(t).toBe(!1),expect(e.length).toBe(0)}),it("observer receives the opts including seq",()=>{const t=vi.fn();e.setSessionUpdateObserver(t),e.sendSessionUpdate("s1",{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"hi"}},{turnId:"t1",messageId:"m1",seq:3}),expect(t).toHaveBeenCalledTimes(1);const s=t.mock.calls[0][2];expect(s).toEqual({turnId:"t1",messageId:"m1",seq:3})})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const DEFAULT_PROMPT_TIMEOUT_MS=18e5;export const DEFAULT_STREAM_IDLE_TIMEOUT_MS=15e3;export const DEFAULT_STREAM_STALE_TIMEOUT_MS=6e5;
|
|
1
|
+
export const DEFAULT_PROMPT_TIMEOUT_MS=18e5;export const DEFAULT_STREAM_IDLE_TIMEOUT_MS=15e3;export const DEFAULT_STREAM_STALE_TIMEOUT_MS=6e5;
|
package/dist/acp-server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{WebSocketServer,WebSocket}from"ws";import{randomUUID}from"node:crypto";let BridgeClientCtor;import{GatewayClient}from"./gateway-client.js";import{TerminalManager}from"./terminal/session-manager.js";import{AcpTransport}from"./acp-gateway/transport.js";import{AcpGatewaySessionState}from"./acp-gateway/session-state.js";import{AcpGatewayBridgeCore}from"./acp-gateway/bridge-core.js";import{BeeosFileResolver}from"./acp-gateway/beeos-file-resolver.js";import{AcpGatewayEvents}from"./acp-gateway/gateway-events.js";import{TerminalBridgeHandler}from"./terminal/bridge-handler.js";import{syncAgentsToPlatform}from"./agent-sync.js";import{CanvasOrchestrator}from"./canvas-orchestrator.js";import{discoverBridgeFromGW}from"./bridge-discovery.js";import{writeDiscoveryCache}from"./discovery-cache.js";export class ACPServer{agentFetchFn;instanceId;wss=null;gateway=null;client=null;config;logger;writeObs;transport;state;core;events;terminalMgr;terminalHandler;canvasOrch;messageSdk=null;msgPrincipalId=null;pendingToolCallSessionKeys=[];thirdPartyChannels;agentSyncRetryTimer=null;bridgeInstance=null;bridgeConsecutiveFailures=0;static RE_DISCOVER_THRESHOLD=2;drainNextDeferredSend(e){const t=e.pendingAgentSends?.shift();t&&(e.pendingAgentSends?.length||(e.pendingAgentSends=void 0),this.agentSend(t.message,t.attachments,e.gatewaySessionKey,t.inputProvenance).catch(e=>this.logger.warn?.("[acp-server] Deferred agentSend failed: %s",e)))}async gatewayRequest(e,t){if(!this.gateway?.isConnected)throw new Error("Gateway not connected");return this.gateway.request(e,t)}async agentSend(e,t,s,n,i){if(!this.gateway?.isConnected)throw new Error("Gateway not connected");const a=this.config.gateway.agentId||this.core.getDefaultAgentId();let r,o;if(s?(r=this.state.findSessionByKey(s),o=s,r?this.logger.info?.(`[acp-server] agentSend: resolved session for key=${s} sid=${r.sessionId}`):(r=this.core.ensureSessionForKey(o),this.logger.info?.(`[acp-server] agentSend: created session for key=${s} sid=${r.sessionId}`))):(o=`agent:${a}:a2a:${randomUUID()}`,r=this.core.ensureSessionForKey(o),this.logger.info?.(`[acp-server] agentSend: no targetSessionKey, created A2A session key=${o}`)),i&&r&&(r.channelId=i),r&&!r.promptDone&&(void 0!==r.pendingPromptId||void 0!==r.currentRunId||void 0!==r.gatewayRequestId))return(r.pendingAgentSends??=[]).push({message:e,attachments:t,inputProvenance:n}),void this.logger.info?.("[acp-server] Session has active run, deferred message (queue=%d)",r.pendingAgentSends.length);const c=await this.canvasOrch.enrichMessageWithCanvasContext(e,o,this.thirdPartyChannels),l=await this.gateway.agentSend(o,c,a,t,n);return l?.runId&&(r?(this.state.resetForNewRun(r,r.sessionId,this.transport),r.currentRunId=l.runId,r.assistantStreamStartedAt=Date.now(),this.state.promptsByRunId.set(l.runId,r)):this.state.promptsByRunId.set(l.runId,{gatewaySessionKey:o,channelId:i})),l}setMessageSdk(e,t){this.messageSdk=e,this.msgPrincipalId=t}sendBridgeMessage=e=>{const t=this.client;if(t&&t.readyState===WebSocket.OPEN)try{t.send(JSON.stringify(e))}catch(e){this.logger.debug?.("[acp-server] bridge send failed (socket may be closing):",e)}else this.logger.debug?.("[acp-server] bridge not ready, dropping message")};constructor(e,t,s,n,i,a){this.agentFetchFn=n,this.instanceId=i,this.config=e,this.logger=t,this.writeObs=s??(()=>{}),this.thirdPartyChannels=a??new Set,this.transport=new AcpTransport(this.sendBridgeMessage,this.writeObs,void 0,()=>{const e=this.client;return!!e&&e.readyState===WebSocket.OPEN}),this.state=new AcpGatewaySessionState(this.logger);const r=this.agentFetchFn&&this.config.agentGatewayUrl?new BeeosFileResolver({agentGatewayUrl:this.config.agentGatewayUrl,agentFetch:this.agentFetchFn,writeObs:this.writeObs}):void 0;this.core=new AcpGatewayBridgeCore({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,getGateway:()=>this.gateway,instanceId:this.instanceId,thirdPartyChannels:this.thirdPartyChannels,beeosFileResolver:r}),this.canvasOrch=new CanvasOrchestrator({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,getSessionIdForToolCall:e=>this.getSessionIdForToolCall(e),gateway:null,getDefaultAgentId:()=>this.core.getDefaultAgentId(),resolvePlatformAgentId:e=>this.core.resolvePlatformAgentId(e)??""}),this.events=new AcpGatewayEvents({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,completePrompt:(e,t)=>this.core.completePrompt(e,t),failPrompt:(e,t,s)=>this.core.failPrompt(e,t,s),maybeCompletePromptFromChatState:(e,t)=>this.core.maybeCompletePromptFromChatState(e,t),agentFetch:this.agentFetchFn,onStreamDelta:(e,t)=>{if(!this.messageSdk||!this.msgPrincipalId)return;const s=e.gatewaySessionKey;if(!s)return;const n=e.channelId,i={session_key:s,update:t};(n&&this.messageSdk.sendToChannel?this.messageSdk.sendToChannel(n,"agent_reply_delta",i):this.messageSdk.sendToPersonal(this.msgPrincipalId,"agent_reply_delta",i)).catch(e=>this.logger.debug?.(`[acp-server] agent_reply_delta publish failed: ${e}`))}}),this.core.onRunEnded=(e,t)=>{"complete"===t.kind?this.canvasOrch.onPromptComplete(e):this.canvasOrch.onPromptFailed(),this.drainNextDeferredSend(e)},this.terminalMgr=new TerminalManager,this.terminalHandler=new TerminalBridgeHandler({terminalMgr:this.terminalMgr,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs}),this.terminalHandler.setupListeners(),this.core.handleTerminalRequest=e=>this.terminalHandler.handleRequest(e),this.core.handleTerminalNotification=(e,t)=>this.terminalHandler.handleNotification(e,t),this.core.onRunComplete=(e,t)=>{const s=this.state.promptsByRunId.get(e),n=s?.gatewaySessionKey,i=s?.channelId;if(this.logger.info?.(`[acp-server] onRunComplete runId=${e} session_key=${n} channel=${i} principal=${this.msgPrincipalId} hasSDK=${!!this.messageSdk}`),this.messageSdk&&this.msgPrincipalId&&n){const e={session_key:n,text:t};(i&&this.messageSdk.sendToChannel?this.messageSdk.sendToChannel(i,"agent_reply",e):this.messageSdk.sendToPersonal(this.msgPrincipalId,"agent_reply",e)).then(()=>{this.logger.info?.(`[acp-server] agent_reply published ok session_key=${n} channel=${i??"personal"}`)}).catch(e=>this.logger.warn?.(`[acp-server] agent_reply publish failed: ${e instanceof Error?e.message:JSON.stringify(e)}`))}else n||this.logger.warn?.(`[acp-server] onRunComplete: no session_key for runId=${e}, cannot publish reply`)},this.core.onRunFailed=(e,t)=>{const s=this.state.promptsByRunId.get(e),n=s?.gatewaySessionKey,i=s?.channelId;if(this.logger.info?.(`[acp-server] onRunFailed runId=${e} session_key=${n} channel=${i}`),this.messageSdk&&this.msgPrincipalId&&n){const e={session_key:n,error:t||"execution failed"};(i&&this.messageSdk.sendToChannel?this.messageSdk.sendToChannel(i,"agent_reply",e):this.messageSdk.sendToPersonal(this.msgPrincipalId,"agent_reply",e)).catch(e=>this.logger.warn?.(`[acp-server] agent_reply error publish failed: ${e instanceof Error?e.message:String(e)}`))}},this.core.handleCanvasNotification=(e,t)=>{this.canvasOrch.handleCanvasNotification(e,t)},this.core.getCanvasState=()=>this.canvasOrch.canvasState,this.core.onSessionLoaded=(e,t,s)=>{this.canvasOrch.onSessionLoaded(e,t,s)},this.core.onSkillInstalled=(e,t)=>{this.registerSkillFormSchemas(e,t)},this.core.onSessionDeleted=e=>{this.canvasOrch.onSessionDeleted(e)},this.core.onSessionCleared=(e,t)=>{this.canvasOrch.onSessionCleared(e,t)},this.core.handleSlashCommand=async e=>this.canvasOrch.handleSlashCommand(e),this.core.onPromptStart=()=>{this.canvasOrch.onPromptStart()},this.state.startSessionGc(e=>this.core.cleanupPrompt(e),e=>{this.canvasOrch.canvasState?.removeSession(e.gatewaySessionKey),this.transport.resetSessionUpdateCount(e.sessionId)})}async start(e){const t=Date.now();this.logger.info?.("[acp-server] start() begin"),e&&(this.config.bridge.url=e);const s=this.config.bridge.url,n=this.config.keyFile;if(s&&!BridgeClientCtor)try{const e=Date.now(),t=await import("@beeos-ai/bridge-client");BridgeClientCtor=t.BridgeClient,this.logger.info?.(`[acp-server] bridge-client import took ${Date.now()-e}ms`)}catch(e){this.logger.warn?.("[acp-server] Bridge SDK not available")}const i=Date.now();if(await this.connectGateway(),this.logger.info?.(`[acp-server] connectGateway() took ${Date.now()-i}ms`),s&&n&&BridgeClientCtor){Date.now();await this.startBridgeMode(s,n)}else this.logger.warn?.("[acp-server] Bridge not configured; running in standby (no ACP listener). Use handleUpgrade() for noServer mode."),this.core.markAgentSyncDone();this.logger.info?.(`[acp-server] start() total ${Date.now()-t}ms`)}async startBridgeMode(e,t){if(!BridgeClientCtor)throw new Error("@beeos-ai/bridge-client not available");const s=new BridgeClientCtor({bridgeUrl:e,service:this.config.bridge.service||"acp",keyFile:t});this.bridgeInstance=s,s.on("connected",()=>{this.bridgeConsecutiveFailures=0,this.logger.info?.("[acp-server] Connected to Bridge (publicKey auth)"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"bridge.connected",severity:"info"}),this.tryAgentSync()}),s.on("disconnected",(...e)=>{const n=String(e[0]??"unknown");if(this.logger.warn?.(`[acp-server] Bridge disconnected: ${n}`),this.core.initialized=!1,this.bridgeConsecutiveFailures++,this.bridgeConsecutiveFailures>=ACPServer.RE_DISCOVER_THRESHOLD&&this.agentFetchFn&&this.config.agentGatewayUrl){this.bridgeConsecutiveFailures=0;const e=this.config.bridge.url;discoverBridgeFromGW(this.config.agentGatewayUrl,this.agentFetchFn).then(async n=>{n&&n.url!==e&&(this.logger.info?.(`[acp-server] Bridge re-discovery: URL changed ${e} → ${n.url}, switching`),this.config.bridge.url=n.url,writeDiscoveryCache({bridge:{url:n.url,discoveredAt:Date.now()}}),await s.close(!1),await this.startBridgeMode(n.url,t))}).catch(()=>{})}}),s.on("message",(...e)=>{const t=e[0],s="string"==typeof t?t:Buffer.from(t).toString("utf-8");try{const e=JSON.parse(s);"id"in e&&void 0!==e.id?this.core.handleRequest(e):this.core.handleNotification(e)}catch{this.logger.error?.("[acp-server] Invalid JSON-RPC message from Bridge")}}),s.on("error",(...e)=>{const t=e[0];this.logger.error?.("[acp-server] Bridge error:",t?.message)});const n={readyState:WebSocket.OPEN,send:(e,t)=>{try{s.send(e),t?.()}catch(e){t?.(e)}},close:()=>s.close(),terminate:()=>s.close(!1),on:()=>n,once:()=>n,removeListener:()=>n,removeAllListeners:()=>n,ping:()=>{}};Object.defineProperty(n,"readyState",{get:()=>"connected"===s.state?WebSocket.OPEN:WebSocket.CLOSED}),this.client=n;const i=Date.now();try{await s.connect(),this.logger.info?.(`[acp-server] bridge.connect() took ${Date.now()-i}ms`)}catch(e){this.logger.warn?.(`[acp-server] Initial bridge connect failed after ${Date.now()-i}ms (will retry in background): ${e?.message}`)}this.core.initialized=!1,this.logger.info?.("[acp-server] Running in Bridge mode (WS client)")}handleUpgrade(e,t,s){this.wss||(this.wss=new WebSocketServer({noServer:!0}),this.wss.on("connection",(e,t)=>this.handleConnection(e,t))),this.wss.handleUpgrade(e,t,s,t=>{this.wss.emit("connection",t,e)})}async tryAgentSync(e=0){if(this.agentSyncRetryTimer&&(clearTimeout(this.agentSyncRetryTimer),this.agentSyncRetryTimer=null),!this.client||this.client.readyState!==WebSocket.OPEN)return;if(!this.gateway||!this.agentFetchFn||!this.config.agentGatewayUrl)return void this.core.markAgentSyncDone();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)},s=Date.now();try{const e=await syncAgentsToPlatform({gateway:this.gateway,agentGatewayUrl:this.config.agentGatewayUrl,capabilities:{canvas:this.config.canvasEnabled,terminal:!0,fileSystem:!0,cron:!0,streaming:!0},agentFetch:this.agentFetchFn,logger:this.logger});e?(this.core.setAgentMapping(e),this.logger.info?.(`[acp-server] agent mapping loaded: ${[...e.keys()].join(", ")} (sync took ${Date.now()-s}ms)`)):t()}catch(e){this.logger.warn?.(`[acp-server] agent sync failed: ${e}`),t()}}async connectGateway(){this.gateway&&(this.gateway.stop(),this.gateway=null);const e=this.config.gateway;this.gateway=new GatewayClient({url:e.url,token:e.token||"",clientId:e.clientId,openclawCanvasCompat:!!this.config.openclawCanvasCompat,retry:{baseMs:this.config.retry.baseMs,maxMs:this.config.retry.maxMs,maxAttempts:this.config.retry.maxAttempts}}),this.gateway.on("chat",e=>this.events.handleChatEvent(e)),this.gateway.on("agent",e=>this.events.handleAgentEvent(e)),this.gateway.on("cron",e=>this.events.handleCronEvent(e)),this.gateway.on("sessionMessage",e=>this.core.handleSessionMessage(e)),this.gateway.on("response",e=>this.core.handleGatewayResponse(e));const t=this.gateway;this.canvasOrch.updateDeps({gateway:t?{get isConnected(){return t.isConnected},request:(e,t)=>this.gateway.request(e,t),agentSend:(e,t,s)=>this.gateway.agentSend(e,t,s)}:null}),this.config.openclawCanvasCompat&&(this.gateway.on("canvas",e=>this.canvasOrch.handleOpenClawCanvasEvent(e)),this.logger.info?.("[acp-server] OpenClaw native canvas compat enabled — listening for canvas events")),this.gateway.on("connected",()=>{this.logger.info?.("[acp-server] Connected to OpenClaw Gateway"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"gateway.connected",severity:"info"}),this.core.resubscribeAllSessionMessages(),this.core.refreshCronIsolatedSessionKeys()}),this.gateway.on("disconnected",()=>{this.logger.warn?.("[acp-server] Gateway disconnected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"gateway.disconnected",severity:"warn"}),this.core.cleanupAllPendingPrompts()}),this.gateway.on("reconnecting",e=>{this.logger.info?.(`[acp-server] Reconnecting to Gateway attempt=${e.attempt} delay=${Math.round(e.delayMs)}ms`)}),this.gateway.on("reconnect-exhausted",e=>{this.logger.error?.(`[acp-server] Gateway reconnect exhausted after ${e} attempts`)}),this.gateway.on("error",e=>{this.logger.error?.("[acp-server] Gateway error:",e.message)}),this.gateway.on("transport",e=>{this.logger.info?.(`[acp-server] transport.${e.event} durationMs=${e.durationMs??"?"}`),this.writeObs({component:"gateway-client",domain:"lifecycle",name:`transport.${e.event}`,severity:"connect_fail"===e.event||"error"===e.event?"warn":"debug",payload:e})}),this.gateway.on("reconnect-notify-scheduled",e=>{this.logger.info?.(`[acp-server] Server-initiated reconnect scheduled in ${e.delayMs}ms`)}),this.gateway.on("reconnect-notify-fired",()=>{this.logger.info?.("[acp-server] Server-initiated reconnect firing")});try{await this.gateway.start()}catch(e){this.logger.error?.("[acp-server] Initial Gateway connect failed:",e)}}handleConnection(e,t){if(this.client){this.logger.warn?.("[acp-server] Replacing existing ACP client with new connection (takeover)");const e=this.client;this.client=null;try{e.close(1008,"replaced by new client")}catch{e.terminate()}}this.client=e,this.core.initialized=!1,this.logger.info?.("[acp-server] ACP client connected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"client.connected",severity:"info"}),e.on("message",e=>{const t="string"==typeof e?e:e.toString("utf-8");try{const e=JSON.parse(t);"id"in e&&void 0!==e.id?this.core.handleRequest(e):this.core.handleNotification(e)}catch{this.logger.error?.("[acp-server] Invalid JSON-RPC message")}}),e.on("close",()=>{this.client===e&&(this.client=null,this.core.initialized=!1),this.logger.info?.("[acp-server] ACP client disconnected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"client.disconnected",severity:"info"})})}pushToolResultContent(e,t,s,n){this.core.pushToolResultContent(e,t,s,n)}setCanvasState(e,t){this.canvasOrch.setCanvasState(e,t)}wireRelayActionHandler(){this.canvasOrch.wireRelayActionHandler()}isCanvasActive(e){return this.canvasOrch.isCanvasActive(e)}isCanvasActiveForGatewayKey(e){return this.canvasOrch.isCanvasActiveForGatewayKey(e)}broadcastNotification(e,t){this.transport.sendNotification(e,t)}getActiveSessionId(){return this.state.lastActiveSessionId}getSessionIdForToolCall(e){const t=this.pendingToolCallSessionKeys.length>0?this.pendingToolCallSessionKeys[this.pendingToolCallSessionKeys.length-1]:void 0;if(t){const s=this.state.findSessionByKey(t)??this.core.ensureSessionForKey(t);if(s?.sessionId)return e&&this.state.toolCallToSessionMap.set(e,s.sessionId),s.sessionId}if(e){const t=this.state.toolCallToSessionMap.get(e);if(t)return t;const s=this.state.toolCallIdMap.get(e);if(s&&s!==e){const e=this.state.toolCallToSessionMap.get(s);if(e)return e}const n=e.split("_");if(n.length>=3&&"tc"===n[0]){const e=n[1],t=this.state.promptsByRunId.get(e);if(t?.sessionId)return t.sessionId}}this.logger.warn?.(`[acp-server] getSessionIdForToolCall MISS: toolCallId=${e??"(none)"}, sessions=${this.state.sessions.size}, pendingKey=${t??"none"}`)}getSessionIdForActivePrompt(){return this.getSessionIdForToolCall()}setPendingToolCallSessionKey(e){e&&(this.pendingToolCallSessionKeys.push(e),this.pendingToolCallSessionKeys.length>16&&this.pendingToolCallSessionKeys.shift())}preMapToolCallSession(e){const t=this.pendingToolCallSessionKeys.length>0?this.pendingToolCallSessionKeys[this.pendingToolCallSessionKeys.length-1]:void 0;if(!t||!e)return;if(this.state.toolCallToSessionMap.has(e))return;const s=this.state.findSessionByKey(t)??this.core.ensureSessionForKey(t);s?.sessionId&&this.state.toolCallToSessionMap.set(e,s.sessionId)}waitForAgentMapping(){return this.core.waitForAgentMapping()}onceAgentMappingReady(e){this.core.onceAgentMappingReady(e)}flushPendingCanvasLinks(){this.canvasOrch.flushPendingCanvasLinks()}onRelayReconnected(){this.canvasOrch.onRelayReconnected()}getLocalAgentId(){return this.config.gateway.agentId||this.core.getDefaultAgentId()}getDefaultPlatformAgentId(){return this.getDefaultPlatformAgent()?.id}getDefaultPlatformAgent(){const e=this.core.agentMapping;if(e&&0!==e.size)return e.values().next().value??void 0}getPlatformAgentIdForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return this.core.resolvePlatformAgentId(s?.agentId??"")??s?.platformAgentId}getGatewaySessionKeyForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return s?.gatewaySessionKey}getMentionsForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return s?.activeMentions}getResourceRenderer(){return this.canvasOrch.resourceRenderer}getDescriptorRegistry(){return this.canvasOrch.descriptorRegistry}getFormBuilder(){return this.canvasOrch.formBuilder}getSchemaRegistry(){return this.canvasOrch.schemaRegistry}registerSkillFormSchemas(e,t){const s=this.canvasOrch.schemaRegistry;s&&import("node:fs/promises").then(async({readFile:n})=>{try{const i=`${t}/skill.json`,a=await n(i,"utf-8"),r=JSON.parse(a);if(r.formSchemas?.length){for(const e of r.formSchemas)s.register({...e,submitLabel:e.submitLabel||"Submit",fields:e.fields});this.logger.info?.(`[acp-server] Registered ${r.formSchemas.length} form schema(s) from skill "${e}"`)}}catch{}})}emitCanvasActionAsUserMessage(e,t){this.canvasOrch.emitCanvasActionAsUserMessage(e,t)}async stop(){this.agentSyncRetryTimer&&(clearTimeout(this.agentSyncRetryTimer),this.agentSyncRetryTimer=null),this.state.destroy(),this.canvasOrch.destroy(),this.gateway&&(this.gateway.removeAllListeners(),this.gateway.stop(),this.gateway=null),this.client&&(this.client.removeAllListeners(),this.client.close(),this.client=null),this.bridgeInstance=null,this.bridgeConsecutiveFailures=0,this.terminalHandler.destroy(),this.terminalMgr.destroy(),this.wss&&(this.wss.removeAllListeners(),this.wss.close(),this.wss=null),this.logger.info?.("[acp-server] Stopped"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"lifecycle.shutdown",severity:"info"})}}
|
|
1
|
+
import{WebSocketServer,WebSocket}from"ws";import{randomUUID}from"node:crypto";let BridgeClientCtor;import{GatewayClient}from"./gateway-client.js";import{TerminalManager}from"./terminal/session-manager.js";import{AcpTransport}from"./acp-gateway/transport.js";import{AcpGatewaySessionState}from"./acp-gateway/session-state.js";import{AcpGatewayBridgeCore}from"./acp-gateway/bridge-core.js";import{BeeosFileResolver}from"./acp-gateway/beeos-file-resolver.js";import{AcpGatewayEvents}from"./acp-gateway/gateway-events.js";import{TerminalBridgeHandler}from"./terminal/bridge-handler.js";import{syncAgentsToPlatform}from"./agent-sync.js";import{CanvasOrchestrator}from"./canvas-orchestrator.js";import{discoverBridgeFromGW}from"./bridge-discovery.js";import{writeDiscoveryCache}from"./discovery-cache.js";export class ACPServer{agentFetchFn;instanceId;wss=null;gateway=null;client=null;config;logger;writeObs;transport;state;core;events;terminalMgr;terminalHandler;canvasOrch;messageSdk=null;msgPrincipalId=null;pendingToolCallSessionKeys=[];thirdPartyChannels;agentSyncRetryTimer=null;bridgeInstance=null;bridgeConsecutiveFailures=0;static RE_DISCOVER_THRESHOLD=2;drainNextDeferredSend(e){const t=e.pendingAgentSends?.shift();t&&(e.pendingAgentSends?.length||(e.pendingAgentSends=void 0),this.agentSend(t.message,t.attachments,e.gatewaySessionKey,t.inputProvenance,t.channelId,t.inboundMessageId).catch(e=>this.logger.warn?.("[acp-server] Deferred agentSend failed: %s",e)))}async gatewayRequest(e,t){if(!this.gateway?.isConnected)throw new Error("Gateway not connected");return this.gateway.request(e,t)}async agentSend(e,t,s,n,i,a){if(!this.gateway?.isConnected)throw new Error("Gateway not connected");const r=this.config.gateway.agentId||this.core.getDefaultAgentId();let o,c;if(s?(o=this.state.findSessionByKey(s),c=s,o?this.logger.info?.(`[acp-server] agentSend: resolved session for key=${s} sid=${o.sessionId}`):(o=this.core.ensureSessionForKey(c),this.logger.info?.(`[acp-server] agentSend: created session for key=${s} sid=${o.sessionId}`))):(c=`agent:${r}:a2a:${randomUUID()}`,o=this.core.ensureSessionForKey(c),this.logger.info?.(`[acp-server] agentSend: no targetSessionKey, created A2A session key=${c}`)),i&&o&&(o.channelId=i),a&&o&&(o.inboundMessageId=a),o&&!o.promptDone&&(void 0!==o.pendingPromptId||void 0!==o.currentRunId||void 0!==o.gatewayRequestId))return(o.pendingAgentSends??=[]).push({message:e,attachments:t,inputProvenance:n,channelId:i,inboundMessageId:a}),void this.logger.info?.("[acp-server] Session has active run, deferred message (queue=%d)",o.pendingAgentSends.length);const l=await this.gateway.agentSend(c,e,r,t,n);return l?.runId&&(o?(this.state.resetForNewRun(o,o.sessionId,this.transport),o.currentRunId=l.runId,o.assistantStreamStartedAt=Date.now(),this.state.promptsByRunId.set(l.runId,o)):this.state.promptsByRunId.set(l.runId,{gatewaySessionKey:c,channelId:i,inboundMessageId:a})),l}setMessageSdk(e,t){this.messageSdk=e,this.msgPrincipalId=t}async publishAgentReply(e,t,s,n){const i=this.messageSdk,a=this.msgPrincipalId;if(i&&a){if(e&&i.sendToChannel)try{return await i.sendToChannel(e,s,n,{inReplyTo:t}),void this.logger.info?.(`[acp-server] ${s} published channel=${e} in_reply_to=${t??"-"}`)}catch(t){this.logger.warn?.(`[acp-server] sendToChannel failed channel=${e}: ${t instanceof Error?t.message:String(t)}; attempting persistent fallback`)}if(e&&i.sendChannelMessage)try{return await i.sendChannelMessage(e,{type:s,payload:n,inReplyTo:t,senderId:a}),void this.logger.info?.(`[acp-server] ${s} persisted channel=${e} in_reply_to=${t??"-"}`)}catch(t){this.logger.warn?.(`[acp-server] sendChannelMessage failed channel=${e}: ${t instanceof Error?t.message:String(t)}; falling back to personal channel`)}await i.sendToPersonal(a,s,n)}}sendBridgeMessage=e=>{const t=this.client;if(t&&t.readyState===WebSocket.OPEN)try{t.send(JSON.stringify(e))}catch(e){this.logger.debug?.("[acp-server] bridge send failed (socket may be closing):",e)}else this.logger.debug?.("[acp-server] bridge not ready, dropping message")};constructor(e,t,s,n,i,a){this.agentFetchFn=n,this.instanceId=i,this.config=e,this.logger=t,this.writeObs=s??(()=>{}),this.thirdPartyChannels=a??new Set,this.transport=new AcpTransport(this.sendBridgeMessage,this.writeObs,void 0,()=>{const e=this.client;return!!e&&e.readyState===WebSocket.OPEN}),this.state=new AcpGatewaySessionState(this.logger);const r=this.agentFetchFn&&this.config.agentGatewayUrl?new BeeosFileResolver({agentGatewayUrl:this.config.agentGatewayUrl,agentFetch:this.agentFetchFn,writeObs:this.writeObs}):void 0;this.core=new AcpGatewayBridgeCore({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,getGateway:()=>this.gateway,instanceId:this.instanceId,thirdPartyChannels:this.thirdPartyChannels,beeosFileResolver:r,agentFetch:this.agentFetchFn,agentGatewayUrl:this.config.agentGatewayUrl}),this.canvasOrch=new CanvasOrchestrator({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,getSessionIdForToolCall:e=>this.getSessionIdForToolCall(e),gateway:null,getDefaultAgentId:()=>this.core.getDefaultAgentId(),resolvePlatformAgentId:e=>this.core.resolvePlatformAgentId(e)??""}),this.events=new AcpGatewayEvents({state:this.state,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs,completePrompt:(e,t)=>this.core.completePrompt(e,t),failPrompt:(e,t,s)=>this.core.failPrompt(e,t,s),maybeCompletePromptFromChatState:(e,t)=>this.core.maybeCompletePromptFromChatState(e,t),agentFetch:this.agentFetchFn,getMessageSdk:()=>{const e=this.messageSdk;return e?.sendToChannel?{sendToChannel:e.sendToChannel.bind(e)}:null},getMsgPrincipalId:()=>this.msgPrincipalId??null,gatewayRequest:(e,t)=>{const s=this.gateway;return s?.isConnected?s.request(e,t):Promise.reject(new Error("gateway not connected"))},cronChannelCache:this.core.cronChannelCache,onStreamDelta:(e,t)=>{if(!this.messageSdk||!this.msgPrincipalId)return;const s=e.gatewaySessionKey;if(!s)return;const n=e.channelId,i={session_key:s,update:t};(n&&this.messageSdk.sendToChannel?this.messageSdk.sendToChannel(n,"agent_reply_delta",i):this.messageSdk.sendToPersonal(this.msgPrincipalId,"agent_reply_delta",i)).catch(e=>this.logger.debug?.(`[acp-server] agent_reply_delta publish failed: ${e}`))}}),this.core.onRunEnded=(e,t)=>{"complete"===t.kind?this.canvasOrch.onPromptComplete(e):this.canvasOrch.onPromptFailed(),this.drainNextDeferredSend(e)},this.terminalMgr=new TerminalManager,this.terminalHandler=new TerminalBridgeHandler({terminalMgr:this.terminalMgr,transport:this.transport,config:this.config,logger:this.logger,writeObs:this.writeObs}),this.terminalHandler.setupListeners(),this.core.handleTerminalRequest=e=>this.terminalHandler.handleRequest(e),this.core.handleTerminalNotification=(e,t)=>this.terminalHandler.handleNotification(e,t),this.core.onRunComplete=(e,t)=>{const s=this.state.promptsByRunId.get(e),n=s?.gatewaySessionKey,i=s?.channelId,a=s?.inboundMessageId;if(this.logger.info?.(`[acp-server] onRunComplete runId=${e} session_key=${n} channel=${i} in_reply_to=${a??"-"} principal=${this.msgPrincipalId} hasSDK=${!!this.messageSdk}`),!n)return void this.logger.warn?.(`[acp-server] onRunComplete: no session_key for runId=${e}, cannot publish reply`);const r={session_key:n,text:t};this.publishAgentReply(i,a,"agent_reply",r).catch(e=>this.logger.warn?.(`[acp-server] agent_reply publish failed: ${e instanceof Error?e.message:JSON.stringify(e)}`))},this.core.onRunFailed=(e,t)=>{const s=this.state.promptsByRunId.get(e),n=s?.gatewaySessionKey,i=s?.channelId,a=s?.inboundMessageId;if(this.logger.info?.(`[acp-server] onRunFailed runId=${e} session_key=${n} channel=${i} in_reply_to=${a??"-"}`),!n)return;const r={session_key:n,error:t||"execution failed"};this.publishAgentReply(i,a,"agent_reply",r).catch(e=>this.logger.warn?.(`[acp-server] agent_reply error publish failed: ${e instanceof Error?e.message:String(e)}`))},this.core.handleCanvasNotification=(e,t)=>{this.canvasOrch.handleCanvasNotification(e,t)},this.core.getCanvasState=()=>this.canvasOrch.canvasState,this.core.onSessionLoaded=(e,t,s)=>{this.canvasOrch.onSessionLoaded(e,t,s)},this.core.onSkillInstalled=(e,t)=>{this.registerSkillFormSchemas(e,t)},this.core.onSessionDeleted=e=>{this.canvasOrch.onSessionDeleted(e)},this.core.onSessionCleared=(e,t)=>{this.canvasOrch.onSessionCleared(e,t)},this.core.handleSlashCommand=async e=>this.canvasOrch.handleSlashCommand(e),this.core.onPromptStart=()=>{this.canvasOrch.onPromptStart()},this.state.startSessionGc(e=>this.core.cleanupPrompt(e),e=>{this.canvasOrch.canvasState?.removeSession(e.gatewaySessionKey),this.transport.resetSessionUpdateCount(e.sessionId)})}async start(e){const t=Date.now();this.logger.info?.("[acp-server] start() begin"),e&&(this.config.bridge.url=e);const s=this.config.bridge.url,n=this.config.keyFile;if(s&&!BridgeClientCtor)try{const e=Date.now(),t=await import("@beeos-ai/bridge-client");BridgeClientCtor=t.BridgeClient,this.logger.info?.(`[acp-server] bridge-client import took ${Date.now()-e}ms`)}catch(e){this.logger.warn?.("[acp-server] Bridge SDK not available")}const i=Date.now();if(await this.connectGateway(),this.logger.info?.(`[acp-server] connectGateway() took ${Date.now()-i}ms`),s&&n&&BridgeClientCtor){Date.now();await this.startBridgeMode(s,n)}else this.logger.warn?.("[acp-server] Bridge not configured; running in standby (no ACP listener). Use handleUpgrade() for noServer mode."),this.core.markAgentSyncDone();this.logger.info?.(`[acp-server] start() total ${Date.now()-t}ms`)}async startBridgeMode(e,t){if(!BridgeClientCtor)throw new Error("@beeos-ai/bridge-client not available");const s=new BridgeClientCtor({bridgeUrl:e,service:this.config.bridge.service||"acp",keyFile:t});this.bridgeInstance=s,s.on("connected",()=>{this.bridgeConsecutiveFailures=0,this.logger.info?.("[acp-server] Connected to Bridge (publicKey auth)"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"bridge.connected",severity:"info"}),this.tryAgentSync()}),s.on("disconnected",(...e)=>{const n=String(e[0]??"unknown");if(this.logger.warn?.(`[acp-server] Bridge disconnected: ${n}`),this.core.initialized=!1,this.bridgeConsecutiveFailures++,this.bridgeConsecutiveFailures>=ACPServer.RE_DISCOVER_THRESHOLD&&this.agentFetchFn&&this.config.agentGatewayUrl){this.bridgeConsecutiveFailures=0;const e=this.config.bridge.url;discoverBridgeFromGW(this.config.agentGatewayUrl,this.agentFetchFn).then(async n=>{n&&n.url!==e&&(this.logger.info?.(`[acp-server] Bridge re-discovery: URL changed ${e} → ${n.url}, switching`),this.config.bridge.url=n.url,writeDiscoveryCache({bridge:{url:n.url,discoveredAt:Date.now()}}),await s.close(!1),await this.startBridgeMode(n.url,t))}).catch(()=>{})}}),s.on("message",(...e)=>{const t=e[0],s="string"==typeof t?t:Buffer.from(t).toString("utf-8");try{const e=JSON.parse(s);"id"in e&&void 0!==e.id?this.core.handleRequest(e):this.core.handleNotification(e)}catch{this.logger.error?.("[acp-server] Invalid JSON-RPC message from Bridge")}}),s.on("error",(...e)=>{const t=e[0];this.logger.error?.("[acp-server] Bridge error:",t?.message)});const n={readyState:WebSocket.OPEN,send:(e,t)=>{try{s.send(e),t?.()}catch(e){t?.(e)}},close:()=>s.close(),terminate:()=>s.close(!1),on:()=>n,once:()=>n,removeListener:()=>n,removeAllListeners:()=>n,ping:()=>{}};Object.defineProperty(n,"readyState",{get:()=>"connected"===s.state?WebSocket.OPEN:WebSocket.CLOSED}),this.client=n;const i=Date.now();try{await s.connect(),this.logger.info?.(`[acp-server] bridge.connect() took ${Date.now()-i}ms`)}catch(e){this.logger.warn?.(`[acp-server] Initial bridge connect failed after ${Date.now()-i}ms (will retry in background): ${e?.message}`)}this.core.initialized=!1,this.logger.info?.("[acp-server] Running in Bridge mode (WS client)")}handleUpgrade(e,t,s){this.wss||(this.wss=new WebSocketServer({noServer:!0}),this.wss.on("connection",(e,t)=>this.handleConnection(e,t))),this.wss.handleUpgrade(e,t,s,t=>{this.wss.emit("connection",t,e)})}async tryAgentSync(e=0){if(this.agentSyncRetryTimer&&(clearTimeout(this.agentSyncRetryTimer),this.agentSyncRetryTimer=null),!this.client||this.client.readyState!==WebSocket.OPEN)return;if(!this.gateway||!this.agentFetchFn||!this.config.agentGatewayUrl)return void this.core.markAgentSyncDone();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)},s=Date.now();try{const e=await syncAgentsToPlatform({gateway:this.gateway,agentGatewayUrl:this.config.agentGatewayUrl,capabilities:{canvas:this.config.canvasEnabled,terminal:!0,fileSystem:!0,cron:!0,streaming:!0},agentFetch:this.agentFetchFn,logger:this.logger});e?(this.core.setAgentMapping(e),this.logger.info?.(`[acp-server] agent mapping loaded: ${[...e.keys()].join(", ")} (sync took ${Date.now()-s}ms)`)):t()}catch(e){this.logger.warn?.(`[acp-server] agent sync failed: ${e}`),t()}}async connectGateway(){this.gateway&&(this.gateway.stop(),this.gateway=null);const e=this.config.gateway;this.gateway=new GatewayClient({url:e.url,token:e.token||"",clientId:e.clientId,openclawCanvasCompat:!!this.config.openclawCanvasCompat,retry:{baseMs:this.config.retry.baseMs,maxMs:this.config.retry.maxMs,maxAttempts:this.config.retry.maxAttempts}}),this.gateway.on("chat",e=>this.events.handleChatEvent(e)),this.gateway.on("agent",e=>this.events.handleAgentEvent(e)),this.gateway.on("cron",e=>this.events.handleCronEvent(e)),this.gateway.on("sessionMessage",e=>this.core.handleSessionMessage(e)),this.gateway.on("response",e=>this.core.handleGatewayResponse(e));const t=this.gateway;this.canvasOrch.updateDeps({gateway:t?{get isConnected(){return t.isConnected},request:(e,t)=>this.gateway.request(e,t),agentSend:(e,t,s)=>this.gateway.agentSend(e,t,s)}:null}),this.config.openclawCanvasCompat&&(this.gateway.on("canvas",e=>this.canvasOrch.handleOpenClawCanvasEvent(e)),this.logger.info?.("[acp-server] OpenClaw native canvas compat enabled — listening for canvas events")),this.gateway.on("connected",()=>{this.logger.info?.("[acp-server] Connected to OpenClaw Gateway"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"gateway.connected",severity:"info"}),this.core.resubscribeAllSessionMessages(),this.core.refreshCronIsolatedSessionKeys()}),this.gateway.on("disconnected",()=>{this.logger.warn?.("[acp-server] Gateway disconnected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"gateway.disconnected",severity:"warn"}),this.core.cleanupAllPendingPrompts()}),this.gateway.on("reconnecting",e=>{this.logger.info?.(`[acp-server] Reconnecting to Gateway attempt=${e.attempt} delay=${Math.round(e.delayMs)}ms`)}),this.gateway.on("reconnect-exhausted",e=>{this.logger.error?.(`[acp-server] Gateway reconnect exhausted after ${e} attempts`)}),this.gateway.on("error",e=>{this.logger.error?.("[acp-server] Gateway error:",e.message)}),this.gateway.on("transport",e=>{this.logger.info?.(`[acp-server] transport.${e.event} durationMs=${e.durationMs??"?"}`),this.writeObs({component:"gateway-client",domain:"lifecycle",name:`transport.${e.event}`,severity:"connect_fail"===e.event||"error"===e.event?"warn":"debug",payload:e})}),this.gateway.on("reconnect-notify-scheduled",e=>{this.logger.info?.(`[acp-server] Server-initiated reconnect scheduled in ${e.delayMs}ms`)}),this.gateway.on("reconnect-notify-fired",()=>{this.logger.info?.("[acp-server] Server-initiated reconnect firing")});try{await this.gateway.start()}catch(e){this.logger.error?.("[acp-server] Initial Gateway connect failed:",e)}}handleConnection(e,t){if(this.client){this.logger.warn?.("[acp-server] Replacing existing ACP client with new connection (takeover)");const e=this.client;this.client=null;try{e.close(1008,"replaced by new client")}catch{e.terminate()}}this.client=e,this.core.initialized=!1,this.logger.info?.("[acp-server] ACP client connected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"client.connected",severity:"info"}),e.on("message",e=>{const t="string"==typeof e?e:e.toString("utf-8");try{const e=JSON.parse(t);"id"in e&&void 0!==e.id?this.core.handleRequest(e):this.core.handleNotification(e)}catch{this.logger.error?.("[acp-server] Invalid JSON-RPC message")}}),e.on("close",()=>{this.client===e&&(this.client=null,this.core.initialized=!1),this.logger.info?.("[acp-server] ACP client disconnected"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"client.disconnected",severity:"info"})})}pushToolResultContent(e,t,s,n){this.core.pushToolResultContent(e,t,s,n)}setCanvasState(e,t){this.canvasOrch.setCanvasState(e,t)}wireRelayActionHandler(){this.canvasOrch.wireRelayActionHandler()}isCanvasActive(e){return this.canvasOrch.isCanvasActive(e)}isCanvasActiveForGatewayKey(e){return this.canvasOrch.isCanvasActiveForGatewayKey(e)}broadcastNotification(e,t){this.transport.sendNotification(e,t)}getActiveSessionId(){return this.state.lastActiveSessionId}getSessionIdForToolCall(e){const t=this.pendingToolCallSessionKeys.length>0?this.pendingToolCallSessionKeys[this.pendingToolCallSessionKeys.length-1]:void 0;if(t){const s=this.state.findSessionByKey(t)??this.core.ensureSessionForKey(t);if(s?.sessionId)return e&&this.state.toolCallToSessionMap.set(e,s.sessionId),s.sessionId}if(e){const t=this.state.toolCallToSessionMap.get(e);if(t)return t;const s=this.state.toolCallIdMap.get(e);if(s&&s!==e){const e=this.state.toolCallToSessionMap.get(s);if(e)return e}const n=e.split("_");if(n.length>=3&&"tc"===n[0]){const e=n[1],t=this.state.promptsByRunId.get(e);if(t?.sessionId)return t.sessionId}}this.logger.warn?.(`[acp-server] getSessionIdForToolCall MISS: toolCallId=${e??"(none)"}, sessions=${this.state.sessions.size}, pendingKey=${t??"none"}`)}getSessionIdForActivePrompt(){return this.getSessionIdForToolCall()}setPendingToolCallSessionKey(e){e&&(this.pendingToolCallSessionKeys.push(e),this.pendingToolCallSessionKeys.length>16&&this.pendingToolCallSessionKeys.shift())}preMapToolCallSession(e){const t=this.pendingToolCallSessionKeys.length>0?this.pendingToolCallSessionKeys[this.pendingToolCallSessionKeys.length-1]:void 0;if(!t||!e)return;if(this.state.toolCallToSessionMap.has(e))return;const s=this.state.findSessionByKey(t)??this.core.ensureSessionForKey(t);s?.sessionId&&this.state.toolCallToSessionMap.set(e,s.sessionId)}waitForAgentMapping(){return this.core.waitForAgentMapping()}onceAgentMappingReady(e){this.core.onceAgentMappingReady(e)}flushPendingCanvasLinks(){this.canvasOrch.flushPendingCanvasLinks()}onRelayReconnected(){this.canvasOrch.onRelayReconnected()}getLocalAgentId(){return this.config.gateway.agentId||this.core.getDefaultAgentId()}getDefaultPlatformAgentId(){return this.getDefaultPlatformAgent()?.id}getDefaultPlatformAgent(){const e=this.core.agentMapping;if(e&&0!==e.size)return e.values().next().value??void 0}getPlatformAgentIdForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return this.core.resolvePlatformAgentId(s?.agentId??"")??s?.platformAgentId}getGatewaySessionKeyForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return s?.gatewaySessionKey}getMentionsForToolCall(e){const t=this.getSessionIdForToolCall(e);if(!t)return;const s=this.state.sessions.get(t);return s?.activeMentions}getResourceRenderer(){return this.canvasOrch.resourceRenderer}getDescriptorRegistry(){return this.canvasOrch.descriptorRegistry}getFormBuilder(){return this.canvasOrch.formBuilder}getSchemaRegistry(){return this.canvasOrch.schemaRegistry}registerSkillFormSchemas(e,t){const s=this.canvasOrch.schemaRegistry;s&&import("node:fs/promises").then(async({readFile:n})=>{try{const i=`${t}/skill.json`,a=await n(i,"utf-8"),r=JSON.parse(a);if(r.formSchemas?.length){for(const e of r.formSchemas)s.register({...e,submitLabel:e.submitLabel||"Submit",fields:e.fields});this.logger.info?.(`[acp-server] Registered ${r.formSchemas.length} form schema(s) from skill "${e}"`)}}catch{}})}emitCanvasActionAsUserMessage(e,t){this.canvasOrch.emitCanvasActionAsUserMessage(e,t)}async stop(){this.agentSyncRetryTimer&&(clearTimeout(this.agentSyncRetryTimer),this.agentSyncRetryTimer=null),this.state.destroy(),this.canvasOrch.destroy(),this.gateway&&(this.gateway.removeAllListeners(),this.gateway.stop(),this.gateway=null),this.client&&(this.client.removeAllListeners(),this.client.close(),this.client=null),this.bridgeInstance=null,this.bridgeConsecutiveFailures=0,this.terminalHandler.destroy(),this.terminalMgr.destroy(),this.wss&&(this.wss.removeAllListeners(),this.wss.close(),this.wss=null),this.logger.info?.("[acp-server] Stopped"),this.writeObs({component:"acp-server",domain:"lifecycle",name:"lifecycle.shutdown",severity:"info"})}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const HEARTBEAT_TOKEN="HEARTBEAT_OK";export const SILENT_REPLY_TOKEN="NO_REPLY";function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const silentExactRegexByToken=new Map,silentTrailingRegexByToken=new Map,silentLeadingAttachedRegexByToken=new Map,silentLeadingRegexByToken=new Map;function getSilentExactRegex(e){const t=silentExactRegexByToken.get(e);if(t)return t;const i=new RegExp(`^\\s*${escapeRegExp(e)}\\s*$`,"i");return silentExactRegexByToken.set(e,i),i}function getSilentTrailingRegex(e){const t=silentTrailingRegexByToken.get(e);if(t)return t;const i=new RegExp(`(?:^|\\s+|\\*+)${escapeRegExp(e)}\\s*$`,"i");return silentTrailingRegexByToken.set(e,i),i}function getSilentLeadingAttachedRegex(e){const t=silentLeadingAttachedRegexByToken.get(e);if(t)return t;const i=escapeRegExp(e),n=new RegExp(`^\\s*(?:${i}\\s+)*${i}(?=[\\p{L}\\p{N}])`,"iu");return silentLeadingAttachedRegexByToken.set(e,n),n}function getSilentLeadingRegex(e){const t=silentLeadingRegexByToken.get(e);if(t)return t;const i=new RegExp(`^(?:\\s*${escapeRegExp(e)})+\\s*`,"i");return silentLeadingRegexByToken.set(e,i),i}export function isSilentReplyText(e,t="NO_REPLY"){return!!e&&getSilentExactRegex(t).test(e)}export function isSilentReplyEnvelopeText(e,t="NO_REPLY"){if(!e)return!1;const i=e.trim();if(!(i&&i.startsWith("{")&&i.endsWith("}")&&i.includes(t)))return!1;try{const e=JSON.parse(i);if(!e||"object"!=typeof e||Array.isArray(e))return!1;const n=e,r=Object.keys(n);return 1===r.length&&"action"===r[0]&&"string"==typeof n.action&&n.action.trim()===t}catch{return!1}}export function isSilentReplyPayloadText(e,t="NO_REPLY"){return isSilentReplyText(e,t)||isSilentReplyEnvelopeText(e,t)}export function stripSilentToken(e,t="NO_REPLY"){return e.replace(getSilentTrailingRegex(t),"").trim()}export function stripLeadingSilentToken(e,t="NO_REPLY"){return e.replace(getSilentLeadingRegex(t),"").trim()}export function startsWithSilentToken(e,t="NO_REPLY"){return!!e&&getSilentLeadingAttachedRegex(t).test(e)}export function isSilentReplyPrefixText(e,t="NO_REPLY"){if(!e)return!1;const i=e.trimStart();if(!i)return!1;if(i!==i.toUpperCase())return!1;const n=i.toUpperCase();if(!n)return!1;if(n.length<2)return!1;if(/[^A-Z_]/.test(n))return!1;const r=t.toUpperCase();return!!r.startsWith(n)&&(!!n.includes("_")||"NO_REPLY"===r&&"NO"===n)}const HEARTBEAT_TOKEN_AT_END_RE=new RegExp(`${escapeRegExp("HEARTBEAT_OK")}[^\\w]{0,4}$`);function stripTokenAtEdges(e){let t=e.trim();if(!t)return{text:"",didStrip:!1};if(!t.includes("HEARTBEAT_OK"))return{text:t,didStrip:!1};let i=!1,n=!0;for(;n;){n=!1;const e=t.trim();if(e.startsWith("HEARTBEAT_OK"))t=e.slice(12).trimStart(),i=!0,n=!0;else if(HEARTBEAT_TOKEN_AT_END_RE.test(e)){const r=e.lastIndexOf("HEARTBEAT_OK"),s=e.slice(0,r).trimEnd();t=s?`${s}${e.slice(r+12).trimStart()}`.trimEnd():"",i=!0,n=!0}}return{text:t.replace(/\s+/g," ").trim(),didStrip:i}}function stripHeartbeatMarkup(e){return e.replace(/<[^>]*>/g," ").replace(/ /gi," ").replace(/^[*`~_]+/,"").replace(/[*`~_]+$/,"")}export function stripHeartbeatToken(e,t={}){if(!e)return{shouldSkip:!0,text:"",didStrip:!1};const i=e.trim();if(!i)return{shouldSkip:!0,text:"",didStrip:!1};const n=t.mode??"message",r=t.maxAckChars,s="string"==typeof r?Number(r):r,p=Math.max(0,"number"==typeof s&&Number.isFinite(s)?s:300),o=stripHeartbeatMarkup(i);if(!i.includes("HEARTBEAT_OK")&&!o.includes("HEARTBEAT_OK"))return{shouldSkip:!1,text:i,didStrip:!1};const a=stripTokenAtEdges(i),l=stripTokenAtEdges(o),c=a.didStrip&&a.text?a:l;if(!c.didStrip)return{shouldSkip:!1,text:i,didStrip:!1};if(!c.text)return{shouldSkip:!0,text:"",didStrip:!0};const x=c.text.trim();return"heartbeat"===n&&x.length<=p?{shouldSkip:!0,text:"",didStrip:!0}:{shouldSkip:!1,text:x,didStrip:!0}}export function normalizeStreamingText(e,t={}){if(!e)return{skip:!0};let i=e;if(!t.isHeartbeat&&i.includes("HEARTBEAT_OK")){const e=stripHeartbeatToken(i,{mode:"message"});if(e.didStrip&&t.onHeartbeatStrip?.(),e.shouldSkip)return{skip:!0};i=e.text}return isSilentReplyText(i,"NO_REPLY")||isSilentReplyPrefixText(i,"NO_REPLY")||isSilentReplyPrefixText(i,"HEARTBEAT_OK")?{skip:!0}:(i&&startsWithSilentToken(i,"NO_REPLY")&&(i=stripLeadingSilentToken(i,"NO_REPLY")),i?{skip:!1,text:i}:{skip:!0})}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{describe,it,expect}from"vitest";import{HEARTBEAT_TOKEN,SILENT_REPLY_TOKEN,isSilentReplyText,isSilentReplyEnvelopeText,isSilentReplyPayloadText,isSilentReplyPrefixText,startsWithSilentToken,stripLeadingSilentToken,stripSilentToken,stripHeartbeatToken,normalizeStreamingText}from"./auto-reply-tokens.js";describe("constants",()=>{it("exports upstream token strings verbatim",()=>{expect(HEARTBEAT_TOKEN).toBe("HEARTBEAT_OK"),expect(SILENT_REPLY_TOKEN).toBe("NO_REPLY")})}),describe("isSilentReplyText",()=>{it("matches exact token (with trimming, case-insensitive)",()=>{expect(isSilentReplyText("NO_REPLY")).toBe(!0),expect(isSilentReplyText(" NO_REPLY ")).toBe(!0),expect(isSilentReplyText("no_reply")).toBe(!0)}),it("rejects token with adjacent text",()=>{expect(isSilentReplyText("NO_REPLY please")).toBe(!1),expect(isSilentReplyText("")).toBe(!1),expect(isSilentReplyText(void 0)).toBe(!1)})}),describe("isSilentReplyEnvelopeText",()=>{it('matches canonical JSON envelope `{"action":"NO_REPLY"}`',()=>{expect(isSilentReplyEnvelopeText('{"action":"NO_REPLY"}')).toBe(!0),expect(isSilentReplyEnvelopeText(' { "action": "NO_REPLY" } ')).toBe(!0)}),it("rejects envelopes with extra keys or non-string action",()=>{expect(isSilentReplyEnvelopeText('{"action":"NO_REPLY","extra":1}')).toBe(!1),expect(isSilentReplyEnvelopeText('{"action":123}')).toBe(!1),expect(isSilentReplyEnvelopeText("not json")).toBe(!1),expect(isSilentReplyEnvelopeText("{broken json")).toBe(!1)})}),describe("isSilentReplyPayloadText",()=>{it("accepts both bare token and envelope",()=>{expect(isSilentReplyPayloadText("NO_REPLY")).toBe(!0),expect(isSilentReplyPayloadText('{"action":"NO_REPLY"}')).toBe(!0),expect(isSilentReplyPayloadText("something else")).toBe(!1)})}),describe("isSilentReplyPrefixText — the critical gate for streamed prefixes",()=>{it("flags NO_REPLY prefix containing `_`",()=>{expect(isSilentReplyPrefixText("NO_")).toBe(!0),expect(isSilentReplyPrefixText("NO_R")).toBe(!0),expect(isSilentReplyPrefixText("NO_REP")).toBe(!0),expect(isSilentReplyPrefixText("NO_REPLY")).toBe(!0)}),it("flags bare `NO` for NO_REPLY (upstream legacy)",()=>{expect(isSilentReplyPrefixText("NO")).toBe(!0)}),it("flags HEARTBEAT_OK prefixes with explicit token arg",()=>{expect(isSilentReplyPrefixText("HEARTBEAT_",HEARTBEAT_TOKEN)).toBe(!0),expect(isSilentReplyPrefixText("HEARTBEAT_O",HEARTBEAT_TOKEN)).toBe(!0)}),it("does NOT flag HEARTBEAT prefixes lacking `_` (upstream trade-off)",()=>{expect(isSilentReplyPrefixText("HEART",HEARTBEAT_TOKEN)).toBe(!1),expect(isSilentReplyPrefixText("HEARTBEAT",HEARTBEAT_TOKEN)).toBe(!1)}),it("requires strict uppercase A-Z_",()=>{expect(isSilentReplyPrefixText("heartbeat_",HEARTBEAT_TOKEN)).toBe(!1),expect(isSilentReplyPrefixText("HEART-BEAT",HEARTBEAT_TOKEN)).toBe(!1),expect(isSilentReplyPrefixText("HEART BEAT",HEARTBEAT_TOKEN)).toBe(!1),expect(isSilentReplyPrefixText("HEART123",HEARTBEAT_TOKEN)).toBe(!1)}),it("requires length >= 2",()=>{expect(isSilentReplyPrefixText("H",HEARTBEAT_TOKEN)).toBe(!1),expect(isSilentReplyPrefixText("N")).toBe(!1)}),it("tolerates leading whitespace, rejects empty",()=>{expect(isSilentReplyPrefixText(" NO_","NO_REPLY")).toBe(!0),expect(isSilentReplyPrefixText("","NO_REPLY")).toBe(!1),expect(isSilentReplyPrefixText(void 0)).toBe(!1)})}),describe("startsWithSilentToken",()=>{it("detects token glued directly to visible content",()=>{expect(startsWithSilentToken("NO_REPLYhello")).toBe(!0),expect(startsWithSilentToken("NO_REPLY NO_REPLYthing")).toBe(!0)}),it("does NOT match when token is space-separated (that's stripSilentToken's job)",()=>{expect(startsWithSilentToken("NO_REPLY hello")).toBe(!1)}),it("rejects unrelated text",()=>{expect(startsWithSilentToken("hello NO_REPLY")).toBe(!1),expect(startsWithSilentToken("")).toBe(!1)})}),describe("stripSilentToken",()=>{it("removes a trailing silent token",()=>{expect(stripSilentToken("see ya NO_REPLY")).toBe("see ya")}),it("leaves embedded tokens alone",()=>{expect(stripSilentToken("NO_REPLY is our sentinel")).toBe("NO_REPLY is our sentinel")})}),describe("stripLeadingSilentToken",()=>{it("strips one or more leading tokens with optional space",()=>{expect(stripLeadingSilentToken("NO_REPLY hello")).toBe("hello"),expect(stripLeadingSilentToken("NO_REPLY NO_REPLY hello")).toBe("hello")}),it("leaves content untouched when no leading token",()=>{expect(stripLeadingSilentToken("hello NO_REPLY")).toBe("hello NO_REPLY")})}),describe("stripHeartbeatToken — OpenClaw 1:1 behaviour",()=>{it("returns shouldSkip when input is empty or whitespace",()=>{expect(stripHeartbeatToken("")).toEqual({shouldSkip:!0,text:"",didStrip:!1}),expect(stripHeartbeatToken(" ")).toEqual({shouldSkip:!0,text:"",didStrip:!1})}),it("passes through text that does not contain the token",()=>{const e=stripHeartbeatToken("hello world");expect(e.didStrip).toBe(!1),expect(e.shouldSkip).toBe(!1),expect(e.text).toBe("hello world")}),it("skips when text is exactly the token",()=>{const e=stripHeartbeatToken("HEARTBEAT_OK");expect(e).toEqual({shouldSkip:!0,text:"",didStrip:!0})}),it("strips token with trailing punctuation; rest may be a bare punct residue",()=>{expect(stripHeartbeatToken("HEARTBEAT_OK.").didStrip).toBe(!0),expect(stripHeartbeatToken("HEARTBEAT_OK!!!").didStrip).toBe(!0),expect(stripHeartbeatToken("HEARTBEAT_OK ✅").didStrip).toBe(!0)}),it("strips token wrapped in markdown markup via the normalised-markup fallback",()=>{expect(stripHeartbeatToken("**HEARTBEAT_OK**").didStrip).toBe(!0),expect(stripHeartbeatToken("`HEARTBEAT_OK`").didStrip).toBe(!0)}),it("fully skips when residue is empty (bare token with no padding)",()=>{expect(stripHeartbeatToken("HEARTBEAT_OK").shouldSkip).toBe(!0),expect(stripHeartbeatToken(" HEARTBEAT_OK ").shouldSkip).toBe(!0)}),it("keeps leading token + content, reporting didStrip",()=>{const e=stripHeartbeatToken("HEARTBEAT_OK the rest of my reply");expect(e.didStrip).toBe(!0),expect(e.shouldSkip).toBe(!1),expect(e.text).toBe("the rest of my reply")}),it("keeps trailing content when token is at the end but with content before",()=>{const e=stripHeartbeatToken("important note HEARTBEAT_OK");expect(e.didStrip).toBe(!0),expect(e.shouldSkip).toBe(!1),expect(e.text).toBe("important note")}),it("collapses internal whitespace when stripping",()=>{const e=stripHeartbeatToken("HEARTBEAT_OK\n\n more\n\ntext");expect(e.didStrip).toBe(!0),expect(e.text).toBe("more text")}),it("heartbeat-mode skips short trailing chatter under maxAckChars",()=>{const e=stripHeartbeatToken("HEARTBEAT_OK short tail",{mode:"heartbeat"});expect(e.shouldSkip).toBe(!0),expect(e.text).toBe(""),expect(e.didStrip).toBe(!0)}),it("heartbeat-mode keeps long trailing content beyond maxAckChars",()=>{const e="x".repeat(400),t=stripHeartbeatToken(`HEARTBEAT_OK ${e}`,{mode:"heartbeat",maxAckChars:300});expect(t.shouldSkip).toBe(!1),expect(t.text).toBe(e)})}),describe("normalizeStreamingText — the full streaming pipeline",()=>{it("skips empty input",()=>{expect(normalizeStreamingText("")).toEqual({skip:!0}),expect(normalizeStreamingText(void 0)).toEqual({skip:!0})}),it("skips the full heartbeat token",()=>{expect(normalizeStreamingText("HEARTBEAT_OK")).toEqual({skip:!0})}),it("skips any HEARTBEAT_OK prefix (ghost-bubble protection)",()=>{expect(normalizeStreamingText("HEARTBEAT_")).toEqual({skip:!0}),expect(normalizeStreamingText("HEARTBEAT_O")).toEqual({skip:!0})}),it("skips NO_REPLY + its uppercase prefixes",()=>{expect(normalizeStreamingText("NO_REPLY")).toEqual({skip:!0}),expect(normalizeStreamingText("NO_")).toEqual({skip:!0}),expect(normalizeStreamingText("NO")).toEqual({skip:!0})}),it("strips leading glued silent tokens and keeps remainder",()=>{const e=normalizeStreamingText("NO_REPLYhello world");expect(e.skip).toBe(!1),expect(e.text).toBe("hello world")}),it("passes real content through untouched",()=>{expect(normalizeStreamingText("Hello user!")).toEqual({skip:!1,text:"Hello user!"})}),it("does NOT skip when isHeartbeat flag is set (heartbeat run consumes its own ack)",()=>{const e=normalizeStreamingText("HEARTBEAT_OK extra",{isHeartbeat:!0});expect(e.skip).toBe(!1),expect(e.text).toBe("HEARTBEAT_OK extra")}),it("invokes onHeartbeatStrip callback the first time",()=>{const e=[];normalizeStreamingText("HEARTBEAT_OK hi",{onHeartbeatStrip:()=>e.push(1)}),expect(e).toEqual([1])})});
|
package/dist/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdirSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,join}from"node:path";function trimStr(e){if("string"==typeof e){const r=e.trim();return r.length>0?r:void 0}}function readInt(e){if("number"==typeof e&&Number.isFinite(e))return Math.trunc(e);if("string"==typeof e){const r=parseInt(e,10);return Number.isFinite(r)?r:void 0}}function readBool(e){return"boolean"==typeof e?e:"true"===e||"false"!==e&&void 0}function pick(e,r){for(const r of e)if(void 0!==r.value)return{value:r.value,source:r.source};return r}const CURRENT_CONFIG_PROTOCOL=1;function shouldTrustOperationalConfig(e){const r=e._generator;if(!r)return!1;return("number"==typeof r.configProtocol?r.configProtocol:0)>=1}const DEFAULT_GATEWAY_URL="ws://127.0.0.1:18789",DEFAULT_LOG_DIR=join(process.env.OPENCLAW_HOME||join(homedir(),".openclaw"),"beeos-logs"),DEFAULT_OPENCLAW_CONFIG_PATH=join(homedir(),".openclaw","openclaw.json");export function resolveConfigWithMeta(e){const r=e.pluginConfig??{},o=e.openclawConfig??{},a=e.openclawConfigPath??DEFAULT_OPENCLAW_CONFIG_PATH,u=shouldTrustOperationalConfig(r),l=pick([{source:"pluginConfig",value:trimStr(r.agentGatewayUrl)},{source:"pluginConfig",value:trimStr(r.platformUrl)},{source:"env",value:trimStr(process.env.AGENT_GATEWAY_URL)}],{source:"default",value:""}),n=r.gateway??{},
|
|
1
|
+
import{mkdirSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,join}from"node:path";function trimStr(e){if("string"==typeof e){const r=e.trim();return r.length>0?r:void 0}}function readInt(e){if("number"==typeof e&&Number.isFinite(e))return Math.trunc(e);if("string"==typeof e){const r=parseInt(e,10);return Number.isFinite(r)?r:void 0}}function readBool(e){return"boolean"==typeof e?e:"true"===e||"false"!==e&&void 0}function pick(e,r){for(const r of e)if(void 0!==r.value)return{value:r.value,source:r.source};return r}const CURRENT_CONFIG_PROTOCOL=1;function shouldTrustOperationalConfig(e){const r=e._generator;if(!r)return!1;return("number"==typeof r.configProtocol?r.configProtocol:0)>=1}const DEFAULT_GATEWAY_URL="ws://127.0.0.1:18789",DEFAULT_LOG_DIR=join(process.env.OPENCLAW_HOME||join(homedir(),".openclaw"),"beeos-logs"),DEFAULT_OPENCLAW_CONFIG_PATH=join(homedir(),".openclaw","openclaw.json");export function resolveConfigWithMeta(e){const r=e.pluginConfig??{},o=e.openclawConfig??{},a=e.openclawConfigPath??DEFAULT_OPENCLAW_CONFIG_PATH,u=shouldTrustOperationalConfig(r),l=pick([{source:"pluginConfig",value:trimStr(r.agentGatewayUrl)},{source:"pluginConfig",value:trimStr(r.platformUrl)},{source:"env",value:trimStr(process.env.AGENT_GATEWAY_URL)}],{source:"default",value:""}),n=r.gateway??{},t=(o.gateway??{}).auth??{},s=pick([...u?[{source:"pluginConfig",value:trimStr(n.url)}]:[],{source:"env",value:trimStr(process.env.BEEOS_GATEWAY_URL)}],{source:"default",value:DEFAULT_GATEWAY_URL}),i=pick([{source:"openclawConfig",value:trimStr(t.token)},{source:"pluginConfig",value:trimStr(n.token)},{source:"env",value:trimStr(process.env.BEEOS_GATEWAY_TOKEN)}],{source:"default",value:""}),c=pick([...u?[{source:"pluginConfig",value:readInt(n.protocol)}]:[]],{source:"default",value:3}),v=pick([...u?[{source:"pluginConfig",value:trimStr(n.clientId)}]:[]],{source:"default",value:`beeos-claw-${process.pid}`}),p=pick([...u?[{source:"pluginConfig",value:trimStr(n.agentId)}]:[]],{source:"default",value:""}),d=r.bridge??{},g=pick([{source:"pluginConfig",value:trimStr(r.keyFile)},{source:"pluginConfig",value:trimStr(d.keyFile)},{source:"env",value:trimStr(process.env.BRIDGE_KEY_FILE)}],{source:"default",value:""}),f=pick([{source:"env",value:trimStr(process.env.BRIDGE_URL)}],{source:"default",value:""}),m=pick([...u?[{source:"pluginConfig",value:trimStr(d.service)}]:[],{source:"env",value:trimStr(process.env.BRIDGE_SERVICE)}],{source:"default",value:"acp"}),E=d.shell??{},_=pick([...u?[{source:"pluginConfig",value:readBool(E.enabled)}]:[],{source:"env",value:readBool(process.env.BEEOS_SHELL_ENABLED)}],{source:"default",value:!0}),S=r.retry??{},A=pick([...u?[{source:"pluginConfig",value:readInt(S.baseMs)}]:[]],{source:"default",value:1e3}),C=pick([...u?[{source:"pluginConfig",value:readInt(S.maxMs)}]:[]],{source:"default",value:6e5}),I=pick([...u?[{source:"pluginConfig",value:readInt(S.maxAttempts)}]:[]],{source:"default",value:0}),O=r.log??{},T=pick([...u?[{source:"pluginConfig",value:readBool(O.enabled)}]:[],{source:"env",value:readBool(process.env.BEEOS_LOG_ENABLED)}],{source:"default",value:!0}),M=pick([...u?[{source:"pluginConfig",value:readBool(O.verbose)}]:[]],{source:"default",value:!1}),R=pick([{source:"pluginConfig",value:trimStr(O.dir)}],{source:"default",value:DEFAULT_LOG_DIR}),w=pick([...u?[{source:"pluginConfig",value:readInt(d.promptTimeoutMs)}]:[],{source:"env",value:readInt(process.env.BEEOS_PROMPT_TIMEOUT_MS)}],{source:"default",value:6e5}),k=pick([...u?[{source:"pluginConfig",value:readInt(r.terminalWsPort)}]:[],{source:"env",value:readInt(process.env.BEEOS_TERMINAL_WS_PORT)}],{source:"default",value:18801}),y=(u?trimStr(r.terminalWsAllowedOrigins):void 0)??trimStr(process.env.BEEOS_TERMINAL_WS_ALLOWED_ORIGINS),B=y?y.split(",").map(e=>e.trim()).filter(Boolean):void 0,L=pick([{source:y?"pluginConfig":"default",value:B?.length?B:void 0}],{source:"default",value:["localhost","127.0.0.1","::1"]}),b=pick([...u?[{source:"pluginConfig",value:readInt(r.streamIdleTimeoutMs)}]:[],{source:"env",value:readInt(process.env.BEEOS_STREAM_IDLE_TIMEOUT_MS)}],{source:"default",value:15e3}),h=pick([...u?[{source:"pluginConfig",value:readInt(r.streamStaleTimeoutMs)}]:[],{source:"env",value:readInt(process.env.BEEOS_STREAM_STALE_TIMEOUT_MS)}],{source:"default",value:6e5}),G=pick([...u?[{source:"pluginConfig",value:readInt(r.cronSignalWindowMs)}]:[],{source:"env",value:readInt(process.env.BEEOS_CRON_SIGNAL_WINDOW_MS)}],{source:"default",value:6e4}),N=pick([{source:"env",value:trimStr(process.env.CANVAS_RELAY_URL)},{source:"pluginConfig",value:trimStr(r.canvasRelayUrl)}],{source:"default",value:"https://canvas-relay.beeos.ai"}),U=pick([...u?[{source:"pluginConfig",value:readBool(r.canvasEnabled)}]:[],{source:"env",value:readBool(process.env.BEEOS_CANVAS_ENABLED)}],{source:"default",value:!0}),P=pick([...u?[{source:"pluginConfig",value:readBool(r.openclawCanvasCompat)}]:[],{source:"env",value:readBool(process.env.BEEOS_OPENCLAW_CANVAS_COMPAT)}],{source:"default",value:!1}),W=r.messageBus??{},F=pick([{source:"pluginConfig",value:trimStr(W.serviceUrl)},{source:"env",value:trimStr(process.env.MESSAGE_SERVICE_URL)}],{source:"default",value:""}),D=pick([{source:"pluginConfig",value:trimStr(W.url)},{source:"env",value:trimStr(process.env.CENTRIFUGO_URL)}],{source:"default",value:""}),x=pick([{source:"pluginConfig",value:trimStr(W.principalId)},{source:"env",value:trimStr(process.env.BEEOS_PRINCIPAL_ID)}],{source:"default",value:""}),H=pick([{source:"pluginConfig",value:readBool(W.a2aEnabled)},{source:"env",value:readBool(process.env.BEEOS_A2A_ENABLED)}],{source:"default",value:!0}),Y=pick([{source:"pluginConfig",value:readBool(W.enabled)},{source:"env",value:readBool(process.env.BEEOS_MESSAGE_BUS_ENABLED)}],{source:"default",value:!(!F.value&&!l.value)}),j={agentGatewayUrl:l.value.replace(/\/+$/,""),keyFile:g.value,bridge:{url:f.value,service:m.value,mode:trimStr(d.mode),shell:{enabled:_.value},promptTimeoutMs:w.value},gateway:{url:s.value,token:i.value,protocol:c.value,clientId:v.value,agentId:p.value},retry:{baseMs:Math.max(0,A.value),maxMs:Math.max(0,C.value),maxAttempts:Math.max(0,I.value)},log:{enabled:T.value,verbose:M.value,dir:R.value},promptTimeoutMs:w.value,terminalWsPort:k.value,terminalWsAllowedOrigins:L.value,streamIdleTimeoutMs:Math.max(0,b.value),streamStaleTimeoutMs:Math.max(0,h.value),cronSignalWindowMs:Math.max(0,G.value),canvasRelayUrl:N.value.replace(/\/+$/,""),canvasEnabled:U.value,openclawCanvasCompat:P.value,messageBus:{enabled:Y.value,serviceUrl:F.value,url:D.value,principalId:x.value,a2aEnabled:H.value}},$={agentGatewayUrl:l.source,keyFile:g.source,bridge:{url:f.source,service:m.source,shell:{enabled:_.source}},gateway:{url:s.source,token:i.source,protocol:c.source,clientId:v.source,agentId:p.source},retry:{baseMs:A.source,maxMs:C.source,maxAttempts:I.source},log:{enabled:T.source,verbose:M.source,dir:R.source},promptTimeoutMs:w.source,terminalWsPort:k.source,terminalWsAllowedOrigins:L.source,streamIdleTimeoutMs:b.source,streamStaleTimeoutMs:h.source,cronSignalWindowMs:G.source,canvasRelayUrl:N.source,canvasEnabled:U.source,openclawCanvasCompat:P.source,messageBus:{enabled:Y.source,serviceUrl:F.source,url:D.source,principalId:x.source,a2aEnabled:H.source}},V=[];return j.agentGatewayUrl||V.push({code:"CONFIG_AGENT_GATEWAY_URL_MISSING",severity:"error",message:"agentGatewayUrl is required for file uploads and Agent Gateway callbacks",nextSteps:[`Set plugins.entries.beeos-claw.config.agentGatewayUrl in ${a}`,"Or set the AGENT_GATEWAY_URL environment variable"]}),j.gateway.token||V.push({code:"CONFIG_GATEWAY_TOKEN_MISSING",severity:"warn",message:"gateway.token is empty; Gateway auth may fail if authentication is enabled",nextSteps:[`Set gateway.auth.token in ${a}`,`Or set plugins.entries.beeos-claw.config.gateway.token in ${a}`]}),{config:j,sources:$,validation:V,openclawConfigPath:a}}export function resolveConfig(e){const{config:r,validation:o}=resolveConfigWithMeta({pluginConfig:e}),a=o.find(e=>"error"===e.severity);if(a)throw new Error(`[beeos-claw] ${a.message}`);return r}const MIRROR_PATH=join(process.env.OPENCLAW_HOME||join(homedir(),".openclaw"),"beeos-claw","openclaw.json");export function mirrorOpenClawConfig(e){if(!e||"object"!=typeof e||Array.isArray(e))return{copied:!1,destinationPath:MIRROR_PATH,reason:"config_invalid"};try{return mkdirSync(dirname(MIRROR_PATH),{recursive:!0}),writeFileSync(MIRROR_PATH,JSON.stringify(e,null,2)+"\n",{encoding:"utf8",mode:384}),{copied:!0,destinationPath:MIRROR_PATH}}catch(e){return{copied:!1,destinationPath:MIRROR_PATH,reason:e instanceof Error?e.message:"write_failed"}}}
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID}from"node:crypto";import{resolveConfigWithMeta,mirrorOpenClawConfig}from"./config.js";import{MessageSDK}from"./messaging/message-sdk.js";import{registerA2ATools,TaskHandleRegistry}from"./a2a/tools.js";import{BEEOS_UPLOAD_TOOL_NAME,BEEOS_UPLOAD_TOOL_SCHEMA,BEEOS_UPLOAD_TOOL_DESCRIPTION,executeUpload}from"./upload/tool.js";import{writeUploadToolResult,cleanupUploadToolResultCache}from"./upload/result-cache.js";import{handleFileStage}from"./upload/file-stage.js";import{ACPServer}from"./acp-server.js";import{createObsEventWriter}from"./observability.js";import{resolvePluginVersion}from"./plugin-version.js";import{createTerminalWebSocketService}from"./terminal/websocket.js";import{TerminalManager}from"./terminal/session-manager.js";import{loadAgentKeyPair,agentFetch}from"./agent-auth.js";import{readDiscoveryCache,writeDiscoveryCache}from"./discovery-cache.js";import{discoverBridgeFromGW}from"./bridge-discovery.js";import{setUploadDeps}from"./upload/upload-file.js";import{registerLocalFileExtractor}from"./upload/local-file-extractors.js";import{browserScreenshotExtractor}from"./browser/screenshot-extractor.js";import{CanvasStateManager}from"./canvas/state.js";import{CanvasRelayClient}from"./canvas/relay-client.js";import{RENDER_UI_TOOL_NAME,RENDER_UI_TOOL_DESCRIPTION,RENDER_UI_TOOL_SCHEMA,CLOSE_UI_TOOL_NAME,CLOSE_UI_TOOL_DESCRIPTION,CLOSE_UI_TOOL_SCHEMA,createRenderUiHandler,createCloseUiHandler,CANVAS_SYSTEM_PROMPT}from"./canvas/tools.js";import{FormSchemaRegistry}from"./surface/form-schema-registry.js";import{CRON_CREATE_SCHEMA,CRON_UPDATE_SCHEMA}from"./surface/cron-schemas.js";import{RENDER_FORM_TOOL_NAME,RENDER_FORM_TOOL_SCHEMA,buildRenderFormDescription,createRenderFormHandler}from"./surface/render-form-tool.js";import{ResourceDescriptorRegistry}from"./surface/resource-descriptor-registry.js";import{CRON_RESOURCE}from"./surface/cron-resource.js";import{generateActionTools}from"./surface/action-tool-generator.js";import{buildThirdPartyChannelSet,isThirdPartyChannel}from"./channel-detection.js";const PLUGIN_VERSION=resolvePluginVersion();let agentKeys=null,sharedCanvasState=null,_initializing=!1,_pluginRegisteredAt=0;function initializePlugin(e){let o,r;try{o=e.runtime?.config?.loadConfig?.()}catch{}try{r=resolveConfigWithMeta({pluginConfig:e.pluginConfig??{},openclawConfig:o})}catch(o){return e.logger.error?.("[beeos-claw] Failed to resolve config:",o),null}const a=r.config,t=buildThirdPartyChannelSet(o);t.size>0&&e.logger.info?.(`[beeos-claw] Third-party channels detected: ${[...t].join(", ")}`);const s=a.log.enabled?createObsEventWriter({dir:a.log.dir,redaction:{gatewayToken:a.gateway.token},logger:e.logger}):()=>{};s({component:"plugin",domain:"lifecycle",name:"lifecycle.startup",severity:"info",payload:{pluginVersion:PLUGIN_VERSION,pid:process.pid,nodeVersion:process.version,cwd:process.cwd()}}),s({component:"plugin",domain:"config",name:"config.resolved",severity:"info",payload:{config:a,sources:r.sources,openclawConfigPath:r.openclawConfigPath}});for(const o of r.validation)s({component:"plugin",domain:"config",name:"config.validation",severity:o.severity,summary:o.message,error:{code:o.code,message:o.message,nextSteps:o.nextSteps}}),"error"===o.severity?e.logger.error?.(`[beeos-claw] ${o.message}`):e.logger.warn?.(`[beeos-claw] ${o.message}`);if(r.validation.some(e=>"error"===e.severity)&&e.logger.error?.("[beeos-claw] Plugin has configuration errors — some features may not work."),a.keyFile)try{agentKeys=loadAgentKeyPair(a.keyFile);const o=Buffer.from(agentKeys.publicKey).toString("base64");e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (publicKey: ${o})`)}catch(o){e.logger.warn?.(`[beeos-claw] Failed to load agent key pair: ${o}`),e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (no key pair — signed requests disabled)`)}else e.logger.info?.(`[beeos-claw] v${PLUGIN_VERSION} registering (no keyFile configured)`);return agentKeys&&a.agentGatewayUrl&&(setUploadDeps({gatewayUrl:a.agentGatewayUrl,keys:agentKeys,logger:e.logger}),registerLocalFileExtractor(browserScreenshotExtractor),e.logger.info?.("[beeos-claw] Upload deps + browser screenshot extractor registered")),{cfg:a,writeObs:s,thirdPartyChannels:t,openclawConfig:o}}function registerUploadTools(e,o,r){const{cfg:a,writeObs:t}=o;cleanupUploadToolResultCache().catch(o=>{e.logger.warn?.(`[beeos_upload_file] cache cleanup failed on startup: ${String(o)}`)}),e.registerTool({name:BEEOS_UPLOAD_TOOL_NAME,description:BEEOS_UPLOAD_TOOL_DESCRIPTION,parameters:BEEOS_UPLOAD_TOOL_SCHEMA,async execute(o,r,s){e.logger.debug?.(`[beeos_upload_file] toolCallId=${o} params=${JSON.stringify(r)}`);const n=await executeUpload(r,a,agentKeys,s);return e.logger.debug?.(`[beeos_upload_file] toolCallId=${o} ok=${n.ok}`),t({component:"upload-tool",domain:"tool",name:n.ok?"upload.success":"upload.failure",severity:n.ok?"info":"warn",payload:{toolCallId:o,ok:n.ok,fileCount:n.files?.length??0,error:n.error}}),(async r=>{try{await writeUploadToolResult(o,BEEOS_UPLOAD_TOOL_NAME,r),await cleanupUploadToolResultCache()}catch(r){e.logger.warn?.(`[beeos_upload_file] persist cache failed toolCallId=${o}: ${String(r)}`)}return r})(n)}}),e.registerHttpRoute({path:"/beeos/files/stage",auth:"gateway",async handler(e,r){await handleFileStage(e,r,o.cfg)}})}function registerServices(e,o,r){const{cfg:a,writeObs:t,thirdPartyChannels:s}=o,n=agentKeys?(e,o)=>agentFetch(e,agentKeys,o):void 0,i=agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):void 0,l=new ACPServer(a,e.logger,t,n,i,s);r.current=l,e.registerService({id:"beeos-acp",async start(){const o=Date.now(),r=_pluginRegisteredAt?o-_pluginRegisteredAt:-1;if(e.logger.info?.(`[beeos-claw] beeos-acp service start() begin, sincePluginRegister=${r}ms, bridge.url=${a.bridge.url||"(empty)"}`),!a.bridge.url&&a.agentGatewayUrl&&n){const o=Date.now(),r=await discoverBridgeFromGW(a.agentGatewayUrl,n);if(e.logger.info?.(`[beeos-claw] bridge discovery took ${Date.now()-o}ms result=${r?.url??"null"}`),r)a.bridge.url=r.url,writeDiscoveryCache({bridge:{url:r.url,discoveredAt:Date.now()}}),e.logger.info?.(`[beeos-claw] Bridge URL discovered from Agent Gateway: ${r.url}`);else{const o=readDiscoveryCache();o?.bridge?.url?(a.bridge.url=o.bridge.url,e.logger.info?.(`[beeos-claw] Bridge URL from cache (GW unreachable): ${o.bridge.url}`)):e.logger.debug?.("[beeos-claw] Bridge URL not available (no GW, no cache) — bridge disabled")}}await l.start(a.bridge.url||void 0),e.logger.info?.(`[beeos-claw] ACP Server started (total service start: ${Date.now()-o}ms)`)},async stop(){await l.stop(),e.logger.info?.("[beeos-claw] ACP Server stopped")}});const g=new TaskHandleRegistry;let c=null;const{enabled:d,url:p,principalId:f,a2aEnabled:y}=a.messageBus;let u;if(a.agentGatewayUrl&&agentKeys){const e=a.agentGatewayUrl,o=agentKeys;u=async r=>{const a=await agentFetch(`${e}/api/v1/messaging/token`,o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({principal_id:r})});if(!a.ok){const e=await a.text().catch(()=>"");throw new Error(`Gateway messaging token returned ${a.status}: ${e}`)}return a.json()}}if(d&&(u||a.messageBus.serviceUrl)){c=new MessageSDK({serviceUrl:u?void 0:a.messageBus.serviceUrl,centrifugoUrl:p},e.logger);const o=f,r=async o=>{c.onceConnected(()=>{l.setMessageSdk(c,o),e.logger.info?.("[beeos-claw] Message SDK connected (principalId=%s, via=%s)",o,u?"gateway":"direct")}),await c.connect(o,{centrifugoUrl:p,tokenProvider:u})};e.registerService({id:"beeos-message-bus",async start(){let 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 r(a):l?(e.logger.info?.("[beeos-claw] Message bus deferred: waiting for late agent sync..."),l.onceAgentMappingReady(()=>{const o=l.getDefaultPlatformAgentId();o?r(o).catch(o=>{e.logger.error?.("[beeos-claw] Deferred message bus connect failed:",o)}):e.logger.warn?.("[beeos-claw] Agent mapping ready but no principalId, message bus stays disabled")})):e.logger.warn?.("[beeos-claw] No principalId resolved, message bus disabled")},async stop(){await(c?.disconnect()),e.logger.info?.("[beeos-claw] Message SDK disconnected")}}),c.onMessage("agent_request",async o=>{const r=o.payload,a=o.metadata,t="string"==typeof r?.message?r.message:"",s=Array.isArray(r?.files)?r.files:void 0,n=o.channel_id??a?.channel_id??("string"==typeof r?.channel_id?r.channel_id:void 0),i=n&&n.length>0?n:void 0;if(!t)return;const g=("string"==typeof r?.context_id&&r.context_id.length>0?r.context_id:void 0)??(a?.context_id&&a.context_id.length>0?a.context_id:void 0);let c="string"==typeof r?.session_key?r.session_key:void 0;if(!c){const e="string"==typeof r?.channel?r.channel:"a2a";c=`agent:${l.getLocalAgentId()}:${e}:${g?`ctx-${g}`:randomUUID()}`}e.logger.debug?.("[beeos-claw] agent_request received (sessionKey=%s, contextId=%s)",c,g??"-"),await l.agentSend(t,s,c,void 0,i)})}else d?e.logger.warn?.("[beeos-claw] Message bus enabled but MESSAGE_SERVICE_URL not set — disabled"):e.logger.info?.("[beeos-claw] Message bus disabled (enabled=%s)",d);if(!1!==y&&a.agentGatewayUrl){const o=e=>l.getGatewaySessionKeyForToolCall(e),r=e=>l.getMentionsForToolCall(e),t=(e,o)=>{l.broadcastNotification(e,o)};registerA2ATools(e,{agentGatewayUrl:a.agentGatewayUrl,agentKeys:agentKeys,logger:e.logger},g,o,r,t),e.logger.info?.("[beeos-claw] A2A tools registered (beeos_discover_agents, beeos_call_agent) via REST")}if(a.canvasEnabled){sharedCanvasState||(sharedCanvasState=new CanvasStateManager);const o=sharedCanvasState;if(a.agentGatewayUrl&&agentKeys){let r;o.setLogger(e.logger);{const e=a.agentGatewayUrl,o=agentKeys;r=async()=>{const r=await agentFetch(`${e}/api/v1/canvas/token`,o,{method:"POST"});if(!r.ok){const e=await r.text().catch(()=>"");throw new Error(`Canvas token returned ${r.status}: ${e}`)}return r.json()}}e.registerService({id:"beeos-canvas-relay",async start(){try{await l.waitForAgentMapping();const t=l.getDefaultPlatformAgent();if(!t?.id)return void e.logger.info?.("[beeos-claw] Canvas Relay skipped: no agentId after sync");const s=new CanvasRelayClient({canvasRelayUrl:a.canvasRelayUrl,agentKeys:agentKeys,agentId:t.id,displayName:t.displayName,avatarUrl:t.avatarUrl,tokenProvider:r,onReconnect:()=>l.onRelayReconnected(),logger:e.logger});s.connect(),o.setRelayClient(s),o.setAgentId(t.id),l.wireRelayActionHandler(),l.flushPendingCanvasLinks(),e.logger.info?.(`[beeos-claw] Canvas Relay multiplexed client connected (agentId=${t.id}, name=${t.name??"none"})`)}catch(o){e.logger.warn?.(`[beeos-claw] Failed to start Canvas Relay client: ${o}`)}},stop(){o.getRelayClient()?.disconnect()}}),e.logger.info?.("[beeos-claw] Canvas Relay configured")}else e.logger.warn?.("[beeos-claw] Canvas Relay unavailable: agentGatewayUrl or agentKeys missing");const r={stateManager:o,logger:e.logger,writeObs:e=>t(e),isCanvasActive:e=>!e||l.isCanvasActiveForGatewayKey(e),getActiveSessionId:e=>l.getSessionIdForToolCall(e),getPlatformAgentId:e=>l.getPlatformAgentIdForToolCall(e),getGatewaySessionKey:e=>l.getGatewaySessionKeyForToolCall(e),waitForAgentSync:()=>l.waitForAgentMapping()},n=new FormSchemaRegistry;n.register(CRON_CREATE_SCHEMA),n.register(CRON_UPDATE_SCHEMA);const i=new ResourceDescriptorRegistry;i.register(CRON_RESOURCE);const g=e=>async(o,r,a)=>(l.preMapToolCallSession(o),e(o,r));e.registerTool({name:RENDER_UI_TOOL_NAME,description:RENDER_UI_TOOL_DESCRIPTION,parameters:RENDER_UI_TOOL_SCHEMA,execute:g(createRenderUiHandler(r))}),e.registerTool({name:CLOSE_UI_TOOL_NAME,description:CLOSE_UI_TOOL_DESCRIPTION,parameters:CLOSE_UI_TOOL_SCHEMA,execute:g(createCloseUiHandler(r))}),l.setCanvasState(o,{schemaRegistry:n,descriptorRegistry:i});const c=l.getFormBuilder();c&&e.registerTool({name:RENDER_FORM_TOOL_NAME,description:buildRenderFormDescription(n),parameters:RENDER_FORM_TOOL_SCHEMA,execute:g(createRenderFormHandler({registry:n,builder:c,logger:e.logger}))});const d=l.getResourceRenderer();if(d){generateActionTools(i,e,async(e,o)=>l.gatewayRequest(e,o),d,e.logger)}const p='\n\nTool selection guidance:\n- browser tool: Use when the user wants to OPEN, VISIT, NAVIGATE to a webpage, take SCREENSHOTS, interact with elements (click, type), or visually inspect pages.\n- beeos_search: Use ONLY for text-based information retrieval (fact-finding, research queries). Never for page interaction or screenshots.\n- beeos_fetch: Use ONLY to extract article text from a known URL. Never for visual content or screenshots.\nWhen the user says "open", "visit", "go to", "screenshot", or mentions seeing/viewing a webpage, ALWAYS prefer the browser tool.',f=new Set([RENDER_UI_TOOL_NAME,CLOSE_UI_TOOL_NAME,RENDER_FORM_TOOL_NAME]),y=256,u=new Map;if("function"==typeof e.on){try{e.on("before_prompt_build",(e,o)=>{if(o?.sessionKey){if(u.size>=y&&!u.has(o.sessionKey)){const e=u.keys().next().value;void 0!==e&&u.delete(e)}u.set(o.sessionKey,o.channelId)}if(isThirdPartyChannel(s,{sessionKey:o?.sessionKey,channelId:o?.channelId}))return;if(!o?.sessionKey)return{appendSystemContext:p};return l.isCanvasActiveForGatewayKey(o.sessionKey)?{appendSystemContext:CANVAS_SYSTEM_PROMPT+p}:{appendSystemContext:"Canvas is closed by user. Do NOT use render_ui, close_ui, or render_form. Respond with plain text only."+p}}),e.logger.debug?.("[beeos-claw] Canvas system prompt hook registered: before_prompt_build")}catch{e.logger.debug?.("[beeos-claw] before_prompt_build hook not supported")}try{e.on("before_tool_call",(e,o)=>{if(o?.sessionKey&&l.setPendingToolCallSessionKey(o.sessionKey),!f.has(e.toolName))return;return isThirdPartyChannel(s,{sessionKey:o?.sessionKey})?{block:!0,blockReason:"Canvas tools are not available in this channel. Respond with plain text only."}:o?.sessionKey?l.isCanvasActiveForGatewayKey(o.sessionKey)?void 0:{block:!0,blockReason:"Canvas is closed by user. Respond with plain text instead."}:{block:!0,blockReason:"Canvas session unknown. Respond with plain text instead."}}),e.logger.debug?.("[beeos-claw] Canvas tool guard registered: before_tool_call")}catch{e.logger.debug?.("[beeos-claw] before_tool_call hook not supported")}}e.logger.info?.("[beeos-claw] Canvas tools registered (render_ui, close_ui, render_form + auto-action tools)")}else e.logger.info?.("[beeos-claw] Canvas disabled by config (canvasEnabled=false)");const m=new TerminalManager,b=createTerminalWebSocketService({config:{port:a.terminalWsPort,token:agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):"",allowedOrigins:a.terminalWsAllowedOrigins},terminalMgr:m,logger:e.logger,writeObs:t});if(a.bridge.shell.enabled?e.registerService({id:"beeos-terminal-ws",start(){b.start(),e.logger.info?.(`[beeos-claw] Terminal WS started on port ${a.terminalWsPort}`)},stop(){b.stop(),m.destroy(),e.logger.info?.("[beeos-claw] Terminal WS stopped")}}):e.logger.info?.("[beeos-claw] Terminal/shell disabled by config (bridge.shell.enabled=false)"),o.openclawConfig){const r=mirrorOpenClawConfig(o.openclawConfig);r.copied?e.logger.info?.(`[beeos-claw] mirrored openclaw config to ${r.destinationPath}`):e.logger.debug?.(`[beeos-claw] openclaw config mirror skipped: ${r.reason}`)}}const plugin={id:"beeos-claw",name:"beeos-claw",description:"BeeOS platform bridge plugin for OpenClaw. Provides file upload/download, ACP bridge, and observability.",version:PLUGIN_VERSION,register(e){if(!_initializing)if(e.registrationMode&&"full"!==e.registrationMode)e.logger.debug?.(`[beeos-claw] Skipping registration (mode=${e.registrationMode})`);else{_initializing=!0;try{const o=initializePlugin(e);if(!o)return;const r={current:null};registerUploadTools(e,o,r),registerServices(e,o,r),_pluginRegisteredAt=Date.now(),e.logger.info?.("[beeos-claw] Plugin registered successfully")}finally{_initializing=!1}}}};export default plugin;
|
|
1
|
+
import{resolveConfigWithMeta,mirrorOpenClawConfig}from"./config.js";import{MessageSDK}from"./messaging/message-sdk.js";import{extractChatPrompt}from"./messaging/chat-envelope.js";import{registerA2ATools,TaskHandleRegistry}from"./a2a/tools.js";import{BEEOS_UPLOAD_TOOL_NAME,BEEOS_UPLOAD_TOOL_SCHEMA,BEEOS_UPLOAD_TOOL_DESCRIPTION,executeUpload}from"./upload/tool.js";import{writeUploadToolResult,cleanupUploadToolResultCache}from"./upload/result-cache.js";import{handleFileStage}from"./upload/file-stage.js";import{handleStatusRequest}from"./status.js";import{ACPServer}from"./acp-server.js";import{createObsEventWriter}from"./observability.js";import{resolvePluginVersion}from"./plugin-version.js";import{createTerminalWebSocketService}from"./terminal/websocket.js";import{TerminalManager}from"./terminal/session-manager.js";import{loadAgentKeyPair,agentFetch}from"./agent-auth.js";import{readDiscoveryCache,writeDiscoveryCache}from"./discovery-cache.js";import{discoverBridgeFromGW}from"./bridge-discovery.js";import{setUploadDeps}from"./upload/upload-file.js";import{registerLocalFileExtractor}from"./upload/local-file-extractors.js";import{browserScreenshotExtractor}from"./browser/screenshot-extractor.js";import{CanvasStateManager}from"./canvas/state.js";import{CanvasRelayClient}from"./canvas/relay-client.js";import{RENDER_UI_TOOL_NAME,RENDER_UI_TOOL_DESCRIPTION,RENDER_UI_TOOL_SCHEMA,CLOSE_UI_TOOL_NAME,CLOSE_UI_TOOL_DESCRIPTION,CLOSE_UI_TOOL_SCHEMA,createRenderUiHandler,createCloseUiHandler,CANVAS_SYSTEM_PROMPT}from"./canvas/tools.js";import{FormSchemaRegistry}from"./surface/form-schema-registry.js";import{buildCronSchemas}from"./surface/cron-schemas.js";import{RENDER_FORM_TOOL_NAME,RENDER_FORM_TOOL_SCHEMA,buildRenderFormDescription,createRenderFormHandler}from"./surface/render-form-tool.js";import{ResourceDescriptorRegistry}from"./surface/resource-descriptor-registry.js";import{CRON_RESOURCE}from"./surface/cron-resource.js";import{generateActionTools}from"./surface/action-tool-generator.js";import{buildThirdPartyChannelSet,isThirdPartyChannel}from"./channel-detection.js";const PLUGIN_VERSION=resolvePluginVersion();let agentKeys=null,sharedCanvasState=null,_initializing=!1,_pluginRegisteredAt=0;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 agentKeys&&r.agentGatewayUrl&&(setUploadDeps({gatewayUrl:r.agentGatewayUrl,keys:agentKeys,logger:e.logger}),registerLocalFileExtractor(browserScreenshotExtractor),e.logger.info?.("[beeos-claw] Upload deps + browser screenshot extractor registered")),{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,a,s){e.logger.debug?.(`[beeos_upload_file] toolCallId=${o} params=${JSON.stringify(a)}`);const n=await executeUpload(a,r,agentKeys,s);return e.logger.debug?.(`[beeos_upload_file] toolCallId=${o} ok=${n.ok}`),t({component:"upload-tool",domain:"tool",name:n.ok?"upload.success":"upload.failure",severity:n.ok?"info":"warn",payload:{toolCallId:o,ok:n.ok,fileCount:n.files?.length??0,error:n.error}}),(async 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)}}),e.registerHttpRoute({path:"/beeos/status",auth:"plugin",handler(e,o){handleStatusRequest(e,o,{publicKey:agentKeys?.publicKey??null,pluginVersion:PLUGIN_VERSION})}})}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(){const o=Date.now(),a=_pluginRegisteredAt?o-_pluginRegisteredAt:-1;if(e.logger.info?.(`[beeos-claw] beeos-acp service start() begin, sincePluginRegister=${a}ms, bridge.url=${r.bridge.url||"(empty)"}`),!r.bridge.url&&r.agentGatewayUrl&&n){const o=Date.now(),a=await discoverBridgeFromGW(r.agentGatewayUrl,n);if(e.logger.info?.(`[beeos-claw] bridge discovery took ${Date.now()-o}ms result=${a?.url??"null"}`),a)r.bridge.url=a.url,writeDiscoveryCache({bridge:{url:a.url,discoveredAt:Date.now()}}),e.logger.info?.(`[beeos-claw] Bridge URL discovered from Agent Gateway: ${a.url}`);else{const 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 (total service start: ${Date.now()-o}ms)`)},async stop(){await l.stop(),e.logger.info?.("[beeos-claw] ACP Server stopped")}});const g=new TaskHandleRegistry;let c=null;const{enabled:d,url:p,principalId:u,a2aEnabled:f}=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,a=async o=>{c.onceConnected(()=>{l.setMessageSdk(c,o),e.logger.info?.("[beeos-claw] Message SDK connected (principalId=%s, via=%s)",o,y?"gateway":"direct")}),await c.connect(o,{centrifugoUrl:p,tokenProvider:y})};e.registerService({id:"beeos-message-bus",async start(){let r=o;if(r||(r=process.env.BEEOS_PRINCIPAL_ID||""),!r&&l)try{await l.waitForAgentMapping(),r=l.getDefaultPlatformAgent()?.instanceId||""}catch(o){e.logger.warn?.("[beeos-claw] Failed to resolve principalId from agent sync:",o)}r?await a(r):l?(e.logger.info?.("[beeos-claw] Message bus deferred: waiting for late agent sync..."),l.onceAgentMappingReady(()=>{const o=l.getDefaultPlatformAgent()?.instanceId;o?a(o).catch(o=>{e.logger.error?.("[beeos-claw] Deferred message bus connect failed:",o)}):e.logger.warn?.("[beeos-claw] Agent mapping ready but no principalId, message bus stays disabled")})):e.logger.warn?.("[beeos-claw] No principalId resolved, message bus disabled")},async stop(){await(c?.disconnect()),e.logger.info?.("[beeos-claw] Message SDK disconnected")}});const t=async(o,a)=>{const r=extractChatPrompt(a,{source:o,localAgentId:l.getLocalAgentId()});r&&(e.logger.debug?.(`[beeos-claw] ${o} received (sessionKey=%s, contextId=%s)`,r.sessionKey,r.contextId??"-"),await l.agentSend(r.message,r.files,r.sessionKey,void 0,r.channelId,r.messageId))};c.onMessage("chat_message",async e=>{await t("chat_message",e)});let s=!1;c.onMessage("agent_request",async o=>{s||(e.logger.warn?.("[beeos-claw] Received legacy 'agent_request' envelope — this path is deprecated and will be removed once all upstreams migrate to 'chat_message' (L0 AgentInvocationService)."),s=!0),await t("agent_request",o)})}else d?e.logger.warn?.("[beeos-claw] Message bus enabled but MESSAGE_SERVICE_URL not set — disabled"):e.logger.info?.("[beeos-claw] Message bus disabled (enabled=%s)",d);if(!1!==f&&r.agentGatewayUrl){const o=e=>l.getGatewaySessionKeyForToolCall(e),a=e=>l.getMentionsForToolCall(e),t=(e,o)=>{l.broadcastNotification(e,o)};registerA2ATools(e,{agentGatewayUrl:r.agentGatewayUrl,agentKeys:agentKeys,logger:e.logger},g,o,a,t),e.logger.info?.("[beeos-claw] A2A tools registered (beeos_discover_agents, beeos_call_agent) via REST")}if(r.canvasEnabled){sharedCanvasState||(sharedCanvasState=new CanvasStateManager);const o=sharedCanvasState;if(r.agentGatewayUrl&&agentKeys){let a;o.setLogger(e.logger);{const e=r.agentGatewayUrl,o=agentKeys;a=async()=>{const a=await agentFetch(`${e}/api/v1/canvas/token`,o,{method:"POST"});if(!a.ok){const e=await a.text().catch(()=>"");throw new Error(`Canvas token returned ${a.status}: ${e}`)}return a.json()}}e.registerService({id:"beeos-canvas-relay",async start(){try{await l.waitForAgentMapping();const t=l.getDefaultPlatformAgent();if(!t?.id)return void e.logger.info?.("[beeos-claw] Canvas Relay skipped: no agentId after sync");const 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:e=>!e||l.isCanvasActiveForGatewayKey(e),getActiveSessionId:e=>l.getSessionIdForToolCall(e),getPlatformAgentId:e=>l.getPlatformAgentIdForToolCall(e),getGatewaySessionKey:e=>l.getGatewaySessionKeyForToolCall(e),waitForAgentSync:()=>l.waitForAgentMapping()},n=new FormSchemaRegistry,i=buildCronSchemas(s);n.register(i.create),n.register(i.update);const g=new ResourceDescriptorRegistry;g.register(CRON_RESOURCE);const c=e=>async(o,a,r)=>(l.preMapToolCallSession(o),e(o,a));e.registerTool({name:RENDER_UI_TOOL_NAME,description:RENDER_UI_TOOL_DESCRIPTION,parameters:RENDER_UI_TOOL_SCHEMA,execute:c(createRenderUiHandler(a))}),e.registerTool({name:CLOSE_UI_TOOL_NAME,description:CLOSE_UI_TOOL_DESCRIPTION,parameters:CLOSE_UI_TOOL_SCHEMA,execute:c(createCloseUiHandler(a))}),l.setCanvasState(o,{schemaRegistry:n,descriptorRegistry:g});const d=l.getFormBuilder();d&&e.registerTool({name:RENDER_FORM_TOOL_NAME,description:buildRenderFormDescription(n),parameters:RENDER_FORM_TOOL_SCHEMA,execute:c(createRenderFormHandler({registry:n,builder:d,logger:e.logger}))});const p=l.getResourceRenderer();if(p){generateActionTools(g,e,async(e,o)=>l.gatewayRequest(e,o),p,e.logger)}const u='\n\nTool selection guidance:\n- browser tool: Use when the user wants to OPEN, VISIT, NAVIGATE to a webpage, take SCREENSHOTS, interact with elements (click, type), or visually inspect pages.\n- beeos_search: Use ONLY for text-based information retrieval (fact-finding, research queries). Never for page interaction or screenshots.\n- beeos_fetch: Use ONLY to extract article text from a known URL. Never for visual content or screenshots.\nWhen the user says "open", "visit", "go to", "screenshot", or mentions seeing/viewing a webpage, ALWAYS prefer the browser tool.',f=new Set([RENDER_UI_TOOL_NAME,CLOSE_UI_TOOL_NAME,RENDER_FORM_TOOL_NAME]),y=256,m=new Map;if("function"==typeof e.on){try{e.on("before_prompt_build",(e,o)=>{if(o?.sessionKey){if(m.size>=y&&!m.has(o.sessionKey)){const e=m.keys().next().value;void 0!==e&&m.delete(e)}m.set(o.sessionKey,o.channelId)}if(isThirdPartyChannel(s,{sessionKey:o?.sessionKey,channelId:o?.channelId}))return;if(!o?.sessionKey)return{appendSystemContext:u};return l.isCanvasActiveForGatewayKey(o.sessionKey)?{appendSystemContext:CANVAS_SYSTEM_PROMPT+u}:{appendSystemContext:"Canvas is closed by user. Do NOT use render_ui, close_ui, or render_form. Respond with plain text only."+u}}),e.logger.debug?.("[beeos-claw] Canvas system prompt hook registered: before_prompt_build")}catch{e.logger.debug?.("[beeos-claw] before_prompt_build hook not supported")}try{e.on("before_tool_call",(e,o)=>{if(o?.sessionKey&&l.setPendingToolCallSessionKey(o.sessionKey),!f.has(e.toolName))return;return isThirdPartyChannel(s,{sessionKey:o?.sessionKey})?{block:!0,blockReason:"Canvas tools are not available in this channel. Respond with plain text only."}:o?.sessionKey?l.isCanvasActiveForGatewayKey(o.sessionKey)?void 0:{block:!0,blockReason:"Canvas is closed by user. Respond with plain text instead."}:{block:!0,blockReason:"Canvas session unknown. Respond with plain text instead."}}),e.logger.debug?.("[beeos-claw] Canvas tool guard registered: before_tool_call")}catch{e.logger.debug?.("[beeos-claw] before_tool_call hook not supported")}}e.logger.info?.("[beeos-claw] Canvas tools registered (render_ui, close_ui, render_form + auto-action tools)")}else e.logger.info?.("[beeos-claw] Canvas disabled by config (canvasEnabled=false)");const m=new TerminalManager,b=createTerminalWebSocketService({config:{port:r.terminalWsPort,token:agentKeys?Buffer.from(agentKeys.publicKey).toString("base64"):"",allowedOrigins:r.terminalWsAllowedOrigins},terminalMgr:m,logger:e.logger,writeObs:t});if(r.bridge.shell.enabled?e.registerService({id:"beeos-terminal-ws",start(){b.start(),e.logger.info?.(`[beeos-claw] Terminal WS started on port ${r.terminalWsPort}`)},stop(){b.stop(),m.destroy(),e.logger.info?.("[beeos-claw] Terminal WS stopped")}}):e.logger.info?.("[beeos-claw] Terminal/shell disabled by config (bridge.shell.enabled=false)"),o.openclawConfig){const a=mirrorOpenClawConfig(o.openclawConfig);a.copied?e.logger.info?.(`[beeos-claw] mirrored openclaw config to ${a.destinationPath}`):e.logger.debug?.(`[beeos-claw] openclaw config mirror skipped: ${a.reason}`)}}const plugin={id:"beeos-claw",name:"beeos-claw",description:"BeeOS platform bridge plugin for OpenClaw. Provides file upload/download, ACP bridge, and observability.",version:PLUGIN_VERSION,register(e){if(!_initializing)if(e.registrationMode&&"full"!==e.registrationMode)e.logger.debug?.(`[beeos-claw] Skipping registration (mode=${e.registrationMode})`);else{_initializing=!0;try{const o=initializePlugin(e);if(!o)return;const a={current:null};registerUploadTools(e,o,a),registerServices(e,o,a),_pluginRegisteredAt=Date.now(),e.logger.info?.("[beeos-claw] Plugin registered successfully")}finally{_initializing=!1}}}};export default plugin;
|
package/dist/message-filter.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const TIMESTAMP_PREFIX_RE=/^\s*\[(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s+\d{4}-\d{2}-\d{2}\s+\d{1,2}:\d{2}(?::\d{2})?\s+GMT[+-]\d{1,2}(?::?\d{2})?]\s*/i,WORKDIR_PREFIX_RE=/^\s*\[working directory:[^\]]*]\s*/i,MESSAGE_ID_PREFIX_RE=/^\s*\[message_id:[^\]]*]\s*/i,USER_MSG_PREFIX_RE=/^\s*User Message From \w+:\s*/i,HEARTBEAT_OK_LINE=
|
|
1
|
+
import{HEARTBEAT_TOKEN,isSilentReplyPrefixText,stripHeartbeatToken}from"./auto-reply-tokens.js";const TIMESTAMP_PREFIX_RE=/^\s*\[(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s+\d{4}-\d{2}-\d{2}\s+\d{1,2}:\d{2}(?::\d{2})?\s+GMT[+-]\d{1,2}(?::?\d{2})?]\s*/i,WORKDIR_PREFIX_RE=/^\s*\[working directory:[^\]]*]\s*/i,MESSAGE_ID_PREFIX_RE=/^\s*\[message_id:[^\]]*]\s*/i,USER_MSG_PREFIX_RE=/^\s*User Message From \w+:\s*/i,HEARTBEAT_OK_LINE=HEARTBEAT_TOKEN,HEARTBEAT_OK_LINE_RE=/^[\s\p{P}\p{S}]*HEARTBEAT_OK[\s\p{P}\p{S}]*$/u,METADATA_PREFIX_PATTERNS=[TIMESTAMP_PREFIX_RE,WORKDIR_PREFIX_RE,MESSAGE_ID_PREFIX_RE,USER_MSG_PREFIX_RE],UNTRUSTED_METADATA_BLOCK_RE=/^Conversation info \(untrusted metadata\):[\s\S]*?Current time:\s*.*?$/i,UNTRUSTED_BLOCK_MARKER="Conversation info (untrusted metadata):",SENDER_UNTRUSTED_MARKER="Sender (untrusted metadata):",SENDER_UNTRUSTED_BLOCK_RE=/Sender\s*\(untrusted[^)]*\)\s*:\s*```[a-z]*\s*[\s\S]*?```/i;function stripMetadataPrefixesFromLine(e){let t=e,r=!1,n=!0;for(;n;){n=!1;for(const e of METADATA_PREFIX_PATTERNS)e.test(t)&&(t=t.replace(e,""),r=!0,n=!0)}return{line:t,changed:r}}export function stripTransportMetadata(e){const t=e.includes(UNTRUSTED_BLOCK_MARKER),r=e.includes(SENDER_UNTRUSTED_MARKER);if(!(e.includes("[")||e.includes(HEARTBEAT_OK_LINE)||e.includes("User Message From")||t||r))return e;if(r){const t=e.replace(SENDER_UNTRUSTED_BLOCK_RE,"").replace(/^\n+/,"").trim();if(t!==e)return t?stripTransportMetadata(t):"";const r=e.indexOf(SENDER_UNTRUSTED_MARKER),n=e.indexOf("\n\n",r),i=-1===n?e.length:n,s=e.slice(i).replace(/^\n+/,"").trim();return s?stripTransportMetadata(s):""}if(t){const t=e.indexOf(UNTRUSTED_BLOCK_MARKER),r=/\nCurrent time:[^\n]*/i.exec(e.slice(t));if(r){const n=t+r.index+r[0].length,i=e.slice(n).replace(/^\n+/,"").trim();return i?stripTransportMetadata(i):""}const n=e.indexOf("\n\n",t),i=-1===n?e.length:n,s=e.slice(i).replace(/^\n+/,"").trim();return s?stripTransportMetadata(s):""}const n=e.split(/\r?\n/),i=[];let s=!1;for(const e of n){const t=stripMetadataPrefixesFromLine(e);HEARTBEAT_OK_LINE_RE.test(t.line.trim())?s=!0:t.changed&&(s=!0,!t.line.trim())||i.push(t.line)}return s?i.join("\n").replace(/^\n+/,"").replace(/\n+$/,""):e}export function normalizeTransportText(e){if(!e)return;const t=stripTransportMetadata(e);return t.length>0?t:void 0}export function isHeartbeatOnlyText(e){const t=e.trim();if(!t)return!1;if(HEARTBEAT_OK_LINE_RE.test(t))return!0;if(t.includes(HEARTBEAT_OK_LINE)){if(stripHeartbeatToken(t,{mode:"message"}).shouldSkip)return!0;if(0===stripTransportMetadata(t).trim().length)return!0}return!1}export function isHeartbeatPrefixText(e){if(!e)return!1;const t=e.trim();return!!t&&(!(t.length>=HEARTBEAT_OK_LINE.length)&&isSilentReplyPrefixText(t,HEARTBEAT_OK_LINE))}export function isHeartbeatFullOrPrefix(e){return"none"!==classifyHeartbeatFilter(e).reason}export function previewFilteredText(e,t=120){if(!e)return"";const r=e.replace(/\\/g,"\\\\").replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(/\s+/g," ").trim();if(r.length<=t)return r;const n=Math.floor((t-1)/2),i=t-1-n;return`${r.slice(0,n)}…${r.slice(-i)}`}export function classifyHeartbeatFilter(e){if(!e)return{reason:"none",filtered:!1};const t=e.trim();if(!t)return{reason:"none",filtered:!1};if(HEARTBEAT_OK_LINE_RE.test(t))return{reason:"full",filtered:!0};if(t.includes(HEARTBEAT_OK_LINE)){if(stripHeartbeatToken(t,{mode:"message"}).shouldSkip)return{reason:"full-stripped",filtered:!0};if(0===stripTransportMetadata(t).trim().length)return{reason:"full-metadata-residue",filtered:!0}}return isHeartbeatPrefixText(t)?{reason:"prefix",filtered:!0}:{reason:"none",filtered:!1}}const HEARTBEAT_PROMPT_PREFIX="read heartbeat.md if it exists";export function isHeartbeatPromptText(e){return e.slice(0,80).toLowerCase().startsWith(HEARTBEAT_PROMPT_PREFIX)}const CRON_PROMPT_PREFIX_RE=/^\[cron:[0-9a-f-]{8,}\s/i;export function isCronPromptText(e){return CRON_PROMPT_PREFIX_RE.test(e.trimStart())}function isRecord(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function sanitizeNode(e){if("string"==typeof e){const t=stripTransportMetadata(e);return{value:t,changed:t!==e}}if(Array.isArray(e)){let t=!1;const r=e.map(e=>{const r=sanitizeNode(e);return r.changed&&(t=!0),r.value});return{value:t?r:e,changed:t}}if(!isRecord(e))return{value:e,changed:!1};let t=!1,r=e;if("string"==typeof e.type&&"text"===e.type&&"string"==typeof e.text){const n=stripTransportMetadata(e.text);n!==e.text&&(r={...r,text:n},t=!0)}if(Array.isArray(e.content)){const n=sanitizeNode(e.content);n.changed&&(t||(r={...r}),r.content=n.value,t=!0)}return{value:t?r:e,changed:t}}export function sanitizePromptPayload(e){return sanitizeNode(e).value}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describe,it,expect}from"vitest";import{isCronPromptText,isHeartbeatPromptText}from"./message-filter.js";describe("isCronPromptText",()=>{it("matches canonical upstream cron prefix",()=>{expect(isCronPromptText("[cron:3f50c57c-e9ee-420c-acb4-cc80c1dbb15d daily-summary] please summarize")).toBe(!0)}),it("matches case-insensitively and tolerates leading whitespace",()=>{expect(isCronPromptText("\n [CRON:abcdef12-3456-7890-abcd-ef0123456789 job] run")).toBe(!0)}),it("rejects text without the cron prefix",()=>{expect(isCronPromptText("hello, please run my task")).toBe(!1),expect(isCronPromptText("[cron] missing id")).toBe(!1),expect(isCronPromptText("")).toBe(!1)}),it("does not collide with heartbeat prompts",()=>{const e="Read HEARTBEAT.md if it exists (workspace context). Follow it strictly.";expect(isHeartbeatPromptText(e)).toBe(!0),expect(isCronPromptText(e)).toBe(!1)})});
|
|
1
|
+
import{describe,it,expect}from"vitest";import{isCronPromptText,isHeartbeatPromptText,isHeartbeatOnlyText,isHeartbeatPrefixText,isHeartbeatFullOrPrefix,classifyHeartbeatFilter,previewFilteredText}from"./message-filter.js";describe("isCronPromptText",()=>{it("matches canonical upstream cron prefix",()=>{expect(isCronPromptText("[cron:3f50c57c-e9ee-420c-acb4-cc80c1dbb15d daily-summary] please summarize")).toBe(!0)}),it("matches case-insensitively and tolerates leading whitespace",()=>{expect(isCronPromptText("\n [CRON:abcdef12-3456-7890-abcd-ef0123456789 job] run")).toBe(!0)}),it("rejects text without the cron prefix",()=>{expect(isCronPromptText("hello, please run my task")).toBe(!1),expect(isCronPromptText("[cron] missing id")).toBe(!1),expect(isCronPromptText("")).toBe(!1)}),it("does not collide with heartbeat prompts",()=>{const e="Read HEARTBEAT.md if it exists (workspace context). Follow it strictly.";expect(isHeartbeatPromptText(e)).toBe(!0),expect(isCronPromptText(e)).toBe(!1)})}),describe("isHeartbeatOnlyText",()=>{it("detects bare token",()=>{expect(isHeartbeatOnlyText("HEARTBEAT_OK")).toBe(!0)}),it("detects token with surrounding whitespace",()=>{expect(isHeartbeatOnlyText(" HEARTBEAT_OK ")).toBe(!0),expect(isHeartbeatOnlyText("\n\nHEARTBEAT_OK\n\n")).toBe(!0)}),it("detects token with trailing punctuation (OpenClaw rule: up to 4 non-word chars)",()=>{expect(isHeartbeatOnlyText("HEARTBEAT_OK.")).toBe(!0),expect(isHeartbeatOnlyText("HEARTBEAT_OK!")).toBe(!0),expect(isHeartbeatOnlyText("HEARTBEAT_OK!!!")).toBe(!0),expect(isHeartbeatOnlyText("HEARTBEAT_OK ✅")).toBe(!0)}),it("detects token wrapped in markdown markup",()=>{expect(isHeartbeatOnlyText("**HEARTBEAT_OK**")).toBe(!0),expect(isHeartbeatOnlyText("`HEARTBEAT_OK`")).toBe(!0),expect(isHeartbeatOnlyText("_HEARTBEAT_OK_")).toBe(!0)}),it("detects token sitting next to stripped transport metadata",()=>{expect(isHeartbeatOnlyText("HEARTBEAT_OK\n[working directory: /home/node]\n[message_id: abc-123]")).toBe(!0)}),it("rejects text that merely mentions the token inline",()=>{expect(isHeartbeatOnlyText("Use the sentinel HEARTBEAT_OK in your ack handler.")).toBe(!1),expect(isHeartbeatOnlyText("The response should be HEARTBEAT_OK always.")).toBe(!1)}),it("rejects empty and pure-whitespace input",()=>{expect(isHeartbeatOnlyText("")).toBe(!1),expect(isHeartbeatOnlyText(" \n\t ")).toBe(!1)})}),describe("isHeartbeatPrefixText",()=>{it("flags the real-world prefix that leaked to staging",()=>{expect(isHeartbeatPrefixText("HEARTBEAT_")).toBe(!0)}),it("flags every meaningful uppercase prefix of HEARTBEAT_OK that includes '_'",()=>{expect(isHeartbeatPrefixText("HEARTBEAT_O")).toBe(!0)}),it("does NOT flag prefixes without '_' (upstream trade-off, avoids eating real words)",()=>{expect(isHeartbeatPrefixText("HEART")).toBe(!1),expect(isHeartbeatPrefixText("HEARTBEAT")).toBe(!1)}),it("rejects length < 2",()=>{expect(isHeartbeatPrefixText("H")).toBe(!1),expect(isHeartbeatPrefixText("")).toBe(!1)}),it("rejects mixed case (avoids eating conversational text)",()=>{expect(isHeartbeatPrefixText("heartbeat_")).toBe(!1),expect(isHeartbeatPrefixText("Heartbeat_")).toBe(!1)}),it("rejects text with non-[A-Z_] characters",()=>{expect(isHeartbeatPrefixText("HEARTBEAT!")).toBe(!1),expect(isHeartbeatPrefixText("HEART-BEAT")).toBe(!1),expect(isHeartbeatPrefixText("HEARTBEAT_OK TRAILING")).toBe(!1)}),it("does NOT flag the full token (that's isHeartbeatOnlyText's job)",()=>{expect(isHeartbeatPrefixText("HEARTBEAT_OK")).toBe(!1)}),it("tolerates leading whitespace",()=>{expect(isHeartbeatPrefixText(" HEARTBEAT_")).toBe(!0)})}),describe("isHeartbeatFullOrPrefix — exactly matches OpenClaw semantics",()=>{it("catches the full token",()=>{expect(isHeartbeatFullOrPrefix("HEARTBEAT_OK")).toBe(!0),expect(isHeartbeatFullOrPrefix("HEARTBEAT_OK.")).toBe(!0),expect(isHeartbeatFullOrPrefix("**HEARTBEAT_OK**")).toBe(!0)}),it("catches prefixes that contain '_'",()=>{expect(isHeartbeatFullOrPrefix("HEARTBEAT_")).toBe(!0),expect(isHeartbeatFullOrPrefix("HEARTBEAT_O")).toBe(!0)}),it("intentionally does NOT catch prefixes without '_' (upstream trade-off)",()=>{expect(isHeartbeatFullOrPrefix("HEART")).toBe(!1),expect(isHeartbeatFullOrPrefix("HEARTBEAT")).toBe(!1),expect(isHeartbeatFullOrPrefix("HE")).toBe(!1)}),it("lets real user content through",()=>{expect(isHeartbeatFullOrPrefix("Let's design a HEARTBEAT_OK-like ack for our API.")).toBe(!1),expect(isHeartbeatFullOrPrefix("Hello, how are you?")).toBe(!1),expect(isHeartbeatFullOrPrefix("Heart of darkness is a novel")).toBe(!1)})}),describe("classifyHeartbeatFilter — structured drop reasons for logs",()=>{it("reports `full` on canonical tokens",()=>{expect(classifyHeartbeatFilter("HEARTBEAT_OK")).toEqual({reason:"full",filtered:!0}),expect(classifyHeartbeatFilter("HEARTBEAT_OK.").reason).toBe("full"),expect(classifyHeartbeatFilter("**HEARTBEAT_OK**").reason).toBe("full"),expect(classifyHeartbeatFilter("`HEARTBEAT_OK`").reason).toBe("full")}),it("reports `full-stripped` as a defensive fallback when regex misses but stripHeartbeatToken catches",()=>{expect(classifyHeartbeatFilter("HEARTBEAT_OK ✅").reason).toBe("full")}),it("reports `full-metadata-residue` when the token is surrounded by transport metadata",()=>{expect(classifyHeartbeatFilter("HEARTBEAT_OK\n[working directory: /home/node]\n[message_id: abc-123]").reason).toBe("full-metadata-residue")}),it("reports `prefix` on uppercase prefixes that contain '_' (upstream rule)",()=>{expect(classifyHeartbeatFilter("HEARTBEAT_").reason).toBe("prefix"),expect(classifyHeartbeatFilter("HEARTBEAT_O").reason).toBe("prefix")}),it("reports `none` for uppercase prefixes WITHOUT '_' (upstream trade-off — avoids eating real words)",()=>{expect(classifyHeartbeatFilter("HEART").reason).toBe("none"),expect(classifyHeartbeatFilter("HEARTBEAT").reason).toBe("none"),expect(classifyHeartbeatFilter("HE").reason).toBe("none")}),it("reports `none` for real content",()=>{expect(classifyHeartbeatFilter("Hello").reason).toBe("none"),expect(classifyHeartbeatFilter("Use HEARTBEAT_OK to reply.").reason).toBe("none"),expect(classifyHeartbeatFilter("").reason).toBe("none"),expect(classifyHeartbeatFilter(" ").reason).toBe("none")}),it("keeps `filtered` in sync with `reason` (never drifts)",()=>{for(const e of["HEARTBEAT_OK","**HEARTBEAT_OK**","HEARTBEAT_","HE","HEART","hello",""]){const t=classifyHeartbeatFilter(e);expect(t.filtered).toBe("none"!==t.reason)}})}),describe("previewFilteredText",()=>{it("returns empty string on empty input",()=>{expect(previewFilteredText("")).toBe("")}),it("escapes newlines / tabs and collapses runs of whitespace",()=>{expect(previewFilteredText("HEARTBEAT_OK\n[meta]")).toBe("HEARTBEAT_OK\\n[meta]"),expect(previewFilteredText("a\t\tb")).toBe("a\\t\\tb"),expect(previewFilteredText("a b c")).toBe("a b c")}),it("returns the full text when within maxLen",()=>{expect(previewFilteredText("HEARTBEAT_OK",20)).toBe("HEARTBEAT_OK")}),it("keeps head + tail with … when longer than maxLen",()=>{const e="A".repeat(50)+"HEARTBEAT_OK"+"B".repeat(50),t=previewFilteredText(e,40);expect(t.length).toBeLessThanOrEqual(40),expect(t).toContain("…"),expect(t.startsWith("A")).toBe(!0),expect(t.endsWith("B")).toBe(!0)})});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{randomUUID}from"node:crypto";export const A2A_PROTOCOL_FIELDS=["task_id","caller_protocol","correlation_id","a2a_task_id","a2a_correlation_id"];export function extractChatPrompt(e,t){const n=e.payload,i=e.metadata,o="string"==typeof n?.message?n.message:"";if(!o)return null;let a;if(Array.isArray(n?.files))a=n.files;else if(Array.isArray(n?.parts)){const e=n.parts.filter(e=>e&&"file"===e.type&&"string"==typeof e.file_url).map(e=>e.file_url);a=e.length>0?e:void 0}const s=e.channel_id??i?.channel_id??("string"==typeof n?.channel_id?n.channel_id:void 0),r=s&&s.length>0?s:void 0,l=("string"==typeof n?.context_id&&n.context_id.length>0?n.context_id:void 0)??(i?.context_id&&i.context_id.length>0?i.context_id:void 0);let d="string"==typeof n?.session_key?n.session_key:void 0;if(!d){const e="chat_message"===t.source?"invoke":"a2a",i="string"==typeof n?.channel?n.channel:e,o=l?`ctx-${l}`:r?`ch-${r}`:t.generateSuffix?.()??fallbackRandom();d=`agent:${t.localAgentId}:${i}:${o}`}const c=e.message_id??i?.message_id??("string"==typeof n?.message_id?n.message_id:void 0);return{message:o,files:a,channelId:r,contextId:l,sessionKey:d,messageId:c&&c.length>0?c:void 0}}function fallbackRandom(){return randomUUID()}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{describe,it,expect}from"vitest";import{extractChatPrompt,A2A_PROTOCOL_FIELDS}from"./chat-envelope.js";const LOCAL_AGENT_ID="agent-local-test",FIXED_SUFFIX=()=>"fixed-suffix";describe("extractChatPrompt — chat_message envelope",()=>{it("returns null when no message is present",()=>{const e=extractChatPrompt({type:"chat_message",payload:{parts:[]}},{source:"chat_message",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e).toBeNull()}),it("extracts message, channelId and contextId from a native envelope",()=>{const e=extractChatPrompt({type:"chat_message",channel_id:"ch-123",payload:{message:"hello",context_id:"ctx-42",parts:[{type:"text",text:"hello"},{type:"file",file_url:"https://cdn/a.png"}]}},{source:"chat_message",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e).not.toBeNull(),expect(e.message).toBe("hello"),expect(e.files).toEqual(["https://cdn/a.png"]),expect(e.channelId).toBe("ch-123"),expect(e.contextId).toBe("ctx-42"),expect(e.sessionKey).toBe(`agent:${LOCAL_AGENT_ID}:invoke:ctx-ctx-42`)}),it("generates a fresh session key when neither context_id nor channel_id is supplied",()=>{const e=extractChatPrompt({type:"chat_message",payload:{message:"hi"}},{source:"chat_message",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e.sessionKey).toBe(`agent:${LOCAL_AGENT_ID}:invoke:fixed-suffix`),expect(e.channelId).toBeUndefined()}),it("uses ch-{channelId} suffix when only channel_id is present",()=>{const e=extractChatPrompt({type:"chat_message",channel_id:"ch-stable",payload:{message:"hi"}},{source:"chat_message",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e.channelId).toBe("ch-stable"),expect(e.sessionKey).toBe(`agent:${LOCAL_AGENT_ID}:invoke:ch-ch-stable`),expect(e.sessionKey.includes("fixed-suffix")).toBe(!1)}),it("prefers ctx-{contextId} over ch-{channelId} when both are present",()=>{const e=extractChatPrompt({type:"chat_message",channel_id:"ch-stable",payload:{message:"hi",context_id:"ctx-pinned"}},{source:"chat_message",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e.sessionKey).toBe(`agent:${LOCAL_AGENT_ID}:invoke:ctx-ctx-pinned`),expect(e.channelId).toBe("ch-stable")}),it("does NOT surface any A2A protocol header even if upstream leaks one",()=>{const e={message:"hello"};for(const t of A2A_PROTOCOL_FIELDS)e[t]=`leaked:${t}`;const t=extractChatPrompt({type:"chat_message",payload:e,metadata:{task_id:"leaked-task",caller_protocol:"a2a",correlation_id:"leaked-corr"}},{source:"chat_message",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(t).not.toBeNull();const a=new Set(["message","files","channelId","contextId","sessionKey","messageId"]);for(const e of Object.keys(t))expect(a.has(e)).toBe(!0);for(const e of A2A_PROTOCOL_FIELDS)expect(t.sessionKey.includes(`leaked:${e}`)).toBe(!1),expect(t.message.includes(`leaked:${e}`)).toBe(!1)}),it("legacy agent_request envelopes still parse, but default channel stays `a2a`",()=>{const e=extractChatPrompt({type:"agent_request",payload:{message:"legacy",files:["/tmp/a.txt"]}},{source:"agent_request",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e.message).toBe("legacy"),expect(e.files).toEqual(["/tmp/a.txt"]),expect(e.sessionKey).toBe(`agent:${LOCAL_AGENT_ID}:a2a:fixed-suffix`)}),it("respects an explicit session_key from legacy callers",()=>{const e=extractChatPrompt({type:"agent_request",payload:{message:"legacy",session_key:"agent:legacy:pre-existing"}},{source:"agent_request",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e.sessionKey).toBe("agent:legacy:pre-existing")}),it("surfaces envelope.message_id as the generic IM request/response correlator",()=>{const e=extractChatPrompt({type:"chat_message",channel_id:"ch-1",message_id:"msg-envelope",payload:{message:"hi",message_id:"msg-payload"},metadata:{message_id:"msg-meta"}},{source:"chat_message",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e.messageId).toBe("msg-envelope")}),it("falls back to metadata.message_id when the envelope field is absent",()=>{const e=extractChatPrompt({type:"chat_message",channel_id:"ch-1",payload:{message:"hi"},metadata:{message_id:"msg-meta"}},{source:"chat_message",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e.messageId).toBe("msg-meta")}),it("normalizes empty string message_id to undefined",()=>{const e=extractChatPrompt({type:"chat_message",channel_id:"ch-1",message_id:"",payload:{message:"hi"}},{source:"chat_message",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e.messageId).toBeUndefined()}),it("prefers envelope.channel_id over metadata over payload",()=>{const e=extractChatPrompt({type:"chat_message",channel_id:"envelope-ch",payload:{message:"m",channel_id:"payload-ch"},metadata:{channel_id:"meta-ch"}},{source:"chat_message",localAgentId:LOCAL_AGENT_ID,generateSuffix:FIXED_SUFFIX});expect(e.channelId).toBe("envelope-ch")})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Centrifuge}from"centrifuge";import WebSocket from"ws";export class MessageSDK{config;client=null;personalSub=null;principalId="";handlers=new Map;_resubscribeTimer=null;_resubscribeAttempts=0;static MAX_RESUBSCRIBE_ATTEMPTS=5;_reconnectCount=0;_lastDisconnectTs=0;_tokenRefreshCount=0;_onConnectedCallback=null;logger;constructor(e,
|
|
1
|
+
import{Centrifuge}from"centrifuge";import WebSocket from"ws";export class MessageSDK{config;client=null;personalSub=null;principalId="";handlers=new Map;_resubscribeTimer=null;_resubscribeAttempts=0;static MAX_RESUBSCRIBE_ATTEMPTS=5;_reconnectCount=0;_lastDisconnectTs=0;_tokenRefreshCount=0;_onConnectedCallback=null;logger;constructor(e,n){this.config=e,this.logger=n}async getToken(e,n,t){const s={principal_id:e};return n&&(s.claims=n),t&&(s.ttl_seconds=t),this.restRequest("POST","/api/v1/tokens",s)}async send(e,n,t){await this.restRequest("POST","/api/v1/messages/send",{target_id:e,message_type:n,payload:t})}async isOnline(e){return(await this.restRequest("GET",`/api/v1/connections/${encodeURIComponent(e)}/online`)).online}async registerWebhook(e,n,t){const s={url:e,events:n};return t&&(s.secret=t),this.restRequest("POST","/api/v1/webhooks",s)}async removeWebhook(e){await this.restRequest("DELETE",`/api/v1/webhooks/${encodeURIComponent(e)}`)}async connect(e,n){this.client&&(this.logger.info?.("[message-sdk] Disconnecting previous client before reconnect"),await this.disconnect()),this.principalId=e,this._reconnectCount=0,this._lastDisconnectTs=0,this._tokenRefreshCount=0;const t=n?.tokenProvider??(e=>this.getToken(e));let s=n?.centrifugoUrl||this.config.centrifugoUrl;if(!s)try{s=(await t(e)).centrifugo_url}catch(e){this.logger.warn?.(`[message-sdk] Token probe failed, cannot discover Centrifugo URL: ${e instanceof Error?e.message:String(e)}`)}if(!s)throw new Error("No Centrifugo URL available. Set centrifugoUrl in config, ConnectOptions, or ensure the token provider is reachable at startup.");const i=`personal:${e}`;this.logger.info?.(`[message-sdk] Connecting as principal=${e} url=${s}`);this.client=new Centrifuge(s,{getToken:async()=>{this._tokenRefreshCount++,this.logger.info?.(`[message-sdk] Token fetch #${this._tokenRefreshCount} for principal=${e}`);return(await t(e)).token},websocket:WebSocket}),this.client.on("connecting",e=>{this.logger.info?.(`[message-sdk] Connecting: code=${e.code} reason=${e.reason}`)}),this.client.on("connected",e=>{if(this._reconnectCount>0){const n=this._lastDisconnectTs>0?Date.now()-this._lastDisconnectTs:0;this.logger.info?.(`[message-sdk] Reconnected (client=${e.client}) reconnects=${this._reconnectCount} downtime=${n}ms`)}else this.logger.info?.(`[message-sdk] Connected (client=${e.client})`);if(this._onConnectedCallback){try{this._onConnectedCallback()}catch{}this._onConnectedCallback=null}}),this.client.on("disconnected",e=>{this._reconnectCount++,this._lastDisconnectTs=Date.now(),this.logger.warn?.(`[message-sdk] Disconnected: code=${e.code} reason=${e.reason} totalDisconnects=${this._reconnectCount}`)}),this.client.on("error",e=>{this.logger.error?.("[message-sdk] Error:",e.error)}),this.client.on("subscribed",e=>{e.channel===i&&this.logger.info?.(`[message-sdk] Subscribed channel=${i} recoverable=${e.recoverable} recovered=${e.recovered}`)}),this.client.on("subscribing",e=>{e.channel===i&&this.logger.info?.(`[message-sdk] Subscribing channel=${i}`)}),this.client.on("unsubscribed",e=>{e.channel===i&&this.logger.warn?.(`[message-sdk] Unsubscribed channel=${i}`)}),this.client.on("publication",e=>{e.channel===i&&this.dispatch(e.data).catch(n=>{const t=e?.data?.type??"(unknown)",s=n instanceof Error?n.message:String(n);this.logger.error?.(`[message-sdk] dispatch failed envType=${t}: ${s}`)})}),this.client.connect()}async disconnect(){this._resubscribeTimer&&(clearTimeout(this._resubscribeTimer),this._resubscribeTimer=null),this._resubscribeAttempts=0,this.personalSub&&(this.personalSub.unsubscribe(),this.personalSub=null),this.client?.disconnect(),this.client=null}onMessage(e,n){this.handlers.set(e,n)}onceConnected(e){this._onConnectedCallback=e}async joinGroup(e,n){if(!this.client)throw new Error("Not connected");const t=this.client.newSubscription(`group:${e}`);return t.on("publication",t=>{n(t.data).catch(n=>{this.logger.error?.(`[message-sdk] group handler error (${e}):`,n)})}),t.subscribe(),t}async publishToGroup(e,n){if(!this.client)throw new Error("Not connected");await this.client.publish(`group:${e}`,{from:this.principalId,content:n,timestamp:Date.now()})}async sendToChannel(e,n,t,s){const i=`ch:${e}`,o={type:n,payload:t,channel_id:e,metadata:{from:this.principalId,channel_id:e,timestamp:String(Date.now())}};if(s?.inReplyTo&&(o.in_reply_to=s.inReplyTo),s?.messageId&&(o.message_id=s.messageId),s?.idempotencyKey&&(o.idempotency_key=s.idempotencyKey),"connected"===this.client?.state)return await this.client.publish(i,o),void this.logger.debug?.(`[message-sdk] Published type=${n} to ${i}`);if(this.config.serviceUrl){this.logger.warn?.(`[message-sdk] Centrifugo not connected, falling back to REST for ch:${e}`);const i={sender_id:this.principalId,type:n,payload:t};return s?.inReplyTo&&(i.in_reply_to=s.inReplyTo),s?.messageId&&(i.message_id=s.messageId),s?.idempotencyKey&&(i.idempotency_key=s.idempotencyKey),void await this.restRequest("POST",`/api/v1/channels/${encodeURIComponent(e)}/messages`,i)}throw new Error(`Cannot send to channel ${e}: no Centrifugo connection and no serviceUrl`)}async sendChannelMessage(e,n){if(!e)throw new Error("channelId is required");if(!n.type)throw new Error("type is required");const t={sender_id:n.senderId??this.principalId,type:n.type,payload:n.payload};if(!t.sender_id)throw new Error("senderId required (and no principalId is known)");return n.messageId&&(t.message_id=n.messageId),n.inReplyTo&&(t.in_reply_to=n.inReplyTo),n.idempotencyKey&&(t.idempotency_key=n.idempotencyKey),this.restRequest("POST",`/api/v1/channels/${encodeURIComponent(e)}/messages`,t)}async replyToMessage(e,n,t,s){const i=e.channel_id??e.metadata?.channel_id;if(!i)throw new Error("replyToMessage: envelope has no channel_id");const o=e.message_id??e.metadata?.message_id??e.metadata?.invocation_id??e.correlationId;if(!o)throw new Error("replyToMessage: envelope has no message_id / invocation_id / correlationId");return this.sendChannelMessage(i,{type:n,payload:t,inReplyTo:o,idempotencyKey:s?.idempotencyKey,messageId:s?.messageId})}async listChannelMessages(e,n){if(!e)throw new Error("channelId is required");const t=new URLSearchParams;void 0!==n?.since&&t.set("since",String(n.since)),void 0!==n?.limit&&t.set("limit",String(n.limit)),n?.type&&t.set("type",n.type);const s=t.toString(),i=`/api/v1/channels/${encodeURIComponent(e)}/messages${s?`?${s}`:""}`;return this.restRequest("GET",i)}async waitForReply(e,n){if(!e)throw new Error("channelId is required");if(!n.inReplyTo)throw new Error("inReplyTo is required");const t={in_reply_to:n.inReplyTo};return void 0!==n.timeoutMs&&(t.timeout_ms=n.timeoutMs),void 0!==n.since&&(t.since=n.since),this.restRequest("POST",`/api/v1/channels/${encodeURIComponent(e)}/wait`,t)}async sendToPersonal(e,n,t){if(!this.client)throw new Error("Not connected");const s=`personal:${e}`,i={type:n,payload:t,metadata:{from:this.principalId,timestamp:String(Date.now())}};try{await this.client.publish(s,i),this.logger.debug?.(`[message-sdk] Published type=${n} to ${s}`)}catch(e){throw this.logger.warn?.(`[message-sdk] Publish failed type=${n} channel=${s}: ${e instanceof Error?e.message:String(e)}`),e}}get isConnected(){return"connected"===this.client?.state}get currentPrincipalId(){return this.principalId}async dispatch(e){const n=this.handlers.get(e.type);n?await n(e):this.logger.debug?.(`[message-sdk] No handler for type=${e.type}`)}async restRequest(e,n,t){if(!this.config.serviceUrl)throw new Error("Message Service REST API requires serviceUrl in config");const s=`${this.config.serviceUrl}${n}`,i={},o={method:e,headers:i};void 0!==t&&(i["Content-Type"]="application/json",o.body=JSON.stringify(t));const r=await fetch(s,o);if(!r.ok){const t=await r.text().catch(()=>"");throw new Error(`Message Service ${e} ${n} returned ${r.status}: ${t}`)}if(204!==r.status)return await r.json()}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{spawn}from"node:child_process";const TIMEOUT_MS=15e3;export class OpenClawCliError extends Error{exitCode;stderr;constructor(e,r,t){super(e),this.exitCode=r,this.stderr=t,this.name="OpenClawCliError"}}function resolveBinary(){const e=process.env.OPENCLAW_BIN?.trim();if(e){const r=e.split(/\s+/);return{cmd:r[0],baseArgs:r.slice(1)}}return{cmd:"openclaw",baseArgs:[]}}const FALLBACK_CMD="node",FALLBACK_ARGS=["/app/openclaw.mjs"];function spawnOnce(e,r){return new Promise((t,n)=>{let o="",s="",a=!1;const i=spawn(e,r,{stdio:["ignore","pipe","pipe"]}),c=setTimeout(()=>{if(!a){a=!0;try{i.kill("SIGKILL")}catch{}n(new OpenClawCliError("openclaw CLI timed out after 15000ms",null,s))}},15e3);i.stdout.on("data",e=>o+=String(e)),i.stderr.on("data",e=>s+=String(e)),i.on("error",e=>{if(a)return;a=!0,clearTimeout(c);const r=new OpenClawCliError(`openclaw CLI spawn failed: ${e.message}`,null,s);r.code=e.code,n(r)}),i.on("exit",e=>{a||(a=!0,clearTimeout(c),0===e?t({stdout:o,stderr:s}):n(new OpenClawCliError(`openclaw CLI exited with code ${e}${s?`: ${s.trim()}`:""}`,e,s)))})})}async function runCli(e){const r=resolveBinary();try{return await spawnOnce(r.cmd,[...r.baseArgs,...e])}catch(r){const t=r?.code;if("ENOENT"===t&&!process.env.OPENCLAW_BIN)return spawnOnce("node",[...FALLBACK_ARGS,...e]);throw r}}let queueTail=Promise.resolve();function enqueue(e){const r=queueTail.catch(()=>{}).then(e);return queueTail=r.catch(()=>{}),r}const SERVER_NAME_RE=/^[a-zA-Z0-9_-]{1,64}$/;export function validateServerName(e){if(!SERVER_NAME_RE.test(e))throw new Error("Invalid MCP server name (allowed: letters, digits, underscore, hyphen, 1-64 chars)")}export async function listMcpServers(){return enqueue(async()=>{const{stdout:e}=await runCli(["mcp","list","--json"]),r=e.trim();if(!r)return{};try{const e=JSON.parse(r);return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch(r){throw new OpenClawCliError(`Failed to parse 'openclaw mcp list --json' output: ${r.message}`,0,e)}})}export async function setMcpServer(e,r){if(validateServerName(e),!r||"object"!=typeof r)throw new Error("MCP server config must be an object");return enqueue(async()=>{await runCli(["mcp","set",e,JSON.stringify(r)])})}export async function unsetMcpServer(e){return validateServerName(e),enqueue(async()=>{await runCli(["mcp","unset",e])})}
|
package/dist/status.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash}from"node:crypto";export function handleStatusRequest(e,t,n){const o=t,s=(e.method??"GET").toUpperCase();if("GET"!==s&&"HEAD"!==s)return o.statusCode=405,o.setHeader("Allow","GET, HEAD"),void o.end();const r=n.publicKey?createHash("sha256").update(n.publicKey).digest("hex"):null,a={plugin:"beeos-claw",plugin_version:n.pluginVersion,fingerprint:r};o.statusCode=200,o.setHeader("Content-Type","application/json"),o.setHeader("Cache-Control","no-store"),"HEAD"!==s?o.end(JSON.stringify(a)):o.end()}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function formatSchedule(e,t){const
|
|
1
|
+
import{BEEOS_CHANNEL_TAG_RE,stripBeeosChannelTag}from"../acp-gateway/bridge-core.js";function formatSchedule(e,t){const n=e;if(!n)return"—";const o=n.kind;if("cron"===o)return n.expr??"—";if("every"===o){const e=n.everyMs??0;return e>=864e5?`Every ${Math.round(e/864e5)}d`:e>=36e5?`Every ${Math.round(e/36e5)}h`:e>=6e4?`Every ${Math.round(e/6e4)}m`:`Every ${Math.round(e/1e3)}s`}return"at"===o?`At ${n.at??"—"}`:"—"}export const CRON_RESOURCE={domain:"cron",title:"Scheduled Tasks",listRpc:"cron.list",listParams:{includeDisabled:!0,limit:50},extractItems:e=>{const t=e?.jobs;return Array.isArray(t)?t:[]},itemId:e=>e.id,columns:[{key:"name",label:"Name"},{key:"schedule",label:"Schedule",format:formatSchedule},{key:"enabled",label:"Status",format:e=>e?"Enabled":"Disabled"},{key:"delivery",label:"Delivery",format:(e,t)=>{const n=e;if(!n||!n.mode||"none"===n.mode){const e=t.description??"";return BEEOS_CHANNEL_TAG_RE.test(e)?"Internal":"None"}return"announce"===n.mode?`Channel: ${n.channel??"last"}`:"webhook"===n.mode?"Webhook":String(n.mode)}},{key:"state.lastRunStatus",label:"Last Run",format:e=>String(e??"—")},{key:"state.nextRunAtMs",label:"Next Run",format:e=>e?new Date(Number(e)).toLocaleString():"—"}],itemActions:[{id:"toggle",type:"rpc",rpc:"cron.update",label:e=>e.enabled?`Disable "${e.name}"`:`Enable "${e.name}"`,buildParams:e=>({id:e.id,patch:{enabled:!e.enabled}}),description:"Toggle a cron job on/off"},{id:"edit",type:"form",formDomain:"cron",formOperation:"update",label:e=>`Edit "${e.name}"`,buildFormData:e=>{const t=e.delivery,n=e.description??"",o=BEEOS_CHANNEL_TAG_RE.test(n),r=stripBeeosChannelTag(n);let a;return a=o?"internal":"announce"===t?.mode?"announce":"webhook"===t?.mode?"webhook":"none",{...e,description:r||void 0,sessionTarget:e.sessionTarget??"isolated",deliveryMode:a,deliveryChannel:"announce"===t?.mode?t?.channel:void 0,webhookUrl:"webhook"===t?.mode?t?.to:void 0}}},{id:"run",type:"rpc",rpc:"cron.run",label:e=>`Run "${e.name}"`,buildParams:e=>({id:e.id,mode:"force"}),description:"Run a cron job immediately"},{id:"delete",type:"rpc",rpc:"cron.remove",label:e=>`Delete "${e.name}"`,buildParams:e=>({id:e.id}),description:"Delete a cron job"}],globalActions:[{id:"refresh",type:"refresh",label:"Refresh"}],slashCommand:"cron",emptyTitle:"No scheduled tasks",emptyContent:"Use the agent to create cron jobs, or add them via the form below."};
|