@sixb/agent 0.2.1 → 0.2.3

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 (107) 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/board-previews.d.ts +41 -0
  6. package/dist/artifacts/board-previews.d.ts.map +1 -0
  7. package/dist/artifacts/layout-check/layout-check.d.ts +38 -6
  8. package/dist/artifacts/layout-check/layout-check.d.ts.map +1 -1
  9. package/dist/artifacts/layout-check/overview.d.ts +17 -0
  10. package/dist/artifacts/layout-check/overview.d.ts.map +1 -0
  11. package/dist/artifacts/materialize.d.ts +56 -24
  12. package/dist/artifacts/materialize.d.ts.map +1 -1
  13. package/dist/artifacts/publish-tool.d.ts +35 -9
  14. package/dist/artifacts/publish-tool.d.ts.map +1 -1
  15. package/dist/background-commands.d.ts +95 -0
  16. package/dist/background-commands.d.ts.map +1 -0
  17. package/dist/background-notices.d.ts +31 -0
  18. package/dist/background-notices.d.ts.map +1 -0
  19. package/dist/computer-runner.d.ts +63 -2
  20. package/dist/computer-runner.d.ts.map +1 -1
  21. package/dist/context-compaction.d.ts +3 -0
  22. package/dist/context-compaction.d.ts.map +1 -1
  23. package/dist/execution-plan.d.ts +12 -2
  24. package/dist/execution-plan.d.ts.map +1 -1
  25. package/dist/index.d.ts +3 -1
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +11814 -8722
  28. package/dist/index.js.map +35 -23
  29. package/dist/login-shell.d.ts +16 -0
  30. package/dist/login-shell.d.ts.map +1 -0
  31. package/dist/run-child.d.ts +3 -0
  32. package/dist/run-child.d.ts.map +1 -1
  33. package/dist/run-conversation-turn.d.ts +6 -2
  34. package/dist/run-conversation-turn.d.ts.map +1 -1
  35. package/dist/run-environment.d.ts +12 -2
  36. package/dist/run-environment.d.ts.map +1 -1
  37. package/dist/run-sandbox.d.ts +23 -0
  38. package/dist/run-sandbox.d.ts.map +1 -1
  39. package/dist/sandbox-files.d.ts +19 -0
  40. package/dist/sandbox-files.d.ts.map +1 -1
  41. package/dist/subagent-tools.d.ts +3 -1
  42. package/dist/subagent-tools.d.ts.map +1 -1
  43. package/dist/tools/background.d.ts +50 -0
  44. package/dist/tools/background.d.ts.map +1 -0
  45. package/dist/tools/bash.d.ts +12 -4
  46. package/dist/tools/bash.d.ts.map +1 -1
  47. package/dist/tools/model-spec.d.ts +9 -2
  48. package/dist/tools/model-spec.d.ts.map +1 -1
  49. package/dist/tools/tool-files.d.ts.map +1 -1
  50. package/dist/tools/tool-outputs.d.ts +12 -2
  51. package/dist/tools/tool-outputs.d.ts.map +1 -1
  52. package/dist/tools/web-fetch/cache.d.ts +33 -0
  53. package/dist/tools/web-fetch/cache.d.ts.map +1 -0
  54. package/dist/tools/web-fetch/html-markdown.d.ts +25 -0
  55. package/dist/tools/web-fetch/html-markdown.d.ts.map +1 -0
  56. package/dist/tools/web-fetch/network.d.ts +55 -0
  57. package/dist/tools/web-fetch/network.d.ts.map +1 -0
  58. package/dist/tools/web-fetch/tool.d.ts +96 -0
  59. package/dist/tools/web-fetch/tool.d.ts.map +1 -0
  60. package/dist/tools/web-search.d.ts +40 -0
  61. package/dist/tools/web-search.d.ts.map +1 -0
  62. package/dist/types.d.ts +5 -4
  63. package/dist/types.d.ts.map +1 -1
  64. package/dist/workspace-instructions.d.ts +15 -0
  65. package/dist/workspace-instructions.d.ts.map +1 -0
  66. package/package.json +15 -5
  67. package/src/agent-prompt.ts +64 -5
  68. package/src/agent-runtime/preflight.ts +2 -1
  69. package/src/artifacts/board-previews.ts +218 -0
  70. package/src/artifacts/layout-check/check.cjs +304 -80
  71. package/src/artifacts/layout-check/layout-check.ts +123 -13
  72. package/src/artifacts/layout-check/overview.ts +291 -0
  73. package/src/artifacts/materialize.ts +181 -55
  74. package/src/artifacts/publish-tool.ts +459 -129
  75. package/src/background-commands.ts +573 -0
  76. package/src/background-notices.ts +178 -0
  77. package/src/computer-runner.ts +211 -9
  78. package/src/context-compaction.ts +4 -1
  79. package/src/execution-plan.ts +15 -2
  80. package/src/index.ts +4 -0
  81. package/src/login-shell.ts +18 -0
  82. package/src/run-child.ts +5 -0
  83. package/src/run-conversation-turn.ts +23 -4
  84. package/src/run-environment.ts +96 -17
  85. package/src/run-sandbox.ts +41 -0
  86. package/src/sandbox-api-context.ts +1 -1
  87. package/src/sandbox-files.ts +88 -1
  88. package/src/skills/sixb-artifacts/SKILL.md +48 -25
  89. package/src/skills/sixb-artifacts/canvas.md +140 -18
  90. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/canvas.json +1 -1
  91. package/src/skills/sixb-artifacts/page.md +1 -1
  92. package/src/skills/sixb-artifacts/references.md +15 -12
  93. package/src/skills/sixb-artifacts/sheet.md +1 -1
  94. package/src/skills/sixb-artifacts/slides.md +1 -1
  95. package/src/subagent-tools.ts +19 -7
  96. package/src/tools/background.ts +127 -0
  97. package/src/tools/bash.ts +80 -11
  98. package/src/tools/model-spec.ts +28 -5
  99. package/src/tools/tool-files.ts +3 -1
  100. package/src/tools/tool-outputs.ts +46 -6
  101. package/src/tools/web-fetch/cache.ts +91 -0
  102. package/src/tools/web-fetch/html-markdown.ts +479 -0
  103. package/src/tools/web-fetch/network.ts +452 -0
  104. package/src/tools/web-fetch/tool.ts +619 -0
  105. package/src/tools/web-search.ts +139 -0
  106. package/src/types.ts +5 -4
  107. package/src/workspace-instructions.ts +163 -0
