@niwa-labs/cli 0.0.0-stage → 0.0.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/src/index.ts ADDED
@@ -0,0 +1,510 @@
1
+ /**
2
+ * index.ts — the commands of the CLI, generated from the list of actions.
3
+ *
4
+ * The list of actions is the single source for three things: the MCP tools an agent sees, the
5
+ * commands of the CLI, and niwa's self-description. This module
6
+ * keeps no list of its own: the commands are built from what `describe()` says, every time the
7
+ * CLI runs.
8
+ *
9
+ * So a plugin that declares a new action has a command at once, with no change here.
10
+ *
11
+ * The command of an action is its own name:
12
+ *
13
+ * niwa telegram.send --chat 42 --text "hello"
14
+ * niwa telegram.send --json '{"chat": 42, "text": "hello"}'
15
+ *
16
+ * The fields and their types come from the action's input schema.
17
+ *
18
+ * The caller is bound by the transport, never by an argument: the CLI connects with its own id,
19
+ * and the host names the caller from the connection.
20
+ */
21
+
22
+ import { homedir } from "node:os";
23
+ import { join } from "node:path";
24
+
25
+ import {
26
+ connect,
27
+ livingHolderPid,
28
+ DescriptionOutput,
29
+ RecordList,
30
+ RecordsOutput,
31
+ STATUS_ACTION,
32
+ STOP_ACTION,
33
+ StatusOutput,
34
+ TracedRecordsOutput,
35
+ withWorkingDirectory,
36
+ } from "@niwa-labs/client";
37
+ import type { ActionDescription, Seq, Token } from "@niwa-labs/core";
38
+ import type { NiwaApi } from "@niwa-labs/client";
39
+ import { AGENT_USAGE, runAgentCommand } from "./agent.ts";
40
+ import { LOG_USAGE, LogUsage, log } from "./log.ts";
41
+ import { SKILL_USAGE } from "./skill/command.ts";
42
+ import {
43
+ fieldsOf,
44
+ recordLine,
45
+ renderDescription,
46
+ renderRecords,
47
+ renderStatus,
48
+ renderTrace,
49
+ renderValue,
50
+ type Format,
51
+ } from "./render.ts";
52
+
53
+ export { AGENT_USAGE, callerSession, runAgentCommand } from "./agent.ts";
54
+ export type { AgentCommandContext, AgentCommandResult, CallerSession } from "./agent.ts";
55
+ export { INSERT_REPORT, INSERT_USAGE, runInsert } from "./insert.ts";
56
+ export { log } from "./log.ts";
57
+ export { logLine } from "./render.ts";
58
+ export { installedText, skillText } from "./skill/install.ts";
59
+ export { SKILL_USAGE, runSkill } from "./skill/command.ts";
60
+ export type { SkillContext, SkillKind, SkillRoots } from "./skill/command.ts";
61
+
62
+ /** What one run of the CLI did. */
63
+ export interface CliResult {
64
+ /** The text to print: what a person reads, or what a machine reads under `--json`. */
65
+ readonly output: string;
66
+ /** The exit code: zero when the command did what it was asked. */
67
+ readonly code: number;
68
+ /** The code of the error the host refused with, when it refused. */
69
+ readonly errorCode?: string;
70
+ }
71
+
72
+ /**
73
+ * The commands the CLI answers itself: the ones that are about the CLI, not about the host.
74
+ *
75
+ * Every other command is an action the host declares, and the observation actions of the core
76
+ * are actions like any other: `niwa records.read`, `niwa trace` and `niwa causes` are commands
77
+ * because the host declares them, not because the CLI knows them.
78
+ *
79
+ * `log` is the one that is about the CLI: it is `niwa.records.search` shown the way a person reads a log,
80
+ * and followed by reading again. `agent attach` reads the session it runs in from its environment, which
81
+ * no action can see.
82
+ */
83
+ const BUILTIN = ["serve", "help", "log", "agent"] as const;
84
+
85
+ /** One builtin command. */
86
+ export type Builtin = (typeof BUILTIN)[number];
87
+
88
+ /** The arguments of one run of the CLI. */
89
+ export interface CliArgs {
90
+ /** The home of the host: from `--home`, from `NIWA_HOME`, or `~/.niwa`. */
91
+ readonly home: string;
92
+ /** The command: an action name, or a builtin. */
93
+ readonly command: string;
94
+ /** The rest of the command line: the fields of the action, or the options of the builtin. */
95
+ readonly args: string[];
96
+ /** True when the machine form was asked for. */
97
+ readonly json: boolean;
98
+ /** Who the CLI is: `NIWA_ID` when the command runs in a session, else the owner's own token. */
99
+ readonly token?: Token;
100
+ /** The environment the command runs in: the process's own when absent. */
101
+ readonly env?: Readonly<Record<string, string | undefined>>;
102
+ /** The directory the command runs in: the process's own when absent. */
103
+ readonly cwd?: string;
104
+ }
105
+
106
+ /**
107
+ * The home of the host: `--home`, else `NIWA_HOME`, else `~/.niwa`.
108
+ *
109
+ * The order is the one a person expects: what was said, then the environment, then the place
110
+ * niwa keeps its home by default.
111
+ */
112
+ export function homeOf(argv: string[], env: Record<string, string | undefined>): string {
113
+ for (let index = 0; index < argv.length; index += 1) {
114
+ const argument = argv[index];
115
+ if (argument === "--home") {
116
+ const value = argv[index + 1];
117
+ if (value !== undefined) return value;
118
+ }
119
+ if (argument?.startsWith("--home=")) {
120
+ return argument.slice("--home=".length);
121
+ }
122
+ }
123
+ const fromEnv = env["NIWA_HOME"];
124
+ if (fromEnv !== undefined && fromEnv.length > 0) return fromEnv;
125
+ return join(homedir(), ".niwa");
126
+ }
127
+
128
+ /**
129
+ * The input of an action, from the command line.
130
+ *
131
+ * `--field value` is read in the type the schema gives the field (number, integer, boolean,
132
+ * array, object; a string otherwise), and every flag names the field of the same name, so an action
133
+ * with a field called `input` takes `--input`. `--json '{...}'` gives the whole input at once;
134
+ * fields named after it win over it. (`--json -` reads the JSON from stdin: see `withStdinJson`.)
135
+ *
136
+ * An action that takes a `box` takes `--allow <item>` and `--only <item>` for it, each as often as
137
+ * there are items: `--allow bun --allow write:../artifacts` adds to the host's default, `--only read:.`
138
+ * puts these instead. An item is a profile's name, `project`, `toolchains`, or `read:`, `write:` or
139
+ * `net:` and a place.
140
+ */
141
+ export function inputOf(action: ActionDescription, args: string[]): Record<string, unknown> {
142
+ const properties = (action.input as { properties?: Record<string, unknown> }).properties;
143
+ // An input that takes keys besides its fields (the options block of a harness's kind) says what they hold.
144
+ const additional = (action.input as { additionalProperties?: unknown }).additionalProperties;
145
+ const others = typeof additional === "object" && additional !== null ? additional : undefined;
146
+ const input: Record<string, unknown> = {};
147
+
148
+ for (let index = 0; index < args.length; index += 1) {
149
+ const argument = args[index];
150
+ if (argument === "--json") {
151
+ const text = args[index + 1];
152
+ if (text === undefined) throw new CliError("--json needs the JSON as its next argument");
153
+ const parsed = parseJson(text);
154
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
155
+ throw new CliError("--json must hold an object");
156
+ }
157
+ Object.assign(input, parsed);
158
+ index += 1;
159
+ continue;
160
+ }
161
+ if (argument === undefined || !argument.startsWith("--")) {
162
+ throw new CliError(`unexpected argument "${String(argument)}"`);
163
+ }
164
+ if ((argument === "--allow" || argument === "--only") && properties !== undefined && Object.hasOwn(properties, "box")) {
165
+ const text = args[index + 1];
166
+ if (text === undefined || text.startsWith("--")) throw new CliError(`${argument} needs an item: a profile, project, toolchains, read:<path>, write:<path> or net:<host>`);
167
+ boxItem(input, argument.slice(2) as "allow" | "only", text);
168
+ index += 1;
169
+ continue;
170
+ }
171
+ const written = argument.slice(2);
172
+ // `--timeout-ms` is the field `timeoutMs`: the dashed form is the one a command line reads in.
173
+ // A key that is no field, in an input that takes such keys, is taken as it is written.
174
+ const name =
175
+ properties !== undefined && !Object.hasOwn(properties, written) && (others === undefined || Object.hasOwn(properties, camelCase(written)))
176
+ ? camelCase(written)
177
+ : written;
178
+ if (properties !== undefined && !Object.hasOwn(properties, name) && others === undefined) {
179
+ const hint = written === "input" ? " (the whole input as JSON is --json)" : "";
180
+ throw new CliError(
181
+ `${action.name} has no field "${written}"${hint}; its fields are: ${Object.keys(properties).join(", ")}`,
182
+ );
183
+ }
184
+ const value = args[index + 1];
185
+ // A flag (a boolean field) with no value after it is true: `--wait`.
186
+ const field = properties !== undefined && Object.hasOwn(properties, name) ? properties[name] : others;
187
+ if (typesOf(field).includes("boolean") && (value === undefined || value.startsWith("--"))) {
188
+ Object.defineProperty(input, name, { value: true, enumerable: true, writable: true, configurable: true });
189
+ continue;
190
+ }
191
+ if (value === undefined) throw new CliError(`--${name} needs a value`);
192
+ index += 1;
193
+ Object.defineProperty(input, name, {
194
+ value: typedValue(field, value),
195
+ enumerable: true,
196
+ writable: true,
197
+ configurable: true,
198
+ });
199
+ }
200
+ return input;
201
+ }
202
+
203
+ /** One item of `--allow` or `--only`, added to the `box` of an input. */
204
+ function boxItem(input: Record<string, unknown>, mode: "allow" | "only", text: string): void {
205
+ const box = (input["box"] ?? {}) as { allow?: unknown[]; only?: unknown[] };
206
+ const other = mode === "allow" ? "only" : "allow";
207
+ if (box[other] !== undefined) throw new CliError("a box takes --allow or --only, not both");
208
+ const kind = /^(read|write|net):(.+)$/.exec(text);
209
+ const item = kind === null ? text : { [kind[1] as string]: kind[2] };
210
+ input["box"] = { [mode]: [...(box[mode] ?? []), item] };
211
+ }
212
+
213
+ /** The arguments with `--json -` replaced by the JSON read from stdin. */
214
+ export async function withStdinJson(args: string[], readStdin: () => Promise<string>): Promise<string[]> {
215
+ const at = args.findIndex((argument, index) => argument === "--json" && args[index + 1] === "-");
216
+ if (at < 0) return args;
217
+ const copy = [...args];
218
+ copy[at + 1] = await readStdin();
219
+ return copy;
220
+ }
221
+
222
+ /** `timeout-ms` as `timeoutMs`. */
223
+ function camelCase(name: string): string {
224
+ return name.replace(/-([a-z])/g, (_, letter: string) => letter.toUpperCase());
225
+ }
226
+
227
+ /** The JSON of the command line, or a CliError that says what was wrong. */
228
+ function parseJson(text: string): unknown {
229
+ try {
230
+ return JSON.parse(text);
231
+ } catch {
232
+ throw new CliError(`"${text}" is not valid JSON`);
233
+ }
234
+ }
235
+
236
+ /** The types a field may have, from its schema: `type`, or the branches of `anyOf`/`oneOf`. */
237
+ function typesOf(schema: unknown): string[] {
238
+ if (schema === null || typeof schema !== "object") return [];
239
+ const holder = schema as { type?: unknown; anyOf?: unknown; oneOf?: unknown };
240
+ if (typeof holder.type === "string") return [holder.type];
241
+ if (Array.isArray(holder.type)) return holder.type.filter((t): t is string => typeof t === "string");
242
+ const branches = [holder.anyOf, holder.oneOf].flatMap((b) => (Array.isArray(b) ? b : []));
243
+ return branches.flatMap(typesOf);
244
+ }
245
+
246
+ /** A value read from the command line, in the type the schema says. */
247
+ function typedValue(schema: unknown, text: string): unknown {
248
+ const types = typesOf(schema);
249
+ if (types.includes("string")) return text;
250
+ // A field of any type takes JSON when the text is JSON (an object, a list, a number), else the text.
251
+ if (types.length === 0) {
252
+ try {
253
+ return JSON.parse(text);
254
+ } catch {
255
+ return text;
256
+ }
257
+ }
258
+ if (types.includes("integer") || types.includes("number")) {
259
+ const parsed = Number(text);
260
+ const whole = types.includes("integer") && !types.includes("number");
261
+ if (text.trim() === "" || !Number.isFinite(parsed) || (whole && !Number.isInteger(parsed))) {
262
+ throw new CliError(`"${text}" is not ${whole ? "an integer" : "a number"}`);
263
+ }
264
+ return parsed;
265
+ }
266
+ if (types.includes("boolean")) {
267
+ if (text === "true") return true;
268
+ if (text === "false") return false;
269
+ throw new CliError(`"${text}" is not a boolean (true or false)`);
270
+ }
271
+ if (types.includes("null") && text === "null") return null;
272
+ return parseJson(text);
273
+ }
274
+
275
+ /** The name the CLI gives itself. Who it is comes from its token, not from this. */
276
+ const CLI_CLIENT_ID = "cli";
277
+
278
+ /** A failure of the CLI itself: the command line was wrong, or the host was not there. */
279
+ export class CliError extends Error {
280
+ override name = "CliError";
281
+ constructor(message: string, readonly code?: string) {
282
+ super(message);
283
+ }
284
+ }
285
+
286
+ /**
287
+ * Run one command of the CLI.
288
+ *
289
+ * The host is asked what it is, and the command is chosen from that answer: an action name is
290
+ * an action, anything else is a builtin. Nothing here knows the names of the actions.
291
+ *
292
+ * `out` is where the command writes what it prints while it runs: the log prints its records
293
+ * as they come, and the other commands answer at once.
294
+ */
295
+ export async function run(args: CliArgs, out: (text: string) => void): Promise<CliResult> {
296
+ const format: Format = args.json ? "json" : "text";
297
+ let api: NiwaApi;
298
+ try {
299
+ api = await connect({ home: args.home, id: CLI_CLIENT_ID, ...(args.token === undefined ? {} : { token: args.token }) });
300
+ } catch (error) {
301
+ if (!isHostDown(error)) throw error;
302
+ return { output: `no host is serving ${args.home} (start it with "niwa serve <composition>")`, code: HOST_DOWN };
303
+ }
304
+ try {
305
+ if (isBuiltin(args.command)) {
306
+ return await runBuiltin(api, args, out);
307
+ }
308
+ const description = await api.describe();
309
+ const wanted = COMMAND_ALIASES[args.command] ?? args.command;
310
+ const action = description.actions.find((entry) => entry.name === wanted);
311
+ if (action === undefined) {
312
+ throw new CliError(
313
+ `there is no action "${args.command}" and no such command. ` +
314
+ `Run "niwa help" to see what there is.`,
315
+ );
316
+ }
317
+ const result = await runAction(api, action, args, format);
318
+ if (action.name !== STOP_ACTION) return result;
319
+ // The host answers before it closes: the command ends when the journal is free again.
320
+ if (!(await untilDown(args))) {
321
+ return { output: `the host did not stop within ${String(STOP_WAIT_MS / 1000)} s`, code: STOP_TIMEOUT };
322
+ }
323
+ return format === "json" ? result : { output: "stopped", code: 0 };
324
+ } catch (error) {
325
+ if (error instanceof CliError) {
326
+ return { output: error.message, code: 1, errorCode: error.code };
327
+ }
328
+ const message = error instanceof Error ? error.message : String(error);
329
+ const code = error instanceof Error && "code" in error ? String(error.code) : undefined;
330
+ return { output: message, code: 1, errorCode: code };
331
+ } finally {
332
+ await api.close().catch(() => undefined);
333
+ }
334
+ }
335
+
336
+ /** The short commands of the actions a person types most. */
337
+ const COMMAND_ALIASES: Record<string, string> = { status: STATUS_ACTION, stop: STOP_ACTION };
338
+
339
+ /** How long `niwa stop` waits for the host to give the journal back. */
340
+ const STOP_WAIT_MS = 30_000;
341
+
342
+ /** The exit code of a `niwa stop` whose host did not stop in time. */
343
+ export const STOP_TIMEOUT = 4;
344
+
345
+ /** Wait until the host that was asked to stop has let go of the journal; false when it did not in time. */
346
+ async function untilDown(args: CliArgs): Promise<boolean> {
347
+ const deadline = Date.now() + STOP_WAIT_MS;
348
+ while (livingHolderPid(args.home) !== undefined) {
349
+ if (Date.now() >= deadline) return false;
350
+ await Bun.sleep(100);
351
+ }
352
+ return true;
353
+ }
354
+
355
+ /** The exit code of a command that found no host: apart from 1, a command the host refused. */
356
+ export const HOST_DOWN = 3;
357
+
358
+ /** Did the connection fail because nothing listens at the home: no socket, or one nobody holds? */
359
+ function isHostDown(error: unknown): boolean {
360
+ const code = error instanceof Error && "code" in error ? error.code : undefined;
361
+ return code === "ENOENT" || code === "ECONNREFUSED";
362
+ }
363
+
364
+ /** True for the names the CLI itself answers. */
365
+ function isBuiltin(command: string): command is Builtin {
366
+ return (BUILTIN as readonly string[]).includes(command);
367
+ }
368
+
369
+ /**
370
+ * Run one action of the host as a command.
371
+ *
372
+ * The fields come from the action's schema, so the CLI knows nothing about the action. What the
373
+ * action answers with is printed as it is, unless the answer is a list of records: those are
374
+ * printed the way a person reads records.
375
+ */
376
+ async function runAction(
377
+ api: NiwaApi,
378
+ action: ActionDescription,
379
+ args: CliArgs,
380
+ format: Format,
381
+ ): Promise<CliResult> {
382
+ const input = withWorkingDirectory(action.input, inputOf(action, await withStdinJson(args.args, () => Bun.stdin.text())));
383
+ const result = await api.call(action.name, input);
384
+ return { output: renderAnswer(result, format), code: 0 };
385
+ }
386
+
387
+ /**
388
+ * What an action answered with, as it is printed.
389
+ *
390
+ * A list of records is printed the way a person reads records; a list of traced records is
391
+ * printed with the depth each was found at. A description is printed as the list of actions and
392
+ * record types it is. Anything else is printed as the value it is, so the machine form is the
393
+ * value itself.
394
+ */
395
+ export function renderAnswer(value: unknown, format: Format): string {
396
+ if (format === "json") return JSON.stringify(value, null, 2);
397
+ const description = DescriptionOutput.safeParse(value);
398
+ if (description.success) return renderDescription(description.data);
399
+ const status = StatusOutput.safeParse(value);
400
+ if (status.success) return renderStatus(status.data);
401
+ const read = RecordsOutput.safeParse(value);
402
+ if (read.success) return `${renderRecords(read.data.records)}\nnext: ${String(read.data.next)}`;
403
+ const trace = TracedRecordsOutput.safeParse(value);
404
+ if (trace.success) return renderTrace(trace.data);
405
+ const records = RecordList.safeParse(value);
406
+ if (records.success) return renderRecords(records.data);
407
+ return renderValue(value, format);
408
+ }
409
+
410
+ /** Run one of the built-in commands. */
411
+ async function runBuiltin(
412
+ api: NiwaApi,
413
+ args: CliArgs,
414
+ out: (text: string) => void,
415
+ ): Promise<CliResult> {
416
+ switch (args.command) {
417
+ case "help": {
418
+ return { output: await usage(api), code: 0 };
419
+ }
420
+ case "log": {
421
+ try {
422
+ await log(api, args.args, args.json, process.stdout.columns ?? 160, out);
423
+ } catch (error) {
424
+ if (error instanceof LogUsage) throw new CliError(error.message);
425
+ throw error;
426
+ }
427
+ return { output: "", code: 0 };
428
+ }
429
+ case "agent": {
430
+ const done = await runAgentCommand(api, args.args, { env: args.env ?? process.env, cwd: args.cwd ?? process.cwd() });
431
+ if (!done.ok) throw new CliError(done.reason);
432
+ return { output: args.json ? JSON.stringify(done.answer, null, 2) : done.answer.briefing, code: 0 };
433
+ }
434
+ default:
435
+ throw new CliError(`there is no command "${args.command}"`);
436
+ }
437
+ }
438
+
439
+ /**
440
+ * What the CLI says when it is asked what it can do.
441
+ *
442
+ * The commands are the actions the host declares, so the list is read from the host: the CLI
443
+ * keeps no list of its own. Without a host there is no list to show, and the usage says so.
444
+ */
445
+ export async function usage(api?: NiwaApi): Promise<string> {
446
+ const description = api === undefined ? undefined : await api.describe();
447
+ const commands =
448
+ description === undefined
449
+ ? [
450
+ ` ${LOG_USAGE}`,
451
+ ` ${SKILL_USAGE}`,
452
+ " niwa help what niwa is: its actions and its record types",
453
+ ]
454
+ : [
455
+ ...description.actions.map((action) => ` ${commandLine(action)}`),
456
+ " niwa status whether the host is up, and what its plugins hold",
457
+ " niwa stop stop the host gracefully",
458
+ " niwa web [--port N] the web cockpit of the host: prints its address and login link",
459
+ " niwa mcp the MCP server of the host, over stdio",
460
+ " niwa serve [-d] <composition.ts> run a host from a file that exports plugins; -d in the background",
461
+ ` ${AGENT_USAGE}`,
462
+ " attach the native session this runs in to an agent (the default one without a name) and print its briefing",
463
+ ` ${LOG_USAGE}`,
464
+ ` ${SKILL_USAGE}`,
465
+ " niwa help what niwa is: its actions and its record types",
466
+ ];
467
+ return [
468
+ "usage: niwa [--home <dir>] <command> [--field value ...]",
469
+ "",
470
+ description === undefined
471
+ ? "No host answers at this home, so its actions are not listed. The commands niwa has of its own:"
472
+ : "The commands are the actions the host declares:",
473
+ "",
474
+ ...commands,
475
+ "",
476
+ "The home of the host: --home, else NIWA_HOME, else ~/.niwa.",
477
+ "--json, before the command, asks for the machine form.",
478
+ "--field value gives one field of the action; after the command, --json '{...}' (or --json - for stdin)",
479
+ "gives the whole input as JSON.",
480
+ "An action that takes a box (proc.run, session.start) takes --allow <item> to add to the host's default and",
481
+ "--only <item> to replace it, once per item: a profile (bun), project, toolchains, read:<path>, write:<path>, net:<host>.",
482
+ "workflow.start runs a script now; workflow.install subscribes one: niwa then starts a run for every matching record.",
483
+ ].join("\n");
484
+ }
485
+
486
+ /** The usage for a run with no command: the host's own list when a host answers, else the part niwa knows. */
487
+ export async function usageAt(home: string, token?: Token): Promise<string> {
488
+ try {
489
+ const api = await connect({ home, id: CLI_CLIENT_ID, ...(token === undefined ? {} : { token }) });
490
+ try {
491
+ return await usage(api);
492
+ } finally {
493
+ await api.close().catch(() => undefined);
494
+ }
495
+ } catch {
496
+ return usage();
497
+ }
498
+ }
499
+
500
+ /**
501
+ * One command, as a person reads it: the action, and the fields it takes.
502
+ *
503
+ * The fields come from the action's own schema, so the line is true whatever the action is.
504
+ */
505
+ function commandLine(action: ActionDescription): string {
506
+ const fields = fieldsOf(action.input);
507
+ const shown = fields.length === 0 ? "" : ` --${fields.join(" --")}`;
508
+ return `${action.name}${shown}`;
509
+ }
510
+
package/src/insert.ts ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * insert.ts — `niwa insert report`: the command an insert reports through.
3
+ *
4
+ * An insert runs inside a harness (a hook of Claude Code, an extension of pi) and is no client of
5
+ * the host. It runs this command and gives one event, as JSON, on stdin. The command connects to
6
+ * the host at the home and calls the action `insert.report`; the host writes the record.
7
+ *
8
+ * The command connects without a token on purpose: the hooks of a harness report without one
9
+ * (the `default` profile may call `insert.report`), and the `NIWA_ID` a session carries in its
10
+ * environment must not make the report a call of that session.
11
+ *
12
+ * echo '{"kind":"compacted","session":{"harness":"pi","native":"s1"}}' | niwa insert report
13
+ *
14
+ * Exit codes: 0 reported, 1 the host refused or is not there, 2 the command line or the event is
15
+ * not usable.
16
+ */
17
+
18
+ import { connect } from "@niwa-labs/client";
19
+ import { actionName } from "@niwa-labs/core";
20
+ import type { CliResult } from "./index.ts";
21
+
22
+ /**
23
+ * The name of the action the command calls: the one the harness module declares as
24
+ * `INSERT_REPORT_ACTION`. The CLI is a client and imports no harness, so the name is written here too.
25
+ */
26
+ export const INSERT_REPORT = "insert.report";
27
+
28
+ /** What the command says of itself. */
29
+ export const INSERT_USAGE = "usage: niwa insert report (the event as JSON on stdin)";
30
+
31
+ /** Where the event comes from: stdin, unless a test says otherwise. */
32
+ export type EventSource = () => Promise<string>;
33
+
34
+ /** Run `niwa insert <args>` against the host at `home`. */
35
+ export async function runInsert(
36
+ args: readonly string[],
37
+ home: string,
38
+ readEvent: EventSource = () => Bun.stdin.text(),
39
+ ): Promise<CliResult> {
40
+ if (args[0] !== "report" || args.length !== 1) return { output: INSERT_USAGE, code: 2 };
41
+
42
+ let event: unknown;
43
+ try {
44
+ event = JSON.parse(await readEvent());
45
+ } catch (error) {
46
+ return { output: `niwa insert report: the event on stdin is not JSON: ${String(error)}`, code: 2 };
47
+ }
48
+ if (event === null || typeof event !== "object" || Array.isArray(event)) {
49
+ return { output: "niwa insert report: the event on stdin must be a JSON object", code: 2 };
50
+ }
51
+
52
+ let api: Awaited<ReturnType<typeof connect>> | undefined;
53
+ try {
54
+ api = await connect({ home, id: "insert-report" });
55
+ await api.call(actionName(INSERT_REPORT), event as never);
56
+ return { output: "", code: 0 };
57
+ } catch (error) {
58
+ const code = error instanceof Error && "code" in error ? String(error.code) : undefined;
59
+ return {
60
+ output: `niwa insert report: ${error instanceof Error ? error.message : String(error)}`,
61
+ code: 1,
62
+ ...(code === undefined ? {} : { errorCode: code }),
63
+ };
64
+ } finally {
65
+ await api?.close().catch(() => {});
66
+ }
67
+ }