chivgent 1.1.2 → 1.1.4

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.
Files changed (160) hide show
  1. package/README.md +22 -8
  2. package/README.zh-CN.md +21 -8
  3. package/dist/agent.d.ts +10 -1
  4. package/dist/agent.d.ts.map +1 -1
  5. package/dist/agent.js +72 -8
  6. package/dist/agent.js.map +1 -1
  7. package/dist/cli-options.d.ts +6 -0
  8. package/dist/cli-options.d.ts.map +1 -1
  9. package/dist/cli-options.js +22 -0
  10. package/dist/cli-options.js.map +1 -1
  11. package/dist/cli-runtime.d.ts +3 -0
  12. package/dist/cli-runtime.d.ts.map +1 -1
  13. package/dist/cli-runtime.js +44 -11
  14. package/dist/cli-runtime.js.map +1 -1
  15. package/dist/cli.d.ts.map +1 -1
  16. package/dist/cli.js +25 -6
  17. package/dist/cli.js.map +1 -1
  18. package/dist/context/compaction.d.ts +10 -0
  19. package/dist/context/compaction.d.ts.map +1 -1
  20. package/dist/context/compaction.js +50 -10
  21. package/dist/context/compaction.js.map +1 -1
  22. package/dist/context/context-manager.d.ts +2 -5
  23. package/dist/context/context-manager.d.ts.map +1 -1
  24. package/dist/context/context-manager.js +47 -19
  25. package/dist/context/context-manager.js.map +1 -1
  26. package/dist/context/errors.d.ts +12 -0
  27. package/dist/context/errors.d.ts.map +1 -0
  28. package/dist/context/errors.js +19 -0
  29. package/dist/context/errors.js.map +1 -0
  30. package/dist/evals/cli.js +5 -5
  31. package/dist/evals/cli.js.map +1 -1
  32. package/dist/evals/report.d.ts.map +1 -1
  33. package/dist/evals/report.js +3 -0
  34. package/dist/evals/report.js.map +1 -1
  35. package/dist/evals/runner.d.ts +2 -0
  36. package/dist/evals/runner.d.ts.map +1 -1
  37. package/dist/evals/runner.js +13 -1
  38. package/dist/evals/runner.js.map +1 -1
  39. package/dist/evals/task.d.ts +2 -0
  40. package/dist/evals/task.d.ts.map +1 -1
  41. package/dist/evals/task.js +7 -0
  42. package/dist/evals/task.js.map +1 -1
  43. package/dist/events.d.ts +7 -0
  44. package/dist/events.d.ts.map +1 -1
  45. package/dist/events.js.map +1 -1
  46. package/dist/llm.d.ts +2 -0
  47. package/dist/llm.d.ts.map +1 -1
  48. package/dist/llm.js.map +1 -1
  49. package/dist/messages.d.ts +5 -0
  50. package/dist/messages.d.ts.map +1 -1
  51. package/dist/permissions.d.ts +9 -3
  52. package/dist/permissions.d.ts.map +1 -1
  53. package/dist/permissions.js +30 -8
  54. package/dist/permissions.js.map +1 -1
  55. package/dist/prompts.d.ts +10 -10
  56. package/dist/prompts.d.ts.map +1 -1
  57. package/dist/prompts.js +44 -10
  58. package/dist/prompts.js.map +1 -1
  59. package/dist/providers/definitions.js +1 -1
  60. package/dist/providers/definitions.js.map +1 -1
  61. package/dist/providers/openai-compatible-chat.d.ts.map +1 -1
  62. package/dist/providers/openai-compatible-chat.js +11 -4
  63. package/dist/providers/openai-compatible-chat.js.map +1 -1
  64. package/dist/providers/openai.js +2 -0
  65. package/dist/providers/openai.js.map +1 -1
  66. package/dist/questions.d.ts +58 -0
  67. package/dist/questions.d.ts.map +1 -0
  68. package/dist/questions.js +155 -0
  69. package/dist/questions.js.map +1 -0
  70. package/dist/remote/server.d.ts +6 -1
  71. package/dist/remote/server.d.ts.map +1 -1
  72. package/dist/remote/server.js +100 -16
  73. package/dist/remote/server.js.map +1 -1
  74. package/dist/repl.d.ts +12 -1
  75. package/dist/repl.d.ts.map +1 -1
  76. package/dist/repl.js +327 -71
  77. package/dist/repl.js.map +1 -1
  78. package/dist/runtime/desktop-runtime.d.ts +6 -0
  79. package/dist/runtime/desktop-runtime.d.ts.map +1 -1
  80. package/dist/runtime/desktop-runtime.js +8 -1
  81. package/dist/runtime/desktop-runtime.js.map +1 -1
  82. package/dist/session-store.d.ts +3 -0
  83. package/dist/session-store.d.ts.map +1 -1
  84. package/dist/session-store.js +5 -0
  85. package/dist/session-store.js.map +1 -1
  86. package/dist/session.d.ts +4 -0
  87. package/dist/session.d.ts.map +1 -1
  88. package/dist/session.js +38 -3
  89. package/dist/session.js.map +1 -1
  90. package/dist/shell/approval.d.ts +12 -2
  91. package/dist/shell/approval.d.ts.map +1 -1
  92. package/dist/shell/approval.js +16 -5
  93. package/dist/shell/approval.js.map +1 -1
  94. package/dist/shell/docker.d.ts.map +1 -1
  95. package/dist/shell/docker.js +1 -0
  96. package/dist/shell/docker.js.map +1 -1
  97. package/dist/shell/native.d.ts.map +1 -1
  98. package/dist/shell/native.js +1 -0
  99. package/dist/shell/native.js.map +1 -1
  100. package/dist/shell/output-store.d.ts +49 -0
  101. package/dist/shell/output-store.d.ts.map +1 -0
  102. package/dist/shell/output-store.js +250 -0
  103. package/dist/shell/output-store.js.map +1 -0
  104. package/dist/shell/output.d.ts +23 -2
  105. package/dist/shell/output.d.ts.map +1 -1
  106. package/dist/shell/output.js +106 -24
  107. package/dist/shell/output.js.map +1 -1
  108. package/dist/shell/types.d.ts +2 -0
  109. package/dist/shell/types.d.ts.map +1 -1
  110. package/dist/tools/bash.d.ts +21 -27
  111. package/dist/tools/bash.d.ts.map +1 -1
  112. package/dist/tools/bash.js +133 -49
  113. package/dist/tools/bash.js.map +1 -1
  114. package/dist/tools/parallel.d.ts.map +1 -1
  115. package/dist/tools/parallel.js +5 -1
  116. package/dist/tools/parallel.js.map +1 -1
  117. package/dist/tools/question.d.ts +72 -0
  118. package/dist/tools/question.d.ts.map +1 -0
  119. package/dist/tools/question.js +52 -0
  120. package/dist/tools/question.js.map +1 -0
  121. package/dist/tools/read-shell-output.d.ts +32 -0
  122. package/dist/tools/read-shell-output.d.ts.map +1 -0
  123. package/dist/tools/read-shell-output.js +39 -0
  124. package/dist/tools/read-shell-output.js.map +1 -0
  125. package/dist/tools/target.d.ts.map +1 -1
  126. package/dist/tools/target.js +3 -1
  127. package/dist/tools/target.js.map +1 -1
  128. package/dist/tools/tool.d.ts +9 -0
  129. package/dist/tools/tool.d.ts.map +1 -1
  130. package/dist/tools/tool.js.map +1 -1
  131. package/dist/tools/web-search.d.ts +42 -0
  132. package/dist/tools/web-search.d.ts.map +1 -0
  133. package/dist/tools/web-search.js +154 -0
  134. package/dist/tools/web-search.js.map +1 -0
  135. package/dist/tui/activity.d.ts +3 -1
  136. package/dist/tui/activity.d.ts.map +1 -1
  137. package/dist/tui/activity.js +93 -14
  138. package/dist/tui/activity.js.map +1 -1
  139. package/dist/tui/editor.d.ts.map +1 -1
  140. package/dist/tui/editor.js +2 -1
  141. package/dist/tui/editor.js.map +1 -1
  142. package/dist/tui/git-diff.d.ts.map +1 -1
  143. package/dist/tui/git-diff.js +2 -23
  144. package/dist/tui/git-diff.js.map +1 -1
  145. package/dist/tui/live.d.ts.map +1 -1
  146. package/dist/tui/live.js +55 -4
  147. package/dist/tui/live.js.map +1 -1
  148. package/dist/tui/markdown.d.ts +13 -0
  149. package/dist/tui/markdown.d.ts.map +1 -1
  150. package/dist/tui/markdown.js +35 -26
  151. package/dist/tui/markdown.js.map +1 -1
  152. package/dist/websearch/backend.d.ts +83 -0
  153. package/dist/websearch/backend.d.ts.map +1 -0
  154. package/dist/websearch/backend.js +238 -0
  155. package/dist/websearch/backend.js.map +1 -0
  156. package/dist/workspace/git-read.d.ts +3 -0
  157. package/dist/workspace/git-read.d.ts.map +1 -0
  158. package/dist/workspace/git-read.js +23 -0
  159. package/dist/workspace/git-read.js.map +1 -0
  160. package/package.json +1 -1
