@operad-io/harness-process 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/LICENSE +21 -0
- package/README.md +11 -2
- package/access-user.schema.json +52 -0
- package/package.json +22 -4
- package/src/acp.ts +370 -0
- package/src/always-allow.ts +204 -0
- package/src/ask-call.ts +252 -0
- package/src/ask-note.ts +47 -0
- package/src/event-note.ts +23 -0
- package/src/fold-lines.ts +238 -0
- package/src/grants.ts +53 -0
- package/src/images.ts +43 -0
- package/src/inbox.ts +45 -0
- package/src/index.ts +23 -0
- package/src/jsonl-log.ts +71 -0
- package/src/limit.ts +89 -0
- package/src/lines.ts +138 -0
- package/src/operad-tools.ts +57 -0
- package/src/process.ts +568 -0
- package/src/step.ts +293 -0
- package/src/usage.ts +62 -0
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Folds the lines of a step's log into entries: what the agent said, what it
|
|
3
|
+
* thought and each tool call. A pure function: the state it returns can be fed
|
|
4
|
+
* back with the next lines, and the entries are the same whether the lines come
|
|
5
|
+
* all at once or one at a time.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { isRecord } from "@operad-io/engine";
|
|
9
|
+
|
|
10
|
+
export type ToolResult = "done" | "failed" | "blocked" | "denied";
|
|
11
|
+
|
|
12
|
+
export type FoldEntry =
|
|
13
|
+
| { readonly kind: "text"; readonly text: string }
|
|
14
|
+
| { readonly kind: "thinking"; readonly text: string }
|
|
15
|
+
| {
|
|
16
|
+
readonly kind: "tool";
|
|
17
|
+
readonly callId: string;
|
|
18
|
+
readonly toolName: string;
|
|
19
|
+
readonly input: string | null;
|
|
20
|
+
readonly result: ToolResult;
|
|
21
|
+
/** Epoch milliseconds; null when the log has no start line for the call. */
|
|
22
|
+
readonly at: number | null;
|
|
23
|
+
readonly durationMs: number;
|
|
24
|
+
readonly output: string | null;
|
|
25
|
+
readonly outputTruncated: boolean;
|
|
26
|
+
/** The first line of the error, when the call failed. */
|
|
27
|
+
readonly error: string | null;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/** A tool call that has started and not ended. */
|
|
31
|
+
export interface OpenCall {
|
|
32
|
+
readonly callId: string;
|
|
33
|
+
readonly toolName: string;
|
|
34
|
+
readonly input: string | null;
|
|
35
|
+
readonly at: number;
|
|
36
|
+
readonly output: string | null;
|
|
37
|
+
readonly outputTruncated: boolean;
|
|
38
|
+
/** The reason of a `blocked` line seen for this call. */
|
|
39
|
+
readonly blocked: string | null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface FoldState {
|
|
43
|
+
/** What has finished, in the order it finished. */
|
|
44
|
+
readonly entries: readonly FoldEntry[];
|
|
45
|
+
/** Text written so far and not finished. */
|
|
46
|
+
readonly text: string;
|
|
47
|
+
/** Thinking written so far and not finished. */
|
|
48
|
+
readonly thinking: string;
|
|
49
|
+
/** Tool calls with no end, in the order they started. */
|
|
50
|
+
readonly calls: readonly OpenCall[];
|
|
51
|
+
/** True when the current message has put text into the entries or `text` already. */
|
|
52
|
+
readonly sawText: boolean;
|
|
53
|
+
/** A `blocked` line that came before its call started, by tool name. */
|
|
54
|
+
readonly earlyBlocks: Readonly<Record<string, string>>;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export const emptyFold: FoldState = {
|
|
58
|
+
entries: [],
|
|
59
|
+
text: "",
|
|
60
|
+
thinking: "",
|
|
61
|
+
calls: [],
|
|
62
|
+
sawText: false,
|
|
63
|
+
earlyBlocks: {},
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const DENIED = " denied by the access profile";
|
|
67
|
+
|
|
68
|
+
function firstLine(text: string): string {
|
|
69
|
+
return text.split("\n")[0] ?? "";
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function str(value: unknown): string | undefined {
|
|
73
|
+
return typeof value === "string" ? value : undefined;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Puts unfinished text and thinking into the entries. */
|
|
77
|
+
function settle(state: FoldState): FoldState {
|
|
78
|
+
const entries = [...state.entries];
|
|
79
|
+
if (state.thinking.length > 0) entries.push({ kind: "thinking", text: state.thinking });
|
|
80
|
+
if (state.text.length > 0) entries.push({ kind: "text", text: state.text });
|
|
81
|
+
return { ...state, entries, text: "", thinking: "", sawText: state.sawText || state.text.length > 0 };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function apply(state: FoldState, line: unknown): FoldState {
|
|
85
|
+
if (!isRecord(line)) return state;
|
|
86
|
+
const type = str(line["type"]);
|
|
87
|
+
switch (type) {
|
|
88
|
+
case "text_delta": {
|
|
89
|
+
const text = str(line["text"]);
|
|
90
|
+
return text === undefined ? state : { ...state, text: state.text + text, sawText: true };
|
|
91
|
+
}
|
|
92
|
+
case "thinking_delta": {
|
|
93
|
+
const text = str(line["text"]);
|
|
94
|
+
return text === undefined ? state : { ...state, thinking: state.thinking + text };
|
|
95
|
+
}
|
|
96
|
+
case "text_end": {
|
|
97
|
+
const text = str(line["text"]);
|
|
98
|
+
if (text === undefined) return state;
|
|
99
|
+
return {
|
|
100
|
+
...state,
|
|
101
|
+
entries: [...state.entries, { kind: "text", text }],
|
|
102
|
+
text: "",
|
|
103
|
+
sawText: true,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
case "thinking_end": {
|
|
107
|
+
const text = str(line["text"]);
|
|
108
|
+
if (text === undefined) return state;
|
|
109
|
+
return { ...state, entries: [...state.entries, { kind: "thinking", text }], thinking: "" };
|
|
110
|
+
}
|
|
111
|
+
case "message_end": {
|
|
112
|
+
const settled = settle(state);
|
|
113
|
+
const said = str(line["text"]);
|
|
114
|
+
// Today's harnesses write only the head of a message's text here.
|
|
115
|
+
const entries =
|
|
116
|
+
!settled.sawText && said !== undefined && said.length > 0
|
|
117
|
+
? [...settled.entries, { kind: "text" as const, text: said }]
|
|
118
|
+
: settled.entries;
|
|
119
|
+
return { ...settled, entries, sawText: false };
|
|
120
|
+
}
|
|
121
|
+
case "tool_execution_start": {
|
|
122
|
+
const callId = str(line["toolCallId"]);
|
|
123
|
+
const toolName = str(line["toolName"]);
|
|
124
|
+
const at = line["at"];
|
|
125
|
+
if (callId === undefined || toolName === undefined || typeof at !== "number") return state;
|
|
126
|
+
if (state.calls.some((call) => call.callId === callId)) return state;
|
|
127
|
+
const settled = settle(state);
|
|
128
|
+
const early = settled.earlyBlocks[toolName];
|
|
129
|
+
const { [toolName]: _used, ...rest } = settled.earlyBlocks;
|
|
130
|
+
const call: OpenCall = {
|
|
131
|
+
callId,
|
|
132
|
+
toolName,
|
|
133
|
+
input: str(line["input"]) ?? null,
|
|
134
|
+
at,
|
|
135
|
+
output: null,
|
|
136
|
+
outputTruncated: false,
|
|
137
|
+
blocked: early ?? null,
|
|
138
|
+
};
|
|
139
|
+
return { ...settled, calls: [...settled.calls, call], earlyBlocks: early === undefined ? settled.earlyBlocks : rest };
|
|
140
|
+
}
|
|
141
|
+
case "blocked": {
|
|
142
|
+
const toolName = str(line["toolName"]);
|
|
143
|
+
if (toolName === undefined) return state;
|
|
144
|
+
const reason = str(line["reason"]) ?? "";
|
|
145
|
+
// The latest open call of that name that is not blocked yet.
|
|
146
|
+
let index = -1;
|
|
147
|
+
state.calls.forEach((call, at) => {
|
|
148
|
+
if (call.toolName === toolName && call.blocked === null) index = at;
|
|
149
|
+
});
|
|
150
|
+
if (index < 0) return { ...state, earlyBlocks: { ...state.earlyBlocks, [toolName]: reason } };
|
|
151
|
+
return {
|
|
152
|
+
...state,
|
|
153
|
+
calls: state.calls.map((call, at) => (at === index ? { ...call, blocked: reason } : call)),
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
case "tool_output": {
|
|
157
|
+
const callId = str(line["toolCallId"]);
|
|
158
|
+
const text = str(line["text"]);
|
|
159
|
+
if (callId === undefined || text === undefined) return state;
|
|
160
|
+
const truncated = line["truncated"] === true;
|
|
161
|
+
if (state.calls.some((call) => call.callId === callId)) {
|
|
162
|
+
return {
|
|
163
|
+
...state,
|
|
164
|
+
calls: state.calls.map((call) =>
|
|
165
|
+
call.callId === callId
|
|
166
|
+
? { ...call, output: (call.output ?? "") + text, outputTruncated: call.outputTruncated || truncated }
|
|
167
|
+
: call,
|
|
168
|
+
),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
// Output after the end: it belongs to the entry that closed the call.
|
|
172
|
+
let index = -1;
|
|
173
|
+
state.entries.forEach((entry, at) => {
|
|
174
|
+
if (entry.kind === "tool" && entry.callId === callId) index = at;
|
|
175
|
+
});
|
|
176
|
+
if (index < 0) return state;
|
|
177
|
+
return {
|
|
178
|
+
...state,
|
|
179
|
+
entries: state.entries.map((entry, at) =>
|
|
180
|
+
at === index && entry.kind === "tool"
|
|
181
|
+
? { ...entry, output: (entry.output ?? "") + text, outputTruncated: entry.outputTruncated || truncated }
|
|
182
|
+
: entry,
|
|
183
|
+
),
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
case "tool_execution_end": {
|
|
187
|
+
const callId = str(line["toolCallId"]);
|
|
188
|
+
if (callId === undefined) return state;
|
|
189
|
+
const settled = settle(state);
|
|
190
|
+
const open = settled.calls.find((call) => call.callId === callId);
|
|
191
|
+
const toolName = open?.toolName ?? str(line["toolName"]) ?? "tool";
|
|
192
|
+
const isError = line["isError"] === true;
|
|
193
|
+
const denied = open?.input?.includes(DENIED) === true;
|
|
194
|
+
const result: ToolResult = !isError ? "done" : denied ? "denied" : typeof open?.blocked === "string" ? "blocked" : "failed";
|
|
195
|
+
const ownError = str(line["error"]);
|
|
196
|
+
const error =
|
|
197
|
+
result === "done" || result === "denied"
|
|
198
|
+
? null
|
|
199
|
+
: ownError !== undefined
|
|
200
|
+
? firstLine(ownError)
|
|
201
|
+
: typeof open?.blocked === "string"
|
|
202
|
+
? firstLine(open.blocked)
|
|
203
|
+
: null;
|
|
204
|
+
const duration = line["durationMs"];
|
|
205
|
+
const entry: FoldEntry = {
|
|
206
|
+
kind: "tool",
|
|
207
|
+
callId,
|
|
208
|
+
toolName,
|
|
209
|
+
input: open?.input ?? null,
|
|
210
|
+
result,
|
|
211
|
+
at: open?.at ?? null,
|
|
212
|
+
durationMs: typeof duration === "number" ? duration : 0,
|
|
213
|
+
output: open?.output ?? null,
|
|
214
|
+
outputTruncated: open?.outputTruncated ?? false,
|
|
215
|
+
error,
|
|
216
|
+
};
|
|
217
|
+
return {
|
|
218
|
+
...settled,
|
|
219
|
+
entries: [...settled.entries, entry],
|
|
220
|
+
calls: settled.calls.filter((call) => call.callId !== callId),
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
default:
|
|
224
|
+
return state;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Adds `lines` (parsed log lines; a line that is not one of the shapes is
|
|
230
|
+
* skipped) to `from`. `foldLines(all)` and feeding the same lines one call at
|
|
231
|
+
* a time give the same state. What is not finished stays in `text`,
|
|
232
|
+
* `thinking` and `calls`.
|
|
233
|
+
*/
|
|
234
|
+
export function foldLines(lines: readonly unknown[], from: FoldState = emptyFold): FoldState {
|
|
235
|
+
let state = from;
|
|
236
|
+
for (const line of lines) state = apply(state, line);
|
|
237
|
+
return state;
|
|
238
|
+
}
|
package/src/grants.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The host's side of a one-time permission. A harness program that is about to
|
|
3
|
+
* run a call its access profile refuses writes one `grant_use` line and waits
|
|
4
|
+
* for one `grant_ack` line on its stdin; the host records the use and answers.
|
|
5
|
+
* `pi` and `claude` share this.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** Whether the run's access profile holds a permission the program may ask to use. */
|
|
9
|
+
export function hasGrants(access: unknown): boolean {
|
|
10
|
+
if (typeof access !== "object" || access === null || Array.isArray(access)) return false;
|
|
11
|
+
const grants: unknown = Reflect.get(access, "grants");
|
|
12
|
+
return Array.isArray(grants) && grants.length > 0;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** The `grant_use` line the program writes before a granted call, if this is one. */
|
|
16
|
+
export function grantUse(line: string): { readonly id: number; readonly waitId: string } | undefined {
|
|
17
|
+
if (!line.includes('"grant_use"')) return undefined;
|
|
18
|
+
try {
|
|
19
|
+
const parsed: unknown = JSON.parse(line);
|
|
20
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return undefined;
|
|
21
|
+
const type: unknown = Reflect.get(parsed, "type");
|
|
22
|
+
const id: unknown = Reflect.get(parsed, "id");
|
|
23
|
+
const waitId: unknown = Reflect.get(parsed, "waitId");
|
|
24
|
+
if (type === "grant_use" && typeof id === "number" && typeof waitId === "string") {
|
|
25
|
+
return { id, waitId };
|
|
26
|
+
}
|
|
27
|
+
} catch {
|
|
28
|
+
// Not JSON: an ordinary line.
|
|
29
|
+
}
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Answers a `grant_use` line: asks the host to use the permission up and
|
|
35
|
+
* writes the `grant_ack` line with the outcome. `used` is true only when the
|
|
36
|
+
* host recorded the use; a host that throws answers `used: false`. Any other
|
|
37
|
+
* line is left alone.
|
|
38
|
+
*/
|
|
39
|
+
export async function answerGrant(
|
|
40
|
+
line: string,
|
|
41
|
+
useGrant: (waitId: string) => Promise<boolean>,
|
|
42
|
+
reply: (text: string) => void,
|
|
43
|
+
): Promise<void> {
|
|
44
|
+
const use = grantUse(line);
|
|
45
|
+
if (use === undefined) return;
|
|
46
|
+
let used = false;
|
|
47
|
+
try {
|
|
48
|
+
used = await useGrant(use.waitId);
|
|
49
|
+
} catch {
|
|
50
|
+
used = false;
|
|
51
|
+
}
|
|
52
|
+
reply(JSON.stringify({ type: "grant_ack", id: use.id, used }));
|
|
53
|
+
}
|
package/src/images.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Images a step gives its agent as input: the `images` param of an `agent`
|
|
3
|
+
* step names files and their media types; the worker reads them and sends
|
|
4
|
+
* them with the prompt. A harness that cannot take an image never gets the param.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { readFile } from "node:fs/promises";
|
|
8
|
+
import { isRecord } from "@operad-io/engine";
|
|
9
|
+
|
|
10
|
+
/** The media types an image input may have. */
|
|
11
|
+
export const IMAGE_MEDIA_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"] as const;
|
|
12
|
+
|
|
13
|
+
/** One image: where the file is, and its media type. */
|
|
14
|
+
export interface ImageInput {
|
|
15
|
+
readonly path: string;
|
|
16
|
+
readonly mediaType: (typeof IMAGE_MEDIA_TYPES)[number];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The images in a value, or the reason it is not a list of them; an absent value is an empty list. */
|
|
20
|
+
export function parseImageInputs(value: unknown): readonly ImageInput[] | string {
|
|
21
|
+
if (value === undefined) return [];
|
|
22
|
+
if (!Array.isArray(value)) return "images must be an array of { path, mediaType }";
|
|
23
|
+
const found: ImageInput[] = [];
|
|
24
|
+
for (const item of value) {
|
|
25
|
+
const type = isRecord(item) ? IMAGE_MEDIA_TYPES.find((known) => known === item.mediaType) : undefined;
|
|
26
|
+
if (!isRecord(item) || typeof item.path !== "string" || item.path.length === 0 || type === undefined) {
|
|
27
|
+
return `images must be an array of { path, mediaType } with a media type of ${IMAGE_MEDIA_TYPES.join(", ")}`;
|
|
28
|
+
}
|
|
29
|
+
found.push({ path: item.path, mediaType: type });
|
|
30
|
+
}
|
|
31
|
+
return found;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The images of a step's params; a value that is not a list of images gives none. */
|
|
35
|
+
export function imageInputsOf(value: unknown): readonly ImageInput[] {
|
|
36
|
+
const parsed = parseImageInputs(value);
|
|
37
|
+
return typeof parsed === "string" ? [] : parsed;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** One image read as base64, the form both agents take. */
|
|
41
|
+
export async function readImage(image: ImageInput): Promise<{ readonly mediaType: ImageInput["mediaType"]; readonly data: string }> {
|
|
42
|
+
return { mediaType: image.mediaType, data: Buffer.from(await readFile(image.path)).toString("base64") };
|
|
43
|
+
}
|
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";
|
package/src/jsonl-log.ts
ADDED
|
@@ -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
|
+
}
|