klaus-agent 0.3.1 → 0.4.1

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 (90) hide show
  1. package/README.md +36 -2
  2. package/README.zh-CN.md +35 -1
  3. package/dist/approval/approval.d.ts +8 -3
  4. package/dist/approval/approval.js +23 -23
  5. package/dist/approval/approval.js.map +1 -1
  6. package/dist/approval/types.d.ts +1 -0
  7. package/dist/background/task-manager.d.ts +2 -0
  8. package/dist/background/task-manager.js +14 -0
  9. package/dist/background/task-manager.js.map +1 -1
  10. package/dist/compaction/compaction.d.ts +0 -1
  11. package/dist/compaction/compaction.js +21 -35
  12. package/dist/compaction/compaction.js.map +1 -1
  13. package/dist/compaction/summarizer.js +2 -7
  14. package/dist/compaction/summarizer.js.map +1 -1
  15. package/dist/core/agent-loop.d.ts +2 -1
  16. package/dist/core/agent-loop.js +14 -9
  17. package/dist/core/agent-loop.js.map +1 -1
  18. package/dist/core/agent.d.ts +7 -0
  19. package/dist/core/agent.js +35 -10
  20. package/dist/core/agent.js.map +1 -1
  21. package/dist/index.d.ts +7 -0
  22. package/dist/index.js +5 -0
  23. package/dist/index.js.map +1 -1
  24. package/dist/injection/history-normalizer.js +20 -10
  25. package/dist/injection/history-normalizer.js.map +1 -1
  26. package/dist/llm/types.d.ts +2 -0
  27. package/dist/multi-agent/task-executor.d.ts +2 -1
  28. package/dist/multi-agent/types.d.ts +3 -0
  29. package/dist/planning/planning-manager.d.ts +2 -0
  30. package/dist/planning/planning-manager.js +6 -0
  31. package/dist/planning/planning-manager.js.map +1 -1
  32. package/dist/providers/anthropic.js +14 -6
  33. package/dist/providers/anthropic.js.map +1 -1
  34. package/dist/providers/google.js.map +1 -1
  35. package/dist/providers/openai-codex.js +5 -8
  36. package/dist/providers/openai-codex.js.map +1 -1
  37. package/dist/providers/openai.js +3 -2
  38. package/dist/providers/openai.js.map +1 -1
  39. package/dist/providers/shared.d.ts +2 -2
  40. package/dist/providers/shared.js +11 -6
  41. package/dist/providers/shared.js.map +1 -1
  42. package/dist/session/session-manager.d.ts +1 -0
  43. package/dist/session/session-manager.js +11 -1
  44. package/dist/session/session-manager.js.map +1 -1
  45. package/dist/task-graph/result-injection.d.ts +8 -0
  46. package/dist/task-graph/result-injection.js +26 -0
  47. package/dist/task-graph/result-injection.js.map +1 -0
  48. package/dist/task-graph/task-graph.d.ts +41 -0
  49. package/dist/task-graph/task-graph.js +266 -0
  50. package/dist/task-graph/task-graph.js.map +1 -0
  51. package/dist/task-graph/tools.d.ts +3 -0
  52. package/dist/task-graph/tools.js +106 -0
  53. package/dist/task-graph/tools.js.map +1 -0
  54. package/dist/task-graph/types.d.ts +44 -0
  55. package/dist/task-graph/types.js +9 -0
  56. package/dist/task-graph/types.js.map +1 -0
  57. package/dist/tools/executor.d.ts +3 -2
  58. package/dist/tools/mcp-adapter.js +22 -5
  59. package/dist/tools/mcp-adapter.js.map +1 -1
  60. package/dist/utils/id.js +2 -6
  61. package/dist/utils/id.js.map +1 -1
  62. package/dist/wire/wire.d.ts +2 -1
  63. package/package.json +1 -1
  64. package/src/approval/approval.ts +29 -23
  65. package/src/approval/types.ts +1 -0
  66. package/src/background/task-manager.ts +17 -0
  67. package/src/compaction/compaction.ts +23 -36
  68. package/src/compaction/summarizer.ts +2 -7
  69. package/src/core/agent-loop.ts +17 -10
  70. package/src/core/agent.ts +41 -9
  71. package/src/index.ts +15 -0
  72. package/src/injection/history-normalizer.ts +22 -12
  73. package/src/llm/types.ts +2 -0
  74. package/src/multi-agent/task-executor.ts +1 -1
  75. package/src/multi-agent/types.ts +3 -0
  76. package/src/planning/planning-manager.ts +8 -0
  77. package/src/providers/anthropic.ts +70 -57
  78. package/src/providers/google.ts +1 -1
  79. package/src/providers/openai-codex.ts +7 -2
  80. package/src/providers/openai.ts +8 -3
  81. package/src/providers/shared.ts +11 -6
  82. package/src/session/session-manager.ts +15 -4
  83. package/src/task-graph/result-injection.ts +29 -0
  84. package/src/task-graph/task-graph.ts +298 -0
  85. package/src/task-graph/tools.ts +109 -0
  86. package/src/task-graph/types.ts +52 -0
  87. package/src/tools/executor.ts +2 -2
  88. package/src/tools/mcp-adapter.ts +23 -7
  89. package/src/utils/id.ts +3 -6
  90. package/src/wire/wire.ts +1 -1
