@sixb/agent 0.2.4 → 0.2.6

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 (117) hide show
  1. package/README.md +2 -2
  2. package/dist/agent-prompt.d.ts +13 -3
  3. package/dist/agent-prompt.d.ts.map +1 -1
  4. package/dist/artifacts/layout-check/layout-check.d.ts +21 -24
  5. package/dist/artifacts/layout-check/layout-check.d.ts.map +1 -1
  6. package/dist/artifacts/publish-tool.d.ts.map +1 -1
  7. package/dist/background-commands.d.ts +2 -2
  8. package/dist/context-compaction.d.ts.map +1 -1
  9. package/dist/conversation-messages.d.ts +1 -1
  10. package/dist/conversation-messages.d.ts.map +1 -1
  11. package/dist/index.d.ts +0 -1
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +11082 -9281
  14. package/dist/index.js.map +37 -33
  15. package/dist/login-shell.d.ts +18 -2
  16. package/dist/login-shell.d.ts.map +1 -1
  17. package/dist/model-adapters.d.ts +5 -2
  18. package/dist/model-adapters.d.ts.map +1 -1
  19. package/dist/model-lines.d.ts +1 -0
  20. package/dist/model-lines.d.ts.map +1 -1
  21. package/dist/run-agent-turn.d.ts +3 -14
  22. package/dist/run-agent-turn.d.ts.map +1 -1
  23. package/dist/run-conversation-turn.d.ts.map +1 -1
  24. package/dist/run-environment.d.ts.map +1 -1
  25. package/dist/run-sandbox.d.ts +11 -1
  26. package/dist/run-sandbox.d.ts.map +1 -1
  27. package/dist/run-subagent.d.ts.map +1 -1
  28. package/dist/sandbox-api-context.d.ts.map +1 -1
  29. package/dist/search-script.d.ts +7 -0
  30. package/dist/search-script.d.ts.map +1 -0
  31. package/dist/skills/built-in.d.ts.map +1 -1
  32. package/dist/subagent-tools.d.ts +11 -1
  33. package/dist/subagent-tools.d.ts.map +1 -1
  34. package/dist/tools/bash.d.ts +1 -1
  35. package/dist/tools/bash.d.ts.map +1 -1
  36. package/dist/tools/glob.d.ts +41 -0
  37. package/dist/tools/glob.d.ts.map +1 -0
  38. package/dist/tools/grep.d.ts +64 -0
  39. package/dist/tools/grep.d.ts.map +1 -0
  40. package/dist/tools/model-spec.d.ts.map +1 -1
  41. package/dist/tools/sandbox-search.d.ts +26 -0
  42. package/dist/tools/sandbox-search.d.ts.map +1 -0
  43. package/dist/tools/search/command.d.ts +15 -0
  44. package/dist/tools/search/command.d.ts.map +1 -0
  45. package/dist/tools/search/gitignore.d.ts +28 -0
  46. package/dist/tools/search/gitignore.d.ts.map +1 -0
  47. package/dist/tools/search/glob.d.ts +15 -0
  48. package/dist/tools/search/glob.d.ts.map +1 -0
  49. package/dist/tools/search/main.d.ts +2 -0
  50. package/dist/tools/search/main.d.ts.map +1 -0
  51. package/dist/tools/search/match.d.ts +30 -0
  52. package/dist/tools/search/match.d.ts.map +1 -0
  53. package/dist/tools/search/pattern.d.ts +19 -0
  54. package/dist/tools/search/pattern.d.ts.map +1 -0
  55. package/dist/tools/search/read.d.ts +62 -0
  56. package/dist/tools/search/read.d.ts.map +1 -0
  57. package/dist/tools/search/request.d.ts +80 -0
  58. package/dist/tools/search/request.d.ts.map +1 -0
  59. package/dist/tools/search/search.d.ts +4 -0
  60. package/dist/tools/search/search.d.ts.map +1 -0
  61. package/dist/tools/search/walk.d.ts +43 -0
  62. package/dist/tools/search/walk.d.ts.map +1 -0
  63. package/dist/tools/tool-outputs.d.ts.map +1 -1
  64. package/dist/turn-inbox.d.ts +75 -0
  65. package/dist/turn-inbox.d.ts.map +1 -0
  66. package/package.json +7 -5
  67. package/src/agent-prompt.ts +63 -28
  68. package/src/agent-runtime/preflight.ts +1 -0
  69. package/src/artifacts/layout-check/check.cjs +176 -95
  70. package/src/artifacts/layout-check/layout-check.ts +118 -76
  71. package/src/artifacts/publish-tool.ts +48 -99
  72. package/src/background-commands.ts +8 -6
  73. package/src/context-compaction.ts +1 -0
  74. package/src/conversation-messages.ts +11 -4
  75. package/src/generated/search.mjs +985 -0
  76. package/src/index.ts +0 -1
  77. package/src/login-shell.ts +30 -3
  78. package/src/model-adapters.ts +23 -4
  79. package/src/model-lines.ts +1 -1
  80. package/src/run-agent-turn.ts +85 -129
  81. package/src/run-conversation-turn.ts +15 -6
  82. package/src/run-environment.ts +42 -11
  83. package/src/run-sandbox.ts +60 -1
  84. package/src/run-subagent.ts +9 -2
  85. package/src/sandbox-api-context.ts +10 -1
  86. package/src/search-script-assets.d.ts +5 -0
  87. package/src/search-script.ts +9 -0
  88. package/src/skills/built-in.ts +16 -0
  89. package/src/skills/sixb-artifacts/SKILL.md +7 -7
  90. package/src/skills/sixb-artifacts/canvas.md +3 -2
  91. package/src/skills/sixb-artifacts/document.md +92 -5
  92. package/src/skills/sixb-artifacts/examples/document/service-proposal/design.css +114 -0
  93. package/src/skills/sixb-artifacts/examples/document/service-proposal/document.html +159 -0
  94. package/src/skills/sixb-artifacts/examples/document/service-proposal/images/fieldwise.svg +1 -0
  95. package/src/skills/sixb-artifacts/examples/document/service-proposal/images/harbor-pine.svg +1 -0
  96. package/src/skills/sixb-artifacts/queries.md +2 -1
  97. package/src/subagent-tools.ts +23 -5
  98. package/src/tools/bash.ts +9 -10
  99. package/src/tools/glob.ts +124 -0
  100. package/src/tools/grep.ts +190 -0
  101. package/src/tools/model-spec.ts +4 -0
  102. package/src/tools/sandbox-search.ts +219 -0
  103. package/src/tools/search/command.ts +116 -0
  104. package/src/tools/search/gitignore.ts +101 -0
  105. package/src/tools/search/glob.ts +90 -0
  106. package/src/tools/search/main.ts +9 -0
  107. package/src/tools/search/match.ts +278 -0
  108. package/src/tools/search/pattern.ts +178 -0
  109. package/src/tools/search/read.ts +237 -0
  110. package/src/tools/search/request.ts +101 -0
  111. package/src/tools/search/search.ts +297 -0
  112. package/src/tools/search/walk.ts +145 -0
  113. package/src/tools/tool-outputs.ts +7 -2
  114. package/src/turn-inbox.ts +283 -0
  115. package/dist/artifacts/board-previews.d.ts +0 -41
  116. package/dist/artifacts/board-previews.d.ts.map +0 -1
  117. package/src/artifacts/board-previews.ts +0 -218
