@sixb/agent 0.2.0 → 0.2.2

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 (76) hide show
  1. package/README.md +2 -1
  2. package/dist/agent-prompt.d.ts +13 -0
  3. package/dist/agent-prompt.d.ts.map +1 -1
  4. package/dist/agent-runtime/preflight.d.ts.map +1 -1
  5. package/dist/artifacts/layout-check/layout-check.d.ts.map +1 -1
  6. package/dist/background-commands.d.ts +95 -0
  7. package/dist/background-commands.d.ts.map +1 -0
  8. package/dist/background-notices.d.ts +31 -0
  9. package/dist/background-notices.d.ts.map +1 -0
  10. package/dist/computer-runner.d.ts +63 -2
  11. package/dist/computer-runner.d.ts.map +1 -1
  12. package/dist/context-compaction.d.ts +3 -0
  13. package/dist/context-compaction.d.ts.map +1 -1
  14. package/dist/execution-plan.d.ts +12 -2
  15. package/dist/execution-plan.d.ts.map +1 -1
  16. package/dist/index.d.ts +2 -1
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +2287 -230
  19. package/dist/index.js.map +28 -18
  20. package/dist/login-shell.d.ts +16 -0
  21. package/dist/login-shell.d.ts.map +1 -0
  22. package/dist/run-child.d.ts +3 -0
  23. package/dist/run-child.d.ts.map +1 -1
  24. package/dist/run-conversation-turn.d.ts +6 -2
  25. package/dist/run-conversation-turn.d.ts.map +1 -1
  26. package/dist/run-environment.d.ts +12 -2
  27. package/dist/run-environment.d.ts.map +1 -1
  28. package/dist/run-sandbox.d.ts +23 -0
  29. package/dist/run-sandbox.d.ts.map +1 -1
  30. package/dist/sandbox-files.d.ts.map +1 -1
  31. package/dist/tools/background.d.ts +50 -0
  32. package/dist/tools/background.d.ts.map +1 -0
  33. package/dist/tools/bash.d.ts +12 -4
  34. package/dist/tools/bash.d.ts.map +1 -1
  35. package/dist/tools/model-spec.d.ts +9 -2
  36. package/dist/tools/model-spec.d.ts.map +1 -1
  37. package/dist/tools/tool-outputs.d.ts +12 -2
  38. package/dist/tools/tool-outputs.d.ts.map +1 -1
  39. package/dist/tools/web-fetch/cache.d.ts +33 -0
  40. package/dist/tools/web-fetch/cache.d.ts.map +1 -0
  41. package/dist/tools/web-fetch/html-markdown.d.ts +25 -0
  42. package/dist/tools/web-fetch/html-markdown.d.ts.map +1 -0
  43. package/dist/tools/web-fetch/network.d.ts +55 -0
  44. package/dist/tools/web-fetch/network.d.ts.map +1 -0
  45. package/dist/tools/web-fetch/tool.d.ts +96 -0
  46. package/dist/tools/web-fetch/tool.d.ts.map +1 -0
  47. package/dist/tools/web-search.d.ts +40 -0
  48. package/dist/tools/web-search.d.ts.map +1 -0
  49. package/dist/workspace-instructions.d.ts +15 -0
  50. package/dist/workspace-instructions.d.ts.map +1 -0
  51. package/package.json +13 -4
  52. package/src/agent-prompt.ts +60 -1
  53. package/src/agent-runtime/preflight.ts +2 -1
  54. package/src/artifacts/layout-check/layout-check.ts +4 -4
  55. package/src/background-commands.ts +573 -0
  56. package/src/background-notices.ts +178 -0
  57. package/src/computer-runner.ts +211 -9
  58. package/src/context-compaction.ts +4 -1
  59. package/src/execution-plan.ts +15 -2
  60. package/src/index.ts +3 -0
  61. package/src/login-shell.ts +18 -0
  62. package/src/run-child.ts +5 -0
  63. package/src/run-conversation-turn.ts +23 -4
  64. package/src/run-environment.ts +92 -12
  65. package/src/run-sandbox.ts +41 -0
  66. package/src/sandbox-files.ts +2 -1
  67. package/src/tools/background.ts +127 -0
  68. package/src/tools/bash.ts +80 -11
  69. package/src/tools/model-spec.ts +25 -3
  70. package/src/tools/tool-outputs.ts +46 -6
  71. package/src/tools/web-fetch/cache.ts +91 -0
  72. package/src/tools/web-fetch/html-markdown.ts +479 -0
  73. package/src/tools/web-fetch/network.ts +452 -0
  74. package/src/tools/web-fetch/tool.ts +619 -0
  75. package/src/tools/web-search.ts +139 -0
  76. package/src/workspace-instructions.ts +163 -0
