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.
@@ -138,6 +138,9 @@ import {
138
138
  selectModelForTask,
139
139
  } from "../lib/task-model-selector.js";
140
140
  import { runnableTaskModel, hasUsableKey } from "../lib/runnable-provider.js";
141
+ import { resolveProviderDefinition } from "../lib/llm-providers.js";
142
+ import { isLkEndpoint, LK_MODELS } from "../lib/llm-channel-presets.js";
143
+ import { maybeWarnDeprecatedModel } from "../lib/model-deprecation.js";
141
144
  import { CLIPermanentMemory } from "../lib/permanent-memory.js";
142
145
  import { resolveClaudeProjectAutoMemory } from "../lib/claude-project-auto-memory.js";
143
146
  import { CLIAutonomousAgent, GoalStatus } from "../lib/autonomous-agent.js";
@@ -225,11 +228,11 @@ import {
225
228
  buildPermissionPrompt,
226
229
  resolveAskIdleTimeoutMs,
227
230
  questionWithIdleTimeout,
231
+ createReplQuestionQueue,
228
232
  } from "./permission-prompt.js";
229
233
  import { describeAskContext, raceLocalAndRemote } from "./remote-approval.js";
230
234
  import { runWithHostHooksV2Workspace } from "../lib/hooks-v2-workspace-context.js";
