@sixb/agent 0.1.0 → 0.2.1

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 (102) hide show
  1. package/dist/agent-prompt.d.ts +34 -28
  2. package/dist/agent-prompt.d.ts.map +1 -1
  3. package/dist/artifacts/publish-tool.d.ts +1 -1
  4. package/dist/attachments.d.ts +42 -1
  5. package/dist/attachments.d.ts.map +1 -1
  6. package/dist/child-files.d.ts +0 -5
  7. package/dist/child-files.d.ts.map +1 -1
  8. package/dist/computer-runner.d.ts +16 -7
  9. package/dist/computer-runner.d.ts.map +1 -1
  10. package/dist/context-budget.d.ts +23 -17
  11. package/dist/context-budget.d.ts.map +1 -1
  12. package/dist/context-compaction.d.ts +118 -18
  13. package/dist/context-compaction.d.ts.map +1 -1
  14. package/dist/context-guard.d.ts +69 -0
  15. package/dist/context-guard.d.ts.map +1 -0
  16. package/dist/conversation-messages.d.ts +33 -0
  17. package/dist/conversation-messages.d.ts.map +1 -0
  18. package/dist/execution-plan.d.ts +5 -1
  19. package/dist/execution-plan.d.ts.map +1 -1
  20. package/dist/failure.d.ts.map +1 -1
  21. package/dist/index.js +4916 -2697
  22. package/dist/index.js.map +41 -34
  23. package/dist/inline-images.d.ts +28 -0
  24. package/dist/inline-images.d.ts.map +1 -0
  25. package/dist/message-authors.d.ts +4 -4
  26. package/dist/message-authors.d.ts.map +1 -1
  27. package/dist/message-times.d.ts +4 -3
  28. package/dist/message-times.d.ts.map +1 -1
  29. package/dist/model-adapters.d.ts +6 -2
  30. package/dist/model-adapters.d.ts.map +1 -1
  31. package/dist/prompt-cache.d.ts +28 -0
  32. package/dist/prompt-cache.d.ts.map +1 -0
  33. package/dist/run-agent-turn.d.ts +33 -3
  34. package/dist/run-agent-turn.d.ts.map +1 -1
  35. package/dist/run-child.d.ts.map +1 -1
  36. package/dist/run-conversation-turn.d.ts.map +1 -1
  37. package/dist/run-environment.d.ts +35 -5
  38. package/dist/run-environment.d.ts.map +1 -1
  39. package/dist/run-files-lock.d.ts +16 -0
  40. package/dist/run-files-lock.d.ts.map +1 -0
  41. package/dist/run-subagent.d.ts +15 -1
  42. package/dist/run-subagent.d.ts.map +1 -1
  43. package/dist/run-workflow-agent-node.d.ts +5 -0
  44. package/dist/run-workflow-agent-node.d.ts.map +1 -1
  45. package/dist/sandbox-api-context.d.ts.map +1 -1
  46. package/dist/subagent-context.d.ts +50 -0
  47. package/dist/subagent-context.d.ts.map +1 -0
  48. package/dist/subagent-continuation.d.ts +10 -4
  49. package/dist/subagent-continuation.d.ts.map +1 -1
  50. package/dist/subagent-tools.d.ts +11 -0
  51. package/dist/subagent-tools.d.ts.map +1 -1
  52. package/dist/thread-context.d.ts +7 -2
  53. package/dist/thread-context.d.ts.map +1 -1
  54. package/dist/tools/bash.d.ts +8 -0
  55. package/dist/tools/bash.d.ts.map +1 -1
  56. package/dist/tools/model-spec.d.ts +7 -2
  57. package/dist/tools/model-spec.d.ts.map +1 -1
  58. package/dist/tools/result-media.d.ts +53 -10
  59. package/dist/tools/result-media.d.ts.map +1 -1
  60. package/dist/tools/result-output.d.ts +1 -1
  61. package/dist/tools/result-output.d.ts.map +1 -1
  62. package/dist/tools/tool-outputs.d.ts +63 -0
  63. package/dist/tools/tool-outputs.d.ts.map +1 -0
  64. package/dist/types.d.ts +9 -2
  65. package/dist/types.d.ts.map +1 -1
  66. package/package.json +4 -4
  67. package/src/agent-prompt.ts +178 -76
  68. package/src/attachments.ts +275 -84
  69. package/src/child-files.ts +1 -6
  70. package/src/computer-runner.ts +75 -23
  71. package/src/context-budget.ts +110 -94
  72. package/src/context-compaction.ts +1007 -187
  73. package/src/context-guard.ts +826 -0
  74. package/src/conversation-messages.ts +86 -0
  75. package/src/execution-plan.ts +22 -2
  76. package/src/failure.ts +11 -0
  77. package/src/inline-images.ts +69 -0
  78. package/src/message-authors.ts +5 -5
  79. package/src/message-times.ts +8 -5
  80. package/src/model-adapters.ts +59 -13
  81. package/src/prompt-cache.ts +40 -0
  82. package/src/run-agent-turn.ts +234 -72
  83. package/src/run-child.ts +30 -5
  84. package/src/run-conversation-turn.ts +16 -1
  85. package/src/run-environment.ts +553 -106
  86. package/src/run-files-lock.ts +118 -0
  87. package/src/run-subagent.ts +132 -46
  88. package/src/run-workflow-agent-node.ts +84 -10
  89. package/src/sandbox-api-context.ts +3 -0
  90. package/src/skills/sixb-artifacts/canvas.md +1 -1
  91. package/src/skills/sixb-artifacts/page.md +1 -1
  92. package/src/skills/sixb-artifacts/slides.md +1 -1
  93. package/src/subagent-context.ts +182 -0
  94. package/src/subagent-continuation.ts +11 -6
  95. package/src/subagent-tools.ts +73 -11
  96. package/src/thread-context.ts +9 -3
  97. package/src/tools/bash.ts +17 -1
  98. package/src/tools/model-spec.ts +9 -4
  99. package/src/tools/result-media.ts +286 -82
  100. package/src/tools/result-output.ts +4 -2
  101. package/src/tools/tool-outputs.ts +464 -0
  102. package/src/types.ts +14 -2
