@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,182 @@
1
+ import {
2
+ type AgentThreadModelContextMessage,
3
+ agentRunApprovalMode,
4
+ conversationThreadId,
5
+ shouldCompactAgentContext,
6
+ toModelMessages,
7
+ } from "@sixb/core/internal/agents"
8
+ import { createSixbError, withFailureMessage } from "@sixb/core/internal/errors"
9
+ import { type ModelCachingIntent, type ModelMessage, ModelProviderError } from "@sixb/core/models"
10
+ import type { AgentMessageRecord, AgentThreadRecord, SubagentRunRecord } from "@sixb/core/storage"
11
+ import {
12
+ attachmentKey,
13
+ type PreparedAgentAttachmentContext,
14
+ toolResultAttachmentKey,
15
+ } from "./attachments"
16
+ import {
17
+ type AgentThreadCompactionInput,
18
+ compactAgentThreadInRun,
19
+ estimateAgentConversation,
20
+ inRunCompactedTokens,
21
+ shouldCompactIdleContext,
22
+ } from "./context-compaction"
23
+ import { childCacheLifetime, conversationPromptCaching } from "./prompt-cache"
24
+ import type { SubagentHistory } from "./subagent-continuation"
25
+ import { agentThreadModelContext, type LoadedAgentThreadModelContext } from "./thread-context"
26
+ import { toolFilesStepKey } from "./tools/result-media"
27
+
28
+ // A child keeps its calls under its model's limit as a conversation's turn does (see
29
+ // createAgentContextGuard): its thread is its history, its task apart. Every request opens with
30
+ // the task as it was sent, then the thread: from its latest checkpoint's summary once it has one.
31
+ // A run that continues the thread compacts what came before the message it started from, on the
32
+ // child's own thread, before its environment is built, as a conversation's preflight does: past
33
+ // the limit, or idle and large. Its own steps are cleared, never summarized. A first run has
34
+ // nothing before its task, so it only clears.
35
+
36
+ /** A child's thread as its requests send it: its task, and the history after it. */
37
+ export interface SubagentThreadContext {
38
+ /** The thread's first message, which every request opens with. */
39
+ readonly task?: AgentMessageRecord
40
+ /** The thread without its task: from the latest checkpoint's summary once it has one. */
41
+ readonly threadContext: LoadedAgentThreadModelContext
42
+ }
43
+
44
+ /** Split a child's history into its task and the rest of its thread. */
45
+ export function subagentThreadContext(history: SubagentHistory): SubagentThreadContext {
46
+ // Until a checkpoint summarized it, the task is the thread's first message.
47
+ const task = history.task ?? (history.checkpoint ? undefined : history.messages[0])
48
+ const messages = history.checkpoint ? history.messages : history.messages.slice(1)
49
+
50
+ return {
51
+ ...(task ? { task } : {}),
52
+ threadContext: agentThreadModelContext({ ...history, messages }, { historyReadable: false }),
53
+ }
54
+ }
55
+
56
+ /**
57
+ * The child's thread as its model reads it: the task, closed by the time the thread was created
58
+ * so each run of the child replays the same bytes, then the rest. Files a tool showed it are
59
+ * projected again as a turn projects its own.
60
+ */
61
+ export function subagentModelMessages(input: {
62
+ readonly thread: SubagentThreadContext
63
+ readonly attachmentContext?: PreparedAgentAttachmentContext
64
+ /** When the thread was created, as the task closes with it. */
65
+ readonly createdAt: string
66
+ }): ModelMessage[] {
67
+ const { task, threadContext } = input.thread
68
+ const projections = input.attachmentContext
69
+ const byMessage = <T>(
70
+ message: AgentThreadModelContextMessage,
71
+ read: (messageId: string) => T | undefined
72
+ ): T | undefined => (message.id ? read(message.id) : undefined)
73
+
74
+ return toModelMessages([...(task ? [task] : []), ...threadContext.modelMessages], {
75
+ userMessageSuffix: (message) => (task && message.id === task.id ? input.createdAt : undefined),
76
+ fileText: ({ message, partIndex }) =>
77
+ byMessage(message, (id) =>
78
+ projections?.promptTextByPartKey.get(attachmentKey(id, partIndex))
79
+ ),
80
+ fileData: ({ message, partIndex }) =>
81
+ byMessage(message, (id) =>
82
+ projections?.modelFileDataByPartKey.get(attachmentKey(id, partIndex))
83
+ ),
84
+ toolResultFileText: ({ message, partIndex, contentIndex }) =>
85
+ byMessage(message, (id) =>
86
+ projections?.promptTextByPartKey.get(toolResultAttachmentKey(id, partIndex, contentIndex))
87
+ ),
88
+ afterToolResults: ({ message, partIndex }) =>
89
+ byMessage(message, (id) =>
90
+ projections?.toolFilesByStep?.get(toolFilesStepKey(id, partIndex))
91
+ ),
92
+ })
93
+ }
94
+
95
+ /** How a child's calls are cached, its summary's included (see childCacheLifetime). */
96
+ export function subagentPromptCaching(input: {
97
+ readonly projectId: string
98
+ readonly thread: AgentThreadRecord
99
+ readonly run: SubagentRunRecord
100
+ readonly history: SubagentHistory
101
+ }): ModelCachingIntent {
102
+ const { run, history } = input
103
+ return conversationPromptCaching({
104
+ projectId: input.projectId,
105
+ threadId: conversationThreadId(input.thread),
106
+ lifetime: childCacheLifetime({
107
+ runsEveryCall: agentRunApprovalMode(run) === "auto",
108
+ // A run that continues the thread finds an earlier run's messages there, or their summary.
109
+ continues:
110
+ history.checkpoint !== null || history.messages.some((message) => message.runId !== run.id),
111
+ }),
112
+ })
113
+ }
114
+
115
+ /**
116
+ * Weigh a child's thread before its first call, and compact it when it crosses the model's limit,
117
+ * or when it comes back idle and large (see shouldCompactIdleContext): what the run then starts
118
+ * from, and the bytes per token the thread was measured at.
119
+ */
120
+ export async function preflightSubagentContext(
121
+ input: AgentThreadCompactionInput & { readonly threadContext: LoadedAgentThreadModelContext }
122
+ ): Promise<{
123
+ readonly threadContext: LoadedAgentThreadModelContext
124
+ readonly bytesPerToken: number
125
+ }> {
126
+ const { plan, budget, threadContext } = input
127
+ const estimateShape = input.estimateShape(threadContext, undefined)
128
+ const estimate = estimateAgentConversation({ plan, budget, threadContext, ...estimateShape })
129
+ const overLimit = shouldCompactAgentContext({
130
+ estimatedInputTokens: estimate.tokens,
131
+ inputBudgetTokens: budget.inputBudgetTokens,
132
+ })
133
+
134
+ // The same rule as a conversation's turn: compacting brings an idle thread under its size.
135
+ const idle =
136
+ !overLimit &&
137
+ shouldCompactIdleContext({
138
+ history: threadContext.history,
139
+ caching: input.caching,
140
+ estimatedInputTokens: estimate.tokens,
141
+ compactedTokens: inRunCompactedTokens({
142
+ plan,
143
+ budget,
144
+ threadContext,
145
+ estimateShape,
146
+ bytesPerToken: estimate.bytesPerToken,
147
+ }),
148
+ })
149
+ if (!overLimit && !idle) return { threadContext, bytesPerToken: estimate.bytesPerToken }
150
+
151
+ const compacted = await compactAgentThreadInRun({
152
+ ...input,
153
+ memory: undefined,
154
+ reason: "threshold",
155
+ // Below the limit, the thread compacts because it came back idle: its cache has gone cold.
156
+ coldCache: !overLimit,
157
+ })
158
+ return {
159
+ threadContext: compacted?.threadContext ?? threadContext,
160
+ bytesPerToken: estimate.bytesPerToken,
161
+ }
162
+ }
163
+
164
+ /**
165
+ * The failure of a child whose call its guard reduced and the provider still refused as too long
166
+ * for the window: what its parent can do about it. Undefined for any other error.
167
+ */
168
+ export function subagentContextFailure(error: unknown, run: SubagentRunRecord): Error | undefined {
169
+ if (!(error instanceof ModelProviderError) || error.reason !== "context-window-exceeded") {
170
+ return undefined
171
+ }
172
+
173
+ const remedy = "Spawn it again with a narrower task, or a model with a larger context window."
174
+ return withFailureMessage(
175
+ createSixbError(
176
+ "agent.execution_failed",
177
+ `[SixbAgent] Subagent run '${run.id}' still exceeds its model's context window after its context was reduced. ${remedy}`,
178
+ { cause: error, details: { parentRunId: run.parentRunId, runId: run.id } }
179
+ ),
180
+ `The subagent's context exceeds its model's context window, even reduced. ${remedy}`
181
+ )
182
+ }
@@ -1,6 +1,7 @@
1
1
  import type { AgentMessagePart } from "@sixb/core"
