clanka 0.21.0 → 0.22.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.
Files changed (48) hide show
  1. package/dist/Acp.test.js +19 -7
  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 +47 -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 -79
  16. package/dist/AgentExecutor.js.map +1 -1
  17. package/dist/AgentExecutor.test.js +108 -83
  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 +218 -29
  24. package/dist/AgentSubagents.test.js.map +1 -1
  25. package/dist/AgentTools.d.ts +318 -290
  26. package/dist/AgentTools.d.ts.map +1 -1
  27. package/dist/AgentTools.js +225 -199
  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/AgentToolsReadFile.test.js +8 -2
  32. package/dist/AgentToolsReadFile.test.js.map +1 -1
  33. package/dist/bin/cli.mjs +309 -289
  34. package/dist/bin/cli.mjs.map +1 -1
  35. package/package.json +1 -1
  36. package/src/Acp.test.ts +31 -10
  37. package/src/Agent.test.ts +5 -4
  38. package/src/Agent.ts +175 -140
  39. package/src/AgentBashJobs.test.ts +70 -38
  40. package/src/AgentCallerConfig.test.ts +39 -7
  41. package/src/AgentExecutor.test.ts +132 -91
  42. package/src/AgentExecutor.ts +120 -105
  43. package/src/AgentExecutorImage.test.ts +2 -2
  44. package/src/AgentImage.test.ts +4 -3
  45. package/src/AgentSubagents.test.ts +825 -562
  46. package/src/AgentTools.test.ts +2 -2
  47. package/src/AgentTools.ts +345 -288
  48. package/src/AgentToolsReadFile.test.ts +14 -3
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>
138
+ /**
139
+ * The agent's status and output so far. A final status counts as reported.
140
+ */
141
+ readonly taskOutput: (id: string) => Effect.Effect<Task, string>
140
142
  /**
141
- * Wait for the listed agents, or all of them when `ids` is undefined.
142
- * Failures are returned as results, not raised.
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.
143
149
  */
144
- readonly waitAgents: (
145
- ids: ReadonlyArray<string> | undefined,
146
- ) => Effect.Effect<ReadonlyArray<SubagentResult>, string>
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,74 +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 and its state: the task that `bash`, `jobOutput`,
225
- * `waitJob` and `stopJob` return. `exitCode` is set once the command has
226
- * exited; a non-zero exit is `failed`. A foreground `bash` command that
227
- * fails rejects instead of returning a task.
231
+ * A task that has started, handed to the `TaskWatcher`.
228
232
  *
229
233
  * @since 1.0.0
230
234
  * @category Models
231
235
  */
