@lucascouts/claude-agent-tui 0.15.1 → 0.16.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.
@@ -469,6 +469,12 @@ export interface AgentDeps {
469
469
  * nothing → the reader uses its billing-free `~/.claude` glob + `fs` read defaults.
470
470
  */
471
471
  diffEnrichOptions?: DiffEnrichedReaderOptions;
472
+ /**
473
+ * Locate a session's transcript for the compacted-history replay ({@link withPrecompactHistory}).
474
+ * Defaults to `diffEnrichOptions.findTranscript`, then to the `~/.claude/projects` glob. Read only
475
+ * on `session/load` of a thread whose first SDK message is a compaction summary.
476
+ */
477
+ findTranscript?: (sessionId: string) => string[];
472
478
  /**
473
479
  * Story 044 (R4.1/R4.2) — opt IN to the live sub-agent watcher: the Option-B 2nd watcher that
474
480
  * POLLs the SDK sidechain readers while a turn is in flight, feeding the story-024 detector's
@@ -713,6 +719,7 @@ export declare class ClaudeAcpAgent implements Agent {
713
719
  private readonly startEngine;
714
720
  /** Override for the live JSONL reader the pump re-reads (default: SDK getSessionMessages). */
715
721
  private readonly getMessages?;
722
+ private readonly precompactOptions;
716
723
  /** Story 041 — the sidechain readers the pump sources nested sub-agent rows from; default to the
717
724
  * SDK's pure `listSubagents` / `getSubagentMessages` (tests inject stubs). */
718
725
  private readonly listSubagents;
package/dist/acp-agent.js CHANGED
@@ -19,6 +19,7 @@ import { linearizeTurns, readOrderedMessages, defaultGetMessages } from "./linea
19
19
  import { createDiffEnrichedReader } from "./diff-enriched-reader.js";
20
20
  import { backgroundTaskEnds } from "./background-task-end.js";
21
21
  import { readTranscriptPermissionMode } from "./resumed-permission-mode.js";
22
+ import { withPrecompactHistory } from "./compacted-history.js";
22
23
  import { sourceSubagentRows, defaultListSubagents, defaultGetSubagentMessages, hasSubagentSpawn, spawnIdsOpen, } from "./subagent-source.js";
23
24
  import { collectSidechainToolUses, registerSidechainGateToolUses, } from "./subagent-gate.js";
24
25
  import { createSubagentWatcher } from "./subagent-watcher.js";
@@ -810,6 +811,10 @@ export class ClaudeAcpAgent {
810
811
  },
811
812
  })
812
813
  : deps.getMessages;
814
+ this.precompactOptions = {
815
+ findTranscript: deps.findTranscript ?? deps.diffEnrichOptions?.findTranscript,
816
+ hydrateToolUseResult: deps.liveDiff ?? false,
817
+ };
813
818
  this.listSubagents = deps.listSubagents ?? defaultListSubagents;
814
819
  this.getSubagentMessages = deps.getSubagentMessages ?? defaultGetSubagentMessages;
815
820
  this.usageUpdate = deps.usageUpdate ?? false;
