@lucascouts/claude-agent-tui 0.7.0 → 0.9.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 CHANGED
@@ -48,6 +48,26 @@ export function toolInfoFromToolUse(toolUse, supportsTerminalOutput = false, cwd
48
48
  : [],
49
49
  };
50
50
  }
51
+ case "ReportFindings": {
52
+ // Story 074 (#826): render the code-review ReportFindings tool as a think-kind
53
+ // label — `Report N finding(s)` with one `file:line — summary` block per finding
54
+ // (`:line` omitted when absent), or `Report findings: none found` when empty.
55
+ const input = toolUse.input;
56
+ const findings = input?.findings ?? [];
57
+ return {
58
+ title: findings.length > 0
59
+ ? `Report ${findings.length} finding${findings.length === 1 ? "" : "s"}`
60
+ : "Report findings: none found",
61
+ kind: "think",
62
+ content: findings.map((f) => ({
63
+ type: "content",
64
+ content: {
65
+ type: "text",
66
+ text: `${f.file}${typeof f.line === "number" ? `:${f.line}` : ""} — ${f.summary}`,
67
+ },
68
+ })),
69
+ };
70
+ }
51
71
  case "Bash": {
52
72
  const input = toolUse.input;
53
73
  return {
@@ -321,7 +341,89 @@ export function toolInfoFromToolUse(toolUse, supportsTerminalOutput = false, cwd
321
341
  };
322
342
  }
323
343
  }
