@operad-io/harness-process 0.1.1 → 0.3.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/timings.ts ADDED
@@ -0,0 +1,83 @@
1
+ /**
2
+ * The times of one agent step, from the injected clock: how long the worker
3
+ * took to become ready, how long the model then took to its first increment,
4
+ * and the whole step. A ready line is a `session` line; a text, thinking or
5
+ * tool increment is the first line of one of those kinds.
6
+ */
7
+
8
+ import { isRecord, type AgentTimings, type PluginStepResult } from "@operad-io/engine";
9
+
10
+ /** The line every harness writes once its session is ready and the prompt is about to go out. */
11
+ export const READY_LINE = "session";
12
+
13
+ const INCREMENT_LINES: ReadonlySet<string> = new Set([
14
+ "text_delta",
15
+ "thinking_delta",
16
+ "text_end",
17
+ "thinking_end",
18
+ "tool_execution_start",
19
+ "message_end",
20
+ ]);
21
+
22
+ function receivedAtOf(value: unknown): number | undefined {
23
+ if (!isRecord(value)) return undefined;
24
+ const at = value["receivedAt"];
25
+ return typeof at === "number" && Number.isFinite(at) ? at : undefined;
26
+ }
27
+
28
+ /** Measures one agent step from the moment it starts. */
29
+ export class StepTimings {
30
+ private readonly startedAt: number;
31
+ private readyAt: number | undefined;
32
+ private firstAt: number | undefined;
33
+
34
+ constructor(private readonly now: () => number) {
35
+ this.startedAt = now();
36
+ }
37
+
38
+ /** Takes one line the host received, with its `receivedAt` when it has one. */
39
+ line(text: string): void {
40
+ let value: unknown;
41
+ try {
42
+ value = JSON.parse(text);
43
+ } catch {
44
+ return;
45
+ }
46
+ this.record(value, receivedAtOf(value) ?? this.now());
47
+ }
48
+
49
+ /** Takes a line the host already parsed, with the time it received it. */
50
+ record(value: unknown, at: number): void {
51
+ if (!isRecord(value)) return;
52
+ const type = value["type"];
53
+ if (typeof type !== "string") return;
54
+ if (type === READY_LINE) {
55
+ if (this.readyAt === undefined) this.readyAt = at;
56
+ return;
57
+ }
58
+ if (!INCREMENT_LINES.has(type)) return;
59
+ if (type === "message_end" && (typeof value["text"] !== "string" || value["text"].length === 0)) return;
60
+ if (this.firstAt === undefined) this.firstAt = at;
61
+ }
62
+
63
+ /** The three durations, with the whole step measured now. */
64
+ finish(): AgentTimings {
65
+ const ready = this.readyAt;
66
+ const first = this.firstAt;
67
+ return {
68
+ startToReadyMs: ready === undefined ? null : Math.max(0, ready - this.startedAt),
69
+ readyToFirstMs:
70
+ ready === undefined || first === undefined
71
+ ? null
72
+ : first >= ready
73
+ ? first - ready
74
+ : null,
75
+ totalMs: Math.max(0, this.now() - this.startedAt),
76
+ };
77
+ }
78
+ }
79
+
80
+ /** The step's result with its timings beside its other data. */
81
+ export function withTimings(result: PluginStepResult, timings: AgentTimings): PluginStepResult {
82
+ return { ...result, data: { ...(result.data ?? {}), timings } };
83
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The line the claude and pi workers write when a tool call starts or ends.
3
+ * The stall timer holds while a call is open; both programs name it under the
4
+ * same `type`, so one classifier reads both.
5
+ */
6
+
7
+ import { isRecord } from "@operad-io/engine";
8
+ import type { ToolEvent } from "./process.ts";
9
+
10
+ /** The tool call one worker line starts or settles, or undefined for another line. */
11
+ export function toolExecutionEvent(line: string): ToolEvent | undefined {
12
+ let value: unknown;
13
+ try {
14
+ value = JSON.parse(line);
15
+ } catch {
16
+ return undefined;
17
+ }
18
+ if (!isRecord(value)) return undefined;
19
+ if (value.type === "tool_execution_start") return "tool-start";
20
+ if (value.type === "tool_execution_end") return "tool-end";
21
+ return undefined;
22
+ }
package/src/version.ts ADDED
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The version comparison the harness installs share. One strict form reads a
3
+ * full semver and orders prereleases; codex's prefix form is lenient in another
4
+ * way: an unreadable version is not compared.
5
+ */
6
+
7
+ import { compareVersionText, readVersionText } from "@operad-io/engine";
8
+
9
+ /** Negative, zero or positive as version `a` is below, equal to or above `b`. */
10
+ export function compareVersions(
11
+ a: string,
12
+ b: string,
13
+ onInvalid?: ((version: string) => Error) | undefined,
14
+ ): number {
15
+ const left = readVersionText(a);
16
+ const right = readVersionText(b);
17
+ if (left === undefined || right === undefined) {
18
+ const bad = left === undefined ? a : b;
19
+ throw onInvalid?.(bad) ?? new Error(`not a version: ${bad}`);
20
+ }
21
+ return compareVersionText(left, right);
22
+ }
23
+
24
+ /** A strict comparison whose error for an unreadable version is this harness's. */
25
+ export function strictVersionCompare(
26
+ onInvalid: (version: string) => Error,
27
+ ): (a: string, b: string) => number {
28
+ return (a, b) => compareVersions(a, b, onInvalid);
29
+ }
30
+
31
+ /** The first three numbers of a version, as codex reports them; undefined when it has none. */
32
+ function versionPrefix(version: string): readonly [number, number, number] | undefined {
33
+ const found = /^(\d+)\.(\d+)\.(\d+)/.exec(version);
34
+ if (found === null) return undefined;
35
+ return [Number(found[1]), Number(found[2]), Number(found[3])];
36
+ }
37
+
38
+ /** Whether `version` is at least `floor`; an unreadable version is not compared. */
39
+ export function versionAtLeast(version: string, floor: string): boolean {
40
+ const left = versionPrefix(version);
41
+ const right = versionPrefix(floor);
42
+ if (left === undefined || right === undefined) return true;
43
+ for (let index = 0; index < 3; index += 1) {
44
+ const a = left[index] ?? 0;
45
+ const b = right[index] ?? 0;
46
+ if (a !== b) return a > b;
47
+ }
48
+ return true;
49
+ }
package/src/wire.ts ADDED
@@ -0,0 +1,205 @@
1
+ /**
2
+ * The wire shapes and the input checks the claude and pi child programs share.
3
+ * Each program keeps its own input and output where they differ; these are the
4
+ * fields both read the same way and the messages both give for a wrong one.
5
+ */
6
+
7
+ import { readProfile } from "@operad-io/access-match";
8
+ import { isRecord } from "@operad-io/engine";
9
+ import { parseImageInputs, type ImageInput } from "./images.ts";
10
+ import type { WorkerKeep } from "./keep.ts";
11
+
12
+ /** What one model call used, as both workers report it. */
13
+ export interface WorkerUsage {
14
+ input?: number;
15
+ output?: number;
16
+ cache_read?: number;
17
+ cache_write?: number;
18
+ }
19
+
20
+ export type WorkerResultName = "done" | "failed" | "cancelled";
21
+
22
+ /**
23
+ * A stdin line after the input: the host's answer to an `ask_call` line.
24
+ * `allow` lets this one call run; `deny` refuses it; `stop` means the wait
25
+ * ended and the program is about to be ended: it holds the call.
26
+ */
27
+ export interface AskAck {
28
+ readonly type: "ask_ack";
29
+ readonly id: number;
30
+ readonly decision: "allow" | "deny" | "stop";
31
+ readonly reason?: string;
32
+ }
33
+
34
+ /** A stdin line after the input: the host's answer to a `grant_use` line. */
35
+ export interface GrantAck {
36
+ readonly type: "grant_ack";
37
+ readonly id: number;
38
+ readonly used: boolean;
39
+ }
40
+
41
+ /** One field read: its value, or the message that names what is wrong. */
42
+ export type FieldRead<T> =
43
+ | { readonly ok: true; readonly value: T }
44
+ | { readonly ok: false; readonly message: string };
45
+
46
+ function failed<T>(message: string): FieldRead<T> {
47
+ return { ok: false, message };
48
+ }
49
+
50
+ function read<T>(value: T): FieldRead<T> {
51
+ return { ok: true, value };
52
+ }
53
+
54
+ /** Refuses a field the program does not know, never ignoring it. */
55
+ export function readUnknownFields(
56
+ value: Readonly<Record<string, unknown>>,
57
+ fields: readonly string[],
58
+ ): FieldRead<undefined> {
59
+ for (const key of Object.keys(value)) {
60
+ if (!fields.includes(key)) return failed(`${key} is not an input field`);
61
+ }
62
+ return read(undefined);
63
+ }
64
+
65
+ /** Reads fields that must be non-empty strings. */
66
+ export function readRequiredStrings(
67
+ value: Readonly<Record<string, unknown>>,
68
+ fields: readonly string[],
69
+ ): FieldRead<Readonly<Record<string, string>>> {
70
+ const strings: Record<string, string> = {};
71
+ for (const field of fields) {
72
+ const found = value[field];
73
+ if (found === undefined) return failed(`${field} is required`);
74
+ if (typeof found !== "string" || found.length === 0) {
75
+ return failed(`${field} must be a non-empty string`);
76
+ }
77
+ strings[field] = found;
78
+ }
79
+ return read(strings);
80
+ }
81
+
82
+ /** Reads a field that is a non-empty string when it is there. */
83
+ export function readOptionalString(
84
+ value: Readonly<Record<string, unknown>>,
85
+ field: string,
86
+ ): FieldRead<string | undefined> {
87
+ const found = value[field];
88
+ if (found === undefined) return read(undefined);
89
+ if (typeof found !== "string" || found.length === 0) {
90
+ return failed(`${field} must be a non-empty string`);
91
+ }
92
+ return read(found);
93
+ }
94
+
95
+ /** Reads a field that is a boolean when it is there. */
96
+ export function readBoolean(
97
+ value: Readonly<Record<string, unknown>>,
98
+ field: string,
99
+ ): FieldRead<boolean | undefined> {
100
+ const found = value[field];
101
+ if (found === undefined) return read(undefined);
102
+ if (typeof found !== "boolean") return failed(`${field} must be a boolean`);
103
+ return read(found);
104
+ }
105
+
106
+ /** Reads a field that is a positive integer when it is there. */
107
+ export function readPositiveInteger(
108
+ value: Readonly<Record<string, unknown>>,
109
+ field: string,
110
+ ): FieldRead<number | undefined> {
111
+ const found = value[field];
112
+ if (found === undefined) return read(undefined);
113
+ if (typeof found !== "number" || !Number.isInteger(found) || found < 1) {
114
+ return failed(`${field} must be a positive integer`);
115
+ }
116
+ return read(found);
117
+ }
118
+
119
+ /** Reads a field that is a positive number when it is there. */
120
+ export function readPositiveNumber(
121
+ value: Readonly<Record<string, unknown>>,
122
+ field: string,
123
+ ): FieldRead<number | undefined> {
124
+ const found = value[field];
125
+ if (found === undefined) return read(undefined);
126
+ if (typeof found !== "number" || !Number.isFinite(found) || found <= 0) {
127
+ return failed(`${field} must be a positive number`);
128
+ }
129
+ return read(found);
130
+ }
131
+
132
+ /** Reads a field that is an array of strings when it is there. */
133
+ export function readStringList(
134
+ value: Readonly<Record<string, unknown>>,
135
+ field: string,
136
+ ): FieldRead<readonly string[] | undefined> {
137
+ const found = value[field];
138
+ if (found === undefined) return read(undefined);
139
+ if (!Array.isArray(found) || !found.every((item) => typeof item === "string")) {
140
+ return failed(`${field} must be an array of strings`);
141
+ }
142
+ return read(found as readonly string[]);
143
+ }
144
+
145
+ /** Reads the secret values a log line masks. */
146
+ export function readSecrets(value: Readonly<Record<string, unknown>>): FieldRead<readonly string[] | undefined> {
147
+ return readStringList(value, "secretValues");
148
+ }
149
+
150
+ /** Reads the images a prompt carries, from their files. */
151
+ export function readImages(value: Readonly<Record<string, unknown>>): FieldRead<readonly ImageInput[]> {
152
+ const images = parseImageInputs(value["images"]);
153
+ return typeof images === "string" ? failed(images) : read(images);
154
+ }
155
+
156
+ /** Reads operad's own tools, served from one home. */
157
+ export function readOperadTools(
158
+ value: Readonly<Record<string, unknown>>,
159
+ ): FieldRead<{ readonly home: string } | undefined> {
160
+ const found = value["operadTools"];
161
+ if (found === undefined) return read(undefined);
162
+ if (!isRecord(found) || typeof found["home"] !== "string" || found["home"].length === 0) {
163
+ return failed("operadTools must be an object with a home");
164
+ }
165
+ return read({ home: String(found["home"]) });
166
+ }
167
+
168
+ /** Reads an access profile, naming the field the profile refuses. */
169
+ export function readAccess(
170
+ value: Readonly<Record<string, unknown>>,
171
+ ): FieldRead<Readonly<Record<string, unknown>> | undefined> {
172
+ const found = value["access"];
173
+ if (found === undefined) return read(undefined);
174
+ if (!isRecord(found)) return failed("access must be an object");
175
+ const profile = readProfile(found);
176
+ if (!profile.ok) return failed(`access.${profile.message}`);
177
+ return read(found);
178
+ }
179
+
180
+ /** Reads the request to keep the worker after this reply. */
181
+ export function readKeep(value: Readonly<Record<string, unknown>>): FieldRead<WorkerKeep | undefined> {
182
+ const found = value["keep"];
183
+ if (found === undefined) return read(undefined);
184
+ if (!isRecord(found)) return failed("keep must be an object");
185
+ const fields: Record<string, string> = {};
186
+ for (const field of ["socket", "meta", "token", "scope", "key"] as const) {
187
+ const field_ = found[field];
188
+ if (typeof field_ !== "string" || field_.length === 0) {
189
+ return failed(`keep.${field} must be a non-empty string`);
190
+ }
191
+ fields[field] = field_;
192
+ }
193
+ const timeoutMs = found["timeoutMs"];
194
+ if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
195
+ return failed("keep.timeoutMs must be a positive number");
196
+ }
197
+ return read({
198
+ socket: fields["socket"] ?? "",
199
+ meta: fields["meta"] ?? "",
200
+ token: fields["token"] ?? "",
201
+ scope: fields["scope"] ?? "",
202
+ key: fields["key"] ?? "",
203
+ timeoutMs,
204
+ });
205
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * The process entry every child program shares: stdin in, stdout lines out,
3
+ * the exit code out. A program supplies its adapter and what its own runtime
4
+ * needs removed or ignored.
5
+ */
6
+
7
+ import { existsSync } from "node:fs";
8
+ import { serveKeptWorker, type ParsedInput, type WorkerAdapter } from "./keep.ts";
9
+
10
+ /** Reads one input object; invalid JSON is a parse failure. */
11
+ export function decodeWorkerInput<TInput>(
12
+ text: string,
13
+ parse: (value: unknown) => ParsedInput<TInput>,
14
+ ): ParsedInput<TInput> {
15
+ let decoded: unknown;
16
+ try {
17
+ decoded = JSON.parse(text);
18
+ } catch {
19
+ return { ok: false, message: "the input is not valid JSON" };
20
+ }
21
+ return parse(decoded);
22
+ }
23
+
24
+ /** What a plugin's `check` knows about its worker program. */
25
+ export interface WorkerAvailability {
26
+ /** The executable a test injected; the running Bun when it is unset. */
27
+ readonly command?: string | undefined;
28
+ /** The arguments a test injected; the worker program when they are unset. */
29
+ readonly args?: readonly string[] | undefined;
30
+ /** The worker program the plugin starts. */
31
+ readonly workerPath: string;
32
+ }
33
+
34
+ /** Refuses `check` when the running Bun or the worker program is not there. */
35
+ export function assertWorkerAvailable(availability: WorkerAvailability): void {
36
+ if (availability.command === undefined && !existsSync(process.execPath)) {
37
+ throw new Error("bun was not found");
38
+ }
39
+ if (availability.args === undefined && !existsSync(availability.workerPath)) {
40
+ throw new Error(`the worker program is missing: ${availability.workerPath}`);
41
+ }
42
+ }
43
+
44
+ /** What a program's entry needs beyond its adapter. */
45
+ export interface WorkerMainOptions {
46
+ /** Environment variables the program's own runtime must not see. */
47
+ readonly envToDelete?: readonly string[] | undefined;
48
+ }
49
+
50
+ /** The process entry: stdin in, stdout lines out, exit code out. */
51
+ export async function runWorkerMain<TInput>(
52
+ adapter: WorkerAdapter<TInput>,
53
+ options: WorkerMainOptions = {},
54
+ ): Promise<never> {
55
+ const flush = (): Promise<void> =>
56
+ new Promise((resolve) => {
57
+ process.stdout.write("", () => resolve());
58
+ });
59
+ // Anything that prints to stdout by accident would corrupt the protocol.
60
+ console.log = (...args: unknown[]): void => {
61
+ process.stderr.write(`${args.map(String).join(" ")}\n`);
62
+ };
63
+ for (const name of options.envToDelete ?? []) delete process.env[name];
64
+
65
+ const controller = new AbortController();
66
+ process.on("SIGTERM", () => controller.abort());
67
+ // A host that closes its end of stdout or stderr has ended the conversation;
68
+ // it must not turn the worker's next write into an unhandled stream error.
69
+ process.stdout.on("error", () => undefined);
70
+ process.stderr.on("error", () => undefined);
71
+ const code = await serveKeptWorker(
72
+ Bun.stdin.stream(),
73
+ {
74
+ write: (text) => {
75
+ process.stdout.write(text);
76
+ },
77
+ log: (text) => process.stderr.write(`${text}\n`),
78
+ },
79
+ controller.signal,
80
+ adapter,
81
+ );
82
+ await flush();
83
+ process.exit(code);
84
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * The second half of the `agent` step of the process harnesses that speak a
3
+ * line protocol over stdin and stdout: the call asker, the run, the log and the
4
+ * result. claude and pi share this shape; only the program and the way one line
5
+ * names a tool call differ.
6
+ */
7
+
8
+ import { AskTimeoutError, type PluginStepResult } from "@operad-io/engine";
9
+ import type { AgentStepAccess, AgentStepValues } from "./agent-step.ts";
10
+ import { askFormRequest, askToolEvent, createCallAsker, formAnswer, type AskForm } from "./ask-call.ts";
11
+ import { answerGrant } from "./grants.ts";
12
+ import { inboxOf } from "./inbox.ts";
13
+ import { JsonlLog } from "./jsonl-log.ts";
14
+ import { deliverLine } from "./lines.ts";
15
+ import { runAgent, skippedLineRecord, type KeptRunOptions, type ToolEvent } from "./process.ts";
16
+ import { resultFor, resultValue, type AgentWorkerResult } from "./step.ts";
17
+ import { withTimings } from "./timings.ts";
18
+ import type { Clock } from "@operad-io/engine/platform";
19
+
20
+ /** What one process harness adds to the shared run of its worker. */
21
+ export interface WorkerStepSpec {
22
+ readonly values: AgentStepValues<string>;
23
+ readonly access: AgentStepAccess;
24
+ readonly command: string;
25
+ readonly args: readonly string[];
26
+ /** The JSON object written to the worker's stdin. */
27
+ readonly stdin: Record<string, unknown>;
28
+ readonly keep: KeptRunOptions | undefined;
29
+ readonly clock: Clock;
30
+ readonly now: () => number;
31
+ /** The classifier of this harness's tool call lines. */
32
+ readonly toolEvent: (line: string) => ToolEvent | undefined;
33
+ /** True when the worker puts an agent's own question to a person. */
34
+ readonly forms?: boolean | undefined;
35
+ /** True when a done result names the model that did the work. */
36
+ readonly modelFromResult?: boolean | undefined;
37
+ }
38
+
39
+ /**
40
+ * Runs one worker, answers its permission lines and reads the last `result`
41
+ * line. A question that ran out of grace ends the worker, and the kernel turns
42
+ * that into the result `waiting`.
43
+ */
44
+ export async function runWorkerStep(spec: WorkerStepSpec): Promise<PluginStepResult> {
45
+ const { values, access } = spec;
46
+ const { ctx, harness, timings } = values;
47
+ const inbox = inboxOf(values.params);
48
+ const jsonl = new JsonlLog(ctx.logger, spec.clock, spec.now);
49
+ let result: AgentWorkerResult | undefined;
50
+ // Ends the program when a question about a call runs out of grace.
51
+ const stopper = new AbortController();
52
+ const asker = createCallAsker({
53
+ ask: (request) => ctx.ask(request),
54
+ ...(spec.forms === true
55
+ ? {
56
+ // The agent's own questions are one form the person fills in.
57
+ async askForm(form: AskForm) {
58
+ try {
59
+ return formAnswer(await ctx.ask(askFormRequest(form)));
60
+ } catch (error) {
61
+ if (error instanceof AskTimeoutError) return { decision: "stop" as const };
62
+ throw error;
63
+ }
64
+ },
65
+ }
66
+ : {}),
67
+ onStop: () => stopper.abort(),
68
+ secrets: access.secrets,
69
+ ...(access.allowAlways ? { alwaysAllow: { home: ctx.home, cwd: values.cwd } } : {}),
70
+ ...(ctx.flow === undefined ? {} : { targetGrants: { home: ctx.home, flow: ctx.flow } }),
71
+ onLog: (message) => {
72
+ void ctx.logger.write(message);
73
+ },
74
+ });
75
+
76
+ const outcome = await runAgent({
77
+ command: spec.command,
78
+ args: spec.args,
79
+ cwd: values.cwd,
80
+ stdin: JSON.stringify(spec.stdin),
81
+ interactive: access.interactive,
82
+ inbox,
83
+ ...(spec.keep === undefined ? {} : { keep: spec.keep }),
84
+ wallMs: values.wallTimeSecs * 1000,
85
+ stallMs: values.stallSecs * 1000,
86
+ signal: AbortSignal.any([ctx.signal, stopper.signal]),
87
+ clock: spec.clock,
88
+ toolEvent: (line) => spec.toolEvent(line) ?? askToolEvent(line),
89
+ onSkipped: (chars) => {
90
+ void jsonl.pushStamped(jsonl.stamp(skippedLineRecord(chars)));
91
+ },
92
+ async onLine(line, reply) {
93
+ const received = jsonl.stamp(line);
94
+ timings.record(received.value, received.at);
95
+ await answerGrant(received.text, (waitId) => ctx.useGrant(waitId), reply);
96
+ await asker.handle(received.text, reply);
97
+ const writing = jsonl.pushStamped(received);
98
+ deliverLine(ctx.receiver, received.text, access.secrets);
99
+ const parsed = resultValue<AgentWorkerResult>(received.value);
100
+ if (parsed !== undefined) result = parsed;
101
+ return writing;
102
+ },
103
+ });
104
+ await jsonl.end();
105
+
106
+ // The grace passed with a question open: the program was ended on purpose.
107
+ const unanswered = asker.stopped();
108
+ if (unanswered !== undefined && !ctx.signal.aborted) throw unanswered.error;
109
+
110
+ const timing = timings.finish();
111
+ const stepResult = resultFor(
112
+ // The step's own model, else the one the worker reports having used.
113
+ { harness, model: spec.modelFromResult === true ? (values.model ?? result?.model ?? null) : (values.model ?? null) },
114
+ outcome,
115
+ result,
116
+ ctx.logger.path,
117
+ timing.totalMs,
118
+ { wallTimeSecs: values.wallTimeSecs, stallSecs: values.stallSecs },
119
+ spec.command,
120
+ );
121
+ return withTimings(stepResult, timing);
122
+ }