@@ -2029,9 +2034,10 @@ export class ClaudeAcpAgent {
2029
2034
  // Read via the SAME seam + ordering the live tail pump uses (readOrderedMessages → getSessionMessages,
2030
2035
  // then linearizeTurns), so a LOADED thread orders identically to a LIVE one (story 026 R4.1/R4.2) and
2031
2036
  // an R1.3 SDK-drift error is surfaced loudly rather than swallowed.
2032
- const messages = await readOrderedMessages(sessionId, session.cwd, {
2033
- getMessages: this.getMessages,
2034
- });
2037
+ // getSessionMessages stops at the last compaction boundary; put the history before it back, so a
2038
+ // reopened compacted thread scrolls to its first prompt (ported from plus). Replay-only on purpose:
2039
+ // the live pump has already emitted that history, and its detector cursor counts SDK messages.
2040
+ const messages = await withPrecompactHistory(sessionId, await readOrderedMessages(sessionId, session.cwd, { getMessages: this.getMessages }), this.precompactOptions);
2035
2041
  // Emit through the SHARED source+merge+linearize+emit loop the live pump runs — top-level turns
2036
2042
  // (toAcpNotifications + structuredPatch diff + optional usage_update) AND the nested sub-agent rows
2037
2043
  // (story 041) on their spawning Task id. Factoring this single loop is what GUARANTEES loaded == live
@@ -3655,9 +3661,15 @@ export function toAcpNotifications(content, role, sessionId, toolUseCache, clien
3655
3661
  case "compaction_delta":
3656
3662
  case "advisor_tool_result":
3657
3663
  case "fallback":
3664
+ case "mcp_tool_listing":
3658
3665
  // `fallback`: model-routing marker (@anthropic-ai/sdk >= 0.104) — from/to
3659
3666
  // model hops, no renderable content. No-op like the control blocks above.
3660
3667
  //
3668
+ // `mcp_tool_listing` (@anthropic-ai/sdk >= 0.131): the tool list an MCP
3669
+ // server returned while the response was produced, carried so the API can
3670
+ // reuse it when the message is sent back. A cache for the API, not content
3671
+ // for the user — skipped like `container_upload`, as claude-agent-plus does.
3672
+ //
3661
3673
  // `mid_conv_system` sat in this list until @anthropic-ai/sdk 0.120.0, whose
3662
3674
  // changelog removes it as an "unsupported content block" — the API never
3663
3675
  // emitted one. The case and the bump had to move together: the switch is
@@ -0,0 +1,52 @@
1
+ import type { SessionMessage } from "./engine-watcher.js";
2
+ /** Seams for {@link withPrecompactHistory}; production passes the defaults. */
3
+ export interface PrecompactHistoryOptions {
4
+ /** Locate `<sessionId>.jsonl`; the first match is read. Default: the SDK's config-dir glob. */
5
+ findTranscript?: (sessionId: string) => string[];
6
+ /**
7
+ * Attach each record's raw `toolUseResult`, as the diff-enriched reader does for the messages
8
+ * after the boundary. Set it exactly when that reader is in use, so both halves render alike.
9
+ */
10
+ hydrateToolUseResult?: boolean;
11
+ }
12
+ /**
13
+ * The history a compaction hid from `getSessionMessages`, put back in front of it.
14
+ *
15
+ * `getSessionMessages` walks `parentUuid` back from the newest record, and a `compact_boundary`
16
+ * has `parentUuid: null`, so the walk ends there: a reopened compacted thread replays only what
17
+ * came after the compaction summary. Measured 2026-10-14 on this machine's compacted transcripts
18
+ * (PARITY-REPORT §21.7): 21 of 43 prompts replayed, and 1 of 19. The boundary does remember what
19
+ * it followed (`logicalParentUuid`), and the SDK never reads it.
20
+ *
21
+ * This reads the transcript itself and walks back across the boundary: through
22
+ * `logicalParentUuid` when that record is in the file, else from the last main-chain record
23
+ * written before the boundary (a manual `/compact` can name a parent the file never received),
24
+ * and across every earlier boundary the same way. What it returns has the shape and the filters
25
+ * `getSessionMessages` uses — user and assistant records only, never `isMeta`, never a sidechain
26
+ * — so the replay loop cannot tell the two halves apart.
27
+ *
28
+ * It only reads anything when the SDK's first message IS a compaction summary, which SDK
29
+ * >= 0.3.284 flags with `isCompactSummary`; an uncompacted session costs nothing. It never writes.
30
+ */
31
+ export declare function withPrecompactHistory(sessionId: string, messages: SessionMessage[], opts?: PrecompactHistoryOptions): Promise<SessionMessage[]>;
32
+ type TranscriptRecord = {
33
+ type?: string;
34
+ subtype?: string;
35
+ uuid?: string;
36
+ parentUuid?: string | null;
37
+ logicalParentUuid?: string | null;
38
+ isSidechain?: boolean;
39
+ isMeta?: boolean;
40
+ isCompactSummary?: boolean;
41
+ message?: unknown;
42
+ timestamp?: string;
43
+ toolUseResult?: unknown;
44
+ line: number;
45
+ };
46
+ export declare function parseTranscript(text: string): TranscriptRecord[];
47
+ /** The main-chain history written before the LAST compaction boundary, oldest first, in
48
+ * `getSessionMessages`'s shape. Empty when the file has no boundary. */
49
+ export declare function precompactMessages(records: TranscriptRecord[], sessionId: string, opts?: {
50
+ hydrateToolUseResult?: boolean;
51
+ }): SessionMessage[];
52
+ export {};
@@ -0,0 +1,146 @@
1
+ // Ported from claude-agent-plus `src/compacted-history.ts` (2026-10-15), adapted to this fork's
2
+ // transcript locator (a glob under `~/.claude/projects`, see jsonl.ts) and to its diff-enriched
3
+ // reader (a pre-compaction tool result keeps its `toolUseResult` when the caller asks for it).
4
+ import { globSync } from "node:fs";
5
+ import { readFile } from "node:fs/promises";
6
+ import { homedir } from "node:os";
7
+ import { join } from "node:path";
8
+ /**
9
+ * `<sessionId>.jsonl` anywhere under `<configDir>/projects`, with `configDir` resolved exactly as the SDK's
10
+ * `getSessionMessages` resolves it (`CLAUDE_CONFIG_DIR`, else `~/.claude`): the file read here must
11
+ * be the one the SDK just read, or the two halves of the history would come from different files.
12
+ */
13
+ function defaultFindTranscript(sessionId) {
14
+ const configDir = process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
15
+ return globSync(join(configDir, "projects", "**", `${sessionId}.jsonl`));
16
+ }
17
+ /**
18
+ * The history a compaction hid from `getSessionMessages`, put back in front of it.
19
+ *
20
+ * `getSessionMessages` walks `parentUuid` back from the newest record, and a `compact_boundary`
21
+ * has `parentUuid: null`, so the walk ends there: a reopened compacted thread replays only what
22
+ * came after the compaction summary. Measured 2026-10-14 on this machine's compacted transcripts
23
+ * (PARITY-REPORT §21.7): 21 of 43 prompts replayed, and 1 of 19. The boundary does remember what
24
+ * it followed (`logicalParentUuid`), and the SDK never reads it.
25
+ *
26
+ * This reads the transcript itself and walks back across the boundary: through
27
+ * `logicalParentUuid` when that record is in the file, else from the last main-chain record
28
+ * written before the boundary (a manual `/compact` can name a parent the file never received),
29
+ * and across every earlier boundary the same way. What it returns has the shape and the filters
30
+ * `getSessionMessages` uses — user and assistant records only, never `isMeta`, never a sidechain
31
+ * — so the replay loop cannot tell the two halves apart.
32
+ *
33
+ * It only reads anything when the SDK's first message IS a compaction summary, which SDK
34
+ * >= 0.3.284 flags with `isCompactSummary`; an uncompacted session costs nothing. It never writes.
35
+ */
36
+ export async function withPrecompactHistory(sessionId, messages, opts = {}) {
37
+ if (!startsWithCompactSummary(messages))
38
+ return messages;
39
+ let file;
40
+ try {
41
+ file = (opts.findTranscript ?? defaultFindTranscript)(sessionId)[0];
42
+ }
43
+ catch {
44
+ return messages;
45
+ }
46
+ if (!file)
47
+ return messages;
48
+ let text;
49
+ try {
50
+ text = await readFile(file, "utf8");
51
+ }
52
+ catch {
53
+ return messages;
54
+ }
55
+ const earlier = precompactMessages(parseTranscript(text), sessionId, {
56
+ hydrateToolUseResult: opts.hydrateToolUseResult,
57
+ });
58
+ if (earlier.length === 0)
59
+ return messages;
60
+ const seen = new Set(messages.map((message) => message.uuid));
61
+ // Messages a compaction preserved keep their uuid on both sides of the boundary; the copy
62
+ // after it is the one the SDK already returns.
63
+ return [...earlier.filter((message) => !seen.has(message.uuid)), ...messages];
64
+ }
65
+ export function parseTranscript(text) {
66
+ const records = [];
67
+ const lines = text.split("\n");
68
+ for (let line = 0; line < lines.length; line++) {
69
+ if (!lines[line].trim())
70
+ continue;
71
+ try {
72
+ const parsed = JSON.parse(lines[line]);
73
+ if (parsed && typeof parsed === "object")
74
+ records.push({ ...parsed, line });
75
+ }
76
+ catch {
77
+ // A torn last line from a crashed writer: skip it, as the SDK does.
78
+ }
79
+ }
80
+ return records;
81
+ }
82
+ function isBoundary(record) {
83
+ return record.type === "system" && record.subtype === "compact_boundary";
84
+ }
85
+ function isMainChain(record) {
86
+ return typeof record.uuid === "string" && record.isSidechain !== true;
87
+ }
88
+ /** The main-chain history written before the LAST compaction boundary, oldest first, in
89
+ * `getSessionMessages`'s shape. Empty when the file has no boundary. */
90
+ export function precompactMessages(records, sessionId, opts = {}) {
91
+ const byUuid = new Map();
92
+ for (const record of records)
93
+ if (record.uuid)
94
+ byUuid.set(record.uuid, record);
95
+ const boundaries = records.filter(isBoundary);
96
+ const last = boundaries[boundaries.length - 1];
97
+ if (!last)
98
+ return [];
99
+ // Where a boundary's history continues: its logical parent when the file has it, else the
100
+ // last main-chain record written before the boundary.
101
+ const continuation = (boundary) => {
102
+ const logical = boundary.logicalParentUuid ? byUuid.get(boundary.logicalParentUuid) : undefined;
103
+ if (logical)
104
+ return logical;
105
+ for (let i = records.indexOf(boundary) - 1; i >= 0; i--) {
106
+ if (isMainChain(records[i]) && !isBoundary(records[i]))
107
+ return records[i];
108
+ }
109
+ return undefined;
110
+ };
111
+ const chain = [];
112
+ const visited = new Set();
113
+ let cursor = continuation(last);
114
+ while (cursor && cursor.uuid && !visited.has(cursor.uuid)) {
115
+ visited.add(cursor.uuid);
116
+ if (isBoundary(cursor)) {
117
+ cursor = continuation(cursor);
118
+ continue;
119
+ }
120
+ chain.push(cursor);
121
+ cursor = cursor.parentUuid ? byUuid.get(cursor.parentUuid) : undefined;
122
+ }
123
+ return chain
124
+ .reverse()
125
+ .filter((record) => (record.type === "user" || record.type === "assistant") &&
126
+ record.isMeta !== true &&
127
+ record.isSidechain !== true)
128
+ .map((record) => ({
129
+ type: record.type,
130
+ uuid: record.uuid,
131
+ session_id: sessionId,
132
+ message: record.message,
133
+ parent_tool_use_id: null,
134
+ parent_agent_id: null,
135
+ ...(record.isCompactSummary ? { isCompactSummary: true } : {}),
136
+ is_meta: false,
137
+ ...(record.timestamp ? { timestamp: record.timestamp } : {}),
138
+ ...(opts.hydrateToolUseResult && record.toolUseResult !== undefined
139
+ ? { toolUseResult: record.toolUseResult }
140
+ : {}),
141
+ }));
142
+ }
143
+ function startsWithCompactSummary(messages) {
144
+ const first = messages[0];
145
+ return first?.isCompactSummary === true;
146
+ }
@@ -41,6 +41,17 @@ export interface LinearizeOptions extends ApplyPolicyOptions {
41
41
  /** Sidechain flattening policy (Task 2); defaults to `'nested'`. */
42
42
  sidechainPolicy?: SidechainPolicy;
43
43
  }
44
+ /**
45
+ * True for a transcript message delivered to the model from another agent, session or channel.
46
+ * Since SDK 0.3.284 `getSessionMessages` returns these as `is_meta` user messages whose content is
47
+ * the full harness framing (envelope XML plus the "not typed by your user" preamble). The user never
48
+ * typed them, so they are never a turn — on `session/load` replay AND on the live pump, which reads
49
+ * the same SDK reader here. Other `is_meta` messages (compaction summaries) are kept. Ported from
50
+ * claude-agent-plus, which took it from upstream #1208.
51
+ *
52
+ * `is_meta` and `origin` are runtime fields the SDK does not declare on `SessionMessage`.
53
+ */
54
+ export declare function isReplayHiddenMetaMessage(message: unknown): boolean;
44
55
  /**
45
56
  * The stable, uuid-anchored, append-only order key (Task 3.1, R3.1/R3.2).
46
57
  *
package/dist/linearize.js CHANGED
@@ -64,8 +64,38 @@ function isMetaMsg(m) {
64
64
  const rec = m;
65
65
  if (rec.isMeta === true)
66
66
  return true;
67
+ if (isReplayHiddenMetaMessage(m))
68
+ return true;
67
69
  return m.type === "summary" || m.type === "system";
68
70
  }
71
+ /** Origin kinds of the meta user messages `getSessionMessages` returns since SDK 0.3.284 (messages
72
+ * from other agents, sessions and channels) — the SDK's own inclusion set for meta rows. */
73
+ const REPLAY_HIDDEN_META_ORIGIN_KINDS = new Set([
74
+ "peer",
75
+ "channel",
76
+ "observer",
77
+ "observer-activity",
78
+ "slack-ping",
79
+ ]);
80
+ /**
81
+ * True for a transcript message delivered to the model from another agent, session or channel.
82
+ * Since SDK 0.3.284 `getSessionMessages` returns these as `is_meta` user messages whose content is
83
+ * the full harness framing (envelope XML plus the "not typed by your user" preamble). The user never
84
+ * typed them, so they are never a turn — on `session/load` replay AND on the live pump, which reads
85
+ * the same SDK reader here. Other `is_meta` messages (compaction summaries) are kept. Ported from
86
+ * claude-agent-plus, which took it from upstream #1208.
87
+ *
88
+ * `is_meta` and `origin` are runtime fields the SDK does not declare on `SessionMessage`.
89
+ */
90
+ export function isReplayHiddenMetaMessage(message) {
91
+ if (!message || typeof message !== "object")
92
+ return false;
93
+ const { type, is_meta, origin } = message;
94
+ return (type === "user" &&
95
+ is_meta === true &&
96
+ typeof origin?.kind === "string" &&
97
+ REPLAY_HIDDEN_META_ORIGIN_KINDS.has(origin.kind));
98
+ }
69
99
  /** Parent uuid when carried by the input (raw fixture / fallback); `null` otherwise. */
70
100
  function parentUuidOf(m) {
71
101
  const rec = m;
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.15.1",
6
+ "version": "0.16.1",
7
7
  "description": "Runs the official Claude Code TUI over a PTY and exposes it via ACP, so Claude Code threads render natively in Zed's agent panel. Built for Anthropic's June 2026 billing split (since paused).",
8
8
  "main": "dist/lib.js",
9
9
  "types": "dist/lib.d.ts",
@@ -64,21 +64,21 @@
64
64
  "node": ">=24"
65
65
  },
66
66
  "dependencies": {
67
- "@agentclientprotocol/sdk": "1.5.1",
68
- "@anthropic-ai/claude-agent-sdk": "0.3.261",
67
+ "@agentclientprotocol/sdk": "1.8.0",
68
+ "@anthropic-ai/claude-agent-sdk": "0.3.296",
69
69
  "node-pty": "1.1.0",
70
70
  "zod": "^4.0.0"
71
71
  },
72
72
  "devDependencies": {
73
- "@anthropic-ai/sdk": "0.126.0",
73
+ "@anthropic-ai/sdk": "0.132.1",
74
74
  "@eslint/js": "10.0.1",
75
- "@types/node": "26.6.1",
76
- "@typescript-eslint/eslint-plugin": "8.70.0",
77
- "@typescript-eslint/parser": "8.70.0",
78
- "eslint": "10.10.0",
75
+ "@types/node": "26.6.4",
76
+ "@typescript-eslint/eslint-plugin": "8.71.1",
77
+ "@typescript-eslint/parser": "8.71.1",
78
+ "eslint": "10.12.0",
79
79
  "eslint-config-prettier": "10.1.8",
80
- "globals": "17.12.0",
81
- "prettier": "3.9.8",
80
+ "globals": "17.13.0",
81
+ "prettier": "3.9.9",
82
82
  "ts-node": "10.9.2",
83
83
  "typescript": "6.0.3"
84
84
  }