@@ -0,0 +1,118 @@
1
+ import { link, readFile, rm, writeFile } from "node:fs/promises"
2
+ import { delay } from "./abort"
3
+
4
+ /** How often a run waiting for a thread's files directory looks again. */
5
+ const POLL_MS = 100
6
+
7
+ /**
8
+ * How long a run waits for a live holder before it takes the directory over. Only one run of a
9
+ * thread is active at a time, so a holder still alive after its run ended is releasing (seconds)
10
+ * or stopping on a lost lease (its next renewal, within seconds); past this, its process id was
11
+ * reused, or it hangs.
12
+ */
13
+ const TAKEOVER_MS = 60_000
14
+
15
+ /** Who holds a thread's files directory, as its lock file says. */
16
+ interface Holder {
17
+ readonly pid: number
18
+ readonly runId: string
19
+ }
20
+
21
+ /**
22
+ * Hold a thread's files directory for one run, across every process on the computer: each `sixb`
23
+ * opened in the folder shares the directory, and the next turn of a thread can start in another
24
+ * one while the last turn's release still removes the directory. The lock is a file beside the
25
+ * directory, created exclusively and naming its holder; one whose process is gone is stale, and
26
+ * taken over. Resolves with the release, which removes the lock only while it is still this run's.
27
+ *
28
+ * Only one run of a thread is active at a time, so no two runs take a stale lock over at once.
29
+ */
30
+ export async function holdRunFiles(input: {
31
+ /** The thread's files directory. */
32
+ readonly directory: string
33
+ readonly runId: string
34
+ readonly signal: AbortSignal
35
+ }): Promise<() => Promise<void>> {
36
+ const lock = `${input.directory}.lock`
37
+ const own = JSON.stringify({ pid: process.pid, runId: input.runId } satisfies Holder)
38
+ const deadline = Date.now() + TAKEOVER_MS
39
+
40
+ for (;;) {
41
+ if (await create(lock, own, input.runId)) break
42
+
43
+ const holder = await readHolder(lock)
44
+ // Released between the two reads: try again at once.
45
+ if (holder === null) continue
46
+
47
+ if (holder === undefined || !alive(holder.pid) || Date.now() >= deadline) {
48
+ if (holder && alive(holder.pid)) {
49
+ console.warn(
50
+ `[SixbAgent] Run '${input.runId}' takes over ${input.directory} from run '${holder.runId}' (process ${holder.pid}), which did not give it back in time.`
51
+ )
52
+ }
53
+ await rm(lock, { force: true })
54
+ continue
55
+ }
56
+
57
+ await delay(POLL_MS, input.signal)
58
+ }
59
+
60
+ return async () => {
61
+ if ((await readFile(lock, "utf8").catch(() => null)) === own) await rm(lock, { force: true })
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Create the lock file, unless one exists. Linked from a file already written, so no reader ever
67
+ * finds it empty.
68
+ */
69
+ async function create(lock: string, contents: string, runId: string): Promise<boolean> {
70
+ const written = `${lock}.${process.pid}.${runId}`
71
+ await writeFile(written, contents)
72
+ try {
73
+ await link(written, lock)
74
+ return true
75
+ } catch (error) {
76
+ if (errorCode(error) === "EEXIST") return false
77
+ throw error
78
+ } finally {
79
+ await rm(written, { force: true })
80
+ }
81
+ }
82
+
83
+ /** The lock's holder; null once it is gone, undefined when it names none a run can wait for. */
84
+ async function readHolder(lock: string): Promise<Holder | null | undefined> {
85
+ let text: string
86
+ try {
87
+ text = await readFile(lock, "utf8")
88
+ } catch (error) {
89
+ if (errorCode(error) === "ENOENT") return null
90
+ throw error
91
+ }
92
+
93
+ try {
94
+ const parsed: unknown = JSON.parse(text)
95
+ if (typeof parsed !== "object" || parsed === null) return undefined
96
+
97
+ const { pid, runId } = parsed as Record<string, unknown>
98
+ return Number.isSafeInteger(pid) && typeof runId === "string"
99
+ ? { pid: pid as number, runId }
100
+ : undefined
101
+ } catch {
102
+ return undefined
103
+ }
104
+ }
105
+
106
+ /** Whether a process runs: one owned by another user still does. */
107
+ function alive(pid: number): boolean {
108
+ try {
109
+ process.kill(pid, 0)
110
+ return true
111
+ } catch (error) {
112
+ return errorCode(error) === "EPERM"
113
+ }
114
+ }
115
+
116
+ function errorCode(error: unknown): string | undefined {
117
+ return error instanceof Error && "code" in error ? String(error.code) : undefined
118
+ }
@@ -1,5 +1,6 @@
1
1
  import type { AgentMessagePart } from "@sixb/core"
2
2
  import {
3
+ type AgentContextBudget,
3
4
  type AgentRunSession,
4
5
  createAgentMessageId,
5
6
  type PausableModelLoopResult,
@@ -15,14 +16,26 @@ import {
15
16
  coerceAgentRunFinishReason,
16
17
  type SubagentRunRecord,
17
18
  } from "@sixb/core/storage"
18
- import { renderCurrentTime } from "./agent-prompt"
19
+ import { renderCurrentTime, sentSettings } from "./agent-prompt"
19
20
  import { unansweredQuestion } from "./ask-parent-tool"
20
- import { attachmentKey, toolResultAttachmentKey } from "./attachments"
21
21
  import { storeChildOutputs } from "./child-files"
22
+ import { createAgentContextGuard } from "./context-guard"
22
23
  import { throwIfExecutionLost } from "./errors"
23
24
  import type { ResolvedAgentExecutionPlan } from "./execution-plan"
24
- import { agentTraceFromModelSteps, agentTraceFromPartialModelLoop } from "./model-adapters"
25
+ import {
26
+ type AgentToolOutputFileOf,
27
+ agentTraceFromModelSteps,
28
+ agentTraceFromPartialModelLoop,
29
+ } from "./model-adapters"
30
+ import { markReducedSteps } from "./run-agent-turn"
31
+ import type { SubagentAgentExecutionEnvironment } from "./run-environment"
25
32
  import { monitorSandboxReadiness } from "./sandbox-readiness"
33
+ import {
34
+ type SubagentThreadContext,
35
+ subagentContextFailure,
36
+ subagentModelMessages,
37
+ subagentPromptCaching,
38
+ } from "./subagent-context"
26
39
  import type { SubagentHistory } from "./subagent-continuation"
27
40
  import type { SubagentDelivery, SubagentInbox } from "./subagent-inbox"
28
41
  import type { AgentTurnRuntime } from "./turn-runtime"
@@ -45,6 +58,18 @@ export interface SubagentWork {
45
58
  export async function runSubagent(input: {
46
59
  readonly context: AgentTurnContext
47
60
  readonly plan: ResolvedAgentExecutionPlan
61
+ /**
62
+ * The limits every call of the child keeps under, what its environment's preflight left of its
63
+ * thread, and how it compacts that thread from within.
64
+ */
65
+ readonly contextLimits: {
66
+ readonly budget: AgentContextBudget
67
+ readonly thread: SubagentThreadContext
68
+ readonly compactInRun?: SubagentAgentExecutionEnvironment["compactInRun"]
69
+ readonly bytesPerToken?: number
70
+ /** What the child's latest counted call measured (see prepareAgentModel). */
71
+ readonly measuredBytesPerToken?: () => number | undefined
72
+ }
48
73
  readonly run: SubagentRunRecord
49
74
  /** The child's session: its finish is fenced by the run's execution token. */
50
75
  readonly session: AgentRunSession
@@ -64,29 +89,80 @@ export async function runSubagent(input: {
64
89
  readonly inbox: SubagentInbox
65
90
  }): Promise<SubagentRunRecord> {
66
91
  const { context, plan, run, thread, runtime, inbox } = input
67
- const messages = subagentModelMessages({
68
- context,
92
+ const { budget, compactInRun, bytesPerToken, measuredBytesPerToken } = input.contextLimits
93
+ const caching = subagentPromptCaching({
94
+ projectId: context.id,
69
95
  thread,
96
+ run,
70
97
  history: input.history,
71
- timeZone: plan.timeZone ?? context.projectTimeZone,
98
+ })
99
+ const createdAt = renderCurrentTime(
100
+ thread.createdAt,
101
+ sentSettings(plan, { timeZone: context.projectTimeZone, locale: context.projectLocale })
102
+ )
103
+ const messages: ModelMessage[] = [
104
+ { role: "system", content: context.systemPrompt },
105
+ ...subagentModelMessages({
106
+ thread: input.contextLimits.thread,
107
+ ...(context.attachmentContext ? { attachmentContext: context.attachmentContext } : {}),
108
+ createdAt,
109
+ }),
110
+ ]
111
+ const guard = createAgentContextGuard({
112
+ budget,
113
+ tools: context.tools.map((tool) => ({
114
+ name: tool.name,
115
+ description: tool.description,
116
+ inputSchema: tool.inputSchema,
117
+ })),
118
+ ...(bytesPerToken === undefined ? {} : { bytesPerToken }),
119
+ ...(measuredBytesPerToken === undefined ? {} : { measuredBytesPerToken }),
120
+ ...(compactInRun
121
+ ? {
122
+ compact: async (compacting) => {
123
+ const request = await compactInRun(compacting)
124
+ return (
125
+ request && [
126
+ { role: "system" as const, content: request.systemPrompt },
127
+ ...request.messages,
128
+ ]
129
+ )
130
+ },
131
+ }
132
+ : {}),
72
133
  })
73
134
  const sandboxReadiness = monitorSandboxReadiness(context.sandboxReady)
74
135
  const abortSignal = AbortSignal.any([runtime.signal, sandboxReadiness.signal])
75
136
  let chunkIndex = 0
76
137
  const generation = await runModelLoop({
77
138
  model: plan.model,
78
- messages: [{ role: "system", content: context.systemPrompt }, ...messages],
139
+ messages,
79
140
  tools: context.tools,
80
141
  ...(plan.reasoning === undefined ? {} : { reasoning: plan.reasoning }),
142
+ ...(plan.maxSteps === undefined ? {} : { maxSteps: plan.maxSteps }),
143
+ caching,
81
144
  // A message from the parent comes after the step that was running when it arrived, and stays
82
- // in the history of every later step.
145
+ // in the history of every later step. The guard weighs the step before it: what it compacts
146
+ // is the history the run started from, never what the parent sent it since.
83
147
  prepareStep: async (step) => {
84
148
  const prepared = await context.prepareStep?.(step)
149
+ const guarded = await guard.prepareStep({
150
+ ...step,
151
+ messages: prepared?.messages ?? step.messages,
152
+ })
85
153
  const mail = await inbox.take(step.stepIndex)
86
- if (!mail) return prepared
154
+ // The guard's request, when it reduced the one prepared, and the room its answer has.
155
+ if (!mail) return { ...prepared, ...guarded }
87
156
 
88
- return { messages: [...(prepared?.messages ?? step.messages), ...toModelMessages([mail])] }
157
+ return {
158
+ ...guarded,
159
+ messages: [
160
+ ...(guarded?.messages ?? prepared?.messages ?? step.messages),
161
+ ...toModelMessages([mail]),
162
+ ],
163
+ }
89
164
  },
165
+ recoverStep: guard.recoverStep,
90
166
  // One that arrives as the child answers is read too: it writes its result again, after it.
91
167
  beforeComplete: async (_step, stepIndex) => {
92
168
  const mail = await inbox.take(stepIndex + 1, { afterAnswer: true })
@@ -100,8 +176,16 @@ export async function runSubagent(input: {
100
176
  // turn ended without answering.
101
177
  pauseAfterStep: async () =>
102
178
  inbox.deferred !== undefined || (await input.session.heldCalls.holdsRun()),
179
+ }).catch((error: unknown) => {
180
+ throw subagentContextFailure(error, run) ?? error
103
181
  })
104
- const work = subagentWorkMessages(generation, run, inbox.deliveries)
182
+ const work = subagentWorkMessages(
183
+ generation,
184
+ run,
185
+ inbox.deliveries,
186
+ guard.reducedFromStep(),
187
+ context.outputFileOf
188
+ )
105
189
  if (input.work) input.work.messages = work
106
190
 
107
191
  return settleSubagent({
@@ -142,6 +226,21 @@ async function settleSubagent(
142
226
  return finishSubagent({ ...input, finishReason: "awaiting_answer" })
143
227
  }
144
228
 
229
+ // Nobody watches a child: its limit ends it, and its parent decides what next. What it wrote
230
+ // stays in its thread, and its parent's wait reads the last of it.
231
+ if (generation.stepLimitReached) {
232
+ const steps = generation.steps.length
233
+ const remedy = "Spawn it again with a narrower task, or do the rest yourself."
234
+ throw withFailureMessage(
235
+ createSixbError(
236
+ "agent.step_limit_reached",
237
+ `[SixbAgent] Subagent run '${run.id}' stopped after ${steps} steps before finishing its task. ${remedy}`,
238
+ { details: { parentRunId: run.parentRunId, runId: run.id } }
239
+ ),
240
+ `The subagent stopped after ${steps} steps before finishing its task. ${remedy}`
241
+ )
242
+ }
243
+
145
244
  // The parent would read a cut-short answer as complete: it gets the cause instead.
146
245
  if (generation.finishReason === "length") {
147
246
  const remedy = "Spawn it again with lower reasoning or a narrower task."
@@ -227,7 +326,10 @@ async function finishSubagent(input: {
227
326
  function subagentWorkMessages(
228
327
  generation: PausableModelLoopResult,
229
328
  run: SubagentRunRecord,
230
- deliveries: readonly SubagentDelivery[]
329
+ deliveries: readonly SubagentDelivery[],
330
+ /** The first step whose request the guard reduced: it and those after it are marked so. */
331
+ reducedFromStep: number | undefined,
332
+ outputFileOf: AgentToolOutputFileOf | undefined
231
333
  ): readonly AppendAgentMessageInput[] {
232
334
  const details = { threadId: run.threadId, runId: run.id }
233
335
  const messages: AppendAgentMessageInput[] = []
@@ -241,13 +343,25 @@ function subagentWorkMessages(
241
343
  parts,
242
344
  })
243
345
  }
244
- const pushSteps = (parts: readonly AgentMessagePart[]) => {
245
- if (parts.some((part) => part.type !== "step-start")) push("assistant", parts)
346
+ // Steps from `from` on, the ones whose request was reduced marked so.
347
+ const pushSteps = (parts: readonly AgentMessagePart[], from: number) => {
348
+ const marked = markReducedSteps(
349
+ parts,
350
+ reducedFromStep === undefined ? undefined : reducedFromStep - from
351
+ )
352
+ if (marked.some((part) => part.type !== "step-start")) push("assistant", marked)
246
353
  }
247
354
 
248
355
  let from = 0
249
356
  for (const delivery of deliveries) {
250
- pushSteps(agentTraceFromModelSteps(generation.steps.slice(from, delivery.afterSteps), details))
357
+ pushSteps(
358
+ agentTraceFromModelSteps(
359
+ generation.steps.slice(from, delivery.afterSteps),
360
+ details,
361
+ outputFileOf
362
+ ),
363
+ from
364
+ )
251
365
  push("user", delivery.parts)
252
366
  from = delivery.afterSteps
253
367
  }
@@ -255,41 +369,13 @@ function subagentWorkMessages(
255
369
  const rest = generation.steps.slice(from)
256
370
  pushSteps(
257
371
  generation.status === "aborted"
258
- ? agentTraceFromPartialModelLoop(rest, generation.partialContent, details)
259
- : agentTraceFromModelSteps(rest, details)
372
+ ? agentTraceFromPartialModelLoop(rest, generation.partialContent, details, outputFileOf)
373
+ : agentTraceFromModelSteps(rest, details, outputFileOf),
374
+ from
260
375
  )
261
376
  return messages
262
377
  }
263
378
 
264
- /**
265
- * The child's thread as its model reads it. The task, its first message, closes with the time the
266
- * thread was created, so each run of the child replays the same bytes. Files a tool showed it are
267
- * projected again as a turn projects its own.
268
- */
269
- function subagentModelMessages(input: {
270
- readonly context: AgentTurnContext
271
- readonly thread: AgentThreadRecord
272
- readonly history: SubagentHistory
273
- readonly timeZone: string
274
- }): ModelMessage[] {
275
- const { messages } = input.history
276
- const projections = input.context.attachmentContext
277
- const taskId = messages[0]?.id
278
- const createdAt = renderCurrentTime(input.thread.createdAt, input.timeZone)
279
-
280
- return toModelMessages(messages, {
281
- userMessageSuffix: (message) => (message.id === taskId ? createdAt : undefined),
282
- fileText: ({ message, partIndex }) =>
283
- projections?.promptTextByPartKey.get(attachmentKey(message.id, partIndex)),
284
- fileData: ({ message, partIndex }) =>
285
- projections?.modelFileDataByPartKey.get(attachmentKey(message.id, partIndex)),
286
- toolResultFileText: ({ message, partIndex, contentIndex }) =>
287
- projections?.promptTextByPartKey.get(
288
- toolResultAttachmentKey(message.id, partIndex, contentIndex)
289
- ),
290
- })
291
- }
292
-
293
379
  function assertSubagentCanFinalize(input: {
294
380
  readonly runtime: AgentTurnRuntime
295
381
  readonly sandboxReadiness: ReturnType<typeof monitorSandboxReadiness>
@@ -1,5 +1,5 @@
1
1
  import type { AgentMessagePart, SchemaOrRef, ValueType } from "@sixb/core"
2
- import { runModelLoop } from "@sixb/core/internal/agents"
2
+ import { type AgentContextBudget, runModelLoop } from "@sixb/core/internal/agents"
3
3
  import { createSixbError, withFailureMessage } from "@sixb/core/internal/errors"
4
4
  import { schemaRecordToJsonSchema } from "@sixb/core/internal/ontology"
5
5
  import {
@@ -9,9 +9,14 @@ import {
9
9
  type WorkflowIOSnapshot,
10
10
  } from "@sixb/core/internal/workflows"
11
11
  import type { ModelMessage, ModelStep } from "@sixb/core/models"
12
- import { StructuredOutputError, UnsupportedModelFeatureError } from "@sixb/core/models"
12
+ import {
13
+ ModelProviderError,
14
+ StructuredOutputError,
15
+ UnsupportedModelFeatureError,
16
+ } from "@sixb/core/models"
13
17
  import { type AgentRunFinishReason, coerceAgentRunFinishReason } from "@sixb/core/storage"
14
- import { renderWorkflowOutputFinalizerPrompt, withCurrentTime } from "./agent-prompt"
18
+ import { renderWorkflowOutputFinalizerPrompt, sentSettings, withCurrentTime } from "./agent-prompt"
19
+ import { createAgentContextGuard } from "./context-guard"
15
20
  import type { ResolvedAgentExecutionPlan } from "./execution-plan"
16
21
  import { agentTraceFromModelSteps } from "./model-adapters"
17
22
  import { monitorSandboxReadiness } from "./sandbox-readiness"
@@ -23,6 +28,10 @@ export interface RunWorkflowAgentNodeInput {
23
28
  readonly context: AgentTurnContext
24
29
  readonly agentStepId: string
25
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
26
35
  readonly agentStep: AgentStepDefinition
27
36
  readonly workflowId: string
28
37
  readonly workflowRunId: string
@@ -119,6 +128,22 @@ export async function runWorkflowAgentNode(
119
128
  schema: outputSchema,
120
129
  })
121
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
122
147
  const research = await runModelLoop({
123
148
  model: input.plan.model,
124
149
  messages: [
@@ -129,18 +154,31 @@ export async function runWorkflowAgentNode(
129
154
  withCurrentTime(
130
155
  { role: "user", content: [{ type: "text", text: input.prompt }] },
131
156
  input.createdAt,
132
- input.context.projectTimeZone
157
+ sentSettings(input.plan, {
158
+ timeZone: input.context.projectTimeZone,
159
+ locale: input.context.projectLocale,
160
+ })
133
161
  ),
134
162
  ],
135
- tools: input.context.tools,
163
+ tools,
136
164
  ...(input.plan.reasoning === undefined ? {} : { reasoning: input.plan.reasoning }),
137
- ...(input.context.prepareStep === undefined
138
- ? {}
139
- : { prepareStep: input.context.prepareStep }),
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,
140
176
  signal: abortSignal,
141
177
  onStepEnd: (step) => {
142
178
  completedSteps.push(step)
143
179
  },
180
+ }).catch((error: unknown) => {
181
+ throw workflowContextFailure(error, input.agentStepId, traceDetails) ?? error
144
182
  })
145
183
  throwIfEnvironmentFailed()
146
184
  if (research.status === "aborted") {
@@ -149,6 +187,18 @@ export async function runWorkflowAgentNode(
149
187
 
150
188
  const researchText = research.output
151
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
+ }
152
202
  // A cut-short answer would be structured as if it were complete; its text is never passed on.
153
203
  if (finishReason === "length") {
154
204
  const remedy =
@@ -256,15 +306,39 @@ export async function runWorkflowAgentNode(
256
306
  }),
257
307
  modelId: input.plan.model.modelId,
258
308
  finishReason,
259
- trace: agentTraceFromModelSteps(completedSteps, traceDetails),
309
+ trace: agentTraceFromModelSteps(completedSteps, traceDetails, input.context.outputFileOf),
260
310
  }
261
311
  } catch (cause) {
262
312
  throwIfEnvironmentFailed()
263
313
  throw new WorkflowAgentNodeExecutionError({
264
314
  phase,
265
315
  finishReason,
266
- trace: agentTraceFromModelSteps(completedSteps, traceDetails),
316
+ trace: agentTraceFromModelSteps(completedSteps, traceDetails, input.context.outputFileOf),
267
317
  cause,
268
318
  })
269
319
  }
270
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
+ }
@@ -18,6 +18,7 @@ import type {
18
18
  import { createSixbError } from "@sixb/core/internal/errors"
19
19
  import type { MaterializedArtifacts } from "./artifacts/materialize"
20
20
  import type { PreparedAgentAttachmentContext } from "./attachments"
21
+ import { TOOL_OUTPUTS_DIRECTORY } from "./tools/tool-outputs"
21
22
 
22
23
  /**
23
24
  * Where a conversation's artifacts are installed, and their manifest, relative to the context
@@ -68,6 +69,7 @@ export async function prepareAgentSandboxApiContext(
68
69
  const artifactsDir = join(contextDir, AGENT_ARTIFACTS_DIRECTORY)
69
70
  const artifactsManifestPath = join(contextDir, AGENT_ARTIFACTS_MANIFEST)
70
71
  const memoryDir = join(contextDir, "memory")
72
+ const toolOutputsDir = join(contextDir, TOOL_OUTPUTS_DIRECTORY)
71
73
  const cli = await loadSandboxCliAssets()
72
74
  // The run's commands reach the API through the sandbox's credentialed address, which adds the
73
75
  // run token on the way out: no command holds it.
@@ -172,6 +174,7 @@ export async function prepareAgentSandboxApiContext(
172
174
  SIXB_RUN_CONTEXT: runContextPath,
173
175
  SIXB_ATTACHMENTS: attachmentsManifestPath,
174
176
  SIXB_ATTACHMENT_DIR: attachmentsDir,
177
+ SIXB_TOOL_OUTPUTS_DIR: toolOutputsDir,
175
178
  ...(input.artifacts
176
179
  ? { SIXB_ARTIFACTS: artifactsManifestPath, SIXB_ARTIFACTS_DIR: artifactsDir }
177
180
  : {}),
@@ -92,7 +92,7 @@ text on a board.
92
92
 
93
93
  Once a canvas publishes, Sixb opens each board at its own size in the sandbox's browser, in light
94
94
  and dark mode or the one its `theme.json` pins, and warns as it does for a page, naming the board.
95
- The result names each board's screenshot, `<id>.png`, under `.sixb/agent/checks/`.
95
+ The result names each board's screenshot, `<id>.png`, under `$SIXB_CONTEXT_DIR/checks/`.
96
96
 
97
97
  1. Open the screenshots with `view_file` and look at each board as the reader will.
98
98
  2. Fix what the warnings name and what you see, in the boards' files or `canvas.json`.
@@ -189,7 +189,7 @@ light and in dark mode or in the one mode its `theme.json` pins, and warns about
189
189
  screen's right edge, drawn over other text, or cut off; text under 12px; a control under 24px;
190
190
  text under WCAG AA contrast; an image that did not load; or a script error. Each warning names the
191
191
  width, the element as CSS names it, and where it is on the page. The result names the screenshots,
192
- `desktop.png` and `phone.png`, each the page's top 4000px, under `.sixb/agent/checks/`. The page's
192
+ `desktop.png` and `phone.png`, each the page's top 4000px, under `$SIXB_CONTEXT_DIR/checks/`. The page's
193
193
  queries run as the user who asked, so the screenshots show their rows; a query that fails for them
194
194
  is a warning, and the page is checked with `sixb.query` rejecting.
195
195
 
@@ -120,7 +120,7 @@ slide that has something past its edge, running
120
120
  into the footer, drawn over other text, or cut off; text under 18px; text under WCAG AA contrast;
121
121
  an image that did not load; or an error while the deck loaded. Each warning names the slide, the
122
122
  element as CSS names it (`p.kicker`), and where it is on the 1280×720 slide. The result names
123
- the screenshots, one per slide, under `.sixb/agent/checks/`.
123
+ the screenshots, one per slide, under `$SIXB_CONTEXT_DIR/checks/`.
124
124
 
125
125
  1. Open the screenshots with `view_file`, at least the slides a warning names, and look at each
126
126
  as the reader will: is anything crowded, misaligned, or unreadable?