clanka 0.8.6 → 0.10.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 (96) hide show
  1. package/dist/Acp.d.ts +6 -1
  2. package/dist/Acp.d.ts.map +1 -1
  3. package/dist/Acp.js +34 -3
  4. package/dist/Acp.js.map +1 -1
  5. package/dist/Acp.test.js +178 -2
  6. package/dist/Acp.test.js.map +1 -1
  7. package/dist/AcpImage.test.js +7 -1
  8. package/dist/AcpImage.test.js.map +1 -1
  9. package/dist/Agent.d.ts +82 -8
  10. package/dist/Agent.d.ts.map +1 -1
  11. package/dist/Agent.js +556 -113
  12. package/dist/Agent.js.map +1 -1
  13. package/dist/Agent.test.js +86 -5
  14. package/dist/Agent.test.js.map +1 -1
  15. package/dist/AgentCallerConfig.test.d.ts +2 -0
  16. package/dist/AgentCallerConfig.test.d.ts.map +1 -0
  17. package/dist/AgentCallerConfig.test.js +335 -0
  18. package/dist/AgentCallerConfig.test.js.map +1 -0
  19. package/dist/AgentEnvironment.d.ts +76 -0
  20. package/dist/AgentEnvironment.d.ts.map +1 -0
  21. package/dist/AgentEnvironment.js +119 -0
  22. package/dist/AgentEnvironment.js.map +1 -0
  23. package/dist/AgentEnvironment.test.d.ts +2 -0
  24. package/dist/AgentEnvironment.test.d.ts.map +1 -0
  25. package/dist/AgentEnvironment.test.js +304 -0
  26. package/dist/AgentEnvironment.test.js.map +1 -0
  27. package/dist/AgentExecutor.d.ts +342 -183
  28. package/dist/AgentExecutor.d.ts.map +1 -1
  29. package/dist/AgentExecutor.js +607 -127
  30. package/dist/AgentExecutor.js.map +1 -1
  31. package/dist/AgentExecutor.test.js +287 -31
  32. package/dist/AgentExecutor.test.js.map +1 -1
  33. package/dist/AgentExecutorImage.test.js +5 -1
  34. package/dist/AgentExecutorImage.test.js.map +1 -1
  35. package/dist/AgentImage.test.js +15 -2
  36. package/dist/AgentImage.test.js.map +1 -1
  37. package/dist/AgentOutput.d.ts +70 -5
  38. package/dist/AgentOutput.d.ts.map +1 -1
  39. package/dist/AgentOutput.js +65 -0
  40. package/dist/AgentOutput.js.map +1 -1
  41. package/dist/AgentSkills.d.ts +37 -0
  42. package/dist/AgentSkills.d.ts.map +1 -1
  43. package/dist/AgentSkills.js +96 -32
  44. package/dist/AgentSkills.js.map +1 -1
  45. package/dist/AgentSkills.test.js +14 -2
  46. package/dist/AgentSkills.test.js.map +1 -1
  47. package/dist/AgentSubagents.test.d.ts +2 -0
  48. package/dist/AgentSubagents.test.d.ts.map +1 -0
  49. package/dist/AgentSubagents.test.js +494 -0
  50. package/dist/AgentSubagents.test.js.map +1 -0
  51. package/dist/AgentTools.d.ts +356 -14
  52. package/dist/AgentTools.d.ts.map +1 -1
  53. package/dist/AgentTools.js +214 -35
  54. package/dist/AgentTools.js.map +1 -1
  55. package/dist/OutputFormatter.d.ts.map +1 -1
  56. package/dist/OutputFormatter.js +19 -2
  57. package/dist/OutputFormatter.js.map +1 -1
  58. package/dist/ToolkitRenderer.d.ts.map +1 -1
  59. package/dist/ToolkitRenderer.js +6 -1
  60. package/dist/ToolkitRenderer.js.map +1 -1
  61. package/dist/bin/{Effect-rADALOOD.mjs → Effect-2jPlJ8eu.mjs} +43 -38
  62. package/dist/bin/Effect-2jPlJ8eu.mjs.map +1 -0
  63. package/dist/bin/{McpClient-NazR2OwL.mjs → McpClient-1W508adc.mjs} +3 -3
  64. package/dist/bin/{McpClient-NazR2OwL.mjs.map → McpClient-1W508adc.mjs.map} +1 -1
  65. package/dist/bin/{OutputFormatter-BVHbgF2b.mjs → OutputFormatter-BFAv48k9.mjs} +17 -5
  66. package/dist/bin/{OutputFormatter-BVHbgF2b.mjs.map → OutputFormatter-BFAv48k9.mjs.map} +1 -1
  67. package/dist/bin/{Schema-C7NXAOWA.mjs → Schema-D-7VuCiC.mjs} +2 -2
  68. package/dist/bin/{Schema-C7NXAOWA.mjs.map → Schema-D-7VuCiC.mjs.map} +1 -1
  69. package/dist/bin/{SemanticSearch-4Jes3jCl.mjs → SemanticSearch-Cb8aqvGv.mjs} +4 -4
  70. package/dist/bin/{SemanticSearch-4Jes3jCl.mjs.map → SemanticSearch-Cb8aqvGv.mjs.map} +1 -1
  71. package/dist/bin/{Stream-CSLA1_GD.mjs → Stream-DEu2tfCV.mjs} +12 -3
  72. package/dist/bin/Stream-DEu2tfCV.mjs.map +1 -0
  73. package/dist/bin/cli.mjs +13333 -12470
  74. package/dist/bin/cli.mjs.map +1 -1
  75. package/package.json +1 -1
  76. package/src/Acp.test.ts +279 -3
  77. package/src/Acp.ts +34 -4
  78. package/src/AcpImage.test.ts +7 -1
  79. package/src/Agent.test.ts +109 -4
  80. package/src/Agent.ts +874 -140
  81. package/src/AgentCallerConfig.test.ts +522 -0
  82. package/src/AgentEnvironment.test.ts +504 -0
  83. package/src/AgentEnvironment.ts +161 -0
  84. package/src/AgentExecutor.test.ts +414 -37
  85. package/src/AgentExecutor.ts +1028 -191
  86. package/src/AgentExecutorImage.test.ts +5 -1
  87. package/src/AgentImage.test.ts +21 -3
  88. package/src/AgentOutput.ts +91 -1
  89. package/src/AgentSkills.test.ts +14 -2
  90. package/src/AgentSkills.ts +117 -34
  91. package/src/AgentSubagents.test.ts +824 -0
  92. package/src/AgentTools.ts +377 -53
  93. package/src/OutputFormatter.ts +19 -2
  94. package/src/ToolkitRenderer.ts +7 -1
  95. package/dist/bin/Effect-rADALOOD.mjs.map +0 -1
  96. package/dist/bin/Stream-CSLA1_GD.mjs.map +0 -1