2
+ import type { AgentTurnHistory } from "@sixb/core/internal/agents"
2
3
  import type { AgentMessageRecord, SubagentRunRecord } from "@sixb/core/storage"
3
- import { renderCurrentTime } from "./agent-prompt"
4
+ import { renderCurrentTime, type SentSettings } from "./agent-prompt"
4
5
  import { mailPart } from "./subagent-inbox"
5
6
 
6
7
  // A child that paused continues as the next run of its thread under a later turn: once its held
@@ -8,9 +9,13 @@ import { mailPart } from "./subagent-inbox"
8
9
  // on, in the turn the parent answers it. The same key, model and task. Its history is its thread,
9
10
  // and what it goes on with is the message that starts the run.
10
11
 
11
- /** What a child run reads of its thread: its messages, and the paused run it continues (`AgentChildContext`). */
12
- export interface SubagentHistory {
13
- readonly messages: readonly AgentMessageRecord[]
12
+ /**
13
+ * What a child run reads of its thread (`AgentChildContext`): its latest checkpoint and the
14
+ * messages after it, its task when the checkpoint summarized it, and the paused run it continues.
15
+ */
16
+ export interface SubagentHistory extends AgentTurnHistory {
17
+ /** The thread's first message, when a checkpoint summarized it: its requests keep it as it is. */
18
+ readonly task?: AgentMessageRecord
14
19
  /** The run of the thread that paused on its held calls, when this run continues it. */
15
20
  readonly paused?: SubagentRunRecord
16
21
  }
@@ -31,7 +36,7 @@ export function continuationTrigger(input: {
31
36
  /** Whether the sandbox provider keeps the child's workspace while it pauses. */
32
37
  readonly keepsWorkspace: boolean
33
38
  readonly createdAt: Date
34
- readonly timeZone: string
39
+ readonly settings: SentSettings
35
40
  }): readonly AgentMessagePart[] {
36
41
  return [
37
42
  ...input.goesOnWith,
@@ -39,7 +44,7 @@ export function continuationTrigger(input: {
39
44
  ...(input.keepsWorkspace
40
45
  ? []
41
46
  : [{ type: "text" as const, text: sandboxRestarted(input.paused) }]),
42
- { type: "text", text: `\n\n${renderCurrentTime(input.createdAt, input.timeZone)}` },
47
+ { type: "text", text: `\n\n${renderCurrentTime(input.createdAt, input.settings)}` },
43
48
  ]
44
49
  }
45
50
 
@@ -1,4 +1,3 @@
1
- import { posix } from "node:path"
2
1
  import { isDeepStrictEqual } from "node:util"
3
2
  import {
4
3
  AGENT_REASONING_LEVELS,
@@ -44,10 +43,9 @@ import type {
44
43
  } from "@sixb/core/storage"
45
44
  import { AgentStorageError } from "@sixb/core/storage"
46
45
  import { delay } from "./abort"
47
- import { renderHandedFiles } from "./agent-prompt"
46
+ import { renderHandedFiles, sentSettings } from "./agent-prompt"
48
47
  import { formatBytes, SANDBOX_ATTACHMENT_LIMITS } from "./attachments"
49
48
  import {
50
- CHILD_FILES_DIRECTORY,
51
49
  handedFileRefs,
52
50
  type InstalledChildFile,
53
51
  installChildOutputs,
@@ -59,7 +57,6 @@ import { ChildMailClosedError, FamilyMailbox } from "./family-mailbox"
59
57
  import { agentToolErrorText } from "./model-adapters"
60
58
  import { renderModelLine } from "./model-lines"
61
59
  import type { TurnChildren } from "./run-agent-turn"
62
- import { SANDBOX_CONTEXT_DIRECTORY } from "./run-sandbox"
63
60
  import { continuationTrigger } from "./subagent-continuation"
64
61
  import type { AgentRunFiles, AgentRunSettings } from "./types"
65
62
 
@@ -97,6 +94,8 @@ export interface SpawnSubagentInput {
97
94
  readonly task: string
98
95
  readonly model?: LanguageModelRef | LanguageModelTier
99
96
  readonly reasoning?: AgentReasoning
97
+ /** At most this many steps, fewer than the project's limit. */
98
+ readonly maxSteps?: number
100
99
  /** Files and directories in the parent's sandbox, copied into the child's at the same paths. */
101
100
  readonly files?: readonly string[]
102
101
  }
@@ -146,6 +145,8 @@ export interface WaitedSubagentResult {
146
145
  /** The question it waits on: answer it with `message_agent` and its key. */
147
146
  readonly question?: QuestionRef
148
147
  readonly error?: { readonly code: string; readonly message: string }
148
+ /** The last text a child its step limit stopped wrote: what it found so far, or where it was. */
149
+ readonly partialAnswer?: string
149
150
  /** Calls it made that wait for the user's approval. */
150
151
  readonly awaitingApproval?: readonly AgentChildApprovalAwaiting[]
151
152
  /**
@@ -374,7 +375,8 @@ export class SubagentCoordinator {
374
375
  renderSubagentModelGuide(this.models),
375
376
  ...modelChoice(this.models).advice,
376
377
  OMIT_MODEL,
377
- `Pass files to copy files or directories of your sandbox into the child's, at the same paths, before it starts. What the child writes to out/ comes back with wait_agent's result when it finishes, under ${posix.join(SANDBOX_CONTEXT_DIRECTORY, CHILD_FILES_DIRECTORY)}/<key>/ this turn.`,
378
+ `Pass files to copy files or directories of your sandbox into the child's, at the same paths, before it starts. What the child writes to out/ comes back with wait_agent's result when it finishes, which lists where each file is.`,
379
+ `A child that has not answered after ${this.models.maxSteps} steps (model calls) stops and fails with agent.step_limit_reached; pass maxSteps to stop it sooner.`,
378
380
  `At most ${this.context.subagentConcurrencyPerRun} child agents may be active for this run.`,
379
381
  ].join("\n"),
380
382
  inputSchema: spawnInputSchema(this.models),
@@ -393,6 +395,7 @@ export class SubagentCoordinator {
393
395
  "Shortly before this run must end, it returns children still at work as queued or running, so you can answer with what the others found.",
394
396
  "A child paused on calls that wait for the user's approval returns as awaiting_approval, with those calls: it continues once the user decides, unless the user sends a new message or stops instead.",
395
397
  "A message you sent a child that it has not read is listed in its unread. When one came as it answered, earlierAnswer holds what it answered before, and text what it wrote after.",
398
+ "A child that failed with agent.step_limit_reached did not finish: partialAnswer holds the last text it wrote.",
396
399
  "It returns as soon as a child of this turn asks you a question, listed in questions with its key, whichever children you wait for: the child waits for your answer, which you give with message_agent.",
397
400
  ].join("\n"),
398
401
  inputSchema: waitInputSchema(this.context.subagentConcurrencyPerRun),
@@ -727,12 +730,13 @@ export class SubagentCoordinator {
727
730
  const task = requireNonEmpty("spawn_agent", input.task, "task")
728
731
  const model = this.resolveModel(input.model)
729
732
  const reasoning = input.reasoning ?? model.defaultReasoning
733
+ const maxSteps = this.resolveMaxSteps(input.maxSteps)
730
734
  const sources = input.files?.length
731
735
  ? await listHandedSources({ files: this.runFiles(), paths: input.files, signal })
732
736
  : undefined
733
737
  const runId = createSubagentRunId(this.parentRun.id, key)
734
738
  const specWith = (files: readonly SubagentRunFile[] | undefined) =>
735
- this.childSpec({ task, model, tier: model.tier, reasoning, files })
739
+ this.childSpec({ task, model, tier: model.tier, reasoning, maxSteps, files })
736
740
 
737
741
  // One admission at a time: only this turn adds children to it, so admission's answer is known
738
742
  // before any file is read, and a refused spawn reads and stores none.
@@ -835,6 +839,7 @@ export class SubagentCoordinator {
835
839
  model: paused.spec.model,
836
840
  tier: paused.spec.tier,
837
841
  reasoning: paused.spec.reasoning,
842
+ maxSteps: paused.spec.maxSteps,
838
843
  files: paused.spec.files,
839
844
  })
840
845
  const createdAt = new Date()
@@ -843,7 +848,7 @@ export class SubagentCoordinator {
843
848
  paused,
844
849
  keepsWorkspace: this.context.keepsChildWorkspaces,
845
850
  createdAt,
846
- timeZone: spec.timeZone ?? this.context.timeZone,
851
+ settings: sentSettings(spec, this.context),
847
852
  })
848
853
  return {
849
854
  spec,
@@ -861,9 +866,10 @@ export class SubagentCoordinator {
861
866
  readonly model: LanguageModelRef
862
867
  readonly tier: LanguageModelTier | undefined
863
868
  readonly reasoning: AgentReasoning | undefined
869
+ readonly maxSteps: number | undefined
864
870
  readonly files: readonly SubagentRunFile[] | undefined
865
871
  }): SubagentRunSpec {
866
- const { task, model, tier, reasoning, files } = input
872
+ const { task, model, tier, reasoning, maxSteps, files } = input
867
873
  const { approvalMode, timeZone, locale } = this.parentRun.spec ?? {}
868
874
  return {
869
875
  model: { provider: model.provider, modelId: model.modelId },
@@ -871,6 +877,7 @@ export class SubagentCoordinator {
871
877
  toolNames: this.delegation.toolNames,
872
878
  ...(tier === undefined ? {} : { tier }),
873
879
  ...(reasoning === undefined ? {} : { reasoning }),
880
+ ...(maxSteps === undefined ? {} : { maxSteps }),
874
881
  ...(approvalMode === undefined ? {} : { approvalMode }),
875
882
  ...(timeZone === undefined ? {} : { timeZone }),
876
883
  ...(locale === undefined ? {} : { locale }),
@@ -958,7 +965,12 @@ export class SubagentCoordinator {
958
965
  if (children.every(isTerminalSubagent) || asked) {
959
966
  const awaiting = await this.session.children.awaitingApproval(runIds)
960
967
  const delivered = await this.deliverFiles(children, signal)
961
- const messages = await Promise.all(children.map((run) => this.messagesTo(run)))
968
+ const messages = await Promise.all(
969
+ children.map(async (run) => ({
970
+ ...(await this.messagesTo(run)),
971
+ ...(await this.partialAnswerOf(run)),
972
+ }))
973
+ )
962
974
  // It lists the questions it returns first, and those its children wait on.
963
975
  const listed = asking.filter(
964
976
  (question) => !this.#reported.has(question.id) || runIds.includes(question.runId)
@@ -1024,6 +1036,27 @@ export class SubagentCoordinator {
1024
1036
  }
1025
1037
  }
1026
1038
 
1039
+ /**
1040
+ * What a child its step limit stopped wrote last, from its thread: its failure says it did not
1041
+ * finish, and its parent decides whether this is enough.
1042
+ */
1043
+ private async partialAnswerOf(
1044
+ run: SubagentRunRecord
1045
+ ): Promise<Pick<WaitedSubagentResult, "partialAnswer">> {
1046
+ if (run.status !== "failed" || run.error?.code !== "agent.step_limit_reached") return {}
1047
+
1048
+ const { messages } = await this.session.threads.messages({
1049
+ threadId: run.threadId,
1050
+ order: "asc",
1051
+ })
1052
+ const written = messages
1053
+ .filter((message) => message.runId === run.id && message.role === "assistant")
1054
+ .flatMap((message) => message.parts)
1055
+ .flatMap((part) => (part.type === "text" && part.text.trim() ? [part.text.trim()] : []))
1056
+ const partialAnswer = written.at(-1)
1057
+ return partialAnswer ? { partialAnswer } : {}
1058
+ }
1059
+
1027
1060
  /**
1028
1061
  * The run a child of an earlier turn is waited for as: its thread's latest, the one that continues
1029
1062
  * it when this turn resumes its pause; else `runId` itself.
@@ -1152,6 +1185,17 @@ export class SubagentCoordinator {
1152
1185
  return this.#runFiles
1153
1186
  }
1154
1187
 
1188
+ /** A spawn may ask for fewer steps than the project allows, never more. */
1189
+ private resolveMaxSteps(maxSteps: number | undefined): number | undefined {
1190
+ const limit = this.models.maxSteps
1191
+ if (maxSteps !== undefined && maxSteps > limit) {
1192
+ throw new AgentToolPublicError(
1193
+ `[SixbAgent] spawn_agent maxSteps must be at most ${limit}, the project's limit. Omit it to use that limit.`
1194
+ )
1195
+ }
1196
+ return maxSteps
1197
+ }
1198
+
1155
1199
  private resolveModel(
1156
1200
  ref: LanguageModelRef | LanguageModelTier | undefined
1157
1201
  ): AgentRunDelegationModel {
@@ -1276,6 +1320,13 @@ function spawnInputSchema(models: AgentRunDelegation): JsonObject {
1276
1320
  },
1277
1321
  ],
1278
1322
  },
1323
+ maxSteps: {
1324
+ type: "integer",
1325
+ minimum: 1,
1326
+ maximum: models.maxSteps,
1327
+ description:
1328
+ "At most this many steps (model calls) for the child. Omit it to use the limit.",
1329
+ },
1279
1330
  files: {
1280
1331
  type: "array",
1281
1332
  minItems: 1,
@@ -1521,10 +1572,12 @@ function errorMessage(error: unknown): string {
1521
1572
  function parseSpawnInput(value: unknown): SpawnSubagentInput {
1522
1573
  if (
1523
1574
  !isJsonObject(value) ||
1524
- Object.keys(value).some((key) => !["key", "task", "model", "reasoning", "files"].includes(key))
1575
+ Object.keys(value).some(
1576
+ (key) => !["key", "task", "model", "reasoning", "maxSteps", "files"].includes(key)
1577
+ )
1525
1578
  ) {
1526
1579
  throw new AgentToolPublicError(
1527
- "[SixbAgent] spawn_agent expects key, task, and optional model/reasoning/files."
1580
+ "[SixbAgent] spawn_agent expects key, task, and optional model/reasoning/maxSteps/files."
1528
1581
  )
1529
1582
  }
1530
1583
  const key = requireNonEmpty("spawn_agent", value.key, "key", 128)
@@ -1552,12 +1605,21 @@ function parseSpawnInput(value: unknown): SpawnSubagentInput {
1552
1605
  if (value.reasoning !== undefined && !isModelReasoning(value.reasoning)) {
1553
1606
  throw new AgentToolPublicError("[SixbAgent] spawn_agent reasoning is invalid.")
1554
1607
  }
1608
+ if (
1609
+ value.maxSteps !== undefined &&
1610
+ (typeof value.maxSteps !== "number" ||
1611
+ !Number.isSafeInteger(value.maxSteps) ||
1612
+ value.maxSteps < 1)
1613
+ ) {
1614
+ throw new AgentToolPublicError("[SixbAgent] spawn_agent maxSteps must be a positive integer.")
1615
+ }
1555
1616
  const files = parseSpawnFiles(value.files)
1556
1617
  return {
1557
1618
  key,
1558
1619
  task,
1559
1620
  ...(model === undefined ? {} : { model }),
1560
1621
  ...(value.reasoning === undefined ? {} : { reasoning: value.reasoning }),
1622
+ ...(value.maxSteps === undefined ? {} : { maxSteps: value.maxSteps }),
1561
1623
  ...(files === undefined ? {} : { files }),
1562
1624
  }
1563
1625
  }
@@ -13,13 +13,19 @@ export interface LoadedAgentThreadModelContext {
13
13
  readonly history: AgentTurnHistory
14
14
  }
15
15
 
16
- /** The retained tail with its checkpoint, projected for the model. */
17
- export function agentThreadModelContext(history: AgentTurnHistory): LoadedAgentThreadModelContext {
16
+ /**
17
+ * The retained tail with its checkpoint, projected for the model. A child's run reads its thread
18
+ * without `historyReadable`: `sixb history` prints only a conversation's.
19
+ */
20
+ export function agentThreadModelContext(
21
+ history: AgentTurnHistory,
22
+ options: { readonly historyReadable?: boolean } = {}
23
+ ): LoadedAgentThreadModelContext {
18
24
  const { checkpoint, messages } = history
19
25
  return {
20
26
  checkpoint,
21
27
  retainedMessages: messages,
22
- modelMessages: projectAgentThreadModelContext({ checkpoint, messages }),
28
+ modelMessages: projectAgentThreadModelContext({ checkpoint, messages, ...options }),
23
29
  history,
24
30
  }
25
31
  }
package/src/tools/bash.ts CHANGED
@@ -41,6 +41,9 @@ export interface BashToolOutput extends CommandResult {
41
41
  * resolver is awaited on the first command, not at tool-construction time, so
42
42
  * sandbox creation can run concurrently with the model's first response instead
43
43
  * of blocking the turn. A resolver rejection surfaces as a failed command.
44
+ *
45
+ * Its output holds the command's streams whole: the run's tools save an output too large for the
46
+ * context to a file and keep {@link keptCommandOutput} of it (see tool-outputs.ts).
44
47
  */
45
48
  export function createBashTool(
46
49
  resolveSandbox: () => Promise<AgentSandboxHandle>
@@ -56,7 +59,12 @@ export function createBashTool(
56
59
  timeout: normalizeTimeout(input.timeoutMs),
57
60
  signal,
58
61
  })
59
- return truncateCommandResult(result) as unknown as JsonValue
62
+ const output: BashToolOutput = {
63
+ ...result,
64
+ stdoutTruncated: false,
65
+ stderrTruncated: false,
66
+ }
67
+ return output as unknown as JsonValue
60
68
  },
61
69
  errorText: () => "The command failed.",
62
70
  }
@@ -95,6 +103,14 @@ function normalizeTimeout(timeoutMs: number | undefined): number {
95
103
  return Math.min(Math.floor(timeoutMs), MAX_COMMAND_TIMEOUT_MS)
96
104
  }
97
105
 
106
+ /**
107
+ * What a command's message part keeps of an output saved to a file: each stream within
108
+ * 20,000 characters, as the app, the TUI and `sixb history` show it.
109
+ */
110
+ export function keptCommandOutput(output: CommandResult): BashToolOutput {
111
+ return truncateCommandResult(output)
112
+ }
113
+
98
114
  function truncateCommandResult(result: CommandResult): BashToolOutput {
99
115
  // stdout is usually a Sixb API JSON response: compact it (and, if still oversized, keep a valid
100
116
  // structural prefix) so both the model and the chat UI receive parseable JSON rather than a body
@@ -7,16 +7,21 @@ import { BASH_TOOL_SPEC } from "./bash"
7
7
  import { READ_TOOL_SPEC } from "./read"
8
8
  import { VIEW_FILE_TOOL_SPEC } from "./view-file"
9
9
 
10
- /** Describe exactly the tools a conversational model receives, without starting its sandbox. */
10
+ /**
11
+ * Describe exactly the tools a conversational model receives, in its order, without starting its
12
+ * sandbox. A conversation publishes artifacts once its run executes in a thread.
13
+ */
11
14
  export function agentModelToolSpecs(
12
- projectTools: readonly AgentToolSpec[]
15
+ projectTools: readonly AgentToolSpec[],
16
+ options: { readonly publishes?: boolean } = {}
13
17
  ): readonly AgentToolSpec[] {
14
18
  return [
15
19
  ...projectTools,
16
20
  VIEW_FILE_TOOL_SPEC,
17
21
  READ_TOOL_SPEC,
18
22
  BASH_TOOL_SPEC,
19
- PUBLISH_ARTIFACT_TOOL_SPEC,
20
- PUBLISH_ARTIFACT_VERSION_TOOL_SPEC,
23
+ ...(options.publishes === false
24
+ ? []
25
+ : [PUBLISH_ARTIFACT_TOOL_SPEC, PUBLISH_ARTIFACT_VERSION_TOOL_SPEC]),
21
26
  ]
22
27
  }