aws-runtime-bridge 1.9.130 → 1.9.134

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.
Files changed (94) hide show
  1. package/dist/adapter/AcodeSdkAdapter.d.ts +15 -0
  2. package/dist/adapter/AcodeSdkAdapter.js +5 -5
  3. package/dist/adapter/types.d.ts +9 -0
  4. package/dist/browser/browser-frame-encode.d.ts +16 -0
  5. package/dist/browser/browser-frame-encode.js +2 -0
  6. package/dist/browser/browser-pool.js +1 -1
  7. package/dist/browser/built-in-browser-tools.js +1 -1
  8. package/dist/browser/screencast-differ.d.ts +35 -0
  9. package/dist/browser/screencast-differ.js +2 -0
  10. package/dist/browser/screencast-manager.d.ts +32 -0
  11. package/dist/browser/screencast-manager.js +1 -1
  12. package/dist/browser/types.d.ts +48 -1
  13. package/dist/browser/types.js +1 -1
  14. package/dist/browser/ws-server.d.ts +1 -1
  15. package/dist/browser/ws-server.js +1 -1
  16. package/dist/routes/background-tasks.js +7 -1
  17. package/dist/routes/instance-tool-status.d.ts +4 -0
  18. package/dist/routes/instance-tool-status.js +2 -0
  19. package/dist/routes/instance.d.ts +0 -2
  20. package/dist/routes/instance.js +1 -1
  21. package/dist/routes/system-metrics.js +1 -1
  22. package/dist/routes/terminal.js +19 -19
  23. package/dist/services/acode-bg-manager.d.ts +36 -0
  24. package/dist/services/acode-bg-manager.js +2 -0
  25. package/dist/services/browser-session-manager.js +1 -1
  26. package/dist/services/instance-features.d.ts +5 -0
  27. package/dist/services/instance-features.js +1 -1
  28. package/dist/services/process-detail.d.ts +77 -0
  29. package/dist/services/process-detail.js +32 -0
  30. package/dist/services/process-top.d.ts +53 -0
  31. package/dist/services/process-top.js +50 -0
  32. package/dist/services/session-output.d.ts +10 -0
  33. package/dist/services/session-output.js +3 -3
  34. package/package/acode/dist/await-complete-tool.js +4 -4
  35. package/package/acode/dist/background-command-manager.d.ts +39 -0
  36. package/package/acode/dist/background-command-manager.js +5 -5
  37. package/package/acode/dist/background-command-tools.js +1 -1
  38. package/package/acode/dist/built-in-file-tools.d.ts +25 -1
  39. package/package/acode/dist/built-in-file-tools.js +2 -2
  40. package/package/acode/dist/builtins/shellCommandResult.d.ts +3 -0
  41. package/package/acode/dist/builtins/shellCommandResult.js +1 -1
  42. package/package/acode/dist/builtins/shellCommandRunner.d.ts +2 -0
  43. package/package/acode/dist/builtins/shellCommandRunner.js +1 -1
  44. package/package/acode/dist/image-utils.d.ts +52 -0
  45. package/package/acode/dist/image-utils.js +2 -0
  46. package/package/acode/dist/index.d.ts +1 -0
  47. package/package/acode/dist/index.js +1 -1
  48. package/package/acode/dist/runtime.d.ts +15 -1
  49. package/package/acode/dist/runtime.js +26 -26
  50. package/package/acode/dist/sub-agent-tools.js +30 -26
  51. package/package/acode/dist/sub-agent-types.d.ts +1 -1
  52. package/package/acode/dist/tool-allocation.d.ts +4 -4
  53. package/package/acode/dist/tool-allocation.js +1 -1
  54. package/package/acode/dist/types.d.ts +3 -1
  55. package/package/aws-client-agent-mcp/dist/http-client.d.ts +4 -0
  56. package/package/aws-client-agent-mcp/dist/http-client.js +1 -1
  57. package/package/aws-client-agent-mcp/dist/mcp-server.d.ts +8 -0
  58. package/package/aws-client-agent-mcp/dist/mcp-server.js +28 -25
  59. package/package/aws-client-agent-mcp/dist/mcp-tools.js +6 -6
  60. package/package/aws-client-agent-mcp/dist/memory-store.d.ts +6 -0
  61. package/package/aws-client-agent-mcp/dist/memory-tools.js +2 -2
  62. package/package/aws-client-agent-mcp/dist/types.d.ts +4 -0
  63. package/package/aws-client-agent-mcp/package.json +1 -1
  64. package/package.json +3 -3
  65. package/package/aws-client-agent-mcp/dist/agent-client.test.d.ts +0 -1
  66. package/package/aws-client-agent-mcp/dist/agent-client.test.js +0 -1066
  67. package/package/aws-client-agent-mcp/dist/config.test.d.ts +0 -1
  68. package/package/aws-client-agent-mcp/dist/config.test.js +0 -259
  69. package/package/aws-client-agent-mcp/dist/context-manager.test.d.ts +0 -2
  70. package/package/aws-client-agent-mcp/dist/context-manager.test.js +0 -312
  71. package/package/aws-client-agent-mcp/dist/http-client.test.d.ts +0 -1
  72. package/package/aws-client-agent-mcp/dist/http-client.test.js +0 -808
  73. package/package/aws-client-agent-mcp/dist/launch-config-tools.test.d.ts +0 -1
  74. package/package/aws-client-agent-mcp/dist/launch-config-tools.test.js +0 -110
  75. package/package/aws-client-agent-mcp/dist/logger.test.d.ts +0 -1
  76. package/package/aws-client-agent-mcp/dist/logger.test.js +0 -27
  77. package/package/aws-client-agent-mcp/dist/mcp-server.test.d.ts +0 -1
  78. package/package/aws-client-agent-mcp/dist/mcp-server.test.js +0 -2798
  79. package/package/aws-client-agent-mcp/dist/mcp-tools.test.d.ts +0 -1
  80. package/package/aws-client-agent-mcp/dist/mcp-tools.test.js +0 -152
  81. package/package/aws-client-agent-mcp/dist/memory-store.test.d.ts +0 -1
  82. package/package/aws-client-agent-mcp/dist/memory-store.test.js +0 -664
  83. package/package/aws-client-agent-mcp/dist/message-buffer.test.d.ts +0 -1
  84. package/package/aws-client-agent-mcp/dist/message-buffer.test.js +0 -142
  85. package/package/aws-client-agent-mcp/dist/parent-lifecycle.test.d.ts +0 -1
  86. package/package/aws-client-agent-mcp/dist/parent-lifecycle.test.js +0 -81
  87. package/package/aws-client-agent-mcp/dist/runtime-launch-binding.test.d.ts +0 -1
  88. package/package/aws-client-agent-mcp/dist/runtime-launch-binding.test.js +0 -201
  89. package/package/aws-client-agent-mcp/dist/status-reporter.test.d.ts +0 -1
  90. package/package/aws-client-agent-mcp/dist/status-reporter.test.js +0 -157
  91. package/package/aws-client-agent-mcp/dist/watchdog.test.d.ts +0 -1
  92. package/package/aws-client-agent-mcp/dist/watchdog.test.js +0 -124
  93. package/package/aws-client-agent-mcp/dist/websocket-client.test.d.ts +0 -1
  94. package/package/aws-client-agent-mcp/dist/websocket-client.test.js +0 -725
@@ -1,19 +1,20 @@
1
- import{PRESET_CORE as d,PRESET_EXPLORE as c,resolveToolAllocation as g,ToolAllocationError as b}from"./tool-allocation.js";const h=`Launch a new sub-agent to handle a task autonomously (non-blocking).
1
+ import{resolveToolAllocation as d,ToolAllocationError as g}from"./tool-allocation.js";const b=`Launch a new sub-agent to handle a task autonomously (non-blocking).
2
2
 
3
3
  Use this tool to:
4
4
  1. Delegate research, exploration, or implementation work to a specialized sub-agent
5
5
  2. Run multiple independent tasks in parallel (multiple tool calls in one message)
6
6
  3. Keep the main context window focused by offloading detailed work
7
7
 
8
- Tool allocation (the 'tools' parameter) \u2014 elements combine by union:
9
- - Presets (start with '@'):
10
- - "${c}": read-only set (read/grep/Bash/symbols etc., plus memory MCP tools).
11
- Omitting 'tools' means ["${c}"] \u2014 read-only default
12
- - "${d}": all core default tools (read/write/edit/grep/Bash/todo/terminal; no suites/MCP)
8
+ Sub-agent types (the 'subagent_type' parameter):
9
+ - "explore": read-only set (read/grep/Bash/symbols etc., plus memory MCP tools). Default.
10
+ - "core": all core default tools (read/write/edit/grep/Bash/todo/terminal; no suites/MCP)
11
+ - "custom": allocate specific tools via 'tools' parameter (required when type is custom)
12
+
13
+ Tool allocation (the 'tools' parameter, required for 'custom' type):
13
14
  - Category name allocates a whole suite: "office", "browser", "desktop"
14
15
  - Exact tool path allocates one tool: "default.read_file"
15
- - Mix freely: ["${d}", "browser"]
16
- - Unknown presets/categories are rejected with an error listing what is available;
16
+ - Elements combine by union: ["browser", "default.read_file"]
17
+ - Unknown categories/paths are rejected with an error listing what is available;
17
18
  call list_sub_agent_tools to see all allocatable categories and tool paths first.