@@ -0,0 +1,298 @@
1
+ // Task graph — dependency-aware DAG with background execution and auto-unlock
2
+
3
+ import { readFileSync, mkdirSync, existsSync } from "fs";
4
+ import { writeFile, rename } from "fs/promises";
5
+ import { join } from "path";
6
+ import { generateId } from "../utils/id.js";
7
+ import type { TaskNode, TaskStatus, TaskGraphConfig, CompletedTaskResult } from "./types.js";
8
+
9
+ export class TaskGraph {
10
+ private _tasks = new Map<string, TaskNode>();
11
+ private _config: TaskGraphConfig;
12
+ private _completedQueue: CompletedTaskResult[] = [];
13
+ private _backgroundAborts = new Map<string, AbortController>();
14
+
15
+ constructor(config: TaskGraphConfig = {}) {
16
+ this._config = config;
17
+ if (config.persistDir) {
18
+ mkdirSync(config.persistDir, { recursive: true });
19
+ this._loadFromDisk();
20
+ }
21
+ }
22
+
23
+
24
+ get(id: string): TaskNode | undefined {
25
+ const task = this._tasks.get(id);
26
+ return task ? { ...task, blockedBy: [...task.blockedBy], blocks: [...task.blocks] } : undefined;
27
+ }
28
+
29
+ listAll(): TaskNode[] {
30
+ return [...this._tasks.values()].map((t) => ({
31
+ ...t,
32
+ blockedBy: [...t.blockedBy],
33
+ blocks: [...t.blocks],
34
+ }));
35
+ }
36
+
37
+ /** Tasks that are pending with no unfinished blockers. */
38
+ listReady(): TaskNode[] {
39
+ return this.listAll().filter(
40
+ (t) => t.status === "pending" && t.blockedBy.length === 0,
41
+ );
42
+ }
43
+
44
+ /** Tasks waiting on unfinished blockers. */
45
+ listBlocked(): TaskNode[] {
46
+ return this.listAll().filter(
47
+ (t) => t.status === "pending" && t.blockedBy.length > 0,
48
+ );
49
+ }
50
+
51
+
52
+ create(subject: string, description = ""): TaskNode {
53
+ const max = this._config.maxTasks ?? 100;
54
+ if (this._tasks.size >= max) {
55
+ throw new Error(`Task limit reached: ${max}.`);
56
+ }
57
+
58
+ const node: TaskNode = {
59
+ id: generateId(),
60
+ subject,
61
+ description,
62
+ status: "pending",
63
+ blockedBy: [],
64
+ blocks: [],
65
+ owner: "",
66
+ createdAt: Date.now(),
67
+ updatedAt: Date.now(),
68
+ };
69
+ this._tasks.set(node.id, node);
70
+ this._persist();
71
+ return { ...node, blockedBy: [...node.blockedBy], blocks: [...node.blocks] };
72
+ }
73
+
74
+ /** Add a dependency: `taskId` is blocked by `blockedById`. */
75
+ addDependency(taskId: string, blockedById: string): void {
76
+ const task = this._require(taskId);
77
+ const blocker = this._require(blockedById);
78
+
79
+ if (task.blockedBy.includes(blockedById)) return;
80
+
81
+ // Cycle detection: if blocker is (transitively) blocked by task, adding this edge creates a cycle
82
+ if (this._isTransitivelyBlockedBy(blockedById, taskId)) {
83
+ throw new Error(`Adding dependency ${blockedById} → ${taskId} would create a cycle.`);
84
+ }
85
+
86
+ task.blockedBy.push(blockedById);
87
+ blocker.blocks.push(taskId);
88
+ task.updatedAt = Date.now();
89
+ blocker.updatedAt = Date.now();
90
+ this._persist();
91
+ }
92
+
93
+ update(taskId: string, fields: { status?: TaskStatus; owner?: string; result?: string }): TaskNode {
94
+ const task = this._require(taskId);
95
+
96
+ if (fields.status !== undefined && fields.status !== task.status) {
97
+ if (fields.status === "in_progress" && task.blockedBy.length > 0) {
98
+ throw new Error(`Task ${taskId} is blocked by: ${task.blockedBy.join(", ")}`);
99
+ }
100
+ task.status = fields.status;
101
+
102
+ if (fields.status === "completed" || fields.status === "failed") {
103
+ task.result = fields.result ?? task.result;
104
+ const unblocked = this._clearDependency(taskId);
105
+
106
+ this._completedQueue.push({
107
+ taskId,
108
+ subject: task.subject,
109
+ result: task.result ?? "",
110
+ status: fields.status,
111
+ unblockedTasks: unblocked,
112
+ });
113
+ }
114
+ }
115
+
116
+ if (fields.owner !== undefined) task.owner = fields.owner;
117
+ // result is already set inside the completion branch above; only apply here for non-completion updates
118
+ if (fields.result !== undefined && task.status !== "completed" && task.status !== "failed") {
119
+ task.result = fields.result;
120
+ }
121
+ task.updatedAt = Date.now();
122
+ this._persist();
123
+ return { ...task, blockedBy: [...task.blockedBy], blocks: [...task.blocks] };
124
+ }
125
+
126
+
127
+ /**
128
+ * Run an async function in the background for a task.
129
+ * Auto-updates task status to in_progress/completed/failed.
130
+ */
131
+ runBackground(
132
+ taskId: string,
133
+ fn: (signal: AbortSignal) => Promise<string>,
134
+ ): void {
135
+ const task = this._require(taskId);
136
+ if (task.blockedBy.length > 0) {
137
+ throw new Error(`Task ${taskId} is blocked by: ${task.blockedBy.join(", ")}`);
138
+ }
139
+
140
+ const ac = new AbortController();
141
+ const bgId = generateId();
142
+ task.status = "in_progress";
143
+ task.backgroundId = bgId;
144
+ task.updatedAt = Date.now();
145
+ this._backgroundAborts.set(bgId, ac);
146
+ this._persist();
147
+
148
+ fn(ac.signal).then(
149
+ (result) => {
150
+ this._backgroundAborts.delete(bgId);
151
+ try { this.update(taskId, { status: "completed", result }); } catch { /* task may have been removed */ }
152
+ },
153
+ (err) => {
154
+ this._backgroundAborts.delete(bgId);
155
+ try {
156
+ this.update(taskId, {
157
+ status: "failed",
158
+ result: err instanceof Error ? err.message : String(err),
159
+ });
160
+ } catch { /* task may have been removed */ }
161
+ },
162
+ );
163
+ }
164
+
165
+ abortBackground(taskId: string): boolean {
166
+ const task = this._tasks.get(taskId);
167
+ if (!task?.backgroundId) return false;
168
+ const ac = this._backgroundAborts.get(task.backgroundId);
169
+ if (!ac) return false;
170
+ ac.abort();
171
+ return true;
172
+ }
173
+
174
+
175
+ drainCompleted(): CompletedTaskResult[] {
176
+ const results = [...this._completedQueue];
177
+ this._completedQueue = [];
178
+ return results;
179
+ }
180
+
181
+
182
+ render(): string {
183
+ const tasks = this.listAll();
184
+ if (tasks.length === 0) return "No tasks.";
185
+
186
+ const lines = tasks.map((t) => {
187
+ const icon = t.status === "completed" ? "[x]"
188
+ : t.status === "failed" ? "[!]"
189
+ : t.status === "in_progress" ? "[>]"
190
+ : t.blockedBy.length > 0 ? "[~]"
191
+ : "[ ]";
192
+ const deps = t.blockedBy.length > 0 ? ` (blocked by: ${t.blockedBy.join(", ")})` : "";
193
+ return `${icon} ${t.id}: ${t.subject}${deps}`;
194
+ });
195
+
196
+ const done = tasks.filter((t) => t.status === "completed").length;
197
+ const ready = tasks.filter((t) => t.status === "pending" && t.blockedBy.length === 0).length;
198
+ return `Tasks: ${done}/${tasks.length} done, ${ready} ready\n${lines.join("\n")}`;
199
+ }
200
+
201
+ dispose(): void {
202
+ for (const ac of this._backgroundAborts.values()) {
203
+ ac.abort();
204
+ }
205
+ this._backgroundAborts.clear();
206
+ }
207
+
208
+
209
+ private _require(id: string): TaskNode {
210
+ const task = this._tasks.get(id);
211
+ if (!task) throw new Error(`Task not found: ${id}`);
212
+ return task;
213
+ }
214
+
215
+ /** Remove completedId from all tasks' blockedBy. Returns IDs of newly unblocked tasks. */
216
+ private _clearDependency(completedId: string): string[] {
217
+ const completed = this._tasks.get(completedId);
218
+ if (!completed) return [];
219
+
220
+ const unblocked: string[] = [];
221
+ for (const dependentId of completed.blocks) {
222
+ const task = this._tasks.get(dependentId);
223
+ if (!task) continue;
224
+ const idx = task.blockedBy.indexOf(completedId);
225
+ if (idx !== -1) {
226
+ task.blockedBy.splice(idx, 1);
227
+ if (task.blockedBy.length === 0 && task.status === "pending") {
228
+ unblocked.push(task.id);
229
+ }
230
+ }
231
+ }
232
+ return unblocked;
233
+ }
234
+
235
+ /** Check if `taskId` is transitively blocked by `targetId`. */
236
+ private _isTransitivelyBlockedBy(taskId: string, targetId: string): boolean {
237
+ const visited = new Set<string>();
238
+ const stack = [taskId];
239
+ while (stack.length > 0) {
240
+ const current = stack.pop()!;
241
+ if (current === targetId) return true;
242
+ if (visited.has(current)) continue;
243
+ visited.add(current);
244
+ const node = this._tasks.get(current);
245
+ if (node) stack.push(...node.blockedBy);
246
+ }
247
+ return false;
248
+ }
249
+
250
+ private _persistPromise: Promise<void> = Promise.resolve();
251
+
252
+ private _persist(): void {
253
+ if (!this._config.persistDir) return;
254
+ const dir = this._config.persistDir;
255
+ const tasks = [...this._tasks.values()];
256
+ this._persistPromise = this._persistPromise
257
+ .then(() => {
258
+ const data = JSON.stringify(tasks, null, 2);
259
+ const target = join(dir, "tasks.json");
260
+ const tmp = target + ".tmp";
261
+ return writeFile(tmp, data, "utf-8").then(() => rename(tmp, target));
262
+ })
263
+ .catch(() => { /* persist failure is non-fatal */ });
264
+ }
265
+
266
+ private _loadFromDisk(): void {
267
+ if (!this._config.persistDir) return;
268
+ const filePath = join(this._config.persistDir, "tasks.json");
269
+ if (!existsSync(filePath)) return;
270
+ try {
271
+ const raw = JSON.parse(readFileSync(filePath, "utf-8"));
272
+ if (!Array.isArray(raw)) return;
273
+ for (const entry of raw) {
274
+ if (!this._isValidTaskNode(entry)) continue;
275
+ this._tasks.set(entry.id, entry as TaskNode);
276
+ }
277
+ } catch {
278
+ // Corrupted file — start fresh
279
+ }
280
+ }
281
+
282
+ private static readonly _validStatuses = new Set(["pending", "in_progress", "completed", "failed"]);
283
+
284
+ private _isValidTaskNode(entry: unknown): entry is TaskNode {
285
+ if (!entry || typeof entry !== "object") return false;
286
+ const e = entry as Record<string, unknown>;
287
+ return (
288
+ typeof e.id === "string" &&
289
+ typeof e.subject === "string" &&
290
+ typeof e.status === "string" &&
291
+ TaskGraph._validStatuses.has(e.status as string) &&
292
+ Array.isArray(e.blockedBy) &&
293
+ Array.isArray(e.blocks) &&
294
+ typeof e.createdAt === "number" &&
295
+ typeof e.updatedAt === "number"
296
+ );
297
+ }
298
+ }
@@ -0,0 +1,109 @@
1
+ // Task graph tools — CRUD + dependency management + background execution
2
+
3
+ import { Type } from "@sinclair/typebox";
4
+ import type { AgentTool, AgentToolResult } from "../tools/types.js";
5
+ import type { TaskGraph } from "./task-graph.js";
6
+ import { TASK_GRAPH_TOOL_NAMES } from "./types.js";
7
+ import type { TaskStatus, TaskNode } from "./types.js";
8
+
9
+ export function createTaskGraphTools(graph: TaskGraph): AgentTool[] {
10
+ return [
11
+ {
12
+ name: TASK_GRAPH_TOOL_NAMES.create,
13
+ label: "Create Task",
14
+ description:
15
+ "Create a new task in the task graph. Tasks start as pending. " +
16
+ "Use task_depend to set up dependency ordering.",
17
+ parameters: Type.Object({
18
+ subject: Type.String({ description: "Short title for the task." }),
19
+ description: Type.Optional(Type.String({ description: "Detailed description." })),
20
+ }),
21
+ async execute(_id, params: { subject: string; description?: string }): Promise<AgentToolResult> {
22
+ const task = graph.create(params.subject, params.description);
23
+ return text(`Created task ${task.id}: ${task.subject}\n\n${graph.render()}`);
24
+ },
25
+ },
26
+ {
27
+ name: TASK_GRAPH_TOOL_NAMES.depend,
28
+ label: "Add Task Dependency",
29
+ description:
30
+ "Add a dependency: task_id cannot start until blocked_by_id completes. " +
31
+ "Rejects if this would create a cycle.",
32
+ parameters: Type.Object({
33
+ task_id: Type.String({ description: "Task that is blocked." }),
34
+ blocked_by_id: Type.String({ description: "Task that must complete first." }),
35
+ }),
36
+ async execute(_id, params: { task_id: string; blocked_by_id: string }): Promise<AgentToolResult> {
37
+ graph.addDependency(params.task_id, params.blocked_by_id);
38
+ return text(`Dependency added: ${params.task_id} blocked by ${params.blocked_by_id}\n\n${graph.render()}`);
39
+ },
40
+ },
41
+ {
42
+ name: TASK_GRAPH_TOOL_NAMES.update,
43
+ label: "Update Task",
44
+ description:
45
+ "Update a task's status, owner, or result. " +
46
+ "Setting status to 'completed' auto-unblocks dependent tasks. " +
47
+ "Cannot start a task that has unfinished blockers.",
48
+ parameters: Type.Object({
49
+ task_id: Type.String({ description: "Task ID." }),
50
+ status: Type.Optional(Type.Union(
51
+ [Type.Literal("pending"), Type.Literal("in_progress"), Type.Literal("completed"), Type.Literal("failed")],
52
+ { description: "New status." },
53
+ )),
54
+ owner: Type.Optional(Type.String({ description: "Assign to an agent or user." })),
55
+ result: Type.Optional(Type.String({ description: "Result summary." })),
56
+ }),
57
+ async execute(_id, params: { task_id: string; status?: string; owner?: string; result?: string }): Promise<AgentToolResult> {
58
+ const task = graph.update(params.task_id, {
59
+ status: params.status as TaskStatus | undefined,
60
+ owner: params.owner,
61
+ result: params.result,
62
+ });
63
+ return text(`Updated task ${task.id}\n\n${graph.render()}`);
64
+ },
65
+ },
66
+ {
67
+ name: TASK_GRAPH_TOOL_NAMES.list,
68
+ label: "List Tasks",
69
+ description: "List all tasks with their status, dependencies, and progress.",
70
+ parameters: Type.Object({
71
+ filter: Type.Optional(Type.Union(
72
+ [Type.Literal("all"), Type.Literal("ready"), Type.Literal("blocked"), Type.Literal("in_progress"), Type.Literal("completed")],
73
+ { description: "Filter tasks by category. Default: all." },
74
+ )),
75
+ }),
76
+ async execute(_id, params: { filter?: string }): Promise<AgentToolResult> {
77
+ let tasks: TaskNode[];
78
+ switch (params.filter) {
79
+ case "ready": tasks = graph.listReady(); break;
80
+ case "blocked": tasks = graph.listBlocked(); break;
81
+ case "in_progress": tasks = graph.listAll().filter((t) => t.status === "in_progress"); break;
82
+ case "completed": tasks = graph.listAll().filter((t) => t.status === "completed"); break;
83
+ default: tasks = graph.listAll();
84
+ }
85
+ if (tasks.length === 0) return text(`No tasks matching filter: ${params.filter ?? "all"}`);
86
+ if (!params.filter || params.filter === "all") return text(graph.render());
87
+ const lines = tasks.map((t) => `${t.id}: ${t.subject} [${t.status}]`);
88
+ return text(`${params.filter}: ${tasks.length} task(s)\n${lines.join("\n")}`);
89
+ },
90
+ },
91
+ {
92
+ name: TASK_GRAPH_TOOL_NAMES.get,
93
+ label: "Get Task",
94
+ description: "Get detailed information about a specific task.",
95
+ parameters: Type.Object({
96
+ task_id: Type.String({ description: "Task ID." }),
97
+ }),
98
+ async execute(_id, params: { task_id: string }): Promise<AgentToolResult> {
99
+ const task = graph.get(params.task_id);
100
+ if (!task) return text(`Task not found: ${params.task_id}`);
101
+ return text(JSON.stringify(task, null, 2));
102
+ },
103
+ },
104
+ ];
105
+ }
106
+
107
+ function text(t: string): AgentToolResult {
108
+ return { content: [{ type: "text", text: t }] };
109
+ }
@@ -0,0 +1,52 @@
1
+ // Task graph types — dependency-aware task DAG with background execution
2
+
3
+ export const TASK_GRAPH_TOOL_NAMES = {
4
+ create: "task_create",
5
+ depend: "task_depend",
6
+ update: "task_update",
7
+ list: "task_list",
8
+ get: "task_get",
9
+ } as const;
10
+
11
+ export type TaskStatus = "pending" | "in_progress" | "completed" | "failed";
12
+
13
+ export interface TaskNode {
14
+ id: string;
15
+ subject: string;
16
+ description: string;
17
+ status: TaskStatus;
18
+ /** IDs of tasks that must complete before this one can start. */
19
+ blockedBy: string[];
20
+ /** IDs of tasks that this task blocks (reverse edges, maintained automatically). */
21
+ blocks: string[];
22
+ /** Agent or user assigned to this task. */
23
+ owner: string;
24
+ /** Result summary after completion/failure. */
25
+ result?: string;
26
+ /** Background execution handle ID, if running in background. */
27
+ backgroundId?: string;
28
+ createdAt: number;
29
+ updatedAt: number;
30
+ }
31
+
32
+ export interface TaskGraphConfig {
33
+ /** Directory for persisting task graph to disk. If omitted, in-memory only. */
34
+ persistDir?: string;
35
+
36
+ /** Maximum number of tasks. Default: 100. */
37
+ maxTasks?: number;
38
+
39
+ /**
40
+ * Auto-inject completed background task results before each LLM call.
41
+ * Default: true.
42
+ */
43
+ autoInjectResults?: boolean;
44
+ }
45
+
46
+ export interface CompletedTaskResult {
47
+ taskId: string;
48
+ subject: string;
49
+ result: string;
50
+ status: "completed" | "failed";
51
+ unblockedTasks: string[];
52
+ }
@@ -5,7 +5,7 @@ import type { ToolCallBlock, TextContent } from "../llm/types.js";
5
5
  import type { Approval } from "../approval/types.js";
