@lucascouts/claude-agent-tui 0.8.0 → 0.10.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/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  An [ACP](https://agentclientprotocol.com)-compatible agent that drives the **Claude Code subscription TUI** over a PTY, so your Claude Code threads render natively in [Zed](https://zed.dev) and other ACP clients.
6
6
 
7
- > **Fork** of [`@agentclientprotocol/claude-agent-acp`](https://github.com/agentclientprotocol/claude-agent-acp) v0.53.0. Where the upstream adapter calls the Claude Agent **SDK**, this fork spawns the `claude` **subscription CLI** in a pseudo-terminal and translates its JSONL transcript into ACP `session/update` notifications. See [`.fork-provenance.json`](.fork-provenance.json) for the exact fork point.
7
+ > **Fork** of [`@agentclientprotocol/claude-agent-acp`](https://github.com/agentclientprotocol/claude-agent-acp) v0.57.0. Where the upstream adapter calls the Claude Agent **SDK**, this fork spawns the `claude` **subscription CLI** in a pseudo-terminal and translates its JSONL transcript into ACP `session/update` notifications. See [`.fork-provenance.json`](.fork-provenance.json) for the exact fork point.
8
8
 
9
9
  ## Why this exists
10
10
 
@@ -25,7 +25,11 @@ This project bridges the two: it drives the **official Claude Code TUI** over a
25
25
  ## Requirements
26
26
 
27
27
  - The **`claude` CLI** (Claude Code subscription) available on your `PATH`.
28
- - **Node.js ≥ 23** — the runtime and test suite use native TypeScript type-stripping.
28
+ - **Node.js ≥ 24** — the runtime and test suite use native TypeScript type-stripping (`node --experimental-strip-types`). Raising this floor from the previous `>=20` is a **breaking change** for consumers still on Node 20–23.
29
+
30
+ > **Why 24, and not upstream's `>=22`?** The floor is a support policy, not a measured minimum: this project targets the **active LTS** line, which is Node 24. It is verified rather than copied — a fresh clone with no host `node_modules` or `dist/`, then `npm ci` → `npm run build` → `npm test`, inside `node:24` pinned by digest `sha256:934240a162082fd8b8a2f90cd5114446443f1eba1c5378f6687167ca405e6584` (Node v24.19.0). Green in both the fork and mirror trees: 1222 tests in the fork, 1183 here, 0 failures.
31
+ >
32
+ > A bare `>=22` cannot keep its own promise: `--experimental-strip-types` only landed in Node 22.6, so `>=22` still admits 22.0–22.5, where `npm install` succeeds and `npm test` cannot start. Any floor of 23 or higher closes that gap.
29
33
 
30
34
  ## Register in Zed
31
35
 
@@ -1008,6 +1008,7 @@ export declare function toAcpNotifications(content: string | ContentBlockParam[]
1008
1008
  parentToolUseId?: string | null;
1009
1009
  cwd?: string;
1010
1010
  taskState?: TaskState;
1011
+ toolUseResult?: unknown;
1011
1012
  }): SessionNotification[];
1012
1013
  export declare function streamEventToAcpNotifications(message: SDKPartialAssistantMessage, sessionId: string, toolUseCache: ToolUseCache, client: AgentSideConnection, logger: Logger, options?: {
1013
1014
  clientCapabilities?: ClientCapabilities;
package/dist/acp-agent.js CHANGED
@@ -1772,6 +1772,10 @@ export class ClaudeAcpAgent {
1772
1772
  if (content === null)
1773
1773
  return;
1774
1774
  }
1775
+ // Story 079 (R4): the same JSONL-hydrated `toolUseResult` the diff block reads below, handed to
1776
+ // the translator so Read/Bash/Agent/WebSearch render from the structured Output. Undefined on a
1777
+ // transcript line that carries no such field — the translator then keeps the raw rendering.
1778
+ const turnToolUseResult = turn.message.toolUseResult;
1775
1779
  for (const notification of toAcpNotifications(
1776
1780
  // @ts-expect-error - message.content/role are untyped in the reduced SDK shape
1777
1781
  content, role, sessionId, toolUseCache, this.client, this.logger, {
@@ -1779,6 +1783,7 @@ export class ClaudeAcpAgent {
1779
1783
  clientCapabilities: this.clientCapabilities,
1780
1784
  cwd: session?.cwd,
1781
1785
  taskState: session?.taskState,
1786
+ toolUseResult: turnToolUseResult,
1782
1787
  })) {
1783
1788
  await this.client.sessionUpdate(notification);
1784
1789
  }
@@ -1889,6 +1894,9 @@ export class ClaudeAcpAgent {
1889
1894
  clientCapabilities: this.clientCapabilities,
1890
1895
  cwd: session?.cwd,
1891
1896
  taskState: session?.taskState,
1897
+ // Story 079 (R4): a nested sidechain row carries its own hydrated `toolUseResult`, so the
1898
+ // sub-agent's Read/Bash results render structured too.
1899
+ toolUseResult: message.toolUseResult,
1892
1900
  });
1893
1901
  // Re-target every translated update as `ToolCallContent` on the PARENT id. A `tool_call_update`
1894
1902
  // replaces the content collection (ToolCallUpdate.content semantics), and Zed APPENDS across
@@ -2944,6 +2952,15 @@ export function toAcpNotifications(content, role, sessionId, toolUseCache, clien
2944
2952
  }
2945
2953
  return [{ sessionId, update }];
2946
2954
  }
2955
+ // Story 079 (R3/R4): `toolUseResult` is message-level and carries no tool_use_id of its own — it
2956
+ // describes "the" tool_result block of the message it rode in on. If several tool_result blocks
2957
+ // were ever batched into one message it couldn't be attributed, so it is only honored when the
2958
+ // message carries exactly one.
2959
+ const toolUseResult = options?.toolUseResult !== undefined &&
2960
+ content.filter((c) => typeof c === "object" && c !== null && c.type === "tool_result")
2961
+ .length === 1
2962
+ ? options.toolUseResult
2963
+ : undefined;
2947
2964
  const output = [];
2948
2965
  // Only handle the first chunk for streaming; extend as needed for batching
2949
2966
  for (const chunk of content) {
@@ -3131,7 +3148,7 @@ export function toAcpNotifications(content, role, sessionId, toolUseCache, clien
3131
3148
  }
3132
3149
  }
3133
3150
  else if (toolUse.name !== "TodoWrite") {
3134
- const { _meta: toolMeta, ...toolUpdate } = toolUpdateFromToolResult(chunk, toolUseCache[chunk.tool_use_id], supportsTerminalOutput);
3151
+ const { _meta: toolMeta, ...toolUpdate } = toolUpdateFromToolResult(chunk, toolUseCache[chunk.tool_use_id], supportsTerminalOutput, toolUseResult);
3135
3152
  // When terminal output is supported, send terminal_output as a
3136
3153
  // separate notification to match codex-acp's streaming lifecycle:
3137
3154
  // 1. tool_call → _meta.terminal_info (already sent above)
package/dist/index.js CHANGED
@@ -37,6 +37,17 @@ if (process.argv.includes("--cli")) {
37
37
  process.exit(1);
38
38
  });
39
39
  }
40
+ else if (process.argv.includes("--version")) {
41
+ // Story 080 (R3.1–R3.3) — the `--version` flag ported from upstream #813. Matched AFTER `--cli` on
42
+ // purpose: `--cli` is a passthrough to the real binary, so `--cli --version` must report CLAUDE's
43
+ // version, not ours. R3.2 — this branch prints and exits 0 before the ACP bootstrap below is ever
44
+ // reached, so no session is opened, no PTY is spawned and no turn is started. The payload module is
45
+ // imported dynamically so it stays off the hot path of the other two branches. It writes to stdout
46
+ // directly and NOT via console.log, which the branch below rewires to stderr for the ACP protocol.
47
+ const { collectVersionInfo, formatVersionInfo } = await import("./version-info.js");
48
+ process.stdout.write(`${formatVersionInfo(collectVersionInfo())}\n`);
49
+ process.exit(0);
50
+ }
40
51
  else {
41
52
  // Apply env vars from the managed-policy tier before any SDK call so the
42
53
  // SDK subprocess inherits them. Going through resolveSettings (vs. a raw
package/dist/tools.d.ts CHANGED
@@ -59,7 +59,9 @@ interface RawToolUse {
59
59
  export declare function toolInfoFromToolUse(toolUse: RawToolUse, supportsTerminalOutput?: boolean, cwd?: string): ToolInfo;
60
60
  export declare function toolUpdateFromToolResult(toolResult: ToolResultBlockParam | BetaToolResultBlockParam | BetaWebSearchToolResultBlockParam | BetaWebFetchToolResultBlockParam | WebSearchToolResultBlockParam | BetaCodeExecutionToolResultBlockParam | BetaBashCodeExecutionToolResultBlockParam | BetaTextEditorCodeExecutionToolResultBlockParam | BetaRequestMCPToolResultBlockParam | BetaToolSearchToolResultBlockParam, toolUse: {
61
61
  name?: string;
62
- } | undefined, supportsTerminalOutput?: boolean): ToolUpdate;
62
+ id?: string;
63
+ input?: unknown;
64
+ } | undefined, supportsTerminalOutput?: boolean, toolUseResult?: unknown): ToolUpdate;
63
65
  export type ClaudePlanEntry = {
64
66
  content: string;
65
67
  status: "pending" | "in_progress" | "completed";
package/dist/tools.js CHANGED
@@ -341,7 +341,89 @@ export function toolInfoFromToolUse(toolUse, supportsTerminalOutput = false, cwd
341
341
  };
342
342
  }
343
343
  }
344
- 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) {
345
427
  if ("is_error" in toolResult &&
346
428
  toolResult.is_error &&
347
429
  toolResult.content &&
@@ -353,8 +435,54 @@ export function toolUpdateFromToolResult(toolResult, toolUse, supportsTerminalOu
353
435
  // Only return errors
354
436
  return toAcpContentUpdate(toolResult.content, true);
355
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);
356
442
  switch (toolUse?.name) {
357
- 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
+ }
358
486
  if (Array.isArray(toolResult.content) && toolResult.content.length > 0) {
359
487
  return {
360
488
  content: toolResult.content.map((content) => ({
@@ -382,17 +510,62 @@ export function toolUpdateFromToolResult(toolResult, toolUse, supportsTerminalOu
382
510
  };
383
511
  }
384
512
  return {};
513
+ }
385
514
  case "Bash": {
386
515
  const result = toolResult.content;
387
- 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);
388
526
  const isError = "is_error" in toolResult && toolResult.is_error;
389
527
  // Extract output and exit code from either format:
390
- // 1. BetaBashCodeExecutionResultBlock: { type: "bash_code_execution_result", stdout, stderr, return_code }
391
- // 2. Plain string content from a regular tool_result
392
- // 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: "..." }])
393
537
  let output = "";
394
538
  let exitCode = isError ? 1 : 0;
395
- 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 &&
396
569
  typeof result === "object" &&
397
570
  "type" in result &&
398
571
  result.type === "bash_code_execution_result") {
@@ -409,7 +582,12 @@ export function toolUpdateFromToolResult(toolResult, toolUse, supportsTerminalOu
409
582
  typeof result[0].text === "string") {
410
583
  output = result.map((c) => c.text).join("\n");
411
584
  }
412
- 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) {
413
591
  return {
414
592
  content: [{ type: "terminal", terminalId }],
415
593
  _meta: {
@@ -451,11 +629,69 @@ export function toolUpdateFromToolResult(toolResult, toolUse, supportsTerminalOu
451
629
  case "ExitPlanMode": {
452
630
  return { title: "Exited Plan Mode" };
453
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
+ }
454
683
  default: {
455
- return toAcpContentUpdate(toolResult.content, "is_error" in toolResult ? toolResult.is_error : false);
684
+ return rawContentUpdate();
456
685
  }
457
686
  }
458
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
+ }
459
695
  function toAcpContentUpdate(content, isError = false) {
460
696
  if (Array.isArray(content) && content.length > 0) {
461
697
  return {
@@ -520,7 +756,7 @@ function toAcpContentBlock(content, isError) {
520
756
  case "tool_search_tool_result_error":
521
757
  return wrapText(`Error: ${content.error_code}${content.error_message ? ` - ${content.error_message}` : ""}`);
522
758
  case "web_search_result":
523
- return wrapText(`${content.title} (${content.url})`);
759
+ return wrapText(formatWebSearchHit(content));
524
760
  case "web_search_tool_result_error":
525
761
  return wrapText(`Error: ${content.error_code}`);
526
762
  case "web_fetch_result":
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Upstream tag currently vendored into src/ — kept in lockstep with `.fork-provenance.json`'s `tag`
3
+ * (re-anchored by sync stories; v0.57.0 came from story 074). A constant rather than a runtime read
4
+ * because the provenance JSON is not published with the package (see the header).
5
+ */
6
+ export declare const FORK_POINT_TAG = "v0.57.0";
7
+ /** Full 40-char upstream commit for {@link FORK_POINT_TAG} — lockstep with `.fork-provenance.json`'s `sha`. */
8
+ export declare const FORK_POINT_SHA = "2bf865eb42bbe744c476d38a005444eab8f4b624";
9
+ /**
10
+ * Printed in place of the `claude` version when the binary is not resolvable on PATH (R3.3).
11
+ *
12
+ * Deliberately carries NO `x.y.z` triple: a reader (or a test) scanning the output for a version must
13
+ * never mistake the marker for one, and a stale pin must never leak in as a consolation value.
14
+ */
15
+ export declare const CLAUDE_UNRESOLVED = "unresolved (not found on PATH)";
16
+ /** The three facts `--version` reports (R3.1). `claudeVersion` is `null` when unresolved/undetected. */
17
+ export interface VersionInfo {
18
+ /** `version` of THIS tree's package.json — read, never pinned (fork 0.5.2 vs mirror 0.8.0, R3.4). */
19
+ packageVersion: string;
20
+ /** Upstream tag the vendored src/ is anchored to ({@link FORK_POINT_TAG}). */
21
+ forkPointTag: string;
22
+ /** Full upstream commit for that tag ({@link FORK_POINT_SHA}). */
23
+ forkPointSha: string;
24
+ /** Live `claude --version`, or `null` when the binary is unresolvable or the probe failed. */
25
+ claudeVersion: string | null;
26
+ }
27
+ /**
28
+ * PURE renderer: three lines, one fact each — package version, fork point (tag + FULL sha), `claude`
29
+ * version or {@link CLAUDE_UNRESOLVED}.
30
+ *
31
+ * Returns a BARE string with NO trailing newline; the caller appends it. Depends only on its argument.
32
+ */
33
+ export declare function formatVersionInfo(info: VersionInfo): string;
34
+ /** Injectable seams for {@link collectVersionInfo} so tests never spawn a real `claude`. */
35
+ export interface VersionInfoDeps {
36
+ /** Override the package.json read (default: {@link readOwnPackageVersion}). */
37
+ readPackageVersion?: () => string;
38
+ /** Override the PATH resolve (default: {@link resolveQuietly}); throwing means "not installed". */
39
+ resolveClaude?: () => string;
40
+ /** Override the version probe (default: `detectClaudeVersion` — claude-path.ts). */
41
+ detectVersion?: (binPath: string) => string | null;
42
+ }
43
+ /**
44
+ * Collect the three `--version` facts (R3.1), degrading instead of failing (R3.3).
45
+ *
46
+ * Every source of truth is an injectable seam with a production default, so the whole payload is
47
+ * unit-checkable without spawning a `claude`. An unresolvable binary costs only the `claudeVersion`
48
+ * field: the package version and the fork point are still collected and nothing escapes to the caller.
49
+ */
50
+ export declare function collectVersionInfo(deps?: VersionInfoDeps): VersionInfo;
@@ -0,0 +1,122 @@
1
+ // === Story 080 / Task 4.2 (R3.1–R3.3) — the `--version` payload: pure collect + pure format ======
2
+ //
3
+ // Ports upstream #813's `--version` flag. The entrypoint (src/index.ts) short-circuits on the flag,
4
+ // prints the three fields this module produces, and exits 0 BEFORE any session is opened, any PTY is
5
+ // spawned or any turn is started (R3.2).
6
+ //
7
+ // WHY ITS OWN MODULE: src/index.ts is a side-effecting entrypoint with a top-level await into the ACP
8
+ // bootstrap — importing it from a test WOULD start the agent. Keeping the collect/format halves here
9
+ // makes them reachable as plain functions, so the whole payload is unit-checkable without a process
10
+ // (the usage-env.ts / live-diff-env.ts precedent). It imports nothing from the ACP, PTY or engine
11
+ // side of the tree, and it is pinned that way by test/version-flag.test.ts.
12
+ //
13
+ // WHY THE FORK POINT IS TWO CONSTANTS, NOT A READ OF .fork-provenance.json: that file is NOT listed in
14
+ // package.json `files`, so a published install ships no such file to read — a runtime read would work
15
+ // in the repo and fail for every user. The constants are instead held in lockstep with the JSON by an
16
+ // assertion in test/version-flag.test.ts, which is what stops them drifting. Same precedent as
17
+ // PROVENANCE_CLAUDE_VERSION in src/claude-path.ts.
18
+ //
19
+ // INVARIANTS:
20
+ // - formatVersionInfo is PURE and returns a BARE 3-line string (no trailing newline — the caller
21
+ // adds it), so the shape is assertable without touching stdout.
22
+ // - collectVersionInfo NEVER throws when `claude` is missing from PATH: the fail-loud resolver error
23
+ // is caught and degraded to `claudeVersion: null`, the remaining fields are still collected, and
24
+ // the entrypoint still exits 0 (R3.3).
25
+ // - The `claude` binary is spawned AT MOST ONCE (see resolveQuietly below), and only to read its
26
+ // version — args-list, no shell, via claude-path.ts's detector.
27
+ //
28
+ // node:test runner: `node --experimental-strip-types --test test/version-flag.test.ts`
29
+ import { readFileSync } from "node:fs";
30
+ import { detectClaudeVersion, resolveClaudePath } from "./claude-path.js";
31
+ /**
32
+ * Upstream tag currently vendored into src/ — kept in lockstep with `.fork-provenance.json`'s `tag`
33
+ * (re-anchored by sync stories; v0.57.0 came from story 074). A constant rather than a runtime read
34
+ * because the provenance JSON is not published with the package (see the header).
35
+ */
36
+ export const FORK_POINT_TAG = "v0.57.0";
37
+ /** Full 40-char upstream commit for {@link FORK_POINT_TAG} — lockstep with `.fork-provenance.json`'s `sha`. */
38
+ export const FORK_POINT_SHA = "2bf865eb42bbe744c476d38a005444eab8f4b624";
39
+ /**
40
+ * Printed in place of the `claude` version when the binary is not resolvable on PATH (R3.3).
41
+ *
42
+ * Deliberately carries NO `x.y.z` triple: a reader (or a test) scanning the output for a version must
43
+ * never mistake the marker for one, and a stale pin must never leak in as a consolation value.
44
+ */
45
+ export const CLAUDE_UNRESOLVED = "unresolved (not found on PATH)";
46
+ /** Fallback for line 1 when the shipped package.json carries no readable `version` string. */
47
+ const UNKNOWN_PACKAGE_VERSION = "unknown";
48
+ /**
49
+ * PURE renderer: three lines, one fact each — package version, fork point (tag + FULL sha), `claude`
50
+ * version or {@link CLAUDE_UNRESOLVED}.
51
+ *
52
+ * Returns a BARE string with NO trailing newline; the caller appends it. Depends only on its argument.
53
+ */
54
+ export function formatVersionInfo(info) {
55
+ return [
56
+ `claude-agent-tui ${info.packageVersion}`,
57
+ `fork point: ${info.forkPointTag} (${info.forkPointSha})`,
58
+ `claude: ${info.claudeVersion ?? CLAUDE_UNRESOLVED}`,
59
+ ].join("\n");
60
+ }
61
+ /**
62
+ * Read `version` out of the package.json that ships NEXT TO this module's own directory.
63
+ *
64
+ * Resolved against `import.meta.url`, not `process.cwd()`, so it reports the installed package's own
65
+ * version from `dist/` no matter where the binary was invoked from. Falls back to
66
+ * {@link UNKNOWN_PACKAGE_VERSION} if the field is missing or not a string.
67
+ */
68
+ function readOwnPackageVersion() {
69
+ const raw = readFileSync(new URL("../package.json", import.meta.url), "utf8");
70
+ const parsed = JSON.parse(raw);
71
+ return typeof parsed.version === "string" ? parsed.version : UNKNOWN_PACKAGE_VERSION;
72
+ }
73
+ /**
74
+ * Resolve `claude` from PATH with the resolver's own observability DISABLED.
75
+ *
76
+ * `resolveClaudePath` normally runs a best-effort `claude --version` probe and logs a resolve/drift
77
+ * line to stderr. Both are unwanted here: `--version` must print the version block and nothing else,
78
+ * and the binary must be spawned exactly once. Passing a null-returning `detectVersion` plus a no-op
79
+ * `log` suppresses the probe and the log, leaving {@link detectResolvedClaudeVersion}'s own detector
80
+ * call the single spawn (measured: one `claude --version`, no other argv). Still THROWS when nothing
81
+ * is on PATH — that fail-loud signal is exactly what R3.3 degrades to `null`.
82
+ */
83
+ function resolveQuietly() {
84
+ return resolveClaudePath({ detectVersion: () => null, log: () => { } });
85
+ }
86
+ /**
87
+ * Resolve `claude`, then read its version — degrading BOTH failure modes to `null` (R3.3).
88
+ *
89
+ * The two steps are deliberately sequential rather than combined: when `resolve` throws (the fail-loud
90
+ * "no claude on PATH" error) this returns EARLY, so `detect` is never handed a path that does not
91
+ * exist. When `detect` itself fails it already answers `null` by contract (`detectClaudeVersion` never
92
+ * throws — claude-path.ts). Either way the caller gets `null` and no exception escapes.
93
+ */
94
+ function detectResolvedClaudeVersion(resolve, detect) {
95
+ let binPath;
96
+ try {
97
+ binPath = resolve();
98
+ }
99
+ catch {
100
+ // A missing `claude` is not an error for `--version`: report the rest and exit 0 (R3.3).
101
+ return null;
102
+ }
103
+ return detect(binPath);
104
+ }
105
+ /**
106
+ * Collect the three `--version` facts (R3.1), degrading instead of failing (R3.3).
107
+ *
108
+ * Every source of truth is an injectable seam with a production default, so the whole payload is
109
+ * unit-checkable without spawning a `claude`. An unresolvable binary costs only the `claudeVersion`
110
+ * field: the package version and the fork point are still collected and nothing escapes to the caller.
111
+ */
112
+ export function collectVersionInfo(deps = {}) {
113
+ const readPackageVersion = deps.readPackageVersion ?? readOwnPackageVersion;
114
+ const resolveClaude = deps.resolveClaude ?? resolveQuietly;
115
+ const detectVersion = deps.detectVersion ?? detectClaudeVersion;
116
+ return {
117
+ packageVersion: readPackageVersion(),
118
+ forkPointTag: FORK_POINT_TAG,
119
+ forkPointSha: FORK_POINT_SHA,
120
+ claudeVersion: detectResolvedClaudeVersion(resolveClaude, detectVersion),
121
+ };
122
+ }
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.8.0",
6
+ "version": "0.10.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",
@@ -60,24 +60,24 @@
60
60
  "author": "lucascouts",
61
61
  "license": "Apache-2.0",
62
62
  "engines": {
63
- "node": ">=20"
63
+ "node": ">=24"
64
64
  },
65
65
  "dependencies": {
66
- "@agentclientprotocol/sdk": "1.2.0",
67
- "@anthropic-ai/claude-agent-sdk": "0.3.202",
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.110.0",
72
+ "@anthropic-ai/sdk": "0.115.0",
73
73
  "@eslint/js": "10.0.1",
74
- "@types/node": "26.1.0",
75
- "@typescript-eslint/eslint-plugin": "8.62.1",
76
- "@typescript-eslint/parser": "8.62.1",
77
- "eslint": "10.6.0",
74
+ "@types/node": "26.1.2",
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.9.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
  }