package/dist/repl.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { TuiInput } from "./tui/input.js";
2
2
  import { EditorController } from "./tui/editor-input.js";
3
3
  import { readLiveGitDiff } from "./tui/git-diff.js";
4
- import { terminalText } from "./tui/text.js";
4
+ import { displayWidth, terminalText } from "./tui/text.js";
5
5
  import { terminalColorEnabled } from "./tui/selection.js";
6
6
  import { PatchReviewController } from "./tui/review.js";
7
7
  import { ProviderPickerController } from "./tui/provider-picker.js";
@@ -9,59 +9,129 @@ import { InputMenu } from "./tui/menu.js";
9
9
  import { createInterface, emitKeypressEvents } from "node:readline";
10
10
  import { formatTokens } from "./providers/usage.js";
11
11
  import { approvalPreview, commandReviewable } from "./tui/activity.js";
12
+ import { fitLine } from "./tui/text.js";
12
13
  import { terminalWidth } from "./tui/live.js";
13
14
  import { formatDiffPage, mostRecentSuccessfulPatch } from "./tui/diff.js";
14
- import { describePermissionMode, parsePermissionMode } from "./permissions.js";
15
+ import { describePermissionMode, parsePermissionMode, WEB_SEARCH_APPROVAL_PREFIX } from "./permissions.js";
15
16
  import { HeuristicTokenEstimator } from "./context/token-estimator.js";
