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/dist/bin/cli.mjs CHANGED
@@ -11538,48 +11538,33 @@ const isUnsupportedImageError = (error) => {
11538
11538
  var CurrentDirectory = class extends Service()("clanka/AgentTools/CurrentDirectory") {};
11539
11539
  var DirectoryChanger = class extends Service()("clanka/AgentTools/DirectoryChanger") {};
11540
11540
  var TaskCompleter = class extends Service()("clanka/AgentTools/TaskCompleter") {};
11541
- const SubagentStatus = Literals$2([
11542
- "completed",
11541
+ const TaskKind = Literals$2(["bash", "agent"]);
11542
+ const TaskStatus = Literals$2([
11543
11543
  "running",
11544
+ "completed",
11544
11545
  "failed",
11545
- "cancelled"
11546
+ "stopped"
11546
11547
  ]);
11547
- const SubagentResult = Struct({
11548
- id: String$7,
11549
- status: SubagentStatus,
11550
- output: optional$2(String$7)
11551
- });
11552
- const DelegateResult = Struct({
11553
- ...SubagentResult.fields,
11554
- status: Literals$2(["completed", "running"])
11555
- });
11556
- const SubagentInfo = Struct({
11557
- id: String$7,
11558
- status: SubagentStatus,
11559
- prompt: String$7
11548
+ const Task = Struct({
11549
+ id: String$7.annotate({ documentation: "The task id, which can be managed with the task tools." }),
11550
+ kind: TaskKind,
11551
+ status: TaskStatus,
11552
+ description: String$7,
11553
+ output: String$7,
11554
+ exitCode: optional$2(Number$2)
11560
11555
  });
11561
- var SubagentExecutor = class extends Service()("clanka/AgentTools/SubagentExecutor") {};
11562
- const subagentsUnavailable = {
11556
+ var AgentTaskExecutor = class extends Service()("clanka/AgentTools/AgentTaskExecutor") {};
11557
+ const agentTasksUnavailable = {
11563
11558
  delegate: () => die(new Error("Sub-agents are not available here")),
11564
- waitAgents: () => fail$1("Sub-agents are not available here"),
11559
+ taskOutput: () => fail$1("Sub-agents are not available here"),
11560
+ waitTasks: () => fail$1("Sub-agents are not available here"),
11565
11561
  messageAgent: () => fail$1("Sub-agents are not available here"),
11566
- stopAgent: () => fail$1("Sub-agents are not available here"),
11567
- listAgents: succeed$1([])
11562
+ stopTask: () => fail$1("Sub-agents are not available here"),
11563
+ listTasks: succeed$1([])
11568
11564
  };
11565
+ var TaskOwner = class extends Reference("clanka/AgentTools/TaskOwner", { defaultValue: () => void 0 }) {};
11569
11566
  var ImageAttacher = class extends Service()("clanka/AgentTools/ImageAttacher") {};
11570
- const BashJobStatus = Literals$2([
11571
- "running",
11572
- "completed",
11573
- "failed",
11574
- "stopped"
11575
- ]);
11576
- const BashJob = Struct({
11577
- id: String$7,
11578
- status: BashJobStatus,
11579
- exitCode: optional$2(Number$2),
11580
- output: String$7
11581
- });
11582
- var JobWatcher = class extends Reference("clanka/AgentTools/JobWatcher", { defaultValue: () => () => void_ }) {};
11567
+ var TaskWatcher = class extends Reference("clanka/AgentTools/TaskWatcher", { defaultValue: () => () => void_ }) {};
11583
11568
  const defaultBashTimeout = minutes(10);
11584
11569
  const defaultMcpCallTimeout = minutes(10);
11585
11570
  var CommandLimits = class extends Reference("clanka/AgentTools/CommandLimits", { defaultValue: () => ({
@@ -11587,23 +11572,23 @@ var CommandLimits = class extends Reference("clanka/AgentTools/CommandLimits", {
11587
11572
  outputChars: void 0
11588
11573
  }) }) {};
11589
11574
  const makeBashTool = (timeout) => make$17("bash", {
11590
- 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.",
11575
+ description: "Run a bash command and return a task.",
11591
11576
  parameters: Struct({
11592
11577
  command: String$7,
11593
- timeoutMs: optional$2(Finite).annotate({ documentation: `How long to wait in ms before moving the command to the background (default and max: ${toMillis(timeout)})` }),
11594
- background: optional$2(Boolean$4).annotate({ documentation: "Start the command in the background and return it as \"running\" without waiting" })
11578
+ timeoutMs: optional$2(Finite).annotate({ documentation: `How long to wait in ms before moving the task to the background (default and max: ${toMillis(timeout)})` }),
11579
+ background: optional$2(Boolean$4).annotate({ documentation: "Start the command in the background. Defaults to false which always returns 'completed' tasks." })
11595
11580
  }).annotate({ identifier: "command" }),
11596
- success: BashJob,
11581
+ success: Task,
11597
11582
  dependencies: [CurrentDirectory]
11598
11583
  });
11599
11584
  const globNamesDirectory = (glob) => glob.split("/").slice(0, -1).some((segment) => segment.length > 0 && !/[*?[\]{}]/.test(segment));
11600
11585
  const AgentTools = make$16(make$17("changeDirectory", {
11601
- 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.",
11586
+ description: "Change the executor's working directory to an existing directory and return its absolute path. The change persists across your scripts.",
11602
11587
  parameters: String$7.annotate({ identifier: "directory" }),
11603
11588
  success: String$7,
11604
11589
  dependencies: [DirectoryChanger]
11605
11590
  }), make$17("readFile", {
11606
- 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.",
11591
+ 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.",
11607
11592
  parameters: Struct({
11608
11593
  path: String$7,
11609
11594
  startLine: optional$2(Number$2),
@@ -11623,40 +11608,22 @@ const AgentTools = make$16(make$17("changeDirectory", {
11623
11608
  success: String$7,
11624
11609
  dependencies: [CurrentDirectory]
11625
11610
  }), make$17("delegate", {
11626
- 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.",
11611
+ 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.",
11627
11612
  parameters: Struct({
11628
11613
  prompt: String$7,
11629
11614
  background: optional$2(Boolean$4)
11630
11615
  }),
11631
- success: DelegateResult,
11632
- failure: String$7,
11633
- dependencies: [SubagentExecutor]
11634
- }), make$17("waitAgents", {
11635
- 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.",
11636
- parameters: UndefinedOr(ArraySchema(String$7)).annotate({ identifier: "ids" }),
11637
- success: ArraySchema(SubagentResult),
11616
+ success: Task,
11638
11617
  failure: String$7,
11639
- dependencies: [SubagentExecutor]
11618
+ dependencies: [AgentTaskExecutor]
11640
11619
  }), make$17("messageAgent", {
11641
- 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.",
11620
+ description: "Send a message to one of your sub-agents.",
11642
11621
  parameters: Struct({
11643
11622
  id: String$7,
11644
11623
  message: String$7
11645
11624
  }),
11646
- success: SubagentResult,
11647
- failure: String$7,
11648
- dependencies: [SubagentExecutor]
11649
- }), make$17("stopAgent", {
11650
- description: "Stop one of your sub-agents and every agent it started. Returns its final status.",
11651
- parameters: String$7.annotate({ identifier: "id" }),
11652
- success: SubagentResult,
11653
11625
  failure: String$7,
11654
- dependencies: [SubagentExecutor]
11655
- }), make$17("listAgents", {
11656
- description: "List the sub-agents you have started in this run, with their status.",
11657
- parameters: Void,
11658
- success: ArraySchema(SubagentInfo),
11659
- dependencies: [SubagentExecutor]
11626
+ dependencies: [AgentTaskExecutor]
11660
11627
  }), make$17("glob", {
11661
11628
  description: "Find files matching a glob pattern.",
11662
11629
  parameters: String$7.annotate({ identifier: "pattern" }),
@@ -11667,24 +11634,32 @@ const AgentTools = make$16(make$17("changeDirectory", {
11667
11634
  parameters: ArraySchema(String$7).annotate({ identifier: "args" }),
11668
11635
  success: String$7,
11669
11636
  dependencies: [CurrentDirectory]
11670
- }), makeBashTool(defaultBashTimeout), make$17("jobOutput", {
11671
- description: "Return the status and output so far of a background bash job.",
11637
+ }), makeBashTool(defaultBashTimeout), make$17("taskOutput", {
11638
+ description: "Return the status and output so far of one of your tasks: a background bash command or a sub-agent.",
11672
11639
  parameters: String$7.annotate({ identifier: "id" }),
11673
- success: BashJob,
11674
- failure: String$7
11675
- }), make$17("waitJob", {
11676
- 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.",
11640
+ success: Task,
11641
+ failure: String$7,
11642
+ dependencies: [AgentTaskExecutor]
11643
+ }), make$17("waitTasks", {
11644
+ description: "Wait until the given tasks have ended and return them, in the order given.",
11677
11645
  parameters: Struct({
11678
- id: String$7,
11679
- timeoutMs: optional$2(Finite).annotate({ documentation: "How long to wait in ms (default and max: the bash timeout)" })
11646
+ ids: ArraySchema(String$7),
11647
+ timeoutMs: optional$2(Finite).annotate({ documentation: "How long to wait in ms (default and max: the bash command timeout)" })
11680
11648
  }),
11681
- success: BashJob,
11682
- failure: String$7
11683
- }), make$17("stopJob", {
11684
- description: "Stop a background bash job and return its final status and output.",
11649
+ success: ArraySchema(Task),
11650
+ failure: String$7,
11651
+ dependencies: [AgentTaskExecutor]
11652
+ }), make$17("stopTask", {
11653
+ description: "Stop one of your tasks.",
11685
11654
  parameters: String$7.annotate({ identifier: "id" }),
11686
- success: BashJob,
11687
- failure: String$7
11655
+ success: Task,
11656
+ failure: String$7,
11657
+ dependencies: [AgentTaskExecutor]
11658
+ }), make$17("listTasks", {
11659
+ description: "List the tasks you have started, with their status.",
11660
+ parameters: Void,
11661
+ success: ArraySchema(Task),
11662
+ dependencies: [AgentTaskExecutor]
11688
11663
  }), make$17("applyPatch", {
11689
11664
  description: "Add, update or remove multiple files with a git diff / unified diff / wrapped patch.",
11690
11665
  parameters: String$7.annotate({ identifier: "patch" }),
@@ -11752,44 +11727,49 @@ const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(gen(function* () {
11752
11727
  output: output.render
11753
11728
  };
11754
11729
  });
11755
- const jobs = new Map();
11756
- let nextJobId = 1;
11757
- const addJob = (command) => {
11758
- const id = String(nextJobId++);
11759
- const running = {
11760
- ...command,
11761
- reported: false
11762
- };
11763
- jobs.set(id, running);
11764
- return {
11730
+ const tasks = new Map();
11731
+ let nextTaskId = 1;
11732
+ const registerAgentTask = fnUntraced(function* () {
11733
+ const id = String(nextTaskId++);
11734
+ tasks.set(id, {
11735
+ kind: "agent",
11765
11736
  id,
11766
- running
11737
+ owner: yield* TaskOwner
11738
+ });
11739
+ return id;
11740
+ });
11741
+ const addBashTask = fnUntraced(function* (description, command) {
11742
+ const entry = {
11743
+ kind: "bash",
11744
+ id: String(nextTaskId++),
11745
+ owner: yield* TaskOwner,
11746
+ description,
11747
+ command: {
11748
+ ...command,
11749
+ reported: false
11750
+ }
11767
11751
  };
11768
- };
11769
- const watchJob = fnUntraced(function* (id, running) {
11770
- yield* (yield* JobWatcher)({
11771
- id,
11772
- await: await_(running.fiber).pipe(map$5(() => jobInfo(id, running))),
11752
+ tasks.set(entry.id, entry);
11753
+ return entry;
11754
+ });
11755
+ const watchBashTask = fnUntraced(function* (entry) {
11756
+ yield* (yield* TaskWatcher)({
11757
+ id: entry.id,
11758
+ kind: "bash",
11759
+ await: await_(entry.command.fiber).pipe(map$5(() => bashTask(entry))),
11773
11760
  claim: sync(() => {
11774
- if (running.reported) return false;
11775
- running.reported = true;
11761
+ if (entry.command.reported) return false;
11762
+ entry.command.reported = true;
11776
11763
  return true;
11777
11764
  })
11778
11765
  });
11779
11766
  });
11780
- const findJob = (id) => {
11781
- const running = jobs.get(id);
11782
- return running === void 0 ? fail$1(`No background job with id "${id}"`) : succeed$1(running);
11783
- };
11784
- const reportJob = (id, running) => {
11785
- const job = jobInfo(id, running);
11786
- if (job.status !== "running") running.reported = true;
11787
- return job;
11788
- };
11789
- const awaitCommand = (running, timeout) => {
11790
- const awaited = await_(running.fiber);
11791
- return (timeout === void 0 ? asSome(awaited) : timeoutOption(awaited, timeout)).pipe(onInterrupt(() => interrupt$2(running.fiber)));
11792
- };
11767
+ const findTask = fnUntraced(function* (id) {
11768
+ const owner = yield* TaskOwner;
11769
+ const entry = tasks.get(id);
11770
+ if (entry === void 0 || entry.owner !== owner) return yield* fail$1(`No task with id ${JSON.stringify(id)}. You can only address tasks you started; call listTasks() to see them.`);
11771
+ return entry;
11772
+ });
11793
11773
  const readImage = fnUntraced(function* (path, extensionType, options) {
11794
11774
  if (options.startLine !== void 0 || options.endLine !== void 0) return yield* die(new Error(`startLine / endLine are not supported for images: ${path}`));
11795
11775
  const bytes = yield* readBoundedFile(fs, path).pipe(catchReason("PlatformError", "NotFound", () => succeed$1(null)), orDie);
@@ -11905,44 +11885,62 @@ const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(gen(function* () {
11905
11885
  cwd,
11906
11886
  stdin: "ignore"
11907
11887
  });
11908
- const { id, running } = addJob(yield* startCommand(cmd));
11888
+ const entry = yield* addBashTask(options.command, yield* startCommand(cmd));
11909
11889
  if (options.background !== true) {
11910
- const exit = yield* awaitCommand(running, millis(timeoutMs));
11890
+ const exit = yield* awaitCommand(entry.command, millis(timeoutMs));
11911
11891
  if (isSome(exit)) {
11912
11892
  const exitCode = yield* exit.value;
11913
- const job = reportJob(id, running);
11914
- if (exitCode === 0) return job;
11915
- return yield* die(new Error(`Command failed with exit code ${exitCode}: ${job.output}`));
11893
+ const task = reportBash(entry);
11894
+ if (exitCode === 0) return task;
11895
+ return yield* die(new Error(`Command failed with exit code ${exitCode}: ${task.output}`));
11916
11896
  }
11917
11897
  }
11918
- const job = reportJob(id, running);
11919
- if (job.status === "running") yield* watchJob(id, running);
11920
- return job;
11898
+ const task = reportBash(entry);
11899
+ if (task.status === "running") yield* watchBashTask(entry);
11900
+ return task;
11921
11901
  }, orDie),
11922
- jobOutput: fn("AgentTools.jobOutput")(function* (input) {
11923
- const id = yield* decodeJobOutput(input);
11924
- yield* logInfo(`Calling "jobOutput"`).pipe(annotateLogs({ id }));
11925
- return reportJob(id, yield* findJob(id));
11902
+ taskOutput: fn("AgentTools.taskOutput")(function* (input) {
11903
+ const id = yield* decodeTaskOutput(input);
11904
+ yield* logInfo(`Calling "taskOutput"`).pipe(annotateLogs({ id }));
11905
+ const entry = yield* findTask(id);
11906
+ if (entry.kind === "bash") return reportBash(entry);
11907
+ return yield* (yield* AgentTaskExecutor).taskOutput(id);
11926
11908
  }),
11927
- waitJob: fn("AgentTools.waitJob")(function* (input) {
11928
- const options = yield* decodeWaitJob(input);
11909
+ waitTasks: fn("AgentTools.waitTasks")(function* (input) {
11910
+ const { ids, timeoutMs: requestedMs } = yield* decodeWaitTasks(input);
11929
11911
  const maxMs = bashTimeoutMs(yield* CommandLimits);
11930
- const timeoutMs = Math.min(options.timeoutMs ?? maxMs, maxMs);
11931
- yield* logInfo(`Calling "waitJob"`).pipe(annotateLogs({
11932
- id: options.id,
11912
+ const timeoutMs = Math.min(requestedMs ?? maxMs, maxMs);
11913
+ yield* logInfo(`Calling "waitTasks"`).pipe(annotateLogs({
11914
+ ids,
11933
11915
  timeoutMs
11934
11916
  }));
11935
- const running = yield* findJob(options.id);
11936
- yield* timeoutOption(await_(running.fiber), timeoutMs);
11937
- return reportJob(options.id, running);
11917
+ const entries = yield* forEach$1(ids, findTask);
11918
+ const bashEntries = entries.filter((entry) => entry.kind === "bash");
11919
+ const agentIds = entries.flatMap((entry) => entry.kind === "agent" ? [entry.id] : []);
11920
+ const agentTasks = yield* AgentTaskExecutor;
11921
+ const startedAt = yield* currentTimeMillis;
11922
+ yield* forEach$1(bashEntries, (entry) => await_(entry.command.fiber), {
11923
+ concurrency: "unbounded",
11924
+ discard: true
11925
+ }).pipe(timeoutOption(timeoutMs));
11926
+ const agentResults = agentIds.length === 0 ? [] : yield* agentTasks.waitTasks(agentIds, { timeoutMs: Math.max(0, timeoutMs - ((yield* currentTimeMillis) - startedAt)) });
11927
+ const ended = new Map([...bashEntries.map(reportBash), ...agentResults].map((task) => [task.id, task]));
11928
+ return ids.map((id) => ended.get(id));
11929
+ }),
11930
+ stopTask: fn("AgentTools.stopTask")(function* (input) {
11931
+ const id = yield* decodeStopTask(input);
11932
+ yield* logInfo(`Calling "stopTask"`).pipe(annotateLogs({ id }));
11933
+ const entry = yield* findTask(id);
11934
+ if (entry.kind === "agent") return yield* (yield* AgentTaskExecutor).stopTask(id);
11935
+ yield* interrupt$2(entry.command.fiber);
11936
+ return reportBash(entry);
11938
11937
  }),
11939
- stopJob: fn("AgentTools.stopJob")(function* (input) {
11940
- const id = yield* decodeStopJob(input);
11941
- yield* logInfo(`Calling "stopJob"`).pipe(annotateLogs({ id }));
11942
- const running = yield* findJob(id);
11943
- yield* interrupt$2(running.fiber);
11944
- running.reported = true;
11945
- return jobInfo(id, running);
11938
+ listTasks: fn("AgentTools.listTasks")(function* () {
11939
+ yield* logInfo(`Calling "listTasks"`);
11940
+ const owner = yield* TaskOwner;
11941
+ const bashTasks = Array$1.from(tasks.values()).flatMap((entry) => entry.kind === "bash" && entry.owner === owner ? [bashTask(entry)] : []);
11942
+ const agentTasks = yield* AgentTaskExecutor;
11943
+ return [...bashTasks, ...yield* agentTasks.listTasks].toSorted((a, b) => Number(a.id) - Number(b.id));
11946
11944
  }),
11947
11945
  gh: fn("AgentTools.gh")(function* (args) {
11948
11946
  yield* logInfo(`Calling "gh"`).pipe(annotateLogs({ args }));
@@ -12066,29 +12064,19 @@ const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(gen(function* () {
12066
12064
  delegate: fn("AgentTools.delegate")(function* (options) {
12067
12065
  const { prompt, background = false } = yield* decodeDelegate(options);
12068
12066
  yield* logInfo(`Calling "delegate"`).pipe(annotateLogs({ background }));
12069
- return yield* (yield* SubagentExecutor).delegate({
12067
+ const id = yield* registerAgentTask();
12068
+ return yield* (yield* AgentTaskExecutor).delegate({
12069
+ id,
12070
12070
  prompt,
12071
12071
  background
12072
12072
  });
12073
12073
  }),
12074
- waitAgents: fn("AgentTools.waitAgents")(function* (input) {
12075
- const ids = yield* decodeWaitAgents(input);
12076
- yield* logInfo(`Calling "waitAgents"`).pipe(annotateLogs({ ids }));
12077
- return yield* (yield* SubagentExecutor).waitAgents(ids);
12078
- }),
12079
12074
  messageAgent: fn("AgentTools.messageAgent")(function* (input) {
12080
12075
  const options = yield* decodeMessageAgent(input);
12081
12076
  yield* logInfo(`Calling "messageAgent"`).pipe(annotateLogs({ id: options.id }));
12082
- return yield* (yield* SubagentExecutor).messageAgent(options);
12083
- }),
12084
- stopAgent: fn("AgentTools.stopAgent")(function* (input) {
12085
- const id = yield* decodeStopAgent(input);
12086
- yield* logInfo(`Calling "stopAgent"`).pipe(annotateLogs({ id }));
12087
- return yield* (yield* SubagentExecutor).stopAgent(id);
12088
- }),
12089
- listAgents: fn("AgentTools.listAgents")(function* () {
12090
- yield* logInfo(`Calling "listAgents"`);
12091
- return yield* (yield* SubagentExecutor).listAgents;
12077
+ const entry = yield* findTask(options.id);
12078
+ if (entry.kind === "bash") return yield* fail$1(`messageAgent only addresses sub-agents, and task ${JSON.stringify(entry.id)} is a bash task. Use taskOutput or stopTask with it instead.`);
12079
+ return yield* (yield* AgentTaskExecutor).messageAgent(options);
12092
12080
  }),
12093
12081
  taskComplete: fn("AgentTools.taskComplete")(function* (message) {
12094
12082
  if (typeof message !== "string") return yield* fail$1("taskComplete requires a string argument. Pass your final output directly, for example: taskComplete(\"done\").");
@@ -12103,35 +12091,50 @@ const decodeParams$1 = (schema, usage) => {
12103
12091
  return (input) => mapError(decode(input), () => usage);
12104
12092
  };
12105
12093
  const decodeDelegate = decodeParams$1(AgentTools.tools.delegate.parametersSchema, "delegate requires an options object, for example: delegate({ prompt: \"...\" }) or delegate({ prompt: \"...\", background: true }).");
12106
- const decodeWaitAgents = decodeParams$1(AgentTools.tools.waitAgents.parametersSchema, "waitAgents takes an optional array of agent ids, for example: waitAgents([\"3\", \"4\"]).");
12107
12094
  const decodeMessageAgent = decodeParams$1(AgentTools.tools.messageAgent.parametersSchema, "messageAgent requires an options object, for example: messageAgent({ id: \"3\", message: \"...\" }).");
12108
- const decodeStopAgent = decodeParams$1(AgentTools.tools.stopAgent.parametersSchema, "stopAgent requires an agent id, for example: stopAgent(\"3\").");
12109
- const decodeJobOutput = decodeParams$1(AgentTools.tools.jobOutput.parametersSchema, "jobOutput requires a job id, for example: jobOutput(\"1\").");
12095
+ const decodeTaskOutput = decodeParams$1(AgentTools.tools.taskOutput.parametersSchema, "taskOutput requires a task id, for example: taskOutput(\"1\").");
12096
+ const decodeWaitTasks = decodeParams$1(AgentTools.tools.waitTasks.parametersSchema, "waitTasks requires an options object, for example: waitTasks({ ids: [\"3\", \"4\"] }) or waitTasks({ ids: [\"3\"], timeoutMs: 60000 }).");
12110
12097
  const bashTimeoutMs = (limits) => toMillis(limits.timeout ?? defaultBashTimeout);
12111
- const decodeWaitJob = decodeParams$1(AgentTools.tools.waitJob.parametersSchema, "waitJob requires an options object, for example: waitJob({ id: \"1\" }) or waitJob({ id: \"1\", timeoutMs: 60000 }).");
12112
- const decodeStopJob = decodeParams$1(AgentTools.tools.stopJob.parametersSchema, "stopJob requires a job id, for example: stopJob(\"1\").");
12113
- const jobInfo = (id, running) => {
12114
- const exit = running.fiber.pollUnsafe();
12115
- const output = running.output();
12098
+ const decodeStopTask = decodeParams$1(AgentTools.tools.stopTask.parametersSchema, "stopTask requires a task id, for example: stopTask(\"1\").");
12099
+ const awaitCommand = (command, timeout) => {
12100
+ const awaited = await_(command.fiber);
12101
+ return (timeout === void 0 ? asSome(awaited) : timeoutOption(awaited, timeout)).pipe(onInterrupt(() => interrupt$2(command.fiber)));
12102
+ };
12103
+ const reportBash = (entry) => {
12104
+ const task = bashTask(entry);
12105
+ if (task.status !== "running") entry.command.reported = true;
12106
+ return task;
12107
+ };
12108
+ const bashTask = ({ id, description, command }) => {
12109
+ const exit = command.fiber.pollUnsafe();
12110
+ const output = command.output();
12116
12111
  if (exit === void 0) return {
12117
12112
  id,
12113
+ kind: "bash",
12118
12114
  status: "running",
12115
+ description,
12119
12116
  output
12120
12117
  };
12121
12118
  if (isSuccess(exit)) return {
12122
12119
  id,
12120
+ kind: "bash",
12123
12121
  status: exit.value === 0 ? "completed" : "failed",
12124
- exitCode: exit.value,
12125
- output
12122
+ description,
12123
+ output,
12124
+ exitCode: exit.value
12126
12125
  };
12127
12126
  if (hasInterruptsOnly(exit.cause)) return {
12128
12127
  id,
12128
+ kind: "bash",
12129
12129
  status: "stopped",
12130
+ description,
12130
12131
  output
12131
12132
  };
12132
12133
  return {
12133
12134
  id,
12135
+ kind: "bash",
12134
12136
  status: "failed",
12137
+ description,
12135
12138
  output: `${output}${output === "" ? "" : "\n"}${pretty(exit.cause)}`
12136
12139
  };
12137
12140
  };
@@ -14152,7 +14155,7 @@ var Capabilities = class extends Class$1("Capabilities")({
14152
14155
  environment: ExecutionEnvironment,
14153
14156
  tools: ArraySchema(String$7),
14154
14157
  skills: ArraySchema(Skill).pipe(withDecodingDefaultKey(succeed$1([])), withConstructorDefault(succeed$1([]))),
14155
- jobPushes: Boolean$4.pipe(withDecodingDefaultKey(succeed$1(false)), withConstructorDefault(succeed$1(false)))
14158
+ taskPushes: Boolean$4.pipe(withDecodingDefaultKey(succeed$1(false)), withConstructorDefault(succeed$1(false)))
14156
14159
  }) {};
14157
14160
  const makeLocal = (options) => map$5(makeLocalWith(options), (local) => local.executor);
14158
14161
  const makeLocalWith = fnUntraced(function* (options) {
@@ -14241,13 +14244,13 @@ const makeLocalWith = fnUntraced(function* (options) {
14241
14244
  currentDirectory = target;
14242
14245
  return onChange ? onChange(currentEnvironment()) : void_;
14243
14246
  }));
14244
- const taskServices = empty$5().pipe(add(TaskCompleter, opts.onTaskComplete), add(DirectoryChanger, changeDirectory), add(SubagentExecutor, {
14245
- ...opts.subagents,
14246
- delegate: (options) => renderEnvironment(currentEnvironment(), { reset: true }).pipe(flatMap$1((environment) => opts.subagents.delegate({
14247
+ const taskServices = empty$5().pipe(add(TaskCompleter, opts.onTaskComplete), add(DirectoryChanger, changeDirectory), add(AgentTaskExecutor, {
14248
+ ...opts.agentTasks,
14249
+ delegate: (options) => renderEnvironment(currentEnvironment(), { reset: true }).pipe(flatMap$1((environment) => opts.agentTasks.delegate({
14247
14250
  ...options,
14248
14251
  environment
14249
14252
  })))
14250
- }), add(ImageAttacher, opts.onImage), add(JobWatcher, opts.onJob ?? (() => void_)), add(CommandLimits, commandLimits), add(Console, console), add(CurrentLogAnnotations, {}), isSome(search) ? add(SemanticSearch, search.value) : identity);
14253
+ }), add(ImageAttacher, opts.onImage), add(TaskWatcher, opts.onTask ?? (() => void_)), add(TaskOwner, opts.agentId), add(CommandLimits, commandLimits), add(Console, console), add(CurrentLogAnnotations, {}), isSome(search) ? add(SemanticSearch, search.value) : identity);
14251
14254
  yield* gen(function* () {
14252
14255
  const source = prepareScript(opts.script);
14253
14256
  const settled = yield* make$42();
@@ -14333,7 +14336,7 @@ const makeLocalWith = fnUntraced(function* (options) {
14333
14336
  }),
14334
14337
  tools: Object.keys(tools.tools),
14335
14338
  skills,
14336
- jobPushes: true
14339
+ taskPushes: true
14337
14340
  });
14338
14341
  }),
14339
14342
  execute: (opts) => execute(opts),
@@ -14344,7 +14347,7 @@ const makeLocalWith = fnUntraced(function* (options) {
14344
14347
  const handler = services.mapUnsafe.get(tool.id);
14345
14348
  if (!handler) return die(new Error(`Unknown tool: ${opts.tool}`));
14346
14349
  const cwd = (opts.environment ?? startupEnvironment).cwd;
14347
- const taskServices = handler.context.pipe(add(TaskCompleter, () => void_), add(CurrentDirectory, cwd), add(DirectoryChanger, (directory) => resolveDirectory(cwd, directory)), add(SubagentExecutor, subagentsUnavailable), add(ImageAttacher, () => void_), add(CommandLimits, commandLimits), add(CurrentLogAnnotations, {}), isSome(search) ? add(SemanticSearch, search.value) : identity);
14350
+ const taskServices = handler.context.pipe(add(TaskCompleter, () => void_), add(CurrentDirectory, cwd), add(DirectoryChanger, (directory) => resolveDirectory(cwd, directory)), add(AgentTaskExecutor, agentTasksUnavailable), add(ImageAttacher, () => void_), add(CommandLimits, commandLimits), add(CurrentLogAnnotations, {}), isSome(search) ? add(SemanticSearch, search.value) : identity);
14348
14351
  const encodeSuccess = encodeUnknownEffect(toCodecJson(tool.successSchema));
14349
14352
  return pipe(handler.handler(opts.params, {}), flatMap$1(encodeSuccess), provideContext(taskServices), orDie);
14350
14353
  })
@@ -14363,7 +14366,8 @@ const makeRpc = gen(function* () {
14363
14366
  script: opts.script,
14364
14367
  environment: opts.environment,
14365
14368
  loopTools: Object.keys(opts.loopTools ?? {}),
14366
- ...opts.onJob === void 0 ? {} : { watchJobs: true }
14369
+ ...opts.agentId === void 0 ? {} : { agentId: opts.agentId },
14370
+ ...opts.onTask === void 0 ? {} : { watchTasks: true }
14367
14371
  }).pipe(tap$1((part) => {
14368
14372
  switch (part._tag) {
14369
14373
  case "Text": return void_;
@@ -14383,13 +14387,14 @@ const makeRpc = gen(function* () {
14383
14387
  case "Environment":
14384
14388
  latest = part.environment;
14385
14389
  return void_;
14386
- case "Job": {
14387
- if (opts.onJob === void 0) return void_;
14390
+ case "Task": {
14391
+ if (opts.onTask === void 0) return void_;
14388
14392
  const id = part.id;
14389
- return opts.onJob({
14393
+ return opts.onTask({
14390
14394
  id,
14391
- await: orDie(client.awaitJob({ id })),
14392
- claim: orDie(client.claimJob({ id }))
14395
+ kind: part.kind,
14396
+ await: orDie(client.awaitTask({ id })),
14397
+ claim: orDie(client.claimTask({ id }))
14393
14398
  });
14394
14399
  }
14395
14400
  }
@@ -14413,17 +14418,22 @@ const layerRpc = effect(AgentExecutor, makeRpc);
14413
14418
  const AgentRequest = TaggedUnion({
14414
14419
  TaskComplete: { summary: String$7 },
14415
14420
  Delegate: {
14421
+ id: String$7,
14416
14422
  prompt: String$7,
14417
14423
  background: Boolean$4,
14418
14424
  environment: EnvironmentUpdate
14419
14425
  },
14420
- WaitAgents: { ids: UndefinedOr(ArraySchema(String$7)) },
14426
+ TaskOutput: { id: String$7 },
14427
+ WaitTasks: {
14428
+ ids: ArraySchema(String$7),
14429
+ timeoutMs: Finite
14430
+ },
14421
14431
  MessageAgent: {
14422
14432
  id: String$7,
14423
14433
  message: String$7
14424
14434
  },
14425
- StopAgent: { id: String$7 },
14426
- ListAgents: {},
14435
+ StopTask: { id: String$7 },
14436
+ ListTasks: {},
14427
14437
  LoopTool: {
14428
14438
  name: String$7,
14429
14439
  params: optional$2(Json)
@@ -14446,7 +14456,10 @@ const ExecuteOutput = TaggedUnion({
14446
14456
  data: Uint8Array$2
14447
14457
  },
14448
14458
  Environment: { environment: ExecutionEnvironment },
14449
- Job: { id: String$7 }
14459
+ Task: {
14460
+ id: String$7,
14461
+ kind: TaskKind
14462
+ }
14450
14463
  });
14451
14464
  var Rpcs = class extends make$12(make$14("capabilities", { success: Capabilities }), make$14("respond", { payload: {
14452
14465
  id: Finite,
@@ -14456,15 +14469,16 @@ var Rpcs = class extends make$12(make$14("capabilities", { success: Capabilities
14456
14469
  script: String$7,
14457
14470
  environment: ExecutionEnvironment,
14458
14471
  loopTools: ArraySchema(String$7).pipe(withDecodingDefaultKey(succeed$1([]))),
14459
- watchJobs: optionalKey(Boolean$4)
14472
+ agentId: optionalKey(String$7),
14473
+ watchTasks: optionalKey(Boolean$4)
14460
14474
  }),
14461
14475
  success: ExecuteOutput,
14462
14476
  stream: true
14463
- }), make$14("awaitJob", {
14477
+ }), make$14("awaitTask", {
14464
14478
  payload: { id: String$7 },
14465
- success: BashJob,
14479
+ success: Task,
14466
14480
  error: String$7
14467
- }), make$14("claimJob", {
14481
+ }), make$14("claimTask", {
14468
14482
  payload: { id: String$7 },
14469
14483
  success: Boolean$4,
14470
14484
  error: String$7
@@ -14506,11 +14520,12 @@ const encodeRpcParams = (tool, params) => {
14506
14520
  const handleRequest = (opts, request) => {
14507
14521
  switch (request._tag) {
14508
14522
  case "TaskComplete": return opts.onTaskComplete(request.summary);
14509
- case "Delegate": return opts.subagents.delegate(request);
14510
- case "WaitAgents": return opts.subagents.waitAgents(request.ids);
14511
- case "MessageAgent": return opts.subagents.messageAgent(request);
14512
- case "StopAgent": return opts.subagents.stopAgent(request.id);
14513
- case "ListAgents": return opts.subagents.listAgents;
14523
+ case "Delegate": return opts.agentTasks.delegate(request);
14524
+ case "TaskOutput": return opts.agentTasks.taskOutput(request.id);
14525
+ case "WaitTasks": return opts.agentTasks.waitTasks(request.ids, request);
14526
+ case "MessageAgent": return opts.agentTasks.messageAgent(request);
14527
+ case "StopTask": return opts.agentTasks.stopTask(request.id);
14528
+ case "ListTasks": return opts.agentTasks.listTasks;
14514
14529
  case "EnvironmentChanged": return void_;
14515
14530
  case "LoopTool": {
14516
14531
  const handler = opts.loopTools?.[request.name];
@@ -14532,16 +14547,14 @@ const exitToResponse = (exit) => {
14532
14547
  const errorMessage$2 = (error) => typeof error === "string" ? error : error instanceof Error ? error.message : String(error);
14533
14548
  const excludedToolNames = (excludeTools) => {
14534
14549
  const names = new Set(excludeTools);
14535
- if (names.has("delegate")) for (const name of [
14536
- "waitAgents",
14537
- "messageAgent",
14538
- "stopAgent",
14539
- "listAgents"
14540
- ]) names.add(name);
14541
- if (names.has("bash")) {
14542
- names.add("jobOutput");
14543
- names.add("waitJob");
14544
- names.add("stopJob");
14550
+ if (names.has("delegate")) {
14551
+ names.add("messageAgent");
14552
+ if (names.has("bash")) for (const name of [
14553
+ "taskOutput",
14554
+ "waitTasks",
14555
+ "stopTask",
14556
+ "listTasks"
14557
+ ]) names.add(name);
14545
14558
  }
14546
14559
  return names;
14547
14560
  };
@@ -20595,13 +20608,13 @@ const makeWith$1 = fnUntraced(function* (options) {
20595
20608
  mcpServers?.dts ?? ""
20596
20609
  ].filter((dts) => dts !== "").join("\n\n"),
20597
20610
  offers: (name) => capabilities.tools.includes(name),
20598
- jobPushes: capabilities.jobPushes,
20611
+ taskPushes: capabilities.taskPushes,
20599
20612
  skillsCatalog: options.skills === void 0 ? renderCatalog(capabilities.skills) : renderProvidedCatalog(options.skills),
20600
20613
  mcp: mcpServers?.prompt ?? ""
20601
20614
  };
20602
20615
  const rootMailbox = makeMailbox();
20603
20616
  const agentsMd = options.instructions === void 0 ? capabilities.instructions : map$8(options.instructions, renderInstructions);
20604
- let agentCounter = 0;
20617
+ const rootTaskOwner = crypto.randomUUID();
20605
20618
  const outputBuffer = new Map();
20606
20619
  let currentOutputAgent = null;
20607
20620
  const history = make$46(empty$1);
@@ -20633,11 +20646,11 @@ const makeWith$1 = fnUntraced(function* (options) {
20633
20646
  let cacheWrite = 0;
20634
20647
  const prompt = opts.history;
20635
20648
  const mailbox = opts.mailbox;
20636
- const onJob = (job) => job.await.pipe(flatMap$1((final) => sync(() => {
20649
+ const onTask = (task) => task.await.pipe(flatMap$1((final) => sync(() => {
20637
20650
  if (final.status === "running") return;
20638
- mailbox.jobs.push({
20639
- job: final,
20640
- claim: job.claim
20651
+ mailbox.tasks.push({
20652
+ task: final,
20653
+ claim: task.claim
20641
20654
  });
20642
20655
  const event = new JobComplete({
20643
20656
  id: final.id,
@@ -20667,6 +20680,7 @@ const makeWith$1 = fnUntraced(function* (options) {
20667
20680
  agentsMd: getOrElse(agentsMd, () => "")
20668
20681
  });
20669
20682
  if (typeof opts.system === "string") system += `\n${opts.system}\n`;
20683
+ console.log("system:", system);
20670
20684
  function maybeSend(options) {
20671
20685
  if (!opts.display) {
20672
20686
  offerUnsafe(output, options.part);
@@ -20712,22 +20726,25 @@ const makeWith$1 = fnUntraced(function* (options) {
20712
20726
  };
20713
20727
  mailbox.notify = notify;
20714
20728
  const runningChildren = () => Array$1.from(children.values()).filter((child) => child.turn.status === "running");
20715
- const hasUndelivered = () => completions.some((turn) => !turn.delivered);
20716
- const finishTurn = (turn, exit) => sync(() => {
20729
+ const hasUndelivered = () => completions.some(({ turn }) => !turn.reported);
20730
+ const finishTurn = (child, turn, exit) => sync(() => {
20717
20731
  if (isSuccess(exit)) {
20718
20732
  turn.status = "completed";
20719
20733
  turn.output = exit.value;
20720
- } else if (hasInterruptsOnly(exit.cause)) turn.status = "cancelled";
20734
+ } else if (hasInterruptsOnly(exit.cause)) turn.status = "stopped";
20721
20735
  else {
20722
20736
  turn.status = "failed";
20723
20737
  turn.output = causeMessage(exit.cause);
20724
20738
  }
20725
20739
  offerUnsafe(output, new SubagentComplete({
20726
- id: turn.agentId,
20740
+ id: child.id,
20727
20741
  summary: turn.output ?? "",
20728
- status: turn.status
20742
+ status: turn.status === "stopped" ? "cancelled" : turn.status
20729
20743
  }));
20730
- if (!turn.delivered) completions.push(turn);
20744
+ if (!turn.reported) completions.push({
20745
+ child,
20746
+ turn
20747
+ });
20731
20748
  doneUnsafe(turn.done, void_);
20732
20749
  notify();
20733
20750
  });
@@ -20737,6 +20754,7 @@ const makeWith$1 = fnUntraced(function* (options) {
20737
20754
  const display = opts.display && !options.background;
20738
20755
  const stream = spawn({
20739
20756
  agentId: child.id,
20757
+ taskOwner: child.taskOwner,
20740
20758
  prompt: make$21(options.prompt),
20741
20759
  environmentUpdate: options.environmentUpdate,
20742
20760
  system: opts.system,
@@ -20776,32 +20794,34 @@ const makeWith$1 = fnUntraced(function* (options) {
20776
20794
  }
20777
20795
  return void_;
20778
20796
  }), as(""), catchTag("AgentFinished", (finished) => succeed$1(finished.summary)));
20779
- }).pipe(onExit((exit) => finishTurn(turn, exit)), provideSubagentModel, provideContext(runContext), forkIn(runScope, { startImmediately: true }));
20797
+ }).pipe(onExit((exit) => finishTurn(child, turn, exit)), provideSubagentModel, provideContext(runContext), forkIn(runScope, { startImmediately: true }));
20780
20798
  });
20781
- const childResult = ({ id, turn }) => turn.output === void 0 ? {
20782
- id: String(id),
20783
- status: turn.status
20784
- } : {
20799
+ const childTask = ({ id, prompt, turn }) => ({
20785
20800
  id: String(id),
20801
+ kind: "agent",
20786
20802
  status: turn.status,
20787
- output: turn.output
20803
+ description: prompt,
20804
+ output: turn.output ?? ""
20805
+ });
20806
+ const reportChild = (child) => {
20807
+ if (child.turn.status !== "running") child.turn.reported = true;
20808
+ return childTask(child);
20788
20809
  };
20789
20810
  const lookupChild = (id) => suspend(() => {
20790
20811
  const child = children.get(id);
20791
- return child ? succeed$1(child) : fail$1(`Unknown agent id ${JSON.stringify(id)}. You can only address agents you started; call listAgents() to see them.`);
20812
+ return child ? succeed$1(child) : fail$1(`No task with id ${JSON.stringify(id)}. You can only address tasks you started; call listTasks() to see them.`);
20792
20813
  });
20793
- const subagents = {
20794
- delegate: fnUntraced(function* ({ prompt, background, environment }) {
20795
- const agentId = agentCounter++;
20814
+ const agentTasks = {
20815
+ delegate: fnUntraced(function* ({ id, prompt, background, environment }) {
20796
20816
  const child = {
20797
- id: agentId,
20817
+ id: Number(id),
20818
+ taskOwner: crypto.randomUUID(),
20798
20819
  prompt,
20799
20820
  history: make$46(empty$1),
20800
20821
  environment: make$46(environment.environment),
20801
20822
  mailbox: makeMailbox(),
20802
- turn: makeTurn(agentId, background)
20823
+ turn: makeTurn(background)
20803
20824
  };
20804
- const id = String(child.id);
20805
20825
  children.set(id, child);
20806
20826
  const turn = child.turn;
20807
20827
  yield* startTurn({
@@ -20813,29 +20833,22 @@ ${prompt}`,
20813
20833
  environmentUpdate: getOrUndefined(environment.update),
20814
20834
  background
20815
20835
  });
20816
- if (background) return {
20817
- id,
20818
- status: "running"
20819
- };
20836
+ if (background) return childTask(child);
20820
20837
  yield* _await(turn.done).pipe(onInterrupt(() => interrupt$2(turn.fiber)));
20821
20838
  if (turn.status !== "completed") return yield* die(new Error(`Sub-agent ${child.id} ${turn.status}${turn.output ? `: ${turn.output}` : ""}`));
20822
- return {
20823
- id,
20824
- status: "completed",
20825
- output: turn.output ?? ""
20826
- };
20839
+ return childTask(child);
20827
20840
  }),
20828
- waitAgents: fnUntraced(function* (ids) {
20829
- const targets = ids === void 0 ? Array$1.from(children.values()) : yield* forEach$1(ids, lookupChild);
20830
- while (true) {
20831
- const running = targets.find((child) => child.turn.status === "running");
20832
- if (!running) break;
20833
- yield* _await(running.turn.done);
20834
- }
20835
- return targets.map((child) => {
20836
- child.turn.delivered = true;
20837
- return childResult(child);
20838
- });
20841
+ taskOutput: (id) => map$5(lookupChild(id), reportChild),
20842
+ waitTasks: fnUntraced(function* (ids, { timeoutMs }) {
20843
+ const targets = yield* forEach$1(ids, lookupChild);
20844
+ yield* gen(function* () {
20845
+ while (true) {
20846
+ const running = targets.find((child) => child.turn.status === "running");
20847
+ if (!running) break;
20848
+ yield* _await(running.turn.done);
20849
+ }
20850
+ }).pipe(timeoutOption(timeoutMs));
20851
+ return targets.map(reportChild);
20839
20852
  }),
20840
20853
  messageAgent: fnUntraced(function* ({ id, message }) {
20841
20854
  const child = yield* lookupChild(id);
@@ -20845,35 +20858,32 @@ ${prompt}`,
20845
20858
  resume: () => {}
20846
20859
  });
20847
20860
  child.mailbox.notify();
20848
- return childResult(child);
20861
+ return childTask(child);
20849
20862
  }
20850
- child.turn = makeTurn(child.id, true);
20863
+ child.turn = makeTurn(true);
20851
20864
  yield* startTurn({
20852
20865
  child,
20853
20866
  prompt: message,
20854
20867
  label: message,
20855
20868
  background: true
20856
20869
  });
20857
- return childResult(child);
20870
+ return childTask(child);
20858
20871
  }),
20859
- stopAgent: fnUntraced(function* (id) {
20872
+ stopTask: fnUntraced(function* (id) {
20860
20873
  const child = yield* lookupChild(id);
20861
20874
  const turn = child.turn;
20862
- turn.delivered = true;
20875
+ turn.reported = true;
20863
20876
  if (turn.status === "running") yield* interrupt$2(turn.fiber);
20864
- return childResult(child);
20877
+ return childTask(child);
20865
20878
  }),
20866
- listAgents: sync(() => Array$1.from(children.values(), (child) => ({
20867
- id: String(child.id),
20868
- status: child.turn.status,
20869
- prompt: child.prompt
20870
- })))
20879
+ listTasks: sync(() => Array$1.from(children.values(), childTask))
20871
20880
  };
20872
20881
  const onTaskComplete = (summary) => suspend(() => {
20873
20882
  const running = runningChildren();
20874
20883
  if (running.length > 0) {
20875
- const ids = running.map((child) => JSON.stringify(String(child.id)));
20876
- return fail$1(`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.`);
20884
+ const ids = running.map((child) => String(child.id));
20885
+ const quoted = ids.map((id) => JSON.stringify(id)).join(", ");
20886
+ return fail$1(`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.`);
20877
20887
  }
20878
20888
  finalSummary = some(summary);
20879
20889
  return void_;
@@ -20975,10 +20985,11 @@ ${prompt}`,
20975
20985
  onEnvironment: (environment) => sync(() => {
20976
20986
  set$1(opts.environment, environment);
20977
20987
  }),
20978
- subagents,
20988
+ agentId: opts.taskOwner,
20989
+ agentTasks,
20979
20990
  onTaskComplete,
20980
20991
  onImage,
20981
- onJob,
20992
+ onTask,
20982
20993
  loopTools: scriptLoopTools
20983
20994
  }), mkString);
20984
20995
  const capped = capOutput(output);
@@ -21037,25 +21048,21 @@ ${prompt}`,
21037
21048
  })));
21038
21049
  mailbox.messages.clear();
21039
21050
  }
21040
- if (completions.length > 0) {
21041
- const pushes = completions.splice(0).filter((turn) => {
21042
- if (turn.delivered) return false;
21043
- turn.delivered = true;
21044
- return true;
21045
- });
21046
- if (pushes.length > 0) appendHistory(make$21(pushes.map((turn) => ({
21047
- role: "user",
21048
- content: `<subagent id="${turn.agentId}" status="${turn.status}">
21049
- ${capOutput(turn.output ?? "").output}
21050
- </subagent>`
21051
- }))));
21052
- }
21053
- if (mailbox.jobs.length > 0) {
21051
+ if (completions.length > 0 || mailbox.tasks.length > 0) {
21054
21052
  const pushes = [];
21055
- for (const { job, claim } of mailbox.jobs.splice(0)) if (yield* claim) pushes.push(job);
21056
- if (pushes.length > 0) appendHistory(make$21(pushes.map((job) => ({
21053
+ for (const { child, turn } of completions.splice(0)) {
21054
+ if (turn.reported) continue;
21055
+ turn.reported = true;
21056
+ pushes.push({
21057
+ ...childTask(child),
21058
+ status: turn.status,
21059
+ output: turn.output ?? ""
21060
+ });
21061
+ }
21062
+ for (const { task, claim } of mailbox.tasks.splice(0)) if (yield* claim) pushes.push(task);
21063
+ if (pushes.length > 0) appendHistory(make$21(pushes.map((task) => ({
21057
21064
  role: "user",
21058
- content: jobMessage(job)
21065
+ content: taskMessage(task)
21059
21066
  }))));
21060
21067
  }
21061
21068
  yield* compactWithEvents("threshold", compactIfNeeded({
@@ -21260,7 +21267,8 @@ ${capOutput(turn.output ?? "").output}
21260
21267
  history,
21261
21268
  environment,
21262
21269
  send: (options) => spawn({
21263
- agentId: agentCounter++,
21270
+ agentId: 0,
21271
+ taskOwner: rootTaskOwner,
21264
21272
  prompt: make$21(options.prompt),
21265
21273
  system: options.system,
21266
21274
  history,
@@ -21287,21 +21295,20 @@ const make$8 = makeWith$1({});
21287
21295
  const makeMailbox = () => ({
21288
21296
  messages: new Set(),
21289
21297
  notify: () => {},
21290
- jobs: [],
21298
+ tasks: [],
21291
21299
  emit: void 0,
21292
21300
  events: []
21293
21301
  });
21294
- const jobMessage = (job) => {
21295
- const exitCode = job.exitCode === void 0 ? "" : ` exitCode="${job.exitCode}"`;
21296
- return `<job id="${job.id}" status="${job.status}"${exitCode}>
21297
- ${capOutput(job.output).output}
21298
- </job>`;
21302
+ const taskMessage = (task) => {
21303
+ const exitCode = task.exitCode === void 0 ? "" : ` exitCode="${task.exitCode}"`;
21304
+ return `<task id="${task.id}" kind="${task.kind}" status="${task.status}"${exitCode}>
21305
+ ${capOutput(task.output).output}
21306
+ </task>`;
21299
21307
  };
21300
- const makeTurn = (agentId, background) => ({
21301
- agentId,
21308
+ const makeTurn = (background) => ({
21302
21309
  status: "running",
21303
21310
  output: void 0,
21304
- delivered: !background,
21311
+ reported: !background,
21305
21312
  done: makeUnsafe$1(),
21306
21313
  fiber: void 0
21307
21314
  });
@@ -21324,7 +21331,7 @@ const environmentUpdateMessage = (text) => make$21([{
21324
21331
  }]);
21325
21332
  const startsWith = (message, prefix) => message.role === "user" && message.content.length === 1 && message.content[0].type === "text" && message.content[0].text.trimStart().startsWith(prefix);
21326
21333
  const isEnvironmentUpdate = (message) => startsWith(message, environmentUpdateOpen);
21327
- const isInjectedMessage = (message) => isEnvironmentUpdate(message) || startsWith(message, "<subagent ");
21334
+ const isInjectedMessage = (message) => isEnvironmentUpdate(message) || startsWith(message, "<task ") || startsWith(message, "<subagent ") || startsWith(message, "<job ");
21328
21335
  const renderInstructions = (content) => `# Project instructions
21329
21336
 
21330
21337
  **ALWAYS follow these instructions when completing tasks**:
@@ -21339,6 +21346,19 @@ ${options.toolInstructions}
21339
21346
  ${options.agentsMd}
21340
21347
  `;
21341
21348
  const when = (condition, text) => condition ? text : "";
21349
+ const taskInstructions = (tools) => {
21350
+ const bash = tools.offers("bash");
21351
+ const delegate = tools.offers("delegate");
21352
+ if (!bash && !delegate) return "";
21353
+ const functions = [
21354
+ ["taskOutput", `"taskOutput" reads one`],
21355
+ ["waitTasks", `"waitTasks" waits for a list of them and returns any still running at its timeout as "running"`],
21356
+ ["stopTask", `"stopTask" stops one`],
21357
+ ["listTasks", `"listTasks" lists yours`]
21358
+ ].filter(([name]) => tools.offers(name)).map(([, text]) => text);
21359
+ return `
21360
+ - ${bash && delegate ? "Background commands and sub-agents are" : bash ? "Background commands are" : "Sub-agents are"} tasks with ids.${functions.length === 0 ? "" : ` ${functions.length === 1 ? functions[0] : `${functions.slice(0, -1).join(", ")} and ${functions.at(-1)}`}.`}${tools.taskPushes ? ` 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.` : bash && tools.offers("taskOutput") ? ` Background commands are not sent to you when they end: check them with "taskOutput".` : ""}`;
21361
+ };
21342
21362
  const generateSystemTools = (tools, conversationMode) => `YOU ONLY HAVE ONE TOOL AVAILABLE: "execute", to run javascript code to do your work.
21343
21363
 
21344
21364
  - Use \`console.log\` to print any output you need.
@@ -21346,11 +21366,10 @@ const generateSystemTools = (tools, conversationMode) => `YOU ONLY HAVE ONE TOOL
21346
21366
  - Use top level await.${when(tools.offers("search") && tools.offers("rg"), `
21347
21367
  - Prefer using the "search" function over "rg", unless you are targeting specific files or patterns.`)}${when(tools.offers("applyPatch"), `
21348
21368
  - You can add / update / remove multiple files in one go with "applyPatch".${when(tools.offers("writeFile"), ` Prefer it over "writeFile" to update existing files.`)}`)}${when(tools.offers("bash"), `
21349
- - Avoid passing scripts into the "bash" function, and instead write javascript.
21350
- - 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(tools.offers("waitJob"), ` "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\`.`)}${when(tools.jobPushes, ` 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.`)}`)}
21369
+ - Avoid passing scripts into the "bash" function, and instead write javascript.`)}
21351
21370
  - Variables are not shared between executions.
21352
21371
  - Do not use \`require\`, \`import\`, \`process\`, or any other Node.js apis.${when(tools.offers("delegate"), `
21353
- - "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(tools.offers("waitAgents"), ` Use "waitAgents" to wait for the returned id.`)}${when(tools.offers("messageAgent"), ` Use "messageAgent" to send a message to the returned id.`)}${when(tools.offers("stopAgent"), ` Use "stopAgent" to stop the returned id.`)}${when(tools.offers("listAgents"), ` "listAgents" shows the agents you started.`)}`)}${when(!conversationMode, `
21372
+ - "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(tools.offers("messageAgent"), ` Use "messageAgent" to send a message to a sub-agent.`)}`)}${taskInstructions(tools)}${when(!conversationMode, `
21354
21373
 
21355
21374
  When you have fully completed your task, call the "taskComplete" function with the final output.
21356
21375
  Make sure every detail of the task is done before calling "taskComplete".${when(tools.offers("delegate"), `
@@ -28493,7 +28512,7 @@ const transformToolCallParams$1 = fnUntraced(function* (options, toolName, toolP
28493
28512
  return yield* decodeEffect(codec)(toolParams).pipe(flatMap$1((decoded) => encodeUnknownEffect(tool.parametersSchema)(decoded)), orElseSucceed(() => toolParams));
28494
28513
  });
28495
28514
  // package.json
28496
- var version$1 = "0.21.0";
28515
+ var version$1 = "0.22.0";
28497
28516
  // src/ClaudeAgent.ts
28498
28517
  const minimumClaudeCodeVersion = "2.1.248";
28499
28518
  const serverName = "clanka";