@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.
- package/LICENSE +661 -0
- package/dist/attach.d.ts +9 -0
- package/dist/attach.js +80 -0
- package/dist/auth-config.d.ts +31 -0
- package/dist/auth-config.js +285 -0
- package/dist/choice-menu.d.ts +13 -0
- package/dist/choice-menu.js +238 -0
- package/dist/cli-diagnostics.d.ts +23 -0
- package/dist/cli-diagnostics.js +42 -0
- package/dist/cli-help.d.ts +6 -0
- package/dist/cli-help.js +163 -0
- package/dist/client.d.ts +13 -0
- package/dist/client.js +90 -0
- package/dist/commands.d.ts +64 -0
- package/dist/commands.js +299 -0
- package/dist/compaction-command.d.ts +16 -0
- package/dist/compaction-command.js +16 -0
- package/dist/composer.d.ts +88 -0
- package/dist/composer.js +124 -0
- package/dist/config-cli.d.ts +1 -0
- package/dist/config-cli.js +47 -0
- package/dist/config-file.d.ts +1 -0
- package/dist/config-file.js +43 -0
- package/dist/config-lock.d.ts +5 -0
- package/dist/config-lock.js +45 -0
- package/dist/duration.d.ts +2 -0
- package/dist/duration.js +11 -0
- package/dist/export.d.ts +19 -0
- package/dist/export.js +66 -0
- package/dist/host-command.d.ts +40 -0
- package/dist/host-command.js +48 -0
- package/dist/host-launcher.d.ts +22 -0
- package/dist/host-launcher.js +300 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +400 -0
- package/dist/markdown.d.ts +1 -0
- package/dist/markdown.js +118 -0
- package/dist/mcp-cli.d.ts +44 -0
- package/dist/mcp-cli.js +647 -0
- package/dist/menu.d.ts +7 -0
- package/dist/menu.js +91 -0
- package/dist/project-mcp-config.d.ts +9 -0
- package/dist/project-mcp-config.js +98 -0
- package/dist/provider-discovery.d.ts +26 -0
- package/dist/provider-discovery.js +138 -0
- package/dist/provider-pricing.d.ts +3 -0
- package/dist/provider-pricing.js +130 -0
- package/dist/provider.d.ts +16 -0
- package/dist/provider.js +370 -0
- package/dist/reconcile-command.d.ts +36 -0
- package/dist/reconcile-command.js +64 -0
- package/dist/renderer.d.ts +204 -0
- package/dist/renderer.js +1134 -0
- package/dist/repl-host.d.ts +22 -0
- package/dist/repl-host.js +51 -0
- package/dist/repl-run-observer.d.ts +27 -0
- package/dist/repl-run-observer.js +86 -0
- package/dist/repl.d.ts +12 -0
- package/dist/repl.js +1834 -0
- package/dist/results.d.ts +23 -0
- package/dist/results.js +1 -0
- package/dist/sandbox-cli.d.ts +39 -0
- package/dist/sandbox-cli.js +324 -0
- package/dist/session-history.d.ts +17 -0
- package/dist/session-history.js +76 -0
- package/dist/settings-menu.d.ts +2 -0
- package/dist/settings-menu.js +111 -0
- package/dist/skill-cli.d.ts +25 -0
- package/dist/skill-cli.js +355 -0
- package/dist/slash-commands.d.ts +66 -0
- package/dist/slash-commands.js +1449 -0
- package/dist/terminal-input.d.ts +24 -0
- package/dist/terminal-input.js +111 -0
- package/dist/terminal-selection.d.ts +21 -0
- package/dist/terminal-selection.js +72 -0
- package/dist/terminal-text.d.ts +38 -0
- package/dist/terminal-text.js +238 -0
- package/dist/tui.d.ts +170 -0
- package/dist/tui.js +2559 -0
- package/dist/usage.d.ts +13 -0
- package/dist/usage.js +46 -0
- package/dist/user-config.d.ts +48 -0
- package/dist/user-config.js +188 -0
- package/package.json +18 -3
- package/README.md +0 -3
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export declare const compactionOptions: {
|
|
2
|
+
readonly 'through-turn': {
|
|
3
|
+
readonly type: "string";
|
|
4
|
+
};
|
|
5
|
+
readonly summary: {
|
|
6
|
+
readonly type: "string";
|
|
7
|
+
};
|
|
8
|
+
};
|
|
9
|
+
export declare const compactionOptionUsage = "[--through-turn ID] [--summary TEXT]";
|
|
10
|
+
export declare function compactionArguments(values: {
|
|
11
|
+
readonly 'through-turn'?: string | boolean | undefined;
|
|
12
|
+
readonly summary?: string | boolean | undefined;
|
|
13
|
+
}): {
|
|
14
|
+
summary?: string;
|
|
15
|
+
throughTurnId?: string;
|
|
16
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { CliError } from './cli-diagnostics.js';
|
|
2
|
+
export const compactionOptions = {
|
|
3
|
+
'through-turn': { type: 'string' },
|
|
4
|
+
summary: { type: 'string' },
|
|
5
|
+
};
|
|
6
|
+
export const compactionOptionUsage = '[--through-turn ID] [--summary TEXT]';
|
|
7
|
+
export function compactionArguments(values) {
|
|
8
|
+
const { 'through-turn': throughTurnId, summary } = values;
|
|
9
|
+
if ((throughTurnId !== undefined && (typeof throughTurnId !== 'string' || !throughTurnId)) ||
|
|
10
|
+
(summary !== undefined && (typeof summary !== 'string' || !summary.trim())))
|
|
11
|
+
throw new CliError('USAGE');
|
|
12
|
+
return {
|
|
13
|
+
...(throughTurnId === undefined ? {} : { throughTurnId }),
|
|
14
|
+
...(summary === undefined ? {} : { summary }),
|
|
15
|
+
};
|
|
16
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import type { DiscoveredSkillSummary, HostMcpServerSummary, HostProfileSummary, ModeSummary } from '@saturn-universe/protocol';
|
|
2
|
+
export interface SlashArgOption {
|
|
3
|
+
readonly value: string;
|
|
4
|
+
readonly summary: string;
|
|
5
|
+
readonly current?: boolean | undefined;
|
|
6
|
+
readonly appendSpace?: boolean | undefined;
|
|
7
|
+
}
|
|
8
|
+
export interface ChoicePrompt {
|
|
9
|
+
readonly title: string;
|
|
10
|
+
readonly subtitle?: string;
|
|
11
|
+
readonly options: readonly {
|
|
12
|
+
readonly id: string;
|
|
13
|
+
readonly label: string;
|
|
14
|
+
readonly meta?: string;
|
|
15
|
+
readonly current?: boolean;
|
|
16
|
+
}[];
|
|
17
|
+
}
|
|
18
|
+
export interface SlashCommandContext {
|
|
19
|
+
readonly permissionMode?: string | undefined;
|
|
20
|
+
readonly reasoningEffort?: string | undefined;
|
|
21
|
+
readonly workerReasoningEffort?: string | undefined;
|
|
22
|
+
readonly availableReasoningEfforts?: readonly string[] | undefined;
|
|
23
|
+
readonly profileName?: string | undefined;
|
|
24
|
+
readonly modelId?: string | undefined;
|
|
25
|
+
readonly modeRef?: string | undefined;
|
|
26
|
+
readonly activeMode?: ModeSummary | undefined;
|
|
27
|
+
readonly skillRefs: readonly string[];
|
|
28
|
+
readonly disabledSkills?: readonly string[] | undefined;
|
|
29
|
+
readonly configSource?: string | undefined;
|
|
30
|
+
readonly availableProfiles?: readonly HostProfileSummary[] | undefined;
|
|
31
|
+
readonly availableModes?: readonly ModeSummary[] | undefined;
|
|
32
|
+
readonly availableSkills?: readonly string[] | undefined;
|
|
33
|
+
readonly discoveredSkills?: readonly DiscoveredSkillSummary[] | undefined;
|
|
34
|
+
readonly mcpServers?: readonly HostMcpServerSummary[] | undefined;
|
|
35
|
+
readonly availableTeamPresets?: readonly string[] | undefined;
|
|
36
|
+
readonly boardUrl?: string | undefined;
|
|
37
|
+
}
|
|
38
|
+
export interface SlashCommandHint {
|
|
39
|
+
readonly command: string;
|
|
40
|
+
readonly summary: string;
|
|
41
|
+
readonly takesArgs?: boolean;
|
|
42
|
+
readonly submitWithoutArgs?: boolean;
|
|
43
|
+
readonly currentValue?: (ctx: SlashCommandContext) => string | undefined;
|
|
44
|
+
readonly argOptions?: (args: readonly string[], ctx: SlashCommandContext) => readonly SlashArgOption[];
|
|
45
|
+
}
|
|
46
|
+
export type PaletteState = {
|
|
47
|
+
readonly kind: 'commands';
|
|
48
|
+
readonly token: string;
|
|
49
|
+
readonly hasSpace: boolean;
|
|
50
|
+
readonly items: readonly (Pick<SlashCommandHint, 'command' | 'summary'> & {
|
|
51
|
+
readonly takesArgs: boolean;
|
|
52
|
+
readonly currentBadge: string | undefined;
|
|
53
|
+
})[];
|
|
54
|
+
} | {
|
|
55
|
+
readonly kind: 'args';
|
|
56
|
+
readonly command: string;
|
|
57
|
+
readonly currentLabel?: string | undefined;
|
|
58
|
+
readonly prefixArgs: readonly string[];
|
|
59
|
+
readonly partial: string;
|
|
60
|
+
readonly hasSpace: boolean;
|
|
61
|
+
readonly submitWithoutArgs?: boolean | undefined;
|
|
62
|
+
readonly options: readonly SlashArgOption[];
|
|
63
|
+
};
|
|
64
|
+
export interface VisualLine {
|
|
65
|
+
readonly text: string;
|
|
66
|
+
readonly startOffset: number;
|
|
67
|
+
readonly endOffset: number;
|
|
68
|
+
}
|
|
69
|
+
export declare function wrapBuffer(buffer: string, innerWidth: number): VisualLine[];
|
|
70
|
+
export declare function locateCursor(visualLines: readonly VisualLine[], cursorOffset: number): {
|
|
71
|
+
row: number;
|
|
72
|
+
col: number;
|
|
73
|
+
};
|
|
74
|
+
export declare function offsetAtColumn(line: VisualLine, column: number): number;
|
|
75
|
+
export declare function prevCharOffset(text: string, cursor: number): number;
|
|
76
|
+
export declare function nextCharOffset(text: string, cursor: number): number;
|
|
77
|
+
export declare function normalizeCursorOffset(text: string, cursor: number): number;
|
|
78
|
+
export declare function prevWordOffset(text: string, cursor: number): number;
|
|
79
|
+
export declare function isSlashDraft(buffer: string): boolean;
|
|
80
|
+
export declare function resolvePaletteState(buffer: string, hints: readonly SlashCommandHint[], ctx: SlashCommandContext): PaletteState | undefined;
|
|
81
|
+
export declare function paletteSelection(state: PaletteState | undefined, index: number): {
|
|
82
|
+
count: number;
|
|
83
|
+
index: number;
|
|
84
|
+
};
|
|
85
|
+
export declare function resolvePaletteAction(state: PaletteState, index: number, key: 'tab' | 'enter', navigated: boolean): {
|
|
86
|
+
readonly kind: 'edit' | 'submit';
|
|
87
|
+
readonly text: string;
|
|
88
|
+
} | undefined;
|
package/dist/composer.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { displayGraphemes, segmentGraphemes, stringDisplayWidth, wrapDisplayRanges, } from './terminal-text.js';
|
|
2
|
+
export function wrapBuffer(buffer, innerWidth) {
|
|
3
|
+
return Array.from(wrapDisplayRanges(buffer, innerWidth), ({ start, end }) => ({
|
|
4
|
+
text: buffer.slice(start, end),
|
|
5
|
+
startOffset: start,
|
|
6
|
+
endOffset: end,
|
|
7
|
+
}));
|
|
8
|
+
}
|
|
9
|
+
export function locateCursor(visualLines, cursorOffset) {
|
|
10
|
+
for (let i = 0; i < visualLines.length; i++) {
|
|
11
|
+
const line = visualLines[i];
|
|
12
|
+
const isLastForParagraph = i === visualLines.length - 1 || visualLines[i + 1].startOffset > line.endOffset;
|
|
13
|
+
if (cursorOffset >= line.startOffset &&
|
|
14
|
+
(cursorOffset < line.endOffset || (isLastForParagraph && cursorOffset <= line.endOffset))) {
|
|
15
|
+
const before = line.text.slice(0, cursorOffset - line.startOffset);
|
|
16
|
+
return { row: i, col: stringDisplayWidth(before) };
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
const last = visualLines[visualLines.length - 1];
|
|
20
|
+
return { row: visualLines.length - 1, col: stringDisplayWidth(last.text) };
|
|
21
|
+
}
|
|
22
|
+
export function offsetAtColumn(line, column) {
|
|
23
|
+
let width = 0;
|
|
24
|
+
for (const { index, width: cells } of displayGraphemes(line.text)) {
|
|
25
|
+
width += cells;
|
|
26
|
+
if (width > column)
|
|
27
|
+
return line.startOffset + index;
|
|
28
|
+
}
|
|
29
|
+
return line.endOffset;
|
|
30
|
+
}
|
|
31
|
+
export function prevCharOffset(text, cursor) {
|
|
32
|
+
if (cursor <= 0)
|
|
33
|
+
return 0;
|
|
34
|
+
return segmentGraphemes(text).containing(cursor - 1)?.index ?? 0;
|
|
35
|
+
}
|
|
36
|
+
export function nextCharOffset(text, cursor) {
|
|
37
|
+
const current = segmentGraphemes(text).containing(cursor);
|
|
38
|
+
return current ? current.index + current.segment.length : text.length;
|
|
39
|
+
}
|
|
40
|
+
export function normalizeCursorOffset(text, cursor) {
|
|
41
|
+
const current = segmentGraphemes(text).containing(cursor);
|
|
42
|
+
return current && current.index < cursor ? current.index + current.segment.length : cursor;
|
|
43
|
+
}
|
|
44
|
+
export function prevWordOffset(text, cursor) {
|
|
45
|
+
let i = cursor;
|
|
46
|
+
while (i > 0 && /\s/.test(text[i - 1]))
|
|
47
|
+
i--;
|
|
48
|
+
while (i > 0 && !/\s/.test(text[i - 1]))
|
|
49
|
+
i--;
|
|
50
|
+
return segmentGraphemes(text).containing(i)?.index ?? i;
|
|
51
|
+
}
|
|
52
|
+
export function isSlashDraft(buffer) {
|
|
53
|
+
return buffer.startsWith('/') && !buffer.includes('\n');
|
|
54
|
+
}
|
|
55
|
+
export function resolvePaletteState(buffer, hints, ctx) {
|
|
56
|
+
if (!isSlashDraft(buffer))
|
|
57
|
+
return undefined;
|
|
58
|
+
const hasSpace = /\s/.test(buffer);
|
|
59
|
+
const cmdToken = buffer.split(/\s/, 1)[0];
|
|
60
|
+
const cmdLower = cmdToken.toLowerCase();
|
|
61
|
+
const matches = hints.filter((item) => item.command.toLowerCase().startsWith(cmdLower));
|
|
62
|
+
const exact = hasSpace || matches.length === 1
|
|
63
|
+
? matches.find((item) => item.command.toLowerCase() === cmdLower)
|
|
64
|
+
: undefined;
|
|
65
|
+
if (exact?.argOptions) {
|
|
66
|
+
const rawArgs = buffer.slice(exact.command.length).trim();
|
|
67
|
+
const words = rawArgs ? rawArgs.split(/\s+/) : [];
|
|
68
|
+
const hasTrailingSpace = /\s$/.test(buffer);
|
|
69
|
+
const partial = hasTrailingSpace ? '' : (words.at(-1) ?? '');
|
|
70
|
+
const prefixArgs = hasTrailingSpace ? words : words.slice(0, -1);
|
|
71
|
+
const partialLower = partial.toLowerCase();
|
|
72
|
+
const options = exact
|
|
73
|
+
.argOptions(prefixArgs, ctx)
|
|
74
|
+
.filter((option) => option.value.toLowerCase().startsWith(partialLower));
|
|
75
|
+
return {
|
|
76
|
+
kind: 'args',
|
|
77
|
+
command: exact.command,
|
|
78
|
+
currentLabel: exact.currentValue?.(ctx),
|
|
79
|
+
prefixArgs,
|
|
80
|
+
partial,
|
|
81
|
+
hasSpace,
|
|
82
|
+
submitWithoutArgs: exact.submitWithoutArgs,
|
|
83
|
+
options,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
kind: 'commands',
|
|
88
|
+
token: cmdToken,
|
|
89
|
+
hasSpace,
|
|
90
|
+
items: matches.map(({ command, summary, takesArgs, currentValue }) => ({
|
|
91
|
+
command,
|
|
92
|
+
summary,
|
|
93
|
+
takesArgs: takesArgs ?? false,
|
|
94
|
+
currentBadge: currentValue?.(ctx),
|
|
95
|
+
})),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
export function paletteSelection(state, index) {
|
|
99
|
+
const count = state?.kind === 'commands' ? state.items.length : (state?.options.length ?? 0);
|
|
100
|
+
return { count, index: Math.max(0, Math.min(index, count - 1)) };
|
|
101
|
+
}
|
|
102
|
+
export function resolvePaletteAction(state, index, key, navigated) {
|
|
103
|
+
const selectedIndex = paletteSelection(state, index).index;
|
|
104
|
+
if (state.kind === 'commands') {
|
|
105
|
+
const selected = state.hasSpace ? undefined : state.items[selectedIndex];
|
|
106
|
+
if (!selected)
|
|
107
|
+
return undefined;
|
|
108
|
+
if (selected.takesArgs)
|
|
109
|
+
return { kind: 'edit', text: `${selected.command} ` };
|
|
110
|
+
return { kind: key === 'tab' ? 'edit' : 'submit', text: selected.command };
|
|
111
|
+
}
|
|
112
|
+
if (key === 'enter' &&
|
|
113
|
+
!navigated &&
|
|
114
|
+
(!state.hasSpace || (state.submitWithoutArgs && !state.partial && !state.prefixArgs.length)))
|
|
115
|
+
return undefined;
|
|
116
|
+
const option = state.options[selectedIndex];
|
|
117
|
+
if (!option) {
|
|
118
|
+
return key === 'tab' && !state.hasSpace ? { kind: 'edit', text: `${state.command} ` } : undefined;
|
|
119
|
+
}
|
|
120
|
+
const text = [state.command, ...state.prefixArgs, option.value].join(' ');
|
|
121
|
+
if (option.appendSpace)
|
|
122
|
+
return { kind: 'edit', text: `${text} ` };
|
|
123
|
+
return { kind: key === 'tab' ? 'edit' : 'submit', text };
|
|
124
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function runConfigCommand(configArgs: string[]): Promise<void>;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { parseArgs } from 'node:util';
|
|
2
|
+
import { CliError } from './cli-diagnostics.js';
|
|
3
|
+
import { workspaceRoot } from './client.js';
|
|
4
|
+
import { sendHostCommand } from './host-command.js';
|
|
5
|
+
import { renderConfigCheck, renderConfigInit, renderConfigSummary } from './renderer.js';
|
|
6
|
+
import { initUserConfig, inspectUserConfig } from './user-config.js';
|
|
7
|
+
export async function runConfigCommand(configArgs) {
|
|
8
|
+
const json = configArgs.includes('--json');
|
|
9
|
+
let parsed;
|
|
10
|
+
try {
|
|
11
|
+
parsed = parseArgs({
|
|
12
|
+
args: configArgs,
|
|
13
|
+
allowPositionals: true,
|
|
14
|
+
strict: true,
|
|
15
|
+
options: {
|
|
16
|
+
force: { type: 'boolean' },
|
|
17
|
+
workspace: { type: 'string', short: 'C' },
|
|
18
|
+
json: { type: 'boolean' },
|
|
19
|
+
},
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
throw new CliError('USAGE');
|
|
24
|
+
}
|
|
25
|
+
const [sub = 'show', ...extra] = parsed.positionals;
|
|
26
|
+
if (extra.length || !['show', 'check', 'init'].includes(sub))
|
|
27
|
+
throw new CliError('USAGE');
|
|
28
|
+
if (parsed.values.force && sub !== 'init')
|
|
29
|
+
throw new CliError('USAGE');
|
|
30
|
+
if (sub === 'init') {
|
|
31
|
+
const result = await initUserConfig(Boolean(parsed.values.force));
|
|
32
|
+
if (json)
|
|
33
|
+
process.stdout.write(JSON.stringify({ ok: true, result }) + '\n');
|
|
34
|
+
else
|
|
35
|
+
process.stdout.write(renderConfigInit(result) + '\n');
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
const workdir = await workspaceRoot(typeof parsed.values.workspace === 'string' ? parsed.values.workspace : process.cwd());
|
|
39
|
+
const inspection = await inspectUserConfig(workdir);
|
|
40
|
+
const status = await sendHostCommand(workdir, { type: 'host.status' }, { timeoutMs: 2000 }).catch(() => undefined);
|
|
41
|
+
if (json) {
|
|
42
|
+
process.stdout.write(JSON.stringify({ ok: true, result: { ...inspection, ...(status ? { host: status } : {}) } }) + '\n');
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
process.stdout.write((sub === 'check' ? renderConfigCheck(inspection, status) : renderConfigSummary(inspection, status)) +
|
|
46
|
+
'\n');
|
|
47
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function atomicWriteText(target: string, data: string, mode: number): Promise<void>;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdir, open, rename, rm } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
5
|
+
const windowsReplaceRetryMs = [25, 50, 100, 200];
|
|
6
|
+
async function replaceConfigFile(temporary, target) {
|
|
7
|
+
for (let attempt = 0;; attempt++) {
|
|
8
|
+
try {
|
|
9
|
+
await rename(temporary, target);
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
const wait = windowsReplaceRetryMs[attempt];
|
|
14
|
+
// A Windows reader can briefly prevent replacing the target file.
|
|
15
|
+
if (process.platform !== 'win32' ||
|
|
16
|
+
error.code !== 'EPERM' ||
|
|
17
|
+
wait === undefined) {
|
|
18
|
+
throw error;
|
|
19
|
+
}
|
|
20
|
+
await delay(wait);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export async function atomicWriteText(target, data, mode) {
|
|
25
|
+
await mkdir(path.dirname(target), { recursive: true });
|
|
26
|
+
const temporary = `${target}.${randomUUID()}.tmp`;
|
|
27
|
+
const file = await open(temporary, 'wx', mode);
|
|
28
|
+
try {
|
|
29
|
+
try {
|
|
30
|
+
await file.writeFile(data, 'utf8');
|
|
31
|
+
if (process.platform !== 'win32')
|
|
32
|
+
await file.chmod(mode);
|
|
33
|
+
}
|
|
34
|
+
finally {
|
|
35
|
+
await file.close();
|
|
36
|
+
}
|
|
37
|
+
await replaceConfigFile(temporary, target);
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
await rm(temporary, { force: true });
|
|
41
|
+
throw error;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export declare function withProjectMcpConfigLock<T>(workdir: string, update: () => Promise<T>): Promise<T>;
|
|
2
|
+
export declare function withUserConfigLock<T>({ env, timeoutError }: {
|
|
3
|
+
readonly env: NodeJS.ProcessEnv;
|
|
4
|
+
readonly timeoutError?: () => Error;
|
|
5
|
+
}, update: () => Promise<T>): Promise<T>;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { mkdir } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
4
|
+
import { projectMcpConfigPath, saturnHomeDir, workspaceConfigPath } from '@saturn-universe/protocol';
|
|
5
|
+
const SQLITE_BUSY = 5;
|
|
6
|
+
const sqlitePrimaryCodeMask = 0xff;
|
|
7
|
+
async function withSqliteWriteLock(filename, timeoutError, update) {
|
|
8
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
9
|
+
const lock = new DatabaseSync(filename, { timeout: 0 });
|
|
10
|
+
const deadline = performance.now() + 4_000;
|
|
11
|
+
try {
|
|
12
|
+
// Keep the lock file's identity stable. The transaction provides the lock without storing config data.
|
|
13
|
+
for (;;) {
|
|
14
|
+
try {
|
|
15
|
+
lock.exec('BEGIN IMMEDIATE');
|
|
16
|
+
break;
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
const { code, errcode } = error;
|
|
20
|
+
if (code !== 'ERR_SQLITE_ERROR' ||
|
|
21
|
+
errcode === undefined ||
|
|
22
|
+
(errcode & sqlitePrimaryCodeMask) !== SQLITE_BUSY)
|
|
23
|
+
throw error;
|
|
24
|
+
const remaining = deadline - performance.now();
|
|
25
|
+
if (remaining <= 0)
|
|
26
|
+
throw timeoutError();
|
|
27
|
+
await delay(Math.min(40, remaining));
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return await update();
|
|
31
|
+
}
|
|
32
|
+
finally {
|
|
33
|
+
lock.close();
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export async function withProjectMcpConfigLock(workdir, update) {
|
|
37
|
+
const lockDir = path.dirname(workspaceConfigPath(workdir));
|
|
38
|
+
await mkdir(lockDir, { recursive: true });
|
|
39
|
+
return withSqliteWriteLock(path.join(lockDir, 'mcp-config.lock'), () => new Error(`Another project MCP config update is in progress: ${projectMcpConfigPath(workdir)}`), update);
|
|
40
|
+
}
|
|
41
|
+
export async function withUserConfigLock({ env, timeoutError }, update) {
|
|
42
|
+
const home = saturnHomeDir(env);
|
|
43
|
+
await mkdir(home, { recursive: true, mode: 0o700 });
|
|
44
|
+
return withSqliteWriteLock(path.join(home, '.config-write.lock'), timeoutError ?? (() => new Error('Another config update is in progress in SATURN_HOME.')), update);
|
|
45
|
+
}
|
package/dist/duration.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export const spinnerFrameMs = 90;
|
|
2
|
+
export function formatDuration(milliseconds) {
|
|
3
|
+
const total = Number.isFinite(milliseconds) ? Math.max(0, Math.floor(milliseconds / 1000)) : 0;
|
|
4
|
+
const hours = Math.floor(total / 3600);
|
|
5
|
+
const minutes = Math.floor(total / 60) % 60;
|
|
6
|
+
const seconds = total % 60;
|
|
7
|
+
const pad = (number) => String(number).padStart(2, '0');
|
|
8
|
+
if (hours)
|
|
9
|
+
return `${hours}h ${pad(minutes)}m ${pad(seconds)}s`;
|
|
10
|
+
return minutes ? `${minutes}m ${pad(seconds)}s` : `${seconds}s`;
|
|
11
|
+
}
|
package/dist/export.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { HostCommandInput, SessionExportPage } from '@saturn-universe/protocol';
|
|
2
|
+
type ExportRequest = Extract<HostCommandInput, {
|
|
3
|
+
type: 'session.export';
|
|
4
|
+
}>;
|
|
5
|
+
export declare function defaultExportFilename(sessionId: string, now?: Date): string;
|
|
6
|
+
export declare function formatByteSize(bytes: number): string;
|
|
7
|
+
export declare function exportSessionToJsonl(options: {
|
|
8
|
+
readonly workdir: string;
|
|
9
|
+
readonly sessionId: string;
|
|
10
|
+
readonly outputPath?: string | undefined;
|
|
11
|
+
readonly sendCommand: (command: ExportRequest) => Promise<SessionExportPage>;
|
|
12
|
+
readonly now?: Date;
|
|
13
|
+
}): Promise<{
|
|
14
|
+
readonly path: string;
|
|
15
|
+
readonly count: number;
|
|
16
|
+
readonly bytes: number;
|
|
17
|
+
readonly sessionId: string;
|
|
18
|
+
}>;
|
|
19
|
+
export {};
|
package/dist/export.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { DEFAULT_SESSION_EXPORT_LIMIT, redactExportValue } from '@saturn-universe/protocol';
|
|
4
|
+
import { CliError } from './cli-diagnostics.js';
|
|
5
|
+
export function defaultExportFilename(sessionId, now = new Date()) {
|
|
6
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
7
|
+
const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-` +
|
|
8
|
+
`${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
|
|
9
|
+
const shortId = sessionId.replace(/[^A-Za-z0-9_-]/g, '').slice(0, 8) || 'session';
|
|
10
|
+
return `saturn-export-${shortId}-${stamp}.jsonl`;
|
|
11
|
+
}
|
|
12
|
+
export function formatByteSize(bytes) {
|
|
13
|
+
if (bytes < 1024)
|
|
14
|
+
return `${bytes} B`;
|
|
15
|
+
if (bytes < 1024 * 1024)
|
|
16
|
+
return `${(bytes / 1024).toFixed(1)} KB`;
|
|
17
|
+
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
|
|
18
|
+
}
|
|
19
|
+
export async function exportSessionToJsonl(options) {
|
|
20
|
+
const request = {
|
|
21
|
+
type: 'session.export',
|
|
22
|
+
sessionId: options.sessionId,
|
|
23
|
+
limit: DEFAULT_SESSION_EXPORT_LIMIT,
|
|
24
|
+
};
|
|
25
|
+
const first = await options.sendCommand(request);
|
|
26
|
+
const { sessionId: resolvedSessionId, through } = first;
|
|
27
|
+
const records = [...first.records];
|
|
28
|
+
let after = first.nextAfter;
|
|
29
|
+
while (after !== undefined) {
|
|
30
|
+
const page = await options.sendCommand({ ...request, after, through });
|
|
31
|
+
if (page.sessionId !== resolvedSessionId || page.through !== through)
|
|
32
|
+
throw new CliError('INVALID_REPLY');
|
|
33
|
+
records.push(...page.records);
|
|
34
|
+
after = page.nextAfter;
|
|
35
|
+
}
|
|
36
|
+
records.sort((a, b) => {
|
|
37
|
+
const tsCmp = a.ts.localeCompare(b.ts);
|
|
38
|
+
if (tsCmp !== 0)
|
|
39
|
+
return tsCmp;
|
|
40
|
+
const pa = BigInt(a.position);
|
|
41
|
+
const pb = BigInt(b.position);
|
|
42
|
+
return pa < pb ? -1 : pa > pb ? 1 : 0;
|
|
43
|
+
});
|
|
44
|
+
const lines = records.map((record) => JSON.stringify({
|
|
45
|
+
ts: record.ts,
|
|
46
|
+
sessionId: record.sessionId,
|
|
47
|
+
runId: record.runId,
|
|
48
|
+
agentId: record.agentId,
|
|
49
|
+
agentRole: record.agentRole,
|
|
50
|
+
...(record.memberId ? { memberId: record.memberId } : {}),
|
|
51
|
+
kind: record.kind,
|
|
52
|
+
payload: redactExportValue(record.payload),
|
|
53
|
+
}));
|
|
54
|
+
const content = lines.length ? `${lines.join('\n')}\n` : '';
|
|
55
|
+
const targetPath = options.outputPath?.trim()
|
|
56
|
+
? path.resolve(options.workdir, options.outputPath.trim())
|
|
57
|
+
: path.resolve(options.workdir, defaultExportFilename(resolvedSessionId, options.now));
|
|
58
|
+
await mkdir(path.dirname(targetPath), { recursive: true });
|
|
59
|
+
await writeFile(targetPath, content, 'utf8');
|
|
60
|
+
return {
|
|
61
|
+
path: targetPath,
|
|
62
|
+
count: records.length,
|
|
63
|
+
bytes: Buffer.byteLength(content, 'utf8'),
|
|
64
|
+
sessionId: resolvedSessionId,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { HostCommandInput, HostCommandResults } from '@saturn-universe/protocol';
|
|
2
|
+
import type { ReconciliationRequest } from './reconcile-command.js';
|
|
3
|
+
interface HostCommandOptions {
|
|
4
|
+
readonly commandId?: string | undefined;
|
|
5
|
+
readonly timeoutMs?: number | undefined;
|
|
6
|
+
readonly signal?: AbortSignal | undefined;
|
|
7
|
+
}
|
|
8
|
+
export declare function sendHostCommand<Type extends keyof HostCommandResults>(root: string, command: {
|
|
9
|
+
readonly type: Type;
|
|
10
|
+
} & Extract<HostCommandInput, {
|
|
11
|
+
readonly type: Type;
|
|
12
|
+
}>, { commandId, timeoutMs, signal }?: HostCommandOptions): Promise<HostCommandResults[Type]>;
|
|
13
|
+
export declare function ensureHostWorkspace(root: string, options?: HostCommandOptions): Promise<HostCommandResults['workspace.create']>;
|
|
14
|
+
export declare function reconcileRunTool(root: string, runId: string, command: ReconciliationRequest, options?: HostCommandOptions): Promise<Readonly<{
|
|
15
|
+
toolCallId: import("@saturn-universe/core").ToolCallId;
|
|
16
|
+
cursor: import("@saturn-universe/core").EventPosition;
|
|
17
|
+
}>>;
|
|
18
|
+
type ApprovalCommand = Extract<HostCommandInput, {
|
|
19
|
+
type: 'tool.approval.resolve';
|
|
20
|
+
}>;
|
|
21
|
+
type ApprovalTarget = Pick<ApprovalCommand['decision'], 'approvalId' | 'toolCallId'>;
|
|
22
|
+
type ApprovalChoice = {
|
|
23
|
+
readonly approved: boolean;
|
|
24
|
+
readonly decidedAt?: string | undefined;
|
|
25
|
+
readonly decidedBy?: string | undefined;
|
|
26
|
+
readonly reason?: string | undefined;
|
|
27
|
+
readonly deferResume?: boolean | undefined;
|
|
28
|
+
};
|
|
29
|
+
export declare function approvalCommand({ approvalId, toolCallId }: ApprovalTarget, { approved, decidedAt, decidedBy, reason, deferResume, }: ApprovalChoice): ApprovalCommand;
|
|
30
|
+
export declare function resolveRunApproval(root: string, runId: string, choice: ApprovalChoice & {
|
|
31
|
+
readonly approvalId?: string | undefined;
|
|
32
|
+
readonly toolCallId?: string | undefined;
|
|
33
|
+
}, options?: HostCommandOptions): Promise<{
|
|
34
|
+
receipt: Readonly<{
|
|
35
|
+
approvalId: import("@saturn-universe/core").ApprovalId;
|
|
36
|
+
cursor: import("@saturn-universe/core").EventPosition;
|
|
37
|
+
}>;
|
|
38
|
+
toolCallId: string;
|
|
39
|
+
} | undefined>;
|
|
40
|
+
export {};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { pathToFileURL } from 'node:url';
|
|
3
|
+
import { CliError } from './cli-diagnostics.js';
|
|
4
|
+
import { request } from './client.js';
|
|
5
|
+
export async function sendHostCommand(root, command, { commandId = randomUUID(), timeoutMs, signal } = {}) {
|
|
6
|
+
const reply = await request(root, command, commandId, timeoutMs, signal);
|
|
7
|
+
if (!reply.ok)
|
|
8
|
+
throw reply.error;
|
|
9
|
+
// The client validates the reply against the decoded command before returning it.
|
|
10
|
+
return reply.result;
|
|
11
|
+
}
|
|
12
|
+
export async function ensureHostWorkspace(root, options = {}) {
|
|
13
|
+
const workspaces = await sendHostCommand(root, { type: 'workspace.query' }, options);
|
|
14
|
+
if (workspaces.length)
|
|
15
|
+
return { workspaceId: workspaces[0].id };
|
|
16
|
+
const commandId = `cli:workspace:${createHash('sha256').update(root).digest('hex')}`;
|
|
17
|
+
return sendHostCommand(root, { type: 'workspace.create', rootUri: pathToFileURL(root).href }, { ...options, commandId });
|
|
18
|
+
}
|
|
19
|
+
export async function reconcileRunTool(root, runId, command, options) {
|
|
20
|
+
const run = await sendHostCommand(root, { type: 'run.query', runId }, options);
|
|
21
|
+
if (!run.tools?.some((tool) => tool.call.id === command.toolCallId))
|
|
22
|
+
throw new CliError('INVALID_COMMAND');
|
|
23
|
+
return sendHostCommand(root, command, options);
|
|
24
|
+
}
|
|
25
|
+
export function approvalCommand({ approvalId, toolCallId }, { approved, decidedAt = new Date().toISOString(), decidedBy = 'cli', reason = approved ? 'Approved from CLI' : 'Denied from CLI', deferResume, }) {
|
|
26
|
+
return {
|
|
27
|
+
type: 'tool.approval.resolve',
|
|
28
|
+
...(deferResume ? { resume: false } : {}),
|
|
29
|
+
decision: { approvalId, toolCallId, approved, decidedAt, decidedBy, reason },
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
export async function resolveRunApproval(root, runId, choice, options) {
|
|
33
|
+
const { approvalId, toolCallId } = choice;
|
|
34
|
+
const explicitPair = approvalId !== undefined && toolCallId !== undefined;
|
|
35
|
+
const run = await sendHostCommand(root, { type: 'run.query', runId }, options);
|
|
36
|
+
const selected = run.tools?.find(({ call, approval }) => approval &&
|
|
37
|
+
(explicitPair || approval.status === 'pending') &&
|
|
38
|
+
(approvalId === undefined || approval.request.approvalId === approvalId) &&
|
|
39
|
+
(toolCallId === undefined || call.id === toolCallId));
|
|
40
|
+
if (!selected?.approval) {
|
|
41
|
+
if (approvalId !== undefined || toolCallId !== undefined)
|
|
42
|
+
throw new CliError('INVALID_COMMAND');
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
const command = approvalCommand({ approvalId: selected.approval.request.approvalId, toolCallId: selected.call.id }, { ...choice, decidedAt: choice.decidedAt ?? selected.approval.decision?.decidedAt });
|
|
46
|
+
const receipt = await sendHostCommand(root, command, options);
|
|
47
|
+
return { receipt, toolCallId: selected.call.id };
|
|
48
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { HostStatusSnapshot } from '@saturn-universe/protocol';
|
|
2
|
+
export interface HostLaunchOptions {
|
|
3
|
+
readonly config?: string;
|
|
4
|
+
readonly profile?: string;
|
|
5
|
+
readonly taskProfile?: string;
|
|
6
|
+
readonly mode?: string;
|
|
7
|
+
readonly allowUnsafeSandboxFallback?: boolean;
|
|
8
|
+
readonly detach?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface ManagedHost {
|
|
11
|
+
readonly owned: boolean;
|
|
12
|
+
readonly status: HostStatusSnapshot;
|
|
13
|
+
stop?(): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
export declare const DEFAULT_HOST_READY_TIMEOUT_MS = 60000;
|
|
16
|
+
export declare function resolveHostReadyTimeoutMs(env?: NodeJS.ProcessEnv): number;
|
|
17
|
+
export declare function resolveHostEntry(): Promise<string>;
|
|
18
|
+
export declare function shouldEnableEnvProxy(env: NodeJS.ProcessEnv): boolean;
|
|
19
|
+
export declare function buildHostSpawnEnv(baseEnv?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
|
|
20
|
+
export declare function ensureHost(root: string, options?: HostLaunchOptions): Promise<ManagedHost>;
|
|
21
|
+
export declare function stopHost(root: string, currentHost?: ManagedHost): Promise<void>;
|
|
22
|
+
export declare function restartHost(root: string, currentHost: ManagedHost | undefined, options: HostLaunchOptions): Promise<ManagedHost>;
|