@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,86 @@
1
+ import { toModelMessages } from "@sixb/core/internal/agents"
2
+ import type { ModelCachingIntent, ModelMessage, ModelReasoning } from "@sixb/core/models"
3
+ import type { SentSettings } from "./agent-prompt"
4
+ import {
5
+ attachmentKey,
6
+ type PreparedAgentAttachmentContext,
7
+ toolResultAttachmentKey,
8
+ } from "./attachments"
9
+ import { type ConversationReaders, conversationAuthors } from "./message-authors"
10
+ import { userMessageTimes } from "./message-times"
11
+ import { conversationPromptCaching } from "./prompt-cache"
12
+ import type { LoadedAgentThreadModelContext } from "./thread-context"
13
+ import { toolFilesStepKey } from "./tools/result-media"
14
+
15
+ /**
16
+ * A conversation's history as its model calls send it: each user message closed by when it was
17
+ * sent and who wrote it, its attachments inline, and the files each step's tools showed. Every
18
+ * part comes from stored data, so a turn, and the summary that continues it, send the bytes the
19
+ * turn before sent.
20
+ */
21
+ export function conversationModelMessages(input: {
22
+ readonly threadContext: LoadedAgentThreadModelContext
23
+ readonly attachmentContext?: PreparedAgentAttachmentContext
24
+ /** The thread and who can read it; without it the model is told nothing of its people. */
25
+ readonly conversation?: ConversationReaders
26
+ /** The project's time zone and locale, for a message whose run captured none. */
27
+ readonly project: SentSettings
28
+ }): ModelMessage[] {
29
+ const { threadContext, attachmentContext } = input
30
+ const sentTimes = userMessageTimes(threadContext.history, input.project)
31
+ const authors = input.conversation
32
+ ? conversationAuthors({
33
+ conversation: input.conversation,
34
+ messages: threadContext.retainedMessages,
35
+ })
36
+ : undefined
37
+
38
+ return toModelMessages(threadContext.modelMessages, {
39
+ // When, then who wrote it: `<sixb_author>` stays the message's last tag. Who takes part is in
40
+ // the system prompt, so no message changes when the next one comes.
41
+ userMessageSuffix: (message) => {
42
+ if (!message.id) return undefined
43
+
44
+ const closing = [sentTimes.get(message.id), authors?.byMessageId.get(message.id)]
45
+ return closing.filter(Boolean).join("\n") || undefined
46
+ },
47
+ fileText: ({ message, partIndex }) =>
48
+ message.id
49
+ ? attachmentContext?.promptTextByPartKey.get(attachmentKey(message.id, partIndex))
50
+ : undefined,
51
+ fileData: ({ message, partIndex }) =>
52
+ message.id
53
+ ? attachmentContext?.modelFileDataByPartKey.get(attachmentKey(message.id, partIndex))
54
+ : undefined,
55
+ toolResultFileText: ({ message, partIndex, contentIndex }) =>
56
+ message.id
57
+ ? attachmentContext?.promptTextByPartKey.get(
58
+ toolResultAttachmentKey(message.id, partIndex, contentIndex)
59
+ )
60
+ : undefined,
61
+ afterToolResults: ({ message, partIndex }) =>
62
+ message.id
63
+ ? attachmentContext?.toolFilesByStep?.get(toolFilesStepKey(message.id, partIndex))
64
+ : undefined,
65
+ })
66
+ }
67
+
68
+ /**
69
+ * How a conversation's model calls reason and are cached. Thinking, effort and the cache intent
70
+ * are part of the prefix a provider reuses, so every call that continues the conversation sends
71
+ * the same: the turn's steps, and the summary that compacts it.
72
+ */
73
+ export function conversationModelSettings(input: {
74
+ readonly reasoning: ModelReasoning | undefined
75
+ readonly projectId: string
76
+ readonly threadId: string
77
+ }): { readonly reasoning?: ModelReasoning; readonly caching: ModelCachingIntent } {
78
+ return {
79
+ ...(input.reasoning === undefined ? {} : { reasoning: input.reasoning }),
80
+ caching: conversationPromptCaching({
81
+ projectId: input.projectId,
82
+ threadId: input.threadId,
83
+ lifetime: "long",
84
+ }),
85
+ }
86
+ }
@@ -1,5 +1,10 @@
1
1
  import type { AgentReasoning, AgentSkillDefinition } from "@sixb/core"
2
- import type { AgentRunPlan, AgentToolSpec, SandboxModel } from "@sixb/core/internal/agents"
2
+ import type {
3
+ AgentContextTokenRateSample,
4
+ AgentRunPlan,
5
+ AgentToolSpec,
6
+ SandboxModel,
7
+ } from "@sixb/core/internal/agents"
3
8
  import type { RenderedOntologyDocs } from "@sixb/core/internal/ontology"
