@lucascouts/claude-agent-tui 0.11.1 → 0.12.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.
@@ -486,11 +486,17 @@ export interface AgentDeps {
486
486
  * resolves the session's `summary` from its JSONL — custom title, auto-summary, or first prompt).
487
487
  * Injected by the unit tests with an in-memory fake so the push is exercised hermetically, never
488
488
  * touching the real `~/.claude` transcript tree. Production passes nothing → the real SDK reader.
489
+ *
490
+ * Task 3.2 (#984): the push reads the record's `lastModified` as well, published as ACP
491
+ * `updatedAt`. OPTIONAL here even though the SDK's own `SDKSessionInfo` always sets it — an
492
+ * injected fake may legitimately supply a summary alone, and {@link ClaudeAcpAgent} treats a
493
+ * missing timestamp as "no timestamp", never as a reason to withhold the title.
489
494
  */
490
495
  getSessionInfo?: (sessionId: string, options?: {
491
496
  dir?: string;
492
497
  }) => Promise<{
493
498
  summary: string;
499
+ lastModified?: number;
494
500
  } | undefined>;
495
501
  /**
496
502
  * Story 073 (R1) — override the fast-mode availability probe (default: {@link defaultFastModeProbe},
@@ -671,7 +677,7 @@ export declare class ClaudeAcpAgent implements Agent {
671
677
  /** Story 063 (R1/R1.1) — offline `available_commands` discovery seam; see {@link AgentDeps.discoverCommands}. */
672
678
  private readonly discoverCommands;
673
679
  /** Story 056 (#812) — SDK session-metadata reader for the end-of-turn title push; see
674
- * {@link AgentDeps.getSessionInfo}. */
680
+ * {@link AgentDeps.getSessionInfo}. Task 3.2 (#984) reads its `lastModified` too. */
675
681
  private readonly getSessionInfo;
676
682
  /** Story 073 (R1) — fast-mode availability probe seam; see {@link AgentDeps.fastModeProbe}. */
677
683
  private readonly fastModeProbe;
@@ -704,6 +710,9 @@ export declare class ClaudeAcpAgent implements Agent {
704
710
  * so an unchanged title is not re-emitted, and silent when `getSessionInfo` finds no transcript /
705
711
  * the title is empty. Every error is swallowed and logged — this MUST NEVER reject the turn (it is
706
712
  * never awaited in `prompt()`), and a slow/never-resolving reader cannot delay the PromptResponse.
713
+ *
714
+ * Task 3.2 (#984): the record's `lastModified` rides along as ACP `updatedAt` whenever it is
715
+ * usable. See the block above for what this port does NOT deliver (R5.3).
707
716
  */
708
717
  private emitSessionTitleUpdate;
709
718
  cancel(params: CancelNotification): Promise<void>;
package/dist/acp-agent.js CHANGED
@@ -55,6 +55,28 @@ function sanitizeTitle(text) {
55
55
  }
56
56
  return sanitized.slice(0, MAX_TITLE_LENGTH - 1) + "…";
57
57
  }
58
+ /**
59
+ * Task 3.2 (#984) — the ISO 8601 form of a `getSessionInfo` record's `lastModified` (epoch ms), or
60
+ * `undefined` when the record carries no usable one.
61
+ *
62
+ * Total by construction, and that is the whole point: `new Date(x).toISOString()` THROWS on an
63
+ * out-of-range value, and its only caller runs inside a catch that swallows — so an unguarded
64
+ * conversion would not surface a bad timestamp, it would silently drop the entire title push.
65
+ * Missing / NaN / out-of-range therefore degrades to "no timestamp" (ACP's `updatedAt` is optional),
66
+ * never to "no title".
67
+ *
68
+ * All three checks earn their place. `Number.isFinite` (unlike the global `isFinite`) does NOT
69
+ * coerce, so it rejects NaN, ±Infinity and anything a loosely-typed fake passes that is not a
70
+ * number — but it does not narrow the type, which is what the `undefined` test is for. And finite
71
+ * is not the same as representable: `new Date(1e20)` takes a finite input and yields Invalid Date,
72
+ * whose `toISOString()` is exactly the throw this function exists to prevent.
73
+ */
74
+ function isoLastModified(lastModified) {
75
+ if (lastModified === undefined || !Number.isFinite(lastModified))
76
+ return undefined;
77
+ const at = new Date(lastModified);
78
+ return Number.isNaN(at.getTime()) ? undefined : at.toISOString();
79
+ }
58
80
  export const DEFAULT_CONTEXT_WINDOW = 200000;
59
81
  /** Production default — fail-closed (R1.2), invariant-safe: performs NO PTY write, so it preserves the
60
82
  * read-only-load (R4.3) and no-unsolicited-Ctrl+U invariants. The live signal is characterized (see
@@ -515,6 +537,13 @@ export function isLocalCommandMetadata(content) {
515
537
  const PERMISSION_MODE_ALIASES = {
516
538
  auto: "auto",
517
539
  default: "default",
540
+ // Ported from upstream #1004 (REBASE-AND-DRIFT.md §15.5). Claude Code 2.1.200 renamed
541
+ // the "default" mode to "Manual" and accepts `"defaultMode": "manual"` in settings.json.
542
+ // This matters more here than upstream: the engine drives whatever `claude` is on PATH,
543
+ // which is far newer than the 2.1.159 provenance pin, so a settings file written by the
544
+ // current CLI can already say "manual". Without this row it resolved to "default" via
545
+ // the unknown-value branch — same outcome, but with a spurious error logged every load.
546
+ manual: "default",
518
547
  acceptedits: "acceptEdits",
519
548
  dontask: "dontAsk",
520
549
  plan: "plan",
@@ -1049,6 +1078,35 @@ export class ClaudeAcpAgent {
1049
1078
  this.flushPendingControlInjections(sessionRecord);
1050
1079
  }
1051
1080
  }
1081
+ // ─── Task 3.2 (R5.2, R5.3) — the session title, and what this port does NOT deliver ──────────
1082
+ //
1083
+ // WHAT IT DELIVERS. Upstream #984 titles a session from two sources, tried in order: first
1084
+ // `query.generateSessionTitle`, a model-WRITTEN title asked for on the live SDK `Query`; and, when
1085
+ // that is unavailable, `getSessionInfo(sessionId, { dir })`, which reads the session's own record
1086
+ // off disk. Only the second one ports, because only the second one exists here — `createSession`
1087
+ // is a CUT seam (SEAM-MAP), so there is no `Query` to ask, and disk is what this engine already
1088
+ // reads. A record is a summary AND the moment it was written, so both travel: the sanitized
1089
+ // summary as `title`, its `lastModified` as ACP's `updatedAt`. Dropping the timestamp would take
1090
+ // the string from disk without the record it came from, leaving a client holding titles it has no
1091
+ // way to order.
1092
+ //
1093
+ // WHAT IT DOES NOT DELIVER. Stated here on purpose: the difference between a port and a claim of
1094
+ // parity is whether the code admits its own gap (REBASE-AND-DRIFT.md §15.7).
1095
+ //
1096
+ // • `query.generateSessionTitle` IS CUT — no model ever writes a title in this adapter. What is
1097
+ // published is whatever the transcript already held: a `/rename`, the CLI's own auto-summary,
1098
+ // or the first prompt verbatim. That is upstream's FALLBACK — the degraded branch it takes
1099
+ // when the generator is unreachable — so a session that upstream would have titled in words
1100
+ // gets its raw first prompt instead.
1101
+ // • AND THAT DEGRADATION IS VISIBLE. Unlike the per-model usage of §15.6, this surface IS
1102
+ // consumed: `session_info_update` is what a client renders as the session's name. The gap
1103
+ // above reaches a user rather than sitting inert.
1104
+ // • `updatedAt` IS THE TITLE'S TIMESTAMP, NOT THE SESSION'S. ACP defines the field as "last
1105
+ // activity", but the push is deduped on the title, so a record whose `lastModified` moved
1106
+ // while its summary did not emits nothing and that newer time is never sent. What a client
1107
+ // receives is the mtime of the record that produced the CURRENT title. Widening the dedup to
1108
+ // the timestamp would match ACP's wording and re-push an identical title every turn — the
1109
+ // louder bug of the two; the narrower claim is the honest one.
1052
1110
  /**
1053
1111
  * Story 056 (#812) — push the sanitized session title to the client via `session_info_update`,
1054
1112
  * fired (fire-and-forget) by the story-024 end-of-turn boundary ONLY (never on cancel/watchdog,
@@ -1056,6 +1114,9 @@ export class ClaudeAcpAgent {
1056
1114
  * so an unchanged title is not re-emitted, and silent when `getSessionInfo` finds no transcript /
1057
1115
  * the title is empty. Every error is swallowed and logged — this MUST NEVER reject the turn (it is
1058
1116
  * never awaited in `prompt()`), and a slow/never-resolving reader cannot delay the PromptResponse.
1117
+ *
1118
+ * Task 3.2 (#984): the record's `lastModified` rides along as ACP `updatedAt` whenever it is
1119
+ * usable. See the block above for what this port does NOT deliver (R5.3).
1059
1120
  */
1060
1121
  async emitSessionTitleUpdate(sessionId) {
1061
1122
  const session = this.sessions[sessionId];
@@ -1066,12 +1127,20 @@ export class ClaudeAcpAgent {
1066
1127
  if (!info)
1067
1128
  return; // no transcript / not found → nothing to push
1068
1129
  const title = sanitizeTitle(info.summary);
1130
+ // Deduped on the TITLE alone, never on the record: two summaries that sanitize to the same
1131
+ // string are ONE title, and a record touched without its summary changing is not a new one.
1069
1132
  if (!title || title === session.lastEmittedTitle)
1070
1133
  return; // dedup + never push empty
1071
1134
  session.lastEmittedTitle = title;
1135
+ // #984: publish the disk record the title came from, not only the string it yielded. The key
1136
+ // is OMITTED rather than sent as null when unknown — ACP reads a null `updatedAt` as "clear
1137
+ // it", which would assert an absence this port has not established.
1138
+ const updatedAt = isoLastModified(info.lastModified);
1072
1139
  await this.client.sessionUpdate({
1073
1140
  sessionId,
1074
- update: { sessionUpdate: "session_info_update", title },
1141
+ update: updatedAt
1142
+ ? { sessionUpdate: "session_info_update", title, updatedAt }
1143
+ : { sessionUpdate: "session_info_update", title },
1075
1144
  });
1076
1145
  }
1077
1146
  catch (err) {
@@ -2654,27 +2723,45 @@ export class ClaudeAcpAgent {
2654
2723
  */
2655
2724
  function buildAvailableModes(modelInfo) {
2656
2725
  const modes = [];
2726
+ // `_meta.kind` is ported from upstream #1025 (REBASE-AND-DRIFT.md §15.5): a coarse
2727
+ // classification a client can style or group by, alongside the free-text description.
2728
+ // Only the CATALOGUE ports — upstream applies the mode through `query.setPermissionMode`,
2729
+ // which is CUT here (SEAM-MAP); this engine keeps its own story-032 gate path.
2730
+ //
2731
+ // Names and descriptions are deliberately NOT taken from upstream. Upstream renamed
2732
+ // "Default" to "Manual" in the same commit; adopting that here would change the label
2733
+ // Zed already shows without changing behaviour, and the alias row above already accepts
2734
+ // "manual" on the way in. Wire ids are what both sides agree on.
2657
2735
  // Only advertise "auto" when the SDK reports the model supports it.
2658
2736
  if (modelInfo?.supportsAutoMode === true) {
2659
2737
  modes.push({
2660
2738
  id: "auto",
2661
2739
  name: "Auto",
2662
2740
  description: "Use a model classifier to approve/deny permission prompts",
2741
+ _meta: { kind: "auto_review" },
2663
2742
  });
2664
2743
  }
2665
2744
  modes.push({
2666
2745
  id: "default",
2667
2746
  name: "Default",
2668
2747
  description: "Standard behavior, prompts for dangerous operations",
2748
+ _meta: { kind: "standard" },
2669
2749
  }, {
2670
2750
  id: "acceptEdits",
2671
2751
  name: "Accept Edits",
2672
2752
  description: "Auto-accept file edit operations",
2753
+ _meta: { kind: "standard" },
2673
2754
  }, {
2674
2755
  id: "plan",
2675
2756
  name: "Plan Mode",
2676
2757
  description: "Planning mode, no actual tool execution",
2758
+ _meta: { kind: "plan" },
2677
2759
  }, {
2760
+ // No `_meta.kind`, matching the decision `claude-agent-fork` reached independently
2761
+ // for the same mode: upstream's four kinds all describe a mode that ASKS or
2762
+ // AUTO-APPROVES, and `dontAsk` DENIES instead. Claiming any of them would assert a
2763
+ // semantic upstream has not defined. `dontAsk` is absent from upstream's catalogue
2764
+ // entirely — it is a Claude Code mode, and omitting the key is how that shows.
2678
2765
  id: "dontAsk",
2679
2766
  name: "Don't Ask",
2680
2767
  description: "Don't prompt for permissions, deny if not pre-approved. Selecting this restarts the session.",
@@ -2684,6 +2771,7 @@ function buildAvailableModes(modelInfo) {
2684
2771
  id: "bypassPermissions",
2685
2772
  name: "Bypass Permissions",
2686
2773
  description: "Bypass all permission checks. Selecting this restarts the session.",
2774
+ _meta: { kind: "full_access" },
2687
2775
  });
2688
2776
  }
2689
2777
  return modes;
@@ -2703,10 +2791,15 @@ function buildConfigOptions(modes, currentModelId, modelInfos, currentEffortLeve
2703
2791
  category: "mode",
2704
2792
  type: "select",
2705
2793
  currentValue: modes.currentModeId,
2794
+ // `_meta` rides along with the mode (upstream #1025, §15.5). The config-option and
2795
+ // `session/set_mode` surfaces describe the SAME catalogue, so a client that reads the
2796
+ // kind from one must find it on the other; dropping it here would make the mode's
2797
+ // classification depend on which surface Zed happened to read.
2706
2798
  options: modes.availableModes.map((m) => ({
2707
2799
  value: m.id,
2708
2800
  name: m.name,
2709
2801
  description: m.description,
2802
+ _meta: m._meta,
2710
2803
  })),
2711
2804
  },
2712
2805
  {
@@ -3326,10 +3419,15 @@ export function toAcpNotifications(content, role, sessionId, toolUseCache, clien
3326
3419
  case "compaction":
3327
3420
  case "compaction_delta":
3328
3421
  case "advisor_tool_result":
3329
- case "mid_conv_system":
3330
3422
  case "fallback":
3331
3423
  // `fallback`: model-routing marker (@anthropic-ai/sdk >= 0.104) — from/to
3332
3424
  // model hops, no renderable content. No-op like the control blocks above.
3425
+ //
3426
+ // `mid_conv_system` sat in this list until @anthropic-ai/sdk 0.120.0, whose
3427
+ // changelog removes it as an "unsupported content block" — the API never
3428
+ // emitted one. The case and the bump had to move together: the switch is
3429
+ // exhaustive against `unreachable`, so keeping the case fails to compile on
3430
+ // 0.120.0 (TS2678) and dropping it fails on 0.117.1 (TS2345).
3333
3431
  break;
3334
3432
  default:
3335
3433
  unreachable(chunk, logger);
package/dist/usage.d.ts CHANGED
@@ -9,6 +9,12 @@ export interface UsageCarrier {
9
9
  input_tokens?: number | null;
10
10
  output_tokens?: number | null;
11
11
  } | null;
12
+ /**
13
+ * The turn's model id, as the JSONL writes it on `assistant.message.model` (story 066).
14
+ * Read ONLY by {@link usageByModel}; {@link toUsageUpdate} ignores it — the pinned wire
15
+ * shape has no field for it. Optional and possibly empty, like every other field here.
16
+ */
17
+ model?: string | null;
12
18
  }
13
19
  export interface UsageOptions {
14
20
  /**
@@ -54,3 +60,27 @@ export interface UsageFlagOptions extends UsageOptions {
54
60
  * shape (see {@link toUsageUpdate}): no `cost`, and `size` is the inferred window on the live path.
55
61
  */
56
62
  export declare function usageUpdatesFor(message: UsageCarrier, options?: UsageFlagOptions): UsageUpdateNotification[];
63
+ /**
64
+ * The key a turn's usage is filed under: its model id verbatim, or `null` when the turn carries no
65
+ * usable model tag.
66
+ *
67
+ * `null` rather than a string sentinel, and that is a correctness choice, not a style one. R5.1
68
+ * names only `assistant.message.model`, so the untagged bucket is a key this port INVENTS — and any
69
+ * string it invented could collide with a real model id. A turn tagged `"unknown"` is a model named
70
+ * "unknown"; a turn with no tag is a different thing entirely, and folding the two together would
71
+ * report two unrelated things as one row. `null` cannot collide, because no model id is `null`.
72
+ */
73
+ export type UsageModelKey = string | null;
74
+ /**
75
+ * Task 3.1 (R5.1) — group token usage per model, keyed by the JSONL's per-turn
76
+ * `assistant.message.model`. PURE and TOTAL, like the rest of this module: it never throws on a
77
+ * partial carrier and never fabricates a count.
78
+ *
79
+ * Each key's value is `input_tokens + output_tokens` summed across every turn filed under it — the
80
+ * same `used` arithmetic {@link toUsageUpdate} emits (R2.2), only partitioned. A carrier with no
81
+ * token counts at ALL contributes nothing and opens no row, matching that function's best-effort
82
+ * skip; a carrier reporting a genuine zero is not the same thing and does open one.
83
+ *
84
+ * See the block comment above for what this does NOT deliver (R5.3).
85
+ */
86
+ export declare function usageByModel(messages: Iterable<UsageCarrier>): Map<UsageModelKey, number>;
package/dist/usage.js CHANGED
@@ -8,6 +8,23 @@
8
8
  //
9
9
  // Kept a self-contained module (cf. diff-source.ts) imported by the acp-agent pump; it does
10
10
  // NOT go through lib.ts (the frozen upstream export surface).
11
+ /**
12
+ * The tokens ONE carrier accounts for — `input_tokens + output_tokens` — or `undefined` when it
13
+ * carries neither count.
14
+ *
15
+ * That `undefined` is the §1 best-effort skip, and it lives here so the module has exactly ONE
16
+ * definition of "there is nothing to report": {@link toUsageUpdate} turns it into an emitted
17
+ * nothing, {@link usageByModel} into an absent row. A genuine zero is a count, not a skip — only
18
+ * absence (missing or null on BOTH fields) skips, so the two can never drift on that distinction.
19
+ */
20
+ function tokensUsed(message) {
21
+ const input = message?.usage?.input_tokens;
22
+ const output = message?.usage?.output_tokens;
23
+ if ((input === undefined || input === null) && (output === undefined || output === null)) {
24
+ return undefined;
25
+ }
26
+ return (input ?? 0) + (output ?? 0);
27
+ }
11
28
  /**
12
29
  * Task 3.2 (R3.2) — map a message-event `usage.{input,output}_tokens` into the UNSTABLE
13
30
  * `usage_update` notification. PURE and TOTAL: returns `undefined` (best-effort skip, §1)
@@ -27,13 +44,10 @@
27
44
  * in the interactive PTY+tail JSONL mapped here (the 68 substring hits were all conversation text).
28
45
  */
29
46
  export function toUsageUpdate(message, options = {}) {
30
- const input = message.usage?.input_tokens;
31
- const output = message.usage?.output_tokens;
47
+ const used = tokensUsed(message);
32
48
  // best-effort: no usage tokens at all -> emit nothing, never fabricate.
33
- if ((input === undefined || input === null) && (output === undefined || output === null)) {
49
+ if (used === undefined)
34
50
  return undefined;
35
- }
36
- const used = (input ?? 0) + (output ?? 0);
37
51
  const size = options.contextWindowSize ?? used;
38
52
  return { sessionUpdate: "usage_update", size, used };
39
53
  }
@@ -55,3 +69,41 @@ export function usageUpdatesFor(message, options = {}) {
55
69
  const update = toUsageUpdate(message, options);
56
70
  return update ? [update] : [];
57
71
  }
72
+ /**
73
+ * The model key for one carrier. VERBATIM: the id is used exactly as the JSONL wrote it, with no
74
+ * normalisation, lower-casing, prefix match or suffix stripping. `claude-opus-4-8` and
75
+ * `claude-opus-4-8[1m]` are two models with two different context windows (see
76
+ * `inferContextWindowFromModelId`), so any rule that merged them would merge two models' spend into
77
+ * one row.
78
+ *
79
+ * Absent, non-string or EMPTY tags fold into the untagged bucket. The `length > 0` half matches the
80
+ * convention the live path already uses on this exact field (acp-agent.ts, story 069): an empty
81
+ * string is a missing tag, not a model whose name is "".
82
+ */
83
+ function modelKeyOf(model) {
84
+ return typeof model === "string" && model.length > 0 ? model : null;
85
+ }
86
+ /**
87
+ * Task 3.1 (R5.1) — group token usage per model, keyed by the JSONL's per-turn
88
+ * `assistant.message.model`. PURE and TOTAL, like the rest of this module: it never throws on a
89
+ * partial carrier and never fabricates a count.
90
+ *
91
+ * Each key's value is `input_tokens + output_tokens` summed across every turn filed under it — the
92
+ * same `used` arithmetic {@link toUsageUpdate} emits (R2.2), only partitioned. A carrier with no
93
+ * token counts at ALL contributes nothing and opens no row, matching that function's best-effort
94
+ * skip; a carrier reporting a genuine zero is not the same thing and does open one.
95
+ *
96
+ * See the block comment above for what this does NOT deliver (R5.3).
97
+ */
98
+ export function usageByModel(messages) {
99
+ const totals = new Map();
100
+ for (const message of messages) {
101
+ const used = tokensUsed(message);
102
+ // best-effort: no usage tokens at all -> no row, never a fabricated zero.
103
+ if (used === undefined)
104
+ continue;
105
+ const key = modelKeyOf(message?.model);
106
+ totals.set(key, (totals.get(key) ?? 0) + used);
107
+ }
108
+ return totals;
109
+ }
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.11.1",
6
+ "version": "0.12.1",
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",
@@ -64,17 +64,17 @@
64
64
  },
65
65
  "dependencies": {
66
66
  "@agentclientprotocol/sdk": "1.3.0",
67
- "@anthropic-ai/claude-agent-sdk": "0.3.232",
67
+ "@anthropic-ai/claude-agent-sdk": "0.3.238",
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.117.1",
72
+ "@anthropic-ai/sdk": "0.122.0",
73
73
  "@eslint/js": "10.0.1",
74
- "@types/node": "26.2.0",
75
- "@typescript-eslint/eslint-plugin": "8.67.0",
76
- "@typescript-eslint/parser": "8.67.0",
77
- "eslint": "10.8.1",
74
+ "@types/node": "26.4.0",
75
+ "@typescript-eslint/eslint-plugin": "8.68.0",
76
+ "@typescript-eslint/parser": "8.68.0",
77
+ "eslint": "10.9.1",
78
78
  "eslint-config-prettier": "10.1.8",
79
79
  "globals": "17.11.0",
80
80
  "prettier": "3.9.6",