@niwa-labs/harness 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 +12 -2
- package/package.json +12 -4
- package/src/bundled.ts +61 -0
- package/src/capabilities.ts +267 -0
- package/src/conformance/control.ts +375 -0
- package/src/conformance/fixtures.ts +44 -0
- package/src/conformance/insert.ts +136 -0
- package/src/conformance/profile.ts +93 -0
- package/src/conformance/reading.ts +339 -0
- package/src/control.ts +448 -0
- package/src/declaration.ts +224 -0
- package/src/delivery.ts +75 -0
- package/src/discover.ts +291 -0
- package/src/index.ts +560 -0
- package/src/insert-report.ts +72 -0
- package/src/insert.ts +171 -0
- package/src/instance.ts +66 -0
- package/src/options.ts +83 -0
- package/src/reading.ts +415 -0
- package/src/reverse.ts +32 -0
- package/src/skills.ts +32 -0
- package/src/tools.ts +106 -0
- package/test/conformance.test.ts +512 -0
- package/test/declaration.test.ts +271 -0
- package/test/delivery.test.ts +30 -0
- package/test/life-event.test.ts +11 -0
- package/test/profile-conformance.test.ts +20 -0
- package/test/record-fields.test.ts +57 -0
- package/test/session-mode.test.ts +39 -0
- package/test/title.test.ts +38 -0
- package/test/tools-mode.test.ts +107 -0
- package/test/tools.test.ts +42 -0
- package/test/unknown-variant.test.ts +28 -0
- package/tsconfig.json +6 -0
package/src/delivery.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What became of an input sent into a session: accepted, never sent, or possibly sent.
|
|
3
|
+
*
|
|
4
|
+
* A message that a side failed to write is safe to send again; a message that was written and
|
|
5
|
+
* whose answer never came may already be running as a turn, and sending it again would start a
|
|
6
|
+
* second one. A control side says which by the error it fails with: `InputNotSent` when nothing
|
|
7
|
+
* reached the harness or the harness refused it, `InputPossiblySent` when it may have taken it.
|
|
8
|
+
* Any other failure of a send is read as possibly sent: an input is never sent twice on a guess.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { NotSent, effectPossibleAfter } from "@niwa-labs/core";
|
|
12
|
+
import { z } from "zod";
|
|
13
|
+
|
|
14
|
+
import { DeliveryReceiptSchema } from "./control.ts";
|
|
15
|
+
import type { DeliveryReceipt } from "./control.ts";
|
|
16
|
+
import type { Harness } from "./instance.ts";
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* How far a request to a harness got before it failed: never written (`unsent`), answered with a
|
|
20
|
+
* refusal (`refused`), or written and never answered (`uncertain`).
|
|
21
|
+
*/
|
|
22
|
+
export type Dispatch = "unsent" | "refused" | "uncertain";
|
|
23
|
+
|
|
24
|
+
/** The input did not reach the harness, or the harness refused it: sending it again is safe. */
|
|
25
|
+
export class InputNotSent extends NotSent {
|
|
26
|
+
override name = "InputNotSent";
|
|
27
|
+
override readonly code = "InputNotSent";
|
|
28
|
+
|
|
29
|
+
constructor(
|
|
30
|
+
readonly harness: Harness["id"],
|
|
31
|
+
readonly ability: string,
|
|
32
|
+
detail: string,
|
|
33
|
+
) {
|
|
34
|
+
super(`harness "${harness}" did not take the input of ${ability}: ${detail}`);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The input may have reached the harness: it is never sent again by itself. */
|
|
39
|
+
export class InputPossiblySent extends Error {
|
|
40
|
+
override name = "InputPossiblySent";
|
|
41
|
+
readonly code = "InputPossiblySent";
|
|
42
|
+
|
|
43
|
+
constructor(
|
|
44
|
+
readonly harness: Harness["id"],
|
|
45
|
+
readonly ability: string,
|
|
46
|
+
detail: string,
|
|
47
|
+
) {
|
|
48
|
+
super(`harness "${harness}" may have taken the input of ${ability}, and it is not sent again: ${detail}`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The error of a request that failed, by how far it got. */
|
|
53
|
+
export function inputFailure(harness: Harness["id"], ability: string, dispatch: Dispatch, detail: string): InputNotSent | InputPossiblySent {
|
|
54
|
+
return dispatch === "uncertain" ? new InputPossiblySent(harness, ability, detail) : new InputNotSent(harness, ability, detail);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** What became of an input. */
|
|
58
|
+
export const InputOutcomeSchema = z.discriminatedUnion("status", [
|
|
59
|
+
z.object({ status: z.literal("accepted"), receipt: DeliveryReceiptSchema }),
|
|
60
|
+
z.object({ status: z.literal("unsent"), reason: z.string() }),
|
|
61
|
+
z.object({ status: z.literal("possibly-sent"), reason: z.string() }),
|
|
62
|
+
]);
|
|
63
|
+
export type InputOutcome = z.output<typeof InputOutcomeSchema>;
|
|
64
|
+
|
|
65
|
+
/** The outcome of a send, by what it gave or failed with. */
|
|
66
|
+
export async function outcomeOf(sending: Promise<DeliveryReceipt>): Promise<InputOutcome> {
|
|
67
|
+
try {
|
|
68
|
+
return { status: "accepted", receipt: await sending };
|
|
69
|
+
} catch (error) {
|
|
70
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
71
|
+
// An error that says it had no effect (any `NotSent`, as a refusal by name) sent nothing.
|
|
72
|
+
if (!effectPossibleAfter(error)) return { status: "unsent", reason };
|
|
73
|
+
return { status: "possibly-sent", reason };
|
|
74
|
+
}
|
|
75
|
+
}
|
package/src/discover.ts
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Finding installed harnesses and proposing instances.
|
|
3
|
+
*
|
|
4
|
+
* Niwa can find the harnesses installed on a machine and propose instances of them; the owner
|
|
5
|
+
* confirms. This module does the finding and nothing else: it looks for the binary of each
|
|
6
|
+
* kind, asks that binary for its version, and checks that the directory the harness keeps its
|
|
7
|
+
* state in is there.
|
|
8
|
+
*
|
|
9
|
+
* What comes out is a proposal, not an instance. An instance has an id and a machine,
|
|
10
|
+
* and both are the owner's to give: niwa says what it found
|
|
11
|
+
* and stops there. A kind that is not installed is named in `missing`, with the reason — the
|
|
12
|
+
* absence of a proposal must not read as "there is none".
|
|
13
|
+
*
|
|
14
|
+
* Finding a binary does not run it. The PATH is scanned for a file that is there and may be
|
|
15
|
+
* run, and only the binary that was found is asked for its version: with a deadline, and with
|
|
16
|
+
* a cap on what it may say.
|
|
17
|
+
*
|
|
18
|
+
* The record of a proposal and the action that writes it are the sessions module's
|
|
19
|
+
* (`sessions/discover.ts`): this module only finds.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { spawn } from "node:child_process";
|
|
23
|
+
import { constants } from "node:fs";
|
|
24
|
+
import { access, stat } from "node:fs/promises";
|
|
25
|
+
import { homedir } from "node:os";
|
|
26
|
+
import { delimiter, join } from "node:path";
|
|
27
|
+
|
|
28
|
+
import { z } from "zod";
|
|
29
|
+
|
|
30
|
+
import { BundledProgramSchema } from "./bundled.ts";
|
|
31
|
+
import { HarnessBinarySchema, HarnessKindSchema } from "./instance.ts";
|
|
32
|
+
import type { HarnessBinary, HarnessKind } from "./instance.ts";
|
|
33
|
+
import type { HarnessKindDefinition } from "./index.ts";
|
|
34
|
+
|
|
35
|
+
/** How long one version probe waits for its answer. */
|
|
36
|
+
const VERSION_TIMEOUT_MS = 2_000;
|
|
37
|
+
/** How many bytes one version probe may read. */
|
|
38
|
+
const VERSION_OUTPUT_CAP_BYTES = 4 * 1024;
|
|
39
|
+
/** The version of a binary that did not say its version. */
|
|
40
|
+
const UNKNOWN_VERSION = "unknown";
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* How a kind is found on a machine.
|
|
44
|
+
*
|
|
45
|
+
* A kind declares this beside the defaults it already has: the program that runs it, the
|
|
46
|
+
* environment variable that points at that program, and the directory the installation keeps
|
|
47
|
+
* its state in.
|
|
48
|
+
*/
|
|
49
|
+
export const HarnessDetectionSchema = z.object({
|
|
50
|
+
/** The program that runs the kind. Absent when the kind is a library and not a program. */
|
|
51
|
+
binary: z.string().min(1).optional(),
|
|
52
|
+
/**
|
|
53
|
+
* The program niwa ships for the kind, run by the runtime that runs niwa, as the kind found it
|
|
54
|
+
* (`findBundled`). It stands where the binary does when the environment does not point
|
|
55
|
+
* elsewhere: it is not looked for on the PATH.
|
|
56
|
+
*/
|
|
57
|
+
bundled: BundledProgramSchema.optional(),
|
|
58
|
+
/**
|
|
59
|
+
* The environment variable that points at the binary. It wins over the PATH.
|
|
60
|
+
*
|
|
61
|
+
* Absent means the rule: the name of the kind in capitals, then `_BIN`.
|
|
62
|
+
*/
|
|
63
|
+
envVar: z.string().min(1).optional(),
|
|
64
|
+
/** The directory the installation keeps its state in. `~` is the home of the user. */
|
|
65
|
+
home: z.string().min(1),
|
|
66
|
+
});
|
|
67
|
+
export type HarnessDetection = z.output<typeof HarnessDetectionSchema>;
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* An installation as it was found.
|
|
71
|
+
*
|
|
72
|
+
* It is not an instance: the id and the machine are the owner's, and a proposal
|
|
73
|
+
* that filled them in would be inventing them.
|
|
74
|
+
*/
|
|
75
|
+
export const HarnessProposalSchema = z.object({
|
|
76
|
+
/** The kind of the installation. */
|
|
77
|
+
kind: HarnessKindSchema,
|
|
78
|
+
/** The program that runs it, when the kind has one. */
|
|
79
|
+
binary: HarnessBinarySchema.optional(),
|
|
80
|
+
/** The directory the installation keeps its state in. */
|
|
81
|
+
home: z.string().min(1),
|
|
82
|
+
});
|
|
83
|
+
export type HarnessProposal = z.output<typeof HarnessProposalSchema>;
|
|
84
|
+
|
|
85
|
+
/** A kind that is not installed, and why it is not. */
|
|
86
|
+
export const HarnessMissingSchema = z.object({
|
|
87
|
+
kind: HarnessKindSchema,
|
|
88
|
+
reason: z.string().min(1),
|
|
89
|
+
});
|
|
90
|
+
export type HarnessMissing = z.output<typeof HarnessMissingSchema>;
|
|
91
|
+
|
|
92
|
+
/** What the finding found: the installations that are there, and the kinds that are not. */
|
|
93
|
+
export interface HarnessDiscoveryResult {
|
|
94
|
+
readonly proposals: readonly HarnessProposal[];
|
|
95
|
+
readonly missing: readonly HarnessMissing[];
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The environment the finding looks in: the PATH, the home, and the overrides of the binaries. */
|
|
99
|
+
export type DiscoverEnv = Readonly<Record<string, string | undefined>>;
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The environment variable that points at the binary of a kind: the name of the kind in
|
|
103
|
+
* capitals, with its dashes turned into underscores, then `_BIN`.
|
|
104
|
+
*
|
|
105
|
+
* `claude-code` → `CLAUDE_CODE_BIN`.
|
|
106
|
+
*/
|
|
107
|
+
export function binaryEnvVarOf(kind: HarnessKind): string {
|
|
108
|
+
return `${String(kind).toUpperCase().replaceAll("-", "_")}_BIN`;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Find the installed harnesses of the given kinds.
|
|
113
|
+
*
|
|
114
|
+
* Every kind that says how it is found is looked for; a kind that does not say is named in
|
|
115
|
+
* `missing`. The kinds are looked at one after another, and the order of the answer is the
|
|
116
|
+
* order of the kinds.
|
|
117
|
+
*/
|
|
118
|
+
export async function discover(
|
|
119
|
+
kinds: readonly HarnessKindDefinition[],
|
|
120
|
+
env: DiscoverEnv,
|
|
121
|
+
): Promise<HarnessDiscoveryResult> {
|
|
122
|
+
const proposals: HarnessProposal[] = [];
|
|
123
|
+
const missing: HarnessMissing[] = [];
|
|
124
|
+
for (const kind of kinds) {
|
|
125
|
+
const found = await discoverKind(kind, env);
|
|
126
|
+
if (found.proposal !== undefined) {
|
|
127
|
+
proposals.push(found.proposal);
|
|
128
|
+
} else {
|
|
129
|
+
missing.push({ kind: kind.kind, reason: found.reason });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return { proposals, missing };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** What one kind turned out to be: an installation, or the reason it is not there. */
|
|
136
|
+
type Found =
|
|
137
|
+
| { readonly proposal: HarnessProposal }
|
|
138
|
+
| { readonly proposal?: undefined; readonly reason: string };
|
|
139
|
+
|
|
140
|
+
/** Look for one kind: its binary, its version and its home. */
|
|
141
|
+
async function discoverKind(kind: HarnessKindDefinition, env: DiscoverEnv): Promise<Found> {
|
|
142
|
+
const detection = kind.detect;
|
|
143
|
+
if (detection === undefined) {
|
|
144
|
+
return { reason: "the kind does not say how it is found" };
|
|
145
|
+
}
|
|
146
|
+
const home = homeOf(detection.home, env);
|
|
147
|
+
|
|
148
|
+
if (detection.binary === undefined && detection.bundled === undefined) {
|
|
149
|
+
// A kind that is a library has no binary: the home is all there is to find.
|
|
150
|
+
if (!(await isDirectory(home))) return { reason: `the home "${home}" is not there` };
|
|
151
|
+
return { proposal: { kind: kind.kind, home } };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const envVar = detection.envVar ?? binaryEnvVarOf(kind.kind);
|
|
155
|
+
const override = await findOverride(envVar, env);
|
|
156
|
+
let binary: HarnessBinary;
|
|
157
|
+
if (override === undefined && detection.bundled !== undefined) {
|
|
158
|
+
const program = detection.bundled;
|
|
159
|
+
if (program.path === undefined) {
|
|
160
|
+
return { reason: `the bundled program "${program.package}" is not installed and ${envVar} points at nothing that is there` };
|
|
161
|
+
}
|
|
162
|
+
binary = { path: program.path, version: program.version ?? UNKNOWN_VERSION };
|
|
163
|
+
} else {
|
|
164
|
+
const path = override ?? (detection.binary === undefined ? undefined : await findOnPath(detection.binary, env));
|
|
165
|
+
if (path === undefined) {
|
|
166
|
+
return { reason: `the binary "${detection.binary}" is not on the PATH and ${envVar} points at nothing that is there` };
|
|
167
|
+
}
|
|
168
|
+
binary = { path, version: (await readVersion(path, env)) ?? UNKNOWN_VERSION };
|
|
169
|
+
}
|
|
170
|
+
if (!(await isDirectory(home))) return { reason: `the home "${home}" is not there` };
|
|
171
|
+
return { proposal: { kind: kind.kind, binary, home } };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The home of the installation: `~` is the home of the user, as the environment says it. */
|
|
175
|
+
function homeOf(home: string, env: DiscoverEnv): string {
|
|
176
|
+
const root = env["HOME"] ?? homedir();
|
|
177
|
+
if (home === "~") return root;
|
|
178
|
+
if (home.startsWith("~/")) return join(root, home.slice(2));
|
|
179
|
+
return home;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** The binary the environment points at, when it is there and may be run. */
|
|
183
|
+
async function findOverride(envVar: string, env: DiscoverEnv): Promise<string | undefined> {
|
|
184
|
+
const override = env[envVar];
|
|
185
|
+
return override !== undefined && override !== "" && (await isExecutable(override)) ? override : undefined;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Find the binary of a kind on the PATH.
|
|
190
|
+
*
|
|
191
|
+
* Nothing is run to find it: the directories of the PATH are scanned for a file that is there
|
|
192
|
+
* and may be run.
|
|
193
|
+
*/
|
|
194
|
+
async function findOnPath(name: string, env: DiscoverEnv): Promise<string | undefined> {
|
|
195
|
+
for (const dir of (env["PATH"] ?? "").split(delimiter)) {
|
|
196
|
+
if (dir === "") continue;
|
|
197
|
+
const candidate = join(dir, name);
|
|
198
|
+
if (await isExecutable(candidate)) return candidate;
|
|
199
|
+
}
|
|
200
|
+
return undefined;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Is that a file that may be run? */
|
|
204
|
+
async function isExecutable(path: string): Promise<boolean> {
|
|
205
|
+
try {
|
|
206
|
+
if (!(await stat(path)).isFile()) return false;
|
|
207
|
+
await access(path, constants.X_OK);
|
|
208
|
+
return true;
|
|
209
|
+
} catch {
|
|
210
|
+
return false;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Is that a directory? */
|
|
215
|
+
async function isDirectory(path: string): Promise<boolean> {
|
|
216
|
+
try {
|
|
217
|
+
return (await stat(path)).isDirectory();
|
|
218
|
+
} catch {
|
|
219
|
+
return false;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Ask a binary for its version.
|
|
225
|
+
*
|
|
226
|
+
* The probe is bounded: it waits two seconds and reads four kilobytes, and a binary that
|
|
227
|
+
* says more or takes longer is stopped. `undefined` means the binary did not answer — it is
|
|
228
|
+
* there, but it did not say what it is.
|
|
229
|
+
*/
|
|
230
|
+
function readVersion(binary: string, env: DiscoverEnv): Promise<string | undefined> {
|
|
231
|
+
return new Promise<string | undefined>((resolve) => {
|
|
232
|
+
const child = spawn(binary, ["--version"], {
|
|
233
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
234
|
+
env: childEnv(env),
|
|
235
|
+
});
|
|
236
|
+
let out = "";
|
|
237
|
+
let bytes = 0;
|
|
238
|
+
let settled = false;
|
|
239
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
240
|
+
|
|
241
|
+
const finish = (version: string | undefined): void => {
|
|
242
|
+
if (settled) return;
|
|
243
|
+
settled = true;
|
|
244
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
245
|
+
resolve(version);
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
timer = setTimeout(() => {
|
|
249
|
+
child.kill("SIGKILL");
|
|
250
|
+
finish(undefined);
|
|
251
|
+
}, VERSION_TIMEOUT_MS);
|
|
252
|
+
timer.unref?.();
|
|
253
|
+
|
|
254
|
+
child.stdout?.on("data", (chunk: Buffer) => {
|
|
255
|
+
const room = VERSION_OUTPUT_CAP_BYTES - bytes;
|
|
256
|
+
if (room <= 0) return;
|
|
257
|
+
out += chunk.toString("utf8", 0, room);
|
|
258
|
+
bytes += Math.min(chunk.length, room);
|
|
259
|
+
if (chunk.length >= room) {
|
|
260
|
+
// It has said enough: the rest is not read, and the probe stops.
|
|
261
|
+
child.kill("SIGKILL");
|
|
262
|
+
finish(firstLine(out));
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
child.on("error", () => finish(undefined));
|
|
266
|
+
// A binary that failed did not give a version, whatever it printed.
|
|
267
|
+
child.on("close", (code) => finish(code === 0 ? firstLine(out) : undefined));
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** The first line that has something on it. */
|
|
272
|
+
function firstLine(text: string): string | undefined {
|
|
273
|
+
for (const line of text.split("\n")) {
|
|
274
|
+
const trimmed = line.trim();
|
|
275
|
+
if (trimmed !== "") return trimmed;
|
|
276
|
+
}
|
|
277
|
+
return undefined;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** The environment a probe runs in: the environment of the process, with the found one over it. */
|
|
281
|
+
function childEnv(env: DiscoverEnv): Record<string, string> {
|
|
282
|
+
const merged: Record<string, string> = {};
|
|
283
|
+
for (const [name, value] of Object.entries(process.env)) {
|
|
284
|
+
if (value !== undefined) merged[name] = value;
|
|
285
|
+
}
|
|
286
|
+
for (const [name, value] of Object.entries(env)) {
|
|
287
|
+
if (value === undefined) delete merged[name];
|
|
288
|
+
else merged[name] = value;
|
|
289
|
+
}
|
|
290
|
+
return merged;
|
|
291
|
+
}
|