@operad-io/harness-claude 0.1.1 → 0.2.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 CHANGED
@@ -8,93 +8,64 @@
8
8
  */
9
9
 
10
10
  import pkg from "../package.json" with { type: "json" };
11
- import { secretValuesOf } from "@operad-io/access-match";
12
- import { existsSync } from "node:fs";
13
11
  import { fileURLToPath } from "node:url";
14
12
  import {
15
13
  isRecord,
16
- paramsObject,
17
- defineFlow,
18
14
  definePlugin,
19
- type AgentResultData,
15
+ type HarnessEfforts,
20
16
  type PluginStepResult,
21
17
  type StepContext,
22
18
  } from "@operad-io/engine";
23
19
  import {
24
- ALLOW_ALWAYS,
25
- accessWithAlwaysAllow,
26
- alwaysAllowFromGrant,
27
- appendAlwaysAllow,
28
- answerGrant,
29
- askToolEvent,
30
- canAsk,
31
- createCallAsker,
20
+ assertWorkerAvailable,
32
21
  CONCURRENCY_SETTING,
33
- eventNote,
34
- askNote,
22
+ createCachedProbe,
23
+ DEFAULT_STALL_SECS,
24
+ DEFAULT_WALL_TIME_SECS,
35
25
  flagValue,
36
- hasGrants,
37
- directoryError,
38
- inboxOf,
26
+ imageInputsOf,
27
+ keepKeyOf,
28
+ MAX_WALL_TIME_SECS,
29
+ modelLimit,
30
+ mountedServersOf,
31
+ operadToolsOf,
32
+ optionalPositive,
39
33
  optionalText,
40
- parseResult,
41
34
  parseStepFlags,
42
- personStarted,
43
- readAlwaysAllow,
44
- resultFor,
45
- secs,
35
+ promptFlowOf,
36
+ readAgentStep,
37
+ runWorkerStep,
38
+ STALL_SETTING,
39
+ STEP_TIMEOUT_SECS,
46
40
  stringListParam,
47
- text,
48
- imageInputsOf,
49
- operadToolsOf,
50
- mountedServersOf,
51
- JsonlLog,
52
- deliverLine,
53
- modelLimit,
54
- standardUsage,
55
- type UsageSource,
56
- runAgent,
57
41
  systemClock,
42
+ text,
43
+ toolExecutionEvent,
44
+ WALL_TIME_SETTING,
58
45
  type Clock,
59
- type ToolEvent,
46
+ type KeptRunOptions,
60
47
  } 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";
48
+ import { CLAUDE_FLOOR, DEFAULT_CLAUDE_COMMAND, claudeSignedIn, inspectClaude, sdkVersion } from "./claude-install.ts";
49
+ import { DEFAULT_BASH_TIMEOUT_SECS, CLAUDE_CONTEXT_WINDOWS, EFFORT_LEVELS } from "./protocol.ts";
63
50
 
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;
51
+ export {
52
+ DEFAULT_STALL_SECS,
53
+ DEFAULT_WALL_TIME_SECS,
54
+ MAX_WALL_TIME_SECS,
55
+ STEP_TIMEOUT_SECS,
56
+ };
69
57
 
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;
58
+ /** The tool call one claude line starts or settles, or undefined for another line. */
59
+ export { toolExecutionEvent as claudeToolEvent } from "@operad-io/harness-process";
72
60
 
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;
61
+ /** How long the answer of `claude auth status` is kept before it is asked again. */
62
+ export const SIGNED_IN_CACHE_MS = 30_000;
75
63
 
76
64
  const WORKER_PATH = fileURLToPath(new URL("./worker.ts", import.meta.url));
77
65
 
78
66
  /** The name the plugin goes by in usage and limit keys. */
79
67
  const HARNESS = "claude";
80
68
 
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
69
  /** What a test injects: the clock and the program the step starts. */
