clanka 0.8.6 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/dist/Acp.d.ts +6 -1
  2. package/dist/Acp.d.ts.map +1 -1
  3. package/dist/Acp.js +34 -3
  4. package/dist/Acp.js.map +1 -1
  5. package/dist/Acp.test.js +178 -2
  6. package/dist/Acp.test.js.map +1 -1
  7. package/dist/AcpImage.test.js +7 -1
  8. package/dist/AcpImage.test.js.map +1 -1
  9. package/dist/Agent.d.ts +82 -8
  10. package/dist/Agent.d.ts.map +1 -1
  11. package/dist/Agent.js +556 -113
  12. package/dist/Agent.js.map +1 -1
  13. package/dist/Agent.test.js +86 -5
  14. package/dist/Agent.test.js.map +1 -1
  15. package/dist/AgentCallerConfig.test.d.ts +2 -0
  16. package/dist/AgentCallerConfig.test.d.ts.map +1 -0
  17. package/dist/AgentCallerConfig.test.js +335 -0
  18. package/dist/AgentCallerConfig.test.js.map +1 -0
  19. package/dist/AgentEnvironment.d.ts +76 -0
  20. package/dist/AgentEnvironment.d.ts.map +1 -0
  21. package/dist/AgentEnvironment.js +119 -0
  22. package/dist/AgentEnvironment.js.map +1 -0
  23. package/dist/AgentEnvironment.test.d.ts +2 -0
  24. package/dist/AgentEnvironment.test.d.ts.map +1 -0
  25. package/dist/AgentEnvironment.test.js +304 -0
  26. package/dist/AgentEnvironment.test.js.map +1 -0
  27. package/dist/AgentExecutor.d.ts +342 -183
  28. package/dist/AgentExecutor.d.ts.map +1 -1
  29. package/dist/AgentExecutor.js +607 -127
  30. package/dist/AgentExecutor.js.map +1 -1
  31. package/dist/AgentExecutor.test.js +287 -31
  32. package/dist/AgentExecutor.test.js.map +1 -1
  33. package/dist/AgentExecutorImage.test.js +5 -1
  34. package/dist/AgentExecutorImage.test.js.map +1 -1
  35. package/dist/AgentImage.test.js +15 -2
  36. package/dist/AgentImage.test.js.map +1 -1
  37. package/dist/AgentOutput.d.ts +70 -5
  38. package/dist/AgentOutput.d.ts.map +1 -1
  39. package/dist/AgentOutput.js +65 -0
  40. package/dist/AgentOutput.js.map +1 -1
  41. package/dist/AgentSkills.d.ts +37 -0
  42. package/dist/AgentSkills.d.ts.map +1 -1
  43. package/dist/AgentSkills.js +96 -32
  44. package/dist/AgentSkills.js.map +1 -1
  45. package/dist/AgentSkills.test.js +14 -2
  46. package/dist/AgentSkills.test.js.map +1 -1
  47. package/dist/AgentSubagents.test.d.ts +2 -0
  48. package/dist/AgentSubagents.test.d.ts.map +1 -0
  49. package/dist/AgentSubagents.test.js +494 -0
  50. package/dist/AgentSubagents.test.js.map +1 -0
  51. package/dist/AgentTools.d.ts +356 -14
  52. package/dist/AgentTools.d.ts.map +1 -1
  53. package/dist/AgentTools.js +214 -35
  54. package/dist/AgentTools.js.map +1 -1
  55. package/dist/OutputFormatter.d.ts.map +1 -1
  56. package/dist/OutputFormatter.js +19 -2
  57. package/dist/OutputFormatter.js.map +1 -1
  58. package/dist/ToolkitRenderer.d.ts.map +1 -1
  59. package/dist/ToolkitRenderer.js +6 -1
  60. package/dist/ToolkitRenderer.js.map +1 -1
  61. package/dist/bin/{Effect-rADALOOD.mjs → Effect-2jPlJ8eu.mjs} +43 -38
  62. package/dist/bin/Effect-2jPlJ8eu.mjs.map +1 -0
  63. package/dist/bin/{McpClient-NazR2OwL.mjs → McpClient-1W508adc.mjs} +3 -3
  64. package/dist/bin/{McpClient-NazR2OwL.mjs.map → McpClient-1W508adc.mjs.map} +1 -1
  65. package/dist/bin/{OutputFormatter-BVHbgF2b.mjs → OutputFormatter-BFAv48k9.mjs} +17 -5
  66. package/dist/bin/{OutputFormatter-BVHbgF2b.mjs.map → OutputFormatter-BFAv48k9.mjs.map} +1 -1
  67. package/dist/bin/{Schema-C7NXAOWA.mjs → Schema-D-7VuCiC.mjs} +2 -2
  68. package/dist/bin/{Schema-C7NXAOWA.mjs.map → Schema-D-7VuCiC.mjs.map} +1 -1
  69. package/dist/bin/{SemanticSearch-4Jes3jCl.mjs → SemanticSearch-Cb8aqvGv.mjs} +4 -4
  70. package/dist/bin/{SemanticSearch-4Jes3jCl.mjs.map → SemanticSearch-Cb8aqvGv.mjs.map} +1 -1
  71. package/dist/bin/{Stream-CSLA1_GD.mjs → Stream-DEu2tfCV.mjs} +12 -3
  72. package/dist/bin/Stream-DEu2tfCV.mjs.map +1 -0
  73. package/dist/bin/cli.mjs +13333 -12470
  74. package/dist/bin/cli.mjs.map +1 -1
  75. package/package.json +1 -1
  76. package/src/Acp.test.ts +279 -3
  77. package/src/Acp.ts +34 -4
  78. package/src/AcpImage.test.ts +7 -1
  79. package/src/Agent.test.ts +109 -4
  80. package/src/Agent.ts +874 -140
  81. package/src/AgentCallerConfig.test.ts +522 -0
  82. package/src/AgentEnvironment.test.ts +504 -0
  83. package/src/AgentEnvironment.ts +161 -0
  84. package/src/AgentExecutor.test.ts +414 -37
  85. package/src/AgentExecutor.ts +1028 -191
  86. package/src/AgentExecutorImage.test.ts +5 -1
  87. package/src/AgentImage.test.ts +21 -3
  88. package/src/AgentOutput.ts +91 -1
  89. package/src/AgentSkills.test.ts +14 -2
  90. package/src/AgentSkills.ts +117 -34
  91. package/src/AgentSubagents.test.ts +824 -0
  92. package/src/AgentTools.ts +377 -53
  93. package/src/OutputFormatter.ts +19 -2
  94. package/src/ToolkitRenderer.ts +7 -1
  95. package/dist/bin/Effect-rADALOOD.mjs.map +0 -1
  96. package/dist/bin/Stream-CSLA1_GD.mjs.map +0 -1
