clanka 0.8.5 → 0.9.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 (92) hide show
  1. package/dist/Acp.d.ts.map +1 -1
  2. package/dist/Acp.js +9 -3
  3. package/dist/Acp.js.map +1 -1
  4. package/dist/Acp.test.js +72 -1
  5. package/dist/Acp.test.js.map +1 -1
  6. package/dist/AcpImage.test.js +1 -0
  7. package/dist/AcpImage.test.js.map +1 -1
  8. package/dist/Agent.d.ts +65 -8
  9. package/dist/Agent.d.ts.map +1 -1
  10. package/dist/Agent.js +481 -113
  11. package/dist/Agent.js.map +1 -1
  12. package/dist/Agent.test.js +77 -4
  13. package/dist/Agent.test.js.map +1 -1
  14. package/dist/AgentCallerConfig.test.d.ts +2 -0
  15. package/dist/AgentCallerConfig.test.d.ts.map +1 -0
  16. package/dist/AgentCallerConfig.test.js +327 -0
  17. package/dist/AgentCallerConfig.test.js.map +1 -0
  18. package/dist/AgentExecutor.d.ts +254 -54
  19. package/dist/AgentExecutor.d.ts.map +1 -1
  20. package/dist/AgentExecutor.js +416 -99
  21. package/dist/AgentExecutor.js.map +1 -1
  22. package/dist/AgentExecutor.test.js +201 -31
  23. package/dist/AgentExecutor.test.js.map +1 -1
  24. package/dist/AgentExecutorImage.test.js +2 -1
  25. package/dist/AgentExecutorImage.test.js.map +1 -1
  26. package/dist/AgentImage.test.js +5 -1
  27. package/dist/AgentImage.test.js.map +1 -1
  28. package/dist/AgentOutput.d.ts +54 -2
  29. package/dist/AgentOutput.d.ts.map +1 -1
  30. package/dist/AgentOutput.js +52 -0
  31. package/dist/AgentOutput.js.map +1 -1
  32. package/dist/AgentSkills.d.ts +22 -0
  33. package/dist/AgentSkills.d.ts.map +1 -1
  34. package/dist/AgentSkills.js +36 -0
  35. package/dist/AgentSkills.js.map +1 -1
  36. package/dist/AgentSkills.test.js +2 -0
  37. package/dist/AgentSkills.test.js.map +1 -1
  38. package/dist/AgentSubagents.test.d.ts +2 -0
  39. package/dist/AgentSubagents.test.d.ts.map +1 -0
  40. package/dist/AgentSubagents.test.js +452 -0
  41. package/dist/AgentSubagents.test.js.map +1 -0
  42. package/dist/AgentTools.d.ts +356 -14
  43. package/dist/AgentTools.d.ts.map +1 -1
  44. package/dist/AgentTools.js +213 -34
  45. package/dist/AgentTools.js.map +1 -1
  46. package/dist/CompactionTransport.test.js +1 -1
  47. package/dist/CompactionTransport.test.js.map +1 -1
  48. package/dist/OutputFormatter.d.ts.map +1 -1
  49. package/dist/OutputFormatter.js +16 -2
  50. package/dist/OutputFormatter.js.map +1 -1
  51. package/dist/ToolkitRenderer.d.ts.map +1 -1
  52. package/dist/ToolkitRenderer.js +6 -1
  53. package/dist/ToolkitRenderer.js.map +1 -1
  54. package/dist/bin/{Effect-BEUn4I5E.mjs → Effect-2jPlJ8eu.mjs} +399 -207
  55. package/dist/bin/Effect-2jPlJ8eu.mjs.map +1 -0
  56. package/dist/bin/{McpClient-C0FVuDj2.mjs → McpClient-1W508adc.mjs} +4 -4
  57. package/dist/bin/{McpClient-C0FVuDj2.mjs.map → McpClient-1W508adc.mjs.map} +1 -1
  58. package/dist/bin/{OutputFormatter-DffD5oxX.mjs → OutputFormatter-DXXKo4E8.mjs} +16 -5
  59. package/dist/bin/{OutputFormatter-DffD5oxX.mjs.map → OutputFormatter-DXXKo4E8.mjs.map} +1 -1
  60. package/dist/bin/{Schema-CjUGw2Xh.mjs → Schema-D-7VuCiC.mjs} +640 -87
  61. package/dist/bin/Schema-D-7VuCiC.mjs.map +1 -0
  62. package/dist/bin/{SemanticSearch-CFB73IPb.mjs → SemanticSearch-Cb8aqvGv.mjs} +89 -56
  63. package/dist/bin/SemanticSearch-Cb8aqvGv.mjs.map +1 -0
  64. package/dist/bin/{Stream-Cu6P7ZHo.mjs → Stream-DEu2tfCV.mjs} +81 -51
  65. package/dist/bin/Stream-DEu2tfCV.mjs.map +1 -0
  66. package/dist/bin/cli.mjs +3632 -5538
  67. package/dist/bin/cli.mjs.map +1 -1
  68. package/dist/bin/{turndown.cjs-usmCKZ4b.mjs → turndown.cjs-DK29wZw3.mjs} +2 -2
  69. package/dist/bin/{turndown.cjs-usmCKZ4b.mjs.map → turndown.cjs-DK29wZw3.mjs.map} +1 -1
  70. package/package.json +7 -7
  71. package/src/Acp.test.ts +121 -2
  72. package/src/Acp.ts +10 -3
  73. package/src/AcpImage.test.ts +1 -0
  74. package/src/Agent.test.ts +100 -3
  75. package/src/Agent.ts +752 -142
  76. package/src/AgentCallerConfig.test.ts +514 -0
  77. package/src/AgentExecutor.test.ts +297 -37
  78. package/src/AgentExecutor.ts +707 -159
  79. package/src/AgentExecutorImage.test.ts +2 -1
  80. package/src/AgentImage.test.ts +11 -2
  81. package/src/AgentOutput.ts +74 -1
  82. package/src/AgentSkills.test.ts +2 -0
  83. package/src/AgentSkills.ts +43 -0
  84. package/src/AgentSubagents.test.ts +758 -0
  85. package/src/AgentTools.ts +376 -52
  86. package/src/CompactionTransport.test.ts +1 -1
  87. package/src/OutputFormatter.ts +16 -2
  88. package/src/ToolkitRenderer.ts +7 -1
  89. package/dist/bin/Effect-BEUn4I5E.mjs.map +0 -1
  90. package/dist/bin/Schema-CjUGw2Xh.mjs.map +0 -1
  91. package/dist/bin/SemanticSearch-CFB73IPb.mjs.map +0 -1
  92. package/dist/bin/Stream-Cu6P7ZHo.mjs.map +0 -1
