clanka 0.21.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 +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 +218 -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/bin/cli.mjs +308 -289
  32. package/dist/bin/cli.mjs.map +1 -1
  33. package/package.json +1 -1
  34. package/src/Acp.test.ts +31 -10
  35. package/src/Agent.test.ts +5 -4
  36. package/src/Agent.ts +175 -140
  37. package/src/AgentBashJobs.test.ts +70 -38
  38. package/src/AgentCallerConfig.test.ts +39 -7
  39. package/src/AgentExecutor.test.ts +132 -91
  40. package/src/AgentExecutor.ts +120 -105
  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 +331 -288
package/src/Agent.ts CHANGED
@@ -12,17 +12,16 @@ import type * as Path from "effect/Path"
12
12
  import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"
13
13
  import type * as HttpClient from "effect/http/HttpClient"
14
14
  import type {
15
- BackgroundJob,
16
- BashJob,
15
+ AgentTaskExecutor,
17
16
  CurrentDirectory,
18
17
  DirectoryChanger,
19
18
  ExcludableTool,
20
19
  ImageAttacher,
21
20
  ImageAttachment,
22
- SubagentExecutor,
23
- SubagentResult,
24
- SubagentStatus,
21
+ Task,
25
22
  TaskCompleter,
23
+ TaskHandle,
24
+ TaskStatus,
26
25
  } from "./AgentTools.ts"
27
26
  import * as Image from "./Image.ts"
28
27
  import type * as FileSystem from "effect/FileSystem"
