@operad-io/harness-process 0.0.0-stage → 0.0.1

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/inbox.ts ADDED
@@ -0,0 +1,45 @@
1
+ /**
2
+ * A way for the host to say something to an agent that is already running.
3
+ *
4
+ * `dev` hands a harness step an object under `params.inbox` with one method,
5
+ * `listen(handler)`. The handler gets each message the host sends, in order,
6
+ * including the ones sent before it listened; the returned function stops
7
+ * listening. A harness that can take a message mid-run listens and passes the
8
+ * text on; one that cannot ignores the field and the run goes on without it.
9
+ */
10
+ export interface MessageInbox {
11
+ listen(handler: (text: string) => void): () => void;
12
+ /**
13
+ * Tells the host the run has begun and how long it may last, in
14
+ * milliseconds, so it can time what it says from the run's own start.
15
+ */
16
+ begin?(limitMs: number): void;
17
+ }
18
+
19
+ /** The inbox in a step's params, or undefined when the host gave none. */
20
+ export function inboxOf(params: unknown): MessageInbox | undefined {
21
+ if (typeof params !== "object" || params === null) return undefined;
22
+ const inbox: unknown = Reflect.get(params, "inbox");
23
+ if (typeof inbox !== "object" || inbox === null) return undefined;
24
+ return typeof Reflect.get(inbox, "listen") === "function"
25
+ ? (inbox as MessageInbox)
26
+ : undefined;
27
+ }
28
+
29
+ /** The stdin line a worker program reads as a message from the host. */
30
+ export function messageLine(text: string): string {
31
+ return JSON.stringify({ type: "message", text });
32
+ }
33
+
34
+ /** The text of a `message` stdin line, or undefined for any other line. */
35
+ export function messageText(line: string): string | undefined {
36
+ try {
37
+ const value: unknown = JSON.parse(line);
38
+ if (typeof value !== "object" || value === null) return undefined;
39
+ if (Reflect.get(value, "type") !== "message") return undefined;
40
+ const text: unknown = Reflect.get(value, "text");
41
+ return typeof text === "string" ? text : undefined;
42
+ } catch {
43
+ return undefined;
44
+ }
45
+ }
package/src/index.ts ADDED
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The process helper every harness needs: run one agent command in a process
3
+ * group of its own, watch the wall time and a stalled output stream, and append
4
+ * its JSONL to the step's log. Radian and pi share this shape; only the command
5
+ * and the way one line names a tool call differ.
6
+ */
7
+
8
+ export * from "./acp.ts";
9
+ export * from "./always-allow.ts";
10
+ export * from "./ask-call.ts";
11
+ export * from "./ask-note.ts";
12
+ export * from "./event-note.ts";
13
+ export * from "./grants.ts";
14
+ export * from "./images.ts";
15
+ export * from "./inbox.ts";
16
+ export * from "./fold-lines.ts";
17
+ export * from "./jsonl-log.ts";
18
+ export * from "./lines.ts";
19
+ export * from "./operad-tools.ts";
20
+ export * from "./process.ts";
21
+ export * from "./step.ts";
22
+ export * from "./limit.ts";
23
+ export * from "./usage.ts";
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Appends complete JSONL lines to the step's log. A full buffer is written
3
+ * before the caller hands over more lines: `push` returns the pending write, so
4
+ * a harness that outruns the disk cannot queue writes without limit.
5
+ */
6
+
7
+ import type { PluginLogger } from "@operad-io/engine";
8
+ import { systemClock, type Clock } from "@operad-io/engine/platform";
9
+
10
+ /** How much text one write carries before the caller must wait for it. */
11
+ export const FLUSH_CHARS = 16 * 1024;
12
+
13
+ /** The longest a line waits in the buffer before it is written. */
14
+ export const FLUSH_MS = 250;
15
+
16
+ export class JsonlLog {
17
+ private buffer = "";
18
+ private timer: unknown = undefined;
19
+ private chain: Promise<void> = Promise.resolve();
20
+ private wrote = false;
21
+ private readonly logger: PluginLogger;
22
+ private readonly clock: Clock;
23
+
24
+ constructor(logger: PluginLogger, clock: Clock = systemClock) {
25
+ this.logger = logger;
26
+ this.clock = clock;
27
+ }
28
+
29
+ /**
30
+ * Adds one line. Once the buffer is full, returns the write to wait for; the
31
+ * caller that awaits it keeps at most one buffered chunk and one write in
32
+ * memory. Before that it returns nothing.
33
+ */
34
+ push(line: string): Promise<void> | undefined {
35
+ this.buffer += `${line}\n`;
36
+ if (this.buffer.length >= FLUSH_CHARS) return this.flush();
37
+ // A short buffer is written within FLUSH_MS of its first line.
38
+ if (this.timer === undefined) {
39
+ this.timer = this.clock.setTimeout(() => {
40
+ this.timer = undefined;
41
+ // A failed write is raised by `end`, which waits for the chain.
42
+ this.flush().catch(() => undefined);
43
+ }, FLUSH_MS);
44
+ }
45
+ return undefined;
46
+ }
47
+
48
+ /** Writes the rest and waits for every queued write. */
49
+ async end(): Promise<void> {
50
+ this.flush();
51
+ if (!this.wrote) {
52
+ this.chain = this.chain.then(() => this.logger.write("")).then(() => undefined);
53
+ }
54
+ await this.chain;
55
+ }
56
+
57
+ private flush(): Promise<void> {
58
+ if (this.timer !== undefined) {
59
+ this.clock.clearTimeout(this.timer);
60
+ this.timer = undefined;
61
+ }
62
+ const text = this.buffer;
63
+ this.buffer = "";
64
+ if (text.length === 0) return this.chain;
65
+ this.wrote = true;
66
+ this.chain = this.chain
67
+ .then(() => this.logger.write(text))
68
+ .then(() => undefined);
69
+ return this.chain;
70
+ }
71
+ }
package/src/limit.ts ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The step limit of a harness `agent` step: how many runs of one model may be
3
+ * going at once. The key is `<harness>:<model>`; the count comes from the
4
+ * plugin setting `concurrency`, a map from model to a positive integer. A
5
+ * model that is not in the map, or a step that names no model, has no limit.
6
+ */
7
+
8
+ import type { StepLimitDefinition } from "@operad-io/engine";
9
+ import { isRecord } from "@operad-io/engine";
10
+
11
+ /** The settings schema property both harnesses declare for `concurrency`. */
12
+ export const CONCURRENCY_SETTING = {
13
+ type: "object" as const,
14
+ additionalProperties: {
15
+ type: "integer" as const,
16
+ minimum: 1,
17
+ },
18
+ default: {},
19
+ description:
20
+ 'How many agent runs of one model may go at once, as { "<model>": <count> }. A model not listed has no limit. Takes effect with the next step that starts.',
21
+ };
22
+
23
+ /**
24
+ * The value of `flag` in an `args` list, as `--flag value` or `--flag=value`.
25
+ * A flag given more than once takes its last value, as radian does.
26
+ */
27
+ export function flagValue(args: unknown, flag: string): string | undefined {
28
+ if (!Array.isArray(args)) return undefined;
29
+ let found: string | undefined;
30
+ for (let index = 0; index < args.length; index += 1) {
31
+ const entry = args[index];
32
+ if (typeof entry !== "string") continue;
33
+ if (entry === flag) {
34
+ const value = args[index + 1];
35
+ if (typeof value === "string") found = value;
36
+ } else if (entry.startsWith(`${flag}=`)) {
37
+ found = entry.slice(flag.length + 1);
38
+ }
39
+ }
40
+ return found;
41
+ }
42
+
43
+ /**
44
+ * Builds the `limit` of a harness step. `modelOf` names the model one call
45
+ * uses, from the step's params and the plugin settings, or nothing.
46
+ */
47
+ export function modelLimit(
48
+ harness: string,
49
+ modelOf: (
50
+ params: unknown,
51
+ settings: Readonly<Record<string, unknown>>,
52
+ ) => string | undefined,
53
+ ): StepLimitDefinition {
54
+ const countFor = (
55
+ model: string,
56
+ settings: Readonly<Record<string, unknown>>,
57
+ ): number | undefined => {
58
+ const map = settings.concurrency;
59
+ if (map === undefined) return undefined;
60
+ if (!isRecord(map)) {
61
+ throw new Error("settings.concurrency: must be an object");
62
+ }
63
+ const count = map[model];
64
+ if (count === undefined) return undefined;
65
+ if (typeof count !== "number" || !Number.isInteger(count) || count < 1) {
66
+ throw new Error(
67
+ `settings.concurrency: "${model}" must be a positive integer`,
68
+ );
69
+ }
70
+ return count;
71
+ };
72
+ return {
73
+ key: (params, settings) => {
74
+ const model = modelOf(params, settings);
75
+ if (model === undefined) return undefined;
76
+ return countFor(model, settings) === undefined
77
+ ? undefined
78
+ : `${harness}:${model}`;
79
+ },
80
+ concurrent: (params, settings) => {
81
+ const model = modelOf(params, settings);
82
+ const count = model === undefined ? undefined : countFor(model, settings);
83
+ if (count === undefined) {
84
+ throw new Error("concurrent: the step has no limit");
85
+ }
86
+ return count;
87
+ },
88
+ };
89
+ }
package/src/lines.ts ADDED
@@ -0,0 +1,138 @@
1
+ /**
2
+ * The lines the child programs of the claude and pi harnesses, and radian's
3
+ * journal once `radianLogLine` has turned it into the same shapes, write to a
4
+ * step's log. A harness keeps in its own protocol only the lines that are its
5
+ * own (a session, a message's usage, a result).
6
+ */
7
+
8
+ /** The longest tool output one `tool_output` line carries, in bytes of UTF-8. */
9
+ export const TOOL_OUTPUT_CAP_BYTES = 64 * 1024;
10
+
11
+ export type SharedLine =
12
+ | {
13
+ readonly type: "tool_execution_start";
14
+ readonly toolCallId: string;
15
+ readonly toolName: string;
16
+ /** When the call started, in epoch milliseconds. */
17
+ readonly at: number;
18
+ /** What ran: the command (500 characters), the path, or the main argument; absent when there is none. */
19
+ readonly input?: string;
20
+ }
21
+ | {
22
+ readonly type: "tool_execution_end";
23
+ readonly toolCallId: string;
24
+ readonly toolName: string;
25
+ readonly isError: boolean;
26
+ /** How long the call took. */
27
+ readonly durationMs: number;
28
+ /** The first line of the error, when the call failed. */
29
+ readonly error?: string;
30
+ }
31
+ | { readonly type: "blocked"; readonly toolName: string; readonly reason: string }
32
+ /**
33
+ * The program asks to use up a one-time permission before it lets a call
34
+ * through. The host writes the fact and answers on stdin with a
35
+ * `GrantAck` line; only `used: true` lets the call run.
36
+ */
37
+ | { readonly type: "grant_use"; readonly id: number; readonly waitId: string }
38
+ /**
39
+ * The program asks a person whether one call may run (the access profile's
40
+ * `askCommands`) and holds the call until the host answers with an `AskAck`
41
+ * line. `session` is what a late answer continues. `ask_resolved` follows
42
+ * the answer, so the host knows the question is closed.
43
+ */
44
+ | {
45
+ readonly type: "ask_call";
46
+ readonly id: number;
47
+ readonly kind: "command" | "path";
48
+ readonly value: string;
49
+ readonly tool?: string;
50
+ readonly shown: string;
51
+ readonly session: string | null;
52
+ }
53
+ | { readonly type: "ask_resolved"; readonly id: number }
54
+ /** New assistant text only, not the text so far. */
55
+ | { readonly type: "text_delta"; readonly text: string }
56
+ /** New thinking only, not the thinking so far. */
57
+ | { readonly type: "thinking_delta"; readonly text: string }
58
+ /** The full text of a finished assistant message. */
59
+ | { readonly type: "text_end"; readonly text: string }
60
+ /** The full text of a finished thinking block. */
61
+ | { readonly type: "thinking_end"; readonly text: string }
62
+ /**
63
+ * What a tool call printed. A line carries at most `TOOL_OUTPUT_CAP_BYTES`;
64
+ * a longer output is written as consecutive lines with the same call id.
65
+ * `truncated` is only for a line a caller had to cut.
66
+ */
67
+ | {
68
+ readonly type: "tool_output";
69
+ readonly toolCallId: string;
70
+ readonly text: string;
71
+ readonly truncated?: true;
72
+ };
73
+
74
+ /** Cuts `text` to the output cap without splitting a character; says whether it cut. */
75
+ export function capToolOutput(text: string): { readonly text: string; readonly truncated: boolean } {
76
+ const bytes = new TextEncoder().encode(text);
77
+ if (bytes.length <= TOOL_OUTPUT_CAP_BYTES) return { text, truncated: false };
78
+ // Back off to the start of a character: a continuation byte is 10xxxxxx.
79
+ let end = TOOL_OUTPUT_CAP_BYTES;
80
+ while (end > 0 && ((bytes[end] ?? 0) & 0xc0) === 0x80) end -= 1;
81
+ const cut = new TextDecoder().decode(bytes.subarray(0, end));
82
+ return { text: cut, truncated: true };
83
+ }
84
+
85
+ /**
86
+ * The `tool_output` payloads for what a tool printed: the text masked once,
87
+ * then cut into pieces no longer than the shared cap. Joining the pieces gives
88
+ * the whole output back; a short output is one piece.
89
+ */
90
+ export function toolOutputLines(
91
+ text: string,
92
+ secrets: readonly string[],
93
+ ): readonly { readonly text: string }[] {
94
+ const masked = maskSecrets(text, secrets);
95
+ const bytes = new TextEncoder().encode(masked);
96
+ if (bytes.length <= TOOL_OUTPUT_CAP_BYTES) return [{ text: masked }];
97
+ const lines: { text: string }[] = [];
98
+ const decoder = new TextDecoder();
99
+ let start = 0;
100
+ while (start < bytes.length) {
101
+ let end = Math.min(start + TOOL_OUTPUT_CAP_BYTES, bytes.length);
102
+ // Back off to the start of a character: a continuation byte is 10xxxxxx.
103
+ while (end > start && ((bytes[end] ?? 0) & 0xc0) === 0x80) end -= 1;
104
+ lines.push({ text: decoder.decode(bytes.subarray(start, end)) });
105
+ start = end;
106
+ }
107
+ return lines;
108
+ }
109
+
110
+ /** Replaces every secret value in a log line, also as it is written inside JSON text, with `***`. */
111
+ export function maskSecrets(line: string, secrets: readonly string[]): string {
112
+ let masked = line;
113
+ for (const secret of [...secrets].sort((x, y) => y.length - x.length)) {
114
+ if (secret.length === 0) continue;
115
+ masked = masked.split(secret).join("***");
116
+ const escaped = JSON.stringify(secret).slice(1, -1);
117
+ if (escaped !== secret) masked = masked.split(escaped).join("***");
118
+ }
119
+ return masked;
120
+ }
121
+
122
+ /**
123
+ * Hands a line that was written to the log to the caller's receiver, with the
124
+ * secret values masked. A receiver that throws does not stop the step: the log
125
+ * has the line.
126
+ */
127
+ export function deliverLine(
128
+ receiver: ((line: string) => void) | undefined,
129
+ line: string,
130
+ secrets: readonly string[],
131
+ ): void {
132
+ if (receiver === undefined) return;
133
+ try {
134
+ receiver(maskSecrets(line, secrets));
135
+ } catch {
136
+ // the log is the record; the caller's trouble stays the caller's
137
+ }
138
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Operad's own tools for a harness: the `operadTools` param of an `agent` step
3
+ * names the home whose tools the agent may call. A harness that starts MCP
4
+ * servers starts `operad`'s as a program (`serverCommand`); one that takes
5
+ * tools in its own process opens them (`@operad-io/mcp`, `openMcpTools`). The
6
+ * agent never runs the `operad` command.
7
+ */
8
+
9
+ import { fileURLToPath } from "node:url";
10
+ import { isRecord } from "@operad-io/engine";
11
+
12
+ /** The name the tools go by in a harness: the server's name, and the prefix claude gives its tools. */
13
+ export const OPERAD_SERVER = "operad";
14
+
15
+ /** The prefix of an MCP tool's name in claude. */
16
+ export const OPERAD_TOOL_PREFIX = `mcp__${OPERAD_SERVER}__`;
17
+
18
+ /** What the `operadTools` param holds. */
19
+ export interface OperadTools {
20
+ /** The operad home the tools read and write. */
21
+ readonly home: string;
22
+ }
23
+
24
+ /** The tools a step's params ask for, or undefined when they ask for none. */
25
+ export function operadToolsOf(value: unknown): OperadTools | undefined {
26
+ if (!isRecord(value)) return undefined;
27
+ const home = value.home;
28
+ return typeof home === "string" && home.length > 0 ? { home } : undefined;
29
+ }
30
+
31
+ /** The program that serves the tools on stdio, and its arguments. */
32
+ export function serverCommand(tools: OperadTools): { readonly command: string; readonly args: readonly string[] } {
33
+ const script = fileURLToPath(import.meta.resolve("@operad-io/mcp/stdio"));
34
+ return { command: process.execPath, args: [script, "--home", tools.home] };
35
+ }
36
+
37
+ /** A server a bot's settings list, started as this command; its name is the one its tools go by. */
38
+ export interface MountedServer {
39
+ readonly command: string;
40
+ readonly args: readonly string[];
41
+ }
42
+
43
+ /**
44
+ * The `mcpServers` param of an `agent` step: other MCP servers to start for
45
+ * the agent, by name. The name of operad's own server is not available.
46
+ */
47
+ export function mountedServersOf(value: unknown): Readonly<Record<string, MountedServer>> | undefined {
48
+ if (!isRecord(value)) return undefined;
49
+ const found: Record<string, MountedServer> = {};
50
+ for (const [name, entry] of Object.entries(value)) {
51
+ if (name === OPERAD_SERVER || name.length === 0 || name.includes("__")) continue;
52
+ if (!isRecord(entry) || typeof entry.command !== "string" || entry.command.length === 0) continue;
53
+ const args = Array.isArray(entry.args) ? entry.args.filter((item): item is string => typeof item === "string") : [];
54
+ found[name] = { command: entry.command, args };
55
+ }
56
+ return Object.keys(found).length === 0 ? undefined : found;
57
+ }