231
235
  import {
232
- parsePermissionTier,
233
236
  parsePermissionModeArg,
234
237
  permissionModeForTier,
235
238
  describeTier,
@@ -3182,6 +3185,7 @@ export async function startAgentRepl(options = {}) {
3182
3185
  async function startAgentReplInWorkspace(options = {}, startupAdmission) {
3183
3186
  let failureHandler = null;
3184
3187
  let disposePipeSafety = null;
3188
+ let disposeTerminalWindow = null;
3185
3189
  const flow = installOutputBackpressure({
3186
3190
  stdout: process.stdout,
3187
3191
  stderr: process.stderr,
@@ -3197,9 +3201,13 @@ async function startAgentReplInWorkspace(options = {}, startupAdmission) {
3197
3201
  setPipeDisposer(disposer) {
3198
3202
  disposePipeSafety = disposer;
3199
3203
  },
3204
+ setTerminalDisposer(disposer) {
3205
+ disposeTerminalWindow = disposer;
3206
+ },
3200
3207
  restore() {
3201
3208
  if (restored) return;
3202
3209
  restored = true;
3210
+ disposeTerminalWindow?.();
3203
3211
  disposePipeSafety?.();
3204
3212
  flow.restore();
3205
3213
  },
@@ -3358,7 +3366,7 @@ async function startAgentReplInWorkspaceOwned(
3358
3366
  // clear steering immediately so queued work cannot start another paid call.
3359
3367
  let _processingLine = false;
3360
3368
  let _lineSettled = null;
3361
- const _activeBtwCalls = new Set();
3369
+ const _activeConcurrentCalls = new Set();
3362
3370
  const _mcpTaskTrackers = new Map();
3363
3371
  const _mcpTaskAutoWakeQueue = [];
3364
3372
  let _mcpTaskAutoWakeRunning = false;
@@ -3459,6 +3467,7 @@ async function startAgentReplInWorkspaceOwned(
3459
3467
  }
3460
3468
  };
3461
3469
  let model = options.model || "qwen2.5:7b";
3470
+ let pendingModel = null;
3462
3471
  let provider = options.provider || "ollama";
3463
3472
  // Extended thinking (Anthropic; opt-in via --think/--ultrathink). Carried from
3464
3473
  // the runtime policy into the agent-loop options below. Mutable so the
@@ -3823,6 +3832,8 @@ async function startAgentReplInWorkspaceOwned(
3823
3832
  // (strict / trusted / autopilot).
3824
3833
  let _renderStatus = null;
3825
3834
  let _managedSettings = null;
3835
+ let _replQuestions;
3836
+ let baseApprovalGate;
3826
3837
  try {
3827
3838
  const { getApprovalGate } =
3828
3839
  await import("../lib/session-core-singletons.js");
@@ -3831,6 +3842,7 @@ async function startAgentReplInWorkspaceOwned(
3831
3842
  _approvalGate?.createSessionScope?.(
3832
3843
  sessionId || `repl-scope:${randomUUID()}`,
3833
3844
  ) || _approvalGate;
3845
+ baseApprovalGate = _approvalGate;
3834
3846
  _approvalGate?.setAuthorizationConsumer?.(null);
3835
3847
  // autoMode.decisions: wrap the gate with the configurable classifier
3836
3848
  // BEFORE setConfirmer so the wrapper captures the interactive confirmer.
@@ -3861,12 +3873,7 @@ async function startAgentReplInWorkspaceOwned(
3861
3873
  // the device answers first, and `canceled` mutes the stranded
3862
3874
  // idle-timeout leg so it can't print "auto-denied" after the fact.
3863
3875
  const askGateApprovalLocally = ({ tool, args, riskLevel }) => {
3864
- const rlConfirm = readline.createInterface({
3865
- input: process.stdin,
3866
- output: process.stdout,
3867
- });
3868
- let canceled = false;
3869
- const q = (p) => new Promise((res) => rlConfirm.question(p, res));
3876
+ const question = _replQuestions.create();
3870
3877
  const cmd = args?.command ? ` ${args.command}` : "";
3871
3878
  const promise = (async () => {
3872
3879
  const status = _renderStatus?.({
@@ -3875,16 +3882,16 @@ async function startAgentReplInWorkspaceOwned(
3875
3882
  });
3876
3883
  if (status) process.stdout.write(status + "\n");
3877
3884
  const res = await questionWithIdleTimeout(
3878
- q,
3885
+ question.ask,
3879
3886
  chalk.yellow(
3880
3887
  `\n[ApprovalGate] ${riskLevel || "medium"} risk command:${cmd}\n` +
3881
3888
  ` Proceed? [y]es once / [a]lways allow / [N]o: `,
3882
3889
  ),
3883
3890
  _askIdleTimeoutMs,
3884
3891
  );
3885
- rlConfirm.close();
3886
- if (canceled) return false; // raced out — the device already decided
3892
+ if (question.canceled) return false;
3887
3893
  if (res.timedOut) {
3894
+ question.cancel();
3888
3895
  process.stdout.write(
3889
3896
  chalk.yellow(
3890
3897
  `\n ⏱ no response in ${_askIdleTimeoutMs}ms — auto-denied\n`,
@@ -3892,7 +3899,7 @@ async function startAgentReplInWorkspaceOwned(
3892
3899
  );
3893
3900
  return false;
3894
3901
  }
3895
- const ans = res.answer.trim().toLowerCase();
3902
+ const ans = (res.answer || "").trim().toLowerCase();
3896
3903
  if (ans === "a" || ans === "always") {
3897
3904
  const saved = await _persistAlwaysAllow(tool || "run_shell", args);
3898
3905
  if (saved) {
@@ -3908,10 +3915,7 @@ async function startAgentReplInWorkspaceOwned(
3908
3915
  })();
3909
3916
  return {
3910
3917
  promise,
3911
- cancel: () => {
3912
- canceled = true;
3913
- rlConfirm.close();
3914
- },
3918
+ cancel: question.cancel,
3915
3919
  };
3916
3920
  };
3917
3921
  _approvalGate.setConfirmer(
@@ -3972,7 +3976,11 @@ async function startAgentReplInWorkspaceOwned(
3972
3976
  const { readBooleanSetting } = await import("../lib/settings-loader.cjs");
3973
3977
  const { createPermissionRulesProvider, loadPermissionAuthority } =
3974
3978
  await import("../lib/permission-authority.js");
3975
- const permissionAuthorityOptions = { cwd: process.cwd() };
3979
+ const permissionAuthorityOptions = {
3980
+ cwd: process.cwd(),
3981
+ settingsFile: options.settingsFile,
3982
+ managedSettingsFile: options.managedSettingsFile,
3983
+ };
3976
3984
  const loaded = loadPermissionAuthority(permissionAuthorityOptions);
3977
3985
  _managedSettings = loaded.managed;
3978
3986
  _permissionRulesProvider = createPermissionRulesProvider(
@@ -3998,25 +4006,20 @@ async function startAgentReplInWorkspaceOwned(
3998
4006
  // Local prompt as a cancelable handle (same shape as the gate confirmer
3999
4007
  // above) so /remote-control can race it against a paired device.
4000
4008
  const askPermissionLocally = ({ tool, args, rule, reason }) => {
4001
- const rl = readline.createInterface({
4002
- input: process.stdin,
4003
- output: process.stdout,
4004
- });
4005
- let canceled = false;
4006
- const q = (p) => new Promise((res) => rl.question(p, res));
4009
+ const question = _replQuestions.create();
4007
4010
  // Picks the right phrasing whether the caller passed a `rule`
4008
4011
  // (settings/hook ask) or a `reason` (destructive-git / sensitive-file
4009
4012
  // guards) — avoids the literal "null" the old template printed.
4010
4013
  const header = buildPermissionPrompt({ tool, args, rule, reason });
4011
4014
  const promise = (async () => {
4012
4015
  const res = await questionWithIdleTimeout(
4013
- q,
4016
+ question.ask,
4014
4017
  chalk.yellow(`\n${header}\n Proceed? (y/N) `),
4015
4018
  _askIdleTimeoutMs,
4016
4019
  );
4017
- rl.close();
4018
- if (canceled) return false; // raced out — the device already decided
4020
+ if (question.canceled) return false;
4019
4021
  if (res.timedOut) {
4022
+ question.cancel();
4020
4023
  process.stdout.write(
4021
4024
  chalk.yellow(
4022
4025
  `\n ⏱ no response in ${_askIdleTimeoutMs}ms — auto-denied\n`,
@@ -4024,15 +4027,12 @@ async function startAgentReplInWorkspaceOwned(
4024
4027
  );
4025
4028
  return false;
4026
4029
  }
4027
- const ans = res.answer.trim().toLowerCase();
4030
+ const ans = (res.answer || "").trim().toLowerCase();
4028
4031
  return ans === "y" || ans === "yes";
4029
4032
  })();
4030
4033
  return {
4031
4034
  promise,
4032
- cancel: () => {
4033
- canceled = true;
4034
- rl.close();
4035
- },
4035
+ cancel: question.cancel,
4036
4036
  };
4037
4037
  };
4038
4038
  // Confirmer is shared by permission `ask` rules AND hook `ask` decisions,
@@ -4951,43 +4951,30 @@ async function startAgentReplInWorkspaceOwned(
4951
4951
  }
4952
4952
  }
4953
4953
 
4954
- // Apply bundle approval policy to this session (after both gate and sessionId are ready)
4955
- const { assertManagedPermissionMode } =
4954
+ const { assertManagedPermissionMode, defaultInteractivePermissionMode } =
4956
4955
  await import("../lib/settings-loader.cjs");
4957
- if (planPermissionMode)
4958
- assertManagedPermissionMode(planPermissionMode, _managedSettings);
4959
- if (
4960
- !planManager.executionLock &&
4961
- _bundleResolved?.approvalPolicy?.default &&
4962
- _approvalGate &&
4963
- sessionId
4964
- ) {
4965
- try {
4966
- await _approvalGate.setSessionPolicy(
4967
- sessionId,
4968
- _bundleResolved.approvalPolicy.default,
4969
- );
4970
- await _approvalGate.awaitPersistence?.();
4971
- // Mirror it so Shift+Tab cycling starts from the real tier.
4972
- const applied = parsePermissionTier(
4973
- _bundleResolved.approvalPolicy.default,
4974
- );
4975
- if (applied) setSessionTier(applied);
4976
- } catch (error) {
4977
- logger.warn(`Bundle approval policy was not persisted: ${error.message}`);
4978
- }
4979
- }
4980
-
4981
- // --permission-mode for the interactive session (headless parity): manual →
4982
- // strict, acceptEdits → trusted, bypassPermissions → autopilot, and auto →
4983
- // trusted tier + the autoMode.decisions classifier. An explicit flag wins
4984
- // over the bundle's approvalPolicy default. Unknown values are ignored here
4985
- // (headless validates them; interactively we just keep the default tier).
4986
- if ((planPermissionMode || options.permissionMode) && sessionId) {
4956
+ const assertSessionTier = (tier) =>
4957
+ assertManagedPermissionMode(permissionModeForTier(tier), _managedSettings);
4958
+ const fallbackPermissionMode =
4959
+ defaultInteractivePermissionMode(_managedSettings);
4960
+ const savedPermissionMode = (sid) => {
4961
+ const saved = baseApprovalGate?.getAuthorizationPolicySnapshot?.(sid);
4962
+ if (!saved?.revision) return fallbackPermissionMode;
4963
+ return saved.policy === "autopilot" && fallbackPermissionMode === "default"
4964
+ ? "default"
4965
+ : saved.policy;
4966
+ };
4967
+ if (sessionId) {
4968
+ const requested =
4969
+ planPermissionMode ||
4970
+ options.permissionMode ||
4971
+ _bundleResolved?.approvalPolicy?.default;
4987
4972
  const parsed = parsePermissionModeArg(
4988
- planPermissionMode || options.permissionMode,
4973
+ requested || savedPermissionMode(sessionId),
4989
4974
  );
4990
- if (parsed && typeof _approvalGate?.setSessionPolicy === "function") {
4975
+ if (!parsed) throw new Error(`Invalid permission mode "${requested}"`);
4976
+ assertSessionTier(parsed.tier);
4977
+ if (typeof _approvalGate?.setSessionPolicy === "function") {
4991
4978
  try {
4992
4979
  await _approvalGate.setSessionPolicy(sessionId, parsed.tier);
4993
4980
  await _approvalGate.awaitPersistence?.();
@@ -5001,11 +4988,6 @@ async function startAgentReplInWorkspaceOwned(
5001
4988
  } else if (planManager.executionLock) {
5002
4989
  throw new Error("Cannot apply the approved plan's permission mode");
5003
4990
  }
5004
- } else if (_approvalGate && sessionId) {
5005
- const tier = parsePermissionTier(
5006
- _approvalGate.getSessionPolicy?.(sessionId),
5007
- );
5008
- if (tier) setSessionTier(tier);
5009
4991
  }
5010
4992
 
5011
4993
  // Phase G #5 — inject top-K memory recall into system prompt for new sessions
@@ -5250,46 +5232,33 @@ async function startAgentReplInWorkspaceOwned(
5250
5232
  if (_screenReaderMode) _theme = "mono";
5251
5233
  applyThemeChalk(_theme, chalk, _chalkBaselineLevel);
5252
5234
 
5253
- // Fullscreen / no-flicker TUI mode (Claude-Code `/tui` parity). Resolve from
5254
- // CC_NO_FLICKER (forces fullscreen) or persisted `cli.tuiMode`; switchable at
5255
- // runtime via `/tui fullscreen|default`. Screen-reader mode forces default —
5256
- // an alternate screen buffer breaks readers. The heavy renderer lives in
5257
- // fullscreen-tui.js; here we just track the mode and toggle the alt buffer.
5258
- const {
5259
- resolveTuiMode: _resolveTuiMode,
5260
- renderTuiStatus: _renderTuiStatus,
5261
- ALT_SCREEN_ENTER: _ALT_ENTER,
5262
- ALT_SCREEN_LEAVE: _ALT_LEAVE,
5263
- } = await import("./fullscreen-tui.js");
5235
+ // A real terminal gets the interactive window by default. Keep scrollback
5236
+ // for screen-reader mode, redirection and an explicit /tui default.
5237
+ const { resolveTuiMode: _resolveTuiMode, renderTuiStatus: _renderTuiStatus } =
5238
+ await import("./fullscreen-tui.js");
5239
+ const canUseTerminalWindow = Boolean(
5240
+ process.stdin.isTTY &&
5241
+ process.stdout.isTTY &&
5242
+ process.env.TERM !== "dumb" &&
5243
+ !_screenReaderMode,
5244
+ );
5264
5245
  let _tuiMode = "default";
5265
- try {
5266
- const { getConfigValue } = await import("../lib/config-manager.js");
5267
- _tuiMode = _resolveTuiMode({
5268
- env: process.env.CC_NO_FLICKER,
5269
- setting: getConfigValue("cli.tuiMode"),
5270
- });
5271
- } catch (_e) {
5272
- _tuiMode = _resolveTuiMode({ env: process.env.CC_NO_FLICKER });
5273
- }
5274
- if (_screenReaderMode) _tuiMode = "default";
5275
- const _setTuiMode = (next) => {
5276
- if (next === _tuiMode) return;
5277
- // Enter/leave the alternate screen buffer so the user's scrollback is
5278
- // preserved either way. Only touch a real TTY.
5279
- if (process.stdout.isTTY) {
5280
- process.stdout.write(next === "fullscreen" ? _ALT_ENTER : _ALT_LEAVE);
5246
+ if (canUseTerminalWindow) {
5247
+ let setting = "fullscreen";
5248
+ try {
5249
+ const { getConfigValue } = await import("../lib/config-manager.js");
5250
+ setting = getConfigValue("cli.tuiMode") || setting;
5251
+ } catch {
5252
+ // Optional configuration.
5281
5253
  }
5282
- _tuiMode = next;
5283
- };
5284
- if (_tuiMode === "fullscreen" && process.stdout.isTTY) {
5285
- process.stdout.write(_ALT_ENTER);
5254
+ _tuiMode = _resolveTuiMode({ env: process.env.CC_NO_FLICKER, setting });
5286
5255
  }
5287
5256
 
5288
5257
  // Fast mode (Claude-Code `/fast` parity, generalized to a latency profile).
5289
5258
  // When on, the next turn minimizes reasoning and — unless the user pinned a
5290
5259
  // model this session — swaps to the provider's low-latency model. Resolved
5291
5260
  // from config `cli.fastMode`; toggled at runtime via `/fast`. `_modelPinned`
5292
- // tracks an explicit `/model x` so fast mode never overrides a chosen model.
5261
+ // tracks an explicit `/model x` so automatic routing keeps that choice.
5293
5262
  const {
5294
5263
  parseFastCommand: _parseFastCommand,
5295
5264
  resolveFastPlan: _resolveFastPlan,
@@ -5387,6 +5356,7 @@ async function startAgentReplInWorkspaceOwned(
5387
5356
  "/hooks",
5388
5357
  "/ide",
5389
5358
  "/init",
5359
+ "/interrupt",
5390
5360
  "/mcp",
5391
5361
  "/mcp-watch",
5392
5362
  "/memory",
@@ -5461,9 +5431,55 @@ async function startAgentReplInWorkspaceOwned(
5461
5431
  },
5462
5432
  });
5463
5433
 
5434
+ const { createTerminalWindow } = await import("./terminal-window.js");
5435
+ const liveSlashCommands = new Set([
5436
+ "/cost",
5437
+ "/help",
5438
+ "/model",
5439
+ "/permissions",
5440
+ "/status",
5441
+ "/tasks",
5442
+ "/todos",
5443
+ "/tui",
5444
+ ]);
5445
+ const isModelCommand = (line) => /^\/model(?:\s|$)/u.test(line);
5446
+ const terminalWindow = canUseTerminalWindow
5447
+ ? createTerminalWindow({
5448
+ input: process.stdin,
5449
+ stdout: process.stdout,
5450
+ stderr: process.stderr,
5451
+ waitForOutput: _waitForReplOutput,
5452
+ getStatus: () =>
5453
+ [
5454
+ _replQuestions.isActive()
5455
+ ? "Waiting for input"
5456
+ : _processingLine
5457
+ ? "Working · Esc to interrupt"
5458
+ : "Ready",
5459
+ `Permissions ${_sessionTier}`,
5460
+ pendingModel ? `Next model ${pendingModel}` : `Model ${model}`,
5461
+ _pendingLines.length && `${_pendingLines.length} queued`,
5462
+ !_slashCommandsDisabled && "/help",
5463
+ ]
5464
+ .filter(Boolean)
5465
+ .join(" · "),
5466
+ getSlashSuggestions: (line) => {
5467
+ if (_replQuestions.isActive() || !/^\/[\w:.-]*$/.test(line))
5468
+ return [];
5469
+ const commands = atCompleter(line)[0];
5470
+ if (line !== "/" || !_processingLine) return commands;
5471
+ return commands.sort(
5472
+ (a, b) =>
5473
+ Number(liveSlashCommands.has(b)) -
5474
+ Number(liveSlashCommands.has(a)),
5475
+ );
5476
+ },
5477
+ isQuestionActive: () => _replQuestions.isActive(),
5478
+ })
5479
+ : null;
5464
5480
  const rl = readline.createInterface({
5465
5481
  input: process.stdin,
5466
- output: process.stdout,
5482
+ output: terminalWindow?.readlineOutput || process.stdout,
5467
5483
  prompt: getPrompt(),
5468
5484
  terminal: true,
5469
5485
  completer: atCompleter,
@@ -5471,6 +5487,25 @@ async function startAgentReplInWorkspaceOwned(
5471
5487
  // Let the EPIPE guard route a broken pipe through this interface's graceful
5472
5488
  // "close" cleanup instead of a bare exit.
5473
5489
  _replRl = rl;
5490
+ _replQuestions = createReplQuestionQueue(rl, (text) =>
5491
+ process.stdout.write(text),
5492
+ );
5493
+ terminalWindow?.bind(rl);
5494
+ const disposeTerminal = () => {
5495
+ terminalWindow?.dispose();
5496
+ process.removeListener("exit", disposeTerminal);
5497
+ };
5498
+ if (terminalWindow) {
5499
+ outputScope.setTerminalDisposer(disposeTerminal);
5500
+ process.once("exit", disposeTerminal);
5501
+ if (_tuiMode === "fullscreen") terminalWindow.enable();
5502
+ }
5503
+ const _setTuiMode = (next) => {
5504
+ if (next === _tuiMode) return;
5505
+ if (next === "fullscreen") terminalWindow?.enable();
5506
+ else terminalWindow?.disable();
5507
+ _tuiMode = next;
5508
+ };
5474
5509
 
5475
5510
  // Prompt-side interaction modules share the production readline surface.
5476
5511
  // A per-REPL registry avoids singleton handlers retaining an old session.
@@ -5510,58 +5545,43 @@ async function startAgentReplInWorkspaceOwned(
5510
5545
  );
5511
5546
  for (const client of mcpElicitationClients) {
5512
5547
  client.setElicitationHandler(
5513
- (request) =>
5514
- new Promise((resolve) => {
5515
- const label =
5516
- request.message || "MCP server requests additional input";
5517
- if (request.mode === "url") {
5518
- rl.question(
5519
- chalk.yellow(
5520
- `\n MCP [${request.server}] ${label}\n` +
5521
- ` Host: ${request.urlHost}\n` +
5522
- ` URL: ${request.url}\n` +
5523
- " Open this secure page? [y/N] ",
5524
- ),
5525
- async (answer) => {
5526
- const approved = /^(y|yes)$/i.test(String(answer || "").trim());
5527
- if (!approved) {
5528
- resolve({ action: "decline" });
5529
- rl.prompt();
5530
- return;
5531
- }
5532
- try {
5533
- const { defaultOpenBrowser } =
5534
- await import("../lib/mcp-oauth.js");
5535
- const opened = defaultOpenBrowser(request.url);
5536
- resolve(opened ? { action: "accept" } : { action: "cancel" });
5537
- } catch {
5538
- resolve({ action: "cancel" });
5539
- }
5540
- rl.prompt();
5541
- },
5542
- );
5543
- return;
5544
- }
5545
- rl.question(
5546
- chalk.yellow(`\n MCP [${request.server}] ${label}\n > `),
5547
- (answer) => {
5548
- const trimmed = String(answer || "").trim();
5549
- if (!trimmed) {
5550
- resolve({ action: "cancel" });
5551
- } else {
5552
- let content = { value: trimmed };
5553
- try {
5554
- const parsed = JSON.parse(trimmed);
5555
- if (parsed && typeof parsed === "object") content = parsed;
5556
- } catch {
5557
- // Plain text remains a valid single-field elicitation answer.
5558
- }
5559
- resolve({ action: "accept", content });
5560
- }
5561
- rl.prompt();
5562
- },
5548
+ async (request) => {
5549
+ const label = request.message || "MCP server requests additional input";
5550
+ const question = _replQuestions.create();
5551
+ if (request.mode === "url") {
5552
+ const answer = await question.ask(
5553
+ chalk.yellow(
5554
+ `\n MCP [${request.server}] ${label}\n` +
5555
+ ` Host: ${request.urlHost}\n` +
5556
+ ` URL: ${request.url}\n` +
5557
+ " Open this secure page? [y/N] ",
5558
+ ),
5563
5559
  );
5564
- }),
5560
+ if (answer === null) return { action: "cancel" };
5561
+ if (!/^(y|yes)$/i.test(answer.trim())) return { action: "decline" };
5562
+ try {
5563
+ const { defaultOpenBrowser } = await import("../lib/mcp-oauth.js");
5564
+ return {
5565
+ action: defaultOpenBrowser(request.url) ? "accept" : "cancel",
5566
+ };
5567
+ } catch {
5568
+ return { action: "cancel" };
5569
+ }
5570
+ }
5571
+ const answer = await question.ask(
5572
+ chalk.yellow(`\n MCP [${request.server}] ${label}\n > `),
5573
+ );
5574
+ const trimmed = answer?.trim();
5575
+ if (!trimmed) return { action: "cancel" };
5576
+ let content = { value: trimmed };
5577
+ try {
5578
+ const parsed = JSON.parse(trimmed);
5579
+ if (parsed && typeof parsed === "object") content = parsed;
5580
+ } catch {
5581
+ // Plain text is a valid single-field answer.
5582
+ }
5583
+ return { action: "accept", content };
5584
+ },
5565
5585
  { timeoutMs: options.mcpElicitationTimeoutMs },
5566
5586
  );
5567
5587
  }
@@ -5676,42 +5696,57 @@ async function startAgentReplInWorkspaceOwned(
5676
5696
  // Idle Esc presses (no active turn) are ignored, and escape-prefixed key
5677
5697
  // sequences (arrows etc.) never reach here as bare "escape".
5678
5698
  _turnAbort = null;
5699
+ const interruptTurn = () => {
5700
+ if (!_turnAbort || _turnAbort.signal.aborted) return false;
5701
+ process.stdout.write(chalk.yellow("\n⎋ interrupting…\n"));
5702
+ _turnAbort.abort();
5703
+ _replQuestions.cancelActive();
5704
+ if (_settingsHooks) {
5705
+ import("../lib/settings-hook-events.js")
5706
+ .then(({ runObserveHooks }) =>
5707
+ runObserveHooks(
5708
+ _settingsHooks,
5709
+ "SessionPause",
5710
+ {
5711
+ session_id: sessionId,
5712
+ reason: "user-interrupt",
5713
+ cwd: process.cwd(),
5714
+ },
5715
+ { cwd: process.cwd() },
5716
+ ),
5717
+ )
5718
+ .catch(() => {});
5719
+ }
5720
+ return true;
5721
+ };
5679
5722
  let _lastIdleEscAt = 0;
5680
5723
  let _replKeypressHandler = null;
5681
5724
  if (process.stdin.isTTY) {
5682
5725
  _replKeypressHandler = async (_str, key) => {
5683
5726
  const k = key || {};
5727
+ if (terminalWindow?.handlePickerKey(_str, k)) {
5728
+ _consumeReadlineKeypress(key);
5729
+ return;
5730
+ }
5684
5731
  // 1) Turn abort always wins, regardless of vim mode.
5685
- if (k.name === "escape" && !k.meta && _turnAbort) {
5732
+ if (
5733
+ k.name === "escape" &&
5734
+ !k.meta &&
5735
+ (_turnAbort || _replQuestions.isActive())
5736
+ ) {
5686
5737
  _consumeReadlineKeypress(key);
5687
- process.stdout.write(chalk.yellow("\n⎋ interrupting…\n"));
5688
- try {
5689
- _turnAbort.abort();
5690
- } catch {
5691
- /* already aborted */
5692
- }
5693
- _turnAbort = null;
5694
- // settings.json SessionPause hooks: the user interrupted the in-flight
5695
- // turn — the session stays open, the current work is suspended. The
5696
- // keypress handler can't await, so fire observe-only fire-and-forget.
5697
- if (_settingsHooks) {
5698
- import("../lib/settings-hook-events.js")
5699
- .then(({ runObserveHooks }) =>
5700
- runObserveHooks(
5701
- _settingsHooks,
5702
- "SessionPause",
5703
- {
5704
- session_id: sessionId,
5705
- reason: "user-interrupt",
5706
- cwd: process.cwd(),
5707
- },
5708
- { cwd: process.cwd() },
5709
- ),
5710
- )
5711
- .catch(() => {});
5712
- }
5738
+ if (!interruptTurn()) _replQuestions.cancelActive();
5713
5739
  return;
5714
5740
  }
5741
+ if (
5742
+ _tuiMode === "fullscreen" &&
5743
+ (k.name === "pageup" || k.name === "pagedown")
5744
+ ) {
5745
+ _consumeReadlineKeypress(key);
5746
+ terminalWindow.scroll(k.name === "pageup" ? 1 : -1);
5747
+ return;
5748
+ }
5749
+ if (_replQuestions.isActive()) return;
5715
5750
 
5716
5751
  // 1.5) Shift+Tab cycles the session approval tier (Claude-Code mode
5717
5752
  // cycling): strict → trusted → autopilot → strict. Drives the existing
@@ -5728,7 +5763,9 @@ async function startAgentReplInWorkspaceOwned(
5728
5763
  ) {
5729
5764
  // "auto" rides the trusted tier, so it cycles as trusted → autopilot
5730
5765
  // (cycling is also how you exit auto mode without /permissions).
5731
- const next = nextTier(gateTierFor(_sessionTier));
5766
+ let next = nextTier(gateTierFor(_sessionTier));
5767
+ if (next === "autopilot" && fallbackPermissionMode === "default")
5768
+ next = nextTier(next);
5732
5769
  try {
5733
5770
  await _approvalGate.setSessionPolicy(sessionId, next);
5734
5771
  await _approvalGate.awaitPersistence?.();
@@ -5750,6 +5787,39 @@ async function startAgentReplInWorkspaceOwned(
5750
5787
  return;
5751
5788
  }
5752
5789
 
5790
+ if (_tuiMode === "fullscreen" && !_vim) {
5791
+ if (
5792
+ (k.meta || k.shift) &&
5793
+ (k.name === "return" || k.name === "enter")
5794
+ ) {
5795
+ _consumeReadlineKeypress(key);
5796
+ rl.line =
5797
+ rl.line.slice(0, rl.cursor) + "\n" + rl.line.slice(rl.cursor);
5798
+ rl.cursor++;
5799
+ terminalWindow.schedule();
5800
+ return;
5801
+ }
5802
+ if (terminalWindow.handleSlashKey(k)) {
5803
+ _consumeReadlineKeypress(key);
5804
+ return;
5805
+ }
5806
+ if (
5807
+ k.name === "up" &&
5808
+ !k.ctrl &&
5809
+ !k.meta &&
5810
+ !k.shift &&
5811
+ _processingLine &&
5812
+ !rl.line &&
5813
+ _pendingLines.length
5814
+ ) {
5815
+ _consumeReadlineKeypress(key);
5816
+ rl.line = _pendingLines.pop();
5817
+ rl.cursor = rl.line.length;
5818
+ terminalWindow.schedule();
5819
+ return;
5820
+ }
5821
+ }
5822
+
5753
5823
  // 1.75) Prompt interaction keybindings share the controller used by
5754
5824
  // slash commands. They are idle-only and stay out of Vim NORMAL mode,
5755
5825
  // where the modal editor owns every key.
@@ -5896,6 +5966,48 @@ async function startAgentReplInWorkspaceOwned(
5896
5966
  let _ctxRequestWindow = null;
5897
5967
  let _turnCount = 0;
5898
5968
  const _costStore = newCostStore(); // running token spend for `/cost`
5969
+
5970
+ const recentModels = new Map();
5971
+ const applyPendingModel = () => {
5972
+ if (!pendingModel) return;
5973
+ model = pendingModel;
5974
+ pendingModel = null;
5975
+ _curModel = model;
5976
+ _ctxRequestWindow = null;
5977
+ _modelPinned = true;
5978
+ terminalWindow?.schedule();
5979
+ };
5980
+ const selectModel = (next, defer) => {
5981
+ pendingModel = next;
5982
+ if (!defer) applyPendingModel();
5983
+ if (!recentModels.has(provider)) recentModels.set(provider, new Set());
5984
+ recentModels.get(provider).add(next);
5985
+ logger.info(
5986
+ defer
5987
+ ? `Next turn will use ${chalk.cyan(next)}`
5988
+ : `Model: ${chalk.cyan(next)}`,
5989
+ );
5990
+ maybeWarnDeprecatedModel({ model: next });
5991
+ };
5992
+ const modelChoices = (selected) => {
5993
+ // The gateway catalog distinguishes chat models by compatible wire API.
5994
+ const protocol = provider === "custom" ? "openai" : provider;
5995
+ const known = isLkEndpoint(baseUrl)
5996
+ ? LK_MODELS.filter(
5997
+ (entry) =>
5998
+ entry.type === "chat" &&
5999
+ entry.compatibleProtocols.includes(protocol),
6000
+ ).map((entry) => entry.id)
6001
+ : resolveProviderDefinition(provider)?.models || [];
6002
+ return [
6003
+ ...new Set([
6004
+ selected,
6005
+ model,
6006
+ ...(recentModels.get(provider) || []),
6007
+ ...known,
6008
+ ]),
6009
+ ];
6010
+ };
5899
6011
  try {
5900
6012
  const slm = await import("../lib/status-line.js");
5901
6013
  const _sl = slm.default || slm;
@@ -5938,6 +6050,7 @@ async function startAgentReplInWorkspaceOwned(
5938
6050
  }
5939
6051
 
5940
6052
  const prompt = () => {
6053
+ if (_replQuestions.isActive()) return;
5941
6054
  if (_statusLineEnabled && _renderStatus) {
5942
6055
  const line = _renderStatus();
5943
6056
  // Built-in line is dimmed; a custom command may carry its own ANSI.
@@ -5945,7 +6058,7 @@ async function startAgentReplInWorkspaceOwned(
5945
6058
  process.stdout.write((_customStatus ? line : chalk.dim(line)) + "\n");
5946
6059
  }
5947
6060
  rl.setPrompt(getPrompt());
5948
- rl.prompt();
6061
+ rl.prompt(true);
5949
6062
  };
5950
6063
 
5951
6064
  // Fire SessionStart hook (fire-and-forget; hook failures never break REPL)
@@ -6060,6 +6173,7 @@ async function startAgentReplInWorkspaceOwned(
6060
6173
  }
6061
6174
  } finally {
6062
6175
  _processingLine = false;
6176
+ if (!_replClosing) applyPendingModel();
6063
6177
  settleLine();
6064
6178
  _lineSettled = null;
6065
6179
  _mcpTaskAutoWakeRunning = false;
@@ -6081,7 +6195,8 @@ async function startAgentReplInWorkspaceOwned(
6081
6195
  kickMcpTaskAutoWake();
6082
6196
  return true;
6083
6197
  };
6084
- const handleLine = async (input) => {
6198
+ const handleLine = async (input, concurrent = false) => {
6199
+ if (!concurrent) applyPendingModel();
6085
6200
  let mcpAutoWakeDelivery =
6086
6201
  input === _mcpTaskAutoWakeSentinel
6087
6202
  ? _mcpTaskAutoWakeQueue.shift() || null
@@ -6106,16 +6221,18 @@ async function startAgentReplInWorkspaceOwned(
6106
6221
  }
6107
6222
  }
6108
6223
  // Backslash continuation — accumulate and re-prompt without firing a turn.
6109
- const _cont = analyzeContinuation(input);
6110
- if (_cont.continued) {
6111
- _mlBuffer.push(_cont.text);
6112
- rl.setPrompt(chalk.dim("... "));
6113
- rl.prompt();
6114
- return;
6115
- }
6116
- if (_mlBuffer.length) {
6117
- input = joinContinuation(_mlBuffer, input);
6118
- _mlBuffer.length = 0;
6224
+ if (!concurrent) {
6225
+ const continuation = analyzeContinuation(input);
6226
+ if (continuation.continued) {
6227
+ _mlBuffer.push(continuation.text);
6228
+ rl.setPrompt(chalk.dim("... "));
6229
+ rl.prompt(true);
6230
+ return;
6231
+ }
6232
+ if (_mlBuffer.length) {
6233
+ input = joinContinuation(_mlBuffer, input);
6234
+ _mlBuffer.length = 0;
6235
+ }
6119
6236
  }
6120
6237
 
6121
6238
  const rawLine = input.trim();
@@ -6218,6 +6335,11 @@ async function startAgentReplInWorkspaceOwned(
6218
6335
  rl.close();
6219
6336
  return;
6220
6337
  }
6338
+ if (trimmed === "/interrupt") {
6339
+ if (!interruptTurn()) logger.info("No active model turn to interrupt.");
6340
+ prompt();
6341
+ return;
6342
+ }
6221
6343
 
6222
6344
  // The interaction commands are registered through the shared registry,
6223
6345
  // while the mature REPL handlers below remain on their existing direct
@@ -6234,6 +6356,9 @@ async function startAgentReplInWorkspaceOwned(
6234
6356
 
6235
6357
  if (trimmed === "/help") {
6236
6358
  logger.log(chalk.bold("\nCommands:"));
6359
+ logger.log(
6360
+ ` ${chalk.cyan("/interrupt")} Stop the current turn without closing the session`,
6361
+ );
6237
6362
  logger.log(
6238
6363
  ` ${chalk.cyan("! <cmd>")} Run a shell command directly (output joins context)`,
6239
6364
  );
@@ -6247,7 +6372,7 @@ async function startAgentReplInWorkspaceOwned(
6247
6372
  ` ${chalk.cyan("/exit")} Exit the agent (alias: /quit)`,
6248
6373
  );
6249
6374
  logger.log(
6250
- ` ${chalk.cyan("/model")} Show/change model (/model <name>)`,
6375
+ ` ${chalk.cyan("/model")} Select a model or enter /model <id>`,
6251
6376
  );
6252
6377
  logger.log(` ${chalk.cyan("/provider")} Show/change provider`);
6253
6378
  logger.log(
@@ -6723,27 +6848,35 @@ async function startAgentReplInWorkspaceOwned(
6723
6848
  return;
6724
6849
  }
6725
6850
 
6726
- if (trimmed.startsWith("/model")) {
6851
+ if (isModelCommand(trimmed)) {
6727
6852
  const arg = trimmed.slice(6).trim();
6728
6853
  if (arg) {
6729
- model = arg;
6730
- _curModel = model; // keep the status-line readout in sync
6731
- _modelPinned = true; // explicit choice — fast mode must not override it
6732
- logger.info(`Model: ${chalk.cyan(model)}`);
6733
- // Claude-Code 2.1.183 parity: warn when the newly-selected model is a
6734
- // provider-retired/deprecated snapshot. Headless paths already warn via
6735
- // maybeWarnDeprecatedModel; the interactive /model switch did not, so a
6736
- // user could silently switch to a retired id and only learn of it when
6737
- // the next turn fails with an opaque "model not found".
6738
- try {
6739
- const { maybeWarnDeprecatedModel } =
6740
- await import("../lib/model-deprecation.js");
6741
- maybeWarnDeprecatedModel({ model });
6742
- } catch {
6743
- // deprecation notice is best-effort
6744
- }
6854
+ if (arg.length > 256 || /[\s\p{Cc}]/u.test(arg))
6855
+ logger.info("Usage: /model <model-id>");
6856
+ else selectModel(arg, concurrent && _processingLine);
6745
6857
  } else {
6746
- logger.info(`Current model: ${chalk.cyan(model)}`);
6858
+ const selected = pendingModel || model;
6859
+ const choices = modelChoices(selected);
6860
+ if (_tuiMode === "fullscreen") {
6861
+ const pickerProvider = provider;
6862
+ terminalWindow.showPicker({
6863
+ title: `Select model · ${pickerProvider}`,
6864
+ choices,
6865
+ selected,
6866
+ current: model,
6867
+ onSelect: (next) => {
6868
+ if (provider === pickerProvider)
6869
+ selectModel(next, _processingLine);
6870
+ else logger.info("Provider changed. Run /model again.");
6871
+ },
6872
+ });
6873
+ } else {
6874
+ logger.info(`Current model: ${chalk.cyan(model)}`);
6875
+ if (pendingModel)
6876
+ logger.info(`Next model: ${chalk.cyan(pendingModel)}`);
6877
+ logger.info(`Models for ${provider}: ${choices.join(", ")}`);
6878
+ logger.info("Use /model <model-id> to switch.");
6879
+ }
6747
6880
  }
6748
6881
  prompt();
6749
6882
  return;
@@ -7023,10 +7156,10 @@ async function startAgentReplInWorkspaceOwned(
7023
7156
  prompt();
7024
7157
  return;
7025
7158
  }
7026
- if (_screenReaderMode && next === "fullscreen") {
7159
+ if (!canUseTerminalWindow && next === "fullscreen") {
7027
7160
  logger.info(
7028
7161
  chalk.gray(
7029
- "Screen-reader mode is on — staying in default (scrollback) view.",
7162
+ "Fullscreen requires an interactive terminal with screen-reader mode off.",
7030
7163
  ),
7031
7164
  );
7032
7165
  prompt();
@@ -7520,12 +7653,13 @@ async function startAgentReplInWorkspaceOwned(
7520
7653
  if (rewindConversation)
7521
7654
  pruneMarksAfter(_checkpointMarks, turnIndex);
7522
7655
  if (cp) {
7523
- const q = (p) => new Promise((r) => rl.question(p, r));
7524
7656
  const promptText = rewindConversation
7525
7657
  ? ` Also restore files to before this turn? (checkpoint ${cp.id}) [Y/n] `
7526
7658
  : ` Restore files to before this turn? (checkpoint ${cp.id}) [Y/n] `;
7527
- const ans = (await q(chalk.yellow(promptText)))
7528
- .trim()
7659
+ const ans = (
7660
+ await _replQuestions.create().ask(chalk.yellow(promptText))
7661
+ )
7662
+ ?.trim()
7529
7663
  .toLowerCase();
7530
7664
  if (ans === "" || ans === "y" || ans === "yes") {
7531
7665
  try {
@@ -7991,7 +8125,7 @@ async function startAgentReplInWorkspaceOwned(
7991
8125
  targetPlan.permissionMode ||
7992
8126
  (reuseCurrentLease
7993
8127
  ? _sessionTier
7994
- : _approvalGate?.getSessionPolicy?.(prepared.sessionId)) ||
8128
+ : savedPermissionMode(prepared.sessionId)) ||
7995
8129
  "strict",
7996
8130
  );
7997
8131
  if (typeof _approvalGate?.setSessionPolicy === "function") {
@@ -9415,6 +9549,7 @@ async function startAgentReplInWorkspaceOwned(
9415
9549
  );
9416
9550
  } else {
9417
9551
  try {
9552
+ assertSessionTier(parsed.tier);
9418
9553
  await _approvalGate.setSessionPolicy(sessionId, parsed.tier);
9419
9554
  await _approvalGate.awaitPersistence?.();
9420
9555
  setSessionTier(
@@ -10055,7 +10190,11 @@ async function startAgentReplInWorkspaceOwned(
10055
10190
  // get a 401). Runnable-first: keep the configured (working) model instead.
10056
10191
  let activeModel = model;
10057
10192
  const taskDetection = detectTaskType(promptText);
10058
- if (taskDetection.confidence > 0.3 && !mcpContinuationStarted) {
10193
+ if (
10194
+ !_modelPinned &&
10195
+ taskDetection.confidence > 0.3 &&
10196
+ !mcpContinuationStarted
10197
+ ) {
10059
10198
  const recommended = selectModelForTask(provider, taskDetection.taskType);
10060
10199
  const switchTo = runnableTaskModel({
10061
10200
  provider,
@@ -10796,6 +10935,11 @@ async function startAgentReplInWorkspaceOwned(
10796
10935
  rl.on("line", async (input) => {
10797
10936
  if (!(await _waitForReplOutput())) return;
10798
10937
  if (_replClosing) return;
10938
+ const submitted = input.trim();
10939
+ if (_tuiMode === "fullscreen" && submitted) {
10940
+ terminalWindow.follow();
10941
+ terminalWindow.append(`\n> ${input}\n`);
10942
+ }
10799
10943
  if (_runtimeLedgerTerminalLatch.isTripped()) {
10800
10944
  const terminalInput = input.trim();
10801
10945
  if (terminalInput === "/exit" || terminalInput === "/quit") {
@@ -10809,21 +10953,29 @@ async function startAgentReplInWorkspaceOwned(
10809
10953
  if (_processingLine) {
10810
10954
  const concurrentBtw = _slashCommandsDisabled
10811
10955
  ? null
10812
- : parseBtwCommand(input.trim());
10813
- if (concurrentBtw) {
10814
- // Intentionally do not await: the main turn keeps streaming while this
10815
- // independent, tool-free snapshot call runs alongside it.
10816
- const sideCall = runBtwSideQuestion(concurrentBtw, {
10817
- concurrent: true,
10818
- });
10819
- _activeBtwCalls.add(sideCall);
10956
+ : parseBtwCommand(submitted);
10957
+ const liveCommand =
10958
+ submitted === "/exit" ||
10959
+ submitted === "/quit" ||
10960
+ (!_slashCommandsDisabled &&
10961
+ (submitted === "/interrupt" ||
10962
+ isModelCommand(submitted) ||
10963
+ liveSlashCommands.has(submitted)));
10964
+ if (liveCommand || concurrentBtw) {
10965
+ const sideCall = liveCommand
10966
+ ? handleLine(input, true)
10967
+ : runBtwSideQuestion(concurrentBtw, { concurrent: true });
10968
+ _activeConcurrentCalls.add(sideCall);
10820
10969
  void sideCall.then(
10821
- () => _activeBtwCalls.delete(sideCall),
10822
- () => _activeBtwCalls.delete(sideCall),
10970
+ () => _activeConcurrentCalls.delete(sideCall),
10971
+ (error) => {
10972
+ _activeConcurrentCalls.delete(sideCall);
10973
+ if (!_replClosing) logger.error(error.message);
10974
+ },
10823
10975
  );
10824
10976
  return;
10825
10977
  }
10826
- if (input.trim()) {
10978
+ if (submitted) {
10827
10979
  _pendingLines.push(input);
10828
10980
  logger.log(
10829
10981
  chalk.gray(
@@ -10853,6 +11005,8 @@ async function startAgentReplInWorkspaceOwned(
10853
11005
  }
10854
11006
  } finally {
10855
11007
  _processingLine = false;
11008
+ if (!_replClosing) applyPendingModel();
11009
+ terminalWindow?.schedule();
10856
11010
  settleLine();
10857
11011
  _lineSettled = null;
10858
11012
  kickMcpTaskAutoWake();
@@ -10871,6 +11025,7 @@ async function startAgentReplInWorkspaceOwned(
10871
11025
  if (_replCleanupStarted) return;
10872
11026
  _replCleanupStarted = true;
10873
11027
  _replClosing = true;
11028
+ disposeTerminal();
10874
11029
  _pendingLines.length = 0;
10875
11030
  _mcpTaskAutoWakeQueue.length = 0;
10876
11031
  // Do not certify a Run while its model/tool or auxiliary usage settlement
@@ -10893,7 +11048,7 @@ async function startAgentReplInWorkspaceOwned(
10893
11048
  const autonomousShutdown = autonomousAgent.shutdown();
10894
11049
  void autonomousShutdown.catch(() => {});
10895
11050
  await _lineSettled;
10896
- await Promise.allSettled([..._activeBtwCalls]);
11051
+ await Promise.allSettled([..._activeConcurrentCalls]);
10897
11052
  try {
10898
11053
  const { interrupted } = await autonomousShutdown;
10899
11054
  if (interrupted > 0 && _evolutionSession !== null) {
@@ -10913,15 +11068,6 @@ async function startAgentReplInWorkspaceOwned(
10913
11068
  process.stdin.removeListener("keypress", listener);
10914
11069
  }
10915
11070
  }
10916
- // Leave the alternate screen buffer first so the terminal is restored to
10917
- // the user's scrollback no matter how the REPL exits.
10918
- if (_tuiMode === "fullscreen" && process.stdout.isTTY) {
10919
- try {
10920
- process.stdout.write(_ALT_LEAVE);
10921
- } catch (_err) {
10922
- // best-effort restore
10923
- }
10924
- }
10925
11071
  // Stop inbound channel listeners before anything else — no new external
10926
11072
  // events may enter a session that is shutting down.
10927
11073
  if (_channels) {