@@ -206,7 +205,7 @@ export const makeWith = Effect.fnUntraced(function* <
206
205
  Scope.Scope | AgentExecutor.AgentExecutor | LoopToolServices<LoopTools>
207
206
  > {
208
207
  const executor = yield* AgentExecutor.AgentExecutor
209
- // Background bash jobs are followed here rather than in a run, since they
208
+ // Background bash tasks are followed here rather than in a run, since they
210
209
  // can outlive the run that started them.
211
210
  const agentScope = yield* Effect.scope
212
211
 
@@ -226,7 +225,7 @@ export const makeWith = Effect.fnUntraced(function* <
226
225
  .filter((dts) => dts !== "")
227
226
  .join("\n\n"),
228
227
  offers: (name) => capabilities.tools.includes(name),
229
- jobPushes: capabilities.jobPushes,
228
+ taskPushes: capabilities.taskPushes,
230
229
  skillsCatalog:
231
230
  options.skills === undefined
232
231
  ? AgentSkills.renderCatalog(capabilities.skills)
@@ -242,7 +241,9 @@ export const makeWith = Effect.fnUntraced(function* <
242
241
  ? capabilities.instructions
243
242
  : Option.map(options.instructions, renderInstructions)
244
243
 
245
- let agentCounter = 0
244
+ // Tasks belong to the agent that started them. Each agent has its own
245
+ // owner id, so no agent sees another's tasks on a shared executor.
246
+ const rootTaskOwner = crypto.randomUUID()
246
247
 
247
248
  const outputBuffer = new Map<number, Array<Output>>()
248
249
  let currentOutputAgent: number | null = null
@@ -251,7 +252,10 @@ export const makeWith = Effect.fnUntraced(function* <
251
252
  const environment = MutableRef.make(capabilities.environment)
252
253
 
253
254
  const spawn: (opts: {
255
+ /** Identifies the agent's output; the root agent is 0. */
254
256
  readonly agentId: number
257
+ /** Passed to the executor as `agentId`, so the agent owns its tasks. */
258
+ readonly taskOwner: string
255
259
  readonly prompt: Prompt.Prompt
256
260
  /** AGENTS.md files and skills added after the prompt. */
257
261
  readonly environmentUpdate?: string | undefined
@@ -323,16 +327,16 @@ export const makeWith = Effect.fnUntraced(function* <
323
327
  const prompt = opts.history
324
328
  const mailbox = opts.mailbox
325
329
 
326
- // A job that ends is queued for the model and shown straight away, or at
327
- // the start of the next run when none is running. It neither wakes a
328
- // waiting run nor keeps one alive.
329
- const onJob = (job: BackgroundJob) =>
330
- job.await.pipe(
330
+ // A bash task that ends is queued for the model and shown straight
331
+ // away, or at the start of the next run when none is running. It
332
+ // neither wakes a waiting run nor keeps one alive.
333
+ const onTask = (task: TaskHandle) =>
334
+ task.await.pipe(
331
335
  Effect.flatMap((final) =>
332
336
  Effect.sync(() => {
333
- // `await` only returns once the job has ended.
337
+ // `await` only returns once the task has ended.
334
338
  if (final.status === "running") return
335
- mailbox.jobs.push({ job: final, claim: job.claim })
339
+ mailbox.tasks.push({ task: final, claim: task.claim })
336
340
  const event = new JobComplete({
337
341
  id: final.id,
338
342
  status: final.status,
@@ -396,6 +400,7 @@ export const makeWith = Effect.fnUntraced(function* <
396
400
  if (typeof opts.system === "string") {
397
401
  system += `\n${opts.system}\n`
398
402
  }
403
+ console.log("system:", system)
399
404
 
400
405
  function maybeSend(options: {
401
406
  readonly agentId: number
@@ -455,7 +460,8 @@ export const makeWith = Effect.fnUntraced(function* <
455
460
  })
456
461
  const children = new Map<string, Child>()
457
462
  // Finished turns waiting to be pushed to the model.
458
- const completions: Array<Turn> = []
463
+ const completions: Array<{ readonly child: Child; readonly turn: Turn }> =
464
+ []
459
465
  let wakeUp: (() => void) | undefined
460
466
  const notify = () => {
461
467
  const resume = wakeUp
@@ -468,15 +474,19 @@ export const makeWith = Effect.fnUntraced(function* <
468
474
  Array.Array.from(children.values()).filter(
469
475
  (child) => child.turn.status === "running",
470
476
  )
471
- const hasUndelivered = () => completions.some((turn) => !turn.delivered)
477
+ const hasUndelivered = () => completions.some(({ turn }) => !turn.reported)
472
478
 
473
- const finishTurn = (turn: Turn, exit: Exit.Exit<string, unknown>) =>
479
+ const finishTurn = (
480
+ child: Child,
481
+ turn: Turn,
482
+ exit: Exit.Exit<string, unknown>,
483
+ ) =>
474
484
  Effect.sync(() => {
475
485
  if (Exit.isSuccess(exit)) {
476
486
  turn.status = "completed"
477
487
  turn.output = exit.value
478
488
  } else if (Cause.hasInterruptsOnly(exit.cause)) {
479
- turn.status = "cancelled"
489
+ turn.status = "stopped"
480
490
  } else {
481
491
  turn.status = "failed"
482
492
  turn.output = causeMessage(exit.cause)
@@ -484,13 +494,14 @@ export const makeWith = Effect.fnUntraced(function* <
484
494
  Queue.offerUnsafe(
485
495
  output,
486
496
  new SubagentComplete({
487
- id: turn.agentId,
497
+ id: child.id,
488
498
  summary: turn.output ?? "",
489
- status: turn.status,
499
+ // The output event keeps its own name for a stopped agent.
500
+ status: turn.status === "stopped" ? "cancelled" : turn.status,
490
501
  }),
491
502
  )
492
- if (!turn.delivered) {
493
- completions.push(turn)
503
+ if (!turn.reported) {
504
+ completions.push({ child, turn })
494
505
  }
495
506
  Deferred.doneUnsafe(turn.done, Effect.void)
496
507
  notify()
@@ -512,6 +523,7 @@ export const makeWith = Effect.fnUntraced(function* <
512
523
  const display = opts.display && !options.background
513
524
  const stream = spawn({
514
525
  agentId: child.id,
526
+ taskOwner: child.taskOwner,
515
527
  prompt: Prompt.make(options.prompt),
516
528
  environmentUpdate: options.environmentUpdate,
517
529
  system: opts.system,
@@ -564,18 +576,25 @@ export const makeWith = Effect.fnUntraced(function* <
564
576
  ),
565
577
  )
566
578
  }).pipe(
567
- Effect.onExit((exit) => finishTurn(turn, exit)),
579
+ Effect.onExit((exit) => finishTurn(child, turn, exit)),
568
580
  provideSubagentModel,
569
581
  Effect.provideContext(runContext),
570
582
  Effect.forkIn(runScope, { startImmediately: true }),
571
583
  )
572
584
  })
573
585
 
574
- // Leaves `output` out when unset, so the result stays JSON for RPC.
575
- const childResult = ({ id, turn }: Child): SubagentResult =>
576
- turn.output === undefined
577
- ? { id: String(id), status: turn.status }
578
- : { id: String(id), status: turn.status, output: turn.output }
586
+ const childTask = ({ id, prompt, turn }: Child): Task => ({
587
+ id: String(id),
588
+ kind: "agent",
589
+ status: turn.status,
590
+ description: prompt,
591
+ output: turn.output ?? "",
592
+ })
593
+ // A final status returned to the script is not pushed as well.
594
+ const reportChild = (child: Child): Task => {
595
+ if (child.turn.status !== "running") child.turn.reported = true
596
+ return childTask(child)
597
+ }
579
598
 
580
599
  const lookupChild = (id: string) =>
581
600
  Effect.suspend(() => {
@@ -583,26 +602,26 @@ export const makeWith = Effect.fnUntraced(function* <
583
602
  return child
584
603
  ? Effect.succeed(child)
585
604
  : Effect.fail(
586
- `Unknown agent id ${JSON.stringify(id)}. You can only address agents you started; call listAgents() to see them.`,
605
+ `No task with id ${JSON.stringify(id)}. You can only address tasks you started; call listTasks() to see them.`,
587
606
  )
588
607
  })
589
608
 
590
- const subagents: AgentExecutor.ExecuteSubagents = {
609
+ const agentTasks: AgentExecutor.ExecuteAgentTasks = {
591
610
  delegate: Effect.fnUntraced(function* ({
611
+ id,
592
612
  prompt,
593
613
  background,
594
614
  environment,
595
615
  }) {
596
- const agentId = agentCounter++
597
616
  const child: Child = {
598
- id: agentId,
617
+ id: Number(id),
618
+ taskOwner: crypto.randomUUID(),
599
619
  prompt,
600
620
  history: MutableRef.make(Prompt.empty),
601
621
  environment: MutableRef.make(environment.environment),
602
622
  mailbox: makeMailbox(),
603
- turn: makeTurn(agentId, background),
623
+ turn: makeTurn(background),
604
624
  }
605
- const id = String(child.id)
606
625
  children.set(id, child)
607
626
  const turn = child.turn
608
627
  yield* startTurn({
@@ -616,7 +635,7 @@ ${prompt}`,
616
635
  background,
617
636
  })
618
637
  if (background) {
619
- return { id, status: "running" }
638
+ return childTask(child)
620
639
  }
621
640
  // Foreground: a failure crashes the script, as before. Interrupting
622
641
  // the script stops the agent.
@@ -630,57 +649,52 @@ ${prompt}`,
630
649
  ),
631
650
  )
632
651
  }
633
- return { id, status: "completed", output: turn.output ?? "" }
652
+ return childTask(child)
634
653
  }),
635
- waitAgents: Effect.fnUntraced(function* (ids) {
636
- const targets =
637
- ids === undefined
638
- ? Array.Array.from(children.values())
639
- : yield* Effect.forEach(ids, lookupChild)
654
+ taskOutput: (id) => Effect.map(lookupChild(id), reportChild),
655
+ waitTasks: Effect.fnUntraced(function* (ids, { timeoutMs }) {
656
+ const targets = yield* Effect.forEach(ids, lookupChild)
640
657
  // A turn started by messageAgent while waiting is waited for too.
641
- while (true) {
642
- const running = targets.find(
643
- (child) => child.turn.status === "running",
644
- )
645
- if (!running) break
646
- yield* Deferred.await(running.turn.done)
647
- }
648
- return targets.map((child) => {
649
- child.turn.delivered = true
650
- return childResult(child)
651
- })
658
+ // Agents still running at the deadline keep going.
659
+ yield* Effect.gen(function* () {
660
+ while (true) {
661
+ const running = targets.find(
662
+ (child) => child.turn.status === "running",
663
+ )
664
+ if (!running) break
665
+ yield* Deferred.await(running.turn.done)
666
+ }
667
+ }).pipe(Effect.timeoutOption(timeoutMs))
668
+ // Reported together: only the agents that ended count as reported.
669
+ return targets.map(reportChild)
652
670
  }),
653
671
  messageAgent: Effect.fnUntraced(function* ({ id, message }) {
654
672
  const child = yield* lookupChild(id)
655
673
  if (child.turn.status === "running") {
656
674
  child.mailbox.messages.add({ message, resume: () => {} })
657
675
  child.mailbox.notify()
658
- return childResult(child)
676
+ return childTask(child)
659
677
  }
660
- child.turn = makeTurn(child.id, true)
678
+ child.turn = makeTurn(true)
661
679
  yield* startTurn({
662
680
  child,
663
681
  prompt: message,
664
682
  label: message,
665
683
  background: true,
666
684
  })
667
- return childResult(child)
685
+ return childTask(child)
668
686
  }),
669
- stopAgent: Effect.fnUntraced(function* (id) {
687
+ stopTask: Effect.fnUntraced(function* (id) {
670
688
  const child = yield* lookupChild(id)
671
689
  const turn = child.turn
672
- turn.delivered = true
690
+ turn.reported = true
673
691
  if (turn.status === "running") {
674
692
  yield* Fiber.interrupt(turn.fiber!)
675
693
  }
676
- return childResult(child)
694
+ return childTask(child)
677
695
  }),
678
- listAgents: Effect.sync(() =>
679
- Array.Array.from(children.values(), (child) => ({
680
- id: String(child.id),
681
- status: child.turn.status,
682
- prompt: child.prompt,
683
- })),
696
+ listTasks: Effect.sync(() =>
697
+ Array.Array.from(children.values(), childTask),
684
698
  ),
685
699
  }
686
700
 
@@ -688,9 +702,10 @@ ${prompt}`,
688
702
  Effect.suspend(() => {
689
703
  const running = runningChildren()
690
704
  if (running.length > 0) {
691
- const ids = running.map((child) => JSON.stringify(String(child.id)))
705
+ const ids = running.map((child) => String(child.id))
706
+ const quoted = ids.map((id) => JSON.stringify(id)).join(", ")
692
707
  return Effect.fail(
693
- `taskComplete was rejected: sub-agents ${ids.join(", ")} are still running. Call waitAgents() to wait for them, or stopAgent(id) to stop them, before calling taskComplete.`,
708
+ `taskComplete was rejected: sub-agents ${quoted} are still running. Call waitTasks({ ids: ${JSON.stringify(ids)} }) to wait for them, or stopTask(id) to stop them, before calling taskComplete.`,
694
709
  )
695
710
  }
696
711
  finalSummary = Option.some(summary)
@@ -846,10 +861,11 @@ ${prompt}`,
846
861
  Effect.sync(() => {
847
862
  MutableRef.set(opts.environment, environment)
848
863
  }),
849
- subagents,
864
+ agentId: opts.taskOwner,
865
+ agentTasks,
850
866
  onTaskComplete,
851
867
  onImage,
852
- onJob,
868
+ onTask,
853
869
  loopTools: scriptLoopTools,
854
870
  }),
855
871
  Stream.mkString,
@@ -937,40 +953,29 @@ ${prompt}`,
937
953
  mailbox.messages.clear()
938
954
  }
939
955
 
940
- // Completion pushes from background sub-agents. These have their own
941
- // queue: the steering path above cuts the model stream short.
942
- if (completions.length > 0) {
943
- const pushes = completions.splice(0).filter((turn) => {
944
- if (turn.delivered) return false
945
- turn.delivered = true
946
- return true
947
- })
948
- if (pushes.length > 0) {
949
- appendHistory(
950
- Prompt.make(
951
- pushes.map((turn) => ({
952
- role: "user" as const,
953
- content: `<subagent id="${turn.agentId}" status="${turn.status}">
954
- ${Compaction.capOutput(turn.output ?? "").output}
955
- </subagent>`,
956
- })),
957
- ),
958
- )
956
+ // Ended tasks not reported otherwise: background sub-agents of this
957
+ // run and bash tasks of this agent. These have their own queue: the
958
+ // steering path above cuts the model stream short.
959
+ if (completions.length > 0 || mailbox.tasks.length > 0) {
960
+ const pushes: Array<Task> = []
961
+ for (const { child, turn } of completions.splice(0)) {
962
+ if (turn.reported) continue
963
+ turn.reported = true
964
+ pushes.push({
965
+ ...childTask(child),
966
+ status: turn.status,
967
+ output: turn.output ?? "",
968
+ })
959
969
  }
960
- }
961
-
962
- // Background bash jobs that ended and were not reported otherwise.
963
- if (mailbox.jobs.length > 0) {
964
- const pushes: Array<BashJob> = []
965
- for (const { job, claim } of mailbox.jobs.splice(0)) {
966
- if (yield* claim) pushes.push(job)
970
+ for (const { task, claim } of mailbox.tasks.splice(0)) {
971
+ if (yield* claim) pushes.push(task)
967
972
  }
968
973
  if (pushes.length > 0) {
969
974
  appendHistory(
970
975
  Prompt.make(
971
- pushes.map((job) => ({
976
+ pushes.map((task) => ({
972
977
  role: "user" as const,
973
- content: jobMessage(job),
978
+ content: taskMessage(task),
974
979
  })),
975
980
  ),
976
981
  )
@@ -1302,7 +1307,8 @@ ${Compaction.capOutput(turn.output ?? "").output}
1302
1307
  environment,
1303
1308
  send: (options) =>
1304
1309
  spawn({
1305
- agentId: agentCounter++,
1310
+ agentId: 0,
1311
+ taskOwner: rootTaskOwner,
1306
1312
  prompt: Prompt.make(options.prompt),
1307
1313
  system: options.system,
1308
1314
  history,
@@ -1345,11 +1351,11 @@ interface Mailbox {
1345
1351
  /** Wakes the agent's run if it is waiting for activity. */
1346
1352
  notify: () => void
1347
1353
  /**
1348
- * Background bash jobs that ended. Each one is pushed to the model before
1354
+ * Background bash tasks that ended. Each one is pushed to the model before
1349
1355
  * its next call, unless `claim` finds it was already reported.
1350
1356
  */
1351
- readonly jobs: Array<{
1352
- readonly job: BashJob
1357
+ readonly tasks: Array<{
1358
+ readonly task: Task
1353
1359
  readonly claim: Effect.Effect<boolean>
1354
1360
  }>
1355
1361
  /** Emits output on the agent's current run. Unset between runs. */
@@ -1361,21 +1367,24 @@ interface Mailbox {
1361
1367
  const makeMailbox = (): Mailbox => ({
1362
1368
  messages: new Set(),
1363
1369
  notify: () => {},
1364
- jobs: [],
1370
+ tasks: [],
1365
1371
  emit: undefined,
1366
1372
  events: [],
1367
1373
  })
1368
1374
 
1369
- const jobMessage = (job: BashJob): string => {
1375
+ const taskMessage = (task: Task): string => {
1370
1376
  const exitCode =
1371
- job.exitCode === undefined ? "" : ` exitCode="${job.exitCode}"`
1372
- return `<job id="${job.id}" status="${job.status}"${exitCode}>
1373
- ${Compaction.capOutput(job.output).output}
1374
- </job>`
1377
+ task.exitCode === undefined ? "" : ` exitCode="${task.exitCode}"`
1378
+ return `<task id="${task.id}" kind="${task.kind}" status="${task.status}"${exitCode}>
1379
+ ${Compaction.capOutput(task.output).output}
1380
+ </task>`
1375
1381
  }
1376
1382
 
1377
1383
  interface Child {
1384
+ /** The task id, as a number for output events. */
1378
1385
  readonly id: number
1386
+ /** The agent's own owner id for the tasks it starts. */
1387
+ readonly taskOwner: string
1379
1388
  readonly prompt: string
1380
1389
  /** Kept for the whole run so `messageAgent` can resume the agent. */
1381
1390
  readonly history: MutableRef.MutableRef<Prompt.Prompt>
@@ -1387,21 +1396,22 @@ interface Child {
1387
1396
  }
1388
1397
 
1389
1398
  interface Turn {
1390
- readonly agentId: number
1391
- status: SubagentStatus
1399
+ status: TaskStatus
1392
1400
  output: string | undefined
1393
- /** Whether the model has seen this result. Undelivered results are pushed. */
1394
- delivered: boolean
1401
+ /**
1402
+ * Whether the model has seen this result, through a push or a task
1403
+ * function. Unreported results are pushed.
1404
+ */
1405
+ reported: boolean
1395
1406
  readonly done: Deferred.Deferred<void>
1396
1407
  fiber: Fiber.Fiber<string, AiError.AiError | RetriesExhausted> | undefined
1397
1408
  }
1398
1409
 
1399
- const makeTurn = (agentId: number, background: boolean): Turn => ({
1400
- agentId,
1410
+ const makeTurn = (background: boolean): Turn => ({
1401
1411
  status: "running",
1402
1412
  output: undefined,
1403
1413
  // Foreground results go straight back to the script.
1404
- delivered: !background,
1414
+ reported: !background,
1405
1415
  done: Deferred.makeUnsafe(),
1406
1416
  fiber: undefined,
1407
1417
  })
@@ -1451,14 +1461,17 @@ const isEnvironmentUpdate = (message: Prompt.Message): boolean =>
1451
1461
 
1452
1462
  /**
1453
1463
  * Whether a user message was added by the agent rather than typed: an
1454
- * `<environment-update>` or a `<subagent>` result. Surfaces that replay
1455
- * history (ACP) skip them.
1464
+ * `<environment-update>` or a `<task>` result, or the `<subagent>` and `<job>`
1465
+ * results of earlier versions. Surfaces that replay history (ACP) skip them.
1456
1466
  *
1457
1467
  * @since 1.0.0
1458
1468
  * @category Models
1459
1469
  */
1460
1470
  export const isInjectedMessage = (message: Prompt.Message): boolean =>
1461
- isEnvironmentUpdate(message) || startsWith(message, "<subagent ")
1471
+ isEnvironmentUpdate(message) ||
1472
+ startsWith(message, "<task ") ||
1473
+ startsWith(message, "<subagent ") ||
1474
+ startsWith(message, "<job ")
1462
1475
 
1463
1476
  const renderInstructions = (content: string) => `# Project instructions
1464
1477
 
@@ -1484,12 +1497,50 @@ interface PromptTools {
1484
1497
  readonly skillsCatalog: Option.Option<string>
1485
1498
  /** The MCP servers section, or `""` without servers. */
1486
1499
  readonly mcp: string
1487
- /** Whether finished background bash jobs are pushed to the model. */
1488
- readonly jobPushes: boolean
1500
+ /** Whether finished background bash tasks are pushed to the model. */
1501
+ readonly taskPushes: boolean
1489
1502
  }
1490
1503
 
1491
1504
  const when = (condition: boolean, text: string) => (condition ? text : "")
1492
1505
 
1506
+ // The task functions the executor offers, and how ended tasks reach the
1507
+ // model. Only offered functions are named.
1508
+ const taskInstructions = (tools: PromptTools): string => {
1509
+ const bash = tools.offers("bash")
1510
+ const delegate = tools.offers("delegate")
1511
+ if (!bash && !delegate) return ""
1512
+ const functions = (
1513
+ [
1514
+ ["taskOutput", `"taskOutput" reads one`],
1515
+ [
1516
+ "waitTasks",
1517
+ `"waitTasks" waits for a list of them and returns any still running at its timeout as "running"`,
1518
+ ],
1519
+ ["stopTask", `"stopTask" stops one`],
1520
+ ["listTasks", `"listTasks" lists yours`],
1521
+ ] as const
1522
+ )
1523
+ .filter(([name]) => tools.offers(name))
1524
+ .map(([, text]) => text)
1525
+ const kinds =
1526
+ bash && delegate
1527
+ ? "Background commands and sub-agents are"
1528
+ : bash
1529
+ ? "Background commands are"
1530
+ : "Sub-agents are"
1531
+ const uses =
1532
+ functions.length === 0
1533
+ ? ""
1534
+ : ` ${functions.length === 1 ? functions[0]! : `${functions.slice(0, -1).join(", ")} and ${functions.at(-1)!}`}.`
1535
+ const pushes = tools.taskPushes
1536
+ ? ` When a task ends, its status and output are sent to you as a \`<task id="..." kind="..." status="...">\` message, unless a task function already gave you its final status, so you do not need to poll.`
1537
+ : bash && tools.offers("taskOutput")
1538
+ ? ` Background commands are not sent to you when they end: check them with "taskOutput".`
1539
+ : ""
1540
+ return `
1541
+ - ${kinds} tasks with ids.${uses}${pushes}`
1542
+ }
1543
+
1493
1544
  const generateSystemTools = (
1494
1545
  tools: PromptTools,
1495
1546
  conversationMode: boolean,
@@ -1514,33 +1565,17 @@ const generateSystemTools = (
1514
1565
  )}${when(
1515
1566
  tools.offers("bash"),
1516
1567
  `
1517
- - Avoid passing scripts into the "bash" function, and instead write javascript.
1518
- - Pass \`background: true\` to "bash" for commands that keep running, such as dev servers or watchers. A command still running at its timeout is moved to the background instead of being stopped. Use "jobOutput" and "stopJob" with the returned job id.${when(
1519
- tools.offers("waitJob"),
1520
- ` "bash" returns a task, and rejects when a command that has not been moved to the background fails. Use "waitJob" to wait for a running task; it returns the task as "running" if its timeout passes first. A background task that fails is returned with status "failed" and its \`exitCode\`.`,
1521
- )}${when(
1522
- tools.jobPushes,
1523
- ` When a job ends, its status and output are sent to you as a \`<job id="..." status="..." exitCode="...">\` message, unless "jobOutput" or "stopJob" already gave you its final status. You do not need to poll jobs with "jobOutput" to find out when they end.`,
1524
- )}`,
1568
+ - Avoid passing scripts into the "bash" function, and instead write javascript.`,
1525
1569
  )}
1526
1570
  - Variables are not shared between executions.
1527
1571
  - Do not use \`require\`, \`import\`, \`process\`, or any other Node.js apis.${when(
1528
1572
  tools.offers("delegate"),
1529
1573
  `
1530
- - "delegate" runs a sub-agent and waits for it. Pass \`background: true\` to keep working while it runs: its result is sent to you later as a \`<subagent id="..." status="...">\` message.${when(
1531
- tools.offers("waitAgents"),
1532
- ` Use "waitAgents" to wait for the returned id.`,
1533
- )}${when(
1574
+ - "delegate" runs a sub-agent and waits for it. Pass \`background: true\` to keep working while it runs: it returns an agent task straight away, and the agent's result is sent to you when it ends.${when(
1534
1575
  tools.offers("messageAgent"),
1535
- ` Use "messageAgent" to send a message to the returned id.`,
1536
- )}${when(
1537
- tools.offers("stopAgent"),
1538
- ` Use "stopAgent" to stop the returned id.`,
1539
- )}${when(
1540
- tools.offers("listAgents"),
1541
- ` "listAgents" shows the agents you started.`,
1576
+ ` Use "messageAgent" to send a message to a sub-agent.`,
1542
1577
  )}`,
1543
- )}${when(
1578
+ )}${taskInstructions(tools)}${when(
1544
1579
  !conversationMode,
1545
1580
  `
1546
1581
 
@@ -1771,7 +1806,7 @@ export const layerLocal = <
1771
1806
  : never,
1772
1807
  | CurrentDirectory
1773
1808
  | DirectoryChanger
1774
- | SubagentExecutor
1809
+ | AgentTaskExecutor
1775
1810
  | TaskCompleter
1776
1811
  | ImageAttacher
1777
1812
  >