@celilo/core 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.
- package/README.md +11 -0
- package/package.json +31 -0
- package/src/command-registry.ts +1519 -0
- package/src/index.ts +3 -0
- package/src/protocol.ts +159 -0
- package/src/remote-client.ts +218 -0
package/src/index.ts
ADDED
package/src/protocol.ts
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Remote API wire protocol (Slice 1).
|
|
3
|
+
*
|
|
4
|
+
* A versioned, Zod-validated tagged union carried as NDJSON. This is the
|
|
5
|
+
* transport-neutral message layer for driving the CLI over the wire — see
|
|
6
|
+
* `v2/API_COMMUNICATION.md`. Slice 1 covers non-interactive command execution
|
|
7
|
+
* + streamed output; `interview` / `answer` / `cancel` arrive in Slice 3.
|
|
8
|
+
*
|
|
9
|
+
* The command crosses the wire as a *structured, validated* `argv` array —
|
|
10
|
+
* never a shell string handed to `exec`.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { z } from 'zod';
|
|
14
|
+
|
|
15
|
+
export const API_PROTOCOL_VERSION = 1;
|
|
16
|
+
|
|
17
|
+
// ── client → server ──────────────────────────────────────────────────────
|
|
18
|
+
|
|
19
|
+
export const CommandMessageSchema = z.object({
|
|
20
|
+
type: z.literal('command'),
|
|
21
|
+
/** Structured argv (e.g. ["module", "list"]) — dispatched into runCli. */
|
|
22
|
+
argv: z.array(z.string()).min(1),
|
|
23
|
+
});
|
|
24
|
+
export type CommandMessage = z.infer<typeof CommandMessageSchema>;
|
|
25
|
+
|
|
26
|
+
/** Client's answer to a server `interview` message, correlated by `id`. */
|
|
27
|
+
export const AnswerMessageSchema = z.object({
|
|
28
|
+
type: z.literal('answer'),
|
|
29
|
+
id: z.string(),
|
|
30
|
+
value: z.unknown(),
|
|
31
|
+
});
|
|
32
|
+
export type AnswerMessage = z.infer<typeof AnswerMessageSchema>;
|
|
33
|
+
|
|
34
|
+
export const ClientMessageSchema = z.discriminatedUnion('type', [
|
|
35
|
+
CommandMessageSchema,
|
|
36
|
+
AnswerMessageSchema,
|
|
37
|
+
// Slice 3+: CancelMessageSchema
|
|
38
|
+
]);
|
|
39
|
+
export type ClientMessage = z.infer<typeof ClientMessageSchema>;
|
|
40
|
+
|
|
41
|
+
// ── server → client ──────────────────────────────────────────────────────
|
|
42
|
+
|
|
43
|
+
/** Handshake: server announces itself + the protocol version it speaks. */
|
|
44
|
+
export const ReadyMessageSchema = z.object({
|
|
45
|
+
type: z.literal('ready'),
|
|
46
|
+
protocolVersion: z.literal(API_PROTOCOL_VERSION),
|
|
47
|
+
});
|
|
48
|
+
export type ReadyMessage = z.infer<typeof ReadyMessageSchema>;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* A forwarded `ProgressDisplay` protocol-mode marker. Mirrors the markers
|
|
52
|
+
* emitted by `packages/cli-display` in protocol mode (start/push/done/fail/sub
|
|
53
|
+
* and the legacy instant `[progress]`).
|
|
54
|
+
*/
|
|
55
|
+
export const ProgressMessageSchema = z.object({
|
|
56
|
+
type: z.literal('progress'),
|
|
57
|
+
kind: z.enum(['start', 'push', 'done', 'fail', 'sub', 'message']),
|
|
58
|
+
doing: z.string().optional(),
|
|
59
|
+
done: z.string().optional(),
|
|
60
|
+
message: z.string().optional(),
|
|
61
|
+
});
|
|
62
|
+
export type ProgressMessage = z.infer<typeof ProgressMessageSchema>;
|
|
63
|
+
|
|
64
|
+
/** A plain output line from the command that isn't a progress marker. */
|
|
65
|
+
export const LogMessageSchema = z.object({
|
|
66
|
+
type: z.literal('log'),
|
|
67
|
+
message: z.string(),
|
|
68
|
+
});
|
|
69
|
+
export type LogMessage = z.infer<typeof LogMessageSchema>;
|
|
70
|
+
|
|
71
|
+
/** Terminal message for a command run. */
|
|
72
|
+
export const ResultMessageSchema = z.object({
|
|
73
|
+
type: z.literal('result'),
|
|
74
|
+
success: z.boolean(),
|
|
75
|
+
exitCode: z.number(),
|
|
76
|
+
});
|
|
77
|
+
export type ResultMessage = z.infer<typeof ResultMessageSchema>;
|
|
78
|
+
|
|
79
|
+
/** Protocol-level error (malformed message, etc.) — distinct from a failed command. */
|
|
80
|
+
export const ErrorMessageSchema = z.object({
|
|
81
|
+
type: z.literal('error'),
|
|
82
|
+
error: z.string(),
|
|
83
|
+
});
|
|
84
|
+
export type ErrorMessage = z.infer<typeof ErrorMessageSchema>;
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* A mid-run interview question forwarded from the server's event bus. The client
|
|
88
|
+
* renders it, then replies with an `answer` carrying the same `id`. Mirrors the
|
|
89
|
+
* generic `interview.required.*` payload (see bus-interview.ts).
|
|
90
|
+
*/
|
|
91
|
+
export const InterviewMessageSchema = z.object({
|
|
92
|
+
type: z.literal('interview'),
|
|
93
|
+
id: z.string(),
|
|
94
|
+
kind: z.enum(['text', 'confirm', 'select', 'multiselect']),
|
|
95
|
+
message: z.string(),
|
|
96
|
+
description: z.string().optional(),
|
|
97
|
+
defaultValue: z.string().optional(),
|
|
98
|
+
placeholder: z.string().optional(),
|
|
99
|
+
options: z
|
|
100
|
+
.array(z.object({ value: z.string(), label: z.string(), hint: z.string().optional() }))
|
|
101
|
+
.optional(),
|
|
102
|
+
required: z.boolean().optional(),
|
|
103
|
+
});
|
|
104
|
+
export type InterviewMessage = z.infer<typeof InterviewMessageSchema>;
|
|
105
|
+
|
|
106
|
+
export const ServerMessageSchema = z.discriminatedUnion('type', [
|
|
107
|
+
ReadyMessageSchema,
|
|
108
|
+
ProgressMessageSchema,
|
|
109
|
+
LogMessageSchema,
|
|
110
|
+
ResultMessageSchema,
|
|
111
|
+
ErrorMessageSchema,
|
|
112
|
+
InterviewMessageSchema,
|
|
113
|
+
]);
|
|
114
|
+
export type ServerMessage = z.infer<typeof ServerMessageSchema>;
|
|
115
|
+
|
|
116
|
+
// ── translation ───────────────────────────────────────────────────────────
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Translate one line of the command's stdout into a server message. Progress
|
|
120
|
+
* markers become structured `progress` messages; everything else is a `log`.
|
|
121
|
+
*
|
|
122
|
+
* ponytail: the marker grammar is duplicated from packages/cli-display's
|
|
123
|
+
* ProgressDisplay (which *emits* it). If a third consumer appears, extract a
|
|
124
|
+
* shared parser into @celilo/cli-display and have both sides import it.
|
|
125
|
+
*/
|
|
126
|
+
export function translateOutputLine(line: string): ProgressMessage | LogMessage {
|
|
127
|
+
const startPush = line.match(/^\[progress:(start|push)\] (.*?) \| (.*)$/);
|
|
128
|
+
if (startPush) {
|
|
129
|
+
return {
|
|
130
|
+
type: 'progress',
|
|
131
|
+
kind: startPush[1] as 'start' | 'push',
|
|
132
|
+
doing: startPush[2],
|
|
133
|
+
done: startPush[3],
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const done = line.match(/^\[progress:done\](.*)$/);
|
|
138
|
+
if (done) {
|
|
139
|
+
const msg = done[1].trim();
|
|
140
|
+
return { type: 'progress', kind: 'done', message: msg || undefined };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const fail = line.match(/^\[progress:fail\] (.*)$/);
|
|
144
|
+
if (fail) {
|
|
145
|
+
return { type: 'progress', kind: 'fail', message: fail[1] };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const sub = line.match(/^\[progress:sub\] (.*)$/);
|
|
149
|
+
if (sub) {
|
|
150
|
+
return { type: 'progress', kind: 'sub', message: sub[1] };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const legacy = line.match(/^\[progress\] (.*)$/);
|
|
154
|
+
if (legacy) {
|
|
155
|
+
return { type: 'progress', kind: 'message', message: legacy[1] };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
return { type: 'log', message: line };
|
|
159
|
+
}
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Remote API client — `celilo --remote <dest> <command...>` (Slice 2c).
|
|
3
|
+
*
|
|
4
|
+
* SSHes to <dest> (whose sshd forced command runs `api-serve --principal=…`),
|
|
5
|
+
* ships the command as a structured argv over the NDJSON protocol, renders the
|
|
6
|
+
* streamed `progress`/`log` through the local ProgressDisplay, and exits with
|
|
7
|
+
* the command's exit code. Reuses the system `ssh` client, so keys, known_hosts,
|
|
8
|
+
* agent, and ~/.ssh/config all apply — execution is remote, presentation local.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { spawn } from 'node:child_process';
|
|
12
|
+
import { Readable } from 'node:stream';
|
|
13
|
+
import { type DisplayWriter, ProgressDisplay } from '@celilo/cli-display';
|
|
14
|
+
import * as clack from '@clack/prompts';
|
|
15
|
+
import { type InterviewMessage, type ServerMessage, ServerMessageSchema } from './protocol';
|
|
16
|
+
|
|
17
|
+
const REMOTE_FLAG = '--remote';
|
|
18
|
+
|
|
19
|
+
/** Render a forwarded interview via clack, returning the operator's answer. */
|
|
20
|
+
async function defaultRenderInterview(iv: InterviewMessage): Promise<unknown> {
|
|
21
|
+
const options = (iv.options ?? []).map((o) => ({ value: o.value, label: o.label, hint: o.hint }));
|
|
22
|
+
let result: unknown;
|
|
23
|
+
switch (iv.kind) {
|
|
24
|
+
case 'confirm':
|
|
25
|
+
result = await clack.confirm({
|
|
26
|
+
message: iv.message,
|
|
27
|
+
initialValue: iv.defaultValue === 'true',
|
|
28
|
+
});
|
|
29
|
+
break;
|
|
30
|
+
case 'select':
|
|
31
|
+
result = await clack.select({ message: iv.message, options });
|
|
32
|
+
break;
|
|
33
|
+
case 'multiselect':
|
|
34
|
+
result = await clack.multiselect({
|
|
35
|
+
message: iv.message,
|
|
36
|
+
options,
|
|
37
|
+
required: iv.required ?? false,
|
|
38
|
+
});
|
|
39
|
+
break;
|
|
40
|
+
default:
|
|
41
|
+
result = await clack.text({
|
|
42
|
+
message: iv.message,
|
|
43
|
+
defaultValue: iv.defaultValue,
|
|
44
|
+
placeholder: iv.placeholder,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
if (clack.isCancel(result)) {
|
|
48
|
+
clack.cancel('Cancelled.');
|
|
49
|
+
process.exit(130);
|
|
50
|
+
}
|
|
51
|
+
return result;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Minimal transport surface — satisfied by a `node:child_process` spawn of `ssh`. */
|
|
55
|
+
export interface RemoteTransport {
|
|
56
|
+
stdin: { write(chunk: string): void; flush?(): number | Promise<number> };
|
|
57
|
+
stdout: ReadableStream<Uint8Array>;
|
|
58
|
+
kill(): void;
|
|
59
|
+
exited: Promise<number>;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Resolve the remote target from a leading `--remote <dest>` / `--remote=<dest>`
|
|
64
|
+
* or the `CELILO_REMOTE` env. Returns null for a local invocation.
|
|
65
|
+
*/
|
|
66
|
+
export function resolveRemote(
|
|
67
|
+
argv: string[],
|
|
68
|
+
remoteEnv: string | undefined = process.env.CELILO_REMOTE,
|
|
69
|
+
): { dest: string; commandArgv: string[] } | null {
|
|
70
|
+
const rest = argv.slice(2);
|
|
71
|
+
|
|
72
|
+
if (rest[0] === REMOTE_FLAG && rest[1]) {
|
|
73
|
+
return { dest: rest[1], commandArgv: rest.slice(2) };
|
|
74
|
+
}
|
|
75
|
+
if (rest[0]?.startsWith(`${REMOTE_FLAG}=`)) {
|
|
76
|
+
return { dest: rest[0].slice(REMOTE_FLAG.length + 1), commandArgv: rest.slice(1) };
|
|
77
|
+
}
|
|
78
|
+
if (remoteEnv) {
|
|
79
|
+
return { dest: remoteEnv, commandArgv: rest };
|
|
80
|
+
}
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function openSshTransport(dest: string): RemoteTransport {
|
|
85
|
+
// -T: no pseudo-tty — we want a raw NDJSON pipe. stderr inherits so ssh's own
|
|
86
|
+
// diagnostics (host-key prompts, connection failures) reach the operator.
|
|
87
|
+
// Plain `node:child_process` (works on Node and Bun) — no Bun runtime dep.
|
|
88
|
+
const proc = spawn('ssh', ['-T', dest], { stdio: ['pipe', 'pipe', 'inherit'] });
|
|
89
|
+
if (!proc.stdout || !proc.stdin) throw new Error('ssh was not spawned with piped stdio');
|
|
90
|
+
return {
|
|
91
|
+
stdin: { write: (chunk: string) => void proc.stdin?.write(chunk) },
|
|
92
|
+
stdout: Readable.toWeb(proc.stdout) as unknown as ReadableStream<Uint8Array>,
|
|
93
|
+
kill: () => void proc.kill(),
|
|
94
|
+
exited: new Promise<number>((resolve) => proc.once('exit', (code) => resolve(code ?? 0))),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Apply one server message to the local display; returns an exit code if terminal. */
|
|
99
|
+
function applyMessage(
|
|
100
|
+
msg: ServerMessage,
|
|
101
|
+
display: ProgressDisplay,
|
|
102
|
+
out: DisplayWriter,
|
|
103
|
+
): number | null {
|
|
104
|
+
switch (msg.type) {
|
|
105
|
+
case 'ready':
|
|
106
|
+
return null;
|
|
107
|
+
case 'progress':
|
|
108
|
+
switch (msg.kind) {
|
|
109
|
+
case 'start':
|
|
110
|
+
display.startStep(msg.doing ?? '', msg.done ?? '');
|
|
111
|
+
break;
|
|
112
|
+
case 'push':
|
|
113
|
+
display.pushStep(msg.doing ?? '', msg.done ?? '');
|
|
114
|
+
break;
|
|
115
|
+
case 'done':
|
|
116
|
+
display.doneStep(msg.message);
|
|
117
|
+
break;
|
|
118
|
+
case 'fail':
|
|
119
|
+
display.failStep(msg.message ?? '');
|
|
120
|
+
break;
|
|
121
|
+
case 'sub':
|
|
122
|
+
display.subEvent(msg.message ?? '');
|
|
123
|
+
break;
|
|
124
|
+
case 'message':
|
|
125
|
+
display.instantEvent(msg.message ?? '');
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
return null;
|
|
129
|
+
case 'log':
|
|
130
|
+
// Nest under the active step so the footer isn't corrupted; otherwise print.
|
|
131
|
+
if (display.hasPending) {
|
|
132
|
+
display.subEvent(msg.message);
|
|
133
|
+
} else {
|
|
134
|
+
out.write(`${msg.message}\n`);
|
|
135
|
+
}
|
|
136
|
+
return null;
|
|
137
|
+
case 'error':
|
|
138
|
+
process.stderr.write(`${msg.error}\n`);
|
|
139
|
+
return null;
|
|
140
|
+
case 'interview':
|
|
141
|
+
// Handled by the caller (needs the transport to reply) — never reached here.
|
|
142
|
+
return null;
|
|
143
|
+
case 'result':
|
|
144
|
+
return msg.exitCode;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export async function runRemoteClient(
|
|
149
|
+
dest: string,
|
|
150
|
+
argv: string[],
|
|
151
|
+
opts: {
|
|
152
|
+
openTransport?: (dest: string) => RemoteTransport;
|
|
153
|
+
out?: DisplayWriter;
|
|
154
|
+
renderInterview?: (interview: InterviewMessage) => Promise<unknown>;
|
|
155
|
+
} = {},
|
|
156
|
+
): Promise<number> {
|
|
157
|
+
if (argv.length === 0) {
|
|
158
|
+
process.stderr.write(
|
|
159
|
+
'celilo --remote <dest> requires a command (e.g. celilo --remote host module list)\n',
|
|
160
|
+
);
|
|
161
|
+
return 2;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const openTransport = opts.openTransport ?? openSshTransport;
|
|
165
|
+
const out = opts.out ?? process.stdout;
|
|
166
|
+
const renderInterview = opts.renderInterview ?? defaultRenderInterview;
|
|
167
|
+
const display = new ProgressDisplay({ out });
|
|
168
|
+
|
|
169
|
+
const transport = openTransport(dest);
|
|
170
|
+
transport.stdin.write(`${JSON.stringify({ type: 'command', argv })}\n`);
|
|
171
|
+
await transport.stdin.flush?.();
|
|
172
|
+
|
|
173
|
+
let resultExit: number | null = null;
|
|
174
|
+
const decoder = new TextDecoder();
|
|
175
|
+
let buffer = '';
|
|
176
|
+
|
|
177
|
+
outer: for await (const chunk of transport.stdout) {
|
|
178
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
179
|
+
let nl = buffer.indexOf('\n');
|
|
180
|
+
while (nl >= 0) {
|
|
181
|
+
const line = buffer.slice(0, nl);
|
|
182
|
+
buffer = buffer.slice(nl + 1);
|
|
183
|
+
nl = buffer.indexOf('\n');
|
|
184
|
+
if (!line.trim()) continue;
|
|
185
|
+
|
|
186
|
+
let msg: ServerMessage;
|
|
187
|
+
try {
|
|
188
|
+
msg = ServerMessageSchema.parse(JSON.parse(line));
|
|
189
|
+
} catch {
|
|
190
|
+
// Non-protocol line (e.g. an ssh notice) — pass through.
|
|
191
|
+
out.write(`${line}\n`);
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (msg.type === 'interview') {
|
|
196
|
+
const value = await renderInterview(msg);
|
|
197
|
+
transport.stdin.write(`${JSON.stringify({ type: 'answer', id: msg.id, value })}\n`);
|
|
198
|
+
await transport.stdin.flush?.();
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const exit = applyMessage(msg, display, out);
|
|
203
|
+
if (exit !== null) {
|
|
204
|
+
resultExit = exit;
|
|
205
|
+
break outer;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (resultExit !== null) {
|
|
211
|
+
// Server is still looping awaiting more input — tear it down.
|
|
212
|
+
transport.kill();
|
|
213
|
+
return resultExit;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// Stream ended without a result — surface the transport's exit (ssh failure).
|
|
217
|
+
return transport.exited;
|
|
218
|
+
}
|