clanka 0.9.0 → 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 (74) 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 +90 -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.js +1 -1
  48. package/dist/AgentTools.js.map +1 -1
  49. package/dist/OutputFormatter.d.ts.map +1 -1
  50. package/dist/OutputFormatter.js +3 -0
  51. package/dist/OutputFormatter.js.map +1 -1
  52. package/dist/bin/{OutputFormatter-DXXKo4E8.mjs → OutputFormatter-BFAv48k9.mjs} +2 -1
  53. package/dist/bin/{OutputFormatter-DXXKo4E8.mjs.map → OutputFormatter-BFAv48k9.mjs.map} +1 -1
  54. package/dist/bin/cli.mjs +13316 -13094
  55. package/dist/bin/cli.mjs.map +1 -1
  56. package/package.json +1 -1
  57. package/src/Acp.test.ts +162 -5
  58. package/src/Acp.ts +24 -1
  59. package/src/AcpImage.test.ts +6 -1
  60. package/src/Agent.test.ts +9 -1
  61. package/src/Agent.ts +136 -12
  62. package/src/AgentCallerConfig.test.ts +9 -1
  63. package/src/AgentEnvironment.test.ts +504 -0
  64. package/src/AgentEnvironment.ts +161 -0
  65. package/src/AgentExecutor.test.ts +121 -4
  66. package/src/AgentExecutor.ts +388 -99
  67. package/src/AgentExecutorImage.test.ts +3 -0
  68. package/src/AgentImage.test.ts +11 -2
  69. package/src/AgentOutput.ts +17 -0
  70. package/src/AgentSkills.test.ts +12 -2
  71. package/src/AgentSkills.ts +74 -34
  72. package/src/AgentSubagents.test.ts +66 -0
  73. package/src/AgentTools.ts +1 -1
  74. package/src/OutputFormatter.ts +3 -0
@@ -29,6 +29,7 @@ import {
29
29
  } from "./AgentTools.ts"
30
30
  import * as Image from "./Image.ts"
31
31
  import { ToolkitRenderer } from "./ToolkitRenderer.ts"
32
+ import * as AgentEnvironment from "./AgentEnvironment.ts"
32
33
  import * as AgentSkills from "./AgentSkills.ts"
33
34
  import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"
34
35
  import type * as HttpClient from "effect/http/HttpClient"
@@ -72,7 +73,31 @@ export class AgentExecutor extends Context.Service<
72
73
  executeUnsafe<Tool extends keyof typeof AgentTools.tools>(options: {
73
74
  readonly tool: Tool
74
75
  readonly params: (typeof AgentTools.tools)[Tool]["parametersSchema"]["Encoded"]
76
+ /**
77
+ * The environment the tool runs in. Defaults to the startup
78
+ * environment. Changes made by the tool are not returned.
79
+ */
80
+ readonly environment?: ExecutionEnvironment | undefined
75
81
  }): Effect.Effect<Schema.Json>
82
+ /**
83
+ * Render the AGENTS.md files and skills that apply to the environment's
84
+ * directory and that the model has not seen yet. The agent calls it once
85
+ * after the scripts of a model response, so one update covers all of
86
+ * them; `execute` itself never renders one.
87
+ *
88
+ * With `reset`, everything sent since the system prompt is forgotten and
89
+ * rendered again. Any operation that rewrites the history, such as
90
+ * compaction, must do this, so the environment's record of what the
91
+ * model has seen matches the history.
92
+ *
93
+ * Optional: without it the agent sends no updates.
94
+ */
95
+ readonly renderEnvironment?:
96
+ | ((
97
+ environment: ExecutionEnvironment,
98
+ options?: { readonly reset?: boolean | undefined } | undefined,
99
+ ) => Effect.Effect<EnvironmentUpdate>)
100
+ | undefined
76
101
  }
77
102
  >()("clanka/AgentExecutor") {}
78
103
 
@@ -82,6 +107,20 @@ export class AgentExecutor extends Context.Service<
82
107
  */