package/dist/Agent.js CHANGED
@@ -4,6 +4,7 @@
4
4
  import * as Model from "effect/ai/Model";
5
5
  import * as AgentExecutor from "./AgentExecutor.js";
6
6
  import * as AgentSkills from "./AgentSkills.js";
7
+ import { ToolkitRenderer } from "./ToolkitRenderer.js";
7
8
  import { stripWrappingCodeFence } from "./ScriptExtraction.js";
8
9
  import * as Image from "./Image.js";
9
10
  import * as Prompt from "effect/ai/Prompt";
@@ -28,8 +29,11 @@ import * as Cause from "effect/Cause";
28
29
  import * as Latch from "effect/Latch";
29
30
  import * as Clock from "effect/Clock";
30
31
  import * as Exit from "effect/Exit";
32
+ import * as Deferred from "effect/Deferred";
33
+ import * as Fiber from "effect/Fiber";
34
+ import * as Scope from "effect/Scope";
31
35
  import * as Compaction from "./Compaction.js";
32
- import { ScriptEnd, ScriptOutput, SubagentComplete, SubagentPart, SubagentStart, AgentFinished, ReasoningStart, ReasoningDelta, ReasoningEnd, Usage, ErrorRetry, ScriptStart, ScriptDelta, AgentStart, ExecuteOutputCapped, CompactionStarted, CompactionEnded, } from "./AgentOutput.js";
36
+ import { ScriptEnd, ScriptOutput, SubagentComplete, SubagentPart, SubagentStart, AgentFinished, ReasoningStart, ReasoningDelta, ReasoningEnd, Usage, ErrorRetry, ScriptStart, ScriptDelta, AgentStart, ExecuteOutputCapped, CompactionStarted, CompactionEnded, EnvironmentUpdated, HistoryAppended, HistoryReplaced, RetriesExhausted, } from "./AgentOutput.js";
33
37
  /**
34
38
  * @since 1.0.0
35
39
  * @category Models
@@ -44,32 +48,43 @@ export const Agent = Context.Service("clanka/Agent");
44
48
  * @since 1.0.0
45
49
  * @category Constructors
46
50
  */
