@sixb/agent 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +31 -2
  3. package/dist/abort.d.ts +6 -0
  4. package/dist/abort.d.ts.map +1 -0
  5. package/dist/agent-prompt.d.ts +120 -0
  6. package/dist/agent-prompt.d.ts.map +1 -0
  7. package/dist/agent-runtime/errors.d.ts +13 -0
  8. package/dist/agent-runtime/errors.d.ts.map +1 -0
  9. package/dist/agent-runtime/preflight.d.ts +18 -0
  10. package/dist/agent-runtime/preflight.d.ts.map +1 -0
  11. package/dist/agent-runtime/profile.d.ts +14 -0
  12. package/dist/agent-runtime/profile.d.ts.map +1 -0
  13. package/dist/artifacts/layout-check/layout-check.d.ts +87 -0
  14. package/dist/artifacts/layout-check/layout-check.d.ts.map +1 -0
  15. package/dist/artifacts/materialize.d.ts +115 -0
  16. package/dist/artifacts/materialize.d.ts.map +1 -0
  17. package/dist/artifacts/publish-tool.d.ts +86 -0
  18. package/dist/artifacts/publish-tool.d.ts.map +1 -0
  19. package/dist/ask-parent-tool.d.ts +36 -0
  20. package/dist/ask-parent-tool.d.ts.map +1 -0
  21. package/dist/attachments.d.ts +68 -0
  22. package/dist/attachments.d.ts.map +1 -0
  23. package/dist/child-files.d.ts +96 -0
  24. package/dist/child-files.d.ts.map +1 -0
  25. package/dist/child-questions.d.ts +24 -0
  26. package/dist/child-questions.d.ts.map +1 -0
  27. package/dist/computer-runner.d.ts +65 -0
  28. package/dist/computer-runner.d.ts.map +1 -0
  29. package/dist/context-budget.d.ts +28 -0
  30. package/dist/context-budget.d.ts.map +1 -0
  31. package/dist/context-compaction.d.ts +48 -0
  32. package/dist/context-compaction.d.ts.map +1 -0
  33. package/dist/conversation-memory.d.ts +21 -0
  34. package/dist/conversation-memory.d.ts.map +1 -0
  35. package/dist/errors.d.ts +46 -0
  36. package/dist/errors.d.ts.map +1 -0
  37. package/dist/execution-plan.d.ts +34 -0
  38. package/dist/execution-plan.d.ts.map +1 -0
  39. package/dist/failure.d.ts +14 -0
  40. package/dist/failure.d.ts.map +1 -0
  41. package/dist/family-mailbox.d.ts +60 -0
  42. package/dist/family-mailbox.d.ts.map +1 -0
  43. package/dist/file-ref.d.ts +6 -0
  44. package/dist/file-ref.d.ts.map +1 -0
  45. package/dist/image-attachments.d.ts +34 -0
  46. package/dist/image-attachments.d.ts.map +1 -0
  47. package/dist/index.d.ts +35 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +12168 -0
  50. package/dist/index.js.map +65 -0
  51. package/dist/message-authors.d.ts +34 -0
  52. package/dist/message-authors.d.ts.map +1 -0
  53. package/dist/message-times.d.ts +8 -0
  54. package/dist/message-times.d.ts.map +1 -0
  55. package/dist/model-adapters.d.ts +55 -0
  56. package/dist/model-adapters.d.ts.map +1 -0
  57. package/dist/model-lines.d.ts +16 -0
  58. package/dist/model-lines.d.ts.map +1 -0
  59. package/dist/requester.d.ts +15 -0
  60. package/dist/requester.d.ts.map +1 -0
  61. package/dist/run-agent-turn.d.ts +63 -0
  62. package/dist/run-agent-turn.d.ts.map +1 -0
  63. package/dist/run-child.d.ts +77 -0
  64. package/dist/run-child.d.ts.map +1 -0
  65. package/dist/run-conversation-turn.d.ts +42 -0
  66. package/dist/run-conversation-turn.d.ts.map +1 -0
  67. package/dist/run-credential.d.ts +22 -0
  68. package/dist/run-credential.d.ts.map +1 -0
  69. package/dist/run-environment.d.ts +115 -0
  70. package/dist/run-environment.d.ts.map +1 -0
  71. package/dist/run-fate.d.ts +15 -0
  72. package/dist/run-fate.d.ts.map +1 -0
  73. package/dist/run-sandbox.d.ts +60 -0
  74. package/dist/run-sandbox.d.ts.map +1 -0
  75. package/dist/run-subagent.d.ts +51 -0
  76. package/dist/run-subagent.d.ts.map +1 -0
  77. package/dist/run-workflow-agent-node.d.ts +41 -0
  78. package/dist/run-workflow-agent-node.d.ts.map +1 -0
  79. package/dist/sandbox-api-context.d.ts +34 -0
  80. package/dist/sandbox-api-context.d.ts.map +1 -0
  81. package/dist/sandbox-file-registry.d.ts +9 -0
  82. package/dist/sandbox-file-registry.d.ts.map +1 -0
  83. package/dist/sandbox-files.d.ts +71 -0
  84. package/dist/sandbox-files.d.ts.map +1 -0
  85. package/dist/sandbox-handle.d.ts +15 -0
  86. package/dist/sandbox-handle.d.ts.map +1 -0
  87. package/dist/sandbox-readiness.d.ts +8 -0
  88. package/dist/sandbox-readiness.d.ts.map +1 -0
  89. package/dist/skills/built-in.d.ts +15 -0
  90. package/dist/skills/built-in.d.ts.map +1 -0
  91. package/dist/subagent-continuation.d.ts +27 -0
  92. package/dist/subagent-continuation.d.ts.map +1 -0
  93. package/dist/subagent-inbox.d.ts +53 -0
  94. package/dist/subagent-inbox.d.ts.map +1 -0
  95. package/dist/subagent-tools.d.ts +282 -0
  96. package/dist/subagent-tools.d.ts.map +1 -0
  97. package/dist/thread-context.d.ts +12 -0
  98. package/dist/thread-context.d.ts.map +1 -0
  99. package/dist/tools/attachments.d.ts +11 -0
  100. package/dist/tools/attachments.d.ts.map +1 -0
  101. package/dist/tools/bash.d.ts +60 -0
  102. package/dist/tools/bash.d.ts.map +1 -0
  103. package/dist/tools/model-spec.d.ts +4 -0
  104. package/dist/tools/model-spec.d.ts.map +1 -0
  105. package/dist/tools/read.d.ts +43 -0
  106. package/dist/tools/read.d.ts.map +1 -0
  107. package/dist/tools/result-media.d.ts +22 -0
  108. package/dist/tools/result-media.d.ts.map +1 -0
  109. package/dist/tools/result-output.d.ts +18 -0
  110. package/dist/tools/result-output.d.ts.map +1 -0
  111. package/dist/tools/tool-files.d.ts +59 -0
  112. package/dist/tools/tool-files.d.ts.map +1 -0
  113. package/dist/tools/view-file.d.ts +40 -0
  114. package/dist/tools/view-file.d.ts.map +1 -0
  115. package/dist/tsconfig.json +5 -0
  116. package/dist/turn-runtime.d.ts +19 -0
  117. package/dist/turn-runtime.d.ts.map +1 -0
  118. package/dist/types.d.ts +76 -0
  119. package/dist/types.d.ts.map +1 -0
  120. package/dist/workflow-input-attachments.d.ts +18 -0
  121. package/dist/workflow-input-attachments.d.ts.map +1 -0
  122. package/package.json +59 -4
  123. package/src/abort.ts +40 -0
  124. package/src/agent-prompt.ts +758 -0
  125. package/src/agent-runtime/errors.ts +44 -0
  126. package/src/agent-runtime/preflight.ts +314 -0
  127. package/src/agent-runtime/profile.ts +23 -0
  128. package/src/artifacts/layout-check/check.cjs +478 -0
  129. package/src/artifacts/layout-check/layout-check.ts +460 -0
  130. package/src/artifacts/materialize.ts +380 -0
  131. package/src/artifacts/publish-tool.ts +700 -0
  132. package/src/ask-parent-tool.ts +100 -0
  133. package/src/attachments.ts +850 -0
  134. package/src/child-files.ts +540 -0
  135. package/src/child-questions.ts +42 -0
  136. package/src/computer-runner.ts +284 -0
  137. package/src/context-budget.ts +161 -0
  138. package/src/context-compaction.ts +529 -0
  139. package/src/conversation-memory.ts +45 -0
  140. package/src/errors.ts +85 -0
  141. package/src/execution-plan.ts +50 -0
  142. package/src/failure.ts +71 -0
  143. package/src/family-mailbox.ts +189 -0
  144. package/src/file-ref.ts +18 -0
  145. package/src/image-attachments.ts +322 -0
  146. package/src/index.ts +54 -0
  147. package/src/message-authors.ts +77 -0
  148. package/src/message-times.ts +21 -0
  149. package/src/model-adapters.ts +227 -0
  150. package/src/model-lines.ts +28 -0
  151. package/src/requester.ts +21 -0
  152. package/src/run-agent-turn.ts +347 -0
  153. package/src/run-child.ts +319 -0
  154. package/src/run-conversation-turn.ts +257 -0
  155. package/src/run-credential.ts +55 -0
  156. package/src/run-environment.ts +769 -0
  157. package/src/run-fate.ts +51 -0
  158. package/src/run-sandbox.ts +63 -0
  159. package/src/run-subagent.ts +347 -0
  160. package/src/run-workflow-agent-node.ts +270 -0
  161. package/src/sandbox-api-context.ts +234 -0
  162. package/src/sandbox-file-registry.ts +26 -0
  163. package/src/sandbox-files.ts +326 -0
  164. package/src/sandbox-handle.ts +19 -0
  165. package/src/sandbox-readiness.ts +22 -0
  166. package/src/skills/built-in.ts +183 -0
  167. package/src/skills/sixb-artifacts/SKILL.md +95 -0
  168. package/src/skills/sixb-artifacts/canvas.md +104 -0
  169. package/src/skills/sixb-artifacts/document.md +63 -0
  170. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/first-job.html +42 -0
  171. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/region.html +29 -0
  172. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/shared.css +35 -0
  173. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/welcome.html +31 -0
  174. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/canvas.json +107 -0
  175. package/src/skills/sixb-artifacts/examples/canvas/retro/canvas.json +158 -0
  176. package/src/skills/sixb-artifacts/examples/document/incident-report/document.md +35 -0
  177. package/src/skills/sixb-artifacts/examples/document/operations-review/document.md +41 -0
  178. package/src/skills/sixb-artifacts/examples/document/operations-review/figures/restorations.svg +1 -0
  179. package/src/skills/sixb-artifacts/examples/page/collections-desk/index.html +169 -0
  180. package/src/skills/sixb-artifacts/examples/page/collections-desk/queries/overdue.json +13 -0
  181. package/src/skills/sixb-artifacts/examples/page/dispatch-board/data/dispatch.json +234 -0
  182. package/src/skills/sixb-artifacts/examples/page/dispatch-board/index.html +245 -0
  183. package/src/skills/sixb-artifacts/examples/page/fleet-planner/data/plan.json +53 -0
  184. package/src/skills/sixb-artifacts/examples/page/fleet-planner/index.html +462 -0
  185. package/src/skills/sixb-artifacts/examples/page/service-explorer/data/service.json +276 -0
  186. package/src/skills/sixb-artifacts/examples/page/service-explorer/index.html +549 -0
  187. package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/queries/overdue.json +13 -0
  188. package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/workbook.json +30 -0
  189. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Inventory.csv +13 -0
  190. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Spend.csv +6 -0
  191. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/workbook.json +47 -0
  192. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Quarters.csv +5 -0
  193. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Regions.csv +5 -0
  194. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/workbook.json +78 -0
  195. package/src/skills/sixb-artifacts/examples/slides/launch-plan/index.html +63 -0
  196. package/src/skills/sixb-artifacts/examples/slides/q3-review/index.html +133 -0
  197. package/src/skills/sixb-artifacts/file.md +17 -0
  198. package/src/skills/sixb-artifacts/page.md +215 -0
  199. package/src/skills/sixb-artifacts/queries.md +66 -0
  200. package/src/skills/sixb-artifacts/references.md +68 -0
  201. package/src/skills/sixb-artifacts/sheet.md +223 -0
  202. package/src/skills/sixb-artifacts/slides.md +137 -0
  203. package/src/skills/sixb-memory/SKILL.md +68 -0
  204. package/src/skills/text-assets.d.ts +25 -0
  205. package/src/subagent-continuation.ts +51 -0
  206. package/src/subagent-inbox.ts +101 -0
  207. package/src/subagent-tools.ts +1609 -0
  208. package/src/thread-context.ts +25 -0
  209. package/src/tools/attachments.ts +28 -0
  210. package/src/tools/bash.ts +217 -0
  211. package/src/tools/model-spec.ts +22 -0
  212. package/src/tools/read.ts +262 -0
  213. package/src/tools/result-media.ts +147 -0
  214. package/src/tools/result-output.ts +44 -0
  215. package/src/tools/tool-files.ts +204 -0
  216. package/src/tools/view-file.ts +155 -0
  217. package/src/turn-runtime.ts +33 -0
  218. package/src/types.ts +79 -0
  219. package/src/workflow-input-attachments.ts +140 -0
