clanka 0.9.0 → 0.10.1

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 (81) hide show
  1. package/dist/Acp.d.ts +6 -1
  2. package/dist/Acp.d.ts.map +1 -1
  3. package/dist/Acp.js +25 -0
  4. package/dist/Acp.js.map +1 -1
  5. package/dist/Acp.test.js +109 -4
  6. package/dist/Acp.test.js.map +1 -1
  7. package/dist/AcpImage.test.js +6 -1
  8. package/dist/AcpImage.test.js.map +1 -1
  9. package/dist/Agent.d.ts +17 -0
  10. package/dist/Agent.d.ts.map +1 -1
  11. package/dist/Agent.js +91 -15
  12. package/dist/Agent.js.map +1 -1
  13. package/dist/Agent.test.js +9 -1
  14. package/dist/Agent.test.js.map +1 -1
  15. package/dist/AgentCallerConfig.test.js +9 -1
  16. package/dist/AgentCallerConfig.test.js.map +1 -1
  17. package/dist/AgentEnvironment.d.ts +76 -0
  18. package/dist/AgentEnvironment.d.ts.map +1 -0
  19. package/dist/AgentEnvironment.js +119 -0
  20. package/dist/AgentEnvironment.js.map +1 -0
  21. package/dist/AgentEnvironment.test.d.ts +2 -0
  22. package/dist/AgentEnvironment.test.d.ts.map +1 -0
  23. package/dist/AgentEnvironment.test.js +304 -0
  24. package/dist/AgentEnvironment.test.js.map +1 -0
  25. package/dist/AgentExecutor.d.ts +146 -187
  26. package/dist/AgentExecutor.d.ts.map +1 -1
  27. package/dist/AgentExecutor.js +212 -49
  28. package/dist/AgentExecutor.js.map +1 -1
  29. package/dist/AgentExecutor.test.js +94 -8
  30. package/dist/AgentExecutor.test.js.map +1 -1
  31. package/dist/AgentExecutorImage.test.js +3 -0
  32. package/dist/AgentExecutorImage.test.js.map +1 -1
  33. package/dist/AgentImage.test.js +11 -2
  34. package/dist/AgentImage.test.js.map +1 -1
  35. package/dist/AgentOutput.d.ts +17 -4
  36. package/dist/AgentOutput.d.ts.map +1 -1
  37. package/dist/AgentOutput.js +13 -0
  38. package/dist/AgentOutput.js.map +1 -1
  39. package/dist/AgentSkills.d.ts +15 -0
  40. package/dist/AgentSkills.d.ts.map +1 -1
  41. package/dist/AgentSkills.js +60 -32
  42. package/dist/AgentSkills.js.map +1 -1
  43. package/dist/AgentSkills.test.js +12 -2
  44. package/dist/AgentSkills.test.js.map +1 -1
  45. package/dist/AgentSubagents.test.js +42 -0
  46. package/dist/AgentSubagents.test.js.map +1 -1
  47. package/dist/AgentTools.d.ts +4 -0
  48. package/dist/AgentTools.d.ts.map +1 -1
  49. package/dist/AgentTools.js +7 -2
  50. package/dist/AgentTools.js.map +1 -1
  51. package/dist/AgentToolsReadFile.test.d.ts +2 -0
  52. package/dist/AgentToolsReadFile.test.d.ts.map +1 -0
  53. package/dist/AgentToolsReadFile.test.js +49 -0
  54. package/dist/AgentToolsReadFile.test.js.map +1 -0
  55. package/dist/OutputFormatter.d.ts.map +1 -1
  56. package/dist/OutputFormatter.js +3 -0
  57. package/dist/OutputFormatter.js.map +1 -1
  58. package/dist/bin/{OutputFormatter-DXXKo4E8.mjs → OutputFormatter-BFAv48k9.mjs} +2 -1
  59. package/dist/bin/{OutputFormatter-DXXKo4E8.mjs.map → OutputFormatter-BFAv48k9.mjs.map} +1 -1
  60. package/dist/bin/cli.mjs +13318 -13094
  61. package/dist/bin/cli.mjs.map +1 -1
  62. package/package.json +1 -1
  63. package/src/Acp.test.ts +162 -5
  64. package/src/Acp.ts +24 -1
  65. package/src/AcpImage.test.ts +6 -1
  66. package/src/Agent.test.ts +9 -1
  67. package/src/Agent.ts +137 -12
  68. package/src/AgentCallerConfig.test.ts +9 -1
  69. package/src/AgentEnvironment.test.ts +504 -0
  70. package/src/AgentEnvironment.ts +161 -0
  71. package/src/AgentExecutor.test.ts +121 -4
  72. package/src/AgentExecutor.ts +388 -99
  73. package/src/AgentExecutorImage.test.ts +3 -0
  74. package/src/AgentImage.test.ts +11 -2
  75. package/src/AgentOutput.ts +17 -0
  76. package/src/AgentSkills.test.ts +12 -2
  77. package/src/AgentSkills.ts +74 -34
  78. package/src/AgentSubagents.test.ts +66 -0
  79. package/src/AgentTools.ts +13 -1
  80. package/src/AgentToolsReadFile.test.ts +61 -0
  81. package/src/OutputFormatter.ts +3 -0
