@operad-io/harness-claude 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/index.ts ADDED
@@ -0,0 +1,450 @@
1
+ /**
2
+ * The claude harness, hub side: one `agent` step that starts the child program
3
+ * `worker.ts` under Bun, writes one JSON object to its stdin and reads the last
4
+ * `result` line of its stdout, plus the `claude:prompt` flow. The step
5
+ * has the params, result names and facts of `pi/agent`, so a flow
6
+ * changes harness by changing `use`. The Agent SDK is imported only by the
7
+ * child program, never by the hub.
8
+ */
9
+
10
+ import pkg from "../package.json" with { type: "json" };
11
+ import { secretValuesOf } from "@operad-io/access-match";
12
+ import { existsSync } from "node:fs";
13
+ import { fileURLToPath } from "node:url";
14
+ import {
15
+ isRecord,
16
+ paramsObject,
17
+ defineFlow,
18
+ definePlugin,
19
+ type AgentResultData,
20
+ type PluginStepResult,
21
+ type StepContext,
22
+ } from "@operad-io/engine";
23
+ import {
24
+ ALLOW_ALWAYS,
25
+ accessWithAlwaysAllow,
26
+ alwaysAllowFromGrant,
27
+ appendAlwaysAllow,
28
+ answerGrant,
29
+ askToolEvent,
30
+ canAsk,
31
+ createCallAsker,
32
+ CONCURRENCY_SETTING,
33
+ eventNote,
34
+ askNote,
35
+ flagValue,
36
+ hasGrants,
37
+ directoryError,
38
+ inboxOf,
39
+ optionalText,
40
+ parseResult,
41
+ parseStepFlags,
42
+ personStarted,
43
+ readAlwaysAllow,
44
+ resultFor,
45
+ secs,
46
+ stringListParam,
47
+ text,
48
+ imageInputsOf,
49
+ operadToolsOf,
50
+ mountedServersOf,
51
+ JsonlLog,
52
+ deliverLine,
53
+ modelLimit,
54
+ standardUsage,
55
+ type UsageSource,
56
+ runAgent,
57
+ systemClock,
58
+ type Clock,
59
+ type ToolEvent,
60
+ } from "@operad-io/harness-process";
61
+ import { CLAUDE_FLOOR, DEFAULT_CLAUDE_COMMAND, inspectClaude, sdkVersion } from "./claude-install.ts";
62
+ import { DEFAULT_BASH_TIMEOUT_SECS, EFFORT_LEVELS, type WorkerResult } from "./protocol.ts";
63
+
64
+ /** How long an agent may run before the step stops it. */
65
+ export const DEFAULT_WALL_TIME_SECS = 3600;
66
+
67
+ /** How long an agent may go without a new output line. */
68
+ export const DEFAULT_STALL_SECS = 600;
69
+
70
+ /** One run of the step may take this long; it is above every allowed wall time. */
71
+ export const STEP_TIMEOUT_SECS = 8 * 3600;
72
+
73
+ /** The longest wall time a run may ask for: the step timeout minus a margin. */
74
+ export const MAX_WALL_TIME_SECS = STEP_TIMEOUT_SECS - 300;
75
+
76
+ const WORKER_PATH = fileURLToPath(new URL("./worker.ts", import.meta.url));
77
+
78
+ /** The name the plugin goes by in usage and limit keys. */
79
+ const HARNESS = "claude";
80
+
81
+ /**
82
+ * Reads one worker line and reports the tool call it starts or settles. The
83
+ * worker writes `tool_execution_start` and `tool_execution_end` under `type`.
84
+ */
85
+ export function claudeToolEvent(line: string): ToolEvent | undefined {
86
+ let value: unknown;
87
+ try {
88
+ value = JSON.parse(line);
89
+ } catch {
90
+ return undefined;
91
+ }
92
+ if (!isRecord(value)) return undefined;
93
+ if (value.type === "tool_execution_start") return "tool-start";
94
+ if (value.type === "tool_execution_end") return "tool-end";
95
+ return undefined;
96
+ }
97
+
98
+ /** What a test injects: the clock and the program the step starts. */
99
+ export interface ClaudeHarnessOptions {
100
+ readonly clock?: Clock | undefined;
101
+ /** The executable; defaults to the running Bun. */
102
+ readonly command?: string | undefined;
103
+ /** The arguments before the worker input; defaults to `worker.ts`. */
104
+ readonly args?: readonly string[] | undefined;
105
+ }
106
+
107
+ /** The models a chat may pick with this agent, and the one used when none is set. */
108
+ export const CLAUDE_MODELS = {
109
+ list: ["opus", "sonnet", "haiku"],
110
+ default: "sonnet",
111
+ } as const;
112
+
113
+ /** The efforts a chat may pick with this agent, the default, and the flag that sets it. */
114
+ export const CLAUDE_EFFORTS = {
115
+ list: EFFORT_LEVELS,
116
+ default: "medium",
117
+ flag: "--effort",
118
+ } as const;
119
+
120
+ /** The settings a config.json section may set for this plugin. */
121
+ export const PLUGIN_SETTINGS = {
122
+ type: "object" as const,
123
+ properties: {
124
+ model: {
125
+ type: "string" as const,
126
+ minLength: 1,
127
+ description: "The model name claude takes (such as opus or sonnet); unset uses claude's default.",
128
+ },
129
+ effort: {
130
+ type: "string" as const,
131
+ enum: EFFORT_LEVELS,
132
+ description: "The reasoning effort; unset uses claude's default.",
133
+ },
134
+ command: {
135
+ type: "string" as const,
136
+ minLength: 1,
137
+ default: DEFAULT_CLAUDE_COMMAND,
138
+ description: "The claude command: a name on PATH or a path.",
139
+ },
140
+ maxTurns: {
141
+ type: "integer" as const,
142
+ minimum: 1,
143
+ description: "The most turns one run may take; unset means no limit.",
144
+ },
145
+ budgetUsd: {
146
+ type: "number" as const,
147
+ minimum: 0.01,
148
+ description: "The most one run may spend, in US dollars; unset means no limit. For API-key logins.",
149
+ },
150
+ bashTimeoutSecs: {
151
+ type: "integer" as const,
152
+ minimum: 1,
153
+ default: DEFAULT_BASH_TIMEOUT_SECS,
154
+ description:
155
+ "The longest one Bash call may run, in seconds. Nothing runs in the background, so a long gate runs in the foreground within this time.",
156
+ },
157
+ wallTimeSecs: {
158
+ type: "number" as const,
159
+ minimum: 1,
160
+ maximum: MAX_WALL_TIME_SECS,
161
+ default: DEFAULT_WALL_TIME_SECS,
162
+ description: "The longest one agent run may take.",
163
+ },
164
+ stallSecs: {
165
+ type: "number" as const,
166
+ minimum: 1,
167
+ default: DEFAULT_STALL_SECS,
168
+ description: "How long an agent may be silent while no tool call is open.",
169
+ },
170
+ concurrency: CONCURRENCY_SETTING,
171
+ },
172
+ additionalProperties: false as const,
173
+ };
174
+
175
+ function optionalNumber(value: unknown, at: string, integer: boolean): number | undefined {
176
+ if (value === undefined) return undefined;
177
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0 || (integer && !Number.isInteger(value))) {
178
+ throw new Error(`${at}: must be a positive ${integer ? "integer" : "number"}`);
179
+ }
180
+ return value;
181
+ }
182
+
183
+ /** The spelling of this harness's step `args`. */
184
+ const STEP_FLAGS = { levelFlag: "--effort", levels: EFFORT_LEVELS, modelHint: "<name>" } as const;
185
+
186
+ /**
187
+ * Creates the claude harness plugin. Its worker is `worker.ts` under the
188
+ * running Bun; a test replaces the program with a fake that prints fixed lines.
189
+ */
190
+ export function createClaudeHarnessPlugin(options: ClaudeHarnessOptions = {}) {
191
+ const clock = options.clock ?? systemClock;
192
+ const command = options.command ?? process.execPath;
193
+ const commandArgs = options.args ?? [WORKER_PATH];
194
+
195
+ const promptFlow = defineFlow({
196
+ name: "claude:prompt",
197
+ entry: "agent",
198
+ steps: [
199
+ {
200
+ id: "agent",
201
+ kind: "plugin",
202
+ params: { use: "claude/agent", params: {} },
203
+ replay: "unsafe",
204
+ next: { done: "done", failed: "failed", interrupted: "cancelled", waiting: "person" },
205
+ },
206
+ {
207
+ // A question about a call ran out of grace. The answer sends the run
208
+ // back to the agent, which continues the session with it.
209
+ id: "person",
210
+ kind: "wait_person",
211
+ params: {
212
+ prompt: "The agent asked about a call.",
213
+ choices: ["allow_once", "reject_once"],
214
+ lateChoices: ["allow_always"],
215
+ },
216
+ replay: "safe",
217
+ next: {
218
+ allow_once: "agent",
219
+ allow_always: "agent",
220
+ reject_once: "agent",
221
+ interrupted: "cancelled",
222
+ },
223
+ },
224
+ { id: "done", kind: "end", params: { status: "done" }, replay: "safe" },
225
+ { id: "failed", kind: "end", params: { status: "failed" }, replay: "safe" },
226
+ { id: "cancelled", kind: "end", params: { status: "cancelled" }, replay: "safe" },
227
+ ],
228
+ });
229
+
230
+ return definePlugin({
231
+ name: HARNESS,
232
+ kind: "harness",
233
+ version: pkg.version,
234
+ models: CLAUDE_MODELS,
235
+ efforts: CLAUDE_EFFORTS,
236
+ settings: PLUGIN_SETTINGS,
237
+ steps: [
238
+ {
239
+ name: "agent",
240
+ // A question's answer comes back as `resumeSession` and `askAnswer`.
241
+ resumable: true,
242
+ // `waiting`: a question about a call was not answered within the grace.
243
+ results: ["done", "failed", "interrupted", "waiting"],
244
+ // The deny and ask fields are applied in the worker's canUseTool.
245
+ enforces: ["denyPaths", "denyCommands", "askCommands", "askPaths", "readPaths", "alwaysAllow"],
246
+ timeoutSecs: STEP_TIMEOUT_SECS,
247
+ // The model the step uses: its `--model` argument, else the setting.
248
+ limit: modelLimit(HARNESS, (params, settings) => {
249
+ const fromArgs = isRecord(params) ? flagValue(params.args, "--model") : undefined;
250
+ const model = fromArgs ?? settings.model;
251
+ return typeof model === "string" && model.length > 0 ? model : undefined;
252
+ }),
253
+ async run(ctx: StepContext, params: unknown): Promise<PluginStepResult> {
254
+ const at = "claude/agent";
255
+ const input = paramsObject(params, at);
256
+ const flow = isRecord(ctx.params) ? ctx.params : {};
257
+
258
+ const prompt = text(input.prompt ?? flow.prompt, `${at}: params.prompt`);
259
+ const note = eventNote(ctx.trigger);
260
+ const rawAskAnswer = input.askAnswer ?? flow.askAnswer;
261
+ const answerNote = askNote(rawAskAnswer);
262
+ const promptWithNote = [prompt, note, answerNote]
263
+ .filter((part): part is string => part !== undefined)
264
+ .join("\n\n");
265
+ const cwd = text(input.cwd ?? flow.cwd, `${at}: params.cwd`);
266
+ const flags = parseStepFlags(
267
+ stringListParam(input.args === undefined ? flow.args : input.args, `${at}: params.args`),
268
+ STEP_FLAGS,
269
+ );
270
+ const settingModel = typeof ctx.settings.model === "string" ? ctx.settings.model : undefined;
271
+ // The model the step will use, known before anything can fail.
272
+ const knownModel =
273
+ typeof flags === "string"
274
+ ? (flagValue(input.args === undefined ? flow.args : input.args, "--model") ?? settingModel)
275
+ : (flags.model ?? settingModel);
276
+ const early: UsageSource = { harness: HARNESS, model: knownModel ?? null };
277
+ const refuse = async (reason: string, message: string): Promise<PluginStepResult> => {
278
+ const log = await ctx.logger.write(message);
279
+ return {
280
+ result: "failed",
281
+ data: {
282
+ reason,
283
+ message,
284
+ exitCode: null,
285
+ signal: null,
286
+ sessionId: null,
287
+ finalMessage: null,
288
+ usage: standardUsage(early, undefined, null),
289
+ log,
290
+ durationMs: 0,
291
+ stderr: [message],
292
+ },
293
+ };
294
+ };
295
+ if (typeof flags === "string") return refuse("invalid_args", `${at}: ${flags}`);
296
+
297
+ const resumeSession = optionalText(
298
+ input.resumeSession ?? flow.resumeSession,
299
+ `${at}: params.resumeSession`,
300
+ );
301
+ const wallTimeSecs = secs(
302
+ input.wallTimeSecs ?? ctx.settings.wallTimeSecs ?? DEFAULT_WALL_TIME_SECS,
303
+ `${at}: params.wallTimeSecs`,
304
+ );
305
+ if (wallTimeSecs > MAX_WALL_TIME_SECS) {
306
+ throw new Error(`${at}: params.wallTimeSecs: must be at most ${MAX_WALL_TIME_SECS}`);
307
+ }
308
+ const stallSecs = secs(
309
+ input.stallSecs ?? ctx.settings.stallSecs ?? DEFAULT_STALL_SECS,
310
+ `${at}: params.stallSecs`,
311
+ );
312
+ const model = flags.model ?? optionalText(ctx.settings.model, `${at}: settings.model`);
313
+ const effort =
314
+ flags.level ??
315
+ optionalText(input.effort, `${at}: params.effort`) ??
316
+ optionalText(ctx.settings.effort, `${at}: settings.effort`);
317
+ const maxTurns = optionalNumber(ctx.settings.maxTurns, `${at}: settings.maxTurns`, true);
318
+ const budgetUsd = optionalNumber(ctx.settings.budgetUsd, `${at}: settings.budgetUsd`, false);
319
+ const bashTimeoutSecs = optionalNumber(
320
+ ctx.settings.bashTimeoutSecs,
321
+ `${at}: settings.bashTimeoutSecs`,
322
+ true,
323
+ );
324
+
325
+ const cwdProblem = await directoryError(cwd);
326
+ if (cwdProblem !== undefined) return refuse("cwd", cwdProblem);
327
+
328
+ const operadTools = operadToolsOf(input.operadTools ?? flow.operadTools);
329
+ const mcpServers = mountedServersOf(input.mcpServers ?? flow.mcpServers);
330
+ const images = imageInputsOf(input.images ?? flow.images);
331
+ const claudeCommand = optionalText(ctx.settings.command, `${at}: settings.command`);
332
+ const storeSecrets = await secretValuesOf(ctx.secrets);
333
+ const allowAlways = personStarted(ctx.trigger);
334
+ if (allowAlways && isRecord(rawAskAnswer) && rawAskAnswer["choice"] === ALLOW_ALWAYS) {
335
+ const entry = alwaysAllowFromGrant(ctx.access, cwd);
336
+ if (entry !== undefined) {
337
+ try {
338
+ await appendAlwaysAllow(ctx.home, entry);
339
+ } catch (error) {
340
+ await ctx.logger.write(
341
+ `allow_always could not be written to the user access file: ${String(error)}; this call runs once`,
342
+ );
343
+ }
344
+ }
345
+ }
346
+ let runAccess = accessWithAlwaysAllow(ctx.access, [], false);
347
+ if (allowAlways) {
348
+ const user = await readAlwaysAllow(ctx.home);
349
+ if (user.problem !== undefined) await ctx.logger.write(user.problem);
350
+ runAccess = accessWithAlwaysAllow(ctx.access, user.entries, true);
351
+ }
352
+ const stdin: Record<string, unknown> = {
353
+ prompt: promptWithNote,
354
+ cwd,
355
+ ...(claudeCommand === undefined ? {} : { command: claudeCommand }),
356
+ ...(resumeSession === undefined ? {} : { resumeSession }),
357
+ ...(model === undefined ? {} : { model }),
358
+ ...(effort === undefined ? {} : { effort }),
359
+ ...(maxTurns === undefined ? {} : { maxTurns }),
360
+ ...(budgetUsd === undefined ? {} : { budgetUsd }),
361
+ ...(bashTimeoutSecs === undefined ? {} : { bashTimeoutSecs }),
362
+ ...(operadTools === undefined ? {} : { operadTools }),
363
+ ...(mcpServers === undefined ? {} : { mcpServers }),
364
+ ...(images.length === 0 ? {} : { images }),
365
+ ...(runAccess === undefined ? {} : { access: runAccess }),
366
+ ...(storeSecrets.length === 0 ? {} : { secretValues: storeSecrets }),
367
+ };
368
+
369
+ const inbox = inboxOf(params);
370
+ const started = Date.now();
371
+ const jsonl = new JsonlLog(ctx.logger, clock);
372
+ let result: WorkerResult | undefined;
373
+ // Ends the program when a question about a call runs out of grace.
374
+ const stopper = new AbortController();
375
+ const asker = createCallAsker({
376
+ ask: (request) => ctx.ask(request),
377
+ onStop: () => stopper.abort(),
378
+ secrets: storeSecrets,
379
+ ...(allowAlways ? { alwaysAllow: { home: ctx.home, cwd } } : {}),
380
+ onLog: (message) => {
381
+ void ctx.logger.write(message);
382
+ },
383
+ });
384
+
385
+ const outcome = await runAgent({
386
+ command,
387
+ args: commandArgs,
388
+ cwd,
389
+ stdin: JSON.stringify(stdin),
390
+ // The program may ask to use a one-time permission; it needs a reply.
391
+ interactive: hasGrants(ctx.access) || canAsk(ctx.access) || inbox !== undefined,
392
+ inbox,
393
+ wallMs: wallTimeSecs * 1000,
394
+ stallMs: stallSecs * 1000,
395
+ signal: AbortSignal.any([ctx.signal, stopper.signal]),
396
+ clock,
397
+ toolEvent: (line) => claudeToolEvent(line) ?? askToolEvent(line),
398
+ async onLine(line, reply) {
399
+ await answerGrant(line, (waitId) => ctx.useGrant(waitId), reply);
400
+ await asker.handle(line, reply);
401
+ const writing = jsonl.push(line);
402
+ deliverLine(ctx.receiver, line, storeSecrets);
403
+ const parsed = parseResult<WorkerResult>(line);
404
+ if (parsed !== undefined) result = parsed;
405
+ return writing;
406
+ },
407
+ });
408
+ await jsonl.end();
409
+
410
+ // The grace passed with a question open: the program was ended on
411
+ // purpose. The kernel turns this into the result `waiting`, and the
412
+ // answer comes back with the session and a one-time grant.
413
+ const unanswered = asker.stopped();
414
+ if (unanswered !== undefined && !ctx.signal.aborted) throw unanswered.error;
415
+
416
+ return resultFor(
417
+ // The step's own model, else the one claude reports having used.
418
+ { harness: HARNESS, model: model ?? result?.model ?? null },
419
+ outcome,
420
+ result,
421
+ ctx.logger.path,
422
+ Date.now() - started,
423
+ { wallTimeSecs, stallSecs },
424
+ command,
425
+ );
426
+ },
427
+ },
428
+ ],
429
+ flows: [promptFlow],
430
+ async check(ctx) {
431
+ const claudeCommand = optionalText(ctx.settings.command, `${HARNESS}: settings.command`);
432
+ // The user's own claude: found, version-checked and asked who is logged
433
+ // in. Only the login kind is reported.
434
+ const claude = inspectClaude(claudeCommand);
435
+ if (options.command === undefined && !existsSync(process.execPath)) {
436
+ throw new Error("bun was not found");
437
+ }
438
+ if (options.args === undefined && !existsSync(WORKER_PATH)) {
439
+ throw new Error(`the worker program is missing: ${WORKER_PATH}`);
440
+ }
441
+ const sdk = await sdkVersion();
442
+ return (
443
+ `claude ${claude.version} at ${claude.path} (floor ${CLAUDE_FLOOR}); ` +
444
+ `agent sdk ${sdk ?? "unknown"}; login ${claude.login}; the worker program is available`
445
+ );
446
+ },
447
+ });
448
+ }
449
+
450
+ export default createClaudeHarnessPlugin();