@@ -0,0 +1,270 @@
1
+ import type { AgentMessagePart, SchemaOrRef, ValueType } from "@sixb/core"
2
+ import { runModelLoop } from "@sixb/core/internal/agents"
3
+ import { createSixbError, withFailureMessage } from "@sixb/core/internal/errors"
4
+ import { schemaRecordToJsonSchema } from "@sixb/core/internal/ontology"
5
+ import {
6
+ type AgentStepDefinition,
7
+ snapshotWorkflowAgentStepOutput,
8
+ validateWorkflowAgentStepOutput,
9
+ type WorkflowIOSnapshot,
10
+ } from "@sixb/core/internal/workflows"
11
+ import type { ModelMessage, ModelStep } from "@sixb/core/models"
12
+ import { StructuredOutputError, UnsupportedModelFeatureError } from "@sixb/core/models"
13
+ import { type AgentRunFinishReason, coerceAgentRunFinishReason } from "@sixb/core/storage"
14
+ import { renderWorkflowOutputFinalizerPrompt, withCurrentTime } from "./agent-prompt"
15
+ import type { ResolvedAgentExecutionPlan } from "./execution-plan"
16
+ import { agentTraceFromModelSteps } from "./model-adapters"
17
+ import { monitorSandboxReadiness } from "./sandbox-readiness"
18
+ import type { AgentTurnContext } from "./types"
19
+
20
+ const WORKFLOW_OUTPUT_FINALIZATION_ATTEMPTS = 2
21
+
22
+ export interface RunWorkflowAgentNodeInput {
23
+ readonly context: AgentTurnContext
24
+ readonly agentStepId: string
25
+ readonly plan: ResolvedAgentExecutionPlan
26
+ readonly agentStep: AgentStepDefinition
27
+ readonly workflowId: string
28
+ readonly workflowRunId: string
29
+ readonly nodeRunId: string
30
+ readonly prompt: string
31
+ /** When the node run was created; dates the prompt for the model. */
32
+ readonly createdAt: Date
33
+ readonly valueTypesById: ReadonlyMap<string, ValueType>
34
+ /** The node's signal, which the caller also applies to its tools' model calls. */
35
+ readonly signal: AbortSignal
36
+ }
37
+
38
+ export interface WorkflowAgentNodeResult {
39
+ readonly output: WorkflowIOSnapshot
40
+ readonly modelId: string
41
+ readonly finishReason: NonNullable<ReturnType<typeof coerceAgentRunFinishReason>>
42
+ readonly trace: readonly AgentMessagePart[]
43
+ }
44
+
45
+ export type WorkflowAgentFailurePhase = "output-preflight" | "agent-loop" | "structured-finalizer"
46
+
47
+ /** Carries best-effort debug context across the workflow node's terminal error boundary. */
48
+ export class WorkflowAgentNodeExecutionError extends Error {
49
+ readonly phase: WorkflowAgentFailurePhase
50
+ readonly finishReason?: AgentRunFinishReason
51
+ readonly trace: readonly AgentMessagePart[]
52
+
53
+ constructor(input: {
54
+ readonly phase: WorkflowAgentFailurePhase
55
+ readonly finishReason?: AgentRunFinishReason
56
+ readonly trace: readonly AgentMessagePart[]
57
+ readonly cause: unknown
58
+ }) {
59
+ super("Workflow agent node execution failed.", { cause: input.cause })
60
+ this.name = "WorkflowAgentNodeExecutionError"
61
+ this.phase = input.phase
62
+ this.finishReason = input.finishReason
63
+ this.trace = input.trace
64
+ }
65
+ }
66
+
67
+ export async function runWorkflowAgentNode(
68
+ input: RunWorkflowAgentNodeInput
69
+ ): Promise<WorkflowAgentNodeResult> {
70
+ const validateOutput = (value: unknown): Record<string, unknown> => ({
71
+ ...validateWorkflowAgentStepOutput({
72
+ workflowId: input.workflowId,
73
+ agentStep: input.agentStep,
74
+ value,
75
+ valueTypesById: input.valueTypesById,
76
+ }),
77
+ })
78
+
79
+ const sandboxReadiness = monitorSandboxReadiness(input.context.sandboxReady)
80
+ const { environmentFailureSignal } = input.context
81
+ const abortSignal = AbortSignal.any([
82
+ input.signal,
83
+ sandboxReadiness.signal,
84
+ ...(environmentFailureSignal ? [environmentFailureSignal] : []),
85
+ ])
86
+ // A provisioning or environment failure (for example lost source credentials) is the concrete
87
+ // cause of the abort it triggers in any phase. Once the node itself is aborted (cancellation or
88
+ // shutdown), provisioning fails because of it, and the abort's reason is the one
89
+ // to report.
90
+ const throwIfEnvironmentFailed = () => {
91
+ if (input.signal.aborted) return
92
+
93
+ sandboxReadiness.throwIfFailed()
94
+ environmentFailureSignal?.throwIfAborted()
95
+ }
96
+ const completedSteps: ModelStep[] = []
97
+ const traceDetails = {
98
+ agentStepId: input.agentStepId,
99
+ workflowId: input.workflowId,
100
+ workflowRunId: input.workflowRunId,
101
+ nodeRunId: input.nodeRunId,
102
+ }
103
+ let phase: WorkflowAgentFailurePhase = "output-preflight"
104
+ let finishReason: AgentRunFinishReason | undefined
105
+ try {
106
+ const outputSchema = schemaRecordToJsonSchema({
107
+ shape: input.agentStep.output as Readonly<Record<string, SchemaOrRef>>,
108
+ valueTypesById: input.valueTypesById,
109
+ })
110
+ if (input.plan.model.definition.capabilities.nativeStructuredOutput === false) {
111
+ throw new UnsupportedModelFeatureError(
112
+ "[SixbAgent] Workflow output requires a model supporting structured output.",
113
+ { reason: "unsupported-model" }
114
+ )
115
+ }
116
+ await input.plan.model.validateResponseFormat?.({
117
+ type: "json",
118
+ name: input.agentStep.id,
119
+ schema: outputSchema,
120
+ })
121
+ phase = "agent-loop"
122
+ const research = await runModelLoop({
123
+ model: input.plan.model,
124
+ messages: [
125
+ {
126
+ role: "system",
127
+ content: input.context.systemPrompt,
128
+ },
129
+ withCurrentTime(
130
+ { role: "user", content: [{ type: "text", text: input.prompt }] },
131
+ input.createdAt,
132
+ input.context.projectTimeZone
133
+ ),
134
+ ],
135
+ tools: input.context.tools,
136
+ ...(input.plan.reasoning === undefined ? {} : { reasoning: input.plan.reasoning }),
137
+ ...(input.context.prepareStep === undefined
138
+ ? {}
139
+ : { prepareStep: input.context.prepareStep }),
140
+ signal: abortSignal,
141
+ onStepEnd: (step) => {
142
+ completedSteps.push(step)
143
+ },
144
+ })
145
+ throwIfEnvironmentFailed()
146
+ if (research.status === "aborted") {
147
+ throw abortSignal.reason ?? new DOMException("The workflow agent was aborted.", "AbortError")
148
+ }
149
+
150
+ const researchText = research.output
151
+ finishReason = coerceAgentRunFinishReason(research.finishReason) ?? "unknown"
152
+ // A cut-short answer would be structured as if it were complete; its text is never passed on.
153
+ if (finishReason === "length") {
154
+ const remedy =
155
+ "Lower the step's reasoning, or raise maxOutputTokens on the model binding if it sets one."
156
+ throw withFailureMessage(
157
+ createSixbError(
158
+ "agent.execution_failed",
159
+ `[SixbAgent] Workflow agent step '${input.agentStepId}' reached the model's output limit before finishing its answer. ${remedy}`,
160
+ { details: traceDetails }
161
+ ),
162
+ `The model reached its output limit before finishing its answer. ${remedy}`
163
+ )
164
+ }
165
+ if (researchText.trim().length === 0) {
166
+ throw createSixbError(
167
+ "agent.execution_failed",
168
+ `[SixbAgent] Workflow agent step '${input.agentStepId}' produced no final answer to structure.`,
169
+ { details: traceDetails }
170
+ )
171
+ }
172
+
173
+ phase = "structured-finalizer"
174
+ let finalizerMessages: ModelMessage[] = [
175
+ {
176
+ role: "system",
177
+ content: renderWorkflowOutputFinalizerPrompt({ instructions: input.plan.instructions }),
178
+ },
179
+ {
180
+ role: "user",
181
+ content: [{ type: "text", text: `Original workflow request:\n${input.prompt}` }],
182
+ },
183
+ { role: "assistant", content: [{ type: "text", text: researchText }] },
184
+ {
185
+ role: "user",
186
+ content: [
187
+ {
188
+ type: "text",
189
+ text: "Convert the final agent answer into the required workflow output.",
190
+ },
191
+ ],
192
+ },
193
+ ]
194
+ let structuredValue: Record<string, unknown> | undefined
195
+ for (let attempt = 1; attempt <= WORKFLOW_OUTPUT_FINALIZATION_ATTEMPTS; attempt += 1) {
196
+ try {
197
+ const finalization = await runModelLoop({
198
+ model: input.plan.model,
199
+ messages: finalizerMessages,
200
+ output: {
201
+ name: input.agentStep.id,
202
+ schema: outputSchema,
203
+ validate: validateOutput,
204
+ },
205
+ maxSteps: 1,
206
+ signal: abortSignal,
207
+ })
208
+ if (finalization.status === "aborted") {
209
+ throw (
210
+ abortSignal.reason ?? new DOMException("The workflow agent was aborted.", "AbortError")
211
+ )
212
+ }
213
+ structuredValue = finalization.output
214
+ break
215
+ } catch (error) {
216
+ throwIfEnvironmentFailed()
217
+ if (
218
+ attempt >= WORKFLOW_OUTPUT_FINALIZATION_ATTEMPTS ||
219
+ !(error instanceof StructuredOutputError)
220
+ ) {
221
+ throw error
222
+ }
223
+ finalizerMessages = [
224
+ ...finalizerMessages,
225
+ {
226
+ role: "user",
227
+ content: [
228
+ {
229
+ type: "text",
230
+ text: [
231
+ "The previous response did not satisfy the workflow output schema.",
232
+ "Correct the structure and types using only the same request and final agent answer.",
233
+ ].join(" "),
234
+ },
235
+ ],
236
+ },
237
+ ]
238
+ }
239
+ }
240
+
241
+ if (structuredValue === undefined) {
242
+ throw createSixbError(
243
+ "internal.unexpected",
244
+ `[SixbAgent] Workflow output finalization for agent step '${input.agentStepId}' ended without a value.`,
245
+ { details: traceDetails }
246
+ )
247
+ }
248
+
249
+ throwIfEnvironmentFailed()
250
+ return {
251
+ output: snapshotWorkflowAgentStepOutput({
252
+ workflowId: input.workflowId,
253
+ agentStep: input.agentStep,
254
+ value: structuredValue,
255
+ valueTypesById: input.valueTypesById,
256
+ }),
257
+ modelId: input.plan.model.modelId,
258
+ finishReason,
259
+ trace: agentTraceFromModelSteps(completedSteps, traceDetails),
260
+ }
261
+ } catch (cause) {
262
+ throwIfEnvironmentFailed()
263
+ throw new WorkflowAgentNodeExecutionError({
264
+ phase,
265
+ finishReason,
266
+ trace: agentTraceFromModelSteps(completedSteps, traceDetails),
267
+ cause,
268
+ })
269
+ }
270
+ }
@@ -0,0 +1,234 @@
1
+ import { join, resolve } from "node:path"
2
+ import {
3
+ AGENT_MEMORY_ENTRY,
4
+ AGENT_MEMORY_MANIFEST,
5
+ AGENT_MEMORY_STARTER,
6
+ AGENT_RUNTIME_PROFILE,
7
+ type AgentMemoryManifest,
8
+ agentMemoryFileHash,
9
+ loadSandboxCliAssets,
10
+ } from "@sixb/cli-core"
11
+ import type {
12
+ AgentMemoryRepoView,
13
+ AgentProjectFile,
14
+ AgentSkillDefinition,
15
+ Sandbox,
16
+ SandboxFileRecord,
17
+ } from "@sixb/core"
18
+ import { createSixbError } from "@sixb/core/internal/errors"
19
+ import type { MaterializedArtifacts } from "./artifacts/materialize"
20
+ import type { PreparedAgentAttachmentContext } from "./attachments"
21
+
22
+ /**
23
+ * Where a conversation's artifacts are installed, and their manifest, relative to the context
24
+ * directory. A sandbox that outlives the run clears that directory when it opens, so each run's
25
+ * install starts empty.
26
+ */
27
+ export const AGENT_ARTIFACTS_DIRECTORY = "artifacts"
28
+ export const AGENT_ARTIFACTS_MANIFEST = "context/artifacts.json"
29
+ const ARTIFACTS_RESET_TIMEOUT_MS = 30_000
30
+
31
+ export interface AgentSandboxApiContext {
32
+ readonly env: Readonly<Record<string, string>>
33
+ }
34
+
35
+ export interface PrepareAgentSandboxApiContextInput {
36
+ readonly sandbox: Sandbox
37
+ /** Where the run's files go: relative to the working directory, or absolute. */
38
+ readonly contextDirectory: string
39
+ /** The API origin; commands reach it at the sandbox's credentialed address for it. */
40
+ readonly apiBaseUrl: string
41
+ readonly projectId: string
42
+ readonly actorId?: string
43
+ readonly threadId?: string
44
+ readonly runId: string
45
+ readonly attachments?: PreparedAgentAttachmentContext
46
+ readonly skills: readonly AgentSkillDefinition[]
47
+ /** The run's ontology reference docs and scripts, by path relative to the ontology directory. */
48
+ readonly ontologyFiles: readonly AgentProjectFile[]
49
+ /** A conversation's published artifacts, under {@link AGENT_ARTIFACTS_DIRECTORY}. */
50
+ readonly artifacts?: MaterializedArtifacts
51
+ /** A conversation's memory repos, under `$SIXB_MEMORY_DIR/<repo>/`. */
52
+ readonly memory?: readonly AgentMemoryRepoView[]
53
+ }
54
+
55
+ export async function prepareAgentSandboxApiContext(
56
+ input: PrepareAgentSandboxApiContextInput
57
+ ): Promise<AgentSandboxApiContext> {
58
+ const contextDir = resolve(input.sandbox.workingDirectory, input.contextDirectory)
59
+ const skillsDir = join(contextDir, "skills")
60
+ const ontologyDir = join(contextDir, "ontology")
61
+ const binDir = join(contextDir, "bin")
62
+ const libDir = join(contextDir, "lib")
63
+ const runContextPath = join(contextDir, "context", "run.json")
64
+ const bashEnvPath = join(contextDir, "context", "bash-env")
65
+ const runtimeProbePath = join(contextDir, "runtime", "read-probe.txt")
66
+ const attachmentsManifestPath = join(contextDir, "context", "attachments.json")
67
+ const attachmentsDir = join(contextDir, "attachments")
68
+ const artifactsDir = join(contextDir, AGENT_ARTIFACTS_DIRECTORY)
69
+ const artifactsManifestPath = join(contextDir, AGENT_ARTIFACTS_MANIFEST)
70
+ const memoryDir = join(contextDir, "memory")
71
+ const cli = await loadSandboxCliAssets()
72
+ // The run's commands reach the API through the sandbox's credentialed address, which adds the
73
+ // run token on the way out: no command holds it.
74
+ if (!input.sandbox.credentialedUrl) {
75
+ throw createSixbError(
76
+ "agent.execution_failed",
77
+ `[SixbAgent] Sandbox provider "${input.sandbox.provider}" advertises request credentials but its sandbox has no credentialedUrl.`
78
+ )
79
+ }
80
+ const apiBaseUrl = input.sandbox.credentialedUrl(input.apiBaseUrl)
81
+
82
+ // apiBaseUrl arrives already normalized (see worker.ts), so it is used verbatim. No file or env
83
+ // var of the run holds the token: the sandbox adds it to requests to apiBaseUrl.
84
+ const runContext = JSON.stringify(
85
+ {
86
+ projectId: input.projectId,
87
+ ...(input.actorId === undefined ? {} : { actorId: input.actorId }),
88
+ ...(input.threadId ? { threadId: input.threadId } : {}),
89
+ runId: input.runId,
90
+ runtimeProfile: AGENT_RUNTIME_PROFILE,
91
+ apiBaseUrl,
92
+ attachmentsManifestPath,
93
+ attachmentsDir,
94
+ ...(input.artifacts ? { artifactsManifestPath, artifactsDir } : {}),
95
+ },
96
+ null,
97
+ 2
98
+ )
99
+
100
+ // A persistent workspace keeps what earlier runs installed: each artifact's copy must hold exactly
101
+ // the version installed now, never a file only an older version had.
102
+ if (input.artifacts) {
103
+ const cleared = await input.sandbox.runCommand(
104
+ "bash",
105
+ ["-c", 'rm -rf -- "$SIXB_ARTIFACTS_RESET"'],
106
+ {
107
+ env: { SIXB_ARTIFACTS_RESET: artifactsDir },
108
+ timeout: ARTIFACTS_RESET_TIMEOUT_MS,
109
+ }
110
+ )
111
+ if (cleared.exitCode !== 0 || cleared.timedOut) {
112
+ throw new Error(
113
+ `[SixbAgent] Could not clear ${join(input.contextDirectory, AGENT_ARTIFACTS_DIRECTORY)}: ${cleared.stderr.trim() || `exit ${cleared.exitCode}`}`
114
+ )
115
+ }
116
+ }
117
+
118
+ // Materialize skills, ontology docs + run context through the sandbox capability rather than the host
119
+ // filesystem, so any provider (including non-host-path ones like smolvm) places the bytes in the
120
+ // guest. Awaited before sandbox tools run, so the agent never sees an un-provisioned sandbox.
121
+ await input.sandbox.writeFiles([
122
+ ...input.skills.flatMap((skill) => installFiles(join(skillsDir, skill.name), skill.files)),
123
+ ...installFiles(ontologyDir, input.ontologyFiles),
124
+ { path: join(binDir, "sixb"), contents: cli.launcher, mode: 0o755 },
125
+ { path: join(libDir, "sixb.mjs"), contents: cli.artifact, mode: 0o644 },
126
+ { path: runContextPath, contents: runContext },
127
+ { path: runtimeProbePath, contents: "first\nsixb-runtime-probe\nthird\n", mode: 0o644 },
128
+ {
129
+ path: bashEnvPath,
130
+ contents: [
131
+ "# Installed by Sixb for every sandboxed bash command.",
132
+ `if [ -n "\${SIXB_BIN_DIR:-}" ]; then`,
133
+ ' export PATH="$SIXB_BIN_DIR:$PATH"',
134
+ "fi",
135
+ "export SIXB_BASH_ENV_READY=1",
136
+ "",
137
+ ].join("\n"),
138
+ },
139
+ {
140
+ path: attachmentsManifestPath,
141
+ contents: input.attachments?.manifestJson ?? emptyManifestJson(),
142
+ },
143
+ ...(input.artifacts
144
+ ? [
145
+ { path: artifactsManifestPath, contents: input.artifacts.manifestJson },
146
+ ...input.artifacts.files.map((file) => ({
147
+ ...file,
148
+ path: resolve(input.sandbox.workingDirectory, file.path),
149
+ })),
150
+ ]
151
+ : []),
152
+ ...(input.memory
153
+ ? memoryFiles(memoryDir, join(contextDir, AGENT_MEMORY_MANIFEST), input.memory)
154
+ : []),
155
+ // Last: a file a parent handed its child from its own copy of an artifact keeps its changes.
156
+ ...(input.attachments?.sandboxFiles.map((file) => ({
157
+ path: resolve(input.sandbox.workingDirectory, file.path),
158
+ contents: file.bytes,
159
+ })) ?? []),
160
+ ])
161
+
162
+ return {
163
+ env: {
164
+ SIXB_API_BASE_URL: apiBaseUrl,
165
+ SIXB_CONTEXT_DIR: contextDir,
166
+ SIXB_SKILLS_DIR: skillsDir,
167
+ SIXB_ONTOLOGY_DIR: ontologyDir,
168
+ SIXB_BIN_DIR: binDir,
169
+ SIXB_AGENT_RUNTIME_PROFILE: AGENT_RUNTIME_PROFILE,
170
+ SIXB_RUNTIME_PROBE_FILE: runtimeProbePath,
171
+ BASH_ENV: bashEnvPath,
172
+ SIXB_RUN_CONTEXT: runContextPath,
173
+ SIXB_ATTACHMENTS: attachmentsManifestPath,
174
+ SIXB_ATTACHMENT_DIR: attachmentsDir,
175
+ ...(input.artifacts
176
+ ? { SIXB_ARTIFACTS: artifactsManifestPath, SIXB_ARTIFACTS_DIR: artifactsDir }
177
+ : {}),
178
+ ...(input.memory ? { SIXB_MEMORY_DIR: memoryDir } : {}),
179
+ SIXB_PROJECT_ID: input.projectId,
180
+ ...(input.actorId === undefined ? {} : { SIXB_ACTOR_ID: input.actorId }),
181
+ ...(input.threadId ? { SIXB_THREAD_ID: input.threadId } : {}),
182
+ SIXB_RUN_ID: input.runId,
183
+ },
184
+ }
185
+ }
186
+
187
+ /** Records that install project files under `dir`, ready to hand to {@link Sandbox.writeFiles}. */
188
+ function installFiles(dir: string, files: readonly AgentProjectFile[]): SandboxFileRecord[] {
189
+ return files.map((file) => ({
190
+ path: join(dir, file.path),
191
+ contents: file.contents,
192
+ ...(file.mode === undefined ? {} : { mode: file.mode }),
193
+ }))
194
+ }
195
+
196
+ /**
197
+ * Each repo's files, a starter MEMORY.md for a repo without one, and the manifest `sixb memory`
198
+ * saves against. The starter is not in the manifest, so the first save stores it.
199
+ */
200
+ function memoryFiles(
201
+ dir: string,
202
+ manifestPath: string,
203
+ repos: readonly AgentMemoryRepoView[]
204
+ ): SandboxFileRecord[] {
205
+ const manifest: AgentMemoryManifest = {
206
+ repos: Object.fromEntries(
207
+ repos.map((repo) => [
208
+ repo.repo,
209
+ {
210
+ revision: repo.revision,
211
+ files: Object.fromEntries(
212
+ repo.files.map((file) => [file.path, agentMemoryFileHash(file.contents)])
213
+ ),
214
+ },
215
+ ])
216
+ ),
217
+ }
218
+ return [
219
+ ...repos.flatMap((repo) => [
220
+ ...repo.files.map((file) => ({
221
+ path: join(dir, repo.repo, ...file.path.split("/")),
222
+ contents: file.contents,
223
+ })),
224
+ ...(repo.files.some((file) => file.path === AGENT_MEMORY_ENTRY)
225
+ ? []
226
+ : [{ path: join(dir, repo.repo, AGENT_MEMORY_ENTRY), contents: AGENT_MEMORY_STARTER }]),
227
+ ]),
228
+ { path: manifestPath, contents: `${JSON.stringify(manifest, null, 2)}\n` },
229
+ ]
230
+ }
231
+
232
+ function emptyManifestJson(): string {
233
+ return JSON.stringify({ attachments: [] }, null, 2)
234
+ }
@@ -0,0 +1,26 @@
1
+ import { posix } from "node:path"
2
+ import type { FileRef } from "@sixb/core"
3
+ import { fileRefKey } from "./file-ref"
4
+
5
+ /** Track durable files materialized in the current run sandbox. */
6
+ export class AgentSandboxFileRegistry {
7
+ readonly #byAbsolutePath = new Map<string, FileRef>()
8
+ readonly #pathByFileRef = new Map<string, string>()
9
+
10
+ register(absolutePath: string, fileRef: FileRef): void {
11
+ const normalizedPath = posix.normalize(absolutePath)
12
+ this.#byAbsolutePath.set(normalizedPath, fileRef)
13
+ const key = fileRefKey(fileRef)
14
+ if (!this.#pathByFileRef.has(key)) {
15
+ this.#pathByFileRef.set(key, normalizedPath)
16
+ }
17
+ }
18
+
19
+ get(absolutePath: string): FileRef | undefined {
20
+ return this.#byAbsolutePath.get(posix.normalize(absolutePath))
21
+ }
22
+
23
+ pathFor(fileRef: FileRef): string | undefined {
24
+ return this.#pathByFileRef.get(fileRefKey(fileRef))
25
+ }
26
+ }