@tinyweb_dev/agent-framework-agent 0.1.0 → 0.2.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.
@@ -13,6 +13,7 @@ import {
13
13
  import { Cause, Effect, Option, Stream } from "effect"
14
14
  import type { AttachmentInput } from "../attachments"
15
15
  import {
16
+ FINISH_REASON_APPROVAL_REQUIRED,
16
17
  fromLLMEvent,
17
18
  type AgentEvent,
18
19
  type CondenseTrigger,
@@ -21,6 +22,7 @@ import {
21
22
  type ContextCondenseStartEvent,
22
23
  type ErrorEvent,
23
24
  } from "../events"
25
+ import { isToolInterruptMetadata } from "../permission"
24
26
  import type { AgentRuntime } from "../runtime"
25
27
  import type { SessionStore } from "./adapter"
26
28
  import { compact, type CompactResult } from "./compaction"
@@ -64,7 +66,15 @@ export type ProcessorConfig = {
64
66
  readonly store: SessionStore
65
67
  readonly runtime: AgentRuntime
66
68
  readonly systemPrompt?: string
69
+ /** Permission-wrapped tools used during the normal agentic loop. */
67
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
68
78
  readonly stopWhen?: StopCondition
69
79
  readonly generation?: GenerationOptions.Input
70
80
  readonly compaction?: ProcessorCompactionConfig
@@ -76,8 +86,18 @@ export type TurnInput = {
76
86
  readonly attachments?: ReadonlyArray<AttachmentInput>
77
87
  }
78
88
 
89
+ export type ResumeInput = {
90
+ readonly sessionId: SessionID | string
91
+ }
92
+
79
93
  export type Processor = {
80
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>
81
101
  }
82
102
 
83
103
  const DEFAULT_COMPACTION: ProcessorCompactionConfig = { auto: true }
@@ -141,6 +161,7 @@ const handleLLMEvent = (acc: Accumulator, event: LLMEvent) => {
141
161
  const idx = acc.parts.indexOf(part)
142
162
  if (idx === -1) return
143
163
  acc.parts[idx] = { ...part, state: "complete", output: event.result.value }
164
+ acc.toolByCall.set(event.id, acc.parts[idx] as ToolPart)
144
165
  return
145
166
  }
146
167
  if (event.type === "tool-error") {
@@ -148,11 +169,78 @@ const handleLLMEvent = (acc: Accumulator, event: LLMEvent) => {
148
169
  if (!part) return
149
170
  const idx = acc.parts.indexOf(part)
150
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
+ }
151
182
  acc.parts[idx] = { ...part, state: "error", output: { message: event.message } }
183
+ acc.toolByCall.set(event.id, acc.parts[idx] as ToolPart)
152
184
  return
153
185
  }
154
186
  }
155
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
+
156
244
  const buildAssistantMessage = (acc: Accumulator): AssistantMessage => {
157
245
  flushText(acc)
158
246
  return makeAssistantMessage(acc.parts)
@@ -271,6 +359,10 @@ export const makeProcessor = (config: ProcessorConfig): Processor => {
271
359
  let sessionId: SessionID | string | undefined = input.sessionId
272
360
  let didRetryAfterOverflow = false
273
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
274
366
  const userMsg = makeUserMessage({
275
367
  text: input.prompt,
276
368
  images: (input.attachments ?? []).map(attachmentToImagePart),
@@ -292,7 +384,8 @@ export const makeProcessor = (config: ProcessorConfig): Processor => {
292
384
  sessionId = session.id
293
385
 
294
386
  // 2) Pre-flight: if estimated tokens exceed budget, compact first.
295
- if (compaction.auto) {
387
+ // Skip on overflow-retry rebuilds — compaction already ran.
388
+ if (compaction.auto && !userMessageAppended) {
296
389
  const history = yield* config.store.getMessages(session.id)
297
390
  const estimate = estimateUpcoming(history, input.prompt)
298
391
  const budgetTokens = budget()
@@ -317,29 +410,33 @@ export const makeProcessor = (config: ProcessorConfig): Processor => {
317
410
  }
318
411
  }
319
412
 
320
- // 3) Re-fetch history (post-compaction view) and append new user message.
413
+ // 3) Re-fetch history (post-compaction view). Append user message
414
+ // only on the first build — overflow retry reuses the same row.
321
415
  const history = yield* config.store.getMessages(session.id)
322
- yield* config.store.appendMessage(session.id, userMsg)
416
+ if (!userMessageAppended) {
417
+ yield* config.store.appendMessage(session.id, userMsg)
418
+ userMessageAppended = true
419
+ }
323
420
 
324
421
  const request = buildRequest(history, input.prompt, input.attachments)
325
422
  const tools = config.tools ?? {}
326
423
  const llmStream = LLMClient.stream({ request, tools, stopWhen })
327
424
  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
- )
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
+ )
343
440
  const iterable = yield* Stream.toAsyncIterableEffect(mapped)
344
441
  return iterable[Symbol.asyncIterator]()
345
442
  }),
@@ -352,7 +449,8 @@ export const makeProcessor = (config: ProcessorConfig): Processor => {
352
449
  }
353
450
 
354
451
  const finalize = async () => {
355
- if (!sessionId) return
452
+ if (!sessionId || finalized) return
453
+ finalized = true
356
454
  const message = buildAssistantMessage(acc)
357
455
  if (message.parts.length === 0) return
358
456
  await config.runtime.runPromise(config.store.appendMessage(sessionId, message))
@@ -475,26 +573,293 @@ export const makeProcessor = (config: ProcessorConfig): Processor => {
475
573
  return handleOverflowAndRetry()
476
574
  }
477
575
  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(() => {})
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 }
490
865
  }
491
- inner = undefined
492
- return { value, done: true }
493
- },
494
- }
495
- },
496
- }
497
- }
498
-
499
- return { runTurn }
500
- }
@@ -78,47 +78,58 @@ const expandMessage = (msg: Message): LLMMessage[] => {
78
78
  }
