clanka 0.20.0 → 0.22.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.
Files changed (45) hide show
  1. package/dist/Acp.test.js +20 -8
  2. package/dist/Acp.test.js.map +1 -1
  3. package/dist/Agent.d.ts +4 -4
  4. package/dist/Agent.d.ts.map +1 -1
  5. package/dist/Agent.js +140 -99
  6. package/dist/Agent.js.map +1 -1
  7. package/dist/Agent.test.js +5 -4
  8. package/dist/Agent.test.js.map +1 -1
  9. package/dist/AgentBashJobs.test.js +51 -32
  10. package/dist/AgentBashJobs.test.js.map +1 -1
  11. package/dist/AgentCallerConfig.test.js +26 -7
  12. package/dist/AgentCallerConfig.test.js.map +1 -1
  13. package/dist/AgentExecutor.d.ts +71 -41
  14. package/dist/AgentExecutor.d.ts.map +1 -1
  15. package/dist/AgentExecutor.js +86 -78
  16. package/dist/AgentExecutor.js.map +1 -1
  17. package/dist/AgentExecutor.test.js +173 -72
  18. package/dist/AgentExecutor.test.js.map +1 -1
  19. package/dist/AgentExecutorImage.test.js +2 -2
  20. package/dist/AgentExecutorImage.test.js.map +1 -1
  21. package/dist/AgentImage.test.js +3 -2
  22. package/dist/AgentImage.test.js.map +1 -1
  23. package/dist/AgentSubagents.test.js +220 -31
  24. package/dist/AgentSubagents.test.js.map +1 -1
  25. package/dist/AgentTools.d.ts +369 -257
  26. package/dist/AgentTools.d.ts.map +1 -1
  27. package/dist/AgentTools.js +247 -190
  28. package/dist/AgentTools.js.map +1 -1
  29. package/dist/AgentTools.test.js +2 -2
  30. package/dist/AgentTools.test.js.map +1 -1
  31. package/dist/bin/cli.mjs +330 -281
  32. package/dist/bin/cli.mjs.map +1 -1
  33. package/package.json +1 -1
  34. package/src/Acp.test.ts +32 -11
  35. package/src/Agent.test.ts +5 -4
  36. package/src/Agent.ts +175 -137
  37. package/src/AgentBashJobs.test.ts +74 -38
  38. package/src/AgentCallerConfig.test.ts +39 -7
  39. package/src/AgentExecutor.test.ts +229 -72
  40. package/src/AgentExecutor.ts +120 -104
  41. package/src/AgentExecutorImage.test.ts +2 -2
  42. package/src/AgentImage.test.ts +4 -3
  43. package/src/AgentSubagents.test.ts +825 -562
  44. package/src/AgentTools.test.ts +2 -2
  45. package/src/AgentTools.ts +370 -278
package/src/AgentTools.ts CHANGED
@@ -7,6 +7,7 @@ import * as ExaSearch from "./ExaSearch.ts"
7
7
  import * as WebToMarkdown from "./WebToMarkdown.ts"
8
8
  import type * as HttpClient from "effect/http/HttpClient"
9
9
  import type * as PlatformError from "effect/PlatformError"
10
+ import * as Clock from "effect/Clock"
10
11
  import * as Context from "effect/Context"
11
12
  import * as Duration from "effect/Duration"
12
13
  import * as Effect from "effect/Effect"
@@ -57,130 +58,153 @@ export class TaskCompleter extends Context.Service<
57
58
  >()("clanka/AgentTools/TaskCompleter") {}
58
59
 
59
60
  /**
61
+ * What a task is: a background `bash` command or a sub-agent started with
62
+ * `delegate`.
63
+ *
60
64
  * @since 1.0.0
61
65
  * @category Models
62
66
  */
63
- export const SubagentStatus = Schema.Literals([
64
- "completed",
65
- "running",
66
- "failed",
67
- "cancelled",
68
- ])
69
-
70
- /**
71
- * @since 1.0.0
72
- * @category Models
73
- */
74
- export type SubagentStatus = typeof SubagentStatus.Type
75
-
76
- /**
77
- * @since 1.0.0
78
- * @category Models
79
- */
80
- export const SubagentResult = Schema.Struct({
81
- id: Schema.String,
82
- status: SubagentStatus,
83
- output: Schema.optional(Schema.String),
84
- })
67
+ export const TaskKind = Schema.Literals(["bash", "agent"])
85
68
 
86
69
  /**
87
70
  * @since 1.0.0
88
71
  * @category Models
89
72
  */
90
- export type SubagentResult = typeof SubagentResult.Type
73
+ export type TaskKind = typeof TaskKind.Type
91
74
 
92
75
  /**
93
76
  * @since 1.0.0
94
77
  * @category Models
95
78
  */
96
- export const DelegateResult = Schema.Struct({
97
- ...SubagentResult.fields,
98
- status: Schema.Literals(["completed", "running"]),
99
- })
79
+ export const TaskStatus = Schema.Literals([
80
+ "running",
81
+ "completed",
82
+ "failed",
83
+ "stopped",
84
+ ])
100
85
 
101
86
  /**
102
87
  * @since 1.0.0
103
88
  * @category Models
104
89
  */
105
- export type DelegateResult = typeof DelegateResult.Type
90
+ export type TaskStatus = typeof TaskStatus.Type
106
91
 
107
92
  /**
93
+ * A background `bash` command or a sub-agent, as returned by the task
94
+ * functions. Both kinds share one id space per executor.
95
+ *
108
96
  * @since 1.0.0
109
97
  * @category Models
110
98
  */
