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
@@ -5,6 +5,7 @@
5
5
  import { parsePatch, patchChunks } from "./ApplyPatch.js";
6
6
  import * as ExaSearch from "./ExaSearch.js";
7
7
  import * as WebToMarkdown from "./WebToMarkdown.js";
8
+ import * as Clock from "effect/Clock";
8
9
  import * as Context from "effect/Context";
9
10
  import * as Duration from "effect/Duration";
10
11
  import * as Effect from "effect/Effect";
@@ -45,101 +46,89 @@ export class DirectoryChanger extends Context.Service()("clanka/AgentTools/Direc
45
46
  export class TaskCompleter extends Context.Service()("clanka/AgentTools/TaskCompleter") {
46
47
  }
47
48
  /**
49
+ * What a task is: a background `bash` command or a sub-agent started with
50
+ * `delegate`.
51
+ *
48
52
  * @since 1.0.0
49
53
  * @category Models
50
54
  */
51
- export const SubagentStatus = Schema.Literals([
52
- "completed",
53
- "running",
54
- "failed",
55
- "cancelled",
56
- ]);
57
- /**
58
- * @since 1.0.0
59
- * @category Models
60
- */
61
- export const SubagentResult = Schema.Struct({
62
- id: Schema.String,
63
- status: SubagentStatus,
64
- output: Schema.optional(Schema.String),
65
- });
55
+ export const TaskKind = Schema.Literals(["bash", "agent"]);
66
56
  /**
67
57
  * @since 1.0.0
68
58
  * @category Models
69
59
  */
70
- export const DelegateResult = Schema.Struct({
71
- ...SubagentResult.fields,
72
- status: Schema.Literals(["completed", "running"]),
73
- });
60
+ export const TaskStatus = Schema.Literals([
61
+ "running",
62
+ "completed",
63
+ "failed",
64
+ "stopped",
65
+ ]);
74
66
  /**
67
+ * A background `bash` command or a sub-agent, as returned by the task
68
+ * functions. Both kinds share one id space per executor.
69
+ *
75
70
  * @since 1.0.0
76
71
  * @category Models
77
72
  */
78
- export const SubagentInfo = Schema.Struct({
79
- id: Schema.String,
80
- status: SubagentStatus,
81
- prompt: Schema.String,
73
+ export const Task = Schema.Struct({
74
+ id: Schema.String.annotate({
75
+ documentation: "The task id, which can be managed with the task tools.",
76
+ }),
77
+ kind: TaskKind,
78
+ status: TaskStatus,
79
+ /** The bash command, or the sub-agent's prompt. */
80
+ description: Schema.String,
81
+ /** Output so far while running; the final output, or the error, once ended. */
82
+ output: Schema.String,
83
+ /** bash only: set when the command exited on its own. */
84
+ exitCode: Schema.optional(Schema.Number),
82
85
  });
83
86
  /**
84
87
  * @since 1.0.0
85
88
  * @category Context
86
89
  */
87
- export class SubagentExecutor extends Context.Service()("clanka/AgentTools/SubagentExecutor") {
90
+ export class AgentTaskExecutor extends Context.Service()("clanka/AgentTools/AgentTaskExecutor") {
88
91
  }
89
92
  /**
90
- * A `Subagents` implementation for contexts that cannot spawn agents.
93
+ * An `AgentTasks` implementation for contexts that cannot spawn agents.
91
94
  *
92
95
  * @since 1.0.0
93
96
  * @category Context
94
97
  */
95
- export const subagentsUnavailable = {
98
+ export const agentTasksUnavailable = {
96
99
  delegate: () => Effect.die(new Error("Sub-agents are not available here")),
97
- waitAgents: () => Effect.fail("Sub-agents are not available here"),
100
+ taskOutput: () => Effect.fail("Sub-agents are not available here"),
101
+ waitTasks: () => Effect.fail("Sub-agents are not available here"),
98
102
  messageAgent: () => Effect.fail("Sub-agents are not available here"),
99
- stopAgent: () => Effect.fail("Sub-agents are not available here"),
100
- listAgents: Effect.succeed([]),
103
+ stopTask: () => Effect.fail("Sub-agents are not available here"),
104
+ listTasks: Effect.succeed([]),
101
105
  };
102
106
  /**
107
+ * The agent running the current script. Tasks are only visible to the agent
108
+ * that started them; scripts without an agent share the `undefined` owner.
109
+ * The executor sets it from `ExecuteOptions.agentId`.
110
+ *
103
111
  * @since 1.0.0
104
112
  * @category Context
105
113
  */
106
- export class ImageAttacher extends Context.Service()("clanka/AgentTools/ImageAttacher") {
114
+ export class TaskOwner extends Context.Reference("clanka/AgentTools/TaskOwner", { defaultValue: () => undefined }) {
107
115
  }
108
116
  /**
109
117
  * @since 1.0.0
110
- * @category Models
111
- */
112
- export const BashJobStatus = Schema.Literals([
113
- "running",
114
- "completed",
115
- "failed",
116
- "stopped",
117
- ]);
118
- /**
119
- * A `bash` command and its state: the task that `bash`, `jobOutput`,
120
- * `waitJob` and `stopJob` return. `exitCode` is set once the command has
121
- * exited; a non-zero exit is `failed`. A foreground `bash` command that
122
- * fails rejects instead of returning a task.
123
- *
124
- * @since 1.0.0
125
- * @category Models
118
+ * @category Context
126
119
  */
127
- export const BashJob = Schema.Struct({
128
- id: Schema.String,
129
- status: BashJobStatus,
130
- exitCode: Schema.optional(Schema.Number),
131
- output: Schema.String,
132
- });
120
+ export class ImageAttacher extends Context.Service()("clanka/AgentTools/ImageAttacher") {
121
+ }
133
122
  /**
134
- * Receives every background `bash` job as it starts: those started with
123
+ * Receives every background `bash` task as it starts: those started with
135
124
  * `background: true` and those moved to the background at their timeout. A
136
125
  * command that `bash` returns finished is never handed over.
137
- * The executor sets it from `ExecuteOptions.onJob`.
126
+ * The executor sets it from `ExecuteOptions.onTask`.
138
127
  *
139
128
  * @since 1.0.0
140
129
  * @category Context
141
130
  */
142
- export class JobWatcher extends Context.Reference("clanka/AgentTools/JobWatcher", {
131
+ export class TaskWatcher extends Context.Reference("clanka/AgentTools/TaskWatcher", {
143
132
  defaultValue: () => () => Effect.void,
144
133
  }) {
145
134
  }
@@ -178,19 +167,19 @@ export class CommandLimits extends Context.Reference("clanka/AgentTools/CommandL
178
167
  * @category Toolkit
179
168
  */
180
169
  export const makeBashTool = (timeout) => Tool.make("bash", {
181
- description: '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.',
170
+ description: "Run a bash command and return a task.",
182
171
  parameters: Schema.Struct({
183
172
  command: Schema.String,
184
173
  timeoutMs: Schema.optional(Schema.Finite).annotate({
185
- documentation: `How long to wait in ms before moving the command to the background (default and max: ${Duration.toMillis(timeout)})`,
174
+ documentation: `How long to wait in ms before moving the task to the background (default and max: ${Duration.toMillis(timeout)})`,
186
175
  }),
187
176
  background: Schema.optional(Schema.Boolean).annotate({
188
- documentation: 'Start the command in the background and return it as "running" without waiting',
177
+ documentation: "Start the command in the background. Defaults to false which always returns 'completed' tasks.",
189
178
  }),
190
179
  }).annotate({
191
180
  identifier: "command",
192
181
  }),
193
- success: BashJob,
182
+ success: Task,
194
183
  dependencies: [CurrentDirectory],
195
184
  });
196
185
  const globNamesDirectory = (glob) => glob
@@ -201,18 +190,18 @@ const globNamesDirectory = (glob) => glob
201
190
  * @since 1.0.0
202
191
  * @category Context
203
192
  */
204
- export const makeContextNoop = (cwd) => SubagentExecutor.context(subagentsUnavailable).pipe(Context.add(CurrentDirectory, cwd ?? "/"), Context.add(DirectoryChanger, () => Effect.die("Not implemented")), Context.add(TaskCompleter, () => Effect.void), Context.add(ImageAttacher, () => Effect.void));
193
+ export const makeContextNoop = (cwd) => AgentTaskExecutor.context(agentTasksUnavailable).pipe(Context.add(CurrentDirectory, cwd ?? "/"), Context.add(DirectoryChanger, () => Effect.die("Not implemented")), Context.add(TaskCompleter, () => Effect.void), Context.add(ImageAttacher, () => Effect.void));
205
194
  /**
206
195
  * @since 1.0.0
207
196
  * @category Toolkit
208
197
  */
209
198
  export const AgentTools = Toolkit.make(Tool.make("changeDirectory", {
210
- description: "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.",
199
+ description: "Change the executor's working directory to an existing directory and return its absolute path. The change persists across your scripts.",
211
200
  parameters: Schema.String.annotate({ identifier: "directory" }),
212
201
  success: Schema.String,
213
202
  dependencies: [DirectoryChanger],
214
203
  }), Tool.make("readFile", {
215
- description: "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.",
204
+ description: "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.",
216
205
  parameters: Schema.Struct({
217
206
  path: Schema.String,
218
207
  startLine: Schema.optional(Schema.Number),
@@ -240,44 +229,22 @@ export const AgentTools = Toolkit.make(Tool.make("changeDirectory", {
240
229
  success: Schema.String,
241
230
  dependencies: [CurrentDirectory],
242
231
  }), Tool.make("delegate", {
243
- description: '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.',
232
+ description: "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.",
244
233
  parameters: Schema.Struct({
245
234
  prompt: Schema.String,
246
235
  background: Schema.optional(Schema.Boolean),
247
236
  }),
248
- success: DelegateResult,
249
- failure: Schema.String,
250
- dependencies: [SubagentExecutor],
251
- }), Tool.make("waitAgents", {
252
- description: '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.',
253
- parameters: Schema.UndefinedOr(Schema.Array(Schema.String)).annotate({
254
- identifier: "ids",
255
- }),
256
- success: Schema.Array(SubagentResult),
237
+ success: Task,
257
238
  failure: Schema.String,
258
- dependencies: [SubagentExecutor],
239
+ dependencies: [AgentTaskExecutor],
259
240
  }), Tool.make("messageAgent", {
260
- description: "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.",
241
+ description: "Send a message to one of your sub-agents.",
261
242
  parameters: Schema.Struct({
262
243
  id: Schema.String,
263
244
  message: Schema.String,
264
245
  }),
265
- success: SubagentResult,
266
- failure: Schema.String,
267
- dependencies: [SubagentExecutor],
268
- }), Tool.make("stopAgent", {
269
- description: "Stop one of your sub-agents and every agent it started. Returns its final status.",
270
- parameters: Schema.String.annotate({
271
- identifier: "id",
272
- }),
273
- success: SubagentResult,
274
246
  failure: Schema.String,
275
- dependencies: [SubagentExecutor],
276
- }), Tool.make("listAgents", {
277
- description: "List the sub-agents you have started in this run, with their status.",
278
- parameters: Schema.Void,
279
- success: Schema.Array(SubagentInfo),
280
- dependencies: [SubagentExecutor],
247
+ dependencies: [AgentTaskExecutor],
281
248
  }), Tool.make("glob", {
282
249
  description: "Find files matching a glob pattern.",
283
250
  parameters: Schema.String.annotate({
@@ -292,30 +259,38 @@ export const AgentTools = Toolkit.make(Tool.make("changeDirectory", {
292
259
  }),
293
260
  success: Schema.String,
294
261
  dependencies: [CurrentDirectory],
295
- }), makeBashTool(defaultBashTimeout), Tool.make("jobOutput", {
296
- description: "Return the status and output so far of a background bash job.",
262
+ }), makeBashTool(defaultBashTimeout), Tool.make("taskOutput", {
263
+ description: "Return the status and output so far of one of your tasks: a background bash command or a sub-agent.",
297
264
  parameters: Schema.String.annotate({
298
265
  identifier: "id",
299
266
  }),
300
- success: BashJob,
267
+ success: Task,
301
268
  failure: Schema.String,
302
- }), Tool.make("waitJob", {
303
- description: '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.',
269
+ dependencies: [AgentTaskExecutor],
270
+ }), Tool.make("waitTasks", {
271
+ description: "Wait until the given tasks have ended and return them, in the order given.",
304
272
  parameters: Schema.Struct({
305
- id: Schema.String,
273
+ ids: Schema.Array(Schema.String),
306
274
  timeoutMs: Schema.optional(Schema.Finite).annotate({
307
- documentation: "How long to wait in ms (default and max: the bash timeout)",
275
+ documentation: "How long to wait in ms (default and max: the bash command timeout)",
308
276
  }),
309
277
  }),
310
- success: BashJob,
278
+ success: Schema.Array(Task),
311
279
  failure: Schema.String,
312
- }), Tool.make("stopJob", {
313
- description: "Stop a background bash job and return its final status and output.",
280
+ dependencies: [AgentTaskExecutor],
281
+ }), Tool.make("stopTask", {
282
+ description: "Stop one of your tasks.",
314
283
  parameters: Schema.String.annotate({
315
284
  identifier: "id",
316
285
  }),
317
- success: BashJob,
286
+ success: Task,
318
287
  failure: Schema.String,
288
+ dependencies: [AgentTaskExecutor],
289
+ }), Tool.make("listTasks", {
290
+ description: "List the tasks you have started, with their status.",
291
+ parameters: Schema.Void,
292
+ success: Schema.Array(Task),
293
+ dependencies: [AgentTaskExecutor],
319
294
  }), Tool.make("applyPatch", {
320
295
  description: "Add, update or remove multiple files with a git diff / unified diff / wrapped patch.",
321
296
  parameters: Schema.String.annotate({
@@ -409,50 +384,52 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(Effect.gen(f
409
384
  const fiber = yield* spawner.spawn(command).pipe(Effect.flatMap((handle) => handle.all.pipe(Stream.decodeText, Stream.runForEach((chunk) => Effect.sync(() => output.append(chunk))), Effect.andThen(handle.exitCode))), Effect.scoped, Effect.forkIn(commandScope));
410
385
  return { fiber, output: output.render };
411
386
  });
412
- // Every `bash` command is a job, so it can be addressed by id. Only
413
- // the ones still running when `bash` returns go to the `JobWatcher`.
414
- const jobs = new Map();
415
- let nextJobId = 1;
416
- const addJob = (command) => {
417
- const id = String(nextJobId++);
418
- const running = { ...command, reported: false };
419
- jobs.set(id, running);
420
- return { id, running };
421
- };
422
- const watchJob = Effect.fnUntraced(function* (id, running) {
423
- const watch = yield* JobWatcher;
387
+ // Every task started on this executor, bash and agent alike, so both
388
+ // kinds share one id space. Each is only visible to the agent that
389
+ // started it.
390
+ const tasks = new Map();
391
+ let nextTaskId = 1;
392
+ const registerAgentTask = Effect.fnUntraced(function* () {
393
+ const id = String(nextTaskId++);
394
+ tasks.set(id, { kind: "agent", id, owner: yield* TaskOwner });
395
+ return id;
396
+ });
397
+ // Every `bash` command is a task, so any of them can be addressed by
398
+ // id. Only the ones still running when `bash` returns go to the
399
+ // `TaskWatcher`.
400
+ const addBashTask = Effect.fnUntraced(function* (description, command) {
401
+ const entry = {
402
+ kind: "bash",
403
+ id: String(nextTaskId++),
404
+ owner: yield* TaskOwner,
405
+ description,
406
+ command: { ...command, reported: false },
407
+ };
408
+ tasks.set(entry.id, entry);
409
+ return entry;
410
+ });
411
+ const watchBashTask = Effect.fnUntraced(function* (entry) {
412
+ const watch = yield* TaskWatcher;
424
413
  yield* watch({
425
- id,
426
- await: Fiber.await(running.fiber).pipe(Effect.map(() => jobInfo(id, running))),
414
+ id: entry.id,
415
+ kind: "bash",
416
+ await: Fiber.await(entry.command.fiber).pipe(Effect.map(() => bashTask(entry))),
427
417
  claim: Effect.sync(() => {
428
- if (running.reported)
418
+ if (entry.command.reported)
429
419
  return false;
430
- running.reported = true;
420
+ entry.command.reported = true;
431
421
  return true;
432
422
  }),
433
423
  });
434
424
  });
435
- const findJob = (id) => {
436
- const running = jobs.get(id);
437
- return running === undefined
438
- ? Effect.fail(`No background job with id "${id}"`)
439
- : Effect.succeed(running);
440
- };
441
- // The final state of a job the model has been given is not pushed.
442
- const reportJob = (id, running) => {
443
- const job = jobInfo(id, running);
444
- if (job.status !== "running")
445
- running.reported = true;
446
- return job;
447
- };
448
- // Waits up to `timeout` for a command to exit. A caller that is
449
- // interrupted first stops the command.
450
- const awaitCommand = (running, timeout) => {
451
- const awaited = Fiber.await(running.fiber);
452
- return (timeout === undefined
453
- ? Effect.asSome(awaited)
454
- : Effect.timeoutOption(awaited, timeout)).pipe(Effect.onInterrupt(() => Fiber.interrupt(running.fiber)));
455
- };
425
+ const findTask = Effect.fnUntraced(function* (id) {
426
+ const owner = yield* TaskOwner;
427
+ const entry = tasks.get(id);
428
+ if (entry === undefined || entry.owner !== owner) {
429
+ return yield* Effect.fail(`No task with id ${JSON.stringify(id)}. You can only address tasks you started; call listTasks() to see them.`);
430
+ }
431
+ return entry;
432
+ });
456
433
  /**
457
434
  * Image branch of `readFile`: the bytes go to the `ImageAttacher` for
458
435
  * the next model turn and the script only sees a marker.
@@ -490,6 +467,13 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(Effect.gen(f
490
467
  if (Option.isSome(imageType)) {
491
468
  return yield* readImage(path, imageType.value, options);
492
469
  }
470
+ if (options.lineNumbers === false &&
471
+ !options.startLine &&
472
+ !options.endLine) {
473
+ // Return the file verbatim, keeping its trailing newline and line
474
+ // endings so the text can be written back unchanged.
475
+ return yield* fs.readFileString(path).pipe(Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(null)), Effect.orDie);
476
+ }
493
477
  let stream = pipe(fs.stream(path), Stream.decodeText, Stream.splitLines);
494
478
  if (options.startLine) {
495
479
  stream = Stream.drop(stream, options.startLine - 1);
@@ -601,48 +585,84 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(Effect.gen(f
601
585
  cwd,
602
586
  stdin: "ignore",
603
587
  });
604
- const { id, running } = addJob(yield* startCommand(cmd));
588
+ const entry = yield* addBashTask(options.command, yield* startCommand(cmd));
605
589
  if (options.background !== true) {
606
- const exit = yield* awaitCommand(running, Duration.millis(timeoutMs));
590
+ const exit = yield* awaitCommand(entry.command, Duration.millis(timeoutMs));
607
591
  if (Option.isSome(exit)) {
608
592
  // A finished command is reported here, so it is never pushed.
609
593
  const exitCode = yield* exit.value;
610
- const job = reportJob(id, running);
594
+ const task = reportBash(entry);
611
595
  if (exitCode === 0)
612
- return job;
613
- return yield* Effect.die(new Error(`Command failed with exit code ${exitCode}: ${job.output}`));
596
+ return task;
597
+ return yield* Effect.die(new Error(`Command failed with exit code ${exitCode}: ${task.output}`));
614
598
  }
615
599
  }
616
600
  // Snapshot the task before yielding to the watcher: the command can
617
601
  // finish while it is being handed over, and its final state must
618
602
  // reach the model only once. A finished task is never handed over.
619
- const job = reportJob(id, running);
620
- if (job.status === "running")
621
- yield* watchJob(id, running);
622
- return job;
603
+ const task = reportBash(entry);
604
+ if (task.status === "running")
605
+ yield* watchBashTask(entry);
606
+ return task;
623
607
  }, Effect.orDie),
624
- jobOutput: Effect.fn("AgentTools.jobOutput")(function* (input) {
625
- const id = yield* decodeJobOutput(input);
626
- yield* Effect.logInfo(`Calling "jobOutput"`).pipe(Effect.annotateLogs({ id }));
627
- return reportJob(id, yield* findJob(id));
608
+ taskOutput: Effect.fn("AgentTools.taskOutput")(function* (input) {
609
+ const id = yield* decodeTaskOutput(input);
610
+ yield* Effect.logInfo(`Calling "taskOutput"`).pipe(Effect.annotateLogs({ id }));
611
+ const entry = yield* findTask(id);
612
+ if (entry.kind === "bash")
613
+ return reportBash(entry);
614
+ const agentTasks = yield* AgentTaskExecutor;
615
+ return yield* agentTasks.taskOutput(id);
628
616
  }),
629
- waitJob: Effect.fn("AgentTools.waitJob")(function* (input) {
630
- const options = yield* decodeWaitJob(input);
617
+ waitTasks: Effect.fn("AgentTools.waitTasks")(function* (input) {
618
+ const { ids, timeoutMs: requestedMs } = yield* decodeWaitTasks(input);
631
619
  const maxMs = bashTimeoutMs(yield* CommandLimits);
632
- const timeoutMs = Math.min(options.timeoutMs ?? maxMs, maxMs);
633
- yield* Effect.logInfo(`Calling "waitJob"`).pipe(Effect.annotateLogs({ id: options.id, timeoutMs }));
634
- const running = yield* findJob(options.id);
635
- // Ending the wait leaves the job running.
636
- yield* Effect.timeoutOption(Fiber.await(running.fiber), timeoutMs);
637
- return reportJob(options.id, running);
620
+ const timeoutMs = Math.min(requestedMs ?? maxMs, maxMs);
621
+ yield* Effect.logInfo(`Calling "waitTasks"`).pipe(Effect.annotateLogs({ ids, timeoutMs }));
622
+ const entries = yield* Effect.forEach(ids, findTask);
623
+ const bashEntries = entries.filter((entry) => entry.kind === "bash");
624
+ const agentIds = entries.flatMap((entry) => entry.kind === "agent" ? [entry.id] : []);
625
+ const agentTasks = yield* AgentTaskExecutor;
626
+ // Nothing is reported until the batch is ready to return: a script
627
+ // stopped while it waits never receives it, so the tasks that ended
628
+ // first must still be pushed. The bash tasks are waited for first,
629
+ // without reporting them. Then one `AgentTasks.waitTasks` call waits
630
+ // for the agents with the time left and reports them together, so
631
+ // over RPC only its single response can be cut off. The agents keep
632
+ // running meanwhile. Tasks still running at the deadline are
633
+ // returned as running and keep going.
634
+ const startedAt = yield* Clock.currentTimeMillis;
635
+ yield* Effect.forEach(bashEntries, (entry) => Fiber.await(entry.command.fiber), { concurrency: "unbounded", discard: true }).pipe(Effect.timeoutOption(timeoutMs));
636
+ const agentResults = agentIds.length === 0
637
+ ? []
638
+ : yield* agentTasks.waitTasks(agentIds, {
639
+ timeoutMs: Math.max(0, timeoutMs - ((yield* Clock.currentTimeMillis) - startedAt)),
640
+ });
641
+ const ended = new Map([...bashEntries.map(reportBash), ...agentResults].map((task) => [
642
+ task.id,
643
+ task,
644
+ ]));
645
+ return ids.map((id) => ended.get(id));
646
+ }),
647
+ stopTask: Effect.fn("AgentTools.stopTask")(function* (input) {
648
+ const id = yield* decodeStopTask(input);
649
+ yield* Effect.logInfo(`Calling "stopTask"`).pipe(Effect.annotateLogs({ id }));
650
+ const entry = yield* findTask(id);
651
+ if (entry.kind === "agent") {
652
+ const agentTasks = yield* AgentTaskExecutor;
653
+ return yield* agentTasks.stopTask(id);
654
+ }
655
+ yield* Fiber.interrupt(entry.command.fiber);
656
+ return reportBash(entry);
638
657
  }),
639
- stopJob: Effect.fn("AgentTools.stopJob")(function* (input) {
640
- const id = yield* decodeStopJob(input);
641
- yield* Effect.logInfo(`Calling "stopJob"`).pipe(Effect.annotateLogs({ id }));
642
- const running = yield* findJob(id);
643
- yield* Fiber.interrupt(running.fiber);
644
- running.reported = true;
645
- return jobInfo(id, running);
658
+ listTasks: Effect.fn("AgentTools.listTasks")(function* () {
659
+ yield* Effect.logInfo(`Calling "listTasks"`);
660
+ const owner = yield* TaskOwner;
661
+ const bashTasks = Array.Array.from(tasks.values()).flatMap((entry) => entry.kind === "bash" && entry.owner === owner
662
+ ? [bashTask(entry)]
663
+ : []);
664
+ const agentTasks = yield* AgentTaskExecutor;
665
+ return [...bashTasks, ...(yield* agentTasks.listTasks)].toSorted((a, b) => Number(a.id) - Number(b.id));
646
666
  }),
647
667
  gh: Effect.fn("AgentTools.gh")(function* (args) {
648
668
  yield* Effect.logInfo(`Calling "gh"`).pipe(Effect.annotateLogs({ args }));
@@ -787,31 +807,19 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(Effect.gen(f
787
807
  delegate: Effect.fn("AgentTools.delegate")(function* (options) {
788
808
  const { prompt, background = false } = yield* decodeDelegate(options);
789
809
  yield* Effect.logInfo(`Calling "delegate"`).pipe(Effect.annotateLogs({ background }));
790
- const subagents = yield* SubagentExecutor;
791
- return yield* subagents.delegate({ prompt, background });
792
- }),
793
- waitAgents: Effect.fn("AgentTools.waitAgents")(function* (input) {
794
- const ids = yield* decodeWaitAgents(input);
795
- yield* Effect.logInfo(`Calling "waitAgents"`).pipe(Effect.annotateLogs({ ids }));
796
- const subagents = yield* SubagentExecutor;
797
- return yield* subagents.waitAgents(ids);
810
+ const id = yield* registerAgentTask();
811
+ const agentTasks = yield* AgentTaskExecutor;
812
+ return yield* agentTasks.delegate({ id, prompt, background });
798
813
  }),
799
814
  messageAgent: Effect.fn("AgentTools.messageAgent")(function* (input) {
800
815
  const options = yield* decodeMessageAgent(input);
801
816
  yield* Effect.logInfo(`Calling "messageAgent"`).pipe(Effect.annotateLogs({ id: options.id }));
802
- const subagents = yield* SubagentExecutor;
803
- return yield* subagents.messageAgent(options);
804
- }),
805
- stopAgent: Effect.fn("AgentTools.stopAgent")(function* (input) {
806
- const id = yield* decodeStopAgent(input);
807
- yield* Effect.logInfo(`Calling "stopAgent"`).pipe(Effect.annotateLogs({ id }));
808
- const subagents = yield* SubagentExecutor;
809
- return yield* subagents.stopAgent(id);
810
- }),
811
- listAgents: Effect.fn("AgentTools.listAgents")(function* () {
812
- yield* Effect.logInfo(`Calling "listAgents"`);
813
- const subagents = yield* SubagentExecutor;
814
- return yield* subagents.listAgents;
817
+ const entry = yield* findTask(options.id);
818
+ if (entry.kind === "bash") {
819
+ return yield* Effect.fail(`messageAgent only addresses sub-agents, and task ${JSON.stringify(entry.id)} is a bash task. Use taskOutput or stopTask with it instead.`);
820
+ }
821
+ const agentTasks = yield* AgentTaskExecutor;
822
+ return yield* agentTasks.messageAgent(options);
815
823
  }),
816
824
  taskComplete: Effect.fn("AgentTools.taskComplete")(function* (message) {
817
825
  if (typeof message !== "string") {
@@ -842,33 +850,51 @@ const decodeParams = (schema, usage) => {
842
850
  return (input) => Effect.mapError(decode(input), () => usage);
843
851
  };
844
852
  const decodeDelegate = decodeParams(AgentTools.tools.delegate.parametersSchema, 'delegate requires an options object, for example: delegate({ prompt: "..." }) or delegate({ prompt: "...", background: true }).');
845
- const decodeWaitAgents = decodeParams(AgentTools.tools.waitAgents.parametersSchema, 'waitAgents takes an optional array of agent ids, for example: waitAgents(["3", "4"]).');
846
853
  const decodeMessageAgent = decodeParams(AgentTools.tools.messageAgent.parametersSchema, 'messageAgent requires an options object, for example: messageAgent({ id: "3", message: "..." }).');
847
- const decodeStopAgent = decodeParams(AgentTools.tools.stopAgent.parametersSchema, 'stopAgent requires an agent id, for example: stopAgent("3").');
848
- const decodeJobOutput = decodeParams(AgentTools.tools.jobOutput.parametersSchema, 'jobOutput requires a job id, for example: jobOutput("1").');
849
- /** The caller's `bash` timeout, which also bounds `waitJob`. */
854
+ const decodeTaskOutput = decodeParams(AgentTools.tools.taskOutput.parametersSchema, 'taskOutput requires a task id, for example: taskOutput("1").');
855
+ const decodeWaitTasks = decodeParams(AgentTools.tools.waitTasks.parametersSchema, 'waitTasks requires an options object, for example: waitTasks({ ids: ["3", "4"] }) or waitTasks({ ids: ["3"], timeoutMs: 60000 }).');
856
+ /** The caller's `bash` timeout, which also bounds `waitTasks`. */
850
857
  const bashTimeoutMs = (limits) => Duration.toMillis(limits.timeout ?? defaultBashTimeout);
851
- const decodeWaitJob = decodeParams(AgentTools.tools.waitJob.parametersSchema, 'waitJob requires an options object, for example: waitJob({ id: "1" }) or waitJob({ id: "1", timeoutMs: 60000 }).');
852
- const decodeStopJob = decodeParams(AgentTools.tools.stopJob.parametersSchema, 'stopJob requires a job id, for example: stopJob("1").');
853
- const jobInfo = (id, running) => {
854
- const exit = running.fiber.pollUnsafe();
855
- const output = running.output();
856
- if (exit === undefined)
857
- return { id, status: "running", output };
858
+ const decodeStopTask = decodeParams(AgentTools.tools.stopTask.parametersSchema, 'stopTask requires a task id, for example: stopTask("1").');
859
+ // Waits up to `timeout` for a command to exit. A caller that is
860
+ // interrupted first stops the command.
861
+ const awaitCommand = (command, timeout) => {
862
+ const awaited = Fiber.await(command.fiber);
863
+ return (timeout === undefined
864
+ ? Effect.asSome(awaited)
865
+ : Effect.timeoutOption(awaited, timeout)).pipe(Effect.onInterrupt(() => Fiber.interrupt(command.fiber)));
866
+ };
867
+ // A bash task's final state, once returned to the script, is not pushed.
868
+ const reportBash = (entry) => {
869
+ const task = bashTask(entry);
870
+ if (task.status !== "running")
871
+ entry.command.reported = true;
872
+ return task;
873
+ };
874
+ const bashTask = ({ id, description, command }) => {
875
+ const exit = command.fiber.pollUnsafe();
876
+ const output = command.output();
877
+ if (exit === undefined) {
878
+ return { id, kind: "bash", status: "running", description, output };
879
+ }
858
880
  if (Exit.isSuccess(exit)) {
859
881
  return {
860
882
  id,
883
+ kind: "bash",
861
884
  status: exit.value === 0 ? "completed" : "failed",
862
- exitCode: exit.value,
885
+ description,
863
886
  output,
887
+ exitCode: exit.value,
864
888
  };
865
889
  }
866
890
  if (Cause.hasInterruptsOnly(exit.cause)) {
867
- return { id, status: "stopped", output };
891
+ return { id, kind: "bash", status: "stopped", description, output };
868
892
  }
869
893
  return {
870
894
  id,
895
+ kind: "bash",
871
896
  status: "failed",
897
+ description,
872
898
  output: `${output}${output === "" ? "" : "\n"}${Cause.pretty(exit.cause)}`,
873
899
  };
874
900
  };