@saturn-universe/cli 0.1.1 → 0.1.2-dev.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/provider.js CHANGED
@@ -4,11 +4,13 @@ import { enrichPrices, modelAlias } from './provider-pricing.js';
4
4
  import { chooseFromPages, chooseManyFromPages } from './choice-menu.js';
5
5
  import { formatTokenCompact } from './usage.js';
6
6
  import { parseArgs } from 'node:util';
7
- import { geminiModelPath, normalizeProviderBaseUrl, normalizeProviderProtocol, providerIdSchema, credentialRefSchema, resolveCredentialMap, providerPresets, } from '@saturn-universe/protocol';
7
+ import { geminiModelPath, normalizeProviderBaseUrl, normalizeProviderProtocol, openCodeClientHeaders, providerIdSchema, credentialRefSchema, resolveCredentialMap, providerPresets, userConfigPath, } from '@saturn-universe/protocol';
8
8
  import { chooseDefault, configuredEndpoint, listProviderLogins, removeProviderLogin, saveProviderLogin, } from './auth-config.js';
9
9
  import { AuthError } from './cli-diagnostics.js';
10
10
  import { topicHelp } from './cli-help.js';
11
11
  import { inferProviderProtocol, probeProviderEndpoint, supportsTextModel, } from './provider-discovery.js';
12
+ import { customProtocols, providerWizard } from './provider-wizard.js';
13
+ const addPresets = providerPresets.filter(({ id }) => id !== 'anthropic' && id !== 'google');
12
14
  function providerId(value) {
13
15
  const parsed = providerIdSchema.safeParse(value);
14
16
  if (!parsed.success)
@@ -44,13 +46,15 @@ function parseProviderArgs(args) {
44
46
  'api-key-stdin': { type: 'boolean' },
45
47
  'api-key': { type: 'string' },
46
48
  protocol: { type: 'string' },
49
+ model: { type: 'string' },
47
50
  models: { type: 'string' },
48
51
  default: { type: 'string' },
49
52
  'no-probe': { type: 'boolean' },
50
53
  },
51
54
  });
52
55
  if (positionals.length <= 1 &&
53
- (!positionals[0] || !values.provider || positionals[0] === values.provider))
56
+ (!positionals[0] || !values.provider || positionals[0] === values.provider) &&
57
+ !(values.default !== undefined && values.model !== undefined))
54
58
  return { action, id: values.provider ?? positionals[0], values };
55
59
  }
56
60
  }
@@ -69,8 +73,10 @@ export async function runProviderCommand(args, options = {}) {
69
73
  const print = options.writeLine ?? ((value) => process.stdout.write(value + '\n'));
70
74
  const result = (value, message) => print(json ? JSON.stringify({ ok: true, result: value }) : message);
71
75
  const progress = json ? () => { } : print;
72
- const interactive = !json && (options.prompt || (process.stdin.isTTY && process.stdout.isTTY && !args.includes('--api-key')));
73
- const prompt = interactive ? (options.prompt ?? terminalPrompt(process.stdin, process.stdout)) : undefined;
76
+ const tty = !json && process.stdin.isTTY && process.stdout.isTTY;
77
+ const prompt = !json
78
+ ? (options.prompt ?? (tty ? terminalPrompt(process.stdin, process.stdout) : undefined))
79
+ : undefined;
74
80
  try {
75
81
  const profiles = () => listProviderLogins(env, root);
76
82
  const describe = (p) => [p.profile, p.selected ? '当前默认' : '', p.configured ? '已配置' : '缺少密钥']
@@ -133,8 +139,24 @@ export async function runProviderCommand(args, options = {}) {
133
139
  await removeProviderLogin(providerId(command.id), command.keep, env);
134
140
  return result({ provider: command.id }, command.keep ? '已移除密钥。' : '已删除服务。');
135
141
  case 'add': {
136
- const added = await login(command, env, root, progress, prompt, options.probe ?? probeProviderEndpoint, options.prices ?? enrichPrices);
137
- return result(added, '已保存 AI 服务。');
142
+ const wizard = tty && !options.prompt && Object.keys(command.values).length === 0;
143
+ if (wizard) {
144
+ prompt?.close();
145
+ providerWizard.start();
146
+ }
147
+ try {
148
+ const { defaultModel, ...added } = await login(command, env, root, progress, options.prompt && !json ? prompt : undefined, wizard, options.probe ?? probeProviderEndpoint, options.prices ?? enrichPrices);
149
+ if (wizard && defaultModel) {
150
+ providerWizard.finish(`${added.provider}/${defaultModel}`, userConfigPath(env));
151
+ return;
152
+ }
153
+ return result(added, '已保存 AI 服务。');
154
+ }
155
+ catch (error) {
156
+ if (!wizard)
157
+ throw error;
158
+ providerWizard.cancel(error);
159
+ }
138
160
  }
139
161
  }
140
162
  }
@@ -209,7 +231,11 @@ export async function testModel(baseUrl, key, model, protocol = 'openai-response
209
231
  method: 'POST',
210
232
  redirect: 'error',
211
233
  signal: AbortSignal.timeout(15000),
212
- headers: { 'Content-Type': 'application/json', ...headers },
234
+ headers: {
235
+ 'Content-Type': 'application/json',
236
+ ...headers,
237
+ ...(new URL(endpoint).origin === 'https://opencode.ai' ? openCodeClientHeaders : {}),
238
+ },
213
239
  body: JSON.stringify(body),
214
240
  });
