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