clanka 0.20.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/Acp.test.js +20 -8
  2. package/dist/Acp.test.js.map +1 -1
  3. package/dist/Agent.d.ts +4 -4
  4. package/dist/Agent.d.ts.map +1 -1
  5. package/dist/Agent.js +140 -99
  6. package/dist/Agent.js.map +1 -1
  7. package/dist/Agent.test.js +5 -4
  8. package/dist/Agent.test.js.map +1 -1
  9. package/dist/AgentBashJobs.test.js +51 -32
  10. package/dist/AgentBashJobs.test.js.map +1 -1
  11. package/dist/AgentCallerConfig.test.js +26 -7
  12. package/dist/AgentCallerConfig.test.js.map +1 -1
  13. package/dist/AgentExecutor.d.ts +71 -41
  14. package/dist/AgentExecutor.d.ts.map +1 -1
  15. package/dist/AgentExecutor.js +86 -78
  16. package/dist/AgentExecutor.js.map +1 -1
  17. package/dist/AgentExecutor.test.js +173 -72
  18. package/dist/AgentExecutor.test.js.map +1 -1
  19. package/dist/AgentExecutorImage.test.js +2 -2
  20. package/dist/AgentExecutorImage.test.js.map +1 -1
  21. package/dist/AgentImage.test.js +3 -2
  22. package/dist/AgentImage.test.js.map +1 -1
  23. package/dist/AgentSubagents.test.js +220 -31
  24. package/dist/AgentSubagents.test.js.map +1 -1
  25. package/dist/AgentTools.d.ts +369 -257
  26. package/dist/AgentTools.d.ts.map +1 -1
  27. package/dist/AgentTools.js +247 -190
  28. package/dist/AgentTools.js.map +1 -1
  29. package/dist/AgentTools.test.js +2 -2
  30. package/dist/AgentTools.test.js.map +1 -1
  31. package/dist/bin/cli.mjs +330 -281
  32. package/dist/bin/cli.mjs.map +1 -1
  33. package/package.json +1 -1
  34. package/src/Acp.test.ts +32 -11
  35. package/src/Agent.test.ts +5 -4
  36. package/src/Agent.ts +175 -137
  37. package/src/AgentBashJobs.test.ts +74 -38
  38. package/src/AgentCallerConfig.test.ts +39 -7
  39. package/src/AgentExecutor.test.ts +229 -72
  40. package/src/AgentExecutor.ts +120 -104
  41. package/src/AgentExecutorImage.test.ts +2 -2
  42. package/src/AgentImage.test.ts +4 -3
  43. package/src/AgentSubagents.test.ts +825 -562
  44. package/src/AgentTools.test.ts +2 -2
  45. package/src/AgentTools.ts +370 -278
package/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 the output. With `background: true` it returns straight away with a job id while the command keeps running. A command still running at its timeout is not stopped: it is moved to the background, and the output so far is returned with its job id. Read a job with \"jobOutput\" and stop it with \"stopJob\".",
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 its job id 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: String$7,
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
11625
  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
- 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,16 +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("stopJob", {
11676
- description: "Stop a background bash job and return its final status and output.",
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.",
11645
+ parameters: Struct({
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)" })
11648
+ }),
11649
+ success: ArraySchema(Task),
11650
+ failure: String$7,
11651
+ dependencies: [AgentTaskExecutor]
11652
+ }), make$17("stopTask", {
11653
+ description: "Stop one of your tasks.",
11677
11654
  parameters: String$7.annotate({ identifier: "id" }),
11678
- success: BashJob,
11679
- 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]
11680
11663
  }), make$17("applyPatch", {
11681
11664
  description: "Add, update or remove multiple files with a git diff / unified diff / wrapped patch.",
11682
11665
  parameters: String$7.annotate({ identifier: "patch" }),
@@ -11744,48 +11727,48 @@ const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(gen(function* () {
11744
11727
  output: output.render
11745
11728
  };
11746
11729
  });
11747
- const jobs = new Map();
11748
- let nextJobId = 1;
11749
- const addJob = fnUntraced(function* (command) {
11750
- const id = String(nextJobId++);
11751
- const running = {
11752
- ...command,
11753
- reported: false
11754
- };
11755
- jobs.set(id, running);
11756
- yield* (yield* JobWatcher)({
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",
11757
11736
  id,
11758
- await: await_(running.fiber).pipe(map$5(() => jobInfo(id, 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
+ }
11751
+ };
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))),
11759
11760
  claim: sync(() => {
11760
- if (running.reported) return false;
11761
- running.reported = true;
11761
+ if (entry.command.reported) return false;
11762
+ entry.command.reported = true;
11762
11763
  return true;
11763
11764
  })
11764
11765
  });
11765
- return id;
11766
11766
  });