package/src/AgentTools.ts CHANGED
@@ -7,6 +7,7 @@ import * as ExaSearch from "./ExaSearch.ts"
7
7
  import * as WebToMarkdown from "./WebToMarkdown.ts"
8
8
  import type * as HttpClient from "effect/http/HttpClient"
9
9
  import * as Context from "effect/Context"
10
+ import * as Duration from "effect/Duration"
10
11
  import * as Effect from "effect/Effect"
11
12
  import * as Toolkit from "effect/ai/Toolkit"
12
13
  import * as Tool from "effect/ai/Tool"
@@ -48,18 +49,134 @@ export class DirectoryChanger extends Context.Service<
48
49
  */
49
50
  export class TaskCompleter extends Context.Service<
50
51
  TaskCompleter,
51
- (output: string) => Effect.Effect<void>
52
+ (output: string) => Effect.Effect<void, string>
52
53
  >()("clanka/AgentTools/TaskCompleter") {}
53
54
 
55
+ /**
56
+ * @since 1.0.0
57
+ * @category Models
58
+ */
59
+ export const SubagentStatus = Schema.Literals([
60
+ "completed",
61
+ "running",
62
+ "failed",
63
+ "cancelled",
64
+ ])
65
+
66
+ /**
67
+ * @since 1.0.0
68
+ * @category Models
69
+ */
70
+ export type SubagentStatus = typeof SubagentStatus.Type
71
+
72
+ /**
73
+ * @since 1.0.0
74
+ * @category Models
75
+ */
76
+ export const SubagentResult = Schema.Struct({
77
+ id: Schema.String,
78
+ status: SubagentStatus,
79
+ output: Schema.optional(Schema.String),
80
+ })
81
+
82
+ /**
83
+ * @since 1.0.0
84
+ * @category Models
85
+ */
86
+ export type SubagentResult = typeof SubagentResult.Type
87
+
88
+ /**
89
+ * @since 1.0.0
90
+ * @category Models
91
+ */
92
+ export const DelegateResult = Schema.Struct({
93
+ ...SubagentResult.fields,
94
+ status: Schema.Literals(["completed", "running"]),
95
+ })
96
+
97
+ /**
98
+ * @since 1.0.0
99
+ * @category Models
100
+ */
101
+ export type DelegateResult = typeof DelegateResult.Type
102
+
103
+ /**
104
+ * @since 1.0.0
105
+ * @category Models
106
+ */
107
+ export const SubagentInfo = Schema.Struct({
108
+ id: Schema.String,
109
+ status: SubagentStatus,
110
+ prompt: Schema.String,
111
+ })
112
+
113
+ /**
114
+ * @since 1.0.0
115
+ * @category Models
116
+ */
117
+ export type SubagentInfo = typeof SubagentInfo.Type
118
+
119
+ /**
120
+ * Manages the sub-agents of one agent. Every function only sees the agents
121
+ * spawned by that agent.
122
+ *
123
+ * @since 1.0.0
124
+ * @category Models
125
+ */
126
+ export interface Subagents {
127
+ /**
128
+ * Start a sub-agent. In the foreground it resolves once the agent has
129
+ * finished, and dies if the agent failed. In the background it resolves
130
+ * straight away with `status: "running"`.
131
+ */
132
+ readonly delegate: (options: {
133
+ readonly prompt: string
134
+ readonly background: boolean
135
+ }) => Effect.Effect<DelegateResult>
136
+ /**
137
+ * Wait for the listed agents, or all of them when `ids` is undefined.
138
+ * Failures are returned as results, not raised.
139
+ */
140
+ readonly waitAgents: (
141
+ ids: ReadonlyArray<string> | undefined,
142
+ ) => Effect.Effect<ReadonlyArray<SubagentResult>, string>
143
+ /**
144
+ * Steer a running agent, or start a new turn on a finished one.
145
+ */
146
+ readonly messageAgent: (options: {
147
+ readonly id: string
148
+ readonly message: string
149
+ }) => Effect.Effect<SubagentResult, string>
150
+ /**
151
+ * Interrupt an agent and everything it spawned.
152
+ */
153
+ readonly stopAgent: (id: string) => Effect.Effect<SubagentResult, string>
154
+ readonly listAgents: Effect.Effect<ReadonlyArray<SubagentInfo>>
155
+ }
156
+
54
157
  /**
55
158
  * @since 1.0.0
56
159
  * @category Context
57
160
  */