@@ -0,0 +1,178 @@
1
+ import { type AgentMessage, stableJsonStringify } from "@sixb/core"
2
+ import type { ModelTool } from "@sixb/core/models"
3
+ import type { BackgroundCommandState, BackgroundCommands } from "./background-commands"
4
+ import { BASH_OUTPUT_TOOL_SPEC, BASH_STOP_TOOL_SPEC } from "./tools/background"
5
+ import { BASH_TOOL_SPEC } from "./tools/bash"
6
+
7
+ /** A command's displayed form in a notice: its first line, cut. */
8
+ const NOTICE_COMMAND_CHARS = 80
9
+
10
+ /** The tools whose results report a background command's state. */
11
+ const STATE_TOOLS: ReadonlySet<string> = new Set([
12
+ BASH_TOOL_SPEC.name,
13
+ BASH_OUTPUT_TOOL_SPEC.name,
14
+ BASH_STOP_TOOL_SPEC.name,
15
+ ])
16
+
17
+ /** A notice's line that tells a command ended, and its id. */
18
+ const ENDED_LINE = /^Background command (\S+) \(`.*?`\) (?:exited with code|was stopped)/gm
19
+
20
+ /**
21
+ * How a run hears of its background commands without polling: a short notice closing the result
22
+ * of the first tool that returns after one ended, and, on its first, those of an earlier turn
23
+ * still running and those its history left running that ended with their run. A tool's result is
24
+ * what its message part keeps (`modelOutput`), so a later turn replays the notice where the model
25
+ * read it, byte for byte; no other request is touched.
26
+ */
27
+ export class BackgroundNotices {
28
+ /** What the run's first notice says of earlier runs, until it is taken. */
29
+ #earlier:
30
+ | {
31
+ readonly running: readonly string[]
32
+ readonly gone: readonly BackgroundCommandState[]
33
+ }
34
+ | undefined
35
+
36
+ /** What ended the commands of earlier runs that this run's do not know. */
37
+ readonly #endedWith: string
38
+
39
+ constructor(
40
+ private readonly commands: BackgroundCommands,
41
+ options: {
42
+ /** The commands the history last read as running ({@link backgroundCommandsLeftRunning}). */
43
+ readonly leftRunning?: readonly BackgroundCommandState[]
44
+ /** What ended those this run's commands do not know: the run, or the `sixb`, that ran them. */
45
+ readonly endedWith?: string
46
+ } = {}
47
+ ) {
48
+ this.#earlier = {
49
+ running: commands
50
+ .list()
51
+ .filter((command) => command.status === "running")
52
+ .map((command) => command.id),
53
+ gone: (options.leftRunning ?? []).filter((command) => !commands.has(command.id)),
54
+ }
55
+ this.#endedWith = options.endedWith ?? "the run that started it"
56
+ }
57
+
58
+ /** The notice due now, once: undefined when nothing is new. */
59
+ take(now = new Date()): string | undefined {
60
+ const earlier = this.#earlier
61
+ this.#earlier = undefined
62
+
63
+ const running = (earlier?.running ?? [])
64
+ .map((id) => this.commands.get(id))
65
+ .filter((command) => command.status === "running")
66
+ const lines = [
67
+ ...(earlier?.gone ?? []).map(
68
+ (command) =>
69
+ `Background command ${command.id} (\`${shortCommand(command.command)}\`) was stopped when ${this.#endedWith} ended; its output file is gone.`
70
+ ),
71
+ ...running.map((command) => runningLine(command, now)),
72
+ ...this.commands.takeEnded().map(endedLine),
73
+ ]
74
+ if (lines.length === 0) return undefined
75
+ return `<sixb_background_commands>\n${lines.join("\n")}\n</sixb_background_commands>`
76
+ }
77
+
78
+ /** The run's tools, each result closed by the notice due as it returns. */
79
+ wrap(tools: readonly ModelTool[]): ModelTool[] {
80
+ return tools.map((tool) => ({
81
+ ...tool,
82
+ toModelOutput: async (output, context) => {
83
+ const projected = tool.toModelOutput
84
+ ? await tool.toModelOutput(output, context)
85
+ : typeof output === "string"
86
+ ? { type: "text" as const, value: output }
87
+ : { type: "json" as const, value: output }
88
+ // An error result says nothing else: the notice waits for the next one.
89
+ if (projected.type !== "text" && projected.type !== "json") return projected
90
+
91
+ const notice = this.take()
92
+ if (notice === undefined) return projected
93
+
94
+ // Keys sorted, as providers print a JSON output; the bytes are kept as the model read them.
95
+ const text =
96
+ projected.type === "text" ? projected.value : stableJsonStringify(projected.value)
97
+ return { type: "text", value: `${text}\n\n${notice}` }
98
+ },
99
+ }))
100
+ }
101
+ }
102
+
103
+ /**
104
+ * The background commands a history last read as running: their tools reported them so, and no
105
+ * later result or notice said they ended. A run whose own commands do not know them is told they
106
+ * ended with the run, or the `sixb`, that ran them.
107
+ */
108
+ export function backgroundCommandsLeftRunning(
109
+ messages: readonly Pick<AgentMessage, "parts">[]
110
+ ): readonly BackgroundCommandState[] {
111
+ const running = new Map<string, BackgroundCommandState>()
112
+ for (const message of messages) {
113
+ for (const part of message.parts) {
114
+ if (part.type !== "tool-call" || part.state !== "output-available") continue
115
+
116
+ if (STATE_TOOLS.has(part.toolName) && isCommandState(part.output)) {
117
+ if (part.output.status === "running") running.set(part.output.id, part.output)
118
+ else running.delete(part.output.id)
119
+ }
120
+ if (part.modelOutput?.type === "text") {
121
+ for (const [, id] of part.modelOutput.value.matchAll(ENDED_LINE)) {
122
+ if (id !== undefined) running.delete(id)
123
+ }
124
+ }
125
+ }
126
+ }
127
+ return [...running.values()]
128
+ }
129
+
130
+ function isCommandState(value: unknown): value is BackgroundCommandState {
131
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false
132
+
133
+ const state = value as Record<string, unknown>
134
+ return (
135
+ typeof state.id === "string" &&
136
+ state.id.startsWith("bg_") &&
137
+ typeof state.command === "string" &&
138
+ typeof state.status === "string"
139
+ )
140
+ }
141
+
142
+ /** How an ended command reads in a notice. */
143
+ function endedLine(command: BackgroundCommandState): string {
144
+ const ran = formatDuration(
145
+ new Date(command.endedAt ?? command.startedAt).getTime() - new Date(command.startedAt).getTime()
146
+ )
147
+ const how =
148
+ command.status === "stopped"
149
+ ? "was stopped"
150
+ : `exited with code ${command.exitCode ?? "unknown"}`
151
+ return `Background command ${command.id} (\`${shortCommand(command.command)}\`) ${how} after ${ran}. Output: ${command.outputPath}`
152
+ }
153
+
154
+ /** How a command still running from an earlier turn reads in a notice. */
155
+ function runningLine(command: BackgroundCommandState, now: Date): string {
156
+ const since = formatDuration(now.getTime() - new Date(command.startedAt).getTime())
157
+ return `Background command ${command.id} (\`${shortCommand(command.command)}\`) is still running, started ${since} ago in an earlier turn. Output: ${command.outputPath}`
158
+ }
159
+
160
+ /** A command's display in a notice: its first line, cut. */
161
+ function shortCommand(command: string): string {
162
+ const line = command.trim().split("\n")[0] ?? ""
163
+ const cut = line.length > NOTICE_COMMAND_CHARS ? `${line.slice(0, NOTICE_COMMAND_CHARS)}…` : line
164
+ return cut + (command.trim().includes("\n") ? " …" : "")
165
+ }
166
+
167
+ /** `2m14s`, `850ms`. */
168
+ function formatDuration(ms: number): string {
169
+ if (ms < 1_000) return `${Math.max(0, Math.round(ms))}ms`
170
+
171
+ const seconds = Math.round(ms / 1_000)
172
+ const hours = Math.floor(seconds / 3_600)
173
+ const minutes = Math.floor((seconds % 3_600) / 60)
174
+ const rest = seconds % 60
175
+ if (hours > 0) return `${hours}h${String(minutes).padStart(2, "0")}m`
176
+ if (minutes > 0) return `${minutes}m${String(rest).padStart(2, "0")}s`
177
+ return `${rest}s`
178
+ }
@@ -1,5 +1,5 @@
1
- import { mkdir, realpath, rm } from "node:fs/promises"
2
- import { join } from "node:path"
1
+ import { mkdir, readdir, realpath, rm } from "node:fs/promises"
2
+ import { join, relative, sep } from "node:path"
3
3
  import type { Sandbox, SandboxRequestCredential } from "@sixb/core"
