@sixb/agent 0.0.0-stage → 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.
Files changed (240) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +31 -2
  3. package/dist/abort.d.ts +6 -0
  4. package/dist/abort.d.ts.map +1 -0
  5. package/dist/agent-prompt.d.ts +126 -0
  6. package/dist/agent-prompt.d.ts.map +1 -0
  7. package/dist/agent-runtime/errors.d.ts +13 -0
  8. package/dist/agent-runtime/errors.d.ts.map +1 -0
  9. package/dist/agent-runtime/preflight.d.ts +18 -0
  10. package/dist/agent-runtime/preflight.d.ts.map +1 -0
  11. package/dist/agent-runtime/profile.d.ts +14 -0
  12. package/dist/agent-runtime/profile.d.ts.map +1 -0
  13. package/dist/artifacts/layout-check/layout-check.d.ts +87 -0
  14. package/dist/artifacts/layout-check/layout-check.d.ts.map +1 -0
  15. package/dist/artifacts/materialize.d.ts +115 -0
  16. package/dist/artifacts/materialize.d.ts.map +1 -0
  17. package/dist/artifacts/publish-tool.d.ts +86 -0
  18. package/dist/artifacts/publish-tool.d.ts.map +1 -0
  19. package/dist/ask-parent-tool.d.ts +36 -0
  20. package/dist/ask-parent-tool.d.ts.map +1 -0
  21. package/dist/attachments.d.ts +109 -0
  22. package/dist/attachments.d.ts.map +1 -0
  23. package/dist/child-files.d.ts +91 -0
  24. package/dist/child-files.d.ts.map +1 -0
  25. package/dist/child-questions.d.ts +24 -0
  26. package/dist/child-questions.d.ts.map +1 -0
  27. package/dist/computer-runner.d.ts +74 -0
  28. package/dist/computer-runner.d.ts.map +1 -0
  29. package/dist/context-budget.d.ts +34 -0
  30. package/dist/context-budget.d.ts.map +1 -0
  31. package/dist/context-compaction.d.ts +148 -0
  32. package/dist/context-compaction.d.ts.map +1 -0
  33. package/dist/context-guard.d.ts +69 -0
  34. package/dist/context-guard.d.ts.map +1 -0
  35. package/dist/conversation-memory.d.ts +21 -0
  36. package/dist/conversation-memory.d.ts.map +1 -0
  37. package/dist/conversation-messages.d.ts +33 -0
  38. package/dist/conversation-messages.d.ts.map +1 -0
  39. package/dist/errors.d.ts +46 -0
  40. package/dist/errors.d.ts.map +1 -0
  41. package/dist/execution-plan.d.ts +38 -0
  42. package/dist/execution-plan.d.ts.map +1 -0
  43. package/dist/failure.d.ts +14 -0
  44. package/dist/failure.d.ts.map +1 -0
  45. package/dist/family-mailbox.d.ts +60 -0
  46. package/dist/family-mailbox.d.ts.map +1 -0
  47. package/dist/file-ref.d.ts +6 -0
  48. package/dist/file-ref.d.ts.map +1 -0
  49. package/dist/image-attachments.d.ts +34 -0
  50. package/dist/image-attachments.d.ts.map +1 -0
  51. package/dist/index.d.ts +35 -0
  52. package/dist/index.d.ts.map +1 -0
  53. package/dist/index.js +14387 -0
  54. package/dist/index.js.map +72 -0
  55. package/dist/inline-images.d.ts +28 -0
  56. package/dist/inline-images.d.ts.map +1 -0
  57. package/dist/message-authors.d.ts +34 -0
  58. package/dist/message-authors.d.ts.map +1 -0
  59. package/dist/message-times.d.ts +9 -0
  60. package/dist/message-times.d.ts.map +1 -0
  61. package/dist/model-adapters.d.ts +59 -0
  62. package/dist/model-adapters.d.ts.map +1 -0
  63. package/dist/model-lines.d.ts +16 -0
  64. package/dist/model-lines.d.ts.map +1 -0
  65. package/dist/prompt-cache.d.ts +28 -0
  66. package/dist/prompt-cache.d.ts.map +1 -0
  67. package/dist/requester.d.ts +15 -0
  68. package/dist/requester.d.ts.map +1 -0
  69. package/dist/run-agent-turn.d.ts +93 -0
  70. package/dist/run-agent-turn.d.ts.map +1 -0
  71. package/dist/run-child.d.ts +77 -0
  72. package/dist/run-child.d.ts.map +1 -0
  73. package/dist/run-conversation-turn.d.ts +42 -0
  74. package/dist/run-conversation-turn.d.ts.map +1 -0
  75. package/dist/run-credential.d.ts +22 -0
  76. package/dist/run-credential.d.ts.map +1 -0
  77. package/dist/run-environment.d.ts +145 -0
  78. package/dist/run-environment.d.ts.map +1 -0
  79. package/dist/run-fate.d.ts +15 -0
  80. package/dist/run-fate.d.ts.map +1 -0
  81. package/dist/run-files-lock.d.ts +16 -0
  82. package/dist/run-files-lock.d.ts.map +1 -0
  83. package/dist/run-sandbox.d.ts +60 -0
  84. package/dist/run-sandbox.d.ts.map +1 -0
  85. package/dist/run-subagent.d.ts +65 -0
  86. package/dist/run-subagent.d.ts.map +1 -0
  87. package/dist/run-workflow-agent-node.d.ts +46 -0
  88. package/dist/run-workflow-agent-node.d.ts.map +1 -0
  89. package/dist/sandbox-api-context.d.ts +34 -0
  90. package/dist/sandbox-api-context.d.ts.map +1 -0
  91. package/dist/sandbox-file-registry.d.ts +9 -0
  92. package/dist/sandbox-file-registry.d.ts.map +1 -0
  93. package/dist/sandbox-files.d.ts +71 -0
  94. package/dist/sandbox-files.d.ts.map +1 -0
  95. package/dist/sandbox-handle.d.ts +15 -0
  96. package/dist/sandbox-handle.d.ts.map +1 -0
  97. package/dist/sandbox-readiness.d.ts +8 -0
  98. package/dist/sandbox-readiness.d.ts.map +1 -0
  99. package/dist/skills/built-in.d.ts +15 -0
  100. package/dist/skills/built-in.d.ts.map +1 -0
  101. package/dist/subagent-context.d.ts +50 -0
  102. package/dist/subagent-context.d.ts.map +1 -0
  103. package/dist/subagent-continuation.d.ts +33 -0
  104. package/dist/subagent-continuation.d.ts.map +1 -0
  105. package/dist/subagent-inbox.d.ts +53 -0
  106. package/dist/subagent-inbox.d.ts.map +1 -0
  107. package/dist/subagent-tools.d.ts +293 -0
  108. package/dist/subagent-tools.d.ts.map +1 -0
  109. package/dist/thread-context.d.ts +17 -0
  110. package/dist/thread-context.d.ts.map +1 -0
  111. package/dist/tools/attachments.d.ts +11 -0
  112. package/dist/tools/attachments.d.ts.map +1 -0
  113. package/dist/tools/bash.d.ts +68 -0
  114. package/dist/tools/bash.d.ts.map +1 -0
  115. package/dist/tools/model-spec.d.ts +9 -0
  116. package/dist/tools/model-spec.d.ts.map +1 -0
  117. package/dist/tools/read.d.ts +43 -0
  118. package/dist/tools/read.d.ts.map +1 -0
  119. package/dist/tools/result-media.d.ts +65 -0
  120. package/dist/tools/result-media.d.ts.map +1 -0
  121. package/dist/tools/result-output.d.ts +18 -0
  122. package/dist/tools/result-output.d.ts.map +1 -0
  123. package/dist/tools/tool-files.d.ts +59 -0
  124. package/dist/tools/tool-files.d.ts.map +1 -0
  125. package/dist/tools/tool-outputs.d.ts +63 -0
  126. package/dist/tools/tool-outputs.d.ts.map +1 -0
  127. package/dist/tools/view-file.d.ts +40 -0
  128. package/dist/tools/view-file.d.ts.map +1 -0
  129. package/dist/tsconfig.json +5 -0
  130. package/dist/turn-runtime.d.ts +19 -0
  131. package/dist/turn-runtime.d.ts.map +1 -0
  132. package/dist/types.d.ts +83 -0
  133. package/dist/types.d.ts.map +1 -0
  134. package/dist/workflow-input-attachments.d.ts +18 -0
  135. package/dist/workflow-input-attachments.d.ts.map +1 -0
  136. package/package.json +59 -4
  137. package/src/abort.ts +40 -0
  138. package/src/agent-prompt.ts +860 -0
  139. package/src/agent-runtime/errors.ts +44 -0
  140. package/src/agent-runtime/preflight.ts +314 -0
  141. package/src/agent-runtime/profile.ts +23 -0
  142. package/src/artifacts/layout-check/check.cjs +478 -0
  143. package/src/artifacts/layout-check/layout-check.ts +460 -0
  144. package/src/artifacts/materialize.ts +380 -0
  145. package/src/artifacts/publish-tool.ts +700 -0
  146. package/src/ask-parent-tool.ts +100 -0
  147. package/src/attachments.ts +1041 -0
  148. package/src/child-files.ts +535 -0
  149. package/src/child-questions.ts +42 -0
  150. package/src/computer-runner.ts +336 -0
  151. package/src/context-budget.ts +177 -0
  152. package/src/context-compaction.ts +1349 -0
  153. package/src/context-guard.ts +826 -0
  154. package/src/conversation-memory.ts +45 -0
  155. package/src/conversation-messages.ts +86 -0
  156. package/src/errors.ts +85 -0
  157. package/src/execution-plan.ts +70 -0
  158. package/src/failure.ts +82 -0
  159. package/src/family-mailbox.ts +189 -0
  160. package/src/file-ref.ts +18 -0
  161. package/src/image-attachments.ts +322 -0
  162. package/src/index.ts +54 -0
  163. package/src/inline-images.ts +69 -0
  164. package/src/message-authors.ts +77 -0
  165. package/src/message-times.ts +24 -0
  166. package/src/model-adapters.ts +273 -0
  167. package/src/model-lines.ts +28 -0
  168. package/src/prompt-cache.ts +40 -0
  169. package/src/requester.ts +21 -0
  170. package/src/run-agent-turn.ts +509 -0
  171. package/src/run-child.ts +344 -0
  172. package/src/run-conversation-turn.ts +272 -0
  173. package/src/run-credential.ts +55 -0
  174. package/src/run-environment.ts +1216 -0
  175. package/src/run-fate.ts +51 -0
  176. package/src/run-files-lock.ts +118 -0
  177. package/src/run-sandbox.ts +63 -0
  178. package/src/run-subagent.ts +433 -0
  179. package/src/run-workflow-agent-node.ts +344 -0
  180. package/src/sandbox-api-context.ts +237 -0
  181. package/src/sandbox-file-registry.ts +26 -0
  182. package/src/sandbox-files.ts +326 -0
  183. package/src/sandbox-handle.ts +19 -0
  184. package/src/sandbox-readiness.ts +22 -0
  185. package/src/skills/built-in.ts +183 -0
  186. package/src/skills/sixb-artifacts/SKILL.md +95 -0
  187. package/src/skills/sixb-artifacts/canvas.md +104 -0
  188. package/src/skills/sixb-artifacts/document.md +63 -0
  189. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/first-job.html +42 -0
  190. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/region.html +29 -0
  191. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/shared.css +35 -0
  192. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/welcome.html +31 -0
  193. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/canvas.json +107 -0
  194. package/src/skills/sixb-artifacts/examples/canvas/retro/canvas.json +158 -0
  195. package/src/skills/sixb-artifacts/examples/document/incident-report/document.md +35 -0
  196. package/src/skills/sixb-artifacts/examples/document/operations-review/document.md +41 -0
  197. package/src/skills/sixb-artifacts/examples/document/operations-review/figures/restorations.svg +1 -0
  198. package/src/skills/sixb-artifacts/examples/page/collections-desk/index.html +169 -0
  199. package/src/skills/sixb-artifacts/examples/page/collections-desk/queries/overdue.json +13 -0
  200. package/src/skills/sixb-artifacts/examples/page/dispatch-board/data/dispatch.json +234 -0
  201. package/src/skills/sixb-artifacts/examples/page/dispatch-board/index.html +245 -0
  202. package/src/skills/sixb-artifacts/examples/page/fleet-planner/data/plan.json +53 -0
  203. package/src/skills/sixb-artifacts/examples/page/fleet-planner/index.html +462 -0
  204. package/src/skills/sixb-artifacts/examples/page/service-explorer/data/service.json +276 -0
  205. package/src/skills/sixb-artifacts/examples/page/service-explorer/index.html +549 -0
  206. package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/queries/overdue.json +13 -0
  207. package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/workbook.json +30 -0
  208. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Inventory.csv +13 -0
  209. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Spend.csv +6 -0
  210. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/workbook.json +47 -0
  211. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Quarters.csv +5 -0
  212. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Regions.csv +5 -0
  213. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/workbook.json +78 -0
  214. package/src/skills/sixb-artifacts/examples/slides/launch-plan/index.html +63 -0
  215. package/src/skills/sixb-artifacts/examples/slides/q3-review/index.html +133 -0
  216. package/src/skills/sixb-artifacts/file.md +17 -0
  217. package/src/skills/sixb-artifacts/page.md +215 -0
  218. package/src/skills/sixb-artifacts/queries.md +66 -0
  219. package/src/skills/sixb-artifacts/references.md +68 -0
  220. package/src/skills/sixb-artifacts/sheet.md +223 -0
  221. package/src/skills/sixb-artifacts/slides.md +137 -0
  222. package/src/skills/sixb-memory/SKILL.md +68 -0
  223. package/src/skills/text-assets.d.ts +25 -0
  224. package/src/subagent-context.ts +182 -0
  225. package/src/subagent-continuation.ts +56 -0
  226. package/src/subagent-inbox.ts +101 -0
  227. package/src/subagent-tools.ts +1671 -0
  228. package/src/thread-context.ts +31 -0
  229. package/src/tools/attachments.ts +28 -0
  230. package/src/tools/bash.ts +233 -0
  231. package/src/tools/model-spec.ts +27 -0
  232. package/src/tools/read.ts +262 -0
  233. package/src/tools/result-media.ts +351 -0
  234. package/src/tools/result-output.ts +46 -0
  235. package/src/tools/tool-files.ts +204 -0
  236. package/src/tools/tool-outputs.ts +464 -0
  237. package/src/tools/view-file.ts +155 -0
  238. package/src/turn-runtime.ts +33 -0
  239. package/src/types.ts +91 -0
  240. package/src/workflow-input-attachments.ts +140 -0
