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
@@ -21,7 +21,16 @@ import * as NodeFs from "node:fs"
21
21
  import * as NodeOs from "node:os"
22
22
  import * as NodePath from "node:path"
23
23
  import * as AgentExecutor from "./AgentExecutor.ts"
24
- import { subagentsUnavailable } from "./AgentTools.ts"
24
+ import { agentTasksUnavailable, type Task } from "./AgentTools.ts"
25
+
26
+ // The task a stub `delegate` resolves with once its agent has finished.
27
+ const completedAgent = (id: string, prompt: string, output: string): Task => ({
28
+ id,
29
+ kind: "agent",
30
+ status: "completed",
31
+ description: prompt,
32
+ output,
33
+ })
25
34
 
26
35
  const withRpc = <A, E, R>(
27
36
  f: (
@@ -81,18 +90,14 @@ describe("RPC subagent executor", () => {
81
90
  'console.log("first:" + (await delegate({ prompt: "first" })).output)',
82
91
  onTaskComplete: () => Effect.void,
83
92
  onImage: () => Effect.void,
84
- subagents: {
85
- ...subagentsUnavailable,
86
- delegate: ({ prompt }) =>
93
+ agentTasks: {
94
+ ...agentTasksUnavailable,
95
+ delegate: ({ id, prompt }) =>
87
96
  Effect.gen(function* () {
88
97
  assert.strictEqual(prompt, "first")
89
98
  yield* Deferred.succeed(firstStarted, undefined)
90
99
  yield* Deferred.await(secondStarted)
91
- return {
92
- id: "1",
93
- status: "completed" as const,
94
- output: "first-output",
95
- }
100
+ return completedAgent(id, prompt, "first-output")
96
101
  }),
97
102
  },
98
103
  })
@@ -105,18 +110,14 @@ describe("RPC subagent executor", () => {
105
110
  'console.log("second:" + (await delegate({ prompt: "second" })).output)',
106
111
  onTaskComplete: () => Effect.void,
107
112
  onImage: () => Effect.void,
108
- subagents: {
109
- ...subagentsUnavailable,
110
- delegate: ({ prompt }) =>
113
+ agentTasks: {
114
+ ...agentTasksUnavailable,
115
+ delegate: ({ id, prompt }) =>
111
116
  Effect.gen(function* () {
112
117
  assert.strictEqual(prompt, "second")
113
118
  yield* Deferred.succeed(secondStarted, undefined)
114
119
  yield* Deferred.await(firstStarted)
115
- return {
116
- id: "2",
117
- status: "completed" as const,
118
- output: "second-output",
119
- }
120
+ return completedAgent(id, prompt, "second-output")
120
121
  }),
121
122
  },
122
123
  })
@@ -144,9 +145,9 @@ describe("RPC subagent executor", () => {
144
145
  'console.log("parent:" + (await delegate({ prompt: "outer" })).output)',
145
146
  onTaskComplete: () => Effect.void,
146
147
  onImage: () => Effect.void,
147
- subagents: {
148
- ...subagentsUnavailable,
149
- delegate: ({ prompt }) =>
148
+ agentTasks: {
149
+ ...agentTasksUnavailable,
150
+ delegate: ({ id, prompt }) =>
150
151
  Effect.gen(function* () {
151
152
  assert.strictEqual(prompt, "outer")
152
153
  const childOutput = yield* executor
@@ -157,16 +158,16 @@ describe("RPC subagent executor", () => {
157
158
  'console.log("child:" + (await delegate({ prompt: "inner" })).output)',
158
159
  onTaskComplete: () => Effect.void,
159
160
  onImage: () => Effect.void,
160
- subagents: {
161
- ...subagentsUnavailable,
162
- delegate: ({ prompt: innerPrompt }) =>
161
+ agentTasks: {
162
+ ...agentTasksUnavailable,
163
+ delegate: ({ id: innerId, prompt: innerPrompt }) =>
163
164
  Effect.sync(() => {
164
165
  assert.strictEqual(innerPrompt, "inner")
165
- return {
166
- id: "2",
167
- status: "completed" as const,
168
- output: "inner-output",
169
- }
166
+ return completedAgent(
167
+ innerId,
168
+ innerPrompt,
169
+ "inner-output",
170
+ )
170
171
  }),
171
172
  },
172
173
  })
@@ -174,11 +175,11 @@ describe("RPC subagent executor", () => {
174
175
  assert.isTrue(
175
176
  childOutput.join("").endsWith("child:inner-output\n"),
176
177
  )
177
- return {
178
- id: "1",
179
- status: "completed" as const,
180
- output: childOutput.join("").trim().split("\n").at(-1)!,
181
- }
178
+ return completedAgent(
179
+ id,
180
+ prompt,
181
+ childOutput.join("").trim().split("\n").at(-1)!,
182
+ )
182
183
  }),
183
184
  },
184
185
  })
@@ -216,11 +217,11 @@ describe("RPC executeUnsafe", () => {
216
217
  NodePath.join(environment.cwd, "x.txt"),
217
218
  "hello",
218
219
  )
219
- const agents = yield* executor.executeUnsafe({
220
- tool: "listAgents",
220
+ const tasks = yield* executor.executeUnsafe({
221
+ tool: "listTasks",
221
222
  params: undefined,
222
223
  })
223
- assert.deepStrictEqual(agents, [])
224
+ assert.deepStrictEqual(tasks, [])
224
225
  const content = yield* executor.executeUnsafe({
225
226
  tool: "readFile",
226
227
  params: { path: "x.txt", startLine: undefined, lineNumbers: false },
@@ -350,7 +351,7 @@ const runScript = (script: string) =>
350
351
  onEnvironment: () => Effect.void,
351
352
  script,
352
353
  onTaskComplete: () => Effect.void,
353
- subagents: subagentsUnavailable,
354
+ agentTasks: agentTasksUnavailable,
354
355
  onImage: () => Effect.void,
355
356
  })
356
357
  .pipe(Stream.mkString)
@@ -459,7 +460,7 @@ console.log({ name: "my-project", version: "1.0.0", scripts: { check: "oxlint -c
459
460
  for (const [mode, executorLayer] of Object.entries(executorModes)) {
460
461
  describe(`${mode} executor environment`, () => {
461
462
  // A cancelled script keeps the directory it changed to, as an ACP
462
- // `session/cancel` or a `stopAgent` continues the same agent afterwards.
463
+ // `session/cancel` or a `stopTask` continues the same agent afterwards.
463
464
  it.live("returns the environment when the caller interrupts", () =>
464
465
  Effect.gen(function* () {
465
466
  const executor = yield* AgentExecutor.AgentExecutor
@@ -477,7 +478,7 @@ await sleep(60000)`,
477
478
  updates.push(update)
478
479
  }),
479
480
  onTaskComplete: () => Effect.void,
480
- subagents: subagentsUnavailable,
481
+ agentTasks: agentTasksUnavailable,
481
482
  onImage: () => Effect.void,
482
483
  })
483
484
  .pipe(
@@ -524,7 +525,7 @@ await sleep(60000)`,
524
525
  updates.push(update)
525
526
  }),
526
527
  onTaskComplete: () => Effect.void,
527
- subagents: subagentsUnavailable,
528
+ agentTasks: agentTasksUnavailable,
528
529
  onImage: () => Effect.void,
529
530
  })
530
531
  .pipe(
@@ -562,13 +563,19 @@ await sleep(60000)`,
562
563
  const executor = yield* AgentExecutor.AgentExecutor
563
564
  const { environment } = yield* executor.capabilities
564
565
  const output = yield* runScript(`
565
- const result = await bash({
566
+ const task = await bash({
566
567
  command: ${JSON.stringify(gatedCommand(environment.cwd))},
567
568
  background: true,
568
569
  })
569
- console.log("RETURNED:", result)`)
570
- assert.include(output, "RETURNED:")
571
- assert.match(output, /background/i)
570
+ console.log("RETURNED:", JSON.stringify(task))`)
571
+ const task = JSON.parse(output.split("RETURNED:")[1]!)
572
+ assert.deepStrictEqual(task, {
573
+ id: "1",
574
+ kind: "bash",
575
+ status: "running",
576
+ description: gatedCommand(environment.cwd),
577
+ output: "",
578
+ })
572
579
  assert.strictEqual(
573
580
  yield* waitForLog(environment.cwd, started),
574
581
  "start\n",
@@ -586,19 +593,25 @@ console.log("RETURNED:", result)`)
586
593
  Effect.gen(function* () {
587
594
  const executor = yield* AgentExecutor.AgentExecutor
588
595
  const { environment } = yield* executor.capabilities
596
+ const command = `echo early && ${gatedCommand(environment.cwd)}`
589
597
  const output = yield* runScript(`
590
598
  try {
591
599
  const result = await bash({
592
- command: ${JSON.stringify(gatedCommand(environment.cwd))},
600
+ command: ${JSON.stringify(command)},
593
601
  timeoutMs: 60000,
594
602
  })
595
- console.log("RETURNED:", result)
603
+ console.log("RETURNED:", JSON.stringify(result))
596
604
  } catch (error) {
597
605
  console.log("REJECTED:", String(error))
598
606
  }`)
599
- assert.include(output, "RETURNED:")
600
607
  assert.notInclude(output, "REJECTED:")
601
- assert.match(output, /background/i)
608
+ assert.deepStrictEqual(JSON.parse(output.split("RETURNED:")[1]!), {
609
+ id: "1",
610
+ kind: "bash",
611
+ status: "running",
612
+ description: command,
613
+ output: "early\n",
614
+ })
602
615
  assert.strictEqual(
603
616
  yield* waitForLog(environment.cwd, started),
604
617
  "start\n",
@@ -615,51 +628,195 @@ try {
615
628
  ),
616
629
  )
617
630
 
618
- it.live("reports background jobs through jobOutput", () =>
631
+ // A foreground command that succeeds returns a task with an id from the
632
+ // same counter as background tasks; one that fails still rejects.
633
+ it.live(
634
+ "returns a task from a foreground bash command, or rejects on failure",
635
+ () =>
636
+ Effect.gen(function* () {
637
+ const output = yield* runScript(`
638
+ try {
639
+ console.log("OK:", JSON.stringify(await bash({ command: "echo hi" })))
640
+ console.log("RETURNED:", JSON.stringify(await bash({ command: "echo out && exit 3" })))
641
+ } catch (error) {
642
+ console.log("REJECTED:", String(error))
643
+ }`)
644
+ assert.deepStrictEqual(
645
+ JSON.parse(output.split("OK:")[1]!.split("\n")[0]!),
646
+ {
647
+ id: "1",
648
+ kind: "bash",
649
+ status: "completed",
650
+ description: "echo hi",
651
+ output: "hi\n",
652
+ exitCode: 0,
653
+ },
654
+ )
655
+ assert.match(
656
+ output,
657
+ /REJECTED:.*Command failed with exit code 3: out/,
658
+ )
659
+ assert.notInclude(output, "RETURNED:")
660
+ }).pipe(Effect.timeout("5 seconds"), Effect.provide(executorLayer({}))),
661
+ )
662
+
663
+ it.live("waits for a background bash task with waitTasks", () =>
619
664
  Effect.gen(function* () {
620
665
  const executor = yield* AgentExecutor.AgentExecutor
621
666
  const { environment } = yield* executor.capabilities
622
667
  const output = yield* runScript(`
668
+ const show = ({ id, kind, status, exitCode, output }) =>
669
+ JSON.stringify({ id, kind, status, exitCode, output })
670
+ const task = await bash({
671
+ command: ${JSON.stringify(`${gatedCommand(environment.cwd)} && echo done`)},
672
+ background: true,
673
+ })
674
+ await writeFile({ path: "gate", content: "" })
675
+ console.log("WAITED:", (await waitTasks({ ids: [task.id] })).map(show).join())`)
676
+ assert.include(
677
+ output,
678
+ 'WAITED: {"id":"1","kind":"bash","status":"completed","exitCode":0,"output":"done\\n"}',
679
+ )
680
+ }).pipe(Effect.timeout("5 seconds"), Effect.provide(executorLayer({}))),
681
+ )
682
+
683
+ // Without `timeoutMs` the wait uses the caller's command timeout, which
684
+ // also caps it. The test timeout catches a wait that never ends.
685
+ it.live("stops waiting at the timeout and leaves the task running", () =>
686
+ Effect.gen(function* () {
687
+ const executor = yield* AgentExecutor.AgentExecutor
688
+ const { environment } = yield* executor.capabilities
689
+ const output = yield* runScript(`
690
+ const task = await bash({
691
+ command: ${JSON.stringify(gatedCommand(environment.cwd))},
692
+ background: true,
693
+ })
694
+ const waits = [
695
+ ...(await waitTasks({ ids: [task.id], timeoutMs: 100 })),
696
+ ...(await waitTasks({ ids: [task.id] })),
697
+ ...(await waitTasks({ ids: [task.id], timeoutMs: 60000 })),
698
+ ]
699
+ console.log("WAITS:", JSON.stringify(waits.map((task) => task.status)))`)
700
+ assert.include(output, 'WAITS: ["running","running","running"]')
701
+ assert.strictEqual(
702
+ yield* waitForLog(environment.cwd, started),
703
+ "start\n",
704
+ "still running after the waits",
705
+ )
706
+ openGate(environment.cwd)
707
+ assert.strictEqual(
708
+ yield* waitForLog(environment.cwd, finished),
709
+ "start\nfinish\n",
710
+ )
711
+ }).pipe(
712
+ Effect.timeout("5 seconds"),
713
+ Effect.provide(executorLayer({ commandTimeout: "300 millis" })),
714
+ ),
715
+ )
716
+
717
+ // The watcher returns only after the task has ended, so the task always
718
+ // finishes before `bash` returns. `bash` must return the snapshot it
719
+ // handed over, leaving the final state to the watcher alone. Over RPC the
720
+ // server's watcher does not wait for the client's, so only local mode
721
+ // forces the ordering.
722
+ it.live("returns the task it hands to the task watcher", () =>
723
+ Effect.gen(function* () {
724
+ const executor = yield* AgentExecutor.AgentExecutor
725
+ const { environment } = yield* executor.capabilities
726
+ const watched: Array<string> = []
727
+ const claims: Array<boolean> = []
728
+ const output = yield* executor
729
+ .execute({
730
+ environment,
731
+ onEnvironment: () => Effect.void,
732
+ script: `
733
+ await bash({ command: "true" })
734
+ const { id, kind, status } = await bash({ command: "true", background: true })
735
+ console.log("RETURNED:", JSON.stringify({ id, kind, status }))`,
736
+ onTaskComplete: () => Effect.void,
737
+ agentTasks: agentTasksUnavailable,
738
+ onImage: () => Effect.void,
739
+ onTask: (task) =>
740
+ Effect.gen(function* () {
741
+ watched.push(task.id)
742
+ yield* task.await
743
+ claims.push(yield* task.claim)
744
+ }),
745
+ })
746
+ .pipe(Stream.mkString)
747
+ assert.include(
748
+ output,
749
+ 'RETURNED: {"id":"2","kind":"bash","status":"running"}',
750
+ )
751
+ assert.deepStrictEqual(watched, ["2"], "only the running task")
752
+ assert.deepStrictEqual(claims, [true], "reported once, by the watcher")
753
+ }).pipe(Effect.timeout("5 seconds"), Effect.provide(executorLayer({}))),
754
+ )
755
+
756
+ it.live("reports background bash tasks through taskOutput", () =>
757
+ Effect.gen(function* () {
758
+ const executor = yield* AgentExecutor.AgentExecutor
759
+ const { environment } = yield* executor.capabilities
760
+ const output = yield* runScript(`
761
+ const show = ({ id, kind, status, exitCode, output }) =>
762
+ JSON.stringify({ id, kind, status, exitCode, output })
623
763
  const done = async (id) => {
624
- let job = await jobOutput(id)
625
- while (job.status === "running") {
764
+ let task = await taskOutput(id)
765
+ while (task.status === "running") {
626
766
  await sleep(20)
627
- job = await jobOutput(id)
767
+ task = await taskOutput(id)
628
768
  }
629
- return job
769
+ return task
630
770
  }
631
771
  await bash({ command: ${JSON.stringify(gatedCommand(environment.cwd))}, background: true })
632
772
  await bash({ command: "echo out && exit 3", background: true })
633
- console.log("RUNNING:", JSON.stringify(await jobOutput("1")))
773
+ console.log("RUNNING:", show(await taskOutput("1")))
634
774
  await writeFile({ path: "gate", content: "" })
635
- console.log("COMPLETED:", JSON.stringify(await done("1")))
636
- console.log("FAILED:", JSON.stringify(await done("2")))`)
637
- assert.include(output, 'RUNNING: {"id":"1","status":"running"')
775
+ console.log("COMPLETED:", show(await done("1")))
776
+ console.log("FAILED:", show(await done("2")))`)
777
+ assert.include(
778
+ output,
779
+ 'RUNNING: {"id":"1","kind":"bash","status":"running","output":""}',
780
+ )
638
781
  assert.include(
639
782
  output,
640
- 'COMPLETED: {"id":"1","status":"completed","exitCode":0,"output":""}',
783
+ 'COMPLETED: {"id":"1","kind":"bash","status":"completed","exitCode":0,"output":""}',
641
784
  )
642
785
  assert.include(
643
786
  output,
644
- 'FAILED: {"id":"2","status":"failed","exitCode":3,"output":"out\\n"}',
787
+ 'FAILED: {"id":"2","kind":"bash","status":"failed","exitCode":3,"output":"out\\n"}',
645
788
  )
646
789
  }).pipe(Effect.timeout("5 seconds"), Effect.provide(executorLayer({}))),
647
790
  )
648
791
 
649
- it.live("stops a background job with stopJob", () =>
792
+ it.live("stops a background bash task with stopTask", () =>
650
793
  Effect.gen(function* () {
651
794
  const executor = yield* AgentExecutor.AgentExecutor
652
795
  const { environment } = yield* executor.capabilities
653
796
  const output = yield* runScript(`
797
+ const show = ({ id, kind, status }) => JSON.stringify({ id, kind, status })
654
798
  await bash({ command: ${JSON.stringify(gatedCommand(environment.cwd))}, background: true })
655
- console.log("STOPPED:", JSON.stringify(await stopJob("1")))
656
799
  try {
657
- await stopJob("99")
800
+ await messageAgent({ id: "1", message: "hello" })
801
+ } catch (error) {
802
+ console.log("MESSAGE-REJECTED:", String(error))
803
+ }
804
+ console.log("STOPPED:", show(await stopTask("1")))
805
+ try {
806
+ await stopTask("99")
658
807
  } catch (error) {
659
808
  console.log("REJECTED:", String(error))
660
809
  }`)
661
- assert.include(output, 'STOPPED: {"id":"1","status":"stopped"')
662
- assert.match(output, /REJECTED:.*No background job with id "99"/)
810
+ assert.match(
811
+ output,
812
+ /MESSAGE-REJECTED:.*\bbash\b/,
813
+ "messageAgent only addresses agent tasks",
814
+ )
815
+ assert.include(
816
+ output,
817
+ 'STOPPED: {"id":"1","kind":"bash","status":"stopped"}',
818
+ )
819
+ assert.match(output, /REJECTED:.*No task with id "99".*listTasks\(\)/)
663
820
  openGate(environment.cwd)
664
821
  yield* Effect.sleep("500 millis")
665
822
  assert.notInclude(
@@ -698,7 +855,7 @@ try {
698
855
 
699
856
  // The log sits outside the executor's directory, which is removed with
700
857
  // the executor.
701
- it.live("stops background jobs when the executor shuts down", () =>
858
+ it.live("stops background bash tasks when the executor shuts down", () =>
702
859
  Effect.gen(function* () {
703
860
  const fs = yield* FileSystem.FileSystem
704
861
  const directory = yield* fs.makeTempDirectoryScoped()
@@ -762,7 +919,7 @@ try {
762
919
  onEnvironment: () => Effect.void,
763
920
  onTaskComplete: () => Effect.void,
764
921
  onImage: () => Effect.void,
765
- subagents: subagentsUnavailable,
922
+ agentTasks: agentTasksUnavailable,
766
923
  script: `
767
924
  console.log("before")
768
925
  await sleep(10000)
@@ -841,8 +998,8 @@ console.log("MAIN" + "_DONE")`)
841
998
  delegate({ prompt: "never finishes" })
842
999
  sleep(100).then(() => console.constructor.constructor("return process")().exit(7))`,
843
1000
  onTaskComplete: () => Effect.void,
844
- subagents: {
845
- ...subagentsUnavailable,
1001
+ agentTasks: {
1002
+ ...agentTasksUnavailable,
846
1003
  delegate: () => Effect.never,
847
1004
  },
848
1005
  onImage: () => Effect.void,
@@ -859,10 +1016,10 @@ sleep(100).then(() => console.constructor.constructor("return process")().exit(7
859
1016
  tool: "bash",
860
1017
  params: { command: "seq 1 1000000" },
861
1018
  })
862
- assert(typeof output === "string")
863
- assert.isBelow(output.length, 10_000 + 500)
864
- assert.isTrue(output.startsWith("1\n2\n3\n"), "start kept")
865
- assert.isTrue(output.trimEnd().endsWith("999999\n1000000"), "end kept")
1019
+ const { output: text } = output as { readonly output: string }
1020
+ assert.isBelow(text.length, 10_000 + 500)
1021
+ assert.isTrue(text.startsWith("1\n2\n3\n"), "start kept")
1022
+ assert.isTrue(text.trimEnd().endsWith("999999\n1000000"), "end kept")
866
1023
  }).pipe(
867
1024
  Effect.timeout("10 seconds"),
868
1025
  Effect.provide(executorLayer({ commandOutputChars: 10_000 })),