11767
- const findJob = (id) => {
11768
- const running = jobs.get(id);
11769
- return running === void 0 ? fail$1(`No background job with id "${id}"`) : succeed$1(running);
11770
- };
11771
- const runCommand = fnUntraced(function* (command, timeout, onTimeout) {
11772
- const running = yield* startCommand(command);
11773
- const awaited = await_(running.fiber);
11774
- const exit = yield* (timeout === void 0 ? asSome(awaited) : timeoutOption(awaited, timeout)).pipe(onInterrupt(() => interrupt$2(running.fiber)));
11775
- if (isNone(exit)) {
11776
- const timeoutMs = toMillis(timeout);
11777
- if (onTimeout === "stop") {
11778
- yield* interrupt$2(running.fiber);
11779
- return yield* die(new Error(`Command timed out after ${timeoutMs}ms`));
11780
- }
11781
- const id = yield* addJob(running);
11782
- const output = running.output();
11783
- return `${output}${output === "" || output.endsWith("\n") ? "" : "\n"}[Still running after ${timeoutMs}ms, so it was moved to the background as job ${id}. ${jobUsage(id)}]`;
11784
- }
11785
- const exitCode = yield* exit.value;
11786
- const output = running.output();
11787
- if (exitCode === 0) return output;
11788
- return yield* die(new Error(`Command failed with exit code ${exitCode}: ${output}`));
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;
11789
11772
  });