83
108
  export interface ExecuteOptions {
84
109
  readonly script: string
110
+ /**
111
+ * The environment the script starts in: the `environment` of the last
112
+ * `onEnvironment` call for this agent, or `Capabilities.environment` for
113
+ * its first script.
114
+ */
115
+ readonly environment: ExecutionEnvironment
116
+ /**
117
+ * Receives the environment the script left behind, once, when the script
118
+ * ends. It is also called when the script fails, times out or is
119
+ * interrupted. Pass it to the next `execute` of the same agent.
120
+ */
121
+ readonly onEnvironment: (
122
+ environment: ExecutionEnvironment,
123
+ ) => Effect.Effect<void>
85
124
  /**
86
125
  * Fails with a message for the script when the task cannot be completed
87
126
  * yet, for example while sub-agents are still running.
@@ -90,7 +129,7 @@ export interface ExecuteOptions {
90
129
  /**
91
130
  * The sub-agents of the agent running the script.
92
131
  */
93
- readonly subagents: Subagents
132
+ readonly subagents: ExecuteSubagents
94
133
  /**
95
134
  * Receives every image `readFile` attached while the script ran.
96
135
  */
@@ -102,6 +141,65 @@ export interface ExecuteOptions {
102
141
  readonly loopTools?: LoopToolHandlers | undefined
103
142
  }
104
143
 
144
+ /**
145
+ * The sub-agents of the agent running a script. `delegate` also receives the
146
+ * environment the new agent starts in: the script's directory at the moment
147
+ * `delegate` was called, with an update holding everything that applies to
148
+ * it beyond the system prompt.
149
+ *
150
+ * @since 1.0.0
151
+ * @category Models
152
+ */
153
+ export interface ExecuteSubagents extends Omit<Subagents, "delegate"> {
154
+ readonly delegate: (options: {
155
+ readonly prompt: string
156
+ readonly background: boolean
157
+ readonly environment: EnvironmentUpdate
158
+ }) => Effect.Effect<DelegateResult>
159
+ }
160
+
161
+ /**
162
+ * The state the executor keeps for one agent, such as its working directory.
163
+ * Only the executor reads its fields. The agent stores the value it last
164
+ * received from `onEnvironment` and passes it to its next `execute`, so every
165
+ * agent has its own working directory.
166
+ *
167
+ * @since 1.0.0
168
+ * @category Models
169
+ */
170
+ export class ExecutionEnvironment extends Schema.Class<ExecutionEnvironment>(
171
+ "clanka/AgentExecutor/ExecutionEnvironment",
172
+ )({
173
+ cwd: Schema.String,
174
+ /**
175
+ * Ids of the context items already in the system prompt.
176
+ */
177
+ baseline: Schema.Array(Schema.String),
178
+ /**
179
+ * Ids of the context items sent to the model in the history since.
180
+ */
181
+ seen: Schema.Array(Schema.String),
182
+ }) {}
183
+
184
+ /**
185
+ * @since 1.0.0
186
+ * @category Models
187
+ */
188
+ export class EnvironmentUpdate extends Schema.Class<EnvironmentUpdate>(
189
+ "clanka/AgentExecutor/EnvironmentUpdate",
190
+ )({
191
+ /**
192
+ * The environment once `update` is in the history: what it describes
193
+ * counts as seen. Store it only together with the update.
194
+ */
195
+ environment: ExecutionEnvironment,
196
+ /**
197
+ * AGENTS.md files and skills the model has not seen yet, or `None` when
198
+ * nothing is new. The agent wraps it in an `<environment-update>` message.
199
+ */
200
+ update: Schema.Option(Schema.String),
201
+ }) {}
202
+
105
203
  /**
106
204
  * Loop-side tool handlers by function name. A handler receives the script's
107
205
  * argument undecoded; a failure rejects the script's call with the string as
@@ -120,8 +218,15 @@ export type LoopToolHandlers = Readonly<
120
218
  */
121
219
  export class Capabilities extends Schema.Class<Capabilities>("Capabilities")({
122
220
  toolsDts: Schema.String,
123
- agentsMd: Schema.Option(Schema.String),
221
+ /**
222
+ * The startup AGENTS.md as rendered for the system prompt, with its path.
223
+ */
224
+ instructions: Schema.Option(Schema.String),
124
225
  supportsSearch: Schema.Boolean,
226
+ /**
227
+ * The environment of an agent's first script.
228
+ */
229
+ environment: ExecutionEnvironment,
125
230
  /**
126
231
  * The names of the script functions the executor offers.
127
232
  */
@@ -187,17 +292,7 @@ export interface LocalOptions<Toolkit extends Toolkit.Any = never> {
187
292
  readonly excludeTools?: ReadonlyArray<ExcludableTool> | undefined
188
293
  }
189
294
 
190
- /**
191
- * @since 1.0.0
192
- * @category Constructors
193
- */
194
- export const makeLocal = Effect.fnUntraced(function* <
195
- Toolkit extends Toolkit.Any = never,
196
- >(
197
- options: LocalOptions<Toolkit>,
198
- ): Effect.fn.Return<
199
- AgentExecutor["Service"],
200
- never,
295
+ type LocalServices<Toolkit> =
201
296
  | ToolkitRenderer
202
297
  | FileSystem.FileSystem
203
298
  | Path.Path
@@ -212,18 +307,58 @@ export const makeLocal = Effect.fnUntraced(function* <
212
307
  | TaskCompleter
213
308
  | ImageAttacher
214
309
  >
310
+
311
+ /**
312
+ * @since 1.0.0
313
+ * @category Constructors
314
+ */
315
+ export const makeLocal = <Toolkit extends Toolkit.Any = never>(
316
+ options: LocalOptions<Toolkit>,
317
+ ): Effect.Effect<AgentExecutor["Service"], never, LocalServices<Toolkit>> =>
318
+ Effect.map(makeLocalWith(options), (local) => local.executor)
319
+
320
+ /**
321
+ * A local executor, plus an `execute` that also reports every change to the
322
+ * environment while the script runs. `layerRpcServer` sends those changes to
323
+ * its client, so the client has the latest environment when it stops reading.
324
+ */
325
+ const makeLocalWith = Effect.fnUntraced(function* <
326
+ Toolkit extends Toolkit.Any = never,
327
+ >(
328
+ options: LocalOptions<Toolkit>,
329
+ ): Effect.fn.Return<
330
+ {
331
+ readonly executor: AgentExecutor["Service"]
332
+ readonly execute: (
333
+ options: ExecuteOptions,
334
+ onChange: (environment: ExecutionEnvironment) => Effect.Effect<void>,
335
+ ) => Stream.Stream<string>
336
+ readonly renderEnvironment: (
337
+ environment: ExecutionEnvironment,
338
+ options?: { readonly reset?: boolean | undefined } | undefined,
339
+ ) => Effect.Effect<EnvironmentUpdate>
340
+ },
341
+ never,
342
+ LocalServices<Toolkit>
215
343
  > {
216
344
  const fs = yield* FileSystem.FileSystem
217
345
  const pathService = yield* Path.Path
218
346
  const renderer = yield* ToolkitRenderer
219
- let currentDirectory = pathService.resolve(options.directory)
220
- const changeDirectory = Effect.fnUntraced(function* (directory: string) {
221
- const target = pathService.resolve(currentDirectory, directory)
347
+ const startupDirectory = pathService.resolve(options.directory)
348
+ const startupEnvironment = new ExecutionEnvironment({
349
+ cwd: startupDirectory,
350
+ baseline: [],
351
+ seen: [],
352
+ })
353
+ const resolveDirectory = Effect.fnUntraced(function* (
354
+ from: string,
355
+ directory: string,
356
+ ) {
357
+ const target = pathService.resolve(from, directory)
222
358
  const info = yield* fs.stat(target)
223
359
  if (info.type !== "Directory") {
224
360
  return yield* Effect.die(new Error(`Not a directory: ${target}`))
225
361
  }
226
- currentDirectory = target
227
362
  return target
228
363
  }, Effect.orDie)
229
364
  const commandTimeout = options.limits?.commandTimeout
@@ -274,20 +409,94 @@ export const makeLocal = Effect.fnUntraced(function* <
274
409
  )
275
410
  const toolNames = Array.from(toolEntries.keys())
276
411
 
412
+ // Skills are read with readFile, so there are none without it.
413
+ const offersSkills = "readFile" in tools.tools
414
+ const home = homeDirectory()
415
+ const discoverAt = (cwd: string) =>
416
+ AgentEnvironment.discover({ cwd, startup: startupDirectory, home }).pipe(
417
+ Effect.map((discovered) =>
418
+ offersSkills ? discovered : { ...discovered, skills: [] },
419
+ ),
420
+ Effect.provideService(FileSystem.FileSystem, fs),
421
+ Effect.provideService(Path.Path, pathService),
422
+ )
423
+ // What applies to the environment's directory and is neither in the
424
+ // system prompt nor seen yet.
425
+ const renderEnvironment = Effect.fnUntraced(function* (
426
+ environment: ExecutionEnvironment,
427
+ options?: { readonly reset?: boolean | undefined } | undefined,
428
+ ) {
429
+ const seen = options?.reset ? [] : environment.seen
430
+ const known = new Set([...environment.baseline, ...seen])
431
+ const discovered = yield* discoverAt(environment.cwd)
432
+ const instructions = discovered.instructions.filter(
433
+ (item) => !known.has(item.id),
434
+ )
435
+ const skills = discovered.skills.filter(
436
+ (skill) => !known.has(AgentEnvironment.skillId(skill)),
437
+ )
438
+ const nothingNew = instructions.length === 0 && skills.length === 0
439
+ return new EnvironmentUpdate({
440
+ environment: new ExecutionEnvironment({
441
+ cwd: environment.cwd,
442
+ baseline: environment.baseline,
443
+ seen: [
444
+ ...seen,
445
+ ...instructions.map((item) => item.id),
446
+ ...skills.map(AgentEnvironment.skillId),
447
+ ],
448
+ }),
449
+ update: nothingNew
450
+ ? Option.none()
451
+ : Option.some(AgentEnvironment.renderUpdate({ instructions, skills })),
452
+ })
453
+ })
454
+
277
455
  if (typeof process !== "undefined") {
278
456
  process.on("uncaughtException", () => {})
279
457
  }
280
458
 
281
- const execute = Effect.fnUntraced(function* (opts: ExecuteOptions) {
459
+ const execute = Effect.fnUntraced(function* (
460
+ opts: ExecuteOptions,
461
+ onChange?: (environment: ExecutionEnvironment) => Effect.Effect<void>,
462
+ ) {
282
463
  const output = yield* Queue.unbounded<string, Cause.Done>()
283
464
  const console = yield* makeConsole(output)
284
465
  const handlerScope = Scope.makeUnsafe("parallel")
285
466
  const trackFiber = Fiber.runIn(handlerScope)
286
467
 
468
+ // Owned by this script, so concurrent scripts never see each other's
469
+ // directory.
470
+ let currentDirectory = opts.environment.cwd
471
+ const currentEnvironment = () =>
472
+ new ExecutionEnvironment({
473
+ cwd: currentDirectory,
474
+ baseline: opts.environment.baseline,
475
+ seen: opts.environment.seen,
476
+ })
477
+ // The script continues only once the change has been reported.
478
+ const changeDirectory = (directory: string) =>
479
+ resolveDirectory(currentDirectory, directory).pipe(
480
+ Effect.tap((target) => {
481
+ currentDirectory = target
482
+ return onChange ? onChange(currentEnvironment()) : Effect.void
483
+ }),
484
+ )
485
+
287
486
  const taskServices = Context.empty().pipe(
288
487
  Context.add(TaskCompleter, opts.onTaskComplete),
289
488
  Context.add(DirectoryChanger, changeDirectory),
290
- Context.add(SubagentExecutor, opts.subagents),
489
+ Context.add(SubagentExecutor, {
490
+ ...opts.subagents,
491
+ // A new agent has only the system prompt, so it gets everything that
492
+ // applies to the directory.
493
+ delegate: (options) =>
494
+ renderEnvironment(currentEnvironment(), { reset: true }).pipe(
495
+ Effect.flatMap((environment) =>
496
+ opts.subagents.delegate({ ...options, environment }),
497
+ ),
498
+ ),
499
+ }),
291
500
  Context.add(ImageAttacher, opts.onImage),
292
501
  Context.add(CommandLimits, commandLimits),
293
502
  Context.add(Console.Console, console),
@@ -409,6 +618,10 @@ export const makeLocal = Effect.fnUntraced(function* <
409
618
  Effect.ensuring(Scope.close(handlerScope, Exit.void)),
410
619
  Effect.catchCause(Effect.logFatal),
411
620
  Effect.provideService(Console.Console, console),
621
+ // Before the output ends, so the caller has it once the stream is done.
622
+ Effect.ensuring(
623
+ Effect.suspend(() => opts.onEnvironment(currentEnvironment())),
624
+ ),
412
625
  Effect.ensuring(Queue.end(output)),
413
626
  Effect.forkScoped,
414
627
  )
@@ -416,32 +629,40 @@ export const makeLocal = Effect.fnUntraced(function* <
416
629
  return Stream.fromQueue(output)
417
630
  }, Stream.unwrap)
418
631
 
419
- return AgentExecutor.of({
632
+ const executor = AgentExecutor.of({
420
633
  capabilities: Effect.gen(function* () {
421
- const agentsMd = yield* Effect.option(
422
- fs.readFileString(pathService.join(options.directory, "AGENTS.md")),
423
- )
424
- // Skills are read with readFile, so there are none without it.
425
- const skills =
426
- "readFile" in tools.tools
427
- ? yield* AgentSkills.discover({
428
- directory: options.directory,
429
- homeDirectory: homeDirectory(),
430
- hermesHome: Option.fromNullishOr(process.env.HERMES_HOME),
431
- }).pipe(
432
- Effect.provideService(FileSystem.FileSystem, fs),
433
- Effect.provideService(Path.Path, pathService),
434
- )
435
- : []
634
+ const startup = yield* discoverAt(startupDirectory)
635
+ const skills = offersSkills
636
+ ? yield* AgentSkills.discover({
637
+ directory: options.directory,
638
+ homeDirectory: home,
639
+ hermesHome: Option.fromNullishOr(process.env.HERMES_HOME),
640
+ }).pipe(
641
+ Effect.provideService(FileSystem.FileSystem, fs),
642
+ Effect.provideService(Path.Path, pathService),
643
+ )
644
+ : []
436
645
  return new Capabilities({
437
646
  toolsDts,
438
- agentsMd,
647
+ instructions: Option.map(
648
+ Option.fromNullishOr(startup.instructions.at(-1)),
649
+ AgentEnvironment.renderInstructions,
650
+ ),
439
651
  supportsSearch: hasSearch,
652
+ environment: new ExecutionEnvironment({
653
+ cwd: startupDirectory,
654
+ baseline: [
655
+ ...startup.instructions.map((item) => item.id),
656
+ ...skills.map(AgentEnvironment.skillId),
657
+ ],
658
+ seen: [],
659
+ }),
440
660
  tools: Object.keys(tools.tools),
441
661
  skills,
442
662
  })
443
663
  }),
444
- execute,
664
+ execute: (opts) => execute(opts),
665
+ renderEnvironment,
445
666
  executeUnsafe: (opts) =>
446
667
  Effect.suspend(() => {
447
668
  const tool = tools.tools[opts.tool as keyof typeof tools.tools]
@@ -453,10 +674,13 @@ export const makeLocal = Effect.fnUntraced(function* <
453
674
  return Effect.die(new Error(`Unknown tool: ${opts.tool}`))
454
675
  }
455
676
 
677
+ const cwd = (opts.environment ?? startupEnvironment).cwd
456
678
  const taskServices = handler.context.pipe(
457
679
  Context.add(TaskCompleter, () => Effect.void),
458
- Context.add(CurrentDirectory, currentDirectory),
459
- Context.add(DirectoryChanger, changeDirectory),
680
+ Context.add(CurrentDirectory, cwd),
681
+ Context.add(DirectoryChanger, (directory) =>
682
+ resolveDirectory(cwd, directory),
683
+ ),
460
684
  Context.add(SubagentExecutor, subagentsUnavailable),
461
685
  // Direct tool calls have no model turn to attach images to.
462
686
  Context.add(ImageAttacher, () => Effect.void),
@@ -478,6 +702,8 @@ export const makeLocal = Effect.fnUntraced(function* <
478
702
  ) as Effect.Effect<Schema.Json>
479
703
  }),
480
704
  })
705
+
706
+ return { executor, execute, renderEnvironment }
481
707
  })
482
708
 
483
709
  /**
@@ -492,10 +718,14 @@ export const makeRpc = Effect.gen(function* () {
492
718
  return AgentExecutor.of({
493
719
  capabilities: Effect.orDie(client.capabilities()),
494
720
  execute: (opts) =>
495
- Scope.Scope.useSync((scope) =>
496
- client
721
+ Scope.Scope.useSync((scope) => {
722
+ // Every change is recorded here before the server is told it arrived,
723
+ // so this is current even when the stream is interrupted early.
724
+ let latest = opts.environment
725
+ return client
497
726
  .execute({
498
727
  script: opts.script,
728
+ environment: opts.environment,
499
729
  loopTools: Object.keys(opts.loopTools ?? {}),
500
730
  })
501
731
  .pipe(
@@ -506,6 +736,9 @@ export const makeRpc = Effect.gen(function* () {
506
736
  }
507
737
  case "Request": {
508
738
  const id = part.id
739
+ if (part.request._tag === "EnvironmentChanged") {
740
+ latest = part.request.environment
741
+ }
509
742
  return pipe(
510
743
  handleRequest(opts, part.request),
511
744
  Effect.exit,
@@ -522,6 +755,10 @@ export const makeRpc = Effect.gen(function* () {
522
755
  data: part.data,
523
756
  })
524
757
  }
758
+ case "Environment": {
759
+ latest = part.environment
760
+ return Effect.void
761
+ }
525
762
  }
526
763
  }),
527
764
  Stream.orDie,
@@ -530,10 +767,19 @@ export const makeRpc = Effect.gen(function* () {
530
767
  ? Result.succeed(part.text)
531
768
  : Result.failVoid,
532
769
  ),
533
- ),
534
- ).pipe(Stream.unwrap),
535
- executeUnsafe(options) {
536
- return client.executeUnsafe(options).pipe(Effect.orDie)
770
+ Stream.ensuring(Effect.suspend(() => opts.onEnvironment(latest))),
771
+ )
772
+ }).pipe(Stream.unwrap),
773
+ renderEnvironment: (environment, options) =>
774
+ client
775
+ .renderEnvironment({ environment, reset: options?.reset ?? false })
776
+ .pipe(Effect.orDie),
777
+ executeUnsafe({ environment, ...options }) {
778
+ return client
779
+ .executeUnsafe(
780
+ environment === undefined ? options : { ...options, environment },
781
+ )
782
+ .pipe(Effect.orDie)
537
783
  },
538
784
  })
539
785
  })
@@ -612,7 +858,7 @@ export const layerRpcServer = <Toolkit extends Toolkit.Any = never>(
612
858
  Layer.provide(
613
859
  Rpcs.toLayer(
614
860
  Effect.gen(function* () {
615
- const local = yield* withBuiltInHandlers(makeLocal(options))
861
+ const local = yield* withBuiltInHandlers(makeLocalWith(options))
616
862
  const requestResumes = new Map<
617
863
  number,
618
864
  (effect: Effect.Effect<unknown, string>) => void
@@ -620,7 +866,9 @@ export const layerRpcServer = <Toolkit extends Toolkit.Any = never>(
620
866
  let requestId = 0
621
867
 
622
868
  return Rpcs.of({
623
- capabilities: () => local.capabilities,
869
+ capabilities: () => local.executor.capabilities,
870
+ renderEnvironment: ({ environment, reset }) =>
871
+ local.renderEnvironment(environment, { reset }),
624
872
  respond: ({ id, response }) => {
625
873
  const resume = requestResumes.get(id)
626
874
  if (resume) {
@@ -633,7 +881,11 @@ export const layerRpcServer = <Toolkit extends Toolkit.Any = never>(
633
881
  }
634
882
  return Effect.void
635
883
  },
636
- execute: Effect.fnUntraced(function* ({ script, loopTools }) {
884
+ execute: Effect.fnUntraced(function* ({
885
+ script,
886
+ environment,
887
+ loopTools,
888
+ }) {
637
889
  const queue = yield* Queue.unbounded<
638
890
  typeof ExecuteOutput.Type,
639
891
  Cause.Done
@@ -655,60 +907,74 @@ export const layerRpcServer = <Toolkit extends Toolkit.Any = never>(
655
907
  })
656
908
  })
657
909
  yield* pipe(
658
- local.execute({
659
- script,
660
- onTaskComplete: (summary) =>
661
- request<void>({ _tag: "TaskComplete", summary }),
662
- subagents: {
663
- delegate: (options) =>
664
- Effect.orDie(
665
- request<DelegateResult>({
666
- _tag: "Delegate",
910
+ local.execute(
911
+ {
912
+ script,
913
+ environment,
914
+ onEnvironment: (environment) =>
915
+ Queue.offer(queue, { _tag: "Environment", environment }),
916
+ onTaskComplete: (summary) =>
917
+ request<void>({ _tag: "TaskComplete", summary }),
918
+ subagents: {
919
+ delegate: (options) =>
920
+ Effect.orDie(
921
+ request<DelegateResult>({
922
+ _tag: "Delegate",
923
+ ...options,
924
+ }),
925
+ ),
926
+ waitAgents: (ids) =>
927
+ request<ReadonlyArray<SubagentResult>>({
928
+ _tag: "WaitAgents",
929
+ ids,
930
+ }),
931
+ messageAgent: (options) =>
932
+ request<SubagentResult>({
933
+ _tag: "MessageAgent",
667
934
  ...options,
668
935
  }),
936
+ stopAgent: (id) =>
937
+ request<SubagentResult>({ _tag: "StopAgent", id }),
938
+ listAgents: Effect.orDie(
939
+ request<ReadonlyArray<SubagentInfo>>({
940
+ _tag: "ListAgents",
941
+ }),
669
942
  ),
670
- waitAgents: (ids) =>
671
- request<ReadonlyArray<SubagentResult>>({
672
- _tag: "WaitAgents",
673
- ids,
674
- }),
675
- messageAgent: (options) =>
676
- request<SubagentResult>({
677
- _tag: "MessageAgent",
678
- ...options,
679
- }),
680
- stopAgent: (id) =>
681
- request<SubagentResult>({ _tag: "StopAgent", id }),
682
- listAgents: Effect.orDie(
683
- request<ReadonlyArray<SubagentInfo>>({
684
- _tag: "ListAgents",
685
- }),
943
+ },
944
+ onImage(image) {
945
+ return Queue.offer(queue, {
946
+ _tag: "Image",
947
+ fileName: image.fileName,
948
+ mediaType: image.mediaType,
949
+ data: image.data,
950
+ })
951
+ },
952
+ loopTools: Object.fromEntries(
953
+ loopTools.map((name) => [
954
+ name,
955
+ (params: unknown) =>
956
+ toJson(name, params).pipe(
957
+ Effect.flatMap((params) =>
958
+ request<unknown>({
959
+ _tag: "LoopTool",
960
+ name,
961
+ params,
962
+ }),
963
+ ),
964
+ ),
965
+ ]),
686
966
  ),
687
967
  },
688
- onImage(image) {
689
- return Queue.offer(queue, {
690
- _tag: "Image",
691
- fileName: image.fileName,
692
- mediaType: image.mediaType,
693
- data: image.data,
694
- })
695
- },
696
- loopTools: Object.fromEntries(
697
- loopTools.map((name) => [
698
- name,
699
- (params: unknown) =>
700
- toJson(name, params).pipe(
701
- Effect.flatMap((params) =>
702
- request<unknown>({
703
- _tag: "LoopTool",
704
- name,
705
- params,
706
- }),
707
- ),
708
- ),
709
- ]),
710
- ),
711
- }),
968
+ // Waits for the client to record the change, so a script
969
+ // that got past `changeDirectory` never leaves it behind.
970
+ (environment) =>
971
+ Effect.orDie(
972
+ request<void>({
973
+ _tag: "EnvironmentChanged",
974
+ environment,
975
+ }),
976
+ ),
977
+ ),
712
978
  Stream.runForEachArray((parts) => {
713
979
  for (const part of parts) {
714
980
  Queue.offerUnsafe(queue, {
@@ -729,7 +995,7 @@ export const layerRpcServer = <Toolkit extends Toolkit.Any = never>(
729
995
  return queue
730
996
  }),
731
997
  executeUnsafe(opts) {
732
- return local.executeUnsafe(opts as any)
998
+ return local.executor.executeUnsafe(opts as any)
733
999
  },
734
1000
  })
735
1001
  }),
@@ -744,12 +1010,21 @@ export const layerRpcServer = <Toolkit extends Toolkit.Any = never>(
744
1010
  */
745
1011
  export const AgentRequest = Schema.TaggedUnion({
746
1012
  TaskComplete: { summary: Schema.String },
747
- Delegate: { prompt: Schema.String, background: Schema.Boolean },
1013
+ Delegate: {
1014
+ prompt: Schema.String,
1015
+ background: Schema.Boolean,
1016
+ environment: EnvironmentUpdate,
1017
+ },
748
1018
  WaitAgents: { ids: Schema.UndefinedOr(Schema.Array(Schema.String)) },
749
1019
  MessageAgent: { id: Schema.String, message: Schema.String },
750
1020
  StopAgent: { id: Schema.String },
751
1021
  ListAgents: {},
752
1022
  LoopTool: { name: Schema.String, params: Schema.optional(Schema.Json) },
1023
+ /**
1024
+ * The script changed its environment. The client records it before it
1025
+ * responds.
1026
+ */
1027
+ EnvironmentChanged: { environment: ExecutionEnvironment },
753
1028
  })
754
1029
 
755
1030
  /**
@@ -776,6 +1051,11 @@ export const ExecuteOutput = Schema.TaggedUnion({
776
1051
  mediaType: Image.ImageMediaType,
777
1052
  data: Schema.Uint8Array,
778
1053
  },
1054
+ /**
1055
+ * Sent once, when the script ends. Changes before then are sent as
1056
+ * `EnvironmentChanged` requests.
1057
+ */
1058
+ Environment: { environment: ExecutionEnvironment },
779
1059
  })
780
1060
 
781
1061
  /**
@@ -795,6 +1075,7 @@ export class Rpcs extends RpcGroup.make(
795
1075
  Rpc.make("execute", {
796
1076
  payload: Schema.Struct({
797
1077
  script: Schema.String,
1078
+ environment: ExecutionEnvironment,
798
1079
  /**
799
1080
  * The loop-side tools to add to the script sandbox.
800
1081
  */
@@ -805,10 +1086,15 @@ export class Rpcs extends RpcGroup.make(
805
1086
  success: ExecuteOutput,
806
1087
  stream: true,
807
1088
  }),
1089
+ Rpc.make("renderEnvironment", {
1090
+ payload: { environment: ExecutionEnvironment, reset: Schema.Boolean },
1091
+ success: EnvironmentUpdate,
1092
+ }),
808
1093
  Rpc.make("executeUnsafe", {
809
1094
  payload: Schema.Struct({
810
1095
  tool: Schema.String,
811
1096
  params: Schema.Json,
1097
+ environment: Schema.optionalKey(ExecutionEnvironment),
812
1098
  }),
813
1099
  success: Schema.Json,
814
1100
  }),
@@ -835,6 +1121,9 @@ const handleRequest = (
835
1121
  return opts.subagents.stopAgent(request.id)
836
1122
  case "ListAgents":
837
1123
  return opts.subagents.listAgents
1124
+ case "EnvironmentChanged":
1125
+ // Recorded by the client before it responds.
1126
+ return Effect.void
838
1127
  case "LoopTool": {
839
1128
  const handler = opts.loopTools?.[request.name]
840
1129
  return handler