16
17
  export const REPL_PROMPT = "› ";
18
+ function parseQuestionAnswer(question, input) {
19
+ const value = input.trim();
20
+ if (value.length === 0 || value.length > 2_000)
21
+ return undefined;
22
+ if (question.options === undefined)
23
+ return value;
24
+ if (question.multiple === true) {
25
+ const selected = [];
26
+ for (const part of value.split(",").map(item => item.trim())) {
27
+ if (/^text:/i.test(part) && question.allowFreeText === true) {
28
+ const custom = part.slice(5).trim();
29
+ if (custom.length === 0 || custom.length > 2_000)
30
+ return undefined;
31
+ selected.push(custom);
32
+ }
33
+ else {
34
+ if (!/^\d+$/.test(part))
35
+ return undefined;
36
+ const option = question.options[Number(part) - 1];
37
+ if (option === undefined || selected.includes(option.label))
38
+ return undefined;
39
+ selected.push(option.label);
40
+ }
41
+ }
42
+ return selected.length === 0 ? undefined : selected;
43
+ }
44
+ if (/^text:/i.test(value) && question.allowFreeText === true) {
45
+ const custom = value.slice(5).trim();
46
+ return custom.length > 0 && custom.length <= 2_000 ? custom : undefined;
47
+ }
48
+ if (!/^\d+$/.test(value))
49
+ return undefined;
50
+ const option = question.options[Number(value) - 1];
51
+ return option?.label;
52
+ }
53
+ function wrapQuestionText(value, width) {
54
+ const lines = [];
55
+ let line = "";
56
+ let cells = 0;
57
+ for (const part of new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(value)) {
58
+ if (part.segment === "\n") {
59
+ lines.push(line);
60
+ line = "";
61
+ cells = 0;
62
+ continue;
63
+ }
64
+ const cellsInPart = displayWidth(part.segment);
65
+ if (line.length > 0 && cells + cellsInPart > width) {
66
+ lines.push(line);
67
+ line = "";
68
+ cells = 0;
69
+ }
70
+ line += part.segment;
71
+ cells += cellsInPart;
72
+ }
73
+ if (line.length > 0 || lines.length === 0)
74
+ lines.push(line);
75
+ return lines;
76
+ }
17
77
  export const BUILT_IN_COMMANDS = [
18
78
  "help",
19
- "session",
20
79
  "status",
21
- "compact",
22
- "plan",
23
- "permissions",
24
80
  "new",
25
81
  "resume",
26
82
  "rename",
27
- "tools",
28
83
  "diff",
84
+ "clear",
85
+ "compact",
86
+ "permissions",
87
+ "provider",
88
+ "model",
89
+ "endpoint",
90
+ "login",
91
+ "exit",
92
+ ];
93
+ export const LEGACY_COMMAND_ALIASES = [
94
+ "session",
95
+ "plan",
96
+ "tools",
29
97
  "compose",
30
98
  "editor",
31
99
  "review",
32
100
  "gitdiff",
33
- "clear",
34
- "exit",
35
101
  "quit",
36
- "login",
37
102
  "logout",
38
- "provider",
39
- "model",
40
- "endpoint",
41
103
  ];
