@lucascouts/claude-agent-acp-plus 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tools.js ADDED
@@ -0,0 +1,757 @@
1
+ import path from "node:path";
2
+ /**
3
+ * Convert an absolute file path to a project-relative path for display.
4
+ * Returns the original path if it's outside the project directory or if no cwd is provided.
5
+ */
6
+ export function toDisplayPath(filePath, cwd) {
7
+ if (!cwd)
8
+ return filePath;
9
+ const resolvedCwd = path.resolve(cwd);
10
+ const resolvedFile = path.resolve(filePath);
11
+ if (resolvedFile.startsWith(resolvedCwd + path.sep) || resolvedFile === resolvedCwd) {
12
+ return path.relative(resolvedCwd, resolvedFile);
13
+ }
14
+ return filePath;
15
+ }
16
+ export function toolInfoFromToolUse(toolUse, supportsTerminalOutput = false, cwd) {
17
+ const name = toolUse.name;
18
+ switch (name) {
19
+ case "Agent":
20
+ case "Task": {
21
+ const input = toolUse.input;
22
+ return {
23
+ title: input?.description ? input.description : "Task",
24
+ kind: "think",
25
+ content: input && "prompt" in input
26
+ ? [
27
+ {
28
+ type: "content",
29
+ content: { type: "text", text: input.prompt },
30
+ },
31
+ ]
32
+ : [],
33
+ };
34
+ }
35
+ case "Bash": {
36
+ const input = toolUse.input;
37
+ return {
38
+ title: input?.command ? input.command : "Terminal",
39
+ kind: "execute",
40
+ content: supportsTerminalOutput
41
+ ? [{ type: "terminal", terminalId: toolUse.id }]
42
+ : input && input.description
43
+ ? [
44
+ {
45
+ type: "content",
46
+ content: { type: "text", text: input.description },
47
+ },
48
+ ]
49
+ : [],
50
+ };
51
+ }
52
+ case "Read": {
53
+ const input = toolUse.input;
54
+ let limit = "";
55
+ if (input?.limit && input.limit > 0) {
56
+ limit = " (" + (input.offset ?? 1) + " - " + ((input.offset ?? 1) + input.limit - 1) + ")";
57
+ }
58
+ else if (input?.offset) {
59
+ limit = " (from line " + input.offset + ")";
60
+ }
61
+ const displayPath = input?.file_path ? toDisplayPath(input.file_path, cwd) : "File";
62
+ return {
63
+ title: "Read " + displayPath + limit,
64
+ kind: "read",
65
+ locations: input?.file_path
66
+ ? [
67
+ {
68
+ path: input.file_path,
69
+ line: input.offset ?? 1,
70
+ },
71
+ ]
72
+ : [],
73
+ content: [],
74
+ };
75
+ }
76
+ case "Write": {
77
+ const input = toolUse.input;
78
+ let content = [];
79
+ if (input && input.file_path) {
80
+ content = [
81
+ {
82
+ type: "diff",
83
+ path: input.file_path,
84
+ oldText: null,
85
+ newText: input.content,
86
+ },
87
+ ];
88
+ }
89
+ else if (input && input.content) {
90
+ content = [
91
+ {
92
+ type: "content",
93
+ content: { type: "text", text: input.content },
94
+ },
95
+ ];
96
+ }
97
+ const displayPath = input?.file_path ? toDisplayPath(input.file_path, cwd) : undefined;
98
+ return {
99
+ title: displayPath ? `Write ${displayPath}` : "Write",
100
+ kind: "edit",
101
+ content,
102
+ locations: input?.file_path ? [{ path: input.file_path }] : [],
103
+ };
104
+ }
105
+ case "Edit": {
106
+ const input = toolUse.input;
107
+ let content = [];
108
+ if (input && input.file_path && (input.old_string || input.new_string)) {
109
+ content = [
110
+ {
111
+ type: "diff",
112
+ path: input.file_path,
113
+ oldText: input.old_string || null,
114
+ newText: input.new_string ?? "",
115
+ },
116
+ ];
117
+ }
118
+ const displayPath = input?.file_path ? toDisplayPath(input.file_path, cwd) : undefined;
119
+ return {
120
+ title: displayPath ? `Edit ${displayPath}` : "Edit",
121
+ kind: "edit",
122
+ content,
123
+ locations: input?.file_path ? [{ path: input.file_path }] : [],
124
+ };
125
+ }
126
+ case "Glob": {
127
+ const input = toolUse.input;
128
+ let label = "Find";
129
+ if (input?.path) {
130
+ label += ` \`${input.path}\``;
131
+ }
132
+ if (input?.pattern) {
133
+ label += ` \`${input.pattern}\``;
134
+ }
135
+ return {
136
+ title: label,
137
+ kind: "search",
138
+ content: [],
139
+ locations: input?.path ? [{ path: input.path }] : [],
140
+ };
141
+ }
142
+ case "Grep": {
143
+ const input = toolUse.input;
144
+ let label = "grep";
145
+ if (input?.["-i"]) {
146
+ label += " -i";
147
+ }
148
+ if (input?.["-n"]) {
149
+ label += " -n";
150
+ }
151
+ if (input?.["-A"] !== undefined) {
152
+ label += ` -A ${input["-A"]}`;
153
+ }
154
+ if (input?.["-B"] !== undefined) {
155
+ label += ` -B ${input["-B"]}`;
156
+ }
157
+ if (input?.["-C"] !== undefined) {
158
+ label += ` -C ${input["-C"]}`;
159
+ }
160
+ if (input?.output_mode) {
161
+ switch (input.output_mode) {
162
+ case "files_with_matches":
163
+ label += " -l";
164
+ break;
165
+ case "count":
166
+ label += " -c";
167
+ break;
168
+ case "content":
169
+ default:
170
+ break;
171
+ }
172
+ }
173
+ if (input?.head_limit !== undefined) {
174
+ label += ` | head -${input.head_limit}`;
175
+ }
176
+ if (input?.glob) {
177
+ label += ` --include="${input.glob}"`;
178
+ }
179
+ if (input?.type) {
180
+ label += ` --type=${input.type}`;
181
+ }
182
+ if (input?.multiline) {
183
+ label += " -P";
184
+ }
185
+ if (input?.pattern) {
186
+ label += ` "${input.pattern}"`;
187
+ }
188
+ if (input?.path) {
189
+ label += ` ${input.path}`;
190
+ }
191
+ return {
192
+ title: label,
193
+ kind: "search",
194
+ content: [],
195
+ };
196
+ }
197
+ case "WebFetch": {
198
+ const input = toolUse.input;
199
+ return {
200
+ title: input?.url ? `Fetch ${input.url}` : "Fetch",
201
+ kind: "fetch",
202
+ content: input && input.prompt
203
+ ? [
204
+ {
205
+ type: "content",
206
+ content: { type: "text", text: input.prompt },
207
+ },
208
+ ]
209
+ : [],
210
+ };
211
+ }
212
+ case "WebSearch": {
213
+ const input = toolUse.input;
214
+ let label = input?.query ? `"${input.query}"` : "Web search";
215
+ if (input?.allowed_domains && input.allowed_domains.length > 0) {
216
+ label += ` (allowed: ${input.allowed_domains.join(", ")})`;
217
+ }
218
+ if (input?.blocked_domains && input.blocked_domains.length > 0) {
219
+ label += ` (blocked: ${input.blocked_domains.join(", ")})`;
220
+ }
221
+ return {
222
+ title: label,
223
+ kind: "fetch",
224
+ content: [],
225
+ };
226
+ }
227
+ case "TodoWrite": {
228
+ const input = toolUse.input;
229
+ return {
230
+ title: Array.isArray(input?.todos)
231
+ ? `Update TODOs: ${input.todos.map((todo) => todo.content).join(", ")}`
232
+ : "Update TODOs",
233
+ kind: "think",
234
+ content: [],
235
+ };
236
+ }
237
+ case "ReportFindings": {
238
+ const input = toolUse.input;
239
+ const findings = input?.findings ?? [];
240
+ return {
241
+ title: findings.length === 0
242
+ ? "Report findings: none found"
243
+ : `Report ${findings.length} finding${findings.length === 1 ? "" : "s"}`,
244
+ kind: "think",
245
+ content: findings.map((finding) => ({
246
+ type: "content",
247
+ content: {
248
+ type: "text",
249
+ text: `**${finding.file}${finding.line ? `:${finding.line}` : ""}** — ${finding.summary}`,
250
+ },
251
+ })),
252
+ };
253
+ }
254
+ case "TaskCreate": {
255
+ const input = toolUse.input;
256
+ return {
257
+ title: input?.subject ? `Create task: ${input.subject}` : "Create task",
258
+ kind: "think",
259
+ content: [],
260
+ };
261
+ }
262
+ case "TaskUpdate": {
263
+ const input = toolUse.input;
264
+ return {
265
+ title: input?.subject ? `Update task: ${input.subject}` : "Update task",
266
+ kind: "think",
267
+ content: [],
268
+ };
269
+ }
270
+ case "TaskList": {
271
+ return {
272
+ title: "List tasks",
273
+ kind: "think",
274
+ content: [],
275
+ };
276
+ }
277
+ case "TaskGet": {
278
+ return {
279
+ title: "Get task",
280
+ kind: "think",
281
+ content: [],
282
+ };
283
+ }
284
+ case "ExitPlanMode": {
285
+ const planInput = toolUse.input;
286
+ return {
287
+ title: "Ready to code?",
288
+ kind: "switch_mode",
289
+ content: planInput?.plan
290
+ ? [{ type: "content", content: { type: "text", text: planInput.plan } }]
291
+ : [],
292
+ };
293
+ }
294
+ case "AskUserQuestion": {
295
+ const input = toolUse.input;
296
+ const questions = Array.isArray(input?.questions) ? input.questions : [];
297
+ return {
298
+ title: questions.length === 1 && questions[0]?.question
299
+ ? questions[0].question
300
+ : "Asking for your input",
301
+ kind: "other",
302
+ content: questions
303
+ .filter((q) => typeof q?.question === "string")
304
+ .map((q) => ({
305
+ type: "content",
306
+ content: { type: "text", text: q.question },
307
+ })),
308
+ };
309
+ }
310
+ case "Other": {
311
+ const input = toolUse.input;
312
+ let output;
313
+ try {
314
+ output = JSON.stringify(input, null, 2);
315
+ }
316
+ catch {
317
+ output = typeof input === "string" ? input : "{}";
318
+ }
319
+ return {
320
+ title: name || "Unknown Tool",
321
+ kind: "other",
322
+ content: [
323
+ {
324
+ type: "content",
325
+ content: {
326
+ type: "text",
327
+ text: `\`\`\`json\n${output}\`\`\``,
328
+ },
329
+ },
330
+ ],
331
+ };
332
+ }
333
+ default:
334
+ return {
335
+ title: name || "Unknown Tool",
336
+ kind: "other",
337
+ content: [],
338
+ };
339
+ }
340
+ }
341
+ export function toolUpdateFromToolResult(toolResult, toolUse, supportsTerminalOutput = false) {
342
+ if ("is_error" in toolResult &&
343
+ toolResult.is_error &&
344
+ toolResult.content &&
345
+ toolResult.content.length > 0 &&
346
+ !(toolUse?.name === "Bash" && supportsTerminalOutput)) {
347
+ // Only return errors
348
+ return toAcpContentUpdate(toolResult.content, true);
349
+ }
350
+ switch (toolUse?.name) {
351
+ case "Read":
352
+ if (Array.isArray(toolResult.content) && toolResult.content.length > 0) {
353
+ return {
354
+ content: toolResult.content.map((content) => ({
355
+ type: "content",
356
+ content: content.type === "text"
357
+ ? {
358
+ type: "text",
359
+ text: markdownEscape(content.text),
360
+ }
361
+ : toAcpContentBlock(content, false),
362
+ })),
363
+ };
364
+ }
365
+ else if (typeof toolResult.content === "string" && toolResult.content.length > 0) {
366
+ return {
367
+ content: [
368
+ {
369
+ type: "content",
370
+ content: {
371
+ type: "text",
372
+ text: markdownEscape(toolResult.content),
373
+ },
374
+ },
375
+ ],
376
+ };
377
+ }
378
+ return {};
379
+ case "Bash": {
380
+ const result = toolResult.content;
381
+ const terminalId = "tool_use_id" in toolResult ? String(toolResult.tool_use_id) : "";
382
+ const isError = "is_error" in toolResult && toolResult.is_error;
383
+ // Extract output and exit code from either format:
384
+ // 1. BetaBashCodeExecutionResultBlock: { type: "bash_code_execution_result", stdout, stderr, return_code }
385
+ // 2. Plain string content from a regular tool_result
386
+ // 3. Array content (e.g. [{ type: "text", text: "..." }] for stdout,
387
+ // or [{ type: "image", source: {...} }] when the local Bash tool
388
+ // produces an image, e.g. piping a base64 data URI)
389
+ let output = "";
390
+ let exitCode = isError ? 1 : 0;
391
+ if (result &&
392
+ typeof result === "object" &&
393
+ "type" in result &&
394
+ result.type === "bash_code_execution_result") {
395
+ const bashResult = result;
396
+ output = [bashResult.stdout, bashResult.stderr].filter(Boolean).join("\n");
397
+ exitCode = bashResult.return_code;
398
+ }
399
+ else if (typeof result === "string") {
400
+ output = result;
401
+ }
402
+ else if (Array.isArray(result) && result.length > 0) {
403
+ const textOnly = result.every((c) => c && typeof c === "object" && typeof c.text === "string");
404
+ if (textOnly) {
405
+ output = result.map((c) => c.text).join("\n");
406
+ }
407
+ else {
408
+ // Image (or mixed non-text) content. Binary payloads can't be
409
+ // streamed through the terminal-output _meta channel, so bypass
410
+ // it and surface the blocks as ACP content. This handles the
411
+ // local Bash tool's image output, which previously failed the
412
+ // text-only guard and was silently dropped.
413
+ return toAcpContentUpdate(result, isError);
414
+ }
415
+ }
416
+ if (supportsTerminalOutput) {
417
+ return {
418
+ content: [{ type: "terminal", terminalId }],
419
+ _meta: {
420
+ terminal_info: {
421
+ terminal_id: terminalId,
422
+ },
423
+ terminal_output: {
424
+ terminal_id: terminalId,
425
+ data: output,
426
+ },
427
+ terminal_exit: {
428
+ terminal_id: terminalId,
429
+ exit_code: exitCode,
430
+ signal: null,
431
+ },
432
+ },
433
+ };
434
+ }
435
+ // Fallback: format output as a code block without terminal _meta
436
+ if (output.trim()) {
437
+ return {
438
+ content: [
439
+ {
440
+ type: "content",
441
+ content: {
442
+ type: "text",
443
+ text: `\`\`\`console\n${output.trimEnd()}\n\`\`\``,
444
+ },
445
+ },
446
+ ],
447
+ };
448
+ }
449
+ return {};
450
+ }
451
+ case "Edit": // Edit is handled in hooks
452
+ case "Write": {
453
+ return {};
454
+ }
455
+ case "ExitPlanMode": {
456
+ return { title: "Exited Plan Mode" };
457
+ }
458
+ default: {
459
+ return toAcpContentUpdate(toolResult.content, "is_error" in toolResult ? toolResult.is_error : false);
460
+ }
461
+ }
462
+ }
463
+ function toAcpContentUpdate(content, isError = false) {
464
+ if (Array.isArray(content) && content.length > 0) {
465
+ return {
466
+ content: content.map((c) => ({
467
+ type: "content",
468
+ content: toAcpContentBlock(c, isError),
469
+ })),
470
+ };
471
+ }
472
+ else if (typeof content === "object" && content !== null && "type" in content) {
473
+ return {
474
+ content: [
475
+ {
476
+ type: "content",
477
+ content: toAcpContentBlock(content, isError),
478
+ },
479
+ ],
480
+ };
481
+ }
482
+ else if (typeof content === "string" && content.length > 0) {
483
+ return {
484
+ content: [
485
+ {
486
+ type: "content",
487
+ content: {
488
+ type: "text",
489
+ text: isError ? `\`\`\`\n${content}\n\`\`\`` : content,
490
+ },
491
+ },
492
+ ],
493
+ };
494
+ }
495
+ return {};
496
+ }
497
+ function toAcpContentBlock(content, isError) {
498
+ const wrapText = (text) => ({
499
+ type: "text",
500
+ text: isError ? `\`\`\`\n${text}\n\`\`\`` : text,
501
+ });
502
+ switch (content.type) {
503
+ case "text":
504
+ return {
505
+ type: "text",
506
+ text: isError ? `\`\`\`\n${content.text}\n\`\`\`` : content.text,
507
+ };
508
+ case "image":
509
+ if (content.source.type === "base64") {
510
+ return {
511
+ type: "image",
512
+ data: content.source.data,
513
+ mimeType: content.source.media_type,
514
+ };
515
+ }
516
+ // URL and file-based images can't be converted to ACP format (requires data)
517
+ return wrapText(content.source.type === "url"
518
+ ? `[image: ${content.source.url}]`
519
+ : "[image: file reference]");
520
+ case "tool_reference":
521
+ return wrapText(`Tool: ${content.tool_name}`);
522
+ case "tool_search_tool_search_result":
523
+ return wrapText(`Tools found: ${content.tool_references.map((r) => r.tool_name).join(", ") || "none"}`);
524
+ case "tool_search_tool_result_error":
525
+ return wrapText(`Error: ${content.error_code}${content.error_message ? ` - ${content.error_message}` : ""}`);
526
+ case "web_search_result":
527
+ return wrapText(`${content.title} (${content.url})`);
528
+ case "web_search_tool_result_error":
529
+ return wrapText(`Error: ${content.error_code}`);
530
+ case "web_fetch_result":
531
+ return wrapText(`Fetched: ${content.url}`);
532
+ case "web_fetch_tool_result_error":
533
+ return wrapText(`Error: ${content.error_code}`);
534
+ case "code_execution_result":
535
+ return wrapText(`Output: ${content.stdout || content.stderr || ""}`);
536
+ case "bash_code_execution_result":
537
+ return wrapText(`Output: ${content.stdout || content.stderr || ""}`);
538
+ case "code_execution_tool_result_error":
539
+ case "bash_code_execution_tool_result_error":
540
+ return wrapText(`Error: ${content.error_code}`);
541
+ case "text_editor_code_execution_view_result":
542
+ return wrapText(content.content);
543
+ case "text_editor_code_execution_create_result":
544
+ return wrapText(content.is_file_update ? "File updated" : "File created");
545
+ case "text_editor_code_execution_str_replace_result":
546
+ return wrapText(content.lines?.join("\n") || "");
547
+ case "text_editor_code_execution_tool_result_error":
548
+ return wrapText(`Error: ${content.error_code}${content.error_message ? ` - ${content.error_message}` : ""}`);
549
+ default:
550
+ return wrapText(JSON.stringify(content));
551
+ }
552
+ }
553
+ export function planEntries(input) {
554
+ return (input?.todos ?? []).map((todo) => ({
555
+ content: todo.content,
556
+ status: todo.status,
557
+ priority: "medium",
558
+ }));
559
+ }
560
+ /**
561
+ * Best-effort parse of a TaskCreate tool_result content into the structured
562
+ * TaskCreateOutput. The SDK delivers tool outputs either as a string or as
563
+ * an array of TextBlockParam-like blocks containing JSON text; try both.
564
+ */
565
+ export function parseTaskCreateOutput(content) {
566
+ const tryParse = (text) => {
567
+ try {
568
+ const parsed = JSON.parse(text);
569
+ if (parsed &&
570
+ typeof parsed === "object" &&
571
+ parsed.task &&
572
+ typeof parsed.task.id === "string") {
573
+ return parsed;
574
+ }
575
+ }
576
+ catch {
577
+ // ignore
578
+ }
579
+ return undefined;
580
+ };
581
+ if (typeof content === "string") {
582
+ return tryParse(content);
583
+ }
584
+ if (Array.isArray(content)) {
585
+ for (const block of content) {
586
+ if (block && typeof block === "object" && "type" in block && block.type === "text") {
587
+ const text = block.text;
588
+ if (typeof text === "string") {
589
+ const parsed = tryParse(text);
590
+ if (parsed)
591
+ return parsed;
592
+ }
593
+ }
594
+ }
595
+ }
596
+ return undefined;
597
+ }
598
+ export function applyTaskCreate(state, input, output) {
599
+ const taskId = output?.task?.id;
600
+ if (!taskId || !input)
601
+ return;
602
+ state.set(taskId, {
603
+ subject: input.subject,
604
+ status: "pending",
605
+ activeForm: input.activeForm,
606
+ description: input.description,
607
+ });
608
+ }
609
+ export function applyTaskUpdate(state, input) {
610
+ if (!input?.taskId)
611
+ return;
612
+ if (input.status === "deleted") {
613
+ state.delete(input.taskId);
614
+ return;
615
+ }
616
+ const existing = state.get(input.taskId);
617
+ // Without a subject from either the existing entry or the update payload,
618
+ // we'd produce a plan entry with empty `content` — drop the update.
619
+ const subject = input.subject ?? existing?.subject;
620
+ if (!subject)
621
+ return;
622
+ state.set(input.taskId, {
623
+ subject,
624
+ status: input.status ?? existing?.status ?? "pending",
625
+ activeForm: input.activeForm ?? existing?.activeForm,
626
+ description: input.description ?? existing?.description,
627
+ });
628
+ }
629
+ export function taskStateToPlanEntries(state) {
630
+ return Array.from(state.values()).map((task) => ({
631
+ content: task.subject,
632
+ status: task.status,
633
+ priority: "medium",
634
+ }));
635
+ }
636
+ export function markdownEscape(text) {
637
+ let escape = "```";
638
+ for (const [m] of text.matchAll(/^```+/gm)) {
639
+ while (m.length >= escape.length) {
640
+ escape += "`";
641
+ }
642
+ }
643
+ return escape + "\n" + text + (text.endsWith("\n") ? "" : "\n") + escape;
644
+ }
645
+ /**
646
+ * Builds diff ToolUpdate content from the structured toolResponse provided by
647
+ * the PostToolUse hook for diff-producing tools (Edit, Write). Unlike parsing
648
+ * the plain unified diff string, this uses the pre-parsed structuredPatch
649
+ * which supports multiple replacement sites (replaceAll) and always includes
650
+ * context lines for better readability.
651
+ */
652
+ export function toolUpdateFromDiffToolResponse(toolResponse) {
653
+ if (!toolResponse || typeof toolResponse !== "object")
654
+ return {};
655
+ const response = toolResponse;
656
+ if (!response.filePath || !Array.isArray(response.structuredPatch))
657
+ return {};
658
+ const content = [];
659
+ const locations = [];
660
+ for (const { lines, newStart } of response.structuredPatch) {
661
+ const oldText = [];
662
+ const newText = [];
663
+ for (const line of lines) {
664
+ if (line.startsWith("-")) {
665
+ oldText.push(line.slice(1));
666
+ }
667
+ else if (line.startsWith("+")) {
668
+ newText.push(line.slice(1));
669
+ }
670
+ else {
671
+ oldText.push(line.slice(1));
672
+ newText.push(line.slice(1));
673
+ }
674
+ }
675
+ if (oldText.length > 0 || newText.length > 0) {
676
+ locations.push({ path: response.filePath, line: newStart });
677
+ content.push({
678
+ type: "diff",
679
+ path: response.filePath,
680
+ oldText: oldText.join("\n") || null,
681
+ newText: newText.join("\n"),
682
+ });
683
+ }
684
+ }
685
+ const result = {};
686
+ if (content.length > 0)
687
+ result.content = content;
688
+ if (locations.length > 0)
689
+ result.locations = locations;
690
+ return result;
691
+ }
692
+ /* A global variable to store callbacks that should be executed when receiving hooks from Claude Code */
693
+ const toolUseCallbacks = {};
694
+ /* Setup callbacks that will be called when receiving hooks from Claude Code */
695
+ export const registerHookCallback = (toolUseID, { onPostToolUseHook, }) => {
696
+ toolUseCallbacks[toolUseID] = {
697
+ onPostToolUseHook,
698
+ };
699
+ };
700
+ /* A callback for Claude Code that is called when receiving a PostToolUse hook */
701
+ export const createPostToolUseHook = (logger = console, options) => async (input, toolUseID) => {
702
+ if (input.hook_event_name === "PostToolUse") {
703
+ // Handle EnterPlanMode tool - notify client of mode change after successful execution
704
+ if (input.tool_name === "EnterPlanMode" && options?.onEnterPlanMode) {
705
+ await options.onEnterPlanMode();
706
+ }
707
+ if (toolUseID) {
708
+ const onPostToolUseHook = toolUseCallbacks[toolUseID]?.onPostToolUseHook;
709
+ if (onPostToolUseHook) {
710
+ await onPostToolUseHook(toolUseID, input.tool_input, input.tool_response);
711
+ delete toolUseCallbacks[toolUseID]; // Cleanup after execution
712
+ }
713
+ else {
714
+ logger.error(`No onPostToolUseHook found for tool use ID: ${toolUseID}`);
715
+ delete toolUseCallbacks[toolUseID];
716
+ }
717
+ }
718
+ }
719
+ return { continue: true };
720
+ };
721
+ /**
722
+ * Hook callback for `TaskCreated` / `TaskCompleted` events. The SDK fires
723
+ * these for both user-facing TaskCreate tool calls and subagent task
724
+ * creation, giving us `task_id` + `task_subject` without having to parse
725
+ * tool_result payloads.
726
+ *
727
+ * Populating `taskState` from the hook means a later `TaskUpdate` (which
728
+ * typically only carries `taskId` + `status`) finds an existing entry with
729
+ * a real subject, instead of synthesizing a placeholder with empty content.
730
+ */
731
+ export const createTaskHook = (options) => async (input) => {
732
+ const taskId = "task_id" in input && typeof input.task_id === "string" ? input.task_id : undefined;
733
+ if (!taskId)
734
+ return { continue: true };
735
+ if (input.hook_event_name === "TaskCreated") {
736
+ if (!input.task_subject)
737
+ return { continue: true };
738
+ if (options.taskState.has(taskId))
739
+ return { continue: true };
740
+ options.taskState.set(taskId, {
741
+ subject: input.task_subject,
742
+ status: "pending",
743
+ description: input.task_description,
744
+ });
745
+ if (options.onChange)
746
+ await options.onChange();
747
+ }
748
+ else if (input.hook_event_name === "TaskCompleted") {
749
+ const existing = options.taskState.get(taskId);
750
+ if (!existing || existing.status === "completed")
751
+ return { continue: true };
752
+ options.taskState.set(taskId, { ...existing, status: "completed" });
753
+ if (options.onChange)
754
+ await options.onChange();
755
+ }
756
+ return { continue: true };
757
+ };