@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/LICENSE +21 -0
- package/README.md +10 -2
- package/package.json +15 -4
- package/src/agent.ts +144 -0
- package/src/index.ts +510 -0
- package/src/insert.ts +67 -0
- package/src/log.ts +203 -0
- package/src/render.ts +172 -0
- package/src/skill/SKILL.md +190 -0
- package/src/skill/command.ts +181 -0
- package/src/skill/install.ts +121 -0
- package/test/agent-attach.test.ts +21 -0
- package/test/cli-answers.test.ts +68 -0
- package/test/fixtures/command.ts +27 -0
- package/test/input-flags.test.ts +76 -0
- package/test/stream.test.ts +55 -0
- package/tsconfig.json +6 -0
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* command.ts — `niwa skill`: print the skill niwa ships, and install it for the agents that read it.
|
|
3
|
+
*
|
|
4
|
+
* Nothing here talks to a host: the skill is a file of niwa's own, so these commands work with
|
|
5
|
+
* no host up. Where each kind of harness reads skills from is declared by the kind
|
|
6
|
+
* (its skill roots); this command only asks, and is given the list of kinds by
|
|
7
|
+
* whoever runs it: a client knows no harness.
|
|
8
|
+
*
|
|
9
|
+
* niwa skill print the text
|
|
10
|
+
* niwa skill install --harness <kind>[,<kind>...]|all [--project [<dir>]] [--dry-run] [--force]
|
|
11
|
+
* niwa skill status [--harness ...] [--project [<dir>]]
|
|
12
|
+
* niwa skill uninstall --harness ... [--project [<dir>]] [--dry-run] [--force]
|
|
13
|
+
*
|
|
14
|
+
* Kinds that read the same directory give one file: the paths are deduplicated.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { resolve } from "node:path";
|
|
18
|
+
|
|
19
|
+
import { installSkill, skillFile, skillText, stateOf, uninstallSkill } from "./install.ts";
|
|
20
|
+
import type { CliResult } from "../index.ts";
|
|
21
|
+
|
|
22
|
+
export const SKILL_USAGE =
|
|
23
|
+
"niwa skill [install|status|uninstall] --harness <kind>[,<kind>...]|all [--project [<dir>]] [--dry-run] [--force]";
|
|
24
|
+
|
|
25
|
+
/** The directories of skills a kind reads: the user's (given the home of the user), and the project's (relative to the project). */
|
|
26
|
+
export interface SkillRoots {
|
|
27
|
+
readonly user: (home: string) => string;
|
|
28
|
+
readonly project: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A kind of harness that reads skills, and where. */
|
|
32
|
+
export interface SkillKind {
|
|
33
|
+
readonly kind: string;
|
|
34
|
+
readonly roots: SkillRoots;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Where a run of the command is: the home of the user and the working directory. */
|
|
38
|
+
export interface SkillContext {
|
|
39
|
+
readonly home: string;
|
|
40
|
+
readonly cwd: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
interface Options {
|
|
44
|
+
readonly kinds: readonly string[] | undefined;
|
|
45
|
+
readonly project: string | undefined;
|
|
46
|
+
readonly dryRun: boolean;
|
|
47
|
+
readonly force: boolean;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** One directory of skills, and the kinds that read it. */
|
|
51
|
+
interface Target {
|
|
52
|
+
readonly file: string;
|
|
53
|
+
readonly kinds: string[];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Run `niwa skill ...`: `args` is what follows the word `skill`, `kinds` the kinds that read skills. */
|
|
57
|
+
export function runSkill(args: readonly string[], context: SkillContext, kinds: readonly SkillKind[]): CliResult {
|
|
58
|
+
const [sub, ...rest] = args;
|
|
59
|
+
if (sub === undefined) return { output: skillText().trimEnd(), code: 0 };
|
|
60
|
+
if (sub !== "install" && sub !== "status" && sub !== "uninstall") {
|
|
61
|
+
return fail(`there is no "niwa skill ${sub}"; usage: ${SKILL_USAGE}`);
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
const options = optionsOf(rest, context, kinds);
|
|
65
|
+
if (options.kinds === undefined && sub !== "status") {
|
|
66
|
+
return fail(`niwa skill ${sub} needs --harness <kind>[,<kind>...]|all; kinds: ${knownKinds(kinds)}`);
|
|
67
|
+
}
|
|
68
|
+
const targets = targetsOf(options, context, kinds);
|
|
69
|
+
return sub === "status" ? status(targets) : sub === "install" ? install(targets, options) : uninstall(targets, options);
|
|
70
|
+
} catch (error) {
|
|
71
|
+
if (error instanceof SkillUsageError) return fail(error.message);
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
class SkillUsageError extends Error {
|
|
77
|
+
override name = "SkillUsageError";
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function fail(message: string): CliResult {
|
|
81
|
+
return { output: message, code: 1 };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function knownKinds(kinds: readonly SkillKind[]): string {
|
|
85
|
+
return kinds.map((entry) => entry.kind).join(", ");
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function optionsOf(args: readonly string[], context: SkillContext, known: readonly SkillKind[]): Options {
|
|
89
|
+
let kinds: string[] | undefined;
|
|
90
|
+
let project: string | undefined;
|
|
91
|
+
let dryRun = false;
|
|
92
|
+
let force = false;
|
|
93
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
94
|
+
const argument = args[index];
|
|
95
|
+
if (argument === "--harness") {
|
|
96
|
+
const value = args[index + 1];
|
|
97
|
+
if (value === undefined || value.startsWith("--")) throw new SkillUsageError("--harness needs a kind, a list of kinds, or all");
|
|
98
|
+
index += 1;
|
|
99
|
+
kinds = kindsOf(value, known);
|
|
100
|
+
} else if (argument === "--project") {
|
|
101
|
+
const value = args[index + 1];
|
|
102
|
+
if (value !== undefined && !value.startsWith("--")) {
|
|
103
|
+
index += 1;
|
|
104
|
+
project = resolve(context.cwd, value);
|
|
105
|
+
} else {
|
|
106
|
+
project = context.cwd;
|
|
107
|
+
}
|
|
108
|
+
} else if (argument === "--dry-run") {
|
|
109
|
+
dryRun = true;
|
|
110
|
+
} else if (argument === "--force") {
|
|
111
|
+
force = true;
|
|
112
|
+
} else {
|
|
113
|
+
throw new SkillUsageError(`unexpected argument "${String(argument)}"; usage: ${SKILL_USAGE}`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return { kinds, project, dryRun, force };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** The kinds a `--harness` value names: `all`, or a list; one that reads no skills is refused. */
|
|
120
|
+
function kindsOf(value: string, known: readonly SkillKind[]): string[] {
|
|
121
|
+
const named = value.split(",").map((kind) => kind.trim()).filter((kind) => kind !== "");
|
|
122
|
+
if (named.length === 0) throw new SkillUsageError("--harness needs a kind, a list of kinds, or all");
|
|
123
|
+
if (named.includes("all")) return known.map((entry) => entry.kind);
|
|
124
|
+
for (const kind of named) {
|
|
125
|
+
if (!known.some((entry) => entry.kind === kind)) {
|
|
126
|
+
throw new SkillUsageError(
|
|
127
|
+
`no skill root is declared for the harness kind "${kind}"; kinds with one: ${knownKinds(known)}. ` +
|
|
128
|
+
`Paste the output of "niwa skill" into its instructions instead.`,
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return named;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** The files the options name, one per directory, with the kinds that read it. */
|
|
136
|
+
function targetsOf(options: Options, context: SkillContext, known: readonly SkillKind[]): Target[] {
|
|
137
|
+
const wanted = options.kinds ?? known.map((entry) => entry.kind);
|
|
138
|
+
const byFile = new Map<string, Target>();
|
|
139
|
+
for (const entry of known) {
|
|
140
|
+
if (!wanted.includes(entry.kind)) continue;
|
|
141
|
+
const root = options.project === undefined ? entry.roots.user(context.home) : resolve(options.project, entry.roots.project);
|
|
142
|
+
const file = skillFile(root);
|
|
143
|
+
const existing = byFile.get(file);
|
|
144
|
+
if (existing === undefined) byFile.set(file, { file, kinds: [entry.kind] });
|
|
145
|
+
else existing.kinds.push(entry.kind);
|
|
146
|
+
}
|
|
147
|
+
return [...byFile.values()];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function status(targets: readonly Target[]): CliResult {
|
|
151
|
+
const lines = targets.map((target) => `${stateOf(target.file)} ${target.file} (${target.kinds.join(", ")})`);
|
|
152
|
+
return { output: lines.join("\n"), code: 0 };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function install(targets: readonly Target[], options: Options): CliResult {
|
|
156
|
+
let code = 0;
|
|
157
|
+
const lines = targets.map((target) => {
|
|
158
|
+
const outcome = installSkill(target.file, options);
|
|
159
|
+
if (outcome === "skipped") {
|
|
160
|
+
code = 1;
|
|
161
|
+
return `skipped ${target.file}: edited by hand; --force overwrites it`;
|
|
162
|
+
}
|
|
163
|
+
if (outcome === "unchanged") return `unchanged ${target.file}`;
|
|
164
|
+
return options.dryRun ? `would write ${target.file}` : target.file;
|
|
165
|
+
});
|
|
166
|
+
return { output: lines.join("\n"), code };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function uninstall(targets: readonly Target[], options: Options): CliResult {
|
|
170
|
+
let code = 0;
|
|
171
|
+
const lines = targets.map((target) => {
|
|
172
|
+
const outcome = uninstallSkill(target.file, options);
|
|
173
|
+
if (outcome === "skipped") {
|
|
174
|
+
code = 1;
|
|
175
|
+
return `skipped ${target.file}: edited by hand; --force removes it`;
|
|
176
|
+
}
|
|
177
|
+
if (outcome === "absent") return `absent ${target.file}`;
|
|
178
|
+
return `${options.dryRun ? "would remove" : "removed"} ${target.file}`;
|
|
179
|
+
});
|
|
180
|
+
return { output: lines.join("\n"), code };
|
|
181
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The skill niwa ships for the agents that use it: the text, its stamp, and putting it on disk.
|
|
3
|
+
*
|
|
4
|
+
* The text is `SKILL.md` beside this file. A file niwa installs ends with a stamp line,
|
|
5
|
+
* `<!-- niwa skill <version> <sha> -->`, where the sha is that of the text above it. The stamp
|
|
6
|
+
* says whether a file on disk is niwa's current text, an older text of niwa's, or something a
|
|
7
|
+
* person edited: niwa overwrites the first two and leaves the third alone unless it is forced.
|
|
8
|
+
*
|
|
9
|
+
* This module knows nothing of harnesses: it is given the directories of skills.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, rmdirSync, writeFileSync } from "node:fs";
|
|
14
|
+
import { dirname, join } from "node:path";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The version of the package this skill ships in: read from the `package.json` that sits two
|
|
18
|
+
* directories above this file, by path, so the skill depends on no import of it.
|
|
19
|
+
*/
|
|
20
|
+
function versionOfPackage(): string {
|
|
21
|
+
const manifest: unknown = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
|
|
22
|
+
const version = manifest !== null && typeof manifest === "object" ? (manifest as { version?: unknown }).version : undefined;
|
|
23
|
+
if (typeof version !== "string") throw new Error("package.json has no version: the skill cannot be stamped");
|
|
24
|
+
return version;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const VERSION = versionOfPackage();
|
|
28
|
+
|
|
29
|
+
/** The name of the skill: its directory under a skills root. */
|
|
30
|
+
export const SKILL_NAME = "niwa";
|
|
31
|
+
|
|
32
|
+
/** The text of the skill, as it ships: one trailing newline. */
|
|
33
|
+
export function skillText(): string {
|
|
34
|
+
const text = readFileSync(new URL("./SKILL.md", import.meta.url), "utf8");
|
|
35
|
+
return `${text.trimEnd()}\n`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The stamp of a text: the version of niwa and a short hash of the text. */
|
|
39
|
+
function stampOf(text: string): string {
|
|
40
|
+
return `<!-- niwa skill ${VERSION} ${shaOf(text)} -->`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function shaOf(text: string): string {
|
|
44
|
+
return createHash("sha256").update(text).digest("hex").slice(0, 16);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The file niwa installs: the text, then its stamp as the last line. */
|
|
48
|
+
export function installedText(): string {
|
|
49
|
+
const text = skillText();
|
|
50
|
+
return `${text}${stampOf(text)}\n`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The file of the skill under a skills root. */
|
|
54
|
+
export function skillFile(root: string): string {
|
|
55
|
+
return join(root, SKILL_NAME, "SKILL.md");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* How a skill file stands.
|
|
60
|
+
*
|
|
61
|
+
* - `absent`: there is no file;
|
|
62
|
+
* - `current`: niwa's own, of the text this niwa ships;
|
|
63
|
+
* - `stale`: niwa's own, of another text (an older niwa);
|
|
64
|
+
* - `modified`: not as niwa wrote it: edited by hand, or never niwa's (no stamp, or a stamp that
|
|
65
|
+
* does not match the text above it).
|
|
66
|
+
*/
|
|
67
|
+
export type SkillState = "absent" | "current" | "stale" | "modified";
|
|
68
|
+
|
|
69
|
+
const STAMP = /^<!-- niwa skill (\S+) ([0-9a-f]{16}) -->$/;
|
|
70
|
+
|
|
71
|
+
/** How the file at `path` stands. */
|
|
72
|
+
export function stateOf(path: string): SkillState {
|
|
73
|
+
if (!existsSync(path)) return "absent";
|
|
74
|
+
const content = readFileSync(path, "utf8").trimEnd();
|
|
75
|
+
const cut = content.lastIndexOf("\n");
|
|
76
|
+
const match = STAMP.exec(content.slice(cut + 1));
|
|
77
|
+
if (match === null || cut === -1) return "modified";
|
|
78
|
+
const text = `${content.slice(0, cut).trimEnd()}\n`;
|
|
79
|
+
if (shaOf(text) !== match[2]) return "modified";
|
|
80
|
+
return content === installedText().trimEnd() ? "current" : "stale";
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** What putting the skill at a path did, or would do. */
|
|
84
|
+
export type InstallOutcome = "written" | "unchanged" | "skipped";
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Put the skill at `path`: an absent or niwa's own file is written (a current one is left as it
|
|
88
|
+
* is), an edited one is written only when forced. With `dryRun` nothing is touched.
|
|
89
|
+
*/
|
|
90
|
+
export function installSkill(path: string, opts: { force: boolean; dryRun: boolean }): InstallOutcome {
|
|
91
|
+
const state = stateOf(path);
|
|
92
|
+
if (state === "current") return "unchanged";
|
|
93
|
+
if (state === "modified" && !opts.force) return "skipped";
|
|
94
|
+
if (!opts.dryRun) {
|
|
95
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
96
|
+
writeFileSync(path, installedText());
|
|
97
|
+
}
|
|
98
|
+
return "written";
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** What taking the skill away at a path did, or would do. */
|
|
102
|
+
export type UninstallOutcome = "removed" | "absent" | "skipped";
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Take the skill away at `path`, and its directory when that is then empty. An edited file goes
|
|
106
|
+
* only when forced.
|
|
107
|
+
*/
|
|
108
|
+
export function uninstallSkill(path: string, opts: { force: boolean; dryRun: boolean }): UninstallOutcome {
|
|
109
|
+
const state = stateOf(path);
|
|
110
|
+
if (state === "absent") return "absent";
|
|
111
|
+
if (state === "modified" && !opts.force) return "skipped";
|
|
112
|
+
if (!opts.dryRun) {
|
|
113
|
+
rmSync(path);
|
|
114
|
+
try {
|
|
115
|
+
rmdirSync(dirname(path));
|
|
116
|
+
} catch {
|
|
117
|
+
// The directory holds something else: it is not niwa's to remove.
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return "removed";
|
|
121
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// Which native session runs `niwa agent attach`: read from the environment its harness gives the command.
|
|
2
|
+
|
|
3
|
+
import { expect, test } from "bun:test";
|
|
4
|
+
|
|
5
|
+
import { callerSession } from "../src/agent.ts";
|
|
6
|
+
|
|
7
|
+
test("ZCode is told first, as it also sets the variables of Claude Code", () => {
|
|
8
|
+
expect(callerSession({ ZCODE_SESSION_ID: "z-1", CLAUDE_CODE_SESSION_ID: "z-1", CLAUDE_PID: "12" })).toEqual({ kind: "zcode", native: "z-1", from: "ZCODE_SESSION_ID" });
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
test("Codex, pi and Claude Code are told by their own variables", () => {
|
|
12
|
+
expect(callerSession({ CODEX_THREAD_ID: "c-1" })).toEqual({ kind: "codex", native: "c-1", from: "CODEX_THREAD_ID" });
|
|
13
|
+
expect(callerSession({ PI_SESSION_ID: "p-1" })).toEqual({ kind: "pi", native: "p-1", from: "PI_SESSION_ID" });
|
|
14
|
+
expect(callerSession({ CLAUDE_CODE_SESSION_ID: "cc-1", CLAUDE_PID: "4242" })).toEqual({ kind: "claude-code", native: "cc-1", from: "CLAUDE_CODE_SESSION_ID", pid: 4242 });
|
|
15
|
+
expect(callerSession({ CLAUDE_CODE_SESSION_ID: "cc-1", CLAUDE_PID: "not a pid" })).toEqual({ kind: "claude-code", native: "cc-1", from: "CLAUDE_CODE_SESSION_ID" });
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
test("no variable, or an empty one, tells nothing", () => {
|
|
19
|
+
expect(callerSession({})).toBeUndefined();
|
|
20
|
+
expect(callerSession({ CODEX_THREAD_ID: " " })).toBeUndefined();
|
|
21
|
+
});
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// How the CLI reads what a host answered: by the schemas the host answers with, not by guards of its own.
|
|
2
|
+
|
|
3
|
+
import { expect, test } from "bun:test";
|
|
4
|
+
|
|
5
|
+
import { renderAnswer } from "@niwa-labs/cli";
|
|
6
|
+
|
|
7
|
+
const RECORD = {
|
|
8
|
+
id: "r1",
|
|
9
|
+
seq: 7,
|
|
10
|
+
stream: "main",
|
|
11
|
+
type: "note.written",
|
|
12
|
+
schema: 1,
|
|
13
|
+
data: { text: "hello" },
|
|
14
|
+
actor: { kind: "host" },
|
|
15
|
+
cause: null,
|
|
16
|
+
root: "r1",
|
|
17
|
+
at: 1,
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
test("a read of records is printed as records, with the position to read after", () => {
|
|
21
|
+
const out = renderAnswer({ records: [RECORD], next: 7 }, "text");
|
|
22
|
+
expect(out).toContain("note.written");
|
|
23
|
+
expect(out).toContain("next: 7");
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test("a trace is printed with the depth of each record", () => {
|
|
27
|
+
const shallow = renderAnswer([{ ...RECORD, depth: 0 }], "text");
|
|
28
|
+
const deep = renderAnswer([{ ...RECORD, depth: 2 }], "text");
|
|
29
|
+
expect(deep).toBe(` ${shallow}`);
|
|
30
|
+
expect(deep).toContain("note.written");
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("a list of records without a depth is printed as records", () => {
|
|
34
|
+
const out = renderAnswer([RECORD], "text");
|
|
35
|
+
expect(out).toContain("note.written");
|
|
36
|
+
expect(out).not.toContain("next:");
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test("a value that only looks like a read is printed as the value it is", () => {
|
|
40
|
+
const looksLikeRead = { records: [{ id: "r1", seq: "seven", type: 3 }], next: 1 };
|
|
41
|
+
const out = renderAnswer(looksLikeRead, "text");
|
|
42
|
+
expect(out).toBe("records: id: r1\nseq: seven\ntype: 3\nnext: 1");
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("a value that only looks like a description is printed as the value it is", () => {
|
|
46
|
+
const out = renderAnswer({ actions: ["a"], types: ["b"] }, "text");
|
|
47
|
+
expect(out).toBe("actions: a\ntypes: b");
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test("a description is printed as the list of actions and types", () => {
|
|
51
|
+
const description = {
|
|
52
|
+
actions: [
|
|
53
|
+
{
|
|
54
|
+
name: "note.add",
|
|
55
|
+
description: "Adds a note.",
|
|
56
|
+
recovery: "repeat",
|
|
57
|
+
effect: "write",
|
|
58
|
+
input: { type: "object", properties: { text: { type: "string" } }, required: ["text"] },
|
|
59
|
+
output: { type: "object" },
|
|
60
|
+
},
|
|
61
|
+
],
|
|
62
|
+
types: [{ name: "note.written", version: 1, schema: { type: "object" } }],
|
|
63
|
+
};
|
|
64
|
+
const out = renderAnswer(description, "text");
|
|
65
|
+
expect(out).toContain("note.add");
|
|
66
|
+
expect(out).toContain("text: string");
|
|
67
|
+
expect(out).toContain("note.written (v1)");
|
|
68
|
+
});
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// The command line as a process: `bun command.ts [--home <dir>] [--json] <command> [args...]`.
|
|
2
|
+
//
|
|
3
|
+
// It runs the commands that are actions on a host, the same way a person's shell does, so a test
|
|
4
|
+
// can follow a host from outside it.
|
|
5
|
+
|
|
6
|
+
import { tokenOf } from "@niwa-labs/client";
|
|
7
|
+
|
|
8
|
+
import { homeOf, run } from "../../src/index.ts";
|
|
9
|
+
|
|
10
|
+
const argv = process.argv.slice(2);
|
|
11
|
+
const flags: string[] = [];
|
|
12
|
+
while (argv[0] === "--json" || argv[0] === "--home" || argv[0]?.startsWith("--home=")) {
|
|
13
|
+
const flag = argv.shift() ?? "";
|
|
14
|
+
flags.push(flag);
|
|
15
|
+
if (flag === "--home") flags.push(argv.shift() ?? "");
|
|
16
|
+
}
|
|
17
|
+
const [command = "", ...args] = argv;
|
|
18
|
+
|
|
19
|
+
const home = homeOf(flags, process.env);
|
|
20
|
+
const token = tokenOf(home);
|
|
21
|
+
const result = await run(
|
|
22
|
+
{ home, ...(token === undefined ? {} : { token }), command, args, json: flags.includes("--json") },
|
|
23
|
+
(text) => console.log(text),
|
|
24
|
+
);
|
|
25
|
+
if (result.code !== 0) console.error(result.output);
|
|
26
|
+
else if (result.output !== "") console.log(result.output);
|
|
27
|
+
process.exit(result.code);
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// How the command line gives the input of an action: every `--field` is the field of that name,
|
|
2
|
+
// and `--json` is the whole input at once.
|
|
3
|
+
|
|
4
|
+
import { expect, test } from "bun:test";
|
|
5
|
+
|
|
6
|
+
import { inputOf, withStdinJson } from "@niwa-labs/cli";
|
|
7
|
+
import type { ActionDescription } from "@niwa-labs/core";
|
|
8
|
+
|
|
9
|
+
/** An action whose input has a field called `input`, as request.ask does. */
|
|
10
|
+
const ASKING = {
|
|
11
|
+
name: "demo.ask",
|
|
12
|
+
description: "Asks.",
|
|
13
|
+
recovery: "repeat",
|
|
14
|
+
effect: "write",
|
|
15
|
+
input: {
|
|
16
|
+
type: "object",
|
|
17
|
+
properties: { question: { type: "string" }, input: { type: "object" }, to: { type: "object" } },
|
|
18
|
+
},
|
|
19
|
+
output: { type: "object" },
|
|
20
|
+
} as unknown as ActionDescription;
|
|
21
|
+
|
|
22
|
+
test("a field named input is given as --input, like any other field", () => {
|
|
23
|
+
expect(inputOf(ASKING, ["--question", "q", "--input", '{"kind":"confirm"}'])).toEqual({
|
|
24
|
+
question: "q",
|
|
25
|
+
input: { kind: "confirm" },
|
|
26
|
+
});
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test("--json gives the whole input, and a field flag wins over it", () => {
|
|
30
|
+
const whole = '{"question":"a","input":{"kind":"text"},"to":{"kind":"owner"}}';
|
|
31
|
+
expect(inputOf(ASKING, ["--json", whole, "--question", "b"])).toEqual({
|
|
32
|
+
question: "b",
|
|
33
|
+
input: { kind: "text" },
|
|
34
|
+
to: { kind: "owner" },
|
|
35
|
+
});
|
|
36
|
+
expect(() => inputOf(ASKING, ["--json", "[1]"])).toThrow("--json must hold an object");
|
|
37
|
+
expect(() => inputOf(ASKING, ["--json"])).toThrow("--json needs the JSON");
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("an action without a field input points to --json", () => {
|
|
41
|
+
const plain = { ...ASKING, input: { type: "object", properties: { text: { type: "string" } } } } as unknown as ActionDescription;
|
|
42
|
+
expect(() => inputOf(plain, ["--input", "{}"])).toThrow(/--json/);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("--json - reads the whole input from stdin", async () => {
|
|
46
|
+
const args = await withStdinJson(["--question", "q", "--json", "-"], async () => '{"to":{"kind":"owner"}}');
|
|
47
|
+
expect(inputOf(ASKING, args)).toEqual({ question: "q", to: { kind: "owner" } });
|
|
48
|
+
// Arguments with no `-` are left alone, and stdin is not read.
|
|
49
|
+
expect(
|
|
50
|
+
await withStdinJson(["--question", "q"], async () => {
|
|
51
|
+
throw new Error("stdin was read");
|
|
52
|
+
}),
|
|
53
|
+
).toEqual(["--question", "q"]);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
/** An action that takes a box, as proc.run and session.start do. */
|
|
57
|
+
const BOXED = {
|
|
58
|
+
name: "demo.run",
|
|
59
|
+
description: "Runs.",
|
|
60
|
+
recovery: "do-not-repeat",
|
|
61
|
+
effect: "write",
|
|
62
|
+
input: { type: "object", properties: { cwd: { type: "string" }, box: { type: "object" } } },
|
|
63
|
+
output: { type: "object" },
|
|
64
|
+
} as unknown as ActionDescription;
|
|
65
|
+
|
|
66
|
+
test("--allow and --only give the items of an action's box, a mode and a place or a name each", () => {
|
|
67
|
+
expect(inputOf(BOXED, ["--cwd", "/w", "--allow", "bun", "--allow", "write:../artifacts", "--allow", "net:crates.io"])).toEqual({
|
|
68
|
+
cwd: "/w",
|
|
69
|
+
box: { allow: ["bun", { write: "../artifacts" }, { net: "crates.io" }] },
|
|
70
|
+
});
|
|
71
|
+
expect(inputOf(BOXED, ["--only", "read:."])).toEqual({ box: { only: [{ read: "." }] } });
|
|
72
|
+
expect(() => inputOf(BOXED, ["--allow", "bun", "--only", "read:."])).toThrow("not both");
|
|
73
|
+
expect(() => inputOf(BOXED, ["--allow"])).toThrow("needs an item");
|
|
74
|
+
// An action without a box has no such flags.
|
|
75
|
+
expect(() => inputOf(ASKING, ["--allow", "bun"])).toThrow('no field "allow"');
|
|
76
|
+
});
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// The command line follows one stream of a running host: `niwa log -f --json --stream`.
|
|
2
|
+
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
import { expect, test } from "bun:test";
|
|
6
|
+
|
|
7
|
+
import { record } from "@niwa-labs/core";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import { createNiwa, plugin, tempHome, connectAsOwner } from "@niwa-labs/testing";
|
|
10
|
+
|
|
11
|
+
const Note = record("stream.note", z.object({ n: z.number() }), { open: true });
|
|
12
|
+
const Other = record("stream.other", z.object({ text: z.string() }), { open: true });
|
|
13
|
+
|
|
14
|
+
const COMMAND = join(import.meta.dir, "fixtures", "command.ts");
|
|
15
|
+
|
|
16
|
+
test("the CLI follows one stream", async () => {
|
|
17
|
+
const home = await tempHome();
|
|
18
|
+
const niwa = createNiwa({ home: home.path });
|
|
19
|
+
niwa.use(
|
|
20
|
+
plugin("stream", (api) => {
|
|
21
|
+
api.declare(Note, Other);
|
|
22
|
+
}),
|
|
23
|
+
);
|
|
24
|
+
await niwa.serve();
|
|
25
|
+
const writer = await connectAsOwner(home.path);
|
|
26
|
+
let follower: ReturnType<typeof Bun.spawn> | undefined;
|
|
27
|
+
|
|
28
|
+
try {
|
|
29
|
+
const note = await writer.emit(Note, { n: 1 });
|
|
30
|
+
await writer.emit(Other, { text: "not-in-this-stream" });
|
|
31
|
+
|
|
32
|
+
follower = Bun.spawn(
|
|
33
|
+
[process.execPath, COMMAND, "--home", home.path, "log", "-f", "--json", "--stream", String(note.stream)],
|
|
34
|
+
{ stdout: "pipe", stderr: "pipe", env: process.env },
|
|
35
|
+
);
|
|
36
|
+
const reader = (follower.stdout as ReadableStream<Uint8Array>).getReader();
|
|
37
|
+
const decoder = new TextDecoder();
|
|
38
|
+
let seen = "";
|
|
39
|
+
while (!seen.includes("\"n\":1")) {
|
|
40
|
+
const { done, value } = await reader.read();
|
|
41
|
+
if (done) break;
|
|
42
|
+
seen += decoder.decode(value);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// The stream it was asked for, and not the other one.
|
|
46
|
+
expect(seen).toContain("stream.note");
|
|
47
|
+
expect(seen).not.toContain("not-in-this-stream");
|
|
48
|
+
} finally {
|
|
49
|
+
follower?.kill("SIGKILL");
|
|
50
|
+
await follower?.exited;
|
|
51
|
+
await writer.close();
|
|
52
|
+
await niwa.close();
|
|
53
|
+
await home.cleanup();
|
|
54
|
+
}
|
|
55
|
+
}, 40_000);
|