@saturn-universe/cli 0.0.0-stage → 0.1.0

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 (85) hide show
  1. package/LICENSE +661 -0
  2. package/dist/attach.d.ts +9 -0
  3. package/dist/attach.js +80 -0
  4. package/dist/auth-config.d.ts +31 -0
  5. package/dist/auth-config.js +285 -0
  6. package/dist/choice-menu.d.ts +13 -0
  7. package/dist/choice-menu.js +238 -0
  8. package/dist/cli-diagnostics.d.ts +23 -0
  9. package/dist/cli-diagnostics.js +42 -0
  10. package/dist/cli-help.d.ts +6 -0
  11. package/dist/cli-help.js +163 -0
  12. package/dist/client.d.ts +13 -0
  13. package/dist/client.js +90 -0
  14. package/dist/commands.d.ts +64 -0
  15. package/dist/commands.js +299 -0
  16. package/dist/compaction-command.d.ts +16 -0
  17. package/dist/compaction-command.js +16 -0
  18. package/dist/composer.d.ts +88 -0
  19. package/dist/composer.js +124 -0
  20. package/dist/config-cli.d.ts +1 -0
  21. package/dist/config-cli.js +47 -0
  22. package/dist/config-file.d.ts +1 -0
  23. package/dist/config-file.js +43 -0
  24. package/dist/config-lock.d.ts +5 -0
  25. package/dist/config-lock.js +45 -0
  26. package/dist/duration.d.ts +2 -0
  27. package/dist/duration.js +11 -0
  28. package/dist/export.d.ts +19 -0
  29. package/dist/export.js +66 -0
  30. package/dist/host-command.d.ts +40 -0
  31. package/dist/host-command.js +48 -0
  32. package/dist/host-launcher.d.ts +22 -0
  33. package/dist/host-launcher.js +300 -0
  34. package/dist/index.d.ts +2 -0
  35. package/dist/index.js +400 -0
  36. package/dist/markdown.d.ts +1 -0
  37. package/dist/markdown.js +118 -0
  38. package/dist/mcp-cli.d.ts +44 -0
  39. package/dist/mcp-cli.js +647 -0
  40. package/dist/menu.d.ts +7 -0
  41. package/dist/menu.js +91 -0
  42. package/dist/project-mcp-config.d.ts +9 -0
  43. package/dist/project-mcp-config.js +98 -0
  44. package/dist/provider-discovery.d.ts +26 -0
  45. package/dist/provider-discovery.js +138 -0
  46. package/dist/provider-pricing.d.ts +3 -0
  47. package/dist/provider-pricing.js +130 -0
  48. package/dist/provider.d.ts +16 -0
  49. package/dist/provider.js +370 -0
  50. package/dist/reconcile-command.d.ts +36 -0
  51. package/dist/reconcile-command.js +64 -0
  52. package/dist/renderer.d.ts +204 -0
  53. package/dist/renderer.js +1134 -0
  54. package/dist/repl-host.d.ts +22 -0
  55. package/dist/repl-host.js +51 -0
  56. package/dist/repl-run-observer.d.ts +27 -0
  57. package/dist/repl-run-observer.js +86 -0
  58. package/dist/repl.d.ts +12 -0
  59. package/dist/repl.js +1834 -0
  60. package/dist/results.d.ts +23 -0
  61. package/dist/results.js +1 -0
  62. package/dist/sandbox-cli.d.ts +39 -0
  63. package/dist/sandbox-cli.js +324 -0
  64. package/dist/session-history.d.ts +17 -0
  65. package/dist/session-history.js +76 -0
  66. package/dist/settings-menu.d.ts +2 -0
  67. package/dist/settings-menu.js +111 -0
  68. package/dist/skill-cli.d.ts +25 -0
  69. package/dist/skill-cli.js +355 -0
  70. package/dist/slash-commands.d.ts +66 -0
  71. package/dist/slash-commands.js +1449 -0
  72. package/dist/terminal-input.d.ts +24 -0
  73. package/dist/terminal-input.js +111 -0
  74. package/dist/terminal-selection.d.ts +21 -0
  75. package/dist/terminal-selection.js +72 -0
  76. package/dist/terminal-text.d.ts +38 -0
  77. package/dist/terminal-text.js +238 -0
  78. package/dist/tui.d.ts +170 -0
  79. package/dist/tui.js +2559 -0
  80. package/dist/usage.d.ts +13 -0
  81. package/dist/usage.js +46 -0
  82. package/dist/user-config.d.ts +48 -0
  83. package/dist/user-config.js +188 -0
  84. package/package.json +18 -3
  85. package/README.md +0 -3
