@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,826 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AGENT_CONTEXT_COMPACTED_SHARE,
|
|
3
|
+
AGENT_TOKEN_RATE_MIN_BYTES_PER_TOKEN,
|
|
4
|
+
type AgentContextBudget,
|
|
5
|
+
measureAgentContextTokenRate,
|
|
6
|
+
measureAgentModelRequest,
|
|
7
|
+
type PrepareModelStepInput,
|
|
8
|
+
type PrepareModelStepResult,
|
|
9
|
+
type RecoverModelStepInput,
|
|
10
|
+
} from "@sixb/core/internal/agents"
|
|
11
|
+
import {
|
|
12
|
+
isJsonObject,
|
|
13
|
+
type JsonValue,
|
|
14
|
+
type LanguageModel,
|
|
15
|
+
type ModelMessage,
|
|
16
|
+
ModelProviderError,
|
|
17
|
+
type ModelStep,
|
|
18
|
+
type ModelToolResultPart,
|
|
19
|
+
type ModelToolSpecification,
|
|
20
|
+
} from "@sixb/core/models"
|
|
21
|
+
import type { AgentContextCheckpointReason } from "@sixb/core/storage"
|
|
22
|
+
import { stableJsonStringify } from "@sixb/core/storage"
|
|
23
|
+
import {
|
|
24
|
+
agentMinimumAnswerTokens,
|
|
25
|
+
agentOutputRoomTokens,
|
|
26
|
+
estimateAgentRequestTokens,
|
|
27
|
+
} from "./context-budget"
|
|
28
|
+
import { savedToolOutputPath } from "./tools/tool-outputs"
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The most recent tool result the model has read always stays. Clearing goes oldest first, in one
|
|
32
|
+
* batch down to the aim: the three most recent stay whenever clearing the older ones gets there,
|
|
33
|
+
* as Anthropic's `clear_tool_uses` keeps by default, and the batch goes on through them when it
|
|
34
|
+
* does not. Keeping three whatever the aim would clear one more at every step of a turn whose
|
|
35
|
+
* results are large, and break the cache each time.
|
|
36
|
+
*/
|
|
37
|
+
const KEPT_TOOL_RESULTS = 1
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* What clearing has to free, as a share of the limit, to be worth the cache it breaks: every
|
|
41
|
+
* request after it rewrites the conversation from the first result it cleared.
|
|
42
|
+
*/
|
|
43
|
+
const CLEARED_AT_LEAST_SHARE = 0.1
|
|
44
|
+
|
|
45
|
+
/** A result smaller than this stays as it is: the note that replaces it weighs about as much. */
|
|
46
|
+
const CLEARED_MIN_BYTES = 1_024
|
|
47
|
+
|
|
48
|
+
/** How far a step's estimated growth may run over what it really adds, as a share of it. */
|
|
49
|
+
const GROWTH_MARGIN = 0.1
|
|
50
|
+
|
|
51
|
+
/** A result the model has not read, cut to fit the model's limit, keeps at least this much. */
|
|
52
|
+
const CUT_MIN_BYTES = 512
|
|
53
|
+
|
|
54
|
+
/** What a turn's requests start with in place of the turn's history, once it compacted. */
|
|
55
|
+
export type CompactConversationBeforeTurn = (input: {
|
|
56
|
+
readonly reason: AgentContextCheckpointReason
|
|
57
|
+
}) => Promise<readonly ModelMessage[] | undefined>
|
|
58
|
+
|
|
59
|
+
export interface AgentContextGuardInput {
|
|
60
|
+
/** Its `inputBudgetTokens` is the limit the turn's requests keep under. */
|
|
61
|
+
readonly budget: AgentContextBudget
|
|
62
|
+
/** The tools every request sends. */
|
|
63
|
+
readonly tools: readonly ModelToolSpecification[]
|
|
64
|
+
/** The bytes per token the turn measured its history at, else the one its run started from. */
|
|
65
|
+
readonly bytesPerToken?: number
|
|
66
|
+
/**
|
|
67
|
+
* What the run's latest counted call measured, around the run's rate (see prepareAgentModel):
|
|
68
|
+
* once there is one, the calls after it go by it, as the output ceiling does.
|
|
69
|
+
*/
|
|
70
|
+
readonly measuredBytesPerToken?: () => number | undefined
|
|
71
|
+
/** Tools whose results are never cleared. */
|
|
72
|
+
readonly excludeTools?: readonly string[]
|
|
73
|
+
/**
|
|
74
|
+
* Compacts what comes before the turn, once: the messages the turn's requests start with from
|
|
75
|
+
* then on, in place of those they started with. Undefined when it could not.
|
|
76
|
+
*/
|
|
77
|
+
readonly compact?: CompactConversationBeforeTurn
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface AgentContextGuard {
|
|
81
|
+
/** Before each call: the request, reduced when it would cross the model's limit. */
|
|
82
|
+
readonly prepareStep: (
|
|
83
|
+
input: PrepareModelStepInput
|
|
84
|
+
) => Promise<PrepareModelStepResult | undefined>
|
|
85
|
+
/** After a call the provider rejected as too long for the window: the request reduced to fit. */
|
|
86
|
+
readonly recoverStep: (
|
|
87
|
+
input: RecoverModelStepInput
|
|
88
|
+
) => Promise<PrepareModelStepResult | undefined>
|
|
89
|
+
/**
|
|
90
|
+
* The first step whose request had tool results cleared or cut, which every later one keeps:
|
|
91
|
+
* those steps' usage weighs less than replaying the stored steps sends.
|
|
92
|
+
*/
|
|
93
|
+
readonly reducedFromStep: () => number | undefined
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Keep every request of a model loop under the model's limit (the window less the output reserve),
|
|
98
|
+
* checked before each call from what the last call really read and what was added since. Right
|
|
99
|
+
* before a request would cross it:
|
|
100
|
+
*
|
|
101
|
+
* 1. clear the oldest tool results the model has read in one batch, down to
|
|
102
|
+
* {@link AGENT_CONTEXT_COMPACTED_SHARE} of the limit, when it frees at least a tenth of the
|
|
103
|
+
* limit ({@link CLEARED_AT_LEAST_SHARE}), enough to be worth the cache it breaks: the three most
|
|
104
|
+
* recent stay when clearing the older ones gets there, only the newest when it does not (see
|
|
105
|
+
* {@link KEPT_TOOL_RESULTS}), and the steps after it read the cleared request through;
|
|
106
|
+
* 2. else compact what came before the turn, once, and clear again what is still needed;
|
|
107
|
+
* 3. past the limit even so, clear as many of the results the model has read as it takes, the
|
|
108
|
+
* newest still kept, and cut those it has not read to fit.
|
|
109
|
+
*
|
|
110
|
+
* A result the model asks for again after it was cleared or cut is one the turn needs: it is
|
|
111
|
+
* neither cleared nor cut again, so a turn whose working set does not fit ends on the provider's
|
|
112
|
+
* refusal instead of reading and reducing the same results in turn.
|
|
113
|
+
*
|
|
114
|
+
* A call the provider rejects as too long for the window is measured at the window at least, and
|
|
115
|
+
* reduced the same way, compacting first when it can, for the loop to ask it again once.
|
|
116
|
+
*
|
|
117
|
+
* The first call has no call before it to go by: its whole request is estimated, at the rate the
|
|
118
|
+
* thread measured.
|
|
119
|
+
*/
|
|
120
|
+
export function createAgentContextGuard(input: AgentContextGuardInput): AgentContextGuard {
|
|
121
|
+
const guard = new ContextGuard(input)
|
|
122
|
+
return {
|
|
123
|
+
prepareStep: (step) => guard.prepareStep(step),
|
|
124
|
+
recoverStep: (step) => guard.recoverStep(step),
|
|
125
|
+
reducedFromStep: () => guard.reducedFrom,
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* A cleared tool result's note: the same bytes whenever it replaces that tool's result. A result
|
|
131
|
+
* saved to a file points at the file, which holds the whole of it, rather than at the call.
|
|
132
|
+
*/
|
|
133
|
+
export function clearedToolResultText(toolName: string, savedPath?: string): string {
|
|
134
|
+
return savedPath === undefined
|
|
135
|
+
? `[This ${toolName} result was cleared to fit the model's context. Call the tool again to see it, unless running it again would repeat a change.]`
|
|
136
|
+
: `[This ${toolName} result was cleared to fit the model's context. Its whole output is in ${savedPath}: read it again from there.]`
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** The note that replaces a result the guard clears. */
|
|
140
|
+
function clearedNote(part: ModelToolResultPart): string {
|
|
141
|
+
const text = part.output.type === "text" ? part.output.value : ""
|
|
142
|
+
return clearedToolResultText(part.toolName, savedToolOutputPath(text))
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
class ContextGuard {
|
|
146
|
+
/** How many messages the loop's first request held: what comes before the turn's own steps. */
|
|
147
|
+
private headLength: number | undefined
|
|
148
|
+
/** The request each step sent, by step index: its last attempt's. */
|
|
149
|
+
private readonly sent = new Map<number, readonly ModelMessage[]>()
|
|
150
|
+
/**
|
|
151
|
+
* How much more the provider counts what a turn adds than the estimate does, once a rejection
|
|
152
|
+
* showed it. What the last call read is counted already, and what is removed from it is not
|
|
153
|
+
* scaled.
|
|
154
|
+
*/
|
|
155
|
+
private scale = 1
|
|
156
|
+
private compacted = false
|
|
157
|
+
/** The first step whose request had tool results cleared or cut. */
|
|
158
|
+
reducedFrom: number | undefined
|
|
159
|
+
/** Whether the request `reduce` returned last had tool results cleared or cut. */
|
|
160
|
+
private cleared = false
|
|
161
|
+
/**
|
|
162
|
+
* The calls whose results this run cleared or cut, by tool and input. A result the model asks
|
|
163
|
+
* for again after that is one it needs: it is never cleared or cut again while it is the newest
|
|
164
|
+
* of its call, or the two would take turns forever when the turn's working set does not fit.
|
|
165
|
+
*/
|
|
166
|
+
private readonly reducedCalls = new Map<string, Set<string>>()
|
|
167
|
+
private readonly excluded: ReadonlySet<string>
|
|
168
|
+
/**
|
|
169
|
+
* The densest rate the provider showed for what one of this turn's steps added: the tokens it
|
|
170
|
+
* counted past the call before, against the bytes the step added to that call's request.
|
|
171
|
+
*/
|
|
172
|
+
private densestAdded: number | undefined
|
|
173
|
+
|
|
174
|
+
constructor(private readonly input: AgentContextGuardInput) {
|
|
175
|
+
this.excluded = new Set(input.excludeTools ?? [])
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* The rate what a turn adds is weighed at before the provider counts it: the run's, or denser
|
|
180
|
+
* once a step of this turn showed it. A result of base64 or random identifiers reads three times
|
|
181
|
+
* denser than prose, and its next ones are weighed as it was counted, not as the run reads.
|
|
182
|
+
*/
|
|
183
|
+
private get addedBytesPerToken(): number {
|
|
184
|
+
return Math.min(this.bytesPerToken, this.densestAdded ?? Number.POSITIVE_INFINITY)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Learn what the last step added weighs, from the provider's counts of the last two calls:
|
|
189
|
+
* only when the last call's request kept every message of the one before it, so the difference
|
|
190
|
+
* is what the step added, and when that is enough to tell (see measureAgentContextTokenRate).
|
|
191
|
+
*/
|
|
192
|
+
private learn(steps: readonly ModelStep[]): void {
|
|
193
|
+
const read = steps.at(-1)?.usage.inputTokens
|
|
194
|
+
const readBefore = steps.at(-2)?.usage.inputTokens
|
|
195
|
+
const sent = this.sent.get(steps.length - 1)
|
|
196
|
+
const sentBefore = this.sent.get(steps.length - 2)
|
|
197
|
+
if (!read || !readBefore || !sent || !sentBefore) return
|
|
198
|
+
|
|
199
|
+
const kept = new Set(sent)
|
|
200
|
+
if (sentBefore.some((message) => !kept.has(message))) return
|
|
201
|
+
|
|
202
|
+
const before = new Set(sentBefore)
|
|
203
|
+
const added = sent.filter((message) => !before.has(message))
|
|
204
|
+
const size = measureAgentModelRequest({ messages: added, tools: [] })
|
|
205
|
+
const bare = measureAgentModelRequest({ messages: [], tools: [] })
|
|
206
|
+
const sample = measureAgentContextTokenRate({
|
|
207
|
+
size: { ...size, bytes: size.bytes - bare.bytes, tokens: size.tokens - bare.tokens },
|
|
208
|
+
inputTokens: read - readBefore,
|
|
209
|
+
})
|
|
210
|
+
if (!sample) return
|
|
211
|
+
|
|
212
|
+
const rate = Math.max(AGENT_TOKEN_RATE_MIN_BYTES_PER_TOKEN, sample.bytes / sample.tokens)
|
|
213
|
+
this.densestAdded = Math.min(this.densestAdded ?? rate, rate)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
private get bytesPerToken(): number {
|
|
217
|
+
return (
|
|
218
|
+
this.input.measuredBytesPerToken?.() ??
|
|
219
|
+
this.input.bytesPerToken ??
|
|
220
|
+
this.input.budget.bytesPerToken
|
|
221
|
+
)
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async prepareStep({
|
|
225
|
+
stepIndex,
|
|
226
|
+
messages,
|
|
227
|
+
steps,
|
|
228
|
+
model,
|
|
229
|
+
}: PrepareModelStepInput): Promise<PrepareModelStepResult | undefined> {
|
|
230
|
+
this.headLength ??= messages.length
|
|
231
|
+
this.learn(steps)
|
|
232
|
+
|
|
233
|
+
const tokens = this.weighed(messages, steps)
|
|
234
|
+
const reduced =
|
|
235
|
+
tokens > this.input.budget.inputBudgetTokens
|
|
236
|
+
? await this.reduce(messages, steps, tokens, "threshold")
|
|
237
|
+
: undefined
|
|
238
|
+
|
|
239
|
+
this.record(stepIndex, reduced ?? messages)
|
|
240
|
+
const sent = reduced ?? messages
|
|
241
|
+
return this.sending(reduced, reduced ? this.weighed(sent, steps) : tokens, model, {
|
|
242
|
+
heaviest: this.heaviest(sent, steps),
|
|
243
|
+
})
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async recoverStep({
|
|
247
|
+
stepIndex,
|
|
248
|
+
messages,
|
|
249
|
+
steps,
|
|
250
|
+
model,
|
|
251
|
+
error,
|
|
252
|
+
usage,
|
|
253
|
+
}: RecoverModelStepInput): Promise<PrepareModelStepResult | undefined> {
|
|
254
|
+
if (!(error instanceof ModelProviderError) || error.reason !== "context-window-exceeded") {
|
|
255
|
+
return undefined
|
|
256
|
+
}
|
|
257
|
+
this.headLength ??= messages.length
|
|
258
|
+
|
|
259
|
+
// What the estimate missed is in what was added since the last call the provider read: that
|
|
260
|
+
// part is counted from now on at the rate that makes the request weigh what the provider
|
|
261
|
+
// counted, when the call says (its answer filled the window), else the window at least.
|
|
262
|
+
const { windowTokens } = this.input.budget
|
|
263
|
+
const read = usage?.inputTokens
|
|
264
|
+
const counted = read !== undefined && read > 0 ? read : windowTokens
|
|
265
|
+
const { fixed, removed, added } = this.measure(messages, steps)
|
|
266
|
+
if (added > 0 && counted > fixed - removed) {
|
|
267
|
+
this.scale = Math.max(this.scale, (counted - fixed + removed) / added)
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const reduced = await this.reduce(
|
|
271
|
+
messages,
|
|
272
|
+
steps,
|
|
273
|
+
Math.max(counted, this.projectedTokens(messages, steps)),
|
|
274
|
+
"overflow"
|
|
275
|
+
)
|
|
276
|
+
if (!reduced) return undefined
|
|
277
|
+
|
|
278
|
+
this.record(stepIndex, reduced)
|
|
279
|
+
return this.sending(reduced, this.weighed(reduced, steps), model, {
|
|
280
|
+
heaviest: this.heaviest(reduced, steps),
|
|
281
|
+
askedAgain: true,
|
|
282
|
+
})
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* What a request weighs before the guard sends it: its projection, and a margin on the growth
|
|
287
|
+
* since the last call, which the estimate may miss. The first call has none to go by: its whole
|
|
288
|
+
* request is estimated, at the rate the thread measured, as its preflight weighed it.
|
|
289
|
+
*/
|
|
290
|
+
private weighed(messages: readonly ModelMessage[], steps: readonly ModelStep[]): number {
|
|
291
|
+
const { fixed, added } = this.measure(messages, steps)
|
|
292
|
+
const margin = fixed > 0 ? Math.ceil(added * this.scale * GROWTH_MARGIN) : 0
|
|
293
|
+
return this.projectedTokens(messages, steps) + margin
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* The most a request may weigh: what the last call read, less what was removed, and what was
|
|
298
|
+
* added since at one byte a token, the densest any tokenizer reads. Without a call to go by, its
|
|
299
|
+
* whole estimate, and the share an estimate may miss (GROWTH_MARGIN): at one byte a token it
|
|
300
|
+
* would leave a first call little more than the reserve, whatever the turn reads. An estimate
|
|
301
|
+
* at the thread's own rate has run about 1 % short of the provider's count.
|
|
302
|
+
*/
|
|
303
|
+
private heaviest(messages: readonly ModelMessage[], steps: readonly ModelStep[]): number {
|
|
304
|
+
const { fixed, removed, added } = this.measure(
|
|
305
|
+
messages,
|
|
306
|
+
steps,
|
|
307
|
+
AGENT_TOKEN_RATE_MIN_BYTES_PER_TOKEN
|
|
308
|
+
)
|
|
309
|
+
if (fixed > 0) return fixed - removed + Math.ceil(added * this.scale)
|
|
310
|
+
|
|
311
|
+
const tokens = this.weighed(messages, steps)
|
|
312
|
+
return tokens + Math.ceil(tokens * GROWTH_MARGIN)
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* The step's request as it goes out, with the room its answer has: what its input leaves of the
|
|
317
|
+
* window, the one measure the model's output ceiling sizes an answer by too (the step's
|
|
318
|
+
* allowance is the smaller of the two). The guard's is the better weight: anchored on what the
|
|
319
|
+
* provider counted, and at the density the turn's additions showed.
|
|
320
|
+
*
|
|
321
|
+
* Within the limit, the room is sized for the most the input may weigh short of the limit: what
|
|
322
|
+
* the turn added since the last call, at one byte a token, so a first dense result whose density
|
|
323
|
+
* the turn has not measured yet still leaves input and answer within the window. The reserve
|
|
324
|
+
* stays its least, as the limit guarantees it.
|
|
325
|
+
*
|
|
326
|
+
* Past the limit, nothing more could be reduced: its answer gets only the room its input leaves,
|
|
327
|
+
* and a request left less than an answer is worth (see agentMinimumAnswerTokens) is not sent: it
|
|
328
|
+
* fails as the provider's refusal would, which ends the turn with the context error rather than a
|
|
329
|
+
* call cut off at once.
|
|
330
|
+
*/
|
|
331
|
+
private sending(
|
|
332
|
+
reduced: readonly ModelMessage[] | undefined,
|
|
333
|
+
tokens: number,
|
|
334
|
+
model: LanguageModel,
|
|
335
|
+
weight: { readonly heaviest: number; readonly askedAgain?: boolean }
|
|
336
|
+
): PrepareModelStepResult {
|
|
337
|
+
const { budget } = this.input
|
|
338
|
+
const messages = reduced ? { messages: reduced } : {}
|
|
339
|
+
if (tokens <= budget.inputBudgetTokens) {
|
|
340
|
+
const atMost = Math.max(tokens, Math.min(weight.heaviest, budget.inputBudgetTokens))
|
|
341
|
+
return {
|
|
342
|
+
...messages,
|
|
343
|
+
maxOutputTokens: agentOutputRoomTokens(atMost, budget, Number.POSITIVE_INFINITY),
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const room = agentOutputRoomTokens(tokens, budget, Number.POSITIVE_INFINITY)
|
|
348
|
+
const minimum = agentMinimumAnswerTokens(budget)
|
|
349
|
+
// A call the provider refused is asked again once, whatever the guard weighs it at: after a
|
|
350
|
+
// refusal, what it weighs leans on the window as the least the provider counted, and the
|
|
351
|
+
// provider's own count of the reduced request decides.
|
|
352
|
+
if (weight.askedAgain && room < minimum) return { ...messages, maxOutputTokens: minimum }
|
|
353
|
+
if (room < minimum) {
|
|
354
|
+
throw new ModelProviderError(
|
|
355
|
+
`[SixbAgent] The request leaves no room in the model's ${budget.windowTokens.toLocaleString("en-US")}-token context window for an answer, and nothing more of it can be cleared or summarized.`,
|
|
356
|
+
model.providerId,
|
|
357
|
+
model.modelId,
|
|
358
|
+
{ reason: "context-window-exceeded" }
|
|
359
|
+
)
|
|
360
|
+
}
|
|
361
|
+
return { ...messages, maxOutputTokens: room }
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** The request a step sends, and from which step on the requests are reduced. */
|
|
365
|
+
private record(stepIndex: number, messages: readonly ModelMessage[]): void {
|
|
366
|
+
this.sent.set(stepIndex, messages)
|
|
367
|
+
if (this.cleared) this.reducedFrom ??= stepIndex
|
|
368
|
+
this.cleared = false
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* Bring `messages` under the model's limit, else as close as clearing, compaction and cutting
|
|
373
|
+
* go. Undefined when nothing was worth changing.
|
|
374
|
+
*/
|
|
375
|
+
private async reduce(
|
|
376
|
+
messages: readonly ModelMessage[],
|
|
377
|
+
steps: readonly ModelStep[],
|
|
378
|
+
tokens: number,
|
|
379
|
+
reason: AgentContextCheckpointReason
|
|
380
|
+
): Promise<readonly ModelMessage[] | undefined> {
|
|
381
|
+
const limitTokens = this.input.budget.inputBudgetTokens
|
|
382
|
+
const aimTokens = Math.floor(limitTokens * AGENT_CONTEXT_COMPACTED_SHARE)
|
|
383
|
+
const clearAtLeast = Math.ceil(limitTokens * CLEARED_AT_LEAST_SHARE)
|
|
384
|
+
const overflow = reason === "overflow"
|
|
385
|
+
this.cleared = false
|
|
386
|
+
|
|
387
|
+
// 1. A threshold crossed is first met by clearing what the model has read already. A request
|
|
388
|
+
// the provider rejected compacts first: the estimate it was sent on was wrong.
|
|
389
|
+
if (!overflow) {
|
|
390
|
+
const cleared = this.clear(messages, steps, tokens - aimTokens)
|
|
391
|
+
if (cleared.tokens >= clearAtLeast && tokens - cleared.tokens <= limitTokens) {
|
|
392
|
+
this.cleared = true
|
|
393
|
+
this.remember(cleared.calls)
|
|
394
|
+
return cleared.messages
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// 2. Compacting summarizes what came before the turn; the turn stays as it is.
|
|
399
|
+
let current = messages
|
|
400
|
+
let currentTokens = tokens
|
|
401
|
+
if (this.input.compact && !this.compacted) {
|
|
402
|
+
this.compacted = true
|
|
403
|
+
const head = await this.input.compact({ reason })
|
|
404
|
+
if (head) {
|
|
405
|
+
current = [...head, ...messages.slice(this.headLength)]
|
|
406
|
+
this.headLength = head.length
|
|
407
|
+
currentTokens = this.projectedTokens(current, steps)
|
|
408
|
+
if (currentTokens <= limitTokens) return current
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// 3. What is left of the turn: its results the model has read, cleared in one batch when it
|
|
413
|
+
// frees enough to be worth the cache it breaks, and whatever it frees past the limit or
|
|
414
|
+
// when the provider refused the request.
|
|
415
|
+
const cleared = this.clear(current, steps, currentTokens - aimTokens)
|
|
416
|
+
if (overflow || cleared.tokens >= clearAtLeast || currentTokens > limitTokens) {
|
|
417
|
+
if (cleared.messages !== current) this.cleared = true
|
|
418
|
+
this.remember(cleared.calls)
|
|
419
|
+
current = cleared.messages
|
|
420
|
+
currentTokens = this.projectedTokens(current, steps)
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// Past the limit even so, the results the model has not read are cut to fit it.
|
|
424
|
+
if (currentTokens > limitTokens) {
|
|
425
|
+
const cut = this.cutUnread(current, currentTokens - limitTokens)
|
|
426
|
+
if (cut.messages !== current) this.cleared = true
|
|
427
|
+
this.remember(cut.calls)
|
|
428
|
+
current = cut.messages
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
return current === messages ? undefined : current
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* The oldest tool results the model has read, cleared until `neededTokens` are freed or only
|
|
436
|
+
* the most recent {@link KEPT_TOOL_RESULTS} is left, and the calls they answered. A result the
|
|
437
|
+
* model asked for again after this run cleared or cut it stays.
|
|
438
|
+
*/
|
|
439
|
+
private clear(
|
|
440
|
+
messages: readonly ModelMessage[],
|
|
441
|
+
steps: readonly ModelStep[],
|
|
442
|
+
neededTokens: number
|
|
443
|
+
): {
|
|
444
|
+
readonly messages: readonly ModelMessage[]
|
|
445
|
+
readonly tokens: number
|
|
446
|
+
readonly calls: readonly ReducedCall[]
|
|
447
|
+
} {
|
|
448
|
+
const counted = this.countedMessages(steps)
|
|
449
|
+
const calls = toolCallKeys(messages)
|
|
450
|
+
const read = messages.map((message) => message.role).lastIndexOf("assistant")
|
|
451
|
+
const candidates: {
|
|
452
|
+
readonly message: number
|
|
453
|
+
readonly part: number
|
|
454
|
+
readonly gain: number
|
|
455
|
+
readonly call: ReducedCall | undefined
|
|
456
|
+
}[] = []
|
|
457
|
+
for (const [index, message] of messages.entries()) {
|
|
458
|
+
if (index >= read || message.role !== "tool") continue
|
|
459
|
+
|
|
460
|
+
for (const [partIndex, part] of message.content.entries()) {
|
|
461
|
+
const bytes = clearableBytes(part)
|
|
462
|
+
if (bytes === undefined || this.excluded.has(part.toolName)) continue
|
|
463
|
+
|
|
464
|
+
if (this.needed(calls, part.toolCallId)) continue
|
|
465
|
+
|
|
466
|
+
const placeholder = utf8Bytes(clearedNote(part))
|
|
467
|
+
candidates.push({
|
|
468
|
+
message: index,
|
|
469
|
+
part: partIndex,
|
|
470
|
+
gain: this.tokensOf(bytes - placeholder, !counted.has(message)),
|
|
471
|
+
call: reducedCall(calls, part.toolCallId),
|
|
472
|
+
})
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
const chosen = new Map<number, Set<number>>()
|
|
477
|
+
const chosenCalls: ReducedCall[] = []
|
|
478
|
+
let tokens = 0
|
|
479
|
+
for (const candidate of candidates.slice(0, -KEPT_TOOL_RESULTS)) {
|
|
480
|
+
if (tokens >= neededTokens) break
|
|
481
|
+
|
|
482
|
+
tokens += candidate.gain
|
|
483
|
+
const parts = chosen.get(candidate.message) ?? new Set<number>()
|
|
484
|
+
parts.add(candidate.part)
|
|
485
|
+
chosen.set(candidate.message, parts)
|
|
486
|
+
if (candidate.call !== undefined) chosenCalls.push(candidate.call)
|
|
487
|
+
}
|
|
488
|
+
if (chosen.size === 0) return { messages, tokens: 0, calls: [] }
|
|
489
|
+
|
|
490
|
+
return {
|
|
491
|
+
tokens,
|
|
492
|
+
calls: chosenCalls,
|
|
493
|
+
messages: replaceToolResults(messages, chosen, (part) => ({
|
|
494
|
+
...withoutOriginalOutput(part),
|
|
495
|
+
output: { type: "text", value: clearedNote(part) },
|
|
496
|
+
})),
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* The results of the step the model has not read yet, each cut to the same length, halved
|
|
502
|
+
* until `excessTokens` are freed: they are the turn's newest work, so the model reads what fits
|
|
503
|
+
* of each and learns how to read the rest. One it asked for again after it was cleared or cut
|
|
504
|
+
* stays whole: what the turn needs then does not fit, and the provider's refusal ends the turn.
|
|
505
|
+
*/
|
|
506
|
+
private cutUnread(
|
|
507
|
+
messages: readonly ModelMessage[],
|
|
508
|
+
excessTokens: number
|
|
509
|
+
): { readonly messages: readonly ModelMessage[]; readonly calls: readonly ReducedCall[] } {
|
|
510
|
+
const calls = toolCallKeys(messages)
|
|
511
|
+
const inputs = toolCallInputs(messages)
|
|
512
|
+
const read = messages.map((message) => message.role).lastIndexOf("assistant")
|
|
513
|
+
const unread = new Map<number, Set<number>>()
|
|
514
|
+
let longest = 0
|
|
515
|
+
for (const [index, message] of messages.entries()) {
|
|
516
|
+
if (index <= read || message.role !== "tool") continue
|
|
517
|
+
|
|
518
|
+
for (const [partIndex, part] of message.content.entries()) {
|
|
519
|
+
const bytes = clearableBytes(part)
|
|
520
|
+
if (bytes === undefined) continue
|
|
521
|
+
|
|
522
|
+
if (this.needed(calls, part.toolCallId)) continue
|
|
523
|
+
|
|
524
|
+
longest = Math.max(longest, bytes)
|
|
525
|
+
const parts = unread.get(index) ?? new Set<number>()
|
|
526
|
+
parts.add(partIndex)
|
|
527
|
+
unread.set(index, parts)
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
let maxBytes = Math.floor(longest / 2)
|
|
532
|
+
let cut = messages
|
|
533
|
+
let cutCalls: ReducedCall[] = []
|
|
534
|
+
while (maxBytes >= CUT_MIN_BYTES) {
|
|
535
|
+
let freed = 0
|
|
536
|
+
const limit = maxBytes
|
|
537
|
+
const calledFor: ReducedCall[] = []
|
|
538
|
+
cut = replaceToolResults(messages, unread, (part) => {
|
|
539
|
+
const text = toolResultText(part)
|
|
540
|
+
const kept = cutToolResult(part, limit, inputs.get(part.toolCallId))
|
|
541
|
+
const call = reducedCall(calls, part.toolCallId)
|
|
542
|
+
if (kept !== text && call) calledFor.push(call)
|
|
543
|
+
|
|
544
|
+
freed += this.tokensOf(utf8Bytes(text) - utf8Bytes(kept), true)
|
|
545
|
+
return { ...withoutOriginalOutput(part), output: { type: "text", value: kept } }
|
|
546
|
+
})
|
|
547
|
+
cutCalls = calledFor
|
|
548
|
+
if (freed >= excessTokens) break
|
|
549
|
+
|
|
550
|
+
maxBytes = Math.floor(maxBytes / 2)
|
|
551
|
+
}
|
|
552
|
+
return { messages: cut, calls: cutCalls }
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/** Remember the calls whose results were cleared or cut. */
|
|
556
|
+
private remember(calls: readonly ReducedCall[]): void {
|
|
557
|
+
for (const { key, toolCallId } of calls) {
|
|
558
|
+
const reduced = this.reducedCalls.get(key) ?? new Set<string>()
|
|
559
|
+
reduced.add(toolCallId)
|
|
560
|
+
this.reducedCalls.set(key, reduced)
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* Whether the model asked for this result again after the run cleared or cut another's, and it
|
|
566
|
+
* is the newest of its call. An older copy is superseded by the newer one: a command the model
|
|
567
|
+
* runs again and again (a status it polls, a listing) leaves every copy but the last clearable.
|
|
568
|
+
*/
|
|
569
|
+
private needed(calls: ReadonlyMap<string, string>, toolCallId: string): boolean {
|
|
570
|
+
const key = calls.get(toolCallId)
|
|
571
|
+
const reduced = key === undefined ? undefined : this.reducedCalls.get(key)
|
|
572
|
+
if (reduced === undefined || reduced.has(toolCallId)) return false
|
|
573
|
+
|
|
574
|
+
// In message order: the last call with the key is its newest.
|
|
575
|
+
let newest: string | undefined
|
|
576
|
+
for (const [id, other] of calls) {
|
|
577
|
+
if (other === key) newest = id
|
|
578
|
+
}
|
|
579
|
+
return newest === toolCallId
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* What `messages` weigh as a request: what the last call really read, less what was removed
|
|
584
|
+
* from its request, plus what was added since at the scaled rate. Without a call to go by, the
|
|
585
|
+
* whole request is estimated, at that rate.
|
|
586
|
+
*/
|
|
587
|
+
private projectedTokens(messages: readonly ModelMessage[], steps: readonly ModelStep[]): number {
|
|
588
|
+
const { fixed, removed, added } = this.measure(messages, steps)
|
|
589
|
+
return fixed - removed + Math.ceil(added * this.scale)
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* What the last call read, then the unscaled estimates of the messages its request held that
|
|
594
|
+
* `messages` no longer do, and of those it adds. Messages are compared by identity: the loop
|
|
595
|
+
* keeps the ones it sends again, and a message cleared or compacted is a new one. What it adds
|
|
596
|
+
* weighs at the rate what the turn adds is (see addedBytesPerToken), what it removes at the
|
|
597
|
+
* run's: the provider counted it already, and subtracting too little is the safe side.
|
|
598
|
+
*/
|
|
599
|
+
private measure(
|
|
600
|
+
messages: readonly ModelMessage[],
|
|
601
|
+
steps: readonly ModelStep[],
|
|
602
|
+
addedBytesPerToken = this.addedBytesPerToken
|
|
603
|
+
): { readonly fixed: number; readonly removed: number; readonly added: number } {
|
|
604
|
+
const read = steps.at(-1)?.usage.inputTokens
|
|
605
|
+
const sent = this.sent.get(steps.length - 1)
|
|
606
|
+
if (read === undefined || read <= 0 || sent === undefined) {
|
|
607
|
+
return { fixed: 0, removed: 0, added: this.rawEstimate(messages) }
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
const before = new Set(sent)
|
|
611
|
+
const after = new Set(messages)
|
|
612
|
+
const weigh = (
|
|
613
|
+
list: readonly ModelMessage[],
|
|
614
|
+
kept: ReadonlySet<ModelMessage>,
|
|
615
|
+
bytesPerToken: number
|
|
616
|
+
) =>
|
|
617
|
+
list.reduce(
|
|
618
|
+
(total, message) => total + (kept.has(message) ? 0 : this.weight(message, bytesPerToken)),
|
|
619
|
+
0
|
|
620
|
+
)
|
|
621
|
+
return {
|
|
622
|
+
fixed: read,
|
|
623
|
+
removed: weigh(sent, after, this.bytesPerToken),
|
|
624
|
+
added: weigh(messages, before, addedBytesPerToken),
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
/** The messages of the last request the provider counted, which their real tokens include. */
|
|
629
|
+
private countedMessages(steps: readonly ModelStep[]): ReadonlySet<ModelMessage> {
|
|
630
|
+
const read = steps.at(-1)?.usage.inputTokens
|
|
631
|
+
const sent = this.sent.get(steps.length - 1)
|
|
632
|
+
return read !== undefined && read > 0 && sent ? new Set(sent) : new Set()
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
private rawEstimate(messages: readonly ModelMessage[]): number {
|
|
636
|
+
return estimateAgentRequestTokens({ messages, tools: this.input.tools }, this.bytesPerToken)
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/** One message's estimate at `bytesPerToken`, without the request's own overhead. */
|
|
640
|
+
private weight(message: ModelMessage, bytesPerToken: number): number {
|
|
641
|
+
return (
|
|
642
|
+
estimateAgentRequestTokens({ messages: [message], tools: [] }, bytesPerToken) -
|
|
643
|
+
estimateAgentRequestTokens({ messages: [], tools: [] }, bytesPerToken)
|
|
644
|
+
)
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* `bytes` as tokens: at the scaled rate of what the turn adds when the provider has not counted
|
|
649
|
+
* them yet, else at the run's.
|
|
650
|
+
*/
|
|
651
|
+
private tokensOf(bytes: number, added: boolean): number {
|
|
652
|
+
const tokens = added
|
|
653
|
+
? (bytes / this.addedBytesPerToken) * this.scale
|
|
654
|
+
: bytes / this.bytesPerToken
|
|
655
|
+
return Math.max(0, Math.ceil(tokens))
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/** A call whose result was cleared or cut: what it asked, and which call it was. */
|
|
660
|
+
interface ReducedCall {
|
|
661
|
+
readonly key: string
|
|
662
|
+
readonly toolCallId: string
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
function reducedCall(
|
|
666
|
+
calls: ReadonlyMap<string, string>,
|
|
667
|
+
toolCallId: string
|
|
668
|
+
): ReducedCall | undefined {
|
|
669
|
+
const key = calls.get(toolCallId)
|
|
670
|
+
return key === undefined ? undefined : { key, toolCallId }
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/** What each call in `messages` asked, by its id: its tool and its input. */
|
|
674
|
+
/** What each tool call of `messages` was called with, by its id. */
|
|
675
|
+
function toolCallInputs(messages: readonly ModelMessage[]): ReadonlyMap<string, JsonValue> {
|
|
676
|
+
const inputs = new Map<string, JsonValue>()
|
|
677
|
+
for (const message of messages) {
|
|
678
|
+
if (message.role !== "assistant") continue
|
|
679
|
+
|
|
680
|
+
for (const part of message.content) {
|
|
681
|
+
if (part.type === "tool-call") inputs.set(part.toolCallId, part.input)
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
return inputs
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
function toolCallKeys(messages: readonly ModelMessage[]): ReadonlyMap<string, string> {
|
|
688
|
+
const keys = new Map<string, string>()
|
|
689
|
+
for (const message of messages) {
|
|
690
|
+
if (message.role !== "assistant") continue
|
|
691
|
+
|
|
692
|
+
for (const part of message.content) {
|
|
693
|
+
if (part.type !== "tool-call") continue
|
|
694
|
+
|
|
695
|
+
keys.set(part.toolCallId, `${part.toolName}\u0000${stableJsonStringify(part.input)}`)
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
return keys
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
/** What a result weighs when clearing it is worth it: text or JSON past the note's own size. */
|
|
702
|
+
function clearableBytes(part: ModelToolResultPart): number | undefined {
|
|
703
|
+
if (part.providerExecuted) return undefined
|
|
704
|
+
if (part.output.type !== "text" && part.output.type !== "json") return undefined
|
|
705
|
+
|
|
706
|
+
const text = toolResultText(part)
|
|
707
|
+
if (text === clearedToolResultText(part.toolName)) return undefined
|
|
708
|
+
|
|
709
|
+
const bytes = utf8Bytes(text)
|
|
710
|
+
return bytes >= CLEARED_MIN_BYTES ? bytes : undefined
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
function toolResultText(part: ModelToolResultPart): string {
|
|
714
|
+
return typeof part.output.value === "string"
|
|
715
|
+
? part.output.value
|
|
716
|
+
: stableJsonStringify(part.output.value)
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/** The text up to its last line within `maxBytes`, saying how much was left out. */
|
|
720
|
+
/**
|
|
721
|
+
* A tool result cut to about `maxBytes`, with a note on how to read the rest. A `read` of a file
|
|
722
|
+
* shows whole lines and names the path and the line to go on from, as the read tool pages: a
|
|
723
|
+
* vaguer note once left a model reading files that did not exist rather than the rest of its own.
|
|
724
|
+
* A `view_file` names its file, to page through with read. Any other is called again for less.
|
|
725
|
+
*/
|
|
726
|
+
function cutToolResult(
|
|
727
|
+
part: ModelToolResultPart,
|
|
728
|
+
maxBytes: number,
|
|
729
|
+
input: JsonValue | undefined
|
|
730
|
+
): string {
|
|
731
|
+
const text = toolResultText(part)
|
|
732
|
+
if (utf8Bytes(text) <= maxBytes) return text
|
|
733
|
+
|
|
734
|
+
const page = part.toolName === "read" ? readPage(part) : undefined
|
|
735
|
+
if (page) return cutReadPage(page, maxBytes)
|
|
736
|
+
|
|
737
|
+
const path = isJsonObject(input) && typeof input.path === "string" ? input.path : undefined
|
|
738
|
+
const rest =
|
|
739
|
+
part.toolName === "view_file" && path !== undefined
|
|
740
|
+
? `Read the rest with read({ path: ${JSON.stringify(path)} }), which pages through the file.`
|
|
741
|
+
: `Call ${part.toolName} again for a smaller part to read the rest.`
|
|
742
|
+
const kept = cutLines(text, maxBytes)
|
|
743
|
+
const omitted = utf8Bytes(text) - utf8Bytes(kept)
|
|
744
|
+
return `${kept}\n[Cut to fit the model's context: ${omitted.toLocaleString("en-US")} more bytes. ${rest}]`
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
/** A read tool's page of a file: its lines `startLine` to `endLine`. */
|
|
748
|
+
interface ReadPage {
|
|
749
|
+
readonly path: string
|
|
750
|
+
readonly content: string
|
|
751
|
+
readonly startLine: number
|
|
752
|
+
readonly endLine: number
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
function readPage(part: ModelToolResultPart): ReadPage | undefined {
|
|
756
|
+
if (part.output.type !== "json" || !isJsonObject(part.output.value)) return undefined
|
|
757
|
+
|
|
758
|
+
const { path, content, startLine, endLine } = part.output.value
|
|
759
|
+
if (typeof path !== "string" || typeof content !== "string") return undefined
|
|
760
|
+
if (typeof startLine !== "number" || typeof endLine !== "number") return undefined
|
|
761
|
+
return { path, content, startLine, endLine }
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
/** The page's first lines that fit, and the read call that shows the next. */
|
|
765
|
+
function cutReadPage(page: ReadPage, maxBytes: number): string {
|
|
766
|
+
const lines = page.content.split("\n")
|
|
767
|
+
let bytes = 0
|
|
768
|
+
let count = 0
|
|
769
|
+
for (const line of lines) {
|
|
770
|
+
bytes += utf8Bytes(line) + 1
|
|
771
|
+
if (bytes > maxBytes) break
|
|
772
|
+
count += 1
|
|
773
|
+
}
|
|
774
|
+
const range = (from: number, to: number) =>
|
|
775
|
+
`${from.toLocaleString("en-US")}–${to.toLocaleString("en-US")}`
|
|
776
|
+
|
|
777
|
+
// A first line longer than fits is shown in part, and the rest goes on from the next line.
|
|
778
|
+
const lastShown = page.startLine + Math.max(count, 1) - 1
|
|
779
|
+
const kept = count > 0 ? lines.slice(0, count).join("\n") : cutLines(lines[0] ?? "", maxBytes)
|
|
780
|
+
const shown =
|
|
781
|
+
count > 0
|
|
782
|
+
? `lines ${range(page.startLine, lastShown)} of ${range(page.startLine, page.endLine)} shown`
|
|
783
|
+
: `line ${page.startLine.toLocaleString("en-US")} shown in part`
|
|
784
|
+
const next = `read({ path: ${JSON.stringify(page.path)}, offset: ${lastShown + 1} })`
|
|
785
|
+
|
|
786
|
+
return `${kept}\n[Cut to fit the model's context: ${shown}. Read the rest with ${next}.]`
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/** `text`'s whole lines that fit `maxBytes`, or as much of its first line. */
|
|
790
|
+
function cutLines(text: string, maxBytes: number): string {
|
|
791
|
+
const bytes = new TextEncoder().encode(text)
|
|
792
|
+
if (bytes.byteLength <= maxBytes) return text
|
|
793
|
+
|
|
794
|
+
// A cut inside a multi-byte character drops it.
|
|
795
|
+
const head = new TextDecoder().decode(bytes.slice(0, maxBytes)).replace(/�$/, "")
|
|
796
|
+
const lastLine = head.lastIndexOf("\n")
|
|
797
|
+
return (lastLine > 0 ? head.slice(0, lastLine) : head).trimEnd()
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
/** `messages` with the chosen tool results replaced, every other message as it was. */
|
|
801
|
+
function replaceToolResults(
|
|
802
|
+
messages: readonly ModelMessage[],
|
|
803
|
+
chosen: ReadonlyMap<number, ReadonlySet<number>>,
|
|
804
|
+
replace: (part: ModelToolResultPart) => ModelToolResultPart
|
|
805
|
+
): readonly ModelMessage[] {
|
|
806
|
+
return messages.map((message, index) => {
|
|
807
|
+
const parts = chosen.get(index)
|
|
808
|
+
if (!parts || message.role !== "tool") return message
|
|
809
|
+
|
|
810
|
+
return {
|
|
811
|
+
role: "tool",
|
|
812
|
+
content: message.content.map((part, partIndex) =>
|
|
813
|
+
parts.has(partIndex) ? replace(part) : part
|
|
814
|
+
),
|
|
815
|
+
}
|
|
816
|
+
})
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
function withoutOriginalOutput(part: ModelToolResultPart): ModelToolResultPart {
|
|
820
|
+
const { originalOutput: _originalOutput, ...rest } = part
|
|
821
|
+
return rest
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
function utf8Bytes(value: string): number {
|
|
825
|
+
return new TextEncoder().encode(value).byteLength
|
|
826
|
+
}
|