@sixb/agent 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) 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 +120 -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 +68 -0
  22. package/dist/attachments.d.ts.map +1 -0
  23. package/dist/child-files.d.ts +96 -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 +65 -0
  28. package/dist/computer-runner.d.ts.map +1 -0
  29. package/dist/context-budget.d.ts +28 -0
  30. package/dist/context-budget.d.ts.map +1 -0
  31. package/dist/context-compaction.d.ts +48 -0
  32. package/dist/context-compaction.d.ts.map +1 -0
  33. package/dist/conversation-memory.d.ts +21 -0
  34. package/dist/conversation-memory.d.ts.map +1 -0
  35. package/dist/errors.d.ts +46 -0
  36. package/dist/errors.d.ts.map +1 -0
  37. package/dist/execution-plan.d.ts +34 -0
  38. package/dist/execution-plan.d.ts.map +1 -0
  39. package/dist/failure.d.ts +14 -0
  40. package/dist/failure.d.ts.map +1 -0
  41. package/dist/family-mailbox.d.ts +60 -0
  42. package/dist/family-mailbox.d.ts.map +1 -0
  43. package/dist/file-ref.d.ts +6 -0
  44. package/dist/file-ref.d.ts.map +1 -0
  45. package/dist/image-attachments.d.ts +34 -0
  46. package/dist/image-attachments.d.ts.map +1 -0
  47. package/dist/index.d.ts +35 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +12168 -0
  50. package/dist/index.js.map +65 -0
  51. package/dist/message-authors.d.ts +34 -0
  52. package/dist/message-authors.d.ts.map +1 -0
  53. package/dist/message-times.d.ts +8 -0
  54. package/dist/message-times.d.ts.map +1 -0
  55. package/dist/model-adapters.d.ts +55 -0
  56. package/dist/model-adapters.d.ts.map +1 -0
  57. package/dist/model-lines.d.ts +16 -0
  58. package/dist/model-lines.d.ts.map +1 -0
  59. package/dist/requester.d.ts +15 -0
  60. package/dist/requester.d.ts.map +1 -0
  61. package/dist/run-agent-turn.d.ts +63 -0
  62. package/dist/run-agent-turn.d.ts.map +1 -0
  63. package/dist/run-child.d.ts +77 -0
  64. package/dist/run-child.d.ts.map +1 -0
  65. package/dist/run-conversation-turn.d.ts +42 -0
  66. package/dist/run-conversation-turn.d.ts.map +1 -0
  67. package/dist/run-credential.d.ts +22 -0
  68. package/dist/run-credential.d.ts.map +1 -0
  69. package/dist/run-environment.d.ts +115 -0
  70. package/dist/run-environment.d.ts.map +1 -0
  71. package/dist/run-fate.d.ts +15 -0
  72. package/dist/run-fate.d.ts.map +1 -0
  73. package/dist/run-sandbox.d.ts +60 -0
  74. package/dist/run-sandbox.d.ts.map +1 -0
  75. package/dist/run-subagent.d.ts +51 -0
  76. package/dist/run-subagent.d.ts.map +1 -0
  77. package/dist/run-workflow-agent-node.d.ts +41 -0
  78. package/dist/run-workflow-agent-node.d.ts.map +1 -0
  79. package/dist/sandbox-api-context.d.ts +34 -0
  80. package/dist/sandbox-api-context.d.ts.map +1 -0
  81. package/dist/sandbox-file-registry.d.ts +9 -0
  82. package/dist/sandbox-file-registry.d.ts.map +1 -0
  83. package/dist/sandbox-files.d.ts +71 -0
  84. package/dist/sandbox-files.d.ts.map +1 -0
  85. package/dist/sandbox-handle.d.ts +15 -0
  86. package/dist/sandbox-handle.d.ts.map +1 -0
  87. package/dist/sandbox-readiness.d.ts +8 -0
  88. package/dist/sandbox-readiness.d.ts.map +1 -0
  89. package/dist/skills/built-in.d.ts +15 -0
  90. package/dist/skills/built-in.d.ts.map +1 -0
  91. package/dist/subagent-continuation.d.ts +27 -0
  92. package/dist/subagent-continuation.d.ts.map +1 -0
  93. package/dist/subagent-inbox.d.ts +53 -0
  94. package/dist/subagent-inbox.d.ts.map +1 -0
  95. package/dist/subagent-tools.d.ts +282 -0
  96. package/dist/subagent-tools.d.ts.map +1 -0
  97. package/dist/thread-context.d.ts +12 -0
  98. package/dist/thread-context.d.ts.map +1 -0
  99. package/dist/tools/attachments.d.ts +11 -0
  100. package/dist/tools/attachments.d.ts.map +1 -0
  101. package/dist/tools/bash.d.ts +60 -0
  102. package/dist/tools/bash.d.ts.map +1 -0
  103. package/dist/tools/model-spec.d.ts +4 -0
  104. package/dist/tools/model-spec.d.ts.map +1 -0
  105. package/dist/tools/read.d.ts +43 -0
  106. package/dist/tools/read.d.ts.map +1 -0
  107. package/dist/tools/result-media.d.ts +22 -0
  108. package/dist/tools/result-media.d.ts.map +1 -0
  109. package/dist/tools/result-output.d.ts +18 -0
  110. package/dist/tools/result-output.d.ts.map +1 -0
  111. package/dist/tools/tool-files.d.ts +59 -0
  112. package/dist/tools/tool-files.d.ts.map +1 -0
  113. package/dist/tools/view-file.d.ts +40 -0
  114. package/dist/tools/view-file.d.ts.map +1 -0
  115. package/dist/tsconfig.json +5 -0
  116. package/dist/turn-runtime.d.ts +19 -0
  117. package/dist/turn-runtime.d.ts.map +1 -0
  118. package/dist/types.d.ts +76 -0
  119. package/dist/types.d.ts.map +1 -0
  120. package/dist/workflow-input-attachments.d.ts +18 -0
  121. package/dist/workflow-input-attachments.d.ts.map +1 -0
  122. package/package.json +59 -4
  123. package/src/abort.ts +40 -0
  124. package/src/agent-prompt.ts +758 -0
  125. package/src/agent-runtime/errors.ts +44 -0
  126. package/src/agent-runtime/preflight.ts +314 -0
  127. package/src/agent-runtime/profile.ts +23 -0
  128. package/src/artifacts/layout-check/check.cjs +478 -0
  129. package/src/artifacts/layout-check/layout-check.ts +460 -0
  130. package/src/artifacts/materialize.ts +380 -0
  131. package/src/artifacts/publish-tool.ts +700 -0
  132. package/src/ask-parent-tool.ts +100 -0
  133. package/src/attachments.ts +850 -0
  134. package/src/child-files.ts +540 -0
  135. package/src/child-questions.ts +42 -0
  136. package/src/computer-runner.ts +284 -0
  137. package/src/context-budget.ts +161 -0
  138. package/src/context-compaction.ts +529 -0
  139. package/src/conversation-memory.ts +45 -0
  140. package/src/errors.ts +85 -0
  141. package/src/execution-plan.ts +50 -0
  142. package/src/failure.ts +71 -0
  143. package/src/family-mailbox.ts +189 -0
  144. package/src/file-ref.ts +18 -0
  145. package/src/image-attachments.ts +322 -0
  146. package/src/index.ts +54 -0
  147. package/src/message-authors.ts +77 -0
  148. package/src/message-times.ts +21 -0
  149. package/src/model-adapters.ts +227 -0
  150. package/src/model-lines.ts +28 -0
  151. package/src/requester.ts +21 -0
  152. package/src/run-agent-turn.ts +347 -0
  153. package/src/run-child.ts +319 -0
  154. package/src/run-conversation-turn.ts +257 -0
  155. package/src/run-credential.ts +55 -0
  156. package/src/run-environment.ts +769 -0
  157. package/src/run-fate.ts +51 -0
  158. package/src/run-sandbox.ts +63 -0
  159. package/src/run-subagent.ts +347 -0
  160. package/src/run-workflow-agent-node.ts +270 -0
  161. package/src/sandbox-api-context.ts +234 -0
  162. package/src/sandbox-file-registry.ts +26 -0
  163. package/src/sandbox-files.ts +326 -0
  164. package/src/sandbox-handle.ts +19 -0
  165. package/src/sandbox-readiness.ts +22 -0
  166. package/src/skills/built-in.ts +183 -0
  167. package/src/skills/sixb-artifacts/SKILL.md +95 -0
  168. package/src/skills/sixb-artifacts/canvas.md +104 -0
  169. package/src/skills/sixb-artifacts/document.md +63 -0
  170. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/first-job.html +42 -0
  171. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/region.html +29 -0
  172. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/shared.css +35 -0
  173. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/welcome.html +31 -0
  174. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/canvas.json +107 -0
  175. package/src/skills/sixb-artifacts/examples/canvas/retro/canvas.json +158 -0
  176. package/src/skills/sixb-artifacts/examples/document/incident-report/document.md +35 -0
  177. package/src/skills/sixb-artifacts/examples/document/operations-review/document.md +41 -0
  178. package/src/skills/sixb-artifacts/examples/document/operations-review/figures/restorations.svg +1 -0
  179. package/src/skills/sixb-artifacts/examples/page/collections-desk/index.html +169 -0
  180. package/src/skills/sixb-artifacts/examples/page/collections-desk/queries/overdue.json +13 -0
  181. package/src/skills/sixb-artifacts/examples/page/dispatch-board/data/dispatch.json +234 -0
  182. package/src/skills/sixb-artifacts/examples/page/dispatch-board/index.html +245 -0
  183. package/src/skills/sixb-artifacts/examples/page/fleet-planner/data/plan.json +53 -0
  184. package/src/skills/sixb-artifacts/examples/page/fleet-planner/index.html +462 -0
  185. package/src/skills/sixb-artifacts/examples/page/service-explorer/data/service.json +276 -0
  186. package/src/skills/sixb-artifacts/examples/page/service-explorer/index.html +549 -0
  187. package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/queries/overdue.json +13 -0
  188. package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/workbook.json +30 -0
  189. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Inventory.csv +13 -0
  190. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Spend.csv +6 -0
  191. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/workbook.json +47 -0
  192. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Quarters.csv +5 -0
  193. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Regions.csv +5 -0
  194. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/workbook.json +78 -0
  195. package/src/skills/sixb-artifacts/examples/slides/launch-plan/index.html +63 -0
  196. package/src/skills/sixb-artifacts/examples/slides/q3-review/index.html +133 -0
  197. package/src/skills/sixb-artifacts/file.md +17 -0
  198. package/src/skills/sixb-artifacts/page.md +215 -0
  199. package/src/skills/sixb-artifacts/queries.md +66 -0
  200. package/src/skills/sixb-artifacts/references.md +68 -0
  201. package/src/skills/sixb-artifacts/sheet.md +223 -0
  202. package/src/skills/sixb-artifacts/slides.md +137 -0
  203. package/src/skills/sixb-memory/SKILL.md +68 -0
  204. package/src/skills/text-assets.d.ts +25 -0
  205. package/src/subagent-continuation.ts +51 -0
  206. package/src/subagent-inbox.ts +101 -0
  207. package/src/subagent-tools.ts +1609 -0
  208. package/src/thread-context.ts +25 -0
  209. package/src/tools/attachments.ts +28 -0
  210. package/src/tools/bash.ts +217 -0
  211. package/src/tools/model-spec.ts +22 -0
  212. package/src/tools/read.ts +262 -0
  213. package/src/tools/result-media.ts +147 -0
  214. package/src/tools/result-output.ts +44 -0
  215. package/src/tools/tool-files.ts +204 -0
  216. package/src/tools/view-file.ts +155 -0
  217. package/src/turn-runtime.ts +33 -0
  218. package/src/types.ts +79 -0
  219. package/src/workflow-input-attachments.ts +140 -0