18
19
 
19
20
  This tool is NON-BLOCKING: it returns immediately with a subId after spawn.
@@ -27,13 +28,13 @@ Guidelines:
27
28
  - Write a clear, self-contained prompt (the sub-agent starts with a fresh context)
28
29
  - Launch multiple agents concurrently when possible (multiple tool calls in one message)
29
30
  - Sub-agents cannot spawn further sub-agents (no nesting)
30
- - Always call await_complete (with this subId in 'sub_agent_ids') before reporting completion to the user`;function m(n){return{kind:"builtin",toolName:"sub_agent",exposedName:"sub_agent",description:h,inputSchema:{type:"object",properties:{description:{type:"string",description:"A short (3-5 words) description of the task."},prompt:{type:"string",description:"The task for the sub-agent to perform (self-contained, fresh context)."},tools:{type:"array",items:{type:"string"},description:`Optional tool allocation, elements combine by union. Presets: '${c}' (read-only default), '${d}' (all core default tools). Or category names ('office', 'browser') / exact tool paths ('default.read_file'). Omit for read-only mode. See list_sub_agent_tools for the full catalog.`}},required:["description","prompt"]},async execute(r){if("subagent_type"in r)return{title:"sub_agent validation error",output:"Invalid input: 'subagent_type' has been removed. Use 'tools' instead: omit for read-only mode, or pass presets ('@explore', '@core') / categories / exact tool paths.",metadata:{error:!0}};const e=typeof r.description=="string"?r.description.trim():"",t=typeof r.prompt=="string"?r.prompt.trim():"";if(!e)return{title:"sub_agent validation error",output:"Invalid input: 'description' is required and must be non-empty.",metadata:{error:!0}};if(!t)return{title:"sub_agent validation error",output:"Invalid input: 'prompt' is required and must be non-empty.",metadata:{error:!0}};const o=r.tools,s=typeof o=="string"?[o]:Array.isArray(o)?o.filter(i=>typeof i=="string"):[];let a,l;try{const i=await n.listSubAgentToolCatalog(),u=g(s,i);a=u.patterns,l=u.label}catch(i){if(i instanceof b)return{title:"sub_agent validation error",output:`Invalid input: ${i.message}`,metadata:{error:!0}};throw i}const p=a.length>0;try{const{subId:i}=await n.spawnSubAgent({subagentType:l,description:e,prompt:t,...p?{allowedTools:a}:{}}),u=p?`
31
- tool allocation (${l}): ${a.join(", ")} (whitelist mode \u2014 only matching tools are exposed)`:`
32
- mode: ${l} (no allocatable tools found in catalog)`;return{title:e,output:`sub_agent spawned: ${i}
33
- type: ${l}${u}
31
+ - Always call await_complete (with this subId in 'sub_agent_ids') before reporting completion to the user`;function h(a){return{kind:"builtin",toolName:"sub_agent",exposedName:"sub_agent",description:b,inputSchema:{type:"object",properties:{description:{type:"string",description:"A short (3-5 words) description of the task."},prompt:{type:"string",description:"The task for the sub-agent to perform (self-contained, fresh context)."},subagent_type:{type:"string",enum:["explore","core","custom"],description:"Sub-agent type: 'explore' (read-only default), 'core' (all core tools), or 'custom' (specific tools via 'tools' param)."},tools:{type:"array",items:{type:"string"},description:"Tool allocation for 'custom' type (required when subagent_type is 'custom'). Category names ('office', 'browser') or exact tool paths ('default.read_file'). Elements combine by union."}},required:["description","prompt","subagent_type"]},async execute(n){const o=typeof n.description=="string"?n.description.trim():"",t=typeof n.prompt=="string"?n.prompt.trim():"",e=typeof n.subagent_type=="string"?n.subagent_type.trim():"";if(!o)return{title:"sub_agent validation error",output:"Invalid input: 'description' is required and must be non-empty.",metadata:{error:!0}};if(!t)return{title:"sub_agent validation error",output:"Invalid input: 'prompt' is required and must be non-empty.",metadata:{error:!0}};if(!e||!["explore","core","custom"].includes(e))return{title:"sub_agent validation error",output:"Invalid input: 'subagent_type' must be one of 'explore', 'core', or 'custom'.",metadata:{error:!0}};const s=n.tools,r=typeof s=="string"?[s]:Array.isArray(s)?s.filter(i=>typeof i=="string"):[];let u,l;try{const i=await a.listSubAgentToolCatalog(),c=d(e,r,i);u=c.patterns,l=c.label}catch(i){if(i instanceof g)return{title:"sub_agent validation error",output:`Invalid input: ${i.message}`,metadata:{error:!0}};throw i}const p=u.length>0;try{const{subId:i}=await a.spawnSubAgent({subagentType:l,description:o,prompt:t,...p?{allowedTools:u}:{}}),c=p?`
32
+ tool allocation (${l}): ${u.join(", ")} (whitelist mode \u2014 only matching tools are exposed)`:`
33
+ mode: ${l} (no allocatable tools found in catalog)`;return{title:o,output:`sub_agent spawned: ${i}
34
+ type: ${l}${c}
34
35
 
35
36
  Call await_complete with this subId in 'sub_agent_ids' to get the result.
36
- Call get_sub_agent_status to check progress.`,metadata:{subId:i,spawned:!0,typeLabel:l,...p?{allocatedTools:a}:{}}}}catch(i){const u=i instanceof Error?i.message:String(i);return{title:e,output:`Failed to spawn sub-agent: ${u}`,metadata:{error:!0}}}}}}const _=`List all sub-agents for the current agent.
37
+ Call get_sub_agent_status to check progress.`,metadata:{subId:i,spawned:!0,typeLabel:l,...p?{allocatedTools:u}:{}}}}catch(i){const c=i instanceof Error?i.message:String(i);return{title:o,output:`Failed to spawn sub-agent: ${c}`,metadata:{error:!0}}}}}}const m=`List all sub-agents for the current agent.
37
38
 
38
39
  Returns two arrays:
39
40
  - running: sub-agents currently in pending/running state
@@ -42,8 +43,8 @@ Returns two arrays:
42
43
  Use this to:
43
44
  1. Check which sub-agents are still running
44
45
  2. Review completed sub-agent history
45
- 3. Find a subId before calling await_complete (sub_agent_ids) or get_sub_agent_status`;function f(n){return{kind:"builtin",toolName:"list_sub_agents",exposedName:"list_sub_agents",description:_,inputSchema:{type:"object",properties:{}},async execute(r){try{const{running:e,history:t}=await n.listSubAgents(),o=a=>{const l=a.durationMs!==void 0?`${(a.durationMs/1e3).toFixed(1)}s`:a.endedAt?`${((a.endedAt-a.startedAt)/1e3).toFixed(1)}s`:"ongoing";return` - ${a.subId} [${a.status}] (${l}) ${a.description}`},s=[];return s.push(`Running (${e.length}):`),e.length===0?s.push(" (none)"):e.forEach(a=>s.push(o(a))),s.push(""),s.push(`History (${t.length}):`),t.length===0?s.push(" (none)"):t.forEach(a=>s.push(o(a))),{title:"sub-agents list",output:s.join(`
46
- `),metadata:{runningCount:e.length,historyCount:t.length}}}catch(e){return{title:"list_sub_agents error",output:`Failed to list sub-agents: ${e instanceof Error?e.message:String(e)}`,metadata:{error:!0}}}}}}const y=`Get the current status and context snapshot of a sub-agent.
46
+ 3. Find a subId before calling await_complete (sub_agent_ids) or get_sub_agent_status`;function f(a){return{kind:"builtin",toolName:"list_sub_agents",exposedName:"list_sub_agents",description:m,inputSchema:{type:"object",properties:{}},async execute(n){try{const{running:o,history:t}=await a.listSubAgents(),e=r=>{const u=r.durationMs!==void 0?`${(r.durationMs/1e3).toFixed(1)}s`:r.endedAt?`${((r.endedAt-r.startedAt)/1e3).toFixed(1)}s`:"ongoing";return` - ${r.subId} [${r.status}] (${u}) ${r.description}`},s=[];return s.push(`Running (${o.length}):`),o.length===0?s.push(" (none)"):o.forEach(r=>s.push(e(r))),s.push(""),s.push(`History (${t.length}):`),t.length===0?s.push(" (none)"):t.forEach(r=>s.push(e(r))),{title:"sub-agents list",output:s.join(`
47
+ `),metadata:{runningCount:o.length,historyCount:t.length}}}catch(o){return{title:"list_sub_agents error",output:`Failed to list sub-agents: ${o instanceof Error?o.message:String(o)}`,metadata:{error:!0}}}}}}const _=`Get the current status and context snapshot of a sub-agent.
47
48
 
48
49
  Returns:
49
50
  - status: pending/running/completed/failed/cancelled
@@ -54,9 +55,9 @@ Returns:
54
55
  - result: final output (if completed)
55
56
  - error: error message (if failed)
56
57
 
