@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,509 @@
1
+ import type { AgentMessage, AgentMessagePart, AgentStepRequestSize } from "@sixb/core"
2
+ import {
3
+ type AgentContextBudget,
4
+ type AgentRunSession,
5
+ createAgentMessageId,
6
+ measureAgentStepRequest,
7
+ type PausableModelLoopResult,
8
+ type PrepareModelStepInput,
9
+ type RecoverModelStepInput,
10
+ runModelLoop,
11
+ } from "@sixb/core/internal/agents"
12
+ import { isAbortError } from "@sixb/core/internal/workers"
13
+ import { type ModelMessage, ModelProviderError, type ModelStep } from "@sixb/core/models"
14
+ import {
15
+ type AgentRunDiagnostic,
16
+ type AgentRunFinishReason,
17
+ type AgentRunRecord,
18
+ type AppendAgentMessageInput,
19
+ type ConversationAgentRunRecord,
20
+ coerceAgentRunFinishReason,
21
+ } from "@sixb/core/storage"
22
+ import { createAgentContextGuard } from "./context-guard"
23
+ import { conversationModelMessages, conversationModelSettings } from "./conversation-messages"
24
+ import { AgentContextCompactionError, throwIfExecutionLost } from "./errors"
25
+ import type { ResolvedAgentExecutionPlan } from "./execution-plan"
26
+ import type { ConversationReaders } from "./message-authors"
27
+ import { agentTraceFromModelSteps, agentTraceFromPartialModelLoop } from "./model-adapters"
28
+ import type { ConversationAgentExecutionEnvironment } from "./run-environment"
29
+ import { monitorSandboxReadiness } from "./sandbox-readiness"
30
+ import type { LoadedAgentThreadModelContext } from "./thread-context"
31
+ import { type AgentTurnRuntime, createAgentTurnRuntime } from "./turn-runtime"
32
+ import type { AgentTurnContext } from "./types"
33
+
34
+ export interface RunAgentTurnInput {
35
+ /** The worker's stable execution context (storage, tools and stream sink). */
36
+ readonly context: AgentTurnContext
37
+ readonly plan: ResolvedAgentExecutionPlan
38
+ /** The run this delivery reserved or reclaimed with its execution token. */
39
+ readonly run: ConversationAgentRunRecord
40
+ /** The run's session: its finish, and every other write, are fenced by its execution token. */
41
+ readonly session: AgentRunSession
42
+ /** The worker's shutdown signal. */
43
+ readonly signal: AbortSignal
44
+ /**
45
+ * The worker's own stop, when `signal` also carries a user cancel. A turn it ends first is
46
+ * recorded with `finishReason: "interrupted"` so the user can resume it.
47
+ */
48
+ readonly stopSignal?: AbortSignal
49
+ /** Shared with preflight when this turn performed compaction. */
50
+ readonly runtime?: AgentTurnRuntime
51
+ /** The thread and who can read it now; without it the model is told nothing of its people. */
52
+ readonly conversation?: ConversationReaders
53
+ /** The history the turn runs on: as it started, or as its compaction left it. */
54
+ readonly threadContext: LoadedAgentThreadModelContext
55
+ /** What the turn's children ask it, and the work it waits for, when it can delegate. */
56
+ readonly children?: TurnChildren
57
+ /**
58
+ * The model's limit every call of the turn keeps under (see createAgentContextGuard), and how
59
+ * it compacts the history before it from within. Without them, only the turn's start was
60
+ * weighed.
61
+ */
62
+ readonly contextLimits?: {
63
+ readonly budget: AgentContextBudget
64
+ /** The bytes per token the turn's history was measured at, else its run's starting one. */
65
+ readonly bytesPerToken?: number
66
+ /** What the run's latest counted call measured (see prepareAgentModel). */
67
+ readonly measuredBytesPerToken?: () => number | undefined
68
+ readonly compactInTurn?: ConversationAgentExecutionEnvironment["compactInTurn"]
69
+ }
70
+ /**
71
+ * Handed the answer so far after each step that completed, as the message the turn would
72
+ * append: a turn that fails then records it with its failure, and keeps that work.
73
+ */
74
+ readonly onWork?: (message: AppendAgentMessageInput) => void
75
+ }
76
+
77
+ /**
78
+ * How a turn hears the questions its children ask, leaves them waiting when it ends, and waits for
79
+ * those still at work when it pauses.
80
+ */
81
+ export interface TurnChildren {
82
+ /** Read after the conversation: children of earlier turns still waiting on their question. */
83
+ readonly waiting?: string
84
+ /** The questions the model has not read yet, read in one more step when it answers. */
85
+ unread(): Promise<string | undefined>
86
+ /**
87
+ * Before the turn records its end: each child still waiting on its question pauses on it, and
88
+ * the turn waits until it has. Only then can its end cancel the others.
89
+ */
90
+ defer(signal: AbortSignal): Promise<void>
91
+ /**
92
+ * Before a pausing turn records its end: wait until none of its children is at work. Its end
93
+ * cancels those still at work; one that holds a call pauses by itself.
94
+ */
95
+ settle(signal: AbortSignal): Promise<void>
96
+ }
97
+
98
+ /** Drive one provider-neutral model/tool turn to completion and persist it. */
99
+ export async function runAgentTurn(input: RunAgentTurnInput): Promise<AgentRunRecord> {
100
+ const { context, plan, run, signal } = input
101
+ const { id: projectId, tools } = context
102
+ const runId = run.id
103
+
104
+ const modelMessages = conversationModelMessages({
105
+ threadContext: input.threadContext,
106
+ ...(context.attachmentContext ? { attachmentContext: context.attachmentContext } : {}),
107
+ ...(input.conversation ? { conversation: input.conversation } : {}),
108
+ project: { timeZone: context.projectTimeZone, locale: context.projectLocale },
109
+ })
110
+
111
+ const sandboxReadiness = monitorSandboxReadiness(context.sandboxReady)
112
+ // Preflight and the answer share one signal. Direct callers own their runtime.
113
+ const ownsRuntime = input.runtime === undefined
114
+ const runtime = input.runtime ?? createAgentTurnRuntime({ signal })
115
+ const abortSignal = AbortSignal.any([
116
+ runtime.signal,
117
+ sandboxReadiness.signal,
118
+ ...(context.environmentFailureSignal ? [context.environmentFailureSignal] : []),
119
+ ])
120
+ let interruptedParts: readonly AgentMessagePart[] | undefined
121
+ const stopReason = () =>
122
+ stoppedByWorker(signal, input.stopSignal) ? { finishReason: "interrupted" as const } : {}
123
+
124
+ const finalizeIfInterrupted = async (error?: unknown): Promise<AgentRunRecord | null> => {
125
+ throwIfExecutionLost(runtime.sourceSignal)
126
+ sandboxReadiness.throwIfFailed()
127
+ context.environmentFailureSignal?.throwIfAborted()
128
+ if (!abortSignal.aborted && (error === undefined || !isAbortError(error))) return null
129
+ return finalizeInterruptedTurn({
130
+ session: input.session,
131
+ context,
132
+ run,
133
+ modelId: plan.model.modelId,
134
+ ...stopReason(),
135
+ parts: interruptedParts,
136
+ })
137
+ }
138
+
139
+ // What every request starts with: the system prompt, the conversation, then what children of
140
+ // earlier turns still wait on.
141
+ const requestHead = (systemPrompt: string, conversation: readonly ModelMessage[]) => [
142
+ { role: "system" as const, content: systemPrompt },
143
+ ...conversation,
144
+ ...(input.children?.waiting
145
+ ? [
146
+ {
147
+ role: "user" as const,
148
+ content: [{ type: "text" as const, text: input.children.waiting }],
149
+ },
150
+ ]
151
+ : []),
152
+ ]
153
+ // What each step's request carried, as it was sent, for its step-start to record. The prompt's
154
+ // sections are known for the prompt the turn rendered, then for the one its compaction rendered.
155
+ const stepRequests: AgentStepRequestSize[] = []
156
+ let systemPromptSize = context.systemPromptSize
157
+ const recordRequest = (stepIndex: number, messages: readonly ModelMessage[]) => {
158
+ stepRequests[stepIndex] = measureAgentStepRequest({
159
+ messages,
160
+ tools,
161
+ ...(systemPromptSize ? { systemPrompt: systemPromptSize } : {}),
162
+ ...(context.contextDirectory === undefined
163
+ ? {}
164
+ : { contextDirectory: context.contextDirectory }),
165
+ })
166
+ }
167
+
168
+ const limits = input.contextLimits
169
+ const compactInTurn = limits?.compactInTurn
170
+ const guard =
171
+ limits &&
172
+ createAgentContextGuard({
173
+ budget: limits.budget,
174
+ ...(limits.bytesPerToken === undefined ? {} : { bytesPerToken: limits.bytesPerToken }),
175
+ ...(limits.measuredBytesPerToken === undefined
176
+ ? {}
177
+ : { measuredBytesPerToken: limits.measuredBytesPerToken }),
178
+ tools: tools.map((tool) => ({
179
+ name: tool.name,
180
+ description: tool.description,
181
+ inputSchema: tool.inputSchema,
182
+ })),
183
+ ...(compactInTurn
184
+ ? {
185
+ compact: async (compaction) => {
186
+ const request = await compactInTurn(compaction)
187
+ if (request) systemPromptSize = request.systemPromptSize
188
+ return request && requestHead(request.systemPrompt, request.messages)
189
+ },
190
+ }
191
+ : {}),
192
+ })
193
+ const guardedStep = guard
194
+ ? async (step: Parameters<typeof guard.prepareStep>[0]) => {
195
+ const prepared = await context.prepareStep?.(step)
196
+ const guarded = await guard.prepareStep({
197
+ ...step,
198
+ messages: prepared?.messages ?? step.messages,
199
+ })
200
+ // The guard's request, when it reduced the one prepared, and the room its answer has.
201
+ return { ...prepared, ...guarded }
202
+ }
203
+ : context.prepareStep
204
+ const prepareStep = async (step: PrepareModelStepInput) => {
205
+ const prepared = await guardedStep?.(step)
206
+ recordRequest(step.stepIndex, prepared?.messages ?? step.messages)
207
+ return prepared
208
+ }
209
+ const recoverStep =
210
+ guard &&
211
+ (async (step: RecoverModelStepInput) => {
212
+ const recovered = await guard.recoverStep(step)
213
+ if (recovered?.messages) recordRequest(step.stepIndex, recovered.messages)
214
+ return recovered
215
+ })
216
+
217
+ // The answer so far, as one message whatever step it is at.
218
+ const workMessageId = createAgentMessageId()
219
+ const finishedSteps: ModelStep[] = []
220
+ const recordStep = (step: ModelStep) => {
221
+ finishedSteps.push(step)
222
+ input.onWork?.({
223
+ id: workMessageId,
224
+ projectId,
225
+ threadId: run.threadId,
226
+ runId,
227
+ role: "assistant",
228
+ parts: recordStepRequests(
229
+ markReducedSteps(
230
+ agentTraceFromModelSteps(
231
+ finishedSteps,
232
+ { threadId: run.threadId, runId },
233
+ context.outputFileOf
234
+ ),
235
+ guard?.reducedFromStep()
236
+ ),
237
+ stepRequests
238
+ ),
239
+ ...(context.authorPrincipal === undefined
240
+ ? {}
241
+ : { authorPrincipal: context.authorPrincipal }),
242
+ })
243
+ }
244
+
245
+ try {
246
+ let chunkIndex = 0
247
+ let result: PausableModelLoopResult
248
+ try {
249
+ result = await runModelLoop({
250
+ model: plan.model,
251
+ messages: requestHead(context.systemPrompt, modelMessages),
252
+ tools,
253
+ ...conversationModelSettings({
254
+ reasoning: plan.reasoning,
255
+ projectId,
256
+ threadId: run.threadId,
257
+ }),
258
+ ...(plan.maxSteps === undefined ? {} : { maxSteps: plan.maxSteps }),
259
+ prepareStep,
260
+ ...(recoverStep ? { recoverStep } : {}),
261
+ onStepEnd: recordStep,
262
+ // A child's question the model has not read comes before its answer ends the turn.
263
+ ...(input.children === undefined
264
+ ? {}
265
+ : {
266
+ beforeComplete: async () => {
267
+ const unread = await input.children?.unread()
268
+ return unread
269
+ ? [{ role: "user", content: [{ type: "text", text: unread }] }]
270
+ : undefined
271
+ },
272
+ }),
273
+ signal: abortSignal,
274
+ onEvent: async (chunk) => {
275
+ await input.session.events.publishUiChunk({ run, chunkIndex: chunkIndex++, chunk })
276
+ },
277
+ // The approval records decide, never the tool output: the model can send a command's
278
+ // output elsewhere, or print one of its own. A held call waits for the children still
279
+ // at work: pausing ends the turn, and that would cancel them.
280
+ pauseAfterStep: () => input.session.heldCalls.pausesAfterStep(),
281
+ })
282
+ } catch (error) {
283
+ const interrupted = await finalizeIfInterrupted(error)
284
+ if (interrupted) return interrupted
285
+
286
+ // Compacted and asked again, the request still did not fit the model's window.
287
+ if (error instanceof ModelProviderError && error.reason === "context-window-exceeded") {
288
+ throw new AgentContextCompactionError(
289
+ "context_limit_exceeded",
290
+ runId,
291
+ "The conversation still exceeds the model's context window after it was reduced. Start a new conversation or select a model with a larger context window.",
292
+ { cause: error }
293
+ )
294
+ }
295
+ throw error
296
+ }
297
+
298
+ interruptedParts = recordStepRequests(
299
+ markReducedSteps(
300
+ result.status === "aborted"
301
+ ? agentTraceFromPartialModelLoop(
302
+ result.steps,
303
+ result.partialContent,
304
+ { threadId: run.threadId, runId },
305
+ context.outputFileOf
306
+ )
307
+ : agentTraceFromModelSteps(
308
+ result.steps,
309
+ { threadId: run.threadId, runId },
310
+ context.outputFileOf
311
+ ),
312
+ guard?.reducedFromStep()
313
+ ),
314
+ stepRequests
315
+ )
316
+
317
+ const interruptedAfterModel = await finalizeIfInterrupted()
318
+ if (interruptedAfterModel) return interruptedAfterModel
319
+ if (result.status === "aborted") {
320
+ return finalizeInterruptedTurn({
321
+ session: input.session,
322
+ context,
323
+ run,
324
+ modelId: plan.model.modelId,
325
+ ...stopReason(),
326
+ parts: interruptedParts,
327
+ })
328
+ }
329
+
330
+ // A child waiting on its question pauses on it while the turn still runs: a waiting child
331
+ // would hold the wait below forever, and the turn's end cancels the children still at work.
332
+ await input.children?.defer(abortSignal)
333
+
334
+ // A call held after the last step that ran tools, by a command left running in the sandbox or
335
+ // by a child, pauses the turn too. Its end cancels the children still at work, so it first
336
+ // waits for them: one that holds a call pauses by itself instead of being stopped.
337
+ if (result.status === "paused" || (await input.session.heldCalls.holdsRun())) {
338
+ await input.children?.settle(abortSignal)
339
+ }
340
+ const interruptedWhileWaiting = await finalizeIfInterrupted()
341
+ if (interruptedWhileWaiting) return interruptedWhileWaiting
342
+
343
+ const finishReason =
344
+ result.status === "paused" || (await input.session.heldCalls.holdsRun())
345
+ ? "awaiting_approval"
346
+ : (coerceAgentRunFinishReason(result.finishReason) ?? "unknown")
347
+ const assistant: AgentMessage = { role: "assistant", parts: interruptedParts }
348
+ const diagnostics = [
349
+ outputLimitDiagnostic(finishReason),
350
+ finishReason === "awaiting_approval" ? undefined : stepLimitDiagnostic(result),
351
+ ].filter((diagnostic) => diagnostic !== undefined)
352
+ const assistantMessageId = createAgentMessageId()
353
+
354
+ const interruptedBeforeCommit = await finalizeIfInterrupted()
355
+ if (interruptedBeforeCommit) return interruptedBeforeCommit
356
+
357
+ await context.beforeFinalize?.()
358
+ const finalizedRun = await input.session.finish(
359
+ {
360
+ status: "succeeded",
361
+ modelId: plan.model.modelId,
362
+ finishReason,
363
+ ...(diagnostics.length === 0 ? {} : { diagnostics }),
364
+ },
365
+ [
366
+ {
367
+ id: assistantMessageId,
368
+ projectId,
369
+ threadId: run.threadId,
370
+ runId,
371
+ role: assistant.role,
372
+ parts: assistant.parts,
373
+ ...(context.authorPrincipal === undefined
374
+ ? {}
375
+ : { authorPrincipal: context.authorPrincipal }),
376
+ },
377
+ ]
378
+ )
379
+
380
+ await input.session.events.publishMessageFinalized({ run, messageId: assistantMessageId })
381
+ await input.session.events.publishRunFinished(finalizedRun)
382
+ return finalizedRun
383
+ } finally {
384
+ if (ownsRuntime) runtime.dispose()
385
+ }
386
+ }
387
+
388
+ /**
389
+ * Whether the turn holds a call for its requester, as `runs.finish` checks before it pauses: one
390
+ * waiting, or decided and not reported to the model yet, its children's included.
391
+ */
392
+
393
+ /**
394
+ * Mark each step from `fromStep` on as answering a request the turn reduced, for the next turn's
395
+ * estimate not to go by what those calls read.
396
+ */
397
+ export function markReducedSteps(
398
+ parts: readonly AgentMessagePart[],
399
+ fromStep: number | undefined
400
+ ): readonly AgentMessagePart[] {
401
+ if (fromStep === undefined) return parts
402
+
403
+ let step = -1
404
+ return parts.map((part) => {
405
+ if (part.type !== "step-start") return part
406
+
407
+ step += 1
408
+ return step >= fromStep ? { type: "step-start", reducedRequest: true } : part
409
+ })
410
+ }
411
+
412
+ /**
413
+ * Record on each step-start what its request carried, by step: the next turn's context meter
414
+ * reads the system prompt and tools the latest one sent.
415
+ */
416
+ export function recordStepRequests(
417
+ parts: readonly AgentMessagePart[],
418
+ requests: readonly (AgentStepRequestSize | undefined)[]
419
+ ): readonly AgentMessagePart[] {
420
+ let step = -1
421
+ return parts.map((part) => {
422
+ if (part.type !== "step-start") return part
423
+
424
+ step += 1
425
+ const request = requests[step]
426
+ return request ? { ...part, request } : part
427
+ })
428
+ }
429
+
430
+ /**
431
+ * Whether the worker's stop, rather than the user's, ended the turn. Whichever fired first wins:
432
+ * the combined turn signal carries the reason of the first source that aborted it.
433
+ */
434
+ export function stoppedByWorker(turnSignal: AbortSignal, stopSignal?: AbortSignal): boolean {
435
+ return stopSignal?.aborted === true && turnSignal.reason === stopSignal.reason
436
+ }
437
+
438
+ /**
439
+ * An answer the output limit cut short keeps what the model produced, reasoning included, and says
440
+ * so through a diagnostic, which chats render in the reader's language. Its unfinished tool calls
441
+ * were dropped unexecuted.
442
+ */
443
+ function outputLimitDiagnostic(finishReason: AgentRunFinishReason): AgentRunDiagnostic | undefined {
444
+ if (finishReason !== "length") return undefined
445
+ return {
446
+ code: "output_limit_reached",
447
+ severity: "warning",
448
+ scope: "run",
449
+ message: "The model reached its output limit before finishing the answer.",
450
+ }
451
+ }
452
+
453
+ /**
454
+ * A turn the project's `maxSteps` stopped keeps its work as its answer, and says so: Continue starts
455
+ * a turn that goes on from it, as a retry would only stop at the same place.
456
+ */
457
+ function stepLimitDiagnostic(result: PausableModelLoopResult): AgentRunDiagnostic | undefined {
458
+ if (result.status !== "completed" || !result.stepLimitReached) return undefined
459
+ return {
460
+ code: "step_limit_reached",
461
+ severity: "warning",
462
+ scope: "run",
463
+ message: "The agent reached its step limit before producing a final answer.",
464
+ }
465
+ }
466
+
467
+ /** Persist a cancelled turn, retaining coherent partial content when any was produced. */
468
+ async function finalizeInterruptedTurn(input: {
469
+ readonly session: AgentRunSession
470
+ readonly context: AgentTurnContext
471
+ readonly run: ConversationAgentRunRecord
472
+ readonly modelId?: string
473
+ readonly finishReason?: "interrupted"
474
+ readonly parts?: readonly AgentMessagePart[]
475
+ }): Promise<AgentRunRecord> {
476
+ const { session, context, run, modelId, finishReason } = input
477
+ const parts = input.parts?.some((part) => part.type !== "step-start") ? input.parts : undefined
478
+
479
+ await context.beforeFinalize?.()
480
+
481
+ const outcome = {
482
+ status: "cancelled" as const,
483
+ ...(modelId === undefined ? {} : { modelId }),
484
+ ...(finishReason === undefined ? {} : { finishReason }),
485
+ }
486
+ if (!parts) {
487
+ const finalizedRun = await session.finish(outcome)
488
+ await session.events.publishRunFinished(finalizedRun)
489
+ return finalizedRun
490
+ }
491
+
492
+ const assistantMessageId = createAgentMessageId()
493
+ const finalizedRun = await session.finish(outcome, [
494
+ {
495
+ id: assistantMessageId,
496
+ projectId: run.projectId,
497
+ threadId: run.threadId,
498
+ runId: run.id,
499
+ role: "assistant",
500
+ parts,
501
+ ...(context.authorPrincipal === undefined
502
+ ? {}
503
+ : { authorPrincipal: context.authorPrincipal }),
504
+ },
505
+ ])
506
+ await session.events.publishMessageFinalized({ run, messageId: assistantMessageId })
507
+ await session.events.publishRunFinished(finalizedRun)
508
+ return finalizedRun
509
+ }