package/src/index.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  export { waitForAbort } from "./abort"
2
2
  export type { AgentWorkspacePromptContext } from "./agent-prompt"
3
- export { renderBoardPreviews } from "./artifacts/board-previews"
4
3
  export { createAskParentTool } from "./ask-tool"
5
4
  export type { BackgroundCommandStatus } from "./background-commands"
6
5
  export {
@@ -1,3 +1,5 @@
1
+ import { posix } from "node:path"
2
+
1
3
  /**
2
4
  * Runs a script in a bash that is not a login shell, once a login shell has loaded the profile:
3
5
  * the profile's exports reach the script, and its `exit` leaves the login shell alone.
@@ -12,7 +14,32 @@
12
14
  */
13
15
  export const LOGIN_SHELL_SCRIPT = 'exec "$BASH" -c "$1" bash'
14
16
 
15
- /** `bash` arguments that run `script` as {@link LOGIN_SHELL_SCRIPT} does. */
16
- export function loginShellArgs(script: string): string[] {
17
- return ["-lc", LOGIN_SHELL_SCRIPT, "bash", script]
17
+ /**
18
+ * {@link LOGIN_SHELL_SCRIPT}, in a directory the shell changes to itself. A directory that does not
19
+ * exist fails the command with bash's own message, which the model can read and correct. Given
20
+ * to the sandbox instead, it would refuse to start the command, and a refused command leaves the
21
+ * workspace unconfirmed. Falling off the end, unlike `exit`, does not run `~/.bash_logout`.
22
+ *
23
+ * Arguments: the directory, then the script.
24
+ */
25
+ export const LOGIN_SHELL_SCRIPT_IN_DIRECTORY = 'cd -- "$1" && exec "$BASH" -c "$2" bash'
26
+
27
+ /** `bash` arguments that run `script` as {@link LOGIN_SHELL_SCRIPT} does, in `directory` if given. */
28
+ export function loginShellArgs(script: string, directory?: string): string[] {
29
+ return directory === undefined
30
+ ? ["-lc", LOGIN_SHELL_SCRIPT, "bash", script]
31
+ : ["-lc", LOGIN_SHELL_SCRIPT_IN_DIRECTORY, "bash", directory, script]
32
+ }
33
+
34
+ /**
35
+ * The absolute directory a command's `cwd` names, for the shell to change to. A relative one
36
+ * resolves against the sandbox's working directory, as the bash tool describes it: in a workspace
37
+ * cloned from Git, that is the checkout, not the provider's own directory above it. A model's
38
+ * `cwd` never reaches the provider: see {@link LOGIN_SHELL_SCRIPT_IN_DIRECTORY}.
39
+ */
40
+ export function commandDirectory(
41
+ workingDirectory: string,
42
+ cwd: string | undefined
43
+ ): string | undefined {
44
+ return cwd === undefined ? undefined : posix.resolve(workingDirectory, cwd)
18
45
  }
@@ -1,5 +1,5 @@
1
1
  import type { AgentMessagePart, JsonValue } from "@sixb/core"
2
- import { AgentToolPublicError } from "@sixb/core"
2
+ import { AgentToolPublicError, SandboxNotRunningError } from "@sixb/core"
3
3
  import {
4
4
  type AgentToolCall,
5
5
  type AgentToolCallFile,
@@ -267,7 +267,26 @@ function assertUnreachableModelPart(part: never, errorDetails?: AgentErrorDetail
267
267
  )
268
268
  }
269
269
 
270
- /** Expose only failures that the tool author explicitly marked as safe for the model and storage. */
271
- export function agentToolErrorText(error: unknown): string {
272
- return error instanceof AgentToolPublicError ? error.message : "An error occurred."
270
+ /** What a tool says when its sandbox stopped: the run ends right after, so this is its last word. */
271
+ const SANDBOX_STOPPED_TOOL_TEXT =
272
+ "The sandbox stopped: commands and files are no longer available in it."
273
+
274
+ /**
275
+ * Expose only failures that the tool author explicitly marked as safe for the model and storage,
276
+ * and a stopped sandbox, in fixed words, even when the tool wrapped it.
277
+ */
278
+ export function agentToolErrorText(error: unknown, fallback = "An error occurred."): string {
279
+ if (error instanceof AgentToolPublicError) return error.message
280
+ if (foundSandboxStopped(error)) return SANDBOX_STOPPED_TOOL_TEXT
281
+ return fallback
282
+ }
283
+
284
+ function foundSandboxStopped(error: unknown): boolean {
285
+ // Bounded: a cause chain can loop.
286
+ let cause = error
287
+ for (let depth = 0; depth < 8 && cause instanceof Error; depth++) {
288
+ if (cause instanceof SandboxNotRunningError) return true
289
+ cause = cause.cause
290
+ }
291
+ return false
273
292
  }
@@ -23,6 +23,6 @@ export function renderModelLine(input: {
23
23
  }
24
24
 
25
25
  // A provider's catalog text may span lines; each model keeps to one.
26
- function oneLine(text: string): string {
26
+ export function oneLine(text: string): string {
27
27
  return text.replace(/\s+/g, " ").trim()
28
28
  }
@@ -1,4 +1,4 @@
1
- import type { AgentMessage, AgentMessagePart, AgentStepRequestSize } from "@sixb/core"
1
+ import type { AgentStepRequestSize } from "@sixb/core"
2
2
  import {
3
3
  type AgentContextBudget,
4
4
  type AgentRunSession,
@@ -25,10 +25,10 @@ import { conversationModelMessages, conversationModelSettings } from "./conversa
25
25
  import { AgentContextCompactionError, throwIfExecutionLost } from "./errors"
26
26
  import type { ResolvedAgentExecutionPlan } from "./execution-plan"
27
27
  import type { ConversationReaders } from "./message-authors"
28
- import { agentTraceFromModelSteps, agentTraceFromPartialModelLoop } from "./model-adapters"
29
28
  import type { ConversationAgentExecutionEnvironment } from "./run-environment"
30
29
  import { monitorSandboxReadiness } from "./sandbox-readiness"
31
30
  import type { LoadedAgentThreadModelContext } from "./thread-context"
31
+ import { TurnInbox, turnResultMessages, turnWorkMessages } from "./turn-inbox"
32
32
  import { type AgentTurnRuntime, createAgentTurnRuntime } from "./turn-runtime"
33
33
  import type { AgentTurnContext } from "./types"
34
34
 
@@ -69,10 +69,10 @@ export interface RunAgentTurnInput {
69
69
  readonly compactInTurn?: ConversationAgentExecutionEnvironment["compactInTurn"]
70
70
  }
71
71
  /**
72
- * Handed the answer so far after each step that completed, as the message the turn would
73
- * append: a turn that fails then records it with its failure, and keeps that work.
72
+ * Handed the answer so far after each step that completed, as the messages the turn would
73
+ * append: a turn that fails then records them with its failure, and keeps that work.
74
74
  */
75
- readonly onWork?: (message: AppendAgentMessageInput) => void
75
+ readonly onWork?: (messages: readonly AppendAgentMessageInput[]) => void
76
76
  }
77
77
 
78
78
  /**
@@ -118,7 +118,7 @@ export async function runAgentTurn(input: RunAgentTurnInput): Promise<AgentRunRe
118
118
  sandboxReadiness.signal,
119
119
  ...(context.environmentFailureSignal ? [context.environmentFailureSignal] : []),
120
120
  ])
121
- let interruptedParts: readonly AgentMessagePart[] | undefined
121
+ let interruptedMessages: readonly AppendAgentMessageInput[] | undefined
122
122
  const stopReason = () =>
123
123
  stoppedByWorker(signal, input.stopSignal) ? { finishReason: "interrupted" as const } : {}
124
124
 
@@ -133,7 +133,7 @@ export async function runAgentTurn(input: RunAgentTurnInput): Promise<AgentRunRe
133
133
  run,
134
134
  modelId: plan.model.modelId,
135
135
  ...stopReason(),
136
- parts: interruptedParts,
136
+ messages: interruptedMessages,
137
137
  })
138
138
  }
139
139
 
@@ -202,10 +202,19 @@ export async function runAgentTurn(input: RunAgentTurnInput): Promise<AgentRunRe
202
202
  return { ...prepared, ...guarded }
203
203
  }
204
204
  : context.prepareStep
205
+ const turnInbox = new TurnInbox(input.session, {
206
+ retainedMessages: input.threadContext.retainedMessages,
207
+ ...(input.conversation === undefined ? {} : { conversation: input.conversation }),
208
+ project: { timeZone: context.projectTimeZone, locale: context.projectLocale },
209
+ })
205
210
  const prepareStep = async (step: PrepareModelStepInput) => {
206
211
  const prepared = await guardedStep?.(step)
207
- recordRequest(step.stepIndex, prepared?.messages ?? step.messages)
208
- return prepared
212
+ const steers = await turnInbox.take(step.stepIndex)
213
+ const baseMessages = prepared?.messages ?? step.messages
214
+ const nextMessages = steers.length > 0 ? [...baseMessages, ...steers] : baseMessages
215
+ recordRequest(step.stepIndex, nextMessages)
216
+ if (steers.length === 0) return prepared
217
+ return { ...prepared, messages: nextMessages }
209
218
  }
210
219
  const recoverStep =
211
220
  guard &&
@@ -215,32 +224,24 @@ export async function runAgentTurn(input: RunAgentTurnInput): Promise<AgentRunRe
215
224
  return recovered
216
225
  })
217
226
 
218
- // The answer so far, as one message whatever step it is at.
219
- const workMessageId = createAgentMessageId()
220
227
  const finishedSteps: ModelStep[] = []
221
228
  const recordStep = (step: ModelStep) => {
222
229
  finishedSteps.push(step)
223
- input.onWork?.({
224
- id: workMessageId,
225
- projectId,
226
- threadId: run.threadId,
227
- runId,
228
- role: "assistant",
229
- parts: recordStepRequests(
230
- markReducedSteps(
231
- agentTraceFromModelSteps(
232
- finishedSteps,
233
- { threadId: run.threadId, runId },
234
- context.outputFileOf
235
- ),
236
- guard?.reducedFromStep()
237
- ),
238
- stepRequests
239
- ),
230
+ const snapshot = turnWorkMessages({
231
+ steps: finishedSteps,
232
+ run,
233
+ deliveries: turnInbox.deliveries,
234
+ ...(guard?.reducedFromStep() === undefined
235
+ ? {}
236
+ : { reducedFromStep: guard.reducedFromStep() }),
237
+ stepRequests,
238
+ ...(context.outputFileOf === undefined ? {} : { outputFileOf: context.outputFileOf }),
240
239
  ...(context.authorPrincipal === undefined
241
240
  ? {}
242
241
  : { authorPrincipal: context.authorPrincipal }),
243
242
  })
243
+ interruptedMessages = snapshot
244
+ input.onWork?.(snapshot)
244
245
  }
245
246
 
246
247
  try {
@@ -261,17 +262,18 @@ export async function runAgentTurn(input: RunAgentTurnInput): Promise<AgentRunRe
261
262
  prepareStep,
262
263
  ...(recoverStep ? { recoverStep } : {}),
263
264
  onStepEnd: recordStep,
264
- // A child's question the model has not read comes before its answer ends the turn.
265
- ...(input.children === undefined
266
- ? {}
267
- : {
268
- beforeComplete: async () => {
269
- const unread = await input.children?.unread()
270
- return unread
271
- ? [{ role: "user", content: [{ type: "text", text: unread }] }]
272
- : undefined
273
- },
274
- }),
265
+ // Mid-run steers and unread child questions arrive before the answer ends the turn.
266
+ beforeComplete: async (_step, stepIndex) => {
267
+ const steers = await turnInbox.take(stepIndex + 1, { afterAnswer: true })
268
+ const unread = await input.children?.unread()
269
+ const followUp: ModelMessage[] = [
270
+ ...steers,
271
+ ...(unread
272
+ ? [{ role: "user" as const, content: [{ type: "text" as const, text: unread }] }]
273
+ : []),
274
+ ]
275
+ return followUp.length > 0 ? followUp : undefined
276
+ },
275
277
  signal: abortSignal,
276
278
  onEvent: async (chunk) => {
277
279
  await input.session.events.publishUiChunk({ run, chunkIndex: chunkIndex++, chunk })
@@ -301,24 +303,18 @@ export async function runAgentTurn(input: RunAgentTurnInput): Promise<AgentRunRe
301
303
  throw error
302
304
  }
303
305
 
304
- interruptedParts = recordStepRequests(
305
- markReducedSteps(
306
- result.status === "aborted"
307
- ? agentTraceFromPartialModelLoop(
308
- result.steps,
309
- result.partialContent,
310
- { threadId: run.threadId, runId },
311
- context.outputFileOf
312
- )
313
- : agentTraceFromModelSteps(
314
- result.steps,
315
- { threadId: run.threadId, runId },
316
- context.outputFileOf
317
- ),
318
- guard?.reducedFromStep()
319
- ),
320
- stepRequests
321
- )
306
+ interruptedMessages = turnResultMessages(result, {
307
+ run,
308
+ deliveries: turnInbox.deliveries,
309
+ ...(guard?.reducedFromStep() === undefined
310
+ ? {}
311
+ : { reducedFromStep: guard.reducedFromStep() }),
312
+ stepRequests,
313
+ ...(context.outputFileOf === undefined ? {} : { outputFileOf: context.outputFileOf }),
314
+ ...(context.authorPrincipal === undefined
315
+ ? {}
316
+ : { authorPrincipal: context.authorPrincipal }),
317
+ })
322
318
 
323
319
  const interruptedAfterModel = await finalizeIfInterrupted()
324
320
  if (interruptedAfterModel) return interruptedAfterModel
@@ -329,7 +325,7 @@ export async function runAgentTurn(input: RunAgentTurnInput): Promise<AgentRunRe
329
325
  run,
330
326
  modelId: plan.model.modelId,
331
327
  ...stopReason(),
332
- parts: interruptedParts,
328
+ messages: interruptedMessages,
333
329
  })
334
330
  }
335
331
 
@@ -354,12 +350,29 @@ export async function runAgentTurn(input: RunAgentTurnInput): Promise<AgentRunRe
354
350
  : result.status === "paused"
355
351
  ? "stop"
356
352
  : (coerceAgentRunFinishReason(result.finishReason) ?? "unknown")
357
- const assistant: AgentMessage = { role: "assistant", parts: interruptedParts }
358
353
  const diagnostics = [
359
354
  outputLimitDiagnostic(finishReason),
360
355
  finishReason === "awaiting_approval" ? undefined : stepLimitDiagnostic(result),
361
356
  ].filter((diagnostic) => diagnostic !== undefined)
362
- const assistantMessageId = createAgentMessageId()
357
+ const committedMessages: readonly AppendAgentMessageInput[] =
358
+ interruptedMessages !== undefined && interruptedMessages.length > 0
359
+ ? interruptedMessages
360
+ : [
361
+ {
362
+ id: createAgentMessageId(),
363
+ projectId,
364
+ threadId: run.threadId,
365
+ runId,
366
+ role: "assistant" as const,
367
+ parts: [],
368
+ ...(context.authorPrincipal === undefined
369
+ ? {}
370
+ : { authorPrincipal: context.authorPrincipal }),
371
+ },
372
+ ]
373
+ const lastAssistant = [...committedMessages]
374
+ .reverse()
375
+ .find((message) => message.role === "assistant")
363
376
 
364
377
  const interruptedBeforeCommit = await finalizeIfInterrupted()
365
378
  if (interruptedBeforeCommit) return interruptedBeforeCommit
@@ -372,22 +385,12 @@ export async function runAgentTurn(input: RunAgentTurnInput): Promise<AgentRunRe
372
385
  finishReason,
373
386
  ...(diagnostics.length === 0 ? {} : { diagnostics }),
374
387
  },
375
- [
376
- {
377
- id: assistantMessageId,
378
- projectId,
379
- threadId: run.threadId,
380
- runId,
381
- role: assistant.role,
382
- parts: assistant.parts,
383
- ...(context.authorPrincipal === undefined
384
- ? {}
385
- : { authorPrincipal: context.authorPrincipal }),
386
- },
387
- ]
388
+ committedMessages
388
389
  )
389
390
 
390
- await input.session.events.publishMessageFinalized({ run, messageId: assistantMessageId })
391
+ if (lastAssistant) {
392
+ await input.session.events.publishMessageFinalized({ run, messageId: lastAssistant.id })
393
+ }
391
394
  await input.session.events.publishRunFinished(finalizedRun)
392
395
  return finalizedRun
393
396
  } finally {
@@ -400,43 +403,6 @@ export async function runAgentTurn(input: RunAgentTurnInput): Promise<AgentRunRe
400
403
  * waiting, or decided and not reported to the model yet, its children's included.
401
404
  */
402
405
 
403
- /**
404
- * Mark each step from `fromStep` on as answering a request the turn reduced, for the next turn's
405
- * estimate not to go by what those calls read.
406
- */
407
- export function markReducedSteps(
408
- parts: readonly AgentMessagePart[],
409
- fromStep: number | undefined
410
- ): readonly AgentMessagePart[] {
411
- if (fromStep === undefined) return parts
412
-
413
- let step = -1
414
- return parts.map((part) => {
415
- if (part.type !== "step-start") return part
416
-
417
- step += 1
418
- return step >= fromStep ? { type: "step-start", reducedRequest: true } : part
419
- })
420
- }
421
-
422
- /**
423
- * Record on each step-start what its request carried, by step: the next turn's context meter
424
- * reads the system prompt and tools the latest one sent.
425
- */
426
- export function recordStepRequests(
427
- parts: readonly AgentMessagePart[],
428
- requests: readonly (AgentStepRequestSize | undefined)[]
429
- ): readonly AgentMessagePart[] {
430
- let step = -1
431
- return parts.map((part) => {
432
- if (part.type !== "step-start") return part
433
-
434
- step += 1
435
- const request = requests[step]
436
- return request ? { ...part, request } : part
437
- })
438
- }
439
-
440
406
  /**
441
407
  * Whether the worker's stop, rather than the user's, ended the turn. Whichever fired first wins:
442
408
  * the combined turn signal carries the reason of the first source that aborted it.
@@ -481,10 +447,10 @@ async function finalizeInterruptedTurn(input: {
481
447
  readonly run: ConversationAgentRunRecord
482
448
  readonly modelId?: string
483
449
  readonly finishReason?: "interrupted"
484
- readonly parts?: readonly AgentMessagePart[]
450
+ readonly messages?: readonly AppendAgentMessageInput[]
485
451
  }): Promise<AgentRunRecord> {
486
452
  const { session, context, run, modelId, finishReason } = input
487
- const parts = input.parts?.some((part) => part.type !== "step-start") ? input.parts : undefined
453
+ const messages = input.messages && input.messages.length > 0 ? input.messages : undefined
488
454
 
489
455
  await context.beforeFinalize?.()
490
456
 
@@ -493,27 +459,17 @@ async function finalizeInterruptedTurn(input: {
493
459
  ...(modelId === undefined ? {} : { modelId }),
494
460
  ...(finishReason === undefined ? {} : { finishReason }),
495
461
  }
496
- if (!parts) {
462
+ if (!messages) {
497
463
  const finalizedRun = await session.finish(outcome)
498
464
  await session.events.publishRunFinished(finalizedRun)
499
465
  return finalizedRun
500
466
  }
501
467
 
502
- const assistantMessageId = createAgentMessageId()
503
- const finalizedRun = await session.finish(outcome, [
504
- {
505
- id: assistantMessageId,
506
- projectId: run.projectId,
507
- threadId: run.threadId,
508
- runId: run.id,
509
- role: "assistant",
510
- parts,
511
- ...(context.authorPrincipal === undefined
512
- ? {}
513
- : { authorPrincipal: context.authorPrincipal }),
514
- },
515
- ])
516
- await session.events.publishMessageFinalized({ run, messageId: assistantMessageId })
468
+ const finalizedRun = await session.finish(outcome, messages)
469
+ const lastAssistant = [...messages].reverse().find((message) => message.role === "assistant")
470
+ if (lastAssistant) {
471
+ await session.events.publishMessageFinalized({ run, messageId: lastAssistant.id })
472
+ }
517
473
  await session.events.publishRunFinished(finalizedRun)
518
474
  return finalizedRun
519
475
  }
@@ -32,10 +32,15 @@ import {
32
32
  type OpenRunSandbox,
33
33
  } from "./run-environment"
34
34
  import { recordFate } from "./run-fate"
35
+ import { sandboxStopOf, sandboxStoppedError } from "./run-sandbox"
35
36
  import { SubagentCoordinator } from "./subagent-tools"
36
37
  import { type AgentTurnRuntime, createAgentTurnRuntime } from "./turn-runtime"
37
38
  import type { AgentExecutionContext, AgentRunSettings } from "./types"
38
39
 
40
+ /** Why a turn ended whose workspace, kept across turns, its provider stopped: as the chat offers. */
41
+ const SANDBOX_STOPPED_UNSAVED_MESSAGE =
42
+ "The sandbox stopped, so this turn ended here. To go on, pick up where it left off or start over."
43
+
39
44
  // A conversation turn, from its claimed session to its end, whichever runner runs it: the worker,
40
45
  // under a queue delivery, or a runner on a computer, over HTTP. The runner keeps what is its own:
41
46
  // how it holds the run, where the turn's sandbox comes from, and where its children run.
@@ -89,7 +94,7 @@ export async function runConversationTurn(input: {
89
94
  let runtime: AgentTurnRuntime | null = null
90
95
  let delegation: SubagentCoordinator | undefined
91
96
  // The answer so far: a turn that fails keeps the steps it completed.
92
- let work: AppendAgentMessageInput | undefined
97
+ let work: readonly AppendAgentMessageInput[] | undefined
93
98
  // A user cancel joins the turn's abort sources, so it stops the model stream as a shutdown does.
94
99
  const turnSignal = AbortSignal.any([signal, session.cancelled])
95
100
 
@@ -113,7 +118,8 @@ export async function runConversationTurn(input: {
113
118
  )
114
119
  }
115
120
  runner.startChild(child, family, environment.networkPolicy)
116
- }
121
+ },
122
+ prepared.thread?.movedAt
117
123
  )
118
124
  // The Agent's own: its children, and its questions to the user, which end the turn.
119
125
  const frameworkTools = [...(await delegation.createTools()), createAskUserTool()]
@@ -164,8 +170,8 @@ export async function runConversationTurn(input: {
164
170
  ? {}
165
171
  : { bytesPerToken: environment.bytesPerToken }),
166
172
  },
167
- onWork: (message) => {
168
- work = message
173
+ onWork: (messages) => {
174
+ work = messages
169
175
  },
170
176
  })
171
177
  } catch (caughtError) {
@@ -180,7 +186,10 @@ export async function runConversationTurn(input: {
180
186
  await environment.beforeFinalize()
181
187
  } catch (saveError) {
182
188
  if (saveError instanceof AgentExecutionLostError) return
183
- error = saveError
189
+ // A workspace its provider stopped cannot be cleaned and saved: it waits for its owner, and
190
+ // the run still says why it ended.
191
+ const stop = sandboxStopOf(error)
192
+ error = stop ? sandboxStoppedError(stop, SANDBOX_STOPPED_UNSAVED_MESSAGE) : saveError
184
193
  environmentSaveFailed = true
185
194
  }
186
195
  }
@@ -197,7 +206,7 @@ export async function runConversationTurn(input: {
197
206
  session,
198
207
  aborted ? "cancelled" : "failed",
199
208
  interrupted ? new AgentTurnInterruptedError(run.id) : error,
200
- !aborted && work ? [work] : undefined
209
+ !aborted && work && work.length > 0 ? work : undefined
201
210
  )
202
211
  if (finalized) {
203
212
  if (finalized.run.status === "failed") {