chainlesschain 0.166.163 → 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
+ }
@@ -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);