111
- export const SubagentInfo = Schema.Struct({
112
- id: Schema.String,
113
- status: SubagentStatus,
114
- prompt: Schema.String,
99
+ export const Task = Schema.Struct({
100
+ id: Schema.String.annotate({
101
+ documentation: "The task id, which can be managed with the task tools.",
102
+ }),
103
+ kind: TaskKind,
104
+ status: TaskStatus,
105
+ /** The bash command, or the sub-agent's prompt. */
106
+ description: Schema.String,
107
+ /** Output so far while running; the final output, or the error, once ended. */
108
+ output: Schema.String,
109
+ /** bash only: set when the command exited on its own. */
110
+ exitCode: Schema.optional(Schema.Number),
115
111
  })
116
112
 
117
113
  /**
118
114
  * @since 1.0.0
119
115
  * @category Models
120
116
  */
121
- export type SubagentInfo = typeof SubagentInfo.Type
117
+ export type Task = typeof Task.Type
122
118
 
123
119
  /**
124
- * Manages the sub-agents of one agent. Every function only sees the agents
125
- * spawned by that agent.
120
+ * The sub-agent side of the task functions, for one agent. The executor
121
+ * resolves bash tasks itself and hands agent tasks to these, so every
122
+ * function only receives ids of agents that this agent started.
126
123
  *
127
124
  * @since 1.0.0
128
125
  * @category Models
129
126
  */
130
- export interface Subagents {
127
+ export interface AgentTasks {
131
128
  /**
132
- * Start a sub-agent. In the foreground it resolves once the agent has
133
- * finished, and dies if the agent failed. In the background it resolves
134
- * straight away with `status: "running"`.
129
+ * Start a sub-agent under the id the executor allocated. In the foreground
130
+ * it resolves once the agent has finished, and dies if the agent failed.
131
+ * In the background it resolves straight away with `status: "running"`.
135
132
  */
136
133
  readonly delegate: (options: {
134
+ readonly id: string
137
135
  readonly prompt: string
138
136
  readonly background: boolean
139
- }) => Effect.Effect<DelegateResult>
137
+ }) => Effect.Effect<Task>
140
138
  /**
141
- * Wait for the listed agents, or all of them when `ids` is undefined.
142
- * Failures are returned as results, not raised.
139
+ * The agent's status and output so far. A final status counts as reported.
143
140
  */
144
- readonly waitAgents: (
145
- ids: ReadonlyArray<string> | undefined,
146
- ) => Effect.Effect<ReadonlyArray<SubagentResult>, string>
141
+ readonly taskOutput: (id: string) => Effect.Effect<Task, string>
142
+ /**
143
+ * Wait up to `timeoutMs` for the listed agents to end, then report the
144
+ * ones that ended all at once. Agents still running at the deadline are
145
+ * returned as running and keep going. Failures are returned as tasks, not
146
+ * raised. The executor calls it once per batch, after waiting for any bash
147
+ * tasks in the batch, with the time left, so nothing is reported while the
148
+ * batch is still waiting.
149
+ */
150
+ readonly waitTasks: (
151
+ ids: ReadonlyArray<string>,
152
+ options: { readonly timeoutMs: number },
153
+ ) => Effect.Effect<ReadonlyArray<Task>, string>
147
154
  /**
148
155
  * Steer a running agent, or start a new turn on a finished one.
149
156
  */
150
157
  readonly messageAgent: (options: {
151
158
  readonly id: string
152
159
  readonly message: string
153
- }) => Effect.Effect<SubagentResult, string>
160
+ }) => Effect.Effect<void, string>
154
161
  /**
155
162
  * Interrupt an agent and everything it spawned.
156
163
  */
157
- readonly stopAgent: (id: string) => Effect.Effect<SubagentResult, string>
158
- readonly listAgents: Effect.Effect<ReadonlyArray<SubagentInfo>>
164
+ readonly stopTask: (id: string) => Effect.Effect<Task, string>
165
+ /**
166
+ * The agents this agent started.
167
+ */
168
+ readonly listTasks: Effect.Effect<ReadonlyArray<Task>>
159
169
  }
160
170
 
161
171
  /**
162
172
  * @since 1.0.0
163
173
  * @category Context
164
174
  */
165
- export class SubagentExecutor extends Context.Service<
166
- SubagentExecutor,
167
- Subagents
168
- >()("clanka/AgentTools/SubagentExecutor") {}
175
+ export class AgentTaskExecutor extends Context.Service<
176
+ AgentTaskExecutor,
177
+ AgentTasks
178
+ >()("clanka/AgentTools/AgentTaskExecutor") {}
169
179
 
170
180
  /**
171
- * A `Subagents` implementation for contexts that cannot spawn agents.
181
+ * An `AgentTasks` implementation for contexts that cannot spawn agents.
172
182
  *
173
183
  * @since 1.0.0
174
184
  * @category Context
175
185
  */
