@sixb/agent 0.2.5 → 0.2.7

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 (70) hide show
  1. package/dist/agent-prompt.d.ts +19 -3
  2. package/dist/agent-prompt.d.ts.map +1 -1
  3. package/dist/background-commands.d.ts +6 -2
  4. package/dist/background-commands.d.ts.map +1 -1
  5. package/dist/computer-runner.d.ts +12 -3
  6. package/dist/computer-runner.d.ts.map +1 -1
  7. package/dist/context-compaction.d.ts.map +1 -1
  8. package/dist/conversation-messages.d.ts +1 -1
  9. package/dist/conversation-messages.d.ts.map +1 -1
  10. package/dist/errors.d.ts +17 -2
  11. package/dist/errors.d.ts.map +1 -1
  12. package/dist/index.d.ts +2 -2
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +693 -365
  15. package/dist/index.js.map +25 -25
  16. package/dist/login-shell.d.ts +18 -2
  17. package/dist/login-shell.d.ts.map +1 -1
  18. package/dist/model-adapters.d.ts +7 -2
  19. package/dist/model-adapters.d.ts.map +1 -1
  20. package/dist/model-lines.d.ts +1 -0
  21. package/dist/model-lines.d.ts.map +1 -1
  22. package/dist/run-agent-turn.d.ts +0 -4
  23. package/dist/run-agent-turn.d.ts.map +1 -1
  24. package/dist/run-child.d.ts +21 -4
  25. package/dist/run-child.d.ts.map +1 -1
  26. package/dist/run-conversation-turn.d.ts +10 -4
  27. package/dist/run-conversation-turn.d.ts.map +1 -1
  28. package/dist/run-environment.d.ts +15 -6
  29. package/dist/run-environment.d.ts.map +1 -1
  30. package/dist/run-fate.d.ts +2 -2
  31. package/dist/run-fate.d.ts.map +1 -1
  32. package/dist/run-sandbox.d.ts +39 -1
  33. package/dist/run-sandbox.d.ts.map +1 -1
  34. package/dist/run-subagent.d.ts.map +1 -1
  35. package/dist/sandbox-api-context.d.ts.map +1 -1
  36. package/dist/subagent-continuation.d.ts +13 -4
  37. package/dist/subagent-continuation.d.ts.map +1 -1
  38. package/dist/subagent-tools.d.ts +29 -2
  39. package/dist/subagent-tools.d.ts.map +1 -1
  40. package/dist/tools/bash.d.ts +1 -1
  41. package/dist/tools/bash.d.ts.map +1 -1
  42. package/dist/tools/model-spec.d.ts +2 -1
  43. package/dist/tools/model-spec.d.ts.map +1 -1
  44. package/dist/types.d.ts +9 -0
  45. package/dist/types.d.ts.map +1 -1
  46. package/package.json +6 -6
  47. package/src/agent-prompt.ts +150 -42
  48. package/src/background-commands.ts +63 -19
  49. package/src/background-notices.ts +3 -2
  50. package/src/computer-runner.ts +135 -80
  51. package/src/context-compaction.ts +1 -0
  52. package/src/conversation-messages.ts +11 -4
  53. package/src/errors.ts +18 -2
  54. package/src/index.ts +7 -2
  55. package/src/login-shell.ts +30 -3
  56. package/src/model-adapters.ts +32 -4
  57. package/src/model-lines.ts +1 -1
  58. package/src/run-agent-turn.ts +25 -3
  59. package/src/run-child.ts +52 -5
  60. package/src/run-conversation-turn.ts +50 -12
  61. package/src/run-environment.ts +95 -24
  62. package/src/run-fate.ts +8 -2
  63. package/src/run-sandbox.ts +110 -1
  64. package/src/run-subagent.ts +17 -7
  65. package/src/sandbox-api-context.ts +7 -1
  66. package/src/subagent-continuation.ts +33 -7
  67. package/src/subagent-tools.ts +141 -27
  68. package/src/tools/bash.ts +10 -11
  69. package/src/tools/model-spec.ts +3 -3
  70. package/src/types.ts +9 -0
@@ -8,7 +8,6 @@ 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"
12
11
  import type {
13
12
  AgentRunRecord,
14
13
  AgentThreadParticipantRecord,
@@ -20,22 +19,33 @@ import type {
20
19
  } from "@sixb/core/storage"
21
20
  import { createAskUserTool } from "./ask-tool"
22
21
  import { prepareAgentModel } from "./context-budget"
23
- import { AgentEnvironmentSaveError, AgentRequesterLeftThreadError, isLostExecution } from "./errors"
22
+ import {
23
+ AgentEnvironmentSaveError,
24
+ AgentRequesterLeftThreadError,
25
+ isLostExecution,
26
+ WORKSPACE_NOT_SAVED_DIAGNOSTIC,
27
+ } from "./errors"
24
28
  import { resolveRunPlan } from "./execution-plan"
25
29
  import type { AgentRunFailure } from "./failure"
26
30
  import type { FamilyMailbox } from "./family-mailbox"
27
31
  import { agentRequester } from "./requester"
28
32
  import { runAgentTurn, stoppedByWorker } from "./run-agent-turn"
33
+ import type { ChildParent } from "./run-child"
29
34
  import {
30
35
  type ConversationAgentExecutionEnvironment,
31
36
  createConversationAgentEnvironment,
32
37
  type OpenRunSandbox,
33
38
  } from "./run-environment"
34
39
  import { recordFate } from "./run-fate"
40
+ import { sandboxStopOf, sandboxStoppedError } from "./run-sandbox"
35
41
  import { SubagentCoordinator } from "./subagent-tools"
36
42
  import { type AgentTurnRuntime, createAgentTurnRuntime } from "./turn-runtime"
37
43
  import type { AgentExecutionContext, AgentRunSettings } from "./types"
38
44
 
45
+ /** Why a turn ended whose workspace, kept across turns, its provider stopped: as the chat offers. */
46
+ const SANDBOX_STOPPED_UNSAVED_MESSAGE =
47
+ "The sandbox stopped, so this turn ended here. To go on, pick up where it left off or start over."
48
+
39
49
  // A conversation turn, from its claimed session to its end, whichever runner runs it: the worker,
40
50
  // under a queue delivery, or a runner on a computer, over HTTP. The runner keeps what is its own:
41
51
  // how it holds the run, where the turn's sandbox comes from, and where its children run.
@@ -52,14 +62,20 @@ export interface ConversationTurnRunner {
52
62
  readonly thread: AgentThreadRecord | null
53
63
  }): OpenRunSandbox
