@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,336 @@
1
+ import { mkdir, realpath, rm } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import type { Sandbox, SandboxRequestCredential } from "@sixb/core"
4
+ import {
5
+ AgentExecutionLostError,
6
+ AgentRunRefusedError,
7
+ type AgentRunSession,
8
+ claimAgentRunChildOverHttp,
9
+ claimAgentRunOverHttp,
10
+ type HttpAgentRunSessionInput,
11
+ } from "@sixb/core/internal/agents"
12
+ import type { ConversationAgentRunRecord } from "@sixb/core/storage"
13
+ import { delay } from "./abort"
14
+ import { ChildRunner } from "./run-child"
15
+ import { runConversationTurn } from "./run-conversation-turn"
16
+ import { runApiCredential, runnerTokenFor, runTokenFor } from "./run-credential"
17
+ import type { OpenRunSandbox } from "./run-environment"
18
+ import { holdRunFiles } from "./run-files-lock"
19
+ import { type RunSandbox, SANDBOX_CONTEXT_DIRECTORY } from "./run-sandbox"
20
+ import type { AgentRunSettings } from "./types"
21
+
22
+ // A turn on its owner's computer: claimed over HTTP as them, run in their folder, its children
23
+ // beside it. The API does everything a turn asks of its project; the computer runs its commands.
24
+
25
+ /** Opens the sandbox a computer's run works in. */
26
+ export type OpenComputerSandbox = (input: {
27
+ /** The user's folder, for a turn; absent for a child, which works in a folder of its own. */
28
+ readonly workingDirectory?: string
29
+ /** Where the run's own files go, outside the folder: its commands may write there too. */
30
+ readonly runFiles: string
31
+ /** The run's token, which the sandbox adds outside its commands. */
32
+ readonly credential: SandboxRequestCredential
33
+ readonly signal: AbortSignal
34
+ }) => Promise<Sandbox>
35
+
36
+ export interface ComputerRunnerOptions {
37
+ /** The project's API origin. */
38
+ readonly apiUrl: string
39
+ /** The user's own credential, as an `Authorization` header value, read for each claim. */
40
+ authorization(): Promise<string>
41
+ /**
42
+ * This computer, as each claim names it with the folder: a thread runs on one of its owner's
43
+ * computers, in one folder there, and only `sixb` open there claims its turns.
44
+ */
45
+ computer(): Promise<{ readonly id: string; readonly name: string }>
46
+ /** The folder the user's turns work in: its real path. */
47
+ readonly folder: string
48
+ /**
49
+ * Where each run's own files go: a directory per thread, so every turn's prompt names the same
50
+ * paths, emptied when a run starts and removed when it ends. Shared by every runner on the
51
+ * computer, which hold a thread's directory one run at a time.
52
+ */
53
+ readonly runFilesRoot: string
54
+ readonly openSandbox: OpenComputerSandbox
55
+ /** How many children of one turn run at once. Defaults to 4. */
56
+ readonly childCapacity?: number
57
+ /** A run that failed, once its end is recorded. */
58
+ readonly onFailure?: (error: unknown) => void
59
+ readonly fetch?: (request: Request) => Promise<Response>
60
+ }
61
+
62
+ /** How far ahead a lease is held, and how often it is renewed: a renewal also hears a cancel. */
63
+ const LEASE_MS = 60_000
64
+ const RENEW_MS = 10_000
65
+ const CHILD_CLAIM_RETRIES = 5
66
+
67
+ export class ComputerRunner {
68
+ private readonly teardowns = new Set<Promise<void>>()
69
+ /** Each running turn's renewal, by run id, to renew at once. */
70
+ private readonly renewals = new Map<string, () => void>()
71
+
72
+ constructor(private readonly options: ComputerRunnerOptions) {}
73
+
74
+ /**
75
+ * Claim a queued turn and run it to its end. False when it was not this computer's to run: it
76
+ * ended already, or another runner holds it. `signal` stops the runner: the turn ends
77
+ * interrupted, its end recorded.
78
+ */
79
+ async runTurn(
80
+ runId: string,
81
+ signal: AbortSignal,
82
+ onClaimed?: (run: ConversationAgentRunRecord) => void
83
+ ): Promise<boolean> {
84
+ const { apiUrl } = this.options
85
+ const fetch = this.options.fetch
86
+ const session = await claimAgentRunOverHttp({
87
+ apiUrl,
88
+ runId,
89
+ authorization: await this.options.authorization(),
90
+ computer: { ...(await this.options.computer()), folder: this.options.folder },
91
+ leaseExpiresAt: lease(),
92
+ ...(fetch === undefined ? {} : { fetch }),
93
+ })
94
+ if (!session) return false
95
+
96
+ const { run } = session
97
+ onClaimed?.(run)
98
+ const turn: HttpAgentRunSessionInput<ConversationAgentRunRecord> = {
99
+ apiUrl,
100
+ runnerToken: runnerTokenFor({
101
+ projectId: run.projectId,
102
+ runId: run.id,
103
+ executionToken: session.executionToken,
104
+ }),
105
+ run,
106
+ ...(fetch === undefined ? {} : { fetch }),
107
+ }
108
+ const lost = new AbortController()
109
+ const held = new Set<AgentRunSession>([session])
110
+ const renewing = this.renew(held, session, lost)
111
+ this.renewals.set(run.id, renewing.now)
112
+ const turnSignal = AbortSignal.any([signal, lost.signal])
113
+ const settings = computerSettings(run.projectId, apiUrl)
114
+ const children = this.childRunner(turn, settings)
115
+
116
+ try {
117
+ await runConversationTurn({
118
+ session,
119
+ signal: turnSignal,
120
+ runner: {
121
+ settings,
122
+ openSandbox: () =>
123
+ this.sandbox({
124
+ runId: run.id,
125
+ threadId: run.threadId,
126
+ executionToken: session.executionToken,
127
+ projectId: run.projectId,
128
+ folder: this.options.folder,
129
+ }),
130
+ startChild: (child, family) =>
131
+ children.start(child, {
132
+ signal: turnSignal,
133
+ family,
134
+ leaseExpiresAt: lease,
135
+ holdLease: async (childSession) => {
136
+ held.add(childSession)
137
+ try {
138
+ await childSession.renewLease(lease())
139
+ } catch (error) {
140
+ held.delete(childSession)
141
+ throw error
142
+ }
143
+ return () => held.delete(childSession)
144
+ },
145
+ }),
146
+ onDetachedTeardown: (teardown) => this.track(teardown),
147
+ reportFailure: (error) => this.options.onFailure?.(error),
148
+ },
149
+ })
150
+ } catch (error) {
151
+ // Stopped with its end recorded: nothing to release, as no queue holds it.
152
+ if (!turnSignal.aborted) throw error
153
+ } finally {
154
+ await children.stopChildrenOf(run.id)
155
+ this.renewals.delete(run.id)
156
+ renewing.stop()
157
+ await session.close()
158
+ }
159
+ return true
160
+ }
161
+
162
+ /**
163
+ * Renew a running turn's lease now rather than at its next renewal: its answer carries a cancel
164
+ * just asked for, so a stop from this computer takes effect at once.
165
+ */
166
+ renewNow(runId: string): void {
167
+ this.renewals.get(runId)?.()
168
+ }
169
+
170
+ /** Wait for sandbox teardowns that outlived their runs. */
171
+ async drain(): Promise<void> {
172
+ await Promise.allSettled([...this.teardowns])
173
+ }
174
+
175
+ /**
176
+ * Renew the turn's lease, and its children's, until stopped. A renewal answers a cancel; one
177
+ * that finds the turn no longer this computer's stops it.
178
+ */
179
+ private renew(
180
+ held: Set<AgentRunSession>,
181
+ turn: AgentRunSession,
182
+ lost: AbortController
183
+ ): { now(): void; stop(): void } {
184
+ const renew = () => {
185
+ for (const session of held) {
186
+ void session.renewLease(lease()).catch((error: unknown) => {
187
+ if (error instanceof AgentExecutionLostError) {
188
+ held.delete(session)
189
+ if (session === turn) lost.abort(error)
190
+ return
191
+ }
192
+ // A blip: the next renewal tries again, well before the lease runs out.
193
+ console.error(`[SixbAgent] Could not renew run '${session.run.id}'.`, error)
194
+ })
195
+ }
196
+ }
197
+ const timer = setInterval(renew, RENEW_MS)
198
+ return { now: renew, stop: () => clearInterval(timer) }
199
+ }
200
+
201
+ private childRunner(
202
+ turn: HttpAgentRunSessionInput<ConversationAgentRunRecord>,
203
+ settings: AgentRunSettings
204
+ ): ChildRunner {
205
+ return new ChildRunner({
206
+ settings,
207
+ capacity: this.options.childCapacity ?? 4,
208
+ claim: async (run, { leaseExpiresAt, stop }) => {
209
+ for (let retry = 0; ; retry += 1) {
210
+ try {
211
+ return await claimAgentRunChildOverHttp(turn, { childRunId: run.id, leaseExpiresAt })
212
+ } catch (error) {
213
+ if (error instanceof AgentRunRefusedError || error instanceof AgentExecutionLostError) {
214
+ return null
215
+ }
216
+ if (retry >= CHILD_CLAIM_RETRIES) throw error
217
+ }
218
+ if (stop.aborted) return null
219
+ await delay(1_000 * 2 ** retry, stop).catch(() => {})
220
+ if (stop.aborted) return null
221
+ }
222
+ },
223
+ openSandbox: ({ session }) =>
224
+ this.sandbox({
225
+ runId: session.run.id,
226
+ threadId: session.run.threadId,
227
+ executionToken: session.executionToken,
228
+ projectId: session.run.projectId,
229
+ }),
230
+ onDetachedTeardown: (teardown) => this.track(teardown),
231
+ reportFailure: (error) => this.options.onFailure?.(error),
232
+ })
233
+ }
234
+
235
+ /**
236
+ * A run's sandbox: the user's folder for a turn, which the prompt describes, or a blank folder
237
+ * of its own for a child. Its own files go in its thread's directory, outside the folder: the
238
+ * prompt names them, so each run of the thread names the same paths.
239
+ */
240
+ private sandbox(input: {
241
+ readonly runId: string
242
+ readonly threadId: string
243
+ readonly executionToken: string
244
+ readonly projectId: string
245
+ readonly folder?: string
246
+ }): OpenRunSandbox {
247
+ const { apiUrl } = this.options
248
+ const credential = runApiCredential(apiUrl, runTokenFor(input))
249
+ return async ({ signal }) => {
250
+ // Real paths: the OS sandbox compares them, and the agent names files by them.
251
+ await mkdir(this.options.runFilesRoot, { recursive: true })
252
+ const runDirectory = join(await realpath(this.options.runFilesRoot), threadDirectory(input))
253
+ // Named as a cloud sandbox names them, so a path reads as the run's files wherever it ran.
254
+ const runFiles = join(runDirectory, SANDBOX_CONTEXT_DIRECTORY)
255
+ const folder = input.folder === undefined ? undefined : await realpath(input.folder)
256
+ let held: (() => Promise<void>) | undefined
257
+
258
+ const sandbox: RunSandbox = {
259
+ waitBeforeModel: folder !== undefined,
260
+ contextDirectory: runFiles,
261
+ acquire: async () => {
262
+ const giveBack = await holdRunFiles({
263
+ directory: runDirectory,
264
+ runId: input.runId,
265
+ signal,
266
+ })
267
+ held = giveBack
268
+ try {
269
+ // Each run starts empty, as with a directory of its own: nothing an earlier run, or
270
+ // one that crashed, left there.
271
+ await rm(runDirectory, { recursive: true, force: true })
272
+ await mkdir(runFiles, { recursive: true })
273
+ return {
274
+ sandbox: await this.options.openSandbox({
275
+ ...(folder === undefined ? {} : { workingDirectory: folder }),
276
+ runFiles,
277
+ credential,
278
+ signal,
279
+ }),
280
+ ...(folder === undefined
281
+ ? {}
282
+ : { promptContext: { workingDirectory: folder, retention: "computer" as const } }),
283
+ }
284
+ } catch (error) {
285
+ await giveBack()
286
+ throw error
287
+ }
288
+ },
289
+ release: async ({ sandbox }) => {
290
+ try {
291
+ await sandbox.destroy()
292
+ await rm(runDirectory, { recursive: true, force: true })
293
+ } finally {
294
+ await held?.()
295
+ }
296
+ },
297
+ }
298
+ return { sandbox }
299
+ }
300
+ }
301
+
302
+ private track(teardown: Promise<void>): void {
303
+ this.teardowns.add(teardown)
304
+ void teardown.finally(() => this.teardowns.delete(teardown))
305
+ }
306
+ }
307
+
308
+ /**
309
+ * A thread's files directory, by its id: one thread runs one run at a time, and its children have
310
+ * threads of their own.
311
+ */
312
+ function threadDirectory(input: { readonly runId: string; readonly threadId: string }): string {
313
+ if (!/^[A-Za-z0-9_-]+$/.test(input.threadId)) {
314
+ throw new Error(
315
+ `[SixbAgent] Run '${input.runId}' names thread '${input.threadId}', which cannot name a directory.`
316
+ )
317
+ }
318
+ return input.threadId
319
+ }
320
+
321
+ function lease(): string {
322
+ return new Date(Date.now() + LEASE_MS).toISOString()
323
+ }
324
+
325
+ /** What a computer's runs share: the person at it sets the time zone and locale. */
326
+ function computerSettings(projectId: string, apiUrl: string): AgentRunSettings {
327
+ const { timeZone, locale } = Intl.DateTimeFormat().resolvedOptions()
328
+ return {
329
+ id: projectId,
330
+ apiBaseUrl: apiUrl,
331
+ subagentConcurrencyPerRun: 4,
332
+ keepsChildWorkspaces: false,
333
+ locale,
334
+ timeZone,
335
+ }
336
+ }
@@ -0,0 +1,177 @@
1
+ import { AgentDefinitionError } from "@sixb/core"
2
+ import {
3
+ AGENT_TOKEN_RATE_SAMPLES,
4
+ type AgentContextBudget,
5
+ type AgentContextTokenRateSample,
6
+ type AgentModelSelection,
7
+ agentContextSizeTokens,
8
+ agentOutputCapTokens,
9
+ calibrateAgentContextBytesPerToken,
10
+ contextSummaryOutputTokens,
11
+ DEFAULT_AGENT_CONTEXT_WINDOW_TOKENS,
12
+ learnedAgentContextBytesPerToken,
13
+ measureAgentContextTokenRate,
14
+ measureAgentModelRequest,
15
+ resolveAgentContextBudget,
16
+ } from "@sixb/core/internal/agents"
17
+ import {
18
+ defineLanguageModel,
19
+ type LanguageModel,
20
+ type LanguageModelRequest,
21
+ type LanguageModelStreamEvent,
22
+ } from "@sixb/core/models"
23
+
24
+ /**
25
+ * Derive the model's input and output budgets from its definition, and cap each call's output to
26
+ * them. The model comes pinned: whoever hands it over resolved it once for the run.
27
+ */
28
+ export function prepareAgentModel(selection: AgentModelSelection): {
29
+ readonly model: LanguageModel
30
+ readonly budget: AgentContextBudget
31
+ /**
32
+ * The bytes per token the run's latest counted call measured, bounded around the run's rate (the
33
+ * project's measurements and its own calls'), as calibration and the output ceiling read it.
34
+ * Undefined until a call is counted.
35
+ */
36
+ readonly measuredBytesPerToken: () => number | undefined
37
+ } {
38
+ const model = selection.model
39
+ const definition = defineLanguageModel(model.definition)
40
+ const budget = resolveAgentContextBudget(selection, definition)
41
+ if (budget.source === "fallback") {
42
+ console.warn(
43
+ `[SixbAgent] No context limit is available for '${model.providerId}/${model.modelId}'; using the ${DEFAULT_AGENT_CONTEXT_WINDOW_TOKENS.toLocaleString("en-US")}-token fallback.`
44
+ )
45
+ }
46
+ const maxOutputTokens = agentOutputCapTokens(selection.model, definition) ?? budget.reserveTokens
47
+ if (
48
+ typeof selection.reasoning === "object" &&
49
+ selection.reasoning.budgetTokens >= maxOutputTokens
50
+ ) {
51
+ throw new AgentDefinitionError(
52
+ "[SixbAgent] Agent context output allowance must exceed the reasoning token budget."
53
+ )
54
+ }
55
+
56
+ // The run's rate, from the project's measurements and, newest first, its own calls'.
57
+ const tokenRates = selection.tokenRates ?? []
58
+ const runTokenRates: AgentContextTokenRateSample[] = []
59
+ let runBytesPerToken = budget.bytesPerToken
60
+ // The rate the run's latest counted call measured, bounded around the run's; else the run's.
61
+ let counted = false
62
+ let measuredBytesPerToken = budget.bytesPerToken
63
+
64
+ return {
65
+ budget,
66
+ measuredBytesPerToken: () => (counted ? measuredBytesPerToken : undefined),
67
+ model: Object.freeze({
68
+ providerId: model.providerId,
69
+ modelId: model.modelId,
70
+ definition: defineLanguageModel({ ...definition, maxOutputTokens }),
71
+ costEstimator: model.costEstimator,
72
+ ...(model.validateResponseFormat === undefined
73
+ ? {}
74
+ : { validateResponseFormat: model.validateResponseFormat.bind(model) }),
75
+ stream: async (request: LanguageModelRequest) => {
76
+ const size = measureAgentModelRequest(request)
77
+ const stream = await model.stream({
78
+ ...request,
79
+ maxOutputTokens: Math.min(
80
+ request.maxOutputTokens ?? maxOutputTokens,
81
+ outputCeilingTokens(
82
+ agentContextSizeTokens(size, Math.min(runBytesPerToken, measuredBytesPerToken)),
83
+ budget,
84
+ maxOutputTokens
85
+ )
86
+ ),
87
+ })
88
+
89
+ return {
90
+ events: withCountedInput(stream.events, (inputTokens) => {
91
+ const sample = measureAgentContextTokenRate({ size, inputTokens })
92
+ if (sample) {
93
+ // The newest 20 are all the statistic reads.
94
+ runTokenRates.unshift(sample)
95
+ runTokenRates.splice(AGENT_TOKEN_RATE_SAMPLES)
96
+ runBytesPerToken = learnedAgentContextBytesPerToken([...runTokenRates, ...tokenRates])
97
+ }
98
+
99
+ measuredBytesPerToken = calibrateAgentContextBytesPerToken({
100
+ bytesPerToken: runBytesPerToken,
101
+ size,
102
+ inputTokens,
103
+ })
104
+ counted = true
105
+ }),
106
+ }
107
+ },
108
+ }),
109
+ }
110
+ }
111
+
112
+ /**
113
+ * A call may write whatever its input leaves of the window, up to the cap, and the reserve at
114
+ * least. The input is weighed at the denser of the run's rate and the one its latest call
115
+ * measured, so it errs high whichever way this request's content tokenizes: a call right after a
116
+ * large tool result can read denser than the calls it was calibrated on, and with no turn to ask
117
+ * it again, an allowance past the window's room is a refused call.
118
+ *
119
+ * Below the reserve, only the guard decides (see createAgentContextGuard): it weighs the request
120
+ * from what the provider counted, and caps the request it lets past the limit at its own room.
121
+ */
122
+ function outputCeilingTokens(
123
+ inputTokens: number,
124
+ budget: AgentContextBudget,
125
+ capTokens: number
126
+ ): number {
127
+ return Math.max(
128
+ Math.min(capTokens, budget.reserveTokens),
129
+ agentOutputRoomTokens(inputTokens, budget, capTokens)
130
+ )
131
+ }
132
+
133
+ /**
134
+ * What a call may write for what its input weighs: the room it leaves of the window, up to
135
+ * `capTokens`. The one measure the output ceiling and the guard size a call's answer by.
136
+ */
137
+ export function agentOutputRoomTokens(
138
+ inputTokens: number,
139
+ budget: AgentContextBudget,
140
+ capTokens: number
141
+ ): number {
142
+ return Math.min(capTokens, budget.windowTokens - inputTokens)
143
+ }
144
+
145
+ /**
146
+ * The least room a request past its model's limit is still sent with: what a compaction summary
147
+ * may write (see contextSummaryOutputTokens), the answer the framework already sizes as enough to
148
+ * carry a conversation on. With less, the turn ends with the context error rather than send a
149
+ * call whose answer would be cut off almost at once.
150
+ */
151
+ export function agentMinimumAnswerTokens(budget: AgentContextBudget): number {
152
+ return contextSummaryOutputTokens(budget.reserveTokens)
153
+ }
154
+
155
+ /**
156
+ * A call's request as the conversation estimator weighs it (see measureAgentModelRequest), at
157
+ * `bytesPerToken`.
158
+ */
159
+ export function estimateAgentRequestTokens(
160
+ request: Pick<LanguageModelRequest, "messages" | "tools" | "responseFormat">,
161
+ bytesPerToken: number
162
+ ): number {
163
+ return agentContextSizeTokens(measureAgentModelRequest(request), bytesPerToken)
164
+ }
165
+
166
+ /** The events as they come, handing over the input tokens the provider counted once it says. */
167
+ async function* withCountedInput(
168
+ events: AsyncIterable<LanguageModelStreamEvent>,
169
+ counted: (inputTokens: number) => void
170
+ ): AsyncIterable<LanguageModelStreamEvent> {
171
+ for await (const event of events) {
172
+ const inputTokens = event.type === "finish" ? event.usage.inputTokens : undefined
173
+ if (inputTokens !== undefined && inputTokens > 0) counted(inputTokens)
174
+
175
+ yield event
176
+ }
177
+ }