58
161
  export class SubagentExecutor extends Context.Service<
59
162
  SubagentExecutor,
60
- (prompt: string) => Effect.Effect<string>
163
+ Subagents
61
164
  >()("clanka/AgentTools/SubagentExecutor") {}
62
165
 
166
+ /**
167
+ * A `Subagents` implementation for contexts that cannot spawn agents.
168
+ *
169
+ * @since 1.0.0
170
+ * @category Context
171
+ */
172
+ export const subagentsUnavailable: Subagents = {
173
+ delegate: () => Effect.die(new Error("Sub-agents are not available here")),
174
+ waitAgents: () => Effect.fail("Sub-agents are not available here"),
175
+ messageAgent: () => Effect.fail("Sub-agents are not available here"),
176
+ stopAgent: () => Effect.fail("Sub-agents are not available here"),
177
+ listAgents: Effect.succeed([]),
178
+ }
179
+
63
180
  /**
64
181
  * An image read by `readFile`, handed to the Agent so it can be spliced onto
65
182
  * the Prompt for the next model turn.
@@ -82,6 +199,57 @@ export class ImageAttacher extends Context.Service<
82
199
  (image: ImageAttachment) => Effect.Effect<void>
83
200
  >()("clanka/AgentTools/ImageAttacher") {}
84
201
 
202
+ /**
203
+ * The `bash` timeout when the caller sets none.
204
+ *
205
+ * @since 1.0.0
206
+ * @category Context
207
+ */
208
+ export const defaultBashTimeout: Duration.Duration = Duration.minutes(10)
209
+
210
+ /**
211
+ * The limits the `bash` and `gh` handlers apply to a single command. The
212
+ * executor sets them from its `limits` option.
213
+ *
214
+ * @since 1.0.0
215
+ * @category Context
216
+ */
217
+ export class CommandLimits extends Context.Reference<{
218
+ /**
219
+ * The longest a `bash` or `gh` command may run, as set by the caller.
220
+ * Unset, `bash` uses `defaultBashTimeout` and `gh` has no limit.
221
+ */
222
+ readonly timeout: Duration.Duration | undefined
223
+ /** The most characters of output held per command. */
224
+ readonly outputChars: number | undefined
225
+ }>("clanka/AgentTools/CommandLimits", {
226
+ defaultValue: () => ({
227
+ timeout: undefined,
228
+ outputChars: undefined,
229
+ }),
230
+ }) {}
231
+
232
+ /**
233
+ * The `bash` tool, with a description that states the timeout that applies.
234
+ *
235
+ * @since 1.0.0
236
+ * @category Toolkit
237
+ */
238
+ export const makeBashTool = (timeout: Duration.Duration) =>
239
+ Tool.make("bash", {
240
+ description: "Run a bash command and return the output",
241
+ parameters: Schema.Struct({
242
+ command: Schema.String,
243
+ timeoutMs: Schema.optional(Schema.Finite).annotate({
244
+ documentation: `Timeout in ms (default and max: ${Duration.toMillis(timeout)})`,
245
+ }),
246
+ }).annotate({
247
+ identifier: "command",
248
+ }),
249
+ success: Schema.String,
250
+ dependencies: [CurrentDirectory],
251
+ })
252
+
85
253
  const globNamesDirectory = (glob: string) =>
