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