@@ -0,0 +1,370 @@
1
+ import { askChoice, terminalPrompt } from './menu.js';
2
+ import { text as readText } from 'node:stream/consumers';
3
+ import { enrichPrices, modelAlias } from './provider-pricing.js';
4
+ import { chooseFromPages, chooseManyFromPages } from './choice-menu.js';
5
+ import { formatTokenCompact } from './usage.js';
6
+ import { parseArgs } from 'node:util';
7
+ import { geminiModelPath, normalizeProviderBaseUrl, normalizeProviderProtocol, providerIdSchema, credentialRefSchema, resolveCredentialMap, providerPresets, } from '@saturn-universe/protocol';
8
+ import { chooseDefault, configuredEndpoint, listProviderLogins, removeProviderLogin, saveProviderLogin, } from './auth-config.js';
9
+ import { AuthError } from './cli-diagnostics.js';
10
+ import { topicHelp } from './cli-help.js';
11
+ import { inferProviderProtocol, probeProviderEndpoint, supportsTextModel, } from './provider-discovery.js';
12
+ function providerId(value) {
13
+ const parsed = providerIdSchema.safeParse(value);
14
+ if (!parsed.success)
15
+ throw new AuthError('请选择有效的服务商编号,或提供由字母、数字、连字符组成的名称。', 'USAGE');
16
+ return parsed.data;
17
+ }
18
+ function parseProviderArgs(args) {
19
+ const [action = 'list', ...rest] = args;
20
+ try {
21
+ if (['help', '--help', '-h'].includes(action) && !rest.length)
22
+ return { action: 'help' };
23
+ if (action === 'list' && !rest.length)
24
+ return { action };
25
+ if ((action === 'test' || action === 'use') && rest.length <= 1)
26
+ return { action, profile: rest[0] };
27
+ if (action === 'remove') {
28
+ const { positionals, values } = parseArgs({
29
+ args: rest,
30
+ allowPositionals: true,
31
+ options: { 'keep-config': { type: 'boolean' } },
32
+ });
33
+ if (positionals.length === 1)
34
+ return { action, id: positionals[0], keep: !!values['keep-config'] };
35
+ }
36
+ if (action === 'add') {
37
+ const { positionals, values } = parseArgs({
38
+ args: rest,
39
+ allowPositionals: true,
40
+ options: {
41
+ provider: { type: 'string' },
42
+ 'base-url': { type: 'string' },
43
+ 'credential-ref': { type: 'string' },
44
+ 'api-key-stdin': { type: 'boolean' },
45
+ 'api-key': { type: 'string' },
46
+ protocol: { type: 'string' },
47
+ models: { type: 'string' },
48
+ default: { type: 'string' },
49
+ 'no-probe': { type: 'boolean' },
50
+ },
51
+ });
52
+ if (positionals.length <= 1 &&
53
+ (!positionals[0] || !values.provider || positionals[0] === values.provider))
54
+ return { action, id: values.provider ?? positionals[0], values };
55
+ }
56
+ }
57
+ catch {
58
+ // parseArgs errors can quote arguments, including a mistyped credential flag.
59
+ }
60
+ throw new AuthError(['add', 'use', 'test', 'remove', 'list'].includes(action)
61
+ ? `参数无法识别。运行 saturn provider ${action} --help 查看用法。`
62
+ : '参数无法识别。运行 saturn provider --help 查看用法。', 'USAGE');
63
+ }
64
+ export async function runProviderCommand(args, options = {}) {
65
+ const json = args.includes('--json');
66
+ args = args.filter((arg) => arg !== '--json');
67
+ const env = options.env ?? process.env;
68
+ const root = options.root ?? process.cwd();
69
+ const print = options.writeLine ?? ((value) => process.stdout.write(value + '\n'));
70
+ const result = (value, message) => print(json ? JSON.stringify({ ok: true, result: value }) : message);
71
+ 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;
74
+ try {
75
+ const profiles = () => listProviderLogins(env, root);
76
+ const describe = (p) => [p.profile, p.selected ? '当前默认' : '', p.configured ? '已配置' : '缺少密钥']
77
+ .filter(Boolean)
78
+ .join(' · ');
79
+ if (!args.length && prompt) {
80
+ const items = await profiles();
81
+ print(items.map(describe).join('\n') || '还没有 AI 服务。');
82
+ const actions = ['add', 'test', 'use', 'edit', 'remove', 'back'];
83
+ const action = actions[await askChoice(prompt, print, '管理 AI 服务', [
84
+ '添加服务',
85
+ '测试模型',
86
+ '更换默认模型',
87
+ '修改服务',
88
+ '删除服务',
89
+ '返回',
90
+ ])];
91
+ if (action === 'back')
92
+ return;
93
+ args = [action === 'edit' ? 'add' : action];
94
+ if (action === 'edit' || action === 'remove') {
95
+ const ids = [...new Set(items.filter((p) => p.removable).map((p) => p.id))];
96
+ const selected = ids[await askChoice(prompt, print, '选择服务', ids)];
97
+ if (action === 'remove' &&
98
+ (await prompt.question('确认删除 ' + selected + '?输入 y 确认:')).toLowerCase() !== 'y')
99
+ return;
100
+ args.push(selected);
101
+ }
102
+ }
103
+ const command = parseProviderArgs(args);
104
+ switch (command.action) {
105
+ case 'help':
106
+ return result({ help: topicHelp('provider') }, topicHelp('provider'));
107
+ case 'list': {
108
+ const items = await profiles();
109
+ return result(items, items.map(describe).join('\n') || '还没有 AI 服务。运行 saturn provider add 开始设置。');
110
+ }
111
+ case 'use':
112
+ case 'test': {
113
+ let profile = command.profile;
114
+ if (!profile) {
115
+ if (!prompt)
116
+ throw new AuthError(`请指定模型。运行 saturn provider ${command.action} --help 查看用法。`, 'USAGE');
117
+ const items = (await profiles()).filter((p) => p.configured && supportsTextModel({ id: p.model }));
118
+ const index = await chooseFromPages(prompt, print, 'Model', items.map((item) => ({
119
+ label: item.profile,
120
+ ...(item.selected ? { detail: '当前默认' } : {}),
121
+ })));
122
+ profile = items[index].profile;
123
+ }
124
+ if (command.action === 'use') {
125
+ await chooseDefault(profile, root, env);
126
+ return result({ profile }, '已设置默认模型。');
127
+ }
128
+ const entry = await configuredEndpoint(profile, root, env);
129
+ await (options.testModel ?? testModel)(entry.baseUrl, entry.key, entry.model, entry.protocol);
130
+ return result({ profile, tested: true }, '模型连接测试通过。');
131
+ }
132
+ case 'remove':
133
+ await removeProviderLogin(providerId(command.id), command.keep, env);
134
+ return result({ provider: command.id }, command.keep ? '已移除密钥。' : '已删除服务。');
135
+ case 'add': {
136
+ const added = await login(command, env, root, progress, prompt, options.probe ?? probeProviderEndpoint, options.prices ?? enrichPrices);
137
+ return result(added, '已保存 AI 服务。');
138
+ }
139
+ }
140
+ }
141
+ finally {
142
+ prompt?.close();
143
+ }
144
+ }
145
+ function modelTestRequest(protocol, key, model) {
146
+ const prompt = 'Reply OK.';
147
+ const messages = [{ role: 'user', content: prompt }];
148
+ const bearer = { Authorization: 'Bearer ' + key };
149
+ switch (protocol) {
150
+ case 'openai-responses':
151
+ return {
152
+ path: '/responses',
153
+ headers: bearer,
154
+ body: { model, input: prompt, max_output_tokens: 32, store: false },
155
+ };
156
+ case 'openai-chat':
157
+ return { path: '/chat/completions', headers: bearer, body: { model, messages, max_tokens: 32 } };
158
+ case 'anthropic':
159
+ return {
160
+ path: '/messages',
161
+ headers: { 'x-api-key': key, 'anthropic-version': '2023-06-01' },
162
+ body: { model, messages, max_tokens: 32 },
163
+ };
164
+ case 'gemini': {
165
+ const path = geminiModelPath(model);
166
+ if (!path)
167
+ throw new AuthError('请提供有效的 Gemini 模型名称。', 'USAGE');
168
+ return {
169
+ path: '/' + path + ':generateContent',
170
+ headers: { 'x-goog-api-key': key },
171
+ body: {
172
+ contents: [{ role: 'user', parts: [{ text: prompt }] }],
173
+ generationConfig: { maxOutputTokens: 64 },
174
+ },
175
+ };
176
+ }
177
+ }
178
+ }
179
+ function hasReply(protocol, value) {
180
+ if (!value || typeof value !== 'object')
181
+ return false;
182
+ const body = value;
183
+ const text = (part) => typeof part === 'string' && Boolean(part.trim());
184
+ switch (protocol) {
185
+ case 'openai-responses':
186
+ return ((body.status === 'completed' || body.status === 'incomplete') &&
187
+ Array.isArray(body.output) &&
188
+ body.output.some((item) => item?.type === 'message' &&
189
+ Array.isArray(item.content) &&
190
+ item.content.some((part) => part?.type === 'output_text' && text(part.text))));
191
+ case 'openai-chat':
192
+ return Array.isArray(body.choices) && body.choices.some((choice) => text(choice?.message?.content));
193
+ case 'anthropic':
194
+ return (Array.isArray(body.content) && body.content.some((part) => part?.type === 'text' && text(part.text)));
195
+ case 'gemini':
196
+ return (Array.isArray(body.candidates) &&
197
+ body.candidates.some((candidate) => Array.isArray(candidate?.content?.parts) &&
198
+ candidate.content.parts.some((part) => part?.thought !== true && text(part?.text))));
199
+ }
200
+ }
201
+ export async function testModel(baseUrl, key, model, protocol = 'openai-responses') {
202
+ const endpoint = normalizeProviderBaseUrl(baseUrl);
203
+ if (!endpoint)
204
+ throw new AuthError('EndPoint 需要完整的 HTTP 或 HTTPS URL。', 'USAGE');
205
+ const { path, headers, body } = modelTestRequest(protocol, key, model);
206
+ let response;
207
+ try {
208
+ response = await fetch(endpoint + path, {
209
+ method: 'POST',
210
+ redirect: 'error',
211
+ signal: AbortSignal.timeout(15000),
212
+ headers: { 'Content-Type': 'application/json', ...headers },
213
+ body: JSON.stringify(body),
214
+ });
215
+ }
216
+ catch {
217
+ throw new AuthError('服务连接超时或地址不可达,请检查地址后重试。');
218
+ }
219
+ if (!response.ok) {
220
+ await response.body?.cancel();
221
+ if ([401, 403].includes(response.status))
222
+ throw new AuthError('密钥无效或没有使用此模型的权限。');
223
+ if (response.status === 429)
224
+ throw new AuthError('服务限流或额度不足,请稍后重试。');
225
+ throw new AuthError('模型测试失败,请检查所选模型与服务地址。');
226
+ }
227
+ if (!hasReply(protocol, await response.json().catch(() => null)))
228
+ throw new AuthError('模型没有返回有效的对话响应,请更换模型或检查服务地址。');
229
+ }
230
+ function parseProtocol(value) {
231
+ const protocol = normalizeProviderProtocol(value);
232
+ if (!protocol)
233
+ throw new AuthError('Choose one of the supported provider protocols.', 'USAGE');
234
+ return protocol;
235
+ }
236
+ function selection(value) {
237
+ return [...new Set(value.split(',').map((part) => part.trim()))];
238
+ }
239
+ async function login(command, env, root, line, prompt, probe, prices) {
240
+ const flags = command.values;
241
+ let requestedId = command.id;
242
+ if (requestedId === undefined && prompt) {
243
+ requestedId =
244
+ providerPresets[await askChoice(prompt, line, 'Provider', providerPresets.map((preset) => preset.label))].id;
245
+ }
246
+ if (prompt && requestedId === 'custom') {
247
+ const used = new Set((await listProviderLogins(env, root)).map((p) => p.id));
248
+ let n = 1;
249
+ while (used.has('custom-' + n))
250
+ n++;
251
+ requestedId = 'custom-' + n;
252
+ }
253
+ const id = providerId(requestedId);
254
+ const preset = providerPresets.find((item) => item.id === id);
255
+ const defaultUrl = preset?.defaultBaseUrl;
256
+ const rawUrl = flags['base-url'] ?? defaultUrl ?? (prompt ? await prompt.question('EndPoint: ') : undefined);
257
+ const baseUrl = rawUrl && normalizeProviderBaseUrl(rawUrl);
258
+ if (!baseUrl)
259
+ throw new AuthError('EndPoint 需要完整的 HTTP 或 HTTPS URL。', 'USAGE');
260
+ if (flags['api-key-stdin'] && (flags['api-key'] !== undefined || process.stdin.isTTY))
261
+ throw new AuthError('请通过管道提供密钥。', 'USAGE');
262
+ const reference = flags['credential-ref'];
263
+ if (reference &&
264
+ (!credentialRefSchema.safeParse(reference).success ||
265
+ flags['api-key-stdin'] ||
266
+ flags['api-key'] !== undefined))
267
+ throw new AuthError('请使用一个 env:变量名 引用密钥。', 'USAGE');
268
+ const configuredKey = reference
269
+ ? (await resolveCredentialMap(root, env)).values.get(reference.slice(4))
270
+ : undefined;
271
+ if (reference && !configuredKey)
272
+ throw new AuthError('指定的环境变量没有密钥。');
273
+ const apiKey = configuredKey ??
274
+ (flags['api-key-stdin'] ? (await readText(process.stdin)).trimEnd() : flags['api-key']) ??
275
+ (prompt ? await prompt.question('API Key: ', true) : undefined);
276
+ if (!apiKey?.trim() || apiKey !== apiKey.trim() || /[\u0000-\u001f\u007f]/.test(apiKey))
277
+ throw new AuthError('请输入一行有效的 API Key。', 'USAGE');
278
+ if (id.includes(apiKey) || baseUrl.includes(apiKey) || decodeURI(baseUrl).includes(apiKey))
279
+ throw new AuthError('请只在密钥输入框中填写 API Key。', 'USAGE');
280
+ const explicitProtocol = flags.protocol === undefined ? undefined : parseProtocol(flags.protocol);
281
+ const preferredProtocol = explicitProtocol ??
282
+ (baseUrl === defaultUrl ? preset?.defaultProtocol : undefined) ??
283
+ inferProviderProtocol(baseUrl);
284
+ let protocol = preferredProtocol;
285
+ 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('无法完全确认服务能力,请确认服务地址和模型权限。');
293
+ }
294
+ const candidates = discovered.filter(supportsTextModel);
295
+ 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;
299
+ let models;
300
+ let chosen;
301
+ if (flags.models !== undefined)
302
+ models = selection(flags.models);
303
+ else if (requestedDefault !== undefined)
304
+ models = [requestedDefault];
305
+ else if (prompt && candidates.length) {
306
+ const selected = await chooseManyFromPages(prompt, line, modelPickerTitle, candidates.map(modelChoice));
307
+ models = selected.map((index) => candidates[index].id);
308
+ chosen = models[0];
309
+ }
310
+ else if (prompt) {
311
+ line(discovered.length ? '模型列表中没有可选的对话模型。' : '未能获取模型列表。');
312
+ models = selection(await prompt.question('Model ID: '));
313
+ }
314
+ else
315
+ models = candidates.length === 1 ? [candidates[0].id] : [];
316
+ if (!models.length ||
317
+ models.some((model) => !model ||
318
+ `${id}/${model}`.length > 200 ||
319
+ (protocol === 'gemini' && !geminiModelPath(model)) ||
320
+ /[\u0000-\u001f\u007f-\u009f]/.test(model) ||
321
+ model.includes(apiKey)))
322
+ throw new AuthError('请指定有效的模型名称。', 'USAGE');
323
+ const selectable = models.filter((model) => supportsTextModel(knownModel.get(model) ?? { id: model }));
324
+ const choicesFor = (items) => items.map((model) => modelChoice(knownModel.get(model) ?? { id: model }));
325
+ const defaultSelection = (flags.models !== undefined ? flags.default : requestedDefault) ??
326
+ chosen ??
327
+ (prompt && selectable.length > 1
328
+ ? selectable[await chooseFromPages(prompt, line, modelPickerTitle, choicesFor(selectable))]
329
+ : prompt
330
+ ? selectable[0]
331
+ : undefined);
332
+ const defaultModel = defaultSelection === undefined || models.includes(defaultSelection)
333
+ ? defaultSelection
334
+ : defaultSelection.startsWith(`${id}/`)
335
+ ? defaultSelection.slice(id.length + 1)
336
+ : defaultSelection;
337
+ if (defaultModel !== undefined && !models.includes(defaultModel))
338
+ throw new AuthError('默认模型必须来自已选择的模型。', 'USAGE');
339
+ if (prompt && (defaultModel === undefined || !selectable.includes(defaultModel)))
340
+ throw new AuthError('请选择可用于对话的默认模型。', 'USAGE');
341
+ await saveProviderLogin({
342
+ providerId: id,
343
+ baseUrl,
344
+ protocol,
345
+ apiKey,
346
+ ...(reference ? { credentialRef: reference } : {}),
347
+ models,
348
+ discovered,
349
+ ...(defaultModel === undefined ? {} : { defaultModel }),
350
+ }, env);
351
+ return { provider: id, models, tested: false };
352
+ }
353
+ const modelPickerTitle = 'Model · 上下文 / USD/1M(入/出,≈估算)';
354
+ function modelChoice(model) {
355
+ const shortId = model.id.split('/').at(-1) ?? model.id;
356
+ const { displayName } = model;
357
+ const displayAlias = displayName && modelAlias(displayName);
358
+ const label = displayAlias && displayAlias !== modelAlias(model.id) && displayAlias !== modelAlias(shortId)
359
+ ? `${model.id} · ${displayName}`
360
+ : model.id;
361
+ 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
+ return {
366
+ label,
367
+ detail: `${context} ${cost}`,
368
+ ...(model.displayName ? { search: model.displayName } : {}),
369
+ };
370
+ }
@@ -0,0 +1,36 @@
1
+ import type { HostCommandInput } from '@saturn-universe/protocol';
2
+ export declare const reconciliationOptions: {
3
+ readonly 'tool-call': {
4
+ readonly type: "string";
5
+ };
6
+ readonly 'not-applied': {
7
+ readonly type: "boolean";
8
+ };
9
+ readonly completed: {
10
+ readonly type: "boolean";
11
+ };
12
+ readonly 'abandon-unknown': {
13
+ readonly type: "boolean";
14
+ };
15
+ readonly evidence: {
16
+ readonly type: "string";
17
+ };
18
+ readonly 'result-json': {
19
+ readonly type: "string";
20
+ };
21
+ readonly reason: {
22
+ readonly type: "string";
23
+ };
24
+ readonly 'decided-by': {
25
+ readonly type: "string";
26
+ };
27
+ };
28
+ export declare function reconciliationUsage(invocation: string): string;
29
+ export type ReconciliationRequest = Extract<HostCommandInput, {
30
+ type: 'tool.reconcile';
31
+ }>;
32
+ type Values = Partial<Record<keyof typeof reconciliationOptions, string | boolean | undefined>>;
33
+ export declare function reconciliationCommand(values: Values): ReconciliationRequest | {
34
+ readonly error: string;
35
+ };
36
+ export {};
@@ -0,0 +1,64 @@
1
+ import { parseReconciliationToolResult } from '@saturn-universe/protocol';
2
+ import { CliError } from './cli-diagnostics.js';
3
+ export const reconciliationOptions = {
4
+ 'tool-call': { type: 'string' },
5
+ 'not-applied': { type: 'boolean' },
6
+ completed: { type: 'boolean' },
7
+ 'abandon-unknown': { type: 'boolean' },
8
+ evidence: { type: 'string' },
9
+ 'result-json': { type: 'string' },
10
+ reason: { type: 'string' },
11
+ 'decided-by': { type: 'string' },
12
+ };
13
+ export function reconciliationUsage(invocation) {
14
+ const prefix = ` ${invocation} --tool-call ID`;
15
+ return [
16
+ `${prefix} --not-applied --evidence REF`,
17
+ `${prefix} --completed --result-json JSON --evidence REF`,
18
+ `${prefix} --abandon-unknown --reason TEXT [--decided-by ID]`,
19
+ ].join('\n');
20
+ }
21
+ export function reconciliationCommand(values) {
22
+ const { 'tool-call': toolCallId, 'not-applied': notApplied, completed, 'abandon-unknown': abandonUnknown, evidence, 'result-json': resultJson, reason, 'decided-by': decidedBy, } = values;
23
+ if (typeof toolCallId !== 'string' ||
24
+ !toolCallId ||
25
+ [notApplied, completed, abandonUnknown].filter(Boolean).length !== 1) {
26
+ return {
27
+ error: 'Provide --tool-call and exactly one of --not-applied, --completed, or --abandon-unknown',
28
+ };
29
+ }
30
+ const target = { type: 'tool.reconcile', toolCallId };
31
+ if (abandonUnknown) {
32
+ if (typeof reason !== 'string' || !reason)
33
+ return { error: '--abandon-unknown requires --reason' };
34
+ if (evidence !== undefined || resultJson !== undefined)
35
+ return { error: '--abandon-unknown cannot be combined with --evidence or --result-json' };
36
+ const acceptedBy = decidedBy ?? 'cli';
37
+ if (typeof acceptedBy !== 'string' || !acceptedBy)
38
+ return { error: '--decided-by requires an actor ID' };
39
+ return { ...target, decision: { kind: 'abandon_unknown', acceptedBy, reason } };
40
+ }
41
+ const mode = completed ? '--completed' : '--not-applied';
42
+ if (typeof evidence !== 'string' || !evidence)
43
+ return { error: `${mode} requires --evidence` };
44
+ if (reason !== undefined || decidedBy !== undefined)
45
+ return { error: `${mode} cannot be combined with --reason or --decided-by` };
46
+ if (!completed) {
47
+ if (resultJson !== undefined)
48
+ return { error: '--not-applied cannot be combined with --result-json' };
49
+ return { ...target, decision: { kind: 'not_applied', evidenceRef: evidence } };
50
+ }
51
+ if (typeof resultJson !== 'string' || !resultJson)
52
+ return { error: '--completed requires --result-json' };
53
+ let value;
54
+ try {
55
+ value = JSON.parse(resultJson);
56
+ }
57
+ catch {
58
+ return { error: '--result-json requires valid JSON' };
59
+ }
60
+ const result = parseReconciliationToolResult(value);
61
+ if (!result)
62
+ throw new CliError('INVALID_COMMAND');
63
+ return { ...target, decision: { kind: 'completed', evidenceRef: evidence, result } };
64
+ }
@@ -0,0 +1,204 @@
1
+ import type { HostStatusSnapshot, RunProgressApproval, RunQueryResult, TeamQueryResult, TodoItem } from '@saturn-universe/protocol';
2
+ import type { CliDiagnostic } from './cli-diagnostics.js';
3
+ import { type SessionUsageView } from './usage.js';
4
+ import type { InitUserConfigResult, UserConfigInspection } from './user-config.js';
5
+ export type ToolBlock = {
6
+ readonly kind: 'fact';
7
+ readonly id?: string;
8
+ readonly category?: string;
9
+ } | {
10
+ readonly kind: 'hypothesis';
11
+ readonly id?: string;
12
+ readonly status?: string;
13
+ } | {
14
+ readonly kind: 'skill';
15
+ readonly action: 'load';
16
+ readonly skill: string;
17
+ } | {
18
+ readonly kind: 'skill';
19
+ readonly action: 'read';
20
+ readonly skill: string;
21
+ readonly path: string;
22
+ } | {
23
+ readonly kind: 'skill';
24
+ readonly action: 'list';
25
+ readonly count: number;
26
+ } | {
27
+ readonly kind: 'web_search';
28
+ readonly query: string;
29
+ readonly count?: number;
30
+ } | {
31
+ readonly kind: 'web_fetch';
32
+ readonly url: string;
33
+ };
34
+ export interface RenderProgressEvent {
35
+ readonly id?: string;
36
+ readonly position: string;
37
+ readonly type: string;
38
+ readonly occurredAt?: string;
39
+ readonly memberId?: string;
40
+ readonly agentSessionId?: string;
41
+ readonly turnId?: string;
42
+ readonly stepId?: string;
43
+ readonly step?: {
44
+ readonly kind?: string;
45
+ };
46
+ readonly requestId?: string;
47
+ readonly messageId?: string;
48
+ readonly steering?: boolean;
49
+ readonly toolCallId?: string;
50
+ readonly toolName?: string;
51
+ readonly toolArguments?: string;
52
+ readonly toolOutput?: string;
53
+ readonly toolBlock?: ToolBlock;
54
+ readonly toolStatus?: 'success' | 'error' | 'denied' | 'cancelled';
55
+ readonly toolTarget?: string;
56
+ readonly effect?: string;
57
+ readonly exitCode?: number;
58
+ readonly exitSignal?: string;
59
+ readonly text?: string;
60
+ readonly reasoningSummary?: string;
61
+ readonly retryAt?: string;
62
+ readonly retryAfterMs?: number;
63
+ readonly reason?: string;
64
+ readonly decision?: 'single' | 'team';
65
+ readonly fallback?: boolean;
66
+ readonly summary?: string;
67
+ readonly evidence?: readonly string[];
68
+ readonly executionSteps?: readonly string[];
69
+ readonly verificationCriteria?: readonly string[];
70
+ readonly team?: {
71
+ readonly concurrency?: number;
72
+ readonly members?: readonly {
73
+ readonly id: string;
74
+ readonly parent: string;
75
+ readonly task: string;
76
+ }[];
77
+ };
78
+ readonly todos?: readonly TodoItem[];
79
+ readonly from?: string;
80
+ readonly to?: string;
81
+ readonly searchId?: string;
82
+ readonly trigger?: string;
83
+ readonly goal?: string;
84
+ readonly isolation?: 'readonly' | 'isolated';
85
+ readonly maxRollouts?: number;
86
+ readonly branchId?: string;
87
+ readonly parentBranchId?: string | null;
88
+ readonly depth?: number;
89
+ readonly mode?: 'wider' | 'deeper';
90
+ readonly hypothesis?: string;
91
+ readonly workspaceKind?: 'shared_readonly' | 'git_worktree' | 'shallow_copy';
92
+ readonly degradedToReadonly?: boolean;
93
+ readonly combinedScore?: number;
94
+ readonly verdict?: 'solved' | 'promising' | 'pruned';
95
+ readonly reflection?: string;
96
+ readonly winnerBranchId?: string | null;
97
+ readonly outcome?: 'solved' | 'best_candidate' | 'exhausted';
98
+ readonly winnerSummary?: string;
99
+ readonly mergedReflections?: readonly string[];
100
+ readonly mergedFiles?: readonly string[];
101
+ readonly approval?: {
102
+ readonly approvalId: string;
103
+ readonly toolCallId: string;
104
+ readonly resources?: readonly string[];
105
+ readonly reason?: string;
106
+ };
107
+ readonly approved?: boolean;
108
+ readonly error?: CliDiagnostic & {
109
+ readonly message?: string;
110
+ readonly phase?: string;
111
+ readonly elapsedMs?: number;
112
+ readonly timeoutKind?: string;
113
+ readonly underlyingCode?: string;
114
+ readonly causes?: readonly {
115
+ readonly code?: string;
116
+ readonly message: string;
117
+ }[];
118
+ };
119
+ readonly limit?: {
120
+ readonly resource: 'modelAttempts' | 'toolCalls' | 'steps' | 'tokens' | 'context' | 'timeMs' | 'modelOutput';
121
+ readonly used: number;
122
+ readonly max: number;
123
+ readonly required?: number;
124
+ readonly unknownUsageTokens?: number;
125
+ readonly triggeredByUnknownUsage?: boolean;
126
+ };
127
+ readonly checkpoint?: boolean;
128
+ readonly dataReviewRounds?: readonly {
129
+ readonly round: number;
130
+ readonly evidence: {
131
+ readonly rule: string;
132
+ readonly failures: number;
133
+ };
134
+ readonly selected: string | null;
135
+ readonly candidates: readonly {
136
+ readonly operation: string;
137
+ readonly checks: readonly {
138
+ readonly rule: string;
139
+ readonly failures: number;
140
+ }[];
141
+ }[];
142
+ readonly todos: readonly TodoItem[];
143
+ }[];
144
+ }
145
+ export type ToolActivity = 'list_dir' | 'read_file' | 'search_files' | 'glob' | 'grep' | 'command' | 'command_failed' | 'write_file' | 'edit_file' | 'todo' | 'team_plan' | 'team_report' | 'tool_other';
146
+ export interface ConversationEntry {
147
+ readonly text: string;
148
+ readonly detail?: string;
149
+ readonly activity?: ToolActivity;
150
+ readonly activityLabel?: string;
151
+ readonly header?: string;
152
+ readonly block?: 'ledger' | 'skill' | 'web';
153
+ readonly tone?: 'muted' | 'warn' | 'error';
154
+ readonly streaming?: boolean;
155
+ }
156
+ export type PendingApprovalView = Omit<RunProgressApproval, 'turnId' | 'expiresAt'>;
157
+ export interface BannerInfo {
158
+ readonly workdir: string;
159
+ readonly sessionId?: string | undefined;
160
+ readonly profile?: string | undefined;
161
+ readonly skillRefs: readonly string[];
162
+ readonly status: HostStatusSnapshot;
163
+ readonly ownedHost: boolean;
164
+ }
165
+ export declare function renderSaturnLogo(frame?: number, colored?: boolean): string[];
166
+ export declare function renderCompactSaturnLogo(colored?: boolean): readonly string[];
167
+ export declare function renderUserTurn(text: string): string;
168
+ export declare function renderBanner(info: BannerInfo): string;
169
+ export declare function renderTeamTree(members: readonly {
170
+ readonly id: string;
171
+ readonly parent: string | null;
172
+ readonly task?: string | undefined;
173
+ readonly status?: string | undefined;
174
+ }[]): string;
175
+ export declare function renderAssistantText(text: string): string;
176
+ export declare function renderModelFailure(event: RenderProgressEvent): string;
177
+ export declare function renderProgressEvent(event: RenderProgressEvent): string | undefined;
178
+ export declare const searchDegradedNotice = "\u975E Git \u5DE5\u4F5C\u533A\u8D85\u8FC7\u590D\u5236\u4E0A\u9650\uFF0C\u5DF2\u964D\u7EA7\u4E3A\u53EA\u8BFB\u5206\u652F";
179
+ export interface UnifiedToolBlockInput {
180
+ readonly toolName?: string | undefined;
181
+ readonly toolBlock?: ToolBlock | undefined;
182
+ readonly toolArguments?: string | undefined;
183
+ readonly toolData?: unknown;
184
+ readonly toolOutput?: string | undefined;
185
+ readonly toolStatus?: 'success' | 'error' | 'denied' | 'cancelled' | string | undefined;
186
+ readonly error?: RenderProgressEvent['error'] | {
187
+ readonly code: string;
188
+ readonly message?: string | undefined;
189
+ readonly diagnosticId?: string | undefined;
190
+ } | undefined;
191
+ readonly detail: string;
192
+ }
193
+ export declare function renderUnifiedToolBlock(input: UnifiedToolBlockInput): ConversationEntry | undefined;
194
+ export declare function renderConversationEvent(event: RenderProgressEvent): ConversationEntry | undefined;
195
+ export declare function renderApprovalPrompt(pending: PendingApprovalView): string;
196
+ export declare function renderTeamBoard(team: TeamQueryResult): string;
197
+ export declare function renderHostStatus(status: HostStatusSnapshot): string;
198
+ export declare function renderRunDetails(details: Partial<RunQueryResult>): string;
199
+ export declare function renderConfigSummary(inspection: UserConfigInspection, status?: HostStatusSnapshot): string;
200
+ export declare function renderConfigCheck(inspection: UserConfigInspection, status?: HostStatusSnapshot): string;
201
+ export declare function renderConfigInit(result: InitUserConfigResult): string;
202
+ export declare function renderUsageCard(usage: SessionUsageView): string;
203
+ export declare function renderReplHelp(): string;
204
+ export declare function renderShortcutHelp(): string;