79
79
 
80
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
- }),
81
+ const text = textOf(msg)
82
+ const toolParts = msg.parts.filter((p): p is ToolPart => (p as { type: string }).type === "tool")
83
+ // Replay only terminal tool states that have a result the model can pair with.
84
+ // pending-approval / approved (not yet executed) / running / pending are skipped —
85
+ // resume() executes them first, then rewrites state to complete|error.
86
+ const completed = toolParts.filter(
87
+ (t) => t.state === "complete" || t.state === "error" || t.state === "rejected",
116
88
  )
89
+
90
+ // Skip entirely if nothing replayable (avoids empty assistant frames).
91
+ if (text.length === 0 && completed.length === 0) return []
92
+
93
+ // Build assistant content: text first, then tool-call parts (only for completed
94
+ // calls — partial/cancelled tool calls have no result to pair with).
95
+ const assistantContent: Array<ReturnType<typeof LLM.text> | ReturnType<typeof LLM.toolCall>> = []
96
+ if (text.length > 0) assistantContent.push(LLM.text(text))
97
+ for (const t of completed) {
98
+ assistantContent.push(LLM.toolCall({ id: t.callID, name: t.name, input: t.input }))
99
+ }
100
+
101
+ const out: LLMMessage[] = []
102
+ if (assistantContent.length > 0) out.push(LLM.assistant(assistantContent))
103
+
104
+ // Emit one tool-result message per completed tool. Errors round-trip as
105
+ // resultType: "error" so the model sees the failure message verbatim.
106
+ //
107
+ // Tool outputs are truncated to MAX_TOOL_OUTPUT_CHARS before replay so a
108
+ // single oversized result (e.g. `browser__read_page`, `browser__screenshot`)
109
+ // cannot single-handedly overflow the context window — which would make
110
+ // compaction retry impossible to satisfy and surface as "compaction retry
111
+ // exhausted" to the caller.
112
+ for (const t of completed) {
113
+ const isError = t.state === "error" || t.state === "rejected"
114
+ const result =
115
+ t.output !== undefined
116
+ ? t.output
117
+ : isError
118
+ ? { message: t.state === "rejected" ? "User denied tool execution" : "Tool failed" }
119
+ : undefined
120
+ out.push(
121
+ LLM.toolMessage({
122
+ id: t.callID,
123
+ name: t.name,
124
+ result: truncateToolOutput(result),
125
+ resultType: isError ? "error" : "json",
126
+ }),
127
+ )
128
+ }
129
+
130
+ return out
117
131
  }
118
132
 
119
- return out
120
- }
121
-
122
133
  export const historyToLLMMessages = (messages: ReadonlyArray<Message>): LLMMessage[] => {
123
134
  // Find the *last* compaction marker — only the most recent matters.
124
135
  let markerIdx = -1
@@ -45,12 +45,28 @@ export type ReasoningPart = {
45
45
  readonly text: string
46
46
  }
47
47
 
48
+ /**
49
+ * Lifecycle of a tool call inside an assistant message.
50
+ *
51
+ * Approval flow (interrupt mode):
52
+ * running → pending-approval → approved → running → complete
53
+ * └→ rejected → error
54
+ */
55
+ export type ToolPartState =
56
+ | "pending"
57
+ | "running"
58
+ | "complete"
59
+ | "error"
60
+ | "pending-approval"
61
+ | "approved"
62
+ | "rejected"
63
+
48
64
  export type ToolPart = {
49
65
  readonly id: PartID
50
66
  readonly type: "tool"
51
67
  readonly callID: string
52
68
  readonly name: string
53
- readonly state: "pending" | "running" | "complete" | "error"
69
+ readonly state: ToolPartState
54
70
  readonly input: unknown
55
71
  readonly output?: unknown
56
72
  readonly metadata?: Record<string, unknown>