@sixb/agent 0.2.1 → 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
@@ -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,
@@ -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 }
@@ -982,7 +1059,10 @@ async function startAgentEnvironment(
982
1059
  blobStorage: context.blobStorage,
983
1060
  apiBaseUrl,
984
1061
  attachmentContext,
985
- tools: toolOutputFiles.wrap(tools),
1062
+ tools: new BackgroundNotices(background, {
1063
+ ...(input.history ? { leftRunning: backgroundCommandsLeftRunning(input.history) } : {}),
1064
+ endedWith: sandbox.background ? "the sixb that ran it" : "the run that started it",
1065
+ }).wrap(toolOutputFiles.wrap(tools)),
986
1066
  outputFileOf: (toolCallId) => toolOutputFiles.fileOf(toolCallId),
987
1067
  prepareStep: mediaBridge.prepareStep,
988
1068
  systemPrompt: systemPrompt.text,
@@ -1133,7 +1213,7 @@ type ProvisionedRunSandbox = AcquiredRunSandbox & AgentSandboxHandle
1133
1213
 
1134
1214
  async function provisionSandbox(input: ProvisionSandboxInput): Promise<ProvisionedRunSandbox> {
1135
1215
  const { context, actorId, run, apiBaseUrl, skills, ontologyFiles } = input
1136
- const acquired = await (input.acquire?.() ?? input.sandbox.acquire())
1216
+ const acquired = await (input.acquire?.() ?? acquireRunSandbox(input.sandbox, input.signal))
1137
1217
  const { sandbox } = acquired
1138
1218
  const { contextDirectory } = input.sandbox
1139
1219
  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
+ }
@@ -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
@@ -233,7 +234,7 @@ async function runScript(
233
234
  options: SandboxCommandOptions,
234
235
  env: Readonly<Record<string, string>>
235
236
  ): Promise<CommandResult> {
236
- const result = await handle.sandbox.runCommand("bash", ["-lc", script], {
237
+ const result = await handle.sandbox.runCommand("bash", loginShellArgs(script), {
237
238
  env: { ...(handle.env ?? {}), ...env },
238
239
  timeout: options.timeoutMs,
239
240
  signal: options.signal,
@@ -0,0 +1,127 @@
1
+ import { AgentToolPublicError } from "@sixb/core"
2
+ import type { JsonObject, JsonValue, ModelTool } from "@sixb/core/models"
3
+ import type { BackgroundCommandOutput, BackgroundCommands } from "../background-commands"
4
+ import { agentToolErrorText } from "../model-adapters"
5
+ import type { AgentSandboxHandle } from "../sandbox-handle"
6
+
7
+ /** The longest `bash_output` waits for a command to end. */
8
+ const MAX_WAIT_MS = 600_000
9
+
10
+ export const BASH_OUTPUT_TOOL_SPEC = {
11
+ name: "bash_output",
12
+ description:
13
+ "A background command's status (running, exited with its code, or stopped) and its output since your last read: the newest 20,000 bytes, the rest in its file. wait blocks until it ends, at most that many ms. You are told when one ends: do not poll.",
14
+ inputSchema: {
15
+ type: "object",
16
+ properties: {
17
+ id: { type: "string", description: "The id bash returned, like bg_3f9a1c." },
18
+ wait: {
19
+ type: "number",
20
+ description: "Milliseconds to wait for its end, up to 600000.",
21
+ },
22
+ },
23
+ required: ["id"],
24
+ additionalProperties: false,
25
+ } satisfies JsonObject,
26
+ } as const
27
+
28
+ export const BASH_STOP_TOOL_SPEC = {
29
+ name: "bash_stop",
30
+ description:
31
+ "Stop a background command and all it started: SIGTERM, then SIGKILL after 3 s. Returns its final status and output since your last read.",
32
+ inputSchema: {
33
+ type: "object",
34
+ properties: {
35
+ id: { type: "string", description: "The id bash returned, like bg_3f9a1c." },
36
+ },
37
+ required: ["id"],
38
+ additionalProperties: false,
39
+ } satisfies JsonObject,
40
+ } as const
41
+
42
+ interface BashOutputToolInput {
43
+ readonly id: string
44
+ readonly wait?: number
45
+ }
46
+
47
+ interface BashStopToolInput {
48
+ readonly id: string
49
+ }
50
+
51
+ /** `bash_output`: a background command's status and new output, after waiting when asked. */
52
+ export function createBashOutputTool(
53
+ resolveSandbox: () => Promise<AgentSandboxHandle>,
54
+ commands: BackgroundCommands
55
+ ): ModelTool<BashOutputToolInput> {
56
+ return {
57
+ ...BASH_OUTPUT_TOOL_SPEC,
58
+ parseInput: (value) => {
59
+ const input = parseInput(BASH_OUTPUT_TOOL_SPEC.name, value, ["id", "wait"])
60
+ if (input.wait !== undefined && (typeof input.wait !== "number" || input.wait < 0)) {
61
+ throw publicError(BASH_OUTPUT_TOOL_SPEC.name, "wait must be a number of milliseconds.")
62
+ }
63
+ return {
64
+ id: input.id as string,
65
+ ...(input.wait === undefined ? {} : { wait: Math.min(input.wait as number, MAX_WAIT_MS) }),
66
+ }
67
+ },
68
+ async execute(input, { signal }): Promise<JsonValue> {
69
+ commands.get(input.id)
70
+ if (input.wait) await commands.wait(input.id, input.wait, signal)
71
+
72
+ const output: BackgroundCommandOutput = await commands.read(
73
+ input.id,
74
+ await resolveSandbox(),
75
+ signal
76
+ )
77
+ return output as unknown as JsonValue
78
+ },
79
+ errorText: agentToolErrorText,
80
+ }
81
+ }
82
+
83
+ /** `bash_stop`: stop a background command, then report how it ended and its last output. */
84
+ export function createBashStopTool(
85
+ resolveSandbox: () => Promise<AgentSandboxHandle>,
86
+ commands: BackgroundCommands
87
+ ): ModelTool<BashStopToolInput> {
88
+ return {
89
+ ...BASH_STOP_TOOL_SPEC,
90
+ parseInput: (value) => ({
91
+ id: parseInput(BASH_STOP_TOOL_SPEC.name, value, ["id"]).id as string,
92
+ }),
93
+ async execute(input, { signal }): Promise<JsonValue> {
94
+ await commands.stop(input.id)
95
+
96
+ const output: BackgroundCommandOutput = await commands.read(
97
+ input.id,
98
+ await resolveSandbox(),
99
+ signal
100
+ )
101
+ return output as unknown as JsonValue
102
+ },
103
+ errorText: agentToolErrorText,
104
+ }
105
+ }
106
+
107
+ function parseInput(
108
+ tool: string,
109
+ value: unknown,
110
+ keys: readonly string[]
111
+ ): Record<string, unknown> & { readonly id: string } {
112
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
113
+ throw publicError(tool, "input must be an object.")
114
+ }
115
+ const input = value as Record<string, unknown>
116
+ for (const key of Object.keys(input)) {
117
+ if (!keys.includes(key)) throw publicError(tool, `input contains unknown property '${key}'.`)
118
+ }
119
+ if (typeof input.id !== "string" || !input.id) {
120
+ throw publicError(tool, "id must be a background command's id, such as bg_3f9a1c.")
121
+ }
122
+ return input as Record<string, unknown> & { readonly id: string }
123
+ }
124
+
125
+ function publicError(tool: string, message: string): AgentToolPublicError {
126
+ return new AgentToolPublicError(`[SixbAgent] ${tool} ${message}`)
127
+ }