@@ -0,0 +1,758 @@
1
+ import { assert, it } from "@effect/vitest"
2
+ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"
3
+ import * as NodeServices from "@effect/platform-node/NodeServices"
4
+ import * as Effect from "effect/Effect"
5
+ import * as Exit from "effect/Exit"
6
+ import * as FileSystem from "effect/FileSystem"
7
+ import * as FetchHttpClient from "effect/http/FetchHttpClient"
8
+ import * as HttpServer from "effect/http/HttpServer"
9
+ import * as Latch from "effect/Latch"
10
+ import * as Layer from "effect/Layer"
11
+ import * as MutableRef from "effect/MutableRef"
12
+ import * as Option from "effect/Option"
13
+ import * as Schema from "effect/Schema"
14
+ import * as Stream from "effect/Stream"
15
+ import * as AiError from "effect/ai/AiError"
16
+ import * as LanguageModel from "effect/ai/LanguageModel"
17
+ import * as Model from "effect/ai/Model"
18
+ import * as Prompt from "effect/ai/Prompt"
19
+ import type * as Response from "effect/ai/Response"
20
+ import * as RpcClient from "effect/rpc/RpcClient"
21
+ import * as RpcSerialization from "effect/rpc/RpcSerialization"
22
+ import * as RpcServer from "effect/rpc/RpcServer"
23
+ import * as Agent from "./Agent.ts"
24
+ import * as AgentExecutor from "./AgentExecutor.ts"
25
+ import * as Compaction from "./Compaction.ts"
26
+
27
+ // =============================================================================
28
+ // Background sub-agents: lifetime and completion delivery.
29
+ //
30
+ // These drive the real Agent loop and a real executor, so the model only
31
+ // talks to the script API: `delegate({ prompt, background })`, `waitAgents`,
32
+ // `messageAgent` and `stopAgent`. One scripted LanguageModel serves every
33
+ // agent; calls are routed by the task marker in each agent's first user
34
+ // message. Agent IDs come from the shared counter: the root run is "0" and
35
+ // the first sub-agent is "1".
36
+ //
37
+ // Sub-agents always finish with `taskComplete`: with the local executor they
38
+ // currently run outside the parent's ConversationMode, so a text-only turn
39
+ // does not end them.
40
+ // =============================================================================
41
+
42
+ type Role = "root" | "child" | "grandchild"
43
+
44
+ interface Call {
45
+ readonly role: Role
46
+ readonly index: number
47
+ readonly prompt: Prompt.Prompt
48
+ }
49
+
50
+ type Respond = (
51
+ call: Call,
52
+ ) => Stream.Stream<Response.StreamPartEncoded, AiError.AiError>
53
+
54
+ const messageText = (message: Prompt.Message): string =>
55
+ typeof message.content === "string"
56
+ ? message.content
57
+ : message.content
58
+ .map((part) => (part.type === "text" ? part.text : ""))
59
+ .join("")
60
+
61
+ const firstUserText = (prompt: Prompt.Prompt): string => {
62
+ const message = prompt.content.find((message) => message.role === "user")
63
+ return message ? messageText(message) : ""
64
+ }
65
+
66
+ const roleOf = (prompt: Prompt.Prompt): Role => {
67
+ const text = firstUserText(prompt)
68
+ if (text.includes("TASK-GRANDCHILD")) return "grandchild"
69
+ if (text.includes("TASK-CHILD")) return "child"
70
+ return "root"
71
+ }
72
+
73
+ const runAgent = (options: {
74
+ readonly conversationMode: boolean
75
+ readonly respond: Respond
76
+ readonly afterExit?: Effect.Effect<void> | undefined
77
+ }) =>
78
+ Effect.gen(function* () {
79
+ const executor = yield* AgentExecutor.AgentExecutor
80
+ const calls: Array<Call> = []
81
+ const counts: Record<Role, number> = { root: 0, child: 0, grandchild: 0 }
82
+ const languageModel = yield* LanguageModel.make({
83
+ generateText: () => Effect.die("unexpected generateText call"),
84
+ streamText: (providerOptions) => {
85
+ const role = roleOf(providerOptions.prompt)
86
+ const call: Call = {
87
+ role,
88
+ index: counts[role]++,
89
+ prompt: providerOptions.prompt,
90
+ }
91
+ calls.push(call)
92
+ return options.respond(call)
93
+ },
94
+ })
95
+ const modelLayer = Layer.mergeAll(
96
+ Layer.succeed(LanguageModel.LanguageModel, languageModel),
97
+ Layer.succeed(Model.ProviderName, "test-provider"),
98
+ Layer.succeed(Model.ModelName, "test-model"),
99
+ )
100
+ const agent = yield* Agent.make.pipe(
101
+ Effect.provideService(AgentExecutor.AgentExecutor, executor),
102
+ )
103
+ const exit = yield* agent.send({ prompt: "hello" }).pipe(
104
+ Effect.flatMap((stream) =>
105
+ stream.pipe(
106
+ Stream.runDrain,
107
+ Effect.as(""),
108
+ Effect.catchTag("AgentFinished", (finished) =>
109
+ Effect.succeed(finished.summary),
110
+ ),
111
+ ),
112
+ ),
113
+ Effect.provide(
114
+ Layer.mergeAll(
115
+ modelLayer,
116
+ Agent.ConversationMode.layer(options.conversationMode),
117
+ Agent.layerSubagentModel(modelLayer),
118
+ ),
119
+ ),
120
+ Effect.exit,
121
+ )
122
+ // Still inside the scope that owns the Agent, so anything observed here
123
+ // was cleaned up by the run itself, not by the test tearing down.
124
+ if (options.afterExit) yield* options.afterExit
125
+ return { exit, calls, history: MutableRef.get(agent.history) }
126
+ }).pipe(Effect.scoped, Effect.timeout("4 seconds"))
127
+
128
+ // --- fixtures ----------------------------------------------------------------
129
+
130
+ const toolCall = (id: string, script: string): Response.StreamPartEncoded => ({
131
+ type: "tool-call",
132
+ id,
133
+ name: "execute",
134
+ params: { script },
135
+ })
136
+
137
+ const text = (content: string, id = "t"): Array<Response.StreamPartEncoded> => [
138
+ { type: "text-start", id },
139
+ { type: "text-delta", id, delta: content },
140
+ { type: "text-end", id },
141
+ ]
142
+
143
+ const invalidRequest = AiError.make({
144
+ module: "OpenAiLanguageModel",
145
+ method: "streamText",
146
+ reason: new AiError.InvalidRequestError({
147
+ description: "The sub-agent request was rejected",
148
+ }),
149
+ })
150
+
151
+ const complete = (output: string) =>
152
+ Stream.make(
153
+ toolCall("complete", `await taskComplete(${JSON.stringify(output)})`),
154
+ )
155
+
156
+ const spawnBackground = (task: string) =>
157
+ toolCall(
158
+ `spawn-${task}`,
159
+ `const result = await delegate({ prompt: "${task}", background: true })
160
+ console.log(JSON.stringify(result))`,
161
+ )
162
+
163
+ const toolResultTexts = (prompt: Prompt.Prompt): Array<string> =>
164
+ prompt.content.flatMap((message) =>
165
+ message.role === "tool"
166
+ ? message.content.flatMap((part) =>
167
+ part.type === "tool-result" ? [String(part.result)] : [],
168
+ )
169
+ : [],
170
+ )
171
+
172
+ const lastToolResult = (prompt: Prompt.Prompt): string =>
173
+ toolResultTexts(prompt).at(-1) ?? ""
174
+
175
+ const encodePrompt = Schema.encodeSync(Prompt.Prompt)
176
+ const messageJsons = (prompt: Prompt.Prompt): Array<string> =>
177
+ encodePrompt(prompt).content.map((message) => JSON.stringify(message))
178
+
179
+ /**
180
+ * The index and text of the first user message carrying a completion push
181
+ * for `id` with `status`, or -1 / "" when there is none.
182
+ */
183
+ const findPush = (
184
+ prompt: Prompt.Prompt,
185
+ id: string,
186
+ status: "completed" | "failed" | "cancelled",
187
+ ): { readonly index: number; readonly text: string } => {
188
+ const pattern = new RegExp(
189
+ `<subagent id="${id}" status="${status}">[\\s\\S]*</subagent>`,
190
+ )
191
+ const index = prompt.content.findIndex(
192
+ (message) => message.role === "user" && pattern.test(messageText(message)),
193
+ )
194
+ return {
195
+ index,
196
+ text: index === -1 ? "" : messageText(prompt.content[index]!),
197
+ }
198
+ }
199
+
200
+ const pushTexts = (prompt: Prompt.Prompt): Array<string> =>
201
+ prompt.content.flatMap((message) => {
202
+ if (message.role !== "user") return []
203
+ const text = messageText(message)
204
+ return text.includes("<subagent id=") ? [text] : []
205
+ })
206
+
207
+ const hasAnyPush = (prompt: Prompt.Prompt, id: string): boolean =>
208
+ pushTexts(prompt).some((push) => push.includes(`<subagent id="${id}"`))
209
+
210
+ const waitFor = (condition: () => boolean) =>
211
+ Effect.gen(function* () {
212
+ while (!condition()) yield* Effect.sleep("10 millis")
213
+ }).pipe(Effect.timeoutOption("1 second"), Effect.map(Option.isSome))
214
+
215
+ const unexpected = (call: Call) =>
216
+ Stream.die(`unexpected ${call.role} model call #${call.index}`)
217
+
218
+ // --- executors ---------------------------------------------------------------
219
+
220
+ const localExecutorLayer = Layer.unwrap(
221
+ Effect.gen(function* () {
222
+ const fs = yield* FileSystem.FileSystem
223
+ const directory = yield* fs.makeTempDirectoryScoped()
224
+ return AgentExecutor.layerLocal({ directory })
225
+ }),
226
+ ).pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer)))
227
+
228
+ const rpcExecutorLayer = Layer.unwrap(
229
+ Effect.gen(function* () {
230
+ const fs = yield* FileSystem.FileSystem
231
+ const directory = yield* fs.makeTempDirectoryScoped()
232
+ const { protocol, httpEffect } =
233
+ yield* RpcServer.makeProtocolWithHttpEffect()
234
+ yield* Layer.build(
235
+ AgentExecutor.layerRpcServer({ directory }).pipe(
236
+ Layer.provide(Layer.succeed(RpcServer.Protocol, protocol)),
237
+ ),
238
+ )
239
+ yield* HttpServer.serveEffect(httpEffect)
240
+ return AgentExecutor.layerRpc.pipe(
241
+ Layer.provide(RpcClient.layerProtocolHttp({ url: "" })),
242
+ )
243
+ }),
244
+ ).pipe(
245
+ Layer.provide(
246
+ Layer.mergeAll(
247
+ RpcSerialization.layerNdjson,
248
+ NodeHttpServer.layerTest,
249
+ NodeServices.layer,
250
+ ),
251
+ ),
252
+ )
253
+
254
+ const executors = [
255
+ ["local", localExecutorLayer],
256
+ ["rpc", rpcExecutorLayer],
257
+ ] as const
258
+
259
+ // --- tests -------------------------------------------------------------------
260
+
261
+ for (const [executorName, executorLayer] of executors) {
262
+ it.layer(executorLayer, { excludeTestServices: true })(
263
+ `background sub-agents (${executorName} executor)`,
264
+ (it) => {
265
+ it.effect(
266
+ "an idle conversation turn waits for a running child, then gets its capped output",
267
+ () =>
268
+ Effect.gen(function* () {
269
+ const childRelease = Latch.makeUnsafe(false)
270
+ const childOutput =
271
+ "CHILD-HEAD " + "x".repeat(40_000) + " CHILD-TAIL"
272
+ const { exit, calls } = yield* runAgent({
273
+ conversationMode: true,
274
+ respond: (call) => {
275
+ if (call.role === "child") {
276
+ // Finishes only after the parent's idle turn is over, so
277
+ // the parent has to block on the completion push.
278
+ return Stream.fromEffect(
279
+ childRelease.await.pipe(
280
+ Effect.andThen(Effect.sleep("50 millis")),
281
+ ),
282
+ ).pipe(Stream.flatMap(() => complete(childOutput)))
283
+ }
284
+ switch (call.index) {
285
+ case 0:
286
+ return Stream.make(spawnBackground("TASK-CHILD"))
287
+ case 1:
288
+ return Stream.fromIterable(
289
+ text("waiting for the child"),
290
+ ).pipe(
291
+ Stream.ensuring(
292
+ Effect.sync(() => childRelease.openUnsafe()),
293
+ ),
294
+ )
295
+ case 2:
296
+ return Stream.fromIterable(text("all done"))
297
+ default:
298
+ return unexpected(call)
299
+ }
300
+ },
301
+ })
302
+
303
+ assert.deepStrictEqual(exit, Exit.succeed("all done"))
304
+ const root = calls.filter((call) => call.role === "root")
305
+ assert.strictEqual(root.length, 3)
306
+
307
+ const started = lastToolResult(root[1]!.prompt)
308
+ assert.include(started, '"id":"1"')
309
+ assert.include(started, '"status":"running"')
310
+ assert.notInclude(started, '"output"', "no output while running")
311
+
312
+ const push = findPush(root[2]!.prompt, "1", "completed")
313
+ assert.notStrictEqual(push.index, -1, "completion push delivered")
314
+ assert.include(push.text, "CHILD-HEAD")
315
+ assert.include(push.text, "CHILD-TAIL")
316
+ assert.isAtMost(
317
+ push.text.length,
318
+ Compaction.executeOutputCapChars + 1_000,
319
+ "push output goes through capOutput",
320
+ )
321
+ }),
322
+ )
323
+
324
+ it.effect(
325
+ "a completion push does not cut off the parent's in-progress response",
326
+ () =>
327
+ Effect.gen(function* () {
328
+ const childRelease = Latch.makeUnsafe(false)
329
+ const childDone = Latch.makeUnsafe(false)
330
+ const { exit, calls } = yield* runAgent({
331
+ conversationMode: true,
332
+ respond: (call) => {
333
+ if (call.role === "child") {
334
+ return Stream.fromEffect(childRelease.await).pipe(
335
+ Stream.flatMap(() => complete("CHILD-RESULT")),
336
+ Stream.ensuring(Effect.sync(() => childDone.openUnsafe())),
337
+ )
338
+ }
339
+ switch (call.index) {
340
+ case 0:
341
+ return Stream.make(spawnBackground("TASK-CHILD"))
342
+ case 1:
343
+ // The child completes between two text blocks of one
344
+ // response. The whole response must still be recorded.
345
+ return Stream.fromIterable(text("PART-ONE", "t1")).pipe(
346
+ Stream.concat(
347
+ Stream.fromEffect(
348
+ Effect.gen(function* () {
349
+ childRelease.openUnsafe()
350
+ yield* childDone.await
351
+ yield* Effect.sleep("100 millis")
352
+ }),
353
+ ).pipe(Stream.drain),
354
+ ),
355
+ Stream.concat(
356
+ Stream.fromIterable([
357
+ ...text("PART-TWO", "t2"),
358
+ toolCall("after", 'console.log("AFTER-SCRIPT-RAN")'),
359
+ ]),
360
+ ),
361
+ )
362
+ default:
363
+ return Stream.fromIterable(text("done"))
364
+ }
365
+ },
366
+ })
367
+
368
+ assert.deepStrictEqual(exit, Exit.succeed("done"))
369
+ const root = calls.filter((call) => call.role === "root")
370
+ const prompt = root[2]!.prompt
371
+ const assistantIndex = prompt.content.findIndex(
372
+ (message) =>
373
+ message.role === "assistant" &&
374
+ messageText(message).includes("PART-ONE"),
375
+ )
376
+ assert.notStrictEqual(assistantIndex, -1)
377
+ assert.include(
378
+ messageText(prompt.content[assistantIndex]!),
379
+ "PART-TWO",
380
+ "the response continued past the first text-end",
381
+ )
382
+ assert.include(
383
+ lastToolResult(prompt),
384
+ "AFTER-SCRIPT-RAN",
385
+ "the tool call after the push still ran",
386
+ )
387
+ const push = findPush(prompt, "1", "completed")
388
+ assert.include(push.text, "CHILD-RESULT")
389
+ assert.isAbove(
390
+ push.index,
391
+ assistantIndex,
392
+ "the push is injected after the response, not into it",
393
+ )
394
+ }),
395
+ )
396
+
397
+ it.effect(
398
+ "a failed background child is pushed as failed and the parent keeps going",
399
+ () =>
400
+ Effect.gen(function* () {
401
+ const childRelease = Latch.makeUnsafe(false)
402
+ const { exit, calls } = yield* runAgent({
403
+ conversationMode: true,
404
+ respond: (call) => {
405
+ if (call.role === "child") {
406
+ return Stream.fromEffect(childRelease.await).pipe(
407
+ Stream.flatMap(() => Stream.fail(invalidRequest)),
408
+ )
409
+ }
410
+ switch (call.index) {
411
+ case 0:
412
+ return Stream.make(spawnBackground("TASK-CHILD"))
413
+ case 1:
414
+ return Stream.fromIterable(text("waiting")).pipe(
415
+ Stream.ensuring(
416
+ Effect.sync(() => childRelease.openUnsafe()),
417
+ ),
418
+ )
419
+ case 2:
420
+ return Stream.fromIterable(text("recovered"))
421
+ default:
422
+ return unexpected(call)
423
+ }
424
+ },
425
+ })
426
+
427
+ assert.deepStrictEqual(exit, Exit.succeed("recovered"))
428
+ const root = calls.filter((call) => call.role === "root")
429
+ const push = findPush(root[2]!.prompt, "1", "failed")
430
+ assert.notStrictEqual(push.index, -1, "failure push delivered")
431
+ assert.include(push.text, "rejected")
432
+ }),
433
+ )
434
+
435
+ it.effect(
436
+ "taskComplete fails while a child is running and leaves it running",
437
+ () =>
438
+ Effect.gen(function* () {
439
+ const childRelease = Latch.makeUnsafe(false)
440
+ const { exit, calls, history } = yield* runAgent({
441
+ conversationMode: false,
442
+ respond: (call) => {
443
+ if (call.role === "child") {
444
+ return call.index === 0
445
+ ? Stream.fromEffect(childRelease.await).pipe(
446
+ Stream.flatMap(() => complete("CHILD-RESULT")),
447
+ )
448
+ : unexpected(call)
449
+ }
450
+ switch (call.index) {
451
+ case 0:
452
+ return Stream.make(
453
+ toolCall(
454
+ "too-early",
455
+ `await delegate({ prompt: "TASK-CHILD", background: true })
456
+ try {
457
+ await taskComplete("too early")
458
+ console.log("ACCEPTED")
459
+ } catch (error) {
460
+ console.log("REJECTED: " + String(error))
461
+ }`,
462
+ ),
463
+ )
464
+ case 1: {
465
+ const rejected = lastToolResult(call.prompt)
466
+ assert.include(rejected, "REJECTED")
467
+ assert.notInclude(rejected, "ACCEPTED")
468
+ assert.match(rejected, /\b1\b/, "lists the running child")
469
+ assert.include(rejected, "waitAgents")
470
+ assert.include(rejected, "stopAgent")
471
+ childRelease.openUnsafe()
472
+ return Stream.make(
473
+ toolCall(
474
+ "wait",
475
+ `const results = await waitAgents()
476
+ console.log(JSON.stringify(results))
477
+ await taskComplete("done")`,
478
+ ),
479
+ )
480
+ }
481
+ default:
482
+ return unexpected(call)
483
+ }
484
+ },
485
+ })
486
+
487
+ assert.deepStrictEqual(exit, Exit.succeed("done"))
488
+ assert.strictEqual(
489
+ calls.filter((call) => call.role === "root").length,
490
+ 2,
491
+ )
492
+ const waited = lastToolResult(history)
493
+ assert.include(waited, '"id":"1"')
494
+ assert.include(
495
+ waited,
496
+ '"status":"completed"',
497
+ "the child was not cancelled by the refused taskComplete",
498
+ )
499
+ assert.include(waited, "CHILD-RESULT")
500
+ }),
501
+ )
502
+
503
+ it.effect("background children do not outlive the parent run", () =>
504
+ Effect.gen(function* () {
505
+ const childStarted = Latch.makeUnsafe(false)
506
+ let childInterrupted = false
507
+ let interruptedBeforeTeardown = false
508
+ const { exit } = yield* runAgent({
509
+ conversationMode: true,
510
+ respond: (call) => {
511
+ if (call.role === "child") {
512
+ return Stream.fromEffect(
513
+ Effect.sync(() => childStarted.openUnsafe()).pipe(
514
+ Effect.andThen(Effect.never),
515
+ ),
516
+ ).pipe(
517
+ Stream.ensuring(
518
+ Effect.sync(() => {
519
+ childInterrupted = true
520
+ }),
521
+ ),
522
+ )
523
+ }
524
+ switch (call.index) {
525
+ case 0:
526
+ return Stream.make(spawnBackground("TASK-CHILD"))
527
+ case 1:
528
+ // The parent run fails while its child is still running.
529
+ return Stream.fromEffect(childStarted.await).pipe(
530
+ Stream.flatMap(() => Stream.fail(invalidRequest)),
531
+ )
532
+ default:
533
+ return unexpected(call)
534
+ }
535
+ },
536
+ afterExit: waitFor(() => childInterrupted).pipe(
537
+ Effect.map((interrupted) => {
538
+ interruptedBeforeTeardown = interrupted
539
+ }),
540
+ ),
541
+ })
542
+
543
+ assert.isTrue(Exit.isFailure(exit), "the parent run fails")
544
+ assert.isTrue(
545
+ interruptedBeforeTeardown,
546
+ "the child is interrupted when the run ends",
547
+ )
548
+ }),
549
+ )
550
+
551
+ it.effect("stopAgent cancels the agent and everything under it", () =>
552
+ Effect.gen(function* () {
553
+ const grandchildStarted = Latch.makeUnsafe(false)
554
+ const childBlocked = Latch.makeUnsafe(false)
555
+ let childInterrupted = false
556
+ let grandchildInterrupted = false
557
+ let interruptedBeforeNextTurn = false
558
+ const { exit, calls } = yield* runAgent({
559
+ conversationMode: true,
560
+ respond: (call) => {
561
+ switch (call.role) {
562
+ case "grandchild":
563
+ return Stream.fromEffect(
564
+ Effect.sync(() => grandchildStarted.openUnsafe()).pipe(
565
+ Effect.andThen(Effect.never),
566
+ ),
567
+ ).pipe(
568
+ Stream.ensuring(
569
+ Effect.sync(() => {
570
+ grandchildInterrupted = true
571
+ }),
572
+ ),
573
+ )
574
+ case "child":
575
+ return call.index === 0
576
+ ? Stream.make(spawnBackground("TASK-GRANDCHILD"))
577
+ : Stream.fromEffect(
578
+ Effect.sync(() => childBlocked.openUnsafe()).pipe(
579
+ Effect.andThen(Effect.never),
580
+ ),
581
+ ).pipe(
582
+ Stream.ensuring(
583
+ Effect.sync(() => {
584
+ childInterrupted = true
585
+ }),
586
+ ),
587
+ )
588
+ case "root":
589
+ switch (call.index) {
590
+ case 0:
591
+ return Stream.make(spawnBackground("TASK-CHILD"))
592
+ case 1:
593
+ return Stream.fromEffect(grandchildStarted.await).pipe(
594
+ Stream.tap(() => childBlocked.await),
595
+ Stream.as(
596
+ toolCall(
597
+ "stop",
598
+ `const result = await stopAgent("1")
599
+ console.log(JSON.stringify(result))`,
600
+ ),
601
+ ),
602
+ )
603
+ default:
604
+ if (call.index === 2) {
605
+ interruptedBeforeNextTurn =
606
+ childInterrupted && grandchildInterrupted
607
+ }
608
+ return Stream.fromIterable(text("stopped"))
609
+ }
610
+ }
611
+ },
612
+ })
613
+
614
+ assert.deepStrictEqual(exit, Exit.succeed("stopped"))
615
+ const root = calls.filter((call) => call.role === "root")
616
+ const stopped = lastToolResult(root[2]!.prompt)
617
+ assert.include(stopped, '"id":"1"')
618
+ assert.include(stopped, '"status":"cancelled"')
619
+ assert.isTrue(
620
+ interruptedBeforeNextTurn,
621
+ "stopAgent interrupts the child and its grandchild before returning",
622
+ )
623
+ }),
624
+ )
625
+
626
+ it.effect(
627
+ "messageAgent resumes a finished child on top of its history",
628
+ () =>
629
+ Effect.gen(function* () {
630
+ let messageCall: number | undefined
631
+ let resumedPrompt: Prompt.Prompt | undefined
632
+ const { exit, calls } = yield* runAgent({
633
+ conversationMode: true,
634
+ respond: (call) => {
635
+ if (call.role === "child") {
636
+ switch (call.index) {
637
+ case 0:
638
+ return complete("FIRST-ANSWER")
639
+ case 1:
640
+ resumedPrompt = call.prompt
641
+ return complete("SECOND-ANSWER")
642
+ default:
643
+ return unexpected(call)
644
+ }
645
+ }
646
+ // Decide from what has been delivered, not from call order:
647
+ // pushes may land before or after an idle turn.
648
+ const pushes = pushTexts(call.prompt)
649
+ if (call.index === 0) {
650
+ return Stream.make(spawnBackground("TASK-CHILD"))
651
+ }
652
+ if (pushes.some((push) => push.includes("SECOND-ANSWER"))) {
653
+ return Stream.fromIterable(text("resumed"))
654
+ }
655
+ if (
656
+ messageCall === undefined &&
657
+ pushes.some((push) => push.includes("FIRST-ANSWER"))
658
+ ) {
659
+ messageCall = call.index
660
+ return Stream.make(
661
+ toolCall(
662
+ "message",
663
+ `const result = await messageAgent({ id: "1", message: "FOLLOW-UP" })
664
+ console.log(JSON.stringify(result))`,
665
+ ),
666
+ )
667
+ }
668
+ return Stream.fromIterable(text("waiting"))
669
+ },
670
+ })
671
+
672
+ assert.deepStrictEqual(exit, Exit.succeed("resumed"))
673
+ assert.isDefined(messageCall, "the first answer was pushed")
674
+ const root = calls.filter((call) => call.role === "root")
675
+ const messaged = lastToolResult(root[messageCall! + 1]!.prompt)
676
+ assert.include(messaged, '"id":"1"')
677
+ assert.include(
678
+ messaged,
679
+ '"status":"running"',
680
+ "messageAgent returns without waiting for the new turn",
681
+ )
682
+
683
+ assert.isDefined(resumedPrompt, "the finished child was resumed")
684
+ const resumed = messageJsons(resumedPrompt!)
685
+ const task = resumed.findIndex((m) => m.includes("TASK-CHILD"))
686
+ const first = resumed.findIndex((m) => m.includes("FIRST-ANSWER"))
687
+ const followUp = resumed.findIndex((m) => m.includes("FOLLOW-UP"))
688
+ assert.notStrictEqual(task, -1, "original task kept")
689
+ assert.isAbove(first, task, "first answer kept")
690
+ assert.isAbove(followUp, first, "message appended after history")
691
+ }),
692
+ )
693
+
694
+ it.effect(
695
+ "pushes go to the agent that spawned the child, at every level",
696
+ () =>
697
+ Effect.gen(function* () {
698
+ const { exit, calls } = yield* runAgent({
699
+ conversationMode: true,
700
+ respond: (call) => {
701
+ switch (call.role) {
702
+ case "grandchild":
703
+ return complete("GRAND-RESULT")
704
+ case "child":
705
+ if (
706
+ findPush(call.prompt, "2", "completed").text.includes(
707
+ "GRAND-RESULT",
708
+ )
709
+ ) {
710
+ return complete("CHILD-DONE")
711
+ }
712
+ // Keep taking turns until the push is drained into the
713
+ // child's own prompt.
714
+ return call.index === 0
715
+ ? Stream.make(spawnBackground("TASK-GRANDCHILD"))
716
+ : Stream.fromEffect(Effect.sleep("20 millis")).pipe(
717
+ Stream.flatMap(() =>
718
+ Stream.fromIterable(text("child waiting")),
719
+ ),
720
+ )
721
+ case "root":
722
+ switch (call.index) {
723
+ case 0:
724
+ // Foreground: blocks until the child is done.
725
+ return Stream.make(
726
+ toolCall(
727
+ "foreground",
728
+ `const result = await delegate({ prompt: "TASK-CHILD" })
729
+ console.log(JSON.stringify(result))`,
730
+ ),
731
+ )
732
+ case 1:
733
+ return Stream.fromIterable(text("root done"))
734
+ default:
735
+ return unexpected(call)
736
+ }
737
+ }
738
+ },
739
+ })
740
+
741
+ assert.deepStrictEqual(exit, Exit.succeed("root done"))
742
+ const root = calls.filter((call) => call.role === "root")
743
+ assert.strictEqual(root.length, 2)
744
+ const foreground = lastToolResult(root[1]!.prompt)
745
+ assert.include(foreground, '"id":"1"')
746
+ assert.include(foreground, '"status":"completed"')
747
+ assert.include(foreground, "CHILD-DONE")
748
+ for (const call of root) {
749
+ assert.isFalse(
750
+ hasAnyPush(call.prompt, "2"),
751
+ "the grandchild's push never reaches the root",
752
+ )
753
+ }
754
+ }),
755
+ )
756
+ },
757
+ )
758
+ }