@saturn-universe/cli 0.0.0-stage → 0.1.1

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,300 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { access, realpath } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { createRequire } from 'node:module';
6
+ import { setTimeout as delay } from 'node:timers/promises';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { matchesModeSelector, parseHostStatusResult } from '@saturn-universe/protocol';
9
+ import { request } from './client.js';
10
+ import { CliError, isHostConnectionError, safeCode } from './cli-diagnostics.js';
11
+ import { sendHostCommand } from './host-command.js';
12
+ export const DEFAULT_HOST_READY_TIMEOUT_MS = 60_000;
13
+ const HOST_SHUTDOWN_TIMEOUT_MS = 2500;
14
+ const HOST_STOP_OBSERVATION_MS = 3000;
15
+ const HOST_RESTART_OWNERSHIP_MS = 5000;
16
+ export function resolveHostReadyTimeoutMs(env = process.env) {
17
+ const raw = env.SATURN_HOST_READY_TIMEOUT_MS?.trim();
18
+ if (!raw)
19
+ return DEFAULT_HOST_READY_TIMEOUT_MS;
20
+ const parsed = Number(raw);
21
+ if (!Number.isFinite(parsed) || !Number.isInteger(parsed) || parsed < 1000) {
22
+ return DEFAULT_HOST_READY_TIMEOUT_MS;
23
+ }
24
+ return parsed;
25
+ }
26
+ export async function resolveHostEntry() {
27
+ const selfDir = path.dirname(await realpath(fileURLToPath(import.meta.url)));
28
+ const packageHost = (() => {
29
+ try {
30
+ return createRequire(import.meta.url).resolve('@saturn-universe/runtime-host/dist/index.js');
31
+ }
32
+ catch {
33
+ return undefined;
34
+ }
35
+ })();
36
+ const candidates = [
37
+ process.env.SATURN_HOST_ENTRY?.trim(),
38
+ packageHost,
39
+ path.resolve(selfDir, '../runtime-host/dist/index.js'),
40
+ path.resolve(selfDir, '../../runtime-host/dist/index.js'),
41
+ ].filter((candidate) => Boolean(candidate));
42
+ for (const candidate of candidates) {
43
+ try {
44
+ await access(candidate);
45
+ return candidate;
46
+ }
47
+ catch {
48
+ // Try the next layout candidate.
49
+ }
50
+ }
51
+ throw new CliError('HOST_UNAVAILABLE');
52
+ }
53
+ function parseHostStartupError(stderrText) {
54
+ for (const line of stderrText.split(/\r?\n/)) {
55
+ const trimmed = line.trim();
56
+ if (!trimmed.startsWith('{'))
57
+ continue;
58
+ try {
59
+ const parsed = JSON.parse(trimmed);
60
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
61
+ const record = parsed;
62
+ if (typeof record.error === 'string') {
63
+ const diagnosticId = typeof record.diagnosticId === 'string' ? record.diagnosticId : randomUUID();
64
+ return new CliError(safeCode(record.error), diagnosticId);
65
+ }
66
+ }
67
+ }
68
+ catch {
69
+ // Ignore non-JSON stderr lines.
70
+ }
71
+ }
72
+ return undefined;
73
+ }
74
+ export function shouldEnableEnvProxy(env) {
75
+ return (env.NODE_USE_ENV_PROXY === undefined &&
76
+ Boolean(env.HTTPS_PROXY?.trim() || env.https_proxy?.trim() || env.HTTP_PROXY?.trim() || env.http_proxy?.trim()));
77
+ }
78
+ export function buildHostSpawnEnv(baseEnv = process.env) {
79
+ if (shouldEnableEnvProxy(baseEnv)) {
80
+ return { ...baseEnv, NODE_USE_ENV_PROXY: '1' };
81
+ }
82
+ return baseEnv;
83
+ }
84
+ export async function ensureHost(root, options = {}) {
85
+ try {
86
+ const status = await sendHostCommand(root, { type: 'host.status' }, { timeoutMs: 8000 });
87
+ if (options.mode && !matchesModeSelector(options.mode, status.activeMode.ref, status.availableModes)) {
88
+ throw new CliError('MODE_MISMATCH');
89
+ }
90
+ return { owned: false, status };
91
+ }
92
+ catch (error) {
93
+ if (!(error instanceof CliError) || error.code !== 'HOST_UNAVAILABLE')
94
+ throw error;
95
+ }
96
+ const hostEntry = await resolveHostEntry();
97
+ const flags = [];
98
+ if (options.config)
99
+ flags.push('--config', options.config);
100
+ if (options.profile)
101
+ flags.push('--profile', options.profile);
102
+ if (options.taskProfile)
103
+ flags.push('--task-profile', options.taskProfile);
104
+ if (options.mode)
105
+ flags.push('--mode', options.mode);
106
+ if (options.allowUnsafeSandboxFallback)
107
+ flags.push('--allow-unsafe-sandbox-fallback');
108
+ const child = spawn(process.execPath, [hostEntry, root, ...flags], {
109
+ stdio: ['ignore', 'pipe', 'pipe'],
110
+ windowsHide: true,
111
+ detached: Boolean(options.detach),
112
+ env: buildHostSpawnEnv(process.env),
113
+ });
114
+ let stdoutBuffer = '';
115
+ let stderrBuffer = '';
116
+ const status = await new Promise((resolve, reject) => {
117
+ let settled = false;
118
+ const timer = setTimeout(() => {
119
+ if (settled)
120
+ return;
121
+ settled = true;
122
+ cleanup();
123
+ child.kill();
124
+ reject(new CliError('HOST_TIMEOUT'));
125
+ }, resolveHostReadyTimeoutMs());
126
+ const onStdout = (chunk) => {
127
+ stdoutBuffer += String(chunk);
128
+ let newlineIndex;
129
+ while ((newlineIndex = stdoutBuffer.indexOf('\n')) >= 0) {
130
+ const line = stdoutBuffer.slice(0, newlineIndex).trim();
131
+ stdoutBuffer = stdoutBuffer.slice(newlineIndex + 1);
132
+ if (!line)
133
+ continue;
134
+ try {
135
+ const parsed = JSON.parse(line);
136
+ if (parsed &&
137
+ typeof parsed === 'object' &&
138
+ !Array.isArray(parsed) &&
139
+ parsed.ready === true) {
140
+ if (!settled) {
141
+ settled = true;
142
+ cleanup();
143
+ resolve(parseHostStatusResult(parsed.status));
144
+ }
145
+ return;
146
+ }
147
+ }
148
+ catch {
149
+ // Ignore non-JSON stdout lines before readiness.
150
+ }
151
+ }
152
+ };
153
+ const onStderr = (chunk) => {
154
+ if (stderrBuffer.length < 16384)
155
+ stderrBuffer += String(chunk);
156
+ };
157
+ const onError = () => {
158
+ if (settled)
159
+ return;
160
+ settled = true;
161
+ cleanup();
162
+ reject(new CliError('HOST_UNAVAILABLE'));
163
+ };
164
+ const onClose = () => {
165
+ if (settled)
166
+ return;
167
+ settled = true;
168
+ cleanup();
169
+ reject(parseHostStartupError(stderrBuffer) ?? new CliError('HOST_UNAVAILABLE'));
170
+ };
171
+ const cleanup = () => {
172
+ clearTimeout(timer);
173
+ child.stdout.off('data', onStdout);
174
+ child.stderr.off('data', onStderr);
175
+ child.off('error', onError);
176
+ child.off('close', onClose);
177
+ };
178
+ child.stdout.on('data', onStdout);
179
+ child.stderr.on('data', onStderr);
180
+ child.once('error', onError);
181
+ child.once('close', onClose);
182
+ });
183
+ // Drain remaining stdio streams so child buffers never block.
184
+ child.stdout.resume();
185
+ child.stderr.resume();
186
+ let stopPromise;
187
+ const stop = () => {
188
+ if (stopPromise)
189
+ return stopPromise;
190
+ stopPromise = (async () => {
191
+ if (child.exitCode !== null || child.signalCode !== null) {
192
+ child.stdout.destroy();
193
+ child.stderr.destroy();
194
+ return;
195
+ }
196
+ const exitWait = new Promise((resolve) => {
197
+ const onExit = () => {
198
+ clearTimeout(timer);
199
+ resolve();
200
+ };
201
+ const timer = setTimeout(() => {
202
+ child.off('exit', onExit);
203
+ if (child.exitCode === null && child.signalCode === null)
204
+ child.kill();
205
+ child.stdout.destroy();
206
+ child.stderr.destroy();
207
+ child.unref();
208
+ resolve();
209
+ }, HOST_SHUTDOWN_TIMEOUT_MS);
210
+ if (child.exitCode !== null || child.signalCode !== null) {
211
+ clearTimeout(timer);
212
+ resolve();
213
+ return;
214
+ }
215
+ child.once('exit', onExit);
216
+ });
217
+ try {
218
+ await request(root, { type: 'host.shutdown' }, randomUUID(), 2000);
219
+ }
220
+ catch {
221
+ // Host may already be closing or unreachable; fall back to waiting/killing.
222
+ if (child.exitCode === null && child.signalCode === null)
223
+ child.kill();
224
+ }
225
+ child.stdout.destroy();
226
+ child.stderr.destroy();
227
+ await exitWait;
228
+ })();
229
+ return stopPromise;
230
+ };
231
+ if (!status) {
232
+ await stop();
233
+ throw new CliError('INVALID_REPLY');
234
+ }
235
+ if (options.detach) {
236
+ child.stdout.destroy();
237
+ child.stderr.destroy();
238
+ child.unref();
239
+ }
240
+ return { owned: true, status, stop };
241
+ }
242
+ export async function stopHost(root, currentHost) {
243
+ if (currentHost?.owned && currentHost.stop) {
244
+ await currentHost.stop();
245
+ }
246
+ else {
247
+ try {
248
+ await sendHostCommand(root, { type: 'host.shutdown' }, { timeoutMs: 2000, signal: AbortSignal.timeout(2000) });
249
+ }
250
+ catch (error) {
251
+ if (!(error instanceof CliError) ||
252
+ error.code === 'HOST_UNAVAILABLE' ||
253
+ !isHostConnectionError(error.code))
254
+ throw error;
255
+ }
256
+ }
257
+ const deadline = performance.now() + HOST_STOP_OBSERVATION_MS;
258
+ const signal = AbortSignal.timeout(HOST_STOP_OBSERVATION_MS);
259
+ for (let remaining = deadline - performance.now(); remaining > 0 && !signal.aborted; remaining = deadline - performance.now()) {
260
+ const timeout = Math.ceil(remaining);
261
+ try {
262
+ // Any valid reply proves that the endpoint is still present, including a shutdown error reply.
263
+ await request(root, { type: 'host.status' }, randomUUID(), Math.min(500, timeout), signal);
264
+ }
265
+ catch (error) {
266
+ if (!(error instanceof CliError) || !isHostConnectionError(error.code))
267
+ throw error;
268
+ if (error.code === 'HOST_UNAVAILABLE')
269
+ return;
270
+ }
271
+ const remainingAfterProbe = deadline - performance.now();
272
+ if (remainingAfterProbe > 0)
273
+ await delay(Math.min(50, remainingAfterProbe));
274
+ }
275
+ throw new CliError('HOST_TIMEOUT', undefined, true);
276
+ }
277
+ export async function restartHost(root, currentHost, options) {
278
+ try {
279
+ await stopHost(root, currentHost);
280
+ }
281
+ catch (error) {
282
+ if (!(error instanceof CliError) || error.code !== 'HOST_UNAVAILABLE')
283
+ throw error;
284
+ }
285
+ const deadline = performance.now() + HOST_RESTART_OWNERSHIP_MS;
286
+ for (;;) {
287
+ try {
288
+ return await ensureHost(root, options);
289
+ }
290
+ catch (error) {
291
+ const remaining = deadline - performance.now();
292
+ if (!(error instanceof CliError) || error.code !== 'WORKSPACE_OWNED' || remaining <= 0)
293
+ throw error;
294
+ // The listener may be gone while the previous process is still releasing its workspace lock.
295
+ await delay(Math.min(100, remaining));
296
+ if (performance.now() >= deadline)
297
+ throw error;
298
+ }
299
+ }
300
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};