54
64
  /**
55
- * Run a child the turn spawned or continues, beside the turn, on the turn's mailbox, its
56
- * `web_fetch` following the network the turn's sandbox declared.
65
+ * Run a child the turn spawned or continues, beside the turn, on the turn's mailbox: in the
66
+ * turn's workspace when it lends one, its `web_fetch` following the network the turn's sandbox
67
+ * declared.
57
68
  */
58
69
  startChild(
59
70
  run: SubagentRunRecord,
60
71
  family: FamilyMailbox,
61
- networkPolicy: SandboxNetworkPolicy | undefined
72
+ turn: Pick<ChildParent, "networkPolicy" | "workspace">
62
73
  ): void
74
+ /**
75
+ * Stop the turn's children still running, and wait for them to record it. A turn that lends its
76
+ * workspace calls it before saving it, so no child works in a workspace being saved.
77
+ */
78
+ stopChildren(runId: string): Promise<void>
63
79
  /** A sandbox teardown that outlives the turn: the runner waits for it before it stops. */
64
80
  onDetachedTeardown(teardown: Promise<void>): void
65
81
  /** A turn that failed: the runner reports it, once its end is recorded. */
@@ -105,15 +121,21 @@ export async function runConversationTurn(input: {
105
121
  runner.settings,
106
122
  run,
107
123
  session,
108
- (child, family) => {
124
+ (child, family, inParentWorkspace) => {
109
125
  // Children start from the turn's tools, once its environment holds its sandbox.
110
126
  if (!environment) {
111
127
  throw new Error(
112
128
  `[SixbAgent] Agent run '${run.id}' started a sub-agent before its sandbox.`
113
129
  )
114
130
  }
115
- runner.startChild(child, family, environment.networkPolicy)
116
- }
131
+ runner.startChild(child, family, {
132
+ ...(environment.networkPolicy ? { networkPolicy: environment.networkPolicy } : {}),
133
+ ...(inParentWorkspace && environment.lendWorkspace
134
+ ? { workspace: environment.lendWorkspace }
135
+ : {}),
136
+ })
137
+ },
138
+ prepared.thread?.movedAt
117
139
  )
118
140
  // The Agent's own: its children, and its questions to the user, which end the turn.
119
141
  const frameworkTools = [...(await delegation.createTools()), createAskUserTool()]
@@ -133,6 +155,7 @@ export async function runConversationTurn(input: {
133
155
  execution: prepared.execution,
134
156
  thread: prepared.thread,
135
157
  }),
158
+ stopChildren: () => runner.stopChildren(run.id),
136
159
  preflight: { budget: prepared.model.budget, runtime },
137
160
  context: prepared.context,
138
161
  plan,
@@ -170,7 +193,12 @@ export async function runConversationTurn(input: {
170
193
  })
171
194
  } catch (caughtError) {
172
195
  let error = caughtError
196
+ // A workspace that could not be saved leaves the turn's own error standing, when it had one:
197
+ // the run says what went wrong, and a diagnostic says the workspace waits for recovery.
173
198
  let environmentSaveFailed = error instanceof AgentEnvironmentSaveError
199
+ if (error instanceof AgentEnvironmentSaveError && error.turnError !== undefined) {
200
+ error = error.turnError
201
+ }
174
202
  // Its runner lost the run: touch nothing; whoever holds it now ends it.
175
203
  if (isLostExecution(error, signal)) return
176
204
  // It ended, but its end could not be recorded (storage down): its runner tries again.
@@ -180,15 +208,24 @@ export async function runConversationTurn(input: {
180
208
  await environment.beforeFinalize()
181
209
  } catch (saveError) {
182
210
  if (saveError instanceof AgentExecutionLostError) return
183
- error = saveError
184
- environmentSaveFailed = true
211
+ if (saveError instanceof AgentEnvironmentSaveError) environmentSaveFailed = true
212
+ else
213
+ console.error(
214
+ `[SixbAgent] Agent run '${run.id}' could not finalize its environment:`,
215
+ saveError
216
+ )
185
217
  }
186
218
  }
219
+
220
+ // A workspace its provider stopped cannot be cleaned and saved: it waits for its owner, and
221
+ // the run says why it ended and what to do.
222
+ const stop = environmentSaveFailed ? sandboxStopOf(error) : undefined
223
+ if (stop) error = sandboxStoppedError(stop, SANDBOX_STOPPED_UNSAVED_MESSAGE)
187
224
  // A user cancel is read off its own signal, so it records `cancelled` however the aborted
188
225
  // stream surfaced. `recordFate` retries a blip, and throws AgentFinalizationError past it.
189
226
  const aborted =
190
227
  error instanceof AgentRequesterLeftThreadError ||
191
- (!environmentSaveFailed &&
228
+ (!(error instanceof AgentEnvironmentSaveError) &&
192
229
  !(error instanceof ModelUsageRecordingError) &&
193
230
  (signal.aborted || session.cancelled.aborted || isAbortError(error)))
194
231
  // A runner that stops, unlike a user cancel, leaves the user something to resume.
@@ -197,7 +234,8 @@ export async function runConversationTurn(input: {
197
234
  session,
198
235
  aborted ? "cancelled" : "failed",
199
236
  interrupted ? new AgentTurnInterruptedError(run.id) : error,
200
- !aborted && work && work.length > 0 ? work : undefined
237
+ !aborted && work && work.length > 0 ? work : undefined,
238
+ environmentSaveFailed ? [WORKSPACE_NOT_SAVED_DIAGNOSTIC] : []
201
239
  )
202
240
  if (finalized) {
203
241
  if (finalized.run.status === "failed") {
@@ -1,5 +1,5 @@
1
1
  import { posix } from "node:path"
2
- import type { Principal } from "@sixb/core"
2
+ import type { Principal, SandboxNotRunningError } from "@sixb/core"
3
3
  import {
4
4
  type AgentContextBudget,
5
5
  type AgentRunArtifacts,
@@ -58,7 +58,7 @@ import {
58
58
  } from "./context-compaction"
59
59
  import { type ConversationMemory, loadConversationMemory } from "./conversation-memory"
60
60
  import { conversationModelMessages } from "./conversation-messages"
61
- import { isLostExecution } from "./errors"
61
+ import { AgentEnvironmentSaveError, isLostExecution } from "./errors"
62
62
  import type { ResolvedAgentExecutionPlan } from "./execution-plan"
63
63
  import { InlineImageBudget } from "./inline-images"
64
64
  import { type ConversationReaders, conversationAuthors } from "./message-authors"
@@ -67,7 +67,9 @@ import {
67
67
  type AcquiredRunSandbox,
68
68
  acquireRunSandbox,
69
69
  type BeforeFinalizeOptions,
70
+ endsWhenStopped,
70
71
  type RunSandbox,
72
+ sandboxStoppedError,
71
73
  } from "./run-sandbox"
72
74
  import {
73
75
  AGENT_ARTIFACTS_DIRECTORY,
@@ -115,6 +117,13 @@ import type { AgentTurnRuntime } from "./turn-runtime"
115
117
  import type { AgentExecutionContext, AgentRunFiles, AgentTurnContext } from "./types"
116
118
  import { prepareWorkflowInputAttachments } from "./workflow-input-attachments"
117
119
 
120
+ // What each kind of run says when its provider stopped its sandbox, to whoever goes on from it: the
121
+ // person in a conversation, the parent of a child, the run of a workflow step.
122
+ const SANDBOX_STOPPED_TURN_MESSAGE =
123
+ "The sandbox stopped, so this turn ended here. Its work so far is kept: send a message to go on."
124
+ const SANDBOX_STOPPED_CHILD_MESSAGE = "The sandbox stopped, so this agent ended here."
125
+ const SANDBOX_STOPPED_STEP_MESSAGE = "The sandbox stopped, so this step ended here."
126
+
118
127
  export interface AgentExecutionEnvironment {
119
128
  readonly turnContext: AgentTurnContext
120
129
  /** The run's sandbox and file budget, for the files a parent and its children hand each other. */
@@ -139,6 +148,8 @@ export interface ConversationAgentExecutionEnvironment extends AgentExecutionEnv
139
148
  readonly bytesPerToken?: number
140
149
  /** The network its sandbox declared, which `web_fetch` follows: its children's too. */
141
150
  readonly networkPolicy?: SandboxNetworkPolicy
151
+ /** Its workspace, which its children work in (`RunSandbox.lend`), when it has one to lend. */
152
+ readonly lendWorkspace?: NonNullable<RunSandbox["lend"]>
142
153
  }
143
154
 
144
155
  /**
@@ -191,6 +202,11 @@ export interface CreateConversationAgentEnvironmentInput extends CreateAgentEnvi
191
202
  readonly frameworkTools?: readonly ModelTool[]
192
203
  /** Its children, which `wait` and `stop` reach beside its background commands. */
193
204
  readonly children?: WaitableChildren
205
+ /**
206
+ * Stop its children still running, and wait for them to record it: called before a workspace
207
+ * it lends them is saved, so none of them works in it meanwhile.
208
+ */
209
+ readonly stopChildren?: () => Promise<void>
194
210
  }
195
211
 
196
212
  export interface CreateSubagentEnvironmentInput extends CreateAgentEnvironmentInput {
@@ -405,13 +421,12 @@ export async function createConversationAgentEnvironment(
405
421
  },
406
422
  sandboxSignal,
407
423
  failureSignal: failure.signal,
424
+ onSandboxStopped: (error) =>
425
+ failure.abort(sandboxStoppedError(error, SANDBOX_STOPPED_TURN_MESSAGE)),
408
426
  context,
409
427
  plan,
410
428
  runId: run.id,
411
429
  threadId: run.threadId,
412
- ...(input.thread?.movedAt
413
- ? { workspaceMovedAt: new Date(input.thread.movedAt).toISOString() }
414
- : {}),
415
430
  callTool: (call, options) => input.session.callTool(call, options),
416
431
  webSearch: input.session.models.webSearch,
417
432
  ...(publishing ? { publishing } : {}),
@@ -423,6 +438,7 @@ export async function createConversationAgentEnvironment(
423
438
  ontologyDocs,
424
439
  frameworkTools: input.frameworkTools,
425
440
  ...(input.children ? { children: input.children } : {}),
441
+ ...(sandbox.lend && input.stopChildren ? { beforeSave: input.stopChildren } : {}),
426
442
  ...(memory ? { memory } : {}),
427
443
  ...(conversation === undefined ? {} : { conversation }),
428
444
  onDetachedTeardown: input.onDetachedTeardown,
@@ -450,12 +466,17 @@ export async function createConversationAgentEnvironment(
450
466
  ...(compactInTurn ? { compactInTurn } : {}),
451
467
  ...(prepared?.bytesPerToken === undefined ? {} : { bytesPerToken: prepared.bytesPerToken }),
452
468
  ...(sandbox.networkPolicy ? { networkPolicy: sandbox.networkPolicy } : {}),
469
+ ...(sandbox.lend ? { lendWorkspace: sandbox.lend.bind(sandbox) } : {}),
453
470
  }
454
471
  } catch (error) {
455
472
  // Preparation can fail before the worker receives this environment. Preserve here, before
456
473
  // the worker records the run's terminal outcome; a lost execution must touch nothing.
457
474
  try {
458
475
  if (!isLostExecution(error, input.signal)) await sandbox.beforeFinalize?.()
476
+ } catch (saveError) {
477
+ // The preparation's own error is what ended the turn: it stays, beside the failed save.
478
+ if (saveError instanceof AgentEnvironmentSaveError) throw new AgentEnvironmentSaveError(error)
479
+ throw saveError
459
480
  } finally {
460
481
  // A workspace the summary acquired goes back as the environment would have given it.
461
482
  if (environment) await environment.dispose()
@@ -466,18 +487,22 @@ export async function createConversationAgentEnvironment(
466
487
  }
467
488
 
468
489
  /**
469
- * Build an isolated environment for one headless child Agent. It knows the project as its parent
470
- * does (ontology docs, memory to read), holds the files its parent handed over at their paths, and
471
- * publishes into its conversation, as its own run.
490
+ * Build the environment of one headless child Agent. It knows the project as its parent does
491
+ * (ontology docs, memory to read), and publishes into its conversation, as its own run.
472
492
  *
473
- * On a provider that resumes sandboxes, its thread keeps its workspace while it pauses: the run
474
- * that continues it finds every file where it was. Elsewhere, or once those files were lost, it
475
- * starts blank, with the handed files and what the paused run left in `out/` given back.
493
+ * A child whose parent lends it its workspace works there, on the parent's files: it is handed
494
+ * none and hands none back. Otherwise it works in a sandbox of its own, which holds the files its
495
+ * parent handed over at their paths. On a provider that resumes sandboxes, its thread keeps that
496
+ * workspace while it pauses: the run that continues it finds every file where it was. Elsewhere,
497
+ * or once those files were lost, it starts blank, with the handed files and what the paused run
498
+ * left in `out/` given back.
476
499
  */
477
500
  export async function createSubagentEnvironment(
478
501
  input: CreateSubagentEnvironmentInput
479
502
  ): Promise<SubagentAgentExecutionEnvironment> {
480
- // A child's workspace is blank, so it has no source credentials to lose.
503
+ // A child's workspace is blank, so it has no source credentials to lose. It ends only when its
504
+ // provider stops the sandbox.
505
+ const failure = new AbortController()
481
506
  const { sandbox, resumed = false } = await input.openSandbox({
482
507
  signal: input.signal ?? NEVER_ABORTED_SIGNAL,
483
508
  onFailure: () => {},
@@ -496,6 +521,9 @@ export async function createSubagentEnvironment(
496
521
  ...input,
497
522
  sandbox,
498
523
  resumed,
524
+ failureSignal: failure.signal,
525
+ onSandboxStopped: (error) =>
526
+ failure.abort(sandboxStoppedError(error, SANDBOX_STOPPED_CHILD_MESSAGE)),
499
527
  acquireBeforeStart: acquire,
500
528
  acquire: () => {
501
529
  provisioning = true
@@ -521,6 +549,9 @@ async function startSubagentEnvironment(
521
549
  readonly sandbox: RunSandbox
522
550
  /** Whether the sandbox is the workspace the paused run left: it holds its files already. */
523
551
  readonly resumed: boolean
552
+ /** Ends the child when its provider stops the sandbox. */
553
+ readonly failureSignal: AbortSignal
554
+ readonly onSandboxStopped: (error: SandboxNotRunningError) => void
524
555
  /** How the summary acquires the workspace its prompt describes, before the environment. */
525
556
  readonly acquireBeforeStart: () => Promise<AcquiredRunSandbox>
526
557
  /** How provisioning acquires it, which from then gives it back. */
@@ -530,8 +561,15 @@ async function startSubagentEnvironment(
530
561
  const { context, plan, run, conversation, sandbox, resumed, preflight } = input
531
562
  const signal = input.signal ?? NEVER_ABORTED_SIGNAL
532
563
  const networkPolicy = input.parentNetworkPolicy ?? sandbox.networkPolicy
533
- // Still listed, as handed over, but never copied over what the child made of them.
534
- const files = resumed ? (run.spec.files ?? []) : subagentSandboxFiles(run, input.history.paused)
564
+ const readOnly = run.spec.readOnly === true
565
+
566
+ // Still listed, as handed over, but never copied over what the child made of them. A child in
567
+ // its parent's workspace has the parent's files already.
568
+ const files = sandbox.lent
569
+ ? []
570
+ : resumed
571
+ ? (run.spec.files ?? [])
572
+ : subagentSandboxFiles(run, input.history.paused)
535
573
  const inlineImages = modelSupportsInlineImages(plan.model)
536
574
  const [memory, handedContext] = await Promise.all([
537
575
  // As of the thread's start, as a conversation's: each run of the child reads the same memory.
@@ -609,6 +647,7 @@ async function startSubagentEnvironment(
609
647
  publishes: publishing !== undefined,
610
648
  web: plan.web,
611
649
  networkPolicy,
650
+ readOnly,
612
651
  }),
613
652
  ...(input.frameworkTools ?? []),
614
653
  ]
@@ -625,6 +664,7 @@ async function startSubagentEnvironment(
625
664
  context,
626
665
  plan,
627
666
  ontologyDocs: plan.ontologyDocs,
667
+ readOnly,
628
668
  ...(workspace ? { workspace } : {}),
629
669
  ...(memory ? { memory } : {}),
630
670
  }),
@@ -646,6 +686,7 @@ async function startSubagentEnvironment(
646
686
  context,
647
687
  plan,
648
688
  ontologyDocs: plan.ontologyDocs,
689
+ readOnly,
649
690
  ...(memory ? { memory } : {}),
650
691
  }),
651
692
  tools: contextEstimateTools(tools),
@@ -681,8 +722,11 @@ async function startSubagentEnvironment(
681
722
  mode: "subagent",
682
723
  sandbox,
683
724
  ...(networkPolicy ? { networkPolicy } : {}),
725
+ readOnly,
684
726
  acquire: input.acquire,
685
727
  sandboxSignal: input.signal,
728
+ failureSignal: input.failureSignal,
729
+ onSandboxStopped: input.onSandboxStopped,
686
730
  context,
687
731
  plan,
688
732
  runId: run.id,
@@ -761,6 +805,8 @@ export async function createWorkflowAgentNodeEnvironment(
761
805
  sandbox,
762
806
  sandboxSignal,
763
807
  failureSignal: failure.signal,
808
+ onSandboxStopped: (error) =>
809
+ failure.abort(sandboxStoppedError(error, SANDBOX_STOPPED_STEP_MESSAGE)),
764
810
  context,
765
811
  actorId: run.actorId,
766
812
  plan,
@@ -798,6 +844,11 @@ interface AgentEnvironmentSetup
798
844
  readonly sandboxSignal?: AbortSignal
799
845
  /** Environment-owned failure, such as lost source credentials. */
800
846
  readonly failureSignal?: AbortSignal
847
+ /**
848
+ * Ends the run when a command or a file write finds that the provider stopped the sandbox, such
849
+ * as at the end of a Vercel session: whichever tool met it, nothing more runs in it.
850
+ */
851
+ readonly onSandboxStopped?: (error: SandboxNotRunningError) => void
801
852
  /** How the run calls a project tool. */
802
853
  readonly callTool: AgentToolCaller
803
854
  /** How it searches the web, where the project is: `web_search` calls it. */
@@ -824,6 +875,10 @@ interface AgentEnvironmentSetup
824
875
  readonly frameworkTools?: readonly ModelTool[]
825
876
  /** The Agent's children, which `wait` and `stop` reach beside its background commands. */
826
877
  readonly children?: WaitableChildren
878
+ /** Runs before the workspace is saved, as the run ends: its children leave the one it lends. */
879
+ readonly beforeSave?: () => Promise<void>
880
+ /** A child that must leave the files as they are: no `edit` and no `write`. */
881
+ readonly readOnly?: boolean
827
882
  /**
828
883
  * A conversation, or a child of one, publishes artifacts into its conversation, through its
829
884
  * session, and edits them from their installed copies; other runs return text.
@@ -836,8 +891,6 @@ interface AgentEnvironmentSetup
836
891
  }
837
892
  /** A conversation's memory, or a child's to read: installed in the sandbox and in the prompt. */
838
893
  readonly memory?: ConversationMemory
839
- /** When the conversation's turns last moved to where they run now: see its `movedAt`. */
840
- readonly workspaceMovedAt?: string
841
894
  /** Who takes part in a conversation several people write in, for its prompt. */
842
895
  readonly conversation?: string
843
896
  }
@@ -929,8 +982,11 @@ async function startAgentEnvironment(
929
982
  // One per run: `edit` and `write` change only files this run read, as it read them.
930
983
  const fileReads = new FileReadLedger()
931
984
  appendBuiltInTool(tools, createReadTool(resolveSandbox, fileReads, fileViewer))
932
- appendBuiltInTool(tools, createEditTool(resolveSandbox, fileReads))
933
- appendBuiltInTool(tools, createWriteTool(resolveSandbox, fileReads))
985
+ // As agentModelToolSpecs advertises them.
986
+ if (!input.readOnly) {
987
+ appendBuiltInTool(tools, createEditTool(resolveSandbox, fileReads))
988
+ appendBuiltInTool(tools, createWriteTool(resolveSandbox, fileReads))
989
+ }
934
990
  appendBuiltInTool(tools, createGlobTool(resolveSandbox))
935
991
  appendBuiltInTool(tools, createGrepTool(resolveSandbox))
936
992
  appendBuiltInTool(tools, createBashTool(resolveSandbox, background))
@@ -995,6 +1051,7 @@ async function startAgentEnvironment(
995
1051
  ontologyFiles: input.ontologyDocs?.files ?? [],
996
1052
  ...(installedArtifacts ? { artifacts: installedArtifacts } : {}),
997
1053
  ...(input.memory ? { memory: input.memory.repos } : {}),
1054
+ ...(input.onSandboxStopped ? { onSandboxStopped: input.onSandboxStopped } : {}),
998
1055
  })
999
1056
  // Creation failure is surfaced where it is awaited (turn / sandbox tool / dispose); attach a no-op
1000
1057
  // catch so a rejection observed by none of them is not reported as unhandled.
@@ -1022,9 +1079,9 @@ async function startAgentEnvironment(
1022
1079
  sandbox,
1023
1080
  context,
1024
1081
  plan,
1082
+ ...(input.readOnly ? { readOnly: true } : {}),
1025
1083
  ...(input.ontologyDocs ? { ontologyDocs: input.ontologyDocs } : {}),
1026
1084
  ...(workspace ? { workspace } : {}),
1027
- ...(input.workspaceMovedAt ? { workspaceMovedAt: input.workspaceMovedAt } : {}),
1028
1085
  ...(input.conversation === undefined ? {} : { conversation: input.conversation }),
1029
1086
  ...(input.memory ? { memory: input.memory } : {}),
1030
1087
  })
@@ -1034,8 +1091,9 @@ async function startAgentEnvironment(
1034
1091
  throw error
1035
1092
  }
1036
1093
 
1037
- // A workspace saved as the run ends keeps no command of it running.
1094
+ // A workspace saved as the run ends keeps no command of it running, its children's included.
1038
1095
  const beforeFinalize = async (options?: BeforeFinalizeOptions) => {
1096
+ await input.beforeSave?.()
1039
1097
  await stopBackground()
1040
1098
  await sandbox.beforeFinalize?.(options)
1041
1099
  }
@@ -1047,6 +1105,10 @@ async function startAgentEnvironment(
1047
1105
  sandbox: resolveSandbox,
1048
1106
  blobStorage: context.blobStorage,
1049
1107
  budget: fileBudget,
1108
+ ...(sandbox.lend
1109
+ ? { lendsWorkspace: true, workspaceResetAt: async () => (await ready).resetAt }
1110
+ : {}),
1111
+ ...(sandbox.lent ? { inParentWorkspace: true } : {}),
1050
1112
  async installTurnArtifacts(signal) {
1051
1113
  if (!artifacts) return []
1052
1114
 
@@ -1064,7 +1126,7 @@ async function startAgentEnvironment(
1064
1126
  runFiles,
1065
1127
  turnContext: {
1066
1128
  environmentFailureSignal: input.failureSignal,
1067
- ...(sandbox.beforeFinalize ? { beforeFinalize } : {}),
1129
+ ...(sandbox.beforeFinalize || input.beforeSave ? { beforeFinalize } : {}),
1068
1130
  id: context.id,
1069
1131
  ...(context.authorPrincipal === undefined
1070
1132
  ? {}
@@ -1108,9 +1170,10 @@ function measureEnvironmentSystemPrompt(input: {
1108
1170
  readonly ontologyDocs?: RenderedOntologyDocs
1109
1171
  /** The acquired workspace, when the prompt describes it. */
1110
1172
  readonly workspace?: Pick<AcquiredRunSandbox, "promptContext" | "resetAt">
1111
- readonly workspaceMovedAt?: string
1112
1173
  readonly conversation?: string
1113
1174
  readonly memory?: ConversationMemory
1175
+ /** A child with no `edit` and no `write`. */
1176
+ readonly readOnly?: boolean
1114
1177
  }): AgentSystemPromptSize {
1115
1178
  const { mode, plan, workspace } = input
1116
1179
  const { requester } = input.context
@@ -1125,12 +1188,15 @@ function measureEnvironmentSystemPrompt(input: {
1125
1188
  ? { ontologyIndex: input.ontologyDocs.index }
1126
1189
  : {}),
1127
1190
  sandboxResetAt: workspace?.resetAt,
1128
- ...(input.workspaceMovedAt ? { workspaceMovedAt: input.workspaceMovedAt } : {}),
1129
1191
  workspace: workspace?.promptContext,
1192
+ ...(mode === "conversation" && input.sandbox.lend ? { lendsWorkspace: true } : {}),
1193
+ ...(mode === "subagent" && input.sandbox.lent ? { inParentWorkspace: true } : {}),
1194
+ ...(input.readOnly ? { readOnly: true } : {}),
1130
1195
  facts: requester === undefined ? {} : { requester },
1131
1196
  ...(input.conversation === undefined ? {} : { conversation: input.conversation }),
1132
1197
  ...(plan.sandboxModels ? { sandboxModels: plan.sandboxModels } : {}),
1133
1198
  ...(input.memory ? { memory: input.memory.prompt } : {}),
1199
+ runningModel: plan.model,
1134
1200
  })
1135
1201
  }
1136
1202
 
@@ -1224,6 +1290,7 @@ interface ProvisionSandboxInput {
1224
1290
  /** The conversation's artifacts, read while the sandbox starts. */
1225
1291
  readonly artifacts?: Promise<MaterializedArtifacts>
1226
1292
  readonly memory?: PrepareAgentSandboxApiContextInput["memory"]
1293
+ readonly onSandboxStopped?: (error: SandboxNotRunningError) => void
1227
1294
  }
1228
1295
 
1229
1296
  /** A sandbox acquired for the run, with the run's files installed in its context directory. */
@@ -1232,7 +1299,10 @@ type ProvisionedRunSandbox = AcquiredRunSandbox & AgentSandboxHandle
1232
1299
  async function provisionSandbox(input: ProvisionSandboxInput): Promise<ProvisionedRunSandbox> {
1233
1300
  const { context, actorId, run, apiBaseUrl, skills, ontologyFiles } = input
1234
1301
  const acquired = await (input.acquire?.() ?? acquireRunSandbox(input.sandbox, input.signal))
1235
- const { sandbox } = acquired
1302
+ // What the run's tools and files reach the sandbox through.
1303
+ const sandbox = input.onSandboxStopped
1304
+ ? endsWhenStopped(acquired.sandbox, input.onSandboxStopped)
1305
+ : acquired.sandbox
1236
1306
  const { contextDirectory } = input.sandbox
1237
1307
  try {
1238
1308
  const apiContext = await prepareAgentSandboxApiContext({
@@ -1256,6 +1326,7 @@ async function provisionSandbox(input: ProvisionSandboxInput): Promise<Provision
1256
1326
  })
1257
1327
  const provisioned = {
1258
1328
  ...acquired,
1329
+ sandbox,
1259
1330
  contextDirectory,
1260
1331
  env: { ...acquired.env, ...apiContext.env },
1261
1332
  }
package/src/run-fate.ts CHANGED
@@ -3,7 +3,11 @@ import {
3
3
  type AgentRunSession,
4
4
  AgentTurnInterruptedError,
5
5
  } from "@sixb/core/internal/agents"
6
- import type { AgentRunRecord, AppendAgentMessageInput } from "@sixb/core/storage"
6
+ import type {
7
+ AgentRunDiagnostic,
8
+ AgentRunRecord,
9
+ AppendAgentMessageInput,
10
+ } from "@sixb/core/storage"
7
11
  import { type AgentRunFailure, toAgentExecutionFailure } from "./failure"
8
12
 
9
13
  /**
@@ -15,7 +19,8 @@ export async function recordFate(
15
19
  session: AgentRunSession,
16
20
  status: "failed" | "cancelled",
17
21
  error: unknown,
18
- messages?: readonly AppendAgentMessageInput[]
22
+ messages?: readonly AppendAgentMessageInput[],
23
+ diagnostics: readonly AgentRunDiagnostic[] = []
19
24
  ): Promise<{ readonly run: AgentRunRecord; readonly failure: AgentRunFailure } | undefined> {
20
25
  const { run } = session
21
26
  const completedAt = new Date()
@@ -30,6 +35,7 @@ export async function recordFate(
30
35
  status,
31
36
  error: failure,
32
37
  completedAt,
38
+ ...(diagnostics.length === 0 ? {} : { diagnostics }),
33
39
  ...(error instanceof AgentTurnInterruptedError
34
40
  ? { finishReason: "interrupted" as const }
35
41
  : {}),
@@ -1,4 +1,7 @@
1
- import type { Sandbox } from "@sixb/core"
1
+ import { posix } from "node:path"
2
+ import { type Sandbox, SandboxNotRunningError } from "@sixb/core"
3
+ import { SANDBOX_CONTEXT_DIRECTORY } from "@sixb/core/internal/agents"
4
+ import { createSixbError, withFailureMessage } from "@sixb/core/internal/errors"
2
5
  import type { SandboxNetworkPolicy } from "@sixb/core/sandboxes"
3
6
  import type { AgentWorkspacePromptContext } from "./agent-prompt"
4
7
  import type { BackgroundCommands } from "./background-commands"
@@ -60,6 +63,19 @@ export interface RunSandbox {
60
63
  readonly networkPolicy?: SandboxNetworkPolicy
61
64
  /** Where `web_fetch` reads pages from. Absent: Sixb's servers. */
62
65
  readonly webNetwork?: WebFetchNetwork
66
+ /**
67
+ * The workspace of the run's parent, lent by its `lend`: the run hands back no files, as its
68
+ * parent sees what it changes, and its commands call the API with the parent's token, saying
69
+ * which run they are (`SIXB_RUN_ID`).
70
+ */
71
+ readonly lent?: boolean
72
+ /**
73
+ * Lend this workspace to a child the run spawns: the child runs its tools here, on the same
74
+ * files, and the parent still decides when the workspace is saved. The child keeps everything
75
+ * else of its own: its run, its token, its context directory. Absent when the run has no
76
+ * workspace to lend, such as a blank sandbox: each child then gets a sandbox of its own.
77
+ */
78
+ readonly lend?: (child: LentRunSandboxChild) => RunSandbox
63
79
  /** Called once, when the run environment starts. */
64
80
  acquire(): Promise<AcquiredRunSandbox>
65
81
  /**
@@ -71,6 +87,41 @@ export interface RunSandbox {
71
87
  beforeFinalize?(options?: BeforeFinalizeOptions): Promise<void>
72
88
  }
73
89
 
90
+ /** The child a run lends its workspace to. */
91
+ export interface LentRunSandboxChild {
92
+ readonly runId: string
93
+ readonly threadId: string
94
+ /** Stops the child's provisioning: its cancellation, or its runner stopping. */
95
+ readonly signal: AbortSignal
96
+ }
97
+
98
+ /**
99
+ * Where a child's run files go when its thread works in its parent's workspace, in whatever sandbox
100
+ * a run of the thread works in: beside the parent's, and the same for each of its runs, so the
101
+ * paths its history names hold. The directory a Git checkout excludes covers it.
102
+ */
103
+ export function threadContextDirectory(threadId: string): string {
104
+ return posix.join(SANDBOX_CONTEXT_DIRECTORY, "threads", threadId)
105
+ }
106
+
107
+ /** `sandbox` with its run's files in `contextDirectory` instead. */
108
+ export function withContextDirectory(sandbox: RunSandbox, contextDirectory: string): RunSandbox {
109
+ return {
110
+ waitBeforeModel: sandbox.waitBeforeModel,
111
+ contextDirectory,
112
+ ...(sandbox.background ? { background: sandbox.background } : {}),
113
+ ...(sandbox.networkPolicy ? { networkPolicy: sandbox.networkPolicy } : {}),
114
+ ...(sandbox.webNetwork ? { webNetwork: sandbox.webNetwork } : {}),
115
+ acquire: () => sandbox.acquire(),
116
+ ...(sandbox.release
117
+ ? { release: (acquired) => sandbox.release?.(acquired) ?? Promise.resolve() }
118
+ : {}),
119
+ ...(sandbox.beforeFinalize
120
+ ? { beforeFinalize: (options) => sandbox.beforeFinalize?.(options) ?? Promise.resolve() }
121
+ : {}),
122
+ }
123
+ }
124
+
74
125
  /** How a run's end leaves its thread's workspace. */
75
126
  export interface BeforeFinalizeOptions {
76
127
  /**
@@ -102,3 +153,61 @@ export async function acquireRunSandbox(
102
153
 
103
154
  return { ...acquired, promptContext: { ...promptContext, instructions } }
104
155
  }
156
+
157
+ /**
158
+ * The run's sandbox, which calls `onStopped` each time a command or a file write finds that its
159
+ * provider stopped it, such as at the end of a Vercel session. Whichever tool met it, nothing more
160
+ * runs in it: the run ends instead of the model retrying there.
161
+ */
162
+ export function endsWhenStopped(
163
+ session: Sandbox,
164
+ onStopped: (error: SandboxNotRunningError) => void
165
+ ): Sandbox {
166
+ // Watched beside its caller, which gets the provider's own promise: its wait gains no step, and
167
+ // the run has ended before the caller reads the failure.
168
+ const watch = <T>(operation: () => Promise<T>): Promise<T> => {
169
+ const result = operation()
170
+ result.catch((error: unknown) => {
171
+ if (error instanceof SandboxNotRunningError) onStopped(error)
172
+ })
173
+ return result
174
+ }
175
+
176
+ return {
177
+ id: session.id,
178
+ provider: session.provider,
179
+ get status() {
180
+ return session.status
181
+ },
182
+ workingDirectory: session.workingDirectory,
183
+ ...(session.setRequestCredentials
184
+ ? { setRequestCredentials: session.setRequestCredentials.bind(session) }
185
+ : {}),
186
+ ...(session.credentialedUrl ? { credentialedUrl: session.credentialedUrl.bind(session) } : {}),
187
+ runCommand: (command, args, options) => watch(() => session.runCommand(command, args, options)),
188
+ writeFiles: (files) => watch(() => session.writeFiles(files)),
189
+ stop: () => session.stop(),
190
+ destroy: () => session.destroy(),
191
+ }
192
+ }
193
+
194
+ const stops = new WeakMap<Error, SandboxNotRunningError>()
195
+
196
+ /** Why a run whose sandbox stopped ended, in the words its run and its reader see. */
197
+ export function sandboxStoppedError(cause: SandboxNotRunningError, message: string): Error {
198
+ const error = withFailureMessage(
199
+ createSixbError(
200
+ "agent.execution_failed",
201
+ "[SixbAgent] The run's sandbox stopped; nothing more can run in it.",
202
+ { cause }
203
+ ),
204
+ message
205
+ )
206
+ stops.set(error, cause)
207
+ return error
208
+ }
209
+
210
+ /** The provider's stop a run ended on, when `sandboxStoppedError` says that is why it ended. */
211
+ export function sandboxStopOf(error: unknown): SandboxNotRunningError | undefined {
212
+ return error instanceof Error ? stops.get(error) : undefined
213
+ }