@tinyweb_dev/agent-framework-agent 0.2.0 → 0.4.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 (144) hide show
  1. package/dist/agent.d.ts +116 -0
  2. package/dist/agent.d.ts.map +1 -0
  3. package/dist/attachments.d.ts +41 -0
  4. package/dist/attachments.d.ts.map +1 -0
  5. package/dist/bus/bus.d.ts +46 -0
  6. package/dist/bus/bus.d.ts.map +1 -0
  7. package/dist/bus/index.d.ts +2 -0
  8. package/dist/bus/index.d.ts.map +1 -0
  9. package/dist/define-tool.d.ts +13 -0
  10. package/dist/define-tool.d.ts.map +1 -0
  11. package/dist/events.d.ts +136 -0
  12. package/dist/events.d.ts.map +1 -0
  13. package/dist/http-handlers.cjs +253 -0
  14. package/dist/http-handlers.cjs.map +1 -0
  15. package/dist/http-handlers.d.ts +49 -0
  16. package/dist/http-handlers.d.ts.map +1 -0
  17. package/dist/http-handlers.js +251 -0
  18. package/dist/http-handlers.js.map +1 -0
  19. package/dist/index.cjs +2073 -0
  20. package/dist/index.cjs.map +1 -0
  21. package/dist/index.d.ts +19 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +2015 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/loop-guard.d.ts +42 -0
  26. package/dist/loop-guard.d.ts.map +1 -0
  27. package/dist/mcp/client.d.ts +25 -0
  28. package/dist/mcp/client.d.ts.map +1 -0
  29. package/dist/mcp/index.cjs +66 -0
  30. package/dist/mcp/index.cjs.map +1 -0
  31. package/{src/mcp/index.ts → dist/mcp/index.d.ts} +2 -1
  32. package/dist/mcp/index.d.ts.map +1 -0
  33. package/dist/mcp/index.js +63 -0
  34. package/dist/mcp/index.js.map +1 -0
  35. package/dist/permission.d.ts +26 -0
  36. package/dist/permission.d.ts.map +1 -0
  37. package/dist/plugin/apply.d.ts +12 -0
  38. package/dist/plugin/apply.d.ts.map +1 -0
  39. package/dist/plugin/index.cjs +63 -0
  40. package/dist/plugin/index.cjs.map +1 -0
  41. package/dist/plugin/index.d.ts +4 -0
  42. package/dist/plugin/index.d.ts.map +1 -0
  43. package/dist/plugin/index.js +52 -0
  44. package/dist/plugin/index.js.map +1 -0
  45. package/dist/plugin/loader.d.ts +3 -0
  46. package/dist/plugin/loader.d.ts.map +1 -0
  47. package/dist/plugin/types.d.ts +98 -0
  48. package/dist/plugin/types.d.ts.map +1 -0
  49. package/dist/prompt/index.d.ts +51 -0
  50. package/dist/prompt/index.d.ts.map +1 -0
  51. package/dist/prompt/objective.d.ts +29 -0
  52. package/dist/prompt/objective.d.ts.map +1 -0
  53. package/dist/prompt/response-style.d.ts +19 -0
  54. package/dist/prompt/response-style.d.ts.map +1 -0
  55. package/dist/prompt/tool-use-guidelines.d.ts +22 -0
  56. package/dist/prompt/tool-use-guidelines.d.ts.map +1 -0
  57. package/dist/prompt/tool-use.d.ts +12 -0
  58. package/dist/prompt/tool-use.d.ts.map +1 -0
  59. package/dist/runtime.d.ts +7 -0
  60. package/dist/runtime.d.ts.map +1 -0
  61. package/dist/session/adapter.d.ts +40 -0
  62. package/dist/session/adapter.d.ts.map +1 -0
  63. package/dist/session/compaction.d.ts +37 -0
  64. package/dist/session/compaction.d.ts.map +1 -0
  65. package/dist/session/index.d.ts +7 -0
  66. package/dist/session/index.d.ts.map +1 -0
  67. package/dist/session/memory.cjs +130 -0
  68. package/dist/session/memory.cjs.map +1 -0
  69. package/dist/session/memory.d.ts +3 -0
  70. package/dist/session/memory.d.ts.map +1 -0
  71. package/dist/session/memory.js +128 -0
  72. package/dist/session/memory.js.map +1 -0
  73. package/dist/session/overflow.d.ts +19 -0
  74. package/dist/session/overflow.d.ts.map +1 -0
  75. package/dist/session/postgres.cjs +245 -0
  76. package/dist/session/postgres.cjs.map +1 -0
  77. package/dist/session/postgres.d.ts +10 -0
  78. package/dist/session/postgres.d.ts.map +1 -0
  79. package/dist/session/postgres.js +243 -0
  80. package/dist/session/postgres.js.map +1 -0
  81. package/dist/session/processor.d.ts +52 -0
  82. package/dist/session/processor.d.ts.map +1 -0
  83. package/dist/session/replay.d.ts +4 -0
  84. package/dist/session/replay.d.ts.map +1 -0
  85. package/dist/session/schema.d.ts +104 -0
  86. package/dist/session/schema.d.ts.map +1 -0
  87. package/dist/session/sqlite.cjs +236 -0
  88. package/dist/session/sqlite.cjs.map +1 -0
  89. package/dist/session/sqlite.d.ts +3 -0
  90. package/dist/session/sqlite.d.ts.map +1 -0
  91. package/dist/session/sqlite.js +234 -0
  92. package/dist/session/sqlite.js.map +1 -0
  93. package/dist/session-api.cjs +56 -0
  94. package/dist/session-api.cjs.map +1 -0
  95. package/dist/session-api.d.ts +36 -0
  96. package/dist/session-api.d.ts.map +1 -0
  97. package/dist/session-api.js +54 -0
  98. package/dist/session-api.js.map +1 -0
  99. package/dist/skill/index.cjs +81 -0
  100. package/dist/skill/index.cjs.map +1 -0
  101. package/dist/skill/index.d.ts +10 -0
  102. package/dist/skill/index.d.ts.map +1 -0
  103. package/dist/skill/index.js +78 -0
  104. package/dist/skill/index.js.map +1 -0
  105. package/dist/sse-handler.d.ts +27 -0
  106. package/dist/sse-handler.d.ts.map +1 -0
  107. package/dist/transcript.d.ts +81 -0
  108. package/dist/transcript.d.ts.map +1 -0
  109. package/package.json +54 -19
  110. package/src/agent.ts +0 -470
  111. package/src/attachments.ts +0 -155
  112. package/src/bus/bus.ts +0 -89
  113. package/src/bus/index.ts +0 -1
  114. package/src/define-tool.ts +0 -41
  115. package/src/events.ts +0 -186
  116. package/src/http-handlers.ts +0 -251
  117. package/src/index.ts +0 -128
  118. package/src/loop-guard.ts +0 -99
  119. package/src/mcp/client.ts +0 -129
  120. package/src/permission.ts +0 -114
  121. package/src/plugin/apply.ts +0 -89
  122. package/src/plugin/index.ts +0 -3
  123. package/src/plugin/loader.ts +0 -42
  124. package/src/plugin/types.ts +0 -134
  125. package/src/prompt/index.ts +0 -90
  126. package/src/prompt/objective.ts +0 -104
  127. package/src/prompt/response-style.ts +0 -59
  128. package/src/prompt/tool-use-guidelines.ts +0 -57
  129. package/src/prompt/tool-use.ts +0 -27
  130. package/src/runtime.ts +0 -22
  131. package/src/session/adapter.ts +0 -46
  132. package/src/session/compaction.ts +0 -160
  133. package/src/session/index.ts +0 -18
  134. package/src/session/memory.ts +0 -169
  135. package/src/session/overflow.ts +0 -50
  136. package/src/session/postgres.ts +0 -355
  137. package/src/session/processor.ts +0 -865
  138. package/src/session/replay.ts +0 -151
  139. package/src/session/schema.ts +0 -156
  140. package/src/session/sqlite.ts +0 -309
  141. package/src/session-api.ts +0 -103
  142. package/src/skill/index.ts +0 -113
  143. package/src/sse-handler.ts +0 -67
  144. package/src/transcript.ts +0 -126
