@sixb/agent 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +31 -2
- package/dist/abort.d.ts +6 -0
- package/dist/abort.d.ts.map +1 -0
- package/dist/agent-prompt.d.ts +120 -0
- package/dist/agent-prompt.d.ts.map +1 -0
- package/dist/agent-runtime/errors.d.ts +13 -0
- package/dist/agent-runtime/errors.d.ts.map +1 -0
- package/dist/agent-runtime/preflight.d.ts +18 -0
- package/dist/agent-runtime/preflight.d.ts.map +1 -0
- package/dist/agent-runtime/profile.d.ts +14 -0
- package/dist/agent-runtime/profile.d.ts.map +1 -0
- package/dist/artifacts/layout-check/layout-check.d.ts +87 -0
- package/dist/artifacts/layout-check/layout-check.d.ts.map +1 -0
- package/dist/artifacts/materialize.d.ts +115 -0
- package/dist/artifacts/materialize.d.ts.map +1 -0
- package/dist/artifacts/publish-tool.d.ts +86 -0
- package/dist/artifacts/publish-tool.d.ts.map +1 -0
- package/dist/ask-parent-tool.d.ts +36 -0
- package/dist/ask-parent-tool.d.ts.map +1 -0
- package/dist/attachments.d.ts +68 -0
- package/dist/attachments.d.ts.map +1 -0
- package/dist/child-files.d.ts +96 -0
- package/dist/child-files.d.ts.map +1 -0
- package/dist/child-questions.d.ts +24 -0
- package/dist/child-questions.d.ts.map +1 -0
- package/dist/computer-runner.d.ts +65 -0
- package/dist/computer-runner.d.ts.map +1 -0
- package/dist/context-budget.d.ts +28 -0
- package/dist/context-budget.d.ts.map +1 -0
- package/dist/context-compaction.d.ts +48 -0
- package/dist/context-compaction.d.ts.map +1 -0
- package/dist/conversation-memory.d.ts +21 -0
- package/dist/conversation-memory.d.ts.map +1 -0
- package/dist/errors.d.ts +46 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/execution-plan.d.ts +34 -0
- package/dist/execution-plan.d.ts.map +1 -0
- package/dist/failure.d.ts +14 -0
- package/dist/failure.d.ts.map +1 -0
- package/dist/family-mailbox.d.ts +60 -0
- package/dist/family-mailbox.d.ts.map +1 -0
- package/dist/file-ref.d.ts +6 -0
- package/dist/file-ref.d.ts.map +1 -0
- package/dist/image-attachments.d.ts +34 -0
- package/dist/image-attachments.d.ts.map +1 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +12168 -0
- package/dist/index.js.map +65 -0
- package/dist/message-authors.d.ts +34 -0
- package/dist/message-authors.d.ts.map +1 -0
- package/dist/message-times.d.ts +8 -0
- package/dist/message-times.d.ts.map +1 -0
- package/dist/model-adapters.d.ts +55 -0
- package/dist/model-adapters.d.ts.map +1 -0
- package/dist/model-lines.d.ts +16 -0
- package/dist/model-lines.d.ts.map +1 -0
- package/dist/requester.d.ts +15 -0
- package/dist/requester.d.ts.map +1 -0
- package/dist/run-agent-turn.d.ts +63 -0
- package/dist/run-agent-turn.d.ts.map +1 -0
- package/dist/run-child.d.ts +77 -0
- package/dist/run-child.d.ts.map +1 -0
- package/dist/run-conversation-turn.d.ts +42 -0
- package/dist/run-conversation-turn.d.ts.map +1 -0
- package/dist/run-credential.d.ts +22 -0
- package/dist/run-credential.d.ts.map +1 -0
- package/dist/run-environment.d.ts +115 -0
- package/dist/run-environment.d.ts.map +1 -0
- package/dist/run-fate.d.ts +15 -0
- package/dist/run-fate.d.ts.map +1 -0
- package/dist/run-sandbox.d.ts +60 -0
- package/dist/run-sandbox.d.ts.map +1 -0
- package/dist/run-subagent.d.ts +51 -0
- package/dist/run-subagent.d.ts.map +1 -0
- package/dist/run-workflow-agent-node.d.ts +41 -0
- package/dist/run-workflow-agent-node.d.ts.map +1 -0
- package/dist/sandbox-api-context.d.ts +34 -0
- package/dist/sandbox-api-context.d.ts.map +1 -0
- package/dist/sandbox-file-registry.d.ts +9 -0
- package/dist/sandbox-file-registry.d.ts.map +1 -0
- package/dist/sandbox-files.d.ts +71 -0
- package/dist/sandbox-files.d.ts.map +1 -0
- package/dist/sandbox-handle.d.ts +15 -0
- package/dist/sandbox-handle.d.ts.map +1 -0
- package/dist/sandbox-readiness.d.ts +8 -0
- package/dist/sandbox-readiness.d.ts.map +1 -0
- package/dist/skills/built-in.d.ts +15 -0
- package/dist/skills/built-in.d.ts.map +1 -0
- package/dist/subagent-continuation.d.ts +27 -0
- package/dist/subagent-continuation.d.ts.map +1 -0
- package/dist/subagent-inbox.d.ts +53 -0
- package/dist/subagent-inbox.d.ts.map +1 -0
- package/dist/subagent-tools.d.ts +282 -0
- package/dist/subagent-tools.d.ts.map +1 -0
- package/dist/thread-context.d.ts +12 -0
- package/dist/thread-context.d.ts.map +1 -0
- package/dist/tools/attachments.d.ts +11 -0
- package/dist/tools/attachments.d.ts.map +1 -0
- package/dist/tools/bash.d.ts +60 -0
- package/dist/tools/bash.d.ts.map +1 -0
- package/dist/tools/model-spec.d.ts +4 -0
- package/dist/tools/model-spec.d.ts.map +1 -0
- package/dist/tools/read.d.ts +43 -0
- package/dist/tools/read.d.ts.map +1 -0
- package/dist/tools/result-media.d.ts +22 -0
- package/dist/tools/result-media.d.ts.map +1 -0
- package/dist/tools/result-output.d.ts +18 -0
- package/dist/tools/result-output.d.ts.map +1 -0
- package/dist/tools/tool-files.d.ts +59 -0
- package/dist/tools/tool-files.d.ts.map +1 -0
- package/dist/tools/view-file.d.ts +40 -0
- package/dist/tools/view-file.d.ts.map +1 -0
- package/dist/tsconfig.json +5 -0
- package/dist/turn-runtime.d.ts +19 -0
- package/dist/turn-runtime.d.ts.map +1 -0
- package/dist/types.d.ts +76 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/workflow-input-attachments.d.ts +18 -0
- package/dist/workflow-input-attachments.d.ts.map +1 -0
- package/package.json +59 -4
- package/src/abort.ts +40 -0
- package/src/agent-prompt.ts +758 -0
- package/src/agent-runtime/errors.ts +44 -0
- package/src/agent-runtime/preflight.ts +314 -0
- package/src/agent-runtime/profile.ts +23 -0
- package/src/artifacts/layout-check/check.cjs +478 -0
- package/src/artifacts/layout-check/layout-check.ts +460 -0
- package/src/artifacts/materialize.ts +380 -0
- package/src/artifacts/publish-tool.ts +700 -0
- package/src/ask-parent-tool.ts +100 -0
- package/src/attachments.ts +850 -0
- package/src/child-files.ts +540 -0
- package/src/child-questions.ts +42 -0
- package/src/computer-runner.ts +284 -0
- package/src/context-budget.ts +161 -0
- package/src/context-compaction.ts +529 -0
- package/src/conversation-memory.ts +45 -0
- package/src/errors.ts +85 -0
- package/src/execution-plan.ts +50 -0
- package/src/failure.ts +71 -0
- package/src/family-mailbox.ts +189 -0
- package/src/file-ref.ts +18 -0
- package/src/image-attachments.ts +322 -0
- package/src/index.ts +54 -0
- package/src/message-authors.ts +77 -0
- package/src/message-times.ts +21 -0
- package/src/model-adapters.ts +227 -0
- package/src/model-lines.ts +28 -0
- package/src/requester.ts +21 -0
- package/src/run-agent-turn.ts +347 -0
- package/src/run-child.ts +319 -0
- package/src/run-conversation-turn.ts +257 -0
- package/src/run-credential.ts +55 -0
- package/src/run-environment.ts +769 -0
- package/src/run-fate.ts +51 -0
- package/src/run-sandbox.ts +63 -0
- package/src/run-subagent.ts +347 -0
- package/src/run-workflow-agent-node.ts +270 -0
- package/src/sandbox-api-context.ts +234 -0
- package/src/sandbox-file-registry.ts +26 -0
- package/src/sandbox-files.ts +326 -0
- package/src/sandbox-handle.ts +19 -0
- package/src/sandbox-readiness.ts +22 -0
- package/src/skills/built-in.ts +183 -0
- package/src/skills/sixb-artifacts/SKILL.md +95 -0
- package/src/skills/sixb-artifacts/canvas.md +104 -0
- package/src/skills/sixb-artifacts/document.md +63 -0
- package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/first-job.html +42 -0
- package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/region.html +29 -0
- package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/shared.css +35 -0
- package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/welcome.html +31 -0
- package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/canvas.json +107 -0
- package/src/skills/sixb-artifacts/examples/canvas/retro/canvas.json +158 -0
- package/src/skills/sixb-artifacts/examples/document/incident-report/document.md +35 -0
- package/src/skills/sixb-artifacts/examples/document/operations-review/document.md +41 -0
- package/src/skills/sixb-artifacts/examples/document/operations-review/figures/restorations.svg +1 -0
- package/src/skills/sixb-artifacts/examples/page/collections-desk/index.html +169 -0
- package/src/skills/sixb-artifacts/examples/page/collections-desk/queries/overdue.json +13 -0
- package/src/skills/sixb-artifacts/examples/page/dispatch-board/data/dispatch.json +234 -0
- package/src/skills/sixb-artifacts/examples/page/dispatch-board/index.html +245 -0
- package/src/skills/sixb-artifacts/examples/page/fleet-planner/data/plan.json +53 -0
- package/src/skills/sixb-artifacts/examples/page/fleet-planner/index.html +462 -0
- package/src/skills/sixb-artifacts/examples/page/service-explorer/data/service.json +276 -0
- package/src/skills/sixb-artifacts/examples/page/service-explorer/index.html +549 -0
- package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/queries/overdue.json +13 -0
- package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/workbook.json +30 -0
- package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Inventory.csv +13 -0
- package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Spend.csv +6 -0
- package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/workbook.json +47 -0
- package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Quarters.csv +5 -0
- package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Regions.csv +5 -0
- package/src/skills/sixb-artifacts/examples/sheet/service-metrics/workbook.json +78 -0
- package/src/skills/sixb-artifacts/examples/slides/launch-plan/index.html +63 -0
- package/src/skills/sixb-artifacts/examples/slides/q3-review/index.html +133 -0
- package/src/skills/sixb-artifacts/file.md +17 -0
- package/src/skills/sixb-artifacts/page.md +215 -0
- package/src/skills/sixb-artifacts/queries.md +66 -0
- package/src/skills/sixb-artifacts/references.md +68 -0
- package/src/skills/sixb-artifacts/sheet.md +223 -0
- package/src/skills/sixb-artifacts/slides.md +137 -0
- package/src/skills/sixb-memory/SKILL.md +68 -0
- package/src/skills/text-assets.d.ts +25 -0
- package/src/subagent-continuation.ts +51 -0
- package/src/subagent-inbox.ts +101 -0
- package/src/subagent-tools.ts +1609 -0
- package/src/thread-context.ts +25 -0
- package/src/tools/attachments.ts +28 -0
- package/src/tools/bash.ts +217 -0
- package/src/tools/model-spec.ts +22 -0
- package/src/tools/read.ts +262 -0
- package/src/tools/result-media.ts +147 -0
- package/src/tools/result-output.ts +44 -0
- package/src/tools/tool-files.ts +204 -0
- package/src/tools/view-file.ts +155 -0
- package/src/turn-runtime.ts +33 -0
- package/src/types.ts +79 -0
- package/src/workflow-input-attachments.ts +140 -0
|
@@ -0,0 +1,1609 @@
|
|
|
1
|
+
import { posix } from "node:path"
|
|
2
|
+
import { isDeepStrictEqual } from "node:util"
|
|
3
|
+
import {
|
|
4
|
+
AGENT_REASONING_LEVELS,
|
|
5
|
+
type AgentApprovalOutcomePart,
|
|
6
|
+
type AgentMailPart,
|
|
7
|
+
type AgentMessage,
|
|
8
|
+
type AgentMessagePart,
|
|
9
|
+
type AgentReasoning,
|
|
10
|
+
AgentToolPublicError,
|
|
11
|
+
type AgentToolResult,
|
|
12
|
+
type LanguageModelRef,
|
|
13
|
+
type LanguageModelTier,
|
|
14
|
+
} from "@sixb/core"
|
|
15
|
+
import {
|
|
16
|
+
type AgentChildApprovalAwaiting,
|
|
17
|
+
type AgentChildDraft,
|
|
18
|
+
AgentExecutionLostError,
|
|
19
|
+
type AgentRunDelegation,
|
|
20
|
+
type AgentRunDelegationModel,
|
|
21
|
+
type AgentRunSession,
|
|
22
|
+
createAgentMessageId,
|
|
23
|
+
createSubagentRunId,
|
|
24
|
+
createSubagentThreadId,
|
|
25
|
+
deferredChildQuestion,
|
|
26
|
+
isAgentToolResult,
|
|
27
|
+
isAwaitingAnswerRun,
|
|
28
|
+
isPausedSubagentRun,
|
|
29
|
+
} from "@sixb/core/internal/agents"
|
|
30
|
+
import { formatLanguageModelTiers, isLanguageModelTier } from "@sixb/core/internal/model-execution"
|
|
31
|
+
import {
|
|
32
|
+
assertJsonValue,
|
|
33
|
+
defineLanguageModel,
|
|
34
|
+
isJsonObject,
|
|
35
|
+
isModelReasoning,
|
|
36
|
+
type JsonObject,
|
|
37
|
+
type ModelTool,
|
|
38
|
+
} from "@sixb/core/models"
|
|
39
|
+
import type {
|
|
40
|
+
ConversationAgentRunRecord,
|
|
41
|
+
SubagentRunFile,
|
|
42
|
+
SubagentRunRecord,
|
|
43
|
+
SubagentRunSpec,
|
|
44
|
+
} from "@sixb/core/storage"
|
|
45
|
+
import { AgentStorageError } from "@sixb/core/storage"
|
|
46
|
+
import { delay } from "./abort"
|
|
47
|
+
import { renderHandedFiles } from "./agent-prompt"
|
|
48
|
+
import { formatBytes, SANDBOX_ATTACHMENT_LIMITS } from "./attachments"
|
|
49
|
+
import {
|
|
50
|
+
CHILD_FILES_DIRECTORY,
|
|
51
|
+
handedFileRefs,
|
|
52
|
+
type InstalledChildFile,
|
|
53
|
+
installChildOutputs,
|
|
54
|
+
listHandedSources,
|
|
55
|
+
storeHandedFiles,
|
|
56
|
+
} from "./child-files"
|
|
57
|
+
import { type ChildQuestion, type QuestionRef, renderChildQuestions } from "./child-questions"
|
|
58
|
+
import { ChildMailClosedError, FamilyMailbox } from "./family-mailbox"
|
|
59
|
+
import { agentToolErrorText } from "./model-adapters"
|
|
60
|
+
import { renderModelLine } from "./model-lines"
|
|
61
|
+
import type { TurnChildren } from "./run-agent-turn"
|
|
62
|
+
import { SANDBOX_CONTEXT_DIRECTORY } from "./run-sandbox"
|
|
63
|
+
import { continuationTrigger } from "./subagent-continuation"
|
|
64
|
+
import type { AgentRunFiles, AgentRunSettings } from "./types"
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* How long a wait for children goes without reading their runs when nothing woke it. A child's
|
|
68
|
+
* question and its end wake it at once, through the turn's mailbox; this bounds an end recorded
|
|
69
|
+
* outside the runner, which nothing here hears: an API cancel of a child still queued, or a repair
|
|
70
|
+
* pass ending one whose own end could not be recorded. Five seconds keeps such a wait short beside
|
|
71
|
+
* the minutes a child works, and a wait reads storage 12 times a minute.
|
|
72
|
+
*/
|
|
73
|
+
export const CHILD_WAIT_RECHECK_MS = 5_000
|
|
74
|
+
/**
|
|
75
|
+
* How often a wait reads a run another turn's mailbox hears, which nothing wakes it for: a child
|
|
76
|
+
* of an earlier turn, or of an earlier attempt of this resume, still stopping. Both are rare and
|
|
77
|
+
* short, so a short poll costs little.
|
|
78
|
+
*/
|
|
79
|
+
export const OTHER_TURN_RECHECK_MS = 250
|
|
80
|
+
const OMIT_MODEL = "Omit model to use the project default."
|
|
81
|
+
|
|
82
|
+
/** With tiers, the model guide says how to choose, so only a list adds advice. */
|
|
83
|
+
const TIERED_MODEL_CHOICE = {
|
|
84
|
+
advice: [],
|
|
85
|
+
field: "A tier, or one exact model reference from the models you can delegate to.",
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const LISTED_MODEL_CHOICE = {
|
|
89
|
+
advice: [
|
|
90
|
+
"Prefer the default model unless another configured model is clearly better suited to the task. Price and runtime speed are not known, so do not infer them from model names.",
|
|
91
|
+
],
|
|
92
|
+
field: "Copy one exact model reference from the available models.",
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface SpawnSubagentInput {
|
|
96
|
+
readonly key: string
|
|
97
|
+
readonly task: string
|
|
98
|
+
readonly model?: LanguageModelRef | LanguageModelTier
|
|
99
|
+
readonly reasoning?: AgentReasoning
|
|
100
|
+
/** Files and directories in the parent's sandbox, copied into the child's at the same paths. */
|
|
101
|
+
readonly files?: readonly string[]
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export interface SpawnSubagentOutput {
|
|
105
|
+
readonly runId: string
|
|
106
|
+
readonly status: SubagentRunRecord["status"]
|
|
107
|
+
readonly model: LanguageModelRef
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export interface MessageSubagentInput {
|
|
111
|
+
readonly key: string
|
|
112
|
+
readonly text: string
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export interface MessageSubagentOutput {
|
|
116
|
+
readonly runId: string
|
|
117
|
+
readonly status: "queued" | "running"
|
|
118
|
+
/**
|
|
119
|
+
* When the child reads it: before its first step while it is queued, else before its next.
|
|
120
|
+
* `answer`: it answers the question the child waits on, now or, once it continues, first.
|
|
121
|
+
*/
|
|
122
|
+
readonly delivery: "first-step" | "next-step" | "answer"
|
|
123
|
+
/** The child of an earlier turn, paused on its question, that this answer continues. */
|
|
124
|
+
readonly continues?: string
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** A message the parent sent a child this turn. */
|
|
128
|
+
interface SentMessage {
|
|
129
|
+
readonly id: string
|
|
130
|
+
readonly text: string
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export interface WaitForSubagentsInput {
|
|
134
|
+
readonly runIds: readonly string[]
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export interface WaitedSubagentResult {
|
|
138
|
+
readonly runId: string
|
|
139
|
+
/**
|
|
140
|
+
* `queued` or `running`: the turn is about to end, so the Agent answers without it.
|
|
141
|
+
* `awaiting_approval`: it paused on calls that wait for the user, and continues once they decide,
|
|
142
|
+
* unless a new message sets the calls aside or the turn is stopped instead.
|
|
143
|
+
*/
|
|
144
|
+
readonly status: SubagentRunRecord["status"] | "awaiting_approval" | "awaiting_answer"
|
|
145
|
+
readonly text?: string
|
|
146
|
+
/** The question it waits on: answer it with `message_agent` and its key. */
|
|
147
|
+
readonly question?: QuestionRef
|
|
148
|
+
readonly error?: { readonly code: string; readonly message: string }
|
|
149
|
+
/** Calls it made that wait for the user's approval. */
|
|
150
|
+
readonly awaitingApproval?: readonly AgentChildApprovalAwaiting[]
|
|
151
|
+
/**
|
|
152
|
+
* What it wrote under `out/`, by path there, and where each is in the parent's sandbox this
|
|
153
|
+
* turn. The first result that lists them holds them as files, which later turns find in
|
|
154
|
+
* `$SIXB_ATTACHMENTS` by their `logicalPath`, `<key>/<path>`.
|
|
155
|
+
*/
|
|
156
|
+
readonly files?: readonly {
|
|
157
|
+
readonly path: string
|
|
158
|
+
readonly sandboxPath: string
|
|
159
|
+
readonly sizeBytes: number
|
|
160
|
+
readonly mediaType?: string
|
|
161
|
+
}[]
|
|
162
|
+
/** Why its files are not listed: they did not come back, could not be copied, or wait. */
|
|
163
|
+
readonly filesNote?: string
|
|
164
|
+
/** What this turn sent it that it has not read: a paused child reads it if it continues. */
|
|
165
|
+
readonly unread?: readonly SentMessage[]
|
|
166
|
+
/**
|
|
167
|
+
* What it answered before a message of yours came, which its `text`, written after, replaces.
|
|
168
|
+
* Set when it answered again.
|
|
169
|
+
*/
|
|
170
|
+
readonly earlierAnswer?: string
|
|
171
|
+
/** Why its `text` does not account for your last message, when it did not answer again. */
|
|
172
|
+
readonly answerNote?: string
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
type MessagesReport = Pick<WaitedSubagentResult, "unread" | "earlierAnswer" | "answerNote">
|
|
176
|
+
|
|
177
|
+
/** A question a child waits on, with the key to answer it by. */
|
|
178
|
+
export interface WaitedQuestion extends QuestionRef {
|
|
179
|
+
readonly key: string
|
|
180
|
+
readonly runId: string
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export interface WaitForSubagentsOutput {
|
|
184
|
+
readonly results: readonly WaitedSubagentResult[]
|
|
185
|
+
/** Every question a child of this turn waits on: `wait_agent` returns as soon as one comes. */
|
|
186
|
+
readonly questions?: readonly WaitedQuestion[]
|
|
187
|
+
/** The files no earlier result held, in the order of `results`. */
|
|
188
|
+
readonly files: readonly InstalledChildFile[]
|
|
189
|
+
/** Why what the children published is not all in `$SIXB_ARTIFACTS`. */
|
|
190
|
+
readonly artifactsError?: string
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** What a turn offers the children it spawns. */
|
|
194
|
+
export interface TurnDelegation {
|
|
195
|
+
/** The project's language models, from the turn's plan. */
|
|
196
|
+
readonly models: AgentRunDelegation
|
|
197
|
+
/** The project tools each child gets. */
|
|
198
|
+
readonly toolNames: readonly string[]
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Run-scoped boundary used by the parent Agent's framework-owned delegation tools. */
|
|
202
|
+
export class SubagentCoordinator {
|
|
203
|
+
private readonly models: AgentRunDelegation
|
|
204
|
+
#runFiles: AgentRunFiles | undefined
|
|
205
|
+
/** Children whose files are in the parent's sandbox, and in the result that first listed them. */
|
|
206
|
+
readonly #installed = new Map<string, readonly InstalledChildFile[]>()
|
|
207
|
+
/** The spawn being admitted: only this turn adds children to it. */
|
|
208
|
+
#admissions: Promise<unknown> = Promise.resolve()
|
|
209
|
+
/** What this turn sent each child, by its run id, in order. */
|
|
210
|
+
readonly #sent = new Map<string, SentMessage[]>()
|
|
211
|
+
/** What the turn and its children say to each other, in their runner. */
|
|
212
|
+
readonly #family = new FamilyMailbox()
|
|
213
|
+
/** The questions a `wait_agent` returned: one alone no longer stops a wait for other children. */
|
|
214
|
+
readonly #reported = new Set<string>()
|
|
215
|
+
/** What each `message_agent` that answered a question returned, by its mail id, for a replay. */
|
|
216
|
+
readonly #answers = new Map<string, MessageSubagentOutput>()
|
|
217
|
+
|
|
218
|
+
constructor(
|
|
219
|
+
/** What the turn offers its children: the project's language models, and its tools. */
|
|
220
|
+
private readonly delegation: TurnDelegation,
|
|
221
|
+
private readonly context: AgentRunSettings,
|
|
222
|
+
private readonly parentRun: ConversationAgentRunRecord,
|
|
223
|
+
/** The turn's session, through which it reaches its children's runs. */
|
|
224
|
+
private readonly session: AgentRunSession,
|
|
225
|
+
/**
|
|
226
|
+
* Run a child this turn spawned or continues, in the turn's own runner, on the turn's mailbox:
|
|
227
|
+
* it claims the child's run, opens its session and environment, and records its fate.
|
|
228
|
+
* Starting a run already running is a no-op.
|
|
229
|
+
*/
|
|
230
|
+
private readonly startChild: (run: SubagentRunRecord, family: FamilyMailbox) => void
|
|
231
|
+
) {
|
|
232
|
+
this.models = delegation.models
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** The turn ended: it sends its children nothing more. */
|
|
236
|
+
close(): void {
|
|
237
|
+
this.#family.close()
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* How the turn hears its children's questions: those of earlier turns' children still paused on
|
|
242
|
+
* one, read after the conversation; those it has not read, before its answer ends it; and the
|
|
243
|
+
* pause, before its end, of each child still waiting on one. And how a pausing turn waits for
|
|
244
|
+
* those still at work.
|
|
245
|
+
*/
|
|
246
|
+
async turnChildren(): Promise<TurnChildren> {
|
|
247
|
+
let waiting: readonly WaitedQuestion[] = []
|
|
248
|
+
try {
|
|
249
|
+
waiting = await this.waitingQuestions()
|
|
250
|
+
} catch (error) {
|
|
251
|
+
console.error(
|
|
252
|
+
`[SixbAgent] Agent run '${this.parentRun.id}' could not read which earlier sub-agents wait on a question; it goes on without them.`,
|
|
253
|
+
error
|
|
254
|
+
)
|
|
255
|
+
}
|
|
256
|
+
return {
|
|
257
|
+
...(waiting.length > 0 ? { waiting: renderChildQuestions(waiting, { earlier: true }) } : {}),
|
|
258
|
+
unread: async () => {
|
|
259
|
+
const unread = await this.unreadQuestions()
|
|
260
|
+
return unread.length > 0 ? renderChildQuestions(unread) : undefined
|
|
261
|
+
},
|
|
262
|
+
defer: (signal) => this.deferOpenQuestions(signal),
|
|
263
|
+
settle: (signal) => this.settleChildren(signal),
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** The parent's environment, started after its tools are defined and before any of them runs. */
|
|
268
|
+
attach(runFiles: AgentRunFiles): void {
|
|
269
|
+
this.#runFiles = runFiles
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* When this turn resumes a paused one, continue each child that paused on its held calls: the
|
|
274
|
+
* next run of its thread, under this turn and the same key, with the paused child's model, task
|
|
275
|
+
* and files, and this turn's mode. The outcomes of its calls start the run. Admitting
|
|
276
|
+
* it again finds it, so a retry of this turn, under its own id, admits its own.
|
|
277
|
+
*/
|
|
278
|
+
async continuePausedChildren(signal: AbortSignal): Promise<void> {
|
|
279
|
+
const paused = await this.pausedChildrenToContinue()
|
|
280
|
+
for (const { child, outcomes } of paused) {
|
|
281
|
+
signal.throwIfAborted()
|
|
282
|
+
await this.clearDeadAttempts(child, signal)
|
|
283
|
+
const { spec, continuation } = this.continuationOf(child, outcomes)
|
|
284
|
+
await this.admitInTurn(() =>
|
|
285
|
+
this.admit(
|
|
286
|
+
createSubagentRunId(this.parentRun.id, child.spawnKey),
|
|
287
|
+
child.spawnKey,
|
|
288
|
+
spec,
|
|
289
|
+
signal,
|
|
290
|
+
continuation
|
|
291
|
+
)
|
|
292
|
+
)
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Remove from a paused child's thread what the runs after its pause did under an earlier attempt
|
|
298
|
+
* of this resume, which failed: this turn continues the paused child again, as a retried turn
|
|
299
|
+
* replays from its trigger. A run still stopping is waited for: its lease ends it if nothing else
|
|
300
|
+
* does.
|
|
301
|
+
*/
|
|
302
|
+
private async clearDeadAttempts(paused: SubagentRunRecord, signal: AbortSignal): Promise<void> {
|
|
303
|
+
const { children } = this.session
|
|
304
|
+
|
|
305
|
+
for (;;) {
|
|
306
|
+
const runs = await children.threadRuns(paused.threadId)
|
|
307
|
+
const pausedAt = runs.findIndex((run) => run.id === paused.id)
|
|
308
|
+
const dead = (pausedAt < 0 ? [] : runs.slice(pausedAt + 1)).filter(
|
|
309
|
+
(run) => run.parentRunId !== this.parentRun.id
|
|
310
|
+
)
|
|
311
|
+
const stopping = dead.filter((run) => !isTerminalSubagent(run))
|
|
312
|
+
if (stopping.length === 0) {
|
|
313
|
+
for (const run of dead) {
|
|
314
|
+
await children.clearAttempt({ threadId: paused.threadId, runId: run.id })
|
|
315
|
+
}
|
|
316
|
+
return
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// Its end goes to the mailbox of the attempt it ran under, not this turn's: read it again.
|
|
320
|
+
await delay(OTHER_TURN_RECHECK_MS, signal)
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* The children this turn continues: those its trigger, a resume, reported as continuing, as the
|
|
326
|
+
* model reads it. The approvals, not the message, say which calls are the child's and that this
|
|
327
|
+
* message reported them, and the child must still be paused on them.
|
|
328
|
+
*/
|
|
329
|
+
private async pausedChildrenToContinue(): Promise<
|
|
330
|
+
readonly {
|
|
331
|
+
readonly child: SubagentRunRecord
|
|
332
|
+
readonly outcomes: readonly AgentApprovalOutcomePart[]
|
|
333
|
+
}[]
|
|
334
|
+
> {
|
|
335
|
+
const { children } = this.session
|
|
336
|
+
const trigger = await this.session.threads.message(this.parentRun.triggerMessageId)
|
|
337
|
+
if (!trigger) return []
|
|
338
|
+
|
|
339
|
+
const parts = trigger.parts.filter(
|
|
340
|
+
(part): part is AgentApprovalOutcomePart => part.type === "approval-outcome"
|
|
341
|
+
)
|
|
342
|
+
const callerIds = [
|
|
343
|
+
...new Set(parts.flatMap((part) => (part.caller?.continues ? [part.caller.runId] : []))),
|
|
344
|
+
]
|
|
345
|
+
if (callerIds.length === 0) return []
|
|
346
|
+
|
|
347
|
+
const continuing = []
|
|
348
|
+
for (const child of await children.getMany(callerIds)) {
|
|
349
|
+
if (child.kind !== "subagent" || !isPausedSubagentRun(child)) continue
|
|
350
|
+
|
|
351
|
+
const approvals = await children.approvals(child.parentRunId)
|
|
352
|
+
const reported = new Set(
|
|
353
|
+
approvals
|
|
354
|
+
.filter(
|
|
355
|
+
(approval) =>
|
|
356
|
+
approval.callerRunId === child.id && approval.reportedInMessageId === trigger.id
|
|
357
|
+
)
|
|
358
|
+
.map((approval) => approval.id)
|
|
359
|
+
)
|
|
360
|
+
const outcomes = parts
|
|
361
|
+
.filter((part) => reported.has(part.approvalId))
|
|
362
|
+
.map(({ caller: _caller, ...outcome }) => outcome)
|
|
363
|
+
if (outcomes.length > 0) continuing.push({ child, outcomes })
|
|
364
|
+
}
|
|
365
|
+
return continuing
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
async createTools(): Promise<readonly ModelTool[]> {
|
|
369
|
+
const spawn: ModelTool<SpawnSubagentInput> = {
|
|
370
|
+
name: "spawn_agent",
|
|
371
|
+
description: [
|
|
372
|
+
"Start an isolated child agent and return immediately.",
|
|
373
|
+
"Use a short, stable key for the same logical delegation so retries cannot duplicate work.",
|
|
374
|
+
renderSubagentModelGuide(this.models),
|
|
375
|
+
...modelChoice(this.models).advice,
|
|
376
|
+
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
|
+
`At most ${this.context.subagentConcurrencyPerRun} child agents may be active for this run.`,
|
|
379
|
+
].join("\n"),
|
|
380
|
+
inputSchema: spawnInputSchema(this.models),
|
|
381
|
+
parseInput: parseSpawnInput,
|
|
382
|
+
execute: async (value, { signal }) => {
|
|
383
|
+
const output = await this.spawn(value, signal)
|
|
384
|
+
assertJsonValue(output)
|
|
385
|
+
return output
|
|
386
|
+
},
|
|
387
|
+
errorText: agentToolErrorText,
|
|
388
|
+
}
|
|
389
|
+
const wait: ModelTool<WaitForSubagentsInput> = {
|
|
390
|
+
name: "wait_agent",
|
|
391
|
+
description: [
|
|
392
|
+
"Wait for previously spawned child agents and return their final text or failure, and the files each wrote to out/, each with its path in your sandbox. Pass every run id whose result is needed.",
|
|
393
|
+
"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
|
+
"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
|
+
"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.",
|
|
396
|
+
"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
|
+
].join("\n"),
|
|
398
|
+
inputSchema: waitInputSchema(this.context.subagentConcurrencyPerRun),
|
|
399
|
+
parseInput: (value) => parseWaitInput(value, this.context.subagentConcurrencyPerRun),
|
|
400
|
+
// A rich result, so its files reach later turns through $SIXB_ATTACHMENTS and the work trace.
|
|
401
|
+
execute: async (value, { signal }) => {
|
|
402
|
+
const { files, ...answer } = await this.wait(value, signal)
|
|
403
|
+
const output: AgentToolResult = {
|
|
404
|
+
kind: "agentToolResult",
|
|
405
|
+
content: [
|
|
406
|
+
{ type: "text", text: JSON.stringify(answer) },
|
|
407
|
+
...files.map(({ fileRef }) => ({ type: "file" as const, fileRef })),
|
|
408
|
+
],
|
|
409
|
+
}
|
|
410
|
+
assertJsonValue(output)
|
|
411
|
+
return output
|
|
412
|
+
},
|
|
413
|
+
// The answer lists each file's path this turn; the Agent reads the ones it needs.
|
|
414
|
+
toModelOutput: (output) => ({
|
|
415
|
+
type: "text",
|
|
416
|
+
value: isAgentToolResult(output)
|
|
417
|
+
? output.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n")
|
|
418
|
+
: JSON.stringify(output),
|
|
419
|
+
}),
|
|
420
|
+
errorText: agentToolErrorText,
|
|
421
|
+
}
|
|
422
|
+
const message: ModelTool<MessageSubagentInput> = {
|
|
423
|
+
name: "message_agent",
|
|
424
|
+
description: [
|
|
425
|
+
"Send a message to a child agent still at work, by the key you spawned it with. It reads the message before its next step, or before its first while it is queued, and its answer accounts for it.",
|
|
426
|
+
"Use it to correct its course, add information it needs, or narrow its task, instead of waiting for an answer you would discard. Then collect its answer with wait_agent as usual.",
|
|
427
|
+
"A child that finished, or paused for the user's approval, cannot read one.",
|
|
428
|
+
"While a child waits on the question it asked you, your message is its answer. A child that wait_agent listed as awaiting_answer, paused on its question when an earlier turn ended, continues where it stopped with your message as its answer.",
|
|
429
|
+
].join("\n"),
|
|
430
|
+
inputSchema: messageInputSchema(),
|
|
431
|
+
parseInput: parseMessageInput,
|
|
432
|
+
execute: async (value, { signal, callId, toolCallId }) => {
|
|
433
|
+
const output = await this.message(value, `${callId}:${toolCallId}`, signal)
|
|
434
|
+
assertJsonValue(output)
|
|
435
|
+
return output
|
|
436
|
+
},
|
|
437
|
+
errorText: agentToolErrorText,
|
|
438
|
+
}
|
|
439
|
+
return [spawn, wait, message]
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* Send a child a message, through the turn's mailbox. Its id names this turn, the model call and
|
|
444
|
+
* the tool call in it, so a replay of the call is the same message and the child reads it once,
|
|
445
|
+
* while two calls never share one, whatever ids the provider gives its tool calls.
|
|
446
|
+
*/
|
|
447
|
+
async message(
|
|
448
|
+
input: MessageSubagentInput,
|
|
449
|
+
callId: string,
|
|
450
|
+
signal: AbortSignal
|
|
451
|
+
): Promise<MessageSubagentOutput> {
|
|
452
|
+
signal.throwIfAborted()
|
|
453
|
+
const key = requireNonEmpty("message_agent", input.key, "key", 128)
|
|
454
|
+
const text = requireNonEmpty("message_agent", input.text, "text")
|
|
455
|
+
const sent = { id: `${this.parentRun.id}:${callId}`, text }
|
|
456
|
+
// A replay of the call that answered a question is that answer, sent once.
|
|
457
|
+
const answered = this.#answers.get(sent.id)
|
|
458
|
+
if (answered) return answered
|
|
459
|
+
|
|
460
|
+
const { children } = this.session
|
|
461
|
+
const child = await children.get(createSubagentRunId(this.parentRun.id, key))
|
|
462
|
+
if (!child) {
|
|
463
|
+
const paused = await this.pausedOnQuestion(key)
|
|
464
|
+
if (paused) return this.answerPaused(paused, key, sent, signal)
|
|
465
|
+
}
|
|
466
|
+
if (child?.kind !== "subagent" || child.parentRunId !== this.parentRun.id) {
|
|
467
|
+
throw new AgentToolPublicError(
|
|
468
|
+
(await this.latestChildUnder(key))
|
|
469
|
+
? `[SixbAgent] '${key}' is a child agent of an earlier turn, which ended with it. Spawn it again in this turn, with the same key if you like, and message it then.`
|
|
470
|
+
: `[SixbAgent] '${key}' is not a child agent of this turn. Use the key you passed to spawn_agent.`
|
|
471
|
+
)
|
|
472
|
+
}
|
|
473
|
+
// Once its call is filed it pauses at the end of its step, before it would read a message.
|
|
474
|
+
if (isPausedSubagentRun(child) || (await children.holdsRun(child.id))) {
|
|
475
|
+
throw new AgentToolPublicError(
|
|
476
|
+
`[SixbAgent] '${key}' is paused for the user's approval and reads no message until it continues, in the turn after the user decides. Message it then, or tell the user what to change.`
|
|
477
|
+
)
|
|
478
|
+
}
|
|
479
|
+
const { status } = child
|
|
480
|
+
if (status !== "queued" && status !== "running") {
|
|
481
|
+
throw new AgentToolPublicError(
|
|
482
|
+
`[SixbAgent] '${key}' already ended (${status}), so it cannot read a message. Spawn a new child with another key to go on.`
|
|
483
|
+
)
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
// While it waits on a question the model read, the message is its answer. The question is
|
|
487
|
+
// claimed before any wait, so of two answers sent at once only the first is one.
|
|
488
|
+
const question = this.#family.question(child.id)
|
|
489
|
+
if (question && status === "running" && this.#reported.has(question.id)) {
|
|
490
|
+
this.#family.answered(question)
|
|
491
|
+
try {
|
|
492
|
+
this.#family.send(child.id, { ...sent, kind: "answer", inReplyTo: question.id })
|
|
493
|
+
} catch (error) {
|
|
494
|
+
this.#family.reopen(question)
|
|
495
|
+
throw stoppedReading(error, key)
|
|
496
|
+
}
|
|
497
|
+
const output = { runId: child.id, status, delivery: "answer" } as const
|
|
498
|
+
this.#answers.set(sent.id, output)
|
|
499
|
+
return output
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
try {
|
|
503
|
+
this.#family.send(child.id, { ...sent, kind: "message" })
|
|
504
|
+
} catch (error) {
|
|
505
|
+
throw stoppedReading(error, key)
|
|
506
|
+
}
|
|
507
|
+
const toChild = this.#sent.get(child.id) ?? []
|
|
508
|
+
if (!toChild.some((message) => message.id === sent.id)) toChild.push(sent)
|
|
509
|
+
this.#sent.set(child.id, toChild)
|
|
510
|
+
|
|
511
|
+
return { runId: child.id, status, delivery: status === "queued" ? "first-step" : "next-step" }
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/** The latest child under `key` of this conversation's turns, this one's included. */
|
|
515
|
+
private async latestChildUnder(key: string): Promise<SubagentRunRecord | undefined> {
|
|
516
|
+
const [latest] = await this.session.children.inConversation({ spawnKey: key, limit: 1 })
|
|
517
|
+
return latest
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* The child paused on its question that a message under `key` would continue: the latest run of
|
|
522
|
+
* the latest thread under the key, or, past the continuations of it that failed or were stopped,
|
|
523
|
+
* the run they continued, so their failure does not hide the question. A later spawn under the
|
|
524
|
+
* key replaces it.
|
|
525
|
+
*/
|
|
526
|
+
private async pausedOnQuestion(key: string): Promise<SubagentRunRecord | undefined> {
|
|
527
|
+
const latest = await this.latestChildUnder(key)
|
|
528
|
+
if (!latest) return undefined
|
|
529
|
+
|
|
530
|
+
const runs = await this.session.children.threadRuns(latest.threadId)
|
|
531
|
+
const live = [...runs]
|
|
532
|
+
.reverse()
|
|
533
|
+
.find((run) => run.status !== "failed" && run.status !== "cancelled")
|
|
534
|
+
return live && isAwaitingAnswerRun(live) ? live : undefined
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/** Whether a continuation went on with its parent's answer, as its trigger says. */
|
|
538
|
+
private async continuesAfterAnswer(run: SubagentRunRecord): Promise<boolean> {
|
|
539
|
+
const trigger = await this.session.threads.message(run.triggerMessageId)
|
|
540
|
+
return trigger?.parts.some((part) => part.type === "mail" && part.kind === "answer") ?? false
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
private async subagentRun(id: string): Promise<SubagentRunRecord | undefined> {
|
|
544
|
+
const run = await this.session.children.get(id)
|
|
545
|
+
return run?.kind === "subagent" ? run : undefined
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* The children of this conversation still paused on their question, each with it: one indexed
|
|
550
|
+
* read, which finds none in a conversation that has none, then one per key that has some.
|
|
551
|
+
*/
|
|
552
|
+
async waitingQuestions(): Promise<readonly WaitedQuestion[]> {
|
|
553
|
+
const paused = await this.session.children.inConversation({ finishReason: "awaiting_answer" })
|
|
554
|
+
const waiting: WaitedQuestion[] = []
|
|
555
|
+
for (const key of new Set(paused.map((run) => run.spawnKey))) {
|
|
556
|
+
const child = await this.pausedOnQuestion(key)
|
|
557
|
+
const question = child ? await this.deferredQuestionOf(child) : undefined
|
|
558
|
+
if (child && question) waiting.push({ key, runId: child.id, ...question })
|
|
559
|
+
}
|
|
560
|
+
return waiting
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* Continue a child paused on its question, as a child of this turn under the same key, with this
|
|
565
|
+
* message as the answer it reads first. Admissions go one at a time, so a second answer in the
|
|
566
|
+
* same step finds the first one's continuation and is refused.
|
|
567
|
+
*/
|
|
568
|
+
private async answerPaused(
|
|
569
|
+
paused: SubagentRunRecord,
|
|
570
|
+
key: string,
|
|
571
|
+
sent: SentMessage,
|
|
572
|
+
signal: AbortSignal
|
|
573
|
+
): Promise<MessageSubagentOutput> {
|
|
574
|
+
const question = await this.deferredQuestionOf(paused)
|
|
575
|
+
if (!question) {
|
|
576
|
+
throw new Error(
|
|
577
|
+
`[SixbAgent] Subagent run '${paused.id}' paused on a question its thread does not hold.`
|
|
578
|
+
)
|
|
579
|
+
}
|
|
580
|
+
const answer: AgentMailPart = {
|
|
581
|
+
type: "mail",
|
|
582
|
+
id: sent.id,
|
|
583
|
+
from: "parent",
|
|
584
|
+
kind: "answer",
|
|
585
|
+
inReplyTo: question.id,
|
|
586
|
+
text: sent.text,
|
|
587
|
+
}
|
|
588
|
+
const runId = createSubagentRunId(this.parentRun.id, key)
|
|
589
|
+
const admitted = await this.admitInTurn(async () => {
|
|
590
|
+
if (await this.subagentRun(runId)) {
|
|
591
|
+
throw new AgentToolPublicError(
|
|
592
|
+
`[SixbAgent] '${key}' already continues with the answer you sent it this turn. Message it again once it is at work, or wait for it with wait_agent.`
|
|
593
|
+
)
|
|
594
|
+
}
|
|
595
|
+
await this.clearDeadAttempts(paused, signal)
|
|
596
|
+
const { spec, continuation } = this.continuationOf(paused, [answer])
|
|
597
|
+
return this.admit(runId, key, spec, signal, continuation)
|
|
598
|
+
})
|
|
599
|
+
|
|
600
|
+
const output: MessageSubagentOutput = {
|
|
601
|
+
runId: admitted.runId,
|
|
602
|
+
status: admitted.status === "queued" ? "queued" : "running",
|
|
603
|
+
delivery: "answer",
|
|
604
|
+
continues: paused.id,
|
|
605
|
+
}
|
|
606
|
+
this.#answers.set(sent.id, output)
|
|
607
|
+
return output
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* The question a child paused on, from its thread: the last message of the run that paused, its
|
|
612
|
+
* work since its last delivery. Only one `awaiting_answer` has one.
|
|
613
|
+
*/
|
|
614
|
+
private async deferredQuestionOf(run: SubagentRunRecord): Promise<QuestionRef | undefined> {
|
|
615
|
+
if (!isAwaitingAnswerRun(run)) return undefined
|
|
616
|
+
|
|
617
|
+
const { messages } = await this.session.threads.messages({
|
|
618
|
+
threadId: run.threadId,
|
|
619
|
+
order: "desc",
|
|
620
|
+
limit: 2,
|
|
621
|
+
})
|
|
622
|
+
const work = messages.find(
|
|
623
|
+
(message) => message.runId === run.id && message.role === "assistant"
|
|
624
|
+
)
|
|
625
|
+
return work ? deferredChildQuestion([work]) : undefined
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
/**
|
|
629
|
+
* The questions of the turn's children still at work that the model has not read, marked read:
|
|
630
|
+
* its answer would otherwise end the turn without them.
|
|
631
|
+
*/
|
|
632
|
+
async unreadQuestions(): Promise<readonly WaitedQuestion[]> {
|
|
633
|
+
const unread = (await this.askingChildren()).filter(
|
|
634
|
+
(question) => !this.#reported.has(question.id)
|
|
635
|
+
)
|
|
636
|
+
for (const question of unread) this.#reported.add(question.id)
|
|
637
|
+
return unread
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* Before the turn records its end, while it still runs: tell each child still waiting on its
|
|
642
|
+
* question that the turn ends without an answer, then wait for each to pause on it. The turn's end cancels the children still at work, so a child it told and that has not
|
|
643
|
+
* paused yet would be stopped; while the turn runs, the repair pass leaves its children alone.
|
|
644
|
+
*/
|
|
645
|
+
async deferOpenQuestions(signal: AbortSignal): Promise<void> {
|
|
646
|
+
let asking: readonly WaitedQuestion[]
|
|
647
|
+
try {
|
|
648
|
+
asking = await this.askingChildren()
|
|
649
|
+
} catch (error) {
|
|
650
|
+
console.error(
|
|
651
|
+
`[SixbAgent] Could not read the questions of Agent run '${this.parentRun.id}'; its children asking one are cancelled with the turn.`,
|
|
652
|
+
error
|
|
653
|
+
)
|
|
654
|
+
return
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
const deferred: string[] = []
|
|
658
|
+
for (const question of asking) {
|
|
659
|
+
try {
|
|
660
|
+
this.#family.send(question.runId, {
|
|
661
|
+
id: `${this.parentRun.id}:deferred:${question.id}`,
|
|
662
|
+
kind: "deferred",
|
|
663
|
+
inReplyTo: question.id,
|
|
664
|
+
text: "",
|
|
665
|
+
})
|
|
666
|
+
deferred.push(question.runId)
|
|
667
|
+
} catch (error) {
|
|
668
|
+
console.error(
|
|
669
|
+
`[SixbAgent] Could not tell subagent run '${question.runId}' that its question waits for a later turn; it is cancelled with the turn.`,
|
|
670
|
+
error
|
|
671
|
+
)
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
try {
|
|
676
|
+
while (deferred.length > 0) {
|
|
677
|
+
const paused = this.#family.changed()
|
|
678
|
+
const runs = await this.session.children.getMany(deferred)
|
|
679
|
+
if (runs.every((run) => run.status !== "queued" && run.status !== "running")) return
|
|
680
|
+
await delay(CHILD_WAIT_RECHECK_MS, signal, paused)
|
|
681
|
+
}
|
|
682
|
+
} catch (error) {
|
|
683
|
+
// The turn's interruption checks record why it stopped.
|
|
684
|
+
if (signal.aborted) return
|
|
685
|
+
throw error
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/**
|
|
690
|
+
* Wait until none of the turn's children is queued or running: a pausing turn's end cancels those
|
|
691
|
+
* still at work, and one that holds a call pauses by itself meanwhile.
|
|
692
|
+
*/
|
|
693
|
+
async settleChildren(signal: AbortSignal): Promise<void> {
|
|
694
|
+
for (;;) {
|
|
695
|
+
const finished = this.#family.changed()
|
|
696
|
+
if ((await this.session.children.activeCount()) === 0) return
|
|
697
|
+
|
|
698
|
+
try {
|
|
699
|
+
await delay(CHILD_WAIT_RECHECK_MS, signal, finished)
|
|
700
|
+
} catch (error) {
|
|
701
|
+
// The turn's interruption checks record why it stopped, with what it wrote.
|
|
702
|
+
if (signal.aborted) return
|
|
703
|
+
throw error
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/** The open questions of the turn's children still at work, each with the child's key. */
|
|
709
|
+
private async askingChildren(): Promise<readonly WaitedQuestion[]> {
|
|
710
|
+
const open = this.#family.questions()
|
|
711
|
+
if (open.length === 0) return []
|
|
712
|
+
|
|
713
|
+
const runs = await this.session.children.getMany(open.map((question) => question.runId))
|
|
714
|
+
const byId = new Map(runs.map((run) => [run.id, run]))
|
|
715
|
+
return open.flatMap((question: ChildQuestion) => {
|
|
716
|
+
const run = byId.get(question.runId)
|
|
717
|
+
if (run?.kind !== "subagent" || run.parentRunId !== this.parentRun.id) return []
|
|
718
|
+
if (run.status !== "running") return []
|
|
719
|
+
|
|
720
|
+
return [{ key: run.spawnKey, runId: run.id, id: question.id, text: question.text }]
|
|
721
|
+
})
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
async spawn(input: SpawnSubagentInput, signal: AbortSignal): Promise<SpawnSubagentOutput> {
|
|
725
|
+
signal.throwIfAborted()
|
|
726
|
+
const key = requireNonEmpty("spawn_agent", input.key, "key", 128)
|
|
727
|
+
const task = requireNonEmpty("spawn_agent", input.task, "task")
|
|
728
|
+
const model = this.resolveModel(input.model)
|
|
729
|
+
const reasoning = input.reasoning ?? model.defaultReasoning
|
|
730
|
+
const sources = input.files?.length
|
|
731
|
+
? await listHandedSources({ files: this.runFiles(), paths: input.files, signal })
|
|
732
|
+
: undefined
|
|
733
|
+
const runId = createSubagentRunId(this.parentRun.id, key)
|
|
734
|
+
const specWith = (files: readonly SubagentRunFile[] | undefined) =>
|
|
735
|
+
this.childSpec({ task, model, tier: model.tier, reasoning, files })
|
|
736
|
+
|
|
737
|
+
// One admission at a time: only this turn adds children to it, so admission's answer is known
|
|
738
|
+
// before any file is read, and a refused spawn reads and stores none.
|
|
739
|
+
return this.admitInTurn(async () => {
|
|
740
|
+
const existing = await this.admissionOf(runId, key)
|
|
741
|
+
if (existing) {
|
|
742
|
+
// The same child only if everything is the same, the files' bytes too.
|
|
743
|
+
const files =
|
|
744
|
+
sources && sameSpecBesidesFiles(existing.spec, specWith(undefined), sources)
|
|
745
|
+
? await handedFileRefs({ files: this.runFiles(), sources, signal })
|
|
746
|
+
: undefined
|
|
747
|
+
const spec = specWith(files)
|
|
748
|
+
if (!isDeepStrictEqual(existing.spec, spec)) throw duplicateKey(key)
|
|
749
|
+
return this.admit(runId, key, spec, signal)
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
const stored = sources
|
|
753
|
+
? await storeHandedFiles({ files: this.runFiles(), sources, signal })
|
|
754
|
+
: undefined
|
|
755
|
+
try {
|
|
756
|
+
return await this.admit(runId, key, specWith(stored?.files), signal)
|
|
757
|
+
} catch (error) {
|
|
758
|
+
// Nothing was admitted, so the files do not count against the run.
|
|
759
|
+
stored?.release()
|
|
760
|
+
throw error
|
|
761
|
+
}
|
|
762
|
+
})
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
private admitInTurn<T>(admission: () => Promise<T>): Promise<T> {
|
|
766
|
+
const admitted = this.#admissions.then(admission)
|
|
767
|
+
this.#admissions = admitted.catch(() => {})
|
|
768
|
+
return admitted
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
/**
|
|
772
|
+
* What admission will answer, read before the files the child is handed: the child already
|
|
773
|
+
* spawned with this key, else nothing once checked that the turn may spawn another.
|
|
774
|
+
*/
|
|
775
|
+
private async admissionOf(runId: string, key: string): Promise<SubagentRunRecord | null> {
|
|
776
|
+
const { children } = this.session
|
|
777
|
+
const maxActive = this.context.subagentConcurrencyPerRun
|
|
778
|
+
const [existing, parent] = await Promise.all([
|
|
779
|
+
children.get(runId),
|
|
780
|
+
children.get(this.parentRun.id),
|
|
781
|
+
])
|
|
782
|
+
if (existing) {
|
|
783
|
+
// A continuation works in the thread of the turn that spawned it, never this turn's.
|
|
784
|
+
if (
|
|
785
|
+
existing.kind === "subagent" &&
|
|
786
|
+
existing.threadId !== createSubagentThreadId(this.parentRun.id, key)
|
|
787
|
+
) {
|
|
788
|
+
const after = (await this.continuesAfterAnswer(existing)) ? "your answer" : "the approval"
|
|
789
|
+
throw new AgentToolPublicError(
|
|
790
|
+
isTerminalSubagent(existing)
|
|
791
|
+
? `[SixbAgent] '${key}' already continued after ${after}, and wait_agent returns how it ended. To run it again, spawn it with a new key.`
|
|
792
|
+
: `[SixbAgent] '${key}' is the sub-agent that continues after ${after}; wait for it with wait_agent.`
|
|
793
|
+
)
|
|
794
|
+
}
|
|
795
|
+
if (existing.kind === "subagent" && existing.parentRunId === this.parentRun.id) {
|
|
796
|
+
return existing
|
|
797
|
+
}
|
|
798
|
+
throw duplicateKey(key)
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
if (parent?.status !== "running") {
|
|
802
|
+
throw publicSpawnError(
|
|
803
|
+
new AgentStorageError("invalid_state", "Parent ended."),
|
|
804
|
+
key,
|
|
805
|
+
maxActive
|
|
806
|
+
)
|
|
807
|
+
}
|
|
808
|
+
if (parent.execution?.token !== requiredExecutionToken(this.parentRun)) {
|
|
809
|
+
throw new AgentExecutionLostError(parent.id)
|
|
810
|
+
}
|
|
811
|
+
if ((await children.activeCount()) >= maxActive) {
|
|
812
|
+
throw publicSpawnError(
|
|
813
|
+
new AgentStorageError("active_child_limit", "Active child limit."),
|
|
814
|
+
key,
|
|
815
|
+
maxActive
|
|
816
|
+
)
|
|
817
|
+
}
|
|
818
|
+
return null
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/**
|
|
822
|
+
* The run of this turn that continues `paused` in its thread: its model, task and files, this
|
|
823
|
+
* turn's mode, and a trigger of what it goes on with (the outcomes of its calls, or
|
|
824
|
+
* its parent's answer), what came back to its sandbox and when it continues.
|
|
825
|
+
*/
|
|
826
|
+
private continuationOf(
|
|
827
|
+
paused: SubagentRunRecord,
|
|
828
|
+
goesOnWith: readonly AgentMessagePart[]
|
|
829
|
+
): {
|
|
830
|
+
readonly spec: SubagentRunSpec
|
|
831
|
+
readonly continuation: Pick<AgentChildDraft, "thread" | "trigger" | "createdAt">
|
|
832
|
+
} {
|
|
833
|
+
const spec = this.childSpec({
|
|
834
|
+
task: paused.spec.task,
|
|
835
|
+
model: paused.spec.model,
|
|
836
|
+
tier: paused.spec.tier,
|
|
837
|
+
reasoning: paused.spec.reasoning,
|
|
838
|
+
files: paused.spec.files,
|
|
839
|
+
})
|
|
840
|
+
const createdAt = new Date()
|
|
841
|
+
const parts = continuationTrigger({
|
|
842
|
+
goesOnWith,
|
|
843
|
+
paused,
|
|
844
|
+
keepsWorkspace: this.context.keepsChildWorkspaces,
|
|
845
|
+
createdAt,
|
|
846
|
+
timeZone: spec.timeZone ?? this.context.timeZone,
|
|
847
|
+
})
|
|
848
|
+
return {
|
|
849
|
+
spec,
|
|
850
|
+
continuation: {
|
|
851
|
+
thread: { id: paused.threadId, create: false },
|
|
852
|
+
trigger: { id: createAgentMessageId(), parts },
|
|
853
|
+
createdAt,
|
|
854
|
+
},
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
/** A child asks no less than its turn, dates as its requester does, and ends with the turn. */
|
|
859
|
+
private childSpec(input: {
|
|
860
|
+
readonly task: string
|
|
861
|
+
readonly model: LanguageModelRef
|
|
862
|
+
readonly tier: LanguageModelTier | undefined
|
|
863
|
+
readonly reasoning: AgentReasoning | undefined
|
|
864
|
+
readonly files: readonly SubagentRunFile[] | undefined
|
|
865
|
+
}): SubagentRunSpec {
|
|
866
|
+
const { task, model, tier, reasoning, files } = input
|
|
867
|
+
const { approvalMode, timeZone, locale } = this.parentRun.spec ?? {}
|
|
868
|
+
return {
|
|
869
|
+
model: { provider: model.provider, modelId: model.modelId },
|
|
870
|
+
task,
|
|
871
|
+
toolNames: this.delegation.toolNames,
|
|
872
|
+
...(tier === undefined ? {} : { tier }),
|
|
873
|
+
...(reasoning === undefined ? {} : { reasoning }),
|
|
874
|
+
...(approvalMode === undefined ? {} : { approvalMode }),
|
|
875
|
+
...(timeZone === undefined ? {} : { timeZone }),
|
|
876
|
+
...(locale === undefined ? {} : { locale }),
|
|
877
|
+
...(files === undefined ? {} : { files }),
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
/**
|
|
882
|
+
* Admit a child of this turn. A spawned child works in a thread of its own, which starts with its
|
|
883
|
+
* task and its files; a continuation goes into its thread with the outcomes it continues with.
|
|
884
|
+
*/
|
|
885
|
+
private async admit(
|
|
886
|
+
runId: string,
|
|
887
|
+
key: string,
|
|
888
|
+
spec: SubagentRunSpec,
|
|
889
|
+
signal: AbortSignal,
|
|
890
|
+
continuation?: Pick<AgentChildDraft, "thread" | "trigger" | "createdAt">
|
|
891
|
+
): Promise<SpawnSubagentOutput> {
|
|
892
|
+
let run: SubagentRunRecord
|
|
893
|
+
try {
|
|
894
|
+
run = await this.session.children.spawn({
|
|
895
|
+
spawnKey: key,
|
|
896
|
+
spec,
|
|
897
|
+
...(continuation ?? {
|
|
898
|
+
thread: { create: true },
|
|
899
|
+
trigger: {
|
|
900
|
+
id: createAgentMessageId(),
|
|
901
|
+
parts: [
|
|
902
|
+
{ type: "text", text: spec.task },
|
|
903
|
+
...(spec.files === undefined
|
|
904
|
+
? []
|
|
905
|
+
: [{ type: "text" as const, text: renderHandedFiles(spec.files) }]),
|
|
906
|
+
],
|
|
907
|
+
},
|
|
908
|
+
}),
|
|
909
|
+
})
|
|
910
|
+
if (run.id !== runId) {
|
|
911
|
+
throw new Error(`[SixbAgent] Child '${key}' was admitted as '${run.id}', not '${runId}'.`)
|
|
912
|
+
}
|
|
913
|
+
} catch (error) {
|
|
914
|
+
throw publicSpawnError(error, key, this.context.subagentConcurrencyPerRun)
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
signal.throwIfAborted()
|
|
918
|
+
if (run.status === "queued") this.startChild(run, this.#family)
|
|
919
|
+
|
|
920
|
+
return {
|
|
921
|
+
runId: run.id,
|
|
922
|
+
status: run.status,
|
|
923
|
+
model: { provider: run.spec.model.provider, modelId: run.spec.model.modelId },
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
async wait(input: WaitForSubagentsInput, signal: AbortSignal): Promise<WaitForSubagentsOutput> {
|
|
928
|
+
const passedIds = normalizeRunIds(input.runIds, this.context.subagentConcurrencyPerRun)
|
|
929
|
+
// A child of an earlier turn is waited for as the child of this one that continues it, else
|
|
930
|
+
// as it ended.
|
|
931
|
+
const runIds = await Promise.all(passedIds.map((runId) => this.continuedChildId(runId)))
|
|
932
|
+
const earlierTurns = await this.earlierTurnsOf(runIds)
|
|
933
|
+
for (;;) {
|
|
934
|
+
signal.throwIfAborted()
|
|
935
|
+
// Taken before the reads, so a question or a finish that comes during them wakes the wait.
|
|
936
|
+
const changed = this.#family.changed()
|
|
937
|
+
const runs = await this.session.children.getMany(runIds)
|
|
938
|
+
const byId = new Map(runs.map((run) => [run.id, run]))
|
|
939
|
+
const children = runIds.map((runId, index) => {
|
|
940
|
+
const run = byId.get(runId)
|
|
941
|
+
if (
|
|
942
|
+
!run ||
|
|
943
|
+
run.kind !== "subagent" ||
|
|
944
|
+
(run.parentRunId !== this.parentRun.id && !earlierTurns.has(run.parentRunId))
|
|
945
|
+
) {
|
|
946
|
+
throw new AgentToolPublicError(
|
|
947
|
+
`[SixbAgent] '${passedIds[index]}' is not a child of the current Agent run.`
|
|
948
|
+
)
|
|
949
|
+
}
|
|
950
|
+
return run
|
|
951
|
+
})
|
|
952
|
+
// A child blocked on its question waits for this turn, so a new question ends any wait,
|
|
953
|
+
// and one already returned ends a wait for its own child.
|
|
954
|
+
const asking = await this.askingChildren()
|
|
955
|
+
const asked = asking.some(
|
|
956
|
+
(question) => !this.#reported.has(question.id) || runIds.includes(question.runId)
|
|
957
|
+
)
|
|
958
|
+
if (children.every(isTerminalSubagent) || asked) {
|
|
959
|
+
const awaiting = await this.session.children.awaitingApproval(runIds)
|
|
960
|
+
const delivered = await this.deliverFiles(children, signal)
|
|
961
|
+
const messages = await Promise.all(children.map((run) => this.messagesTo(run)))
|
|
962
|
+
// It lists the questions it returns first, and those its children wait on.
|
|
963
|
+
const listed = asking.filter(
|
|
964
|
+
(question) => !this.#reported.has(question.id) || runIds.includes(question.runId)
|
|
965
|
+
)
|
|
966
|
+
for (const question of asking) this.#reported.add(question.id)
|
|
967
|
+
const open = new Map(asking.map((question) => [question.runId, question]))
|
|
968
|
+
const questions = await Promise.all(
|
|
969
|
+
children.map(async (run) => open.get(run.id) ?? (await this.deferredQuestionOf(run)))
|
|
970
|
+
)
|
|
971
|
+
return {
|
|
972
|
+
// Each result keeps the id the Agent passed.
|
|
973
|
+
results: children.map((run, index) => ({
|
|
974
|
+
...waitedResult(
|
|
975
|
+
run,
|
|
976
|
+
awaiting.get(run.id),
|
|
977
|
+
delivered.byChild.get(run.id),
|
|
978
|
+
questions[index]
|
|
979
|
+
),
|
|
980
|
+
...messages[index],
|
|
981
|
+
runId: passedIds[index] ?? run.id,
|
|
982
|
+
})),
|
|
983
|
+
...(listed.length > 0 ? { questions: listed } : {}),
|
|
984
|
+
files: delivered.attached,
|
|
985
|
+
...(delivered.artifactsError === undefined
|
|
986
|
+
? {}
|
|
987
|
+
: { artifactsError: delivered.artifactsError }),
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
// A child of an earlier turn ends into that turn's mailbox, which this one does not hear.
|
|
991
|
+
const unheard = children.some(
|
|
992
|
+
(run) => run.parentRunId !== this.parentRun.id && !isTerminalSubagent(run)
|
|
993
|
+
)
|
|
994
|
+
const recheckMs = unheard ? OTHER_TURN_RECHECK_MS : CHILD_WAIT_RECHECK_MS
|
|
995
|
+
await delay(recheckMs, signal, changed)
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
/**
|
|
1000
|
+
* What became of what this turn sent an ended child, from its thread, which holds each message
|
|
1001
|
+
* it read: those it did not read, and, when one came as it answered, the answer it gave before.
|
|
1002
|
+
* A failed child's failure is what the parent acts on.
|
|
1003
|
+
*/
|
|
1004
|
+
private async messagesTo(run: SubagentRunRecord): Promise<MessagesReport> {
|
|
1005
|
+
const sent = this.#sent.get(run.id)
|
|
1006
|
+
if (!sent || !isTerminalSubagent(run) || run.status === "failed") return {}
|
|
1007
|
+
|
|
1008
|
+
const { messages } = await this.session.threads.messages({
|
|
1009
|
+
threadId: run.threadId,
|
|
1010
|
+
order: "asc",
|
|
1011
|
+
})
|
|
1012
|
+
const read = new Set(
|
|
1013
|
+
messages.flatMap((message) =>
|
|
1014
|
+
message.parts.flatMap((part) => (part.type === "mail" ? [part.id] : []))
|
|
1015
|
+
)
|
|
1016
|
+
)
|
|
1017
|
+
const unread = sent.filter((message) => !read.has(message.id))
|
|
1018
|
+
return {
|
|
1019
|
+
...(unread.length > 0 ? { unread } : {}),
|
|
1020
|
+
...answerBeforeLateMessage(
|
|
1021
|
+
messages.filter((message) => message.runId === run.id),
|
|
1022
|
+
run.result?.text ?? ""
|
|
1023
|
+
),
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
/**
|
|
1028
|
+
* The run a child of an earlier turn is waited for as: its thread's latest, the one that continues
|
|
1029
|
+
* it when this turn resumes its pause; else `runId` itself.
|
|
1030
|
+
*/
|
|
1031
|
+
private async continuedChildId(runId: string): Promise<string> {
|
|
1032
|
+
const { children } = this.session
|
|
1033
|
+
const waited = await children.get(runId)
|
|
1034
|
+
if (waited?.kind !== "subagent" || waited.parentRunId === this.parentRun.id) return runId
|
|
1035
|
+
|
|
1036
|
+
const latest = await children.threadRuns(waited.threadId)
|
|
1037
|
+
return latest.at(-1)?.id ?? runId
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
/** Which parents of these children are earlier turns of this turn's conversation. */
|
|
1041
|
+
private async earlierTurnsOf(runIds: readonly string[]): Promise<ReadonlySet<string>> {
|
|
1042
|
+
const children = await this.session.children.getMany(runIds)
|
|
1043
|
+
const parentIds = children.flatMap((run) =>
|
|
1044
|
+
run.kind === "subagent" && run.parentRunId !== this.parentRun.id ? [run.parentRunId] : []
|
|
1045
|
+
)
|
|
1046
|
+
if (parentIds.length === 0) return new Set()
|
|
1047
|
+
|
|
1048
|
+
const parents = await this.session.children.getMany(parentIds)
|
|
1049
|
+
return new Set(
|
|
1050
|
+
parents
|
|
1051
|
+
.filter(
|
|
1052
|
+
(parent) =>
|
|
1053
|
+
parent.kind === "conversation" &&
|
|
1054
|
+
parent.threadId === this.parentRun.threadId &&
|
|
1055
|
+
parent.createdAt <= this.parentRun.createdAt
|
|
1056
|
+
)
|
|
1057
|
+
.map((parent) => parent.id)
|
|
1058
|
+
)
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
/**
|
|
1062
|
+
* Copy what each finished child wrote under `out/` into the parent's sandbox, once, and install
|
|
1063
|
+
* what the children published in its `$SIXB_ARTIFACTS`, as the parent's own. A result holds at
|
|
1064
|
+
* most the attachment limits of new files, a child's whole or not at all; a child that does not
|
|
1065
|
+
* fit, or whose files cannot be copied, says so, and its files come with a later wait.
|
|
1066
|
+
*/
|
|
1067
|
+
private async deliverFiles(
|
|
1068
|
+
children: readonly SubagentRunRecord[],
|
|
1069
|
+
signal: AbortSignal
|
|
1070
|
+
): Promise<{
|
|
1071
|
+
readonly byChild: ReadonlyMap<string, ChildFiles>
|
|
1072
|
+
readonly attached: readonly InstalledChildFile[]
|
|
1073
|
+
readonly artifactsError?: string
|
|
1074
|
+
}> {
|
|
1075
|
+
const byChild = new Map<string, ChildFiles>()
|
|
1076
|
+
const attached: InstalledChildFile[] = []
|
|
1077
|
+
let attachedBytes = 0
|
|
1078
|
+
|
|
1079
|
+
for (const child of children) {
|
|
1080
|
+
if (child.status !== "succeeded") continue
|
|
1081
|
+
if (isAwaitingAnswerRun(child)) {
|
|
1082
|
+
if (child.result?.files?.length) {
|
|
1083
|
+
byChild.set(child.id, { note: "They come back once it continues and finishes." })
|
|
1084
|
+
}
|
|
1085
|
+
continue
|
|
1086
|
+
}
|
|
1087
|
+
if (isPausedSubagentRun(child)) {
|
|
1088
|
+
if (child.result?.files?.length) {
|
|
1089
|
+
byChild.set(child.id, {
|
|
1090
|
+
note: "They come back if it continues once the user decides, when it finishes.",
|
|
1091
|
+
})
|
|
1092
|
+
}
|
|
1093
|
+
continue
|
|
1094
|
+
}
|
|
1095
|
+
const { files: outputs = [], filesError } = child.result ?? {}
|
|
1096
|
+
if (filesError) byChild.set(child.id, { note: filesError })
|
|
1097
|
+
|
|
1098
|
+
const installed = this.#installed.get(child.id)
|
|
1099
|
+
if (installed) {
|
|
1100
|
+
byChild.set(child.id, { files: installed })
|
|
1101
|
+
continue
|
|
1102
|
+
}
|
|
1103
|
+
if (outputs.length === 0) continue
|
|
1104
|
+
|
|
1105
|
+
const bytes = outputs.reduce((sum, file) => sum + file.fileRef.sizeBytes, 0)
|
|
1106
|
+
const { maxFiles, totalMaxBytes } = SANDBOX_ATTACHMENT_LIMITS
|
|
1107
|
+
const fits =
|
|
1108
|
+
attached.length + outputs.length <= maxFiles && attachedBytes + bytes <= totalMaxBytes
|
|
1109
|
+
if (!fits && attached.length > 0) {
|
|
1110
|
+
byChild.set(child.id, {
|
|
1111
|
+
note: `Its ${outputs.length} files did not fit in this result, which holds at most ${maxFiles} files, ${formatBytes(totalMaxBytes)} in all. Wait for this child again to get them.`,
|
|
1112
|
+
})
|
|
1113
|
+
continue
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
try {
|
|
1117
|
+
const copied = await installChildOutputs({
|
|
1118
|
+
files: this.runFiles(),
|
|
1119
|
+
key: child.spawnKey,
|
|
1120
|
+
outputs,
|
|
1121
|
+
signal,
|
|
1122
|
+
})
|
|
1123
|
+
this.#installed.set(child.id, copied)
|
|
1124
|
+
attached.push(...copied)
|
|
1125
|
+
attachedBytes += bytes
|
|
1126
|
+
byChild.set(child.id, { files: copied })
|
|
1127
|
+
} catch (error) {
|
|
1128
|
+
if (signal.aborted) throw error
|
|
1129
|
+
byChild.set(child.id, {
|
|
1130
|
+
note: `Its files could not be copied into your sandbox (${errorMessage(error)}). Wait for this child again to retry.`,
|
|
1131
|
+
})
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
let artifactsError: string | undefined
|
|
1136
|
+
try {
|
|
1137
|
+
await this.#runFiles?.installArtifactsFrom(
|
|
1138
|
+
children.map((child) => child.id),
|
|
1139
|
+
signal
|
|
1140
|
+
)
|
|
1141
|
+
} catch (error) {
|
|
1142
|
+
if (signal.aborted) throw error
|
|
1143
|
+
artifactsError = `What these children published could not all be installed in $SIXB_ARTIFACTS (${errorMessage(error)}). The addresses in their answers still work.`
|
|
1144
|
+
}
|
|
1145
|
+
return { byChild, attached, ...(artifactsError === undefined ? {} : { artifactsError }) }
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
private runFiles(): AgentRunFiles {
|
|
1149
|
+
if (!this.#runFiles) {
|
|
1150
|
+
throw new Error("[SixbAgent] Delegation tools ran before their run's environment.")
|
|
1151
|
+
}
|
|
1152
|
+
return this.#runFiles
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
private resolveModel(
|
|
1156
|
+
ref: LanguageModelRef | LanguageModelTier | undefined
|
|
1157
|
+
): AgentRunDelegationModel {
|
|
1158
|
+
const { models, defaultModel } = this.models
|
|
1159
|
+
const byRef = (wanted: LanguageModelRef) => models.find((model) => sameModel(model, wanted))
|
|
1160
|
+
const projectDefault = () => {
|
|
1161
|
+
const model = byRef(defaultModel)
|
|
1162
|
+
if (!model)
|
|
1163
|
+
throw new Error("[SixbAgent] The project's default model is not among its models.")
|
|
1164
|
+
return model
|
|
1165
|
+
}
|
|
1166
|
+
if (ref === undefined) return projectDefault()
|
|
1167
|
+
// A tier's first model; a tier left out, or any tier of a list, gives the default.
|
|
1168
|
+
if (typeof ref === "string")
|
|
1169
|
+
return models.find((model) => model.tier === ref) ?? projectDefault()
|
|
1170
|
+
const model = byRef(ref)
|
|
1171
|
+
if (model) return model
|
|
1172
|
+
const available = models.map(formatModelRef).join(", ")
|
|
1173
|
+
throw new AgentToolPublicError(
|
|
1174
|
+
`[SixbAgent] Language model ${formatModelRef(ref)} is not configured for this project. ` +
|
|
1175
|
+
`Use one of: ${available}. Omit model to use the project default.`
|
|
1176
|
+
)
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
/**
|
|
1181
|
+
* Built from each model's configured definition, never from its provider catalog: the guide is in
|
|
1182
|
+
* every turn's tools, so it stays the same for the process and catalog I/O cannot fail a turn.
|
|
1183
|
+
*/
|
|
1184
|
+
export function renderSubagentModelGuide(models: AgentRunDelegation): string {
|
|
1185
|
+
const entries = models.models.map((entry) => {
|
|
1186
|
+
const metadata = defineLanguageModel(entry.definition)
|
|
1187
|
+
if (metadata.providerId !== entry.provider || metadata.modelId !== entry.modelId) {
|
|
1188
|
+
throw new Error(
|
|
1189
|
+
"[SixbAgent] Delegation model definition identity does not match its catalog entry."
|
|
1190
|
+
)
|
|
1191
|
+
}
|
|
1192
|
+
const details: string[] = []
|
|
1193
|
+
if (sameModel(entry, models.defaultModel)) details.push("default")
|
|
1194
|
+
if (metadata.contextWindow !== undefined)
|
|
1195
|
+
details.push(`context ${formatTokenCount(metadata.contextWindow)} tokens`)
|
|
1196
|
+
if (metadata.maxInputTokens !== undefined)
|
|
1197
|
+
details.push(`max input ${formatTokenCount(metadata.maxInputTokens)} tokens`)
|
|
1198
|
+
if (metadata.capabilities.reasoning) details.push("reasoning")
|
|
1199
|
+
if (metadata.capabilities.localTools) details.push("tools")
|
|
1200
|
+
const media = metadata.capabilities.inputMediaTypes
|
|
1201
|
+
if (media === "any") details.push("multimodal input")
|
|
1202
|
+
else if (media?.length) details.push(`input: ${media.join(", ")}`)
|
|
1203
|
+
if (details.length === 0 || (details.length === 1 && details[0] === "default"))
|
|
1204
|
+
details.push("metadata unavailable")
|
|
1205
|
+
|
|
1206
|
+
return renderModelLine({
|
|
1207
|
+
...(entry.tier === undefined ? {} : { tier: entry.tier }),
|
|
1208
|
+
reference: formatModelRef(entry),
|
|
1209
|
+
...(metadata.name === undefined ? {} : { name: metadata.name }),
|
|
1210
|
+
details: `(${details.join("; ")})`,
|
|
1211
|
+
...(metadata.description === undefined ? {} : { description: metadata.description }),
|
|
1212
|
+
})
|
|
1213
|
+
})
|
|
1214
|
+
|
|
1215
|
+
const { tiers } = models
|
|
1216
|
+
if (tiers.length === 0) {
|
|
1217
|
+
return ["Available models (provider-declared metadata when available):", ...entries].join("\n")
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
return [
|
|
1221
|
+
"Models you can delegate to:",
|
|
1222
|
+
...entries,
|
|
1223
|
+
"Tiers rank cost and strength: light is the cheapest and fastest, heavy the strongest.",
|
|
1224
|
+
`Use a tier by default (model: ${tiers.map((tier) => `"${tier}"`).join(" | ")}). Use a specific model when its description fits the task.`,
|
|
1225
|
+
].join("\n")
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
function modelChoice(models: AgentRunDelegation): typeof LISTED_MODEL_CHOICE {
|
|
1229
|
+
return models.tiers.length > 0 ? TIERED_MODEL_CHOICE : LISTED_MODEL_CHOICE
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
function formatModelRef({ provider, modelId }: LanguageModelRef): string {
|
|
1233
|
+
return JSON.stringify({ provider, modelId })
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
function sameModel(
|
|
1237
|
+
left: { readonly provider: string; readonly modelId: string },
|
|
1238
|
+
right: { readonly provider: string; readonly modelId: string }
|
|
1239
|
+
): boolean {
|
|
1240
|
+
return left.provider === right.provider && left.modelId === right.modelId
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
function formatTokenCount(value: number): string {
|
|
1244
|
+
if (value >= 1_000_000) return `${formatScaled(value, 1_000_000)}M`
|
|
1245
|
+
if (value >= 1_000) return `${formatScaled(value, 1_000)}k`
|
|
1246
|
+
return String(value)
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
function formatScaled(value: number, scale: number): string {
|
|
1250
|
+
return (Math.round((value / scale) * 100) / 100).toString()
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
function spawnInputSchema(models: AgentRunDelegation): JsonObject {
|
|
1254
|
+
return {
|
|
1255
|
+
type: "object",
|
|
1256
|
+
properties: {
|
|
1257
|
+
key: {
|
|
1258
|
+
type: "string",
|
|
1259
|
+
minLength: 1,
|
|
1260
|
+
maxLength: 128,
|
|
1261
|
+
description: "Stable key for this logical delegation, for example 'compare-suppliers'.",
|
|
1262
|
+
},
|
|
1263
|
+
task: { type: "string", minLength: 1, description: "Focused task for the child agent." },
|
|
1264
|
+
model: {
|
|
1265
|
+
description: `${modelChoice(models).field} Keep provider and modelId unchanged, including any '/' inside modelId. ${OMIT_MODEL}`,
|
|
1266
|
+
anyOf: [...tierChoice(models.tiers), ...modelRefChoices(models)],
|
|
1267
|
+
},
|
|
1268
|
+
reasoning: {
|
|
1269
|
+
anyOf: [
|
|
1270
|
+
{ type: "string", enum: [...AGENT_REASONING_LEVELS] },
|
|
1271
|
+
{
|
|
1272
|
+
type: "object",
|
|
1273
|
+
properties: { budgetTokens: { type: "integer", minimum: 0 } },
|
|
1274
|
+
required: ["budgetTokens"],
|
|
1275
|
+
additionalProperties: false,
|
|
1276
|
+
},
|
|
1277
|
+
],
|
|
1278
|
+
},
|
|
1279
|
+
files: {
|
|
1280
|
+
type: "array",
|
|
1281
|
+
minItems: 1,
|
|
1282
|
+
maxItems: SANDBOX_ATTACHMENT_LIMITS.maxFiles,
|
|
1283
|
+
uniqueItems: true,
|
|
1284
|
+
items: { type: "string", minLength: 1 },
|
|
1285
|
+
description:
|
|
1286
|
+
"Paths of files or directories in your sandbox, such as an attachment from $SIXB_ATTACHMENTS or out/chart.png.",
|
|
1287
|
+
},
|
|
1288
|
+
},
|
|
1289
|
+
required: ["key", "task"],
|
|
1290
|
+
additionalProperties: false,
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
function tierChoice(tiers: readonly LanguageModelTier[]): readonly JsonObject[] {
|
|
1295
|
+
return tiers.length > 0 ? [{ type: "string", enum: [...tiers] }] : []
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
// Keep each pair together: independent enums would also admit unconfigured bindings.
|
|
1299
|
+
function modelRefChoices(models: AgentRunDelegation): readonly JsonObject[] {
|
|
1300
|
+
return models.models.map(({ provider, modelId }) => ({
|
|
1301
|
+
type: "object",
|
|
1302
|
+
properties: {
|
|
1303
|
+
provider: { type: "string", enum: [provider] },
|
|
1304
|
+
modelId: { type: "string", enum: [modelId] },
|
|
1305
|
+
},
|
|
1306
|
+
required: ["provider", "modelId"],
|
|
1307
|
+
additionalProperties: false,
|
|
1308
|
+
}))
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
function messageInputSchema(): JsonObject {
|
|
1312
|
+
return {
|
|
1313
|
+
type: "object",
|
|
1314
|
+
properties: {
|
|
1315
|
+
key: {
|
|
1316
|
+
type: "string",
|
|
1317
|
+
minLength: 1,
|
|
1318
|
+
maxLength: 128,
|
|
1319
|
+
description: "The key you spawned the child with.",
|
|
1320
|
+
},
|
|
1321
|
+
text: {
|
|
1322
|
+
type: "string",
|
|
1323
|
+
minLength: 1,
|
|
1324
|
+
description: "What the child should change or know, as an instruction for its task.",
|
|
1325
|
+
},
|
|
1326
|
+
},
|
|
1327
|
+
required: ["key", "text"],
|
|
1328
|
+
additionalProperties: false,
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
function waitInputSchema(maxRunIds: number): JsonObject {
|
|
1333
|
+
return {
|
|
1334
|
+
type: "object",
|
|
1335
|
+
properties: {
|
|
1336
|
+
runIds: {
|
|
1337
|
+
type: "array",
|
|
1338
|
+
minItems: 1,
|
|
1339
|
+
maxItems: maxRunIds,
|
|
1340
|
+
uniqueItems: true,
|
|
1341
|
+
items: { type: "string", minLength: 1 },
|
|
1342
|
+
},
|
|
1343
|
+
},
|
|
1344
|
+
required: ["runIds"],
|
|
1345
|
+
additionalProperties: false,
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
function normalizeRunIds(value: readonly string[], maxRunIds: number): readonly string[] {
|
|
1350
|
+
if (!Array.isArray(value) || value.length < 1 || value.length > maxRunIds) {
|
|
1351
|
+
throw new AgentToolPublicError(
|
|
1352
|
+
`[SixbAgent] wait_agent requires between 1 and ${maxRunIds} child run ids.`
|
|
1353
|
+
)
|
|
1354
|
+
}
|
|
1355
|
+
const runIds = value.map((runId) => requireNonEmpty("wait_agent", runId, "runId"))
|
|
1356
|
+
if (new Set(runIds).size !== runIds.length) {
|
|
1357
|
+
throw new AgentToolPublicError("[SixbAgent] wait_agent run ids must be unique.")
|
|
1358
|
+
}
|
|
1359
|
+
return runIds
|
|
1360
|
+
}
|
|
1361
|
+
|
|
1362
|
+
function requireNonEmpty(
|
|
1363
|
+
toolName: "spawn_agent" | "wait_agent" | "message_agent",
|
|
1364
|
+
value: unknown,
|
|
1365
|
+
field: string,
|
|
1366
|
+
maxLength?: number
|
|
1367
|
+
): string {
|
|
1368
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
1369
|
+
throw new AgentToolPublicError(`[SixbAgent] ${toolName} ${field} must not be empty.`)
|
|
1370
|
+
}
|
|
1371
|
+
const normalized = value.trim()
|
|
1372
|
+
if (maxLength !== undefined && normalized.length > maxLength) {
|
|
1373
|
+
throw new AgentToolPublicError(
|
|
1374
|
+
`[SixbAgent] ${toolName} ${field} must not exceed ${maxLength} characters.`
|
|
1375
|
+
)
|
|
1376
|
+
}
|
|
1377
|
+
return normalized
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
function requiredExecutionToken(run: ConversationAgentRunRecord): string {
|
|
1381
|
+
if (!run.execution?.token) {
|
|
1382
|
+
throw new Error(`[SixbAgent] Parent Agent run '${run.id}' has no execution token.`)
|
|
1383
|
+
}
|
|
1384
|
+
return run.execution.token
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
function publicSpawnError(error: unknown, key: string, maxActive: number): unknown {
|
|
1388
|
+
if (!(error instanceof AgentStorageError)) return error
|
|
1389
|
+
switch (error.code) {
|
|
1390
|
+
case "active_child_limit":
|
|
1391
|
+
return new AgentToolPublicError(
|
|
1392
|
+
`[SixbAgent] The current Agent run already has ${maxActive} active children. Wait for one before spawning another.`
|
|
1393
|
+
)
|
|
1394
|
+
case "duplicate_id":
|
|
1395
|
+
return new AgentToolPublicError(
|
|
1396
|
+
`[SixbAgent] spawn_agent key '${key}' was already used with different inputs.`
|
|
1397
|
+
)
|
|
1398
|
+
case "invalid_state":
|
|
1399
|
+
return new AgentToolPublicError("[SixbAgent] The parent Agent run is no longer active.")
|
|
1400
|
+
default:
|
|
1401
|
+
return error
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
/**
|
|
1406
|
+
* When a message came as the child answered (`afterAnswer`), the answer it gave before: kept for
|
|
1407
|
+
* the parent beside the one it wrote after, which may only amend it. If it wrote none after, its
|
|
1408
|
+
* answer is the one before, and the parent is told it predates the message.
|
|
1409
|
+
*/
|
|
1410
|
+
function answerBeforeLateMessage(
|
|
1411
|
+
transcript: readonly AgentMessage[],
|
|
1412
|
+
answer: string
|
|
1413
|
+
): Pick<WaitedSubagentResult, "earlierAnswer" | "answerNote"> {
|
|
1414
|
+
const isLate = (message: AgentMessage) =>
|
|
1415
|
+
message.parts.some((part) => part.type === "mail" && part.afterAnswer === true)
|
|
1416
|
+
const late = transcript.map(isLate).lastIndexOf(true)
|
|
1417
|
+
const before = late > 0 ? transcript[late - 1] : undefined
|
|
1418
|
+
if (before?.role !== "assistant") return {}
|
|
1419
|
+
|
|
1420
|
+
const earlier = answerOfSteps(before.parts)
|
|
1421
|
+
if (!earlier) return {}
|
|
1422
|
+
return earlier === answer
|
|
1423
|
+
? {
|
|
1424
|
+
answerNote:
|
|
1425
|
+
"It wrote this answer before your last message came, and did not answer again after reading it.",
|
|
1426
|
+
}
|
|
1427
|
+
: { earlierAnswer: earlier }
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
/** The text written after the last local tool call of these steps, as a child's answer is. */
|
|
1431
|
+
function answerOfSteps(parts: readonly AgentMessagePart[]): string {
|
|
1432
|
+
const steps: AgentMessagePart[][] = []
|
|
1433
|
+
for (const part of parts) {
|
|
1434
|
+
if (part.type === "step-start" || steps.length === 0) steps.push([])
|
|
1435
|
+
if (part.type !== "step-start") steps.at(-1)?.push(part)
|
|
1436
|
+
}
|
|
1437
|
+
const ranTools = steps.map((step) =>
|
|
1438
|
+
step.some((part) => part.type === "tool-call" && part.providerExecuted !== true)
|
|
1439
|
+
)
|
|
1440
|
+
return steps
|
|
1441
|
+
.slice(ranTools.lastIndexOf(true) + 1)
|
|
1442
|
+
.flat()
|
|
1443
|
+
.flatMap((part) => (part.type === "text" ? [part.text] : []))
|
|
1444
|
+
.join("\n")
|
|
1445
|
+
.trim()
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
function isTerminalSubagent(
|
|
1449
|
+
run: SubagentRunRecord
|
|
1450
|
+
): run is SubagentRunRecord & { readonly status: "succeeded" | "failed" | "cancelled" } {
|
|
1451
|
+
return run.status !== "queued" && run.status !== "running"
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
interface ChildFiles {
|
|
1455
|
+
readonly files?: readonly InstalledChildFile[]
|
|
1456
|
+
readonly note?: string
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
function waitedResult(
|
|
1460
|
+
run: SubagentRunRecord,
|
|
1461
|
+
awaitingApproval: readonly AgentChildApprovalAwaiting[] | undefined,
|
|
1462
|
+
files: ChildFiles | undefined,
|
|
1463
|
+
question: QuestionRef | undefined
|
|
1464
|
+
): WaitedSubagentResult {
|
|
1465
|
+
return {
|
|
1466
|
+
runId: run.id,
|
|
1467
|
+
status: isPausedSubagentRun(run)
|
|
1468
|
+
? "awaiting_approval"
|
|
1469
|
+
: isAwaitingAnswerRun(run)
|
|
1470
|
+
? "awaiting_answer"
|
|
1471
|
+
: run.status,
|
|
1472
|
+
...(run.result?.text ? { text: run.result.text } : {}),
|
|
1473
|
+
...(question === undefined ? {} : { question: { id: question.id, text: question.text } }),
|
|
1474
|
+
...(run.error === undefined
|
|
1475
|
+
? {}
|
|
1476
|
+
: { error: { code: run.error.code, message: run.error.message } }),
|
|
1477
|
+
...(awaitingApproval?.length ? { awaitingApproval } : {}),
|
|
1478
|
+
...(files?.files?.length
|
|
1479
|
+
? {
|
|
1480
|
+
files: files.files.map(({ path, sandboxPath, fileRef }) => ({
|
|
1481
|
+
path,
|
|
1482
|
+
sandboxPath,
|
|
1483
|
+
sizeBytes: fileRef.sizeBytes,
|
|
1484
|
+
...(fileRef.mediaType === undefined ? {} : { mediaType: fileRef.mediaType }),
|
|
1485
|
+
})),
|
|
1486
|
+
}
|
|
1487
|
+
: {}),
|
|
1488
|
+
...(files?.note === undefined ? {} : { filesNote: files.note }),
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
/** Whether a spawn under a key in use may be its replay, before reading its files' bytes. */
|
|
1493
|
+
function sameSpecBesidesFiles(
|
|
1494
|
+
existing: SubagentRunSpec,
|
|
1495
|
+
spec: SubagentRunSpec,
|
|
1496
|
+
sources: readonly { readonly path: string; readonly sizeBytes?: number }[]
|
|
1497
|
+
): boolean {
|
|
1498
|
+
const { files: existingFiles = [], ...existingRest } = existing
|
|
1499
|
+
const { files: _files, ...rest } = spec
|
|
1500
|
+
return (
|
|
1501
|
+
isDeepStrictEqual(existingRest, rest) &&
|
|
1502
|
+
existingFiles.length === sources.length &&
|
|
1503
|
+
existingFiles.every(
|
|
1504
|
+
(file, index) =>
|
|
1505
|
+
file.path === sources[index]?.path &&
|
|
1506
|
+
(sources[index]?.sizeBytes ?? file.fileRef.sizeBytes) === file.fileRef.sizeBytes
|
|
1507
|
+
)
|
|
1508
|
+
)
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
function duplicateKey(key: string): AgentToolPublicError {
|
|
1512
|
+
return new AgentToolPublicError(
|
|
1513
|
+
`[SixbAgent] spawn_agent key '${key}' was already used with different inputs.`
|
|
1514
|
+
)
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
function errorMessage(error: unknown): string {
|
|
1518
|
+
return (error instanceof Error ? error.message : String(error)).replace(/^\[\w+\] /, "")
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
function parseSpawnInput(value: unknown): SpawnSubagentInput {
|
|
1522
|
+
if (
|
|
1523
|
+
!isJsonObject(value) ||
|
|
1524
|
+
Object.keys(value).some((key) => !["key", "task", "model", "reasoning", "files"].includes(key))
|
|
1525
|
+
) {
|
|
1526
|
+
throw new AgentToolPublicError(
|
|
1527
|
+
"[SixbAgent] spawn_agent expects key, task, and optional model/reasoning/files."
|
|
1528
|
+
)
|
|
1529
|
+
}
|
|
1530
|
+
const key = requireNonEmpty("spawn_agent", value.key, "key", 128)
|
|
1531
|
+
const task = requireNonEmpty("spawn_agent", value.task, "task")
|
|
1532
|
+
let model: LanguageModelRef | LanguageModelTier | undefined
|
|
1533
|
+
if (typeof value.model === "string") {
|
|
1534
|
+
if (!isLanguageModelTier(value.model)) {
|
|
1535
|
+
throw new AgentToolPublicError(
|
|
1536
|
+
`[SixbAgent] Unknown spawn_agent model tier '${value.model}'. Use ${formatLanguageModelTiers()}, or a model reference.`
|
|
1537
|
+
)
|
|
1538
|
+
}
|
|
1539
|
+
model = value.model
|
|
1540
|
+
} else if (value.model !== undefined) {
|
|
1541
|
+
if (
|
|
1542
|
+
!isJsonObject(value.model) ||
|
|
1543
|
+
Object.keys(value.model).some((key) => !["provider", "modelId"].includes(key))
|
|
1544
|
+
) {
|
|
1545
|
+
throw new AgentToolPublicError("[SixbAgent] spawn_agent model requires provider and modelId.")
|
|
1546
|
+
}
|
|
1547
|
+
model = {
|
|
1548
|
+
provider: requireNonEmpty("spawn_agent", value.model.provider, "model.provider"),
|
|
1549
|
+
modelId: requireNonEmpty("spawn_agent", value.model.modelId, "model.modelId"),
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
if (value.reasoning !== undefined && !isModelReasoning(value.reasoning)) {
|
|
1553
|
+
throw new AgentToolPublicError("[SixbAgent] spawn_agent reasoning is invalid.")
|
|
1554
|
+
}
|
|
1555
|
+
const files = parseSpawnFiles(value.files)
|
|
1556
|
+
return {
|
|
1557
|
+
key,
|
|
1558
|
+
task,
|
|
1559
|
+
...(model === undefined ? {} : { model }),
|
|
1560
|
+
...(value.reasoning === undefined ? {} : { reasoning: value.reasoning }),
|
|
1561
|
+
...(files === undefined ? {} : { files }),
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
function parseSpawnFiles(value: unknown): readonly string[] | undefined {
|
|
1566
|
+
if (value === undefined) return undefined
|
|
1567
|
+
|
|
1568
|
+
const { maxFiles } = SANDBOX_ATTACHMENT_LIMITS
|
|
1569
|
+
if (!Array.isArray(value) || value.length > maxFiles) {
|
|
1570
|
+
throw new AgentToolPublicError(
|
|
1571
|
+
`[SixbAgent] spawn_agent files must be a list of at most ${maxFiles} sandbox paths.`
|
|
1572
|
+
)
|
|
1573
|
+
}
|
|
1574
|
+
const files = value.map((path) => requireNonEmpty("spawn_agent", path, "files entry"))
|
|
1575
|
+
if (new Set(files).size !== files.length) {
|
|
1576
|
+
throw new AgentToolPublicError("[SixbAgent] spawn_agent files must not repeat a path.")
|
|
1577
|
+
}
|
|
1578
|
+
return files.length > 0 ? files : undefined
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
function parseMessageInput(value: unknown): MessageSubagentInput {
|
|
1582
|
+
if (!isJsonObject(value) || Object.keys(value).some((key) => key !== "key" && key !== "text")) {
|
|
1583
|
+
throw new AgentToolPublicError("[SixbAgent] message_agent expects key and text.")
|
|
1584
|
+
}
|
|
1585
|
+
return {
|
|
1586
|
+
key: requireNonEmpty("message_agent", value.key, "key", 128),
|
|
1587
|
+
text: requireNonEmpty("message_agent", value.text, "text"),
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
function parseWaitInput(value: unknown, maxRunIds: number): WaitForSubagentsInput {
|
|
1592
|
+
if (
|
|
1593
|
+
!isJsonObject(value) ||
|
|
1594
|
+
Object.keys(value).some((key) => key !== "runIds") ||
|
|
1595
|
+
!Array.isArray(value.runIds) ||
|
|
1596
|
+
!value.runIds.every((id) => typeof id === "string")
|
|
1597
|
+
) {
|
|
1598
|
+
throw new AgentToolPublicError("[SixbAgent] wait_agent expects an array of child run ids.")
|
|
1599
|
+
}
|
|
1600
|
+
return { runIds: normalizeRunIds(value.runIds, maxRunIds) }
|
|
1601
|
+
}
|
|
1602
|
+
|
|
1603
|
+
/** A child that stopped reading as the turn sent to it: it paused or ended just then. */
|
|
1604
|
+
function stoppedReading(error: unknown, key: string): unknown {
|
|
1605
|
+
if (!(error instanceof ChildMailClosedError)) return error
|
|
1606
|
+
return new AgentToolPublicError(
|
|
1607
|
+
`[SixbAgent] '${key}' stopped as you sent this, so it will not read it: it paused or ended. Wait for it with wait_agent to see which.`
|
|
1608
|
+
)
|
|
1609
|
+
}
|