@sixb/agent 0.0.0-stage → 0.2.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 +126 -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 +109 -0
- package/dist/attachments.d.ts.map +1 -0
- package/dist/child-files.d.ts +91 -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 +74 -0
- package/dist/computer-runner.d.ts.map +1 -0
- package/dist/context-budget.d.ts +34 -0
- package/dist/context-budget.d.ts.map +1 -0
- package/dist/context-compaction.d.ts +148 -0
- package/dist/context-compaction.d.ts.map +1 -0
- package/dist/context-guard.d.ts +69 -0
- package/dist/context-guard.d.ts.map +1 -0
- package/dist/conversation-memory.d.ts +21 -0
- package/dist/conversation-memory.d.ts.map +1 -0
- package/dist/conversation-messages.d.ts +33 -0
- package/dist/conversation-messages.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 +38 -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 +14387 -0
- package/dist/index.js.map +72 -0
- package/dist/inline-images.d.ts +28 -0
- package/dist/inline-images.d.ts.map +1 -0
- package/dist/message-authors.d.ts +34 -0
- package/dist/message-authors.d.ts.map +1 -0
- package/dist/message-times.d.ts +9 -0
- package/dist/message-times.d.ts.map +1 -0
- package/dist/model-adapters.d.ts +59 -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/prompt-cache.d.ts +28 -0
- package/dist/prompt-cache.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 +93 -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 +145 -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-files-lock.d.ts +16 -0
- package/dist/run-files-lock.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 +65 -0
- package/dist/run-subagent.d.ts.map +1 -0
- package/dist/run-workflow-agent-node.d.ts +46 -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-context.d.ts +50 -0
- package/dist/subagent-context.d.ts.map +1 -0
- package/dist/subagent-continuation.d.ts +33 -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 +293 -0
- package/dist/subagent-tools.d.ts.map +1 -0
- package/dist/thread-context.d.ts +17 -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 +68 -0
- package/dist/tools/bash.d.ts.map +1 -0
- package/dist/tools/model-spec.d.ts +9 -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 +65 -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/tool-outputs.d.ts +63 -0
- package/dist/tools/tool-outputs.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 +83 -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 +860 -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 +1041 -0
- package/src/child-files.ts +535 -0
- package/src/child-questions.ts +42 -0
- package/src/computer-runner.ts +336 -0
- package/src/context-budget.ts +177 -0
- package/src/context-compaction.ts +1349 -0
- package/src/context-guard.ts +826 -0
- package/src/conversation-memory.ts +45 -0
- package/src/conversation-messages.ts +86 -0
- package/src/errors.ts +85 -0
- package/src/execution-plan.ts +70 -0
- package/src/failure.ts +82 -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/inline-images.ts +69 -0
- package/src/message-authors.ts +77 -0
- package/src/message-times.ts +24 -0
- package/src/model-adapters.ts +273 -0
- package/src/model-lines.ts +28 -0
- package/src/prompt-cache.ts +40 -0
- package/src/requester.ts +21 -0
- package/src/run-agent-turn.ts +509 -0
- package/src/run-child.ts +344 -0
- package/src/run-conversation-turn.ts +272 -0
- package/src/run-credential.ts +55 -0
- package/src/run-environment.ts +1216 -0
- package/src/run-fate.ts +51 -0
- package/src/run-files-lock.ts +118 -0
- package/src/run-sandbox.ts +63 -0
- package/src/run-subagent.ts +433 -0
- package/src/run-workflow-agent-node.ts +344 -0
- package/src/sandbox-api-context.ts +237 -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-context.ts +182 -0
- package/src/subagent-continuation.ts +56 -0
- package/src/subagent-inbox.ts +101 -0
- package/src/subagent-tools.ts +1671 -0
- package/src/thread-context.ts +31 -0
- package/src/tools/attachments.ts +28 -0
- package/src/tools/bash.ts +233 -0
- package/src/tools/model-spec.ts +27 -0
- package/src/tools/read.ts +262 -0
- package/src/tools/result-media.ts +351 -0
- package/src/tools/result-output.ts +46 -0
- package/src/tools/tool-files.ts +204 -0
- package/src/tools/tool-outputs.ts +464 -0
- package/src/tools/view-file.ts +155 -0
- package/src/turn-runtime.ts +33 -0
- package/src/types.ts +91 -0
- package/src/workflow-input-attachments.ts +140 -0
|
@@ -0,0 +1,1216 @@
|
|
|
1
|
+
import { posix } from "node:path"
|
|
2
|
+
import type { Principal } from "@sixb/core"
|
|
3
|
+
import {
|
|
4
|
+
type AgentContextBudget,
|
|
5
|
+
type AgentRunArtifacts,
|
|
6
|
+
type AgentRunSession,
|
|
7
|
+
type AgentSystemPromptSize,
|
|
8
|
+
type AgentToolCallFile,
|
|
9
|
+
type AgentTurnHistory,
|
|
10
|
+
conversationThreadId,
|
|
11
|
+
subagentSandboxFiles,
|
|
12
|
+
} from "@sixb/core/internal/agents"
|
|
13
|
+
import type { RenderedOntologyDocs } from "@sixb/core/internal/ontology"
|
|
14
|
+
import type { WorkflowIOSnapshot } from "@sixb/core/internal/workflows"
|
|
15
|
+
import type { ModelTool } from "@sixb/core/models"
|
|
16
|
+
import type {
|
|
17
|
+
AgentContextCheckpointReason,
|
|
18
|
+
AgentMessageRecord,
|
|
19
|
+
AgentThreadRecord,
|
|
20
|
+
ConversationAgentRunRecord,
|
|
21
|
+
SubagentRunRecord,
|
|
22
|
+
WorkflowAgentNodeRunRecord,
|
|
23
|
+
} from "@sixb/core/storage"
|
|
24
|
+
import { NEVER_ABORTED_SIGNAL, waitForAbort } from "./abort"
|
|
25
|
+
import {
|
|
26
|
+
type AgentExecutionMode,
|
|
27
|
+
measureAgentSystemPrompt,
|
|
28
|
+
renderCurrentTime,
|
|
29
|
+
sentSettings,
|
|
30
|
+
} from "./agent-prompt"
|
|
31
|
+
import { assertAgentRuntimeProfile } from "./agent-runtime/preflight"
|
|
32
|
+
import {
|
|
33
|
+
type InstalledArtifacts,
|
|
34
|
+
installArtifactsPublishedBy,
|
|
35
|
+
type MaterializedArtifacts,
|
|
36
|
+
materializeThreadArtifacts,
|
|
37
|
+
} from "./artifacts/materialize"
|
|
38
|
+
import { createPublishArtifactTools } from "./artifacts/publish-tool"
|
|
39
|
+
import {
|
|
40
|
+
modelSupportsInlineImages,
|
|
41
|
+
type PreparedAgentAttachmentContext,
|
|
42
|
+
prepareAgentAttachments,
|
|
43
|
+
} from "./attachments"
|
|
44
|
+
import { prepareHandedFiles } from "./child-files"
|
|
45
|
+
import {
|
|
46
|
+
type AgentThreadCompactionInput,
|
|
47
|
+
type BuildConversationRequest,
|
|
48
|
+
type ConversationRequest,
|
|
49
|
+
compactAgentConversationInTurn,
|
|
50
|
+
compactAgentThreadInRun,
|
|
51
|
+
contextEstimateTools,
|
|
52
|
+
type LoadConversationMemory,
|
|
53
|
+
prepareAgentConversationContext,
|
|
54
|
+
} from "./context-compaction"
|
|
55
|
+
import { type ConversationMemory, loadConversationMemory } from "./conversation-memory"
|
|
56
|
+
import { conversationModelMessages } from "./conversation-messages"
|
|
57
|
+
import { isLostExecution } from "./errors"
|
|
58
|
+
import type { ResolvedAgentExecutionPlan } from "./execution-plan"
|
|
59
|
+
import { InlineImageBudget } from "./inline-images"
|
|
60
|
+
import { type ConversationReaders, conversationAuthors } from "./message-authors"
|
|
61
|
+
import { type AgentErrorDetails, type AgentToolCaller, projectModelTools } from "./model-adapters"
|
|
62
|
+
import type { AcquiredRunSandbox, BeforeFinalizeOptions, RunSandbox } from "./run-sandbox"
|
|
63
|
+
import {
|
|
64
|
+
AGENT_ARTIFACTS_DIRECTORY,
|
|
65
|
+
AGENT_ARTIFACTS_MANIFEST,
|
|
66
|
+
type PrepareAgentSandboxApiContextInput,
|
|
67
|
+
prepareAgentSandboxApiContext,
|
|
68
|
+
} from "./sandbox-api-context"
|
|
69
|
+
import { AgentSandboxFileRegistry } from "./sandbox-file-registry"
|
|
70
|
+
import type { AgentSandboxHandle } from "./sandbox-handle"
|
|
71
|
+
import { MEMORY_SKILL } from "./skills/built-in"
|
|
72
|
+
import {
|
|
73
|
+
preflightSubagentContext,
|
|
74
|
+
type SubagentThreadContext,
|
|
75
|
+
subagentModelMessages,
|
|
76
|
+
subagentPromptCaching,
|
|
77
|
+
subagentThreadContext,
|
|
78
|
+
} from "./subagent-context"
|
|
79
|
+
import type { SubagentHistory } from "./subagent-continuation"
|
|
80
|
+
import { agentThreadModelContext, type LoadedAgentThreadModelContext } from "./thread-context"
|
|
81
|
+
import { createBashTool } from "./tools/bash"
|
|
82
|
+
import { agentModelToolSpecs } from "./tools/model-spec"
|
|
83
|
+
import { createReadTool } from "./tools/read"
|
|
84
|
+
import {
|
|
85
|
+
AgentToolResultMediaBridge,
|
|
86
|
+
allocateInlineImages,
|
|
87
|
+
replayToolFiles,
|
|
88
|
+
type SuppliesToolFiles,
|
|
89
|
+
} from "./tools/result-media"
|
|
90
|
+
import { AgentFileBudget, createAgentToolFiles, installAgentToolFiles } from "./tools/tool-files"
|
|
91
|
+
import {
|
|
92
|
+
restoreSavedToolOutputs,
|
|
93
|
+
savedToolOutputFiles,
|
|
94
|
+
ToolOutputFiles,
|
|
95
|
+
} from "./tools/tool-outputs"
|
|
96
|
+
import { createViewFileTool, VIEW_FILE_TOOL_SPEC } from "./tools/view-file"
|
|
97
|
+
import type { AgentTurnRuntime } from "./turn-runtime"
|
|
98
|
+
import type { AgentExecutionContext, AgentRunFiles, AgentTurnContext } from "./types"
|
|
99
|
+
import { prepareWorkflowInputAttachments } from "./workflow-input-attachments"
|
|
100
|
+
|
|
101
|
+
export interface AgentExecutionEnvironment {
|
|
102
|
+
readonly turnContext: AgentTurnContext
|
|
103
|
+
/** The run's sandbox and file budget, for the files a parent and its children hand each other. */
|
|
104
|
+
readonly runFiles: AgentRunFiles
|
|
105
|
+
/** Confirm preservation before recording success, cancellation or failure. Idempotent. */
|
|
106
|
+
beforeFinalize(options?: BeforeFinalizeOptions): Promise<void>
|
|
107
|
+
dispose(): Promise<void>
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export interface ConversationAgentExecutionEnvironment extends AgentExecutionEnvironment {
|
|
111
|
+
/** The history the turn runs on: as it started, or as its compaction left it. */
|
|
112
|
+
readonly threadContext: LoadedAgentThreadModelContext
|
|
113
|
+
/**
|
|
114
|
+
* Compact the history before the turn from within it, once: the request the turn's calls then
|
|
115
|
+
* start with. Undefined when it could not. Only a turn whose environment ran its preflight has
|
|
116
|
+
* it.
|
|
117
|
+
*/
|
|
118
|
+
readonly compactInTurn?: (input: {
|
|
119
|
+
readonly reason: AgentContextCheckpointReason
|
|
120
|
+
}) => Promise<ConversationRequest | undefined>
|
|
121
|
+
/** The bytes per token the preflight measured the history at, which the turn's calls go by. */
|
|
122
|
+
readonly bytesPerToken?: number
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* How a runner gives a run its environment: a cloud sandbox, or a folder on a computer. The runner
|
|
127
|
+
* closes over whatever it opens it from (a factory, the thread's recipe, the run's credentials).
|
|
128
|
+
*/
|
|
129
|
+
export type OpenRunSandbox = (lifecycle: {
|
|
130
|
+
/** Stops provisioning: cancellation, lost ownership, or shutdown. */
|
|
131
|
+
readonly signal: AbortSignal
|
|
132
|
+
/** Ends the run when its environment can no longer serve it, such as lost source credentials. */
|
|
133
|
+
readonly onFailure: (error: Error) => void
|
|
134
|
+
}) => Promise<OpenedRunSandbox>
|
|
135
|
+
|
|
136
|
+
export interface OpenedRunSandbox {
|
|
137
|
+
readonly sandbox: RunSandbox
|
|
138
|
+
/** The workspace the run's paused attempt left: it holds that attempt's files already. */
|
|
139
|
+
readonly resumed?: boolean
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
interface CreateAgentEnvironmentInput {
|
|
143
|
+
readonly context: AgentExecutionContext
|
|
144
|
+
readonly plan: ResolvedAgentExecutionPlan
|
|
145
|
+
/** The run's environment, opened by its runner. */
|
|
146
|
+
readonly openSandbox: OpenRunSandbox
|
|
147
|
+
readonly signal?: AbortSignal
|
|
148
|
+
/**
|
|
149
|
+
* Sink for a sandbox teardown that outlives dispose() (the model answered before the boot
|
|
150
|
+
* finished, so dispose returns without stalling on it). The worker registers these so a graceful
|
|
151
|
+
* stop() can drain them instead of leaving orphaned machines being torn down.
|
|
152
|
+
*/
|
|
153
|
+
readonly onDetachedTeardown?: (teardown: Promise<void>) => void
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export interface CreateConversationAgentEnvironmentInput extends CreateAgentEnvironmentInput {
|
|
157
|
+
/** The turn's session: its workspace, conversation and checkpoint go through it. */
|
|
158
|
+
readonly session: AgentRunSession
|
|
159
|
+
readonly thread?: AgentThreadRecord | null
|
|
160
|
+
/** Who asked for the turn: what it publishes is theirs, in an artifact the thread's owner owns. */
|
|
161
|
+
readonly requestedBy?: Principal
|
|
162
|
+
/** Who can read the thread now: in a shared one, who wrote what counts toward the estimate. */
|
|
163
|
+
readonly conversation?: ConversationReaders
|
|
164
|
+
/** Others were added to the thread, so it reaches the project's memory alone. */
|
|
165
|
+
readonly shared?: boolean
|
|
166
|
+
/** Run preflight only after current sandbox access has been resolved. */
|
|
167
|
+
readonly preflight?: { readonly budget: AgentContextBudget; readonly runtime: AgentTurnRuntime }
|
|
168
|
+
readonly run: ConversationAgentRunRecord
|
|
169
|
+
/** The conversation's history as the turn started (`AgentTurnContext.history`). */
|
|
170
|
+
readonly history: AgentTurnHistory
|
|
171
|
+
/** Framework-owned tools of the conversational Agent: delegation. */
|
|
172
|
+
readonly frameworkTools?: readonly ModelTool[]
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export interface CreateSubagentEnvironmentInput extends CreateAgentEnvironmentInput {
|
|
176
|
+
/** The child's session: its workspace goes through it. */
|
|
177
|
+
readonly session: AgentRunSession
|
|
178
|
+
readonly run: SubagentRunRecord
|
|
179
|
+
/** The child's own thread: memory is read as of its creation. */
|
|
180
|
+
readonly thread: AgentThreadRecord
|
|
181
|
+
/** The conversation: what the child publishes lands there. Absent, it publishes nothing. */
|
|
182
|
+
readonly conversation?: AgentThreadRecord | null
|
|
183
|
+
/** Who asked for the parent turn: what the child publishes is theirs. */
|
|
184
|
+
readonly requestedBy?: Principal
|
|
185
|
+
/** Its thread's messages, whose files are projected again, and the paused run it continues. */
|
|
186
|
+
readonly history: SubagentHistory
|
|
187
|
+
/** Framework-owned tools of a child: `ask_parent`. */
|
|
188
|
+
readonly frameworkTools?: readonly ModelTool[]
|
|
189
|
+
/** Weigh the thread before the first call, and compact it on the child's thread when needed. */
|
|
190
|
+
readonly preflight?: { readonly budget: AgentContextBudget; readonly runtime: AgentTurnRuntime }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export interface SubagentAgentExecutionEnvironment extends AgentExecutionEnvironment {
|
|
194
|
+
/** The thread the child runs on: as it started, or as its compaction left it. */
|
|
195
|
+
readonly thread: SubagentThreadContext
|
|
196
|
+
/**
|
|
197
|
+
* Compact the thread before the run from within it, once: the request the run's calls then
|
|
198
|
+
* start with. Undefined when it could not. Only a child whose environment ran its preflight has
|
|
199
|
+
* it.
|
|
200
|
+
*/
|
|
201
|
+
readonly compactInRun?: (input: {
|
|
202
|
+
readonly reason: AgentContextCheckpointReason
|
|
203
|
+
}) => Promise<ConversationRequest | undefined>
|
|
204
|
+
/** The bytes per token the preflight measured the thread at, which the run's calls go by. */
|
|
205
|
+
readonly bytesPerToken?: number
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export interface CreateWorkflowAgentNodeEnvironmentInput extends CreateAgentEnvironmentInput {
|
|
209
|
+
readonly run: WorkflowAgentNodeRunRecord
|
|
210
|
+
readonly workflowId: string
|
|
211
|
+
readonly stepId: string
|
|
212
|
+
readonly nodeInput: WorkflowIOSnapshot
|
|
213
|
+
readonly errorDetails: AgentErrorDetails
|
|
214
|
+
/** How the step calls a project tool: it runs in the cloud, so in the worker's process. */
|
|
215
|
+
readonly callTool: AgentToolCaller
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Prepare conversation history and attachments, then start the shared agent environment. */
|
|
219
|
+
export async function createConversationAgentEnvironment(
|
|
220
|
+
input: CreateConversationAgentEnvironmentInput
|
|
221
|
+
): Promise<ConversationAgentExecutionEnvironment> {
|
|
222
|
+
const { context, plan, run, preflight } = input
|
|
223
|
+
const { apiBaseUrl } = context
|
|
224
|
+
const failure = new AbortController()
|
|
225
|
+
const sandboxSignal = input.signal
|
|
226
|
+
? AbortSignal.any([input.signal, failure.signal])
|
|
227
|
+
: failure.signal
|
|
228
|
+
const { sandbox } = await input.openSandbox({
|
|
229
|
+
signal: sandboxSignal,
|
|
230
|
+
onFailure: (error) => failure.abort(error),
|
|
231
|
+
})
|
|
232
|
+
let environment: AgentExecutionEnvironment | undefined
|
|
233
|
+
// A workspace the prompt describes is acquired once: by the summary that continues the turn's
|
|
234
|
+
// prompt when the turn compacts, else when the environment starts.
|
|
235
|
+
let acquisition: Promise<AcquiredRunSandbox> | undefined
|
|
236
|
+
let provisioning = false
|
|
237
|
+
const acquire = () => {
|
|
238
|
+
acquisition ??= sandbox.acquire()
|
|
239
|
+
return acquisition
|
|
240
|
+
}
|
|
241
|
+
// The prompt shows memory as of the thread's start or its latest compaction (see
|
|
242
|
+
// loadConversationMemory).
|
|
243
|
+
const threadCreatedAt = input.thread?.createdAt ?? run.createdAt
|
|
244
|
+
const loadMemory: LoadConversationMemory = (checkpoint) =>
|
|
245
|
+
loadConversationMemory({
|
|
246
|
+
session: input.session,
|
|
247
|
+
asOf: checkpoint?.createdAt ?? threadCreatedAt,
|
|
248
|
+
})
|
|
249
|
+
const publishing =
|
|
250
|
+
input.thread && run.execution
|
|
251
|
+
? {
|
|
252
|
+
artifacts: input.session.artifacts,
|
|
253
|
+
threadId: input.thread.id,
|
|
254
|
+
owner: input.thread.ownerPrincipal,
|
|
255
|
+
}
|
|
256
|
+
: undefined
|
|
257
|
+
|
|
258
|
+
// What a history's files make of the request: its attachments and the images its tools showed,
|
|
259
|
+
// within one request's inline image budget, the history first.
|
|
260
|
+
const prepareFiles = async (messages: readonly AgentMessageRecord[]) => {
|
|
261
|
+
const inlineImages = await modelSupportsInlineImages(plan.model)
|
|
262
|
+
const attachments = await prepareAgentAttachments({
|
|
263
|
+
projectId: context.id,
|
|
264
|
+
threadId: run.threadId,
|
|
265
|
+
messages,
|
|
266
|
+
blobStorage: context.blobStorage,
|
|
267
|
+
apiBaseUrl,
|
|
268
|
+
contextDirectory: sandbox.contextDirectory,
|
|
269
|
+
inlineImages,
|
|
270
|
+
signal: sandboxSignal,
|
|
271
|
+
})
|
|
272
|
+
|
|
273
|
+
const imageBudget = new InlineImageBudget()
|
|
274
|
+
const attachmentContext = await allocateInlineImages({
|
|
275
|
+
messages,
|
|
276
|
+
attachments,
|
|
277
|
+
toolFiles: replayToolFiles({
|
|
278
|
+
messages,
|
|
279
|
+
suppliesToolFiles: suppliesToolFiles(plan),
|
|
280
|
+
supportsImages: inlineImages,
|
|
281
|
+
}),
|
|
282
|
+
budget: imageBudget,
|
|
283
|
+
blobStorage: context.blobStorage,
|
|
284
|
+
signal: sandboxSignal,
|
|
285
|
+
})
|
|
286
|
+
return { attachmentContext, imageBudget }
|
|
287
|
+
}
|
|
288
|
+
const authorsOf = (messages: readonly AgentMessageRecord[]) =>
|
|
289
|
+
input.conversation
|
|
290
|
+
? conversationAuthors({ conversation: input.conversation, messages }).section
|
|
291
|
+
: undefined
|
|
292
|
+
|
|
293
|
+
// The request this turn's calls would send for a history, built as the environment and
|
|
294
|
+
// runAgentTurn build it: the summary continues it, so the provider reads it from its cache.
|
|
295
|
+
const conversationRequest: BuildConversationRequest = async ({ threadContext, memory }) => {
|
|
296
|
+
const { attachmentContext } = await prepareFiles(threadContext.retainedMessages)
|
|
297
|
+
const workspace = sandbox.waitBeforeModel
|
|
298
|
+
? await waitForAbort(acquire(), sandboxSignal)
|
|
299
|
+
: undefined
|
|
300
|
+
const conversation = authorsOf(threadContext.retainedMessages)
|
|
301
|
+
|
|
302
|
+
const systemPrompt = measureEnvironmentSystemPrompt({
|
|
303
|
+
mode: "conversation",
|
|
304
|
+
sandbox,
|
|
305
|
+
context,
|
|
306
|
+
plan,
|
|
307
|
+
ontologyDocs: plan.ontologyDocs,
|
|
308
|
+
...(workspace ? { workspace } : {}),
|
|
309
|
+
...(conversation === undefined ? {} : { conversation }),
|
|
310
|
+
...(memory ? { memory } : {}),
|
|
311
|
+
})
|
|
312
|
+
|
|
313
|
+
return {
|
|
314
|
+
systemPrompt: systemPrompt.text,
|
|
315
|
+
systemPromptSize: systemPrompt,
|
|
316
|
+
tools: [
|
|
317
|
+
...agentModelToolSpecs(plan.tools, { publishes: publishing !== undefined }),
|
|
318
|
+
...(input.frameworkTools ?? []),
|
|
319
|
+
],
|
|
320
|
+
messages: conversationModelMessages({
|
|
321
|
+
threadContext,
|
|
322
|
+
attachmentContext,
|
|
323
|
+
...(input.conversation ? { conversation: input.conversation } : {}),
|
|
324
|
+
project: { timeZone: context.timeZone, locale: context.locale },
|
|
325
|
+
}),
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
try {
|
|
330
|
+
const { ontologyDocs } = plan
|
|
331
|
+
// What the conversation's compaction reads and writes through, before the turn or during it.
|
|
332
|
+
const compaction = preflight && {
|
|
333
|
+
context,
|
|
334
|
+
session: input.session,
|
|
335
|
+
plan,
|
|
336
|
+
ontologyIndex: ontologyDocs.index,
|
|
337
|
+
contextDirectory: sandbox.contextDirectory,
|
|
338
|
+
run,
|
|
339
|
+
...(input.conversation === undefined ? {} : { conversation: input.conversation }),
|
|
340
|
+
budget: preflight.budget,
|
|
341
|
+
runtime: {
|
|
342
|
+
...preflight.runtime,
|
|
343
|
+
signal: sandboxSignal,
|
|
344
|
+
assertCanContinue() {
|
|
345
|
+
preflight.runtime.assertCanContinue()
|
|
346
|
+
failure.signal.throwIfAborted()
|
|
347
|
+
},
|
|
348
|
+
},
|
|
349
|
+
frameworkTools: input.frameworkTools,
|
|
350
|
+
loadMemory,
|
|
351
|
+
conversationRequest,
|
|
352
|
+
}
|
|
353
|
+
// Resolve application access before any compaction model call. Once acquired, this
|
|
354
|
+
// environment owns preservation even if history, attachments or runtime preparation fail.
|
|
355
|
+
const prepared = compaction
|
|
356
|
+
? await prepareAgentConversationContext({ ...compaction, history: input.history })
|
|
357
|
+
: undefined
|
|
358
|
+
const threadContext = prepared?.threadContext ?? agentThreadModelContext(input.history)
|
|
359
|
+
const messages = threadContext.retainedMessages
|
|
360
|
+
const conversation = authorsOf(messages)
|
|
361
|
+
const [{ attachmentContext, imageBudget }, memory] = await Promise.all([
|
|
362
|
+
prepareFiles(messages),
|
|
363
|
+
prepared ? prepared.memory : loadMemory(threadContext.checkpoint),
|
|
364
|
+
])
|
|
365
|
+
environment = await startAgentEnvironment({
|
|
366
|
+
mode: "conversation",
|
|
367
|
+
sandbox,
|
|
368
|
+
// From here the environment gives back what it acquires.
|
|
369
|
+
acquire: () => {
|
|
370
|
+
provisioning = true
|
|
371
|
+
return acquire()
|
|
372
|
+
},
|
|
373
|
+
sandboxSignal,
|
|
374
|
+
failureSignal: failure.signal,
|
|
375
|
+
context,
|
|
376
|
+
plan,
|
|
377
|
+
runId: run.id,
|
|
378
|
+
threadId: run.threadId,
|
|
379
|
+
...(input.thread?.movedAt
|
|
380
|
+
? { workspaceMovedAt: new Date(input.thread.movedAt).toISOString() }
|
|
381
|
+
: {}),
|
|
382
|
+
callTool: (call, options) => input.session.callTool(call, options),
|
|
383
|
+
...(publishing ? { publishing } : {}),
|
|
384
|
+
apiBaseUrl,
|
|
385
|
+
attachmentContext,
|
|
386
|
+
toolOutputs: savedToolOutputFiles(messages),
|
|
387
|
+
imageBudget,
|
|
388
|
+
ontologyDocs,
|
|
389
|
+
frameworkTools: input.frameworkTools,
|
|
390
|
+
...(memory ? { memory } : {}),
|
|
391
|
+
...(conversation === undefined ? {} : { conversation }),
|
|
392
|
+
onDetachedTeardown: input.onDetachedTeardown,
|
|
393
|
+
})
|
|
394
|
+
|
|
395
|
+
// The turn compacts from within at most once: a run writes one checkpoint.
|
|
396
|
+
const compactInTurn: ConversationAgentExecutionEnvironment["compactInTurn"] =
|
|
397
|
+
compaction &&
|
|
398
|
+
(async ({ reason }) => {
|
|
399
|
+
const compacted = await compactAgentConversationInTurn({
|
|
400
|
+
...compaction,
|
|
401
|
+
threadContext,
|
|
402
|
+
memory,
|
|
403
|
+
reason,
|
|
404
|
+
coldCache: false,
|
|
405
|
+
})
|
|
406
|
+
return (
|
|
407
|
+
compacted &&
|
|
408
|
+
conversationRequest({ threadContext: compacted.threadContext, memory: compacted.memory })
|
|
409
|
+
)
|
|
410
|
+
})
|
|
411
|
+
return {
|
|
412
|
+
...environment,
|
|
413
|
+
threadContext,
|
|
414
|
+
...(compactInTurn ? { compactInTurn } : {}),
|
|
415
|
+
...(prepared?.bytesPerToken === undefined ? {} : { bytesPerToken: prepared.bytesPerToken }),
|
|
416
|
+
}
|
|
417
|
+
} catch (error) {
|
|
418
|
+
// Preparation can fail before the worker receives this environment. Preserve here, before
|
|
419
|
+
// the worker records the run's terminal outcome; a lost execution must touch nothing.
|
|
420
|
+
try {
|
|
421
|
+
if (!isLostExecution(error, input.signal)) await sandbox.beforeFinalize?.()
|
|
422
|
+
} finally {
|
|
423
|
+
// A workspace the summary acquired goes back as the environment would have given it.
|
|
424
|
+
if (environment) await environment.dispose()
|
|
425
|
+
else if (acquisition && !provisioning) await releaseAcquisition(sandbox, acquisition)
|
|
426
|
+
}
|
|
427
|
+
throw error
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Build an isolated environment for one headless child Agent. It knows the project as its parent
|
|
433
|
+
* does (ontology docs, memory to read), holds the files its parent handed over at their paths, and
|
|
434
|
+
* publishes into its conversation, as its own run.
|
|
435
|
+
*
|
|
436
|
+
* On a provider that resumes sandboxes, its thread keeps its workspace while it pauses: the run
|
|
437
|
+
* that continues it finds every file where it was. Elsewhere, or once those files were lost, it
|
|
438
|
+
* starts blank, with the handed files and what the paused run left in `out/` given back.
|
|
439
|
+
*/
|
|
440
|
+
export async function createSubagentEnvironment(
|
|
441
|
+
input: CreateSubagentEnvironmentInput
|
|
442
|
+
): Promise<SubagentAgentExecutionEnvironment> {
|
|
443
|
+
// A child's workspace is blank, so it has no source credentials to lose.
|
|
444
|
+
const { sandbox, resumed = false } = await input.openSandbox({
|
|
445
|
+
signal: input.signal ?? NEVER_ABORTED_SIGNAL,
|
|
446
|
+
onFailure: () => {},
|
|
447
|
+
})
|
|
448
|
+
// A workspace the prompt describes is acquired once: by the summary that continues the child's
|
|
449
|
+
// prompt when it compacts, else when the environment starts.
|
|
450
|
+
let acquisition: Promise<AcquiredRunSandbox> | undefined
|
|
451
|
+
let provisioning = false
|
|
452
|
+
const acquire = () => {
|
|
453
|
+
acquisition ??= sandbox.acquire()
|
|
454
|
+
return acquisition
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
try {
|
|
458
|
+
return await startSubagentEnvironment({
|
|
459
|
+
...input,
|
|
460
|
+
sandbox,
|
|
461
|
+
resumed,
|
|
462
|
+
acquireBeforeStart: acquire,
|
|
463
|
+
acquire: () => {
|
|
464
|
+
provisioning = true
|
|
465
|
+
return acquire()
|
|
466
|
+
},
|
|
467
|
+
})
|
|
468
|
+
} catch (error) {
|
|
469
|
+
// Preparation failed before the worker got this environment: the child ends here, so its
|
|
470
|
+
// workspace goes, as the worker's failure path would destroy it. A lost execution must touch
|
|
471
|
+
// nothing.
|
|
472
|
+
try {
|
|
473
|
+
if (!isLostExecution(error, input.signal)) await sandbox.beforeFinalize?.({ discard: true })
|
|
474
|
+
} finally {
|
|
475
|
+
// A workspace the summary acquired goes back as the environment would have given it.
|
|
476
|
+
if (acquisition && !provisioning) await releaseAcquisition(sandbox, acquisition)
|
|
477
|
+
}
|
|
478
|
+
throw error
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
async function startSubagentEnvironment(
|
|
483
|
+
input: CreateSubagentEnvironmentInput & {
|
|
484
|
+
readonly sandbox: RunSandbox
|
|
485
|
+
/** Whether the sandbox is the workspace the paused run left: it holds its files already. */
|
|
486
|
+
readonly resumed: boolean
|
|
487
|
+
/** How the summary acquires the workspace its prompt describes, before the environment. */
|
|
488
|
+
readonly acquireBeforeStart: () => Promise<AcquiredRunSandbox>
|
|
489
|
+
/** How provisioning acquires it, which from then gives it back. */
|
|
490
|
+
readonly acquire: () => Promise<AcquiredRunSandbox>
|
|
491
|
+
}
|
|
492
|
+
): Promise<SubagentAgentExecutionEnvironment> {
|
|
493
|
+
const { context, plan, run, conversation, sandbox, resumed, preflight } = input
|
|
494
|
+
const signal = input.signal ?? NEVER_ABORTED_SIGNAL
|
|
495
|
+
// Still listed, as handed over, but never copied over what the child made of them.
|
|
496
|
+
const files = resumed ? (run.spec.files ?? []) : subagentSandboxFiles(run, input.history.paused)
|
|
497
|
+
const inlineImages = modelSupportsInlineImages(plan.model)
|
|
498
|
+
const [memory, handedContext] = await Promise.all([
|
|
499
|
+
// As of the thread's start, as a conversation's: each run of the child reads the same memory.
|
|
500
|
+
loadConversationMemory({ session: input.session, asOf: input.thread.createdAt }),
|
|
501
|
+
files.length
|
|
502
|
+
? prepareHandedFiles({
|
|
503
|
+
projectId: context.id,
|
|
504
|
+
parentRunId: run.parentRunId,
|
|
505
|
+
files,
|
|
506
|
+
inSandbox: resumed,
|
|
507
|
+
contextDirectory: sandbox.contextDirectory,
|
|
508
|
+
blobStorage: context.blobStorage,
|
|
509
|
+
signal: input.signal,
|
|
510
|
+
})
|
|
511
|
+
: emptyAttachmentContext(context.id),
|
|
512
|
+
])
|
|
513
|
+
const publishing = conversation
|
|
514
|
+
? {
|
|
515
|
+
artifacts: input.session.artifacts,
|
|
516
|
+
threadId: conversation.id,
|
|
517
|
+
owner: conversation.ownerPrincipal,
|
|
518
|
+
}
|
|
519
|
+
: undefined
|
|
520
|
+
|
|
521
|
+
// What a history's files make of the request: the handed files, its attachments and the images
|
|
522
|
+
// its tools showed, within one request's inline image budget, the history first.
|
|
523
|
+
const prepareFiles = async (messages: readonly AgentMessageRecord[]) => {
|
|
524
|
+
const historyContext =
|
|
525
|
+
messages.length && context.apiBaseUrl
|
|
526
|
+
? await prepareAgentAttachments({
|
|
527
|
+
projectId: context.id,
|
|
528
|
+
// Its messages are its thread's, so their files are read there.
|
|
529
|
+
threadId: input.thread.id,
|
|
530
|
+
messages,
|
|
531
|
+
blobStorage: context.blobStorage,
|
|
532
|
+
apiBaseUrl: context.apiBaseUrl,
|
|
533
|
+
contextDirectory: sandbox.contextDirectory,
|
|
534
|
+
inlineImages,
|
|
535
|
+
signal: input.signal,
|
|
536
|
+
})
|
|
537
|
+
: undefined
|
|
538
|
+
|
|
539
|
+
const imageBudget = new InlineImageBudget()
|
|
540
|
+
const attachmentContext = await allocateInlineImages({
|
|
541
|
+
messages,
|
|
542
|
+
attachments: historyContext
|
|
543
|
+
? mergeAttachmentContexts(handedContext, historyContext)
|
|
544
|
+
: handedContext,
|
|
545
|
+
toolFiles: replayToolFiles({
|
|
546
|
+
messages,
|
|
547
|
+
suppliesToolFiles: suppliesToolFiles(plan),
|
|
548
|
+
supportsImages: inlineImages,
|
|
549
|
+
}),
|
|
550
|
+
budget: imageBudget,
|
|
551
|
+
blobStorage: context.blobStorage,
|
|
552
|
+
signal,
|
|
553
|
+
})
|
|
554
|
+
return { attachmentContext, imageBudget }
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
// The request the child's calls would send for a history, built as the environment and
|
|
558
|
+
// runSubagent build it: the summary continues it, so the provider reads it from its cache.
|
|
559
|
+
const createdAt = renderCurrentTime(
|
|
560
|
+
input.thread.createdAt,
|
|
561
|
+
sentSettings(plan, { timeZone: context.timeZone, locale: context.locale })
|
|
562
|
+
)
|
|
563
|
+
const initial = subagentThreadContext(input.history)
|
|
564
|
+
const task = initial.task
|
|
565
|
+
const threadOf = (threadContext: LoadedAgentThreadModelContext): SubagentThreadContext => ({
|
|
566
|
+
...(task ? { task } : {}),
|
|
567
|
+
threadContext,
|
|
568
|
+
})
|
|
569
|
+
const tools = [
|
|
570
|
+
...agentModelToolSpecs(plan.tools, { publishes: publishing !== undefined }),
|
|
571
|
+
...(input.frameworkTools ?? []),
|
|
572
|
+
]
|
|
573
|
+
const childRequest: BuildConversationRequest = async ({ threadContext }) => {
|
|
574
|
+
const { attachmentContext } = await prepareFiles(threadContext.retainedMessages)
|
|
575
|
+
const workspace = sandbox.waitBeforeModel
|
|
576
|
+
? await waitForAbort(input.acquireBeforeStart(), input.signal)
|
|
577
|
+
: undefined
|
|
578
|
+
|
|
579
|
+
return {
|
|
580
|
+
systemPrompt: renderEnvironmentSystemPrompt({
|
|
581
|
+
mode: "subagent",
|
|
582
|
+
sandbox,
|
|
583
|
+
context,
|
|
584
|
+
plan,
|
|
585
|
+
ontologyDocs: plan.ontologyDocs,
|
|
586
|
+
...(workspace ? { workspace } : {}),
|
|
587
|
+
...(memory ? { memory } : {}),
|
|
588
|
+
}),
|
|
589
|
+
tools,
|
|
590
|
+
messages: subagentModelMessages({
|
|
591
|
+
thread: threadOf(threadContext),
|
|
592
|
+
attachmentContext,
|
|
593
|
+
createdAt,
|
|
594
|
+
}),
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
// What the child's estimates count besides the thread: its prompt, its tools, and the task
|
|
599
|
+
// every request opens with.
|
|
600
|
+
const estimateShape = {
|
|
601
|
+
systemPrompt: renderEnvironmentSystemPrompt({
|
|
602
|
+
mode: "subagent",
|
|
603
|
+
sandbox,
|
|
604
|
+
context,
|
|
605
|
+
plan,
|
|
606
|
+
ontologyDocs: plan.ontologyDocs,
|
|
607
|
+
...(memory ? { memory } : {}),
|
|
608
|
+
}),
|
|
609
|
+
tools: contextEstimateTools(tools),
|
|
610
|
+
...(task ? { head: [task] } : {}),
|
|
611
|
+
}
|
|
612
|
+
// What the child's compaction reads and writes through, before the run or during it.
|
|
613
|
+
const compaction: AgentThreadCompactionInput | undefined = preflight && {
|
|
614
|
+
context,
|
|
615
|
+
session: input.session,
|
|
616
|
+
plan,
|
|
617
|
+
budget: preflight.budget,
|
|
618
|
+
run,
|
|
619
|
+
runtime: preflight.runtime,
|
|
620
|
+
// No `loadMemory`: a child's prompt shows memory as of its thread's start, whatever it
|
|
621
|
+
// compacted, so its summary and its calls send the same prompt.
|
|
622
|
+
conversationRequest: childRequest,
|
|
623
|
+
estimateShape: () => estimateShape,
|
|
624
|
+
caching: subagentPromptCaching({
|
|
625
|
+
projectId: context.id,
|
|
626
|
+
thread: input.thread,
|
|
627
|
+
run,
|
|
628
|
+
history: input.history,
|
|
629
|
+
}),
|
|
630
|
+
}
|
|
631
|
+
// Compacted before its files are read: the inline image budget goes to what the run sends.
|
|
632
|
+
const prepared = compaction
|
|
633
|
+
? await preflightSubagentContext({ ...compaction, threadContext: initial.threadContext })
|
|
634
|
+
: undefined
|
|
635
|
+
const threadContext = prepared?.threadContext ?? initial.threadContext
|
|
636
|
+
const { attachmentContext, imageBudget } = await prepareFiles(threadContext.retainedMessages)
|
|
637
|
+
|
|
638
|
+
const environment = await startAgentEnvironment({
|
|
639
|
+
mode: "subagent",
|
|
640
|
+
sandbox,
|
|
641
|
+
acquire: input.acquire,
|
|
642
|
+
sandboxSignal: input.signal,
|
|
643
|
+
context,
|
|
644
|
+
plan,
|
|
645
|
+
runId: run.id,
|
|
646
|
+
parentRunId: run.parentRunId,
|
|
647
|
+
threadId: conversationThreadId(input.thread),
|
|
648
|
+
callTool: (call, options) => input.session.callTool(call, options),
|
|
649
|
+
...(publishing ? { publishing } : {}),
|
|
650
|
+
apiBaseUrl: context.apiBaseUrl,
|
|
651
|
+
attachmentContext,
|
|
652
|
+
toolOutputs: savedToolOutputFiles(threadContext.retainedMessages),
|
|
653
|
+
imageBudget,
|
|
654
|
+
ontologyDocs: plan.ontologyDocs,
|
|
655
|
+
...(memory ? { memory } : {}),
|
|
656
|
+
frameworkTools: input.frameworkTools,
|
|
657
|
+
errorDetails: { parentRunId: run.parentRunId, runId: run.id },
|
|
658
|
+
onDetachedTeardown: input.onDetachedTeardown,
|
|
659
|
+
})
|
|
660
|
+
|
|
661
|
+
// The run compacts from within at most once: a run writes one checkpoint.
|
|
662
|
+
const compactInRun: SubagentAgentExecutionEnvironment["compactInRun"] =
|
|
663
|
+
compaction &&
|
|
664
|
+
(async ({ reason }) => {
|
|
665
|
+
const compacted = await compactAgentThreadInRun({
|
|
666
|
+
...compaction,
|
|
667
|
+
threadContext,
|
|
668
|
+
memory: undefined,
|
|
669
|
+
reason,
|
|
670
|
+
coldCache: false,
|
|
671
|
+
})
|
|
672
|
+
return (
|
|
673
|
+
compacted && childRequest({ threadContext: compacted.threadContext, memory: undefined })
|
|
674
|
+
)
|
|
675
|
+
})
|
|
676
|
+
return {
|
|
677
|
+
...environment,
|
|
678
|
+
thread: threadOf(threadContext),
|
|
679
|
+
...(compactInRun ? { compactInRun } : {}),
|
|
680
|
+
...(prepared ? { bytesPerToken: prepared.bytesPerToken } : {}),
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/** Build the same tool/sandbox environment for a fresh, headless workflow task. */
|
|
685
|
+
export async function createWorkflowAgentNodeEnvironment(
|
|
686
|
+
input: CreateWorkflowAgentNodeEnvironmentInput
|
|
687
|
+
): Promise<AgentExecutionEnvironment> {
|
|
688
|
+
const { context, plan, run } = input
|
|
689
|
+
const execution = run.execution
|
|
690
|
+
if (!execution) {
|
|
691
|
+
throw new Error(
|
|
692
|
+
`[SixbAgent] Agent workflow node run '${run.nodeRunId}' must hold an execution token.`
|
|
693
|
+
)
|
|
694
|
+
}
|
|
695
|
+
// Cancellation, lost ownership or worker shutdown stop provisioning. A step's lost source
|
|
696
|
+
// credentials end the node through `failure`.
|
|
697
|
+
const failure = new AbortController()
|
|
698
|
+
const sandboxSignal = input.signal
|
|
699
|
+
? AbortSignal.any([input.signal, failure.signal])
|
|
700
|
+
: failure.signal
|
|
701
|
+
|
|
702
|
+
const { sandbox } = await input.openSandbox({
|
|
703
|
+
signal: sandboxSignal,
|
|
704
|
+
onFailure: (error) => failure.abort(error),
|
|
705
|
+
})
|
|
706
|
+
const attachmentContext = await prepareWorkflowInputAttachments({
|
|
707
|
+
input: input.nodeInput,
|
|
708
|
+
blobStorage: context.blobStorage,
|
|
709
|
+
contextDirectory: sandbox.contextDirectory,
|
|
710
|
+
signal: input.signal,
|
|
711
|
+
})
|
|
712
|
+
|
|
713
|
+
try {
|
|
714
|
+
return await startAgentEnvironment({
|
|
715
|
+
mode: "workflow-task",
|
|
716
|
+
sandbox,
|
|
717
|
+
sandboxSignal,
|
|
718
|
+
failureSignal: failure.signal,
|
|
719
|
+
context,
|
|
720
|
+
actorId: run.actorId,
|
|
721
|
+
plan,
|
|
722
|
+
runId: run.nodeRunId,
|
|
723
|
+
callTool: input.callTool,
|
|
724
|
+
apiBaseUrl: context.apiBaseUrl,
|
|
725
|
+
attachmentContext,
|
|
726
|
+
// A step's inputs are files, never inline images: its own steps have the whole budget.
|
|
727
|
+
imageBudget: new InlineImageBudget(),
|
|
728
|
+
ontologyDocs: plan.ontologyDocs,
|
|
729
|
+
errorDetails: input.errorDetails,
|
|
730
|
+
onDetachedTeardown: input.onDetachedTeardown,
|
|
731
|
+
})
|
|
732
|
+
} catch (error) {
|
|
733
|
+
// Provisioning can fail, or be abandoned, before the node receives this environment. Confirm
|
|
734
|
+
// the step's credentials are closed before the node records its fate; a lost execution must
|
|
735
|
+
// touch nothing.
|
|
736
|
+
if (!isLostExecution(error, input.signal)) await sandbox.beforeFinalize?.()
|
|
737
|
+
throw error
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
interface AgentEnvironmentSetup
|
|
742
|
+
extends Omit<CreateAgentEnvironmentInput, "signal" | "openSandbox"> {
|
|
743
|
+
readonly sandbox: RunSandbox
|
|
744
|
+
/** How provisioning acquires the sandbox, when the run may have acquired it already. */
|
|
745
|
+
readonly acquire?: () => Promise<AcquiredRunSandbox>
|
|
746
|
+
/**
|
|
747
|
+
* Run end or environment failure: stops waiting for a sandbox the first model call needs, and
|
|
748
|
+
* stops reading the artifacts it installs.
|
|
749
|
+
*/
|
|
750
|
+
readonly sandboxSignal?: AbortSignal
|
|
751
|
+
/** Environment-owned failure, such as lost source credentials. */
|
|
752
|
+
readonly failureSignal?: AbortSignal
|
|
753
|
+
/** How the run calls a project tool. */
|
|
754
|
+
readonly callTool: AgentToolCaller
|
|
755
|
+
readonly actorId?: string
|
|
756
|
+
readonly parentRunId?: string
|
|
757
|
+
readonly mode: AgentExecutionMode
|
|
758
|
+
readonly runId: string
|
|
759
|
+
readonly threadId?: string
|
|
760
|
+
readonly apiBaseUrl: string
|
|
761
|
+
readonly attachmentContext: PreparedAgentAttachmentContext
|
|
762
|
+
/**
|
|
763
|
+
* The outputs the history saved to files, which provisioning writes back where their previews
|
|
764
|
+
* name them: read from the store while the model starts, unless the sandbox holds them.
|
|
765
|
+
*/
|
|
766
|
+
readonly toolOutputs?: readonly AgentToolCallFile[]
|
|
767
|
+
/** What the history left of the request's inline image budget, which the run's steps take. */
|
|
768
|
+
readonly imageBudget: InlineImageBudget
|
|
769
|
+
/** Installed under `$SIXB_ONTOLOGY_DIR`; a workflow step's prompt does not list them. */
|
|
770
|
+
readonly ontologyDocs?: RenderedOntologyDocs
|
|
771
|
+
readonly errorDetails?: AgentErrorDetails
|
|
772
|
+
readonly frameworkTools?: readonly ModelTool[]
|
|
773
|
+
/**
|
|
774
|
+
* A conversation, or a child of one, publishes artifacts into its conversation, through its
|
|
775
|
+
* session, and edits them from their installed copies; other runs return text.
|
|
776
|
+
*/
|
|
777
|
+
readonly publishing?: {
|
|
778
|
+
readonly artifacts: AgentRunArtifacts
|
|
779
|
+
/** The conversation's thread, and its owner, who owns what the run creates. */
|
|
780
|
+
readonly threadId: string
|
|
781
|
+
readonly owner: Principal
|
|
782
|
+
}
|
|
783
|
+
/** A conversation's memory, or a child's to read: installed in the sandbox and in the prompt. */
|
|
784
|
+
readonly memory?: ConversationMemory
|
|
785
|
+
/** When the conversation's turns last moved to where they run now: see its `movedAt`. */
|
|
786
|
+
readonly workspaceMovedAt?: string
|
|
787
|
+
/** Who takes part in a conversation several people write in, for its prompt. */
|
|
788
|
+
readonly conversation?: string
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
/**
|
|
792
|
+
* Start the shared tools, sandbox, and teardown lifecycle after source-specific preparation.
|
|
793
|
+
* A blank sandbox boots concurrently with the model call and tools await it only when used; a
|
|
794
|
+
* workspace (a thread's or a step's) is ready first, so the system prompt describes the one the
|
|
795
|
+
* run got.
|
|
796
|
+
*/
|
|
797
|
+
async function startAgentEnvironment(
|
|
798
|
+
input: AgentEnvironmentSetup
|
|
799
|
+
): Promise<AgentExecutionEnvironment> {
|
|
800
|
+
const { mode, sandbox, context, actorId, plan, runId, threadId, apiBaseUrl, attachmentContext } =
|
|
801
|
+
input
|
|
802
|
+
|
|
803
|
+
let ready: Promise<ProvisionedRunSandbox>
|
|
804
|
+
const fileRegistry = new AgentSandboxFileRegistry()
|
|
805
|
+
const fileBudget = new AgentFileBudget()
|
|
806
|
+
const mediaBridge = new AgentToolResultMediaBridge({
|
|
807
|
+
blobStorage: context.blobStorage,
|
|
808
|
+
suppliesToolFiles: suppliesToolFiles(plan),
|
|
809
|
+
inlineImages: input.imageBudget,
|
|
810
|
+
// As the agent names it, so the output a later turn replays names the path that turn
|
|
811
|
+
// materializes the file at, in its own sandbox.
|
|
812
|
+
sandboxPathForFileRef: async (fileRef) => {
|
|
813
|
+
const path = fileRegistry.pathFor(fileRef)
|
|
814
|
+
return path === undefined ? undefined : agentSandboxPath(await ready, path)
|
|
815
|
+
},
|
|
816
|
+
})
|
|
817
|
+
const filesForToolCall = (input: {
|
|
818
|
+
readonly toolName: string
|
|
819
|
+
readonly toolCallId: string
|
|
820
|
+
readonly signal: AbortSignal
|
|
821
|
+
}) =>
|
|
822
|
+
createAgentToolFiles({
|
|
823
|
+
...input,
|
|
824
|
+
blobStorage: context.blobStorage,
|
|
825
|
+
budget: fileBudget,
|
|
826
|
+
resolveSandbox: () => ready,
|
|
827
|
+
onPublished: (file) => fileRegistry.register(file.sandboxPath, file.fileRef),
|
|
828
|
+
})
|
|
829
|
+
const tools = [
|
|
830
|
+
...projectModelTools({
|
|
831
|
+
specs: plan.tools,
|
|
832
|
+
runId,
|
|
833
|
+
callTool: input.callTool,
|
|
834
|
+
contextDirectory: sandbox.contextDirectory,
|
|
835
|
+
fileBytesLeft: () => fileBudget.maxBytes - fileBudget.reservedBytes,
|
|
836
|
+
installFiles: ({ toolName, files, signal }) =>
|
|
837
|
+
installAgentToolFiles({
|
|
838
|
+
toolName,
|
|
839
|
+
files,
|
|
840
|
+
blobStorage: context.blobStorage,
|
|
841
|
+
resolveSandbox: () => ready,
|
|
842
|
+
budget: fileBudget,
|
|
843
|
+
signal,
|
|
844
|
+
onPublished: (file) => fileRegistry.register(file.sandboxPath, file.fileRef),
|
|
845
|
+
}),
|
|
846
|
+
toolResultToModelOutput: (output) => mediaBridge.toModelOutput(output),
|
|
847
|
+
...(input.errorDetails === undefined ? {} : { errorDetails: input.errorDetails }),
|
|
848
|
+
}),
|
|
849
|
+
]
|
|
850
|
+
|
|
851
|
+
appendBuiltInTool(
|
|
852
|
+
tools,
|
|
853
|
+
createViewFileTool({
|
|
854
|
+
resolveSandbox: () => ready,
|
|
855
|
+
attachments: attachmentContext,
|
|
856
|
+
registry: fileRegistry,
|
|
857
|
+
filesForToolCall: ({ toolCallId, signal }) =>
|
|
858
|
+
filesForToolCall({ toolName: "view_file", toolCallId, signal }),
|
|
859
|
+
toolResultToModelOutput: (output) => mediaBridge.toModelOutput(output),
|
|
860
|
+
})
|
|
861
|
+
)
|
|
862
|
+
const resolveSandbox = () => ready
|
|
863
|
+
// Its own budget: saving outputs never takes what published artifacts and tool files need.
|
|
864
|
+
const toolOutputFiles = new ToolOutputFiles({
|
|
865
|
+
sandbox: resolveSandbox,
|
|
866
|
+
blobStorage: context.blobStorage,
|
|
867
|
+
})
|
|
868
|
+
appendBuiltInTool(tools, createReadTool(resolveSandbox))
|
|
869
|
+
appendBuiltInTool(tools, createBashTool(resolveSandbox))
|
|
870
|
+
let installedArtifacts: Promise<InstalledArtifacts> | undefined
|
|
871
|
+
const { publishing } = input
|
|
872
|
+
if (publishing) {
|
|
873
|
+
// Read concurrently with sandbox creation; both run while the model starts.
|
|
874
|
+
installedArtifacts = materializeThreadArtifacts({
|
|
875
|
+
threadId: publishing.threadId,
|
|
876
|
+
// As the requester: the turn installs nothing they could not read themselves.
|
|
877
|
+
artifacts: publishing.artifacts,
|
|
878
|
+
blobStorage: context.blobStorage,
|
|
879
|
+
directory: posix.join(sandbox.contextDirectory, AGENT_ARTIFACTS_DIRECTORY),
|
|
880
|
+
manifestPath: posix.join(sandbox.contextDirectory, AGENT_ARTIFACTS_MANIFEST),
|
|
881
|
+
signal: input.sandboxSignal,
|
|
882
|
+
})
|
|
883
|
+
// Surfaced where provisioning awaits it.
|
|
884
|
+
installedArtifacts.catch(() => {})
|
|
885
|
+
const publishTools = createPublishArtifactTools({
|
|
886
|
+
artifacts: publishing.artifacts,
|
|
887
|
+
threadId: publishing.threadId,
|
|
888
|
+
owner: publishing.owner,
|
|
889
|
+
blobStorage: context.blobStorage,
|
|
890
|
+
budget: fileBudget,
|
|
891
|
+
resolveSandbox,
|
|
892
|
+
installed: installedArtifacts,
|
|
893
|
+
})
|
|
894
|
+
for (const tool of publishTools) appendBuiltInTool(tools, tool)
|
|
895
|
+
}
|
|
896
|
+
for (const frameworkTool of input.frameworkTools ?? []) appendBuiltInTool(tools, frameworkTool)
|
|
897
|
+
|
|
898
|
+
ready = provisionSandbox({
|
|
899
|
+
sandbox,
|
|
900
|
+
...(input.acquire ? { acquire: input.acquire } : {}),
|
|
901
|
+
context,
|
|
902
|
+
actorId,
|
|
903
|
+
run: { id: runId, ...(threadId ? { threadId } : {}) },
|
|
904
|
+
apiBaseUrl,
|
|
905
|
+
attachmentContext,
|
|
906
|
+
...(input.toolOutputs ? { toolOutputs: input.toolOutputs } : {}),
|
|
907
|
+
...(input.sandboxSignal ? { signal: input.sandboxSignal } : {}),
|
|
908
|
+
// A conversation's memory section names the memory skill; other runs never see it.
|
|
909
|
+
skills: input.memory && mode === "conversation" ? [...plan.skills, MEMORY_SKILL] : plan.skills,
|
|
910
|
+
ontologyFiles: input.ontologyDocs?.files ?? [],
|
|
911
|
+
...(installedArtifacts ? { artifacts: installedArtifacts } : {}),
|
|
912
|
+
...(input.memory ? { memory: input.memory.repos } : {}),
|
|
913
|
+
})
|
|
914
|
+
// Creation failure is surfaced where it is awaited (turn / sandbox tool / dispose); attach a no-op
|
|
915
|
+
// catch so a rejection observed by none of them is not reported as unhandled.
|
|
916
|
+
ready.catch(() => {})
|
|
917
|
+
// Track settlement so dispose() can avoid blocking teardown on a boot still in flight.
|
|
918
|
+
let settled = false
|
|
919
|
+
const markSettled = () => {
|
|
920
|
+
settled = true
|
|
921
|
+
}
|
|
922
|
+
ready.then(markSettled, markSettled)
|
|
923
|
+
|
|
924
|
+
const dispose = () => disposeEnvironment(ready, () => settled, sandbox, input.onDetachedTeardown)
|
|
925
|
+
|
|
926
|
+
let systemPrompt: AgentSystemPromptSize
|
|
927
|
+
try {
|
|
928
|
+
const workspace = sandbox.waitBeforeModel
|
|
929
|
+
? await waitForAbort(ready, input.sandboxSignal)
|
|
930
|
+
: undefined
|
|
931
|
+
|
|
932
|
+
systemPrompt = measureEnvironmentSystemPrompt({
|
|
933
|
+
mode,
|
|
934
|
+
sandbox,
|
|
935
|
+
context,
|
|
936
|
+
plan,
|
|
937
|
+
...(input.ontologyDocs ? { ontologyDocs: input.ontologyDocs } : {}),
|
|
938
|
+
...(workspace ? { workspace } : {}),
|
|
939
|
+
...(input.workspaceMovedAt ? { workspaceMovedAt: input.workspaceMovedAt } : {}),
|
|
940
|
+
...(input.conversation === undefined ? {} : { conversation: input.conversation }),
|
|
941
|
+
...(input.memory ? { memory: input.memory } : {}),
|
|
942
|
+
})
|
|
943
|
+
} catch (error) {
|
|
944
|
+
// Provisioning has started: give back what it acquires, or the sandbox outlives the run.
|
|
945
|
+
await dispose()
|
|
946
|
+
throw error
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
const beforeFinalize = (options?: BeforeFinalizeOptions) =>
|
|
950
|
+
sandbox.beforeFinalize?.(options) ?? Promise.resolve()
|
|
951
|
+
const artifacts =
|
|
952
|
+
publishing && installedArtifacts
|
|
953
|
+
? { reader: publishing.artifacts, installed: installedArtifacts }
|
|
954
|
+
: undefined
|
|
955
|
+
const runFiles: AgentRunFiles = {
|
|
956
|
+
sandbox: resolveSandbox,
|
|
957
|
+
blobStorage: context.blobStorage,
|
|
958
|
+
budget: fileBudget,
|
|
959
|
+
async installArtifactsFrom(runIds, signal) {
|
|
960
|
+
if (!artifacts) return
|
|
961
|
+
|
|
962
|
+
await installArtifactsPublishedBy({
|
|
963
|
+
installed: await artifacts.installed,
|
|
964
|
+
artifacts: artifacts.reader,
|
|
965
|
+
blobStorage: context.blobStorage,
|
|
966
|
+
sandbox: (await ready).sandbox,
|
|
967
|
+
runIds,
|
|
968
|
+
signal,
|
|
969
|
+
})
|
|
970
|
+
},
|
|
971
|
+
}
|
|
972
|
+
return {
|
|
973
|
+
beforeFinalize,
|
|
974
|
+
runFiles,
|
|
975
|
+
turnContext: {
|
|
976
|
+
environmentFailureSignal: input.failureSignal,
|
|
977
|
+
...(sandbox.beforeFinalize ? { beforeFinalize } : {}),
|
|
978
|
+
id: context.id,
|
|
979
|
+
...(context.authorPrincipal === undefined
|
|
980
|
+
? {}
|
|
981
|
+
: { authorPrincipal: context.authorPrincipal }),
|
|
982
|
+
blobStorage: context.blobStorage,
|
|
983
|
+
apiBaseUrl,
|
|
984
|
+
attachmentContext,
|
|
985
|
+
tools: toolOutputFiles.wrap(tools),
|
|
986
|
+
outputFileOf: (toolCallId) => toolOutputFiles.fileOf(toolCallId),
|
|
987
|
+
prepareStep: mediaBridge.prepareStep,
|
|
988
|
+
systemPrompt: systemPrompt.text,
|
|
989
|
+
systemPromptSize: systemPrompt,
|
|
990
|
+
contextDirectory: sandbox.contextDirectory,
|
|
991
|
+
projectTimeZone: context.timeZone,
|
|
992
|
+
projectLocale: context.locale,
|
|
993
|
+
sandboxReady: ready,
|
|
994
|
+
},
|
|
995
|
+
dispose,
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
/**
|
|
1000
|
+
* A run's system prompt, from its plan and what its sandbox tells it: the environment renders it,
|
|
1001
|
+
* and so does the summary that continues a conversation's prompt.
|
|
1002
|
+
*/
|
|
1003
|
+
function renderEnvironmentSystemPrompt(
|
|
1004
|
+
input: Parameters<typeof measureEnvironmentSystemPrompt>[0]
|
|
1005
|
+
): string {
|
|
1006
|
+
return measureEnvironmentSystemPrompt(input).text
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
/** The same, with each section's bytes, for the turn's steps to record what they sent. */
|
|
1010
|
+
function measureEnvironmentSystemPrompt(input: {
|
|
1011
|
+
readonly mode: AgentExecutionMode
|
|
1012
|
+
readonly sandbox: RunSandbox
|
|
1013
|
+
readonly context: AgentExecutionContext
|
|
1014
|
+
readonly plan: ResolvedAgentExecutionPlan
|
|
1015
|
+
readonly ontologyDocs?: RenderedOntologyDocs
|
|
1016
|
+
/** The acquired workspace, when the prompt describes it. */
|
|
1017
|
+
readonly workspace?: Pick<AcquiredRunSandbox, "promptContext" | "resetAt">
|
|
1018
|
+
readonly workspaceMovedAt?: string
|
|
1019
|
+
readonly conversation?: string
|
|
1020
|
+
readonly memory?: ConversationMemory
|
|
1021
|
+
}): AgentSystemPromptSize {
|
|
1022
|
+
const { mode, plan, workspace } = input
|
|
1023
|
+
const { requester } = input.context
|
|
1024
|
+
|
|
1025
|
+
return measureAgentSystemPrompt({
|
|
1026
|
+
mode,
|
|
1027
|
+
contextDirectory: input.sandbox.contextDirectory,
|
|
1028
|
+
instructions: plan.instructions,
|
|
1029
|
+
skills: plan.skills,
|
|
1030
|
+
// Workflow prompts are kept lean: their steps get the files without the index.
|
|
1031
|
+
...(mode !== "workflow-task" && input.ontologyDocs
|
|
1032
|
+
? { ontologyIndex: input.ontologyDocs.index }
|
|
1033
|
+
: {}),
|
|
1034
|
+
sandboxResetAt: workspace?.resetAt,
|
|
1035
|
+
...(input.workspaceMovedAt ? { workspaceMovedAt: input.workspaceMovedAt } : {}),
|
|
1036
|
+
workspace: workspace?.promptContext,
|
|
1037
|
+
facts: requester === undefined ? {} : { requester },
|
|
1038
|
+
...(input.conversation === undefined ? {} : { conversation: input.conversation }),
|
|
1039
|
+
...(plan.sandboxModels ? { sandboxModels: plan.sandboxModels } : {}),
|
|
1040
|
+
...(input.memory ? { memory: input.memory.prompt } : {}),
|
|
1041
|
+
})
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
/** Give back a sandbox acquired for a run whose environment never started. */
|
|
1045
|
+
async function releaseAcquisition(
|
|
1046
|
+
sandbox: RunSandbox,
|
|
1047
|
+
acquisition: Promise<AcquiredRunSandbox>
|
|
1048
|
+
): Promise<void> {
|
|
1049
|
+
// A failed acquisition gave back what it held.
|
|
1050
|
+
const acquired = await acquisition.catch(() => undefined)
|
|
1051
|
+
if (!acquired || !sandbox.release) return
|
|
1052
|
+
|
|
1053
|
+
await sandbox.release(acquired).catch((error) => {
|
|
1054
|
+
console.error("[SixbAgent] Could not release agent run sandbox:", error)
|
|
1055
|
+
})
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
/** An absolute sandbox path relative to the working directory when it is inside it. */
|
|
1059
|
+
function agentSandboxPath(handle: AgentSandboxHandle, path: string): string {
|
|
1060
|
+
const relative = posix.relative(handle.sandbox.workingDirectory, path)
|
|
1061
|
+
return relative && !relative.startsWith("../") && !posix.isAbsolute(relative) ? relative : path
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
/**
|
|
1065
|
+
* The tools whose images reach the model after their step: the project's and `view_file`, whose
|
|
1066
|
+
* outputs go through the run's media bridge. A replay asks the same of the stored trace.
|
|
1067
|
+
*/
|
|
1068
|
+
function suppliesToolFiles(plan: Pick<ResolvedAgentExecutionPlan, "tools">): SuppliesToolFiles {
|
|
1069
|
+
const names = new Set([...plan.tools.map((tool) => tool.name), VIEW_FILE_TOOL_SPEC.name])
|
|
1070
|
+
return (toolName) => names.has(toolName)
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
/** The handed files' context, with what a continuation's history showed its tools. */
|
|
1074
|
+
function mergeAttachmentContexts(
|
|
1075
|
+
handed: PreparedAgentAttachmentContext,
|
|
1076
|
+
history: PreparedAgentAttachmentContext
|
|
1077
|
+
): PreparedAgentAttachmentContext {
|
|
1078
|
+
const manifest = (json: string) => JSON.parse(json) as { readonly attachments?: unknown[] }
|
|
1079
|
+
const handedManifest = manifest(handed.manifestJson)
|
|
1080
|
+
return {
|
|
1081
|
+
entries: [...handed.entries, ...history.entries],
|
|
1082
|
+
promptTextByPartKey: new Map([...handed.promptTextByPartKey, ...history.promptTextByPartKey]),
|
|
1083
|
+
modelFileDataByPartKey: new Map([
|
|
1084
|
+
...handed.modelFileDataByPartKey,
|
|
1085
|
+
...history.modelFileDataByPartKey,
|
|
1086
|
+
]),
|
|
1087
|
+
sandboxFiles: [...handed.sandboxFiles, ...history.sandboxFiles],
|
|
1088
|
+
...(history.pendingImages === undefined ? {} : { pendingImages: history.pendingImages }),
|
|
1089
|
+
manifestJson: JSON.stringify(
|
|
1090
|
+
{
|
|
1091
|
+
...handedManifest,
|
|
1092
|
+
attachments: [
|
|
1093
|
+
...(handedManifest.attachments ?? []),
|
|
1094
|
+
...(manifest(history.manifestJson).attachments ?? []),
|
|
1095
|
+
],
|
|
1096
|
+
},
|
|
1097
|
+
null,
|
|
1098
|
+
2
|
|
1099
|
+
),
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
function emptyAttachmentContext(projectId: string): PreparedAgentAttachmentContext {
|
|
1104
|
+
return {
|
|
1105
|
+
entries: [],
|
|
1106
|
+
promptTextByPartKey: new Map(),
|
|
1107
|
+
modelFileDataByPartKey: new Map(),
|
|
1108
|
+
sandboxFiles: [],
|
|
1109
|
+
manifestJson: JSON.stringify({ projectId, attachments: [] }, null, 2),
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
interface ProvisionSandboxInput {
|
|
1114
|
+
readonly sandbox: RunSandbox
|
|
1115
|
+
readonly acquire?: () => Promise<AcquiredRunSandbox>
|
|
1116
|
+
readonly context: AgentExecutionContext
|
|
1117
|
+
readonly actorId?: string
|
|
1118
|
+
readonly run: { readonly id: string; readonly threadId?: string }
|
|
1119
|
+
readonly apiBaseUrl: string
|
|
1120
|
+
readonly attachmentContext: PreparedAgentAttachmentContext
|
|
1121
|
+
readonly toolOutputs?: readonly AgentToolCallFile[]
|
|
1122
|
+
/** Stops reading the saved outputs it writes back. */
|
|
1123
|
+
readonly signal?: AbortSignal
|
|
1124
|
+
readonly skills: ResolvedAgentExecutionPlan["skills"]
|
|
1125
|
+
readonly ontologyFiles: RenderedOntologyDocs["files"]
|
|
1126
|
+
/** The conversation's artifacts, read while the sandbox starts. */
|
|
1127
|
+
readonly artifacts?: Promise<MaterializedArtifacts>
|
|
1128
|
+
readonly memory?: PrepareAgentSandboxApiContextInput["memory"]
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
/** A sandbox acquired for the run, with the run's files installed in its context directory. */
|
|
1132
|
+
type ProvisionedRunSandbox = AcquiredRunSandbox & AgentSandboxHandle
|
|
1133
|
+
|
|
1134
|
+
async function provisionSandbox(input: ProvisionSandboxInput): Promise<ProvisionedRunSandbox> {
|
|
1135
|
+
const { context, actorId, run, apiBaseUrl, skills, ontologyFiles } = input
|
|
1136
|
+
const acquired = await (input.acquire?.() ?? input.sandbox.acquire())
|
|
1137
|
+
const { sandbox } = acquired
|
|
1138
|
+
const { contextDirectory } = input.sandbox
|
|
1139
|
+
try {
|
|
1140
|
+
const apiContext = await prepareAgentSandboxApiContext({
|
|
1141
|
+
sandbox,
|
|
1142
|
+
contextDirectory,
|
|
1143
|
+
apiBaseUrl,
|
|
1144
|
+
projectId: context.id,
|
|
1145
|
+
...(actorId === undefined ? {} : { actorId }),
|
|
1146
|
+
...(run.threadId ? { threadId: run.threadId } : {}),
|
|
1147
|
+
runId: run.id,
|
|
1148
|
+
attachments: input.attachmentContext,
|
|
1149
|
+
skills,
|
|
1150
|
+
ontologyFiles,
|
|
1151
|
+
...(input.artifacts ? { artifacts: await input.artifacts } : {}),
|
|
1152
|
+
...(input.memory ? { memory: input.memory } : {}),
|
|
1153
|
+
})
|
|
1154
|
+
await assertAgentRuntimeProfile({
|
|
1155
|
+
sandbox,
|
|
1156
|
+
env: apiContext.env,
|
|
1157
|
+
projectId: context.id,
|
|
1158
|
+
})
|
|
1159
|
+
const provisioned = {
|
|
1160
|
+
...acquired,
|
|
1161
|
+
contextDirectory,
|
|
1162
|
+
env: { ...acquired.env, ...apiContext.env },
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
// Best effort: an output not written back is still in its message, cut, and in the store.
|
|
1166
|
+
await restoreSavedToolOutputs({
|
|
1167
|
+
handle: provisioned,
|
|
1168
|
+
files: input.toolOutputs ?? [],
|
|
1169
|
+
blobStorage: context.blobStorage,
|
|
1170
|
+
signal: input.signal ?? NEVER_ABORTED_SIGNAL,
|
|
1171
|
+
}).catch((error: unknown) => {
|
|
1172
|
+
input.signal?.throwIfAborted()
|
|
1173
|
+
console.warn("[SixbAgent] Could not write the saved tool outputs back:", error)
|
|
1174
|
+
})
|
|
1175
|
+
return provisioned
|
|
1176
|
+
} catch (error) {
|
|
1177
|
+
// Give back a half-provisioned sandbox before propagating to the awaiter.
|
|
1178
|
+
await input.sandbox.release?.(acquired).catch(() => {})
|
|
1179
|
+
throw error
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
function disposeEnvironment(
|
|
1184
|
+
ready: Promise<AcquiredRunSandbox>,
|
|
1185
|
+
isSettled: () => boolean,
|
|
1186
|
+
sandbox: RunSandbox,
|
|
1187
|
+
onDetachedTeardown?: (teardown: Promise<void>) => void
|
|
1188
|
+
): Promise<void> {
|
|
1189
|
+
// Nothing to give back: teardown, and a worker's stop(), must not wait on provisioning.
|
|
1190
|
+
const release = sandbox.release?.bind(sandbox)
|
|
1191
|
+
if (!release) return Promise.resolve()
|
|
1192
|
+
|
|
1193
|
+
// Release the sandbox once provisioning settles. A rejection means provisionSandbox already
|
|
1194
|
+
// released whatever it acquired, so there is nothing left to give back.
|
|
1195
|
+
const teardown = ready
|
|
1196
|
+
.then(release, () => undefined)
|
|
1197
|
+
.catch((error) => {
|
|
1198
|
+
console.error("[SixbAgent] Could not release agent run sandbox:", error)
|
|
1199
|
+
})
|
|
1200
|
+
// Once provisioning has settled, await the release so cleanup completes inline.
|
|
1201
|
+
if (isSettled()) {
|
|
1202
|
+
return teardown
|
|
1203
|
+
}
|
|
1204
|
+
// Boot still in flight (the model answered before it finished and never used bash): don't stall
|
|
1205
|
+
// run teardown on it. Hand the chained release to the worker so a graceful stop() can drain it
|
|
1206
|
+
// rather than orphaning a machine that is still being torn down.
|
|
1207
|
+
onDetachedTeardown?.(teardown)
|
|
1208
|
+
return Promise.resolve()
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
function appendBuiltInTool(tools: ModelTool[], tool: ModelTool): void {
|
|
1212
|
+
if (tools.some((candidate) => candidate.name === tool.name)) {
|
|
1213
|
+
throw new Error(`[SixbAgent] Agent tool name '${tool.name}' is reserved by the worker runtime.`)
|
|
1214
|
+
}
|
|
1215
|
+
tools.push(tool)
|
|
1216
|
+
}
|