11790
11773
  const readImage = fnUntraced(function* (path, extensionType, options) {
11791
11774
  if (options.startLine !== void 0 || options.endLine !== void 0) return yield* die(new Error(`startLine / endLine are not supported for images: ${path}`));
@@ -11891,8 +11874,7 @@ const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(gen(function* () {
11891
11874
  return yield* promise(() => import("./index.min-ClUfQ5ji.mjs").then((Glob) => Glob.glob(pattern, { cwd })));
11892
11875
  }),
11893
11876
  bash: fn("AgentTools.bash")(function* (options) {
11894
- const limits = yield* CommandLimits;
11895
- const maxMs = toMillis(limits.timeout ?? defaultBashTimeout);
11877
+ const maxMs = bashTimeoutMs(yield* CommandLimits);
11896
11878
  const timeoutMs = Math.min(options.timeoutMs ?? maxMs, maxMs);
11897
11879
  yield* logInfo(`Calling "bash"`).pipe(annotateLogs({
11898
11880
  ...options,
@@ -11903,27 +11885,62 @@ const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(gen(function* () {
11903
11885
  cwd,
11904
11886
  stdin: "ignore"
11905
11887
  });
11906
- if (options.background === true) {
11907
- const id = yield* addJob(yield* startCommand(cmd));
11908
- return `Started background job ${id}. ${jobUsage(id)}`;
11888
+ const entry = yield* addBashTask(options.command, yield* startCommand(cmd));
11889
+ if (options.background !== true) {
11890
+ const exit = yield* awaitCommand(entry.command, millis(timeoutMs));
11891
+ if (isSome(exit)) {
11892
+ const exitCode = yield* exit.value;
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}`));
11896
+ }
11909
11897
  }
11910
- return yield* runCommand(cmd, millis(timeoutMs), "background");
11898
+ const task = reportBash(entry);
11899
+ if (task.status === "running") yield* watchBashTask(entry);
11900
+ return task;
11911
11901
  }, orDie),
11912
- jobOutput: fn("AgentTools.jobOutput")(function* (input) {
11913
- const id = yield* decodeJobOutput(input);
11914
- yield* logInfo(`Calling "jobOutput"`).pipe(annotateLogs({ id }));
11915
- const running = yield* findJob(id);
11916
- const job = jobInfo(id, running);
11917
- if (job.status !== "running") running.reported = true;
11918
- return job;
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);
11919
11908
  }),
11920
- stopJob: fn("AgentTools.stopJob")(function* (input) {
11921
- const id = yield* decodeStopJob(input);
11922
- yield* logInfo(`Calling "stopJob"`).pipe(annotateLogs({ id }));
11923
- const running = yield* findJob(id);
11924
- yield* interrupt$2(running.fiber);
11925
- running.reported = true;
11926
- return jobInfo(id, running);
11909
+ waitTasks: fn("AgentTools.waitTasks")(function* (input) {
11910
+ const { ids, timeoutMs: requestedMs } = yield* decodeWaitTasks(input);
11911
+ const maxMs = bashTimeoutMs(yield* CommandLimits);
11912
+ const timeoutMs = Math.min(requestedMs ?? maxMs, maxMs);
11913
+ yield* logInfo(`Calling "waitTasks"`).pipe(annotateLogs({
11914
+ ids,
11915
+ timeoutMs
11916
+ }));
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);
11937
+ }),
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));
11927
11944
  }),
11928
11945
  gh: fn("AgentTools.gh")(function* (args) {
11929
11946
  yield* logInfo(`Calling "gh"`).pipe(annotateLogs({ args }));
@@ -11933,7 +11950,16 @@ const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(gen(function* () {
11933
11950
  stdin: "ignore"
11934
11951
  });
11935
11952
  const { timeout } = yield* CommandLimits;
11936
- return yield* runCommand(cmd, timeout, "stop");
11953
+ const running = yield* startCommand(cmd);
11954
+ const exit = yield* awaitCommand(running, timeout);
11955
+ if (isNone(exit)) {
11956
+ yield* interrupt$2(running.fiber);
11957
+ return yield* die(new Error(`Command timed out after ${toMillis(timeout)}ms`));
11958
+ }
11959
+ const exitCode = yield* exit.value;
11960
+ const output = running.output();
11961
+ if (exitCode === 0) return output;
11962
+ return yield* die(new Error(`Command failed with exit code ${exitCode}: ${output}`));
11937
11963
  }, orDie),
11938
11964
  webSearch: fn("AgentTools.webSearch")(function* (options) {
11939
11965
  yield* logInfo(`Calling "webSearch"`).pipe(annotateLogs(options));
@@ -12038,29 +12064,19 @@ const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(gen(function* () {
12038
12064
  delegate: fn("AgentTools.delegate")(function* (options) {
12039
12065
  const { prompt, background = false } = yield* decodeDelegate(options);
12040
12066
  yield* logInfo(`Calling "delegate"`).pipe(annotateLogs({ background }));
12041
- return yield* (yield* SubagentExecutor).delegate({
12067
+ const id = yield* registerAgentTask();
12068
+ return yield* (yield* AgentTaskExecutor).delegate({
12069
+ id,
12042
12070
  prompt,
12043
12071
  background
12044
12072
  });
12045
12073
  }),
12046
- waitAgents: fn("AgentTools.waitAgents")(function* (input) {
12047
- const ids = yield* decodeWaitAgents(input);
12048
- yield* logInfo(`Calling "waitAgents"`).pipe(annotateLogs({ ids }));
12049
- return yield* (yield* SubagentExecutor).waitAgents(ids);
12050
- }),
12051
12074
  messageAgent: fn("AgentTools.messageAgent")(function* (input) {
12052
12075
  const options = yield* decodeMessageAgent(input);
12053
12076
  yield* logInfo(`Calling "messageAgent"`).pipe(annotateLogs({ id: options.id }));
12054
- return yield* (yield* SubagentExecutor).messageAgent(options);
12055
- }),
12056
- stopAgent: fn("AgentTools.stopAgent")(function* (input) {
12057
- const id = yield* decodeStopAgent(input);
12058
- yield* logInfo(`Calling "stopAgent"`).pipe(annotateLogs({ id }));
12059
- return yield* (yield* SubagentExecutor).stopAgent(id);
12060
- }),
12061
- listAgents: fn("AgentTools.listAgents")(function* () {
12062
- yield* logInfo(`Calling "listAgents"`);
12063
- 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);
12064
12080
  }),
12065
12081
  taskComplete: fn("AgentTools.taskComplete")(function* (message) {
12066
12082
  if (typeof message !== "string") return yield* fail$1("taskComplete requires a string argument. Pass your final output directly, for example: taskComplete(\"done\").");
@@ -12075,34 +12091,50 @@ const decodeParams$1 = (schema, usage) => {
12075
12091
  return (input) => mapError(decode(input), () => usage);
12076
12092
  };
12077
12093
  const decodeDelegate = decodeParams$1(AgentTools.tools.delegate.parametersSchema, "delegate requires an options object, for example: delegate({ prompt: \"...\" }) or delegate({ prompt: \"...\", background: true }).");
12078
- const decodeWaitAgents = decodeParams$1(AgentTools.tools.waitAgents.parametersSchema, "waitAgents takes an optional array of agent ids, for example: waitAgents([\"3\", \"4\"]).");
12079
12094
  const decodeMessageAgent = decodeParams$1(AgentTools.tools.messageAgent.parametersSchema, "messageAgent requires an options object, for example: messageAgent({ id: \"3\", message: \"...\" }).");
12080
- const decodeStopAgent = decodeParams$1(AgentTools.tools.stopAgent.parametersSchema, "stopAgent requires an agent id, for example: stopAgent(\"3\").");
12081
- const decodeJobOutput = decodeParams$1(AgentTools.tools.jobOutput.parametersSchema, "jobOutput requires a job id, for example: jobOutput(\"1\").");
12082
- const decodeStopJob = decodeParams$1(AgentTools.tools.stopJob.parametersSchema, "stopJob requires a job id, for example: stopJob(\"1\").");
12083
- const jobUsage = (id) => `Use jobOutput("${id}") for its status and output, or stopJob("${id}") to stop it.`;
12084
- const jobInfo = (id, running) => {
12085
- const exit = running.fiber.pollUnsafe();
12086
- const output = running.output();
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 }).");
12097
+ const bashTimeoutMs = (limits) => toMillis(limits.timeout ?? defaultBashTimeout);
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();
12087
12111
  if (exit === void 0) return {
12088
12112
  id,
12113
+ kind: "bash",
12089
12114
  status: "running",
12115
+ description,
12090
12116
  output
12091
12117
  };
12092
12118
  if (isSuccess(exit)) return {
12093
12119
  id,
12120
+ kind: "bash",
12094
12121
  status: exit.value === 0 ? "completed" : "failed",
12095
- exitCode: exit.value,
12096
- output
12122
+ description,
12123
+ output,
12124
+ exitCode: exit.value
12097
12125
  };
12098
12126
  if (hasInterruptsOnly(exit.cause)) return {
12099
12127
  id,
12128
+ kind: "bash",
12100
12129
  status: "stopped",
12130
+ description,
12101
12131
  output
12102
12132
  };
12103
12133
  return {
12104
12134
  id,
12135
+ kind: "bash",
12105
12136
  status: "failed",
12137
+ description,
12106
12138
  output: `${output}${output === "" ? "" : "\n"}${pretty(exit.cause)}`
12107
12139
  };
12108
12140
  };
@@ -14123,7 +14155,7 @@ var Capabilities = class extends Class$1("Capabilities")({
14123
14155
  environment: ExecutionEnvironment,
14124
14156
  tools: ArraySchema(String$7),
14125
14157
  skills: ArraySchema(Skill).pipe(withDecodingDefaultKey(succeed$1([])), withConstructorDefault(succeed$1([]))),
14126
- 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)))
14127
14159
  }) {};
14128
14160
  const makeLocal = (options) => map$5(makeLocalWith(options), (local) => local.executor);
14129
14161
  const makeLocalWith = fnUntraced(function* (options) {
@@ -14212,13 +14244,13 @@ const makeLocalWith = fnUntraced(function* (options) {
14212
14244
  currentDirectory = target;
14213
14245
  return onChange ? onChange(currentEnvironment()) : void_;
14214
14246
  }));
14215
- const taskServices = empty$5().pipe(add(TaskCompleter, opts.onTaskComplete), add(DirectoryChanger, changeDirectory), add(SubagentExecutor, {
14216
- ...opts.subagents,
14217
- 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({
14218
14250
  ...options,
14219
14251
  environment
14220
14252
  })))
14221
- }), 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);
14222
14254
  yield* gen(function* () {
14223
14255
  const source = prepareScript(opts.script);
14224
14256
  const settled = yield* make$42();
@@ -14304,7 +14336,7 @@ const makeLocalWith = fnUntraced(function* (options) {
14304
14336
  }),
14305
14337
  tools: Object.keys(tools.tools),
14306
14338
  skills,
14307
- jobPushes: true
14339
+ taskPushes: true
14308
14340
  });
14309
14341
  }),
14310
14342
  execute: (opts) => execute(opts),
@@ -14315,7 +14347,7 @@ const makeLocalWith = fnUntraced(function* (options) {
14315
14347
  const handler = services.mapUnsafe.get(tool.id);
14316
14348
  if (!handler) return die(new Error(`Unknown tool: ${opts.tool}`));
14317
14349
  const cwd = (opts.environment ?? startupEnvironment).cwd;
14318
- 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);
14319
14351
  const encodeSuccess = encodeUnknownEffect(toCodecJson(tool.successSchema));
14320
14352
  return pipe(handler.handler(opts.params, {}), flatMap$1(encodeSuccess), provideContext(taskServices), orDie);
14321
14353
  })
@@ -14334,7 +14366,8 @@ const makeRpc = gen(function* () {
14334
14366
  script: opts.script,
14335
14367
  environment: opts.environment,
14336
14368
  loopTools: Object.keys(opts.loopTools ?? {}),
14337
- ...opts.onJob === void 0 ? {} : { watchJobs: true }
14369
+ ...opts.agentId === void 0 ? {} : { agentId: opts.agentId },
14370
+ ...opts.onTask === void 0 ? {} : { watchTasks: true }
14338
14371
  }).pipe(tap$1((part) => {
14339
14372
  switch (part._tag) {
14340
14373
  case "Text": return void_;
@@ -14354,13 +14387,14 @@ const makeRpc = gen(function* () {
14354
14387
  case "Environment":
14355
14388
  latest = part.environment;
14356
14389
  return void_;
14357
- case "Job": {
14358
- if (opts.onJob === void 0) return void_;
14390
+ case "Task": {
14391
+ if (opts.onTask === void 0) return void_;
14359
14392
  const id = part.id;
14360
- return opts.onJob({
14393
+ return opts.onTask({
14361
14394
  id,
14362
- await: orDie(client.awaitJob({ id })),
14363
- claim: orDie(client.claimJob({ id }))
14395
+ kind: part.kind,
14396
+ await: orDie(client.awaitTask({ id })),
14397
+ claim: orDie(client.claimTask({ id }))
14364
14398
  });
14365
14399
  }
14366
14400
  }
@@ -14384,17 +14418,22 @@ const layerRpc = effect(AgentExecutor, makeRpc);
14384
14418
  const AgentRequest = TaggedUnion({
14385
14419
  TaskComplete: { summary: String$7 },
14386
14420
  Delegate: {
14421
+ id: String$7,
14387
14422
  prompt: String$7,
14388
14423
  background: Boolean$4,
14389
14424
  environment: EnvironmentUpdate
14390
14425
  },
14391
- WaitAgents: { ids: UndefinedOr(ArraySchema(String$7)) },
14426
+ TaskOutput: { id: String$7 },
14427
+ WaitTasks: {
14428
+ ids: ArraySchema(String$7),
14429
+ timeoutMs: Finite
14430
+ },
14392
14431
  MessageAgent: {
14393
14432
  id: String$7,
14394
14433
  message: String$7
14395
14434
  },
14396
- StopAgent: { id: String$7 },
14397
- ListAgents: {},
14435
+ StopTask: { id: String$7 },
14436
+ ListTasks: {},
14398
14437
  LoopTool: {
14399
14438
  name: String$7,
14400
14439
  params: optional$2(Json)
@@ -14417,7 +14456,10 @@ const ExecuteOutput = TaggedUnion({
14417
14456
  data: Uint8Array$2
14418
14457
  },
14419
14458
  Environment: { environment: ExecutionEnvironment },
14420
- Job: { id: String$7 }
14459
+ Task: {
14460
+ id: String$7,
14461
+ kind: TaskKind
14462
+ }
14421
14463
  });
14422
14464
  var Rpcs = class extends make$12(make$14("capabilities", { success: Capabilities }), make$14("respond", { payload: {
14423
14465
  id: Finite,
@@ -14427,15 +14469,16 @@ var Rpcs = class extends make$12(make$14("capabilities", { success: Capabilities
14427
14469
  script: String$7,
14428
14470
  environment: ExecutionEnvironment,
14429
14471
  loopTools: ArraySchema(String$7).pipe(withDecodingDefaultKey(succeed$1([]))),
14430
- watchJobs: optionalKey(Boolean$4)
14472
+ agentId: optionalKey(String$7),
14473
+ watchTasks: optionalKey(Boolean$4)
14431
14474
  }),
14432
14475
  success: ExecuteOutput,
14433
14476
  stream: true
14434
- }), make$14("awaitJob", {
14477
+ }), make$14("awaitTask", {
14435
14478
  payload: { id: String$7 },
14436
- success: BashJob,
14479
+ success: Task,
14437
14480
  error: String$7
14438
- }), make$14("claimJob", {
14481
+ }), make$14("claimTask", {
14439
14482
  payload: { id: String$7 },
14440
14483
  success: Boolean$4,
14441
14484
  error: String$7
@@ -14477,11 +14520,12 @@ const encodeRpcParams = (tool, params) => {
14477
14520
  const handleRequest = (opts, request) => {
14478
14521
  switch (request._tag) {
14479
14522
  case "TaskComplete": return opts.onTaskComplete(request.summary);
14480
- case "Delegate": return opts.subagents.delegate(request);
14481
- case "WaitAgents": return opts.subagents.waitAgents(request.ids);
14482
- case "MessageAgent": return opts.subagents.messageAgent(request);
14483
- case "StopAgent": return opts.subagents.stopAgent(request.id);
14484
- 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;
14485
14529
  case "EnvironmentChanged": return void_;
14486
14530
  case "LoopTool": {
14487
14531
  const handler = opts.loopTools?.[request.name];
@@ -14503,15 +14547,14 @@ const exitToResponse = (exit) => {
14503
14547
  const errorMessage$2 = (error) => typeof error === "string" ? error : error instanceof Error ? error.message : String(error);
14504
14548
  const excludedToolNames = (excludeTools) => {
14505
14549
  const names = new Set(excludeTools);
14506
- if (names.has("delegate")) for (const name of [
14507
- "waitAgents",
14508
- "messageAgent",
14509
- "stopAgent",
14510
- "listAgents"
14511
- ]) names.add(name);
14512
- if (names.has("bash")) {
14513
- names.add("jobOutput");
14514
- 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);
14515
14558
  }
14516
14559
  return names;
14517
14560
  };
@@ -20565,13 +20608,13 @@ const makeWith$1 = fnUntraced(function* (options) {
20565
20608
  mcpServers?.dts ?? ""
20566
20609
  ].filter((dts) => dts !== "").join("\n\n"),
20567
20610
  offers: (name) => capabilities.tools.includes(name),
20568
- jobPushes: capabilities.jobPushes,
20611
+ taskPushes: capabilities.taskPushes,
20569
20612
  skillsCatalog: options.skills === void 0 ? renderCatalog(capabilities.skills) : renderProvidedCatalog(options.skills),
20570
20613
  mcp: mcpServers?.prompt ?? ""
20571
20614
  };
20572
20615
  const rootMailbox = makeMailbox();
20573
20616
  const agentsMd = options.instructions === void 0 ? capabilities.instructions : map$8(options.instructions, renderInstructions);
20574
- let agentCounter = 0;
20617
+ const rootTaskOwner = crypto.randomUUID();
20575
20618
  const outputBuffer = new Map();
20576
20619
  let currentOutputAgent = null;
20577
20620
  const history = make$46(empty$1);
@@ -20603,11 +20646,11 @@ const makeWith$1 = fnUntraced(function* (options) {
20603
20646
  let cacheWrite = 0;
20604
20647
  const prompt = opts.history;
20605
20648
  const mailbox = opts.mailbox;
20606
- const onJob = (job) => job.await.pipe(flatMap$1((final) => sync(() => {
20649
+ const onTask = (task) => task.await.pipe(flatMap$1((final) => sync(() => {
20607
20650
  if (final.status === "running") return;
20608
- mailbox.jobs.push({
20609
- job: final,
20610
- claim: job.claim
20651
+ mailbox.tasks.push({
20652
+ task: final,
20653
+ claim: task.claim
20611
20654
  });
20612
20655
  const event = new JobComplete({
20613
20656
  id: final.id,
@@ -20637,6 +20680,7 @@ const makeWith$1 = fnUntraced(function* (options) {
20637
20680
  agentsMd: getOrElse(agentsMd, () => "")
20638
20681
  });
20639
20682
  if (typeof opts.system === "string") system += `\n${opts.system}\n`;
20683
+ console.log("system:", system);
20640
20684
  function maybeSend(options) {
20641
20685
  if (!opts.display) {
20642
20686
  offerUnsafe(output, options.part);
@@ -20682,22 +20726,25 @@ const makeWith$1 = fnUntraced(function* (options) {
20682
20726
  };
20683
20727
  mailbox.notify = notify;
20684
20728
  const runningChildren = () => Array$1.from(children.values()).filter((child) => child.turn.status === "running");
20685
- const hasUndelivered = () => completions.some((turn) => !turn.delivered);
20686
- const finishTurn = (turn, exit) => sync(() => {
20729
+ const hasUndelivered = () => completions.some(({ turn }) => !turn.reported);
20730
+ const finishTurn = (child, turn, exit) => sync(() => {
20687
20731
  if (isSuccess(exit)) {
20688
20732
  turn.status = "completed";
20689
20733
  turn.output = exit.value;
20690
- } else if (hasInterruptsOnly(exit.cause)) turn.status = "cancelled";
20734
+ } else if (hasInterruptsOnly(exit.cause)) turn.status = "stopped";
20691
20735
  else {
20692
20736
  turn.status = "failed";
20693
20737
  turn.output = causeMessage(exit.cause);
20694
20738
  }
20695
20739
  offerUnsafe(output, new SubagentComplete({
20696
- id: turn.agentId,
20740
+ id: child.id,
20697
20741
  summary: turn.output ?? "",
20698
- status: turn.status
20742
+ status: turn.status === "stopped" ? "cancelled" : turn.status
20699
20743
  }));
20700
- if (!turn.delivered) completions.push(turn);
20744
+ if (!turn.reported) completions.push({
20745
+ child,
20746
+ turn
20747
+ });
20701
20748
  doneUnsafe(turn.done, void_);
20702
20749
  notify();
20703
20750
  });
@@ -20707,6 +20754,7 @@ const makeWith$1 = fnUntraced(function* (options) {
20707
20754
  const display = opts.display && !options.background;
20708
20755
  const stream = spawn({
20709
20756
  agentId: child.id,
20757
+ taskOwner: child.taskOwner,
20710
20758
  prompt: make$21(options.prompt),
20711
20759
  environmentUpdate: options.environmentUpdate,
20712
20760
  system: opts.system,
@@ -20746,32 +20794,34 @@ const makeWith$1 = fnUntraced(function* (options) {
20746
20794
  }
20747
20795
  return void_;
20748
20796
  }), as(""), catchTag("AgentFinished", (finished) => succeed$1(finished.summary)));
20749
- }).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 }));
20750
20798
  });
20751
- const childResult = ({ id, turn }) => turn.output === void 0 ? {
20752
- id: String(id),
20753
- status: turn.status
20754
- } : {
20799
+ const childTask = ({ id, prompt, turn }) => ({
20755
20800
  id: String(id),
20801
+ kind: "agent",
20756
20802
  status: turn.status,
20757
- 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);
20758
20809
  };
20759
20810
  const lookupChild = (id) => suspend(() => {
20760
20811
  const child = children.get(id);
20761
- 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.`);
20762
20813
  });
20763
- const subagents = {
20764
- delegate: fnUntraced(function* ({ prompt, background, environment }) {
20765
- const agentId = agentCounter++;
20814
+ const agentTasks = {
20815
+ delegate: fnUntraced(function* ({ id, prompt, background, environment }) {
20766
20816
  const child = {
20767
- id: agentId,
20817
+ id: Number(id),
20818
+ taskOwner: crypto.randomUUID(),
20768
20819
  prompt,
20769
20820
  history: make$46(empty$1),
20770
20821
  environment: make$46(environment.environment),
20771
20822
  mailbox: makeMailbox(),
20772
- turn: makeTurn(agentId, background)
20823
+ turn: makeTurn(background)
20773
20824
  };
20774
- const id = String(child.id);
20775
20825
  children.set(id, child);
20776
20826
  const turn = child.turn;
20777
20827
  yield* startTurn({
@@ -20783,29 +20833,22 @@ ${prompt}`,
20783
20833
  environmentUpdate: getOrUndefined(environment.update),
20784
20834
  background
20785
20835
  });
20786
- if (background) return {
20787
- id,
20788
- status: "running"
20789
- };
20836
+ if (background) return childTask(child);
20790
20837
  yield* _await(turn.done).pipe(onInterrupt(() => interrupt$2(turn.fiber)));
20791
20838
  if (turn.status !== "completed") return yield* die(new Error(`Sub-agent ${child.id} ${turn.status}${turn.output ? `: ${turn.output}` : ""}`));
20792
- return {
20793
- id,
20794
- status: "completed",
20795
- output: turn.output ?? ""
20796
- };
20839
+ return childTask(child);
20797
20840
  }),
20798
- waitAgents: fnUntraced(function* (ids) {
20799
- const targets = ids === void 0 ? Array$1.from(children.values()) : yield* forEach$1(ids, lookupChild);
20800
- while (true) {
20801
- const running = targets.find((child) => child.turn.status === "running");
20802
- if (!running) break;
20803
- yield* _await(running.turn.done);
20804
- }
20805
- return targets.map((child) => {
20806
- child.turn.delivered = true;
20807
- return childResult(child);
20808
- });
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);
20809
20852
  }),
20810
20853
  messageAgent: fnUntraced(function* ({ id, message }) {
20811
20854
  const child = yield* lookupChild(id);
@@ -20815,35 +20858,32 @@ ${prompt}`,
20815
20858
  resume: () => {}
20816
20859
  });
20817
20860
  child.mailbox.notify();
20818
- return childResult(child);
20861
+ return childTask(child);
20819
20862
  }
20820
- child.turn = makeTurn(child.id, true);
20863
+ child.turn = makeTurn(true);
20821
20864
  yield* startTurn({
20822
20865
  child,
20823
20866
  prompt: message,
20824
20867
  label: message,
20825
20868
  background: true
20826
20869
  });
20827
- return childResult(child);
20870
+ return childTask(child);
20828
20871
  }),
20829
- stopAgent: fnUntraced(function* (id) {
20872
+ stopTask: fnUntraced(function* (id) {
20830
20873
  const child = yield* lookupChild(id);
20831
20874
  const turn = child.turn;
20832
- turn.delivered = true;
20875
+ turn.reported = true;
20833
20876
  if (turn.status === "running") yield* interrupt$2(turn.fiber);
20834
- return childResult(child);
20877
+ return childTask(child);
20835
20878
  }),
20836
- listAgents: sync(() => Array$1.from(children.values(), (child) => ({
20837
- id: String(child.id),
20838
- status: child.turn.status,
20839
- prompt: child.prompt
20840
- })))
20879
+ listTasks: sync(() => Array$1.from(children.values(), childTask))
20841
20880
  };
20842
20881
  const onTaskComplete = (summary) => suspend(() => {
20843
20882
  const running = runningChildren();
20844
20883
  if (running.length > 0) {
20845
- const ids = running.map((child) => JSON.stringify(String(child.id)));
20846
- 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.`);
20847
20887
  }
20848
20888
  finalSummary = some(summary);
20849
20889
  return void_;
@@ -20945,10 +20985,11 @@ ${prompt}`,
20945
20985
  onEnvironment: (environment) => sync(() => {
20946
20986
  set$1(opts.environment, environment);
20947
20987
  }),
20948
- subagents,
20988
+ agentId: opts.taskOwner,
20989
+ agentTasks,
20949
20990
  onTaskComplete,
20950
20991
  onImage,
20951
- onJob,
20992
+ onTask,
20952
20993
  loopTools: scriptLoopTools
20953
20994
  }), mkString);
20954
20995
  const capped = capOutput(output);
@@ -21007,25 +21048,21 @@ ${prompt}`,
21007
21048
  })));
21008
21049
  mailbox.messages.clear();
21009
21050
  }
21010
- if (completions.length > 0) {
21011
- const pushes = completions.splice(0).filter((turn) => {
21012
- if (turn.delivered) return false;
21013
- turn.delivered = true;
21014
- return true;
21015
- });
21016
- if (pushes.length > 0) appendHistory(make$21(pushes.map((turn) => ({
21017
- role: "user",
21018
- content: `<subagent id="${turn.agentId}" status="${turn.status}">
21019
- ${capOutput(turn.output ?? "").output}
21020
- </subagent>`
21021
- }))));
21022
- }
21023
- if (mailbox.jobs.length > 0) {
21051
+ if (completions.length > 0 || mailbox.tasks.length > 0) {
21024
21052
  const pushes = [];
21025
- for (const { job, claim } of mailbox.jobs.splice(0)) if (yield* claim) pushes.push(job);
21026
- 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) => ({
21027
21064
  role: "user",
21028
- content: jobMessage(job)
21065
+ content: taskMessage(task)
21029
21066
  }))));
21030
21067
  }
21031
21068
  yield* compactWithEvents("threshold", compactIfNeeded({
@@ -21230,7 +21267,8 @@ ${capOutput(turn.output ?? "").output}
21230
21267
  history,
21231
21268
  environment,
21232
21269
  send: (options) => spawn({
21233
- agentId: agentCounter++,
21270
+ agentId: 0,
21271
+ taskOwner: rootTaskOwner,
21234
21272
  prompt: make$21(options.prompt),
21235
21273
  system: options.system,
21236
21274
  history,
@@ -21257,21 +21295,20 @@ const make$8 = makeWith$1({});
21257
21295
  const makeMailbox = () => ({
21258
21296
  messages: new Set(),
21259
21297
  notify: () => {},
21260
- jobs: [],
21298
+ tasks: [],
21261
21299
  emit: void 0,
21262
21300
  events: []
21263
21301
  });
21264
- const jobMessage = (job) => {
21265
- const exitCode = job.exitCode === void 0 ? "" : ` exitCode="${job.exitCode}"`;
21266
- return `<job id="${job.id}" status="${job.status}"${exitCode}>
21267
- ${capOutput(job.output).output}
21268
- </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>`;
21269
21307
  };
21270
- const makeTurn = (agentId, background) => ({
21271
- agentId,
21308
+ const makeTurn = (background) => ({
21272
21309
  status: "running",
21273
21310
  output: void 0,
21274
- delivered: !background,
21311
+ reported: !background,
21275
21312
  done: makeUnsafe$1(),
21276
21313
  fiber: void 0
21277
21314
  });
@@ -21294,7 +21331,7 @@ const environmentUpdateMessage = (text) => make$21([{
21294
21331
  }]);
21295
21332
  const startsWith = (message, prefix) => message.role === "user" && message.content.length === 1 && message.content[0].type === "text" && message.content[0].text.trimStart().startsWith(prefix);
21296
21333
  const isEnvironmentUpdate = (message) => startsWith(message, environmentUpdateOpen);
21297
- const isInjectedMessage = (message) => isEnvironmentUpdate(message) || startsWith(message, "<subagent ");
21334
+ const isInjectedMessage = (message) => isEnvironmentUpdate(message) || startsWith(message, "<task ") || startsWith(message, "<subagent ") || startsWith(message, "<job ");
21298
21335
  const renderInstructions = (content) => `# Project instructions
21299
21336
 
21300
21337
  **ALWAYS follow these instructions when completing tasks**:
@@ -21309,6 +21346,19 @@ ${options.toolInstructions}
21309
21346
  ${options.agentsMd}
21310
21347
  `;
21311
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
+ };
21312
21362
  const generateSystemTools = (tools, conversationMode) => `YOU ONLY HAVE ONE TOOL AVAILABLE: "execute", to run javascript code to do your work.
21313
21363
 
21314
21364
  - Use \`console.log\` to print any output you need.
@@ -21316,11 +21366,10 @@ const generateSystemTools = (tools, conversationMode) => `YOU ONLY HAVE ONE TOOL
21316
21366
  - Use top level await.${when(tools.offers("search") && tools.offers("rg"), `
21317
21367
  - Prefer using the "search" function over "rg", unless you are targeting specific files or patterns.`)}${when(tools.offers("applyPatch"), `
21318
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"), `
21319
- - Avoid passing scripts into the "bash" function, and instead write javascript.
21320
- - 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.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.`)}
21321
21370
  - Variables are not shared between executions.
21322
21371
  - Do not use \`require\`, \`import\`, \`process\`, or any other Node.js apis.${when(tools.offers("delegate"), `
21323
- - "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, `
21324
21373
 
21325
21374
  When you have fully completed your task, call the "taskComplete" function with the final output.
21326
21375
  Make sure every detail of the task is done before calling "taskComplete".${when(tools.offers("delegate"), `
@@ -28463,7 +28512,7 @@ const transformToolCallParams$1 = fnUntraced(function* (options, toolName, toolP
28463
28512
  return yield* decodeEffect(codec)(toolParams).pipe(flatMap$1((decoded) => encodeUnknownEffect(tool.parametersSchema)(decoded)), orElseSucceed(() => toolParams));
28464
28513
  });
28465
28514
  // package.json
28466
- var version$1 = "0.20.0";
28515
+ var version$1 = "0.22.0";
28467
28516
  // src/ClaudeAgent.ts
28468
28517
  const minimumClaudeCodeVersion = "2.1.248";
28469
28518
  const serverName = "clanka";