4
4
  import {
5
5
  AgentExecutionLostError,
@@ -11,6 +11,12 @@ import {
11
11
  } from "@sixb/core/internal/agents"
12
12
  import type { ConversationAgentRunRecord } from "@sixb/core/storage"
13
13
  import { delay } from "./abort"
14
+ import {
15
+ BACKGROUND_DIRECTORY,
16
+ type BackgroundCommandStatus,
17
+ BackgroundCommands,
18
+ stopLeftRunning,
19
+ } from "./background-commands"
14
20
  import { ChildRunner } from "./run-child"
15
21
  import { runConversationTurn } from "./run-conversation-turn"
16
22
  import { runApiCredential, runnerTokenFor, runTokenFor } from "./run-credential"
@@ -47,8 +53,9 @@ export interface ComputerRunnerOptions {
47
53
  readonly folder: string
48
54
  /**
49
55
  * 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.
56
+ * paths, emptied when a run starts and removed when it ends, but for the files of the thread's
57
+ * background commands. Shared by every runner on the computer, which hold a thread's directory
58
+ * one run at a time.
52
59
  */
53
60
  readonly runFilesRoot: string
54
61
  readonly openSandbox: OpenComputerSandbox
@@ -56,9 +63,40 @@ export interface ComputerRunnerOptions {
56
63
  readonly childCapacity?: number
57
64
  /** A run that failed, once its end is recorded. */
58
65
  readonly onFailure?: (error: unknown) => void
66
+ /**
67
+ * A background command started or ended: the computer's session reports
68
+ * {@link ComputerRunner.backgroundCommands} at once, so the web shows it.
69
+ */
70
+ readonly onBackgroundChange?: () => void
59
71
  readonly fetch?: (request: Request) => Promise<Response>
60
72
  }
61
73
 
74
+ /** A thread's background command, as the computer reports it to the web. */
75
+ export interface ComputerBackgroundCommand {
76
+ readonly threadId: string
77
+ /** `bg_<hex>`: unique in its thread while `sixb` stays open, with `startedAt` beyond. */
78
+ readonly id: string
79
+ /** Cut to {@link REPORTED_COMMAND_CHARS}. */
80
+ readonly command: string
81
+ readonly status: BackgroundCommandStatus
82
+ readonly exitCode?: number
83
+ /** ISO timestamps. */
84
+ readonly startedAt: string
85
+ readonly endedAt?: string
86
+ }
87
+
88
+ /** Which command a stop names: an id comes again once `sixb` restarts, its start does not. */
89
+ export interface ComputerBackgroundCommandRef {
90
+ readonly threadId: string
91
+ readonly id: string
92
+ readonly startedAt: string
93
+ }
94
+
95
+ /** How many commands the computer reports: the running ones, then the latest to end. */
96
+ const REPORTED_COMMANDS = 64
97
+ /** How much of each command it reports: the web shows the rest from the call. */
98
+ const REPORTED_COMMAND_CHARS = 1_000
99
+
62
100
  /** How far ahead a lease is held, and how often it is renewed: a renewal also hears a cancel. */
63
101
  const LEASE_MS = 60_000
64
102
  const RENEW_MS = 10_000
@@ -68,6 +106,11 @@ export class ComputerRunner {
68
106
  private readonly teardowns = new Set<Promise<void>>()
69
107
  /** Each running turn's renewal, by run id, to renew at once. */
70
108
  private readonly renewals = new Map<string, () => void>()
109
+ /**
110
+ * Each thread's background commands, by thread id: they outlive the turn that started them,
111
+ * until they end, the agent stops them or {@link stopBackgroundCommands}.
112
+ */
113
+ private readonly background = new Map<string, BackgroundCommands>()
71
114
 
72
115
  constructor(private readonly options: ComputerRunnerOptions) {}
73
116
 
@@ -127,10 +170,11 @@ export class ComputerRunner {
127
170
  projectId: run.projectId,
128
171
  folder: this.options.folder,
129
172
  }),
130
- startChild: (child, family) =>
173
+ startChild: (child, family, networkPolicy) =>
131
174
  children.start(child, {
132
175
  signal: turnSignal,
133
176
  family,
177
+ ...(networkPolicy ? { networkPolicy } : {}),
134
178
  leaseExpiresAt: lease,
135
179
  holdLease: async (childSession) => {
136
180
  held.add(childSession)
@@ -167,6 +211,59 @@ export class ComputerRunner {
167
211
  this.renewals.get(runId)?.()
168
212
  }
169
213
 
214
+ /** Whether a background command a turn started runs now. */
215
+ get runsBackgroundCommands(): boolean {
216
+ return [...this.background.values()].some((commands) => commands.running)
217
+ }
218
+
219
+ /**
220
+ * Stop every background command a turn left running, as `sixb` closes: the sandboxes kept for
221
+ * them are torn down then, which {@link drain} waits for.
222
+ */
223
+ async stopBackgroundCommands(): Promise<void> {
224
+ await Promise.all([...this.background.values()].map((commands) => commands.stopAll()))
225
+ }
226
+
227
+ /**
228
+ * Every thread's background commands while `sixb` stays open: the running ones, then the latest
229
+ * to end, {@link REPORTED_COMMANDS} at most.
230
+ */
231
+ backgroundCommands(): readonly ComputerBackgroundCommand[] {
232
+ const all = [...this.background].flatMap(([threadId, commands]) =>
233
+ commands.list().map(
234
+ (command): ComputerBackgroundCommand => ({
235
+ threadId,
236
+ id: command.id,
237
+ command: reportedCommand(command.command),
238
+ status: command.status,
239
+ ...(command.exitCode === undefined ? {} : { exitCode: command.exitCode }),
240
+ startedAt: command.startedAt,
241
+ ...(command.endedAt === undefined ? {} : { endedAt: command.endedAt }),
242
+ })
243
+ )
244
+ )
245
+ const running = all.filter((command) => command.status === "running")
246
+ const ended = all
247
+ .filter((command) => command.status !== "running")
248
+ .sort((a, b) => (b.endedAt ?? "").localeCompare(a.endedAt ?? ""))
249
+ return [...running, ...ended].slice(0, REPORTED_COMMANDS)
250
+ }
251
+
252
+ /**
253
+ * Stop a thread's background command, as someone asked from the web. False when it is not one
254
+ * this `sixb` runs: it ended already, or the id names a later command, after a restart.
255
+ */
256
+ async stopBackgroundCommand(ref: ComputerBackgroundCommandRef): Promise<boolean> {
257
+ const commands = this.background.get(ref.threadId)
258
+ const command = commands?.list().find((each) => each.id === ref.id)
259
+ if (!commands || command?.startedAt !== ref.startedAt || command.status !== "running") {
260
+ return false
261
+ }
262
+
263
+ await commands.stop(ref.id)
264
+ return true
265
+ }
266
+
170
267
  /** Wait for sandbox teardowns that outlived their runs. */
171
268
  async drain(): Promise<void> {
172
269
  await Promise.allSettled([...this.teardowns])
@@ -255,9 +352,18 @@ export class ComputerRunner {
255
352
  const folder = input.folder === undefined ? undefined : await realpath(input.folder)
256
353
  let held: (() => Promise<void>) | undefined
257
354
 
355
+ // A turn's background commands are its thread's, and so are their files, which every run
356
+ // of the thread keeps; a child's end with it.
357
+ const background = folder === undefined ? undefined : this.threadBackground(input.threadId)
358
+ const kept = () =>
359
+ background?.hasCommands ? join(runFiles, BACKGROUND_DIRECTORY) : undefined
360
+
258
361
  const sandbox: RunSandbox = {
259
362
  waitBeforeModel: folder !== undefined,
260
363
  contextDirectory: runFiles,
364
+ // The person's own machine: its pages leave from there, and its dev servers are readable.
365
+ webNetwork: "computer",
366
+ ...(background ? { background } : {}),
261
367
  acquire: async () => {
262
368
  const giveBack = await holdRunFiles({
263
369
  directory: runDirectory,
@@ -266,9 +372,20 @@ export class ComputerRunner {
266
372
  })
267
373
  held = giveBack
268
374
  try {
375
+ // What a sixb killed, or that crashed, left running is stopped before its files go.
376
+ if (background && folder !== undefined) {
377
+ await this.stopCommandsLeftRunning({
378
+ runFiles,
379
+ background,
380
+ folder,
381
+ credential,
382
+ signal,
383
+ })
384
+ }
385
+
269
386
  // 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 })
387
+ // one that crashed, left there, but its thread's background commands.
388
+ await emptyDirectory(runDirectory, kept())
272
389
  await mkdir(runFiles, { recursive: true })
273
390
  return {
274
391
  sandbox: await this.options.openSandbox({
@@ -288,8 +405,13 @@ export class ComputerRunner {
288
405
  },
289
406
  release: async ({ sandbox }) => {
290
407
  try {
291
- await sandbox.destroy()
292
- await rm(runDirectory, { recursive: true, force: true })
408
+ // A background command runs in the call that started it: its sandbox is torn down
409
+ // once the last one it runs ended.
410
+ const running = background?.endOf(sandbox)
411
+ if (running) this.track(running.then(() => sandbox.destroy()))
412
+ else await sandbox.destroy()
413
+
414
+ await emptyDirectory(runDirectory, kept())
293
415
  } finally {
294
416
  await held?.()
295
417
  }
@@ -299,6 +421,56 @@ export class ComputerRunner {
299
421
  }
300
422
  }
301
423
 
424
+ /**
425
+ * Stop the thread's commands a `sixb` killed, or that crashed, left running: their groups run
426
+ * on, re-parented, and this one knows them only by the pid files its run is about to remove.
427
+ * Done in a sandbox of its own, opened only when there are some; a failure is reported, and the
428
+ * run goes on.
429
+ */
430
+ private async stopCommandsLeftRunning(input: {
431
+ readonly runFiles: string
432
+ readonly background: BackgroundCommands
433
+ readonly folder: string
434
+ readonly credential: SandboxRequestCredential
435
+ readonly signal: AbortSignal
436
+ }): Promise<void> {
437
+ const directory = join(input.runFiles, BACKGROUND_DIRECTORY)
438
+ const pidFiles = (await readdir(directory).catch(() => []))
439
+ .filter((name) => name.endsWith(".pid") && !input.background.has(name.slice(0, -4)))
440
+ .sort()
441
+ .map((name) => join(directory, name))
442
+ if (pidFiles.length === 0) return
443
+
444
+ try {
445
+ const sandbox = await this.options.openSandbox({
446
+ workingDirectory: input.folder,
447
+ runFiles: input.runFiles,
448
+ credential: input.credential,
449
+ signal: input.signal,
450
+ })
451
+ try {
452
+ await stopLeftRunning(sandbox, pidFiles, input.signal)
453
+ } finally {
454
+ await sandbox.destroy()
455
+ }
456
+ } catch (error) {
457
+ console.warn(
458
+ `[SixbAgent] Could not stop the background commands a sixb that ended left running in ${directory}:`,
459
+ error
460
+ )
461
+ }
462
+ }
463
+
464
+ private threadBackground(threadId: string): BackgroundCommands {
465
+ let commands = this.background.get(threadId)
466
+ if (!commands) {
467
+ const { onBackgroundChange } = this.options
468
+ commands = new BackgroundCommands(onBackgroundChange ? { onChange: onBackgroundChange } : {})
469
+ this.background.set(threadId, commands)
470
+ }
471
+ return commands
472
+ }
473
+
302
474
  private track(teardown: Promise<void>): void {
303
475
  this.teardowns.add(teardown)
304
476
  void teardown.finally(() => this.teardowns.delete(teardown))
@@ -318,6 +490,36 @@ function threadDirectory(input: { readonly runId: string; readonly threadId: str
318
490
  return input.threadId
319
491
  }
320
492
 
493
+ /**
494
+ * Remove `directory`, or, with `keep`, everything in it but `keep` and the directories that lead
495
+ * to it.
496
+ */
497
+ export async function emptyDirectory(directory: string, keep?: string): Promise<void> {
498
+ const path = keep === undefined ? [] : relative(directory, keep).split(sep)
499
+ if (path.length === 0 || path[0] === "" || path[0] === "..") {
500
+ await rm(directory, { recursive: true, force: true })
501
+ return
502
+ }
503
+
504
+ let current = directory
505
+ for (const segment of path) {
506
+ const entries = await readdir(current).catch(() => [])
507
+ for (const entry of entries) {
508
+ if (entry !== segment) await rm(join(current, entry), { recursive: true, force: true })
509
+ }
510
+ current = join(current, segment)
511
+ }
512
+ }
513
+
514
+ /**
515
+ * A command cut to {@link REPORTED_COMMAND_CHARS}, never between an emoji's two halves: a lone half
516
+ * is no text Postgres stores, and each renewal reporting it would fail.
517
+ */
518
+ function reportedCommand(command: string): string {
519
+ const cut = command.slice(0, REPORTED_COMMAND_CHARS)
520
+ return /[\uD800-\uDBFF]$/.test(cut) ? cut.slice(0, -1) : cut
521
+ }
522
+
321
523
  function lease(): string {
322
524
  return new Date(Date.now() + LEASE_MS).toISOString()
323
525
  }
@@ -27,6 +27,7 @@ import {
27
27
  } from "@sixb/core/internal/model-execution"
28
28
  import type { OntologyDocsIndexEntry } from "@sixb/core/internal/ontology"
29
29
  import type { ModelCachingIntent, ModelMessage, ModelReasoning, ModelTool } from "@sixb/core/models"
30
+ import type { SandboxNetworkPolicy } from "@sixb/core/sandboxes"
30
31
  import type {
31
32
  AgentContextCheckpointReason,
32
33
  AgentContextCheckpointRecord,
@@ -156,6 +157,8 @@ interface ConversationCompactionInput
156
157
  readonly ontologyIndex?: readonly OntologyDocsIndexEntry[]
157
158
  /** Where the run's files go, as the prompt names them. */
158
159
  readonly contextDirectory: string
160
+ /** Its sandbox's declared network, which decides whether it has `web_fetch`. */
161
+ readonly networkPolicy?: SandboxNetworkPolicy
159
162
  /** Who can read the run's thread: in a shared one, who wrote what counts toward the estimate. */
160
163
  readonly conversation?: ConversationReaders
161
164
  readonly frameworkTools?: readonly ModelTool[]
@@ -375,7 +378,7 @@ function conversationEstimateShape(
375
378
  authors ? conversationAuthorsText(authors) : "",
376
379
  ].join("\n"),
377
380
  tools: contextEstimateTools([
378
- ...agentModelToolSpecs(plan.tools),
381
+ ...agentModelToolSpecs(plan.tools, { web: plan.web, networkPolicy: input.networkPolicy }),
379
382
  ...(input.frameworkTools ?? []),
380
383
  ]),
381
384
  }
@@ -2,6 +2,7 @@ import type { AgentReasoning, AgentSkillDefinition } from "@sixb/core"
2
2
  import type {
3
3
  AgentContextTokenRateSample,
4
4
  AgentRunPlan,
5
+ AgentRunWebPlan,
5
6
  AgentToolSpec,
6
7
  SandboxModel,
7
8
  } from "@sixb/core/internal/agents"
@@ -17,6 +18,12 @@ import { withBuiltInSkills } from "./skills/built-in"
17
18
  */
18
19
  export interface ResolvedAgentExecutionPlan {
19
20
  readonly model: LanguageModel
21
+ /**
22
+ * The same model as the run's session records each call, without the context budget `model`
23
+ * may add: a tool's side call (`web_fetch`'s question) is admitted and accounted with the run's
24
+ * calls, but never weighs on the run's context, nor measures its tokenizer.
25
+ */
26
+ readonly recordedModel: LanguageModel
20
27
  readonly reasoning?: AgentReasoning
21
28
  readonly instructions?: string
22
29
  /** The project tools it offers, as the model is offered them; they run where the project is. */
@@ -34,15 +41,18 @@ export interface ResolvedAgentExecutionPlan {
34
41
  readonly tokenRates?: readonly AgentContextTokenRateSample[]
35
42
  /** At most this many model calls. Absent: it runs until its model answers. */
36
43
  readonly maxSteps?: number
44
+ /** Its web tools. Absent: it has none. */
45
+ readonly web?: AgentRunWebPlan
37
46
  }
38
47
 
39
48
  /**
40
49
  * A turn's or a child's plan, with the session's model, which records each call itself, and the
41
- * harness's skills added. Its project tools run through the session.
50
+ * harness's skills added. Its project tools run through the session. `recordedModel` is the same
51
+ * model, its calls kept out of the run's tokenizer measure; absent, `model`.
42
52
  */
43
53
  export function resolveRunPlan(
44
54
  plan: AgentRunPlan,
45
- resolved: { readonly model: LanguageModel }
55
+ resolved: { readonly model: LanguageModel; readonly recordedModel?: LanguageModel }
46
56
  ): ResolvedAgentExecutionPlan {
47
57
  const {
48
58
  reasoning,
@@ -53,9 +63,11 @@ export function resolveRunPlan(
53
63
  ontologyDocs,
54
64
  tools,
55
65
  maxSteps,
66
+ web,
56
67
  } = plan
57
68
  return Object.freeze({
58
69
  model: resolved.model,
70
+ recordedModel: resolved.recordedModel ?? resolved.model,
59
71
  ontologyDocs,
60
72
  tokenRates: plan.tokenRates,
61
73
  ...(instructions === undefined ? {} : { instructions }),
@@ -66,5 +78,6 @@ export function resolveRunPlan(
66
78
  ...(locale === undefined ? {} : { locale }),
67
79
  ...(sandboxModels.length ? { sandboxModels } : {}),
68
80
  ...(maxSteps === undefined ? {} : { maxSteps }),
81
+ ...(web === undefined ? {} : { web }),
69
82
  })
70
83
  }
package/src/index.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  export { waitForAbort } from "./abort"
2
2
  export type { AgentWorkspacePromptContext } from "./agent-prompt"
3
3
  export { createAskParentTool } from "./ask-parent-tool"
4
+ export type { BackgroundCommandStatus } from "./background-commands"
4
5
  export {
6
+ type ComputerBackgroundCommand,
7
+ type ComputerBackgroundCommandRef,
5
8
  ComputerRunner,
6
9
  type ComputerRunnerOptions,
7
10
  type OpenComputerSandbox,
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Runs a script in a bash that is not a login shell, once a login shell has loaded the profile:
3
+ * the profile's exports reach the script, and its `exit` leaves the login shell alone.
4
+ *
5
+ * A login shell runs `~/.bash_logout` when the `exit` builtin ends it, with the script's options
6
+ * still set. Debian's and Ubuntu's default one runs `clear_console`, which fails without a
7
+ * terminal, so a script under `set -e` that ends with `exit 0` exits 1. `exec` replaces the login
8
+ * shell without running that file, and keeps its pid, so a background command's `$!` and process
9
+ * group are still the script's.
10
+ *
11
+ * Arguments: the script.
12
+ */
13
+ export const LOGIN_SHELL_SCRIPT = 'exec "$BASH" -c "$1" bash'
14
+
15
+ /** `bash` arguments that run `script` as {@link LOGIN_SHELL_SCRIPT} does. */
16
+ export function loginShellArgs(script: string): string[] {
17
+ return ["-lc", LOGIN_SHELL_SCRIPT, "bash", script]
18
+ }
package/src/run-child.ts CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  import { createSixbError } from "@sixb/core/internal/errors"
8
8
  import { ModelUsageRecordingError } from "@sixb/core/internal/model-execution"
9
9
  import { isAbortError } from "@sixb/core/internal/workers"
10
+ import type { SandboxNetworkPolicy } from "@sixb/core/sandboxes"
10
11
  import type {
11
12
  AgentRunRecord,
12
13
  AgentThreadRecord,
@@ -74,6 +75,8 @@ export interface ChildParent {
74
75
  holdLease(session: AgentRunSession<SubagentRunRecord>): Promise<() => void>
75
76
  /** The turn's mailbox, through which they talk. */
76
77
  readonly family: FamilyMailbox
78
+ /** The network the turn's `web_fetch` follows, which the child's follows too. */
79
+ readonly networkPolicy?: SandboxNetworkPolicy
77
80
  }
78
81
 
79
82
  interface RunningChild {
@@ -211,6 +214,7 @@ export class ChildRunner {
211
214
  thread,
212
215
  conversation,
213
216
  frameworkTools: [createAskParentTool(inbox)],
217
+ ...(parent.networkPolicy ? { parentNetworkPolicy: parent.networkPolicy } : {}),
214
218
  ...(execution.requestedBy === undefined ? {} : { requestedBy: execution.requestedBy }),
215
219
  history,
216
220
  signal: runtime.signal,
@@ -312,6 +316,7 @@ export class ChildRunner {
312
316
  const runPlan = await session.plan()
313
317
  const configured = resolveRunPlan(runPlan, {
314
318
  model: await session.models.language(runPlan.model),
319
+ recordedModel: await session.models.language(runPlan.model, { measures: false }),
315
320
  })
316
321
  const { model, budget, measuredBytesPerToken } = prepareAgentModel(configured)
317
322
  const plan = Object.freeze({ ...configured, model })