104
+ export const BUILT_IN_DESCRIPTIONS = {
105
+ help: "show this help",
106
+ status: "show session, model, tokens & permissions",
107
+ new: "save and start a fresh session",
108
+ resume: "switch to a saved session in workspace",
109
+ rename: "set current session title",
110
+ diff: "review workspace Git changes (/diff patch for patch)",
111
+ clear: "clear transcript in current session",
112
+ compact: "summarise older history for the model",
113
+ permissions: "inspect or change permission policy",
114
+ provider: "choose a Provider",
115
+ model: "show or change current model",
116
+ endpoint: "set URL for OpenAI-compatible Provider",
117
+ login: "store API key or sign in with subscription",
118
+ exit: "leave chivgent",
119
+ };
42
120
  const HELP = `Commands:
43
121
  /help Show this help
44
- /session Show the current session id, workspace, and size
45
- /status Show live session, model, permissions, plan state, and usage
122
+ /status Show live session, model, permissions, plan state, and usage (alias: /session)
46
123
  /compact Summarise older history for the model; keeps the full transcript
47
124
  /plan [on|off] Toggle restricted read-only Plan Mode
48
- /permissions [ask-first|workspace|unrestricted] Inspect or change this process's policy
125
+ /permissions [ask-first|workspace|unrestricted|plan] Inspect or change this process's policy
49
126
  /new [title] Save this session and start a fresh session
50
127
  /resume [id] Switch to a saved session in this workspace
51
128
  /rename TITLE Set the current session title
52
- /tools List the tools available to the model
53
- /diff [N] Review the latest successful apply_patch, page N
54
- /compose Write a multi-line prompt (/send to submit, /cancel to discard)
55
- /editor Open the cursor-editable multiline composer (Ctrl+S sends)
56
- /review Browse last applied patch with arrows, q to close
57
- /gitdiff [--staged] Review actual workspace Git changes after explicit approval
129
+ /diff [--staged|patch] Review workspace Git changes (or latest patch)
58
130
  /clear Start a new transcript in the same session
59
131
  /provider Choose a Provider (↑↓ and Enter in the TUI)
60
132
  /model Show or change the current model: /model MODEL
61
133
  /endpoint Set the URL for an OpenAI-compatible Provider
62
- /login Choose a Provider, then store its key; /login NAME skips the list
63
- /login oauth [openai|xai] Sign in with a subscription
64
- /logout Sign out of the current OAuth subscription
134
+ /login Store API key or sign in with subscription (/login logout to sign out)
65
135
  /exit Leave chivgent
66
136
 
67
137
  Anything else is sent to the model. Ctrl+C stops a running answer.
@@ -96,8 +166,6 @@ export function handleSlashCommand(line, context) {
96
166
  context.write(helpText(context));
97
167
  return "handled";
98
168
  case "/session":
99
- context.write(describeSession(context));
100
- return "handled";
101
169
  case "/status":
102
170
  context.write(describeStatus(context));
103
171
  return "handled";
@@ -124,6 +192,12 @@ export function handleSlashCommand(line, context) {
124
192
  }
125
193
  case "/permissions": {
126
194
  const argument = trimmed.slice("/permissions".length).trim().toLowerCase();
195
+ if (argument === "plan" || argument === "plan on") {
196
+ return { kind: "plan", enabled: true };
197
+ }
198
+ if (argument === "plan off") {
199
+ return { kind: "plan", enabled: false };
200
+ }
127
201
  if (context.permissionPolicy === undefined) {
128
202
  context.write("Named permission modes are unavailable because this session uses legacy capability flags. Start with --permission-mode to enable them.\n");
129
203
  }
@@ -135,7 +209,7 @@ export function handleSlashCommand(line, context) {
135
209
  return { kind: "permission-mode", mode: parsePermissionMode(argument) };
136
210
  }
137
211
  catch {
138
- context.write("Usage: /permissions [ask-first|workspace|unrestricted]\n");
212
+ context.write("Usage: /permissions [ask-first|workspace|unrestricted|plan]\n");
139
213
  }
140
214
  }
141
215
  return "handled";
@@ -163,13 +237,28 @@ export function handleSlashCommand(line, context) {
163
237
  return "handled";
164
238
  case "/diff": {
165
239
  const argument = trimmed.slice("/diff".length).trim();
166
- if (argument.length > 0 && !/^[1-9]\d*$/.test(argument)) {
167
- context.write("Usage: /diff [positive page number]\n");
240
+ if (argument === "patch" || argument.startsWith("patch ")) {
241
+ const pageArg = argument.slice("patch".length).trim();
242
+ if (pageArg.length > 0 && !/^[1-9]\d*$/.test(pageArg)) {
243
+ context.write("Usage: /diff patch [positive page number]\n");
244
+ return "handled";
245
+ }
246
+ const patch = mostRecentSuccessfulPatch(context.session.messages);
247
+ if (patch === undefined) {
248
+ context.write("No successfully applied patch found in this session.\n");
249
+ return "handled";
250
+ }
251
+ const page = pageArg.length === 0 ? 1 : Number(pageArg);
252
+ context.write(formatDiffPage(patch, page, context.width ?? 80, context.color === true).text);
253
+ return "handled";
254
+ }
255
+ if (argument.length > 0 && !/^[1-9]\d*$/.test(argument) && argument !== "--staged") {
256
+ context.write("Usage: /diff [--staged|patch [positive page number]]\n");
168
257
  return "handled";
169
258
  }
170
259
  const patch = mostRecentSuccessfulPatch(context.session.messages);
171
260
  if (patch === undefined) {
172
- context.write("No successfully applied patch found in this session.\n");
261
+ context.write("No successfully applied patch found in this session. In interactive TUI, use /diff to review workspace Git changes.\n");
173
262
  return "handled";
174
263
  }
175
264
  const page = argument.length === 0 ? 1 : Number(argument);
@@ -177,10 +266,14 @@ export function handleSlashCommand(line, context) {
177
266
  return "handled";
178
267
  }
179
268
  case "/compose":
180
- context.write("Use /compose at the interactive prompt to enter multi-line mode.\n");
269
+ context.write(context.inlineComposer
270
+ ? "The multiline editor is already active in this prompt. Enter sends; Ctrl+O inserts a newline.\n"
271
+ : "Use /compose at the interactive prompt to enter multi-line mode.\n");
181
272
  return "handled";
182
273
  case "/editor":
183
- context.write("Use /editor in the rich interactive TUI to open the multiline editor.\n");
274
+ context.write(context.inlineComposer
275
+ ? "The cursor-addressable multiline editor is already active in this prompt. Enter sends; Ctrl+O inserts a newline.\n"
276
+ : "Use /editor in the rich interactive TUI to open the multiline editor.\n");
184
277
  return "handled";
185
278
  case "/review":
186
279
  context.write("Use /review in an interactive TUI to browse the most recent successful patch.\n");
@@ -198,6 +291,9 @@ export function handleSlashCommand(line, context) {
198
291
  return "handled";
199
292
  }
200
293
  if (trimmed === "/provider") {
294
+ if (context.interactivePicker === true) {
295
+ return { kind: "provider", argument: "" };
296
+ }
201
297
  context.write(context.providers.describe());
202
298
  return "handled";
203
299
  }
@@ -222,12 +318,21 @@ export function handleSlashCommand(line, context) {
222
318
  return "handled";
223
319
  }
224
320
  return { kind: "endpoint", argument: trimmed.slice("/endpoint".length).trim() };
225
- case "/login":
321
+ case "/login": {
322
+ const argument = trimmed.slice("/login".length).trim();
323
+ if (argument === "logout" || argument === "--logout") {
324
+ if (context.signIn?.signOut === undefined) {
325
+ context.write("OAuth sign-out is unavailable in this session.\n");
326
+ return "handled";
327
+ }
328
+ return { kind: "login", providerArgument: "__logout__" };
329
+ }
226
330
  if (context.signIn === undefined) {
227
331
  context.write("This session cannot store a key; it is attached to a server that already has one.\n");
228
332
  return "handled";
229
333
  }
230
- return { kind: "login", providerArgument: trimmed.slice("/login".length).trim() };
334
+ return { kind: "login", providerArgument: argument };
335
+ }
231
336
  case "/logout":
232
337
  if (context.signIn?.signOut === undefined) {
233
338
  context.write("OAuth sign-out is unavailable in this session.\n");
@@ -267,20 +372,6 @@ function describeUsage(context) {
267
372
  `tokens: ${parts.join(", ")}${usage.complete ? "" : " (a turn reported none)"}`,
268
373
  ];
269
374
  }
270
- function describeSession(context) {
271
- const lines = [
272
- `id: ${context.session.id}`,
273
- `workspace: ${context.session.cwd}`,
274
- `prompts: ${context.session.turns}`,
275
- `messages: ${context.session.messages.length}`,
276
- ...describeUsage(context),
277
- ];
278
- const sessionFile = context.sessionFileForSession?.(context.session) ?? context.sessionFile;
279
- if (sessionFile !== undefined) {
280
- lines.push(`log: ${sessionFile}`);
281
- }
282
- return `${lines.join("\n")}\n`;
283
- }
284
375
  function describeStatus(context) {
285
376
  const usage = describeUsage(context);
286
377
  let contextEstimate = "unavailable";
@@ -288,13 +379,19 @@ function describeStatus(context) {
288
379
  contextEstimate = `approximately ${new HeuristicTokenEstimator().estimateMessages(context.session.messages)} tokens (transcript only; excludes system prompt and tool schemas)`;
289
380
  }
290
381
  catch { /* inaccessible estimates are reported explicitly */ }
382
+ const sessionFile = context.sessionFileForSession?.(context.session) ?? context.sessionFile;
291
383
  const lines = [
292
384
  `provider: ${context.providers?.provider ?? context.providerName ?? "unavailable"}`,
293
385
  `model: ${context.providers === undefined ? context.modelName ?? "unavailable" : context.providers.model ?? "unavailable"}`,
294
- `cwd: ${context.session.cwd}`,
295
- `session: ${context.session.id}${context.session.title ? ` · ${context.session.title}` : ""}`,
386
+ `workspace: ${context.session.cwd}`,
387
+ `id: ${context.session.id}${context.session.title ? ` · ${context.session.title}` : ""}`,
388
+ `prompts: ${context.session.turns}`,
389
+ `messages: ${context.session.messages.length}`,
296
390
  `plan: ${context.session.planMode ? "on (writes and Shell blocked for this session)" : "off"}`,
297
391
  ...(context.permissionPolicy === undefined ? [] : [`permissions: ${context.permissionPolicy.mode} (${describePermissionMode(context.permissionPolicy.mode)})`]),
392
+ ...(context.webSearch === undefined ? [] : [
393
+ `web search: ${context.webSearch.provider}${context.permissionPolicy === undefined || context.permissionPolicy.mode === "unrestricted" ? "" : " (each query asks for approval)"}`,
394
+ ]),
298
395
  ...(context.permissionPolicy === undefined ? [
299
396
  `file write grant: ${context.permissions === undefined ? "unavailable" : context.permissions.includes("file-write") ? "enabled" : "disabled"}`,
300
397
  `Shell grant: ${context.permissions === undefined ? "unavailable" : context.permissions.includes("shell") ? "enabled" : "disabled"}`,
@@ -302,6 +399,7 @@ function describeStatus(context) {
302
399
  ] : []),
303
400
  ...usage,
304
401
  `context: ${contextEstimate}`,
402
+ ...(sessionFile !== undefined ? [`log: ${sessionFile}`] : []),
305
403
  ];
306
404
  return `${lines.join("\n")}\n`;
307
405
  }
@@ -312,13 +410,14 @@ function describeStatus(context) {
312
410
  * keeps an API key off the screen and out of the scrollback. The original
313
411
  * writer is always restored, even if reading throws.
314
412
  */
315
- async function withoutEcho(readline, read) {
413
+ async function withoutEcho(readline, read, echoWhile = () => false) {
316
414
  const internals = readline;
317
415
  const original = internals._writeToOutput?.bind(readline);
318
416
  if (original === undefined) {
319
417
  return read();
320
418
  }
321
- internals._writeToOutput = () => undefined;
419
+ internals._writeToOutput = (text) => { if (echoWhile())
420
+ original(text); };
322
421
  try {
323
422
  return await read();
324
423
  }
@@ -393,7 +492,7 @@ export async function runRepl(options) {
393
492
  const menu = tuiInput === undefined ? undefined : new InputMenu(readline, options.output);
394
493
  let dismissedLine;
395
494
  let refreshQueued = false;
396
- const menuPriority = ["provider", "model", "editor", "review", "help"];
495
+ const menuPriority = ["status", "diff", "provider", "model", "new", "resume", "help"];
397
496
  const commands = [...BUILT_IN_COMMANDS, ...(options.extensionCommands ?? []).map((command) => command.name)]
398
497
  .filter((name, index, all) => all.indexOf(name) === index)
399
498
  .sort((a, b) => {
@@ -404,10 +503,9 @@ export async function runRepl(options) {
404
503
  return rank(a) - rank(b);
405
504
  })
406
505
  .map((name) => {
407
- const description = options.extensionCommands?.find(command => command.name === name)?.description;
408
- const suffix = name === "provider" ? " · choose a Provider"
409
- : name === "model" ? " · change model"
410
- : description === undefined ? "" : ` · ${description}`;
506
+ const description = BUILT_IN_DESCRIPTIONS[name]
507
+ ?? options.extensionCommands?.find(command => command.name === name)?.description;
508
+ const suffix = description === undefined ? "" : ` · ${description}`;
411
509
  return { value: name, label: `/${name}${suffix}` };
412
510
  });
413
511
  const menuItems = (line) => {
@@ -440,6 +538,8 @@ export async function runRepl(options) {
440
538
  readline.write(value);
441
539
  };
442
540
  let controller;
541
+ let questionMode = false;
542
+ let questionCancel;
443
543
  let promptVisible = false;
444
544
  let inputClosed = false;
445
545
  let signingIn = false;
@@ -451,6 +551,10 @@ export async function runRepl(options) {
451
551
  menu?.clear();
452
552
  dismissedLine = undefined;
453
553
  }, (key) => {
554
+ if (questionCancel !== undefined && key === "escape") {
555
+ questionCancel();
556
+ return true;
557
+ }
454
558
  if (signingIn || controller !== undefined)
455
559
  return false;
456
560
  if (key === "enter" && !menu?.active && readline.line === "/provider" && options.providers !== undefined) {
@@ -550,41 +654,145 @@ export async function runRepl(options) {
550
654
  const next = await lines.next();
551
655
  return next.done === true ? undefined : next.value;
552
656
  };
657
+ const questionPresenter = async (request, signal) => {
658
+ if (inputClosed || controller?.signal.aborted === true)
659
+ return { status: "unavailable", reason: "the local input channel is closed" };
660
+ menu?.clear();
661
+ dismissedLine = undefined;
662
+ options.liveRegion?.pause();
663
+ tuiInput?.setBusy(false);
664
+ questionMode = true;
665
+ const answers = [];
666
+ try {
667
+ for (let index = 0; index < request.questions.length; index += 1) {
668
+ const question = request.questions[index];
669
+ if (question === undefined)
670
+ continue;
671
+ if (signal?.aborted)
672
+ return { status: "cancelled" };
673
+ let answer;
674
+ for (;;) {
675
+ const width = Math.max(1, terminalWidth({ columns: options.output.columns }) - 1);
676
+ const line = (value) => { for (const part of wrapQuestionText(terminalText(value), width))
677
+ write(`${part}\n`); };
678
+ line(`Question ${index + 1}/${request.questions.length} · ${question.header}`);
679
+ line(question.question);
680
+ question.options?.forEach((option, optionIndex) => {
681
+ line(` ${optionIndex + 1}. ${option.label}${option.description === undefined ? "" : ` — ${option.description}`}`);
682
+ });
683
+ if (question.options === undefined)
684
+ line("Enter your answer.");
685
+ else if (question.multiple === true)
686
+ line(`Enter choice numbers separated by commas${question.allowFreeText === true ? "; use text:… to add a custom answer" : ""}.`);
687
+ else
688
+ line(`Enter a choice number${question.allowFreeText === true ? " or text:… for another answer" : ""}.`);
689
+ line(options.tui === true
690
+ ? "Type /cancel or press Esc to cancel this question. Ctrl+C cancels the run."
691
+ : "Type /cancel to cancel this question. Ctrl+C cancels the run.");
692
+ readline.setPrompt("answer> ");
693
+ readline.prompt();
694
+ let escaped = false;
695
+ const cancelOnEscape = () => { escaped = true; if (!inputClosed)
696
+ readline.write("\n"); };
697
+ questionCancel = cancelOnEscape;
698
+ const unblockOnAbort = () => { if (!inputClosed)
699
+ readline.write("\n"); };
700
+ signal?.addEventListener("abort", unblockOnAbort, { once: true });
701
+ try {
702
+ if (signal?.aborted)
703
+ return { status: "cancelled" };
704
+ const input = await readNextLine();
705
+ if (signal?.aborted)
706
+ return { status: "cancelled" };
707
+ if (input === undefined)
708
+ return { status: "unavailable", reason: "the local input channel closed before an answer arrived" };
709
+ if (escaped || input.trim().toLowerCase() === "/cancel")
710
+ return { status: "cancelled" };
711
+ answer = parseQuestionAnswer(question, input);
712
+ if (answer !== undefined)
713
+ break;
714
+ line("That answer does not match this question. Choose a listed number or enter a non-empty answer.");
715
+ }
716
+ finally {
717
+ questionCancel = undefined;
718
+ signal?.removeEventListener("abort", unblockOnAbort);
719
+ }
720
+ }
721
+ answers.push({ questionId: question.id, value: answer });
722
+ }
723
+ if (inputClosed)
724
+ return { status: "unavailable", reason: "the local input channel closed before the answer could be submitted" };
725
+ return { ...request, answers };
726
+ }
727
+ finally {
728
+ questionCancel = undefined;
729
+ questionMode = false;
730
+ readline.setPrompt(REPL_PROMPT);
731
+ tuiInput?.setBusy(true);
732
+ options.liveRegion?.resume();
733
+ }
734
+ };
553
735
  // Approval and normal input share the same readline iterator.
554
736
  if (options.shellApproval !== undefined) {
555
737
  options.shellApproval.setHandler(async (command, signal, context) => {
556
738
  if (signal?.aborted)
557
- return false;
739
+ return { approved: false, reason: "cancelled" };
740
+ let resizeListener;
558
741
  menu?.clear();
559
742
  options.liveRegion?.pause();
560
743
  tuiInput?.setApprovalMode(true);
561
744
  tuiInput?.setBusy(false);
562
745
  try {
563
746
  const width = terminalWidth({ columns: options.output.columns });
564
- write(approvalPreview(command, width, context ?? "Shell command"));
565
- if (!commandReviewable(command, width)) {
566
- write(" Denied: command cannot be fully reviewed at this width. Ask for a shorter command.\n");
567
- return false;
747
+ const wraps = context?.startsWith(WEB_SEARCH_APPROVAL_PREFIX) === true;
748
+ const reviewable = wraps || commandReviewable(command, width);
749
+ const approvalOutput = options.output;
750
+ let previewInvalidated = false;
751
+ const invalidateOnResize = () => {
752
+ if (approvalOutput.columns !== width)
753
+ previewInvalidated = true;
754
+ };
755
+ if (!wraps) {
756
+ resizeListener = invalidateOnResize;
757
+ options.output.on("resize", invalidateOnResize);
758
+ }
759
+ write(approvalPreview(command, width, context ?? "Shell command", wraps ? { wrap: true } : {}));
760
+ if (!reviewable) {
761
+ return { approved: false, reason: "unreviewable" };
568
762
  }
569
763
  readline.setPrompt("approve> ");
570
764
  readline.prompt();
571
765
  // Ctrl+C must unblock the pending line read, not leave the agent
572
766
  // stuck waiting for a reply to an approval that was cancelled.
573
767
  const unblockOnAbort = () => {
574
- readline.write("\n");
768
+ if (!inputClosed)
769
+ readline.write("\n");
575
770
  };
576
771
  signal?.addEventListener("abort", unblockOnAbort, { once: true });
577
772
  try {
578
773
  if (signal?.aborted)
579
- return false;
774
+ return { approved: false, reason: "cancelled" };
580
775
  const answer = await readNextLine();
581
- return answer?.trim().toLowerCase() === "y" && signal?.aborted !== true;
776
+ if (signal?.aborted)
777
+ return { approved: false, reason: "cancelled" };
778
+ if (answer === undefined)
779
+ return { approved: false, reason: "unavailable" };
780
+ if (answer.trim().toLowerCase() !== "y")
781
+ return { approved: false, reason: "user" };
782
+ const currentWidth = terminalWidth({ columns: options.output.columns });
783
+ if (!wraps && (previewInvalidated || currentWidth !== width || !commandReviewable(command, currentWidth))) {
784
+ write(`${fitLine(" Denied: resized; review again.", currentWidth - 1)}\n`);
785
+ return { approved: false, reason: "unreviewable" };
786
+ }
787
+ return { approved: true };
582
788
  }
583
789
  finally {
584
790
  signal?.removeEventListener("abort", unblockOnAbort);
585
791
  }
586
792
  }
587
793
  finally {
794
+ if (resizeListener !== undefined)
795
+ options.output.off("resize", resizeListener);
588
796
  readline.setPrompt(REPL_PROMPT);
589
797
  tuiInput?.setApprovalMode(false);
590
798
  tuiInput?.setBusy(true);
@@ -869,21 +1077,31 @@ export async function runRepl(options) {
869
1077
  }
870
1078
  const fromComposer = line.trim() === "/compose";
871
1079
  const fromEditor = line.trim() === "/editor";
872
- if (line.trim() === "/review") {
1080
+ if (line.trim() === "/review" || line.trim() === "/diff patch") {
873
1081
  await inspectPatch();
874
1082
  if (inputClosed)
875
1083
  break;
876
1084
  showPrompt();
877
1085
  continue;
878
1086
  }
879
- if (line.trim().startsWith("/gitdiff")) {
880
- await inspectLiveGitDiff(line.trim());
1087
+ if (line.trim() === "/diff" || line.trim() === "/diff --staged" || line.trim().startsWith("/gitdiff")) {
1088
+ const gitDiffLine = line.trim().startsWith("/gitdiff")
1089
+ ? line.trim()
1090
+ : `/gitdiff${line.trim().slice("/diff".length)}`;
1091
+ await inspectLiveGitDiff(gitDiffLine);
881
1092
  if (inputClosed)
882
1093
  break;
883
1094
  showPrompt();
884
1095
  continue;
885
1096
  }
886
1097
  if (fromComposer || fromEditor) {
1098
+ if (options.inlineComposer && tuiInput !== undefined) {
1099
+ write("The cursor-addressable multiline editor is already active in this prompt. Enter sends; Ctrl+O inserts a newline.\n");
1100
+ if (inputClosed)
1101
+ break;
1102
+ showPrompt();
1103
+ continue;
1104
+ }
887
1105
  const draft = fromEditor ? await collectEditor() : await collectMultiline();
888
1106
  if (draft === undefined) {
889
1107
  if (inputClosed)
@@ -893,6 +1111,14 @@ export async function runRepl(options) {
893
1111
  }
894
1112
  line = draft;
895
1113
  }
1114
+ if (options.inlineComposer && tuiInput !== undefined) {
1115
+ const isOutputTTY = typeof options.output === "object" && options.output !== null && "isTTY" in options.output && options.output.isTTY === true;
1116
+ const useColor = options.tui === true && terminalColorEnabled(isOutputTTY, process.env);
1117
+ const prefix = useColor ? "\u001b[1m\u001b[2m›\u001b[0m " : "› ";
1118
+ const lines = line.split("\n");
1119
+ const formattedPrompt = lines.map((l, i) => `${i === 0 ? prefix : " "}${terminalText(l)}`).join("\n");
1120
+ write(`\n${formattedPrompt}\n\n`);
1121
+ }
896
1122
  const outcome = fromComposer || fromEditor ? "not-a-command" : handleSlashCommand(line, {
897
1123
  session: activeSession,
898
1124
  write,
@@ -910,9 +1136,11 @@ export async function runRepl(options) {
910
1136
  ...(options.compactionEnabled === undefined ? {} : { compactionEnabled: options.compactionEnabled }),
911
1137
  ...(options.providerName === undefined ? {} : { providerName: options.providerName }),
912
1138
  ...(options.modelName === undefined ? {} : { modelName: options.modelName }),
1139
+ ...(options.webSearch === undefined ? {} : { webSearch: options.webSearch }),
913
1140
  ...(options.permissions === undefined ? {} : { permissions: options.permissions }),
914
1141
  ...(options.permissionPolicy === undefined ? {} : { permissionPolicy: options.permissionPolicy }),
915
1142
  ...(options.inlineComposer === true ? { inlineComposer: true } : {}),
1143
+ ...(tuiInput !== undefined ? { interactivePicker: true } : {}),
916
1144
  ...(options.sessionOptions === undefined ? {} : { sessionOptions: options.sessionOptions }),
917
1145
  });
918
1146
  if (outcome === "exit") {
@@ -1011,6 +1239,31 @@ export async function runRepl(options) {
1011
1239
  }
1012
1240
  if (typeof outcome === "object" && (outcome.kind === "provider" || outcome.kind === "model" || outcome.kind === "endpoint")) {
1013
1241
  if (options.providers !== undefined) {
1242
+ if (outcome.kind === "provider" && outcome.argument.length === 0 && tuiInput !== undefined) {
1243
+ signingIn = true;
1244
+ let chosen;
1245
+ try {
1246
+ chosen = await chooseLoginProvider();
1247
+ }
1248
+ finally {
1249
+ signingIn = false;
1250
+ }
1251
+ if (chosen === undefined) {
1252
+ write("No Provider selected; current Provider retained.\n");
1253
+ if (inputClosed)
1254
+ break;
1255
+ showPrompt();
1256
+ continue;
1257
+ }
1258
+ const selected = await options.providers.select(chosen);
1259
+ write(selected.message);
1260
+ if (selected.ok)
1261
+ await signInAfterProviderSelection();
1262
+ if (inputClosed)
1263
+ break;
1264
+ showPrompt();
1265
+ continue;
1266
+ }
1014
1267
  const selected = outcome.kind === "provider"
1015
1268
  ? await options.providers.select(outcome.argument)
1016
1269
  : outcome.kind === "model" ? await options.providers.changeModel(outcome.argument)
@@ -1077,6 +1330,7 @@ export async function runRepl(options) {
1077
1330
  const next = await options.sessionOptions?.create?.(outcome.title);
1078
1331
  if (next === undefined)
1079
1332
  throw new Error("Session creation is unavailable.");
1333
+ await activeSession.close();
1080
1334
  activeSession = next;
1081
1335
  write(`Started a new session${next.title ? ` · ${next.title}` : ""}. Previous session saved.\n`);
1082
1336
  }
@@ -1099,6 +1353,7 @@ export async function runRepl(options) {
1099
1353
  const next = await options.sessionOptions?.resume?.(id);
1100
1354
  if (next === undefined)
1101
1355
  throw new Error(`Unknown session in this workspace: ${id}`);
1356
+ await activeSession.close();
1102
1357
  activeSession = next;
1103
1358
  write(`Resumed saved session${next.title ? ` · ${next.title}` : ""}.\n`);
1104
1359
  }
@@ -1141,9 +1396,9 @@ export async function runRepl(options) {
1141
1396
  tuiInput?.setBusy(true);
1142
1397
  try {
1143
1398
  const signal = controller.signal;
1144
- const prompt = () => activeSession.prompt(line, { signal });
1399
+ const prompt = () => activeSession.prompt(line, { signal, questionPresenter });
1145
1400
  if (options.tui)
1146
- await withoutEcho(readline, prompt);
1401
+ await withoutEcho(readline, prompt, () => questionMode);
1147
1402
  else
1148
1403
  await prompt();
1149
1404
  }
@@ -1162,6 +1417,7 @@ export async function runRepl(options) {
1162
1417
  options.shellApproval?.setHandler(undefined);
1163
1418
  readline.close();
1164
1419
  tuiInput?.dispose();
1420
+ await activeSession.close();
1165
1421
  }
1166
1422
  return interrupted ? 130 : 0;
1167
1423
  }