@@ -1,865 +0,0 @@
1
- import {
2
- LLM,
3
- LLMClient,
4
- LLMError,
5
- type ContentPart,
6
- type ExecutableTools,
7
- type GenerationOptions,
8
- type LLMEvent,
9
- type LLMRequest,
10
- type ModelRef,
11
- type StopCondition,
12
- } from "@tinyweb-agent-framework/llm"
13
- import { Cause, Effect, Option, Stream } from "effect"
14
- import type { AttachmentInput } from "../attachments"
15
- import {
16
- FINISH_REASON_APPROVAL_REQUIRED,
17
- fromLLMEvent,
18
- type AgentEvent,
19
- type CondenseTrigger,
20
- type ContextCondenseErrorEvent,
21
- type ContextCondenseEvent,
22
- type ContextCondenseStartEvent,
23
- type ErrorEvent,
24
- } from "../events"
25
- import { isToolInterruptMetadata } from "../permission"
26
- import type { AgentRuntime } from "../runtime"
27
- import type { SessionStore } from "./adapter"
28
- import { compact, type CompactResult } from "./compaction"
29
- import { estimateTokens, usable } from "./overflow"
30
- import { historyToLLMMessages } from "./replay"
31
- import {
32
- makeAssistantMessage,
33
- makeUserMessage,
34
- newPartID,
35
- type AssistantMessage,
36
- type ImagePart,
37
- type Message,
38
- type SessionID,
39
- type TextPart,
40
- type ToolPart,
41
- } from "./schema"
42
-
43
- const attachmentToImagePart = (a: AttachmentInput): ImagePart => ({
44
- type: "image",
45
- url: a.url,
46
- data: a.data,
47
- mediaType: a.mediaType,
48
- })
49
-
50
- const attachmentToContentPart = (a: AttachmentInput): ContentPart => ({
51
- type: "media",
52
- mediaType: a.mediaType,
53
- data: a.url ?? a.data ?? "",
54
- filename: a.filename,
55
- })
56
-
57
- export type ProcessorCompactionConfig = {
58
- readonly auto: boolean
59
- readonly reservedTokens?: number
60
- readonly preserveRecentTurns?: number
61
- }
62
-
63
- export type ProcessorConfig = {
64
- readonly agentName: string
65
- readonly model: ModelRef
66
- readonly store: SessionStore
67
- readonly runtime: AgentRuntime
68
- readonly systemPrompt?: string
69
- /** Permission-wrapped tools used during the normal agentic loop. */
70
- readonly tools?: ExecutableTools
71
- /**
72
- * Unwrapped tools used when executing host-approved calls on resume.
73
- * Required when `permission.askMode === "interrupt"` — wrapped tools always
74
- * short-circuit with ToolInterrupt and cannot re-run after approval.
75
- * Defaults to `tools` when omitted.
76
- */
77
- readonly resumeTools?: ExecutableTools
78
- readonly stopWhen?: StopCondition
79
- readonly generation?: GenerationOptions.Input
80
- readonly compaction?: ProcessorCompactionConfig
81
- }
82
-
83
- export type TurnInput = {
84
- readonly prompt: string
85
- readonly sessionId?: SessionID | string
86
- readonly attachments?: ReadonlyArray<AttachmentInput>
87
- }
88
-
89
- export type ResumeInput = {
90
- readonly sessionId: SessionID | string
91
- }
92
-
93
- export type Processor = {
94
- readonly runTurn: (input: TurnInput) => AsyncIterable<AgentEvent>
95
- /**
96
- * Continue a session after the host resolved one or more pending tool
97
- * approvals. Executes tools marked `approved`, records denials for
98
- * `rejected`, then runs a normal LLM follow-up turn (no new user message).
99
- */
100
- readonly resumeTurn: (input: ResumeInput) => AsyncIterable<AgentEvent>
101
- }
102
-
103
- const DEFAULT_COMPACTION: ProcessorCompactionConfig = { auto: true }
104
-
105
- const errorFromCause = (cause: Cause.Cause<unknown>): ErrorEvent => {
106
- const failure = Cause.findErrorOption(cause)
107
- if (Option.isSome(failure)) {
108
- const e = failure.value as { message?: string; retryable?: boolean }
109
- return { type: "error", message: e.message ?? String(failure.value), retryable: e.retryable }
110
- }
111
- return { type: "error", message: Cause.pretty(cause) }
112
- }
113
-
114
- /** True when a failure carries a `ContextOverflow` reason from the LLM layer. */
115
- const isContextOverflowError = (failure: unknown): boolean => {
116
- if (!(failure instanceof LLMError)) return false
117
- return failure.reason._tag === "ContextOverflow"
118
- }
119
-
120
- // Mutable accumulator that turns the LLMEvent stream into an AssistantMessage at finish time.
121
- type Accumulator = {
122
- textBuffer: string
123
- parts: Array<TextPart | ToolPart>
124
- toolByCall: Map<string, ToolPart>
125
- }
126
-
127
- const emptyAcc = (): Accumulator => ({ textBuffer: "", parts: [], toolByCall: new Map() })
128
-
129
- const flushText = (acc: Accumulator) => {
130
- if (acc.textBuffer.length === 0) return
131
- acc.parts.push({ type: "text", text: acc.textBuffer })
132
- acc.textBuffer = ""
133
- }
134
-
135
- const handleLLMEvent = (acc: Accumulator, event: LLMEvent) => {
136
- if (event.type === "text-delta") {
137
- acc.textBuffer += event.text
138
- return
139
- }
140
- if (event.type === "text-end") {
141
- flushText(acc)
142
- return
143
- }
144
- if (event.type === "tool-call") {
145
- flushText(acc)
146
- const part: ToolPart = {
147
- id: newPartID(),
148
- type: "tool",
149
- callID: event.id,
150
- name: event.name,
151
- state: "running",
152
- input: event.input,
153
- }
154
- acc.parts.push(part)
155
- acc.toolByCall.set(event.id, part)
156
- return
157
- }
158
- if (event.type === "tool-result") {
159
- const part = acc.toolByCall.get(event.id)
160
- if (!part) return
161
- const idx = acc.parts.indexOf(part)
162
- if (idx === -1) return
163
- acc.parts[idx] = { ...part, state: "complete", output: event.result.value }
164
- acc.toolByCall.set(event.id, acc.parts[idx] as ToolPart)
165
- return
166
- }
167
- if (event.type === "tool-error") {
168
- const part = acc.toolByCall.get(event.id)
169
- if (!part) return
170
- const idx = acc.parts.indexOf(part)
171
- if (idx === -1) return
172
- // Permission interrupt → pending-approval (persisted; host must resolve).
173
- if (isToolInterruptMetadata(event.metadata as Record<string, unknown> | undefined)) {
174
- acc.parts[idx] = {
175
- ...part,
176
- state: "pending-approval",
177
- metadata: { ...(part.metadata ?? {}), ...(event.metadata as Record<string, unknown>) },
178
- }
179
- acc.toolByCall.set(event.id, acc.parts[idx] as ToolPart)
180
- return
181
- }
182
- acc.parts[idx] = { ...part, state: "error", output: { message: event.message } }
183
- acc.toolByCall.set(event.id, acc.parts[idx] as ToolPart)
184
- return
185
- }
186
- }
187
-
188
- const mapAgentEvent = (acc: Accumulator, event: LLMEvent): AgentEvent | undefined => {
189
- if (event.type === "tool-error" && isToolInterruptMetadata(event.metadata as Record<string, unknown> | undefined)) {
190
- const part = acc.toolByCall.get(event.id)
191
- return {
192
- type: "tool-approval-request",
193
- id: event.id,
194
- name: event.name,
195
- input: part?.input ?? event.metadata?.input,
196
- }
197
- }
198
- return fromLLMEvent(event)
199
- }
200
-
201
- const hasPendingApproval = (acc: Accumulator): boolean =>
202
- acc.parts.some((p) => (p as ToolPart).type === "tool" && (p as ToolPart).state === "pending-approval")
203
-
204
- /** Persist an in-place message update (approval resolve / resume). */
205
- export const persistMessageUpdate = (
206
- store: SessionStore,
207
- sessionId: SessionID | string,
208
- message: Message,
209
- ): Effect.Effect<void> => {
210
- if (store.updateMessage) {
211
- return store.updateMessage(sessionId, message.id, message)
212
- }
213
- // Fallback for stores that only support append/delete.
214
- return Effect.gen(function* () {
215
- yield* store.deleteMessage(sessionId, message.id)
216
- yield* store.appendMessage(sessionId, message)
217
- })
218
- }
219
-
220
- const DENIED_OUTPUT = { message: "User denied tool execution" } as const
221
-
222
- /**
223
- * Find the latest assistant message that still has tools waiting for (or
224
- * already granted) approval, and return a mutable clone of it.
225
- */
226
- const findApprovalMessage = (
227
- history: ReadonlyArray<Message>,
228
- ): { message: AssistantMessage; index: number } | undefined => {
229
- for (let i = history.length - 1; i >= 0; i--) {
230
- const msg = history[i]
231
- if (!msg || msg.role !== "assistant") continue
232
- const has = msg.parts.some(
233
- (p) =>
234
- (p as ToolPart).type === "tool" &&
235
- ((p as ToolPart).state === "pending-approval" ||
236
- (p as ToolPart).state === "approved" ||
237
- (p as ToolPart).state === "rejected"),
238
- )
239
- if (has) return { message: msg as AssistantMessage, index: i }
240
- }
241
- return undefined
242
- }
243
-
244
- const buildAssistantMessage = (acc: Accumulator): AssistantMessage => {
245
- flushText(acc)
246
- return makeAssistantMessage(acc.parts)
247
- }
248
-
249
- export const makeProcessor = (config: ProcessorConfig): Processor => {
250
- // Default cap mirrors `defineAgent` — see agent.ts for rationale.
251
- const stopWhen = config.stopWhen ?? LLM.stepCountIs(100)
252
- const compaction = config.compaction ?? DEFAULT_COMPACTION
253
-
254
- const buildRequest = (
255
- history: ReadonlyArray<Message>,
256
- prompt: string,
257
- attachments?: ReadonlyArray<AttachmentInput>,
258
- ): LLMRequest => {
259
- const userContent: ContentPart[] = []
260
- if (prompt.length > 0) userContent.push({ type: "text", text: prompt })
261
- for (const a of attachments ?? []) userContent.push(attachmentToContentPart(a))
262
- const userMsg = userContent.length === 0 ? LLM.user(prompt) : LLM.user(userContent)
263
- return LLM.request({
264
- model: config.model,
265
- system: config.systemPrompt,
266
- messages: [...historyToLLMMessages([...history]), userMsg],
267
- generation: config.generation,
268
- })
269
- }
270
-
271
- /**
272
- * Estimate the prompt token count for the upcoming turn. Reuses `estimateTokens`
273
- * on the raw app history + the synthetic user prompt; the system prompt is
274
- * folded in as a plain text bump so callers don't need a separate slot.
275
- */
276
- const estimateUpcoming = (history: ReadonlyArray<Message>, prompt: string): number => {
277
- const promptTokens = Math.ceil(prompt.length / 4)
278
- const systemTokens = Math.ceil((config.systemPrompt?.length ?? 0) / 4)
279
- return estimateTokens(history) + promptTokens + systemTokens
280
- }
281
-
282
- const budget = (): number =>
283
- usable({
284
- limits: config.model.limits,
285
- reservedTokens: compaction.reservedTokens,
286
- })
287
-
288
- /** Run a compaction pass against the store. */
289
- const runCompaction = (
290
- sessionId: SessionID | string,
291
- overflow: boolean,
292
- keepRecentOverride?: number,
293
- ) =>
294
- compact({
295
- sessionId,
296
- store: config.store,
297
- model: config.model,
298
- keepRecent: keepRecentOverride ?? compaction.preserveRecentTurns ?? 4,
299
- overflow,
300
- })
301
-
302
- // ----- condense event builders ------------------------------------------
303
- // We construct event objects up-front (no `new` Effect needed) and push them
304
- // onto a queue drained by the outer AsyncIterator. This keeps the wiring
305
- // surface tiny without touching the inner Effect stream.
306
-
307
- const condenseStart = (
308
- trigger: CondenseTrigger,
309
- estimatedTokens: number | undefined,
310
- budgetTokens: number | undefined,
311
- ): ContextCondenseStartEvent => ({
312
- type: "context-condense-start",
313
- trigger,
314
- estimatedTokens,
315
- budgetTokens,
316
- })
317
-
318
- const condenseSuccess = (
319
- trigger: CondenseTrigger,
320
- result: {
321
- readonly markerId?: unknown
322
- readonly summary?: string
323
- readonly prevTokens?: number
324
- readonly newTokens?: number
325
- readonly cost?: number
326
- readonly modelId?: string
327
- },
328
- ): ContextCondenseEvent | undefined => {
329
- if (!result.markerId || typeof result.summary !== "string") return undefined
330
- return {
331
- type: "context-condense",
332
- trigger,
333
- summary: result.summary,
334
- markerId: String(result.markerId),
335
- prevTokens: result.prevTokens,
336
- newTokens: result.newTokens,
337
- cost: result.cost,
338
- modelId: result.modelId,
339
- }
340
- }
341
-
342
- const condenseError = (
343
- trigger: CondenseTrigger,
344
- message: string,
345
- retryExhausted = false,
346
- ): ContextCondenseErrorEvent => ({
347
- type: "context-condense-error",
348
- trigger,
349
- message,
350
- retryExhausted,
351
- })
352
-
353
- const runTurn = (input: TurnInput): AsyncIterable<AgentEvent> => {
354
- const acc = emptyAcc()
355
-
356
- return {
357
- [Symbol.asyncIterator]() {
358
- let inner: AsyncIterator<AgentEvent> | undefined
359
- let sessionId: SessionID | string | undefined = input.sessionId
360
- let didRetryAfterOverflow = false
361
- let overflowPending = false
362
- // userMsg is created once per turn. Overflow retry rebuilds the LLM
363
- // stream via buildIterable() — must NOT re-append the same id.
364
- let userMessageAppended = false
365
- let finalized = false
366
- const userMsg = makeUserMessage({
367
- text: input.prompt,
368
- images: (input.attachments ?? []).map(attachmentToImagePart),
369
- })
370
- // Out-of-band events (currently: context-condense-*) drained by the
371
- // outer next() BEFORE delegating to the inner LLM-event iterator.
372
- // This keeps the start/success/error trio synchronously ordered with
373
- // the LLM turn they bracket without rewriting the inner Effect stream.
374
- const pendingEvents: AgentEvent[] = []
375
-
376
- const buildIterable = () =>
377
- config.runtime.runPromise(
378
- Effect.gen(function* () {
379
- // 1) Resolve session (idempotent — same id reused across retry).
380
- const session = yield* config.store.upsertSession({
381
- id: sessionId,
382
- agentName: config.agentName,
383
- })
384
- sessionId = session.id
385
-
386
- // 2) Pre-flight: if estimated tokens exceed budget, compact first.
387
- // Skip on overflow-retry rebuilds — compaction already ran.
388
- if (compaction.auto && !userMessageAppended) {
389
- const history = yield* config.store.getMessages(session.id)
390
- const estimate = estimateUpcoming(history, input.prompt)
391
- const budgetTokens = budget()
392
- if (estimate >= budgetTokens) {
393
- pendingEvents.push(
394
- condenseStart(
395
- "preflight",
396
- estimate,
397
- Number.isFinite(budgetTokens) ? budgetTokens : undefined,
398
- ),
399
- )
400
- const preflight = yield* runCompaction(session.id, false).pipe(
401
- Effect.catchCause((cause) =>
402
- Effect.sync((): CompactResult => {
403
- pendingEvents.push(condenseError("preflight", Cause.pretty(cause)))
404
- return { compacted: false }
405
- }),
406
- ),
407
- )
408
- const successEvent = condenseSuccess("preflight", preflight)
409
- if (successEvent) pendingEvents.push(successEvent)
410
- }
411
- }
412
-
413
- // 3) Re-fetch history (post-compaction view). Append user message
414
- // only on the first build — overflow retry reuses the same row.
415
- const history = yield* config.store.getMessages(session.id)
416
- if (!userMessageAppended) {
417
- yield* config.store.appendMessage(session.id, userMsg)
418
- userMessageAppended = true
419
- }
420
-
421
- const request = buildRequest(history, input.prompt, input.attachments)
422
- const tools = config.tools ?? {}
423
- const llmStream = LLMClient.stream({ request, tools, stopWhen })
424
- const mapped: Stream.Stream<AgentEvent, never, typeof LLMClient.Service> = llmStream.pipe(
425
- Stream.tap((event) => Effect.sync(() => handleLLMEvent(acc, event))),
426
- Stream.map((event) => mapAgentEvent(acc, event)),
427
- Stream.filter((event): event is AgentEvent => event !== undefined),
428
- Stream.catchCause((cause) => {
429
- const failure = Cause.findErrorOption(cause)
430
- if (Option.isSome(failure) && isContextOverflowError(failure.value)) {
431
- // Flag the overflow so the outer next() loop can retry. We
432
- // emit zero events from this stream — the outer loop will
433
- // intercept on `result.done`.
434
- overflowPending = true
435
- return Stream.empty
436
- }
437
- return Stream.succeed(errorFromCause(cause))
438
- }),
439
- )
440
- const iterable = yield* Stream.toAsyncIterableEffect(mapped)
441
- return iterable[Symbol.asyncIterator]()
442
- }),
443
- )
444
-
445
- const ensure = async () => {
446
- if (inner) return inner
447
- inner = await buildIterable()
448
- return inner
449
- }
450
-
451
- const finalize = async () => {
452
- if (!sessionId || finalized) return
453
- finalized = true
454
- const message = buildAssistantMessage(acc)
455
- if (message.parts.length === 0) return
456
- await config.runtime.runPromise(config.store.appendMessage(sessionId, message))
457
- }
458
-
459
- // Emits the terminal "compaction retry exhausted" error exactly once,
460
- // even when callers keep polling next() after the iterator is done.
461
- let terminalErrorEmitted = false
462
-
463
- const handleOverflowAndRetry = async (): Promise<IteratorResult<AgentEvent>> => {
464
- if (didRetryAfterOverflow || !compaction.auto || !sessionId) {
465
- // Exhausted: emit ONE terminal pair (condense-error with
466
- // retryExhausted=true PLUS the legacy generic error for back-compat),
467
- // then HARD-STOP. We must cancel the inner iterator so any buffered
468
- // tool-call/tool-result events from the failed retry stream don't
469
- // bleed out *after* the error pill — without `inner.return()` the
470
- // tool-runtime loop continues to drain locally-resolved tool
471
- // promises and the outer iterator keeps yielding them.
472
- overflowPending = false
473
- if (!done) {
474
- done = true
475
- await finalize()
476
- }
477
- if (inner && typeof inner.return === "function") {
478
- await inner.return(undefined).catch(() => {})
479
- }
480
- inner = undefined
481
- if (terminalErrorEmitted) {
482
- return { done: true, value: undefined as unknown as AgentEvent }
483
- }
484
- terminalErrorEmitted = true
485
- // Queue the legacy generic error to drain on the NEXT call so old
486
- // UIs that only switch on `type === "error"` still see it.
487
- pendingEvents.push({
488
- type: "error",
489
- message: "Context overflow: compaction retry exhausted",
490
- retryable: false,
491
- })
492
- return {
493
- done: false,
494
- value: condenseError(
495
- "overflow-retry",
496
- "Context overflow: compaction retry exhausted — the model context could not be reduced further.",
497
- true,
498
- ),
499
- }
500
- }
501
- didRetryAfterOverflow = true
502
- overflowPending = false
503
- // Reset accumulator — prior partials must not leak into the retry message.
504
- acc.textBuffer = ""
505
- acc.parts = []
506
- acc.toolByCall = new Map()
507
- // Emit start BEFORE the recovery summariser call.
508
- pendingEvents.push(condenseStart("overflow-retry", undefined, undefined))
509
- // Aggressive retry: keep ONLY the most recent turn verbatim so the
510
- // post-compaction history has the best chance of fitting even when
511
- // the previous turn contained a huge tool result. The default
512
- // `preserveRecentTurns` (4) is tuned for the *pre-flight* pass — on
513
- // a provider-confirmed overflow we should be much more conservative.
514
- const retryResult: CompactResult = await config.runtime
515
- .runPromise(runCompaction(sessionId, true, 1))
516
- .catch((err: unknown): CompactResult => {
517
- pendingEvents.push(
518
- condenseError("overflow-retry", err instanceof Error ? err.message : String(err)),
519
- )
520
- return { compacted: false }
521
- })
522
- const successEvent = condenseSuccess("overflow-retry", retryResult)
523
- if (successEvent) pendingEvents.push(successEvent)
524
- inner = await buildIterable()
525
- return inner.next()
526
- }
527
-
528
- let done = false
529
- return {
530
- async next() {
531
- // Drain queued out-of-band events FIRST. This is what keeps
532
- // `context-condense-start` ordered immediately before the deltas
533
- // of the turn it brackets, and is also how the legacy "error"
534
- // event still drains after the condense-error on exhaustion.
535
- if (pendingEvents.length > 0) {
536
- const value = pendingEvents.shift() as AgentEvent
537
- return { done: false, value }
538
- }
539
- // Hard-stop once the terminal error has been emitted AND its
540
- // legacy companion drained. `inner` was nulled in
541
- // handleOverflowAndRetry's exhausted branch; calling ensure()
542
- // here would spin up a fresh stream and resurrect tool-runtime
543
- // events we explicitly cancelled — visually surfacing as
544
- // `TOOL-CALL` rows appearing AFTER the "retry exhausted" pill.
545
- if (terminalErrorEmitted) {
546
- return { done: true, value: undefined as unknown as AgentEvent }
547
- }
548
- // Build the inner iterator now (compaction may push events into
549
- // the queue during build — drain them on the NEXT call).
550
- const it = await ensure()
551
- if (pendingEvents.length > 0) {
552
- const value = pendingEvents.shift() as AgentEvent
553
- return { done: false, value }
554
- }
555
- const result = await it.next()
556
- // After advancing the inner stream, drain anything compaction
557
- // pushed (e.g. condense-success queued during ensure() on the
558
- // very first call when buildIterable ran pre-flight compaction).
559
- if (pendingEvents.length > 0) {
560
- const value = pendingEvents.shift() as AgentEvent
561
- // The fetched `result` is intentionally discarded only when it's
562
- // a sentinel (done with no value). In practice this branch is
563
- // hit on the first next() after a pre-flight condense, where
564
- // result.value is the first text-delta — we must not drop it.
565
- if (!result.done) {
566
- pendingEvents.push(result.value)
567
- }
568
- return { done: false, value }
569
- }
570
- // If the underlying stream ended because of overflow, run compaction
571
- // + retry once. The accumulator is reset so the retry starts clean.
572
- if (result.done && overflowPending) {
573
- return handleOverflowAndRetry()
574
- }
575
- if (result.done && !done) {
576
- done = true
577
- await finalize()
578
- // If tools are waiting for approval, surface a terminal finish
579
- // with a dedicated reason so hosts can pause the UI cleanly.
580
- if (hasPendingApproval(acc)) {
581
- return {
582
- done: false,
583
- value: { type: "finish", reason: FINISH_REASON_APPROVAL_REQUIRED } satisfies AgentEvent,
584
- }
585
- }
586
- }
587
- return result
588
- },
589
- async return(value) {
590
- if (!done) {
591
- done = true
592
- await finalize()
593
- }
594
- if (inner && typeof inner.return === "function") {
595
- await inner.return(value).catch(() => {})
596
- }
597
- inner = undefined
598
- return { value, done: true }
599
- },
600
- }
601
- },
602
- }
603
- }
604
-
605
- /**
606
- * Resume after the host resolved pending tool approvals.
607
- *
608
- * Steps:
609
- * 1. Load history, find the latest assistant message with approved/rejected tools.
610
- * 2. Execute each `approved` tool via the real tool handlers (permission is
611
- * bypassed by calling the underlying execute on the *raw* tools — resume
612
- * receives tools that already had permission applied, so we re-run only
613
- * the tools the host explicitly approved by calling tool.execute directly
614
- * through a temporary allow-all view).
615
- * 3. Mark `rejected` tools as error with a denial message.
616
- * 4. Persist the updated assistant message.
617
- * 5. Run a follow-up LLM turn with empty user prompt so the model sees the
618
- * tool results and continues.
619
- */
620
- const resumeTurn = (input: ResumeInput): AsyncIterable<AgentEvent> => {
621
- const acc = emptyAcc()
622
-
623
- return {
624
- [Symbol.asyncIterator]() {
625
- let inner: AsyncIterator<AgentEvent> | undefined
626
- let sessionId: SessionID | string | undefined = input.sessionId
627
- let finalized = false
628
- let done = false
629
- let preEvents: AgentEvent[] = []
630
- let preDrained = false
631
- const pendingEvents: AgentEvent[] = []
632
-
633
- const stopWhen = config.stopWhen ?? LLM.stepCountIs(100)
634
-
635
- const executeApprovedTools = async (): Promise<void> => {
636
- const history = await config.runtime.runPromise(config.store.getMessages(input.sessionId))
637
- const found = findApprovalMessage(history)
638
- if (!found) {
639
- preEvents.push({
640
- type: "error",
641
- message: "No pending tool approvals to resume",
642
- retryable: false,
643
- })
644
- return
645
- }
646
-
647
- // Use unwrapped tools so interrupt-mode wrappers don't re-block execution.
648
- const tools = config.resumeTools ?? config.tools ?? {}
649
- const original = found.message
650
- type MsgPart = AssistantMessage["parts"][number]
651
- const nextParts: MsgPart[] = original.parts.map((p) => ({ ...p }) as MsgPart)
652
- let mutated = false
653
-
654
- for (let i = 0; i < nextParts.length; i++) {
655
- const part = nextParts[i]
656
- if (!part || (part as ToolPart).type !== "tool") continue
657
- const toolPart = part as ToolPart
658
-
659
- if (toolPart.state === "rejected") {
660
- const updated: ToolPart = {
661
- ...toolPart,
662
- state: "error",
663
- output: DENIED_OUTPUT,
664
- }
665
- nextParts[i] = updated
666
- mutated = true
667
- preEvents.push({
668
- type: "tool-error",
669
- id: toolPart.callID,
670
- name: toolPart.name,
671
- message: DENIED_OUTPUT.message,
672
- })
673
- continue
674
- }
675
-
676
- if (toolPart.state !== "approved") continue
677
-
678
- // Emit a tool-call so UIs that missed the original turn still render it.
679
- preEvents.push({
680
- type: "tool-call",
681
- id: toolPart.callID,
682
- name: toolPart.name,
683
- input: toolPart.input,
684
- })
685
-
686
- const tool = tools[toolPart.name]
687
- if (!tool || !tool.execute) {
688
- const msg = tool
689
- ? `Tool has no execute handler: ${toolPart.name}`
690
- : `Unknown tool: ${toolPart.name}`
691
- nextParts[i] = { ...toolPart, state: "error", output: { message: msg } }
692
- mutated = true
693
- preEvents.push({
694
- type: "tool-error",
695
- id: toolPart.callID,
696
- name: toolPart.name,
697
- message: msg,
698
- })
699
- continue
700
- }
701
-
702
- // Permission already granted by the host — execute unwrapped tool.
703
- try {
704
- const value = await config.runtime.runPromise(tool.execute(toolPart.input))
705
- nextParts[i] = { ...toolPart, state: "complete", output: value }
706
- mutated = true
707
- preEvents.push({
708
- type: "tool-result",
709
- id: toolPart.callID,
710
- name: toolPart.name,
711
- result: value,
712
- })
713
- } catch (err) {
714
- const message =
715
- err && typeof err === "object" && "message" in err
716
- ? String((err as { message: unknown }).message)
717
- : err instanceof Error
718
- ? err.message
719
- : String(err)
720
- nextParts[i] = { ...toolPart, state: "error", output: { message } }
721
- mutated = true
722
- preEvents.push({
723
- type: "tool-error",
724
- id: toolPart.callID,
725
- name: toolPart.name,
726
- message,
727
- })
728
- }
729
- }
730
-
731
- // Still-pending tools stay as pending-approval (host only resolved a subset).
732
- const stillPending = nextParts.some(
733
- (p) => (p as ToolPart).type === "tool" && (p as ToolPart).state === "pending-approval",
734
- )
735
-
736
- if (mutated) {
737
- const updatedMsg: AssistantMessage = { ...original, parts: nextParts }
738
- await config.runtime.runPromise(persistMessageUpdate(config.store, input.sessionId, updatedMsg))
739
- }
740
-
741
- if (stillPending) {
742
- preEvents.push({ type: "finish", reason: FINISH_REASON_APPROVAL_REQUIRED })
743
- }
744
- }
745
-
746
- const buildFollowUp = () =>
747
- config.runtime.runPromise(
748
- Effect.gen(function* () {
749
- const session = yield* config.store.upsertSession({
750
- id: sessionId,
751
- agentName: config.agentName,
752
- })
753
- sessionId = session.id
754
- const history = yield* config.store.getMessages(session.id)
755
- // Empty prompt: model only sees replayed history with tool results.
756
- const request = buildRequest(history, "")
757
- const tools = config.tools ?? {}
758
- const llmStream = LLMClient.stream({ request, tools, stopWhen })
759
- const mapped: Stream.Stream<AgentEvent, never, typeof LLMClient.Service> = llmStream.pipe(
760
- Stream.tap((event) => Effect.sync(() => handleLLMEvent(acc, event))),
761
- Stream.map((event) => mapAgentEvent(acc, event)),
762
- Stream.filter((event): event is AgentEvent => event !== undefined),
763
- Stream.catchCause((cause) => {
764
- const failure = Cause.findErrorOption(cause)
765
- if (Option.isSome(failure) && isContextOverflowError(failure.value)) {
766
- return Stream.succeed({
767
- type: "error",
768
- message: "Context overflow during approval resume",
769
- retryable: false,
770
- } satisfies AgentEvent)
771
- }
772
- return Stream.succeed(errorFromCause(cause))
773
- }),
774
- )
775
- const iterable = yield* Stream.toAsyncIterableEffect(mapped)
776
- return iterable[Symbol.asyncIterator]()
777
- }),
778
- )
779
-
780
- const finalize = async () => {
781
- if (!sessionId || finalized) return
782
- finalized = true
783
- const message = buildAssistantMessage(acc)
784
- if (message.parts.length === 0) return
785
- await config.runtime.runPromise(config.store.appendMessage(sessionId, message))
786
- }
787
-
788
- return {
789
- async next() {
790
- if (!preDrained) {
791
- preDrained = true
792
- await executeApprovedTools()
793
- // If we finished with still-pending approvals, don't start LLM.
794
- const endedEarly = preEvents.some(
795
- (e) => e.type === "finish" && e.reason === FINISH_REASON_APPROVAL_REQUIRED,
796
- )
797
- if (endedEarly) {
798
- done = true
799
- } else if (preEvents.some((e) => e.type === "error" && !e.retryable)) {
800
- // No approvals found — stop without LLM.
801
- const onlyError =
802
- preEvents.length === 1 && preEvents[0]?.type === "error"
803
- if (onlyError) {
804
- done = true
805
- }
806
- } else {
807
- // Start follow-up LLM turn after draining pre-events.
808
- try {
809
- inner = await buildFollowUp()
810
- } catch (err) {
811
- preEvents.push({
812
- type: "error",
813
- message: err instanceof Error ? err.message : String(err),
814
- retryable: false,
815
- })
816
- done = true
817
- }
818
- }
819
- }
820
-
821
- if (preEvents.length > 0) {
822
- const value = preEvents.shift() as AgentEvent
823
- return { done: false, value }
824
- }
825
-
826
- if (pendingEvents.length > 0) {
827
- const value = pendingEvents.shift() as AgentEvent
828
- return { done: false, value }
829
- }
830
-
831
- if (done || !inner) {
832
- return { done: true, value: undefined as unknown as AgentEvent }
833
- }
834
-
835
- const result = await inner.next()
836
- if (result.done && !done) {
837
- done = true
838
- await finalize()
839
- if (hasPendingApproval(acc)) {
840
- return {
841
- done: false,
842
- value: { type: "finish", reason: FINISH_REASON_APPROVAL_REQUIRED } satisfies AgentEvent,
843
- }
844
- }
845
- }
846
- return result
847
- },
848
- async return(value) {
849
- if (!done) {
850
- done = true
851
- await finalize()
852
- }
853
- if (inner && typeof inner.return === "function") {
854
- await inner.return(value).catch(() => {})
855
- }
856
- inner = undefined
857
- return { value, done: true }
858
- },
859
- }
860
- },
861
- }
862
- }
863
-
864
- return { runTurn, resumeTurn }
865
- }