47
- export const make = Effect.gen(function* () {
51
+ export const makeWith = Effect.fnUntraced(function* (options) {
48
52
  const executor = yield* AgentExecutor.AgentExecutor;
49
53
  const singleTool = yield* SingleTools.pipe(Effect.provide(SingleToolHandlers));
50
54
  const capabilities = yield* executor.capabilities;
51
- const pendingMessages = new Set();
52
- const agentsMd = Option.map(capabilities.agentsMd, (content) => `# AGENTS.md
53
-
54
- The following instructions are from ./AGENTS.md in the current directory.
55
- You do not need to read this file again.
56
-
57
- **ALWAYS follow these instructions when completing tasks**:
58
-
59
- <!-- AGENTS.md start -->
60
- ${content}
61
- <!-- AGENTS.md end -->`);
55
+ const loopTools = yield* makeLoopTools({
56
+ loopTools: options.loopTools,
57
+ skills: options.skills,
58
+ executorTools: capabilities.tools,
59
+ });
60
+ const promptTools = {
61
+ toolsDts: loopTools.dts === ""
62
+ ? capabilities.toolsDts
63
+ : `${capabilities.toolsDts}\n\n${loopTools.dts}`,
64
+ offers: (name) => capabilities.tools.includes(name),
65
+ skillsCatalog: options.skills === undefined
66
+ ? AgentSkills.renderCatalog(capabilities.skills)
67
+ : AgentSkills.renderProvidedCatalog(options.skills),
68
+ };
69
+ // Steering messages for the root agent. Sub-agents get their own mailbox.
70
+ const rootMailbox = makeMailbox();
71
+ const agentsMd = options.instructions === undefined
72
+ ? capabilities.instructions
73
+ : Option.map(options.instructions, renderInstructions);
62
74
  let agentCounter = 0;
63
75
  const outputBuffer = new Map();
64
76
  let currentOutputAgent = null;
65
77
  const history = MutableRef.make(Prompt.empty);
78
+ const environment = MutableRef.make(capabilities.environment);
66
79
  const spawn = Effect.fnUntraced(function* (opts) {
67
80
  const agentId = opts.agentId;
68
81
  const ai = yield* LanguageModel.LanguageModel;
69
- const subagentModel = yield* SubagentModel;
82
+ // Without a SubagentModel, sub-agents run on this agent's model.
83
+ const subagentModel = yield* Effect.serviceOption(SubagentModel);
70
84
  const modelConfig = yield* AgentModelConfig;
71
85
  const conversationMode = yield* ConversationMode;
72
86
  const turnTimeout = yield* TurnTimeout;
87
+ const maxRetries = yield* MaxRetries;
73
88
  let finalSummary = Option.none();
74
89
  // `inputTokens.total` from the most recent finish part; undefined until
75
90
  // the first response and after every compaction.
@@ -81,15 +96,42 @@ ${content}
81
96
  // Images attached by `readFile` during the current script, spliced onto
82
97
  // the Prompt as a user message once the tool result has been recorded.
83
98
  const pendingImages = [];
99
+ // Whether a script ran in the current response. Their environment
100
+ // update is rendered once, after all of their tool results.
101
+ let scriptsRan = false;
84
102
  const output = yield* Queue.make();
85
103
  let inputTokens = 0;
86
104
  let outputTokens = 0;
87
105
  let cacheRead = 0;
88
106
  let cacheWrite = 0;
89
- const prompt = opts.disableHistory ? MutableRef.make(Prompt.empty) : history;
107
+ const prompt = opts.history;
108
+ const mailbox = opts.mailbox;
109
+ // Every change to `prompt` after the system message is set goes through
110
+ // these two, so the history events always add up to the history.
111
+ const appendHistory = (input) => {
112
+ MutableRef.update(prompt, Prompt.concat(input));
113
+ if (!opts.historyEvents)
114
+ return;
115
+ const messages = input.content.filter((message) => message.role !== "system");
116
+ if (messages.length > 0) {
117
+ Queue.offerUnsafe(output, new HistoryAppended({ messages }));
118
+ }
119
+ };
120
+ const replaceHistory = (next) => {
121
+ MutableRef.set(prompt, next);
122
+ if (!opts.historyEvents)
123
+ return;
124
+ Queue.offerUnsafe(output, new HistoryReplaced({
125
+ messages: next.content.filter((message) => message.role !== "system"),
126
+ }));
127
+ };
128
+ // Committed now, emitted after AgentStart below.
90
129
  MutableRef.update(prompt, Prompt.concat(opts.prompt));
130
+ if (opts.environmentUpdate !== undefined) {
131
+ MutableRef.update(prompt, Prompt.concat(environmentUpdateMessage(opts.environmentUpdate)));
132
+ }
91
133
  const generateSystem = typeof opts.system === "function" ? opts.system : defaultSystem;
92
- const toolInstructions = generateSystemTools(capabilities, conversationMode);
134
+ const toolInstructions = generateSystemTools(promptTools, conversationMode);
93
135
  let system = generateSystem({
94
136
  toolInstructions,
95
137
  agentsMd: Option.getOrElse(agentsMd, () => ""),
@@ -98,6 +140,10 @@ ${content}
98
140
  system += `\n${opts.system}\n`;
99
141
  }
100
142
  function maybeSend(options) {
143
+ if (!opts.display) {
144
+ Queue.offerUnsafe(output, options.part);
145
+ return;
146
+ }
101
147
  if (currentOutputAgent === null || currentOutputAgent === opts.agentId) {
102
148
  Queue.offerUnsafe(output, options.part);
103
149
  if (options.acquire) {
@@ -126,42 +172,217 @@ ${content}
126
172
  state.push(options.part);
127
173
  return;
128
174
  }
129
- const spawnSubagent = Effect.fnUntraced(function* (prompt) {
130
- let id = agentCounter++;
175
+ // Sub-agents. Every agent tracks only the children it spawned. They are
176
+ // forked into a scope owned by this run, so none of them outlive it.
177
+ const runScope = yield* Scope.make();
178
+ const runContext = yield* Effect.context();
179
+ const provideSubagentModel = (effect) => Option.match(subagentModel, {
180
+ onNone: () => effect,
181
+ onSome: (model) => effect.pipe(Effect.provide(model), Effect.provideService(SubagentModel, model)),
182
+ });
183
+ const children = new Map();
184
+ // Finished turns waiting to be pushed to the model.
185
+ const completions = [];
186
+ let wakeUp;
187
+ const notify = () => {
188
+ const resume = wakeUp;
189
+ wakeUp = undefined;
190
+ resume?.();
191
+ };
192
+ mailbox.notify = notify;
193
+ const runningChildren = () => Array.Array.from(children.values()).filter((child) => child.turn.status === "running");
194
+ const hasUndelivered = () => completions.some((turn) => !turn.delivered);
195
+ const finishTurn = (turn, exit) => Effect.sync(() => {
196
+ if (Exit.isSuccess(exit)) {
197
+ turn.status = "completed";
198
+ turn.output = exit.value;
199
+ }
200
+ else if (Cause.hasInterruptsOnly(exit.cause)) {
201
+ turn.status = "cancelled";
202
+ }
203
+ else {
204
+ turn.status = "failed";
205
+ turn.output = causeMessage(exit.cause);
206
+ }
207
+ Queue.offerUnsafe(output, new SubagentComplete({
208
+ id: turn.agentId,
209
+ summary: turn.output ?? "",
210
+ status: turn.status,
211
+ }));
212
+ if (!turn.delivered) {
213
+ completions.push(turn);
214
+ }
215
+ Deferred.doneUnsafe(turn.done, Effect.void);
216
+ notify();
217
+ });
218
+ // Runs the child's current turn in its own fiber, with this run's
219
+ // services and the sub-agent model.
220
+ const startTurn = Effect.fnUntraced(function* (options) {
221
+ const { child } = options;
222
+ const turn = child.turn;
223
+ const display = opts.display && !options.background;
131
224
  const stream = spawn({
132
- agentId: id,
133
- prompt: Prompt.make(prompt),
225
+ agentId: child.id,
226
+ prompt: Prompt.make(options.prompt),
227
+ environmentUpdate: options.environmentUpdate,
134
228
  system: opts.system,
135
- disableHistory: true,
136
- });
137
- const provider = yield* Model.ProviderName;
138
- const model = yield* Model.ModelName;
139
- maybeSend({
140
- agentId: opts.agentId,
141
- part: new SubagentStart({ id, prompt, model, provider }),
142
- release: true,
229
+ history: child.history,
230
+ environment: child.environment,
231
+ mailbox: child.mailbox,
232
+ display,
233
+ historyEvents: false,
143
234
  });
144
- return yield* stream.pipe(Stream.runForEachArray((parts) => {
145
- for (const part of parts) {
146
- switch (part._tag) {
147
- case "AgentStart":
148
- break;
149
- case "SubagentStart":
150
- case "SubagentComplete":
151
- case "SubagentPart":
152
- Queue.offerUnsafe(output, part);
153
- break;
154
- default:
155
- Queue.offerUnsafe(output, new SubagentPart({ id, part }));
156
- break;
235
+ turn.fiber = yield* Effect.gen(function* () {
236
+ maybeSend({
237
+ agentId: opts.agentId,
238
+ part: new SubagentStart({
239
+ id: child.id,
240
+ prompt: options.label,
241
+ model: yield* Model.ModelName,
242
+ provider: yield* Model.ProviderName,
243
+ background: options.background,
244
+ }),
245
+ release: true,
246
+ });
247
+ return yield* stream.pipe(Stream.runForEachArray((parts) => {
248
+ for (const part of parts) {
249
+ switch (part._tag) {
250
+ case "AgentStart":
251
+ case "HistoryAppended":
252
+ case "HistoryReplaced":
253
+ break;
254
+ case "SubagentStart":
255
+ case "SubagentComplete":
256
+ Queue.offerUnsafe(output, part);
257
+ break;
258
+ default:
259
+ // Background agents only report start and completion.
260
+ if (!display)
261
+ break;
262
+ Queue.offerUnsafe(output, part._tag === "SubagentPart"
263
+ ? part
264
+ : new SubagentPart({ id: child.id, part }));
265
+ }
157
266
  }
267
+ return Effect.void;
268
+ }), Effect.as(""), Effect.catchTag("AgentFinished", (finished) => Effect.succeed(finished.summary)));
269
+ }).pipe(Effect.onExit((exit) => finishTurn(turn, exit)), provideSubagentModel, Effect.provideContext(runContext), Effect.forkIn(runScope, { startImmediately: true }));
270
+ });
271
+ // Leaves `output` out when unset, so the result stays JSON for RPC.
272
+ const childResult = ({ id, turn }) => turn.output === undefined
273
+ ? { id: String(id), status: turn.status }
274
+ : { id: String(id), status: turn.status, output: turn.output };
275
+ const lookupChild = (id) => Effect.suspend(() => {
276
+ const child = children.get(id);
277
+ return child
278
+ ? Effect.succeed(child)
279
+ : Effect.fail(`Unknown agent id ${JSON.stringify(id)}. You can only address agents you started; call listAgents() to see them.`);
280
+ });
281
+ const subagents = {
282
+ delegate: Effect.fnUntraced(function* ({ prompt, background, environment, }) {
283
+ const agentId = agentCounter++;
284
+ const child = {
285
+ id: agentId,
286
+ prompt,
287
+ history: MutableRef.make(Prompt.empty),
288
+ environment: MutableRef.make(environment.environment),
289
+ mailbox: makeMailbox(),
290
+ turn: makeTurn(agentId, background),
291
+ };
292
+ const id = String(child.id);
293
+ children.set(id, child);
294
+ const turn = child.turn;
295
+ yield* startTurn({
296
+ child,
297
+ label: prompt,
298
+ prompt: `You have been asked using the "delegate" function to complete the following task. Try to avoid using the "delegate" function yourself unless strictly necessary:
299
+
300
+ ${prompt}`,
301
+ // The update goes into the child's first prompt.
302
+ environmentUpdate: Option.getOrUndefined(environment.update),
303
+ background,
304
+ });
305
+ if (background) {
306
+ return { id, status: "running" };
158
307
  }
159
- return Effect.void;
160
- }), Effect.as(""), Effect.catchTag("AgentFinished", (finished) => {
161
- Queue.offerUnsafe(output, new SubagentComplete({ id, summary: finished.summary }));
162
- return Effect.succeed(finished.summary);
163
- }), Effect.orDie);
164
- }, Effect.provide(subagentModel), Effect.provideService(SubagentModel, subagentModel));
308
+ // Foreground: a failure crashes the script, as before. Interrupting
309
+ // the script stops the agent.
310
+ yield* Deferred.await(turn.done).pipe(Effect.onInterrupt(() => Fiber.interrupt(turn.fiber)));
311
+ if (turn.status !== "completed") {
312
+ return yield* Effect.die(new Error(`Sub-agent ${child.id} ${turn.status}${turn.output ? `: ${turn.output}` : ""}`));
313
+ }
314
+ return { id, status: "completed", output: turn.output ?? "" };
315
+ }),
316
+ waitAgents: Effect.fnUntraced(function* (ids) {
317
+ const targets = ids === undefined
318
+ ? Array.Array.from(children.values())
319
+ : yield* Effect.forEach(ids, lookupChild);
320
+ // A turn started by messageAgent while waiting is waited for too.
321
+ while (true) {
322
+ const running = targets.find((child) => child.turn.status === "running");
323
+ if (!running)
324
+ break;
325
+ yield* Deferred.await(running.turn.done);
326
+ }
327
+ return targets.map((child) => {
328
+ child.turn.delivered = true;
329
+ return childResult(child);
330
+ });
331
+ }),
332
+ messageAgent: Effect.fnUntraced(function* ({ id, message }) {
333
+ const child = yield* lookupChild(id);
334
+ if (child.turn.status === "running") {
335
+ child.mailbox.messages.add({ message, resume: () => { } });
336
+ child.mailbox.notify();
337
+ return childResult(child);
338
+ }
339
+ child.turn = makeTurn(child.id, true);
340
+ yield* startTurn({
341
+ child,
342
+ prompt: message,
343
+ label: message,
344
+ background: true,
345
+ });
346
+ return childResult(child);
347
+ }),
348
+ stopAgent: Effect.fnUntraced(function* (id) {
349
+ const child = yield* lookupChild(id);
350
+ const turn = child.turn;
351
+ turn.delivered = true;
352
+ if (turn.status === "running") {
353
+ yield* Fiber.interrupt(turn.fiber);
354
+ }
355
+ return childResult(child);
356
+ }),
357
+ listAgents: Effect.sync(() => Array.Array.from(children.values(), (child) => ({
358
+ id: String(child.id),
359
+ status: child.turn.status,
360
+ prompt: child.prompt,
361
+ }))),
362
+ };
363
+ const onTaskComplete = (summary) => Effect.suspend(() => {
364
+ const running = runningChildren();
365
+ if (running.length > 0) {
366
+ const ids = running.map((child) => JSON.stringify(String(child.id)));
367
+ return Effect.fail(`taskComplete was rejected: sub-agents ${ids.join(", ")} are still running. Call waitAgents() to wait for them, or stopAgent(id) to stop them, before calling taskComplete.`);
368
+ }
369
+ finalSummary = Option.some(summary);
370
+ return Effect.void;
371
+ });
372
+ // Blocks an idle conversation turn until a child finishes or a message
373
+ // arrives.
374
+ const waitForActivity = Effect.callback((resume) => {
375
+ if (mailbox.messages.size > 0 ||
376
+ hasUndelivered() ||
377
+ runningChildren().length === 0) {
378
+ resume(Effect.void);
379
+ return;
380
+ }
381
+ wakeUp = () => resume(Effect.void);
382
+ return Effect.sync(() => {
383
+ wakeUp = undefined;
384
+ });
385
+ });
165
386
  // Turn timeout
166
387
  const clock = yield* Clock.Clock;
167
388
  const turnTimeoutMs = Duration.toMillis(turnTimeout);
@@ -194,17 +415,47 @@ ${content}
194
415
  compactionStarted = true;
195
416
  maybeSend({ agentId, part: new CompactionStarted({ reason }) });
196
417
  });
418
+ // The AGENTS.md files and skills for the current directory that the
419
+ // history does not have yet. Rendered once per response, after all of
420
+ // its scripts; nothing counts as seen until `applyEnvironmentUpdate` has
421
+ // put it in the history, so an interrupted response is covered by the
422
+ // next one. With `reset`, everything is rendered again: any operation
423
+ // that rewrites the history must do this, because the rewrite drops the
424
+ // earlier updates.
425
+ const renderEnvironment = (options) => executor.renderEnvironment?.(opts.environment.current, options) ??
426
+ Effect.succeed(new AgentExecutor.EnvironmentUpdate({
427
+ environment: opts.environment.current,
428
+ update: Option.none(),
429
+ }));
430
+ const applyEnvironmentUpdate = (update) => {
431
+ MutableRef.set(opts.environment, update.environment);
432
+ if (Option.isNone(update.update))
433
+ return;
434
+ appendHistory(environmentUpdateMessage(update.update.value));
435
+ maybeSend({
436
+ agentId,
437
+ part: new EnvironmentUpdated({ update: update.update.value }),
438
+ });
439
+ };
440
+ // The refresh is rendered before the rewrite and both are committed
441
+ // together, so an interrupt leaves the old history and the old
442
+ // environment, which still agree.
197
443
  const compactWithEvents = (reason, compaction) => Effect.suspend(() => {
198
444
  compactionStarted = false;
199
445
  return compaction;
200
- }).pipe(Effect.onExit((exit) => Effect.sync(() => {
446
+ }).pipe(Effect.flatMap(Option.match({
447
+ onNone: () => Effect.succeedNone,
448
+ onSome: (result) => Effect.map(renderEnvironment({ reset: true }), (refresh) => Option.some({ ...result, refresh })),
449
+ })), Effect.onExit((exit) => Effect.sync(() => {
201
450
  if (!compactionStarted)
202
451
  return;
203
452
  const result = Exit.isSuccess(exit) ? exit.value : Option.none();
204
453
  let tokensBefore;
205
454
  let tokensAfter;
206
455
  if (Option.isSome(result)) {
207
- MutableRef.set(prompt, result.value.prompt);
456
+ // The refresh sends the kept updates again, so they are
457
+ // dropped here to appear once.
458
+ replaceHistory(Prompt.fromMessages(result.value.prompt.content.filter((message) => !isEnvironmentUpdate(message))));
208
459
  lastContextTokens = undefined;
209
460
  tokensBefore = result.value.tokensBefore;
210
461
  tokensAfter = result.value.tokensAfter;
@@ -216,21 +467,28 @@ ${content}
216
467
  agentId,
217
468
  part: new CompactionEnded({ reason, tokensBefore, tokensAfter }),
218
469
  });
470
+ if (Option.isSome(result)) {
471
+ applyEnvironmentUpdate(result.value.refresh);
472
+ }
219
473
  })));
220
474
  // Script execution
221
475
  const executeScript = Effect.fnUntraced(function* (script) {
222
476
  yield* toolLatchAcquire;
223
477
  maybeSend({ agentId, part: new ScriptEnd(), release: true });
224
478
  const normalizedScript = stripWrappingCodeFence(script);
479
+ scriptsRan = true;
225
480
  const output = yield* pipe(executor.execute({
226
481
  script: normalizedScript,
227
- onSubagent: spawnSubagent,
228
- onTaskComplete: (summary) => Effect.sync(() => {
229
- finalSummary = Option.some(summary);
482
+ environment: opts.environment.current,
483
+ onEnvironment: (environment) => Effect.sync(() => {
484
+ MutableRef.set(opts.environment, environment);
230
485
  }),
486
+ subagents,
487
+ onTaskComplete,
231
488
  onImage: (image) => Effect.sync(() => {
232
489
  pendingImages.push(image);
233
490
  }),
491
+ loopTools: loopTools.handlers,
234
492
  }), Stream.mkString);
235
493
  // Always-on cap on what enters the Prompt. The ScriptOutput event keeps
236
494
  // the full output for display; the formatter applies its own truncation.
@@ -250,21 +508,57 @@ ${content}
250
508
  if (!modelConfig.systemPromptTransform) {
251
509
  MutableRef.update(prompt, Prompt.setSystem(system));
252
510
  }
511
+ yield* Queue.offer(output, new AgentStart({
512
+ id: opts.agentId,
513
+ prompt: opts.prompt,
514
+ provider: yield* Model.ProviderName,
515
+ model: yield* Model.ModelName,
516
+ }));
517
+ if (opts.environmentUpdate !== undefined) {
518
+ maybeSend({
519
+ agentId,
520
+ part: new EnvironmentUpdated({ update: opts.environmentUpdate }),
521
+ });
522
+ }
523
+ if (opts.historyEvents) {
524
+ const messages = opts.prompt.content.filter((message) => message.role !== "system");
525
+ if (messages.length > 0) {
526
+ yield* Queue.offer(output, new HistoryAppended({ messages }));
527
+ }
528
+ }
253
529
  yield* Effect.gen(function* () {
254
530
  while (true) {
255
531
  if (Option.isSome(finalSummary)) {
256
532
  yield* Queue.fail(output, new AgentFinished({ summary: finalSummary.value }));
257
533
  return;
258
534
  }
259
- if (pendingMessages.size > 0) {
260
- MutableRef.update(prompt, Prompt.concat(Array.Array.from(pendingMessages, ({ message, resume }) => {
535
+ if (mailbox.messages.size > 0) {
536
+ appendHistory(Prompt.make(Array.Array.from(mailbox.messages, ({ message, resume }) => {
261
537
  resume(Effect.void);
262
538
  return {
263
539
  role: "user",
264
540
  content: message,
265
541
  };
266
542
  })));
267
- pendingMessages.clear();
543
+ mailbox.messages.clear();
544
+ }
545
+ // Completion pushes from background sub-agents. These have their own
546
+ // queue: the steering path above cuts the model stream short.
547
+ if (completions.length > 0) {
548
+ const pushes = completions.splice(0).filter((turn) => {
549
+ if (turn.delivered)
550
+ return false;
551
+ turn.delivered = true;
552
+ return true;
553
+ });
554
+ if (pushes.length > 0) {
555
+ appendHistory(Prompt.make(pushes.map((turn) => ({
556
+ role: "user",
557
+ content: `<subagent id="${turn.agentId}" status="${turn.status}">
558
+ ${Compaction.capOutput(turn.output ?? "").output}
559
+ </subagent>`,
560
+ }))));
561
+ }
268
562
  }
269
563
  // Threshold compaction before the next model call
270
564
  yield* compactWithEvents("threshold", Compaction.compactIfNeeded({
@@ -281,6 +575,19 @@ ${content}
281
575
  let reasoningStarted = false;
282
576
  let hadReasoningDelta = false;
283
577
  let hadToolCall = false;
578
+ // Retries of this model call so far, and the error that used up the
579
+ // last one.
580
+ let retries = 0;
581
+ let exhaustedBy;
582
+ const retryOrExhaust = (error) => {
583
+ if (retries >= maxRetries) {
584
+ exhaustedBy = error;
585
+ return false;
586
+ }
587
+ retries++;
588
+ maybeSend({ agentId, part: new ErrorRetry({ error }) });
589
+ return true;
590
+ };
284
591
  const runModel = pipe(Stream.suspend(() => ai.streamText({
285
592
  prompt: sendImages
286
593
  ? prompt.current
@@ -288,7 +595,7 @@ ${content}
288
595
  toolkit: singleTool,
289
596
  })), Stream.takeUntil((part) => {
290
597
  if ((part.type === "text-end" || part.type === "reasoning-end") &&
291
- pendingMessages.size > 0) {
598
+ mailbox.messages.size > 0) {
292
599
  return true;
293
600
  }
294
601
  return false;
@@ -367,32 +674,23 @@ ${content}
367
674
  const attempt = pipe(runModel, Effect.raceFirst(turnTimeoutEffect), Effect.retry({
368
675
  while(err) {
369
676
  if (err._tag === "TimeoutError") {
370
- maybeSend({
371
- agentId,
372
- part: new ErrorRetry({
373
- error: AiError.make({
374
- module: "clanka/Agent",
375
- method: "send",
376
- reason: new AiError.UnknownError({
377
- description: "TurnTimeout was reached",
378
- }),
379
- }),
380
- }),
381
- });
382
677
  discardAttempt();
383
- return true;
678
+ return retryOrExhaust(turnTimeoutError);
384
679
  }
385
680
  // Never retry a context-length error as is: the overflow
386
681
  // handler below compacts first.
387
682
  if (Compaction.isContextLengthError(err))
388
683
  return false;
389
684
  if (err.isRetryable) {
390
- maybeSend({ agentId, part: new ErrorRetry({ error: err }) });
685
+ if (!retryOrExhaust(err)) {
686
+ discardAttempt();
687
+ return false;
688
+ }
391
689
  switch (err.reason._tag) {
392
690
  case "ToolNotFoundError":
393
691
  case "InvalidOutputError": {
394
692
  const toAppend = Prompt.fromResponseParts(response).pipe(Prompt.concat(`There was an error, please try again using the "execute" tool:\n\n${Cause.pretty(Cause.fail(err))}`));
395
- MutableRef.update(prompt, Prompt.concat(toAppend));
693
+ appendHistory(toAppend);
396
694
  }
397
695
  }
398
696
  }
@@ -400,10 +698,11 @@ ${content}
400
698
  return err.isRetryable;
401
699
  },
402
700
  schedule: retryPolicy,
403
- }), Effect.catchTag("TimeoutError", Effect.die));
701
+ }), Effect.catchIf(() => exhaustedBy !== undefined, () => Effect.fail(new RetriesExhausted({ retries, error: exhaustedBy }))), Effect.catchTag("TimeoutError", Effect.die));
404
702
  // Unsupported images: drop them from the request and retry once.
405
703
  // The images stay in the Prompt with an omitted note in their place.
406
- const attemptWithImageFallback = attempt.pipe(Effect.catchIf((err) => sendImages &&
704
+ const attemptWithImageFallback = attempt.pipe(Effect.catchIf((err) => err._tag === "AiError" &&
705
+ sendImages &&
407
706
  Image.hasImages(prompt.current) &&
408
707
  Image.isUnsupportedImageError(err), (err) => {
409
708
  sendImages = false;
@@ -412,7 +711,7 @@ ${content}
412
711
  return attempt;
413
712
  }));
414
713
  // Overflow: compact once, retry the attempt once, then fail.
415
- yield* attemptWithImageFallback.pipe(Effect.catchIf((err) => Compaction.isContextLengthError(err), (err) => Effect.gen(function* () {
714
+ yield* attemptWithImageFallback.pipe(Effect.catchIf((err) => err._tag === "AiError" && Compaction.isContextLengthError(err), (err) => Effect.gen(function* () {
416
715
  discardAttempt();
417
716
  const compacted = yield* compactWithEvents("overflow", Compaction.compact({
418
717
  prompt: prompt.current,
@@ -426,13 +725,24 @@ ${content}
426
725
  ? yield* attemptWithImageFallback
427
726
  : yield* err;
428
727
  })));
429
- MutableRef.update(prompt, Prompt.concat(Prompt.fromResponseParts(response)));
728
+ appendHistory(Prompt.fromResponseParts(response));
430
729
  if (pendingImages.length > 0) {
431
730
  // After the tool result, so call / result pairing stays intact.
432
- MutableRef.update(prompt, Prompt.concat(Prompt.fromMessages([Image.userMessage(pendingImages)])));
731
+ appendHistory(Prompt.fromMessages([Image.userMessage(pendingImages)]));
433
732
  pendingImages.length = 0;
434
733
  }
435
- if (conversationMode && !hadToolCall && pendingMessages.size === 0) {
734
+ // After the tool results too, and before any steering messages.
735
+ if (scriptsRan) {
736
+ scriptsRan = false;
737
+ applyEnvironmentUpdate(yield* renderEnvironment());
738
+ }
739
+ if (conversationMode && !hadToolCall && mailbox.messages.size === 0) {
740
+ // The run is not over while children are running or their results
741
+ // have not been seen yet.
742
+ if (runningChildren().length > 0 || hasUndelivered()) {
743
+ yield* waitForActivity;
744
+ continue;
745
+ }
436
746
  finalSummary = Option.some(responseToSummary(response));
437
747
  }
438
748
  }
@@ -440,57 +750,130 @@ ${content}
440
750
  maybeSend({ agentId, part: new ScriptStart() });
441
751
  maybeSend({ agentId, part: new ScriptDelta({ delta: script }) });
442
752
  return executeScript(script);
443
- }), Effect.catchCause((cause) => Queue.failCause(output, cause)), Effect.forkScoped);
444
- yield* Queue.offer(output, new AgentStart({
445
- id: opts.agentId,
446
- prompt: opts.prompt,
447
- provider: yield* Model.ProviderName,
448
- model: yield* Model.ModelName,
449
- }));
753
+ }), Effect.ensuring(Scope.close(runScope, Exit.void)), Effect.catchCause((cause) => Queue.failCause(output, cause)), Effect.forkScoped);
450
754
  return Stream.fromQueue(output);
451
755
  }, Stream.unwrap);
452
756
  const sendLock = Semaphore.makeUnsafe(1);
453
757
  return Agent.of({
454
758
  [TypeId]: TypeId,
455
759
  history,
760
+ environment,
456
761
  send: (options) => spawn({
457
762
  agentId: agentCounter++,
458
763
  prompt: Prompt.make(options.prompt),
459
764
  system: options.system,
765
+ history,
766
+ environment,
767
+ mailbox: rootMailbox,
768
+ display: true,
769
+ historyEvents: true,
460
770
  }).pipe(Stream.broadcast({ capacity: "unbounded", replay: 1 }), sendLock.withPermit),
461
771
  steer: (message) => Effect.callback((resume) => {
462
772
  const entry = { message, resume };
463
- pendingMessages.add(entry);
464
- return Effect.sync(() => pendingMessages.delete(entry));
773
+ rootMailbox.messages.add(entry);
774
+ rootMailbox.notify();
775
+ return Effect.sync(() => rootMailbox.messages.delete(entry));
465
776
  }),
466
777
  });
467
778
  });
779
+ /**
780
+ * Create an Agent with every executor tool, the executor's `AGENTS.md` and
781
+ * skills, and no loop-side tools.
782
+ *
783
+ * @since 1.0.0
784
+ * @category Constructors
785
+ */
786
+ export const make = makeWith({});
787
+ const makeMailbox = () => ({
788
+ messages: new Set(),
789
+ notify: () => { },
790
+ });
791
+ const makeTurn = (agentId, background) => ({
792
+ agentId,
793
+ status: "running",
794
+ output: undefined,
795
+ // Foreground results go straight back to the script.
796
+ delivered: !background,
797
+ done: Deferred.makeUnsafe(),
798
+ fiber: undefined,
799
+ });
800
+ const causeMessage = (cause) => errorMessage(Cause.squash(cause));
801
+ const turnTimeoutError = AiError.make({
802
+ module: "clanka/Agent",
803
+ method: "send",
804
+ reason: new AiError.UnknownError({
805
+ description: "TurnTimeout was reached",
806
+ }),
807
+ });
468
808
  const retryPolicy = Schedule.min([
469
809
  Schedule.exponential(100, 1.5),
470
810
  Schedule.spaced(5000),
471
811
  ]).pipe(Schedule.jittered);
812
+ const environmentUpdateOpen = "<environment-update>";
813
+ const environmentUpdateMessage = (text) => Prompt.make([
814
+ {
815
+ role: "user",
816
+ content: `${environmentUpdateOpen}\n${text}\n</environment-update>`,
817
+ },
818
+ ]);
819
+ // A user message that is one text part starting with `prefix`.
820
+ const startsWith = (message, prefix) => message.role === "user" &&
821
+ message.content.length === 1 &&
822
+ message.content[0].type === "text" &&
823
+ message.content[0].text.trimStart().startsWith(prefix);
824
+ const isEnvironmentUpdate = (message) => startsWith(message, environmentUpdateOpen);
825
+ /**
826
+ * Whether a user message was added by the agent rather than typed: an
827
+ * `<environment-update>` or a `<subagent>` result. Surfaces that replay
828
+ * history (ACP) skip them.
829
+ *
830
+ * @since 1.0.0
831
+ * @category Models
832
+ */
833
+ export const isInjectedMessage = (message) => isEnvironmentUpdate(message) || startsWith(message, "<subagent ");
834
+ const renderInstructions = (content) => `# Project instructions
835
+
836
+ **ALWAYS follow these instructions when completing tasks**:
837
+
838
+ <!-- instructions start -->
839
+ ${content}
840
+ <!-- instructions end -->`;
472
841
  const defaultSystem = (options) => `You are a world-class software engineer: precise and efficient.
473
842
 
474
843
  ${options.toolInstructions}
475
844
 
476
845
  ${options.agentsMd}
477
846
  `;
478
- const generateSystemTools = (capabilities, conversationMode) => `YOU ONLY HAVE ONE TOOL AVAILABLE: "execute", to run javascript code to do your work.
847
+ const when = (condition, text) => (condition ? text : "");
848
+ const generateSystemTools = (tools, conversationMode) => `YOU ONLY HAVE ONE TOOL AVAILABLE: "execute", to run javascript code to do your work.
479
849
 
480
850
  - Use \`console.log\` to print any output you need.
481
- - Use top level await.${capabilities.supportsSearch
482
- ? `
483
- - Prefer using the "search" function over "rg", unless you are targeting specific files or patterns.`
484
- : ""}
485
- - You can add / update / remove multiple files in one go with "applyPatch".
486
- - Avoid passing scripts into the "bash" function, and instead write javascript.
851
+ - Use top level await.${when(tools.offers("search") && tools.offers("rg"), `
852
+ - Prefer using the "search" function over "rg", unless you are targeting specific files or patterns.`)}${when(tools.offers("applyPatch"), `
853
+ - You can add / update / remove multiple files in one go with "applyPatch".${when(tools.offers("writeFile"), ` Prefer it over "writeFile" to update existing files.`)}`)}${when(tools.offers("bash"), `
854
+ - Avoid passing scripts into the "bash" function, and instead write javascript.`)}
487
855
  - Variables are not shared between executions.
488
- - Do not use \`require\`, \`import\`, \`process\`, or any other Node.js apis.${conversationMode
489
- ? ""
490
- : `
856
+ - Do not use \`require\`, \`import\`, \`process\`, or any other Node.js apis.${when(tools.offers("delegate"), `
857
+ - "delegate" runs a sub-agent and waits for it. Pass \`background: true\` to keep working while it runs: its result is sent to you later as a \`<subagent id="..." status="...">\` message.${when(tools.offers("waitAgents"), ` Use "waitAgents" to wait for the returned id.`)}${when(tools.offers("messageAgent"), ` Use "messageAgent" to send a message to the returned id.`)}${when(tools.offers("stopAgent"), ` Use "stopAgent" to stop the returned id.`)}${when(tools.offers("listAgents"), ` "listAgents" shows the agents you started.`)}`)}${when(!conversationMode, `
491
858
 
492
859
  When you have fully completed your task, call the "taskComplete" function with the final output.
493
- Make sure every detail of the task is done before calling "taskComplete".`}
860
+ Make sure every detail of the task is done before calling "taskComplete".${when(tools.offers("delegate"), `
861
+ Any sub-agents you started must finish first: "taskComplete" fails while they are running.`)}`)}${when(tools.offers("readFile") && tools.offers("ls"), example)}
862
+
863
+ These are the functions available to you:
864
+
865
+ \`\`\`ts
866
+ ${tools.toolsDts}
867
+
868
+ /** The global Fetch API available for making HTTP requests. */
869
+ declare const fetch: typeof globalThis.fetch
870
+ \`\`\`${Option.match(tools.skillsCatalog, {
871
+ onNone: () => "",
872
+ onSome: (catalog) => `
873
+
874
+ ${catalog}`,
875
+ })}`;
876
+ const example = `
494
877
 
495
878
  Here is how you would read a file and list a directory:
496
879
 
@@ -517,21 +900,63 @@ package.json: {
517
900
  "name": "my-project",
518
901
  "version": "1.0.0"
519
902
  }
520
- \`\`\`
521
-
522
- These are the functions available to you:
523
-
524
- \`\`\`ts
525
- ${capabilities.toolsDts}
526
-
527
- /** The global Fetch API available for making HTTP requests. */
528
- declare const fetch: typeof globalThis.fetch
529
- \`\`\`${Option.match(AgentSkills.renderCatalog(capabilities.skills), {
530
- onNone: () => "",
531
- onSome: (catalog) => `
532
-
533
- ${catalog}`,
534
- })}`;
903
+ \`\`\``;
904
+ const ReadSkillTools = Toolkit.make(Tool.make("readSkill", {
905
+ description: "Read the instructions of a skill listed under Skills, by its name.",
906
+ parameters: Schema.String.annotate({ identifier: "name" }),
907
+ success: Schema.String,
908
+ failure: Schema.String,
909
+ }));
910
+ /**
911
+ * Builds the loop-side handlers the executor puts in the sandbox, and their
912
+ * type declarations. Every call is decoded by `Toolkit.handle` before the
913
+ * handler runs; results are encoded to JSON.
914
+ */
915
+ const makeLoopTools = Effect.fnUntraced(function* (options) {
916
+ const skills = options.skills ?? [];
917
+ const callerTools = Object.keys(options.loopTools?.tools ?? {});
918
+ const names = skills.length > 0 ? [...callerTools, "readSkill"] : callerTools;
919
+ for (const name of names) {
920
+ if (options.executorTools.includes(name) ||
921
+ names.indexOf(name) !== names.lastIndexOf(name)) {
922
+ return yield* Effect.die(new Error(`Loop-side tool "${name}" clashes with another tool`));
923
+ }
924
+ }
925
+ const toolkit = Toolkit.merge(options.loopTools ?? Toolkit.empty, skills.length > 0 ? ReadSkillTools : Toolkit.empty);
926
+ const withHandlers = toolkit;
927
+ // Only provided with the tool itself, so it never replaces a caller's
928
+ // `readSkill` handler.
929
+ const handled = yield* skills.length > 0
930
+ ? withHandlers.pipe(Effect.provide(ReadSkillTools.toLayer({
931
+ readSkill: (name) => {
932
+ const skill = skills.find((skill) => skill.name === name);
933
+ return skill
934
+ ? Effect.succeed(skill.content)
935
+ : Effect.fail(`Unknown skill ${JSON.stringify(name)}. Available skills: ${skills.map((skill) => skill.name).join(", ")}`);
936
+ },
937
+ })))
938
+ : withHandlers;
939
+ // Provides the services the caller's handlers depend on.
940
+ const context = yield* Effect.context();
941
+ const handlers = {};
942
+ for (const [name, tool] of Object.entries(handled.tools)) {
943
+ const encodeSuccess = Schema.encodeUnknownEffect(Schema.toCodecJson(tool.successSchema));
944
+ handlers[name] = (params) => handled.handle(name, params).pipe(Effect.flatMap(Stream.runLast), Effect.flatMap((last) => {
945
+ if (Option.isNone(last))
946
+ return Effect.void;
947
+ return last.value.isFailure
948
+ ? Effect.fail(last.value.result)
949
+ : encodeSuccess(last.value.result);
950
+ }), Effect.mapError(errorMessage), Effect.provideContext(context));
951
+ }
952
+ const renderer = yield* Effect.service(ToolkitRenderer).pipe(Effect.provide(ToolkitRenderer.layer));
953
+ return { handlers, dts: renderer.render(toolkit) };
954
+ });
955
+ const errorMessage = (error) => typeof error === "string"
956
+ ? error
957
+ : error instanceof Error
958
+ ? error.message
959
+ : (JSON.stringify(error) ?? String(error));
535
960
  class ScriptExecutor extends Context.Service()("clanka/Agent/ScriptExecutor") {
536
961
  }
537
962
  const SingleTools = Toolkit.make(Tool.make("execute", {
@@ -553,13 +978,18 @@ const SingleToolHandlers = SingleTools.toLayer({
553
978
  * @category Layers
554
979
  */
555
980
  export const layer = Layer.effect(Agent, make);
981
+ /**
982
+ * @since 1.0.0
983
+ * @category Layers
984
+ */
985
+ export const layerWith = (options) => Layer.effect(Agent, makeWith(options));
556
986
  /**
557
987
  * Create an Agent layer that uses a local AgentExecutor.
558
988
  *
559
989
  * @since 1.0.0
560
990
  * @category Layers
561
991
  */
562
- export const layerLocal = (options) => layer.pipe(Layer.provide(AgentExecutor.layerLocal(options)));
992
+ export const layerLocal = (options) => layerWith(options).pipe(Layer.provide(AgentExecutor.layerLocal(options)));
563
993
  /**
564
994
  * @since 1.0.0
565
995
  * @category Subagent model
@@ -594,6 +1024,19 @@ export class TurnTimeout extends Context.Reference("clanka/Agent/TurnTimeout", {
594
1024
  }) {
595
1025
  static layer = (timeout) => Layer.succeed(TurnTimeout, Duration.fromInputUnsafe(timeout));
596
1026
  }
1027
+ /**
1028
+ * The number of times in a row a model call is retried, after a retryable
1029
+ * error or after reaching `TurnTimeout`, before `send` fails with
1030
+ * `RetriesExhausted`. The count resets after a model call succeeds.
1031
+ *
1032
+ * @since 1.0.0
1033
+ * @category Retries
1034
+ */
1035
+ export class MaxRetries extends Context.Reference("clanka/Agent/MaxRetries", {
1036
+ defaultValue: () => 20,
1037
+ }) {
1038
+ static layer = (retries) => Layer.succeed(MaxRetries, retries);
1039
+ }
597
1040
  /**
598
1041
  * @since 1.0.0
599
1042
  * @category System prompts