57
- Use this to check progress of a running sub-agent before awaiting it.`;function w(n){return{kind:"builtin",toolName:"get_sub_agent_status",exposedName:"get_sub_agent_status",description:y,inputSchema:{type:"object",properties:{sub_id:{type:"string",description:"The sub-agent ID returned by sub_agent tool."}},required:["sub_id"]},async execute(r){const e=typeof r.sub_id=="string"?r.sub_id.trim():"";if(!e)return{title:"get_sub_agent_status validation error",output:"Invalid input: 'sub_id' is required.",metadata:{error:!0}};try{const t=await n.getSubAgentStatus(e);if(!t)return{title:"sub-agent not found",output:`sub-agent not found: ${e}`,metadata:{subId:e,error:!0}};const o=[];if(o.push(`subId: ${t.subId}`),o.push(`type: ${t.subagentType}`),o.push(`description: ${t.description}`),o.push(`status: ${t.status}`),t.startedAt&&o.push(`startedAt: ${new Date(t.startedAt).toISOString()}`),t.endedAt&&o.push(`endedAt: ${new Date(t.endedAt).toISOString()}`),t.durationMs!==void 0&&o.push(`duration: ${(t.durationMs/1e3).toFixed(2)}s`),t.contextSnapshot){if(o.push(""),o.push("Context:"),t.contextSnapshot.currentTool&&o.push(` currentTool: ${t.contextSnapshot.currentTool}`),t.contextSnapshot.lastAssistantText){const s=t.contextSnapshot.lastAssistantText;o.push(` lastOutput: ${s.length>200?s.slice(-200)+"...":s}`)}o.push(` tokens: input=${t.contextSnapshot.tokenUsage.input}, output=${t.contextSnapshot.tokenUsage.output}`),o.push(` messages: ${t.contextSnapshot.messageCount}`),o.push(` updatedAt: ${t.contextSnapshot.updatedAt}`)}if(t.result){o.push(""),o.push("Result:");const s=t.result;o.push(s.length>500?s.slice(0,500)+`
58
- ... (truncated)`:s)}return t.errorMessage&&(o.push(""),o.push(`Error: ${t.errorMessage}`)),{title:`status: ${t.description}`,output:o.join(`
59
- `),metadata:{subId:t.subId,status:t.status}}}catch(t){return{title:"get_sub_agent_status error",output:`Failed to get status: ${t instanceof Error?t.message:String(t)}`,metadata:{subId:e,error:!0}}}}}}const S=`Abort a running sub-agent.
58
+ Use this to check progress of a running sub-agent before awaiting it.`;function y(a){return{kind:"builtin",toolName:"get_sub_agent_status",exposedName:"get_sub_agent_status",description:_,inputSchema:{type:"object",properties:{sub_id:{type:"string",description:"The sub-agent ID returned by sub_agent tool."}},required:["sub_id"]},async execute(n){const o=typeof n.sub_id=="string"?n.sub_id.trim():"";if(!o)return{title:"get_sub_agent_status validation error",output:"Invalid input: 'sub_id' is required.",metadata:{error:!0}};try{const t=await a.getSubAgentStatus(o);if(!t)return{title:"sub-agent not found",output:`sub-agent not found: ${o}`,metadata:{subId:o,error:!0}};const e=[];if(e.push(`subId: ${t.subId}`),e.push(`type: ${t.subagentType}`),e.push(`description: ${t.description}`),e.push(`status: ${t.status}`),t.startedAt&&e.push(`startedAt: ${new Date(t.startedAt).toISOString()}`),t.endedAt&&e.push(`endedAt: ${new Date(t.endedAt).toISOString()}`),t.durationMs!==void 0&&e.push(`duration: ${(t.durationMs/1e3).toFixed(2)}s`),t.contextSnapshot){if(e.push(""),e.push("Context:"),t.contextSnapshot.currentTool&&e.push(` currentTool: ${t.contextSnapshot.currentTool}`),t.contextSnapshot.lastAssistantText){const s=t.contextSnapshot.lastAssistantText;e.push(` lastOutput: ${s.length>200?s.slice(-200)+"...":s}`)}e.push(` tokens: input=${t.contextSnapshot.tokenUsage.input}, output=${t.contextSnapshot.tokenUsage.output}`),e.push(` messages: ${t.contextSnapshot.messageCount}`),e.push(` updatedAt: ${t.contextSnapshot.updatedAt}`)}if(t.result){e.push(""),e.push("Result:");const s=t.result;e.push(s.length>500?s.slice(0,500)+`
59
+ ... (truncated)`:s)}return t.errorMessage&&(e.push(""),e.push(`Error: ${t.errorMessage}`)),{title:`status: ${t.description}`,output:e.join(`
60
+ `),metadata:{subId:t.subId,status:t.status}}}catch(t){return{title:"get_sub_agent_status error",output:`Failed to get status: ${t instanceof Error?t.message:String(t)}`,metadata:{subId:o,error:!0}}}}}}const w=`Abort a running sub-agent.
60
61
 
61
62
  Use this to cancel a sub-agent that is taking too long or is no longer needed.
62
63
  Only pending or running sub-agents can be aborted; completed/failed/cancelled are no-ops.
@@ -64,21 +65,24 @@ Only pending or running sub-agents can be aborted; completed/failed/cancelled ar
64
65
  After abort:
65
66
  - The sub-agent's status becomes 'cancelled'
66
67
  - Its completionPromise resolves with error='aborted'
67
- - Any await_complete waiting on it (with this subId in 'sub_agent_ids') will return immediately`;function $(n){return{kind:"builtin",toolName:"abort_sub_agent",exposedName:"abort_sub_agent",description:S,inputSchema:{type:"object",properties:{sub_id:{type:"string",description:"The sub-agent ID to abort."}},required:["sub_id"]},async execute(r){const e=typeof r.sub_id=="string"?r.sub_id.trim():"";if(!e)return{title:"abort_sub_agent validation error",output:"Invalid input: 'sub_id' is required.",metadata:{error:!0}};try{return await n.abortSubAgent(e),{title:"sub-agent aborted",output:`sub-agent ${e} has been aborted.`,metadata:{subId:e,aborted:!0}}}catch(t){return{title:"abort_sub_agent error",output:`Failed to abort sub-agent: ${t instanceof Error?t.message:String(t)}`,metadata:{subId:e,error:!0}}}}}}const T=`List all tool presets, categories and tools that can be allocated to sub-agents.
68
+ - Any await_complete waiting on it (with this subId in 'sub_agent_ids') will return immediately`;function S(a){return{kind:"builtin",toolName:"abort_sub_agent",exposedName:"abort_sub_agent",description:w,inputSchema:{type:"object",properties:{sub_id:{type:"string",description:"The sub-agent ID to abort."}},required:["sub_id"]},async execute(n){const o=typeof n.sub_id=="string"?n.sub_id.trim():"";if(!o)return{title:"abort_sub_agent validation error",output:"Invalid input: 'sub_id' is required.",metadata:{error:!0}};try{return await a.abortSubAgent(o),{title:"sub-agent aborted",output:`sub-agent ${o} has been aborted.`,metadata:{subId:o,aborted:!0}}}catch(t){return{title:"abort_sub_agent error",output:`Failed to abort sub-agent: ${t instanceof Error?t.message:String(t)}`,metadata:{subId:o,error:!0}}}}}}const T=`List all tool categories and tools that can be allocated to sub-agents.
68
69
 
69
- Output starts with the built-in '@' presets, then categories (suite). Each category
70
- line shows its tool short names:
70
+ Output shows categories (suite). Each category line shows its tool short names:
71
71
  - default: core file/shell tools (read_file, write_file, grep, Bash, ...)
72
72
  - <suite>: suite tools (e.g. browser: launch, navigate, click, ...)
73
73
  - <mcp-server>: MCP tools under that server (e.g. memory: read_memory, ...)
74
74
 
75
- Use this before spawning a sub-agent with the 'tools' parameter:
76
- - Pass a preset to use a built-in bundle: tools: ["@explore"] or ["@core"]
75
+ Use this before spawning a sub-agent with subagent_type='custom' and 'tools' parameter:
77
76
  - Pass a category name to allocate the whole suite: tools: ["office"]
78
77
  - Pass an exact tool path for one tool: tools: ["default.read_file"]
79
- - Elements combine by union: ["@core", "browser"]
78
+ - Elements combine by union: ["browser", "default.read_file"]
79
+
80
+ Sub-agent types:
81
+ - "explore": read-only set (default category minus write tools + memory MCP tools)
82
+ - "core": all core default tools (no suites/MCP)
83
+ - "custom": allocate specific tools via 'tools' parameter
80
84
 