6
6
  import { Value } from "@sinclair/typebox/value";
7
7
 
8
- export interface ToolExecutorConfig {
8
+ interface ToolExecutorConfig {
9
9
  tools: AgentTool[];
10
10
  mode: "sequential" | "parallel";
11
11
  approval: Approval;
@@ -16,7 +16,7 @@ export interface ToolExecutorConfig {
16
16
  onEvent: (event: ToolExecutorEvent) => void;
17
17
  }
18
18
 
19
- export type ToolExecutorEvent =
19
+ type ToolExecutorEvent =
20
20
  | { type: "tool_execution_start"; toolCallId: string; toolName: string; args: unknown }
21
21
  | { type: "tool_execution_update"; toolCallId: string; toolName: string; partialResult: AgentToolResult }
22
22
  | { type: "tool_execution_end"; toolCallId: string; toolName: string; result: AgentToolResult; isError: boolean };
@@ -156,17 +156,33 @@ export class MCPAdapter {
156
156
  // Approval is handled by the executor via approvalAction field
157
157
  // No need to request approval here
158
158
 
159
- // Call with timeout
159
+ // Call with timeout and abort signal support
160
160
  const callPromise = client.callTool(def.name, params);
161
161
  let result: MCPToolResult;
162
162
 
163
+ let timer: ReturnType<typeof setTimeout> | undefined;
164
+ let abortHandler: (() => void) | undefined;
165
+ const racers: Promise<MCPToolResult>[] = [callPromise];
166
+
163
167
  if (timeout) {
164
- const timeoutPromise = new Promise<never>((_, reject) =>
165
- setTimeout(() => reject(new Error(`MCP tool ${def.name} timed out after ${timeout}ms`)), timeout),
166
- );
167
- result = await Promise.race([callPromise, timeoutPromise]);
168
- } else {
169
- result = await callPromise;
168
+ racers.push(new Promise<never>((_, reject) => {
169
+ timer = setTimeout(() => reject(new Error(`MCP tool ${def.name} timed out after ${timeout}ms`)), timeout);
170
+ }));
171
+ }
172
+
173
+ if (context.signal.aborted) throw new Error("Aborted");
174
+ racers.push(new Promise<never>((_, reject) => {
175
+ abortHandler = () => reject(new Error("Aborted"));
176
+ context.signal.addEventListener("abort", abortHandler, { once: true });
177
+ }));
178
+
179
+ try {
180
+ result = await Promise.race(racers);
181
+ } finally {
182
+ if (timer !== undefined) clearTimeout(timer);
183
+ if (abortHandler) {
184
+ context.signal.removeEventListener("abort", abortHandler);
185
+ }
170
186
  }
171
187
 
172
188
  // Convert MCP result to AgentToolResult
package/src/utils/id.ts CHANGED
@@ -1,8 +1,5 @@
1
+ import { randomBytes } from "node:crypto";
2
+
1
3
  export function generateId(): string {
2
- const chars = "0123456789abcdefghijklmnopqrstuvwxyz";
3
- let id = "";
4
- for (let i = 0; i < 12; i++) {
5
- id += chars[Math.floor(Math.random() * chars.length)];
6
- }
7
- return id;
4
+ return randomBytes(9).toString("base64url").slice(0, 12);
8
5
  }
package/src/wire/wire.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  import { generateId } from "../utils/id.js";
4
4
  import type { WireMessage, WireSubscriber, WireSubscription } from "./types.js";
5
5
 
6
- export interface WireOptions {
6
+ interface WireOptions {
7
7
  /** Max messages to buffer for replay to late subscribers. 0 = no buffering. */
8
8
  bufferSize?: number;
9
9
  }