chainlesschain 0.166.162 → 0.166.164

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.
@@ -19,7 +19,8 @@ import { redactSecrets } from "../lib/secret-scan.js";
19
19
 
20
20
  export function visualizePermissionText(value) {
21
21
  return String(value ?? "").replace(
22
- /[\u0000-\u001f\u007f-\u009f\u00ad\u034f\u061c\u115f\u1160\u17b4\u17b5\u180b-\u180f\u200b-\u200f\u202a-\u202e\u2060-\u206f\u3164\ufeff\uffa0]/gu,
22
+ // eslint-disable-next-line no-misleading-character-class -- Match each invisible character on its own.
23
+ /[\p{Cc}\u00ad\u034f\u061c\u115f\u1160\u17b4\u17b5\u180b-\u180f\u200b-\u200f\u202a-\u202e\u2060-\u206f\u3164\ufeff\uffa0]/gu,
23
24
  (character) => {
24
25
  if (character === "\t") return "<TAB>";
25
26
  if (character === "\n") return "<LF>";
@@ -75,11 +76,10 @@ export function resolveAskIdleTimeoutMs({ env, config } = {}) {
75
76
  /**
76
77
  * Race an interactive question against an idle timeout.
77
78
  *
78
- * `ask` is the readline-question-as-promise (never rejects). On timeout the
79
- * caller must still close its readline interface; the stranded question
80
- * callback becomes a no-op once the interface is closed.
79
+ * `ask` is the readline question as a promise. On timeout the caller cancels
80
+ * the question so the input can return to the conversation.
81
81
  *
82
- * @param {(prompt: string) => Promise<string>} ask
82
+ * @param {(prompt: string) => Promise<string|null>} ask
83
83
  * @param {string} prompt
84
84
  * @param {number} timeoutMs - 0/negative = no timeout (plain await)
85
85
  * @returns {Promise<{answer: string|null, timedOut: boolean}>}
@@ -103,3 +103,60 @@ export async function questionWithIdleTimeout(ask, prompt, timeoutMs) {
103
103
  if (timer) clearTimeout(timer);
104
104
  }
105
105
  }
106
+
107
+ // All terminal questions share readline with the composer. Suspending the
108
+ // draft keeps an approval response separate from the next user message.
109
+ export function createReplQuestionQueue(readline, write) {
110
+ let tail = Promise.resolve();
111
+ let current = null;
112
+ let closed = false;
113
+ readline.once("close", () => {
114
+ closed = true;
115
+ current?.abort();
116
+ });
117
+
118
+ return {
119
+ isActive: () => current !== null,
120
+ cancelActive: () => current?.abort(),
121
+ create() {
122
+ const controller = new AbortController();
123
+ const { signal } = controller;
124
+ return {
125
+ get canceled() {
126
+ return signal.aborted;
127
+ },
128
+ cancel: () => controller.abort(),
129
+ ask(text) {
130
+ const answer = tail.then(() => {
131
+ if (closed || signal.aborted) return null;
132
+ return new Promise((resolve) => {
133
+ current = controller;
134
+ const { line, cursor } = readline;
135
+ readline.line = "";
136
+ readline.cursor = 0;
137
+ const split = text.lastIndexOf("\n") + 1;
138
+ if (split) write(text.slice(0, split));
139
+ const finish = (value) => {
140
+ signal.removeEventListener("abort", onAbort);
141
+ current = null;
142
+ if (!closed) {
143
+ readline.line = line;
144
+ readline.cursor = cursor;
145
+ readline.prompt(true);
146
+ }
147
+ resolve(value);
148
+ };
149
+ // Let readline cancel its callback and restore its prompt
150
+ // before putting the draft back.
151
+ const onAbort = () => queueMicrotask(() => finish(null));
152
+ signal.addEventListener("abort", onAbort, { once: true });
153
+ readline.question(text.slice(split), { signal }, finish);
154
+ });
155
+ });
156
+ tail = answer;
157
+ return answer;
158
+ },
159
+ };
160
+ },
161
+ };
162
+ }
@@ -0,0 +1,355 @@
1
+ import { EventEmitter } from "node:events";
2
+ import { stripVTControlCharacters } from "node:util";
3
+ import {
4
+ ALT_SCREEN_ENTER,
5
+ ALT_SCREEN_LEAVE,
6
+ diffRepaint,
7
+ HIDE_CURSOR,
8
+ SHOW_CURSOR,
9
+ } from "./fullscreen-tui.js";
10
+
11
+ const MAX_TRANSCRIPT_LINES = 2000;
12
+ const MAX_LINE_LENGTH = 16000;
13
+ const FRAME_INTERVAL_MS = 24;
14
+ const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
15
+
16
+ function terminalText(value) {
17
+ return stripVTControlCharacters(value)
18
+ .replace(/\r\n?/g, "\n")
19
+ .replace(/\t/g, " ")
20
+ .replace(/\p{Cc}/gu, (character) => (character === "\n" ? character : ""));
21
+ }
22
+
23
+ function wrapLine(text, columns, widthOf) {
24
+ const rows = [""];
25
+ let col = 0;
26
+ for (const { segment } of graphemes.segment(text)) {
27
+ const width =
28
+ segment.length === 1 && segment.charCodeAt(0) < 127
29
+ ? 1
30
+ : widthOf(segment);
31
+ if (col + width > columns) {
32
+ rows.push("");
33
+ col = 0;
34
+ }
35
+ rows[rows.length - 1] += segment;
36
+ col += width;
37
+ }
38
+ return { rows, col };
39
+ }
40
+
41
+ export function createTerminalWindow({
42
+ input,
43
+ stdout,
44
+ stderr,
45
+ waitForOutput,
46
+ getStatus,
47
+ getSlashSuggestions,
48
+ isQuestionActive = () => false,
49
+ }) {
50
+ let rl;
51
+ let active = false;
52
+ let frameTimer;
53
+ let blocked = false;
54
+ let painted = [];
55
+ let offset = 0;
56
+ let wrappedColumns;
57
+ let cursorPosition = "";
58
+ let slashQuery = "";
59
+ let slashSelection = 0;
60
+ let picker = null;
61
+ const transcript = [{ text: "" }];
62
+ const writeTerminal = stdout.write.bind(stdout);
63
+ const writeError = stderr.write;
64
+ const writeOutput = stdout.write;
65
+
66
+ function schedule() {
67
+ if (!active || blocked || frameTimer) return;
68
+ frameTimer = setTimeout(render, FRAME_INTERVAL_MS);
69
+ }
70
+
71
+ function append(value) {
72
+ const parts = terminalText(value).split("\n");
73
+ const last = transcript.pop();
74
+ transcript.push({ text: (last.text + parts[0]).slice(-MAX_LINE_LENGTH) });
75
+ for (let i = 1; i < parts.length; i++) {
76
+ transcript.push({ text: parts[i].slice(-MAX_LINE_LENGTH) });
77
+ }
78
+ if (transcript.length > MAX_TRANSCRIPT_LINES)
79
+ transcript.splice(0, transcript.length - MAX_TRANSCRIPT_LINES);
80
+ schedule();
81
+ }
82
+
83
+ function capture(chunk, encoding, callback) {
84
+ append(typeof chunk === "string" ? chunk : Buffer.from(chunk).toString());
85
+ const done = typeof encoding === "function" ? encoding : callback;
86
+ if (done) queueMicrotask(() => done());
87
+ return true;
88
+ }
89
+
90
+ const readlineOutput = new EventEmitter();
91
+ Object.defineProperties(readlineOutput, {
92
+ columns: { get: () => stdout.columns },
93
+ rows: { get: () => stdout.rows },
94
+ isTTY: { get: () => stdout.isTTY },
95
+ });
96
+ readlineOutput.write = (value, ...args) => {
97
+ if (!active) return writeTerminal(value, ...args);
98
+ // readline draws its own prompt and emits cursor controls. Its completion
99
+ // listing is regular output, which belongs in the transcript.
100
+ if (value === "\x07") return writeTerminal(value);
101
+ if (
102
+ value.includes("\n") &&
103
+ value !== rl.getPrompt() + rl.line &&
104
+ terminalText(value).trim()
105
+ )
106
+ append(value);
107
+ schedule();
108
+ return true;
109
+ };
110
+
111
+ function render() {
112
+ frameTimer = undefined;
113
+ if (!active) return;
114
+ const rows = Math.max(2, stdout.rows || 24);
115
+ const columns = Math.max(2, (stdout.columns || 80) - 1);
116
+ if (wrappedColumns !== columns) {
117
+ for (const line of transcript) delete line.wrapped;
118
+ wrappedColumns = columns;
119
+ }
120
+ const widthOf = (value) => {
121
+ const size = rl._getDisplayPos(value);
122
+ return size.cols + size.rows * (stdout.columns || 80);
123
+ };
124
+ const wrap = (value) => wrapLine(value, columns, widthOf);
125
+ const wrapInput = (value) => value.split("\n").map(wrap);
126
+ const prompt = terminalText(rl.getPrompt());
127
+ const inputRows = wrapInput(prompt + terminalText(rl.line)).flatMap(
128
+ (line) => line.rows,
129
+ );
130
+ const cursor = wrapInput(
131
+ prompt + terminalText(rl.line.slice(0, rl.cursor)),
132
+ );
133
+ const cursorRow = cursor.reduce((n, line) => n + line.rows.length, 0) - 1;
134
+ const inputHeight = Math.min(
135
+ inputRows.length,
136
+ Math.max(1, Math.min(5, rows - 3)),
137
+ );
138
+ const inputStart = Math.max(0, cursorRow - inputHeight + 1);
139
+ const visiblePicker = picker && !isQuestionActive() ? picker : null;
140
+ const suggestions = visiblePicker
141
+ ? pickerMatches()
142
+ : currentSlashSuggestions();
143
+ const selection = visiblePicker ? visiblePicker.index : slashSelection;
144
+ const pickerTitle = visiblePicker
145
+ ? wrap(
146
+ visiblePicker.query
147
+ ? `${visiblePicker.title} · Filter ${visiblePicker.query}${suggestions.length ? "" : " · No matches"}`
148
+ : `${visiblePicker.title} · ↑↓ Select · Enter Apply · Esc Close`,
149
+ ).rows[0]
150
+ : null;
151
+ const menuHeight = Math.min(
152
+ 5,
153
+ Math.max(0, rows - inputHeight - (pickerTitle ? 4 : 3)),
154
+ suggestions.length,
155
+ );
156
+ const menuStart = Math.max(0, selection - menuHeight + 1);
157
+ const footer = [
158
+ "",
159
+ ...inputRows.slice(inputStart, inputStart + inputHeight),
160
+ ];
161
+ if (pickerTitle && rows > footer.length) footer.push(pickerTitle);
162
+ for (let i = menuStart; i < menuStart + menuHeight; i++) {
163
+ const choice = suggestions[i];
164
+ const label = wrap(
165
+ terminalText(
166
+ `${i === selection ? "›" : " "} ${choice}${visiblePicker?.current === choice ? " (current)" : ""}`,
167
+ ),
168
+ ).rows[0];
169
+ footer.push(i === selection ? `\x1b[7m${label}\x1b[0m` : label);
170
+ }
171
+ const capacity = Math.max(0, rows - footer.length);
172
+ const recent = [];
173
+ if (offset > 0) {
174
+ let total = 0;
175
+ for (const line of transcript) {
176
+ if (line === transcript.at(-1) && !line.text) break;
177
+ line.wrapped ??= wrap(line.text).rows;
178
+ total += line.wrapped.length;
179
+ }
180
+ offset = Math.min(offset, Math.max(0, total - capacity));
181
+ }
182
+ const range = offset ? " · PgDn for newer output" : "";
183
+ footer[0] = wrap(getStatus() + range).rows[0];
184
+ let skip = offset;
185
+ for (
186
+ let i = transcript.length - 1;
187
+ i >= 0 && recent.length < capacity;
188
+ i--
189
+ ) {
190
+ const line = transcript[i];
191
+ if (i === transcript.length - 1 && !line.text) continue;
192
+ line.wrapped ??= wrap(line.text).rows;
193
+ for (
194
+ let j = line.wrapped.length - 1;
195
+ j >= 0 && recent.length < capacity;
196
+ j--
197
+ ) {
198
+ if (skip > 0) skip--;
199
+ else recent.push(line.wrapped[j]);
200
+ }
201
+ }
202
+ const next = [
203
+ ...recent.reverse(),
204
+ ...Array(capacity - recent.length).fill(""),
205
+ ...footer,
206
+ ];
207
+ const position = `\x1b[${capacity + 2 + cursorRow - inputStart};${cursor.at(-1).col + 1}H`;
208
+ const update = diffRepaint(painted.slice(0, rows), next);
209
+ if (!update && cursorPosition === position) return;
210
+ painted = next;
211
+ cursorPosition = position;
212
+ if (!writeTerminal(HIDE_CURSOR + update + position + SHOW_CURSOR)) {
213
+ blocked = true;
214
+ void waitForOutput().finally(() => {
215
+ blocked = false;
216
+ schedule();
217
+ });
218
+ }
219
+ }
220
+
221
+ function currentSlashSuggestions() {
222
+ const suggestions = getSlashSuggestions(rl.line);
223
+ if (slashQuery !== rl.line) {
224
+ slashQuery = rl.line;
225
+ slashSelection = Math.max(0, suggestions.indexOf(rl.line));
226
+ }
227
+ slashSelection = Math.min(
228
+ slashSelection,
229
+ Math.max(0, suggestions.length - 1),
230
+ );
231
+ return suggestions;
232
+ }
233
+
234
+ function pickerMatches() {
235
+ const query = picker.query.toLowerCase();
236
+ return picker.choices.filter((choice) =>
237
+ choice.toLowerCase().includes(query),
238
+ );
239
+ }
240
+
241
+ const refreshSize = () => {
242
+ painted = [];
243
+ cursorPosition = "";
244
+ readlineOutput.emit("resize");
245
+ schedule();
246
+ };
247
+
248
+ function disable() {
249
+ if (!active) return;
250
+ active = false;
251
+ clearTimeout(frameTimer);
252
+ frameTimer = undefined;
253
+ input.off("keypress", schedule);
254
+ stdout.write = writeOutput;
255
+ if (stderr.write === capture) stderr.write = writeError;
256
+ rl.prevRows = 0;
257
+ writeTerminal(SHOW_CURSOR + ALT_SCREEN_LEAVE);
258
+ }
259
+
260
+ return {
261
+ readlineOutput,
262
+ bind(readline) {
263
+ rl = readline;
264
+ stdout.on("resize", refreshSize);
265
+ },
266
+ schedule,
267
+ append,
268
+ follow() {
269
+ offset = 0;
270
+ schedule();
271
+ },
272
+ showPicker({ title, choices, selected, current = selected, onSelect }) {
273
+ picker = {
274
+ title,
275
+ choices,
276
+ current,
277
+ onSelect,
278
+ index: Math.max(0, choices.indexOf(selected)),
279
+ query: "",
280
+ };
281
+ schedule();
282
+ },
283
+ handlePickerKey(text, key) {
284
+ if (!active || !picker || isQuestionActive()) return false;
285
+ if (key.ctrl && key.name === "c") return false;
286
+ if (key.ctrl || key.meta) return true;
287
+ const matches = pickerMatches();
288
+ if (key.name === "escape") {
289
+ picker = null;
290
+ } else if (key.name === "up" || key.name === "down") {
291
+ const delta = key.name === "up" ? -1 : 1;
292
+ if (matches.length)
293
+ picker.index =
294
+ (picker.index + delta + matches.length) % matches.length;
295
+ } else if (key.name === "return" || key.name === "enter") {
296
+ const choice = matches[picker.index];
297
+ if (choice) {
298
+ const { onSelect } = picker;
299
+ picker = null;
300
+ onSelect(choice);
301
+ }
302
+ } else if (key.name === "backspace") {
303
+ picker.query = Array.from(picker.query).slice(0, -1).join("");
304
+ picker.index = 0;
305
+ } else if (text && !/\p{Cc}/u.test(text)) {
306
+ picker.query = (picker.query + text).slice(0, 256);
307
+ picker.index = 0;
308
+ }
309
+ schedule();
310
+ return true;
311
+ },
312
+ handleSlashKey(key) {
313
+ if (!active || key.ctrl || key.meta || key.shift) return false;
314
+ if (!["up", "down", "tab", "return", "enter"].includes(key.name))
315
+ return false;
316
+ const suggestions = currentSlashSuggestions();
317
+ if (suggestions.length === 0) return false;
318
+ if (key.name === "up" || key.name === "down") {
319
+ const delta = key.name === "up" ? -1 : 1;
320
+ slashSelection =
321
+ (slashSelection + delta + suggestions.length) % suggestions.length;
322
+ schedule();
323
+ return true;
324
+ }
325
+ rl.line = suggestions[slashSelection] + (key.name === "tab" ? " " : "");
326
+ rl.cursor = rl.line.length;
327
+ schedule();
328
+ return key.name === "tab";
329
+ },
330
+ scroll(delta) {
331
+ offset = Math.max(
332
+ 0,
333
+ offset + delta * Math.max(1, (stdout.rows || 24) - 5),
334
+ );
335
+ schedule();
336
+ },
337
+ enable() {
338
+ if (active) return;
339
+ active = true;
340
+ painted = [];
341
+ cursorPosition = "";
342
+ writeTerminal(ALT_SCREEN_ENTER);
343
+ stdout.write = capture;
344
+ if (stderr.isTTY) stderr.write = capture;
345
+ input.on("keypress", schedule);
346
+ schedule();
347
+ },
348
+ disable,
349
+ dispose() {
350
+ picker = null;
351
+ disable();
352
+ stdout.off("resize", refreshSize);
353
+ },
354
+ };
355
+ }
@@ -220,6 +220,8 @@ import {
220
220
  import { buildSearchCommand } from "../lib/search-command.js";
221
221
  import { discoverCommands } from "../lib/slash-commands.js";
222
222
  import {
223
+ CHAT_COMPLETIONS_STREAM_FAILED,
224
+ cancelProviderStreamReader,
223
225
  isRetryableStreamError,
224
226
  STREAM_RETRY_BASE_MS,
225
227
  resolveStreamRetryMax,
@@ -1266,7 +1268,7 @@ ${CODING_TASK_QUALITY_GUIDANCE}
1266
1268
  - The git tool accepts ONE Git argument list, without pipes, redirects, &&, semicolons or echo. Use log -n 5 instead of piping to head; inspect the returned exitCode for predicates such as merge-base --is-ancestor (1 means false). Discover remote names with remote -v; do not assume origin exists.
1267
1269
  - On Windows, run_shell defaults to cmd unless configured otherwise. Set shell: "powershell" for PowerShell syntax or shell: "pwsh" for PowerShell 7. Parse saved JSON after stripping an initial UTF-8 BOM; a BOM parse error is not a JavaScript syntax defect.
1268
1270
  - When asked about files or code, use search_files to locate relevant sections, then read_file with offset/limit. Follow nextRead for large files. Reuse unchanged content already in context instead of repeatedly reading the same page; re-read when the file changes or the earlier content is no longer available.
1269
- - For long text files, use search_files with path and pattern to find matching lines/columns and nearby text; read the returned nextRead location instead of paging from the top.
1271
+ - To find specific text in a long file, use search_files with path and a nonempty pattern, then read the returned nextRead location. To inspect a file without a search term, use read_file with offset and limit.
1270
1272
  - For online discovery without a known URL, use web_search with keywords. Return relevant source links and snippets; use web_fetch only when the source needs closer reading. For a known URL, fetch it directly. Download large pages once, then use snapshotId to search or read local chunks. Never invent URLs or claim a blocked search returned no results.
1271
1273
  - Large task documents include a sampled outline with line numbers. Use it to locate relevant unfinished work and inspect those sections instead of scanning the entire document unless the task requires full coverage. File coverage and excerpts survive compaction; reading to EOF is not completing the user's task.
1272
1274
  - For task counts or completion status, search the named document for the latest status/summary table first, then read that section. Distinguish historical entries from current status and repository work from external acceptance. Once the relevant entries are verified, answer; do not read every implementation detail just to count tasks.
@@ -13666,6 +13668,10 @@ async function _chatOpenAIStreaming(
13666
13668
  }
13667
13669
  } catch (err) {
13668
13670
  attachStreamRetryMetadata(err, retryMetadata);
13671
+ if (err?.code === CHAT_COMPLETIONS_STREAM_FAILED) {
13672
+ cancelProviderStreamReader(reader);
13673
+ throw err;
13674
+ }
13669
13675
  if (!ui.hasVisibleOutput() && !state.text && state.tools.length)
13670
13676
  err.noReplay = true;
13671
13677
  if (
@@ -390,13 +390,15 @@ const CODING_AGENT_TOOL_CONTRACTS = Object.freeze([
390
390
  kind: "filesystem",
391
391
  tier: "mvp",
392
392
  description:
393
- "Search for files by name pattern or content. For a long text file, pass path and pattern: returns matching line/column positions, nearby context, and nextRead arguments for read_file. This streams the file instead of loading it into model context. Continue capped results with nextOffset as offset. Omit path for the existing directory search.",
393
+ "Find files by name or search for matching text. For one text file, supply path and a nonempty pattern to get line/column positions, nearby text, and nextRead arguments. Continue capped results with nextOffset as offset. To inspect a known file without a search term, use read_file with path, offset, and limit. For a directory search, omit path and set content_search:true to search file contents.",
394
394
  inputSchema: {
395
395
  type: "object",
396
396
  properties: {
397
397
  pattern: {
398
398
  type: "string",
399
- description: "Glob pattern or search string",
399
+ minLength: 1,
400
+ description:
401
+ "Nonempty filename pattern or text to match. For a single file, use at most 2048 characters.",
400
402
  },
401
403
  path: {
402
404
  type: "string",
@@ -2311,6 +2311,16 @@ async function runAgentHeadlessStreamInWorkspace(
2311
2311
 
2312
2312
  let pm = deps.planManager || new PlanModeManager();
2313
2313
  let restoredPlanMode = false;
2314
+ // The IDE supplies the flag for older CLIs as well. Its implicit selection
2315
+ // yields to a verified plan or to an organization that disables bypass.
2316
+ const idePermissionFallback =
2317
+ options.interactiveApprovals === true &&
2318
+ options.permissionMode === "bypassPermissions" &&
2319
+ process.env.CC_IDE_DEFAULT_PERMISSION_MODE === "1" &&
2320
+ process.env.CC_IDE_REQUESTED_MODE === "bypassPermissions" &&
2321
+ /^[a-zA-Z0-9-]{1,80}$/.test(process.env.CC_IDE_MODE_REQUEST_ID || "");
2322
+ if (idePermissionFallback)
2323
+ options = { ...options, permissionMode: undefined };
2314
2324
  if (persist && !hasInjectedSessionStore && !deps.planManager) {
2315
2325
  try {
2316
2326
  const plan = openSessionPlan(sessionId, options.permissionMode);
@@ -2334,9 +2344,15 @@ async function runAgentHeadlessStreamInWorkspace(
2334
2344
  }
2335
2345
  }
2336
2346
 
2337
- if (managedSettings) {
2338
- const { assertManagedPermissionMode } =
2347
+ if (managedSettings || idePermissionFallback) {
2348
+ const { assertManagedPermissionMode, defaultInteractivePermissionMode } =
2339
2349
  await import("../lib/settings-loader.cjs");
2350
+ if (idePermissionFallback && options.permissionMode == null) {
2351
+ options = {
2352
+ ...options,
2353
+ permissionMode: defaultInteractivePermissionMode(managedSettings),
2354
+ };
2355
+ }
2340
2356
  assertManagedPermissionMode(options.permissionMode, managedSettings);
2341
2357
  }
2342
2358
  const perm = resolvePermissionMode(options.permissionMode);
@@ -2684,6 +2700,7 @@ async function runAgentHeadlessStreamInWorkspace(
2684
2700
  // resolution is echoed as `approval_resolved` so UIs can settle their cards.
2685
2701
  const interactive = options.interactiveApprovals === true;
2686
2702
  const pendingApprovals = new Map();
2703
+ let currentAbort = null;
2687
2704
  let approvalSeq = 0;
2688
2705
  const approvalTimeoutMs =
2689
2706
  Number(process.env.CC_APPROVAL_TIMEOUT_MS) > 0
@@ -2698,11 +2715,18 @@ async function runAgentHeadlessStreamInWorkspace(
2698
2715
  ) => {
2699
2716
  const p = pendingApprovals.get(id);
2700
2717
  if (!p) return;
2701
- const approve = [
2702
- "acceptOnce",
2703
- "acceptForTurn",
2704
- "acceptForSession",
2705
- ].includes(decision?.kind);
2718
+ let approve = ["acceptOnce", "acceptForTurn", "acceptForSession"].includes(
2719
+ decision?.kind,
2720
+ );
2721
+ if (
2722
+ approve &&
2723
+ p.turn &&
2724
+ (p.turn !== currentAbort || p.turn.signal.aborted)
2725
+ ) {
2726
+ approve = false;
2727
+ decision = { kind: "decline", reason: "Approval turn ended" };
2728
+ via = "turn-ended";
2729
+ }
2706
2730
  // Approval binding (authority §"权限来源与跨 Agent 授权边界"): an *approve*
2707
2731
  // verdict that carries a binding which does NOT match the one the request
2708
2732
  // advertised is stale / mis-routed / argument-tampered — reject it (deny,
@@ -2766,7 +2790,8 @@ async function runAgentHeadlessStreamInWorkspace(
2766
2790
  });
2767
2791
  p.resolve(!invalidReason && approve);
2768
2792
  };
2769
- const interactiveConfirm = (ctx = {}) => {
2793
+ const interactiveConfirm = (ctx = {}, turn = currentAbort) => {
2794
+ if (turn && (turn !== currentAbort || turn.signal.aborted)) return false;
2770
2795
  const requiredPermission = approvalPermissionForContext(ctx, { cwd });
2771
2796
  if (approvalGrantLedger.allows(requiredPermission)) return true;
2772
2797
  return new Promise((resolve) => {
@@ -2796,6 +2821,7 @@ async function runAgentHeadlessStreamInWorkspace(
2796
2821
  timer,
2797
2822
  binding,
2798
2823
  requiredPermission,
2824
+ turn,
2799
2825
  });
2800
2826
  emit({
2801
2827
  type: "approval_request",
@@ -4075,10 +4101,6 @@ async function runAgentHeadlessStreamInWorkspace(
4075
4101
  classifyAllShell,
4076
4102
  enabledToolNames,
4077
4103
  disabledTools,
4078
- // --interactive-approvals: settings/hook `ask` (and, with an IDE bridge,
4079
- // edit reviews via openDiff) route to the structured approval round-trip
4080
- // instead of failing closed. Absent in CI/pipes → unchanged fail-closed.
4081
- permissionConfirm: interactive ? interactiveConfirm : undefined,
4082
4104
  // ask_user_question round-trip (opt-in via CC_INTERACTIVE_QUESTIONS): give
4083
4105
  // the tool handler an askUser that emits question_request + blocks on stdin.
4084
4106
  // Absent → agent-core returns user_not_reachable (graceful proceed).
@@ -4337,7 +4359,6 @@ async function runAgentHeadlessStreamInWorkspace(
4337
4359
  const queue = [];
4338
4360
  let wakeQueue = null;
4339
4361
  let inputDone = false;
4340
- let currentAbort = null;
4341
4362
  let inputBacklogFailure = false;
4342
4363
  let slashRequestSeq = 0;
4343
4364
  const inputLines = readJsonLines(input);
@@ -4402,7 +4423,19 @@ async function runAgentHeadlessStreamInWorkspace(
4402
4423
  settlePermissionDecisionGate(true);
4403
4424
  }
4404
4425
  if (parsed.interrupt) {
4405
- currentAbort?.abort();
4426
+ const interruptedTurn = currentAbort;
4427
+ interruptedTurn?.abort();
4428
+ if (interruptedTurn) {
4429
+ for (const [id, pending] of pendingApprovals) {
4430
+ if (pending.turn === interruptedTurn) {
4431
+ settleApproval(
4432
+ id,
4433
+ { kind: "decline", reason: "Approval turn interrupted" },
4434
+ "turn-interrupted",
4435
+ );
4436
+ }
4437
+ }
4438
+ }
4406
4439
  continue;
4407
4440
  }
4408
4441
  if (parsed.approval) {
@@ -5825,10 +5858,11 @@ async function runAgentHeadlessStreamInWorkspace(
5825
5858
  // Per-turn abort scope: an {"type":"interrupt"} from the pump above
5826
5859
  // aborts THIS turn (LLM fetch included — the signal reaches chatWithTools)
5827
5860
  // while the conversation/process stays alive for the next message.
5828
- currentAbort = new AbortController();
5861
+ const turn = new AbortController();
5862
+ currentAbort = turn;
5829
5863
  const turnSignal = options.signal
5830
- ? AbortSignal.any([options.signal, currentAbort.signal])
5831
- : currentAbort.signal;
5864
+ ? AbortSignal.any([options.signal, turn.signal])
5865
+ : turn.signal;
5832
5866
 
5833
5867
  // Capture the resumed pairs once, then normalize those same pairs only in
5834
5868
  // every provider request. The live authority array retains separate turns.
@@ -5843,6 +5877,9 @@ async function runAgentHeadlessStreamInWorkspace(
5843
5877
  messages,
5844
5878
  {
5845
5879
  ...loopOptionsBase,
5880
+ permissionConfirm: interactive
5881
+ ? (context) => interactiveConfirm(context, turn)
5882
+ : undefined,
5846
5883
  // Custom-command frontmatter scopes THIS turn (parity with `cc command
5847
5884
  // run` / headless -p): a matched /name applies its model: and
5848
5885
  // allowed-tools:. Lowest-priority override — an explicit per-turn
@@ -8,6 +8,7 @@ import {
8
8
  projectUsagePricingContext,
9
9
  projectEnvelopePricingContext,
10
10
  } from "../lib/usage-pricing-context.js";
11
+ import { createChatCompletionsStreamError } from "../lib/stream-retry.js";
11
12
 
12
13
  export function _isNonNegativeSafeInteger(value) {
13
14
  return Number.isSafeInteger(value) && value >= 0;
@@ -321,7 +322,8 @@ export function _openaiReduceLine(state, raw, onToken) {
321
322
  state.terminationInvalid = true;
322
323
  return state;
323
324
  }
324
- if (state.streamDone || obj.error) state.terminationInvalid = true;
325
+ if (obj?.error) throw createChatCompletionsStreamError();
326
+ if (state.streamDone) state.terminationInvalid = true;
325
327
  if (!Array.isArray(obj.choices) || obj.choices.length > 1) {
326
328
  state.terminationInvalid = true;
327
329
  }