176
- export const subagentsUnavailable: Subagents = {
186
+ export const agentTasksUnavailable: AgentTasks = {
177
187
  delegate: () => Effect.die(new Error("Sub-agents are not available here")),
178
- waitAgents: () => Effect.fail("Sub-agents are not available here"),
188
+ taskOutput: () => Effect.fail("Sub-agents are not available here"),
189
+ waitTasks: () => Effect.fail("Sub-agents are not available here"),
179
190
  messageAgent: () => Effect.fail("Sub-agents are not available here"),
180
- stopAgent: () => Effect.fail("Sub-agents are not available here"),
181
- listAgents: Effect.succeed([]),
191
+ stopTask: () => Effect.fail("Sub-agents are not available here"),
192
+ listTasks: Effect.succeed([]),
182
193
  }
183
194
 
195
+ /**
196
+ * The agent running the current script. Tasks are only visible to the agent
197
+ * that started them; scripts without an agent share the `undefined` owner.
198
+ * The executor sets it from `ExecuteOptions.agentId`.
199
+ *
200
+ * @since 1.0.0
201
+ * @category Context
202
+ */
203
+ export class TaskOwner extends Context.Reference<string | undefined>(
204
+ "clanka/AgentTools/TaskOwner",
205
+ { defaultValue: () => undefined },
206
+ ) {}
207
+
184
208
  /**
185
209
  * An image read by `readFile`, handed to the Agent so it can be spliced onto
186
210
  * the Prompt for the next model turn.
@@ -204,71 +228,36 @@ export class ImageAttacher extends Context.Service<
204
228
  >()("clanka/AgentTools/ImageAttacher") {}
205
229
 
206
230
  /**
207
- * @since 1.0.0
208
- * @category Models
209
- */
210
- export const BashJobStatus = Schema.Literals([
211
- "running",
212
- "completed",
213
- "failed",
214
- "stopped",
215
- ])
216
-
217
- /**
218
- * @since 1.0.0
219
- * @category Models
220
- */
221
- export type BashJobStatus = typeof BashJobStatus.Type
222
-
223
- /**
224
- * A `bash` command running in the background, as returned by `jobOutput`
225
- * and `stopJob`.
226
- *
227
- * @since 1.0.0
228
- * @category Models
229
- */
230
- export const BashJob = Schema.Struct({
231
- id: Schema.String,
232
- status: BashJobStatus,
233
- exitCode: Schema.optional(Schema.Number),
234
- output: Schema.String,
235
- })
236
-
237
- /**
238
- * @since 1.0.0
239
- * @category Models
240
- */
241
- export type BashJob = typeof BashJob.Type
242
-
243
- /**
244
- * A background `bash` job, handed to the `JobWatcher` when it starts.
231
+ * A task that has started, handed to the `TaskWatcher`.
245
232
  *
246
233
  * @since 1.0.0
247
234
  * @category Models
248
235
  */
249
- export interface BackgroundJob {
236
+ export interface TaskHandle {
250
237
  readonly id: string
251
- /** Waits for the job to end and succeeds with its final state. */
252
- readonly await: Effect.Effect<BashJob>
238
+ readonly kind: TaskKind
239
+ /** Waits for the task to end and succeeds with its final state. */
240
+ readonly await: Effect.Effect<Task>
253
241
  /**
254
- * Marks the job's final state as reported. Succeeds with `false` when it
255
- * already was: by `stopJob`, by a `jobOutput` call that returned it, or by
256
- * an earlier `claim`.
242
+ * Marks the task's final state as reported. Succeeds with `false` when it
243
+ * already was: by `stopTask`, `waitTasks`, a `taskOutput` call that
244
+ * returned it, or an earlier `claim`.
257
245
  */
258
246
  readonly claim: Effect.Effect<boolean>
259
247
  }
260
248
 
261
249
  /**
262
- * Receives every background `bash` job as it starts: those started with
263
- * `background: true` and those moved to the background at their timeout.
264
- * The executor sets it from `ExecuteOptions.onJob`.
250
+ * Receives every background `bash` task as it starts: those started with
251
+ * `background: true` and those moved to the background at their timeout. A
252
+ * command that `bash` returns finished is never handed over.
253
+ * The executor sets it from `ExecuteOptions.onTask`.
265
254
  *
266
255
  * @since 1.0.0
267
256
  * @category Context
268
257
  */
269
- export class JobWatcher extends Context.Reference<
270
- (job: BackgroundJob) => Effect.Effect<void>
271
- >("clanka/AgentTools/JobWatcher", {
258
+ export class TaskWatcher extends Context.Reference<
259
+ (task: TaskHandle) => Effect.Effect<void>
260
+ >("clanka/AgentTools/TaskWatcher", {
272
261
  defaultValue: () => () => Effect.void,
273
262
  }) {}
274
263
 
@@ -318,21 +307,20 @@ export class CommandLimits extends Context.Reference<{
318
307
  */
319
308
  export const makeBashTool = (timeout: Duration.Duration) =>
320
309
  Tool.make("bash", {
321
- description:
322
- 'Run a bash command and return the output. With `background: true` it returns straight away with a job id while the command keeps running. A command still running at its timeout is not stopped: it is moved to the background, and the output so far is returned with its job id. Read a job with "jobOutput" and stop it with "stopJob".',
310
+ description: "Run a bash command and return a task.",
323
311
  parameters: Schema.Struct({
324
312
  command: Schema.String,
325
313
  timeoutMs: Schema.optional(Schema.Finite).annotate({
326
- documentation: `How long to wait in ms before moving the command to the background (default and max: ${Duration.toMillis(timeout)})`,
314
+ documentation: `How long to wait in ms before moving the task to the background (default and max: ${Duration.toMillis(timeout)})`,
327
315
  }),
328
316
  background: Schema.optional(Schema.Boolean).annotate({
329
317
  documentation:
330
- "Start the command in the background and return its job id without waiting",
318
+ "Start the command in the background. Defaults to false which always returns 'completed' tasks.",
331
319
  }),
332
320
  }).annotate({
333
321
  identifier: "command",
334
322
  }),
335
- success: Schema.String,
323
+ success: Task,
336
324
  dependencies: [CurrentDirectory],
337
325
  })
338
326
 
@@ -347,7 +335,7 @@ const globNamesDirectory = (glob: string) =>
347
335
  * @category Context
348
336
  */
349
337
  export const makeContextNoop = (cwd?: string) =>
350
- SubagentExecutor.context(subagentsUnavailable).pipe(
338
+ AgentTaskExecutor.context(agentTasksUnavailable).pipe(
351
339
  Context.add(CurrentDirectory, cwd ?? "/"),
352
340
  Context.add(DirectoryChanger, () => Effect.die("Not implemented")),
353
341
  Context.add(TaskCompleter, () => Effect.void),
@@ -361,14 +349,14 @@ export const makeContextNoop = (cwd?: string) =>
361
349
  export const AgentTools = Toolkit.make(
362
350
  Tool.make("changeDirectory", {
363
351
  description:
364
- "Change the executor's working directory to an existing directory and return its absolute path. Relative paths resolve from the current directory without shell expansion. Await this before dependent tools. The change persists across your scripts. A sub-agent starts in your directory at the time it is created, and its changes do not affect yours. AGENTS.md files and skills that apply to the new directory are sent to you after the script ends. The semantic-search index root stays fixed.",
352
+ "Change the executor's working directory to an existing directory and return its absolute path. The change persists across your scripts.",
365
353
  parameters: Schema.String.annotate({ identifier: "directory" }),
366
354
  success: Schema.String,
367
355
  dependencies: [DirectoryChanger],
368
356
  }),
369
357
  Tool.make("readFile", {
370
358
  description:
371
- "Read a file and optionally filter the lines to return. Returns null if the file doesn't exist. For png/jpeg/gif/webp files the image itself is attached to your next turn and a short marker is returned instead of the bytes; line ranges are not allowed on images.",
359
+ "Read a file and optionally filter the lines to return. Returns null if the file doesn't exist. For png/jpeg/gif/webp files the image itself is attached to your next turn.",
372
360
  parameters: Schema.Struct({
373
361
  path: Schema.String,
374
362
  startLine: Schema.optional(Schema.Number),
@@ -401,52 +389,23 @@ export const AgentTools = Toolkit.make(
401
389
  }),
402
390
  Tool.make("delegate", {
403
391
  description:
404
- 'Delegate a task to another software engineer / sub-agent. By default it waits for the sub-agent and returns its output. With `background: true` it returns straight away with status "running"; the sub-agent keeps working while you take more turns, and its result is sent to you as a <subagent> message when it finishes. Keep the returned id to address the agent later.',
392
+ "Delegate a task to another software engineer / sub-agent. With `background: true` the sub-agent works in the background, and its result is sent to you when it finishes.",
405
393
  parameters: Schema.Struct({
406
394
  prompt: Schema.String,
407
395
  background: Schema.optional(Schema.Boolean),
408
396
  }),
409
- success: DelegateResult,
410
- failure: Schema.String,
411
- dependencies: [SubagentExecutor],
412
- }),
413
- Tool.make("waitAgents", {
414
- description:
415
- 'Wait until the given sub-agents have finished, or all of your sub-agents when no ids are passed. A failed agent is returned with status "failed" and its error as the output; it does not throw.',
416
- parameters: Schema.UndefinedOr(Schema.Array(Schema.String)).annotate({
417
- identifier: "ids",
418
- }),
419
- success: Schema.Array(SubagentResult),
397
+ success: Task,
420
398
  failure: Schema.String,
421
- dependencies: [SubagentExecutor],
399
+ dependencies: [AgentTaskExecutor],
422
400
  }),
423
401
  Tool.make("messageAgent", {
424
- description:
425
- "Send a message to one of your sub-agents. A running agent receives it as steering; a finished agent starts a new turn on top of its previous conversation. Returns straight away; the result is sent to you as a <subagent> message.",
402
+ description: "Send a message to one of your sub-agents.",
426
403
  parameters: Schema.Struct({
427
404
  id: Schema.String,
428
405
  message: Schema.String,
429
406
  }),
430
- success: SubagentResult,
431
- failure: Schema.String,
432
- dependencies: [SubagentExecutor],
433
- }),
434
- Tool.make("stopAgent", {
435
- description:
436
- "Stop one of your sub-agents and every agent it started. Returns its final status.",
437
- parameters: Schema.String.annotate({
438
- identifier: "id",
439
- }),
440
- success: SubagentResult,
441
407
  failure: Schema.String,
442
- dependencies: [SubagentExecutor],
443
- }),
444
- Tool.make("listAgents", {
445
- description:
446
- "List the sub-agents you have started in this run, with their status.",
447
- parameters: Schema.Void,
448
- success: Schema.Array(SubagentInfo),
449
- dependencies: [SubagentExecutor],
408
+ dependencies: [AgentTaskExecutor],
450
409
  }),
451
410
  Tool.make("glob", {
452
411
  description: "Find files matching a glob pattern.",
@@ -466,23 +425,44 @@ export const AgentTools = Toolkit.make(
466
425
  dependencies: [CurrentDirectory],
467
426
  }),
468
427
  makeBashTool(defaultBashTimeout),
469
- Tool.make("jobOutput", {
428
+ Tool.make("taskOutput", {
470
429
  description:
471
- "Return the status and output so far of a background bash job.",
430
+ "Return the status and output so far of one of your tasks: a background bash command or a sub-agent.",
472
431
  parameters: Schema.String.annotate({
473
432
  identifier: "id",
474
433
  }),
475
- success: BashJob,
434
+ success: Task,
476
435
  failure: Schema.String,
436
+ dependencies: [AgentTaskExecutor],
477
437
  }),
478
- Tool.make("stopJob", {
438
+ Tool.make("waitTasks", {
479
439
  description:
480
- "Stop a background bash job and return its final status and output.",
440
+ "Wait until the given tasks have ended and return them, in the order given.",
441
+ parameters: Schema.Struct({
442
+ ids: Schema.Array(Schema.String),
443
+ timeoutMs: Schema.optional(Schema.Finite).annotate({
444
+ documentation:
445
+ "How long to wait in ms (default and max: the bash command timeout)",
446
+ }),
447
+ }),
448
+ success: Schema.Array(Task),
449
+ failure: Schema.String,
450
+ dependencies: [AgentTaskExecutor],
451
+ }),
452
+ Tool.make("stopTask", {
453
+ description: "Stop one of your tasks.",
481
454
  parameters: Schema.String.annotate({
482
455
  identifier: "id",
483
456
  }),
484
- success: BashJob,
457
+ success: Task,
485
458
  failure: Schema.String,
459
+ dependencies: [AgentTaskExecutor],
460
+ }),
461
+ Tool.make("listTasks", {
462
+ description: "List the tasks you have started, with their status.",
463
+ parameters: Schema.Void,
464
+ success: Schema.Array(Task),
465
+ dependencies: [AgentTaskExecutor],
486
466
  }),
487
467
  Tool.make("applyPatch", {
488
468
  description:
@@ -623,70 +603,58 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(
623
603
  return { fiber, output: output.render }
624
604
  })
625
605
 
626
- const jobs = new Map<string, RunningCommand>()
627
- let nextJobId = 1
628
- const addJob = Effect.fnUntraced(function* (
606
+ // Every task started on this executor, bash and agent alike, so both
607
+ // kinds share one id space. Each is only visible to the agent that
608
+ // started it.
609
+ const tasks = new Map<string, TaskEntry>()
610
+ let nextTaskId = 1
611
+ const registerAgentTask = Effect.fnUntraced(function* () {
612
+ const id = String(nextTaskId++)
613
+ tasks.set(id, { kind: "agent", id, owner: yield* TaskOwner })
614
+ return id
615
+ })
616
+ // Every `bash` command is a task, so any of them can be addressed by
617
+ // id. Only the ones still running when `bash` returns go to the
618
+ // `TaskWatcher`.
619
+ const addBashTask = Effect.fnUntraced(function* (
620
+ description: string,
629
621
  command: Omit<RunningCommand, "reported">,
630
622
  ) {
631
- const id = String(nextJobId++)
632
- const running: RunningCommand = { ...command, reported: false }
633
- jobs.set(id, running)
634
- const watch = yield* JobWatcher
623
+ const entry: BashEntry = {
624
+ kind: "bash",
625
+ id: String(nextTaskId++),
626
+ owner: yield* TaskOwner,
627
+ description,
628
+ command: { ...command, reported: false },
629
+ }
630
+ tasks.set(entry.id, entry)
631
+ return entry
632
+ })
633
+ const watchBashTask = Effect.fnUntraced(function* (entry: BashEntry) {
634
+ const watch = yield* TaskWatcher
635
635
  yield* watch({
636
- id,
637
- await: Fiber.await(running.fiber).pipe(
638
- Effect.map(() => jobInfo(id, running)),
636
+ id: entry.id,
637
+ kind: "bash",
638
+ await: Fiber.await(entry.command.fiber).pipe(
639
+ Effect.map(() => bashTask(entry)),
639
640
  ),
640
641
  claim: Effect.sync(() => {
641
- if (running.reported) return false
642
- running.reported = true
642
+ if (entry.command.reported) return false
643
+ entry.command.reported = true
643
644
  return true
644
645
  }),
645
646
  })
646
- return id
647
647
  })
648
- const findJob = (id: string) => {
649
- const running = jobs.get(id)
650
- return running === undefined
651
- ? Effect.fail(`No background job with id "${id}"`)
652
- : Effect.succeed(running)
653
- }
654
-
655
- // A command still running at its timeout is stopped, or with
656
- // `background` handed over as a job. A caller that is interrupted first
657
- // stops it either way.
658
- const runCommand = Effect.fnUntraced(function* (
659
- command: ChildProcess.Command,
660
- timeout: Duration.Duration | undefined,
661
- onTimeout: "stop" | "background",
662
- ) {
663
- const running = yield* startCommand(command)
664
- const awaited = Fiber.await(running.fiber)
665
- const exit = yield* (
666
- timeout === undefined
667
- ? Effect.asSome(awaited)
668
- : Effect.timeoutOption(awaited, timeout)
669
- ).pipe(Effect.onInterrupt(() => Fiber.interrupt(running.fiber)))
670
- if (Option.isNone(exit)) {
671
- const timeoutMs = Duration.toMillis(timeout!)
672
- if (onTimeout === "stop") {
673
- yield* Fiber.interrupt(running.fiber)
674
- return yield* Effect.die(
675
- new Error(`Command timed out after ${timeoutMs}ms`),
676
- )
677
- }
678
- const id = yield* addJob(running)
679
- const output = running.output()
680
- return `${output}${output === "" || output.endsWith("\n") ? "" : "\n"}[Still running after ${timeoutMs}ms, so it was moved to the background as job ${id}. ${jobUsage(id)}]`
648
+ const findTask = Effect.fnUntraced(function* (id: string) {
649
+ const owner = yield* TaskOwner
650
+ const entry = tasks.get(id)
651
+ if (entry === undefined || entry.owner !== owner) {
652
+ return yield* Effect.fail(
653
+ `No task with id ${JSON.stringify(id)}. You can only address tasks you started; call listTasks() to see them.`,
654
+ )
681
655
  }
682
- const exitCode = yield* exit.value
683
- const output = running.output()
684
- if (exitCode === 0) return output
685
- return yield* Effect.die(
686
- new Error(`Command failed with exit code ${exitCode}: ${output}`),
687
- )
656
+ return entry
688
657
  })
689
-
690
658
  /**
691
659
  * Image branch of `readFile`: the bytes go to the `ImageAttacher` for
692
660
  * the next model turn and the script only sees a marker.
@@ -889,8 +857,7 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(
889
857
  )
890
858
  }),
891
859
  bash: Effect.fn("AgentTools.bash")(function* (options) {
892
- const limits = yield* CommandLimits
893
- const maxMs = Duration.toMillis(limits.timeout ?? defaultBashTimeout)
860
+ const maxMs = bashTimeoutMs(yield* CommandLimits)
894
861
  const timeoutMs = Math.min(options.timeoutMs ?? maxMs, maxMs)
895
862
  yield* Effect.logInfo(`Calling "bash"`).pipe(
896
863
  Effect.annotateLogs({
@@ -903,31 +870,117 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(
903
870
  cwd,
904
871
  stdin: "ignore",
905
872
  })
906
- if (options.background === true) {
907
- const id = yield* addJob(yield* startCommand(cmd))
908
- return `Started background job ${id}. ${jobUsage(id)}`
873
+ const entry = yield* addBashTask(
874
+ options.command,
875
+ yield* startCommand(cmd),
876
+ )
877
+ if (options.background !== true) {
878
+ const exit = yield* awaitCommand(
879
+ entry.command,
880
+ Duration.millis(timeoutMs),
881
+ )
882
+ if (Option.isSome(exit)) {
883
+ // A finished command is reported here, so it is never pushed.
884
+ const exitCode = yield* exit.value
885
+ const task = reportBash(entry)
886
+ if (exitCode === 0) return task
887
+ return yield* Effect.die(
888
+ new Error(
889
+ `Command failed with exit code ${exitCode}: ${task.output}`,
890
+ ),
891
+ )
892
+ }
909
893
  }
910
- return yield* runCommand(cmd, Duration.millis(timeoutMs), "background")
894
+ // Snapshot the task before yielding to the watcher: the command can
895
+ // finish while it is being handed over, and its final state must
896
+ // reach the model only once. A finished task is never handed over.
897
+ const task = reportBash(entry)
898
+ if (task.status === "running") yield* watchBashTask(entry)
899
+ return task
911
900
  }, Effect.orDie),
912
- jobOutput: Effect.fn("AgentTools.jobOutput")(function* (input: unknown) {
913
- const id = yield* decodeJobOutput(input)
914
- yield* Effect.logInfo(`Calling "jobOutput"`).pipe(
901
+ taskOutput: Effect.fn("AgentTools.taskOutput")(function* (
902
+ input: unknown,
903
+ ) {
904
+ const id = yield* decodeTaskOutput(input)
905
+ yield* Effect.logInfo(`Calling "taskOutput"`).pipe(
915
906
  Effect.annotateLogs({ id }),
916
907
  )
917
- const running = yield* findJob(id)
918
- const job = jobInfo(id, running)
919
- if (job.status !== "running") running.reported = true
920
- return job
908
+ const entry = yield* findTask(id)
909
+ if (entry.kind === "bash") return reportBash(entry)
910
+ const agentTasks = yield* AgentTaskExecutor
911
+ return yield* agentTasks.taskOutput(id)
912
+ }),
913
+ waitTasks: Effect.fn("AgentTools.waitTasks")(function* (input: unknown) {
914
+ const { ids, timeoutMs: requestedMs } = yield* decodeWaitTasks(input)
915
+ const maxMs = bashTimeoutMs(yield* CommandLimits)
916
+ const timeoutMs = Math.min(requestedMs ?? maxMs, maxMs)
917
+ yield* Effect.logInfo(`Calling "waitTasks"`).pipe(
918
+ Effect.annotateLogs({ ids, timeoutMs }),
919
+ )
920
+ const entries = yield* Effect.forEach(ids, findTask)
921
+ const bashEntries = entries.filter(
922
+ (entry): entry is BashEntry => entry.kind === "bash",
923
+ )
924
+ const agentIds = entries.flatMap((entry) =>
925
+ entry.kind === "agent" ? [entry.id] : [],
926
+ )
927
+ const agentTasks = yield* AgentTaskExecutor
928
+ // Nothing is reported until the batch is ready to return: a script
929
+ // stopped while it waits never receives it, so the tasks that ended
930
+ // first must still be pushed. The bash tasks are waited for first,
931
+ // without reporting them. Then one `AgentTasks.waitTasks` call waits
932
+ // for the agents with the time left and reports them together, so
933
+ // over RPC only its single response can be cut off. The agents keep
934
+ // running meanwhile. Tasks still running at the deadline are
935
+ // returned as running and keep going.
936
+ const startedAt = yield* Clock.currentTimeMillis
937
+ yield* Effect.forEach(
938
+ bashEntries,
939
+ (entry) => Fiber.await(entry.command.fiber),
940
+ { concurrency: "unbounded", discard: true },
941
+ ).pipe(Effect.timeoutOption(timeoutMs))
942
+ const agentResults =
943
+ agentIds.length === 0
944
+ ? []
945
+ : yield* agentTasks.waitTasks(agentIds, {
946
+ timeoutMs: Math.max(
947
+ 0,
948
+ timeoutMs - ((yield* Clock.currentTimeMillis) - startedAt),
949
+ ),
950
+ })
951
+ const ended = new Map(
952
+ [...bashEntries.map(reportBash), ...agentResults].map((task) => [
953
+ task.id,
954
+ task,
955
+ ]),
956
+ )
957
+ return ids.map((id) => ended.get(id)!)
921
958
  }),
922
- stopJob: Effect.fn("AgentTools.stopJob")(function* (input: unknown) {
923
- const id = yield* decodeStopJob(input)
924
- yield* Effect.logInfo(`Calling "stopJob"`).pipe(
959
+ stopTask: Effect.fn("AgentTools.stopTask")(function* (input: unknown) {
960
+ const id = yield* decodeStopTask(input)
961
+ yield* Effect.logInfo(`Calling "stopTask"`).pipe(
925
962
  Effect.annotateLogs({ id }),
926
963
  )
927
- const running = yield* findJob(id)
928
- yield* Fiber.interrupt(running.fiber)
929
- running.reported = true
930
- return jobInfo(id, running)
964
+ const entry = yield* findTask(id)
965
+ if (entry.kind === "agent") {
966
+ const agentTasks = yield* AgentTaskExecutor
967
+ return yield* agentTasks.stopTask(id)
968
+ }
969
+ yield* Fiber.interrupt(entry.command.fiber)
970
+ return reportBash(entry)
971
+ }),
972
+ listTasks: Effect.fn("AgentTools.listTasks")(function* () {
973
+ yield* Effect.logInfo(`Calling "listTasks"`)
974
+ const owner = yield* TaskOwner
975
+ const bashTasks = Array.Array.from(tasks.values()).flatMap((entry) =>
976
+ entry.kind === "bash" && entry.owner === owner
977
+ ? [bashTask(entry)]
978
+ : [],
979
+ )
980
+ const agentTasks = yield* AgentTaskExecutor
981
+ return [...bashTasks, ...(yield* agentTasks.listTasks)].toSorted(
982
+ (a, b) => Number(a.id) - Number(b.id),
983
+ )
931
984
  }),
932
985
  gh: Effect.fn("AgentTools.gh")(function* (args) {
933
986
  yield* Effect.logInfo(`Calling "gh"`).pipe(
@@ -939,7 +992,22 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(
939
992
  stdin: "ignore",
940
993
  })
941
994
  const { timeout } = yield* CommandLimits
942
- return yield* runCommand(cmd, timeout, "stop")
995
+ const running = yield* startCommand(cmd)
996
+ const exit = yield* awaitCommand(running, timeout)
997
+ if (Option.isNone(exit)) {
998
+ yield* Fiber.interrupt(running.fiber)
999
+ return yield* Effect.die(
1000
+ new Error(
1001
+ `Command timed out after ${Duration.toMillis(timeout!)}ms`,
1002
+ ),
1003
+ )
1004
+ }
1005
+ const exitCode = yield* exit.value
1006
+ const output = running.output()
1007
+ if (exitCode === 0) return output
1008
+ return yield* Effect.die(
1009
+ new Error(`Command failed with exit code ${exitCode}: ${output}`),
1010
+ )
943
1011
  }, Effect.orDie),
944
1012
  webSearch: Effect.fn("AgentTools.webSearch")(function* (options) {
945
1013
  yield* Effect.logInfo(`Calling "webSearch"`).pipe(
@@ -1100,18 +1168,9 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(
1100
1168
  yield* Effect.logInfo(`Calling "delegate"`).pipe(
1101
1169
  Effect.annotateLogs({ background }),
1102
1170
  )
1103
- const subagents = yield* SubagentExecutor
1104
- return yield* subagents.delegate({ prompt, background })
1105
- }),
1106
- waitAgents: Effect.fn("AgentTools.waitAgents")(function* (
1107
- input: unknown,
1108
- ) {
1109
- const ids = yield* decodeWaitAgents(input)
1110
- yield* Effect.logInfo(`Calling "waitAgents"`).pipe(
1111
- Effect.annotateLogs({ ids }),
1112
- )
1113
- const subagents = yield* SubagentExecutor
1114
- return yield* subagents.waitAgents(ids)
1171
+ const id = yield* registerAgentTask()
1172
+ const agentTasks = yield* AgentTaskExecutor
1173
+ return yield* agentTasks.delegate({ id, prompt, background })
1115
1174
  }),
1116
1175
  messageAgent: Effect.fn("AgentTools.messageAgent")(function* (
1117
1176
  input: unknown,
@@ -1120,21 +1179,14 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(
1120
1179
  yield* Effect.logInfo(`Calling "messageAgent"`).pipe(
1121
1180
  Effect.annotateLogs({ id: options.id }),
1122
1181
  )
1123
- const subagents = yield* SubagentExecutor
1124
- return yield* subagents.messageAgent(options)
1125
- }),
1126
- stopAgent: Effect.fn("AgentTools.stopAgent")(function* (input: unknown) {
1127
- const id = yield* decodeStopAgent(input)
1128
- yield* Effect.logInfo(`Calling "stopAgent"`).pipe(
1129
- Effect.annotateLogs({ id }),
1130
- )
1131
- const subagents = yield* SubagentExecutor
1132
- return yield* subagents.stopAgent(id)
1133
- }),
1134
- listAgents: Effect.fn("AgentTools.listAgents")(function* () {
1135
- yield* Effect.logInfo(`Calling "listAgents"`)
1136
- const subagents = yield* SubagentExecutor
1137
- return yield* subagents.listAgents
1182
+ const entry = yield* findTask(options.id)
1183
+ if (entry.kind === "bash") {
1184
+ return yield* Effect.fail(
1185
+ `messageAgent only addresses sub-agents, and task ${JSON.stringify(entry.id)} is a bash task. Use taskOutput or stopTask with it instead.`,
1186
+ )
1187
+ }
1188
+ const agentTasks = yield* AgentTaskExecutor
1189
+ return yield* agentTasks.messageAgent(options)
1138
1190
  }),
1139
1191
  taskComplete: Effect.fn("AgentTools.taskComplete")(function* (
1140
1192
  message: unknown,
@@ -1191,26 +1243,25 @@ const decodeDelegate = decodeParams(
1191
1243
  AgentTools.tools.delegate.parametersSchema,
1192
1244
  'delegate requires an options object, for example: delegate({ prompt: "..." }) or delegate({ prompt: "...", background: true }).',
1193
1245
  )
1194
- const decodeWaitAgents = decodeParams(
1195
- AgentTools.tools.waitAgents.parametersSchema,
1196
- 'waitAgents takes an optional array of agent ids, for example: waitAgents(["3", "4"]).',
1197
- )
1198
1246
  const decodeMessageAgent = decodeParams(
1199
1247
  AgentTools.tools.messageAgent.parametersSchema,
1200
1248
  'messageAgent requires an options object, for example: messageAgent({ id: "3", message: "..." }).',
1201
1249
  )
1202
- const decodeStopAgent = decodeParams(
1203
- AgentTools.tools.stopAgent.parametersSchema,
1204
- 'stopAgent requires an agent id, for example: stopAgent("3").',
1250
+ const decodeTaskOutput = decodeParams(
1251
+ AgentTools.tools.taskOutput.parametersSchema,
1252
+ 'taskOutput requires a task id, for example: taskOutput("1").',
1205
1253
  )
1206
-
1207
- const decodeJobOutput = decodeParams(
1208
- AgentTools.tools.jobOutput.parametersSchema,
1209
- 'jobOutput requires a job id, for example: jobOutput("1").',
1254
+ const decodeWaitTasks = decodeParams(
1255
+ AgentTools.tools.waitTasks.parametersSchema,
1256
+ 'waitTasks requires an options object, for example: waitTasks({ ids: ["3", "4"] }) or waitTasks({ ids: ["3"], timeoutMs: 60000 }).',
1210
1257
  )
1211
- const decodeStopJob = decodeParams(
1212
- AgentTools.tools.stopJob.parametersSchema,
1213
- 'stopJob requires a job id, for example: stopJob("1").',
1258
+
1259
+ /** The caller's `bash` timeout, which also bounds `waitTasks`. */
1260
+ const bashTimeoutMs = (limits: typeof CommandLimits.Service) =>
1261
+ Duration.toMillis(limits.timeout ?? defaultBashTimeout)
1262
+ const decodeStopTask = decodeParams(
1263
+ AgentTools.tools.stopTask.parametersSchema,
1264
+ 'stopTask requires a task id, for example: stopTask("1").',
1214
1265
  )
1215
1266
 
1216
1267
  interface RunningCommand {
@@ -1226,27 +1277,68 @@ interface RunningCommand {
1226
1277
  reported: boolean
1227
1278
  }
1228
1279
 
1229
- const jobUsage = (id: string) =>
1230
- `Use jobOutput("${id}") for its status and output, or stopJob("${id}") to stop it.`
1280
+ // Waits up to `timeout` for a command to exit. A caller that is
1281
+ // interrupted first stops the command.
1282
+ const awaitCommand = (
1283
+ command: Omit<RunningCommand, "reported">,
1284
+ timeout: Duration.Duration | undefined,
1285
+ ) => {
1286
+ const awaited = Fiber.await(command.fiber)
1287
+ return (
1288
+ timeout === undefined
1289
+ ? Effect.asSome(awaited)
1290
+ : Effect.timeoutOption(awaited, timeout)
1291
+ ).pipe(Effect.onInterrupt(() => Fiber.interrupt(command.fiber)))
1292
+ }
1293
+
1294
+ interface BashEntry {
1295
+ readonly kind: "bash"
1296
+ readonly id: string
1297
+ readonly owner: string | undefined
1298
+ readonly description: string
1299
+ readonly command: RunningCommand
1300
+ }
1301
+
1302
+ /** The executor only records who owns an agent task; the agent tracks it. */
1303
+ interface AgentEntry {
1304
+ readonly kind: "agent"
1305
+ readonly id: string
1306
+ readonly owner: string | undefined
1307
+ }
1308
+
1309
+ type TaskEntry = BashEntry | AgentEntry
1231
1310
 
1232
- const jobInfo = (id: string, running: RunningCommand): BashJob => {
1233
- const exit = running.fiber.pollUnsafe()
1234
- const output = running.output()
1235
- if (exit === undefined) return { id, status: "running", output }
1311
+ // A bash task's final state, once returned to the script, is not pushed.
1312
+ const reportBash = (entry: BashEntry): Task => {
1313
+ const task = bashTask(entry)
1314
+ if (task.status !== "running") entry.command.reported = true
1315
+ return task
1316
+ }
1317
+
1318
+ const bashTask = ({ id, description, command }: BashEntry): Task => {
1319
+ const exit = command.fiber.pollUnsafe()
1320
+ const output = command.output()
1321
+ if (exit === undefined) {
1322
+ return { id, kind: "bash", status: "running", description, output }
1323
+ }
1236
1324
  if (Exit.isSuccess(exit)) {
1237
1325
  return {
1238
1326
  id,
1327
+ kind: "bash",
1239
1328
  status: exit.value === 0 ? "completed" : "failed",
1240
- exitCode: exit.value,
1329
+ description,
1241
1330
  output,
1331
+ exitCode: exit.value,
1242
1332
  }
1243
1333
  }
1244
1334
  if (Cause.hasInterruptsOnly(exit.cause)) {
1245
- return { id, status: "stopped", output }
1335
+ return { id, kind: "bash", status: "stopped", description, output }
1246
1336
  }
1247
1337
  return {
1248
1338
  id,
1339
+ kind: "bash",
1249
1340
  status: "failed",
1341
+ description,
1250
1342
  output: `${output}${output === "" ? "" : "\n"}${Cause.pretty(exit.cause)}`,
1251
1343
  }
1252
1344
  }