@@ -8,6 +8,7 @@ import {
8
8
  import { createSixbError } from "@sixb/core/internal/errors"
9
9
  import { ModelUsageRecordingError } from "@sixb/core/internal/model-execution"
10
10
  import { isAbortError } from "@sixb/core/internal/workers"
11
+ import type { SandboxNetworkPolicy } from "@sixb/core/sandboxes"
11
12
  import type {
12
13
  AgentRunRecord,
13
14
  AgentThreadParticipantRecord,
@@ -49,8 +50,15 @@ export interface ConversationTurnRunner {
49
50
  readonly execution: ExecutionRecord
50
51
  readonly thread: AgentThreadRecord | null
51
52
  }): OpenRunSandbox
52
- /** Run a child the turn spawned or continues, beside the turn, on the turn's mailbox. */
53
- startChild(run: SubagentRunRecord, family: FamilyMailbox): void
53
+ /**
54
+ * Run a child the turn spawned or continues, beside the turn, on the turn's mailbox, its
55
+ * `web_fetch` following the network the turn's sandbox declared.
56
+ */
57
+ startChild(
58
+ run: SubagentRunRecord,
59
+ family: FamilyMailbox,
60
+ networkPolicy: SandboxNetworkPolicy | undefined
61
+ ): void
54
62
  /** A sandbox teardown that outlives the turn: the runner waits for it before it stops. */
55
63
  onDetachedTeardown(teardown: Promise<void>): void
56
64
  /** A turn that failed: the runner reports it, once its end is recorded. */
@@ -96,7 +104,15 @@ export async function runConversationTurn(input: {
96
104
  runner.settings,
97
105
  run,
98
106
  session,
99
- (child, family) => runner.startChild(child, family)
107
+ (child, family) => {
108
+ // Children start from the turn's tools, once its environment holds its sandbox.
109
+ if (!environment) {
110
+ throw new Error(
111
+ `[SixbAgent] Agent run '${run.id}' started a sub-agent before its sandbox.`
112
+ )
113
+ }
114
+ runner.startChild(child, family, environment.networkPolicy)
115
+ }
100
116
  )
101
117
  const frameworkTools = await delegation.createTools()
102
118
  environment = await createConversationAgentEnvironment({
@@ -204,7 +220,10 @@ async function prepareConversationTurn(
204
220
  const turn = await session.context()
205
221
  const { thread, execution, participants } = turn
206
222
  const runPlan = await session.plan()
207
- const plan = resolveRunPlan(runPlan, { model: await session.models.language(runPlan.model) })
223
+ const plan = resolveRunPlan(runPlan, {
224
+ model: await session.models.language(runPlan.model),
225
+ recordedModel: await session.models.language(runPlan.model, { measures: false }),
226
+ })
208
227
  // A turn's plan always carries it; only a child's goes without.
209
228
  if (!runPlan.delegation) {
210
229
  throw createSixbError(
@@ -3,6 +3,7 @@ import type { Principal } from "@sixb/core"
3
3
  import {
4
4
  type AgentContextBudget,
5
5
  type AgentRunArtifacts,
6
+ type AgentRunModels,
6
7
  type AgentRunSession,
7
8
  type AgentSystemPromptSize,
8
9
  type AgentToolCallFile,
@@ -13,6 +14,7 @@ import {
13
14
  import type { RenderedOntologyDocs } from "@sixb/core/internal/ontology"
14
15
  import type { WorkflowIOSnapshot } from "@sixb/core/internal/workflows"
15
16
  import type { ModelTool } from "@sixb/core/models"
17
+ import type { SandboxNetworkPolicy } from "@sixb/core/sandboxes"
16
18
  import type {
17
19
  AgentContextCheckpointReason,
18
20
  AgentMessageRecord,
@@ -31,7 +33,7 @@ import {
31
33
  import { assertAgentRuntimeProfile } from "./agent-runtime/preflight"
32
34
  import {
33
35
  type InstalledArtifacts,
34
- installArtifactsPublishedBy,
36
+ installTurnArtifacts,
35
37
  type MaterializedArtifacts,
36
38
  materializeThreadArtifacts,
37
39
  } from "./artifacts/materialize"
@@ -41,6 +43,8 @@ import {
41
43
  type PreparedAgentAttachmentContext,
42
44
  prepareAgentAttachments,
43
45
  } from "./attachments"
46
+ import { BackgroundCommands } from "./background-commands"
47
+ import { BackgroundNotices, backgroundCommandsLeftRunning } from "./background-notices"
44
48
  import { prepareHandedFiles } from "./child-files"
45
49
  import {
46
50
  type AgentThreadCompactionInput,
@@ -59,7 +63,12 @@ import type { ResolvedAgentExecutionPlan } from "./execution-plan"
59
63
  import { InlineImageBudget } from "./inline-images"
60
64
  import { type ConversationReaders, conversationAuthors } from "./message-authors"
61
65
  import { type AgentErrorDetails, type AgentToolCaller, projectModelTools } from "./model-adapters"
62
- import type { AcquiredRunSandbox, BeforeFinalizeOptions, RunSandbox } from "./run-sandbox"
66
+ import {
67
+ type AcquiredRunSandbox,
68
+ acquireRunSandbox,
69
+ type BeforeFinalizeOptions,
70
+ type RunSandbox,
71
+ } from "./run-sandbox"
63
72
  import {
64
73
  AGENT_ARTIFACTS_DIRECTORY,
65
74
  AGENT_ARTIFACTS_MANIFEST,
@@ -78,8 +87,9 @@ import {
78
87
  } from "./subagent-context"
79
88
  import type { SubagentHistory } from "./subagent-continuation"
80
89
  import { agentThreadModelContext, type LoadedAgentThreadModelContext } from "./thread-context"
90
+ import { createBashOutputTool, createBashStopTool } from "./tools/background"
81
91
  import { createBashTool } from "./tools/bash"
82
- import { agentModelToolSpecs } from "./tools/model-spec"
92
+ import { agentModelToolSpecs, fetchesWeb } from "./tools/model-spec"
83
93
  import { createReadTool } from "./tools/read"
84
94
  import {
85
95
  AgentToolResultMediaBridge,
@@ -94,6 +104,8 @@ import {
94
104
  ToolOutputFiles,
95
105
  } from "./tools/tool-outputs"
96
106
  import { createViewFileTool, VIEW_FILE_TOOL_SPEC } from "./tools/view-file"
107
+ import { createWebFetchTool } from "./tools/web-fetch/tool"
108
+ import { createWebSearchTool } from "./tools/web-search"
97
109
  import type { AgentTurnRuntime } from "./turn-runtime"
98
110
  import type { AgentExecutionContext, AgentRunFiles, AgentTurnContext } from "./types"
99
111
  import { prepareWorkflowInputAttachments } from "./workflow-input-attachments"
@@ -120,6 +132,8 @@ export interface ConversationAgentExecutionEnvironment extends AgentExecutionEnv
120
132
  }) => Promise<ConversationRequest | undefined>
121
133
  /** The bytes per token the preflight measured the history at, which the turn's calls go by. */
122
134
  readonly bytesPerToken?: number
135
+ /** The network its sandbox declared, which `web_fetch` follows: its children's too. */
136
+ readonly networkPolicy?: SandboxNetworkPolicy
123
137
  }
124
138
 
125
139
  /**
@@ -188,6 +202,11 @@ export interface CreateSubagentEnvironmentInput extends CreateAgentEnvironmentIn
188
202
  readonly frameworkTools?: readonly ModelTool[]
189
203
  /** Weigh the thread before the first call, and compact it on the child's thread when needed. */
190
204
  readonly preflight?: { readonly budget: AgentContextBudget; readonly runtime: AgentTurnRuntime }
205
+ /**
206
+ * The network its parent's `web_fetch` follows, which the child's follows too: a child's blank
207
+ * sandbox declares none, and would otherwise read any URL.
208
+ */
209
+ readonly parentNetworkPolicy?: SandboxNetworkPolicy
191
210
  }
192
211
 
193
212
  export interface SubagentAgentExecutionEnvironment extends AgentExecutionEnvironment {
@@ -213,6 +232,8 @@ export interface CreateWorkflowAgentNodeEnvironmentInput extends CreateAgentEnvi
213
232
  readonly errorDetails: AgentErrorDetails
214
233
  /** How the step calls a project tool: it runs in the cloud, so in the worker's process. */
215
234
  readonly callTool: AgentToolCaller
235
+ /** How the step searches the web, recorded with its other model calls. */
236
+ readonly webSearch: AgentRunModels["webSearch"]
216
237
  }
217
238
 
218
239
  /** Prepare conversation history and attachments, then start the shared agent environment. */
@@ -235,7 +256,7 @@ export async function createConversationAgentEnvironment(
235
256
  let acquisition: Promise<AcquiredRunSandbox> | undefined
236
257
  let provisioning = false
237
258
  const acquire = () => {
238
- acquisition ??= sandbox.acquire()
259
+ acquisition ??= acquireRunSandbox(sandbox, sandboxSignal)
239
260
  return acquisition
240
261
  }
241
262
  // The prompt shows memory as of the thread's start or its latest compaction (see
@@ -314,7 +335,11 @@ export async function createConversationAgentEnvironment(
314
335
  systemPrompt: systemPrompt.text,
315
336
  systemPromptSize: systemPrompt,
316
337
  tools: [
317
- ...agentModelToolSpecs(plan.tools, { publishes: publishing !== undefined }),
338
+ ...agentModelToolSpecs(plan.tools, {
339
+ publishes: publishing !== undefined,
340
+ web: plan.web,
341
+ networkPolicy: sandbox.networkPolicy,
342
+ }),
318
343
  ...(input.frameworkTools ?? []),
319
344
  ],
320
345
  messages: conversationModelMessages({
@@ -335,6 +360,7 @@ export async function createConversationAgentEnvironment(
335
360
  plan,
336
361
  ontologyIndex: ontologyDocs.index,
337
362
  contextDirectory: sandbox.contextDirectory,
363
+ networkPolicy: sandbox.networkPolicy,
338
364
  run,
339
365
  ...(input.conversation === undefined ? {} : { conversation: input.conversation }),
340
366
  budget: preflight.budget,
@@ -380,10 +406,12 @@ export async function createConversationAgentEnvironment(
380
406
  ? { workspaceMovedAt: new Date(input.thread.movedAt).toISOString() }
381
407
  : {}),
382
408
  callTool: (call, options) => input.session.callTool(call, options),
409
+ webSearch: input.session.models.webSearch,
383
410
  ...(publishing ? { publishing } : {}),
384
411
  apiBaseUrl,
385
412
  attachmentContext,
386
413
  toolOutputs: savedToolOutputFiles(messages),
414
+ history: messages,
387
415
  imageBudget,
388
416
  ontologyDocs,
389
417
  frameworkTools: input.frameworkTools,
@@ -413,6 +441,7 @@ export async function createConversationAgentEnvironment(
413
441
  threadContext,
414
442
  ...(compactInTurn ? { compactInTurn } : {}),
415
443
  ...(prepared?.bytesPerToken === undefined ? {} : { bytesPerToken: prepared.bytesPerToken }),
444
+ ...(sandbox.networkPolicy ? { networkPolicy: sandbox.networkPolicy } : {}),
416
445
  }
417
446
  } catch (error) {
418
447
  // Preparation can fail before the worker receives this environment. Preserve here, before
@@ -450,7 +479,7 @@ export async function createSubagentEnvironment(
450
479
  let acquisition: Promise<AcquiredRunSandbox> | undefined
451
480
  let provisioning = false
452
481
  const acquire = () => {
453
- acquisition ??= sandbox.acquire()
482
+ acquisition ??= acquireRunSandbox(sandbox, input.signal)
454
483
  return acquisition
455
484
  }
456
485
 
@@ -492,6 +521,7 @@ async function startSubagentEnvironment(
492
521
  ): Promise<SubagentAgentExecutionEnvironment> {
493
522
  const { context, plan, run, conversation, sandbox, resumed, preflight } = input
494
523
  const signal = input.signal ?? NEVER_ABORTED_SIGNAL
524
+ const networkPolicy = input.parentNetworkPolicy ?? sandbox.networkPolicy
495
525
  // Still listed, as handed over, but never copied over what the child made of them.
496
526
  const files = resumed ? (run.spec.files ?? []) : subagentSandboxFiles(run, input.history.paused)
497
527
  const inlineImages = modelSupportsInlineImages(plan.model)
@@ -567,7 +597,11 @@ async function startSubagentEnvironment(
567
597
  threadContext,
568
598
  })
569
599
  const tools = [
570
- ...agentModelToolSpecs(plan.tools, { publishes: publishing !== undefined }),
600
+ ...agentModelToolSpecs(plan.tools, {
601
+ publishes: publishing !== undefined,
602
+ web: plan.web,
603
+ networkPolicy,
604
+ }),
571
605
  ...(input.frameworkTools ?? []),
572
606
  ]
573
607
  const childRequest: BuildConversationRequest = async ({ threadContext }) => {
@@ -638,6 +672,7 @@ async function startSubagentEnvironment(
638
672
  const environment = await startAgentEnvironment({
639
673
  mode: "subagent",
640
674
  sandbox,
675
+ ...(networkPolicy ? { networkPolicy } : {}),
641
676
  acquire: input.acquire,
642
677
  sandboxSignal: input.signal,
643
678
  context,
@@ -646,10 +681,12 @@ async function startSubagentEnvironment(
646
681
  parentRunId: run.parentRunId,
647
682
  threadId: conversationThreadId(input.thread),
648
683
  callTool: (call, options) => input.session.callTool(call, options),
684
+ webSearch: input.session.models.webSearch,
649
685
  ...(publishing ? { publishing } : {}),
650
686
  apiBaseUrl: context.apiBaseUrl,
651
687
  attachmentContext,
652
688
  toolOutputs: savedToolOutputFiles(threadContext.retainedMessages),
689
+ history: threadContext.retainedMessages,
653
690
  imageBudget,
654
691
  ontologyDocs: plan.ontologyDocs,
655
692
  ...(memory ? { memory } : {}),
@@ -721,6 +758,7 @@ export async function createWorkflowAgentNodeEnvironment(
721
758
  plan,
722
759
  runId: run.nodeRunId,
723
760
  callTool: input.callTool,
761
+ webSearch: input.webSearch,
724
762
  apiBaseUrl: context.apiBaseUrl,
725
763
  attachmentContext,
726
764
  // A step's inputs are files, never inline images: its own steps have the whole budget.
@@ -741,6 +779,8 @@ export async function createWorkflowAgentNodeEnvironment(
741
779
  interface AgentEnvironmentSetup
742
780
  extends Omit<CreateAgentEnvironmentInput, "signal" | "openSandbox"> {
743
781
  readonly sandbox: RunSandbox
782
+ /** The network `web_fetch` follows, when not the sandbox's own: a child's parent's. */
783
+ readonly networkPolicy?: SandboxNetworkPolicy
744
784
  /** How provisioning acquires the sandbox, when the run may have acquired it already. */
745
785
  readonly acquire?: () => Promise<AcquiredRunSandbox>
746
786
  /**
@@ -752,6 +792,8 @@ interface AgentEnvironmentSetup
752
792
  readonly failureSignal?: AbortSignal
753
793
  /** How the run calls a project tool. */
754
794
  readonly callTool: AgentToolCaller
795
+ /** How it searches the web, where the project is: `web_search` calls it. */
796
+ readonly webSearch: AgentRunModels["webSearch"]
755
797
  readonly actorId?: string
756
798
  readonly parentRunId?: string
757
799
  readonly mode: AgentExecutionMode
@@ -764,6 +806,8 @@ interface AgentEnvironmentSetup
764
806
  * name them: read from the store while the model starts, unless the sandbox holds them.
765
807
  */
766
808
  readonly toolOutputs?: readonly AgentToolCallFile[]
809
+ /** The history the run goes on from: the background commands it left running are told ended. */
810
+ readonly history?: readonly AgentMessageRecord[]
767
811
  /** What the history left of the request's inline image budget, which the run's steps take. */
768
812
  readonly imageBudget: InlineImageBudget
769
813
  /** Installed under `$SIXB_ONTOLOGY_DIR`; a workflow step's prompt does not list them. */
@@ -865,8 +909,35 @@ async function startAgentEnvironment(
865
909
  sandbox: resolveSandbox,
866
910
  blobStorage: context.blobStorage,
867
911
  })
912
+ // A computer's thread keeps its background commands across turns; a run's own stop as it ends.
913
+ const background = sandbox.background ?? new BackgroundCommands()
914
+ const stopBackground = async () => {
915
+ if (sandbox.background) return
916
+
917
+ await background.stopAll().catch((error: unknown) => {
918
+ console.error("[SixbAgent] Could not stop the run's background commands:", error)
919
+ })
920
+ }
868
921
  appendBuiltInTool(tools, createReadTool(resolveSandbox))
869
- appendBuiltInTool(tools, createBashTool(resolveSandbox))
922
+ appendBuiltInTool(tools, createBashTool(resolveSandbox, background))
923
+ appendBuiltInTool(tools, createBashOutputTool(resolveSandbox, background))
924
+ appendBuiltInTool(tools, createBashStopTool(resolveSandbox, background))
925
+ if (plan.web?.search) {
926
+ appendBuiltInTool(tools, createWebSearchTool({ search: input.webSearch, web: plan.web }))
927
+ }
928
+ const networkPolicy = input.networkPolicy ?? sandbox.networkPolicy
929
+ if (plan.web && fetchesWeb(plan.web, networkPolicy)) {
930
+ appendBuiltInTool(
931
+ tools,
932
+ createWebFetchTool({
933
+ web: plan.web,
934
+ network: sandbox.webNetwork ?? "server",
935
+ ...(networkPolicy ? { networkPolicy } : {}),
936
+ files: toolOutputFiles,
937
+ model: plan.recordedModel,
938
+ })
939
+ )
940
+ }
870
941
  let installedArtifacts: Promise<InstalledArtifacts> | undefined
871
942
  const { publishing } = input
872
943
  if (publishing) {
@@ -921,7 +992,10 @@ async function startAgentEnvironment(
921
992
  }
922
993
  ready.then(markSettled, markSettled)
923
994
 
924
- const dispose = () => disposeEnvironment(ready, () => settled, sandbox, input.onDetachedTeardown)
995
+ const dispose = async () => {
996
+ await stopBackground()
997
+ await disposeEnvironment(ready, () => settled, sandbox, input.onDetachedTeardown)
998
+ }
925
999
 
926
1000
  let systemPrompt: AgentSystemPromptSize
927
1001
  try {
@@ -946,8 +1020,11 @@ async function startAgentEnvironment(
946
1020
  throw error
947
1021
  }
948
1022
 
949
- const beforeFinalize = (options?: BeforeFinalizeOptions) =>
950
- sandbox.beforeFinalize?.(options) ?? Promise.resolve()
1023
+ // A workspace saved as the run ends keeps no command of it running.
1024
+ const beforeFinalize = async (options?: BeforeFinalizeOptions) => {
1025
+ await stopBackground()
1026
+ await sandbox.beforeFinalize?.(options)
1027
+ }
951
1028
  const artifacts =
952
1029
  publishing && installedArtifacts
953
1030
  ? { reader: publishing.artifacts, installed: installedArtifacts }
@@ -956,15 +1033,14 @@ async function startAgentEnvironment(
956
1033
  sandbox: resolveSandbox,
957
1034
  blobStorage: context.blobStorage,
958
1035
  budget: fileBudget,
959
- async installArtifactsFrom(runIds, signal) {
960
- if (!artifacts) return
1036
+ async installTurnArtifacts(signal) {
1037
+ if (!artifacts) return []
961
1038
 
962
- await installArtifactsPublishedBy({
1039
+ return installTurnArtifacts({
963
1040
  installed: await artifacts.installed,
964
1041
  artifacts: artifacts.reader,
965
1042
  blobStorage: context.blobStorage,
966
1043
  sandbox: (await ready).sandbox,
967
- runIds,
968
1044
  signal,
969
1045
  })
970
1046
  },
@@ -982,7 +1058,10 @@ async function startAgentEnvironment(
982
1058
  blobStorage: context.blobStorage,
983
1059
  apiBaseUrl,
984
1060
  attachmentContext,
985
- tools: toolOutputFiles.wrap(tools),
1061
+ tools: new BackgroundNotices(background, {
1062
+ ...(input.history ? { leftRunning: backgroundCommandsLeftRunning(input.history) } : {}),
1063
+ endedWith: sandbox.background ? "the sixb that ran it" : "the run that started it",
1064
+ }).wrap(toolOutputFiles.wrap(tools)),
986
1065
  outputFileOf: (toolCallId) => toolOutputFiles.fileOf(toolCallId),
987
1066
  prepareStep: mediaBridge.prepareStep,
988
1067
  systemPrompt: systemPrompt.text,
@@ -1133,7 +1212,7 @@ type ProvisionedRunSandbox = AcquiredRunSandbox & AgentSandboxHandle
1133
1212
 
1134
1213
  async function provisionSandbox(input: ProvisionSandboxInput): Promise<ProvisionedRunSandbox> {
1135
1214
  const { context, actorId, run, apiBaseUrl, skills, ontologyFiles } = input
1136
- const acquired = await (input.acquire?.() ?? input.sandbox.acquire())
1215
+ const acquired = await (input.acquire?.() ?? acquireRunSandbox(input.sandbox, input.signal))
1137
1216
  const { sandbox } = acquired
1138
1217
  const { contextDirectory } = input.sandbox
1139
1218
  try {
@@ -1,5 +1,9 @@
1
1
  import type { Sandbox } from "@sixb/core"
2
+ import type { SandboxNetworkPolicy } from "@sixb/core/sandboxes"
2
3
  import type { AgentWorkspacePromptContext } from "./agent-prompt"
4
+ import type { BackgroundCommands } from "./background-commands"
5
+ import type { WebFetchNetwork } from "./tools/web-fetch/network"
6
+ import { readWorkspaceInstructions } from "./workspace-instructions"
3
7
 
4
8
  /**
5
9
  * Where a provider's sandbox keeps a run's files: in its working directory, which a Git checkout
@@ -42,6 +46,20 @@ export interface RunSandbox {
42
46
  * names it: relative to the working directory, or absolute.
43
47
  */
44
48
  readonly contextDirectory: string
49
+ /**
50
+ * The background commands the run's tools start and see, when they outlive the run: a
51
+ * computer's thread keeps them across its turns, and its runner stops them. Absent, the run has
52
+ * its own, stopped as it ends.
53
+ */
54
+ readonly background?: BackgroundCommands
55
+ /**
56
+ * The network policy the project declared for the sandbox, which `web_fetch` follows: only the
57
+ * origins a `restricted` one lists, and no tool for `none`. Absent, as for a blank sandbox: any
58
+ * URL.
59
+ */
60
+ readonly networkPolicy?: SandboxNetworkPolicy
61
+ /** Where `web_fetch` reads pages from. Absent: Sixb's servers. */
62
+ readonly webNetwork?: WebFetchNetwork
45
63
  /** Called once, when the run environment starts. */
46
64
  acquire(): Promise<AcquiredRunSandbox>
47
65
  /**
@@ -61,3 +79,26 @@ export interface BeforeFinalizeOptions {
61
79
  */
62
80
  readonly discard?: boolean
63
81
  }
82
+
83
+ /**
84
+ * Acquire a run's sandbox. A workspace the prompt describes comes with the instruction files it
85
+ * carries, read once here: every request of the run then renders the same prompt, and so does the
86
+ * next run while the files stay as they are.
87
+ */
88
+ export async function acquireRunSandbox(
89
+ sandbox: RunSandbox,
90
+ signal?: AbortSignal
91
+ ): Promise<AcquiredRunSandbox> {
92
+ const acquired = await sandbox.acquire()
93
+ const { promptContext } = acquired
94
+ if (!sandbox.waitBeforeModel || !promptContext) return acquired
95
+
96
+ const instructions = await readWorkspaceInstructions(
97
+ acquired.sandbox,
98
+ promptContext.workingDirectory,
99
+ signal
100
+ )
101
+ if (instructions.length === 0) return acquired
102
+
103
+ return { ...acquired, promptContext: { ...promptContext, instructions } }
104
+ }
@@ -100,7 +100,7 @@ export async function prepareAgentSandboxApiContext(
100
100
  )
101
101
 
102
102
  // A persistent workspace keeps what earlier runs installed: each artifact's copy must hold exactly
103
- // the version installed now, never a file only an older version had.
103
+ // the revision installed now, never a file only an older one had.
104
104
  if (input.artifacts) {
105
105
  const cleared = await input.sandbox.runCommand(
106
106
  "bash",
@@ -1,5 +1,6 @@
1
1
  import { posix } from "node:path"
2
2
  import type { CommandResult } from "@sixb/core"
3
+ import { loginShellArgs } from "./login-shell"
3
4
  import { type AgentSandboxHandle, contextPath } from "./sandbox-handle"
4
5
 
5
6
  // Every read of sandbox files the worker makes goes through these two scripts. A sandbox has no
@@ -186,6 +187,58 @@ export async function readSandboxFile(
186
187
  return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)
187
188
  }
188
189
 
190
+ /** One file of {@link readSandboxFiles}: its bytes, or why it could not be read. */
191
+ export type SandboxFileRead =
192
+ | { readonly path: string; readonly bytes: Uint8Array }
193
+ | { readonly path: string; readonly error: SandboxFileErrorReason }
194
+
195
+ /**
196
+ * Read many regular files in one command, with the checks {@link readSandboxFile} makes on each.
197
+ * A file that fails is reported in its place and the others are read: one per path, in order.
198
+ * Everything comes back on one stdout, so keep the files' total to what a command prints.
199
+ */
200
+ export async function readSandboxFiles(
201
+ handle: AgentSandboxHandle,
202
+ input: SandboxCommandOptions & {
203
+ /** Absolute paths, as `resolveSandboxPath` returns them. */
204
+ readonly paths: readonly string[]
205
+ /** The most each file may hold. */
206
+ readonly maxBytes: number
207
+ }
208
+ ): Promise<SandboxFileRead[]> {
209
+ if (input.paths.length === 0) return []
210
+
211
+ const result = await runScript(handle, READ_SANDBOX_FILES_SCRIPT, input, {
212
+ SIXB_READ_PATHS: input.paths
213
+ .map((path) => Buffer.from(path, "utf-8").toString("base64"))
214
+ .join("\n"),
215
+ SIXB_READ_ROOTS: sandboxRoots(handle).join("\n"),
216
+ SIXB_READ_MAX_BYTES: String(input.maxBytes),
217
+ })
218
+ if (result.exitCode !== 0) {
219
+ throw new SandboxFileError(
220
+ "failed",
221
+ `files could not be read (${result.stderr.trim() || `exit ${result.exitCode}`})`
222
+ )
223
+ }
224
+
225
+ const lines = result.stdout.split("\n")
226
+ return input.paths.map((path, index) => {
227
+ const [status = "", size = "", data = ""] = (lines[index] ?? "").split("\t")
228
+ if (status !== "ok") {
229
+ return { path, error: isReadError(status) ? status : "failed" }
230
+ }
231
+
232
+ const bytes = Buffer.from(data, "base64")
233
+ if (bytes.byteLength !== Number(size)) return { path, error: "changed" }
234
+ return { path, bytes: new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength) }
235
+ })
236
+ }
237
+
238
+ function isReadError(status: string): status is SandboxFileErrorReason {
239
+ return status === "not_found" || status === "outside_root" || status === "too_large"
240
+ }
241
+
189
242
  /** What a path names once its symbolic links are followed. */
190
243
  export type SandboxPathEntry =
191
244
  | {
@@ -233,7 +286,7 @@ async function runScript(
233
286
  options: SandboxCommandOptions,
234
287
  env: Readonly<Record<string, string>>
235
288
  ): Promise<CommandResult> {
236
- const result = await handle.sandbox.runCommand("bash", ["-lc", script], {
289
+ const result = await handle.sandbox.runCommand("bash", loginShellArgs(script), {
237
290
  env: { ...(handle.env ?? {}), ...env },
238
291
  timeout: options.timeoutMs,
239
292
  signal: options.signal,
@@ -302,6 +355,40 @@ printf '%s\\n%s\\n' "$kind" "$(printf '%s' "$real" | base64 | tr -d '\\n')"`
302
355
 
303
356
  // Prints the file's size on the first line and its bytes as base64 on the second, so the caller
304
357
  // can tell a file that changed between the two reads.
358
+ // One line per path, in order: `ok<TAB>size<TAB>base64`, or the reason it was not read.
359
+ const READ_SANDBOX_FILES_SCRIPT = `# sixb-read-sandbox-files
360
+ set -uo pipefail
361
+ max_bytes="\${SIXB_READ_MAX_BYTES:?}"
362
+ real_roots=()
363
+ while IFS= read -r root; do
364
+ real_root="$(cd -P -- "$root" 2>/dev/null && pwd)" && real_roots+=("$real_root")
365
+ done <<< "\${SIXB_READ_ROOTS:?}"
366
+ while IFS= read -r encoded; do
367
+ requested="$(printf '%s' "$encoded" | base64 -d)"
368
+ if [ ! -f "$requested" ] || [ -L "$requested" ]; then
369
+ printf 'not_found\\n'
370
+ continue
371
+ fi
372
+ parent="$(cd -P -- "$(dirname -- "$requested")" && pwd)"
373
+ resolved="$parent/$(basename -- "$requested")"
374
+ inside=0
375
+ for real_root in "\${real_roots[@]}"; do
376
+ case "$resolved" in "$real_root"/*) inside=1 ;; esac
377
+ done
378
+ if [ "$inside" != 1 ]; then
379
+ printf 'outside_root\\n'
380
+ continue
381
+ fi
382
+ size="$(wc -c < "$resolved" | tr -d ' ')"
383
+ if [ "$size" -gt "$max_bytes" ]; then
384
+ printf 'too_large\\n'
385
+ continue
386
+ fi
387
+ printf 'ok\\t%s\\t' "$size"
388
+ head -c "$max_bytes" "$resolved" | base64 | tr -d '\\n'
389
+ printf '\\n'
390
+ done <<< "\${SIXB_READ_PATHS:?}"`
391
+
305
392
  const READ_SANDBOX_FILE_SCRIPT = `# sixb-read-sandbox-file
306
393
  set -euo pipefail
307
394
  requested="$(printf '%s' "\${SIXB_READ_PATH_B64:?}" | base64 -d)"