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.
- package/dist/adapter/AcodeSdkAdapter.d.ts +15 -0
- package/dist/adapter/AcodeSdkAdapter.js +5 -5
- package/dist/adapter/types.d.ts +9 -0
- package/dist/browser/browser-frame-encode.d.ts +16 -0
- package/dist/browser/browser-frame-encode.js +2 -0
- package/dist/browser/browser-pool.js +1 -1
- package/dist/browser/built-in-browser-tools.js +1 -1
- package/dist/browser/screencast-differ.d.ts +35 -0
- package/dist/browser/screencast-differ.js +2 -0
- package/dist/browser/screencast-manager.d.ts +32 -0
- package/dist/browser/screencast-manager.js +1 -1
- package/dist/browser/types.d.ts +48 -1
- package/dist/browser/types.js +1 -1
- package/dist/browser/ws-server.d.ts +1 -1
- package/dist/browser/ws-server.js +1 -1
- package/dist/routes/background-tasks.js +7 -1
- package/dist/routes/instance-tool-status.d.ts +4 -0
- package/dist/routes/instance-tool-status.js +2 -0
- package/dist/routes/instance.d.ts +0 -2
- package/dist/routes/instance.js +1 -1
- package/dist/routes/system-metrics.js +1 -1
- package/dist/routes/terminal.js +19 -19
- package/dist/services/acode-bg-manager.d.ts +36 -0
- package/dist/services/acode-bg-manager.js +2 -0
- package/dist/services/browser-session-manager.js +1 -1
- package/dist/services/instance-features.d.ts +5 -0
- package/dist/services/instance-features.js +1 -1
- package/dist/services/process-detail.d.ts +77 -0
- package/dist/services/process-detail.js +32 -0
- package/dist/services/process-top.d.ts +53 -0
- package/dist/services/process-top.js +50 -0
- package/dist/services/session-output.d.ts +10 -0
- package/dist/services/session-output.js +3 -3
- package/package/acode/dist/await-complete-tool.js +4 -4
- package/package/acode/dist/background-command-manager.d.ts +39 -0
- package/package/acode/dist/background-command-manager.js +5 -5
- package/package/acode/dist/background-command-tools.js +1 -1
- package/package/acode/dist/built-in-file-tools.d.ts +25 -1
- package/package/acode/dist/built-in-file-tools.js +2 -2
- package/package/acode/dist/builtins/shellCommandResult.d.ts +3 -0
- package/package/acode/dist/builtins/shellCommandResult.js +1 -1
- package/package/acode/dist/builtins/shellCommandRunner.d.ts +2 -0
- package/package/acode/dist/builtins/shellCommandRunner.js +1 -1
- package/package/acode/dist/image-utils.d.ts +52 -0
- package/package/acode/dist/image-utils.js +2 -0
- package/package/acode/dist/index.d.ts +1 -0
- package/package/acode/dist/index.js +1 -1
- package/package/acode/dist/runtime.d.ts +15 -1
- package/package/acode/dist/runtime.js +26 -26
- package/package/acode/dist/sub-agent-tools.js +30 -26
- package/package/acode/dist/sub-agent-types.d.ts +1 -1
- package/package/acode/dist/tool-allocation.d.ts +4 -4
- package/package/acode/dist/tool-allocation.js +1 -1
- package/package/acode/dist/types.d.ts +3 -1
- package/package/aws-client-agent-mcp/dist/http-client.d.ts +4 -0
- package/package/aws-client-agent-mcp/dist/http-client.js +1 -1
- package/package/aws-client-agent-mcp/dist/mcp-server.d.ts +8 -0
- package/package/aws-client-agent-mcp/dist/mcp-server.js +28 -25
- package/package/aws-client-agent-mcp/dist/mcp-tools.js +6 -6
- package/package/aws-client-agent-mcp/dist/memory-store.d.ts +6 -0
- package/package/aws-client-agent-mcp/dist/memory-tools.js +2 -2
- package/package/aws-client-agent-mcp/dist/types.d.ts +4 -0
- package/package/aws-client-agent-mcp/package.json +1 -1
- package/package.json +3 -3
- package/package/aws-client-agent-mcp/dist/agent-client.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/agent-client.test.js +0 -1066
- package/package/aws-client-agent-mcp/dist/config.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/config.test.js +0 -259
- package/package/aws-client-agent-mcp/dist/context-manager.test.d.ts +0 -2
- package/package/aws-client-agent-mcp/dist/context-manager.test.js +0 -312
- package/package/aws-client-agent-mcp/dist/http-client.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/http-client.test.js +0 -808
- package/package/aws-client-agent-mcp/dist/launch-config-tools.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/launch-config-tools.test.js +0 -110
- package/package/aws-client-agent-mcp/dist/logger.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/logger.test.js +0 -27
- package/package/aws-client-agent-mcp/dist/mcp-server.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/mcp-server.test.js +0 -2798
- package/package/aws-client-agent-mcp/dist/mcp-tools.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/mcp-tools.test.js +0 -152
- package/package/aws-client-agent-mcp/dist/memory-store.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/memory-store.test.js +0 -664
- package/package/aws-client-agent-mcp/dist/message-buffer.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/message-buffer.test.js +0 -142
- package/package/aws-client-agent-mcp/dist/parent-lifecycle.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/parent-lifecycle.test.js +0 -81
- package/package/aws-client-agent-mcp/dist/runtime-launch-binding.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/runtime-launch-binding.test.js +0 -201
- package/package/aws-client-agent-mcp/dist/status-reporter.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/status-reporter.test.js +0 -157
- package/package/aws-client-agent-mcp/dist/watchdog.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/watchdog.test.js +0 -124
- package/package/aws-client-agent-mcp/dist/websocket-client.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/websocket-client.test.js +0 -725
|
@@ -1,19 +1,20 @@
|
|
|
1
|
-
import{
|
|
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
|
-
|
|
9
|
-
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
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
|
-
-
|
|
16
|
-
- Unknown
|
|
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
|
|
31
|
-
tool allocation (${l}): ${
|
|
32
|
-
mode: ${l} (no allocatable tools found in catalog)`;return{title:
|
|
33
|
-
type: ${l}${
|
|
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:
|
|
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(
|
|
46
|
-
`),metadata:{runningCount:
|
|
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
|
|
58
|
-
... (truncated)`:s)}return t.errorMessage&&(
|
|
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:
|
|
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
|
|
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
|
|
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
|
|
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: ["
|
|
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(
|
|
83
|
-
`),metadata:{categories:
|
|
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
|
|
|
@@ -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 = "
|
|
51
|
+
export declare const PRESET_EXPLORE = "explore";
|
|
52
52
|
|
|
53
|
-
export declare const PRESET_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
|
|
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(
|
|
69
|
+
export declare function resolveToolAllocation(subagentType: SubAgentType, rawTools: readonly string[], catalog: readonly ToolCatalogEntry[]): ResolvedToolAllocation;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const i="default",
|
|
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;
|