clanka 0.8.5 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Acp.d.ts.map +1 -1
- package/dist/Acp.js +9 -3
- package/dist/Acp.js.map +1 -1
- package/dist/Acp.test.js +72 -1
- package/dist/Acp.test.js.map +1 -1
- package/dist/AcpImage.test.js +1 -0
- package/dist/AcpImage.test.js.map +1 -1
- package/dist/Agent.d.ts +65 -8
- package/dist/Agent.d.ts.map +1 -1
- package/dist/Agent.js +481 -113
- package/dist/Agent.js.map +1 -1
- package/dist/Agent.test.js +77 -4
- package/dist/Agent.test.js.map +1 -1
- package/dist/AgentCallerConfig.test.d.ts +2 -0
- package/dist/AgentCallerConfig.test.d.ts.map +1 -0
- package/dist/AgentCallerConfig.test.js +327 -0
- package/dist/AgentCallerConfig.test.js.map +1 -0
- package/dist/AgentExecutor.d.ts +254 -54
- package/dist/AgentExecutor.d.ts.map +1 -1
- package/dist/AgentExecutor.js +416 -99
- package/dist/AgentExecutor.js.map +1 -1
- package/dist/AgentExecutor.test.js +201 -31
- package/dist/AgentExecutor.test.js.map +1 -1
- package/dist/AgentExecutorImage.test.js +2 -1
- package/dist/AgentExecutorImage.test.js.map +1 -1
- package/dist/AgentImage.test.js +5 -1
- package/dist/AgentImage.test.js.map +1 -1
- package/dist/AgentOutput.d.ts +54 -2
- package/dist/AgentOutput.d.ts.map +1 -1
- package/dist/AgentOutput.js +52 -0
- package/dist/AgentOutput.js.map +1 -1
- package/dist/AgentSkills.d.ts +22 -0
- package/dist/AgentSkills.d.ts.map +1 -1
- package/dist/AgentSkills.js +36 -0
- package/dist/AgentSkills.js.map +1 -1
- package/dist/AgentSkills.test.js +2 -0
- package/dist/AgentSkills.test.js.map +1 -1
- package/dist/AgentSubagents.test.d.ts +2 -0
- package/dist/AgentSubagents.test.d.ts.map +1 -0
- package/dist/AgentSubagents.test.js +452 -0
- package/dist/AgentSubagents.test.js.map +1 -0
- package/dist/AgentTools.d.ts +356 -14
- package/dist/AgentTools.d.ts.map +1 -1
- package/dist/AgentTools.js +213 -34
- package/dist/AgentTools.js.map +1 -1
- package/dist/CompactionTransport.test.js +1 -1
- package/dist/CompactionTransport.test.js.map +1 -1
- package/dist/OutputFormatter.d.ts.map +1 -1
- package/dist/OutputFormatter.js +16 -2
- package/dist/OutputFormatter.js.map +1 -1
- package/dist/ToolkitRenderer.d.ts.map +1 -1
- package/dist/ToolkitRenderer.js +6 -1
- package/dist/ToolkitRenderer.js.map +1 -1
- package/dist/bin/{Effect-BEUn4I5E.mjs → Effect-2jPlJ8eu.mjs} +399 -207
- package/dist/bin/Effect-2jPlJ8eu.mjs.map +1 -0
- package/dist/bin/{McpClient-C0FVuDj2.mjs → McpClient-1W508adc.mjs} +4 -4
- package/dist/bin/{McpClient-C0FVuDj2.mjs.map → McpClient-1W508adc.mjs.map} +1 -1
- package/dist/bin/{OutputFormatter-DffD5oxX.mjs → OutputFormatter-DXXKo4E8.mjs} +16 -5
- package/dist/bin/{OutputFormatter-DffD5oxX.mjs.map → OutputFormatter-DXXKo4E8.mjs.map} +1 -1
- package/dist/bin/{Schema-CjUGw2Xh.mjs → Schema-D-7VuCiC.mjs} +640 -87
- package/dist/bin/Schema-D-7VuCiC.mjs.map +1 -0
- package/dist/bin/{SemanticSearch-CFB73IPb.mjs → SemanticSearch-Cb8aqvGv.mjs} +89 -56
- package/dist/bin/SemanticSearch-Cb8aqvGv.mjs.map +1 -0
- package/dist/bin/{Stream-Cu6P7ZHo.mjs → Stream-DEu2tfCV.mjs} +81 -51
- package/dist/bin/Stream-DEu2tfCV.mjs.map +1 -0
- package/dist/bin/cli.mjs +3632 -5538
- package/dist/bin/cli.mjs.map +1 -1
- package/dist/bin/{turndown.cjs-usmCKZ4b.mjs → turndown.cjs-DK29wZw3.mjs} +2 -2
- package/dist/bin/{turndown.cjs-usmCKZ4b.mjs.map → turndown.cjs-DK29wZw3.mjs.map} +1 -1
- package/package.json +7 -7
- package/src/Acp.test.ts +121 -2
- package/src/Acp.ts +10 -3
- package/src/AcpImage.test.ts +1 -0
- package/src/Agent.test.ts +100 -3
- package/src/Agent.ts +752 -142
- package/src/AgentCallerConfig.test.ts +514 -0
- package/src/AgentExecutor.test.ts +297 -37
- package/src/AgentExecutor.ts +707 -159
- package/src/AgentExecutorImage.test.ts +2 -1
- package/src/AgentImage.test.ts +11 -2
- package/src/AgentOutput.ts +74 -1
- package/src/AgentSkills.test.ts +2 -0
- package/src/AgentSkills.ts +43 -0
- package/src/AgentSubagents.test.ts +758 -0
- package/src/AgentTools.ts +376 -52
- package/src/CompactionTransport.test.ts +1 -1
- package/src/OutputFormatter.ts +16 -2
- package/src/ToolkitRenderer.ts +7 -1
- package/dist/bin/Effect-BEUn4I5E.mjs.map +0 -1
- package/dist/bin/Schema-CjUGw2Xh.mjs.map +0 -1
- package/dist/bin/SemanticSearch-CFB73IPb.mjs.map +0 -1
- package/dist/bin/Stream-Cu6P7ZHo.mjs.map +0 -1
package/src/Agent.ts
CHANGED
|
@@ -5,6 +5,7 @@ import * as Model from "effect/ai/Model"
|
|
|
5
5
|
import type * as Response from "effect/ai/Response"
|
|
6
6
|
import * as AgentExecutor from "./AgentExecutor.ts"
|
|
7
7
|
import * as AgentSkills from "./AgentSkills.ts"
|
|
8
|
+
import { ToolkitRenderer } from "./ToolkitRenderer.ts"
|
|
8
9
|
import { stripWrappingCodeFence } from "./ScriptExtraction.ts"
|
|
9
10
|
import type * as Path from "effect/Path"
|
|
10
11
|
import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"
|
|
@@ -12,9 +13,13 @@ import type * as HttpClient from "effect/http/HttpClient"
|
|
|
12
13
|
import type {
|
|
13
14
|
CurrentDirectory,
|
|
14
15
|
DirectoryChanger,
|
|
16
|
+
ExcludableTool,
|
|
15
17
|
ImageAttacher,
|
|
16
18
|
ImageAttachment,
|
|
17
19
|
SubagentExecutor,
|
|
20
|
+
SubagentResult,
|
|
21
|
+
SubagentStatus,
|
|
22
|
+
Subagents,
|
|
18
23
|
TaskCompleter,
|
|
19
24
|
} from "./AgentTools.ts"
|
|
20
25
|
import * as Image from "./Image.ts"
|
|
@@ -22,7 +27,6 @@ import type * as FileSystem from "effect/FileSystem"
|
|
|
22
27
|
import * as Prompt from "effect/ai/Prompt"
|
|
23
28
|
import * as Effect from "effect/Effect"
|
|
24
29
|
import * as Stream from "effect/Stream"
|
|
25
|
-
import type * as Scope from "effect/Scope"
|
|
26
30
|
import * as LanguageModel from "effect/ai/LanguageModel"
|
|
27
31
|
import * as AiError from "effect/ai/AiError"
|
|
28
32
|
import * as Context from "effect/Context"
|
|
@@ -42,6 +46,9 @@ import * as Cause from "effect/Cause"
|
|
|
42
46
|
import * as Latch from "effect/Latch"
|
|
43
47
|
import * as Clock from "effect/Clock"
|
|
44
48
|
import * as Exit from "effect/Exit"
|
|
49
|
+
import * as Deferred from "effect/Deferred"
|
|
50
|
+
import * as Fiber from "effect/Fiber"
|
|
51
|
+
import * as Scope from "effect/Scope"
|
|
45
52
|
import * as Compaction from "./Compaction.ts"
|
|
46
53
|
import {
|
|
47
54
|
ScriptEnd,
|
|
@@ -62,6 +69,9 @@ import {
|
|
|
62
69
|
ExecuteOutputCapped,
|
|
63
70
|
CompactionStarted,
|
|
64
71
|
CompactionEnded,
|
|
72
|
+
HistoryAppended,
|
|
73
|
+
HistoryReplaced,
|
|
74
|
+
RetriesExhausted,
|
|
65
75
|
} from "./AgentOutput.ts"
|
|
66
76
|
|
|
67
77
|
/**
|
|
@@ -105,13 +115,12 @@ export interface Agent {
|
|
|
105
115
|
}) => string)
|
|
106
116
|
| undefined
|
|
107
117
|
}): Effect.Effect<
|
|
108
|
-
Stream.Stream<Output, AgentFinished | AiError.AiError>,
|
|
118
|
+
Stream.Stream<Output, AgentFinished | AiError.AiError | RetriesExhausted>,
|
|
109
119
|
never,
|
|
110
120
|
| Scope.Scope
|
|
111
121
|
| LanguageModel.LanguageModel
|
|
112
122
|
| Model.ProviderName
|
|
113
123
|
| Model.ModelName
|
|
114
|
-
| SubagentModel
|
|
115
124
|
>
|
|
116
125
|
|
|
117
126
|
/**
|
|
@@ -131,38 +140,85 @@ export interface Agent {
|
|
|
131
140
|
*/
|
|
132
141
|
export const Agent = Context.Service<Agent>("clanka/Agent")
|
|
133
142
|
|
|
143
|
+
/**
|
|
144
|
+
* What the Agent offers the model, beyond the executor's built-in tools.
|
|
145
|
+
*
|
|
146
|
+
* @since 1.0.0
|
|
147
|
+
* @category Models
|
|
148
|
+
*/
|
|
149
|
+
export interface Options<LoopTools extends Toolkit.Any = never> {
|
|
150
|
+
/**
|
|
151
|
+
* The project instructions for the system prompt. Unset uses the
|
|
152
|
+
* executor's `AGENTS.md`; `Option.none()` leaves them out.
|
|
153
|
+
*/
|
|
154
|
+
readonly instructions?: Option.Option<string> | undefined
|
|
155
|
+
/**
|
|
156
|
+
* The skills offered to the model. Unset uses the skills discovered on the
|
|
157
|
+
* executor; a list, possibly empty, replaces them. The model reads a
|
|
158
|
+
* skill's content with `readSkill`, which runs on the loop side.
|
|
159
|
+
*/
|
|
160
|
+
readonly skills?: ReadonlyArray<AgentSkills.ProvidedSkill> | undefined
|
|
161
|
+
/**
|
|
162
|
+
* Tools whose handlers run next to the Agent rather than in the executor.
|
|
163
|
+
* Scripts call them like any other function; arguments are decoded with
|
|
164
|
+
* the tool's parameters schema before the handler runs, and a handler
|
|
165
|
+
* failure rejects the script's call with that message.
|
|
166
|
+
*/
|
|
167
|
+
readonly loopTools?: LoopTools | undefined
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* The services needed by the handlers of a loop-side toolkit.
|
|
172
|
+
*
|
|
173
|
+
* @since 1.0.0
|
|
174
|
+
* @category Models
|
|
175
|
+
*/
|
|
176
|
+
export type LoopToolServices<LoopTools> =
|
|
177
|
+
LoopTools extends Toolkit.Toolkit<infer T>
|
|
178
|
+
? Tool.HandlersFor<T> | Tool.HandlerServices<T[keyof T]>
|
|
179
|
+
: never
|
|
180
|
+
|
|
134
181
|
/**
|
|
135
182
|
* @since 1.0.0
|
|
136
183
|
* @category Constructors
|
|
137
184
|
*/
|
|
138
|
-
export const
|
|
185
|
+
export const makeWith = Effect.fnUntraced(function* <
|
|
186
|
+
LoopTools extends Toolkit.Any = never,
|
|
187
|
+
>(
|
|
188
|
+
options: Options<LoopTools>,
|
|
189
|
+
): Effect.fn.Return<
|
|
139
190
|
Agent,
|
|
140
191
|
never,
|
|
141
|
-
Scope.Scope | AgentExecutor.AgentExecutor
|
|
192
|
+
Scope.Scope | AgentExecutor.AgentExecutor | LoopToolServices<LoopTools>
|
|
142
193
|
> {
|
|
143
194
|
const executor = yield* AgentExecutor.AgentExecutor
|
|
144
195
|
|
|
145
196
|
const singleTool = yield* SingleTools.pipe(Effect.provide(SingleToolHandlers))
|
|
146
197
|
const capabilities = yield* executor.capabilities
|
|
198
|
+
const loopTools = yield* makeLoopTools({
|
|
199
|
+
loopTools: options.loopTools,
|
|
200
|
+
skills: options.skills,
|
|
201
|
+
executorTools: capabilities.tools,
|
|
202
|
+
})
|
|
203
|
+
const promptTools: PromptTools = {
|
|
204
|
+
toolsDts:
|
|
205
|
+
loopTools.dts === ""
|
|
206
|
+
? capabilities.toolsDts
|
|
207
|
+
: `${capabilities.toolsDts}\n\n${loopTools.dts}`,
|
|
208
|
+
offers: (name) => capabilities.tools.includes(name),
|
|
209
|
+
skillsCatalog:
|
|
210
|
+
options.skills === undefined
|
|
211
|
+
? AgentSkills.renderCatalog(capabilities.skills)
|
|
212
|
+
: AgentSkills.renderProvidedCatalog(options.skills),
|
|
213
|
+
}
|
|
147
214
|
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
readonly resume: (effect: Effect.Effect<void>) => void
|
|
151
|
-
}>()
|
|
152
|
-
|
|
153
|
-
const agentsMd = Option.map(
|
|
154
|
-
capabilities.agentsMd,
|
|
155
|
-
(content) => `# AGENTS.md
|
|
156
|
-
|
|
157
|
-
The following instructions are from ./AGENTS.md in the current directory.
|
|
158
|
-
You do not need to read this file again.
|
|
159
|
-
|
|
160
|
-
**ALWAYS follow these instructions when completing tasks**:
|
|
215
|
+
// Steering messages for the root agent. Sub-agents get their own mailbox.
|
|
216
|
+
const rootMailbox = makeMailbox()
|
|
161
217
|
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
218
|
+
const agentsMd =
|
|
219
|
+
options.instructions === undefined
|
|
220
|
+
? Option.map(capabilities.agentsMd, renderAgentsMd)
|
|
221
|
+
: Option.map(options.instructions, renderInstructions)
|
|
166
222
|
|
|
167
223
|
let agentCounter = 0
|
|
168
224
|
|
|
@@ -181,21 +237,31 @@ ${content}
|
|
|
181
237
|
readonly agentsMd: string
|
|
182
238
|
}) => string)
|
|
183
239
|
| undefined
|
|
184
|
-
readonly
|
|
240
|
+
readonly history: MutableRef.MutableRef<Prompt.Prompt>
|
|
241
|
+
readonly mailbox: Mailbox
|
|
242
|
+
/**
|
|
243
|
+
* Whether this agent's output is streamed for display. Background agents
|
|
244
|
+
* and everything under them are not, so they never hold the output lock.
|
|
245
|
+
*/
|
|
246
|
+
readonly display: boolean
|
|
247
|
+
/**
|
|
248
|
+
* Whether commits to `history` are emitted as `HistoryAppended` and
|
|
249
|
+
* `HistoryReplaced` events. Only the root agent's history is public.
|
|
250
|
+
*/
|
|
251
|
+
readonly historyEvents: boolean
|
|
185
252
|
}) => Stream.Stream<
|
|
186
253
|
Output,
|
|
187
|
-
AgentFinished | AiError.AiError,
|
|
188
|
-
|
|
|
189
|
-
| Model.ProviderName
|
|
190
|
-
| Model.ModelName
|
|
191
|
-
| SubagentModel
|
|
254
|
+
AgentFinished | AiError.AiError | RetriesExhausted,
|
|
255
|
+
LanguageModel.LanguageModel | Model.ProviderName | Model.ModelName
|
|
192
256
|
> = Effect.fnUntraced(function* (opts) {
|
|
193
257
|
const agentId = opts.agentId
|
|
194
258
|
const ai = yield* LanguageModel.LanguageModel
|
|
195
|
-
|
|
259
|
+
// Without a SubagentModel, sub-agents run on this agent's model.
|
|
260
|
+
const subagentModel = yield* Effect.serviceOption(SubagentModel)
|
|
196
261
|
const modelConfig = yield* AgentModelConfig
|
|
197
262
|
const conversationMode = yield* ConversationMode
|
|
198
263
|
const turnTimeout = yield* TurnTimeout
|
|
264
|
+
const maxRetries = yield* MaxRetries
|
|
199
265
|
let finalSummary = Option.none<string>()
|
|
200
266
|
// `inputTokens.total` from the most recent finish part; undefined until
|
|
201
267
|
// the first response and after every compaction.
|
|
@@ -208,19 +274,47 @@ ${content}
|
|
|
208
274
|
// the Prompt as a user message once the tool result has been recorded.
|
|
209
275
|
const pendingImages: Array<ImageAttachment> = []
|
|
210
276
|
|
|
211
|
-
const output = yield* Queue.make<
|
|
277
|
+
const output = yield* Queue.make<
|
|
278
|
+
Output,
|
|
279
|
+
AgentFinished | AiError.AiError | RetriesExhausted
|
|
280
|
+
>()
|
|
212
281
|
let inputTokens = 0
|
|
213
282
|
let outputTokens = 0
|
|
214
283
|
let cacheRead = 0
|
|
215
284
|
let cacheWrite = 0
|
|
216
|
-
const prompt = opts.
|
|
285
|
+
const prompt = opts.history
|
|
286
|
+
const mailbox = opts.mailbox
|
|
217
287
|
|
|
288
|
+
// Every change to `prompt` after the system message is set goes through
|
|
289
|
+
// these two, so the history events always add up to the history.
|
|
290
|
+
const appendHistory = (input: Prompt.Prompt) => {
|
|
291
|
+
MutableRef.update(prompt, Prompt.concat(input))
|
|
292
|
+
if (!opts.historyEvents) return
|
|
293
|
+
const messages = input.content.filter(
|
|
294
|
+
(message) => message.role !== "system",
|
|
295
|
+
)
|
|
296
|
+
if (messages.length > 0) {
|
|
297
|
+
Queue.offerUnsafe(output, new HistoryAppended({ messages }))
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
const replaceHistory = (next: Prompt.Prompt) => {
|
|
301
|
+
MutableRef.set(prompt, next)
|
|
302
|
+
if (!opts.historyEvents) return
|
|
303
|
+
Queue.offerUnsafe(
|
|
304
|
+
output,
|
|
305
|
+
new HistoryReplaced({
|
|
306
|
+
messages: next.content.filter((message) => message.role !== "system"),
|
|
307
|
+
}),
|
|
308
|
+
)
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// Committed now, emitted after AgentStart below.
|
|
218
312
|
MutableRef.update(prompt, Prompt.concat(opts.prompt))
|
|
219
313
|
|
|
220
314
|
const generateSystem =
|
|
221
315
|
typeof opts.system === "function" ? opts.system : defaultSystem
|
|
222
316
|
|
|
223
|
-
const toolInstructions = generateSystemTools(
|
|
317
|
+
const toolInstructions = generateSystemTools(promptTools, conversationMode)
|
|
224
318
|
let system = generateSystem({
|
|
225
319
|
toolInstructions,
|
|
226
320
|
agentsMd: Option.getOrElse(agentsMd, () => ""),
|
|
@@ -235,6 +329,10 @@ ${content}
|
|
|
235
329
|
readonly acquire?: boolean
|
|
236
330
|
readonly release?: boolean
|
|
237
331
|
}) {
|
|
332
|
+
if (!opts.display) {
|
|
333
|
+
Queue.offerUnsafe(output, options.part)
|
|
334
|
+
return
|
|
335
|
+
}
|
|
238
336
|
if (currentOutputAgent === null || currentOutputAgent === opts.agentId) {
|
|
239
337
|
Queue.offerUnsafe(output, options.part)
|
|
240
338
|
if (options.acquire) {
|
|
@@ -266,20 +364,95 @@ ${content}
|
|
|
266
364
|
return
|
|
267
365
|
}
|
|
268
366
|
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
367
|
+
// Sub-agents. Every agent tracks only the children it spawned. They are
|
|
368
|
+
// forked into a scope owned by this run, so none of them outlive it.
|
|
369
|
+
const runScope = yield* Scope.make()
|
|
370
|
+
const runContext = yield* Effect.context<
|
|
371
|
+
LanguageModel.LanguageModel | Model.ProviderName | Model.ModelName
|
|
372
|
+
>()
|
|
373
|
+
const provideSubagentModel = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
|
374
|
+
Option.match(subagentModel, {
|
|
375
|
+
onNone: () => effect,
|
|
376
|
+
onSome: (model) =>
|
|
377
|
+
effect.pipe(
|
|
378
|
+
Effect.provide(model),
|
|
379
|
+
Effect.provideService(SubagentModel, model),
|
|
380
|
+
),
|
|
381
|
+
})
|
|
382
|
+
const children = new Map<string, Child>()
|
|
383
|
+
// Finished turns waiting to be pushed to the model.
|
|
384
|
+
const completions: Array<Turn> = []
|
|
385
|
+
let wakeUp: (() => void) | undefined
|
|
386
|
+
const notify = () => {
|
|
387
|
+
const resume = wakeUp
|
|
388
|
+
wakeUp = undefined
|
|
389
|
+
resume?.()
|
|
390
|
+
}
|
|
391
|
+
mailbox.notify = notify
|
|
392
|
+
|
|
393
|
+
const runningChildren = () =>
|
|
394
|
+
Array.Array.from(children.values()).filter(
|
|
395
|
+
(child) => child.turn.status === "running",
|
|
396
|
+
)
|
|
397
|
+
const hasUndelivered = () => completions.some((turn) => !turn.delivered)
|
|
398
|
+
|
|
399
|
+
const finishTurn = (turn: Turn, exit: Exit.Exit<string, unknown>) =>
|
|
400
|
+
Effect.sync(() => {
|
|
401
|
+
if (Exit.isSuccess(exit)) {
|
|
402
|
+
turn.status = "completed"
|
|
403
|
+
turn.output = exit.value
|
|
404
|
+
} else if (Cause.hasInterruptsOnly(exit.cause)) {
|
|
405
|
+
turn.status = "cancelled"
|
|
406
|
+
} else {
|
|
407
|
+
turn.status = "failed"
|
|
408
|
+
turn.output = causeMessage(exit.cause)
|
|
409
|
+
}
|
|
410
|
+
Queue.offerUnsafe(
|
|
411
|
+
output,
|
|
412
|
+
new SubagentComplete({
|
|
413
|
+
id: turn.agentId,
|
|
414
|
+
summary: turn.output ?? "",
|
|
415
|
+
status: turn.status,
|
|
416
|
+
}),
|
|
417
|
+
)
|
|
418
|
+
if (!turn.delivered) {
|
|
419
|
+
completions.push(turn)
|
|
420
|
+
}
|
|
421
|
+
Deferred.doneUnsafe(turn.done, Effect.void)
|
|
422
|
+
notify()
|
|
423
|
+
})
|
|
424
|
+
|
|
425
|
+
// Runs the child's current turn in its own fiber, with this run's
|
|
426
|
+
// services and the sub-agent model.
|
|
427
|
+
const startTurn = Effect.fnUntraced(function* (options: {
|
|
428
|
+
readonly child: Child
|
|
429
|
+
readonly prompt: string
|
|
430
|
+
/** Shown in the start event: the task, or the follow-up message. */
|
|
431
|
+
readonly label: string
|
|
432
|
+
readonly background: boolean
|
|
433
|
+
}) {
|
|
434
|
+
const { child } = options
|
|
435
|
+
const turn = child.turn
|
|
436
|
+
const display = opts.display && !options.background
|
|
437
|
+
const stream = spawn({
|
|
438
|
+
agentId: child.id,
|
|
439
|
+
prompt: Prompt.make(options.prompt),
|
|
440
|
+
system: opts.system,
|
|
441
|
+
history: child.history,
|
|
442
|
+
mailbox: child.mailbox,
|
|
443
|
+
display,
|
|
444
|
+
historyEvents: false,
|
|
445
|
+
})
|
|
446
|
+
turn.fiber = yield* Effect.gen(function* () {
|
|
280
447
|
maybeSend({
|
|
281
448
|
agentId: opts.agentId,
|
|
282
|
-
part: new SubagentStart({
|
|
449
|
+
part: new SubagentStart({
|
|
450
|
+
id: child.id,
|
|
451
|
+
prompt: options.label,
|
|
452
|
+
model: yield* Model.ModelName,
|
|
453
|
+
provider: yield* Model.ProviderName,
|
|
454
|
+
background: options.background,
|
|
455
|
+
}),
|
|
283
456
|
release: true,
|
|
284
457
|
})
|
|
285
458
|
return yield* stream.pipe(
|
|
@@ -287,34 +460,174 @@ ${content}
|
|
|
287
460
|
for (const part of parts) {
|
|
288
461
|
switch (part._tag) {
|
|
289
462
|
case "AgentStart":
|
|
463
|
+
case "HistoryAppended":
|
|
464
|
+
case "HistoryReplaced":
|
|
290
465
|
break
|
|
291
466
|
case "SubagentStart":
|
|
292
467
|
case "SubagentComplete":
|
|
293
|
-
case "SubagentPart":
|
|
294
468
|
Queue.offerUnsafe(output, part)
|
|
295
469
|
break
|
|
296
|
-
|
|
297
470
|
default:
|
|
298
|
-
|
|
299
|
-
break
|
|
471
|
+
// Background agents only report start and completion.
|
|
472
|
+
if (!display) break
|
|
473
|
+
Queue.offerUnsafe(
|
|
474
|
+
output,
|
|
475
|
+
part._tag === "SubagentPart"
|
|
476
|
+
? part
|
|
477
|
+
: new SubagentPart({ id: child.id, part }),
|
|
478
|
+
)
|
|
300
479
|
}
|
|
301
480
|
}
|
|
302
481
|
return Effect.void
|
|
303
482
|
}),
|
|
304
483
|
Effect.as(""),
|
|
305
|
-
Effect.catchTag("AgentFinished", (finished) =>
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
484
|
+
Effect.catchTag("AgentFinished", (finished) =>
|
|
485
|
+
Effect.succeed(finished.summary),
|
|
486
|
+
),
|
|
487
|
+
)
|
|
488
|
+
}).pipe(
|
|
489
|
+
Effect.onExit((exit) => finishTurn(turn, exit)),
|
|
490
|
+
provideSubagentModel,
|
|
491
|
+
Effect.provideContext(runContext),
|
|
492
|
+
Effect.forkIn(runScope, { startImmediately: true }),
|
|
493
|
+
)
|
|
494
|
+
})
|
|
495
|
+
|
|
496
|
+
// Leaves `output` out when unset, so the result stays JSON for RPC.
|
|
497
|
+
const childResult = ({ id, turn }: Child): SubagentResult =>
|
|
498
|
+
turn.output === undefined
|
|
499
|
+
? { id: String(id), status: turn.status }
|
|
500
|
+
: { id: String(id), status: turn.status, output: turn.output }
|
|
501
|
+
|
|
502
|
+
const lookupChild = (id: string) =>
|
|
503
|
+
Effect.suspend(() => {
|
|
504
|
+
const child = children.get(id)
|
|
505
|
+
return child
|
|
506
|
+
? Effect.succeed(child)
|
|
507
|
+
: Effect.fail(
|
|
508
|
+
`Unknown agent id ${JSON.stringify(id)}. You can only address agents you started; call listAgents() to see them.`,
|
|
309
509
|
)
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
510
|
+
})
|
|
511
|
+
|
|
512
|
+
const subagents: Subagents = {
|
|
513
|
+
delegate: Effect.fnUntraced(function* ({ prompt, background }) {
|
|
514
|
+
const agentId = agentCounter++
|
|
515
|
+
const child: Child = {
|
|
516
|
+
id: agentId,
|
|
517
|
+
prompt,
|
|
518
|
+
history: MutableRef.make(Prompt.empty),
|
|
519
|
+
mailbox: makeMailbox(),
|
|
520
|
+
turn: makeTurn(agentId, background),
|
|
521
|
+
}
|
|
522
|
+
const id = String(child.id)
|
|
523
|
+
children.set(id, child)
|
|
524
|
+
const turn = child.turn
|
|
525
|
+
yield* startTurn({
|
|
526
|
+
child,
|
|
527
|
+
label: prompt,
|
|
528
|
+
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:
|
|
529
|
+
|
|
530
|
+
${prompt}`,
|
|
531
|
+
background,
|
|
532
|
+
})
|
|
533
|
+
if (background) {
|
|
534
|
+
return { id, status: "running" }
|
|
535
|
+
}
|
|
536
|
+
// Foreground: a failure crashes the script, as before. Interrupting
|
|
537
|
+
// the script stops the agent.
|
|
538
|
+
yield* Deferred.await(turn.done).pipe(
|
|
539
|
+
Effect.onInterrupt(() => Fiber.interrupt(turn.fiber!)),
|
|
313
540
|
)
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
541
|
+
if (turn.status !== "completed") {
|
|
542
|
+
return yield* Effect.die(
|
|
543
|
+
new Error(
|
|
544
|
+
`Sub-agent ${child.id} ${turn.status}${turn.output ? `: ${turn.output}` : ""}`,
|
|
545
|
+
),
|
|
546
|
+
)
|
|
547
|
+
}
|
|
548
|
+
return { id, status: "completed", output: turn.output ?? "" }
|
|
549
|
+
}),
|
|
550
|
+
waitAgents: Effect.fnUntraced(function* (ids) {
|
|
551
|
+
const targets =
|
|
552
|
+
ids === undefined
|
|
553
|
+
? Array.Array.from(children.values())
|
|
554
|
+
: yield* Effect.forEach(ids, lookupChild)
|
|
555
|
+
// A turn started by messageAgent while waiting is waited for too.
|
|
556
|
+
while (true) {
|
|
557
|
+
const running = targets.find(
|
|
558
|
+
(child) => child.turn.status === "running",
|
|
559
|
+
)
|
|
560
|
+
if (!running) break
|
|
561
|
+
yield* Deferred.await(running.turn.done)
|
|
562
|
+
}
|
|
563
|
+
return targets.map((child) => {
|
|
564
|
+
child.turn.delivered = true
|
|
565
|
+
return childResult(child)
|
|
566
|
+
})
|
|
567
|
+
}),
|
|
568
|
+
messageAgent: Effect.fnUntraced(function* ({ id, message }) {
|
|
569
|
+
const child = yield* lookupChild(id)
|
|
570
|
+
if (child.turn.status === "running") {
|
|
571
|
+
child.mailbox.messages.add({ message, resume: () => {} })
|
|
572
|
+
child.mailbox.notify()
|
|
573
|
+
return childResult(child)
|
|
574
|
+
}
|
|
575
|
+
child.turn = makeTurn(child.id, true)
|
|
576
|
+
yield* startTurn({
|
|
577
|
+
child,
|
|
578
|
+
prompt: message,
|
|
579
|
+
label: message,
|
|
580
|
+
background: true,
|
|
581
|
+
})
|
|
582
|
+
return childResult(child)
|
|
583
|
+
}),
|
|
584
|
+
stopAgent: Effect.fnUntraced(function* (id) {
|
|
585
|
+
const child = yield* lookupChild(id)
|
|
586
|
+
const turn = child.turn
|
|
587
|
+
turn.delivered = true
|
|
588
|
+
if (turn.status === "running") {
|
|
589
|
+
yield* Fiber.interrupt(turn.fiber!)
|
|
590
|
+
}
|
|
591
|
+
return childResult(child)
|
|
592
|
+
}),
|
|
593
|
+
listAgents: Effect.sync(() =>
|
|
594
|
+
Array.Array.from(children.values(), (child) => ({
|
|
595
|
+
id: String(child.id),
|
|
596
|
+
status: child.turn.status,
|
|
597
|
+
prompt: child.prompt,
|
|
598
|
+
})),
|
|
599
|
+
),
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
const onTaskComplete = (summary: string) =>
|
|
603
|
+
Effect.suspend(() => {
|
|
604
|
+
const running = runningChildren()
|
|
605
|
+
if (running.length > 0) {
|
|
606
|
+
const ids = running.map((child) => JSON.stringify(String(child.id)))
|
|
607
|
+
return Effect.fail(
|
|
608
|
+
`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.`,
|
|
609
|
+
)
|
|
610
|
+
}
|
|
611
|
+
finalSummary = Option.some(summary)
|
|
612
|
+
return Effect.void
|
|
613
|
+
})
|
|
614
|
+
|
|
615
|
+
// Blocks an idle conversation turn until a child finishes or a message
|
|
616
|
+
// arrives.
|
|
617
|
+
const waitForActivity = Effect.callback<void>((resume) => {
|
|
618
|
+
if (
|
|
619
|
+
mailbox.messages.size > 0 ||
|
|
620
|
+
hasUndelivered() ||
|
|
621
|
+
runningChildren().length === 0
|
|
622
|
+
) {
|
|
623
|
+
resume(Effect.void)
|
|
624
|
+
return
|
|
625
|
+
}
|
|
626
|
+
wakeUp = () => resume(Effect.void)
|
|
627
|
+
return Effect.sync(() => {
|
|
628
|
+
wakeUp = undefined
|
|
629
|
+
})
|
|
630
|
+
})
|
|
318
631
|
|
|
319
632
|
// Turn timeout
|
|
320
633
|
const clock = yield* Clock.Clock
|
|
@@ -368,7 +681,7 @@ ${content}
|
|
|
368
681
|
let tokensBefore: number
|
|
369
682
|
let tokensAfter: number
|
|
370
683
|
if (Option.isSome(result)) {
|
|
371
|
-
|
|
684
|
+
replaceHistory(result.value.prompt)
|
|
372
685
|
lastContextTokens = undefined
|
|
373
686
|
tokensBefore = result.value.tokensBefore
|
|
374
687
|
tokensAfter = result.value.tokensAfter
|
|
@@ -393,15 +706,13 @@ ${content}
|
|
|
393
706
|
const output = yield* pipe(
|
|
394
707
|
executor.execute({
|
|
395
708
|
script: normalizedScript,
|
|
396
|
-
|
|
397
|
-
onTaskComplete
|
|
398
|
-
Effect.sync(() => {
|
|
399
|
-
finalSummary = Option.some(summary)
|
|
400
|
-
}),
|
|
709
|
+
subagents,
|
|
710
|
+
onTaskComplete,
|
|
401
711
|
onImage: (image) =>
|
|
402
712
|
Effect.sync(() => {
|
|
403
713
|
pendingImages.push(image)
|
|
404
714
|
}),
|
|
715
|
+
loopTools: loopTools.handlers,
|
|
405
716
|
}),
|
|
406
717
|
Stream.mkString,
|
|
407
718
|
)
|
|
@@ -425,6 +736,24 @@ ${content}
|
|
|
425
736
|
MutableRef.update(prompt, Prompt.setSystem(system))
|
|
426
737
|
}
|
|
427
738
|
|
|
739
|
+
yield* Queue.offer(
|
|
740
|
+
output,
|
|
741
|
+
new AgentStart({
|
|
742
|
+
id: opts.agentId,
|
|
743
|
+
prompt: opts.prompt,
|
|
744
|
+
provider: yield* Model.ProviderName,
|
|
745
|
+
model: yield* Model.ModelName,
|
|
746
|
+
}),
|
|
747
|
+
)
|
|
748
|
+
if (opts.historyEvents) {
|
|
749
|
+
const messages = opts.prompt.content.filter(
|
|
750
|
+
(message) => message.role !== "system",
|
|
751
|
+
)
|
|
752
|
+
if (messages.length > 0) {
|
|
753
|
+
yield* Queue.offer(output, new HistoryAppended({ messages }))
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
|
|
428
757
|
yield* Effect.gen(function* () {
|
|
429
758
|
while (true) {
|
|
430
759
|
if (Option.isSome(finalSummary)) {
|
|
@@ -435,11 +764,10 @@ ${content}
|
|
|
435
764
|
return
|
|
436
765
|
}
|
|
437
766
|
|
|
438
|
-
if (
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
Array.Array.from(pendingMessages, ({ message, resume }) => {
|
|
767
|
+
if (mailbox.messages.size > 0) {
|
|
768
|
+
appendHistory(
|
|
769
|
+
Prompt.make(
|
|
770
|
+
Array.Array.from(mailbox.messages, ({ message, resume }) => {
|
|
443
771
|
resume(Effect.void)
|
|
444
772
|
return {
|
|
445
773
|
role: "user",
|
|
@@ -448,7 +776,29 @@ ${content}
|
|
|
448
776
|
}),
|
|
449
777
|
),
|
|
450
778
|
)
|
|
451
|
-
|
|
779
|
+
mailbox.messages.clear()
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// Completion pushes from background sub-agents. These have their own
|
|
783
|
+
// queue: the steering path above cuts the model stream short.
|
|
784
|
+
if (completions.length > 0) {
|
|
785
|
+
const pushes = completions.splice(0).filter((turn) => {
|
|
786
|
+
if (turn.delivered) return false
|
|
787
|
+
turn.delivered = true
|
|
788
|
+
return true
|
|
789
|
+
})
|
|
790
|
+
if (pushes.length > 0) {
|
|
791
|
+
appendHistory(
|
|
792
|
+
Prompt.make(
|
|
793
|
+
pushes.map((turn) => ({
|
|
794
|
+
role: "user" as const,
|
|
795
|
+
content: `<subagent id="${turn.agentId}" status="${turn.status}">
|
|
796
|
+
${Compaction.capOutput(turn.output ?? "").output}
|
|
797
|
+
</subagent>`,
|
|
798
|
+
})),
|
|
799
|
+
),
|
|
800
|
+
)
|
|
801
|
+
}
|
|
452
802
|
}
|
|
453
803
|
|
|
454
804
|
// Threshold compaction before the next model call
|
|
@@ -477,6 +827,19 @@ ${content}
|
|
|
477
827
|
let reasoningStarted = false
|
|
478
828
|
let hadReasoningDelta = false
|
|
479
829
|
let hadToolCall = false
|
|
830
|
+
// Retries of this model call so far, and the error that used up the
|
|
831
|
+
// last one.
|
|
832
|
+
let retries = 0
|
|
833
|
+
let exhaustedBy: AiError.AiError | undefined
|
|
834
|
+
const retryOrExhaust = (error: AiError.AiError) => {
|
|
835
|
+
if (retries >= maxRetries) {
|
|
836
|
+
exhaustedBy = error
|
|
837
|
+
return false
|
|
838
|
+
}
|
|
839
|
+
retries++
|
|
840
|
+
maybeSend({ agentId, part: new ErrorRetry({ error }) })
|
|
841
|
+
return true
|
|
842
|
+
}
|
|
480
843
|
const runModel = pipe(
|
|
481
844
|
Stream.suspend(() =>
|
|
482
845
|
ai.streamText({
|
|
@@ -489,7 +852,7 @@ ${content}
|
|
|
489
852
|
Stream.takeUntil((part) => {
|
|
490
853
|
if (
|
|
491
854
|
(part.type === "text-end" || part.type === "reasoning-end") &&
|
|
492
|
-
|
|
855
|
+
mailbox.messages.size > 0
|
|
493
856
|
) {
|
|
494
857
|
return true
|
|
495
858
|
}
|
|
@@ -576,26 +939,17 @@ ${content}
|
|
|
576
939
|
Effect.retry({
|
|
577
940
|
while(err) {
|
|
578
941
|
if (err._tag === "TimeoutError") {
|
|
579
|
-
maybeSend({
|
|
580
|
-
agentId,
|
|
581
|
-
part: new ErrorRetry({
|
|
582
|
-
error: AiError.make({
|
|
583
|
-
module: "clanka/Agent",
|
|
584
|
-
method: "send",
|
|
585
|
-
reason: new AiError.UnknownError({
|
|
586
|
-
description: "TurnTimeout was reached",
|
|
587
|
-
}),
|
|
588
|
-
}),
|
|
589
|
-
}),
|
|
590
|
-
})
|
|
591
942
|
discardAttempt()
|
|
592
|
-
return
|
|
943
|
+
return retryOrExhaust(turnTimeoutError)
|
|
593
944
|
}
|
|
594
945
|
// Never retry a context-length error as is: the overflow
|
|
595
946
|
// handler below compacts first.
|
|
596
947
|
if (Compaction.isContextLengthError(err)) return false
|
|
597
948
|
if (err.isRetryable) {
|
|
598
|
-
|
|
949
|
+
if (!retryOrExhaust(err)) {
|
|
950
|
+
discardAttempt()
|
|
951
|
+
return false
|
|
952
|
+
}
|
|
599
953
|
switch (err.reason._tag) {
|
|
600
954
|
case "ToolNotFoundError":
|
|
601
955
|
case "InvalidOutputError": {
|
|
@@ -604,7 +958,7 @@ ${content}
|
|
|
604
958
|
`There was an error, please try again using the "execute" tool:\n\n${Cause.pretty(Cause.fail(err))}`,
|
|
605
959
|
),
|
|
606
960
|
)
|
|
607
|
-
|
|
961
|
+
appendHistory(toAppend)
|
|
608
962
|
}
|
|
609
963
|
}
|
|
610
964
|
}
|
|
@@ -613,6 +967,13 @@ ${content}
|
|
|
613
967
|
},
|
|
614
968
|
schedule: retryPolicy,
|
|
615
969
|
}),
|
|
970
|
+
Effect.catchIf(
|
|
971
|
+
() => exhaustedBy !== undefined,
|
|
972
|
+
() =>
|
|
973
|
+
Effect.fail(
|
|
974
|
+
new RetriesExhausted({ retries, error: exhaustedBy! }),
|
|
975
|
+
),
|
|
976
|
+
),
|
|
616
977
|
Effect.catchTag("TimeoutError", Effect.die),
|
|
617
978
|
)
|
|
618
979
|
// Unsupported images: drop them from the request and retry once.
|
|
@@ -620,6 +981,7 @@ ${content}
|
|
|
620
981
|
const attemptWithImageFallback = attempt.pipe(
|
|
621
982
|
Effect.catchIf(
|
|
622
983
|
(err): err is AiError.AiError =>
|
|
984
|
+
err._tag === "AiError" &&
|
|
623
985
|
sendImages &&
|
|
624
986
|
Image.hasImages(prompt.current) &&
|
|
625
987
|
Image.isUnsupportedImageError(err),
|
|
@@ -635,7 +997,7 @@ ${content}
|
|
|
635
997
|
yield* attemptWithImageFallback.pipe(
|
|
636
998
|
Effect.catchIf(
|
|
637
999
|
(err): err is AiError.AiError =>
|
|
638
|
-
Compaction.isContextLengthError(err),
|
|
1000
|
+
err._tag === "AiError" && Compaction.isContextLengthError(err),
|
|
639
1001
|
(err) =>
|
|
640
1002
|
Effect.gen(function* () {
|
|
641
1003
|
discardAttempt()
|
|
@@ -660,21 +1022,19 @@ ${content}
|
|
|
660
1022
|
}),
|
|
661
1023
|
),
|
|
662
1024
|
)
|
|
663
|
-
|
|
664
|
-
prompt,
|
|
665
|
-
Prompt.concat(Prompt.fromResponseParts(response)),
|
|
666
|
-
)
|
|
1025
|
+
appendHistory(Prompt.fromResponseParts(response))
|
|
667
1026
|
if (pendingImages.length > 0) {
|
|
668
1027
|
// After the tool result, so call / result pairing stays intact.
|
|
669
|
-
|
|
670
|
-
prompt,
|
|
671
|
-
Prompt.concat(
|
|
672
|
-
Prompt.fromMessages([Image.userMessage(pendingImages)]),
|
|
673
|
-
),
|
|
674
|
-
)
|
|
1028
|
+
appendHistory(Prompt.fromMessages([Image.userMessage(pendingImages)]))
|
|
675
1029
|
pendingImages.length = 0
|
|
676
1030
|
}
|
|
677
|
-
if (conversationMode && !hadToolCall &&
|
|
1031
|
+
if (conversationMode && !hadToolCall && mailbox.messages.size === 0) {
|
|
1032
|
+
// The run is not over while children are running or their results
|
|
1033
|
+
// have not been seen yet.
|
|
1034
|
+
if (runningChildren().length > 0 || hasUndelivered()) {
|
|
1035
|
+
yield* waitForActivity
|
|
1036
|
+
continue
|
|
1037
|
+
}
|
|
678
1038
|
finalSummary = Option.some(responseToSummary(response))
|
|
679
1039
|
}
|
|
680
1040
|
}
|
|
@@ -684,20 +1044,11 @@ ${content}
|
|
|
684
1044
|
maybeSend({ agentId, part: new ScriptDelta({ delta: script }) })
|
|
685
1045
|
return executeScript(script)
|
|
686
1046
|
}),
|
|
1047
|
+
Effect.ensuring(Scope.close(runScope, Exit.void)),
|
|
687
1048
|
Effect.catchCause((cause) => Queue.failCause(output, cause)),
|
|
688
1049
|
Effect.forkScoped,
|
|
689
1050
|
)
|
|
690
1051
|
|
|
691
|
-
yield* Queue.offer(
|
|
692
|
-
output,
|
|
693
|
-
new AgentStart({
|
|
694
|
-
id: opts.agentId,
|
|
695
|
-
prompt: opts.prompt,
|
|
696
|
-
provider: yield* Model.ProviderName,
|
|
697
|
-
model: yield* Model.ModelName,
|
|
698
|
-
}),
|
|
699
|
-
)
|
|
700
|
-
|
|
701
1052
|
return Stream.fromQueue(output)
|
|
702
1053
|
}, Stream.unwrap)
|
|
703
1054
|
|
|
@@ -711,6 +1062,10 @@ ${content}
|
|
|
711
1062
|
agentId: agentCounter++,
|
|
712
1063
|
prompt: Prompt.make(options.prompt),
|
|
713
1064
|
system: options.system,
|
|
1065
|
+
history,
|
|
1066
|
+
mailbox: rootMailbox,
|
|
1067
|
+
display: true,
|
|
1068
|
+
historyEvents: true,
|
|
714
1069
|
}).pipe(
|
|
715
1070
|
Stream.broadcast({ capacity: "unbounded", replay: 1 }),
|
|
716
1071
|
sendLock.withPermit,
|
|
@@ -718,17 +1073,105 @@ ${content}
|
|
|
718
1073
|
steer: (message) =>
|
|
719
1074
|
Effect.callback((resume) => {
|
|
720
1075
|
const entry = { message, resume }
|
|
721
|
-
|
|
722
|
-
|
|
1076
|
+
rootMailbox.messages.add(entry)
|
|
1077
|
+
rootMailbox.notify()
|
|
1078
|
+
return Effect.sync(() => rootMailbox.messages.delete(entry))
|
|
723
1079
|
}),
|
|
724
1080
|
})
|
|
725
1081
|
})
|
|
726
1082
|
|
|
1083
|
+
/**
|
|
1084
|
+
* Create an Agent with every executor tool, the executor's `AGENTS.md` and
|
|
1085
|
+
* skills, and no loop-side tools.
|
|
1086
|
+
*
|
|
1087
|
+
* @since 1.0.0
|
|
1088
|
+
* @category Constructors
|
|
1089
|
+
*/
|
|
1090
|
+
export const make: Effect.Effect<
|
|
1091
|
+
Agent,
|
|
1092
|
+
never,
|
|
1093
|
+
Scope.Scope | AgentExecutor.AgentExecutor
|
|
1094
|
+
> = makeWith({})
|
|
1095
|
+
|
|
1096
|
+
interface Mailbox {
|
|
1097
|
+
readonly messages: Set<{
|
|
1098
|
+
readonly message: string
|
|
1099
|
+
readonly resume: (effect: Effect.Effect<void>) => void
|
|
1100
|
+
}>
|
|
1101
|
+
/** Wakes the agent's run if it is waiting for activity. */
|
|
1102
|
+
notify: () => void
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
const makeMailbox = (): Mailbox => ({
|
|
1106
|
+
messages: new Set(),
|
|
1107
|
+
notify: () => {},
|
|
1108
|
+
})
|
|
1109
|
+
|
|
1110
|
+
interface Child {
|
|
1111
|
+
readonly id: number
|
|
1112
|
+
readonly prompt: string
|
|
1113
|
+
/** Kept for the whole run so `messageAgent` can resume the agent. */
|
|
1114
|
+
readonly history: MutableRef.MutableRef<Prompt.Prompt>
|
|
1115
|
+
readonly mailbox: Mailbox
|
|
1116
|
+
/** The latest turn. Replaced when `messageAgent` resumes the agent. */
|
|
1117
|
+
turn: Turn
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
interface Turn {
|
|
1121
|
+
readonly agentId: number
|
|
1122
|
+
status: SubagentStatus
|
|
1123
|
+
output: string | undefined
|
|
1124
|
+
/** Whether the model has seen this result. Undelivered results are pushed. */
|
|
1125
|
+
delivered: boolean
|
|
1126
|
+
readonly done: Deferred.Deferred<void>
|
|
1127
|
+
fiber: Fiber.Fiber<string, AiError.AiError | RetriesExhausted> | undefined
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
const makeTurn = (agentId: number, background: boolean): Turn => ({
|
|
1131
|
+
agentId,
|
|
1132
|
+
status: "running",
|
|
1133
|
+
output: undefined,
|
|
1134
|
+
// Foreground results go straight back to the script.
|
|
1135
|
+
delivered: !background,
|
|
1136
|
+
done: Deferred.makeUnsafe(),
|
|
1137
|
+
fiber: undefined,
|
|
1138
|
+
})
|
|
1139
|
+
|
|
1140
|
+
const causeMessage = (cause: Cause.Cause<unknown>): string =>
|
|
1141
|
+
errorMessage(Cause.squash(cause))
|
|
1142
|
+
|
|
1143
|
+
const turnTimeoutError = AiError.make({
|
|
1144
|
+
module: "clanka/Agent",
|
|
1145
|
+
method: "send",
|
|
1146
|
+
reason: new AiError.UnknownError({
|
|
1147
|
+
description: "TurnTimeout was reached",
|
|
1148
|
+
}),
|
|
1149
|
+
})
|
|
1150
|
+
|
|
727
1151
|
const retryPolicy = Schedule.min([
|
|
728
1152
|
Schedule.exponential(100, 1.5),
|
|
729
1153
|
Schedule.spaced(5000),
|
|
730
1154
|
]).pipe(Schedule.jittered)
|
|
731
1155
|
|
|
1156
|
+
const renderAgentsMd = (content: string) => `# AGENTS.md
|
|
1157
|
+
|
|
1158
|
+
The following instructions are from ./AGENTS.md in the current directory.
|
|
1159
|
+
You do not need to read this file again.
|
|
1160
|
+
|
|
1161
|
+
**ALWAYS follow these instructions when completing tasks**:
|
|
1162
|
+
|
|
1163
|
+
<!-- AGENTS.md start -->
|
|
1164
|
+
${content}
|
|
1165
|
+
<!-- AGENTS.md end -->`
|
|
1166
|
+
|
|
1167
|
+
const renderInstructions = (content: string) => `# Project instructions
|
|
1168
|
+
|
|
1169
|
+
**ALWAYS follow these instructions when completing tasks**:
|
|
1170
|
+
|
|
1171
|
+
<!-- instructions start -->
|
|
1172
|
+
${content}
|
|
1173
|
+
<!-- instructions end -->`
|
|
1174
|
+
|
|
732
1175
|
const defaultSystem = (options: {
|
|
733
1176
|
readonly toolInstructions: string
|
|
734
1177
|
readonly agentsMd: string | null
|
|
@@ -739,29 +1182,80 @@ ${options.toolInstructions}
|
|
|
739
1182
|
${options.agentsMd}
|
|
740
1183
|
`
|
|
741
1184
|
|
|
1185
|
+
interface PromptTools {
|
|
1186
|
+
readonly toolsDts: string
|
|
1187
|
+
readonly offers: (name: ExcludableTool) => boolean
|
|
1188
|
+
readonly skillsCatalog: Option.Option<string>
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
const when = (condition: boolean, text: string) => (condition ? text : "")
|
|
1192
|
+
|
|
742
1193
|
const generateSystemTools = (
|
|
743
|
-
|
|
1194
|
+
tools: PromptTools,
|
|
744
1195
|
conversationMode: boolean,
|
|
745
1196
|
) => `YOU ONLY HAVE ONE TOOL AVAILABLE: "execute", to run javascript code to do your work.
|
|
746
1197
|
|
|
747
1198
|
- Use \`console.log\` to print any output you need.
|
|
748
|
-
- Use top level await.${
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
- Prefer using the "search" function over "rg", unless you are targeting specific files or patterns
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
-
|
|
1199
|
+
- Use top level await.${when(
|
|
1200
|
+
tools.offers("search") && tools.offers("rg"),
|
|
1201
|
+
`
|
|
1202
|
+
- Prefer using the "search" function over "rg", unless you are targeting specific files or patterns.`,
|
|
1203
|
+
)}${when(
|
|
1204
|
+
tools.offers("applyPatch"),
|
|
1205
|
+
`
|
|
1206
|
+
- You can add / update / remove multiple files in one go with "applyPatch".${when(
|
|
1207
|
+
tools.offers("writeFile"),
|
|
1208
|
+
` Prefer it over "writeFile" to update existing files.`,
|
|
1209
|
+
)}`,
|
|
1210
|
+
)}${when(
|
|
1211
|
+
tools.offers("bash"),
|
|
1212
|
+
`
|
|
1213
|
+
- Avoid passing scripts into the "bash" function, and instead write javascript.`,
|
|
1214
|
+
)}
|
|
756
1215
|
- Variables are not shared between executions.
|
|
757
|
-
- Do not use \`require\`, \`import\`, \`process\`, or any other Node.js apis.${
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
1216
|
+
- Do not use \`require\`, \`import\`, \`process\`, or any other Node.js apis.${when(
|
|
1217
|
+
tools.offers("delegate"),
|
|
1218
|
+
`
|
|
1219
|
+
- "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(
|
|
1220
|
+
tools.offers("waitAgents"),
|
|
1221
|
+
` Use "waitAgents" to wait for the returned id.`,
|
|
1222
|
+
)}${when(
|
|
1223
|
+
tools.offers("messageAgent"),
|
|
1224
|
+
` Use "messageAgent" to send a message to the returned id.`,
|
|
1225
|
+
)}${when(
|
|
1226
|
+
tools.offers("stopAgent"),
|
|
1227
|
+
` Use "stopAgent" to stop the returned id.`,
|
|
1228
|
+
)}${when(
|
|
1229
|
+
tools.offers("listAgents"),
|
|
1230
|
+
` "listAgents" shows the agents you started.`,
|
|
1231
|
+
)}`,
|
|
1232
|
+
)}${when(
|
|
1233
|
+
!conversationMode,
|
|
1234
|
+
`
|
|
761
1235
|
|
|
762
1236
|
When you have fully completed your task, call the "taskComplete" function with the final output.
|
|
763
|
-
Make sure every detail of the task is done before calling "taskComplete"
|
|
764
|
-
|
|
1237
|
+
Make sure every detail of the task is done before calling "taskComplete".${when(
|
|
1238
|
+
tools.offers("delegate"),
|
|
1239
|
+
`
|
|
1240
|
+
Any sub-agents you started must finish first: "taskComplete" fails while they are running.`,
|
|
1241
|
+
)}`,
|
|
1242
|
+
)}${when(tools.offers("readFile") && tools.offers("ls"), example)}
|
|
1243
|
+
|
|
1244
|
+
These are the functions available to you:
|
|
1245
|
+
|
|
1246
|
+
\`\`\`ts
|
|
1247
|
+
${tools.toolsDts}
|
|
1248
|
+
|
|
1249
|
+
/** The global Fetch API available for making HTTP requests. */
|
|
1250
|
+
declare const fetch: typeof globalThis.fetch
|
|
1251
|
+
\`\`\`${Option.match(tools.skillsCatalog, {
|
|
1252
|
+
onNone: () => "",
|
|
1253
|
+
onSome: (catalog) => `
|
|
1254
|
+
|
|
1255
|
+
${catalog}`,
|
|
1256
|
+
})}`
|
|
1257
|
+
|
|
1258
|
+
const example = `
|
|
765
1259
|
|
|
766
1260
|
Here is how you would read a file and list a directory:
|
|
767
1261
|
|
|
@@ -788,21 +1282,104 @@ package.json: {
|
|
|
788
1282
|
"name": "my-project",
|
|
789
1283
|
"version": "1.0.0"
|
|
790
1284
|
}
|
|
791
|
-
|
|
1285
|
+
\`\`\``
|
|
792
1286
|
|
|
793
|
-
|
|
1287
|
+
const ReadSkillTools = Toolkit.make(
|
|
1288
|
+
Tool.make("readSkill", {
|
|
1289
|
+
description:
|
|
1290
|
+
"Read the instructions of a skill listed under Skills, by its name.",
|
|
1291
|
+
parameters: Schema.String.annotate({ identifier: "name" }),
|
|
1292
|
+
success: Schema.String,
|
|
1293
|
+
failure: Schema.String,
|
|
1294
|
+
}),
|
|
1295
|
+
)
|
|
794
1296
|
|
|
795
|
-
|
|
796
|
-
|
|
1297
|
+
/**
|
|
1298
|
+
* Builds the loop-side handlers the executor puts in the sandbox, and their
|
|
1299
|
+
* type declarations. Every call is decoded by `Toolkit.handle` before the
|
|
1300
|
+
* handler runs; results are encoded to JSON.
|
|
1301
|
+
*/
|
|
1302
|
+
const makeLoopTools = Effect.fnUntraced(function* (options: {
|
|
1303
|
+
readonly loopTools: Toolkit.Any | undefined
|
|
1304
|
+
readonly skills: ReadonlyArray<AgentSkills.ProvidedSkill> | undefined
|
|
1305
|
+
readonly executorTools: ReadonlyArray<string>
|
|
1306
|
+
}) {
|
|
1307
|
+
const skills = options.skills ?? []
|
|
1308
|
+
const callerTools = Object.keys(options.loopTools?.tools ?? {})
|
|
1309
|
+
const names = skills.length > 0 ? [...callerTools, "readSkill"] : callerTools
|
|
1310
|
+
for (const name of names) {
|
|
1311
|
+
if (
|
|
1312
|
+
options.executorTools.includes(name) ||
|
|
1313
|
+
names.indexOf(name) !== names.lastIndexOf(name)
|
|
1314
|
+
) {
|
|
1315
|
+
return yield* Effect.die(
|
|
1316
|
+
new Error(`Loop-side tool "${name}" clashes with another tool`),
|
|
1317
|
+
)
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
797
1320
|
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
1321
|
+
const toolkit = Toolkit.merge(
|
|
1322
|
+
options.loopTools ?? Toolkit.empty,
|
|
1323
|
+
skills.length > 0 ? ReadSkillTools : Toolkit.empty,
|
|
1324
|
+
) as unknown as Toolkit.Toolkit<Record<string, Tool.Any>>
|
|
1325
|
+
const withHandlers = toolkit as unknown as Effect.Effect<
|
|
1326
|
+
Toolkit.WithHandler<Record<string, Tool.Any>>
|
|
1327
|
+
>
|
|
1328
|
+
// Only provided with the tool itself, so it never replaces a caller's
|
|
1329
|
+
// `readSkill` handler.
|
|
1330
|
+
const handled = yield* skills.length > 0
|
|
1331
|
+
? withHandlers.pipe(
|
|
1332
|
+
Effect.provide(
|
|
1333
|
+
ReadSkillTools.toLayer({
|
|
1334
|
+
readSkill: (name) => {
|
|
1335
|
+
const skill = skills.find((skill) => skill.name === name)
|
|
1336
|
+
return skill
|
|
1337
|
+
? Effect.succeed(skill.content)
|
|
1338
|
+
: Effect.fail(
|
|
1339
|
+
`Unknown skill ${JSON.stringify(name)}. Available skills: ${skills.map((skill) => skill.name).join(", ")}`,
|
|
1340
|
+
)
|
|
1341
|
+
},
|
|
1342
|
+
}),
|
|
1343
|
+
),
|
|
1344
|
+
)
|
|
1345
|
+
: withHandlers
|
|
1346
|
+
// Provides the services the caller's handlers depend on.
|
|
1347
|
+
const context = yield* Effect.context<never>()
|
|
803
1348
|
|
|
804
|
-
|
|
805
|
-
|
|
1349
|
+
const handlers: Record<
|
|
1350
|
+
string,
|
|
1351
|
+
(params: unknown) => Effect.Effect<unknown, string>
|
|
1352
|
+
> = {}
|
|
1353
|
+
for (const [name, tool] of Object.entries(handled.tools)) {
|
|
1354
|
+
const encodeSuccess = Schema.encodeUnknownEffect(
|
|
1355
|
+
Schema.toCodecJson(tool.successSchema as Schema.Codec<unknown>),
|
|
1356
|
+
)
|
|
1357
|
+
handlers[name] = (params) =>
|
|
1358
|
+
handled.handle(name, params as never).pipe(
|
|
1359
|
+
Effect.flatMap(Stream.runLast),
|
|
1360
|
+
Effect.flatMap((last): Effect.Effect<unknown, unknown> => {
|
|
1361
|
+
if (Option.isNone(last)) return Effect.void
|
|
1362
|
+
return last.value.isFailure
|
|
1363
|
+
? Effect.fail(last.value.result)
|
|
1364
|
+
: encodeSuccess(last.value.result)
|
|
1365
|
+
}),
|
|
1366
|
+
Effect.mapError(errorMessage),
|
|
1367
|
+
Effect.provideContext(context),
|
|
1368
|
+
) as Effect.Effect<unknown, string>
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
const renderer = yield* Effect.service(ToolkitRenderer).pipe(
|
|
1372
|
+
Effect.provide(ToolkitRenderer.layer),
|
|
1373
|
+
)
|
|
1374
|
+
return { handlers, dts: renderer.render(toolkit) }
|
|
1375
|
+
})
|
|
1376
|
+
|
|
1377
|
+
const errorMessage = (error: unknown): string =>
|
|
1378
|
+
typeof error === "string"
|
|
1379
|
+
? error
|
|
1380
|
+
: error instanceof Error
|
|
1381
|
+
? error.message
|
|
1382
|
+
: (JSON.stringify(error) ?? String(error))
|
|
806
1383
|
|
|
807
1384
|
class ScriptExecutor extends Context.Service<
|
|
808
1385
|
ScriptExecutor,
|
|
@@ -833,18 +1410,33 @@ const SingleToolHandlers = SingleTools.toLayer({
|
|
|
833
1410
|
export const layer: Layer.Layer<Agent, never, AgentExecutor.AgentExecutor> =
|
|
834
1411
|
Layer.effect(Agent, make)
|
|
835
1412
|
|
|
1413
|
+
/**
|
|
1414
|
+
* @since 1.0.0
|
|
1415
|
+
* @category Layers
|
|
1416
|
+
*/
|
|
1417
|
+
export const layerWith = <LoopTools extends Toolkit.Any = never>(
|
|
1418
|
+
options: Options<LoopTools>,
|
|
1419
|
+
): Layer.Layer<
|
|
1420
|
+
Agent,
|
|
1421
|
+
never,
|
|
1422
|
+
AgentExecutor.AgentExecutor | LoopToolServices<LoopTools>
|
|
1423
|
+
> => Layer.effect(Agent, makeWith(options))
|
|
1424
|
+
|
|
836
1425
|
/**
|
|
837
1426
|
* Create an Agent layer that uses a local AgentExecutor.
|
|
838
1427
|
*
|
|
839
1428
|
* @since 1.0.0
|
|
840
1429
|
* @category Layers
|
|
841
1430
|
*/
|
|
842
|
-
export const layerLocal = <
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
1431
|
+
export const layerLocal = <
|
|
1432
|
+
Toolkit extends Toolkit.Any = never,
|
|
1433
|
+
LoopTools extends Toolkit.Any = never,
|
|
1434
|
+
>(
|
|
1435
|
+
options: AgentExecutor.LocalOptions<Toolkit> & Options<LoopTools>,
|
|
1436
|
+
): Layer.Layer<
|
|
846
1437
|
Agent,
|
|
847
1438
|
never,
|
|
1439
|
+
| LoopToolServices<LoopTools>
|
|
848
1440
|
| FileSystem.FileSystem
|
|
849
1441
|
| Path.Path
|
|
850
1442
|
| ChildProcessSpawner.ChildProcessSpawner
|
|
@@ -859,7 +1451,7 @@ export const layerLocal = <Toolkit extends Toolkit.Any = never>(options: {
|
|
|
859
1451
|
| TaskCompleter
|
|
860
1452
|
| ImageAttacher
|
|
861
1453
|
>
|
|
862
|
-
> =>
|
|
1454
|
+
> => layerWith(options).pipe(Layer.provide(AgentExecutor.layerLocal(options)))
|
|
863
1455
|
|
|
864
1456
|
/**
|
|
865
1457
|
* @since 1.0.0
|
|
@@ -923,6 +1515,24 @@ export class TurnTimeout extends Context.Reference<Duration.Duration>(
|
|
|
923
1515
|
Layer.succeed(TurnTimeout, Duration.fromInputUnsafe(timeout))
|
|
924
1516
|
}
|
|
925
1517
|
|
|
1518
|
+
/**
|
|
1519
|
+
* The number of times in a row a model call is retried, after a retryable
|
|
1520
|
+
* error or after reaching `TurnTimeout`, before `send` fails with
|
|
1521
|
+
* `RetriesExhausted`. The count resets after a model call succeeds.
|
|
1522
|
+
*
|
|
1523
|
+
* @since 1.0.0
|
|
1524
|
+
* @category Retries
|
|
1525
|
+
*/
|
|
1526
|
+
export class MaxRetries extends Context.Reference<number>(
|
|
1527
|
+
"clanka/Agent/MaxRetries",
|
|
1528
|
+
{
|
|
1529
|
+
defaultValue: () => 20,
|
|
1530
|
+
},
|
|
1531
|
+
) {
|
|
1532
|
+
static readonly layer = (retries: number) =>
|
|
1533
|
+
Layer.succeed(MaxRetries, retries)
|
|
1534
|
+
}
|
|
1535
|
+
|
|
926
1536
|
/**
|
|
927
1537
|
* @since 1.0.0
|
|
928
1538
|
* @category System prompts
|