324
- export function toolUpdateFromToolResult(toolResult, toolUse, supportsTerminalOutput = false) {
344
+ /**
345
+ * Narrow the untyped message-level `toolUseResult` toward a per-tool Output shape: rejects
346
+ * everything but a plain non-null object (arrays pass a bare `typeof === "object"` check, so they're
347
+ * excluded here). The returned value is only *nominally* typed — it arrives from arbitrary CLI
348
+ * versions via the JSONL transcript, so each caller must still guard the specific fields it reads
349
+ * before trusting them.
350
+ */
351
+ function structuredResult(toolUseResult) {
352
+ return toolUseResult !== null &&
353
+ typeof toolUseResult === "object" &&
354
+ !Array.isArray(toolUseResult)
355
+ ? toolUseResult
356
+ : undefined;
357
+ }
358
+ /**
359
+ * Strip the model-directed trailer from a raw Agent/Task tool_result text: a `<usage>…</usage>`
360
+ * totals block and/or an `agentId: <id> (use SendMessage …)` continuation line at the end of the
361
+ * text. Both patterns are tail-anchored and independent (older CLIs emit variants with only one of
362
+ * them), so a format change makes them stop matching rather than mangle the report.
363
+ *
364
+ * Ported from upstream #879 (v0.60.0), which replaced a regex sweep with this linear parse — the
365
+ * same posture `redos-command-marker.test.ts` guards elsewhere in the fork.
366
+ */
367
+ function stripAgentTrailer(text) {
368
+ return stripAgentIdLine(stripUsageBlock(text));
369
+ }
370
+ const USAGE_OPEN = "<usage>";
371
+ const USAGE_CLOSE = "</usage>";
372
+ /**
373
+ * Remove a trailing `<usage>…</usage>` block, plus trailing whitespace and one preceding newline.
374
+ * Matches from the *last* `<usage>` so a report that merely mentions the marker earlier isn't
375
+ * truncated at the mention.
376
+ */
377
+ function stripUsageBlock(text) {
378
+ const body = text.trimEnd();
379
+ if (!body.endsWith(USAGE_CLOSE)) {
380
+ return text;
381
+ }
382
+ const open = body.lastIndexOf(USAGE_OPEN, body.length - USAGE_CLOSE.length - USAGE_OPEN.length);
383
+ if (open === -1) {
384
+ return text;
385
+ }
386
+ return body.slice(0, open > 0 && body[open - 1] === "\n" ? open - 1 : open);
387
+ }
388
+ /**
389
+ * The continuation line, anchored to a whole line so the regex has a single start position and no
390
+ * ambiguous repetition (`[\w-]+` can't consume the following space, `[^)]*` can't consume the
391
+ * closing paren) — it runs in linear time on any input.
392
+ */
393
+ const AGENT_ID_LINE = /^agentId: [\w-]+ \([^)]*\)$/;
394
+ /** Remove a final `agentId: <id> (…)` line, plus trailing whitespace and the preceding newline. */
395
+ function stripAgentIdLine(text) {
396
+ const body = text.trimEnd();
397
+ const lineStart = body.lastIndexOf("\n") + 1;
398
+ if (!AGENT_ID_LINE.test(body.slice(lineStart))) {
399
+ return text;
400
+ }
401
+ return body.slice(0, Math.max(lineStart - 1, 0));
402
+ }
403
+ /**
404
+ * Apply {@link stripAgentTrailer} across a raw tool_result `content` (plain string or block array),
405
+ * leaving non-text blocks untouched.
406
+ */
407
+ function stripAgentTrailerFromContent(content) {
408
+ if (typeof content === "string") {
409
+ return stripAgentTrailer(content);
410
+ }
411
+ if (Array.isArray(content)) {
412
+ return content.map((block) => block !== null &&
413
+ typeof block === "object" &&
414
+ block.type === "text" &&
415
+ typeof block.text === "string"
416
+ ? { ...block, text: stripAgentTrailer(block.text) }
417
+ : block);
418
+ }
419
+ return content;
420
+ }
421
+ export function toolUpdateFromToolResult(toolResult, toolUse, supportsTerminalOutput = false,
422
+ // Story 079 (R3/R4): the message-level `toolUseResult` hydrated from the JSONL transcript by
423
+ // `diff-enriched-reader.ts`. Upstream notes its own structured renders go dark on replay because
424
+ // `getSessionMessages` doesn't expose this field — the fork reads the transcript directly, so the
425
+ // structured path is available on BOTH the live tail and `session/load`.
426
+ toolUseResult) {
325
427
  if ("is_error" in toolResult &&
326
428
  toolResult.is_error &&
327
429
  toolResult.content &&
@@ -333,8 +435,54 @@ export function toolUpdateFromToolResult(toolResult, toolUse, supportsTerminalOu
333
435
  // Only return errors
334
436
  return toAcpContentUpdate(toolResult.content, true);
335
437
  }
438
+ // Shared raw-text fallback: renders the tool_result content the model saw. The structured cases
439
+ // below fall back to this when `toolUseResult` is absent or fails its shape guard (older CLIs, a
440
+ // transcript line without the field).
441
+ const rawContentUpdate = () => toAcpContentUpdate(toolResult.content, "is_error" in toolResult ? toolResult.is_error : false);
336
442
  switch (toolUse?.name) {
337
- case "Read":
443
+ case "Read": {
444
+ // The raw tool_result text is the model-facing view: line-numbered content plus any appended
445
+ // <system-reminder> blocks (malicious-code checks, memory staleness notes, …) that clients
446
+ // shouldn't see. The structured FileReadOutput carries the clean content — rebuild the
447
+ // line-numbered view from it. Non-text variants (image/notebook/pdf) fall back to the raw
448
+ // content blocks, which already render fine.
449
+ const structuredRead = structuredResult(toolUseResult);
450
+ if (structuredRead?.type === "text" &&
451
+ typeof structuredRead.file?.content === "string" &&
452
+ // An empty file has nothing to line-number; keep the raw view (the model-facing "file is
453
+ // empty" note) rather than a phantom blank line.
454
+ structuredRead.file.content.length > 0) {
455
+ // startLine is typed non-optional but defended anyway; a Read's `offset` input is the same
456
+ // 1-based starting line, so it beats a blind 1 when an emitter omits the field.
457
+ const startLine = structuredRead.file.startLine ??
458
+ toolUse?.input?.offset ??
459
+ 1;
460
+ // A trailing newline is a line terminator, not an extra line — don't number a phantom empty
461
+ // line after it.
462
+ let numbered = structuredRead.file.content
463
+ .replace(/\n$/, "")
464
+ .split("\n")
465
+ .map((line, i) => `${startLine + i}\t${line}`)
466
+ .join("\n");
467
+ // The model-facing truncation banner doesn't survive reconstruction from file.content (the
468
+ // SDK flag exists for exactly this case) — re-establish it so a partial first page doesn't
469
+ // read as the whole file.
470
+ if (structuredRead.file.truncatedByTokenCap) {
471
+ const { numLines, totalLines } = structuredRead.file;
472
+ const detail = typeof numLines === "number" && typeof totalLines === "number"
473
+ ? `: showing ${numLines} of ${totalLines} lines`
474
+ : "";
475
+ numbered += `\n[File truncated${detail}]`;
476
+ }
477
+ return {
478
+ content: [
479
+ {
480
+ type: "content",
481
+ content: { type: "text", text: markdownEscape(numbered) },
482
+ },
483
+ ],
484
+ };
485
+ }
338
486
  if (Array.isArray(toolResult.content) && toolResult.content.length > 0) {
339
487
  return {
340
488
  content: toolResult.content.map((content) => ({
@@ -362,17 +510,62 @@ export function toolUpdateFromToolResult(toolResult, toolUse, supportsTerminalOu
362
510
  };
363
511
  }
364
512
  return {};
513
+ }
365
514
  case "Bash": {
366
515
  const result = toolResult.content;
367
- const terminalId = "tool_use_id" in toolResult ? String(toolResult.tool_use_id) : "";
516
+ // The terminal was announced under the tool_use's own id (see `toolInfoFromToolUse`, which
517
+ // emits `terminalId: toolUse.id`), so key the output/exit metas off that: it is the id the
518
+ // client actually created a terminal for. `toolResult.tool_use_id` is the same value whenever
519
+ // present, so preferring `toolUse.id` only adds a source for the case where the result block
520
+ // carries no id at all. Anything that isn't a non-empty string is no id at all: `""` matches
521
+ // no terminal, and stringifying a present-but-undefined field would invent the literal
522
+ // `"undefined"`. Ported from upstream #917 (v0.63.0).
523
+ const terminalIdOf = (id) => typeof id === "string" && id.length > 0 ? id : undefined;
524
+ const terminalId = terminalIdOf(toolUse?.id) ??
525
+ terminalIdOf("tool_use_id" in toolResult ? toolResult.tool_use_id : undefined);
368
526
  const isError = "is_error" in toolResult && toolResult.is_error;
369
527
  // Extract output and exit code from either format:
370
- // 1. BetaBashCodeExecutionResultBlock: { type: "bash_code_execution_result", stdout, stderr, return_code }
371
- // 2. Plain string content from a regular tool_result
372
- // 3. Array content (e.g. [{ type: "text", text: "..." }])
528
+ // 1. The structured BashOutput (message-level `toolUseResult`): its stdout/stderr exclude the
529
+ // model-directed suffixes the raw text carries (stale-read hints, gh rate-limit hints, the
530
+ // persisted-output wrapper for too-large outputs — the interruption and truncation facts
531
+ // those carried are re-established from the structured flags below). Skipped for image
532
+ // output (the raw content array carries the actual image blocks) and backgrounded commands
533
+ // (the raw text carries the background-task notice; structured stdout may be empty).
534
+ // 2. BetaBashCodeExecutionResultBlock: { type: "bash_code_execution_result", stdout, stderr, return_code }
535
+ // 3. Plain string content from a regular tool_result
536
+ // 4. Array content (e.g. [{ type: "text", text: "..." }])
373
537
  let output = "";
374
538
  let exitCode = isError ? 1 : 0;
375
- if (result &&
539
+ const structuredBash = structuredResult(toolUseResult);
540
+ if (structuredBash &&
541
+ typeof structuredBash.stdout === "string" &&
542
+ typeof structuredBash.stderr === "string" &&
543
+ !structuredBash.isImage &&
544
+ structuredBash.backgroundTaskId === undefined) {
545
+ output = [structuredBash.stdout, structuredBash.stderr].filter(Boolean).join("\n");
546
+ // Two raw-text notices don't survive the structured stdout/stderr — re-establish them so the
547
+ // client isn't shown a clean-looking result: the CLI appends its abort marker only to the
548
+ // model-facing text, and an aborted command isn't a success, so synthesize a failing exit
549
+ // code when the result wasn't already an error.
550
+ if (structuredBash.interrupted) {
551
+ output = [output, "[Command was aborted before completion]"].filter(Boolean).join("\n");
552
+ exitCode = 1;
553
+ }
554
+ // Structured stdout is clipped (~30k chars) when the full output was persisted to disk;
555
+ // without this note the clip is silent and the path to the full output is lost.
556
+ if (typeof structuredBash.persistedOutputPath === "string") {
557
+ const size = typeof structuredBash.persistedOutputSize === "number"
558
+ ? ` (${structuredBash.persistedOutputSize} bytes total)`
559
+ : "";
560
+ output = [
561
+ output,
562
+ `[Output truncated${size}: full output saved to ${structuredBash.persistedOutputPath}]`,
563
+ ]
564
+ .filter(Boolean)
565
+ .join("\n");
566
+ }
567
+ }
568
+ else if (result &&
376
569
  typeof result === "object" &&
377
570
  "type" in result &&
378
571
  result.type === "bash_code_execution_result") {
@@ -389,7 +582,12 @@ export function toolUpdateFromToolResult(toolResult, toolUse, supportsTerminalOu
389
582
  typeof result[0].text === "string") {
390
583
  output = result.map((c) => c.text).join("\n");
391
584
  }
392
- if (supportsTerminalOutput) {
585
+ // Without a terminal id there is nothing the client can reconcile these metas against, and
586
+ // emitting them anyway strands the output: a client that buffers output/exit for terminals it
587
+ // has not been told about (Zed keeps them in `pending_terminal_output`/`pending_terminal_exit`,
588
+ // drained only on a matching create) would hold them forever behind an id that never arrives,
589
+ // showing an empty terminal. Fall through to the code-block rendering below instead.
590
+ if (supportsTerminalOutput && terminalId !== undefined) {
393
591
  return {
394
592
  content: [{ type: "terminal", terminalId }],
395
593
  _meta: {
@@ -431,11 +629,69 @@ export function toolUpdateFromToolResult(toolResult, toolUse, supportsTerminalOu
431
629
  case "ExitPlanMode": {
432
630
  return { title: "Exited Plan Mode" };
433
631
  }
632
+ case "Agent":
633
+ case "Task": {
634
+ // The raw tool_result text ends with a model-directed trailer (an `agentId: … (use
635
+ // SendMessage …)` line plus a `<usage>` totals block) that ACP clients shouldn't see. The
636
+ // structured AgentOutput carries the subagent's report without the trailer — render from it
637
+ // when present (per the SDK 0.3.207 guidance) and fall back to the tail-anchored strip
638
+ // otherwise.
639
+ // Narrowed to the full union, not the completed variant — the status check below is what
640
+ // discriminates it, and pre-narrowing would let future field reads typecheck against a variant
641
+ // the runtime value may not be.
642
+ const structuredAgent = structuredResult(toolUseResult);
643
+ if (structuredAgent?.status === "completed" &&
644
+ Array.isArray(structuredAgent.content) &&
645
+ // A completed subagent can end with zero text blocks; an empty structured render would beat
646
+ // the raw fallback for no benefit.
647
+ structuredAgent.content.length > 0) {
648
+ return toAcpContentUpdate(structuredAgent.content, "is_error" in toolResult ? toolResult.is_error : false);
649
+ }
650
+ // No structured report to render from (older CLIs, a transcript line without the field). The
651
+ // tail-anchored strip is the only cleanup available; if the trailer format changes it simply
652
+ // stops matching and the full raw text renders, no worse than before.
653
+ return toAcpContentUpdate(stripAgentTrailerFromContent(toolResult.content), "is_error" in toolResult ? toolResult.is_error : false);
654
+ }
655
+ case "WebSearch": {
656
+ // The raw tool_result text is a model-directed dump ("Web search results for query: …\n\n
657
+ // Links: [{…json…}]"). The structured WebSearchOutput carries the hits — render them the way
658
+ // server-side web_search_result blocks render ("Title (url)").
659
+ const structuredSearch = structuredResult(toolUseResult);
660
+ if (structuredSearch && Array.isArray(structuredSearch.results)) {
661
+ const lines = structuredSearch.results.flatMap((entry) => typeof entry === "string"
662
+ ? [entry]
663
+ : Array.isArray(entry?.content)
664
+ ? // toolUseResult arrives untyped across CLI version skew — skip off-spec hits rather
665
+ // than rendering "undefined (undefined)" lines.
666
+ entry.content.flatMap((hit) => typeof hit?.title === "string" && typeof hit?.url === "string"
667
+ ? [formatWebSearchHit(hit)]
668
+ : [])
669
+ : []);
670
+ if (lines.length > 0) {
671
+ return {
672
+ content: [
673
+ {
674
+ type: "content",
675
+ content: { type: "text", text: lines.join("\n") },
676
+ },
677
+ ],
678
+ };
679
+ }
680
+ }
681
+ return rawContentUpdate();
682
+ }
434
683
  default: {
435
- return toAcpContentUpdate(toolResult.content, "is_error" in toolResult ? toolResult.is_error : false);
684
+ return rawContentUpdate();
436
685
  }
437
686
  }
438
687
  }
688
+ /**
689
+ * One display format for a web-search hit, shared by the structured WebSearchOutput render and the
690
+ * server-side `web_search_result` block so the two paths can't drift.
691
+ */
692
+ function formatWebSearchHit(hit) {
693
+ return `${hit.title} (${hit.url})`;
694
+ }
439
695
  function toAcpContentUpdate(content, isError = false) {
440
696
  if (Array.isArray(content) && content.length > 0) {
441
697
  return {
@@ -500,7 +756,7 @@ function toAcpContentBlock(content, isError) {
500
756
  case "tool_search_tool_result_error":
501
757
  return wrapText(`Error: ${content.error_code}${content.error_message ? ` - ${content.error_message}` : ""}`);
502
758
  case "web_search_result":
503
- return wrapText(`${content.title} (${content.url})`);
759
+ return wrapText(formatWebSearchHit(content));
504
760
  case "web_search_tool_result_error":
505
761
  return wrapText(`Error: ${content.error_code}`);
506
762
  case "web_fetch_result":
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.7.0",
6
+ "version": "0.9.0",
7
7
  "description": "Run the official Claude Code TUI in Zed's agent panel on your Claude Pro/Max subscription — an ACP-over-PTY bridge created for Anthropic's billing split (paused June 15; see README).",
8
8
  "main": "dist/lib.js",
9
9
  "types": "dist/lib.d.ts",
@@ -63,21 +63,21 @@
63
63
  "node": ">=20"
64
64
  },
65
65
  "dependencies": {
66
- "@agentclientprotocol/sdk": "1.0.0",
67
- "@anthropic-ai/claude-agent-sdk": "0.3.195",
66
+ "@agentclientprotocol/sdk": "1.3.0",
67
+ "@anthropic-ai/claude-agent-sdk": "0.3.220",
68
68
  "node-pty": "1.1.0",
69
69
  "zod": "^3.25.0 || ^4.0.0"
70
70
  },
71
71
  "devDependencies": {
72
- "@anthropic-ai/sdk": "0.106.0",
72
+ "@anthropic-ai/sdk": "0.115.0",
73
73
  "@eslint/js": "10.0.1",
74
- "@types/node": "26.0.1",
75
- "@typescript-eslint/eslint-plugin": "8.62.0",
76
- "@typescript-eslint/parser": "8.62.0",
77
- "eslint": "10.5.0",
74
+ "@types/node": "26.1.1",
75
+ "@typescript-eslint/eslint-plugin": "8.65.0",
76
+ "@typescript-eslint/parser": "8.65.0",
77
+ "eslint": "10.8.0",
78
78
  "eslint-config-prettier": "10.1.8",
79
- "globals": "17.7.0",
80
- "prettier": "3.8.4",
79
+ "globals": "17.8.0",
80
+ "prettier": "3.9.6",
81
81
  "ts-node": "10.9.2",
82
82
  "typescript": "6.0.3"
83
83
  }