@tinyweb_dev/agent-framework-agent 0.1.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.
@@ -0,0 +1,500 @@
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
+ fromLLMEvent,
17
+ type AgentEvent,
18
+ type CondenseTrigger,
19
+ type ContextCondenseErrorEvent,
20
+ type ContextCondenseEvent,
21
+ type ContextCondenseStartEvent,
22
+ type ErrorEvent,
23
+ } from "../events"
24
+ import type { AgentRuntime } from "../runtime"
25
+ import type { SessionStore } from "./adapter"
26
+ import { compact, type CompactResult } from "./compaction"
27
+ import { estimateTokens, usable } from "./overflow"
28
+ import { historyToLLMMessages } from "./replay"
29
+ import {
30
+ makeAssistantMessage,
31
+ makeUserMessage,
32
+ newPartID,
33
+ type AssistantMessage,
34
+ type ImagePart,
35
+ type Message,
36
+ type SessionID,
37
+ type TextPart,
38
+ type ToolPart,
39
+ } from "./schema"
40
+
41
+ const attachmentToImagePart = (a: AttachmentInput): ImagePart => ({
42
+ type: "image",
43
+ url: a.url,
44
+ data: a.data,
45
+ mediaType: a.mediaType,
46
+ })
47
+
48
+ const attachmentToContentPart = (a: AttachmentInput): ContentPart => ({
49
+ type: "media",
50
+ mediaType: a.mediaType,
51
+ data: a.url ?? a.data ?? "",
52
+ filename: a.filename,
53
+ })
54
+
55
+ export type ProcessorCompactionConfig = {
56
+ readonly auto: boolean
57
+ readonly reservedTokens?: number
58
+ readonly preserveRecentTurns?: number
59
+ }
60
+
61
+ export type ProcessorConfig = {
62
+ readonly agentName: string
63
+ readonly model: ModelRef
64
+ readonly store: SessionStore
65
+ readonly runtime: AgentRuntime
66
+ readonly systemPrompt?: string
67
+ readonly tools?: ExecutableTools
68
+ readonly stopWhen?: StopCondition
69
+ readonly generation?: GenerationOptions.Input
70
+ readonly compaction?: ProcessorCompactionConfig
71
+ }
72
+
73
+ export type TurnInput = {
74
+ readonly prompt: string
75
+ readonly sessionId?: SessionID | string
76
+ readonly attachments?: ReadonlyArray<AttachmentInput>
77
+ }
78
+
79
+ export type Processor = {
80
+ readonly runTurn: (input: TurnInput) => AsyncIterable<AgentEvent>
81
+ }
82
+
83
+ const DEFAULT_COMPACTION: ProcessorCompactionConfig = { auto: true }
84
+
85
+ const errorFromCause = (cause: Cause.Cause<unknown>): ErrorEvent => {
86
+ const failure = Cause.findErrorOption(cause)
87
+ if (Option.isSome(failure)) {
88
+ const e = failure.value as { message?: string; retryable?: boolean }
89
+ return { type: "error", message: e.message ?? String(failure.value), retryable: e.retryable }
90
+ }
91
+ return { type: "error", message: Cause.pretty(cause) }
92
+ }
93
+
94
+ /** True when a failure carries a `ContextOverflow` reason from the LLM layer. */
95
+ const isContextOverflowError = (failure: unknown): boolean => {
96
+ if (!(failure instanceof LLMError)) return false
97
+ return failure.reason._tag === "ContextOverflow"
98
+ }
99
+
100
+ // Mutable accumulator that turns the LLMEvent stream into an AssistantMessage at finish time.
101
+ type Accumulator = {
102
+ textBuffer: string
103
+ parts: Array<TextPart | ToolPart>
104
+ toolByCall: Map<string, ToolPart>
105
+ }
106
+
107
+ const emptyAcc = (): Accumulator => ({ textBuffer: "", parts: [], toolByCall: new Map() })
108
+
109
+ const flushText = (acc: Accumulator) => {
110
+ if (acc.textBuffer.length === 0) return
111
+ acc.parts.push({ type: "text", text: acc.textBuffer })
112
+ acc.textBuffer = ""
113
+ }
114
+
115
+ const handleLLMEvent = (acc: Accumulator, event: LLMEvent) => {
116
+ if (event.type === "text-delta") {
117
+ acc.textBuffer += event.text
118
+ return
119
+ }
120
+ if (event.type === "text-end") {
121
+ flushText(acc)
122
+ return
123
+ }
124
+ if (event.type === "tool-call") {
125
+ flushText(acc)
126
+ const part: ToolPart = {
127
+ id: newPartID(),
128
+ type: "tool",
129
+ callID: event.id,
130
+ name: event.name,
131
+ state: "running",
132
+ input: event.input,
133
+ }
134
+ acc.parts.push(part)
135
+ acc.toolByCall.set(event.id, part)
136
+ return
137
+ }
138
+ if (event.type === "tool-result") {
139
+ const part = acc.toolByCall.get(event.id)
140
+ if (!part) return
141
+ const idx = acc.parts.indexOf(part)
142
+ if (idx === -1) return
143
+ acc.parts[idx] = { ...part, state: "complete", output: event.result.value }
144
+ return
145
+ }
146
+ if (event.type === "tool-error") {
147
+ const part = acc.toolByCall.get(event.id)
148
+ if (!part) return
149
+ const idx = acc.parts.indexOf(part)
150
+ if (idx === -1) return
151
+ acc.parts[idx] = { ...part, state: "error", output: { message: event.message } }
152
+ return
153
+ }
154
+ }
155
+
156
+ const buildAssistantMessage = (acc: Accumulator): AssistantMessage => {
157
+ flushText(acc)
158
+ return makeAssistantMessage(acc.parts)
159
+ }
160
+
161
+ export const makeProcessor = (config: ProcessorConfig): Processor => {
162
+ // Default cap mirrors `defineAgent` — see agent.ts for rationale.
163
+ const stopWhen = config.stopWhen ?? LLM.stepCountIs(100)
164
+ const compaction = config.compaction ?? DEFAULT_COMPACTION
165
+
166
+ const buildRequest = (
167
+ history: ReadonlyArray<Message>,
168
+ prompt: string,
169
+ attachments?: ReadonlyArray<AttachmentInput>,
170
+ ): LLMRequest => {
171
+ const userContent: ContentPart[] = []
172
+ if (prompt.length > 0) userContent.push({ type: "text", text: prompt })
173
+ for (const a of attachments ?? []) userContent.push(attachmentToContentPart(a))
174
+ const userMsg = userContent.length === 0 ? LLM.user(prompt) : LLM.user(userContent)
175
+ return LLM.request({
176
+ model: config.model,
177
+ system: config.systemPrompt,
178
+ messages: [...historyToLLMMessages([...history]), userMsg],
179
+ generation: config.generation,
180
+ })
181
+ }
182
+
183
+ /**
184
+ * Estimate the prompt token count for the upcoming turn. Reuses `estimateTokens`
185
+ * on the raw app history + the synthetic user prompt; the system prompt is
186
+ * folded in as a plain text bump so callers don't need a separate slot.
187
+ */
188
+ const estimateUpcoming = (history: ReadonlyArray<Message>, prompt: string): number => {
189
+ const promptTokens = Math.ceil(prompt.length / 4)
190
+ const systemTokens = Math.ceil((config.systemPrompt?.length ?? 0) / 4)
191
+ return estimateTokens(history) + promptTokens + systemTokens
192
+ }
193
+
194
+ const budget = (): number =>
195
+ usable({
196
+ limits: config.model.limits,
197
+ reservedTokens: compaction.reservedTokens,
198
+ })
199
+
200
+ /** Run a compaction pass against the store. */
201
+ const runCompaction = (
202
+ sessionId: SessionID | string,
203
+ overflow: boolean,
204
+ keepRecentOverride?: number,
205
+ ) =>
206
+ compact({
207
+ sessionId,
208
+ store: config.store,
209
+ model: config.model,
210
+ keepRecent: keepRecentOverride ?? compaction.preserveRecentTurns ?? 4,
211
+ overflow,
212
+ })
213
+
214
+ // ----- condense event builders ------------------------------------------
215
+ // We construct event objects up-front (no `new` Effect needed) and push them
216
+ // onto a queue drained by the outer AsyncIterator. This keeps the wiring
217
+ // surface tiny without touching the inner Effect stream.
218
+
219
+ const condenseStart = (
220
+ trigger: CondenseTrigger,
221
+ estimatedTokens: number | undefined,
222
+ budgetTokens: number | undefined,
223
+ ): ContextCondenseStartEvent => ({
224
+ type: "context-condense-start",
225
+ trigger,
226
+ estimatedTokens,
227
+ budgetTokens,
228
+ })
229
+
230
+ const condenseSuccess = (
231
+ trigger: CondenseTrigger,
232
+ result: {
233
+ readonly markerId?: unknown
234
+ readonly summary?: string
235
+ readonly prevTokens?: number
236
+ readonly newTokens?: number
237
+ readonly cost?: number
238
+ readonly modelId?: string
239
+ },
240
+ ): ContextCondenseEvent | undefined => {
241
+ if (!result.markerId || typeof result.summary !== "string") return undefined
242
+ return {
243
+ type: "context-condense",
244
+ trigger,
245
+ summary: result.summary,
246
+ markerId: String(result.markerId),
247
+ prevTokens: result.prevTokens,
248
+ newTokens: result.newTokens,
249
+ cost: result.cost,
250
+ modelId: result.modelId,
251
+ }
252
+ }
253
+
254
+ const condenseError = (
255
+ trigger: CondenseTrigger,
256
+ message: string,
257
+ retryExhausted = false,
258
+ ): ContextCondenseErrorEvent => ({
259
+ type: "context-condense-error",
260
+ trigger,
261
+ message,
262
+ retryExhausted,
263
+ })
264
+
265
+ const runTurn = (input: TurnInput): AsyncIterable<AgentEvent> => {
266
+ const acc = emptyAcc()
267
+
268
+ return {
269
+ [Symbol.asyncIterator]() {
270
+ let inner: AsyncIterator<AgentEvent> | undefined
271
+ let sessionId: SessionID | string | undefined = input.sessionId
272
+ let didRetryAfterOverflow = false
273
+ let overflowPending = false
274
+ const userMsg = makeUserMessage({
275
+ text: input.prompt,
276
+ images: (input.attachments ?? []).map(attachmentToImagePart),
277
+ })
278
+ // Out-of-band events (currently: context-condense-*) drained by the
279
+ // outer next() BEFORE delegating to the inner LLM-event iterator.
280
+ // This keeps the start/success/error trio synchronously ordered with
281
+ // the LLM turn they bracket without rewriting the inner Effect stream.
282
+ const pendingEvents: AgentEvent[] = []
283
+
284
+ const buildIterable = () =>
285
+ config.runtime.runPromise(
286
+ Effect.gen(function* () {
287
+ // 1) Resolve session (idempotent — same id reused across retry).
288
+ const session = yield* config.store.upsertSession({
289
+ id: sessionId,
290
+ agentName: config.agentName,
291
+ })
292
+ sessionId = session.id
293
+
294
+ // 2) Pre-flight: if estimated tokens exceed budget, compact first.
295
+ if (compaction.auto) {
296
+ const history = yield* config.store.getMessages(session.id)
297
+ const estimate = estimateUpcoming(history, input.prompt)
298
+ const budgetTokens = budget()
299
+ if (estimate >= budgetTokens) {
300
+ pendingEvents.push(
301
+ condenseStart(
302
+ "preflight",
303
+ estimate,
304
+ Number.isFinite(budgetTokens) ? budgetTokens : undefined,
305
+ ),
306
+ )
307
+ const preflight = yield* runCompaction(session.id, false).pipe(
308
+ Effect.catchCause((cause) =>
309
+ Effect.sync((): CompactResult => {
310
+ pendingEvents.push(condenseError("preflight", Cause.pretty(cause)))
311
+ return { compacted: false }
312
+ }),
313
+ ),
314
+ )
315
+ const successEvent = condenseSuccess("preflight", preflight)
316
+ if (successEvent) pendingEvents.push(successEvent)
317
+ }
318
+ }
319
+
320
+ // 3) Re-fetch history (post-compaction view) and append new user message.
321
+ const history = yield* config.store.getMessages(session.id)
322
+ yield* config.store.appendMessage(session.id, userMsg)
323
+
324
+ const request = buildRequest(history, input.prompt, input.attachments)
325
+ const tools = config.tools ?? {}
326
+ const llmStream = LLMClient.stream({ request, tools, stopWhen })
327
+ const mapped: Stream.Stream<AgentEvent, never, typeof LLMClient.Service> = llmStream.pipe(
328
+ Stream.tap((event) => Effect.sync(() => handleLLMEvent(acc, event))),
329
+ Stream.map(fromLLMEvent),
330
+ Stream.filter((event): event is AgentEvent => event !== undefined),
331
+ Stream.catchCause((cause) => {
332
+ const failure = Cause.findErrorOption(cause)
333
+ if (Option.isSome(failure) && isContextOverflowError(failure.value)) {
334
+ // Flag the overflow so the outer next() loop can retry. We
335
+ // emit zero events from this stream — the outer loop will
336
+ // intercept on `result.done`.
337
+ overflowPending = true
338
+ return Stream.empty
339
+ }
340
+ return Stream.succeed(errorFromCause(cause))
341
+ }),
342
+ )
343
+ const iterable = yield* Stream.toAsyncIterableEffect(mapped)
344
+ return iterable[Symbol.asyncIterator]()
345
+ }),
346
+ )
347
+
348
+ const ensure = async () => {
349
+ if (inner) return inner
350
+ inner = await buildIterable()
351
+ return inner
352
+ }
353
+
354
+ const finalize = async () => {
355
+ if (!sessionId) return
356
+ const message = buildAssistantMessage(acc)
357
+ if (message.parts.length === 0) return
358
+ await config.runtime.runPromise(config.store.appendMessage(sessionId, message))
359
+ }
360
+
361
+ // Emits the terminal "compaction retry exhausted" error exactly once,
362
+ // even when callers keep polling next() after the iterator is done.
363
+ let terminalErrorEmitted = false
364
+
365
+ const handleOverflowAndRetry = async (): Promise<IteratorResult<AgentEvent>> => {
366
+ if (didRetryAfterOverflow || !compaction.auto || !sessionId) {
367
+ // Exhausted: emit ONE terminal pair (condense-error with
368
+ // retryExhausted=true PLUS the legacy generic error for back-compat),
369
+ // then HARD-STOP. We must cancel the inner iterator so any buffered
370
+ // tool-call/tool-result events from the failed retry stream don't
371
+ // bleed out *after* the error pill — without `inner.return()` the
372
+ // tool-runtime loop continues to drain locally-resolved tool
373
+ // promises and the outer iterator keeps yielding them.
374
+ overflowPending = false
375
+ if (!done) {
376
+ done = true
377
+ await finalize()
378
+ }
379
+ if (inner && typeof inner.return === "function") {
380
+ await inner.return(undefined).catch(() => {})
381
+ }
382
+ inner = undefined
383
+ if (terminalErrorEmitted) {
384
+ return { done: true, value: undefined as unknown as AgentEvent }
385
+ }
386
+ terminalErrorEmitted = true
387
+ // Queue the legacy generic error to drain on the NEXT call so old
388
+ // UIs that only switch on `type === "error"` still see it.
389
+ pendingEvents.push({
390
+ type: "error",
391
+ message: "Context overflow: compaction retry exhausted",
392
+ retryable: false,
393
+ })
394
+ return {
395
+ done: false,
396
+ value: condenseError(
397
+ "overflow-retry",
398
+ "Context overflow: compaction retry exhausted — the model context could not be reduced further.",
399
+ true,
400
+ ),
401
+ }
402
+ }
403
+ didRetryAfterOverflow = true
404
+ overflowPending = false
405
+ // Reset accumulator — prior partials must not leak into the retry message.
406
+ acc.textBuffer = ""
407
+ acc.parts = []
408
+ acc.toolByCall = new Map()
409
+ // Emit start BEFORE the recovery summariser call.
410
+ pendingEvents.push(condenseStart("overflow-retry", undefined, undefined))
411
+ // Aggressive retry: keep ONLY the most recent turn verbatim so the
412
+ // post-compaction history has the best chance of fitting even when
413
+ // the previous turn contained a huge tool result. The default
414
+ // `preserveRecentTurns` (4) is tuned for the *pre-flight* pass — on
415
+ // a provider-confirmed overflow we should be much more conservative.
416
+ const retryResult: CompactResult = await config.runtime
417
+ .runPromise(runCompaction(sessionId, true, 1))
418
+ .catch((err: unknown): CompactResult => {
419
+ pendingEvents.push(
420
+ condenseError("overflow-retry", err instanceof Error ? err.message : String(err)),
421
+ )
422
+ return { compacted: false }
423
+ })
424
+ const successEvent = condenseSuccess("overflow-retry", retryResult)
425
+ if (successEvent) pendingEvents.push(successEvent)
426
+ inner = await buildIterable()
427
+ return inner.next()
428
+ }
429
+
430
+ let done = false
431
+ return {
432
+ async next() {
433
+ // Drain queued out-of-band events FIRST. This is what keeps
434
+ // `context-condense-start` ordered immediately before the deltas
435
+ // of the turn it brackets, and is also how the legacy "error"
436
+ // event still drains after the condense-error on exhaustion.
437
+ if (pendingEvents.length > 0) {
438
+ const value = pendingEvents.shift() as AgentEvent
439
+ return { done: false, value }
440
+ }
441
+ // Hard-stop once the terminal error has been emitted AND its
442
+ // legacy companion drained. `inner` was nulled in
443
+ // handleOverflowAndRetry's exhausted branch; calling ensure()
444
+ // here would spin up a fresh stream and resurrect tool-runtime
445
+ // events we explicitly cancelled — visually surfacing as
446
+ // `TOOL-CALL` rows appearing AFTER the "retry exhausted" pill.
447
+ if (terminalErrorEmitted) {
448
+ return { done: true, value: undefined as unknown as AgentEvent }
449
+ }
450
+ // Build the inner iterator now (compaction may push events into
451
+ // the queue during build — drain them on the NEXT call).
452
+ const it = await ensure()
453
+ if (pendingEvents.length > 0) {
454
+ const value = pendingEvents.shift() as AgentEvent
455
+ return { done: false, value }
456
+ }
457
+ const result = await it.next()
458
+ // After advancing the inner stream, drain anything compaction
459
+ // pushed (e.g. condense-success queued during ensure() on the
460
+ // very first call when buildIterable ran pre-flight compaction).
461
+ if (pendingEvents.length > 0) {
462
+ const value = pendingEvents.shift() as AgentEvent
463
+ // The fetched `result` is intentionally discarded only when it's
464
+ // a sentinel (done with no value). In practice this branch is
465
+ // hit on the first next() after a pre-flight condense, where
466
+ // result.value is the first text-delta — we must not drop it.
467
+ if (!result.done) {
468
+ pendingEvents.push(result.value)
469
+ }
470
+ return { done: false, value }
471
+ }
472
+ // If the underlying stream ended because of overflow, run compaction
473
+ // + retry once. The accumulator is reset so the retry starts clean.
474
+ if (result.done && overflowPending) {
475
+ return handleOverflowAndRetry()
476
+ }
477
+ if (result.done && !done) {
478
+ done = true
479
+ await finalize()
480
+ }
481
+ return result
482
+ },
483
+ async return(value) {
484
+ if (!done) {
485
+ done = true
486
+ await finalize()
487
+ }
488
+ if (inner && typeof inner.return === "function") {
489
+ await inner.return(value).catch(() => {})
490
+ }
491
+ inner = undefined
492
+ return { value, done: true }
493
+ },
494
+ }
495
+ },
496
+ }
497
+ }
498
+
499
+ return { runTurn }
500
+ }
@@ -0,0 +1,140 @@
1
+ import { LLM, type ContentPart, type Message as LLMMessage } from "@tinyweb-agent-framework/llm"
2
+ import { findCompactionPart, type ImagePart, type Message, type TextPart, type ToolPart } from "./schema"
3
+
4
+ const COMPACTION_PREFIX = "[Compacted conversation summary]"
5
+
6
+ /**
7
+ * Hard cap on the serialised size (in characters, ~4 chars/token) of a
8
+ * single tool result when replayed into the LLM. Adapted from
9
+ * opencode@v1.14.48 — `truncateToolOutput` — to prevent a single huge
10
+ * `read_page`/`screenshot`/`get_content` output from blowing the context
11
+ * window all on its own and making compaction retry impossible to satisfy.
12
+ *
13
+ * 60 000 chars ≈ 15k tokens — generous enough that small/medium tool calls
14
+ * pass through unchanged, but capped well below any model's context window
15
+ * even when several tool calls are stacked back-to-back.
16
+ */
17
+ const MAX_TOOL_OUTPUT_CHARS = 60_000
18
+
19
+ const TRUNCATION_NOTE = (elided: number) =>
20
+ `\n\n[... ${elided} chars elided by tinyweb-agent — output exceeded ${MAX_TOOL_OUTPUT_CHARS} chars ...]\n\n`
21
+
22
+ const truncateToolOutput = (output: unknown): unknown => {
23
+ if (output === undefined || output === null) return output
24
+ if (typeof output === "string") {
25
+ if (output.length <= MAX_TOOL_OUTPUT_CHARS) return output
26
+ const half = Math.floor(MAX_TOOL_OUTPUT_CHARS / 2) - 64
27
+ return `${output.slice(0, half)}${TRUNCATION_NOTE(output.length - MAX_TOOL_OUTPUT_CHARS)}${output.slice(-half)}`
28
+ }
29
+ // Non-string: stringify and only mutate when it overflows.
30
+ const serialised = (() => {
31
+ try {
32
+ return JSON.stringify(output)
33
+ } catch {
34
+ return String(output)
35
+ }
36
+ })()
37
+ if (serialised.length <= MAX_TOOL_OUTPUT_CHARS) return output
38
+ const half = Math.floor(MAX_TOOL_OUTPUT_CHARS / 2) - 64
39
+ return `${serialised.slice(0, half)}${TRUNCATION_NOTE(serialised.length - MAX_TOOL_OUTPUT_CHARS)}${serialised.slice(-half)}`
40
+ }
41
+
42
+ const textOf = (msg: Message): string =>
43
+ msg.parts
44
+ .map((p) => ((p as TextPart).type === "text" ? (p as TextPart).text : ""))
45
+ .filter((s) => s.length > 0)
46
+ .join("\n")
47
+
48
+ /**
49
+ * Replay app-level history into wire-level LLM messages.
50
+ *
51
+ * Faithful to the agentic loop: every assistant turn that called tools is
52
+ * rebuilt as an `assistant` message carrying both its text and `tool-call`
53
+ * parts, followed by one `tool` message per completed `tool-result`. This is
54
+ * what lets the model "remember" what it did across user turns — without it
55
+ * the second user prompt would see only naked text and answer "no context".
56
+ *
57
+ * Marker-aware: if any message carries a `CompactionPart`, replay starts from
58
+ * the most recent marker and emits the marker's summary as a synthetic user
59
+ * message, followed by the tail (messages after the marker).
60
+ */
61
+ const imagePartToMedia = (part: ImagePart): ContentPart | undefined => {
62
+ const data = part.url ?? part.data
63
+ if (!data) return undefined
64
+ return { type: "media", mediaType: part.mediaType ?? "image/png", data }
65
+ }
66
+
67
+ const expandMessage = (msg: Message): LLMMessage[] => {
68
+ if (msg.role === "user") {
69
+ const content: ContentPart[] = []
70
+ const text = textOf(msg)
71
+ if (text.length > 0) content.push({ type: "text", text })
72
+ for (const p of msg.parts) {
73
+ if ((p as { type: string }).type !== "image") continue
74
+ const media = imagePartToMedia(p as ImagePart)
75
+ if (media) content.push(media)
76
+ }
77
+ return content.length > 0 ? [LLM.user(content)] : []
78
+ }
79
+
80
+ // Assistant: split parts into text + tool-call, then emit follow-up tool messages.
81
+ const text = textOf(msg)
82
+ const toolParts = msg.parts.filter((p): p is ToolPart => (p as { type: string }).type === "tool")
83
+ const completed = toolParts.filter((t) => t.state === "complete" || t.state === "error")
84
+
85
+ // Skip entirely if nothing replayable (avoids empty assistant frames).
86
+ if (text.length === 0 && completed.length === 0) return []
87
+
88
+ // Build assistant content: text first, then tool-call parts (only for completed
89
+ // calls — partial/cancelled tool calls have no result to pair with).
90
+ const assistantContent: Array<ReturnType<typeof LLM.text> | ReturnType<typeof LLM.toolCall>> = []
91
+ if (text.length > 0) assistantContent.push(LLM.text(text))
92
+ for (const t of completed) {
93
+ assistantContent.push(LLM.toolCall({ id: t.callID, name: t.name, input: t.input }))
94
+ }
95
+
96
+ const out: LLMMessage[] = []
97
+ if (assistantContent.length > 0) out.push(LLM.assistant(assistantContent))
98
+
99
+ // Emit one tool-result message per completed tool. Errors round-trip as
100
+ // resultType: "error" so the model sees the failure message verbatim.
101
+ //
102
+ // Tool outputs are truncated to MAX_TOOL_OUTPUT_CHARS before replay so a
103
+ // single oversized result (e.g. `browser__read_page`, `browser__screenshot`)
104
+ // cannot single-handedly overflow the context window — which would make
105
+ // compaction retry impossible to satisfy and surface as "compaction retry
106
+ // exhausted" to the caller.
107
+ for (const t of completed) {
108
+ const isError = t.state === "error"
109
+ out.push(
110
+ LLM.toolMessage({
111
+ id: t.callID,
112
+ name: t.name,
113
+ result: truncateToolOutput(t.output),
114
+ resultType: isError ? "error" : "json",
115
+ }),
116
+ )
117
+ }
118
+
119
+ return out
120
+ }
121
+
122
+ export const historyToLLMMessages = (messages: ReadonlyArray<Message>): LLMMessage[] => {
123
+ // Find the *last* compaction marker — only the most recent matters.
124
+ let markerIdx = -1
125
+ for (let i = messages.length - 1; i >= 0; i--) {
126
+ if (findCompactionPart(messages[i]!)) {
127
+ markerIdx = i
128
+ break
129
+ }
130
+ }
131
+
132
+ if (markerIdx === -1) {
133
+ return messages.flatMap(expandMessage)
134
+ }
135
+
136
+ const marker = findCompactionPart(messages[markerIdx]!)!
137
+ const seed = LLM.user(`${COMPACTION_PREFIX}\n${marker.summary}`)
138
+ const tail = messages.slice(markerIdx + 1)
139
+ return [seed, ...tail.flatMap(expandMessage)]
140
+ }