215
241
  }
@@ -236,14 +262,18 @@ function parseProtocol(value) {
236
262
  function selection(value) {
237
263
  return [...new Set(value.split(',').map((part) => part.trim()))];
238
264
  }
239
- async function login(command, env, root, line, prompt, probe, prices) {
265
+ async function login(command, env, root, line, prompt, wizard, probe, prices) {
240
266
  const flags = command.values;
241
267
  let requestedId = command.id;
242
- if (requestedId === undefined && prompt) {
268
+ if (requestedId === undefined && wizard) {
269
+ requestedId = await providerWizard.selectProvider(addPresets);
270
+ }
271
+ else if (requestedId === undefined && prompt) {
243
272
  requestedId =
244
- providerPresets[await askChoice(prompt, line, 'Provider', providerPresets.map((preset) => preset.label))].id;
273
+ addPresets[await askChoice(prompt, line, 'Provider', addPresets.map((preset) => preset.label))].id;
245
274
  }
246
- if (prompt && requestedId === 'custom') {
275
+ const custom = requestedId === 'custom';
276
+ if ((prompt || wizard) && custom) {
247
277
  const used = new Set((await listProviderLogins(env, root)).map((p) => p.id));
248
278
  let n = 1;
249
279
  while (used.has('custom-' + n))
@@ -253,55 +283,91 @@ async function login(command, env, root, line, prompt, probe, prices) {
253
283
  const id = providerId(requestedId);
254
284
  const preset = providerPresets.find((item) => item.id === id);
255
285
  const defaultUrl = preset?.defaultBaseUrl;
256
- const rawUrl = flags['base-url'] ?? defaultUrl ?? (prompt ? await prompt.question('EndPoint: ') : undefined);
286
+ const explicitProtocol = flags.protocol !== undefined
287
+ ? parseProtocol(flags.protocol)
288
+ : custom && wizard
289
+ ? await providerWizard.selectProtocol()
290
+ : custom && prompt
291
+ ? customProtocols[await askChoice(prompt, line, 'Protocol', ['openai-chat (推荐)', ...customProtocols.slice(1)], 0)]
292
+ : undefined;
293
+ const rawUrl = flags['base-url'] ??
294
+ defaultUrl ??
295
+ (wizard ? await providerWizard.endpoint(explicitProtocol) : await prompt?.question('EndPoint: '));
257
296
  const baseUrl = rawUrl && normalizeProviderBaseUrl(rawUrl);
258
297
  if (!baseUrl)
259
298
  throw new AuthError('EndPoint 需要完整的 HTTP 或 HTTPS URL。', 'USAGE');
260
299
  if (flags['api-key-stdin'] && (flags['api-key'] !== undefined || process.stdin.isTTY))
261
300
  throw new AuthError('请通过管道提供密钥。', 'USAGE');
262
- const reference = flags['credential-ref'];
301
+ const openCodeModelsUrl = baseUrl === defaultUrl ? preset?.openCodeModelsUrl : undefined;
302
+ const defaultReference = openCodeModelsUrl && preset && !flags['api-key-stdin'] && flags['api-key'] === undefined
303
+ ? preset.defaultEnvKey
304
+ : undefined;
305
+ const presetKey = !flags['credential-ref'] && defaultReference
306
+ ? (await resolveCredentialMap(root, env)).values.get(defaultReference)
307
+ : undefined;
308
+ const reference = flags['credential-ref'] ?? (presetKey ? 'env:' + defaultReference : undefined);
263
309
  if (reference &&
264
310
  (!credentialRefSchema.safeParse(reference).success ||
265
311
  flags['api-key-stdin'] ||
266
312
  flags['api-key'] !== undefined))
267
313
  throw new AuthError('请使用一个 env:变量名 引用密钥。', 'USAGE');
268
- const configuredKey = reference
269
- ? (await resolveCredentialMap(root, env)).values.get(reference.slice(4))
270
- : undefined;
314
+ const configuredKey = presetKey ??
315
+ (reference ? (await resolveCredentialMap(root, env)).values.get(reference.slice(4)) : undefined);
271
316
  if (reference && !configuredKey)
272
317
  throw new AuthError('指定的环境变量没有密钥。');
273
318
  const apiKey = configuredKey ??
274
319
  (flags['api-key-stdin'] ? (await readText(process.stdin)).trimEnd() : flags['api-key']) ??
275
- (prompt ? await prompt.question('API Key: ', true) : undefined);
320
+ (wizard ? await providerWizard.apiKey() : await prompt?.question('API Key: ', true));
276
321
  if (!apiKey?.trim() || apiKey !== apiKey.trim() || /[\u0000-\u001f\u007f]/.test(apiKey))
277
322
  throw new AuthError('请输入一行有效的 API Key。', 'USAGE');
278
323
  if (id.includes(apiKey) || baseUrl.includes(apiKey) || decodeURI(baseUrl).includes(apiKey))
279
324
  throw new AuthError('请只在密钥输入框中填写 API Key。', 'USAGE');
280
- const explicitProtocol = flags.protocol === undefined ? undefined : parseProtocol(flags.protocol);
281
325
  const preferredProtocol = explicitProtocol ??
282
- (baseUrl === defaultUrl ? preset?.defaultProtocol : undefined) ??
326
+ (custom ? 'openai-chat' : baseUrl === defaultUrl ? preset?.defaultProtocol : undefined) ??
283
327
  inferProviderProtocol(baseUrl);
284
328
  let protocol = preferredProtocol;
285
329
  let discovered = [];
286
- if (!flags['no-probe'] && flags.models === undefined && flags.default === undefined) {
287
- line('读取模型…');
288
- const result = await probe(baseUrl, apiKey, { preferredProtocol });
289
- discovered = await prices(baseUrl, result.models.filter((model) => (id + '/' + model.id).length <= 200));
290
- protocol = explicitProtocol ?? result.protocol;
291
- if (result.warning)
292
- line('无法完全确认服务能力,请确认服务地址和模型权限。');
330
+ const defaultFlag = flags.default ?? flags.model;
331
+ if (!flags['no-probe'] &&
332
+ (openCodeModelsUrl || (flags.models === undefined && defaultFlag === undefined))) {
333
+ const discover = async (signal) => {
334
+ const result = await probe(baseUrl, apiKey, { preferredProtocol, ...(signal ? { signal } : {}) });
335
+ signal?.throwIfAborted();
336
+ const candidates = result.models.filter((model) => (id + '/' + model.id).length <= 200);
337
+ const models = openCodeModelsUrl
338
+ ? candidates
339
+ : signal
340
+ ? await prices(baseUrl, candidates, undefined, signal)
341
+ : await prices(baseUrl, candidates);
342
+ return { ...result, models };
343
+ };
344
+ if (!wizard)
345
+ line('读取模型…');
346
+ const result = wizard ? await providerWizard.fetchModels(discover) : await discover();
347
+ if (result) {
348
+ discovered = result.models;
349
+ protocol = explicitProtocol ?? result.protocol;
350
+ if (!wizard && result.warning)
351
+ line('无法完全确认服务能力,请确认服务地址和模型权限。');
352
+ }
293
353
  }
294
354
  const candidates = discovered.filter(supportsTextModel);
295
355
  const knownModel = new Map(discovered.map((model) => [model.id, model]));
296
- const requestedDefault = flags.default !== undefined && !knownModel.has(flags.default) && flags.default.startsWith(`${id}/`)
297
- ? flags.default.slice(id.length + 1)
298
- : flags.default;
356
+ const requestedDefault = defaultFlag !== undefined && !knownModel.has(defaultFlag) && defaultFlag.startsWith(`${id}/`)
357
+ ? defaultFlag.slice(id.length + 1)
358
+ : defaultFlag;
299
359
  let models;
300
360
  let chosen;
301
361
  if (flags.models !== undefined)
302
362
  models = selection(flags.models);
303
363
  else if (requestedDefault !== undefined)
304
364
  models = [requestedDefault];
365
+ else if (wizard) {
366
+ chosen = candidates.length
367
+ ? await providerWizard.selectModel(candidates.map((model) => wizardModelChoice(model, protocol)))
368
+ : (await providerWizard.manualModel()).trim();
369
+ models = [chosen];
370
+ }
305
371
  else if (prompt && candidates.length) {
306
372
  const selected = await chooseManyFromPages(prompt, line, modelPickerTitle, candidates.map(modelChoice));
307
373
  models = selected.map((index) => candidates[index].id);
@@ -316,13 +382,13 @@ async function login(command, env, root, line, prompt, probe, prices) {
316
382
  if (!models.length ||
317
383
  models.some((model) => !model ||
318
384
  `${id}/${model}`.length > 200 ||
319
- (protocol === 'gemini' && !geminiModelPath(model)) ||
385
+ ((knownModel.get(model)?.protocol ?? protocol) === 'gemini' && !geminiModelPath(model)) ||
320
386
  /[\u0000-\u001f\u007f-\u009f]/.test(model) ||
321
387
  model.includes(apiKey)))
322
388
  throw new AuthError('请指定有效的模型名称。', 'USAGE');
323
389
  const selectable = models.filter((model) => supportsTextModel(knownModel.get(model) ?? { id: model }));
324
390
  const choicesFor = (items) => items.map((model) => modelChoice(knownModel.get(model) ?? { id: model }));
325
- const defaultSelection = (flags.models !== undefined ? flags.default : requestedDefault) ??
391
+ const defaultSelection = (flags.models !== undefined ? defaultFlag : requestedDefault) ??
326
392
  chosen ??
327
393
  (prompt && selectable.length > 1
328
394
  ? selectable[await chooseFromPages(prompt, line, modelPickerTitle, choicesFor(selectable))]
@@ -336,7 +402,7 @@ async function login(command, env, root, line, prompt, probe, prices) {
336
402
  : defaultSelection;
337
403
  if (defaultModel !== undefined && !models.includes(defaultModel))
338
404
  throw new AuthError('默认模型必须来自已选择的模型。', 'USAGE');
339
- if (prompt && (defaultModel === undefined || !selectable.includes(defaultModel)))
405
+ if ((prompt || wizard) && (defaultModel === undefined || !selectable.includes(defaultModel)))
340
406
  throw new AuthError('请选择可用于对话的默认模型。', 'USAGE');
341
407
  await saveProviderLogin({
342
408
  providerId: id,
@@ -348,7 +414,7 @@ async function login(command, env, root, line, prompt, probe, prices) {
348
414
  discovered,
349
415
  ...(defaultModel === undefined ? {} : { defaultModel }),
350
416
  }, env);
351
- return { provider: id, models, tested: false };
417
+ return { provider: id, models, tested: false, defaultModel };
352
418
  }
353
419
  const modelPickerTitle = 'Model · 上下文 / USD/1M(入/出,≈估算)';
354
420
  function modelChoice(model) {
@@ -359,12 +425,23 @@ function modelChoice(model) {
359
425
  ? `${model.id} · ${displayName}`
360
426
  : model.id;
361
427
  const context = model.contextWindow === undefined ? '—' : formatTokenCompact(model.contextWindow);
362
- const cost = model.pricing
363
- ? `${model.priceSource === 'models.dev' ? '' : '≈'}$${model.pricing.inputPerMillion}/$${model.pricing.outputPerMillion}`
364
- : '—';
365
428
  return {
366
429
  label,
367
- detail: `${context} ${cost}`,
430
+ detail: `${context} ${modelCost(model) ?? '—'}`,
368
431
  ...(model.displayName ? { search: model.displayName } : {}),
369
432
  };
370
433
  }
434
+ function modelCost(model) {
435
+ const exactPrice = model.priceSource === 'models.dev' || model.priceSource === 'opencode';
436
+ if (model.pricing)
437
+ return `${exactPrice ? '' : '≈'}$${model.pricing.inputPerMillion}/$${model.pricing.outputPerMillion}`;
438
+ }
439
+ function wizardModelChoice(model, protocol) {
440
+ const metadata = [
441
+ model.protocol ?? protocol,
442
+ model.contextWindow && formatTokenCompact(model.contextWindow).toUpperCase(),
443
+ (model.reasoningModel ?? !!model.reasoningEfforts?.length) && 'reasoning',
444
+ modelCost(model),
445
+ ];
446
+ return { value: model.id, label: modelChoice(model).label, hint: metadata.filter(Boolean).join(' · ') };
447
+ }
@@ -197,7 +197,7 @@ export declare function renderTeamBoard(team: TeamQueryResult): string;
197
197
  export declare function renderHostStatus(status: HostStatusSnapshot): string;
198
198
  export declare function renderRunDetails(details: Partial<RunQueryResult>): string;
199
199
  export declare function renderConfigSummary(inspection: UserConfigInspection, status?: HostStatusSnapshot): string;
200
- export declare function renderConfigCheck(inspection: UserConfigInspection, status?: HostStatusSnapshot): string;
200
+ export declare function renderConfigCheck(inspection: UserConfigInspection, status?: HostStatusSnapshot, availableModes?: readonly import("@saturn-universe/protocol").ModeSummary[] | undefined): string;
201
201
  export declare function renderConfigInit(result: InitUserConfigResult): string;
202
202
  export declare function renderUsageCard(usage: SessionUsageView): string;
203
203
  export declare function renderReplHelp(): string;
package/dist/renderer.js CHANGED
@@ -4,6 +4,7 @@ import { reconciliationUsage } from './reconcile-command.js';
4
4
  import { createTerminalPainter, padEndDisplay, paintSgr, stringDisplayWidth, stripAnsi, terminalColorEnabled, } from './terminal-text.js';
5
5
  import { formatDuration } from './duration.js';
6
6
  import { estimateUsageCostUsd, formatCacheRate, formatTokenCompact, formatTokenExact, formatUsd, resolveModelPricing, } from './usage.js';
7
+ const SATURN_CLI_VERSION = '0.1.2-dev.10';
7
8
  const { bold, dim, cyan, brightCyan, green, yellow, red, magenta, whiteBold } = createTerminalPainter();
8
9
  function padLogoLines(lines) {
9
10
  const maxWidth = Math.max(0, ...lines.map(stringDisplayWidth));
@@ -197,7 +198,7 @@ export function renderBanner(info) {
197
198
  : `Sandbox: ${green(`${info.status.sandbox.backend}`)}${info.status.sandbox.image ? ` (${info.status.sandbox.image})` : ''}`
198
199
  : undefined;
199
200
  const metaLines = [
200
- `${brightCyan('>_')} ${whiteBold('Saturn')} ${dim('(v0.1.1)')}`,
201
+ `${brightCyan('>_')} ${whiteBold('Saturn')} ${dim(`(v${SATURN_CLI_VERSION})`)}`,
201
202
  dim('Ringed Agent Kernel · Orbiting Agent Teams'),
202
203
  `Workspace: ${info.workdir}`,
203
204
  `Config: ${info.status.configSource ?? 'none'} · Profile: ${profileLabel}`,
@@ -1001,12 +1002,14 @@ export function renderConfigSummary(inspection, status) {
1001
1002
  return [
1002
1003
  cyan('[Config] 当前设置'),
1003
1004
  ' 工作区:' + inspection.workdir,
1004
- active ? ' 使用的配置文件:' + active.path : ' 目前使用内置设置。',
1005
+ active ? ' 使用的配置文件:' + active.path : ' 未找到 config.toml。',
1005
1006
  status ? ' 工作台已连接。默认模型:' + (status.defaultProfile ?? '尚未选择') : ' 工作台未连接。',
1006
1007
  ].join('\n');
1007
1008
  }
1008
- export function renderConfigCheck(inspection, status) {
1009
+ export function renderConfigCheck(inspection, status, availableModes = status?.availableModes) {
1009
1010
  const lines = [renderConfigSummary(inspection, status)];
1011
+ if (availableModes?.length)
1012
+ lines.push(' 可用模式:' + availableModes.map(({ ref }) => ref).join('、'));
1010
1013
  if (!inspection.files.workspaceConfig.exists && !inspection.files.userConfig.exists) {
1011
1014
  lines.push(' 运行 saturn provider add 连接第一个 AI 服务。');
1012
1015
  }
@@ -5,8 +5,10 @@ export interface ReplHostState {
5
5
  host?: ManagedHost | undefined;
6
6
  activeMode?: ModeSummary | undefined;
7
7
  modeRef?: string | undefined;
8
+ sessionModeRef?: string | undefined;
8
9
  }
9
10
  export declare function applyReplMode(state: ReplHostState, activeMode: ModeSummary | undefined, modeRef?: string): void;
11
+ export declare function applyReplSessionMode(state: ReplHostState, modeRef: string | undefined): void;
10
12
  export declare function createReplHostConnection(state: ReplHostState, initialOptions: HostLaunchOptions): {
11
13
  launch: () => Promise<ManagedHost>;
12
14
  accept: (host: ManagedHost) => ManagedHost;
package/dist/repl-host.js CHANGED
@@ -4,12 +4,20 @@ export function applyReplMode(state, activeMode, modeRef) {
4
4
  state.activeMode = activeMode;
5
5
  state.modeRef = activeMode?.ref ?? modeRef;
6
6
  }
7
+ export function applyReplSessionMode(state, modeRef) {
8
+ state.sessionModeRef = modeRef;
9
+ const status = state.host?.status;
10
+ if (modeRef)
11
+ applyReplMode(state, status?.availableModes.find(({ ref }) => ref === modeRef), modeRef);
12
+ else
13
+ applyReplMode(state, status?.activeMode);
14
+ }
7
15
  export function createReplHostConnection(state, initialOptions) {
8
16
  let launchOptions = { ...initialOptions };
9
17
  let latestStatusRequest = 0;
10
18
  function accept(host) {
11
19
  state.host = host;
12
- applyReplMode(state, host.status.activeMode);
20
+ applyReplSessionMode(state, state.sessionModeRef);
13
21
  return host;
14
22
  }
15
23
  async function refreshStatus({ signal, merge = false } = {}) {
@@ -34,6 +34,7 @@ export function createReplRunObserver(workdir, runCursors) {
34
34
  result = await attach(workdir, {
35
35
  runId,
36
36
  ...(interactiveProgress ? { interactiveProgress } : {}),
37
+ initialPollMs: 16,
37
38
  values: { after: cursor, 'poll-ms': '100', 'timeout-ms': '0', reconnect: true },
38
39
  commandId: randomUUID(),
39
40
  }, (frame) => {
package/dist/repl.js CHANGED
@@ -4,7 +4,7 @@ import { isTerminalRunEventType, MAX_SESSION_HISTORY_PAGE_SIZE, mergeAgentContex
4
4
  import { formatDuration } from './duration.js';
5
5
  import { CliError, formatDiagnosticReference } from './cli-diagnostics.js';
6
6
  import { approvalCommand, sendHostCommand } from './host-command.js';
7
- import { createReplHostConnection } from './repl-host.js';
7
+ import { applyReplSessionMode, createReplHostConnection } from './repl-host.js';
8
8
  import { createReplRunObserver } from './repl-run-observer.js';
9
9
  import { renderApprovalPrompt, renderAssistantText, renderBanner, renderConversationEvent, renderProgressEvent, renderUnifiedToolBlock, } from './renderer.js';
10
10
  import { createSessionHistoryLoader, historyEntryKey, messageEntryKey } from './session-history.js';
@@ -14,18 +14,16 @@ function replSubmission(state, runOptions, target) {
14
14
  const config = {};
15
15
  if (target.streamText)
16
16
  config.streamText = target.streamText;
17
- if (target.modeRef)
18
- config.modeRef = target.modeRef;
19
17
  if (runOptions.team)
20
18
  config.team = { ...runOptions.team, members: [...runOptions.team.members] };
21
- const reasoningEffort = state.reasoningEffort ?? state.profileDefaultReasoningEffort;
19
+ const reasoningEffort = state.userMutatedDefaults?.has('effort') ? state.reasoningEffort : undefined;
22
20
  if (reasoningEffort !== undefined) {
23
21
  config.responses = {
24
22
  storage: 'local_stateless',
25
23
  ...(reasoningEffort && reasoningEffort !== 'off' ? { reasoning: { effort: reasoningEffort } } : {}),
26
24
  };
27
25
  }
28
- if (state.workerReasoningEffort !== undefined)
26
+ if (state.userMutatedDefaults?.has('workerEffort') && state.workerReasoningEffort !== undefined)
29
27
  config.workerReasoningEffort = state.workerReasoningEffort;
30
28
  if (state.disabledSkills?.length)
31
29
  config.disabledSkills = [...state.disabledSkills];
@@ -68,6 +66,8 @@ function formatCliError(error) {
68
66
  if (error.code === 'CREDENTIAL_UNAVAILABLE') {
69
67
  return `Error: ${error.code} (diagnosticId=${error.diagnosticId}). Configure credentials in ~/.saturn/credentials.toml or run \`/config check\`.`;
70
68
  }
69
+ if (error.code === 'SESSION_BUSY')
70
+ return '当前会话有正在执行的任务,请等待完成或先 /cancel 后再切换 Mode';
71
71
  if (error.code === 'MODE_MISMATCH') {
72
72
  return `Error: MODE_MISMATCH (diagnosticId=${error.diagnosticId}). 当前工作区 Host 运行在其他 Mode 下;请使用 \`/mode <target>\` 切换或重启 Host。`;
73
73
  }
@@ -189,7 +189,7 @@ export function showTeamEvent(event, member) {
189
189
  return !event.memberId || event.memberId === 'main' || event.memberId === 'planner';
190
190
  }
191
191
  function activeModeRef(state, status) {
192
- return status?.activeMode?.ref ?? state.activeMode?.ref ?? state.modeRef;
192
+ return state.sessionModeRef ?? status?.activeMode?.ref ?? state.activeMode?.ref ?? state.modeRef;
193
193
  }
194
194
  function hydrateDefaultsFromStatus(state, status) {
195
195
  const defaults = status?.runDefaults;
@@ -342,6 +342,7 @@ async function runPipedRepl(options, hostOptions) {
342
342
  sessionId: state.sessionId,
343
343
  });
344
344
  state.member = session.member;
345
+ applyReplSessionMode(state, session.modeRef);
345
346
  if (session.member)
346
347
  state.lastRunId = session.latestRun?.id;
347
348
  await printMemberHistory();
@@ -557,7 +558,6 @@ async function runPipedRepl(options, hostOptions) {
557
558
  const input = replSubmission(state, runOptions, {
558
559
  workspaceId,
559
560
  sessionId,
560
- modeRef: state.activeMode?.ref ?? state.modeRef,
561
561
  });
562
562
  const result = await sendHostCommand(state.workdir, {
563
563
  type: 'run.submit',
@@ -636,8 +636,14 @@ async function runTtyRepl(options, hostOptions) {
636
636
  let openingMember = false;
637
637
  let navigationSeq = 0;
638
638
  let navigationAbort;
639
+ let navigationPausesHistory = false;
639
640
  let lastHostConnectedAt = 0;
640
641
  const liveMemberSessions = new Map();
642
+ let liveParentSessionId;
643
+ let liveStatus;
644
+ let liveAgents;
645
+ // Keep only a small tail of the first history page for recently viewed sessions.
646
+ const recentPages = new Map();
641
647
  let interruptingRun;
642
648
  let latestRunPausedOrCheckpoint = false;
643
649
  const tui = createOrbitalTui({
@@ -670,7 +676,7 @@ async function runTtyRepl(options, hostOptions) {
670
676
  usage: retainedContextTelemetry,
671
677
  permissionMode: state.permissionMode,
672
678
  ...(activeModeRef(state, status) ? { modeRef: activeModeRef(state, status) } : { modeRef: undefined }),
673
- activeMode: status?.activeMode ?? state.activeMode,
679
+ activeMode: state.activeMode ?? status?.activeMode,
674
680
  sandbox: status?.sandbox,
675
681
  skillRefs: [...state.skillRefs],
676
682
  ...(state.disabledSkills?.length ? { disabledSkills: [...state.disabledSkills] } : {}),
@@ -782,6 +788,7 @@ async function runTtyRepl(options, hostOptions) {
782
788
  return;
783
789
  if (info.member)
784
790
  state.member = info.member;
791
+ applyReplSessionMode(state, info.modeRef);
785
792
  if (history)
786
793
  bindHistory(targetId);
787
794
  if ((info.runCount ?? 0) > 0 || info.latestRun?.id)
@@ -857,14 +864,57 @@ async function runTtyRepl(options, hostOptions) {
857
864
  return history.loader;
858
865
  history?.loader.close();
859
866
  const route = agentSessionId === undefined ? { sessionId } : { sessionId, agentSessionId };
867
+ const cached = recentPages.get(targetId);
868
+ const agent = member && liveAgents?.[member.id];
869
+ if (cached?.length)
870
+ tui.showHistoryPreview(cached);
871
+ else if (agent?.agentSessionId && agent.agentSessionId === agentSessionId) {
872
+ if (agent.reasoningSummary && (agent.phase === 'thinking' || agent.phase === 'streaming')) {
873
+ tui.showHistoryPreview([
874
+ { kind: 'thinking', text: agent.reasoningSummary, streaming: agent.phase === 'thinking' },
875
+ ]);
876
+ }
877
+ else if (agent.phase === 'tool' && agent.currentTool) {
878
+ tui.showHistoryPreview([{ kind: 'tool', text: agent.currentTool }]);
879
+ }
880
+ }
881
+ let firstPage = true;
860
882
  const loader = createSessionHistoryLoader(state.workdir, route, {
861
- onPage: (messages) => tui.prependHistory(messages.map((message) => ({
862
- ...formatHistoryEntry(message, member?.id),
863
- key: historyEntryKey(message),
864
- }))),
883
+ onPage: (messages) => {
884
+ const entries = messages.map((message) => {
885
+ const key = historyEntryKey(message);
886
+ const entry = formatHistoryEntry(message, member?.id);
887
+ // The TUI caches Markdown layouts by entry identity. Tools have additional mutable fields.
888
+ if (firstPage && message.role !== 'tool') {
889
+ const previous = cached?.find((item) => item.key === key);
890
+ if (previous && previous.kind === entry.kind && previous.text === entry.text)
891
+ return previous;
892
+ }
893
+ return { ...entry, key };
894
+ });
895
+ if (firstPage) {
896
+ firstPage = false;
897
+ recentPages.delete(targetId);
898
+ if (entries.length) {
899
+ if (recentPages.size >= 16)
900
+ recentPages.delete(recentPages.keys().next().value);
901
+ recentPages.set(targetId, entries
902
+ .slice(-8)
903
+ .map((entry) => entry.text.length + (entry.detail?.length ?? 0) + (entry.header?.length ?? 0) <= 6144
904
+ ? entry
905
+ : { kind: entry.kind, key: entry.key, text: entry.text.slice(0, 2048) }));
906
+ }
907
+ }
908
+ tui.prependHistory(entries);
909
+ },
865
910
  onMessage: (message, text) => tui.setEntry(formatHistoryEntry(message, member?.id, text), historyEntryKey(message)),
866
- onError: (error) => tui.appendEntry('error', `历史加载失败 · ${formatCliError(error)}`),
867
- });
911
+ onError: (error) => {
912
+ tui.showHistoryPreview([]);
913
+ tui.appendEntry('error', `历史加载失败 · ${formatCliError(error)}`);
914
+ },
915
+ }, navigationPausesHistory ? 8 : MAX_SESSION_HISTORY_PAGE_SIZE);
916
+ if (navigationPausesHistory)
917
+ loader.pause();
868
918
  history = { sessionId, agentSessionId, loader };
869
919
  return loader;
870
920
  }
@@ -878,8 +928,14 @@ async function runTtyRepl(options, hostOptions) {
878
928
  const info = sessionSummary?.id === targetId ? sessionSummary : await refreshSummary(true);
879
929
  if (signal.aborted || exiting || state.sessionId !== targetId)
880
930
  return;
931
+ const hadFollowingRun = Boolean(followingRun);
881
932
  await bindHistory(targetId).load();
882
- if (signal.aborted || exiting || followingRun || openingMember)
933
+ if (signal.aborted || exiting)
934
+ return;
935
+ // Live membership identifies the route; only the Host summary carries a storage cursor.
936
+ if (hadFollowingRun && info?.member && !info.cursor)
937
+ void refreshSummary();
938
+ if (hadFollowingRun || followingRun || openingMember)
883
939
  return;
884
940
  const followStatuses = state.member
885
941
  ? ['created', 'running', 'paused', 'cancelling']
@@ -997,10 +1053,15 @@ async function runTtyRepl(options, hostOptions) {
997
1053
  throw error;
998
1054
  }
999
1055
  }
1000
- async function followRun(runId, initialAfter = '0', initialInputKey) {
1056
+ async function followRun(runId, initialAfter = '0', initialInputKey, submittedSessionId) {
1001
1057
  if (followingRun)
1002
1058
  throw new Error('当前正在跟随一个任务');
1003
1059
  followingRun = runId;
1060
+ liveParentSessionId =
1061
+ submittedSessionId ??
1062
+ (sessionSummary?.latestRun?.id === runId
1063
+ ? (state.member?.parentSessionId ?? state.sessionId)
1064
+ : undefined);
1004
1065
  let pendingInputKey = initialInputKey;
1005
1066
  let terminalAt;
1006
1067
  const satellites = [{ id: 'main', role: 'main', status: 'running' }];
@@ -1401,6 +1462,8 @@ async function runTtyRepl(options, hostOptions) {
1401
1462
  });
1402
1463
  telemetryDirty = true;
1403
1464
  }
1465
+ liveStatus = page.status;
1466
+ liveAgents = page.liveAgents;
1404
1467
  for (const [memberId, agent] of Object.entries(page.liveAgents ?? {})) {
1405
1468
  if (memberId === 'planner')
1406
1469
  continue;
@@ -1553,6 +1616,9 @@ async function runTtyRepl(options, hostOptions) {
1553
1616
  interruptingRun = undefined;
1554
1617
  followingRun = undefined;
1555
1618
  liveMemberSessions.clear();
1619
+ liveParentSessionId = undefined;
1620
+ liveStatus = undefined;
1621
+ liveAgents = undefined;
1556
1622
  runningModel = undefined;
1557
1623
  if (!exiting) {
1558
1624
  const startedAt = runStarts.get(runId);
@@ -1612,7 +1678,6 @@ async function runTtyRepl(options, hostOptions) {
1612
1678
  const input = replSubmission(state, runOptions, {
1613
1679
  workspaceId,
1614
1680
  sessionId,
1615
- modeRef: activeModeRef(state, state.host?.status),
1616
1681
  streamText: true,
1617
1682
  });
1618
1683
  tui.updateTelemetry({
@@ -1639,7 +1704,7 @@ async function runTtyRepl(options, hostOptions) {
1639
1704
  const inputKey = `input:${result.runId}`;
1640
1705
  tui.setEntry({ kind: 'user', text: runOptions.text }, inputKey);
1641
1706
  tui.setEntry({ kind: 'system', text: '', detail: `Run ${result.runId} submitted.` });
1642
- await followRun(result.runId, '0', inputKey);
1707
+ await followRun(result.runId, '0', inputKey, sessionId);
1643
1708
  }
1644
1709
  const hooks = {
1645
1710
  promptMcpSecret: (label) => tui.promptSecret(label),
@@ -1681,7 +1746,25 @@ async function runTtyRepl(options, hostOptions) {
1681
1746
  if (followingRun && info.latestRun?.id !== followingRun)
1682
1747
  throw new Error('请先按 Ctrl+C 分离当前任务,再切换到其他任务的会话');
1683
1748
  },
1749
+ getLiveMemberSession(sessionId) {
1750
+ if (!followingRun || !liveParentSessionId || liveStatus !== 'running')
1751
+ return;
1752
+ for (const [id, agentSessionId] of liveMemberSessions) {
1753
+ if (id !== 'main' && agentSessionId === sessionId)
1754
+ return {
1755
+ id: sessionId,
1756
+ member: { id, agentSessionId, parentSessionId: liveParentSessionId },
1757
+ latestRun: { id: followingRun, status: liveStatus },
1758
+ ...(state.sessionModeRef ? { modeRef: state.sessionModeRef } : {}),
1759
+ };
1760
+ }
1761
+ },
1684
1762
  onSessionChanged(info) {
1763
+ if (followingRun && info.latestRun?.id === followingRun) {
1764
+ liveParentSessionId = info.member?.parentSessionId ?? info.id;
1765
+ if (info.member)
1766
+ liveMemberSessions.set(info.member.id, info.member.agentSessionId);
1767
+ }
1685
1768
  latestRunPausedOrCheckpoint = info.latestRun?.status === 'paused';
1686
1769
  if (restoredSessionId !== info.id) {
1687
1770
  viewGeneration += 1;
@@ -1706,7 +1789,15 @@ async function runTtyRepl(options, hostOptions) {
1706
1789
  navigationAbort?.abort();
1707
1790
  const navAbort = new AbortController();
1708
1791
  navigationAbort = navAbort;
1709
- tui.updateTelemetry({ statusHint: label ? `正在切换到 ${label}...` : '正在切换会话...' });
1792
+ navigationPausesHistory = Boolean(label) || /^\/session\s+\S|^\/team\s+.*--member(?:\s|=)/i.test(command);
1793
+ if (navigationPausesHistory)
1794
+ history?.loader.pause();
1795
+ else
1796
+ history?.loader.resume();
1797
+ tui.updateTelemetry({
1798
+ pendingSatellite: label,
1799
+ statusHint: label ? `正在切换到 ${label}...` : '正在切换会话...',
1800
+ });
1710
1801
  void handleSlashCommand(command, state, hooks)
1711
1802
  .catch((error) => {
1712
1803
  if (!exiting &&
@@ -1717,10 +1808,14 @@ async function runTtyRepl(options, hostOptions) {
1717
1808
  }
1718
1809
  })
1719
1810
  .finally(() => {
1720
- if (navigationAbort === navAbort)
1721
- navigationAbort = undefined;
1722
- if (!exiting && seq === navigationSeq)
1723
- tui.updateTelemetry({ statusHint: undefined });
1811
+ if (navigationAbort !== navAbort)
1812
+ return;
1813
+ navigationAbort = undefined;
1814
+ navigationPausesHistory = false;
1815
+ if (!exiting) {
1816
+ history?.loader.resume();
1817
+ tui.updateTelemetry({ pendingSatellite: undefined, statusHint: undefined });
1818
+ }
1724
1819
  });
1725
1820
  }
1726
1821
  tui.onSelectSatellite?.((memberId) => {