@flyingrobots/parley-emit 0.0.0-stage → 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/src/tool.ts ADDED
@@ -0,0 +1,328 @@
1
+ // A tool: its commands, their declarations, and the entry point that turns argv and a handler
2
+ // into a conforming run (spec §3, §4, §6).
3
+ import { closeSync, openSync, readSync, readdirSync, rmSync, statSync, unlinkSync, writeSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { join, resolve } from "node:path";
6
+ import { computeInv, type InputDecl } from "./inv.ts";
7
+ import { bookkeepingFor, chooseLocation, isLocationFailure, type Bookkeeping } from "./location.ts";
8
+ import { carriesSecret, classifySecrets, collectSecretValues, redactArgv, scrub } from "./redact.ts";
9
+ import { Run, SCHEMA_IDS, type Record_, type SchemaRef, type Sink } from "./run.ts";
10
+ import { SCHEMAS } from "./schemas.ts";
11
+ import { ulid } from "./ulid.ts";
12
+
13
+ export interface Effects { reads: string[]; writes: string[]; network: boolean; idempotent: boolean }
14
+ export interface EmittedType extends SchemaRef { readonly schema?: Record<string, unknown> }
15
+ export interface CommandSpec {
16
+ readonly intent: string;
17
+ readonly effects: Effects;
18
+ /** Flags (`--token`), environment variables (`APP_TOKEN`) and logical credential sources (`netrc`). */
19
+ readonly secrets?: readonly string[];
20
+ /** The result types the command can emit; a tool-owned type carries its JSON Schema for discovery. */
21
+ readonly emits: readonly EmittedType[];
22
+ /** The error types the command can produce; defaults to `parley.error`. */
23
+ readonly errors?: readonly EmittedType[];
24
+ }
25
+ export interface ToolSpec {
26
+ readonly name: string;
27
+ readonly version: string;
28
+ readonly commands: Readonly<Record<string, CommandSpec>>;
29
+ /** §5.1: a stated policy. Completed receipts beyond `count` in a location are deleted, oldest first. */
30
+ readonly retention: { readonly count: number };
31
+ /** Resolvers for declared credential sources, called before the head is written (§5.3). */
32
+ readonly sources?: Readonly<Record<string, () => boolean | Promise<boolean>>>;
33
+ /** Prose for `--human`: return a string for a line, or null for the default rendering. */
34
+ readonly human?: (line: Record_) => string | null;
35
+ }
36
+
37
+ export function defineTool(spec: ToolSpec): ToolSpec {
38
+ if (!spec.name) throw new TypeError("tool name is never empty");
39
+ if (!spec.version) throw new TypeError("tool version is never empty");
40
+ if (!Object.keys(spec.commands).length) throw new TypeError("a tool has at least one command");
41
+ if (!Number.isInteger(spec.retention?.count) || spec.retention.count < 1) throw new TypeError("retention.count must be a positive integer (spec §5.1)");
42
+ for (const [name, c] of Object.entries(spec.commands)) {
43
+ if (!c.intent) throw new TypeError(`command ${name} needs an intent`);
44
+ for (const e of c.emits) if (!e.id || !/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/.test(e.version)) throw new TypeError(`command ${name} emits an invalid type ${e.id}@${e.version}`);
45
+ }
46
+ return spec;
47
+ }
48
+
49
+ export type { InputDecl };
50
+ export interface MainOptions {
51
+ cwd?: string;
52
+ env?: Record<string, string | undefined>;
53
+ home?: string;
54
+ stdout?: Sink;
55
+ stderr?: Sink;
56
+ session?: string;
57
+ now?: () => number;
58
+ /** The declared inputs of this invocation, from the command's arguments. */
59
+ inputs?: (args: string[], command: string) => InputDecl[] | Promise<InputDecl[]>;
60
+ /** The resolved interpretation after defaults (§5): order-normalised and free of volatile values, since it enters inv. The default records the command and its arguments. */
61
+ resolved?: (args: string[], command: string) => Record<string, unknown> | Promise<Record<string, unknown>>;
62
+ }
63
+
64
+ /**
65
+ * A sink on a file descriptor that delivers the whole line: a partial write continues from where
66
+ * it stopped, and EAGAIN (a full pipe on a descriptor the runtime left non-blocking) waits a
67
+ * millisecond and tries again, which is what a blocking write would have done.
68
+ */
69
+ export function fdSink(fd: number): Sink {
70
+ const pause = new Int32Array(new SharedArrayBuffer(4));
71
+ return {
72
+ write(line) {
73
+ const buf = Buffer.from(line, "utf8");
74
+ let off = 0;
75
+ while (off < buf.length) {
76
+ try { off += writeSync(fd, buf, off, buf.length - off); }
77
+ catch (e) { if ((e as NodeJS.ErrnoException).code === "EAGAIN") { Atomics.wait(pause, 0, 0, 1); continue; } throw e; }
78
+ }
79
+ },
80
+ };
81
+ }
82
+ const OWN_FLAGS = new Set(["--human", "--humanize", "--dry-run", "--schema", "--help", "-h"]);
83
+ const WRITER_SCHEMAS: SchemaRef[] = Object.values(SCHEMA_IDS);
84
+ /** Incomplete receipts (no end line) older than this are deletable by retention; younger ones may still be in flight. */
85
+ const INCOMPLETE_GRACE_MS = 24 * 60 * 60 * 1000;
86
+
87
+ export type Handler = (run: Run, args: string[]) => void | Promise<void>;
88
+
89
+ /**
90
+ * Run a tool: parse the writer-owned flags, bootstrap, write the receipt, run the handler under
91
+ * the top-level handler of §6, and close with `end`. Returns the exit status (§3.4).
92
+ */
93
+ export async function main(spec: ToolSpec, argv: readonly string[], handler: Handler, opts: MainOptions = {}): Promise<number> {
94
+ const env = opts.env ?? process.env;
95
+ const cwd = resolve(opts.cwd ?? process.cwd());
96
+ const stdout = opts.stdout ?? fdSink(1), stderr = opts.stderr ?? fdSink(2);
97
+ const now = opts.now ?? Date.now;
98
+ const rawArgs = argv.slice(1);
99
+ const human = rawArgs.some((a) => a === "--human" || a === "--humanize");
100
+ const dryRun = rawArgs.includes("--dry-run");
101
+ const discovery = rawArgs.includes("--schema") ? "schema" : rawArgs.includes("--help") || rawArgs.includes("-h") ? "help" : null;
102
+ const args = rawArgs.filter((a) => !OWN_FLAGS.has(a));
103
+ const names = Object.keys(spec.commands);
104
+ const commandName = args.find((a) => !a.startsWith("-") && Object.hasOwn(spec.commands, a)) ?? (names.length === 1 ? names[0]! : undefined);
105
+ const command = commandName ? spec.commands[commandName]! : undefined;
106
+
107
+ // Declared secrets of every command: a value passed to the wrong command is still a secret (§5.3).
108
+ const allNames = classifySecrets(names.flatMap((n) => spec.commands[n]!.secrets ?? []));
109
+ const secretValues = collectSecretValues(argv, allNames, env);
110
+ const ownNames = classifySecrets(command?.secrets ?? []);
111
+
112
+ let id = ulid(now());
113
+ for (let i = 0; i < 16 && carriesSecret(id, secretValues); i++) id = ulid(now());
114
+
115
+ const startupFailed = (code: string, problem: string, remedy: string): number => {
116
+ const line = { event: "startup.failed", t: now(), seq: 0, run: id, tool: spec.name, v: spec.version, code, problem: scrubText(problem, secretValues), remedy, _schema: SCHEMA_IDS.startupFailed };
117
+ try { stderr.write(human ? `startup failed ${code}: ${line.problem} (${remedy})\n` : JSON.stringify(line) + "\n"); } catch { /* nothing else can be said */ }
118
+ return 3;
119
+ };
120
+
121
+ if (carriesSecret(id, secretValues)) return startupFailed("startup.secret_in_path", "no run id free of a declared secret value could be chosen", "do not pass a value this short as a declared secret");
122
+ // The bootstrap line's identity fields are never scrubbed. The tool's name and version are public
123
+ // and printed on every startup line regardless, so a secret inside them is not protectable and
124
+ // the run proceeds; a session is caller-supplied and can be withheld, so one carrying a secret
125
+ // is a startup failure (the startup line omits it).
126
+ const sessionEarly = opts.session ?? env.PARLEY_SESSION;
127
+ if (sessionEarly && carriesSecret(sessionEarly, secretValues)) return startupFailed("startup.secret_in_identity", "the session id contains a declared secret value and cannot be printed", "supply a session id that does not contain the secret");
128
+ if (!commandName && discovery === null) return startupFailed("startup.unknown_command", `no command named; commands are ${names.join(", ")}`, `name one of: ${names.join(", ")}`);
129
+
130
+ // Console capture starts here, before any tool code runs; captured text is buffered until the receipt exists (§1.2).
131
+ const capture = captureConsole();
132
+ const release = capture.release;
133
+ const fail = (code: string, problem: string, remedy: string): number => { release(); return startupFailed(code, problem, remedy); };
134
+
135
+ // Declared credential sources, resolved before the head (§5.3); a throwing resolver means "not present".
136
+ const presentSources: string[] = [];
137
+ for (const s of ownNames.sources) { try { if (await spec.sources?.[s]?.()) presentSources.push(s); } catch { /* not present */ } }
138
+ const presentEnv = allNames.env.filter((n) => env[n] !== undefined);
139
+
140
+ const location = chooseLocation({ cwd, run: id, env, home: opts.home ?? homedir(), secrets: secretValues });
141
+ if (isLocationFailure(location)) return fail(location.code, location.problem, location.remedy);
142
+
143
+ // Everything the tool supplies before the bootstrap line can throw; a throw here is a startup failure (§3.2), not a stack trace.
144
+ let resolvedRaw: Record<string, unknown>, inputs: InputDecl[];
145
+ try {
146
+ const rest = args.filter((a) => a !== commandName);
147
+ resolvedRaw = discovery ? { discovery, command: commandName } : await (opts.resolved ?? ((a, c) => ({ command: c, args: a })))(rest, commandName!);
148
+ inputs = discovery || !command ? [] : await (opts.inputs ?? (() => []))(rest, commandName!);
149
+ } catch (e) {
150
+ try { closeSync(location.fd); unlinkSync(location.receiptPath); } catch { /* the reservation is gone either way */ }
151
+ const err = e instanceof Error ? e : new Error(String(e));
152
+ return fail("startup.arguments_invalid", `the arguments could not be interpreted: ${err.message || err.name}`, "fix the arguments; see the command's --help");
153
+ }
154
+
155
+ const sessionRaw = opts.session ?? env.PARLEY_SESSION;
156
+ const session = sessionRaw ? sessionRaw : undefined;
157
+ const resolvedPointers: string[] = [];
158
+ const resolved = scrub(resolvedRaw, secretValues, "", resolvedPointers);
159
+ const { argv: argvRedacted, indexes: argvIndexes } = redactArgv(argv, secretValues, allNames.flags);
160
+ const inputPointers: string[] = [];
161
+ const inputDescriptors = scrub(inputs.map((i) => ({ path: i.path, ...(i.role ? { role: i.role } : {}) })), secretValues, "", inputPointers) as { path: string; role?: string }[];
162
+ const inputIndexes = inputPointers.map((p) => Number(p.split("/")[1]));
163
+ const redacted: Record<string, unknown> = {};
164
+ if (argvIndexes.length) redacted.argv = argvIndexes;
165
+ if (resolvedPointers.length) redacted.resolved = resolvedPointers;
166
+ if (inputIndexes.length) redacted.inputs = [...new Set(inputIndexes)];
167
+ if (presentEnv.length) redacted.env = presentEnv;
168
+ if (presentSources.length) redacted.sources = presentSources;
169
+ const headRedacted = Object.keys(redacted).length > 0;
170
+ const inv = inputs.length === 0 && command ? computeInv({ tool: spec.name, v: spec.version, command: commandName!, resolved, inputs: [] }) : undefined;
171
+
172
+ const run = new Run({
173
+ tool: spec.name, v: spec.version, id, session, dryRun, stdout, stderr, receiptFd: location.fd, receiptPath: location.receiptPath, receiptDir: location.receiptDir,
174
+ secretValues, now, cwd, command: commandName ?? discovery!, resolved, inputs, headRedacted, human: human ? spec.human ?? (() => null) : undefined,
175
+ });
176
+
177
+ run.bootstrap(inv);
178
+ const bookkeeping = bookkeepingFor(cwd, env, opts.home);
179
+ run.head({
180
+ tool: spec.name, v: spec.version, ...(inv ? { inv } : {}), ...(session ? { session } : {}),
181
+ argv: argvRedacted, resolved, ...(headRedacted ? { redacted } : {}), inputs: inputDescriptors,
182
+ effects: command ? { ...command.effects, bookkeeping } : { reads: [], writes: [], network: false, idempotent: true, bookkeeping },
183
+ ...(dryRun ? { dry_run: true } : {}),
184
+ });
185
+ run.flushDeferredFailures();
186
+ capture.attach(run);
187
+ if (run.sinkFailed) { release(); return run.end(); }
188
+ if (location.warning) run.warning(location.warning);
189
+
190
+ retain(run, location.receiptDir, spec.retention.count, dryRun, now());
191
+
192
+ if (discovery) {
193
+ try { discover(run, spec, discovery, commandName, bookkeeping); } catch (e) {
194
+ const err = e instanceof Error ? e : new Error(String(e));
195
+ if (!run.ended) run.error({ code: "uncaught.exception", problem: `uncaught ${err.name} during discovery: ${err.message || "(no message)"}`, remedy: `this is a defect in the tool's declaration; report it with the receipt at ${run.receiptPath}` }, { detail: { stack: err.stack } });
196
+ }
197
+ release();
198
+ return run.ended ? run.status ?? 4 : run.end();
199
+ }
200
+
201
+ try {
202
+ await handler(run, args.filter((a) => a !== commandName));
203
+ } catch (e) {
204
+ if (run.ended) { release(); return 4; }
205
+ const err = e instanceof Error ? e : new Error(String(e));
206
+ run.error({ code: "uncaught.exception", problem: `uncaught ${err.name}: ${err.message || "(no message)"}`, remedy: `this is a defect in the tool; report it with the receipt at ${run.receiptPath}` }, { detail: { stack: err.stack } });
207
+ } finally {
208
+ release();
209
+ }
210
+ return run.ended ? run.status ?? 4 : run.end();
211
+ }
212
+
213
+ function discover(run: Run, spec: ToolSpec, discovery: "schema" | "help", commandName: string | undefined, bookkeeping: Bookkeeping[]): void {
214
+ const names = Object.keys(spec.commands);
215
+ {
216
+ const which = discovery === "help" && commandName ? [commandName] : names;
217
+ for (const name of which) {
218
+ const c = spec.commands[name]!;
219
+ run.describe({ event: "command", name, intent: c.intent, effects: { ...c.effects, bookkeeping }, secrets: [...(c.secrets ?? [])], emits: [...c.emits, ...(c.errors ?? [SCHEMA_IDS.error])].map(({ id, version }) => ({ id, version })) }, SCHEMA_IDS.command);
220
+ }
221
+ const types = new Map<string, EmittedType>();
222
+ const add = (t: EmittedType) => { const k = `${t.id}@${t.version}`; if (!types.has(k)) types.set(k, t); };
223
+ for (const name of which) { const c = spec.commands[name]!; c.emits.forEach(add); (c.errors ?? [SCHEMA_IDS.error]).forEach(add); }
224
+ if (discovery === "schema") WRITER_SCHEMAS.forEach(add);
225
+ for (const t of types.values()) {
226
+ const doc = t.schema ?? SCHEMAS.find((s) => s.id === t.id && s.version === t.version)?.schema;
227
+ if (!doc) { run.warning({ code: "schema.unavailable", problem: `no schema document for ${t.id}@${t.version}`, remedy: "declare the schema on the emitted type" }); continue; }
228
+ run.describe({ event: "schema", id: t.id, version: t.version, schema: doc }, SCHEMA_IDS.schema);
229
+ }
230
+ run.end(0);
231
+ }
232
+ }
233
+
234
+ function scrubText(s: string, values: ReadonlySet<string>): string { return scrub(s, values) as string; }
235
+
236
+ /** True when the receipt's final line is a newline-terminated `end` (§5.4), read from its tail. */
237
+ function hasEnded(path: string): boolean {
238
+ let fd: number | null = null;
239
+ try {
240
+ const size = statSync(path).size;
241
+ if (size === 0) return false;
242
+ fd = openSync(path, "r");
243
+ const len = Math.min(size, 8192);
244
+ const buf = Buffer.alloc(len);
245
+ readSync(fd, buf, 0, len, size - len);
246
+ const text = buf.toString("utf8");
247
+ if (!text.endsWith("\n")) return false;
248
+ const last = text.slice(0, -1).split("\n").pop() ?? "";
249
+ const obj = JSON.parse(last) as { event?: string };
250
+ return obj.event === "end";
251
+ } catch { return false; } finally { if (fd !== null) closeSync(fd); }
252
+ }
253
+
254
+ /** §5.1: delete the oldest completed bundles beyond `count` in this location; never a receipt still in flight; never on a dry run; recorded as a decision. */
255
+ function retain(run: Run, receiptDir: string, count: number, dryRun: boolean, at: number): void {
256
+ let files: { name: string; mtime: number }[];
257
+ try { files = readdirSync(receiptDir).filter((f) => f.endsWith(".jsonl")).map((name) => ({ name, mtime: statSync(join(receiptDir, name)).mtimeMs })); } catch { return; }
258
+ const excess = files.length - count;
259
+ if (excess <= 0) return;
260
+ const candidates = files.filter((f) => f.name !== `${run.id}.jsonl`).sort((a, b) => a.mtime - b.mtime || a.name.localeCompare(b.name));
261
+ const victims: string[] = [];
262
+ for (const f of candidates) {
263
+ if (victims.length >= excess) break;
264
+ const p = join(receiptDir, f.name);
265
+ if (hasEnded(p) || at - f.mtime > INCOMPLETE_GRACE_MS) victims.push(f.name);
266
+ }
267
+ if (!victims.length) { run.step("retention: nothing to delete", `${files.length} receipts exceed the retention count of ${count}, but every excess receipt is still in flight (no end line yet); only completed bundles, or incomplete ones older than a day, are deleted (§5.1)`); return; }
268
+ if (dryRun) { run.step(`retention: would delete ${victims.length} receipt bundle(s)`, `${files.length} receipts exceed the retention count of ${count}; a dry run performs no retention deletion (§4.3)`, { receipts: victims }); return; }
269
+ const deleted: string[] = [];
270
+ for (const name of victims) {
271
+ const base = name.slice(0, -".jsonl".length);
272
+ try { rmSync(join(receiptDir, name), { force: true }); rmSync(join(receiptDir, base), { recursive: true, force: true }); deleted.push(name); } catch { /* a bundle another run is deleting */ }
273
+ }
274
+ run.step(`retention: deleted ${deleted.length} receipt bundle(s)`, `${files.length} receipts exceeded the retention count of ${count}; the oldest completed bundles are deleted with their sidecars (§5.1)`, { receipts: deleted });
275
+ }
276
+
277
+ // ---- console capture (§1.2) --------------------------------------------------------------
278
+ // One saved copy of the real console, taken when the first capture starts; a stack of captures,
279
+ // each bound to a run once that run's receipt exists and buffering until then. Every function
280
+ // on console is routed into the receipt of the most recent capture that is still open. The real
281
+ // console returns when the last capture releases. Direct writes to a file descriptor and timers
282
+ // that fire after end are outside this net; the README names them as exceptions.
283
+
284
+ type ConsoleFn = (...a: unknown[]) => unknown;
285
+ interface Capture { run: Run | null; pending: { method: string; text: string }[]; released: boolean }
286
+ const active: Capture[] = [];
287
+ let saved: Map<string, ConsoleFn> | null = null;
288
+
289
+ function record(c: Capture, method: string, text: string): void {
290
+ if (c.run === null) { c.pending.push({ method, text }); return; }
291
+ if (c.run.ended) return;
292
+ try { c.run.step("captured console output", `a library called console.${method}; stdout and stderr carry only protocol lines (§1.2), so the text is kept here`, { method, text }); } catch { /* the run ended between the check and the write */ }
293
+ }
294
+
295
+ function captureConsole(): { attach: (run: Run) => void; release: () => void } {
296
+ const c: Capture = { run: null, pending: [], released: false };
297
+ active.push(c);
298
+ if (saved === null) {
299
+ saved = new Map();
300
+ const con = console as unknown as Record<string, unknown>;
301
+ for (const key of Object.getOwnPropertyNames(console)) {
302
+ const fn = con[key];
303
+ if (typeof fn !== "function") continue;
304
+ saved.set(key, fn as ConsoleFn);
305
+ con[key] = (...a: unknown[]) => {
306
+ const target = [...active].reverse().find((x) => !x.released && (x.run === null || !x.run.ended));
307
+ if (!target) return;
308
+ record(target, key, a.map((x) => (typeof x === "string" ? x : safeJson(x))).join(" "));
309
+ };
310
+ }
311
+ }
312
+ return {
313
+ attach(run) { c.run = run; for (const p of c.pending) record(c, p.method, p.text); c.pending = []; },
314
+ release() {
315
+ if (c.released) return; c.released = true;
316
+ const i = active.indexOf(c); if (i >= 0) active.splice(i, 1);
317
+ if (active.length === 0 && saved !== null) {
318
+ const con = console as unknown as Record<string, unknown>;
319
+ for (const [key, fn] of saved) con[key] = fn;
320
+ saved = null;
321
+ }
322
+ },
323
+ };
324
+ }
325
+
326
+ function safeJson(x: unknown): string { try { return JSON.stringify(x) ?? String(x); } catch { return String(x); } }
327
+
328
+ export type { Bookkeeping };
package/src/ulid.ts ADDED
@@ -0,0 +1,13 @@
1
+ // A ULID: 10 characters of millisecond time and 16 of randomness, Crockford base32, so run ids
2
+ // sort lexicographically by creation time (spec §2.1).
3
+ const ENC = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
4
+
5
+ export function ulid(time: number = Date.now()): string {
6
+ let t = Math.max(0, Math.floor(time));
7
+ let head = "";
8
+ for (let i = 0; i < 10; i++) { head = ENC[t % 32] + head; t = Math.floor(t / 32); }
9
+ const rnd = crypto.getRandomValues(new Uint8Array(16));
10
+ let tail = "";
11
+ for (let i = 0; i < 16; i++) tail += ENC[rnd[i]! & 31];
12
+ return head + tail;
13
+ }