232
- export const BashJob = Schema.Struct({
233
- id: Schema.String,
234
- status: BashJobStatus,
235
- exitCode: Schema.optional(Schema.Number),
236
- output: Schema.String,
237
- })
238
-
239
- /**
240
- * @since 1.0.0
241
- * @category Models
242
- */
243
- export type BashJob = typeof BashJob.Type
244
-
245
- /**
246
- * A background `bash` job, handed to the `JobWatcher` when it starts.
247
- *
248
- * @since 1.0.0
249
- * @category Models
250
- */
251
- export interface BackgroundJob {
236
+ export interface TaskHandle {
252
237
  readonly id: string
253
- /** Waits for the job to end and succeeds with its final state. */
254
- 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>
255
241
  /**
256
- * Marks the job's final state as reported. Succeeds with `false` when it
257
- * already was: by `stopJob`, by a `jobOutput` call that returned it, or by
258
- * 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`.
259
245
  */
260
246
  readonly claim: Effect.Effect<boolean>
261
247
  }
262
248
 
263
249
  /**
264
- * Receives every background `bash` job as it starts: those started with
250
+ * Receives every background `bash` task as it starts: those started with
265
251
  * `background: true` and those moved to the background at their timeout. A
266
252
  * command that `bash` returns finished is never handed over.
267
- * The executor sets it from `ExecuteOptions.onJob`.
253
+ * The executor sets it from `ExecuteOptions.onTask`.
268
254
  *
269
255
  * @since 1.0.0
270
256
  * @category Context
271
257
  */
272
- export class JobWatcher extends Context.Reference<
273
- (job: BackgroundJob) => Effect.Effect<void>
274
- >("clanka/AgentTools/JobWatcher", {
258
+ export class TaskWatcher extends Context.Reference<
259
+ (task: TaskHandle) => Effect.Effect<void>
260
+ >("clanka/AgentTools/TaskWatcher", {
275
261
  defaultValue: () => () => Effect.void,
276
262
  }) {}
277
263
 
@@ -321,21 +307,20 @@ export class CommandLimits extends Context.Reference<{
321
307
  */
322
308
  export const makeBashTool = (timeout: Duration.Duration) =>
323
309
  Tool.make("bash", {
324
- description:
325
- 'Run a bash command and return a task with its job id, status, exit code and output. A command that fails before it is returned rejects with its exit code and output. With `background: true` it returns straight away with status "running" while the command keeps going. A command still running at its timeout is not stopped: it is moved to the background and returned as "running" with the output so far. Wait for a job with "waitJob", read it with "jobOutput" and stop it with "stopJob"; a background job that fails is reported with status "failed" and its exitCode.',
310
+ description: "Run a bash command and return a task.",
326
311
  parameters: Schema.Struct({
327
312
  command: Schema.String,
328
313
  timeoutMs: Schema.optional(Schema.Finite).annotate({
329
- 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)})`,
330
315
  }),
331
316
  background: Schema.optional(Schema.Boolean).annotate({
332
317
  documentation:
333
- 'Start the command in the background and return it as "running" without waiting',
318
+ "Start the command in the background. Defaults to false which always returns 'completed' tasks.",
334
319
  }),
335
320
  }).annotate({
336
321
  identifier: "command",
337
322
  }),
338
- success: BashJob,
323
+ success: Task,
339
324
  dependencies: [CurrentDirectory],
340
325
  })
341
326
 
@@ -350,7 +335,7 @@ const globNamesDirectory = (glob: string) =>
350
335
  * @category Context
351
336
  */
352
337
  export const makeContextNoop = (cwd?: string) =>
353
- SubagentExecutor.context(subagentsUnavailable).pipe(
338
+ AgentTaskExecutor.context(agentTasksUnavailable).pipe(
354
339
  Context.add(CurrentDirectory, cwd ?? "/"),
355
340
  Context.add(DirectoryChanger, () => Effect.die("Not implemented")),
356
341
  Context.add(TaskCompleter, () => Effect.void),
@@ -364,14 +349,14 @@ export const makeContextNoop = (cwd?: string) =>
364
349
  export const AgentTools = Toolkit.make(
365
350
  Tool.make("changeDirectory", {
366
351
  description:
367
- "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.",
368
353
  parameters: Schema.String.annotate({ identifier: "directory" }),
369
354
  success: Schema.String,
370
355
  dependencies: [DirectoryChanger],
371
356
  }),
372
357
  Tool.make("readFile", {
373
358
  description:
374
- "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.",
375
360
  parameters: Schema.Struct({
376
361
  path: Schema.String,
377
362
  startLine: Schema.optional(Schema.Number),
@@ -404,52 +389,23 @@ export const AgentTools = Toolkit.make(
404
389
  }),
405
390
  Tool.make("delegate", {
406
391
  description:
407
- '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.",
408
393
  parameters: Schema.Struct({
409
394
  prompt: Schema.String,
410
395
  background: Schema.optional(Schema.Boolean),
411
396
  }),
412
- success: DelegateResult,
397
+ success: Task,
413
398
  failure: Schema.String,
414
- dependencies: [SubagentExecutor],
415
- }),
416
- Tool.make("waitAgents", {
417
- description:
418
- '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.',
419
- parameters: Schema.UndefinedOr(Schema.Array(Schema.String)).annotate({
420
- identifier: "ids",
421
- }),
422
- success: Schema.Array(SubagentResult),
423
- failure: Schema.String,
424
- dependencies: [SubagentExecutor],
399
+ dependencies: [AgentTaskExecutor],
425
400
  }),
426
401
  Tool.make("messageAgent", {
427
- description:
428
- "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.",
429
403
  parameters: Schema.Struct({
430
404
  id: Schema.String,
431
405
  message: Schema.String,
432
406
  }),
433
- success: SubagentResult,
434
407
  failure: Schema.String,
435
- dependencies: [SubagentExecutor],
436
- }),
437
- Tool.make("stopAgent", {
438
- description:
439
- "Stop one of your sub-agents and every agent it started. Returns its final status.",
440
- parameters: Schema.String.annotate({
441
- identifier: "id",
442
- }),
443
- success: SubagentResult,
444
- failure: Schema.String,
445
- dependencies: [SubagentExecutor],
446
- }),
447
- Tool.make("listAgents", {
448
- description:
449
- "List the sub-agents you have started in this run, with their status.",
450
- parameters: Schema.Void,
451
- success: Schema.Array(SubagentInfo),
452
- dependencies: [SubagentExecutor],
408
+ dependencies: [AgentTaskExecutor],
453
409
  }),
454
410
  Tool.make("glob", {
455
411
  description: "Find files matching a glob pattern.",
@@ -469,36 +425,44 @@ export const AgentTools = Toolkit.make(
469
425
  dependencies: [CurrentDirectory],
470
426
  }),
471
427
  makeBashTool(defaultBashTimeout),
472
- Tool.make("jobOutput", {
428
+ Tool.make("taskOutput", {
473
429
  description:
474
- "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.",
475
431
  parameters: Schema.String.annotate({
476
432
  identifier: "id",
477
433
  }),
478
- success: BashJob,
434
+ success: Task,
479
435
  failure: Schema.String,
436
+ dependencies: [AgentTaskExecutor],
480
437
  }),
481
- Tool.make("waitJob", {
438
+ Tool.make("waitTasks", {
482
439
  description:
483
- 'Wait for a bash job to end and return its task. When the timeout passes first, the task is returned as "running" and the command keeps going.',
440
+ "Wait until the given tasks have ended and return them, in the order given.",
484
441
  parameters: Schema.Struct({
485
- id: Schema.String,
442
+ ids: Schema.Array(Schema.String),
486
443
  timeoutMs: Schema.optional(Schema.Finite).annotate({
487
444
  documentation:
488
- "How long to wait in ms (default and max: the bash timeout)",
445
+ "How long to wait in ms (default and max: the bash command timeout)",
489
446
  }),
490
447
  }),
491
- success: BashJob,
448
+ success: Schema.Array(Task),
492
449
  failure: Schema.String,
450
+ dependencies: [AgentTaskExecutor],
493
451
  }),
494
- Tool.make("stopJob", {
495
- description:
496
- "Stop a background bash job and return its final status and output.",
452
+ Tool.make("stopTask", {
453
+ description: "Stop one of your tasks.",
497
454
  parameters: Schema.String.annotate({
498
455
  identifier: "id",
499
456
  }),
500
- success: BashJob,
457
+ success: Task,
501
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],
502
466
  }),
503
467
  Tool.make("applyPatch", {
504
468
  description:
@@ -639,59 +603,58 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(
639
603
  return { fiber, output: output.render }
640
604
  })
641
605
 
642
- // Every `bash` command is a job, so it can be addressed by id. Only
643
- // the ones still running when `bash` returns go to the `JobWatcher`.
644
- const jobs = new Map<string, RunningCommand>()
645
- let nextJobId = 1
646
- const addJob = (command: Omit<RunningCommand, "reported">) => {
647
- const id = String(nextJobId++)
648
- const running: RunningCommand = { ...command, reported: false }
649
- jobs.set(id, running)
650
- return { id, running }
651
- }
652
- const watchJob = Effect.fnUntraced(function* (
653
- id: string,
654
- running: RunningCommand,
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,
621
+ command: Omit<RunningCommand, "reported">,
655
622
  ) {
656
- 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
657
635
  yield* watch({
658
- id,
659
- await: Fiber.await(running.fiber).pipe(
660
- 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)),
661
640
  ),
662
641
  claim: Effect.sync(() => {
663
- if (running.reported) return false
664
- running.reported = true
642
+ if (entry.command.reported) return false
643
+ entry.command.reported = true
665
644
  return true
666
645
  }),
667
646
  })
668
647
  })
669
- const findJob = (id: string) => {
670
- const running = jobs.get(id)
671
- return running === undefined
672
- ? Effect.fail(`No background job with id "${id}"`)
673
- : Effect.succeed(running)
674
- }
675
- // The final state of a job the model has been given is not pushed.
676
- const reportJob = (id: string, running: RunningCommand) => {
677
- const job = jobInfo(id, running)
678
- if (job.status !== "running") running.reported = true
679
- return job
680
- }
681
- // Waits up to `timeout` for a command to exit. A caller that is
682
- // interrupted first stops the command.
683
- const awaitCommand = (
684
- running: RunningCommand | Omit<RunningCommand, "reported">,
685
- timeout: Duration.Duration | undefined,
686
- ) => {
687
- const awaited = Fiber.await(running.fiber)
688
- return (
689
- timeout === undefined
690
- ? Effect.asSome(awaited)
691
- : Effect.timeoutOption(awaited, timeout)
692
- ).pipe(Effect.onInterrupt(() => Fiber.interrupt(running.fiber)))
693
- }
694
-
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
+ )
655
+ }
656
+ return entry
657
+ })
695
658
  /**
696
659
  * Image branch of `readFile`: the bytes go to the `ImageAttacher` for
697
660
  * the next model turn and the script only sees a marker.
@@ -757,6 +720,20 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(
757
720
  if (Option.isSome(imageType)) {
758
721
  return yield* readImage(path, imageType.value, options)
759
722
  }
723
+ if (
724
+ options.lineNumbers === false &&
725
+ !options.startLine &&
726
+ !options.endLine
727
+ ) {
728
+ // Return the file verbatim, keeping its trailing newline and line
729
+ // endings so the text can be written back unchanged.
730
+ return yield* fs.readFileString(path).pipe(
731
+ Effect.catchReason("PlatformError", "NotFound", () =>
732
+ Effect.succeed(null),
733
+ ),
734
+ Effect.orDie,
735
+ )
736
+ }
760
737
  let stream = pipe(fs.stream(path), Stream.decodeText, Stream.splitLines)
761
738
  if (options.startLine) {
762
739
  stream = Stream.drop(stream, options.startLine - 1)
@@ -907,17 +884,23 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(
907
884
  cwd,
908
885
  stdin: "ignore",
909
886
  })
910
- const { id, running } = addJob(yield* startCommand(cmd))
887
+ const entry = yield* addBashTask(
888
+ options.command,
889
+ yield* startCommand(cmd),
890
+ )
911
891
  if (options.background !== true) {
912
- const exit = yield* awaitCommand(running, Duration.millis(timeoutMs))
892
+ const exit = yield* awaitCommand(
893
+ entry.command,
894
+ Duration.millis(timeoutMs),
895
+ )
913
896
  if (Option.isSome(exit)) {
914
897
  // A finished command is reported here, so it is never pushed.
915
898
  const exitCode = yield* exit.value
916
- const job = reportJob(id, running)
917
- if (exitCode === 0) return job
899
+ const task = reportBash(entry)
900
+ if (exitCode === 0) return task
918
901
  return yield* Effect.die(
919
902
  new Error(
920
- `Command failed with exit code ${exitCode}: ${job.output}`,
903
+ `Command failed with exit code ${exitCode}: ${task.output}`,
921
904
  ),
922
905
  )
923
906
  }
@@ -925,38 +908,93 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(
925
908
  // Snapshot the task before yielding to the watcher: the command can
926
909
  // finish while it is being handed over, and its final state must
927
910
  // reach the model only once. A finished task is never handed over.
928
- const job = reportJob(id, running)
929
- if (job.status === "running") yield* watchJob(id, running)
930
- return job
911
+ const task = reportBash(entry)
912
+ if (task.status === "running") yield* watchBashTask(entry)
913
+ return task
931
914
  }, Effect.orDie),
932
- jobOutput: Effect.fn("AgentTools.jobOutput")(function* (input: unknown) {
933
- const id = yield* decodeJobOutput(input)
934
- yield* Effect.logInfo(`Calling "jobOutput"`).pipe(
915
+ taskOutput: Effect.fn("AgentTools.taskOutput")(function* (
916
+ input: unknown,
917
+ ) {
918
+ const id = yield* decodeTaskOutput(input)
919
+ yield* Effect.logInfo(`Calling "taskOutput"`).pipe(
935
920
  Effect.annotateLogs({ id }),
936
921
  )
937
- return reportJob(id, yield* findJob(id))
922
+ const entry = yield* findTask(id)
923
+ if (entry.kind === "bash") return reportBash(entry)
924
+ const agentTasks = yield* AgentTaskExecutor
925
+ return yield* agentTasks.taskOutput(id)
938
926
  }),
939
- waitJob: Effect.fn("AgentTools.waitJob")(function* (input: unknown) {
940
- const options = yield* decodeWaitJob(input)
927
+ waitTasks: Effect.fn("AgentTools.waitTasks")(function* (input: unknown) {
928
+ const { ids, timeoutMs: requestedMs } = yield* decodeWaitTasks(input)
941
929
  const maxMs = bashTimeoutMs(yield* CommandLimits)
942
- const timeoutMs = Math.min(options.timeoutMs ?? maxMs, maxMs)
943
- yield* Effect.logInfo(`Calling "waitJob"`).pipe(
944
- Effect.annotateLogs({ id: options.id, timeoutMs }),
930
+ const timeoutMs = Math.min(requestedMs ?? maxMs, maxMs)
931
+ yield* Effect.logInfo(`Calling "waitTasks"`).pipe(
932
+ Effect.annotateLogs({ ids, timeoutMs }),
945
933
  )
946
- const running = yield* findJob(options.id)
947
- // Ending the wait leaves the job running.
948
- yield* Effect.timeoutOption(Fiber.await(running.fiber), timeoutMs)
949
- return reportJob(options.id, running)
934
+ const entries = yield* Effect.forEach(ids, findTask)
935
+ const bashEntries = entries.filter(
936
+ (entry): entry is BashEntry => entry.kind === "bash",
937
+ )
938
+ const agentIds = entries.flatMap((entry) =>
939
+ entry.kind === "agent" ? [entry.id] : [],
940
+ )
941
+ const agentTasks = yield* AgentTaskExecutor
942
+ // Nothing is reported until the batch is ready to return: a script
943
+ // stopped while it waits never receives it, so the tasks that ended
944
+ // first must still be pushed. The bash tasks are waited for first,
945
+ // without reporting them. Then one `AgentTasks.waitTasks` call waits
946
+ // for the agents with the time left and reports them together, so
947
+ // over RPC only its single response can be cut off. The agents keep
948
+ // running meanwhile. Tasks still running at the deadline are
949
+ // returned as running and keep going.
950
+ const startedAt = yield* Clock.currentTimeMillis
951
+ yield* Effect.forEach(
952
+ bashEntries,
953
+ (entry) => Fiber.await(entry.command.fiber),
954
+ { concurrency: "unbounded", discard: true },
955
+ ).pipe(Effect.timeoutOption(timeoutMs))
956
+ const agentResults =
957
+ agentIds.length === 0
958
+ ? []
959
+ : yield* agentTasks.waitTasks(agentIds, {
960
+ timeoutMs: Math.max(
961
+ 0,
962
+ timeoutMs - ((yield* Clock.currentTimeMillis) - startedAt),
963
+ ),
964
+ })
965
+ const ended = new Map(
966
+ [...bashEntries.map(reportBash), ...agentResults].map((task) => [
967
+ task.id,
968
+ task,
969
+ ]),
970
+ )
971
+ return ids.map((id) => ended.get(id)!)
950
972
  }),
951
- stopJob: Effect.fn("AgentTools.stopJob")(function* (input: unknown) {
952
- const id = yield* decodeStopJob(input)
953
- yield* Effect.logInfo(`Calling "stopJob"`).pipe(
973
+ stopTask: Effect.fn("AgentTools.stopTask")(function* (input: unknown) {
974
+ const id = yield* decodeStopTask(input)
975
+ yield* Effect.logInfo(`Calling "stopTask"`).pipe(
954
976
  Effect.annotateLogs({ id }),
955
977
  )
956
- const running = yield* findJob(id)
957
- yield* Fiber.interrupt(running.fiber)
958
- running.reported = true
959
- return jobInfo(id, running)
978
+ const entry = yield* findTask(id)
979
+ if (entry.kind === "agent") {
980
+ const agentTasks = yield* AgentTaskExecutor
981
+ return yield* agentTasks.stopTask(id)
982
+ }
983
+ yield* Fiber.interrupt(entry.command.fiber)
984
+ return reportBash(entry)
985
+ }),
986
+ listTasks: Effect.fn("AgentTools.listTasks")(function* () {
987
+ yield* Effect.logInfo(`Calling "listTasks"`)
988
+ const owner = yield* TaskOwner
989
+ const bashTasks = Array.Array.from(tasks.values()).flatMap((entry) =>
990
+ entry.kind === "bash" && entry.owner === owner
991
+ ? [bashTask(entry)]
992
+ : [],
993
+ )
994
+ const agentTasks = yield* AgentTaskExecutor
995
+ return [...bashTasks, ...(yield* agentTasks.listTasks)].toSorted(
996
+ (a, b) => Number(a.id) - Number(b.id),
997
+ )
960
998
  }),
961
999
  gh: Effect.fn("AgentTools.gh")(function* (args) {
962
1000
  yield* Effect.logInfo(`Calling "gh"`).pipe(
@@ -1144,18 +1182,9 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(
1144
1182
  yield* Effect.logInfo(`Calling "delegate"`).pipe(
1145
1183
  Effect.annotateLogs({ background }),
1146
1184
  )
1147
- const subagents = yield* SubagentExecutor
1148
- return yield* subagents.delegate({ prompt, background })
1149
- }),
1150
- waitAgents: Effect.fn("AgentTools.waitAgents")(function* (
1151
- input: unknown,
1152
- ) {
1153
- const ids = yield* decodeWaitAgents(input)
1154
- yield* Effect.logInfo(`Calling "waitAgents"`).pipe(
1155
- Effect.annotateLogs({ ids }),
1156
- )
1157
- const subagents = yield* SubagentExecutor
1158
- return yield* subagents.waitAgents(ids)
1185
+ const id = yield* registerAgentTask()
1186
+ const agentTasks = yield* AgentTaskExecutor
1187
+ return yield* agentTasks.delegate({ id, prompt, background })
1159
1188
  }),
1160
1189
  messageAgent: Effect.fn("AgentTools.messageAgent")(function* (
1161
1190
  input: unknown,
@@ -1164,21 +1193,14 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(
1164
1193
  yield* Effect.logInfo(`Calling "messageAgent"`).pipe(
1165
1194
  Effect.annotateLogs({ id: options.id }),
1166
1195
  )
1167
- const subagents = yield* SubagentExecutor
1168
- return yield* subagents.messageAgent(options)
1169
- }),
1170
- stopAgent: Effect.fn("AgentTools.stopAgent")(function* (input: unknown) {
1171
- const id = yield* decodeStopAgent(input)
1172
- yield* Effect.logInfo(`Calling "stopAgent"`).pipe(
1173
- Effect.annotateLogs({ id }),
1174
- )
1175
- const subagents = yield* SubagentExecutor
1176
- return yield* subagents.stopAgent(id)
1177
- }),
1178
- listAgents: Effect.fn("AgentTools.listAgents")(function* () {
1179
- yield* Effect.logInfo(`Calling "listAgents"`)
1180
- const subagents = yield* SubagentExecutor
1181
- return yield* subagents.listAgents
1196
+ const entry = yield* findTask(options.id)
1197
+ if (entry.kind === "bash") {
1198
+ return yield* Effect.fail(
1199
+ `messageAgent only addresses sub-agents, and task ${JSON.stringify(entry.id)} is a bash task. Use taskOutput or stopTask with it instead.`,
1200
+ )
1201
+ }
1202
+ const agentTasks = yield* AgentTaskExecutor
1203
+ return yield* agentTasks.messageAgent(options)
1182
1204
  }),
1183
1205
  taskComplete: Effect.fn("AgentTools.taskComplete")(function* (
1184
1206
  message: unknown,
@@ -1235,34 +1257,25 @@ const decodeDelegate = decodeParams(
1235
1257
  AgentTools.tools.delegate.parametersSchema,
1236
1258
  'delegate requires an options object, for example: delegate({ prompt: "..." }) or delegate({ prompt: "...", background: true }).',
1237
1259
  )
1238
- const decodeWaitAgents = decodeParams(
1239
- AgentTools.tools.waitAgents.parametersSchema,
1240
- 'waitAgents takes an optional array of agent ids, for example: waitAgents(["3", "4"]).',
1241
- )
1242
1260
  const decodeMessageAgent = decodeParams(
1243
1261
  AgentTools.tools.messageAgent.parametersSchema,
1244
1262
  'messageAgent requires an options object, for example: messageAgent({ id: "3", message: "..." }).',
1245
1263
  )
1246
- const decodeStopAgent = decodeParams(
1247
- AgentTools.tools.stopAgent.parametersSchema,
1248
- 'stopAgent requires an agent id, for example: stopAgent("3").',
1264
+ const decodeTaskOutput = decodeParams(
1265
+ AgentTools.tools.taskOutput.parametersSchema,
1266
+ 'taskOutput requires a task id, for example: taskOutput("1").',
1249
1267
  )
1250
-
1251
- const decodeJobOutput = decodeParams(
1252
- AgentTools.tools.jobOutput.parametersSchema,
1253
- 'jobOutput requires a job id, for example: jobOutput("1").',
1268
+ const decodeWaitTasks = decodeParams(
1269
+ AgentTools.tools.waitTasks.parametersSchema,
1270
+ 'waitTasks requires an options object, for example: waitTasks({ ids: ["3", "4"] }) or waitTasks({ ids: ["3"], timeoutMs: 60000 }).',
1254
1271
  )
1255
- /** The caller's `bash` timeout, which also bounds `waitJob`. */
1272
+
1273
+ /** The caller's `bash` timeout, which also bounds `waitTasks`. */
1256
1274
  const bashTimeoutMs = (limits: typeof CommandLimits.Service) =>
1257
1275
  Duration.toMillis(limits.timeout ?? defaultBashTimeout)
1258
-
1259
- const decodeWaitJob = decodeParams(
1260
- AgentTools.tools.waitJob.parametersSchema,
1261
- 'waitJob requires an options object, for example: waitJob({ id: "1" }) or waitJob({ id: "1", timeoutMs: 60000 }).',
1262
- )
1263
- const decodeStopJob = decodeParams(
1264
- AgentTools.tools.stopJob.parametersSchema,
1265
- 'stopJob requires a job id, for example: stopJob("1").',
1276
+ const decodeStopTask = decodeParams(
1277
+ AgentTools.tools.stopTask.parametersSchema,
1278
+ 'stopTask requires a task id, for example: stopTask("1").',
1266
1279
  )
1267
1280
 
1268
1281
  interface RunningCommand {
@@ -1278,24 +1291,68 @@ interface RunningCommand {
1278
1291
  reported: boolean
1279
1292
  }
1280
1293
 
1281
- const jobInfo = (id: string, running: RunningCommand): BashJob => {
1282
- const exit = running.fiber.pollUnsafe()
1283
- const output = running.output()
1284
- if (exit === undefined) return { id, status: "running", output }
1294
+ // Waits up to `timeout` for a command to exit. A caller that is
1295
+ // interrupted first stops the command.
1296
+ const awaitCommand = (
1297
+ command: Omit<RunningCommand, "reported">,
1298
+ timeout: Duration.Duration | undefined,
1299
+ ) => {
1300
+ const awaited = Fiber.await(command.fiber)
1301
+ return (
1302
+ timeout === undefined
1303
+ ? Effect.asSome(awaited)
1304
+ : Effect.timeoutOption(awaited, timeout)
1305
+ ).pipe(Effect.onInterrupt(() => Fiber.interrupt(command.fiber)))
1306
+ }
1307
+
1308
+ interface BashEntry {
1309
+ readonly kind: "bash"
1310
+ readonly id: string
1311
+ readonly owner: string | undefined
1312
+ readonly description: string
1313
+ readonly command: RunningCommand
1314
+ }
1315
+
1316
+ /** The executor only records who owns an agent task; the agent tracks it. */
1317
+ interface AgentEntry {
1318
+ readonly kind: "agent"
1319
+ readonly id: string
1320
+ readonly owner: string | undefined
1321
+ }
1322
+
1323
+ type TaskEntry = BashEntry | AgentEntry
1324
+
1325
+ // A bash task's final state, once returned to the script, is not pushed.
1326
+ const reportBash = (entry: BashEntry): Task => {
1327
+ const task = bashTask(entry)
1328
+ if (task.status !== "running") entry.command.reported = true
1329
+ return task
1330
+ }
1331
+
1332
+ const bashTask = ({ id, description, command }: BashEntry): Task => {
1333
+ const exit = command.fiber.pollUnsafe()
1334
+ const output = command.output()
1335
+ if (exit === undefined) {
1336
+ return { id, kind: "bash", status: "running", description, output }
1337
+ }
1285
1338
  if (Exit.isSuccess(exit)) {
1286
1339
  return {
1287
1340
  id,
1341
+ kind: "bash",
1288
1342
  status: exit.value === 0 ? "completed" : "failed",
1289
- exitCode: exit.value,
1343
+ description,
1290
1344
  output,
1345
+ exitCode: exit.value,
1291
1346
  }
1292
1347
  }
1293
1348
  if (Cause.hasInterruptsOnly(exit.cause)) {
1294
- return { id, status: "stopped", output }
1349
+ return { id, kind: "bash", status: "stopped", description, output }
1295
1350
  }
1296
1351
  return {
1297
1352
  id,
1353
+ kind: "bash",
1298
1354
  status: "failed",
1355
+ description,
1299
1356
  output: `${output}${output === "" ? "" : "\n"}${Cause.pretty(exit.cause)}`,
1300
1357
  }
1301
1358
  }