99
70
  export interface ClaudeHarnessOptions {
100
71
  readonly clock?: Clock | undefined;
@@ -102,20 +73,62 @@ export interface ClaudeHarnessOptions {
102
73
  readonly command?: string | undefined;
103
74
  /** The arguments before the worker input; defaults to `worker.ts`. */
104
75
  readonly args?: readonly string[] | undefined;
76
+ /** The time now in milliseconds; defaults to `Date.now`. It ages the login cache. */
77
+ readonly now?: (() => number) | undefined;
78
+ /** Test seam: how long a chat's worker is kept after a reply. */
79
+ readonly keepMs?: number | undefined;
80
+ /** Test seam: how long a kept worker may take to answer its first line. */
81
+ readonly keptFirstLineMs?: number | undefined;
82
+ /** Test seam: how many workers one home keeps. */
83
+ readonly maxKept?: number | undefined;
105
84
  }
106
85
 
107
- /** The models a chat may pick with this agent, and the one used when none is set. */
86
+ /** What each model claude lists can do, as far as claude's own interface says. */
87
+ const CLAUDE_MODEL_INFO = {
88
+ opus: {
89
+ id: "opus",
90
+ provider: "anthropic",
91
+ window: CLAUDE_CONTEXT_WINDOWS["opus"],
92
+ capabilities: ["vision", "reasoning", "tools"],
93
+ },
94
+ sonnet: {
95
+ id: "sonnet",
96
+ provider: "anthropic",
97
+ window: CLAUDE_CONTEXT_WINDOWS["sonnet"],
98
+ capabilities: ["vision", "reasoning", "tools"],
99
+ },
100
+ haiku: {
101
+ id: "haiku",
102
+ provider: "anthropic",
103
+ window: CLAUDE_CONTEXT_WINDOWS["haiku"],
104
+ capabilities: ["vision", "reasoning", "tools"],
105
+ },
106
+ "opus[1m]": {
107
+ id: "opus[1m]",
108
+ provider: "anthropic",
109
+ window: CLAUDE_CONTEXT_WINDOWS["opus[1m]"],
110
+ capabilities: ["vision", "reasoning", "tools"],
111
+ },
112
+ "sonnet[1m]": {
113
+ id: "sonnet[1m]",
114
+ provider: "anthropic",
115
+ window: CLAUDE_CONTEXT_WINDOWS["sonnet[1m]"],
116
+ capabilities: ["vision", "reasoning", "tools"],
117
+ },
118
+ } as const;
119
+
120
+ /** The models a chat may pick with this agent, the one used when none is set, and what each is. */
108
121
  export const CLAUDE_MODELS = {
109
- list: ["opus", "sonnet", "haiku"],
122
+ list: ["opus", "sonnet", "haiku", "opus[1m]", "sonnet[1m]"],
110
123
  default: "sonnet",
124
+ windows: CLAUDE_CONTEXT_WINDOWS,
125
+ info: CLAUDE_MODEL_INFO,
111
126
  } as const;
112
127
 
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;
128
+ function claudeEfforts(settings: Readonly<Record<string, unknown>>): HarnessEfforts {
129
+ const configured = EFFORT_LEVELS.find((level) => level === settings.effort) ?? null;
130
+ return { list: EFFORT_LEVELS, default: configured, flag: "--effort" };
131
+ }
119
132
 
120
133
  /** The settings a config.json section may set for this plugin. */
121
134
  export const PLUGIN_SETTINGS = {
@@ -123,63 +136,50 @@ export const PLUGIN_SETTINGS = {
123
136
  properties: {
124
137
  model: {
125
138
  type: "string" as const,
139
+ title: "Model",
126
140
  minLength: 1,
127
141
  description: "The model name claude takes (such as opus or sonnet); unset uses claude's default.",
128
142
  },
129
143
  effort: {
130
144
  type: "string" as const,
145
+ title: "Effort",
131
146
  enum: EFFORT_LEVELS,
132
147
  description: "The reasoning effort; unset uses claude's default.",
133
148
  },
134
149
  command: {
135
150
  type: "string" as const,
151
+ title: "Claude command",
136
152
  minLength: 1,
137
153
  default: DEFAULT_CLAUDE_COMMAND,
138
154
  description: "The claude command: a name on PATH or a path.",
139
155
  },
140
156
  maxTurns: {
141
157
  type: "integer" as const,
158
+ title: "Turn limit",
142
159
  minimum: 1,
143
160
  description: "The most turns one run may take; unset means no limit.",
144
161
  },
145
162
  budgetUsd: {
146
163
  type: "number" as const,
164
+ title: "Spending limit",
147
165
  minimum: 0.01,
148
166
  description: "The most one run may spend, in US dollars; unset means no limit. For API-key logins.",
149
167
  },
150
168
  bashTimeoutSecs: {
151
169
  type: "integer" as const,
170
+ title: "Bash timeout",
152
171
  minimum: 1,
153
172
  default: DEFAULT_BASH_TIMEOUT_SECS,
154
173
  description:
155
174
  "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
175
  },
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
- },
176
+ wallTimeSecs: WALL_TIME_SETTING,
177
+ stallSecs: STALL_SETTING,
170
178
  concurrency: CONCURRENCY_SETTING,
171
179
  },
172
180
  additionalProperties: false as const,
173
181
  };
174
182
 
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
183
  /** The spelling of this harness's step `args`. */
184
184
  const STEP_FLAGS = { levelFlag: "--effort", levels: EFFORT_LEVELS, modelHint: "<name>" } as const;
185
185
 
@@ -191,48 +191,32 @@ export function createClaudeHarnessPlugin(options: ClaudeHarnessOptions = {}) {
191
191
  const clock = options.clock ?? systemClock;
192
192
  const command = options.command ?? process.execPath;
193
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
- ],
194
+ const now = options.now ?? Date.now;
195
+ // `claude auth status` runs a child process, so its answer is kept for a
196
+ // short time and asked without blocking serve. A failed answer is kept too,
197
+ // so a missing claude is not spawned for on every list.
198
+ const signedInProbe = createCachedProbe<boolean | undefined>({
199
+ now,
200
+ ttlMs: SIGNED_IN_CACHE_MS,
228
201
  });
229
202
 
203
+ async function claudeSignedInCached(settings: Readonly<Record<string, unknown>>): Promise<boolean | undefined> {
204
+ const commandSetting = typeof settings.command === "string" ? settings.command : undefined;
205
+ const key = commandSetting ?? "";
206
+ // Two clients asking at once share one probe, so serve starts one claude.
207
+ return await signedInProbe(key, () => claudeSignedIn(commandSetting));
208
+ }
209
+
210
+ const promptFlow = promptFlowOf("claude:prompt", "claude/agent");
211
+
230
212
  return definePlugin({
231
213
  name: HARNESS,
232
214
  kind: "harness",
233
215
  version: pkg.version,
234
216
  models: CLAUDE_MODELS,
235
- efforts: CLAUDE_EFFORTS,
217
+ efforts: claudeEfforts,
218
+ capabilities: { backgroundModel: "haiku", loadsSkills: true, takesMessagesMidRun: true, accessLevels: ["plan", "ask", "edits", "full"] },
219
+ signedIn: (settings) => claudeSignedInCached(settings),
236
220
  settings: PLUGIN_SETTINGS,
237
221
  steps: [
238
222
  {
@@ -242,7 +226,7 @@ export function createClaudeHarnessPlugin(options: ClaudeHarnessOptions = {}) {
242
226
  // `waiting`: a question about a call was not answered within the grace.
243
227
  results: ["done", "failed", "interrupted", "waiting"],
244
228
  // The deny and ask fields are applied in the worker's canUseTool.
245
- enforces: ["denyPaths", "denyCommands", "askCommands", "askPaths", "readPaths", "alwaysAllow"],
229
+ enforces: ["level", "denyPaths", "denyCommands", "askCommands", "askPaths", "readPaths", "alwaysAllow"],
246
230
  timeoutSecs: STEP_TIMEOUT_SECS,
247
231
  // The model the step uses: its `--model` argument, else the setting.
248
232
  limit: modelLimit(HARNESS, (params, settings) => {
@@ -252,106 +236,57 @@ export function createClaudeHarnessPlugin(options: ClaudeHarnessOptions = {}) {
252
236
  }),
253
237
  async run(ctx: StepContext, params: unknown): Promise<PluginStepResult> {
254
238
  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}`);
239
+ let maxTurns: number | undefined;
240
+ let budgetUsd: number | undefined;
241
+ let bashTimeoutSecs: number | undefined;
242
+ let operadTools: ReturnType<typeof operadToolsOf>;
243
+ let skills: readonly string[] = [];
244
+ let ownSettings: unknown;
245
+ let mcpServers: ReturnType<typeof mountedServersOf>;
246
+ let images: readonly ReturnType<typeof imageInputsOf>[number][] = [];
247
+ let claudeCommand: string | undefined;
296
248
 
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
- );
249
+ const step = await readAgentStep(ctx, params, {
250
+ at,
251
+ harness: HARNESS,
252
+ flags: STEP_FLAGS,
253
+ defaultWallTimeSecs: DEFAULT_WALL_TIME_SECS,
254
+ defaultStallSecs: DEFAULT_STALL_SECS,
255
+ maxWallTimeSecs: MAX_WALL_TIME_SECS,
256
+ levelSetting: "effort",
257
+ now,
258
+ beforeDirectory() {
259
+ maxTurns = optionalPositive(ctx.settings.maxTurns, `${at}: settings.maxTurns`, true);
260
+ budgetUsd = optionalPositive(ctx.settings.budgetUsd, `${at}: settings.budgetUsd`, false);
261
+ bashTimeoutSecs = optionalPositive(
262
+ ctx.settings.bashTimeoutSecs,
263
+ `${at}: settings.bashTimeoutSecs`,
264
+ true,
265
+ );
266
+ },
267
+ afterDirectory(read) {
268
+ operadTools = operadToolsOf(read.input.operadTools ?? read.flow.operadTools);
269
+ skills = stringListParam(
270
+ read.input.skills === undefined ? read.flow.skills : read.input.skills,
271
+ `${at}: params.skills`,
272
+ );
273
+ ownSettings = read.input.useOwnSettings ?? read.flow.useOwnSettings;
274
+ if (ownSettings !== undefined && typeof ownSettings !== "boolean") {
275
+ throw new Error(`${at}: params.useOwnSettings: must be a boolean`);
276
+ }
277
+ mcpServers = mountedServersOf(read.input.mcpServers ?? read.flow.mcpServers);
278
+ images = imageInputsOf(read.input.images ?? read.flow.images);
279
+ claudeCommand = optionalText(ctx.settings.command, `${at}: settings.command`);
280
+ },
281
+ });
282
+ if ("refused" in step) return step.refused;
324
283
 
325
- const cwdProblem = await directoryError(cwd);
326
- if (cwdProblem !== undefined) return refuse("cwd", cwdProblem);
284
+ const { values, access } = step;
285
+ const { resumeSession, wallTimeSecs, stallSecs, model, level: effort } = values;
327
286
 
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
287
  const stdin: Record<string, unknown> = {
353
- prompt: promptWithNote,
354
- cwd,
288
+ prompt: values.promptWithNote,
289
+ cwd: values.cwd,
355
290
  ...(claudeCommand === undefined ? {} : { command: claudeCommand }),
356
291
  ...(resumeSession === undefined ? {} : { resumeSession }),
357
292
  ...(model === undefined ? {} : { model }),
@@ -362,67 +297,38 @@ export function createClaudeHarnessPlugin(options: ClaudeHarnessOptions = {}) {
362
297
  ...(operadTools === undefined ? {} : { operadTools }),
363
298
  ...(mcpServers === undefined ? {} : { mcpServers }),
364
299
  ...(images.length === 0 ? {} : { images }),
365
- ...(runAccess === undefined ? {} : { access: runAccess }),
366
- ...(storeSecrets.length === 0 ? {} : { secretValues: storeSecrets }),
300
+ ...(skills.length === 0 ? {} : { skills }),
301
+ ...(ownSettings === true ? { useOwnSettings: true } : {}),
302
+ ...(access.runAccess === undefined ? {} : { access: access.runAccess }),
303
+ ...(access.secrets.length === 0 ? {} : { secretValues: access.secrets }),
367
304
  };
368
305
 
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
- });
306
+ const keep: KeptRunOptions | undefined =
307
+ values.input.keepWorker === true && ctx.object !== undefined
308
+ ? {
309
+ home: ctx.home,
310
+ name: HARNESS,
311
+ scope: `${ctx.object.type}:${ctx.object.id}`,
312
+ key: keepKeyOf(stdin),
313
+ ...(options.keepMs === undefined ? {} : { timeoutMs: options.keepMs }),
314
+ ...(options.keptFirstLineMs === undefined ? {} : { firstLineMs: options.keptFirstLineMs }),
315
+ ...(options.maxKept === undefined ? {} : { max: options.maxKept }),
316
+ }
317
+ : undefined;
384
318
 
385
- const outcome = await runAgent({
319
+ return await runWorkerStep({
320
+ values,
321
+ access,
386
322
  command,
387
323
  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]),
324
+ stdin,
325
+ keep,
396
326
  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
- },
327
+ now,
328
+ toolEvent: toolExecutionEvent,
329
+ forms: true,
330
+ modelFromResult: true,
407
331
  });
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
332
  },
427
333
  },
428
334
  ],
@@ -432,12 +338,7 @@ export function createClaudeHarnessPlugin(options: ClaudeHarnessOptions = {}) {
432
338
  // The user's own claude: found, version-checked and asked who is logged
433
339
  // in. Only the login kind is reported.
434
340
  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
- }
341
+ assertWorkerAvailable({ command: options.command, args: options.args, workerPath: WORKER_PATH });
441
342
  const sdk = await sdkVersion();
442
343
  return (
443
344
  `claude ${claude.version} at ${claude.path} (floor ${CLAUDE_FLOOR}); ` +