@@ -0,0 +1,1349 @@
1
+ import type { AgentMessagePart } from "@sixb/core"
2
+ import {
3
+ AGENT_CONTEXT_COMPACTED_SHARE,
4
+ AGENT_IDLE_COMPACTION_TOKENS,
5
+ type AgentContextBudget,
6
+ type AgentContextCompactionBoundary,
7
+ type AgentContextEstimateTool,
8
+ AgentExecutionLostError,
9
+ type AgentRunSession,
10
+ type AgentSystemPromptSize,
11
+ type AgentThreadModelContextMessage,
12
+ type AgentToolSpec,
13
+ type AgentTurnHistory,
14
+ agentContextCheckpointId,
15
+ contextSummaryOutputTokens,
16
+ estimateAgentContextMessagesTokens,
17
+ estimateAgentContextRequestTokens,
18
+ estimateAgentThreadRequest,
19
+ projectAgentThreadModelContext,
20
+ runModelLoop,
21
+ selectAgentContextCompactionBoundary,
22
+ shouldCompactAgentContext,
23
+ } from "@sixb/core/internal/agents"
24
+ import {
25
+ isModelCallAccountingFailure,
26
+ modelCacheLifetimeMs,
27
+ } from "@sixb/core/internal/model-execution"
28
+ import type { OntologyDocsIndexEntry } from "@sixb/core/internal/ontology"
29
+ import type { ModelCachingIntent, ModelMessage, ModelReasoning, ModelTool } from "@sixb/core/models"
30
+ import type {
31
+ AgentContextCheckpointReason,
32
+ AgentContextCheckpointRecord,
33
+ AgentMessageRecord,
34
+ ConversationAgentRunRecord,
35
+ SubagentRunRecord,
36
+ } from "@sixb/core/storage"
37
+ import { AgentStorageError, stableJsonStringify } from "@sixb/core/storage"
38
+ import { renderAgentSystemPrompt } from "./agent-prompt"
39
+ import type { ConversationMemory } from "./conversation-memory"
40
+ import { conversationModelSettings } from "./conversation-messages"
41
+ import { AgentContextCompactionError } from "./errors"
42
+ import type { ResolvedAgentExecutionPlan } from "./execution-plan"
43
+ import {
44
+ type ConversationReaders,
45
+ conversationAuthors,
46
+ conversationAuthorsText,
47
+ } from "./message-authors"
48
+ import { agentThreadModelContext, type LoadedAgentThreadModelContext } from "./thread-context"
49
+ import { agentModelToolSpecs } from "./tools/model-spec"
50
+ import type { AgentTurnRuntime } from "./turn-runtime"
51
+ import type { AgentExecutionContext } from "./types"
52
+
53
+ const SUMMARY_FORMAT_VERSION = 1 as const
54
+ const CHECKPOINT_RETRY_DELAYS_MS = [50, 200, 600] as const
55
+
56
+ /** English prose runs about this many words per token, to state the summary's length in words. */
57
+ const WORDS_PER_TOKEN = 0.75
58
+
59
+ /** How much of the message the recent work kept as it is starts from the instruction quotes. */
60
+ const KEPT_FROM_QUOTE_CHARS = 120
61
+
62
+ /** How much of each user message a summary quotes. */
63
+ const USER_MESSAGE_QUOTE_CHARS = 300
64
+
65
+ const HISTORY_POINTER = "`sixb history` prints the earlier conversation."
66
+
67
+ /** What the message that carries a summary adds to it: its opening sentence and tags. */
68
+ const SUMMARY_HEADER_TOKENS = 64
69
+
70
+ /** A turn cut to fit the summary request keeps at least this much of each text and result. */
71
+ const SHRUNK_PART_MIN_BYTES = 1_024
72
+
73
+ /** What a turn's model calls start with: the prefix a summary of the conversation continues. */
74
+ export interface ConversationRequest {
75
+ readonly systemPrompt: string
76
+ /** The same prompt with each section's bytes, when the environment rendered it. */
77
+ readonly systemPromptSize?: AgentSystemPromptSize
78
+ readonly tools: readonly Pick<ModelTool, "name" | "description" | "inputSchema">[]
79
+ readonly messages: readonly ModelMessage[]
80
+ }
81
+
82
+ /**
83
+ * The request a turn's calls send for a history, built as the run's environment and its turn
84
+ * build it, with the memory its prompt shows.
85
+ */
86
+ export type BuildConversationRequest = (input: {
87
+ readonly threadContext: LoadedAgentThreadModelContext
88
+ readonly memory: ConversationMemory | undefined
89
+ }) => Promise<ConversationRequest>
90
+
91
+ export interface PreparedAgentConversationContext {
92
+ readonly threadContext: LoadedAgentThreadModelContext
93
+ /** The memory the run's prompt shows, as of the active checkpoint. */
94
+ readonly memory?: ConversationMemory
95
+ /** The bytes per token the turn's history was measured at, when the preflight measured it. */
96
+ readonly bytesPerToken?: number
97
+ }
98
+
99
+ /** Memory as of a checkpoint's creation, or of the thread's start when there is none. */
100
+ export type LoadConversationMemory = (
101
+ checkpoint: { readonly createdAt: Date } | null
102
+ ) => Promise<ConversationMemory | undefined>
103
+
104
+ /** What a request carries besides its history, as an estimate counts it. */
105
+ export interface AgentContextEstimateShape {
106
+ readonly systemPrompt: string
107
+ readonly tools: readonly AgentContextEstimateTool[]
108
+ /** Messages every request sends ahead of the history: a child's task, once summarized. */
109
+ readonly head?: readonly AgentThreadModelContextMessage[]
110
+ }
111
+
112
+ /** What a request of this shape weighs with `messages` as its history. */
113
+ function estimateShapedRequest(
114
+ shape: AgentContextEstimateShape,
115
+ messages: readonly AgentThreadModelContextMessage[],
116
+ bytesPerToken: number
117
+ ) {
118
+ return estimateAgentContextRequestTokens({
119
+ systemPrompt: shape.systemPrompt,
120
+ tools: shape.tools,
121
+ messages: [...(shape.head ?? []), ...messages],
122
+ bytesPerToken,
123
+ })
124
+ }
125
+
126
+ /**
127
+ * What a thread's compaction reads and writes through, before a run or during it: a
128
+ * conversation's, or a child's, whose thread is its history.
129
+ */
130
+ export interface AgentThreadCompactionInput {
131
+ readonly context: Pick<AgentExecutionContext, "id">
132
+ /** The run's session: its history, the checkpoint it writes, and the records it publishes. */
133
+ readonly session: AgentRunSession
134
+ readonly plan: ResolvedAgentExecutionPlan
135
+ readonly budget: AgentContextBudget
136
+ readonly run: ConversationAgentRunRecord | SubagentRunRecord
137
+ readonly runtime: AgentTurnRuntime
138
+ readonly loadMemory?: LoadConversationMemory
139
+ /** The request the run would send for a history: what its summary continues. */
140
+ readonly conversationRequest: BuildConversationRequest
141
+ /** What the run's requests carry besides a history, with the memory its prompt shows. */
142
+ readonly estimateShape: (
143
+ threadContext: LoadedAgentThreadModelContext,
144
+ memory: ConversationMemory | undefined
145
+ ) => AgentContextEstimateShape
146
+ /** How the run's calls are cached: the summary is read as their continuation. */
147
+ readonly caching: ModelCachingIntent
148
+ }
149
+
150
+ /** What a conversation's compaction reads and writes through, before its turn or during it. */
151
+ interface ConversationCompactionInput
152
+ extends Omit<AgentThreadCompactionInput, "context" | "run" | "estimateShape" | "caching"> {
153
+ readonly context: AgentExecutionContext
154
+ readonly run: ConversationAgentRunRecord
155
+ /** The ontology files listed in the conversation's prompt. */
156
+ readonly ontologyIndex?: readonly OntologyDocsIndexEntry[]
157
+ /** Where the run's files go, as the prompt names them. */
158
+ readonly contextDirectory: string
159
+ /** Who can read the run's thread: in a shared one, who wrote what counts toward the estimate. */
160
+ readonly conversation?: ConversationReaders
161
+ readonly frameworkTools?: readonly ModelTool[]
162
+ }
163
+
164
+ /** Load, estimate, and—when required—compact one admitted conversational run before setup. */
165
+ export async function prepareAgentConversationContext(
166
+ input: ConversationCompactionInput & {
167
+ /** The conversation's history as the turn started. */
168
+ readonly history: AgentTurnHistory
169
+ }
170
+ ): Promise<PreparedAgentConversationContext> {
171
+ const { plan, budget, run, runtime } = input
172
+ const compaction = conversationCompaction(input)
173
+ const initialContext = agentThreadModelContext(input.history)
174
+ const memory = await input.loadMemory?.(initialContext.checkpoint)
175
+ runtime.assertCanContinue()
176
+
177
+ const estimateShape = conversationEstimateShape(input, initialContext, memory)
178
+ const { tokens: estimatedInputTokensBefore, bytesPerToken } = estimateAgentConversation({
179
+ plan,
180
+ budget,
181
+ threadContext: initialContext,
182
+ ...estimateShape,
183
+ })
184
+ runtime.assertCanContinue()
185
+
186
+ const unchanged = { threadContext: initialContext, ...(memory ? { memory } : {}), bytesPerToken }
187
+ const overLimit = shouldCompactAgentContext({
188
+ estimatedInputTokens: estimatedInputTokensBefore,
189
+ inputBudgetTokens: budget.inputBudgetTokens,
190
+ })
191
+
192
+ // Compaction aims well under the limit, so the turns after it grow into the room it leaves
193
+ // instead of compacting again: the system prompt and tools, the summary at its longest, and the
194
+ // recent work that fits the rest.
195
+ const summaryTokens = contextSummaryTextTokens(plan, budget)
196
+ const summaryMessageTokens = summaryTokens + SUMMARY_HEADER_TOKENS
197
+ const fixedTokens = estimateShapedRequest(estimateShape, [], bytesPerToken).tokens
198
+ const aimTokens = Math.floor(budget.inputBudgetTokens * AGENT_CONTEXT_COMPACTED_SHARE)
199
+
200
+ // This run's own checkpoint is already as compact as it gets.
201
+ const ownCheckpoint = initialContext.checkpoint?.createdByRunId === run.id
202
+ const boundary = ownCheckpoint
203
+ ? null
204
+ : selectAgentContextCompactionBoundary({
205
+ messages: initialContext.retainedMessages,
206
+ keepRecentTokens: Math.max(
207
+ 0,
208
+ Math.min(budget.keepRecentTokens, aimTokens - fixedTokens - summaryMessageTokens)
209
+ ),
210
+ bytesPerToken,
211
+ })
212
+
213
+ const idle =
214
+ !overLimit &&
215
+ shouldCompactIdleContext({
216
+ history: input.history,
217
+ caching: compaction.caching,
218
+ estimatedInputTokens: estimatedInputTokensBefore,
219
+ compactedTokens: compactedRequestTokens({
220
+ fixedTokens,
221
+ summaryMessageTokens,
222
+ boundary,
223
+ bytesPerToken,
224
+ }),
225
+ })
226
+ if (!overLimit && !idle) return unchanged
227
+
228
+ try {
229
+ const compacted = await compactAgentConversation({
230
+ ...compaction,
231
+ threadContext: initialContext,
232
+ memory,
233
+ bytesPerToken,
234
+ reason: "threshold",
235
+ boundary,
236
+ ownCheckpoint,
237
+ estimatedInputTokensBefore,
238
+ // Below the limit, the thread compacts because it is idle: its cache has gone cold.
239
+ coldCache: !overLimit,
240
+ })
241
+ return { ...compacted, bytesPerToken }
242
+ } catch (error) {
243
+ if (overLimit || !(error instanceof AgentContextCompactionError)) throw error
244
+
245
+ // Below the limit, a failed idle compaction leaves the turn as it was.
246
+ console.warn(`[SixbAgent] Run '${run.id}' goes on uncompacted: ${error.message}`, error)
247
+ return unchanged
248
+ }
249
+ }
250
+
251
+ /** What compacting a thread from within the run in flight is given. */
252
+ interface InRunCompaction {
253
+ /** The history the run works on: as it started, or as its compaction left it. */
254
+ readonly threadContext: LoadedAgentThreadModelContext
255
+ /** The memory the run's prompt shows. */
256
+ readonly memory: ConversationMemory | undefined
257
+ readonly reason: AgentContextCheckpointReason
258
+ /** Whether the thread came back idle, its cache expired: see summarize. */
259
+ readonly coldCache: boolean
260
+ }
261
+
262
+ /**
263
+ * Compact the conversation before the turn in flight, from within it: everything before the
264
+ * turn's own message is summarized, and the turn, its message and the steps it has taken, stays
265
+ * as it is. Undefined when there is nothing before the turn to summarize, when the run already
266
+ * compacted the thread (a run writes one checkpoint), or when the compaction failed: the turn
267
+ * then goes on with what it has.
268
+ */
269
+ export function compactAgentConversationInTurn(
270
+ input: ConversationCompactionInput & InRunCompaction
271
+ ): Promise<PreparedAgentConversationContext | undefined> {
272
+ return compactAgentThreadInRun({ ...input, ...conversationCompaction(input) })
273
+ }
274
+
275
+ /**
276
+ * Compact a thread before the run in flight, from within it: everything before the message the
277
+ * run started from is summarized, and that message and the steps it took stay as they are. A
278
+ * conversation's turn, or a child continuing its thread. Undefined as for
279
+ * {@link compactAgentConversationInTurn}.
280
+ *
281
+ * Its estimates before and after weigh the same request, the history with the run's message,
282
+ * without the steps it keeps: what the summary replaced, not what the run is about to send.
283
+ */
284
+ export async function compactAgentThreadInRun(
285
+ input: AgentThreadCompactionInput & InRunCompaction
286
+ ): Promise<PreparedAgentConversationContext | undefined> {
287
+ const { threadContext, run } = input
288
+ if (threadContext.checkpoint?.createdByRunId === run.id) return undefined
289
+
290
+ const estimateShape = input.estimateShape(threadContext, input.memory)
291
+ const { tokens, bytesPerToken } = estimateAgentConversation({
292
+ plan: input.plan,
293
+ budget: input.budget,
294
+ threadContext,
295
+ ...estimateShape,
296
+ })
297
+ const boundary = inRunBoundary(threadContext, bytesPerToken)
298
+ if (!boundary) return undefined
299
+
300
+ // A summary at its longest weighs as much as an earlier history this short: nothing to gain.
301
+ const summarizedTokens = estimateAgentContextMessagesTokens(
302
+ threadContext.modelMessages.slice(
303
+ 0,
304
+ threadContext.modelMessages.length - boundary.retainedMessages.length
305
+ ),
306
+ bytesPerToken
307
+ ).tokens
308
+ if (
309
+ summarizedTokens <=
310
+ contextSummaryTextTokens(input.plan, input.budget) + SUMMARY_HEADER_TOKENS
311
+ ) {
312
+ return undefined
313
+ }
314
+
315
+ try {
316
+ return await compactAgentConversation({
317
+ ...input,
318
+ bytesPerToken,
319
+ boundary,
320
+ ownCheckpoint: false,
321
+ estimatedInputTokensBefore: tokens,
322
+ coldCache: input.coldCache,
323
+ })
324
+ } catch (error) {
325
+ if (!(error instanceof AgentContextCompactionError)) throw error
326
+
327
+ console.warn(`[SixbAgent] Run '${run.id}' goes on uncompacted: ${error.message}`, error)
328
+ return undefined
329
+ }
330
+ }
331
+
332
+ /** A conversation's compaction as any thread's: its estimate's prompt, and its turns' caching. */
333
+ function conversationCompaction(input: ConversationCompactionInput): AgentThreadCompactionInput {
334
+ return {
335
+ ...input,
336
+ estimateShape: (threadContext, memory) =>
337
+ conversationEstimateShape(input, threadContext, memory),
338
+ caching: conversationModelSettings({
339
+ reasoning: undefined,
340
+ projectId: input.context.id,
341
+ threadId: input.run.threadId,
342
+ }).caching,
343
+ }
344
+ }
345
+
346
+ /** The system prompt and tools a conversation's estimate counts, with the memory its prompt shows. */
347
+ function conversationEstimateShape(
348
+ input: ConversationCompactionInput,
349
+ threadContext: LoadedAgentThreadModelContext,
350
+ memory: ConversationMemory | undefined
351
+ ): AgentContextEstimateShape {
352
+ const { context, plan } = input
353
+
354
+ // Who takes part is in the system prompt, and each message's author on it.
355
+ const authors = input.conversation
356
+ ? conversationAuthors({
357
+ conversation: input.conversation,
358
+ messages: threadContext.retainedMessages,
359
+ })
360
+ : undefined
361
+
362
+ return {
363
+ systemPrompt: [
364
+ renderAgentSystemPrompt({
365
+ mode: "conversation",
366
+ contextDirectory: input.contextDirectory,
367
+ instructions: plan.instructions,
368
+ skills: plan.skills,
369
+ ...(input.ontologyIndex === undefined ? {} : { ontologyIndex: input.ontologyIndex }),
370
+ facts: context.requester === undefined ? {} : { requester: context.requester },
371
+ ...(authors?.section === undefined ? {} : { conversation: authors.section }),
372
+ ...(plan.sandboxModels ? { sandboxModels: plan.sandboxModels } : {}),
373
+ ...(memory ? { memory: memory.prompt } : {}),
374
+ }),
375
+ authors ? conversationAuthorsText(authors) : "",
376
+ ].join("\n"),
377
+ tools: contextEstimateTools([
378
+ ...agentModelToolSpecs(plan.tools),
379
+ ...(input.frameworkTools ?? []),
380
+ ]),
381
+ }
382
+ }
383
+
384
+ /**
385
+ * Summarize the conversation up to `boundary` into a checkpoint, and answer the history from it
386
+ * with the memory its prompt now shows. Publishes the compaction's start and end; throws an
387
+ * {@link AgentContextCompactionError} when it cannot compact, and lost ownership, cancellation or
388
+ * the summary call's own accounting failure as they are.
389
+ */
390
+ async function compactAgentConversation(
391
+ input: AgentThreadCompactionInput & {
392
+ readonly threadContext: LoadedAgentThreadModelContext
393
+ readonly memory: ConversationMemory | undefined
394
+ readonly bytesPerToken: number
395
+ readonly reason: AgentContextCheckpointReason
396
+ readonly boundary: AgentContextCompactionBoundary | null
397
+ readonly ownCheckpoint: boolean
398
+ readonly estimatedInputTokensBefore: number
399
+ /** Whether the conversation's cache has expired: see summarize. */
400
+ readonly coldCache: boolean
401
+ }
402
+ ): Promise<PreparedAgentConversationContext> {
403
+ const { context, session, plan, budget, run, runtime, reason, boundary, bytesPerToken } = input
404
+ const { estimatedInputTokensBefore, memory } = input
405
+ const initialContext = input.threadContext
406
+ const estimateShape = input.estimateShape(initialContext, memory)
407
+ const summaryTokens = contextSummaryTextTokens(plan, budget)
408
+
409
+ await session.events.publishCompactionStarted({
410
+ run,
411
+ reason,
412
+ estimatedInputTokensBefore,
413
+ })
414
+
415
+ try {
416
+ if (input.ownCheckpoint) {
417
+ throw new AgentContextCompactionError(
418
+ "context_limit_exceeded",
419
+ run.id,
420
+ "The current run already compacted this thread, but its retained context still exceeds the model input budget."
421
+ )
422
+ }
423
+ if (!boundary) {
424
+ throw new AgentContextCompactionError(
425
+ "context_limit_exceeded",
426
+ run.id,
427
+ "The current request exceeds the model input budget and no older complete turn can be removed."
428
+ )
429
+ }
430
+
431
+ // Only a conversation's turn can print its thread's stored messages: what a summary says of them.
432
+ const historyReadable = run.kind === "conversation"
433
+ const checkpointId = agentContextCheckpointId(run.id)
434
+ const observedHeadSeq = requiredHeadSeq(initialContext.retainedMessages, run)
435
+ const candidateBase: AgentContextCheckpointRecord = {
436
+ id: checkpointId,
437
+ projectId: context.id,
438
+ threadId: run.threadId,
439
+ createdByRunId: run.id,
440
+ ...(initialContext.checkpoint ? { previousCheckpointId: initialContext.checkpoint.id } : {}),
441
+ reason,
442
+ // Project a minimal summary to reject an oversized retained tail before a billable call.
443
+ summary: ".",
444
+ summaryFormatVersion: SUMMARY_FORMAT_VERSION,
445
+ summarizedThroughSeq: boundary.summarizedThroughSeq,
446
+ observedHeadSeq,
447
+ estimatedInputTokensBefore,
448
+ estimatedInputTokensAfter: 0,
449
+ summaryModelId: plan.model.modelId,
450
+ createdAt: new Date(),
451
+ }
452
+ // The continuation's prompt shows memory as of the new checkpoint.
453
+ const compactedMemory = await input.loadMemory?.(candidateBase)
454
+ runtime.assertCanContinue()
455
+ const compactedShape = input.estimateShape(initialContext, compactedMemory)
456
+ const minimumContinuationTokens = estimateShapedRequest(
457
+ compactedShape,
458
+ projectAgentThreadModelContext({
459
+ checkpoint: candidateBase,
460
+ messages: boundary.retainedMessages,
461
+ historyReadable,
462
+ }),
463
+ bytesPerToken
464
+ ).tokens
465
+ if (minimumContinuationTokens >= budget.inputBudgetTokens) {
466
+ throw new AgentContextCompactionError(
467
+ "context_limit_exceeded",
468
+ run.id,
469
+ "The retained turn and tools leave no room for a context summary. Start a new conversation or select a model with a larger context window."
470
+ )
471
+ }
472
+
473
+ // The summary request leaves the window room for the summary, and for a reasoning budget the
474
+ // provider requires below the output limit. A history whose turns cleared tool results replays
475
+ // them whole, a prefix no call sent and no provider cached: its summary reads it in steps under
476
+ // the model's limit, rather than all of it at once.
477
+ const { requiredTokens } = summaryReasoning(plan.reasoning, summaryTokens)
478
+ const replaysReduced = initialContext.retainedMessages.some((message) =>
479
+ message.parts.some((part) => part.type === "step-start" && part.reducedRequest)
480
+ )
481
+ const steps = planSummary({
482
+ threadContext: initialContext,
483
+ boundary,
484
+ estimateShape,
485
+ bytesPerToken,
486
+ summaryTokens,
487
+ historyReadable,
488
+ inputLimitTokens: Math.min(
489
+ plan.model.definition.maxInputTokens ?? Number.POSITIVE_INFINITY,
490
+ budget.windowTokens - summaryTokens - requiredTokens,
491
+ replaysReduced ? budget.inputBudgetTokens : Number.POSITIVE_INFINITY
492
+ ),
493
+ })
494
+ if (!steps) {
495
+ throw new AgentContextCompactionError(
496
+ "context_limit_exceeded",
497
+ run.id,
498
+ "The earlier history exceeds the selected model's summary input budget. Select a model with a larger context window or start a new conversation."
499
+ )
500
+ }
501
+
502
+ const summary = await generateCheckpointSummary({
503
+ plan,
504
+ budget,
505
+ run,
506
+ runtime,
507
+ threadContext: initialContext,
508
+ steps,
509
+ stepCheckpoint: (summary, messages) => ({
510
+ ...candidateBase,
511
+ summary,
512
+ summarizedThroughSeq: messages[0]!.seq - 1,
513
+ observedHeadSeq: messages.at(-1)!.seq,
514
+ }),
515
+ memory,
516
+ conversationRequest: input.conversationRequest,
517
+ caching: input.caching,
518
+ bytesPerToken,
519
+ summaryTokens: Math.min(summaryTokens, budget.inputBudgetTokens - minimumContinuationTokens),
520
+ coldCache: input.coldCache,
521
+ historyReadable,
522
+ })
523
+ runtime.assertCanContinue()
524
+ const candidate = { ...candidateBase, summary }
525
+ const estimatedInputTokensAfter = estimateShapedRequest(
526
+ compactedShape,
527
+ projectAgentThreadModelContext({
528
+ checkpoint: candidate,
529
+ messages: boundary.retainedMessages,
530
+ historyReadable,
531
+ }),
532
+ bytesPerToken
533
+ ).tokens
534
+ if (estimatedInputTokensAfter > budget.inputBudgetTokens) {
535
+ throw new AgentContextCompactionError(
536
+ "context_limit_exceeded",
537
+ run.id,
538
+ "The summary and selected recent tail still exceed the model input budget. Start a new conversation or select a model with a larger context window."
539
+ )
540
+ }
541
+
542
+ const threadContext = agentThreadModelContext(
543
+ await createCheckpoint({
544
+ session,
545
+ runtime,
546
+ run,
547
+ candidate,
548
+ estimatedInputTokensAfter,
549
+ expectedPreviousCheckpointId: initialContext.checkpoint?.id ?? null,
550
+ }),
551
+ { historyReadable }
552
+ )
553
+ runtime.assertCanContinue()
554
+ const checkpoint = candidate
555
+ if (threadContext.checkpoint?.id !== checkpoint.id) {
556
+ throw new AgentContextCompactionError(
557
+ "checkpoint_failed",
558
+ run.id,
559
+ `Context checkpoint '${checkpoint.id}' was not the active checkpoint after creation.`
560
+ )
561
+ }
562
+
563
+ await session.events.publishCompactionCompleted({
564
+ run,
565
+ reason,
566
+ checkpointId: checkpoint.id,
567
+ estimatedInputTokensBefore,
568
+ estimatedInputTokensAfter,
569
+ })
570
+ return { threadContext, ...(compactedMemory ? { memory: compactedMemory } : {}) }
571
+ } catch (error) {
572
+ // Preserve lost ownership, cancellation and the model call's own accounting failure as their
573
+ // original run-level outcome instead of relabeling them as a compaction implementation failure.
574
+ runtime.assertCanContinue()
575
+ const compactionError = normalizeCompactionError(error, run.id)
576
+ await session.events.publishCompactionFailed({
577
+ run,
578
+ reason,
579
+ errorCode: compactionError.code,
580
+ })
581
+ throw compactionError
582
+ }
583
+ }
584
+
585
+ /**
586
+ * Whether a run starts on a thread worth compacting though it fits: its last model call is older
587
+ * than the cache its calls ask for, so the next one rewrites the whole prompt anyway, the prompt
588
+ * is large enough for a summary to make that rewrite much smaller, and compacting brings it under
589
+ * that size, rather than summarize at every idle turn. A thread whose last call the session cannot
590
+ * date (none since its checkpoint) is not compacted for it.
591
+ */
592
+ export function shouldCompactIdleContext(input: {
593
+ readonly history: AgentTurnHistory
594
+ readonly caching: ModelCachingIntent
595
+ readonly estimatedInputTokens: number
596
+ /** What the next request weighs once compacted: see compactedRequestTokens. */
597
+ readonly compactedTokens: number
598
+ }): boolean {
599
+ const lastCall = input.history.usageAnchor?.modelCall.occurredAt
600
+ if (!lastCall || input.estimatedInputTokens < AGENT_IDLE_COMPACTION_TOKENS) return false
601
+ if (Date.now() - lastCall.getTime() <= modelCacheLifetimeMs(input.caching.lifetime)) return false
602
+
603
+ return input.compactedTokens < AGENT_IDLE_COMPACTION_TOKENS
604
+ }
605
+
606
+ /** Where a compaction from within a run cuts: the run's own message starts what stays. */
607
+ function inRunBoundary(
608
+ threadContext: LoadedAgentThreadModelContext,
609
+ bytesPerToken: number
610
+ ): AgentContextCompactionBoundary | null {
611
+ // Its steps are not stored yet.
612
+ return selectAgentContextCompactionBoundary({
613
+ messages: threadContext.retainedMessages,
614
+ keepRecentTokens: 0,
615
+ bytesPerToken,
616
+ })
617
+ }
618
+
619
+ /** What a thread weighs once compacted from within its run (see compactAgentThreadInRun). */
620
+ export function inRunCompactedTokens(input: {
621
+ readonly plan: ResolvedAgentExecutionPlan
622
+ readonly budget: AgentContextBudget
623
+ readonly threadContext: LoadedAgentThreadModelContext
624
+ readonly estimateShape: AgentContextEstimateShape
625
+ readonly bytesPerToken: number
626
+ }): number {
627
+ const { threadContext, bytesPerToken } = input
628
+ return compactedRequestTokens({
629
+ fixedTokens: estimateShapedRequest(input.estimateShape, [], bytesPerToken).tokens,
630
+ summaryMessageTokens:
631
+ contextSummaryTextTokens(input.plan, input.budget) + SUMMARY_HEADER_TOKENS,
632
+ boundary: inRunBoundary(threadContext, bytesPerToken),
633
+ bytesPerToken,
634
+ })
635
+ }
636
+
637
+ /**
638
+ * What the next request weighs once compacted at `boundary`: what it carries besides its history,
639
+ * the summary at its longest, and the messages that stay. Without a boundary, nothing can be.
640
+ */
641
+ function compactedRequestTokens(input: {
642
+ readonly fixedTokens: number
643
+ readonly summaryMessageTokens: number
644
+ readonly boundary: AgentContextCompactionBoundary | null
645
+ readonly bytesPerToken: number
646
+ }): number {
647
+ if (!input.boundary) return Number.POSITIVE_INFINITY
648
+
649
+ return (
650
+ input.fixedTokens +
651
+ input.summaryMessageTokens +
652
+ estimateAgentContextMessagesTokens(input.boundary.retainedMessages, input.bytesPerToken).tokens
653
+ )
654
+ }
655
+
656
+ /**
657
+ * The conversation's next request as the model will count it, and the bytes per token it was
658
+ * counted at (see estimateAgentThreadRequest): the run's history, at the rate its run started
659
+ * from, with the system prompt and tools its requests send.
660
+ */
661
+ export function estimateAgentConversation(
662
+ input: AgentContextEstimateShape & {
663
+ readonly plan: ResolvedAgentExecutionPlan
664
+ readonly budget: AgentContextBudget
665
+ readonly threadContext: LoadedAgentThreadModelContext
666
+ }
667
+ ): { readonly tokens: number; readonly bytesPerToken: number } {
668
+ const { threadContext } = input
669
+ return estimateAgentThreadRequest({
670
+ usageAnchor: threadContext.history.usageAnchor,
671
+ retainedMessages: threadContext.retainedMessages,
672
+ modelMessages: threadContext.modelMessages,
673
+ model: input.plan.model,
674
+ bytesPerToken: input.budget.bytesPerToken,
675
+ systemPrompt: input.systemPrompt,
676
+ tools: input.tools,
677
+ ...(input.head ? { head: input.head } : {}),
678
+ })
679
+ }
680
+
681
+ /** Tools as an estimate counts them: their schemas serialized as they are sent. */
682
+ export function contextEstimateTools(
683
+ specs: readonly Pick<AgentToolSpec, "name" | "description" | "inputSchema">[]
684
+ ): readonly AgentContextEstimateTool[] {
685
+ return specs.map((spec) => ({
686
+ name: spec.name,
687
+ description: spec.description,
688
+ inputSchema: stableJsonStringify(spec.inputSchema),
689
+ }))
690
+ }
691
+
692
+ /**
693
+ * Write the checkpoint's summary as the continuation of the conversation's cached prompt: the
694
+ * request the turn before this one sent, from the same model with the same system prompt, tools,
695
+ * reasoning and cache intent, then one instruction. The provider reads that prefix from its cache
696
+ * instead of a one-shot transcript at the full price, and the summary rewrites the earlier one it
697
+ * reads there instead of growing from it.
698
+ *
699
+ * A history too long for the model to read at once is summarized in several calls, oldest first,
700
+ * each continuing from the summary the one before wrote.
701
+ */
702
+ async function generateCheckpointSummary(input: {
703
+ readonly plan: ResolvedAgentExecutionPlan
704
+ readonly budget: AgentContextBudget
705
+ readonly run: ConversationAgentRunRecord | SubagentRunRecord
706
+ readonly runtime: AgentTurnRuntime
707
+ /** The history as the turn started, before compaction. */
708
+ readonly threadContext: LoadedAgentThreadModelContext
709
+ readonly steps: readonly SummaryStep[]
710
+ /** The checkpoint a step after the first reads its summary from. */
711
+ readonly stepCheckpoint: (
712
+ summary: string,
713
+ messages: readonly AgentMessageRecord[]
714
+ ) => AgentContextCheckpointRecord
715
+ /** The memory the history's prompt shows: as of its checkpoint, not the new one. */
716
+ readonly memory: ConversationMemory | undefined
717
+ readonly conversationRequest: BuildConversationRequest
718
+ readonly caching: ModelCachingIntent
719
+ readonly bytesPerToken: number
720
+ /** The longest summary the continuation has room for. */
721
+ readonly summaryTokens: number
722
+ /** Whether the conversation's cache has expired: see summarize. */
723
+ readonly coldCache: boolean
724
+ /** Whether the run can print the thread's stored messages, for the summary to say so. */
725
+ readonly historyReadable: boolean
726
+ }): Promise<string> {
727
+ const { threadContext, summaryTokens, historyReadable } = input
728
+ const retained = threadContext.retainedMessages
729
+ const offset = threadContext.modelMessages.length - retained.length
730
+ const maxBytes = Math.floor(summaryTokens * input.bytesPerToken)
731
+
732
+ let summary = threadContext.checkpoint?.summary
733
+ for (const [index, step] of input.steps.entries()) {
734
+ const messages = step.messages ?? retained.slice(step.start, step.end)
735
+ // The first step reads the history as the turn started; each later one, the summary so far.
736
+ const modelMessages =
737
+ index === 0 && !step.messages
738
+ ? threadContext.modelMessages.slice(0, offset + step.end)
739
+ : summary === undefined
740
+ ? messages
741
+ : projectAgentThreadModelContext({
742
+ checkpoint: input.stepCheckpoint(summary, messages),
743
+ messages,
744
+ historyReadable,
745
+ })
746
+ let request: ConversationRequest
747
+ try {
748
+ request = await input.conversationRequest({
749
+ threadContext: { ...threadContext, retainedMessages: messages, modelMessages },
750
+ memory: input.memory,
751
+ })
752
+ } catch (error) {
753
+ throw new ConversationRequestFailure(error)
754
+ }
755
+ input.runtime.assertCanContinue()
756
+
757
+ const text = await summarize({
758
+ plan: input.plan,
759
+ budget: input.budget,
760
+ run: input.run,
761
+ runtime: input.runtime,
762
+ request,
763
+ caching: input.caching,
764
+ instruction: summaryInstruction({
765
+ summaryTokens,
766
+ ...(step.keptFrom ? { keptFrom: step.keptFrom } : {}),
767
+ }),
768
+ estimatedInputTokens: step.estimatedInputTokens,
769
+ summaryTokens,
770
+ coldCache: input.coldCache,
771
+ })
772
+ summary =
773
+ text.output.length === 0
774
+ ? userMessagesSummary({ previous: summary, messages, maxBytes, historyReadable })
775
+ : // A summary the output limit cut short, or longer than the room it has, is kept up to
776
+ // its last complete line: the thread goes on from it instead of failing every turn.
777
+ text.cut || utf8Bytes(text.output) > maxBytes
778
+ ? cutSummary(text.output, maxBytes, historyReadable)
779
+ : text.output
780
+ }
781
+
782
+ // A plan always has a step.
783
+ return summary!
784
+ }
785
+
786
+ /** One summary call: the conversation's request, then the instruction. */
787
+ async function summarize(input: {
788
+ readonly plan: ResolvedAgentExecutionPlan
789
+ readonly budget: AgentContextBudget
790
+ readonly run: ConversationAgentRunRecord | SubagentRunRecord
791
+ readonly runtime: AgentTurnRuntime
792
+ readonly request: ConversationRequest
793
+ /** The run's own: the summary continues what its calls cached. */
794
+ readonly caching: ModelCachingIntent
795
+ readonly instruction: string
796
+ readonly estimatedInputTokens: number
797
+ readonly summaryTokens: number
798
+ /**
799
+ * Whether the conversation's cache has expired. The summary then reads the history at the full
800
+ * price either way, and the next request starts from it: caching the history would only write
801
+ * it, at the long cache's price.
802
+ */
803
+ readonly coldCache: boolean
804
+ }): Promise<{ readonly output: string; readonly cut: boolean }> {
805
+ const { plan, budget, run, request, summaryTokens } = input
806
+ const reasoning = summaryReasoning(plan.reasoning, summaryTokens)
807
+ const maxOutputTokens = Math.max(
808
+ summaryTokens,
809
+ Math.min(
810
+ summaryTokens + reasoning.allowanceTokens,
811
+ budget.windowTokens - input.estimatedInputTokens,
812
+ plan.model.definition.maxOutputTokens ?? Number.POSITIVE_INFINITY
813
+ )
814
+ )
815
+
816
+ let result: Awaited<ReturnType<typeof runModelLoop<string>>>
817
+ try {
818
+ result = await runModelLoop({
819
+ model: plan.model,
820
+ messages: [
821
+ { role: "system", content: request.systemPrompt },
822
+ ...request.messages,
823
+ { role: "user", content: [{ type: "text", text: input.instruction }] },
824
+ ],
825
+ tools: request.tools.map(summaryTool),
826
+ ...(reasoning.reasoning === undefined ? {} : { reasoning: reasoning.reasoning }),
827
+ caching: input.coldCache ? "off" : input.caching,
828
+ maxSteps: 1,
829
+ maxOutputTokens,
830
+ signal: input.runtime.signal,
831
+ })
832
+ } catch (error) {
833
+ input.runtime.assertCanContinue()
834
+ // The summary's own model call was refused or left unrecorded: that ends the run as it is.
835
+ if (isModelCallAccountingFailure(error)) throw error
836
+ throw new AgentContextCompactionError(
837
+ "summary_failed",
838
+ run.id,
839
+ "Could not generate a complete context summary.",
840
+ { cause: error }
841
+ )
842
+ }
843
+ input.runtime.assertCanContinue()
844
+
845
+ if (result.status === "aborted") {
846
+ throw new AgentContextCompactionError("summary_failed", run.id, "Context summary was aborted.")
847
+ }
848
+
849
+ // An answer that calls a tool, as to read the history first, holds only its preamble.
850
+ const calledTool = result.steps.some((step) =>
851
+ step.content.some((part) => part.type === "tool-call")
852
+ )
853
+ if (calledTool) return { output: "", cut: false }
854
+
855
+ return { output: result.output.trim(), cut: result.finishReason === "length" }
856
+ }
857
+
858
+ /** One summary call: the retained messages it reads, from `start` to before `end`. */
859
+ interface SummaryStep {
860
+ readonly start: number
861
+ readonly end: number
862
+ /** The message the recent work kept as it is starts from, when the step reads past it. */
863
+ readonly keptFrom?: AgentMessageRecord
864
+ /** A turn too large to read whole, cut to fit: read in place of its stored messages. */
865
+ readonly messages?: readonly AgentMessageRecord[]
866
+ readonly estimatedInputTokens: number
867
+ }
868
+
869
+ /**
870
+ * What the summary reads. First the whole conversation before the turn: the request the turn's
871
+ * last call sent, which the provider cached. Then only what compaction removes. A history the
872
+ * model's window cannot read at once (a smaller model took over, or a turn outgrew the window)
873
+ * is read in several steps, oldest first, each as many turns as fit beside the summary so far.
874
+ * Undefined when even one turn does not fit.
875
+ */
876
+ function planSummary(input: {
877
+ readonly threadContext: LoadedAgentThreadModelContext
878
+ readonly boundary: AgentContextCompactionBoundary
879
+ readonly estimateShape: AgentContextEstimateShape
880
+ readonly bytesPerToken: number
881
+ readonly summaryTokens: number
882
+ /** Whether the run can print the thread's stored messages, for a turn cut short to say so. */
883
+ readonly historyReadable: boolean
884
+ /** The most a summary request may read. */
885
+ readonly inputLimitTokens: number
886
+ }): readonly SummaryStep[] | undefined {
887
+ const { threadContext, bytesPerToken, summaryTokens } = input
888
+ const retained = threadContext.retainedMessages
889
+ const offset = threadContext.modelMessages.length - retained.length
890
+ const keptFrom = retained.length - input.boundary.retainedMessages.length
891
+ // The turn being answered stays out: what comes before it is the request its last call sent.
892
+ const turnStart = retained.map((message) => message.role).lastIndexOf("user")
893
+
894
+ // Messages weigh the same alone as together: each one's attachments have their own budget.
895
+ const weights = [0]
896
+ for (const message of threadContext.modelMessages) {
897
+ weights.push(
898
+ weights.at(-1)! + estimateAgentContextMessagesTokens([message], bytesPerToken).tokens
899
+ )
900
+ }
901
+ const instructionTokens = (keptFrom?: AgentMessageRecord) =>
902
+ estimateShapedRequest(
903
+ input.estimateShape,
904
+ [
905
+ {
906
+ role: "user",
907
+ parts: [
908
+ {
909
+ type: "text",
910
+ text: summaryInstruction({ summaryTokens, ...(keptFrom ? { keptFrom } : {}) }),
911
+ },
912
+ ],
913
+ },
914
+ ],
915
+ bytesPerToken
916
+ ).tokens
917
+ // A later step reads the summary so far in place of the earlier summary and turns.
918
+ const requestTokens = (start: number, end: number, keptFrom?: AgentMessageRecord) =>
919
+ instructionTokens(keptFrom) +
920
+ (start === 0 ? weights[offset]! : summaryTokens + SUMMARY_HEADER_TOKENS) +
921
+ weights[offset + end]! -
922
+ weights[offset + start]!
923
+
924
+ for (const end of new Set([turnStart, keptFrom])) {
925
+ const step = {
926
+ start: 0,
927
+ end,
928
+ ...(end > keptFrom ? { keptFrom: retained[keptFrom]! } : {}),
929
+ }
930
+ const estimatedInputTokens = requestTokens(step.start, step.end, step.keptFrom)
931
+ if (estimatedInputTokens <= input.inputLimitTokens) return [{ ...step, estimatedInputTokens }]
932
+ }
933
+
934
+ const steps: SummaryStep[] = []
935
+ for (let start = 0; start < keptFrom; start = steps.at(-1)!.end) {
936
+ let step: SummaryStep | undefined
937
+ let nextTurn = keptFrom
938
+ for (let end = keptFrom; end > start && !step; end -= 1) {
939
+ if (retained[end]?.role !== "user") continue
940
+
941
+ nextTurn = end
942
+ const estimatedInputTokens = requestTokens(start, end)
943
+ if (estimatedInputTokens <= input.inputLimitTokens) {
944
+ step = { start, end, estimatedInputTokens }
945
+ }
946
+ }
947
+
948
+ // Even one turn does not fit: it is read with its longest texts and results cut.
949
+ step ??= shrunkStep({
950
+ start,
951
+ end: nextTurn,
952
+ messages: retained.slice(start, nextTurn),
953
+ // What the request reads besides the turn: the prompt, the summary so far, the instruction.
954
+ baseTokens: requestTokens(start, start),
955
+ inputLimitTokens: input.inputLimitTokens,
956
+ bytesPerToken,
957
+ historyReadable: input.historyReadable,
958
+ })
959
+ if (!step) return undefined
960
+
961
+ steps.push(step)
962
+ }
963
+ return steps
964
+ }
965
+
966
+ /**
967
+ * A step over one turn too large to read whole: its texts and tool results cut, the longest first,
968
+ * until the request fits. Undefined when even cut short it does not.
969
+ */
970
+ function shrunkStep(input: {
971
+ readonly start: number
972
+ readonly end: number
973
+ readonly messages: readonly AgentMessageRecord[]
974
+ /** What the request reads besides the turn. */
975
+ readonly baseTokens: number
976
+ readonly inputLimitTokens: number
977
+ readonly bytesPerToken: number
978
+ readonly historyReadable: boolean
979
+ }): SummaryStep | undefined {
980
+ const longest = Math.max(
981
+ 0,
982
+ ...input.messages.flatMap((message) => message.parts.map((part) => partBytes(part)))
983
+ )
984
+
985
+ for (
986
+ let maxBytes = Math.floor(longest / 2);
987
+ maxBytes >= SHRUNK_PART_MIN_BYTES;
988
+ maxBytes = Math.floor(maxBytes / 2)
989
+ ) {
990
+ const messages = input.messages.map((message) => ({
991
+ ...message,
992
+ parts: message.parts.map((part) =>
993
+ cutPart(part, maxBytes, input.historyReadable ? message.seq : undefined)
994
+ ),
995
+ }))
996
+ const estimatedInputTokens =
997
+ input.baseTokens + estimateAgentContextMessagesTokens(messages, input.bytesPerToken).tokens
998
+ if (estimatedInputTokens <= input.inputLimitTokens) {
999
+ return { start: input.start, end: input.end, messages, estimatedInputTokens }
1000
+ }
1001
+ }
1002
+ return undefined
1003
+ }
1004
+
1005
+ /** What a part weighs in the request: its text, or its call's input and what the model read. */
1006
+ function partBytes(part: AgentMessagePart): number {
1007
+ switch (part.type) {
1008
+ case "text":
1009
+ case "reasoning":
1010
+ return utf8Bytes(part.text)
1011
+ case "tool-call":
1012
+ return utf8Bytes(stableJsonStringify(part.input)) + utf8Bytes(toolOutputText(part))
1013
+ default:
1014
+ return 0
1015
+ }
1016
+ }
1017
+
1018
+ /**
1019
+ * A text or tool result cut to `maxBytes`, saying where the whole is when the run can read it: the
1020
+ * message `seq` its history prints.
1021
+ */
1022
+ function cutPart(
1023
+ part: AgentMessagePart,
1024
+ maxBytes: number,
1025
+ seq: number | undefined
1026
+ ): AgentMessagePart {
1027
+ const note =
1028
+ seq === undefined ? "[Cut short.]" : `[Cut short: \`sixb history ${seq}\` prints it whole.]`
1029
+ const cut = (value: string) =>
1030
+ utf8Bytes(value) <= maxBytes ? value : `${upToLastLine(value, maxBytes)}\n${note}`
1031
+
1032
+ switch (part.type) {
1033
+ case "text":
1034
+ case "reasoning":
1035
+ return { ...part, text: cut(part.text) }
1036
+ case "tool-call":
1037
+ if (part.state === "output-error") return { ...part, errorText: cut(part.errorText) }
1038
+ return { ...part, modelOutput: { type: "text", value: cut(toolOutputText(part)) } }
1039
+ default:
1040
+ return part
1041
+ }
1042
+ }
1043
+
1044
+ /** What the model reads of a call's result: the output its tool projected, else the output. */
1045
+ function toolOutputText(part: Extract<AgentMessagePart, { readonly type: "tool-call" }>): string {
1046
+ if (part.state === "output-error") return part.errorText
1047
+ if (part.modelOutput?.type === "text") return part.modelOutput.value
1048
+ return stableJsonStringify(part.modelOutput ? part.modelOutput.value : part.output)
1049
+ }
1050
+
1051
+ /** The summary's own allowance, apart from any reasoning: half the output reserve, at most 8,192. */
1052
+ function contextSummaryTextTokens(
1053
+ plan: ResolvedAgentExecutionPlan,
1054
+ budget: AgentContextBudget
1055
+ ): number {
1056
+ return Math.min(
1057
+ contextSummaryOutputTokens(budget.reserveTokens),
1058
+ plan.model.definition.maxOutputTokens ?? Number.POSITIVE_INFINITY
1059
+ )
1060
+ }
1061
+
1062
+ /**
1063
+ * How the summary call reasons, and the output it may spend on that on top of the summary. It
1064
+ * reasons as the turn's calls do: thinking and effort are part of the prefix a provider caches,
1065
+ * so a summary that changed them would read the conversation again at the full price (measured
1066
+ * through the Gateway on Haiku 5.5: 17,359 tokens read with the turn's settings, 8,928 without its
1067
+ * thinking, none with reasoning off as well).
1068
+ *
1069
+ * To summarize without thinking instead, return `reasoning: "none"` and no allowance here, and
1070
+ * leave out the binding's own thinking option as well: on the Gateway, `"none"` keeps it.
1071
+ */
1072
+ function summaryReasoning(
1073
+ reasoning: ModelReasoning | undefined,
1074
+ summaryTokens: number
1075
+ ): {
1076
+ readonly reasoning: ModelReasoning | undefined
1077
+ readonly allowanceTokens: number
1078
+ /** What the output limit must hold whatever the window: a budget providers reject beyond it. */
1079
+ readonly requiredTokens: number
1080
+ } {
1081
+ if (reasoning === "none") return { reasoning, allowanceTokens: 0, requiredTokens: 0 }
1082
+ if (typeof reasoning === "object") {
1083
+ return {
1084
+ reasoning,
1085
+ allowanceTokens: reasoning.budgetTokens,
1086
+ requiredTokens: reasoning.budgetTokens,
1087
+ }
1088
+ }
1089
+
1090
+ // An effort, or the binding's own default: it may think as long as it writes, and writes less
1091
+ // when the window leaves it less.
1092
+ return { reasoning, allowanceTokens: summaryTokens, requiredTokens: 0 }
1093
+ }
1094
+
1095
+ /**
1096
+ * The turn's tools as the summary call sends them: the same definitions, so the prefix is the one
1097
+ * the provider cached. The instruction asks for text alone; a call the model makes anyway never
1098
+ * runs.
1099
+ */
1100
+ function summaryTool(tool: Pick<ModelTool, "name" | "description" | "inputSchema">): ModelTool {
1101
+ return {
1102
+ name: tool.name,
1103
+ description: tool.description,
1104
+ inputSchema: tool.inputSchema,
1105
+ parseInput: (value) => value,
1106
+ execute: async () => {
1107
+ throw new Error("[SixbAgent] A context summary runs no tools.")
1108
+ },
1109
+ errorText: () => "A context summary runs no tools.",
1110
+ }
1111
+ }
1112
+
1113
+ /**
1114
+ * The one instruction that ends the summary request. The summary replaces the conversation in the
1115
+ * model's context, the earlier summary included, so each one is written anew from what the model
1116
+ * reads, within a length it states, instead of growing from the last.
1117
+ */
1118
+ function summaryInstruction(input: {
1119
+ readonly summaryTokens: number
1120
+ /** The message the recent work kept as it is starts from, when the request reads past it. */
1121
+ readonly keptFrom?: AgentMessageRecord
1122
+ }): string {
1123
+ const words = Math.max(100, Math.floor((input.summaryTokens * WORDS_PER_TOKEN) / 100) * 100)
1124
+
1125
+ return [
1126
+ "<sixb_summary_request>",
1127
+ "This conversation is being compacted. The summary you write now replaces it in your context: write what you need to go on with the work from it alone.",
1128
+ ...(input.keptFrom
1129
+ ? [
1130
+ `The conversation from the user message that begins ${quoteStart(input.keptFrom)} on stays in your context as it is: summarize what comes before it, and mention what follows only under Current work.`,
1131
+ ]
1132
+ : []),
1133
+ "It replaces any earlier summary above: carry over what is still useful from it, rewritten, rather than adding to it.",
1134
+ `Write at most ${words.toLocaleString("en-US")} words of plain Markdown. No JSON, no escaped text, no message or tool call ids, and no tool calls.`,
1135
+ "",
1136
+ "Use these sections, in this order, and leave out any that would be empty:",
1137
+ "## Goal",
1138
+ "What the user wants and why, and how the request changed.",
1139
+ "## Current work",
1140
+ "What was in progress just before this summary, and the next step if one was agreed or is clearly due.",
1141
+ "## Pending work",
1142
+ "What was asked and is not done yet.",
1143
+ "## Decisions and constraints",
1144
+ "What was decided, and the user's preferences and constraints.",
1145
+ "## Errors and fixes",
1146
+ "What failed, and how it was fixed or worked around.",
1147
+ "## Files and resources",
1148
+ "Files, artifacts and attachments read, created or changed, by path, and what they hold.",
1149
+ "## Identifiers",
1150
+ "Exact ids, names, URLs, numbers and other values the work depends on.",
1151
+ "## Completed work",
1152
+ "What was done, and its results.",
1153
+ "## User messages",
1154
+ `Every message the user wrote, oldest first, each verbatim and cut after ${USER_MESSAGE_QUOTE_CHARS} characters with […]. When they do not all fit, keep the latest verbatim and sum up the older ones in a line each.`,
1155
+ "</sixb_summary_request>",
1156
+ ].join("\n")
1157
+ }
1158
+
1159
+ /** How the instruction names a message: by its first words, else by its first file. */
1160
+ function quoteStart(message: AgentMessageRecord): string {
1161
+ const text = messageText(message).replace(/\s+/g, " ").trim()
1162
+ if (text) {
1163
+ return JSON.stringify(
1164
+ text.length > KEPT_FROM_QUOTE_CHARS ? `${text.slice(0, KEPT_FROM_QUOTE_CHARS)}…` : text
1165
+ )
1166
+ }
1167
+
1168
+ const file = message.parts.find((part) => part.type === "file")
1169
+ return file?.type === "file" && file.fileRef.fileName
1170
+ ? `with the file ${JSON.stringify(file.fileRef.fileName)}`
1171
+ : `sent at ${message.createdAt.toISOString()}`
1172
+ }
1173
+
1174
+ /** A summary up to its last complete line within `maxBytes`, marked as cut short. */
1175
+ function cutSummary(text: string, maxBytes: number, historyReadable: boolean): string {
1176
+ const note = historyReadable ? ` ${HISTORY_POINTER}` : ""
1177
+ return `${upToLastLine(text, maxBytes)}\n\n[The summary was cut short here.${note}]`
1178
+ }
1179
+
1180
+ /**
1181
+ * A summary written without the model, when its answer held no text: the earlier summary and the
1182
+ * user's messages, newest last, as many as the allowance holds. The thread goes on from it rather
1183
+ * than failing every turn on the same call.
1184
+ */
1185
+ function userMessagesSummary(input: {
1186
+ readonly previous: string | undefined
1187
+ readonly messages: readonly AgentMessageRecord[]
1188
+ readonly maxBytes: number
1189
+ readonly historyReadable: boolean
1190
+ }): string {
1191
+ const header = "The summary could not be written. What the user asked, newest last:"
1192
+ const footer = input.historyReadable ? [HISTORY_POINTER] : []
1193
+ const quotes = input.messages
1194
+ .filter((message) => message.role === "user")
1195
+ .map((message) => messageText(message).trim())
1196
+ .filter((text) => text.length > 0)
1197
+ .map((text) => {
1198
+ const quoted =
1199
+ text.length > USER_MESSAGE_QUOTE_CHARS
1200
+ ? `${text.slice(0, USER_MESSAGE_QUOTE_CHARS)} […]`
1201
+ : text
1202
+ return `> ${quoted.replaceAll("\n", "\n> ")}`
1203
+ })
1204
+
1205
+ let bytes = [header, ...footer].reduce((total, line) => total + utf8Bytes(line) + 2, 0)
1206
+ const kept: string[] = []
1207
+ for (const quote of [...quotes].reverse()) {
1208
+ bytes += utf8Bytes(quote) + 2
1209
+ if (bytes > input.maxBytes) break
1210
+
1211
+ kept.unshift(quote)
1212
+ }
1213
+ const previous =
1214
+ input.previous && bytes + utf8Bytes(input.previous) + 2 <= input.maxBytes
1215
+ ? [input.previous]
1216
+ : []
1217
+
1218
+ return [...previous, header, ...kept, ...footer].join("\n\n")
1219
+ }
1220
+
1221
+ function messageText(message: AgentMessageRecord): string {
1222
+ return message.parts.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n")
1223
+ }
1224
+
1225
+ /**
1226
+ * The text up to its last line break within `maxBytes`: what follows it was cut mid-line. Up to
1227
+ * `maxBytes` when it has no line break.
1228
+ */
1229
+ function upToLastLine(text: string, maxBytes: number): string {
1230
+ const bytes = new TextEncoder().encode(text)
1231
+ // A cut inside a multi-byte character drops it.
1232
+ const head =
1233
+ bytes.byteLength <= maxBytes
1234
+ ? text
1235
+ : new TextDecoder().decode(bytes.slice(0, maxBytes)).replace(/\uFFFD$/, "")
1236
+ const lastLine = head.lastIndexOf("\n")
1237
+ return (lastLine > 0 ? head.slice(0, lastLine) : head).trimEnd()
1238
+ }
1239
+
1240
+ function utf8Bytes(value: string): number {
1241
+ return new TextEncoder().encode(value).byteLength
1242
+ }
1243
+
1244
+ async function createCheckpoint(input: {
1245
+ readonly session: AgentRunSession
1246
+ readonly runtime: AgentTurnRuntime
1247
+ readonly run: ConversationAgentRunRecord | SubagentRunRecord
1248
+ readonly candidate: AgentContextCheckpointRecord
1249
+ readonly estimatedInputTokensAfter: number
1250
+ readonly expectedPreviousCheckpointId: string | null
1251
+ }): Promise<AgentTurnHistory> {
1252
+ for (let attempt = 0; ; attempt += 1) {
1253
+ input.runtime.assertCanContinue()
1254
+ try {
1255
+ return await input.session.checkpoint({
1256
+ id: input.candidate.id,
1257
+ threadId: input.candidate.threadId,
1258
+ expectedPreviousCheckpointId: input.expectedPreviousCheckpointId,
1259
+ expectedHeadSeq: input.candidate.observedHeadSeq,
1260
+ reason: input.candidate.reason,
1261
+ summary: input.candidate.summary,
1262
+ summaryFormatVersion: input.candidate.summaryFormatVersion,
1263
+ summarizedThroughSeq: input.candidate.summarizedThroughSeq,
1264
+ observedHeadSeq: input.candidate.observedHeadSeq,
1265
+ estimatedInputTokensBefore: input.candidate.estimatedInputTokensBefore,
1266
+ estimatedInputTokensAfter: input.estimatedInputTokensAfter,
1267
+ summaryModelId: input.candidate.summaryModelId,
1268
+ createdAt: input.candidate.createdAt,
1269
+ })
1270
+ } catch (error) {
1271
+ if (error instanceof AgentExecutionLostError) throw error
1272
+ if (error instanceof AgentStorageError) {
1273
+ throw new AgentContextCompactionError(
1274
+ "checkpoint_failed",
1275
+ input.run.id,
1276
+ "The context checkpoint no longer matches the active thread state.",
1277
+ { cause: error }
1278
+ )
1279
+ }
1280
+ const delayMs = CHECKPOINT_RETRY_DELAYS_MS[attempt]
1281
+ if (delayMs === undefined) {
1282
+ throw new AgentContextCompactionError(
1283
+ "checkpoint_failed",
1284
+ input.run.id,
1285
+ "Could not persist the context checkpoint.",
1286
+ { cause: error }
1287
+ )
1288
+ }
1289
+ await wait(delayMs, input.runtime.signal)
1290
+ }
1291
+ }
1292
+ }
1293
+
1294
+ function requiredHeadSeq(
1295
+ messages: readonly AgentMessageRecord[],
1296
+ run: ConversationAgentRunRecord | SubagentRunRecord
1297
+ ): number {
1298
+ const head = messages.at(-1)?.seq
1299
+ if (head === undefined) {
1300
+ throw new AgentContextCompactionError(
1301
+ "checkpoint_failed",
1302
+ run.id,
1303
+ "Cannot compact a thread without a retained trigger message."
1304
+ )
1305
+ }
1306
+ return head
1307
+ }
1308
+
1309
+ /**
1310
+ * The run's environment failed while it built the summary request, as acquiring its workspace or
1311
+ * reading its files: that failure is the run's, not compaction's.
1312
+ */
1313
+ class ConversationRequestFailure extends Error {
1314
+ readonly name = "ConversationRequestFailure"
1315
+
1316
+ constructor(override readonly cause: unknown) {
1317
+ super("[SixbAgent] The summary request could not be built.", { cause })
1318
+ }
1319
+ }
1320
+
1321
+ function normalizeCompactionError(error: unknown, runId: string): AgentContextCompactionError {
1322
+ if (error instanceof ConversationRequestFailure) throw error.cause
1323
+ if (error instanceof AgentContextCompactionError) return error
1324
+ if (error instanceof AgentExecutionLostError || isModelCallAccountingFailure(error)) throw error
1325
+ return new AgentContextCompactionError(
1326
+ "checkpoint_failed",
1327
+ runId,
1328
+ "Context compaction failed before the checkpoint became active.",
1329
+ { cause: error }
1330
+ )
1331
+ }
1332
+
1333
+ function wait(ms: number, signal: AbortSignal): Promise<void> {
1334
+ return new Promise((resolve, reject) => {
1335
+ if (signal.aborted) {
1336
+ reject(signal.reason)
1337
+ return
1338
+ }
1339
+ const onAbort = () => {
1340
+ clearTimeout(timer)
1341
+ reject(signal.reason)
1342
+ }
1343
+ const timer = setTimeout(() => {
1344
+ signal.removeEventListener("abort", onAbort)
1345
+ resolve()
1346
+ }, ms)
1347
+ signal.addEventListener("abort", onAbort, { once: true })
1348
+ })
1349
+ }