@lucascouts/claude-agent-tui 0.15.0 → 0.16.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/acp-agent.d.ts +38 -1
- package/dist/acp-agent.js +93 -12
- package/dist/background-task-end.d.ts +11 -0
- package/dist/background-task-end.js +92 -0
- package/dist/compacted-history.d.ts +52 -0
- package/dist/compacted-history.js +146 -0
- package/dist/diff-enriched-reader.d.ts +6 -0
- package/dist/diff-enriched-reader.js +1 -0
- package/dist/linearize.d.ts +11 -0
- package/dist/linearize.js +30 -0
- package/dist/resumed-permission-mode.d.ts +6 -0
- package/dist/resumed-permission-mode.js +104 -0
- package/dist/tools.d.ts +16 -2
- package/dist/tools.js +45 -6
- package/package.json +10 -10
package/dist/acp-agent.d.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { SessionEngine } from "./engine-lifecycle.js";
|
|
|
10
10
|
import type { SessionWatcher } from "./engine-lifecycle.js";
|
|
11
11
|
import type { JsonlWatcher, GetMessages, SessionMessage } from "./engine-watcher.js";
|
|
12
12
|
import type { LocateOptions } from "./jsonl.js";
|
|
13
|
+
import { type BackgroundTaskEnd } from "./background-task-end.js";
|
|
13
14
|
import type { DiffEnrichedReaderOptions } from "./diff-enriched-reader.js";
|
|
14
15
|
import type { ListSubagents, GetSubagentMessages } from "./subagent-source.js";
|
|
15
16
|
import { type SidechainToolUse } from "./subagent-gate.js";
|
|
@@ -52,6 +53,19 @@ type Session = {
|
|
|
52
53
|
* was surfaced in an earlier pump). Per-session — sub-agent row uuids are session-scoped.
|
|
53
54
|
*/
|
|
54
55
|
emittedNested: Set<string>;
|
|
56
|
+
/**
|
|
57
|
+
* Item 92 (upstream #1312) — ended background tasks, keyed by the `tool_use_id` of the Bash call that
|
|
58
|
+
* started them, re-derived from the raw transcript on every read (`backgroundTaskEnds`). Absent when
|
|
59
|
+
* the raw transcript is not read (`liveDiff` off), which is also when no result is known to be
|
|
60
|
+
* backgrounded.
|
|
61
|
+
*/
|
|
62
|
+
backgroundTaskEnds?: Map<string, BackgroundTaskEnd>;
|
|
63
|
+
/**
|
|
64
|
+
* Item 92 — terminals of backgrounded commands whose exit the live pump held back at the tool result
|
|
65
|
+
* because the command was still running; {@link ClaudeAcpAgent.flushBackgroundExits} sends each exit
|
|
66
|
+
* once the task's notification reaches the transcript.
|
|
67
|
+
*/
|
|
68
|
+
heldBackgroundExits?: Set<string>;
|
|
55
69
|
/**
|
|
56
70
|
* Story 056 (#812) — the last session title pushed to the client via `session_info_update` at the
|
|
57
71
|
* story-024 turn boundary. Used to DEDUP: `emitSessionTitleUpdate` skips the push when the freshly
|
|
@@ -269,6 +283,11 @@ export interface StartedEngine {
|
|
|
269
283
|
watcher?: JsonlWatcher | SessionWatcher;
|
|
270
284
|
engine?: SessionEngine;
|
|
271
285
|
cwd?: string;
|
|
286
|
+
/**
|
|
287
|
+
* Item 107: the located transcript, set by the replay-only load path so `createSession` can read
|
|
288
|
+
* the permission mode it last recorded. Absent on the spawning paths.
|
|
289
|
+
*/
|
|
290
|
+
transcriptPath?: string;
|
|
272
291
|
}
|
|
273
292
|
/** Arguments passed to {@link StartEngine}. `sessionId` is the requested id for resume/fork; for a
|
|
274
293
|
* fresh session it is undefined and the engine's spawn generates the authoritative id. */
|
|
@@ -450,6 +469,12 @@ export interface AgentDeps {
|
|
|
450
469
|
* nothing → the reader uses its billing-free `~/.claude` glob + `fs` read defaults.
|
|
451
470
|
*/
|
|
452
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[];
|
|
453
478
|
/**
|
|
454
479
|
* Story 044 (R4.1/R4.2) — opt IN to the live sub-agent watcher: the Option-B 2nd watcher that
|
|
455
480
|
* POLLs the SDK sidechain readers while a turn is in flight, feeding the story-024 detector's
|
|
@@ -631,7 +656,7 @@ export type ToolUpdateMeta = {
|
|
|
631
656
|
};
|
|
632
657
|
terminal_exit?: {
|
|
633
658
|
terminal_id: string;
|
|
634
|
-
exit_code: number;
|
|
659
|
+
exit_code: number | null;
|
|
635
660
|
signal: string | null;
|
|
636
661
|
};
|
|
637
662
|
};
|
|
@@ -694,6 +719,7 @@ export declare class ClaudeAcpAgent implements Agent {
|
|
|
694
719
|
private readonly startEngine;
|
|
695
720
|
/** Override for the live JSONL reader the pump re-reads (default: SDK getSessionMessages). */
|
|
696
721
|
private readonly getMessages?;
|
|
722
|
+
private readonly precompactOptions;
|
|
697
723
|
/** Story 041 — the sidechain readers the pump sources nested sub-agent rows from; default to the
|
|
698
724
|
* SDK's pure `listSubagents` / `getSubagentMessages` (tests inject stubs). */
|
|
699
725
|
private readonly listSubagents;
|
|
@@ -994,6 +1020,13 @@ export declare class ClaudeAcpAgent implements Agent {
|
|
|
994
1020
|
* is NO SDK message stream. The end-of-turn predicate is story 024; this only consumes the signal.
|
|
995
1021
|
*/
|
|
996
1022
|
private pumpUpdates;
|
|
1023
|
+
/**
|
|
1024
|
+
* Item 92 (upstream #1312) — send the terminal exit of each backgrounded command whose task has now
|
|
1025
|
+
* ended. The live pump held that exit back at the tool result (the command was still running); the
|
|
1026
|
+
* task's `<task-notification>` in the raw transcript is its end, and its summary the code. Each held
|
|
1027
|
+
* exit is sent once. Live-only: replay never holds an exit, so it has nothing to flush.
|
|
1028
|
+
*/
|
|
1029
|
+
private flushBackgroundExits;
|
|
997
1030
|
/**
|
|
998
1031
|
* Story 041 (R3.1, R3.2) — the SHARED source+merge+linearize+emit loop run by BOTH the live tail pump
|
|
999
1032
|
* ({@link pumpUpdates}) and the `session/load` replay ({@link replaySessionHistory}), so a LOADED
|
|
@@ -1084,6 +1117,10 @@ export declare function toAcpNotifications(content: string | ContentBlockParam[]
|
|
|
1084
1117
|
cwd?: string;
|
|
1085
1118
|
taskState?: TaskState;
|
|
1086
1119
|
toolUseResult?: unknown;
|
|
1120
|
+
background?: {
|
|
1121
|
+
ended: (toolUseId: string) => BackgroundTaskEnd | undefined;
|
|
1122
|
+
held?: Set<string>;
|
|
1123
|
+
};
|
|
1087
1124
|
}): SessionNotification[];
|
|
1088
1125
|
export declare function streamEventToAcpNotifications(message: SDKPartialAssistantMessage, sessionId: string, toolUseCache: ToolUseCache, client: AgentSideConnection, logger: Logger, options?: {
|
|
1089
1126
|
clientCapabilities?: ClientCapabilities;
|
package/dist/acp-agent.js
CHANGED
|
@@ -17,6 +17,9 @@ import { createJsonlWatcher } from "./engine-watcher.js";
|
|
|
17
17
|
import { resolveWatchTarget } from "./jsonl.js";
|
|
18
18
|
import { linearizeTurns, readOrderedMessages, defaultGetMessages } from "./linearize.js";
|
|
19
19
|
import { createDiffEnrichedReader } from "./diff-enriched-reader.js";
|
|
20
|
+
import { backgroundTaskEnds } from "./background-task-end.js";
|
|
21
|
+
import { readTranscriptPermissionMode } from "./resumed-permission-mode.js";
|
|
22
|
+
import { withPrecompactHistory } from "./compacted-history.js";
|
|
20
23
|
import { sourceSubagentRows, defaultListSubagents, defaultGetSubagentMessages, hasSubagentSpawn, spawnIdsOpen, } from "./subagent-source.js";
|
|
21
24
|
import { collectSidechainToolUses, registerSidechainGateToolUses, } from "./subagent-gate.js";
|
|
22
25
|
import { createSubagentWatcher } from "./subagent-watcher.js";
|
|
@@ -193,13 +196,16 @@ export async function defaultStartEngine(args) {
|
|
|
193
196
|
// sessionId glob ambiguous → resourceNotFound on the next load. A missing/ambiguous transcript
|
|
194
197
|
// throws here → createSession's resume catch maps it to resourceNotFound (unchanged client
|
|
195
198
|
// contract). No PTY, no tail watcher, no live engine — the only emission is replaySessionHistory.
|
|
196
|
-
const { cwd } = await resolveWatchTarget(args.sessionId, {
|
|
199
|
+
const { cwd, transcriptPath } = await resolveWatchTarget(args.sessionId, {
|
|
200
|
+
...args.locateOptions,
|
|
201
|
+
});
|
|
197
202
|
return {
|
|
198
203
|
sessionId: args.sessionId,
|
|
199
204
|
pty: REPLAY_ONLY_NOOP_PTY,
|
|
200
205
|
watcher: undefined,
|
|
201
206
|
engine: undefined,
|
|
202
207
|
cwd,
|
|
208
|
+
transcriptPath,
|
|
203
209
|
};
|
|
204
210
|
}
|
|
205
211
|
if (args.resume && args.sessionId) {
|
|
@@ -794,8 +800,21 @@ export class ClaudeAcpAgent {
|
|
|
794
800
|
// (index.ts) is what defaults it ON. OFF → byte-for-byte the pre-043 reduced reader (R5.1).
|
|
795
801
|
this.getMessages =
|
|
796
802
|
(deps.liveDiff ?? false)
|
|
797
|
-
? createDiffEnrichedReader(deps.getMessages ?? defaultGetMessages,
|
|
803
|
+
? createDiffEnrichedReader(deps.getMessages ?? defaultGetMessages, {
|
|
804
|
+
...deps.diffEnrichOptions,
|
|
805
|
+
// Item 92 (#1312): the same raw read yields the ended background tasks, so a held terminal
|
|
806
|
+
// exit costs no second read of the transcript.
|
|
807
|
+
onRawLines: (sid, lines) => {
|
|
808
|
+
const session = this.sessions[sid];
|
|
809
|
+
if (session)
|
|
810
|
+
session.backgroundTaskEnds = backgroundTaskEnds(lines);
|
|
811
|
+
},
|
|
812
|
+
})
|
|
798
813
|
: deps.getMessages;
|
|
814
|
+
this.precompactOptions = {
|
|
815
|
+
findTranscript: deps.findTranscript ?? deps.diffEnrichOptions?.findTranscript,
|
|
816
|
+
hydrateToolUseResult: deps.liveDiff ?? false,
|
|
817
|
+
};
|
|
799
818
|
this.listSubagents = deps.listSubagents ?? defaultListSubagents;
|
|
800
819
|
this.getSubagentMessages = deps.getSubagentMessages ?? defaultGetSubagentMessages;
|
|
801
820
|
this.usageUpdate = deps.usageUpdate ?? false;
|
|
@@ -2015,9 +2034,10 @@ export class ClaudeAcpAgent {
|
|
|
2015
2034
|
// Read via the SAME seam + ordering the live tail pump uses (readOrderedMessages → getSessionMessages,
|
|
2016
2035
|
// then linearizeTurns), so a LOADED thread orders identically to a LIVE one (story 026 R4.1/R4.2) and
|
|
2017
2036
|
// an R1.3 SDK-drift error is surfaced loudly rather than swallowed.
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
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);
|
|
2021
2041
|
// Emit through the SHARED source+merge+linearize+emit loop the live pump runs — top-level turns
|
|
2022
2042
|
// (toAcpNotifications + structuredPatch diff + optional usage_update) AND the nested sub-agent rows
|
|
2023
2043
|
// (story 041) on their spawning Task id. Factoring this single loop is what GUARANTEES loaded == live
|
|
@@ -2042,7 +2062,7 @@ export class ClaudeAcpAgent {
|
|
|
2042
2062
|
* live pump) rendered Edit/Write WITHOUT a diff; story 038 moved usage_update HERE for the SAME
|
|
2043
2063
|
* reason (loaded==live for usage). Only dedup and the billing guard-rail stay with the callers.
|
|
2044
2064
|
*/
|
|
2045
|
-
async emitTurnUpdates(sessionId, turn, toolUseCache) {
|
|
2065
|
+
async emitTurnUpdates(sessionId, turn, toolUseCache, live = false) {
|
|
2046
2066
|
const session = this.sessions[sessionId];
|
|
2047
2067
|
const source = turn.message;
|
|
2048
2068
|
const role = source.message?.role;
|
|
@@ -2065,6 +2085,12 @@ export class ClaudeAcpAgent {
|
|
|
2065
2085
|
cwd: session?.cwd,
|
|
2066
2086
|
taskState: session?.taskState,
|
|
2067
2087
|
toolUseResult: turnToolUseResult,
|
|
2088
|
+
// Item 92 (#1312): only the live pump can send a backgrounded command's exit later, so only
|
|
2089
|
+
// it holds the exit back; replay exits at the result.
|
|
2090
|
+
background: {
|
|
2091
|
+
ended: (id) => session?.backgroundTaskEnds?.get(id),
|
|
2092
|
+
held: live && session ? (session.heldBackgroundExits ??= new Set()) : undefined,
|
|
2093
|
+
},
|
|
2068
2094
|
})) {
|
|
2069
2095
|
await this.client.sessionUpdate(notification);
|
|
2070
2096
|
}
|
|
@@ -2369,7 +2395,8 @@ export class ClaudeAcpAgent {
|
|
|
2369
2395
|
// The merge MUST NOT reach the detector / §10 guard / §9 gate above — those already consumed the
|
|
2370
2396
|
// un-merged `messages` slice exactly-once (R4.1 structural: sub-agent rows never advance
|
|
2371
2397
|
// `detectorCursor` nor register as gate tool_uses).
|
|
2372
|
-
await this.emitLinearizedWithNested(sessionId, session, messages);
|
|
2398
|
+
await this.emitLinearizedWithNested(sessionId, session, messages, true);
|
|
2399
|
+
await this.flushBackgroundExits(sessionId, session);
|
|
2373
2400
|
// === SEAM(054) — feed the gate correlator from the sidechain rows (R3). Gated + LIVE-ONLY: runs
|
|
2374
2401
|
// only with a present, non-torndown gate, and NEVER inside the shared emitLinearizedWithNested that
|
|
2375
2402
|
// session/load replay also calls — so replay stays pure (U3). Additive: touches only the correlator +
|
|
@@ -2407,7 +2434,7 @@ export class ClaudeAcpAgent {
|
|
|
2407
2434
|
schedule: this.schedule,
|
|
2408
2435
|
onActivity: async () => {
|
|
2409
2436
|
session.turnDetector?.noteActivity();
|
|
2410
|
-
await this.emitLinearizedWithNested(sessionId, session, session.lastMessages ?? messages);
|
|
2437
|
+
await this.emitLinearizedWithNested(sessionId, session, session.lastMessages ?? messages, true);
|
|
2411
2438
|
},
|
|
2412
2439
|
});
|
|
2413
2440
|
}
|
|
@@ -2421,6 +2448,33 @@ export class ClaudeAcpAgent {
|
|
|
2421
2448
|
}
|
|
2422
2449
|
}
|
|
2423
2450
|
}
|
|
2451
|
+
/**
|
|
2452
|
+
* Item 92 (upstream #1312) — send the terminal exit of each backgrounded command whose task has now
|
|
2453
|
+
* ended. The live pump held that exit back at the tool result (the command was still running); the
|
|
2454
|
+
* task's `<task-notification>` in the raw transcript is its end, and its summary the code. Each held
|
|
2455
|
+
* exit is sent once. Live-only: replay never holds an exit, so it has nothing to flush.
|
|
2456
|
+
*/
|
|
2457
|
+
async flushBackgroundExits(sessionId, session) {
|
|
2458
|
+
const held = session.heldBackgroundExits;
|
|
2459
|
+
if (!held?.size)
|
|
2460
|
+
return;
|
|
2461
|
+
for (const terminalId of [...held]) {
|
|
2462
|
+
const end = session.backgroundTaskEnds?.get(terminalId);
|
|
2463
|
+
if (!end)
|
|
2464
|
+
continue;
|
|
2465
|
+
held.delete(terminalId);
|
|
2466
|
+
await this.client.sessionUpdate({
|
|
2467
|
+
sessionId,
|
|
2468
|
+
update: {
|
|
2469
|
+
sessionUpdate: "tool_call_update",
|
|
2470
|
+
toolCallId: terminalId,
|
|
2471
|
+
_meta: {
|
|
2472
|
+
terminal_exit: { terminal_id: terminalId, exit_code: end.exitCode, signal: null },
|
|
2473
|
+
},
|
|
2474
|
+
},
|
|
2475
|
+
});
|
|
2476
|
+
}
|
|
2477
|
+
}
|
|
2424
2478
|
/**
|
|
2425
2479
|
* Story 041 (R3.1, R3.2) — the SHARED source+merge+linearize+emit loop run by BOTH the live tail pump
|
|
2426
2480
|
* ({@link pumpUpdates}) and the `session/load` replay ({@link replaySessionHistory}), so a LOADED
|
|
@@ -2443,7 +2497,7 @@ export class ClaudeAcpAgent {
|
|
|
2443
2497
|
* un-merged main chain in the caller (sub-agent rows must never advance the detector cursor or register
|
|
2444
2498
|
* as gate tool_uses). The replay caller has no detector/gate feed, so it simply does not run one.
|
|
2445
2499
|
*/
|
|
2446
|
-
async emitLinearizedWithNested(sessionId, session, messages) {
|
|
2500
|
+
async emitLinearizedWithNested(sessionId, session, messages, live = false) {
|
|
2447
2501
|
const subagentRows = await sourceSubagentRows(sessionId, messages, {
|
|
2448
2502
|
dir: session.cwd,
|
|
2449
2503
|
listSubagents: this.listSubagents,
|
|
@@ -2456,7 +2510,7 @@ export class ClaudeAcpAgent {
|
|
|
2456
2510
|
// so live and loaded render byte-for-byte the same (story 026 R3.3; story 038 moved usage_update
|
|
2457
2511
|
// into the shared emit).
|
|
2458
2512
|
if (!(turn.uuid && session.emitted.has(turn.uuid))) {
|
|
2459
|
-
await this.emitTurnUpdates(sessionId, turn, session.toolUseCache);
|
|
2513
|
+
await this.emitTurnUpdates(sessionId, turn, session.toolUseCache, live);
|
|
2460
2514
|
if (turn.uuid)
|
|
2461
2515
|
session.emitted.add(turn.uuid);
|
|
2462
2516
|
}
|
|
@@ -2816,8 +2870,21 @@ export class ClaudeAcpAgent {
|
|
|
2816
2870
|
// is why the seed below can stay a constant.
|
|
2817
2871
|
const liveModelCatalog = await resolveModelCatalog(this.logger, this.modelCatalogSource);
|
|
2818
2872
|
const availableModes = buildAvailableModes(DEFAULT_MODEL_INFO, allowBypass);
|
|
2873
|
+
// Item 107 (plus 0.23.5 / upstream #1218's mode half): a replay-only load starts no engine, so the
|
|
2874
|
+
// pump that reconciles the mode from the transcript never runs, and the thread would advertise the
|
|
2875
|
+
// settings default. Seed it from the mode the transcript last recorded instead — only a mode this
|
|
2876
|
+
// session offers, so the bypass guard above still holds. Display-only: a loaded session runs
|
|
2877
|
+
// nothing until it is resumed.
|
|
2878
|
+
let currentModeId = seededMode;
|
|
2879
|
+
if (creationOpts.replayOnly && started.transcriptPath) {
|
|
2880
|
+
const recorded = await readTranscriptPermissionMode(started.transcriptPath);
|
|
2881
|
+
if (recorded !== undefined && availableModes.some((m) => m.id === recorded)) {
|
|
2882
|
+
// Every advertised mode id is a PermissionMode (buildAvailableModes builds them from it).
|
|
2883
|
+
currentModeId = recorded;
|
|
2884
|
+
}
|
|
2885
|
+
}
|
|
2819
2886
|
const modes = {
|
|
2820
|
-
currentModeId
|
|
2887
|
+
currentModeId,
|
|
2821
2888
|
availableModes,
|
|
2822
2889
|
};
|
|
2823
2890
|
// Story 056 (R3.2): discover the main-thread agent personas for THIS session's cwd (glob-only via
|
|
@@ -3540,7 +3607,15 @@ export function toAcpNotifications(content, role, sessionId, toolUseCache, clien
|
|
|
3540
3607
|
}
|
|
3541
3608
|
}
|
|
3542
3609
|
else if (toolUse.name !== "TodoWrite") {
|
|
3543
|
-
const
|
|
3610
|
+
const background = options?.background;
|
|
3611
|
+
const { _meta: toolMeta, ...toolUpdate } = toolUpdateFromToolResult(chunk, toolUseCache[chunk.tool_use_id], supportsTerminalOutput, toolUseResult, background
|
|
3612
|
+
? { ended: background.ended, holdRunning: background.held !== undefined }
|
|
3613
|
+
: undefined);
|
|
3614
|
+
// A terminal announced without its exit is a backgrounded command still running: remember it
|
|
3615
|
+
// so the live pump sends the exit when the task ends.
|
|
3616
|
+
if (background?.held && toolMeta?.terminal_info && !toolMeta.terminal_exit) {
|
|
3617
|
+
background.held.add(toolMeta.terminal_info.terminal_id);
|
|
3618
|
+
}
|
|
3544
3619
|
// When terminal output is supported, send terminal_output as a
|
|
3545
3620
|
// separate notification to match codex-acp's streaming lifecycle:
|
|
3546
3621
|
// 1. tool_call → _meta.terminal_info (already sent above)
|
|
@@ -3586,9 +3661,15 @@ export function toAcpNotifications(content, role, sessionId, toolUseCache, clien
|
|
|
3586
3661
|
case "compaction_delta":
|
|
3587
3662
|
case "advisor_tool_result":
|
|
3588
3663
|
case "fallback":
|
|
3664
|
+
case "mcp_tool_listing":
|
|
3589
3665
|
// `fallback`: model-routing marker (@anthropic-ai/sdk >= 0.104) — from/to
|
|
3590
3666
|
// model hops, no renderable content. No-op like the control blocks above.
|
|
3591
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
|
+
//
|
|
3592
3673
|
// `mid_conv_system` sat in this list until @anthropic-ai/sdk 0.120.0, whose
|
|
3593
3674
|
// changelog removes it as an "unsupported content block" — the API never
|
|
3594
3675
|
// emitted one. The case and the bump had to move together: the switch is
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** How a backgrounded command's task ended, as the notification reports it. */
|
|
2
|
+
export type BackgroundTaskEnd = {
|
|
3
|
+
status: string;
|
|
4
|
+
exitCode: number;
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* Index every ended background task in the raw transcript lines by the `tool_use_id` of the call that
|
|
8
|
+
* started it. Lines that are not JSON, or carry no notification, are skipped; the last notification for
|
|
9
|
+
* an id wins. Pure; never throws.
|
|
10
|
+
*/
|
|
11
|
+
export declare function backgroundTaskEnds(lines: readonly string[]): Map<string, BackgroundTaskEnd>;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// Item 92 (upstream #1312) — when a backgrounded command's task ended, read off the raw transcript.
|
|
2
|
+
//
|
|
3
|
+
// A `run_in_background` Bash returns its tool result as soon as the command detaches, so the result
|
|
4
|
+
// cannot carry the command's exit. Claude Code reports the end later, as a `<task-notification>` block
|
|
5
|
+
// naming the Bash call's `tool_use_id`. Measured on CLI 2.1.280 (`sdk-cli`) and on an interactive
|
|
6
|
+
// (`cli`) transcript: the block is written into a `queue-operation` (`content`) and a `queued_command`
|
|
7
|
+
// attachment (`prompt`), and can also reach the transcript as the text of a user message. None of those
|
|
8
|
+
// records reaches `getSessionMessages`' reduced shape, so the raw lines are the only source.
|
|
9
|
+
//
|
|
10
|
+
// The block carries no structured code. Its summary names one ("… completed (exit code 0)", "… failed
|
|
11
|
+
// with exit code 3"); without one, `completed` reads 0 and anything else 1, because Zeo marks a command
|
|
12
|
+
// failed only on a non-null non-zero code and a stopped or failed command is not a success.
|
|
13
|
+
const BLOCK = /<task-notification>([\s\S]*?)<\/task-notification>/g;
|
|
14
|
+
const SUMMARY_CODE = /exit code (\d+)/i;
|
|
15
|
+
function tag(block, name) {
|
|
16
|
+
const open = `<${name}>`;
|
|
17
|
+
const start = block.indexOf(open);
|
|
18
|
+
if (start === -1)
|
|
19
|
+
return undefined;
|
|
20
|
+
const end = block.indexOf(`</${name}>`, start + open.length);
|
|
21
|
+
if (end === -1)
|
|
22
|
+
return undefined;
|
|
23
|
+
return block.slice(start + open.length, end).trim();
|
|
24
|
+
}
|
|
25
|
+
function endOf(status, summary) {
|
|
26
|
+
const named = summary?.match(SUMMARY_CODE);
|
|
27
|
+
if (named)
|
|
28
|
+
return { status, exitCode: Number(named[1]) };
|
|
29
|
+
return { status, exitCode: status === "completed" ? 0 : 1 };
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The texts of one transcript record that may hold a notification Claude Code wrote. A tool_result's
|
|
33
|
+
* content and an assistant's text are deliberately excluded: `cat` of a transcript, or a model quoting
|
|
34
|
+
* one, would otherwise end a command that is still running.
|
|
35
|
+
*/
|
|
36
|
+
function notificationTexts(record) {
|
|
37
|
+
const texts = [];
|
|
38
|
+
if (record.type === "queue-operation" && typeof record.content === "string") {
|
|
39
|
+
texts.push(record.content);
|
|
40
|
+
}
|
|
41
|
+
const attachment = record.attachment;
|
|
42
|
+
if (record.type === "attachment" && attachment?.type === "queued_command") {
|
|
43
|
+
if (typeof attachment.prompt === "string")
|
|
44
|
+
texts.push(attachment.prompt);
|
|
45
|
+
}
|
|
46
|
+
const message = record.message;
|
|
47
|
+
if (record.type === "user" && message?.role === "user") {
|
|
48
|
+
if (typeof message.content === "string")
|
|
49
|
+
texts.push(message.content);
|
|
50
|
+
else if (Array.isArray(message.content)) {
|
|
51
|
+
for (const block of message.content) {
|
|
52
|
+
const b = block;
|
|
53
|
+
if (b?.type === "text" && typeof b.text === "string")
|
|
54
|
+
texts.push(b.text);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return texts;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Index every ended background task in the raw transcript lines by the `tool_use_id` of the call that
|
|
62
|
+
* started it. Lines that are not JSON, or carry no notification, are skipped; the last notification for
|
|
63
|
+
* an id wins. Pure; never throws.
|
|
64
|
+
*/
|
|
65
|
+
export function backgroundTaskEnds(lines) {
|
|
66
|
+
const ends = new Map();
|
|
67
|
+
for (const line of lines) {
|
|
68
|
+
// Cheap pre-filter: nearly every line carries no notification, and parsing them all is the cost.
|
|
69
|
+
if (!line.includes("task-notification"))
|
|
70
|
+
continue;
|
|
71
|
+
let record;
|
|
72
|
+
try {
|
|
73
|
+
record = JSON.parse(line);
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (!record || typeof record !== "object")
|
|
79
|
+
continue;
|
|
80
|
+
for (const text of notificationTexts(record)) {
|
|
81
|
+
for (const match of text.matchAll(BLOCK)) {
|
|
82
|
+
const block = match[1];
|
|
83
|
+
const toolUseId = tag(block, "tool-use-id");
|
|
84
|
+
const status = tag(block, "status");
|
|
85
|
+
if (!toolUseId || !status)
|
|
86
|
+
continue;
|
|
87
|
+
ends.set(toolUseId, endOf(status, tag(block, "summary")));
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return ends;
|
|
92
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -24,6 +24,12 @@ export interface DiffEnrichedReaderOptions {
|
|
|
24
24
|
* unreadable transcript for the R1.3 fallback) without touching the filesystem.
|
|
25
25
|
*/
|
|
26
26
|
readRawLines?: (path: string) => string[];
|
|
27
|
+
/**
|
|
28
|
+
* Item 92 (upstream #1312): handed the raw lines of every successful read, so a caller can derive
|
|
29
|
+
* more from the same read (the agent indexes ended background tasks) without reading the transcript
|
|
30
|
+
* twice. Not called when the transcript cannot be located or read.
|
|
31
|
+
*/
|
|
32
|
+
onRawLines?: (sessionId: string, lines: string[]) => void;
|
|
27
33
|
}
|
|
28
34
|
/**
|
|
29
35
|
* Wrap a base `getSessionMessages`-shaped reader so each returned message gains its `toolUseResult`
|
package/dist/linearize.d.ts
CHANGED
|
@@ -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;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The permission mode the transcript at `filePath` last recorded, or undefined when it records none,
|
|
3
|
+
* the last one is a `plan` that was exited, or the file cannot be read. Reads backwards in
|
|
4
|
+
* {@link TAIL_CHUNK_BYTES} chunks, so a long transcript costs only its tail.
|
|
5
|
+
*/
|
|
6
|
+
export declare function readTranscriptPermissionMode(filePath: string): Promise<string | undefined>;
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// Item 107 — the permission mode a loaded session was last in, read from the end of its transcript.
|
|
2
|
+
//
|
|
3
|
+
// Ported from the plus adapter's `readResumedPermissionMode` (its 0.23.5; upstream #1218's mode half)
|
|
4
|
+
// and adapted to the transcripts this adapter reads. Plus runs the SDK, whose transcripts record the
|
|
5
|
+
// mode only on prompt records. This adapter drives the INTERACTIVE CLI, which also writes
|
|
6
|
+
// `permission-mode` records — several per session, and the only mode record in a short session — and
|
|
7
|
+
// the live pump already reconciles from them (story 046). So both count here, and the tail-most wins.
|
|
8
|
+
//
|
|
9
|
+
// A `plan` before a later `plan_mode_exit` attachment is not the current mode and gives none: leaving
|
|
10
|
+
// plan mode through ExitPlanMode writes the attachment, not a mode. The search stops at the first mode,
|
|
11
|
+
// or at a human prompt that records none (a transcript that does not record modes). Sidechain
|
|
12
|
+
// (subagent) records are ignored. Best-effort: any failure gives undefined and the caller keeps its
|
|
13
|
+
// default.
|
|
14
|
+
import { open } from "node:fs/promises";
|
|
15
|
+
/** The size of one backward read of a transcript. */
|
|
16
|
+
const TAIL_CHUNK_BYTES = 64 * 1024;
|
|
17
|
+
/** Visits transcript lines from the end. */
|
|
18
|
+
class PermissionModeScan {
|
|
19
|
+
constructor() {
|
|
20
|
+
this.planExited = false;
|
|
21
|
+
}
|
|
22
|
+
/** Visit the previous line. Return true when the search is over. */
|
|
23
|
+
visit(line) {
|
|
24
|
+
let parsed;
|
|
25
|
+
// Most lines carry no marker of interest; the check skips their JSON parse.
|
|
26
|
+
const record = (marker) => {
|
|
27
|
+
if (line.indexOf(marker) < 0)
|
|
28
|
+
return undefined;
|
|
29
|
+
if (parsed === undefined)
|
|
30
|
+
parsed = parseMainThreadRecord(line);
|
|
31
|
+
return parsed ?? undefined;
|
|
32
|
+
};
|
|
33
|
+
const modeEntry = record('"permissionMode"');
|
|
34
|
+
if ((modeEntry?.type === "user" || modeEntry?.type === "permission-mode") &&
|
|
35
|
+
typeof modeEntry.permissionMode === "string" &&
|
|
36
|
+
modeEntry.permissionMode.trim() !== "") {
|
|
37
|
+
const mode = modeEntry.permissionMode.trim();
|
|
38
|
+
if (!(this.planExited && mode === "plan"))
|
|
39
|
+
this.mode = mode;
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
if (record('"plan_mode_exit"')?.attachment?.type === "plan_mode_exit") {
|
|
43
|
+
this.planExited = true;
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
const human = record('"human"');
|
|
47
|
+
return human?.type === "user" && human.origin?.kind === "human";
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** The parsed record of one line, or null for a subagent record or a bad line. */
|
|
51
|
+
function parseMainThreadRecord(line) {
|
|
52
|
+
let entry;
|
|
53
|
+
try {
|
|
54
|
+
entry = JSON.parse(line.toString("utf8"));
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
if (!entry || typeof entry !== "object")
|
|
60
|
+
return null;
|
|
61
|
+
const record = entry;
|
|
62
|
+
return record.isSidechain === true ? null : record;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The permission mode the transcript at `filePath` last recorded, or undefined when it records none,
|
|
66
|
+
* the last one is a `plan` that was exited, or the file cannot be read. Reads backwards in
|
|
67
|
+
* {@link TAIL_CHUNK_BYTES} chunks, so a long transcript costs only its tail.
|
|
68
|
+
*/
|
|
69
|
+
export async function readTranscriptPermissionMode(filePath) {
|
|
70
|
+
let handle;
|
|
71
|
+
try {
|
|
72
|
+
handle = await open(filePath, "r");
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
const scan = new PermissionModeScan();
|
|
78
|
+
try {
|
|
79
|
+
let end = (await handle.stat()).size;
|
|
80
|
+
// The bytes of the line whose start is not read yet, in file order.
|
|
81
|
+
let pending = [];
|
|
82
|
+
while (end > 0) {
|
|
83
|
+
const start = Math.max(0, end - TAIL_CHUNK_BYTES);
|
|
84
|
+
let chunk = Buffer.alloc(end - start);
|
|
85
|
+
await handle.read(chunk, 0, chunk.length, start);
|
|
86
|
+
for (let at = chunk.lastIndexOf(0x0a); at >= 0; at = chunk.lastIndexOf(0x0a)) {
|
|
87
|
+
if (scan.visit(Buffer.concat([chunk.subarray(at + 1), ...pending])))
|
|
88
|
+
return scan.mode;
|
|
89
|
+
pending = [];
|
|
90
|
+
chunk = chunk.subarray(0, at);
|
|
91
|
+
}
|
|
92
|
+
pending.unshift(chunk);
|
|
93
|
+
end = start;
|
|
94
|
+
}
|
|
95
|
+
scan.visit(Buffer.concat(pending));
|
|
96
|
+
return scan.mode;
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
finally {
|
|
102
|
+
await handle.close();
|
|
103
|
+
}
|
|
104
|
+
}
|
package/dist/tools.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { TaskCreateInput, TaskCreateOutput, TaskListOutput, TaskUpdateInput, Tas
|
|
|
4
4
|
import { ToolResultBlockParam, WebSearchToolResultBlockParam } from "@anthropic-ai/sdk/resources";
|
|
5
5
|
import { BetaBashCodeExecutionToolResultBlockParam, BetaCodeExecutionToolResultBlockParam, BetaRequestMCPToolResultBlockParam, BetaTextEditorCodeExecutionToolResultBlockParam, BetaToolResultBlockParam, BetaToolSearchToolResultBlockParam, BetaWebFetchToolResultBlockParam, BetaWebSearchToolResultBlockParam } from "@anthropic-ai/sdk/resources/beta.mjs";
|
|
6
6
|
import { Logger } from "./acp-agent.js";
|
|
7
|
+
import type { BackgroundTaskEnd } from "./background-task-end.js";
|
|
7
8
|
interface ToolInfo {
|
|
8
9
|
title: string;
|
|
9
10
|
kind: ToolKind;
|
|
@@ -24,11 +25,24 @@ interface ToolUpdate {
|
|
|
24
25
|
};
|
|
25
26
|
terminal_exit?: {
|
|
26
27
|
terminal_id: string;
|
|
27
|
-
exit_code: number;
|
|
28
|
+
exit_code: number | null;
|
|
28
29
|
signal: string | null;
|
|
29
30
|
};
|
|
30
31
|
};
|
|
31
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* Item 92 (upstream #1312) — how a backgrounded Bash's terminal exit is reported at its tool result.
|
|
35
|
+
* The result only announces the command; the command's end arrives later as a task notification.
|
|
36
|
+
*/
|
|
37
|
+
export type BackgroundExitPolicy = {
|
|
38
|
+
/** The task's end, when the transcript already holds its notification (keyed by tool_use id). */
|
|
39
|
+
ended: (toolUseId: string) => BackgroundTaskEnd | undefined;
|
|
40
|
+
/**
|
|
41
|
+
* Leave the exit out while the task runs. Only the live pump sets this, because only it sends the
|
|
42
|
+
* exit later ({@link ClaudeAcpAgent} `flushBackgroundExits`); every other caller exits at the result.
|
|
43
|
+
*/
|
|
44
|
+
holdRunning: boolean;
|
|
45
|
+
};
|
|
32
46
|
/**
|
|
33
47
|
* Convert an absolute file path to a project-relative path for display.
|
|
34
48
|
* Returns the original path if it's outside the project directory or if no cwd is provided.
|
|
@@ -61,7 +75,7 @@ export declare function toolUpdateFromToolResult(toolResult: ToolResultBlockPara
|
|
|
61
75
|
name?: string;
|
|
62
76
|
id?: string;
|
|
63
77
|
input?: unknown;
|
|
64
|
-
} | undefined, supportsTerminalOutput?: boolean, toolUseResult?: unknown): ToolUpdate;
|
|
78
|
+
} | undefined, supportsTerminalOutput?: boolean, toolUseResult?: unknown, background?: BackgroundExitPolicy): ToolUpdate;
|
|
65
79
|
export type ClaudePlanEntry = {
|
|
66
80
|
content: string;
|
|
67
81
|
status: "pending" | "in_progress" | "completed";
|
package/dist/tools.js
CHANGED
|
@@ -1,4 +1,12 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
|
+
/**
|
|
3
|
+
* Upstream #1252: the exit code Claude Code's text of a failed command names. It starts that text with
|
|
4
|
+
* `Exit code N`; a failure that names none (a denial, a command that could not start) yields undefined.
|
|
5
|
+
*/
|
|
6
|
+
function failureExitCode(text) {
|
|
7
|
+
const match = text.match(/^Exit code (\d+)(?:\n|$)/);
|
|
8
|
+
return match ? Number(match[1]) : undefined;
|
|
9
|
+
}
|
|
2
10
|
/**
|
|
3
11
|
* Convert an absolute file path to a project-relative path for display.
|
|
4
12
|
* Returns the original path if it's outside the project directory or if no cwd is provided.
|
|
@@ -451,7 +459,10 @@ export function toolUpdateFromToolResult(toolResult, toolUse, supportsTerminalOu
|
|
|
451
459
|
// `diff-enriched-reader.ts`. Upstream notes its own structured renders go dark on replay because
|
|
452
460
|
// `getSessionMessages` doesn't expose this field — the fork reads the transcript directly, so the
|
|
453
461
|
// structured path is available on BOTH the live tail and `session/load`.
|
|
454
|
-
toolUseResult
|
|
462
|
+
toolUseResult,
|
|
463
|
+
// Item 92 (#1312): how a backgrounded Bash's exit is reported. Absent → exit at the result, with
|
|
464
|
+
// null as the (unknown) code.
|
|
465
|
+
background) {
|
|
455
466
|
if ("is_error" in toolResult &&
|
|
456
467
|
toolResult.is_error &&
|
|
457
468
|
toolResult.content &&
|
|
@@ -563,6 +574,8 @@ toolUseResult) {
|
|
|
563
574
|
// 3. Plain string content from a regular tool_result
|
|
564
575
|
// 4. Array content (e.g. [{ type: "text", text: "..." }])
|
|
565
576
|
let output = "";
|
|
577
|
+
// `null` is an exit whose code nobody knows (a replayed backgrounded command); Zeo reads it as
|
|
578
|
+
// "not failed", so a failure always carries a number — the one its text names, else 1.
|
|
566
579
|
let exitCode = isError ? 1 : 0;
|
|
567
580
|
const structuredBash = structuredResult(toolUseResult);
|
|
568
581
|
if (structuredBash &&
|
|
@@ -610,6 +623,28 @@ toolUseResult) {
|
|
|
610
623
|
typeof result[0].text === "string") {
|
|
611
624
|
output = result.map((c) => c.text).join("\n");
|
|
612
625
|
}
|
|
626
|
+
// Upstream #1252: a failed command's text starts with `Exit code N` when the command itself
|
|
627
|
+
// exited non-zero. Report N instead of the conventional 1; a failure naming no code keeps 1.
|
|
628
|
+
if (isError) {
|
|
629
|
+
const named = failureExitCode(output);
|
|
630
|
+
if (named !== undefined && named !== 0)
|
|
631
|
+
exitCode = named;
|
|
632
|
+
}
|
|
633
|
+
// Upstream #1312: a backgrounded command is still running when its result arrives — the result
|
|
634
|
+
// only announces it. Its exit comes from the task's notification: at the result when the
|
|
635
|
+
// transcript already holds it, otherwise from the live pump once it lands (`holdRunning`), or —
|
|
636
|
+
// for callers that cannot send it later (replay, nested rows) — at the result with no code.
|
|
637
|
+
const backgroundTaskId = structuredBash?.backgroundTaskId;
|
|
638
|
+
let holdExit = false;
|
|
639
|
+
if (backgroundTaskId !== undefined && !isError) {
|
|
640
|
+
const end = terminalId !== undefined ? background?.ended(terminalId) : undefined;
|
|
641
|
+
if (end)
|
|
642
|
+
exitCode = end.exitCode;
|
|
643
|
+
else if (background?.holdRunning)
|
|
644
|
+
holdExit = true;
|
|
645
|
+
else
|
|
646
|
+
exitCode = null;
|
|
647
|
+
}
|
|
613
648
|
// Without a terminal id there is nothing the client can reconcile these metas against, and
|
|
614
649
|
// emitting them anyway strands the output: a client that buffers output/exit for terminals it
|
|
615
650
|
// has not been told about (Zed keeps them in `pending_terminal_output`/`pending_terminal_exit`,
|
|
@@ -626,11 +661,15 @@ toolUseResult) {
|
|
|
626
661
|
terminal_id: terminalId,
|
|
627
662
|
data: output,
|
|
628
663
|
},
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
664
|
+
...(holdExit
|
|
665
|
+
? {}
|
|
666
|
+
: {
|
|
667
|
+
terminal_exit: {
|
|
668
|
+
terminal_id: terminalId,
|
|
669
|
+
exit_code: exitCode,
|
|
670
|
+
signal: null,
|
|
671
|
+
},
|
|
672
|
+
}),
|
|
634
673
|
},
|
|
635
674
|
};
|
|
636
675
|
}
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"publishConfig": {
|
|
4
4
|
"access": "public"
|
|
5
5
|
},
|
|
6
|
-
"version": "0.
|
|
6
|
+
"version": "0.16.0",
|
|
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.
|
|
68
|
-
"@anthropic-ai/claude-agent-sdk": "0.3.
|
|
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.
|
|
73
|
+
"@anthropic-ai/sdk": "0.131.0",
|
|
74
74
|
"@eslint/js": "10.0.1",
|
|
75
|
-
"@types/node": "26.6.
|
|
76
|
-
"@typescript-eslint/eslint-plugin": "8.
|
|
77
|
-
"@typescript-eslint/parser": "8.
|
|
78
|
-
"eslint": "10.
|
|
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.
|
|
81
|
-
"prettier": "3.9.
|
|
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
|
}
|