@lucascouts/claude-agent-tui 0.15.0 → 0.15.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.
- package/dist/acp-agent.d.ts +31 -1
- package/dist/acp-agent.js +78 -9
- package/dist/background-task-end.d.ts +11 -0
- package/dist/background-task-end.js +92 -0
- package/dist/diff-enriched-reader.d.ts +6 -0
- package/dist/diff-enriched-reader.js +1 -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 +1 -1
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. */
|
|
@@ -631,7 +650,7 @@ export type ToolUpdateMeta = {
|
|
|
631
650
|
};
|
|
632
651
|
terminal_exit?: {
|
|
633
652
|
terminal_id: string;
|
|
634
|
-
exit_code: number;
|
|
653
|
+
exit_code: number | null;
|
|
635
654
|
signal: string | null;
|
|
636
655
|
};
|
|
637
656
|
};
|
|
@@ -994,6 +1013,13 @@ export declare class ClaudeAcpAgent implements Agent {
|
|
|
994
1013
|
* is NO SDK message stream. The end-of-turn predicate is story 024; this only consumes the signal.
|
|
995
1014
|
*/
|
|
996
1015
|
private pumpUpdates;
|
|
1016
|
+
/**
|
|
1017
|
+
* Item 92 (upstream #1312) — send the terminal exit of each backgrounded command whose task has now
|
|
1018
|
+
* ended. The live pump held that exit back at the tool result (the command was still running); the
|
|
1019
|
+
* task's `<task-notification>` in the raw transcript is its end, and its summary the code. Each held
|
|
1020
|
+
* exit is sent once. Live-only: replay never holds an exit, so it has nothing to flush.
|
|
1021
|
+
*/
|
|
1022
|
+
private flushBackgroundExits;
|
|
997
1023
|
/**
|
|
998
1024
|
* Story 041 (R3.1, R3.2) — the SHARED source+merge+linearize+emit loop run by BOTH the live tail pump
|
|
999
1025
|
* ({@link pumpUpdates}) and the `session/load` replay ({@link replaySessionHistory}), so a LOADED
|
|
@@ -1084,6 +1110,10 @@ export declare function toAcpNotifications(content: string | ContentBlockParam[]
|
|
|
1084
1110
|
cwd?: string;
|
|
1085
1111
|
taskState?: TaskState;
|
|
1086
1112
|
toolUseResult?: unknown;
|
|
1113
|
+
background?: {
|
|
1114
|
+
ended: (toolUseId: string) => BackgroundTaskEnd | undefined;
|
|
1115
|
+
held?: Set<string>;
|
|
1116
|
+
};
|
|
1087
1117
|
}): SessionNotification[];
|
|
1088
1118
|
export declare function streamEventToAcpNotifications(message: SDKPartialAssistantMessage, sessionId: string, toolUseCache: ToolUseCache, client: AgentSideConnection, logger: Logger, options?: {
|
|
1089
1119
|
clientCapabilities?: ClientCapabilities;
|
package/dist/acp-agent.js
CHANGED
|
@@ -17,6 +17,8 @@ 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";
|
|
20
22
|
import { sourceSubagentRows, defaultListSubagents, defaultGetSubagentMessages, hasSubagentSpawn, spawnIdsOpen, } from "./subagent-source.js";
|
|
21
23
|
import { collectSidechainToolUses, registerSidechainGateToolUses, } from "./subagent-gate.js";
|
|
22
24
|
import { createSubagentWatcher } from "./subagent-watcher.js";
|
|
@@ -193,13 +195,16 @@ export async function defaultStartEngine(args) {
|
|
|
193
195
|
// sessionId glob ambiguous → resourceNotFound on the next load. A missing/ambiguous transcript
|
|
194
196
|
// throws here → createSession's resume catch maps it to resourceNotFound (unchanged client
|
|
195
197
|
// contract). No PTY, no tail watcher, no live engine — the only emission is replaySessionHistory.
|
|
196
|
-
const { cwd } = await resolveWatchTarget(args.sessionId, {
|
|
198
|
+
const { cwd, transcriptPath } = await resolveWatchTarget(args.sessionId, {
|
|
199
|
+
...args.locateOptions,
|
|
200
|
+
});
|
|
197
201
|
return {
|
|
198
202
|
sessionId: args.sessionId,
|
|
199
203
|
pty: REPLAY_ONLY_NOOP_PTY,
|
|
200
204
|
watcher: undefined,
|
|
201
205
|
engine: undefined,
|
|
202
206
|
cwd,
|
|
207
|
+
transcriptPath,
|
|
203
208
|
};
|
|
204
209
|
}
|
|
205
210
|
if (args.resume && args.sessionId) {
|
|
@@ -794,7 +799,16 @@ export class ClaudeAcpAgent {
|
|
|
794
799
|
// (index.ts) is what defaults it ON. OFF → byte-for-byte the pre-043 reduced reader (R5.1).
|
|
795
800
|
this.getMessages =
|
|
796
801
|
(deps.liveDiff ?? false)
|
|
797
|
-
? createDiffEnrichedReader(deps.getMessages ?? defaultGetMessages,
|
|
802
|
+
? createDiffEnrichedReader(deps.getMessages ?? defaultGetMessages, {
|
|
803
|
+
...deps.diffEnrichOptions,
|
|
804
|
+
// Item 92 (#1312): the same raw read yields the ended background tasks, so a held terminal
|
|
805
|
+
// exit costs no second read of the transcript.
|
|
806
|
+
onRawLines: (sid, lines) => {
|
|
807
|
+
const session = this.sessions[sid];
|
|
808
|
+
if (session)
|
|
809
|
+
session.backgroundTaskEnds = backgroundTaskEnds(lines);
|
|
810
|
+
},
|
|
811
|
+
})
|
|
798
812
|
: deps.getMessages;
|
|
799
813
|
this.listSubagents = deps.listSubagents ?? defaultListSubagents;
|
|
800
814
|
this.getSubagentMessages = deps.getSubagentMessages ?? defaultGetSubagentMessages;
|
|
@@ -2042,7 +2056,7 @@ export class ClaudeAcpAgent {
|
|
|
2042
2056
|
* live pump) rendered Edit/Write WITHOUT a diff; story 038 moved usage_update HERE for the SAME
|
|
2043
2057
|
* reason (loaded==live for usage). Only dedup and the billing guard-rail stay with the callers.
|
|
2044
2058
|
*/
|
|
2045
|
-
async emitTurnUpdates(sessionId, turn, toolUseCache) {
|
|
2059
|
+
async emitTurnUpdates(sessionId, turn, toolUseCache, live = false) {
|
|
2046
2060
|
const session = this.sessions[sessionId];
|
|
2047
2061
|
const source = turn.message;
|
|
2048
2062
|
const role = source.message?.role;
|
|
@@ -2065,6 +2079,12 @@ export class ClaudeAcpAgent {
|
|
|
2065
2079
|
cwd: session?.cwd,
|
|
2066
2080
|
taskState: session?.taskState,
|
|
2067
2081
|
toolUseResult: turnToolUseResult,
|
|
2082
|
+
// Item 92 (#1312): only the live pump can send a backgrounded command's exit later, so only
|
|
2083
|
+
// it holds the exit back; replay exits at the result.
|
|
2084
|
+
background: {
|
|
2085
|
+
ended: (id) => session?.backgroundTaskEnds?.get(id),
|
|
2086
|
+
held: live && session ? (session.heldBackgroundExits ??= new Set()) : undefined,
|
|
2087
|
+
},
|
|
2068
2088
|
})) {
|
|
2069
2089
|
await this.client.sessionUpdate(notification);
|
|
2070
2090
|
}
|
|
@@ -2369,7 +2389,8 @@ export class ClaudeAcpAgent {
|
|
|
2369
2389
|
// The merge MUST NOT reach the detector / §10 guard / §9 gate above — those already consumed the
|
|
2370
2390
|
// un-merged `messages` slice exactly-once (R4.1 structural: sub-agent rows never advance
|
|
2371
2391
|
// `detectorCursor` nor register as gate tool_uses).
|
|
2372
|
-
await this.emitLinearizedWithNested(sessionId, session, messages);
|
|
2392
|
+
await this.emitLinearizedWithNested(sessionId, session, messages, true);
|
|
2393
|
+
await this.flushBackgroundExits(sessionId, session);
|
|
2373
2394
|
// === SEAM(054) — feed the gate correlator from the sidechain rows (R3). Gated + LIVE-ONLY: runs
|
|
2374
2395
|
// only with a present, non-torndown gate, and NEVER inside the shared emitLinearizedWithNested that
|
|
2375
2396
|
// session/load replay also calls — so replay stays pure (U3). Additive: touches only the correlator +
|
|
@@ -2407,7 +2428,7 @@ export class ClaudeAcpAgent {
|
|
|
2407
2428
|
schedule: this.schedule,
|
|
2408
2429
|
onActivity: async () => {
|
|
2409
2430
|
session.turnDetector?.noteActivity();
|
|
2410
|
-
await this.emitLinearizedWithNested(sessionId, session, session.lastMessages ?? messages);
|
|
2431
|
+
await this.emitLinearizedWithNested(sessionId, session, session.lastMessages ?? messages, true);
|
|
2411
2432
|
},
|
|
2412
2433
|
});
|
|
2413
2434
|
}
|
|
@@ -2421,6 +2442,33 @@ export class ClaudeAcpAgent {
|
|
|
2421
2442
|
}
|
|
2422
2443
|
}
|
|
2423
2444
|
}
|
|
2445
|
+
/**
|
|
2446
|
+
* Item 92 (upstream #1312) — send the terminal exit of each backgrounded command whose task has now
|
|
2447
|
+
* ended. The live pump held that exit back at the tool result (the command was still running); the
|
|
2448
|
+
* task's `<task-notification>` in the raw transcript is its end, and its summary the code. Each held
|
|
2449
|
+
* exit is sent once. Live-only: replay never holds an exit, so it has nothing to flush.
|
|
2450
|
+
*/
|
|
2451
|
+
async flushBackgroundExits(sessionId, session) {
|
|
2452
|
+
const held = session.heldBackgroundExits;
|
|
2453
|
+
if (!held?.size)
|
|
2454
|
+
return;
|
|
2455
|
+
for (const terminalId of [...held]) {
|
|
2456
|
+
const end = session.backgroundTaskEnds?.get(terminalId);
|
|
2457
|
+
if (!end)
|
|
2458
|
+
continue;
|
|
2459
|
+
held.delete(terminalId);
|
|
2460
|
+
await this.client.sessionUpdate({
|
|
2461
|
+
sessionId,
|
|
2462
|
+
update: {
|
|
2463
|
+
sessionUpdate: "tool_call_update",
|
|
2464
|
+
toolCallId: terminalId,
|
|
2465
|
+
_meta: {
|
|
2466
|
+
terminal_exit: { terminal_id: terminalId, exit_code: end.exitCode, signal: null },
|
|
2467
|
+
},
|
|
2468
|
+
},
|
|
2469
|
+
});
|
|
2470
|
+
}
|
|
2471
|
+
}
|
|
2424
2472
|
/**
|
|
2425
2473
|
* Story 041 (R3.1, R3.2) — the SHARED source+merge+linearize+emit loop run by BOTH the live tail pump
|
|
2426
2474
|
* ({@link pumpUpdates}) and the `session/load` replay ({@link replaySessionHistory}), so a LOADED
|
|
@@ -2443,7 +2491,7 @@ export class ClaudeAcpAgent {
|
|
|
2443
2491
|
* un-merged main chain in the caller (sub-agent rows must never advance the detector cursor or register
|
|
2444
2492
|
* as gate tool_uses). The replay caller has no detector/gate feed, so it simply does not run one.
|
|
2445
2493
|
*/
|
|
2446
|
-
async emitLinearizedWithNested(sessionId, session, messages) {
|
|
2494
|
+
async emitLinearizedWithNested(sessionId, session, messages, live = false) {
|
|
2447
2495
|
const subagentRows = await sourceSubagentRows(sessionId, messages, {
|
|
2448
2496
|
dir: session.cwd,
|
|
2449
2497
|
listSubagents: this.listSubagents,
|
|
@@ -2456,7 +2504,7 @@ export class ClaudeAcpAgent {
|
|
|
2456
2504
|
// so live and loaded render byte-for-byte the same (story 026 R3.3; story 038 moved usage_update
|
|
2457
2505
|
// into the shared emit).
|
|
2458
2506
|
if (!(turn.uuid && session.emitted.has(turn.uuid))) {
|
|
2459
|
-
await this.emitTurnUpdates(sessionId, turn, session.toolUseCache);
|
|
2507
|
+
await this.emitTurnUpdates(sessionId, turn, session.toolUseCache, live);
|
|
2460
2508
|
if (turn.uuid)
|
|
2461
2509
|
session.emitted.add(turn.uuid);
|
|
2462
2510
|
}
|
|
@@ -2816,8 +2864,21 @@ export class ClaudeAcpAgent {
|
|
|
2816
2864
|
// is why the seed below can stay a constant.
|
|
2817
2865
|
const liveModelCatalog = await resolveModelCatalog(this.logger, this.modelCatalogSource);
|
|
2818
2866
|
const availableModes = buildAvailableModes(DEFAULT_MODEL_INFO, allowBypass);
|
|
2867
|
+
// Item 107 (plus 0.23.5 / upstream #1218's mode half): a replay-only load starts no engine, so the
|
|
2868
|
+
// pump that reconciles the mode from the transcript never runs, and the thread would advertise the
|
|
2869
|
+
// settings default. Seed it from the mode the transcript last recorded instead — only a mode this
|
|
2870
|
+
// session offers, so the bypass guard above still holds. Display-only: a loaded session runs
|
|
2871
|
+
// nothing until it is resumed.
|
|
2872
|
+
let currentModeId = seededMode;
|
|
2873
|
+
if (creationOpts.replayOnly && started.transcriptPath) {
|
|
2874
|
+
const recorded = await readTranscriptPermissionMode(started.transcriptPath);
|
|
2875
|
+
if (recorded !== undefined && availableModes.some((m) => m.id === recorded)) {
|
|
2876
|
+
// Every advertised mode id is a PermissionMode (buildAvailableModes builds them from it).
|
|
2877
|
+
currentModeId = recorded;
|
|
2878
|
+
}
|
|
2879
|
+
}
|
|
2819
2880
|
const modes = {
|
|
2820
|
-
currentModeId
|
|
2881
|
+
currentModeId,
|
|
2821
2882
|
availableModes,
|
|
2822
2883
|
};
|
|
2823
2884
|
// Story 056 (R3.2): discover the main-thread agent personas for THIS session's cwd (glob-only via
|
|
@@ -3540,7 +3601,15 @@ export function toAcpNotifications(content, role, sessionId, toolUseCache, clien
|
|
|
3540
3601
|
}
|
|
3541
3602
|
}
|
|
3542
3603
|
else if (toolUse.name !== "TodoWrite") {
|
|
3543
|
-
const
|
|
3604
|
+
const background = options?.background;
|
|
3605
|
+
const { _meta: toolMeta, ...toolUpdate } = toolUpdateFromToolResult(chunk, toolUseCache[chunk.tool_use_id], supportsTerminalOutput, toolUseResult, background
|
|
3606
|
+
? { ended: background.ended, holdRunning: background.held !== undefined }
|
|
3607
|
+
: undefined);
|
|
3608
|
+
// A terminal announced without its exit is a backgrounded command still running: remember it
|
|
3609
|
+
// so the live pump sends the exit when the task ends.
|
|
3610
|
+
if (background?.held && toolMeta?.terminal_info && !toolMeta.terminal_exit) {
|
|
3611
|
+
background.held.add(toolMeta.terminal_info.terminal_id);
|
|
3612
|
+
}
|
|
3544
3613
|
// When terminal output is supported, send terminal_output as a
|
|
3545
3614
|
// separate notification to match codex-acp's streaming lifecycle:
|
|
3546
3615
|
// 1. tool_call → _meta.terminal_info (already sent above)
|
|
@@ -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
|
+
}
|
|
@@ -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`
|
|
@@ -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.15.
|
|
6
|
+
"version": "0.15.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",
|