81
85
  If a tool you need is not listed, it cannot be allocated (the sub-agent pool
82
- equals the current agent's tool set).`;function x(n){return{kind:"builtin",toolName:"list_sub_agent_tools",exposedName:"list_sub_agent_tools",description:T,inputSchema:{type:"object",properties:{}},async execute(r){try{const e=await n.listSubAgentToolCatalog();if(e.length===0)return{title:"allocatable tools",output:"No allocatable tools found (tool catalog is empty).",metadata:{categories:0}};const t=["Presets (for sub_agent 'tools' param):",` ${c} \u2014 read-only set (default category minus write tools + memory MCP tools); omitting 'tools' means ["${c}"]`,` ${d} \u2014 all core default tools (no suites/MCP)`,"","Allocatable tool categories:",""];for(const o of e)t.push(`[${o.category}] ${o.kind} (${o.tools.length}):`),t.push(` ${o.tools.join(", ")}`);return t.push(""),t.push("Usage:"),t.push(`- tools: ["${d}"] \u2192 all core default tools`),t.push(`- tools: ["<category>"] \u2192 all tools in that category (e.g. ["${e[0].category}"])`),t.push(`- tools: ["<category>.<tool>"] \u2192 exactly that tool (e.g. ["${e[0].category}.${e[0].tools[0]??"tool"}"])`),t.push('- elements combine by union, e.g. ["@core", "browser"]'),t.push(`- omit tools \u2192 read-only mode (\u2261 ["${c}"])`),{title:"allocatable tools",output:t.join(`
83
- `),metadata:{categories:e.length}}}catch(e){return{title:"list_sub_agent_tools error",output:`Failed to list allocatable tools: ${e instanceof Error?e.message:String(e)}`,metadata:{error:!0}}}}}}function I(n){return[m(n),f(n),w(n),$(n),x(n)]}export{$ as createAbortSubAgentTool,w as createGetSubAgentStatusTool,x as createListSubAgentToolsTool,f as createListSubAgentsTool,m as createSubAgentTool,I as createSubAgentTools};
86
+ equals the current agent's tool set).`;function x(a){return{kind:"builtin",toolName:"list_sub_agent_tools",exposedName:"list_sub_agent_tools",description:T,inputSchema:{type:"object",properties:{}},async execute(n){try{const o=await a.listSubAgentToolCatalog();if(o.length===0)return{title:"allocatable tools",output:"No allocatable tools found (tool catalog is empty).",metadata:{categories:0}};const t=["Sub-agent types:"," explore \u2014 read-only set (default category minus write tools + memory MCP tools)"," core \u2014 all core default tools (no suites/MCP)"," custom \u2014 allocate specific tools via 'tools' parameter","","Allocatable tool categories:",""];for(const e of o)t.push(`[${e.category}] ${e.kind} (${e.tools.length}):`),t.push(` ${e.tools.join(", ")}`);return t.push(""),t.push("Usage:"),t.push('- subagent_type: "explore" \u2192 read-only mode (default)'),t.push('- subagent_type: "core" \u2192 all core default tools'),t.push('- subagent_type: "custom", tools: ["<category>"] \u2192 all tools in that category'),t.push('- subagent_type: "custom", tools: ["<category>.<tool>"] \u2192 exactly that tool'),t.push('- tools elements combine by union, e.g. ["browser", "default.read_file"]'),{title:"allocatable tools",output:t.join(`
87
+ `),metadata:{categories:o.length}}}catch(o){return{title:"list_sub_agent_tools error",output:`Failed to list allocatable tools: ${o instanceof Error?o.message:String(o)}`,metadata:{error:!0}}}}}}function $(a){return[h(a),f(a),y(a),S(a),x(a)]}export{S as createAbortSubAgentTool,y as createGetSubAgentStatusTool,x as createListSubAgentToolsTool,f as createListSubAgentsTool,h as createSubAgentTool,$ as createSubAgentTools};
84
88
 
@@ -1,6 +1,6 @@
1
1
 
2
2
 
3
- export type SubAgentType = "@explore" | "@core" | "custom";
3
+ export type SubAgentType = "explore" | "core" | "custom";
4
4
 
5
5
  export type SubAgentStatus = "pending" | "running" | "completed" | "failed" | "cancelled";
6
6
 
@@ -48,16 +48,16 @@ export declare const EXPLORE_READONLY_DENIED_TOOLS: Set<string>;
48
48
 
49
49
  export declare const SUB_AGENT_ALLOWED_MCP_TOOLS: Set<string>;
50
50
 
51
- export declare const PRESET_EXPLORE = "@explore";
51
+ export declare const PRESET_EXPLORE = "explore";
52
52
 
53
- export declare const PRESET_CORE = "@core";
53
+ export declare const PRESET_CORE = "core";
54
54
 
55
55
  export declare const TYPE_LABEL_CUSTOM = "custom";
56
56
 
57
57
  export declare class ToolAllocationError extends Error {
58
58
  }
59
59
 
60
- export declare function deriveTypeLabel(rawTokens: readonly string[]): SubAgentType;
60
+ export declare function expandPreset(preset: SubAgentType, catalog: readonly ToolCatalogEntry[]): string[];
61
61
 
62
62
  export interface ResolvedToolAllocation {
63
63
 
@@ -66,4 +66,4 @@ export interface ResolvedToolAllocation {
66
66
  label: SubAgentType;
67
67
  }
68
68
 
69
- export declare function resolveToolAllocation(raw: readonly string[], catalog: readonly ToolCatalogEntry[]): ResolvedToolAllocation;
69
+ export declare function resolveToolAllocation(subagentType: SubAgentType, rawTools: readonly string[], catalog: readonly ToolCatalogEntry[]): ResolvedToolAllocation;
@@ -1,2 +1,2 @@
1
- const i="default",h=new Set(["sub_agent","list_sub_agents","get_sub_agent_status","abort_sub_agent","list_sub_agent_tools"]),g=new Set(["poll_message","get_message","send_group","send_private","create_task_instance_comment","submit_task_result","start_task_rollback","finish_task_rollback","reject_task","terminate_task","hire_colleague","hire_colleagues_batch","abandon_memory_update"]);function p(e){return e.kind==="mcp"&&g.has(e.toolName)}function S(e,r){if(r.length===0)return[...e];const n=new Set(e.map(t=>t.exposedName)),o=[...e];for(const t of r)n.has(t.exposedName)||(n.add(t.exposedName),o.push(t));return o}function x(e){return e.kind==="mcp"?e.serverName||"mcp":e.category||i}function O(e,r){return!r||e.length===0?[...e]:e.map(n=>{if(n.kind!=="builtin")return n;const t=n.execute;return typeof t!="function"?n:{...n,execute:(s,c)=>{const a=s&&typeof s=="object"&&s.agentId==null?{...s,agentId:r}:s;return t(a,c)}}})}function y(e){if(e.kind==="mcp"){const t=e.serverName||"mcp",s=[`${t}.${e.toolName}`];return e.exposedName&&e.exposedName!==e.toolName&&s.push(`${t}.${e.exposedName}`),s}const r=e.category||i,n=[`${r}.${e.exposedName}`],o=`${r}_`;return r!==i&&e.exposedName.startsWith(o)&&n.push(`${r}.${e.exposedName.slice(o.length)}`),n}function m(e){let r=e.trim();for(;r.length>0&&(r.endsWith("*")||r.endsWith("."));)r=r.slice(0,-1).trimEnd();return r}function w(e,r){if(p(e))return!1;const n=r.map(t=>typeof t=="string"?m(t):"").filter(t=>t.length>0);if(n.length===0)return!1;const o=y(e);return n.some(t=>o.some(s=>s===t||s.startsWith(`${t}.`)))}function L(e){const r=[],n=new Map;for(const o of e){if(h.has(o.exposedName)||p(o))continue;const t=x(o);let s=n.get(t);s||(s={kind:o.kind,names:[],seen:new Set},n.set(t,s),r.push(t));const c=E(o);s.seen.has(c)||(s.seen.add(c),s.names.push(c))}return r.sort((o,t)=>o===i?-1:t===i?1:o<t?-1:o>t?1:0).map(o=>{const t=n.get(o);return{category:o,kind:t.kind,tools:t.names}})}function E(e){if(e.kind==="mcp")return e.toolName;const r=e.category||i,n=`${r}_`;return r!==i&&e.exposedName.startsWith(n)?e.exposedName.slice(n.length):e.exposedName}const N=new Set(["write_file","edit_file","delete_file"]),A=new Set(["create_memory","read_memory","update_memory","delete_memory","search_memory","list_memories","get_memory_stats","list_memories_by_file","memory_recurrence","memory_recurrence_complete"]),l="@explore",u="@core",T="custom",_={explore:l,general:u};class d extends Error{}function $(e){const r=e.map(n=>n.trim()).filter(n=>n.length>0).map(n=>_[n]??n);return r.length===0||r.every(n=>n===l)?l:r.every(n=>n===u)?u:T}function b(e,r){if(e===u)return[i];const n=[],o=r.find(t=>t.category===i);if(o)for(const t of o.tools)N.has(t)||n.push(`${i}.${t}`);for(const t of r)if(t.kind==="mcp")for(const s of t.tools)A.has(s)&&n.push(`${t.category}.${s}`);return n}function k(e,r,n){for(const o of n){if(o.category===r)return;for(const t of o.tools){const s=`${o.category}.${t}`;if(s===r||s.startsWith(`${r}.`))return}}throw new d(`Unknown tool allocation '${e}'. Allocatable categories: ${n.map(o=>o.category).join(", ")}. Call list_sub_agent_tools to see all allocatable categories and tool paths.`)}function C(e,r){const n=e.map(a=>typeof a=="string"?a.trim():"").filter(a=>a.length>0),o=n.map(a=>_[a]??a);o.length===0&&o.push(l);const t=[];for(const a of o){if(a.startsWith("@")){if(a!==l&&a!==u)throw new d(`Unknown tool preset '${a}'. Available presets: ${l} (read-only default), ${u} (all core default tools).`);t.push(...b(a,r));continue}const f=m(a);k(a,f,r),t.push(f)}const s=new Set,c=[];for(const a of t)a.length===0||s.has(a)||(s.add(a),c.push(a));return{patterns:c,label:$(n)}}export{g as AGENT_IDENTITY_MCP_RESTRICTED_TOOLS,i as DEFAULT_TOOL_CATEGORY,N as EXPLORE_READONLY_DENIED_TOOLS,u as PRESET_CORE,l as PRESET_EXPLORE,A as SUB_AGENT_ALLOWED_MCP_TOOLS,h as SUB_AGENT_MANAGEMENT_TOOL_NAMES,T as TYPE_LABEL_CUSTOM,d as ToolAllocationError,L as buildToolCatalog,$ as deriveTypeLabel,p as isAgentIdentityRestrictedTool,w as matchesToolAllocation,S as mergeAllocatableTools,m as normalizeAllocationPattern,O as rebindDefaultAgentId,C as resolveToolAllocation,y as toolAllocationAliases,x as toolAllocationCategory};
1
+ const i="default",p=new Set(["sub_agent","list_sub_agents","get_sub_agent_status","abort_sub_agent","list_sub_agent_tools"]),_=new Set(["poll_message","get_message","send_group","send_private","create_task_instance_comment","submit_task_result","start_task_rollback","finish_task_rollback","reject_task","terminate_task","hire_colleague","hire_colleagues_batch","abandon_memory_update"]);function m(e){return e.kind==="mcp"&&_.has(e.toolName)}function k(e,n){if(n.length===0)return[...e];const r=new Set(e.map(t=>t.exposedName)),o=[...e];for(const t of n)r.has(t.exposedName)||(r.add(t.exposedName),o.push(t));return o}function d(e){return e.kind==="mcp"?e.serverName||"mcp":e.category||i}function T(e,n){return!n||e.length===0?[...e]:e.map(r=>{if(r.kind!=="builtin")return r;const t=r.execute;return typeof t!="function"?r:{...r,execute:(s,c)=>{const a=s&&typeof s=="object"&&s.agentId==null?{...s,agentId:n}:s;return t(a,c)}}})}function h(e){if(e.kind==="mcp"){const t=e.serverName||"mcp",s=[`${t}.${e.toolName}`];return e.exposedName&&e.exposedName!==e.toolName&&s.push(`${t}.${e.exposedName}`),s}const n=e.category||i,r=[`${n}.${e.exposedName}`],o=`${n}_`;return n!==i&&e.exposedName.startsWith(o)&&r.push(`${n}.${e.exposedName.slice(o.length)}`),r}function f(e){let n=e.trim();for(;n.length>0&&(n.endsWith("*")||n.endsWith("."));)n=n.slice(0,-1).trimEnd();return n}function b(e,n){if(m(e))return!1;const r=n.map(t=>typeof t=="string"?f(t):"").filter(t=>t.length>0);if(r.length===0)return!1;const o=h(e);return r.some(t=>o.some(s=>s===t||s.startsWith(`${t}.`)))}function w(e){const n=[],r=new Map;for(const o of e){if(p.has(o.exposedName)||m(o))continue;const t=d(o);let s=r.get(t);s||(s={kind:o.kind,names:[],seen:new Set},r.set(t,s),n.push(t));const c=x(o);s.seen.has(c)||(s.seen.add(c),s.names.push(c))}return n.sort((o,t)=>o===i?-1:t===i?1:o<t?-1:o>t?1:0).map(o=>{const t=r.get(o);return{category:o,kind:t.kind,tools:t.names}})}function x(e){if(e.kind==="mcp")return e.toolName;const n=e.category||i,r=`${n}_`;return n!==i&&e.exposedName.startsWith(r)?e.exposedName.slice(r.length):e.exposedName}const g=new Set(["write_file","edit_file","delete_file"]),y=new Set(["create_memory","read_memory","update_memory","delete_memory","search_memory","list_memories","get_memory_stats","list_memories_by_file","memory_recurrence","memory_recurrence_complete"]),E="explore",N="core",O="custom";class l extends Error{}function A(e,n){if(e==="core")return[i];const r=[],o=n.find(t=>t.category===i);if(o)for(const t of o.tools)g.has(t)||r.push(`${i}.${t}`);for(const t of n)if(t.kind==="mcp")for(const s of t.tools)y.has(s)&&r.push(`${t.category}.${s}`);return r}function $(e,n,r){for(const o of r){if(o.category===n)return;for(const t of o.tools){const s=`${o.category}.${t}`;if(s===n||s.startsWith(`${n}.`))return}}throw e.startsWith("@")?new l(`Unknown tool preset '${e}'. Presets are now specified via the 'subagent_type' parameter ('${E}', '${N}', or 'custom'); '@explore'/'@core' are no longer valid in 'tools'.`):new l(`Unknown tool allocation '${e}'. Allocatable categories: ${r.map(o=>o.category).join(", ")}. Call list_sub_agent_tools to see all allocatable categories and tool paths.`)}function S(e,n,r){if(e==="custom"&&n.length===0)throw new l("'tools' parameter is required when subagent_type is 'custom'. Call list_sub_agent_tools to see all allocatable categories and tool paths.");if(e==="explore"||e==="core")return{patterns:A(e,r),label:e};const o=n.map(a=>typeof a=="string"?a.trim():"").filter(a=>a.length>0),t=[];for(const a of o){const u=f(a);$(a,u,r),t.push(u)}const s=new Set,c=[];for(const a of t)a.length===0||s.has(a)||(s.add(a),c.push(a));return{patterns:c,label:e}}export{_ as AGENT_IDENTITY_MCP_RESTRICTED_TOOLS,i as DEFAULT_TOOL_CATEGORY,g as EXPLORE_READONLY_DENIED_TOOLS,N as PRESET_CORE,E as PRESET_EXPLORE,y as SUB_AGENT_ALLOWED_MCP_TOOLS,p as SUB_AGENT_MANAGEMENT_TOOL_NAMES,O as TYPE_LABEL_CUSTOM,l as ToolAllocationError,w as buildToolCatalog,A as expandPreset,m as isAgentIdentityRestrictedTool,b as matchesToolAllocation,k as mergeAllocatableTools,f as normalizeAllocationPattern,T as rebindDefaultAgentId,S as resolveToolAllocation,h as toolAllocationAliases,d as toolAllocationCategory};
2
2
 
@@ -57,7 +57,7 @@ export interface ACodeSkillGroup {
57
57
  exists: boolean;
58
58
  skills: ACodeSkillMetadata[];
59
59
  }
60
- export type ACodeEventType = "session_started" | "startup_phase" | "ai_request" | "thinking_delta" | "assistant_delta" | "command_output" | "command_status" | "mcp_status" | "skill_status" | "warning" | "turn_complete" | "session_complete" | "context_compaction" | "question_request" | "error" | "background_command_completed";
60
+ export type ACodeEventType = "session_started" | "startup_phase" | "ai_request" | "thinking_delta" | "assistant_delta" | "command_output" | "command_status" | "mcp_status" | "skill_status" | "warning" | "turn_complete" | "session_complete" | "context_compaction" | "question_request" | "tool_permission_request" | "error" | "background_command_completed";
61
61
  export interface ACodeEvent {
62
62
  type: ACodeEventType;
63
63
  sessionId: string;
@@ -132,6 +132,8 @@ export interface ACodeRuntimeConfig {
132
132
 
133
133
  onFileChange?: import("./built-in-file-tools.js").OnAgentFileChange;
134
134
 
135
+ toolPermissionPolicy?: import("./built-in-file-tools.js").ToolPermissionPolicy;
136
+
135
137
  extraBuiltInTools?: import("./built-in-file-tools.js").ACodeBuiltInTool[];
136
138
 
137
139
  subAgentSuiteTools?: import("./built-in-file-tools.js").ACodeBuiltInTool[];
@@ -4,6 +4,10 @@ export interface McpToolResponse {
4
4
  error?: string;
5
5
  [key: string]: unknown;
6
6
  }
7
+
8
+ export declare function normalizeServerHttpBase(value: unknown, options?: {
9
+ fromAgentWebSocketUrl?: boolean;
10
+ }): string | undefined;
7
11
  export declare class HttpClient {
8
12
  private serverConfig;
9
13
  private mcpHttpUrl;
@@ -1,2 +1,2 @@
1
- import{logger as o}from"./logger.js";import{meetingDebugLog as h}from"./meeting-debug-log.js";const w=12e4,g=5e3,T=3e4,d=1e3;function p(l){const e=l.trim();return e?e.length<=d?e:`${e.slice(0,d)}...(truncated)`:""}function y(l){return l.replace(/^((?:https?|wss?):\/\/(?:\[[^\]]+\]|[^/:?#]+):\d+):\d+(?=\/|$)/i,"$1")}function C(l){const e=l.toLowerCase();return e==="localhost"||e==="::1"||e==="[::1]"?"127.0.0.1":e}function m(l,e={}){const r=String(l||"").trim();if(!r)return;const s=y(r);try{const t=new URL(s);t.protocol==="ws:"?t.protocol="http:":t.protocol==="wss:"?t.protocol="https:":t.protocol=t.protocol.toLowerCase(),t.hostname=C(t.hostname);const n=e.fromAgentWebSocketUrl?t.pathname.replace(/\/ws\/agent\/?$/,""):t.pathname;return t.pathname=n.includes("/mcp/call")?n:`${n.replace(/\/$/,"")}/mcp/call`,t.search="",t.hash="",t.toString()}catch{const t=(e.fromAgentWebSocketUrl?s.replace(/\/ws\/agent\/?$/i,""):s).replace(/\/+$/,"");return t.endsWith("/mcp/call")?t:`${t}/mcp/call`}}const R=6e5;class E{serverConfig;mcpHttpUrl;tokenRefreshPromise=null;constructor(e){this.serverConfig=e,this.mcpHttpUrl=this.resolveMcpHttpUrl()}async callTool(e,r){await this.ensureRuntimeAccessToken();const s=Date.now()+this.resolveRetryMaxAccumulatedMs();let t=0;for(;;){t++;let n;try{n=await this.executeToolRequest(e,r)}catch(a){if(Date.now()<s&&this.isTransientError(a)){await this.delayForRetry(s,e,t);continue}throw o.warn("[HttpClient] MCP tool %s \u8BF7\u6C42\u4E0D\u53EF\u6062\u590D\u5F02\u5E38 (attempt=%s): %s",e,t,a instanceof Error?a.message:String(a)),a}if(n.status===401){if(o.warn(`[HttpClient] MCP Tool ${e} \u8FD4\u56DE 401\uFF0C\u5C1D\u8BD5\u5411 bridge \u5237\u65B0 token`),await this.tryRefreshToken(r)){let c;try{c=await this.executeToolRequest(e,r)}catch(f){if(Date.now()<s&&this.isTransientError(f)){await this.delayForRetry(s,e,t);continue}throw o.warn("[HttpClient] MCP tool %s 401\u91CD\u8BD5\u5F02\u5E38 (attempt=%s): %s",e,t,f instanceof Error?f.message:String(f)),f}if(!c.ok){if(Date.now()<s&&this.isRetryableHttpStatus(c.status)){await this.delayForRetry(s,e,t);continue}const f=typeof c.text=="function"?p(await c.text().catch(()=>"")):"";throw new Error(`MCP tool ${e} call failed: ${c.status} ${c.statusText}${f?` - ${f}`:""}`)}const u=await c.json();if(typeof u.error=="string"&&u.error.trim().length>0)throw new Error(`MCP tool ${e} failed: ${u.error}`);return u}o.warn("[HttpClient] token \u5237\u65B0\u5931\u8D25\u6216\u65E0\u65B0 token\uFF0C\u8FD4\u56DE\u539F\u59CB 401 \u9519\u8BEF")}if(!n.ok){if(Date.now()<s&&this.isRetryableHttpStatus(n.status)){await this.delayForRetry(s,e,t);continue}const a=typeof n.text=="function"?p(await n.text().catch(()=>"")):"";throw new Error(`MCP tool ${e} call failed: ${n.status} ${n.statusText}${a?` - ${a}`:""}`)}const i=await n.json();if(typeof i.error=="string"&&i.error.trim().length>0)throw new Error(`MCP tool ${e} failed: ${i.error}`);return i}}async fetchRuntimeFeatures(){await this.ensureRuntimeAccessToken();const e=this.mcpHttpUrl.replace(/\/mcp\/call(\/)?$/,"/mcp/features$1");let r;try{r=await fetch(e,{method:"POST",headers:this.buildRequestHeaders(),body:JSON.stringify({})})}catch(t){throw o.warn("[HttpClient] \u67E5\u8BE2\u80FD\u529B\u5F00\u5173\u8BF7\u6C42\u5931\u8D25: %s",t instanceof Error?t.message:String(t)),new Error(`fetch runtime features failed: ${t instanceof Error?t.message:String(t)}`)}if(!r.ok)throw o.warn("[HttpClient] \u67E5\u8BE2\u80FD\u529B\u5F00\u5173\u5931\u8D25: status=%s, statusText=%s",r.status,r.statusText),new Error(`fetch runtime features failed: ${r.status} ${r.statusText}`);const s=await r.json();return!s||typeof s.features!="object"||s.features===null?{}:s.features}async callToolOnce(e,r,s=R){await this.ensureRuntimeAccessToken(),o.info("[HttpClient] callToolOnce \u5F00\u59CB: tool=%s, timeoutMs=%d, url=%s, agentId=%s",e,s,this.mcpHttpUrl,String(r?.agentId??"")),e==="poll_message"&&h("http.callToolOnce.start",`tool=${e} timeoutMs=${s} preemptiveJoinWaitMs=${String(r?.preemptiveJoinWaitMs??"-")}`);const t=c=>fetch(this.mcpHttpUrl,{method:"POST",headers:this.buildRequestHeaders(),body:JSON.stringify({tool:e,arguments:r}),signal:c}),n=Date.now();let i=await this.singleFetchWithTimeout(t,s,e);if(o.info("[HttpClient] callToolOnce \u6536\u5230\u54CD\u5E94: tool=%s, status=%d, \u8017\u65F6=%dms",e,i.status,Date.now()-n),e==="poll_message"&&h("http.callToolOnce.response",`status=${i.status} elapsedMs=${Date.now()-n}`),i.status===401&&(o.warn(`[HttpClient] MCP Tool ${e} \u8FD4\u56DE 401\uFF0C\u5C1D\u8BD5\u5411 bridge \u5237\u65B0 token`),await this.tryRefreshToken(r)&&(i=await this.singleFetchWithTimeout(t,s,e),o.info("[HttpClient] callToolOnce token \u5237\u65B0\u540E\u91CD\u8BD5\u6536\u5230\u54CD\u5E94: tool=%s, status=%d, \u7D2F\u8BA1\u8017\u65F6=%dms",e,i.status,Date.now()-n))),!i.ok){const c=typeof i.text=="function"?p(await this.readTextWithTimeout(i,s,e).catch(()=>"")):"";throw o.info("[HttpClient] callToolOnce \u975E 2xx \u54CD\u5E94: tool=%s, status=%d, body=%s",e,i.status,c||"(\u7A7A)"),new Error(`MCP tool ${e} call failed: ${i.status} ${i.statusText}${c?` - ${c}`:""}`)}const a=await this.parseJsonWithTimeout(i,s,e);if(o.info("[HttpClient] callToolOnce \u5B8C\u6210: tool=%s, \u603B\u8017\u65F6=%dms, error=%s",e,Date.now()-n,typeof a.error=="string"?a.error:"(\u65E0)"),e==="poll_message"){const c=Array.isArray(a.messages)?a.messages:[];h("http.callToolOnce.parsed",`totalElapsedMs=${Date.now()-n} serverMessages=${c.length} `+JSON.stringify(c.map(u=>({msgId:u.msgId,channel:u.channel,sender:u.senderId}))))}if(typeof a.error=="string"&&a.error.trim().length>0)throw new Error(`MCP tool ${e} failed: ${a.error}`);return a}async readTextWithTimeout(e,r,s){if(r<=0)return await e.text();let t;try{return await Promise.race([e.text(),new Promise((n,i)=>{t=setTimeout(()=>i(new Error(`MCP tool ${s} timed out after ${r}ms`)),r)})])}finally{t!==void 0&&clearTimeout(t)}}async parseJsonWithTimeout(e,r,s){if(r<=0)return await e.json();let t;try{return await Promise.race([e.json(),new Promise((n,i)=>{t=setTimeout(()=>i(new Error(`MCP tool ${s} timed out after ${r}ms`)),r)})])}finally{t!==void 0&&clearTimeout(t)}}async singleFetchWithTimeout(e,r,s){const t=new AbortController;let n;r>0&&(n=setTimeout(()=>t.abort(),r));try{return await e(t.signal)}catch(i){throw t.signal.aborted?(s==="poll_message"&&h("http.callToolOnce.timeout",`timeoutMs=${r} \u670D\u52A1\u7AEF\u53EF\u80FD\u4ECD\u5728\u6267\u884C\u540C\u4E00\u8BF7\u6C42\uFF08Callable \u5360\u7EBF\u81F3\u9884\u7B97\u7ED3\u675F\uFF09`),new Error(`MCP tool ${s} timed out after ${r}ms`)):i}finally{n!==void 0&&clearTimeout(n)}}async executeToolRequest(e,r){return await this.fetchWithTimeout(this.mcpHttpUrl,{method:"POST",headers:this.buildRequestHeaders(),body:JSON.stringify({tool:e,arguments:r})},`MCP tool ${e}`)}async fetchWithTimeout(e,r,s){const t=this.resolveRequestTimeoutMs(),n=new AbortController,i=setTimeout(()=>n.abort(),t);try{return await fetch(e,{...r,signal:n.signal})}catch(a){throw n.signal.aborted?new Error(`${s} timed out after ${t}ms`):a}finally{clearTimeout(i)}}resolveRequestTimeoutMs(){const e=this.serverConfig.mcpHttpRequestTimeoutMs;return typeof e=="number"&&Number.isFinite(e)&&e>0?e:w}resolveRetryIntervalMs(){const e=this.serverConfig.mcpRetryIntervalMs;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:g}resolveRetryMaxAccumulatedMs(){const e=this.serverConfig.mcpRetryMaxAccumulatedMs;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:T}isTransientError(e){if(!(e instanceof Error))return!1;const r=e.message;return!!(/timed out after \d+ms/.test(r)||/fetch failed/i.test(r)||/network/i.test(r)||/ECONNREFUSED/i.test(r)||/ECONNRESET/i.test(r))}isRetryableHttpStatus(e){return e>=500||e===429}async delayForRetry(e,r,s){const t=e-Date.now(),n=Math.min(this.resolveRetryIntervalMs(),Math.max(0,t));o.warn(`[HttpClient] MCP tool ${r} \u8BF7\u6C42\u5931\u8D25\uFF0C${n}ms \u540E\u91CD\u8BD5 (\u7B2C${s}\u6B21)`),n>0&&await new Promise(i=>setTimeout(i,n))}buildRequestHeaders(){const e={"Content-Type":"application/json"};return this.serverConfig.runtimeAccessToken&&(e["X-Runtime-Token"]=this.serverConfig.runtimeAccessToken,e.Authorization=`Bearer ${this.serverConfig.runtimeAccessToken}`),e}async ensureRuntimeAccessToken(){if(this.serverConfig.runtimeAccessToken||!this.serverConfig.runtimeBridgeBaseUrl){o.info("[HttpClient] ensureRuntimeAccessToken: tokenLen=%d, bridgeBaseUrl=%s",(this.serverConfig.runtimeAccessToken||"").length,this.serverConfig.runtimeBridgeBaseUrl||"(\u7A7A)");return}throw new Error("runtimeAccessToken is required; MCP nodes must claim a session token from launch binding")}async tryRefreshToken(e){if(this.tokenRefreshPromise)return this.tokenRefreshPromise;this.tokenRefreshPromise=this.doRefreshToken(e);try{return await this.tokenRefreshPromise}finally{this.tokenRefreshPromise=null}}async doRefreshToken(e){const r=this.serverConfig.runtimeBridgeBaseUrl;if(!r)return o.warn("[HttpClient] \u65E0 runtimeBridgeBaseUrl\uFF0C\u65E0\u6CD5\u5237\u65B0 token"),!1;const s=String(e?.agentId||"").trim();if(!s)return o.warn("[HttpClient] \u65E0 agentId\uFF0C\u65E0\u6CD5\u5237\u65B0 token"),!1;try{const t=await fetch(`${r}/runtime/binding/refresh-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:s,currentToken:this.serverConfig.runtimeAccessToken||""})});if(!t.ok)return o.warn(`[HttpClient] bridge refresh-token \u8FD4\u56DE ${t.status}\uFF0C\u65E0\u6CD5\u5237\u65B0`),!1;const i=(await t.json()).runtimeAccessToken;return i?i===this.serverConfig.runtimeAccessToken?!1:(this.serverConfig.runtimeAccessToken=i,o.info("[HttpClient] runtimeAccessToken \u5DF2\u901A\u8FC7 bridge refresh \u66F4\u65B0"),!0):(o.warn("[HttpClient] bridge \u672A\u8FD4\u56DE\u65B0 token"),!1)}catch(t){return o.warn("[HttpClient] \u5237\u65B0 token \u5931\u8D25: %s",t instanceof Error?t.message:String(t)),t instanceof Error&&t.stack&&o.warn("[HttpClient] \u5237\u65B0 token \u5F02\u5E38\u5806\u6808:",t.stack),!1}}async refreshRuntimeAccessToken(e){return this.tryRefreshToken({agentId:e})}resolveMcpHttpUrl(){const e=this.serverConfig.mcpHttpUrl;if(e&&e.trim().length>0){const s=m(e);if(s)return s}const r=m(this.serverConfig.serverUrl,{fromAgentWebSocketUrl:!0});return r||this.serverConfig.serverUrl}getMcpHttpUrl(){return this.mcpHttpUrl}}export{E as HttpClient};
1
+ import{logger as o}from"./logger.js";import{meetingDebugLog as h}from"./meeting-debug-log.js";const w=12e4,g=5e3,T=3e4,d=1e3;function p(l){const e=l.trim();return e?e.length<=d?e:`${e.slice(0,d)}...(truncated)`:""}function y(l){return l.replace(/^((?:https?|wss?):\/\/(?:\[[^\]]+\]|[^/:?#]+):\d+):\d+(?=\/|$)/i,"$1")}function C(l){const e=l.toLowerCase();return e==="localhost"||e==="::1"||e==="[::1]"?"127.0.0.1":e}function m(l,e={}){const r=R(l,e);if(r)try{const s=new URL(r);return s.pathname=s.pathname.includes("/mcp/call")?s.pathname:`${s.pathname.replace(/\/$/,"")}/mcp/call`,s.search="",s.hash="",s.toString()}catch{return r.endsWith("/mcp/call")?r:`${r}/mcp/call`}}function R(l,e={}){const r=String(l||"").trim();if(!r)return;const s=y(r);try{const t=new URL(s);t.protocol==="ws:"?t.protocol="http:":t.protocol==="wss:"?t.protocol="https:":t.protocol=t.protocol.toLowerCase(),t.hostname=C(t.hostname);const n=e.fromAgentWebSocketUrl?t.pathname.replace(/\/ws\/agent\/?$/,""):t.pathname;return t.pathname=n,t.search="",t.hash="",t.toString().replace(/\/+$/,"")}catch{return(e.fromAgentWebSocketUrl?s.replace(/\/ws\/agent\/?$/i,""):s).replace(/\/+$/,"")||void 0}}const $=6e5;class H{serverConfig;mcpHttpUrl;tokenRefreshPromise=null;constructor(e){this.serverConfig=e,this.mcpHttpUrl=this.resolveMcpHttpUrl()}async callTool(e,r){await this.ensureRuntimeAccessToken();const s=Date.now()+this.resolveRetryMaxAccumulatedMs();let t=0;for(;;){t++;let n;try{n=await this.executeToolRequest(e,r)}catch(a){if(Date.now()<s&&this.isTransientError(a)){await this.delayForRetry(s,e,t);continue}throw o.warn("[HttpClient] MCP tool %s \u8BF7\u6C42\u4E0D\u53EF\u6062\u590D\u5F02\u5E38 (attempt=%s): %s",e,t,a instanceof Error?a.message:String(a)),a}if(n.status===401){if(o.warn(`[HttpClient] MCP Tool ${e} \u8FD4\u56DE 401\uFF0C\u5C1D\u8BD5\u5411 bridge \u5237\u65B0 token`),await this.tryRefreshToken(r)){let c;try{c=await this.executeToolRequest(e,r)}catch(f){if(Date.now()<s&&this.isTransientError(f)){await this.delayForRetry(s,e,t);continue}throw o.warn("[HttpClient] MCP tool %s 401\u91CD\u8BD5\u5F02\u5E38 (attempt=%s): %s",e,t,f instanceof Error?f.message:String(f)),f}if(!c.ok){if(Date.now()<s&&this.isRetryableHttpStatus(c.status)){await this.delayForRetry(s,e,t);continue}const f=typeof c.text=="function"?p(await c.text().catch(()=>"")):"";throw new Error(`MCP tool ${e} call failed: ${c.status} ${c.statusText}${f?` - ${f}`:""}`)}const u=await c.json();if(typeof u.error=="string"&&u.error.trim().length>0)throw new Error(`MCP tool ${e} failed: ${u.error}`);return u}o.warn("[HttpClient] token \u5237\u65B0\u5931\u8D25\u6216\u65E0\u65B0 token\uFF0C\u8FD4\u56DE\u539F\u59CB 401 \u9519\u8BEF")}if(!n.ok){if(Date.now()<s&&this.isRetryableHttpStatus(n.status)){await this.delayForRetry(s,e,t);continue}const a=typeof n.text=="function"?p(await n.text().catch(()=>"")):"";throw new Error(`MCP tool ${e} call failed: ${n.status} ${n.statusText}${a?` - ${a}`:""}`)}const i=await n.json();if(typeof i.error=="string"&&i.error.trim().length>0)throw new Error(`MCP tool ${e} failed: ${i.error}`);return i}}async fetchRuntimeFeatures(){await this.ensureRuntimeAccessToken();const e=this.mcpHttpUrl.replace(/\/mcp\/call(\/)?$/,"/mcp/features$1");let r;try{r=await fetch(e,{method:"POST",headers:this.buildRequestHeaders(),body:JSON.stringify({})})}catch(t){throw o.warn("[HttpClient] \u67E5\u8BE2\u80FD\u529B\u5F00\u5173\u8BF7\u6C42\u5931\u8D25: %s",t instanceof Error?t.message:String(t)),new Error(`fetch runtime features failed: ${t instanceof Error?t.message:String(t)}`)}if(!r.ok)throw o.warn("[HttpClient] \u67E5\u8BE2\u80FD\u529B\u5F00\u5173\u5931\u8D25: status=%s, statusText=%s",r.status,r.statusText),new Error(`fetch runtime features failed: ${r.status} ${r.statusText}`);const s=await r.json();return!s||typeof s.features!="object"||s.features===null?{}:s.features}async callToolOnce(e,r,s=$){await this.ensureRuntimeAccessToken(),o.info("[HttpClient] callToolOnce \u5F00\u59CB: tool=%s, timeoutMs=%d, url=%s, agentId=%s",e,s,this.mcpHttpUrl,String(r?.agentId??"")),e==="poll_message"&&h("http.callToolOnce.start",`tool=${e} timeoutMs=${s} preemptiveJoinWaitMs=${String(r?.preemptiveJoinWaitMs??"-")}`);const t=c=>fetch(this.mcpHttpUrl,{method:"POST",headers:this.buildRequestHeaders(),body:JSON.stringify({tool:e,arguments:r}),signal:c}),n=Date.now();let i=await this.singleFetchWithTimeout(t,s,e);if(o.info("[HttpClient] callToolOnce \u6536\u5230\u54CD\u5E94: tool=%s, status=%d, \u8017\u65F6=%dms",e,i.status,Date.now()-n),e==="poll_message"&&h("http.callToolOnce.response",`status=${i.status} elapsedMs=${Date.now()-n}`),i.status===401&&(o.warn(`[HttpClient] MCP Tool ${e} \u8FD4\u56DE 401\uFF0C\u5C1D\u8BD5\u5411 bridge \u5237\u65B0 token`),await this.tryRefreshToken(r)&&(i=await this.singleFetchWithTimeout(t,s,e),o.info("[HttpClient] callToolOnce token \u5237\u65B0\u540E\u91CD\u8BD5\u6536\u5230\u54CD\u5E94: tool=%s, status=%d, \u7D2F\u8BA1\u8017\u65F6=%dms",e,i.status,Date.now()-n))),!i.ok){const c=typeof i.text=="function"?p(await this.readTextWithTimeout(i,s,e).catch(()=>"")):"";throw o.info("[HttpClient] callToolOnce \u975E 2xx \u54CD\u5E94: tool=%s, status=%d, body=%s",e,i.status,c||"(\u7A7A)"),new Error(`MCP tool ${e} call failed: ${i.status} ${i.statusText}${c?` - ${c}`:""}`)}const a=await this.parseJsonWithTimeout(i,s,e);if(o.info("[HttpClient] callToolOnce \u5B8C\u6210: tool=%s, \u603B\u8017\u65F6=%dms, error=%s",e,Date.now()-n,typeof a.error=="string"?a.error:"(\u65E0)"),e==="poll_message"){const c=Array.isArray(a.messages)?a.messages:[];h("http.callToolOnce.parsed",`totalElapsedMs=${Date.now()-n} serverMessages=${c.length} `+JSON.stringify(c.map(u=>({msgId:u.msgId,channel:u.channel,sender:u.senderId}))))}if(typeof a.error=="string"&&a.error.trim().length>0)throw new Error(`MCP tool ${e} failed: ${a.error}`);return a}async readTextWithTimeout(e,r,s){if(r<=0)return await e.text();let t;try{return await Promise.race([e.text(),new Promise((n,i)=>{t=setTimeout(()=>i(new Error(`MCP tool ${s} timed out after ${r}ms`)),r)})])}finally{t!==void 0&&clearTimeout(t)}}async parseJsonWithTimeout(e,r,s){if(r<=0)return await e.json();let t;try{return await Promise.race([e.json(),new Promise((n,i)=>{t=setTimeout(()=>i(new Error(`MCP tool ${s} timed out after ${r}ms`)),r)})])}finally{t!==void 0&&clearTimeout(t)}}async singleFetchWithTimeout(e,r,s){const t=new AbortController;let n;r>0&&(n=setTimeout(()=>t.abort(),r));try{return await e(t.signal)}catch(i){throw t.signal.aborted?(s==="poll_message"&&h("http.callToolOnce.timeout",`timeoutMs=${r} \u670D\u52A1\u7AEF\u53EF\u80FD\u4ECD\u5728\u6267\u884C\u540C\u4E00\u8BF7\u6C42\uFF08Callable \u5360\u7EBF\u81F3\u9884\u7B97\u7ED3\u675F\uFF09`),new Error(`MCP tool ${s} timed out after ${r}ms`)):i}finally{n!==void 0&&clearTimeout(n)}}async executeToolRequest(e,r){return await this.fetchWithTimeout(this.mcpHttpUrl,{method:"POST",headers:this.buildRequestHeaders(),body:JSON.stringify({tool:e,arguments:r})},`MCP tool ${e}`)}async fetchWithTimeout(e,r,s){const t=this.resolveRequestTimeoutMs(),n=new AbortController,i=setTimeout(()=>n.abort(),t);try{return await fetch(e,{...r,signal:n.signal})}catch(a){throw n.signal.aborted?new Error(`${s} timed out after ${t}ms`):a}finally{clearTimeout(i)}}resolveRequestTimeoutMs(){const e=this.serverConfig.mcpHttpRequestTimeoutMs;return typeof e=="number"&&Number.isFinite(e)&&e>0?e:w}resolveRetryIntervalMs(){const e=this.serverConfig.mcpRetryIntervalMs;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:g}resolveRetryMaxAccumulatedMs(){const e=this.serverConfig.mcpRetryMaxAccumulatedMs;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:T}isTransientError(e){if(!(e instanceof Error))return!1;const r=e.message;return!!(/timed out after \d+ms/.test(r)||/fetch failed/i.test(r)||/network/i.test(r)||/ECONNREFUSED/i.test(r)||/ECONNRESET/i.test(r))}isRetryableHttpStatus(e){return e>=500||e===429}async delayForRetry(e,r,s){const t=e-Date.now(),n=Math.min(this.resolveRetryIntervalMs(),Math.max(0,t));o.warn(`[HttpClient] MCP tool ${r} \u8BF7\u6C42\u5931\u8D25\uFF0C${n}ms \u540E\u91CD\u8BD5 (\u7B2C${s}\u6B21)`),n>0&&await new Promise(i=>setTimeout(i,n))}buildRequestHeaders(){const e={"Content-Type":"application/json"};return this.serverConfig.runtimeAccessToken&&(e["X-Runtime-Token"]=this.serverConfig.runtimeAccessToken,e.Authorization=`Bearer ${this.serverConfig.runtimeAccessToken}`),e}async ensureRuntimeAccessToken(){if(this.serverConfig.runtimeAccessToken||!this.serverConfig.runtimeBridgeBaseUrl){o.info("[HttpClient] ensureRuntimeAccessToken: tokenLen=%d, bridgeBaseUrl=%s",(this.serverConfig.runtimeAccessToken||"").length,this.serverConfig.runtimeBridgeBaseUrl||"(\u7A7A)");return}throw new Error("runtimeAccessToken is required; MCP nodes must claim a session token from launch binding")}async tryRefreshToken(e){if(this.tokenRefreshPromise)return this.tokenRefreshPromise;this.tokenRefreshPromise=this.doRefreshToken(e);try{return await this.tokenRefreshPromise}finally{this.tokenRefreshPromise=null}}async doRefreshToken(e){const r=this.serverConfig.runtimeBridgeBaseUrl;if(!r)return o.warn("[HttpClient] \u65E0 runtimeBridgeBaseUrl\uFF0C\u65E0\u6CD5\u5237\u65B0 token"),!1;const s=String(e?.agentId||"").trim();if(!s)return o.warn("[HttpClient] \u65E0 agentId\uFF0C\u65E0\u6CD5\u5237\u65B0 token"),!1;try{const t=await fetch(`${r}/runtime/binding/refresh-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:s,currentToken:this.serverConfig.runtimeAccessToken||""})});if(!t.ok)return o.warn(`[HttpClient] bridge refresh-token \u8FD4\u56DE ${t.status}\uFF0C\u65E0\u6CD5\u5237\u65B0`),!1;const i=(await t.json()).runtimeAccessToken;return i?i===this.serverConfig.runtimeAccessToken?!1:(this.serverConfig.runtimeAccessToken=i,o.info("[HttpClient] runtimeAccessToken \u5DF2\u901A\u8FC7 bridge refresh \u66F4\u65B0"),!0):(o.warn("[HttpClient] bridge \u672A\u8FD4\u56DE\u65B0 token"),!1)}catch(t){return o.warn("[HttpClient] \u5237\u65B0 token \u5931\u8D25: %s",t instanceof Error?t.message:String(t)),t instanceof Error&&t.stack&&o.warn("[HttpClient] \u5237\u65B0 token \u5F02\u5E38\u5806\u6808:",t.stack),!1}}async refreshRuntimeAccessToken(e){return this.tryRefreshToken({agentId:e})}resolveMcpHttpUrl(){const e=this.serverConfig.mcpHttpUrl;if(e&&e.trim().length>0){const s=m(e);if(s)return s}const r=m(this.serverConfig.serverUrl,{fromAgentWebSocketUrl:!0});return r||this.serverConfig.serverUrl}getMcpHttpUrl(){return this.mcpHttpUrl}}export{H as HttpClient,R as normalizeServerHttpBase};
2
2
 
@@ -150,6 +150,8 @@ export declare class McpServer {
150
150
 
151
151
  private searchChildMemoriesByFileLocal;
152
152
 
153
+ private searchPeerMemoriesByFileLocal;
154
+
153
155
  private collectOwnMemoriesByFile;
154
156
 
155
157
  private handleAbandonMemoryUpdate;
@@ -161,6 +163,12 @@ export declare class McpServer {
161
163
  private fetchRecentMessages;
162
164
  private handleSendGroup;
163
165
 
166
+ private uploadAttachmentFiles;
167
+
168
+ private uploadFileRequest;
169
+
170
+ private mergeContentWithAttachmentMarkers;
171
+
164
172
  private recordMessageTokenUsage;
165
173
  private handleHireColleague;
166
174
  private handleHireColleaguesBatch;