@@ -69,8 +69,11 @@ describe("RPC image executor", () => {
69
69
  withRpc((executor) =>
70
70
  Effect.gen(function* () {
71
71
  const images: Array<ImageAttachment> = []
72
+ const { environment } = yield* executor.capabilities
72
73
  const output = yield* executor
73
74
  .execute({
75
+ environment,
76
+ onEnvironment: () => Effect.void,
74
77
  script: fixtures
75
78
  .map(
76
79
  ([name]) =>
@@ -17,7 +17,12 @@ import { tinyPng } from "./fixtures/TestImages.ts"
17
17
 
18
18
  const capabilities = new AgentExecutor.Capabilities({
19
19
  toolsDts: "",
20
- agentsMd: Option.none(),
20
+ environment: new AgentExecutor.ExecutionEnvironment({
21
+ cwd: "/",
22
+ baseline: [],
23
+ seen: [],
24
+ }),
25
+ instructions: Option.none(),
21
26
  supportsSearch: false,
22
27
  tools: [],
23
28
  skills: [],
@@ -265,11 +270,15 @@ describe("Agent images", () => {
265
270
 
266
271
  it.effect("does not copy image bytes into a delegate prompt", () =>
267
272
  Effect.gen(function* () {
268
- const executor = makeExecutor(({ subagents }) =>
273
+ const executor = makeExecutor(({ subagents, environment }) =>
269
274
  Stream.fromEffect(
270
275
  subagents.delegate({
271
276
  prompt: "child task: describe the layout",
272
277
  background: false,
278
+ environment: new AgentExecutor.EnvironmentUpdate({
279
+ environment,
280
+ update: Option.none(),
281
+ }),
273
282
  }),
274
283
  ).pipe(
275
284
  Stream.map((result) => result.output ?? ""),
@@ -214,6 +214,21 @@ export class CompactionEnded extends Schema.TaggedClass<CompactionEnded>()(
214
214
  },
215
215
  ) {}
216
216
 
217
+ /**
218
+ * Emitted when AGENTS.md files or skills the model has not seen yet are
219
+ * added to the history, after a directory change or a compaction. `update`
220
+ * is the text the model receives.
221
+ *
222
+ * @since 1.0.0
223
+ * @category Output
224
+ */
225
+ export class EnvironmentUpdated extends Schema.TaggedClass<EnvironmentUpdated>()(
226
+ "EnvironmentUpdated",
227
+ {
228
+ update: Schema.String,
229
+ },
230
+ ) {}
231
+
217
232
  export type ContentPart =
218
233
  | ReasoningStart
219
234
  | ReasoningDelta
@@ -227,6 +242,7 @@ export type ContentPart =
227
242
  | ExecuteOutputCapped
228
243
  | CompactionStarted
229
244
  | CompactionEnded
245
+ | EnvironmentUpdated
230
246
 
231
247
  export const ContentPart = Schema.Union([
232
248
  ReasoningStart,
@@ -241,6 +257,7 @@ export const ContentPart = Schema.Union([
241
257
  ExecuteOutputCapped,
242
258
  CompactionStarted,
243
259
  CompactionEnded,
260
+ EnvironmentUpdated,
244
261
  ])
245
262
 
246
263
  /**
@@ -521,7 +521,12 @@ describe("AgentSkills", () => {
521
521
  it("defaults skills when constructing capabilities without the new field", () => {
522
522
  const capabilities = new AgentExecutor.Capabilities({
523
523
  toolsDts: "",
524
- agentsMd: Option.none(),
524
+ environment: new AgentExecutor.ExecutionEnvironment({
525
+ cwd: "/",
526
+ baseline: [],
527
+ seen: [],
528
+ }),
529
+ instructions: Option.none(),
525
530
  supportsSearch: false,
526
531
  tools: [],
527
532
  })
@@ -835,7 +840,12 @@ const makeExecutor = (skills: ReadonlyArray<AgentSkills.Skill>) =>
835
840
  capabilities: Effect.succeed(
836
841
  new AgentExecutor.Capabilities({
837
842
  toolsDts: "",
838
- agentsMd: Option.none(),
843
+ environment: new AgentExecutor.ExecutionEnvironment({
844
+ cwd: "/",
845
+ baseline: [],
846
+ seen: [],
847
+ }),
848
+ instructions: Option.none(),
839
849
  supportsSearch: false,
840
850
  tools: [],
841
851
  skills,
@@ -56,7 +56,6 @@ export const discover: (options: {
56
56
  never,
57
57
  FileSystem.FileSystem | Path.Path
58
58
  > = Effect.fnUntraced(function* (options) {
59
- const fs = yield* FileSystem.FileSystem
60
59
  const path = yield* Path.Path
61
60
 
62
61
  const roots: Array<{ readonly root: string; readonly source: SkillSource }> =
@@ -84,39 +83,71 @@ export const discover: (options: {
84
83
  }
85
84
 
86
85
  const byName = new Map<string, Skill>()
87
- for (const { root: skillsDir, source } of roots) {
88
- const entries = yield* fs
89
- .readDirectory(skillsDir)
90
- .pipe(Effect.orElseSucceed(() => []))
91
- entries.sort()
92
- for (const entry of entries) {
93
- const files = yield* fs
94
- .readDirectory(path.join(skillsDir, entry))
95
- .pipe(Effect.orElseSucceed((): Array<string> => []))
96
- if (!files.includes("SKILL.md")) continue
97
- const location = path.join(skillsDir, entry, "SKILL.md")
98
- const content = yield* Effect.option(
99
- fs.stat(location).pipe(
100
- Effect.filterOrFail((info) => info.type === "File"),
101
- Effect.andThen(() => fs.readFileString(location)),
102
- ),
103
- )
104
- if (Option.isNone(content)) continue
105
- const frontmatter = parseFrontmatter(content.value)
106
- if (Option.isNone(frontmatter)) continue
107
- const description = singleLine(frontmatter.value.description)
108
- if (description === "") continue
109
- const name = Predicate.isString(frontmatter.value.name)
110
- ? singleLine(frontmatter.value.name) || singleLine(entry)
111
- : singleLine(entry)
112
- if (byName.has(name)) continue
113
- byName.set(name, new Skill({ name, description, location, source }))
86
+ for (const { root, source } of roots) {
87
+ for (const skill of yield* scan(root, source)) {
88
+ if (!byName.has(skill.name)) byName.set(skill.name, skill)
114
89
  }
115
90
  }
116
91
 
117
92
  return Array.from(byName.values())
118
93
  })
119
94
 
95
+ /**
96
+ * Scan only `<directory>/.agents/skills/<dir>/SKILL.md`, as `discover` does
97
+ * for the project.
98
+ *
99
+ * @since 1.0.0
100
+ * @category Discovery
101
+ */
102
+ export const discoverProject: (
103
+ directory: string,
104
+ ) => Effect.Effect<
105
+ ReadonlyArray<Skill>,
106
+ never,
107
+ FileSystem.FileSystem | Path.Path
108
+ > = Effect.fnUntraced(function* (directory) {
109
+ const path = yield* Path.Path
110
+ return yield* scan(path.resolve(directory, ".agents", "skills"), "project")
111
+ })
112
+
113
+ // The skills in one `skills` directory. The first name wins.
114
+ const scan = Effect.fnUntraced(function* (
115
+ skillsDir: string,
116
+ source: SkillSource,
117
+ ) {
118
+ const fs = yield* FileSystem.FileSystem
119
+ const path = yield* Path.Path
120
+ const byName = new Map<string, Skill>()
121
+ const entries = yield* fs
122
+ .readDirectory(skillsDir)
123
+ .pipe(Effect.orElseSucceed(() => []))
124
+ entries.sort()
125
+ for (const entry of entries) {
126
+ const files = yield* fs
127
+ .readDirectory(path.join(skillsDir, entry))
128
+ .pipe(Effect.orElseSucceed((): Array<string> => []))
129
+ if (!files.includes("SKILL.md")) continue
130
+ const location = path.join(skillsDir, entry, "SKILL.md")
131
+ const content = yield* Effect.option(
132
+ fs.stat(location).pipe(
133
+ Effect.filterOrFail((info) => info.type === "File"),
134
+ Effect.andThen(() => fs.readFileString(location)),
135
+ ),
136
+ )
137
+ if (Option.isNone(content)) continue
138
+ const frontmatter = parseFrontmatter(content.value)
139
+ if (Option.isNone(frontmatter)) continue
140
+ const description = singleLine(frontmatter.value.description)
141
+ if (description === "") continue
142
+ const name = Predicate.isString(frontmatter.value.name)
143
+ ? singleLine(frontmatter.value.name) || singleLine(entry)
144
+ : singleLine(entry)
145
+ if (byName.has(name)) continue
146
+ byName.set(name, new Skill({ name, description, location, source }))
147
+ }
148
+ return Array.from(byName.values())
149
+ })
150
+
120
151
  /**
121
152
  * Render the skills prompt section, or `None` for an empty catalog.
122
153
  *
@@ -127,12 +158,7 @@ export const renderCatalog = (
127
158
  skills: ReadonlyArray<Skill>,
128
159
  ): Option.Option<string> => {
129
160
  if (skills.length === 0) return Option.none()
130
- const entries = skills
131
- .map(
132
- (skill) => `- ${skill.name}: ${skill.description}
133
- location: ${renderLocation(skill.location)}`,
134
- )
135
- .join("\n")
161
+ const entries = renderEntries(skills)
136
162
  return Option.some(`# Skills
137
163
 
138
164
  The following skills are available. Each one is a folder with instructions for
@@ -149,6 +175,20 @@ paths when accessing them.
149
175
  ${entries}`)
150
176
  }
151
177
 
178
+ /**
179
+ * One catalog line, plus its location, per skill.
180
+ *
181
+ * @since 1.0.0
182
+ * @category Rendering
183
+ */
184
+ export const renderEntries = (skills: ReadonlyArray<Skill>): string =>
185
+ skills
186
+ .map(
187
+ (skill) => `- ${skill.name}: ${skill.description}
188
+ location: ${renderLocation(skill.location)}`,
189
+ )
190
+ .join("\n")
191
+
152
192
  /**
153
193
  * A skill supplied by the caller instead of discovered on the executor. Its
154
194
  * content stays on the loop side and is read with `readSkill`.
@@ -753,6 +753,72 @@ console.log(JSON.stringify(result))`,
753
753
  }
754
754
  }),
755
755
  )
756
+
757
+ it.effect(
758
+ "each agent keeps its own working directory, starting from its parent's",
759
+ () =>
760
+ Effect.gen(function* () {
761
+ // Both children change directory before either prints it, so a
762
+ // shared directory shows up as the wrong path.
763
+ const bothChanged = Latch.makeUnsafe(false)
764
+ let changed = 0
765
+ const { exit, calls } = yield* runAgent({
766
+ conversationMode: true,
767
+ respond: (call) => {
768
+ if (call.role === "child") {
769
+ const name = firstUserText(call.prompt).includes("ONE")
770
+ ? "one"
771
+ : "two"
772
+ if (toolResultTexts(call.prompt).length === 0) {
773
+ return Stream.make(
774
+ toolCall(
775
+ `cd-${name}`,
776
+ `await changeDirectory("${name}")`,
777
+ ),
778
+ )
779
+ }
780
+ if (++changed === 2) bothChanged.openUnsafe()
781
+ return Stream.fromEffect(bothChanged.await).pipe(
782
+ Stream.flatMap(() =>
783
+ Stream.make(
784
+ toolCall(
785
+ `pwd-${name}`,
786
+ `const pwd = await bash({ command: "pwd" })
787
+ await taskComplete("${name.toUpperCase()}:" + pwd.trim())`,
788
+ ),
789
+ ),
790
+ ),
791
+ )
792
+ }
793
+ switch (call.index) {
794
+ case 0:
795
+ return Stream.make(
796
+ toolCall(
797
+ "spawn",
798
+ `await bash({ command: "mkdir -p a/one a/two" })
799
+ await changeDirectory("a")
800
+ await delegate({ prompt: "TASK-CHILD-ONE", background: true })
801
+ await delegate({ prompt: "TASK-CHILD-TWO", background: true })
802
+ console.log(JSON.stringify(await waitAgents()))
803
+ console.log("ROOT:" + (await bash({ command: "pwd" })).trim())`,
804
+ ),
805
+ )
806
+ case 1:
807
+ return Stream.fromIterable(text("done"))
808
+ default:
809
+ return unexpected(call)
810
+ }
811
+ },
812
+ })
813
+
814
+ assert.deepStrictEqual(exit, Exit.succeed("done"))
815
+ const root = calls.filter((call) => call.role === "root")
816
+ const result = lastToolResult(root[1]!.prompt)
817
+ assert.match(result, /ONE:[^"\s]*\/a\/one"/)
818
+ assert.match(result, /TWO:[^"\s]*\/a\/two"/)
819
+ assert.match(result, /ROOT:\S*\/a$/m)
820
+ }),
821
+ )
756
822
  },
757
823
  )
758
824
  }
package/src/AgentTools.ts CHANGED
@@ -275,7 +275,7 @@ export const makeContextNoop = (cwd?: string) =>
275
275
  export const AgentTools = Toolkit.make(
276
276
  Tool.make("changeDirectory", {
277
277
  description:
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 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.",
279
279
  parameters: Schema.String.annotate({ identifier: "directory" }),
280
280
  success: Schema.String,
281
281
  dependencies: [DirectoryChanger],
@@ -287,6 +287,10 @@ export const AgentTools = Toolkit.make(
287
287
  path: Schema.String,
288
288
  startLine: Schema.optional(Schema.Number),
289
289
  endLine: Schema.optional(Schema.Number),
290
+ lineNumbers: Schema.optional(Schema.Boolean).annotate({
291
+ documentation:
292
+ "Prefix text lines with their line numbers (default: true)",
293
+ }),
290
294
  }),
291
295
  success: Schema.NullOr(Schema.String),
292
296
  dependencies: [CurrentDirectory, ImageAttacher],
@@ -603,6 +607,14 @@ export const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(
603
607
  )
604
608
  }
605
609
  return yield* Stream.runCollect(stream).pipe(
610
+ Effect.map((lines) =>
611
+ options.lineNumbers === false
612
+ ? lines
613
+ : lines.map(
614
+ (line, index) =>
615
+ `${(options.startLine ?? 1) + index}: ${line}`,
616
+ ),
617
+ ),
606
618
  Effect.map(Array.join("\n")),
607
619
  Effect.catchReason("PlatformError", "NotFound", () =>
608
620
  Effect.succeed(null),
@@ -0,0 +1,61 @@
1
+ import { assert, describe, it } from "@effect/vitest"
2
+ import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient"
3
+ import * as NodeServices from "@effect/platform-node/NodeServices"
4
+ import * as Effect from "effect/Effect"
5
+ import * as FileSystem from "effect/FileSystem"
6
+ import * as Layer from "effect/Layer"
7
+ import * as Path from "effect/Path"
8
+ import * as AgentExecutor from "./AgentExecutor.ts"
9
+
10
+ describe("readFile line numbers", () => {
11
+ const cases = [
12
+ {
13
+ name: "numbers lines by default",
14
+ options: {},
15
+ expected: "1: alpha\n2: beta\n3: gamma\n4: delta",
16
+ },
17
+ {
18
+ name: "numbers lines when explicitly enabled",
19
+ options: { lineNumbers: true },
20
+ expected: "1: alpha\n2: beta\n3: gamma\n4: delta",
21
+ },
22
+ {
23
+ name: "returns unnumbered text when disabled",
24
+ options: { lineNumbers: false },
25
+ expected: "alpha\nbeta\ngamma\ndelta",
26
+ },
27
+ {
28
+ name: "preserves original line numbers for a selected range",
29
+ options: { lineNumbers: true, startLine: 2, endLine: 3 },
30
+ expected: "2: beta\n3: gamma",
31
+ },
32
+ ]
33
+
34
+ for (const { name, options, expected } of cases) {
35
+ it.effect(name, () =>
36
+ Effect.gen(function* () {
37
+ const fs = yield* FileSystem.FileSystem
38
+ const path = yield* Path.Path
39
+ const project = yield* fs.makeTempDirectoryScoped()
40
+ yield* fs.writeFileString(
41
+ path.join(project, "sample.txt"),
42
+ "alpha\nbeta\ngamma\ndelta",
43
+ )
44
+ const result = yield* Effect.gen(function* () {
45
+ const executor = yield* AgentExecutor.AgentExecutor
46
+ return yield* executor.executeUnsafe({
47
+ tool: "readFile",
48
+ params: { path: "sample.txt", ...options },
49
+ })
50
+ }).pipe(
51
+ Effect.provide(
52
+ AgentExecutor.layerLocal({ directory: project }).pipe(
53
+ Layer.provide(NodeHttpClient.layerUndici),
54
+ ),
55
+ ),
56
+ )
57
+ assert.strictEqual(result, expected)
58
+ }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
59
+ )
60
+ }
61
+ })
@@ -117,6 +117,9 @@ ${chalk.dim(output.summary)}\n\n`
117
117
  case "CompactionEnded": {
118
118
  return `${prefix}${chalkInfoHeading(`${infoIcon} Context compacted (${output.reason}):`)} ~${numberFormat.format(output.tokensBefore)} tokens to ~${numberFormat.format(output.tokensAfter)}\n\n`
119
119
  }
120
+ case "EnvironmentUpdated": {
121
+ return `${prefix}${chalkInfoHeading(`${infoIcon} Environment update:`)}\n\n${chalk.dim(truncate(output.update))}\n\n`
122
+ }
120
123
  case "HistoryAppended":
121
124
  case "HistoryReplaced": {
122
125
  return ""