86
254
  glob
87
255
  .split("/")
@@ -93,7 +261,7 @@ const globNamesDirectory = (glob: string) =>
93
261
  * @category Context
94
262
  */
95
263
  export const makeContextNoop = (cwd?: string) =>
96
- SubagentExecutor.context(() => Effect.die("Not implemented")).pipe(
264
+ SubagentExecutor.context(subagentsUnavailable).pipe(
97
265
  Context.add(CurrentDirectory, cwd ?? "/"),
98
266
  Context.add(DirectoryChanger, () => Effect.die("Not implemented")),
99
267
  Context.add(TaskCompleter, () => Effect.void),
@@ -107,7 +275,7 @@ export const makeContextNoop = (cwd?: string) =>
107
275
  export const AgentTools = Toolkit.make(
108
276
  Tool.make("changeDirectory", {
109
277
  description:
110
- "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 scripts and is shared with delegates using this executor. Startup AGENTS.md, skills, and the semantic-search index root remain fixed. Navigation does not survive a session reload.",
278
+ "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.",
111
279
  parameters: Schema.String.annotate({ identifier: "directory" }),
112
280
  success: Schema.String,
113
281
  dependencies: [DirectoryChanger],
@@ -143,11 +311,51 @@ export const AgentTools = Toolkit.make(
143
311
  }),
144
312
  Tool.make("delegate", {
145
313
  description:
146
- "Delegate a task to another software engineer / sub-agent. Returns the result of the task.",
314
+ '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.',
315
+ parameters: Schema.Struct({
316
+ prompt: Schema.String,
317
+ background: Schema.optional(Schema.Boolean),
318
+ }),
319
+ success: DelegateResult,
320
+ failure: Schema.String,
321
+ dependencies: [SubagentExecutor],
322
+ }),
323
+ Tool.make("waitAgents", {
324
+ description:
325
+ '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.',
326
+ parameters: Schema.UndefinedOr(Schema.Array(Schema.String)).annotate({
327
+ identifier: "ids",
328
+ }),
329
+ success: Schema.Array(SubagentResult),
330
+ failure: Schema.String,
331
+ dependencies: [SubagentExecutor],
332
+ }),
333
+ Tool.make("messageAgent", {
334
+ description:
335
+ "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.",
336
+ parameters: Schema.Struct({
337
+ id: Schema.String,
338
+ message: Schema.String,
339
+ }),
340
+ success: SubagentResult,
341
+ failure: Schema.String,
342
+ dependencies: [SubagentExecutor],
343
+ }),
344
+ Tool.make("stopAgent", {
345
+ description:
346
+ "Stop one of your sub-agents and every agent it started. Returns its final status.",
147
347
  parameters: Schema.String.annotate({
148
- identifier: "task",
348
+ identifier: "id",
149
349
  }),
150
- success: Schema.String,
350
+ success: SubagentResult,
351
+ failure: Schema.String,
352
+ dependencies: [SubagentExecutor],
353
+ }),
354
+ Tool.make("listAgents", {
355
+ description:
356
+ "List the sub-agents you have started in this run, with their status.",
357
+ parameters: Schema.Void,
358
+ success: Schema.Array(SubagentInfo),
151
359
  dependencies: [SubagentExecutor],
152
360
  }),
153
361
  Tool.make("glob", {
@@ -167,19 +375,7 @@ export const AgentTools = Toolkit.make(
167
375
  success: Schema.String,
168
376
  dependencies: [CurrentDirectory],
169
377
  }),
170
- Tool.make("bash", {
171
- description: "Run a bash command and return the output",
172
- parameters: Schema.Struct({
173
- command: Schema.String,
174
- timeoutMs: Schema.optional(Schema.Finite).annotate({
175
- documentation: "Timeout in ms (default: 120000, max 4 minutes)",
176
- }),
177
- }).annotate({
178
- identifier: "command",
179
- }),
180
- success: Schema.String,
181
- dependencies: [CurrentDirectory],
182
- }),
378
+ makeBashTool(defaultBashTimeout),
183
379
  Tool.make("applyPatch", {
184
380
  description:
185
381
  "Add, update or remove multiple files with a git diff / unified diff / wrapped patch.",
@@ -191,7 +387,7 @@ export const AgentTools = Toolkit.make(
191
387
  }),
192
388
  Tool.make("writeFile", {
193
389
  description:
194
- "Write content to a file, creating parent directories if needed. Prefer applyPatch to update existing files.",
390
+ "Write content to a file, creating parent directories if needed.",
195
391
  parameters: Schema.Struct({
196
392
  path: Schema.String,
197
393
  content: Schema.String,
@@ -269,6 +465,17 @@ const SearchTool = Toolkit.make(
269
465
  */
270
466
  export const AgentToolsWithSearch = Toolkit.merge(SearchTool, AgentTools)
271
467
 
468
+ /**
469
+ * A built-in tool a caller can leave out. `taskComplete` always stays.
470
+ *
471
+ * @since 1.0.0
472
+ * @category Toolkit
473
+ */
474
+ export type ExcludableTool = Exclude<
475
+ keyof typeof AgentToolsWithSearch.tools,
476
+ "taskComplete"
477
+ >
478
+
272
479
  /**
273
480
  * @since 1.0.0
274
481
  * @category Toolkit
@@ -280,22 +487,45 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(
280
487
  const pathService = yield* Path.Path
281
488
  const webSearch = yield* ExaSearch.ExaSearch
282
489
  const fetchMarkdown = yield* WebToMarkdown.WebToMarkdown
283
- const execute = Effect.fn(function* (command: ChildProcess.Command) {
284
- const handle = yield* spawner.spawn(command)
285
- return yield* handle.all.pipe(
286
- Stream.decodeText,
287
- Stream.mkString,
288
- Effect.flatMap(
289
- Effect.fnUntraced(function* (output) {
290
- const exitCode = yield* handle.exitCode
291
- if (exitCode === 0) return output
292
- return yield* Effect.die(
293
- new Error(`Command failed with exit code ${exitCode}: ${output}`),
294
- )
295
- }),
296
- ),
297
- )
298
- }, Effect.scoped)
490
+ const execute = Effect.fn(
491
+ function* (
492
+ command: ChildProcess.Command,
493
+ _timeout: Duration.Duration | undefined,
494
+ ) {
495
+ const { outputChars } = yield* CommandLimits
496
+ const handle = yield* spawner.spawn(command)
497
+ return yield* handle.all.pipe(
498
+ Stream.decodeText,
499
+ outputChars === undefined
500
+ ? Stream.mkString
501
+ : collectBounded(outputChars),
502
+ Effect.flatMap(
503
+ Effect.fnUntraced(function* (output) {
504
+ const exitCode = yield* handle.exitCode
505
+ if (exitCode === 0) return output
506
+ return yield* Effect.die(
507
+ new Error(
508
+ `Command failed with exit code ${exitCode}: ${output}`,
509
+ ),
510
+ )
511
+ }),
512
+ ),
513
+ )
514
+ },
515
+ (effect, _command, timeout) =>
516
+ timeout === undefined
517
+ ? effect
518
+ : Effect.timeoutOrElse(effect, {
519
+ duration: timeout,
520
+ orElse: () =>
521
+ Effect.die(
522
+ new Error(
523
+ `Command timed out after ${Duration.toMillis(timeout)}ms`,
524
+ ),
525
+ ),
526
+ }),
527
+ Effect.scoped,
528
+ )
299
529
 
300
530
  /**
301
531
  * Image branch of `readFile`: the bytes go to the `ImageAttacher` for
@@ -489,7 +719,9 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(
489
719
  )
490
720
  }),
491
721
  bash: Effect.fn("AgentTools.bash")(function* (options) {
492
- const timeoutMs = Math.min(options.timeoutMs ?? 600_000, 600_000)
722
+ const limits = yield* CommandLimits
723
+ const maxMs = Duration.toMillis(limits.timeout ?? defaultBashTimeout)
724
+ const timeoutMs = Math.min(options.timeoutMs ?? maxMs, maxMs)
493
725
  yield* Effect.logInfo(`Calling "bash"`).pipe(
494
726
  Effect.annotateLogs({
495
727
  ...options,
@@ -501,13 +733,7 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(
501
733
  cwd,
502
734
  stdin: "ignore",
503
735
  })
504
- return yield* execute(cmd).pipe(
505
- Effect.timeoutOrElse({
506
- duration: timeoutMs,
507
- orElse: () =>
508
- Effect.die(new Error(`Command timed out after ${timeoutMs}ms`)),
509
- }),
510
- )
736
+ return yield* execute(cmd, Duration.millis(timeoutMs))
511
737
  }, Effect.orDie),
512
738
  gh: Effect.fn("AgentTools.gh")(function* (args) {
513
739
  yield* Effect.logInfo(`Calling "gh"`).pipe(
@@ -518,7 +744,8 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(
518
744
  cwd,
519
745
  stdin: "ignore",
520
746
  })
521
- return yield* execute(cmd)
747
+ const { timeout } = yield* CommandLimits
748
+ return yield* execute(cmd, timeout)
522
749
  }, Effect.orDie),
523
750
  webSearch: Effect.fn("AgentTools.webSearch")(function* (options) {
524
751
  yield* Effect.logInfo(`Calling "webSearch"`).pipe(
@@ -674,13 +901,47 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(
674
901
 
675
902
  return `Success. Updated the following files:\n${out.join("\n")}`
676
903
  }, Effect.orDie),
677
- delegate: Effect.fn("AgentTools.delegate")(function* (prompt) {
678
- yield* Effect.logInfo(`Calling "delegate"`)
679
- const spawn = yield* SubagentExecutor
680
- return yield* spawn(`You have been asked using the "delegate" function to complete the following task. Try to avoid using the "delegate" function yourself unless strictly necessary:
681
-
682
- ${prompt}`)
683
- }, Effect.orDie),
904
+ delegate: Effect.fn("AgentTools.delegate")(function* (options: unknown) {
905
+ const { prompt, background = false } = yield* decodeDelegate(options)
906
+ yield* Effect.logInfo(`Calling "delegate"`).pipe(
907
+ Effect.annotateLogs({ background }),
908
+ )
909
+ const subagents = yield* SubagentExecutor
910
+ return yield* subagents.delegate({ prompt, background })
911
+ }),
912
+ waitAgents: Effect.fn("AgentTools.waitAgents")(function* (
913
+ input: unknown,
914
+ ) {
915
+ const ids = yield* decodeWaitAgents(input)
916
+ yield* Effect.logInfo(`Calling "waitAgents"`).pipe(
917
+ Effect.annotateLogs({ ids }),
918
+ )
919
+ const subagents = yield* SubagentExecutor
920
+ return yield* subagents.waitAgents(ids)
921
+ }),
922
+ messageAgent: Effect.fn("AgentTools.messageAgent")(function* (
923
+ input: unknown,
924
+ ) {
925
+ const options = yield* decodeMessageAgent(input)
926
+ yield* Effect.logInfo(`Calling "messageAgent"`).pipe(
927
+ Effect.annotateLogs({ id: options.id }),
928
+ )
929
+ const subagents = yield* SubagentExecutor
930
+ return yield* subagents.messageAgent(options)
931
+ }),
932
+ stopAgent: Effect.fn("AgentTools.stopAgent")(function* (input: unknown) {
933
+ const id = yield* decodeStopAgent(input)
934
+ yield* Effect.logInfo(`Calling "stopAgent"`).pipe(
935
+ Effect.annotateLogs({ id }),
936
+ )
937
+ const subagents = yield* SubagentExecutor
938
+ return yield* subagents.stopAgent(id)
939
+ }),
940
+ listAgents: Effect.fn("AgentTools.listAgents")(function* () {
941
+ yield* Effect.logInfo(`Calling "listAgents"`)
942
+ const subagents = yield* SubagentExecutor
943
+ return yield* subagents.listAgents
944
+ }),
684
945
  taskComplete: Effect.fn("AgentTools.taskComplete")(function* (
685
946
  message: unknown,
686
947
  ) {
@@ -722,6 +983,69 @@ export const AgentToolHandlersTest = AgentToolHandlersNoDeps.pipe(
722
983
  ]),
723
984
  )
724
985
 
986
+ // Scripts pass tool arguments undecoded. Invalid input fails with a usage
987
+ // message the model can act on.
988
+ const decodeParams = <S extends Schema.Decoder<unknown>>(
989
+ schema: S,
990
+ usage: string,
991
+ ) => {
992
+ const decode = Schema.decodeUnknownEffect(schema)
993
+ return (input: unknown) => Effect.mapError(decode(input), () => usage)
994
+ }
995
+
996
+ const decodeDelegate = decodeParams(
997
+ AgentTools.tools.delegate.parametersSchema,
998
+ 'delegate requires an options object, for example: delegate({ prompt: "..." }) or delegate({ prompt: "...", background: true }).',
999
+ )
1000
+ const decodeWaitAgents = decodeParams(
1001
+ AgentTools.tools.waitAgents.parametersSchema,
1002
+ 'waitAgents takes an optional array of agent ids, for example: waitAgents(["3", "4"]).',
1003
+ )
1004
+ const decodeMessageAgent = decodeParams(
1005
+ AgentTools.tools.messageAgent.parametersSchema,
1006
+ 'messageAgent requires an options object, for example: messageAgent({ id: "3", message: "..." }).',
1007
+ )
1008
+ const decodeStopAgent = decodeParams(
1009
+ AgentTools.tools.stopAgent.parametersSchema,
1010
+ 'stopAgent requires an agent id, for example: stopAgent("3").',
1011
+ )
1012
+
1013
+ /**
1014
+ * Collects text output keeping at most `maxChars` characters: the start, the
1015
+ * end, and a marker in place of the middle. Only the kept text is held in
1016
+ * memory while the stream runs.
1017
+ */
1018
+ const collectBounded =
1019
+ (maxChars: number) =>
1020
+ <E, R>(stream: Stream.Stream<string, E, R>): Effect.Effect<string, E, R> => {
1021
+ const headChars = Math.floor(maxChars / 2)
1022
+ const tailChars = maxChars - headChars
1023
+ let head = ""
1024
+ let tail = ""
1025
+ let total = 0
1026
+ return stream.pipe(
1027
+ Stream.runForEach((chunk) =>
1028
+ Effect.sync(() => {
1029
+ total += chunk.length
1030
+ let rest = chunk
1031
+ if (head.length < headChars) {
1032
+ const take = headChars - head.length
1033
+ head += rest.slice(0, take)
1034
+ rest = rest.slice(take)
1035
+ }
1036
+ if (rest.length > 0 && tailChars > 0) {
1037
+ tail = (tail + rest).slice(-tailChars)
1038
+ }
1039
+ }),
1040
+ ),
1041
+ Effect.map(() => {
1042
+ const omitted = total - head.length - tail.length
1043
+ if (omitted <= 0) return head + tail
1044
+ return `${head}\n\n[... ${omitted} of ${total} chars omitted from the middle of the output ...]\n\n${tail}`
1045
+ }),
1046
+ )
1047
+ }
1048
+
725
1049
  class ApplyPatchError extends Data.TaggedClass("ApplyPatchError")<{
726
1050
  readonly message: string
727
1051
  }> {}
@@ -60,14 +60,24 @@ export const pretty = (options?: {
60
60
  return `${chalkAgentHeading(`${subagentIcon} Agent #${output.id} starting (${output.modelAndProvider})`)}\n\n${promptToString(output.prompt)}\n\n`
61
61
  }
62
62
  case "SubagentStart": {
63
- return `${chalkSubagentHeading(`${subagentIcon} Subagent #${output.id} starting (${output.modelAndProvider})`)}
63
+ const mode = output.background ? " in the background" : ""
64
+ return `${chalkSubagentHeading(`${subagentIcon} Subagent #${output.id} starting${mode} (${output.modelAndProvider})`)}
64
65
 
65
66
  ${chalk.dim(output.prompt)}\n\n`
66
67
  }
67
68
  case "SubagentComplete": {
68
- return `${chalkSubagentHeading(`${subagentIcon} Subagent #${output.id} complete`)}
69
+ switch (output.status) {
70
+ case "completed":
71
+ return `${chalkSubagentHeading(`${subagentIcon} Subagent #${output.id} complete`)}
69
72
 
70
73
  ${output.summary}\n\n`
74
+ case "failed":
75
+ return `${chalk.bold.red(`${subagentIcon} Subagent #${output.id} failed`)}
76
+
77
+ ${chalk.dim(output.summary)}\n\n`
78
+ case "cancelled":
79
+ return `${chalkSubagentHeading(`${subagentIcon} Subagent #${output.id} cancelled`)}\n\n`
80
+ }
71
81
  }
72
82
  case "ReasoningStart": {
73
83
  return (
@@ -107,6 +117,13 @@ ${output.summary}\n\n`
107
117
  case "CompactionEnded": {
108
118
  return `${prefix}${chalkInfoHeading(`${infoIcon} Context compacted (${output.reason}):`)} ~${numberFormat.format(output.tokensBefore)} tokens to ~${numberFormat.format(output.tokensAfter)}\n\n`
109
119
  }
120
+ case "EnvironmentUpdated": {
121
+ return `${prefix}${chalkInfoHeading(`${infoIcon} Environment update:`)}\n\n${chalk.dim(truncate(output.update))}\n\n`
122
+ }
123
+ case "HistoryAppended":
124
+ case "HistoryReplaced": {
125
+ return ""
126
+ }
110
127
  }
111
128
  }),
112
129
  Stream.catchIf(
@@ -33,7 +33,11 @@ export class ToolkitRenderer extends Context.Service<
33
33
  SchemaAST.resolveIdentifier(tool.parametersSchema.ast) ?? "options"
34
34
  const paramType = TypeBuilder.render(tool.parametersSchema)
35
35
  const params =
36
- paramType === "void" ? "" : `${paramName}: ${paramType}`
36
+ paramType === "void"
37
+ ? ""
38
+ : paramType.endsWith(optionalSuffix)
39
+ ? `${paramName}?: ${paramType.slice(0, -optionalSuffix.length)}`
40
+ : `${paramName}: ${paramType}`
37
41
  output.push(
38
42
  `/** ${tool.description} */
39
43
  declare function ${name}(${params}): Promise<${TypeBuilder.render(tool.successSchema)}>`,
@@ -44,3 +48,5 @@ declare function ${name}(${params}): Promise<${TypeBuilder.render(tool.successSc
44
48
  ),
45
49
  })
46
50
  }
51
+
52
+ const optionalSuffix = " | undefined"