@@ -0,0 +1,284 @@
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 type { RunSandbox } from "./run-sandbox"
19
+ import type { AgentRunSettings } from "./types"
20
+
21
+ // A turn on its owner's computer: claimed over HTTP as them, run in their folder, its children
22
+ // beside it. The API does everything a turn asks of its project; the computer runs its commands.
23
+
24
+ /** Opens the sandbox a computer's run works in. */
25
+ export type OpenComputerSandbox = (input: {
26
+ /** The user's folder, for a turn; absent for a child, which works in a folder of its own. */
27
+ readonly workingDirectory?: string
28
+ /** Where the run's own files go, outside the folder: its commands may write there too. */
29
+ readonly runFiles: string
30
+ /** The run's token, which the sandbox adds outside its commands. */
31
+ readonly credential: SandboxRequestCredential
32
+ readonly signal: AbortSignal
33
+ }) => Promise<Sandbox>
34
+
35
+ export interface ComputerRunnerOptions {
36
+ /** The project's API origin. */
37
+ readonly apiUrl: string
38
+ /** The user's own credential, as an `Authorization` header value, read for each claim. */
39
+ authorization(): Promise<string>
40
+ /**
41
+ * This computer's id, which each claim names: a thread runs on one of its owner's computers, and
42
+ * only that one claims its turns.
43
+ */
44
+ computerId(): Promise<string>
45
+ /** The folder the user's turns work in. */
46
+ readonly folder: string
47
+ /** Where each run's own files go, a directory per run, removed when the run ends. */
48
+ readonly runFilesRoot: string
49
+ readonly openSandbox: OpenComputerSandbox
50
+ /** How many children of one turn run at once. Defaults to 4. */
51
+ readonly childCapacity?: number
52
+ /** A run that failed, once its end is recorded. */
53
+ readonly onFailure?: (error: unknown) => void
54
+ readonly fetch?: (request: Request) => Promise<Response>
55
+ }
56
+
57
+ /** How far ahead a lease is held, and how often it is renewed: a renewal also hears a cancel. */
58
+ const LEASE_MS = 60_000
59
+ const RENEW_MS = 10_000
60
+ const CHILD_CLAIM_RETRIES = 5
61
+
62
+ export class ComputerRunner {
63
+ private readonly teardowns = new Set<Promise<void>>()
64
+ /** Each running turn's renewal, by run id, to renew at once. */
65
+ private readonly renewals = new Map<string, () => void>()
66
+
67
+ constructor(private readonly options: ComputerRunnerOptions) {}
68
+
69
+ /**
70
+ * Claim a queued turn and run it to its end. False when it was not this computer's to run: it
71
+ * ended already, or another runner holds it. `signal` stops the runner: the turn ends
72
+ * interrupted, its end recorded.
73
+ */
74
+ async runTurn(runId: string, signal: AbortSignal): Promise<boolean> {
75
+ const { apiUrl } = this.options
76
+ const fetch = this.options.fetch
77
+ const session = await claimAgentRunOverHttp({
78
+ apiUrl,
79
+ runId,
80
+ authorization: await this.options.authorization(),
81
+ computerId: await this.options.computerId(),
82
+ leaseExpiresAt: lease(),
83
+ ...(fetch === undefined ? {} : { fetch }),
84
+ })
85
+ if (!session) return false
86
+
87
+ const { run } = session
88
+ const turn: HttpAgentRunSessionInput<ConversationAgentRunRecord> = {
89
+ apiUrl,
90
+ runnerToken: runnerTokenFor({
91
+ projectId: run.projectId,
92
+ runId: run.id,
93
+ executionToken: session.executionToken,
94
+ }),
95
+ run,
96
+ ...(fetch === undefined ? {} : { fetch }),
97
+ }
98
+ const lost = new AbortController()
99
+ const held = new Set<AgentRunSession>([session])
100
+ const renewing = this.renew(held, session, lost)
101
+ this.renewals.set(run.id, renewing.now)
102
+ const turnSignal = AbortSignal.any([signal, lost.signal])
103
+ const settings = computerSettings(run.projectId, apiUrl)
104
+ const children = this.childRunner(turn, settings)
105
+
106
+ try {
107
+ await runConversationTurn({
108
+ session,
109
+ signal: turnSignal,
110
+ runner: {
111
+ settings,
112
+ openSandbox: () =>
113
+ this.sandbox({
114
+ runId: run.id,
115
+ executionToken: session.executionToken,
116
+ projectId: run.projectId,
117
+ folder: this.options.folder,
118
+ }),
119
+ startChild: (child, family) =>
120
+ children.start(child, {
121
+ signal: turnSignal,
122
+ family,
123
+ leaseExpiresAt: lease,
124
+ holdLease: async (childSession) => {
125
+ held.add(childSession)
126
+ try {
127
+ await childSession.renewLease(lease())
128
+ } catch (error) {
129
+ held.delete(childSession)
130
+ throw error
131
+ }
132
+ return () => held.delete(childSession)
133
+ },
134
+ }),
135
+ onDetachedTeardown: (teardown) => this.track(teardown),
136
+ reportFailure: (error) => this.options.onFailure?.(error),
137
+ },
138
+ })
139
+ } catch (error) {
140
+ // Stopped with its end recorded: nothing to release, as no queue holds it.
141
+ if (!turnSignal.aborted) throw error
142
+ } finally {
143
+ await children.stopChildrenOf(run.id)
144
+ this.renewals.delete(run.id)
145
+ renewing.stop()
146
+ await session.close()
147
+ }
148
+ return true
149
+ }
150
+
151
+ /**
152
+ * Renew a running turn's lease now rather than at its next renewal: its answer carries a cancel
153
+ * just asked for, so a stop from this computer takes effect at once.
154
+ */
155
+ renewNow(runId: string): void {
156
+ this.renewals.get(runId)?.()
157
+ }
158
+
159
+ /** Wait for sandbox teardowns that outlived their runs. */
160
+ async drain(): Promise<void> {
161
+ await Promise.allSettled([...this.teardowns])
162
+ }
163
+
164
+ /**
165
+ * Renew the turn's lease, and its children's, until stopped. A renewal answers a cancel; one
166
+ * that finds the turn no longer this computer's stops it.
167
+ */
168
+ private renew(
169
+ held: Set<AgentRunSession>,
170
+ turn: AgentRunSession,
171
+ lost: AbortController
172
+ ): { now(): void; stop(): void } {
173
+ const renew = () => {
174
+ for (const session of held) {
175
+ void session.renewLease(lease()).catch((error: unknown) => {
176
+ if (error instanceof AgentExecutionLostError) {
177
+ held.delete(session)
178
+ if (session === turn) lost.abort(error)
179
+ return
180
+ }
181
+ // A blip: the next renewal tries again, well before the lease runs out.
182
+ console.error(`[SixbAgent] Could not renew run '${session.run.id}'.`, error)
183
+ })
184
+ }
185
+ }
186
+ const timer = setInterval(renew, RENEW_MS)
187
+ return { now: renew, stop: () => clearInterval(timer) }
188
+ }
189
+
190
+ private childRunner(
191
+ turn: HttpAgentRunSessionInput<ConversationAgentRunRecord>,
192
+ settings: AgentRunSettings
193
+ ): ChildRunner {
194
+ return new ChildRunner({
195
+ settings,
196
+ capacity: this.options.childCapacity ?? 4,
197
+ claim: async (run, { leaseExpiresAt, stop }) => {
198
+ for (let retry = 0; ; retry += 1) {
199
+ try {
200
+ return await claimAgentRunChildOverHttp(turn, { childRunId: run.id, leaseExpiresAt })
201
+ } catch (error) {
202
+ if (error instanceof AgentRunRefusedError || error instanceof AgentExecutionLostError) {
203
+ return null
204
+ }
205
+ if (retry >= CHILD_CLAIM_RETRIES) throw error
206
+ }
207
+ if (stop.aborted) return null
208
+ await delay(1_000 * 2 ** retry, stop).catch(() => {})
209
+ if (stop.aborted) return null
210
+ }
211
+ },
212
+ openSandbox: ({ session }) =>
213
+ this.sandbox({
214
+ runId: session.run.id,
215
+ executionToken: session.executionToken,
216
+ projectId: session.run.projectId,
217
+ }),
218
+ onDetachedTeardown: (teardown) => this.track(teardown),
219
+ reportFailure: (error) => this.options.onFailure?.(error),
220
+ })
221
+ }
222
+
223
+ /**
224
+ * A run's sandbox: the user's folder for a turn, which the prompt describes, or a blank folder
225
+ * of its own for a child. Its own files go in a directory of their own, outside the folder.
226
+ */
227
+ private sandbox(input: {
228
+ readonly runId: string
229
+ readonly executionToken: string
230
+ readonly projectId: string
231
+ readonly folder?: string
232
+ }): OpenRunSandbox {
233
+ const { apiUrl } = this.options
234
+ const credential = runApiCredential(apiUrl, runTokenFor(input))
235
+ return async ({ signal }) => {
236
+ await mkdir(join(this.options.runFilesRoot, input.runId), { recursive: true })
237
+ // Real paths: the OS sandbox compares them, and the agent names files by them.
238
+ const runFiles = await realpath(join(this.options.runFilesRoot, input.runId))
239
+ const folder = input.folder === undefined ? undefined : await realpath(input.folder)
240
+ const sandbox: RunSandbox = {
241
+ waitBeforeModel: folder !== undefined,
242
+ contextDirectory: runFiles,
243
+ acquire: async () => ({
244
+ sandbox: await this.options.openSandbox({
245
+ ...(folder === undefined ? {} : { workingDirectory: folder }),
246
+ runFiles,
247
+ credential,
248
+ signal,
249
+ }),
250
+ ...(folder === undefined
251
+ ? {}
252
+ : { promptContext: { workingDirectory: folder, retention: "computer" as const } }),
253
+ }),
254
+ release: async ({ sandbox }) => {
255
+ await sandbox.destroy()
256
+ await rm(runFiles, { recursive: true, force: true })
257
+ },
258
+ }
259
+ return { sandbox }
260
+ }
261
+ }
262
+
263
+ private track(teardown: Promise<void>): void {
264
+ this.teardowns.add(teardown)
265
+ void teardown.finally(() => this.teardowns.delete(teardown))
266
+ }
267
+ }
268
+
269
+ function lease(): string {
270
+ return new Date(Date.now() + LEASE_MS).toISOString()
271
+ }
272
+
273
+ /** What a computer's runs share: the person at it sets the time zone and locale. */
274
+ function computerSettings(projectId: string, apiUrl: string): AgentRunSettings {
275
+ const { timeZone, locale } = Intl.DateTimeFormat().resolvedOptions()
276
+ return {
277
+ id: projectId,
278
+ apiBaseUrl: apiUrl,
279
+ subagentConcurrencyPerRun: 4,
280
+ keepsChildWorkspaces: false,
281
+ locale,
282
+ timeZone,
283
+ }
284
+ }
@@ -0,0 +1,161 @@
1
+ import { AgentDefinitionError } from "@sixb/core"
2
+ import {
3
+ defineLanguageModel,
4
+ type LanguageModel,
5
+ type LanguageModelDefinition,
6
+ type LanguageModelRequest,
7
+ type ModelReasoning,
8
+ } from "@sixb/core/models"
9
+
10
+ const DEFAULT_AGENT_CONTEXT_WINDOW_TOKENS = 128_000
11
+
12
+ export interface AgentContextBudget {
13
+ readonly windowTokens: number
14
+ readonly inputBudgetTokens: number
15
+ readonly reserveTokens: number
16
+ readonly keepRecentTokens: number
17
+ readonly source: "model" | "fallback"
18
+ }
19
+
20
+ interface AgentModelSelection {
21
+ readonly model: LanguageModel
22
+ readonly reasoning?: ModelReasoning
23
+ }
24
+
25
+ /**
26
+ * Derive the model's input and output budgets from its definition, and cap each call's output to
27
+ * them. The model comes pinned: whoever hands it over resolved it once for the run.
28
+ */
29
+ export function prepareAgentModel(selection: AgentModelSelection): {
30
+ readonly model: LanguageModel
31
+ readonly budget: AgentContextBudget
32
+ } {
33
+ const model = selection.model
34
+ const definition = defineLanguageModel(model.definition)
35
+ const budget = resolveAgentContextBudget(selection, definition)
36
+ if (budget.source === "fallback") {
37
+ console.warn(
38
+ `[SixbAgent] No context limit is available for '${model.providerId}/${model.modelId}'; using the ${DEFAULT_AGENT_CONTEXT_WINDOW_TOKENS.toLocaleString("en-US")}-token fallback.`
39
+ )
40
+ }
41
+ const maxOutputTokens = outputCapTokens(selection.model, definition) ?? budget.reserveTokens
42
+ if (
43
+ typeof selection.reasoning === "object" &&
44
+ selection.reasoning.budgetTokens >= maxOutputTokens
45
+ ) {
46
+ throw invalidBudget("output allowance must exceed the reasoning token budget.")
47
+ }
48
+ return {
49
+ budget,
50
+ model: Object.freeze({
51
+ providerId: model.providerId,
52
+ modelId: model.modelId,
53
+ definition: defineLanguageModel({ ...definition, maxOutputTokens }),
54
+ costEstimator: model.costEstimator,
55
+ ...(model.validateResponseFormat === undefined
56
+ ? {}
57
+ : { validateResponseFormat: model.validateResponseFormat.bind(model) }),
58
+ stream: (request: LanguageModelRequest) =>
59
+ model.stream({
60
+ ...request,
61
+ maxOutputTokens: Math.min(
62
+ request.maxOutputTokens ?? maxOutputTokens,
63
+ outputCeilingTokens(request, budget, maxOutputTokens)
64
+ ),
65
+ }),
66
+ }),
67
+ }
68
+ }
69
+
70
+ /**
71
+ * A call may write whatever its input leaves of the window, up to the cap. Compaction keeps the
72
+ * input within its budget, so the reserve is always left, and it is all a call gets when its input
73
+ * cannot be estimated.
74
+ */
75
+ function outputCeilingTokens(
76
+ request: LanguageModelRequest,
77
+ budget: AgentContextBudget,
78
+ capTokens: number
79
+ ): number {
80
+ const inputTokens = estimateRequestInputTokens(request)
81
+ if (inputTokens === undefined) return budget.reserveTokens
82
+ return Math.min(capTokens, Math.max(budget.reserveTokens, budget.windowTokens - inputTokens))
83
+ }
84
+
85
+ /**
86
+ * Serialized bytes at two per token. Gateway tokenizers measured from 2.8 (Hindi on GLM) to 12
87
+ * bytes per token, and an underestimate is the costly side: whenever the window bounds the ceiling,
88
+ * any input it misses overflows providers that reject input plus output beyond the window. Attached
89
+ * files have no byte-to-token rate.
90
+ */
91
+ function estimateRequestInputTokens(request: LanguageModelRequest): number | undefined {
92
+ const hasFile = request.messages.some(
93
+ (message) => message.role === "user" && message.content.some((part) => part.type === "file")
94
+ )
95
+ if (hasFile) return undefined
96
+ const serialized = JSON.stringify([request.messages, request.tools, request.responseFormat])
97
+ return Math.ceil(new TextEncoder().encode(serialized).byteLength / 2)
98
+ }
99
+
100
+ /** The most one call may write: the binding's limit, capped at the model maximum. */
101
+ function outputCapTokens(
102
+ binding: LanguageModel,
103
+ definition: LanguageModelDefinition
104
+ ): number | undefined {
105
+ if (binding.maxOutputTokens === undefined) return definition.maxOutputTokens
106
+ return Math.min(binding.maxOutputTokens, definition.maxOutputTokens ?? binding.maxOutputTokens)
107
+ }
108
+
109
+ /**
110
+ * Input-only limits are a conservative window: leave the same reserve without inventing a total.
111
+ * The reserve is the output every call is guaranteed, not its ceiling, so it stays small and a
112
+ * larger output limit never shrinks the input budget.
113
+ */
114
+ export function resolveAgentContextBudget(
115
+ selection: AgentModelSelection,
116
+ definition: LanguageModelDefinition = selection.model.definition
117
+ ): AgentContextBudget {
118
+ const modelWindow = definition.contextWindow ?? definition.maxInputTokens
119
+ const windowTokens = modelWindow ?? DEFAULT_AGENT_CONTEXT_WINDOW_TOKENS
120
+ const reserveTokens = Math.max(
121
+ Math.min(
122
+ 16_384,
123
+ Math.floor(windowTokens * 0.25),
124
+ outputCapTokens(selection.model, definition) ?? Number.POSITIVE_INFINITY
125
+ ),
126
+ typeof selection.reasoning === "object" ? selection.reasoning.budgetTokens + 1 : 0
127
+ )
128
+ assertPositiveSafeInteger(windowTokens, "windowTokens")
129
+ assertPositiveSafeInteger(reserveTokens, "reserveTokens")
130
+ if (reserveTokens >= windowTokens) {
131
+ throw invalidBudget("reserveTokens must be less than the resolved context window.")
132
+ }
133
+ const inputBudgetTokens = Math.min(
134
+ definition.maxInputTokens ?? Number.POSITIVE_INFINITY,
135
+ windowTokens - reserveTokens
136
+ )
137
+ assertPositiveSafeInteger(inputBudgetTokens, "inputBudgetTokens")
138
+ const keepRecentTokens = Math.min(20_000, Math.floor(inputBudgetTokens * 0.5))
139
+ assertPositiveSafeInteger(keepRecentTokens, "keepRecentTokens")
140
+ if (keepRecentTokens >= inputBudgetTokens) {
141
+ throw invalidBudget("keepRecentTokens must be less than the resolved input budget.")
142
+ }
143
+
144
+ return Object.freeze({
145
+ windowTokens,
146
+ inputBudgetTokens,
147
+ reserveTokens,
148
+ keepRecentTokens,
149
+ source: modelWindow === undefined ? "fallback" : "model",
150
+ })
151
+ }
152
+
153
+ function invalidBudget(message: string): AgentDefinitionError {
154
+ return new AgentDefinitionError(`[SixbAgent] Agent context ${message}`)
155
+ }
156
+
157
+ function assertPositiveSafeInteger(value: number, field: string): void {
158
+ if (!Number.isSafeInteger(value) || value <= 0) {
159
+ throw invalidBudget(`${field} must be a positive safe integer.`)
160
+ }
161
+ }