4
9
  import type { LanguageModel } from "@sixb/core/models"
5
10
  import { withBuiltInSkills } from "./skills/built-in"
@@ -25,6 +30,10 @@ export interface ResolvedAgentExecutionPlan {
25
30
  readonly sandboxModels?: readonly SandboxModel[]
26
31
  /** Reference docs for the object types the run's requester can see, from their own view. */
27
32
  readonly ontologyDocs: RenderedOntologyDocs
33
+ /** What the project's runs measured of the model's tokenizer lately, newest first. */
34
+ readonly tokenRates?: readonly AgentContextTokenRateSample[]
35
+ /** At most this many model calls. Absent: it runs until its model answers. */
36
+ readonly maxSteps?: number
28
37
  }
29
38
 
30
39
  /**
@@ -35,10 +44,20 @@ export function resolveRunPlan(
35
44
  plan: AgentRunPlan,
36
45
  resolved: { readonly model: LanguageModel }
37
46
  ): ResolvedAgentExecutionPlan {
38
- const { reasoning, instructions, timeZone, locale, sandboxModels, ontologyDocs, tools } = plan
47
+ const {
48
+ reasoning,
49
+ instructions,
50
+ timeZone,
51
+ locale,
52
+ sandboxModels,
53
+ ontologyDocs,
54
+ tools,
55
+ maxSteps,
56
+ } = plan
39
57
  return Object.freeze({
40
58
  model: resolved.model,
41
59
  ontologyDocs,
60
+ tokenRates: plan.tokenRates,
42
61
  ...(instructions === undefined ? {} : { instructions }),
43
62
  tools,
44
63
  skills: withBuiltInSkills(plan.skills),
@@ -46,5 +65,6 @@ export function resolveRunPlan(
46
65
  ...(timeZone === undefined ? {} : { timeZone }),
47
66
  ...(locale === undefined ? {} : { locale }),
48
67
  ...(sandboxModels.length ? { sandboxModels } : {}),
68
+ ...(maxSteps === undefined ? {} : { maxSteps }),
49
69
  })
50
70
  }
package/src/failure.ts CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  } from "@sixb/core/internal/errors"
8
8
  import { AGENT_RUN_FAILURE_CODES, type AgentRunFailureCode } from "@sixb/core/storage"
9
9
  import { AgentRuntimeProfileError } from "./agent-runtime/errors"
10
+ import { AgentContextCompactionError } from "./errors"
10
11
 
11
12
  export type AgentRunFailure = SixbFailure<AgentRunFailureCode>
12
13
 
@@ -53,10 +54,20 @@ function translateAgentExecutionError(
53
54
  })
54
55
  }
55
56
 
57
+ // Compaction found no way to fit the conversation in the model's window: a retry would fail the
58
+ // same way, so the failure says what gets past it.
59
+ if (error instanceof AgentContextCompactionError && error.code === "context_limit_exceeded") {
60
+ return createSixbError("agent.context_limit_exceeded", error.message, {
61
+ cause: error,
62
+ details,
63
+ })
64
+ }
65
+
56
66
  if (
57
67
  isSixbError(error) &&
58
68
  (error.code === "internal.unexpected" ||
59
69
  error.code === "agent.execution_failed" ||
70
+ error.code === "agent.step_limit_reached" ||
60
71
  error.code === "ai.usage_limit_exceeded" ||
61
72
  error.code === "ai.usage_limit_unavailable")
62
73
  ) {
@@ -0,0 +1,69 @@
1
+ import { AGENT_INLINE_IMAGE_LIMITS } from "@sixb/core/internal/agents"
2
+
3
+ /** What a request says in place of an attachment's image the budget left out. */
4
+ export const INLINE_IMAGE_BUDGET_NOTE =
5
+ "[Image not inlined: the conversation's inline image budget is used up until it is compacted; the file is available through the sandbox path or content URL.]"
6
+
7
+ /** How many images a request projects at once while the budget decides them in order. */
8
+ const PROJECTION_CONCURRENCY = 4
9
+
10
+ /**
11
+ * What one request has left of {@link AGENT_INLINE_IMAGE_LIMITS}. A run takes from it in thread
12
+ * order, oldest first: the history's attachments and tool images, then the images its own steps
13
+ * return. The first image that does not fit closes it, so nothing after it is projected at all. A
14
+ * replay walks the same order: an image that fitted keeps its inline data until compaction, and one
15
+ * that did not stays metadata from its own turn on.
16
+ */
17
+ export class InlineImageBudget {
18
+ #bytes = 0
19
+ #images = 0
20
+ #closed = false
21
+
22
+ /** Whether no further image can go inline in this request. */
23
+ get closed(): boolean {
24
+ return this.#closed
25
+ }
26
+
27
+ /** Count the image in when it fits what is left; one that does not closes the budget. */
28
+ take(data: URL): boolean {
29
+ const bytes = data.href.length
30
+ this.#closed ||=
31
+ this.#images >= AGENT_INLINE_IMAGE_LIMITS.maxImages ||
32
+ this.#bytes + bytes > AGENT_INLINE_IMAGE_LIMITS.maxBytes
33
+ if (this.#closed) return false
34
+
35
+ this.#bytes += bytes
36
+ this.#images += 1
37
+ return true
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Project images and let the budget decide each, in their order: a few run ahead at once, while
43
+ * every decision waits for the ones before it. Once the budget closes, the rest are never projected:
44
+ * `decide` gets `undefined` for them.
45
+ */
46
+ export async function projectInOrder<TItem, TProjection>(input: {
47
+ readonly items: readonly TItem[]
48
+ readonly budget: InlineImageBudget
49
+ readonly project: (item: TItem) => Promise<TProjection>
50
+ readonly decide: (item: TItem, projection: TProjection | undefined) => void
51
+ }): Promise<void> {
52
+ const { items, budget } = input
53
+ const projections: Promise<TProjection>[] = []
54
+
55
+ for (const [index, item] of items.entries()) {
56
+ if (budget.closed) {
57
+ input.decide(item, undefined)
58
+ continue
59
+ }
60
+
61
+ while (projections.length < Math.min(items.length, index + PROJECTION_CONCURRENCY)) {
62
+ const projection = input.project(items[projections.length] as TItem)
63
+ // Awaited in order below; one the budget no longer needs must not go unhandled.
64
+ projection.catch(() => {})
65
+ projections.push(projection)
66
+ }
67
+ input.decide(item, await projections[index])
68
+ }
69
+ }
@@ -8,7 +8,7 @@ import {
8
8
 
9
9
  /** What the model reads of who writes in a conversation. Nothing of it is stored or shown. */
10
10
  export interface ConversationAuthors {
11
- /** Who takes part, for the newest user message only; absent in a one-person conversation. */
11
+ /** Who takes part, for the system prompt; absent in a one-person conversation. */
12
12
  readonly section?: string
13
13
  /** The `<sixb_author>` closing each retained user message, by message id. */
14
14
  readonly byMessageId: ReadonlyMap<string, string>
@@ -32,8 +32,8 @@ export interface ConversationReaders {
32
32
  *
33
33
  * Each message's author derives from stored data, so a turn replays the bytes the previous one
34
34
  * sent. They change only when someone renames their account. The section naming who takes part
35
- * rides on the newest user message: on the next turn only that message, the history's tail, loses
36
- * it.
35
+ * goes in the system prompt, the same whoever sends the turn: it changes when someone joins or
36
+ * leaves, or is renamed.
37
37
  */
38
38
  export function conversationAuthors(input: {
39
39
  readonly conversation: ConversationReaders
@@ -71,7 +71,7 @@ export function conversationAuthors(input: {
71
71
  }
72
72
  }
73
73
 
74
- /** Everything the authors add to the model input, for its token estimate. */
74
+ /** What the authors add to the user messages, for the model input's token estimate. */
75
75
  export function conversationAuthorsText(authors: ConversationAuthors): string {
76
- return [authors.section ?? "", ...authors.byMessageId.values()].join("\n")
76
+ return [...authors.byMessageId.values()].join("\n")
77
77
  }
@@ -1,21 +1,24 @@
1
1
  import type { AgentTurnHistory } from "@sixb/core/internal/agents"
2
- import { renderCurrentTime } from "./agent-prompt"
2
+ import { renderCurrentTime, type SentSettings } from "./agent-prompt"
3
3
 
4
4
  /**
5
5
  * The `<sixb_current_time>` closing each retained user message: when it was sent, in the time zone
6
- * of the run that answered it (the project's when that run captured none). Stored data only, so
7
- * every later run replays the same bytes and the history stays a cacheable prefix.
6
+ * and locale of the run that answered it (the project's when that run captured none). Stored data
7
+ * only, so every later run replays the same bytes and the history stays a cacheable prefix.
8
8
  */
9
9
  export function userMessageTimes(
10
10
  history: AgentTurnHistory,
11
- projectTimeZone: string
11
+ project: SentSettings
12
12
  ): ReadonlyMap<string, string> {
13
13
  return new Map(
14
14
  history.messages
15
15
  .filter((message) => message.role === "user")
16
16
  .map((message) => [
17
17
  message.id,
18
- renderCurrentTime(message.createdAt, history.sentTimeZones[message.id] ?? projectTimeZone),
18
+ renderCurrentTime(message.createdAt, {
19
+ timeZone: history.sentTimeZones[message.id] ?? project.timeZone,
20
+ locale: history.sentLocales?.[message.id] ?? project.locale,
21
+ }),
19
22
  ])
20
23
  )
21
24
  }
@@ -39,6 +39,8 @@ interface ProjectModelToolsInput {
39
39
  readonly specs: readonly AgentToolSpec[]
40
40
  readonly runId: string
41
41
  readonly callTool: AgentToolCaller
42
+ /** Where the sandbox keeps the run's files, which the paths a tool's files get start with. */
43
+ readonly contextDirectory: string
42
44
  /** The bytes the run's file budget has left, which a call's files may take. */
43
45
  readonly fileBytesLeft: () => number
44
46
  /** Copy the files a call stored into the sandbox, before the model reads its output. */
@@ -93,7 +95,11 @@ function projectModelTool(
93
95
  try {
94
96
  result = await context.callTool(
95
97
  { toolName: spec.name, toolCallId, input: toolInput },
96
- { signal, maxFileBytes: context.fileBytesLeft() }
98
+ {
99
+ signal,
100
+ maxFileBytes: context.fileBytesLeft(),
101
+ contextDirectory: context.contextDirectory,
102
+ }
97
103
  )
98
104
  } catch (error) {
99
105
  if (error instanceof AgentToolResultValidationError) {
@@ -113,36 +119,58 @@ function projectModelTool(
113
119
  }
114
120
 
115
121
  type ToolOutcome =
116
- | { readonly state: "output-available"; readonly output: JsonValue }
122
+ | {
123
+ readonly state: "output-available"
124
+ readonly output: JsonValue
125
+ readonly modelOutput?: AgentToolModelOutput
126
+ readonly outputFile?: AgentToolCallFile
127
+ }
117
128
  | { readonly state: "output-error"; readonly errorText: string }
118
129
 
130
+ /** The stored file of a call whose output was too large for the context (`outputFileOf`). */
131
+ export type AgentToolOutputFileOf = (toolCallId: string) => AgentToolCallFile | undefined
132
+
119
133
  /** Project validated model-loop steps into Sixb's durable trace contract. */
120
134
  export function agentTraceFromModelSteps(
121
135
  steps: readonly ModelStep[],
122
- errorDetails?: AgentErrorDetails
136
+ errorDetails?: AgentErrorDetails,
137
+ outputFileOf?: AgentToolOutputFileOf
123
138
  ): readonly AgentMessagePart[] {
124
- return steps.flatMap((step) => tracePartsFromModelContent(step.content, errorDetails))
139
+ return steps.flatMap((step) =>
140
+ tracePartsFromModelContent(step.content, { errorDetails, outputFileOf })
141
+ )
125
142
  }
126
143
 
127
144
  /** Convert an aborted model loop, retaining only coherent content from its in-flight step. */
128
145
  export function agentTraceFromPartialModelLoop(
129
146
  steps: readonly ModelStep[],
130
147
  partialContent: readonly ModelAssistantPart[],
131
- errorDetails?: AgentErrorDetails
148
+ errorDetails?: AgentErrorDetails,
149
+ outputFileOf?: AgentToolOutputFileOf
132
150
  ): readonly AgentMessagePart[] {
133
151
  return [
134
- ...agentTraceFromModelSteps(steps, errorDetails),
152
+ ...agentTraceFromModelSteps(steps, errorDetails, outputFileOf),
135
153
  ...(partialContent.length === 0
136
154
  ? []
137
- : tracePartsFromModelContent(partialContent, errorDetails, "Tool execution was cancelled.")),
155
+ : tracePartsFromModelContent(partialContent, {
156
+ errorDetails,
157
+ outputFileOf,
158
+ missingToolResultText: "Tool execution was cancelled.",
159
+ })),
138
160
  ]
139
161
  }
140
162
 
141
163
  function tracePartsFromModelContent(
142
164
  content: readonly ModelAssistantPart[],
143
- errorDetails?: AgentErrorDetails,
144
- missingToolResultText = "Tool call did not produce a result."
165
+ options: {
166
+ readonly errorDetails?: AgentErrorDetails
167
+ readonly outputFileOf?: AgentToolOutputFileOf
168
+ readonly missingToolResultText?: string
169
+ }
145
170
  ): AgentMessagePart[] {
171
+ const { errorDetails, outputFileOf } = options
172
+ const missingToolResultText =
173
+ options.missingToolResultText ?? "Tool call did not produce a result."
146
174
  const results = new Map(
147
175
  content.filter((part) => part.type === "tool-result").map((part) => [part.toolCallId, part])
148
176
  )
@@ -180,7 +208,11 @@ function tracePartsFromModelContent(
180
208
  ? {}
181
209
  : { providerExecuted: part.providerExecuted }),
182
210
  ...(part.providerData === undefined ? {} : { providerMetadata: part.providerData }),
183
- ...toolOutcome(results.get(part.toolCallId), missingToolResultText),
211
+ ...toolOutcome(
212
+ results.get(part.toolCallId),
213
+ missingToolResultText,
214
+ outputFileOf?.(part.toolCallId)
215
+ ),
184
216
  },
185
217
  ]
186
218
  }
@@ -195,13 +227,27 @@ function tracePartsFromModelContent(
195
227
 
196
228
  function toolOutcome(
197
229
  result: ModelToolResultPart | undefined,
198
- missingResultText: string
230
+ missingResultText: string,
231
+ outputFile: AgentToolCallFile | undefined
199
232
  ): ToolOutcome {
200
233
  if (!result) return { state: "output-error", errorText: missingResultText }
234
+ const { output } = result
235
+
236
+ // The tool projected its output for the model: the trace keeps both, and later turns replay
237
+ // what the model read, byte for byte. An output saved to a file keeps it as well.
201
238
  if (result.originalOutput !== undefined) {
202
- return { state: "output-available", output: result.originalOutput }
239
+ return {
240
+ state: "output-available",
241
+ output: result.originalOutput,
242
+ ...(output.type === "text"
243
+ ? { modelOutput: { type: "text", value: output.value } }
244
+ : output.type === "json"
245
+ ? { modelOutput: { type: "json", value: output.value } }
246
+ : {}),
247
+ ...(outputFile === undefined ? {} : { outputFile }),
248
+ }
203
249
  }
204
- const { output } = result
250
+
205
251
  switch (output.type) {
206
252
  case "text":
207
253
  case "json":
@@ -0,0 +1,40 @@
1
+ import { createHash } from "node:crypto"
2
+ import type { ModelCachingIntent } from "@sixb/core/models"
3
+
4
+ /**
5
+ * How a conversation's model calls are cached. Its prompt is read again by its next turn, which can
6
+ * come after a human pause, so a turn asks for a long lifetime; a child does too when it can wait on
7
+ * a human decision (see {@link childCacheLifetime}). Both name the conversation, so a provider
8
+ * keeps the turn and its children on the upstream that holds what they cached: a child shares its
9
+ * whole prefix with the runs that continue it, and, in a provider sandbox, its system prompt with
10
+ * siblings given the same tools. On a computer, each child's prompt names its own thread's files.
11
+ */
12
+ export function conversationPromptCaching(input: {
13
+ readonly projectId: string
14
+ /** The conversation's thread: a child's parent thread, never its own. */
15
+ readonly threadId: string
16
+ readonly lifetime: NonNullable<ModelCachingIntent["lifetime"]>
17
+ }): ModelCachingIntent {
18
+ return { lifetime: input.lifetime, key: conversationCacheKey(input.projectId, input.threadId) }
19
+ }
20
+
21
+ /**
22
+ * A child's next read can come after a human decision when its calls can be held for approval, or
23
+ * when it continues a run that paused, as it may pause again: long. Otherwise its next read is its
24
+ * own next step, within the turn: default. A question its parent's turn leaves to the user pauses a
25
+ * child too; that is rare, so a child that can only pause on one keeps the default.
26
+ */
27
+ export function childCacheLifetime(input: {
28
+ /** Whether its run's approval mode lets every call run without asking. */
29
+ readonly runsEveryCall: boolean
30
+ /** Whether it continues a run that paused. */
31
+ readonly continues: boolean
32
+ }): NonNullable<ModelCachingIntent["lifetime"]> {
33
+ return input.runsEveryCall && !input.continues ? "default" : "long"
34
+ }
35
+
36
+ /** Opaque and stable for a conversation: the provider learns neither the project nor the thread. */
37
+ function conversationCacheKey(projectId: string, threadId: string): string {
38
+ const digest = createHash("sha256").update(projectId).update("\0").update(threadId).digest("hex")
39
+ return `sixb_${digest.slice(0, 32)}`
40
+ }