@namzu/sdk 73.0.0 → 74.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +56 -0
- package/README.md +34 -34
- package/dist/authorization/protected-paths.d.ts +7 -0
- package/dist/authorization/protected-paths.d.ts.map +1 -1
- package/dist/authorization/protected-paths.js +7 -0
- package/dist/authorization/protected-paths.js.map +1 -1
- package/dist/authorization/readonly-commands.d.ts +23 -0
- package/dist/authorization/readonly-commands.d.ts.map +1 -1
- package/dist/authorization/readonly-commands.js +89 -3
- package/dist/authorization/readonly-commands.js.map +1 -1
- package/dist/authorization/shell-paths.d.ts +8 -0
- package/dist/authorization/shell-paths.d.ts.map +1 -1
- package/dist/authorization/shell-paths.js +125 -2
- package/dist/authorization/shell-paths.js.map +1 -1
- package/dist/bridge/acp/permission.d.ts +6 -0
- package/dist/bridge/acp/permission.d.ts.map +1 -1
- package/dist/bridge/acp/permission.js.map +1 -1
- package/dist/bridge/acp/server.d.ts.map +1 -1
- package/dist/bridge/acp/server.js +21 -3
- package/dist/bridge/acp/server.js.map +1 -1
- package/dist/compaction/context-window.d.ts.map +1 -1
- package/dist/compaction/context-window.js +11 -0
- package/dist/compaction/context-window.js.map +1 -1
- package/dist/compaction/manual.d.ts.map +1 -1
- package/dist/compaction/manual.js +15 -8
- package/dist/compaction/manual.js.map +1 -1
- package/dist/compaction/plan.d.ts +2 -1
- package/dist/compaction/plan.d.ts.map +1 -1
- package/dist/compaction/plan.js +6 -5
- package/dist/compaction/plan.js.map +1 -1
- package/dist/compaction/retained-images.d.ts +16 -0
- package/dist/compaction/retained-images.d.ts.map +1 -0
- package/dist/compaction/retained-images.js +113 -0
- package/dist/compaction/retained-images.js.map +1 -0
- package/dist/compaction/token-estimate.d.ts +8 -3
- package/dist/compaction/token-estimate.d.ts.map +1 -1
- package/dist/compaction/token-estimate.js +76 -8
- package/dist/compaction/token-estimate.js.map +1 -1
- package/dist/compaction/tool-result-editing.d.ts.map +1 -1
- package/dist/compaction/tool-result-editing.js +15 -8
- package/dist/compaction/tool-result-editing.js.map +1 -1
- package/dist/config/runtime.d.ts +3 -3
- package/dist/constants/acp/index.d.ts +2 -0
- package/dist/constants/acp/index.d.ts.map +1 -1
- package/dist/constants/acp/index.js +2 -0
- package/dist/constants/acp/index.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/manager/session/turn-recorder.d.ts +1 -0
- package/dist/manager/session/turn-recorder.d.ts.map +1 -1
- package/dist/manager/session/turn-recorder.js +31 -7
- package/dist/manager/session/turn-recorder.js.map +1 -1
- package/dist/pricing/catalogue.generated.d.ts.map +1 -1
- package/dist/pricing/catalogue.generated.js +353 -21
- package/dist/pricing/catalogue.generated.js.map +1 -1
- package/dist/provider/attribution.js +1 -1
- package/dist/provider/attribution.js.map +1 -1
- package/dist/public-runtime.d.ts +5 -2
- package/dist/public-runtime.d.ts.map +1 -1
- package/dist/public-runtime.js +8 -1
- package/dist/public-runtime.js.map +1 -1
- package/dist/rag/embedding.d.ts +5 -1
- package/dist/rag/embedding.d.ts.map +1 -1
- package/dist/rag/embedding.js +22 -7
- package/dist/rag/embedding.js.map +1 -1
- package/dist/runtime/query/abandon-turn.d.ts.map +1 -1
- package/dist/runtime/query/abandon-turn.js +9 -0
- package/dist/runtime/query/abandon-turn.js.map +1 -1
- package/dist/runtime/query/compact-session.d.ts +10 -3
- package/dist/runtime/query/compact-session.d.ts.map +1 -1
- package/dist/runtime/query/compact-session.js +24 -14
- package/dist/runtime/query/compact-session.js.map +1 -1
- package/dist/runtime/query/guard.d.ts.map +1 -1
- package/dist/runtime/query/guard.js +12 -2
- package/dist/runtime/query/guard.js.map +1 -1
- package/dist/runtime/query/index.d.ts.map +1 -1
- package/dist/runtime/query/index.js +2 -0
- package/dist/runtime/query/index.js.map +1 -1
- package/dist/runtime/query/iteration/index.d.ts +3 -0
- package/dist/runtime/query/iteration/index.d.ts.map +1 -1
- package/dist/runtime/query/iteration/index.js +46 -11
- package/dist/runtime/query/iteration/index.js.map +1 -1
- package/dist/runtime/query/iteration/phases/advisory.js +2 -2
- package/dist/runtime/query/iteration/phases/advisory.js.map +1 -1
- package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
- package/dist/runtime/query/iteration/phases/compaction.js +60 -5
- package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
- package/dist/runtime/query/iteration/phases/context.d.ts +2 -0
- package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
- package/dist/runtime/query/iteration/phases/context.js +1 -0
- package/dist/runtime/query/iteration/phases/context.js.map +1 -1
- package/dist/runtime/query/iteration/request-prefix.d.ts +21 -0
- package/dist/runtime/query/iteration/request-prefix.d.ts.map +1 -0
- package/dist/runtime/query/iteration/request-prefix.js +111 -0
- package/dist/runtime/query/iteration/request-prefix.js.map +1 -0
- package/dist/runtime/query/prepare-turn.d.ts.map +1 -1
- package/dist/runtime/query/prepare-turn.js +1 -1
- package/dist/runtime/query/prepare-turn.js.map +1 -1
- package/dist/runtime/query/review-policy.d.ts +11 -3
- package/dist/runtime/query/review-policy.d.ts.map +1 -1
- package/dist/runtime/query/review-policy.js +54 -3
- package/dist/runtime/query/review-policy.js.map +1 -1
- package/dist/sandbox/exec-stdin.d.ts +21 -0
- package/dist/sandbox/exec-stdin.d.ts.map +1 -0
- package/dist/sandbox/exec-stdin.js +40 -0
- package/dist/sandbox/exec-stdin.js.map +1 -0
- package/dist/sandbox/file-walk-program.js +1 -1
- package/dist/sandbox/file-walk.d.ts +12 -7
- package/dist/sandbox/file-walk.d.ts.map +1 -1
- package/dist/sandbox/file-walk.js +13 -4
- package/dist/sandbox/file-walk.js.map +1 -1
- package/dist/sandbox/ignore-matcher.d.ts +3 -0
- package/dist/sandbox/ignore-matcher.d.ts.map +1 -1
- package/dist/sandbox/ignore-matcher.js +8 -2
- package/dist/sandbox/ignore-matcher.js.map +1 -1
- package/dist/sandbox/ignore-source.d.ts.map +1 -1
- package/dist/sandbox/ignore-source.js +52 -8
- package/dist/sandbox/ignore-source.js.map +1 -1
- package/dist/sandbox/index.d.ts +3 -2
- package/dist/sandbox/index.d.ts.map +1 -1
- package/dist/sandbox/index.js +2 -1
- package/dist/sandbox/index.js.map +1 -1
- package/dist/sandbox/limit-error.d.ts +7 -0
- package/dist/sandbox/limit-error.d.ts.map +1 -0
- package/dist/sandbox/limit-error.js +13 -0
- package/dist/sandbox/limit-error.js.map +1 -0
- package/dist/sandbox/provider/local.d.ts +1 -0
- package/dist/sandbox/provider/local.d.ts.map +1 -1
- package/dist/sandbox/provider/local.js +52 -13
- package/dist/sandbox/provider/local.js.map +1 -1
- package/dist/session/paths.d.ts +6 -0
- package/dist/session/paths.d.ts.map +1 -1
- package/dist/session/paths.js +7 -0
- package/dist/session/paths.js.map +1 -1
- package/dist/session-query/index.d.ts +1 -0
- package/dist/session-query/index.d.ts.map +1 -1
- package/dist/session-query/index.js +26 -15
- package/dist/session-query/index.js.map +1 -1
- package/dist/store/budget/ledger.d.ts +15 -1
- package/dist/store/budget/ledger.d.ts.map +1 -1
- package/dist/store/budget/ledger.js +80 -1
- package/dist/store/budget/ledger.js.map +1 -1
- package/dist/store/evidence/disk.js +3 -1
- package/dist/store/evidence/disk.js.map +1 -1
- package/dist/store/evidence/index-page.d.ts +1 -0
- package/dist/store/evidence/index-page.d.ts.map +1 -1
- package/dist/store/evidence/index-page.js +8 -0
- package/dist/store/evidence/index-page.js.map +1 -1
- package/dist/store/evidence/source-text.d.ts +1 -1
- package/dist/store/memory/operation-lock.d.ts.map +1 -1
- package/dist/store/memory/operation-lock.js +15 -1
- package/dist/store/memory/operation-lock.js.map +1 -1
- package/dist/store/session-log/core.d.ts.map +1 -1
- package/dist/store/session-log/core.js +23 -0
- package/dist/store/session-log/core.js.map +1 -1
- package/dist/tools/builtins/atomic-write-file.d.ts +2 -0
- package/dist/tools/builtins/atomic-write-file.d.ts.map +1 -1
- package/dist/tools/builtins/atomic-write-file.js +37 -8
- package/dist/tools/builtins/atomic-write-file.js.map +1 -1
- package/dist/tools/builtins/computer-use-image.d.ts +9 -0
- package/dist/tools/builtins/computer-use-image.d.ts.map +1 -1
- package/dist/tools/builtins/computer-use-image.js +21 -0
- package/dist/tools/builtins/computer-use-image.js.map +1 -1
- package/dist/tools/builtins/computer-use.d.ts +1 -9
- package/dist/tools/builtins/computer-use.d.ts.map +1 -1
- package/dist/tools/builtins/computer-use.js +2 -22
- package/dist/tools/builtins/computer-use.js.map +1 -1
- package/dist/tools/builtins/read-file.d.ts.map +1 -1
- package/dist/tools/builtins/read-file.js +20 -12
- package/dist/tools/builtins/read-file.js.map +1 -1
- package/dist/tools/defineTool.d.ts.map +1 -1
- package/dist/tools/defineTool.js +4 -3
- package/dist/tools/defineTool.js.map +1 -1
- package/dist/tools/tool-is-available.d.ts +4 -0
- package/dist/tools/tool-is-available.d.ts.map +1 -0
- package/dist/tools/tool-is-available.js +8 -0
- package/dist/tools/tool-is-available.js.map +1 -0
- package/dist/toolsets/manager.d.ts +7 -3
- package/dist/toolsets/manager.d.ts.map +1 -1
- package/dist/toolsets/manager.js +7 -3
- package/dist/toolsets/manager.js.map +1 -1
- package/dist/types/common/index.d.ts +26 -0
- package/dist/types/common/index.d.ts.map +1 -1
- package/dist/types/common/index.js +17 -1
- package/dist/types/common/index.js.map +1 -1
- package/dist/types/hitl/index.d.ts +11 -0
- package/dist/types/hitl/index.d.ts.map +1 -1
- package/dist/types/hitl/index.js.map +1 -1
- package/dist/types/rag/embedding.d.ts +4 -0
- package/dist/types/rag/embedding.d.ts.map +1 -1
- package/dist/types/sandbox/index.d.ts +32 -2
- package/dist/types/sandbox/index.d.ts.map +1 -1
- package/dist/types/sandbox/index.js.map +1 -1
- package/dist/types/session/checkpoint.d.ts +4 -0
- package/dist/types/session/checkpoint.d.ts.map +1 -1
- package/dist/types/session/checkpoint.js +2 -0
- package/dist/types/session/checkpoint.js.map +1 -1
- package/dist/types/session/events.d.ts +49 -0
- package/dist/types/session/events.d.ts.map +1 -1
- package/dist/types/session/events.js.map +1 -1
- package/dist/types/session/records.d.ts +44 -6
- package/dist/types/session/records.d.ts.map +1 -1
- package/dist/types/session/records.js +10 -0
- package/dist/types/session/records.js.map +1 -1
- package/dist/utils/cost.d.ts +32 -0
- package/dist/utils/cost.d.ts.map +1 -1
- package/dist/utils/cost.js +101 -8
- package/dist/utils/cost.js.map +1 -1
- package/package.json +2 -2
- package/src/authorization/protected-paths.ts +7 -0
- package/src/authorization/readonly-commands.ts +85 -3
- package/src/authorization/shell-paths.ts +141 -3
- package/src/bridge/acp/permission.ts +6 -0
- package/src/bridge/acp/server.ts +20 -1
- package/src/compaction/context-window.ts +11 -0
- package/src/compaction/manual.ts +23 -8
- package/src/compaction/plan.ts +11 -5
- package/src/compaction/retained-images.ts +130 -0
- package/src/compaction/token-estimate.ts +86 -8
- package/src/compaction/tool-result-editing.ts +20 -8
- package/src/constants/acp/index.ts +2 -0
- package/src/index.ts +2 -0
- package/src/manager/session/turn-recorder.ts +31 -7
- package/src/pricing/catalogue.generated.ts +353 -21
- package/src/pricing/rates.source.json +254 -26
- package/src/provider/attribution.ts +1 -1
- package/src/public-runtime.ts +22 -0
- package/src/rag/embedding.ts +23 -7
- package/src/runtime/query/abandon-turn.ts +9 -0
- package/src/runtime/query/compact-session.ts +50 -15
- package/src/runtime/query/guard.ts +13 -2
- package/src/runtime/query/index.ts +2 -0
- package/src/runtime/query/iteration/index.ts +46 -11
- package/src/runtime/query/iteration/phases/advisory.ts +2 -2
- package/src/runtime/query/iteration/phases/compaction.ts +77 -5
- package/src/runtime/query/iteration/phases/context.ts +3 -0
- package/src/runtime/query/iteration/request-prefix.ts +161 -0
- package/src/runtime/query/prepare-turn.ts +2 -1
- package/src/runtime/query/review-policy.ts +79 -11
- package/src/sandbox/exec-stdin.ts +54 -0
- package/src/sandbox/file-walk-program.ts +1 -1
- package/src/sandbox/file-walk.ts +25 -18
- package/src/sandbox/ignore-matcher.ts +13 -3
- package/src/sandbox/ignore-source.ts +52 -8
- package/src/sandbox/index.ts +8 -2
- package/src/sandbox/limit-error.ts +10 -0
- package/src/sandbox/provider/local.ts +56 -23
- package/src/session/paths.ts +9 -0
- package/src/session-query/index.ts +23 -14
- package/src/store/budget/ledger.ts +93 -2
- package/src/store/evidence/disk.ts +3 -1
- package/src/store/evidence/index-page.ts +11 -0
- package/src/store/memory/operation-lock.ts +19 -1
- package/src/store/session-log/core.ts +26 -0
- package/src/tools/builtins/atomic-write-file.ts +49 -7
- package/src/tools/builtins/computer-use-image.ts +20 -0
- package/src/tools/builtins/computer-use.ts +1 -20
- package/src/tools/builtins/read-file.ts +34 -12
- package/src/tools/defineTool.ts +4 -3
- package/src/tools/tool-is-available.ts +11 -0
- package/src/toolsets/manager.ts +7 -3
- package/src/types/common/index.ts +50 -1
- package/src/types/hitl/index.ts +11 -0
- package/src/types/rag/embedding.ts +7 -0
- package/src/types/sandbox/index.ts +31 -1
- package/src/types/session/checkpoint.ts +2 -0
- package/src/types/session/events.ts +50 -0
- package/src/types/session/records.ts +15 -0
- package/src/utils/cost.ts +144 -8
|
@@ -16,8 +16,11 @@ import {
|
|
|
16
16
|
readCumulativeDropped,
|
|
17
17
|
readFoldedHistory,
|
|
18
18
|
} from '../../manager/session/turn-recorder.js'
|
|
19
|
-
import
|
|
20
|
-
|
|
19
|
+
import {
|
|
20
|
+
DiskSessionLog,
|
|
21
|
+
type SessionLease,
|
|
22
|
+
type SessionLog,
|
|
23
|
+
} from '../../store/session-log/index.js'
|
|
21
24
|
import { accumulateTokenUsage } from '../../types/common/index.js'
|
|
22
25
|
import { NamzuError } from '../../types/errors/index.js'
|
|
23
26
|
import type { MessageId, SessionId } from '../../types/ids/index.js'
|
|
@@ -50,6 +53,12 @@ export interface CompactSessionParams
|
|
|
50
53
|
* which always stops it.
|
|
51
54
|
*/
|
|
52
55
|
readonly preparedSummary?: 'only' | false
|
|
56
|
+
/**
|
|
57
|
+
* Close a turn whose writer is gone before a manual pass, keeping its
|
|
58
|
+
* recorded messages. Ignored for idle passes. Running and paused turns
|
|
59
|
+
* are always refused.
|
|
60
|
+
*/
|
|
61
|
+
readonly abandonInterrupted?: boolean
|
|
53
62
|
/** Where to find the session's log, and the lease to append under. */
|
|
54
63
|
readonly locator?: SessionLocatorOptions
|
|
55
64
|
}
|
|
@@ -60,19 +69,25 @@ export interface CompactSessionParams
|
|
|
60
69
|
* with no `turnId`: the messages the pass kept are named by id, the summary
|
|
61
70
|
* is recorded in full, and the shed messages stay in the log for audit.
|
|
62
71
|
*
|
|
63
|
-
* Refused while a turn is active (`TurnInProgressError`)
|
|
64
|
-
*
|
|
72
|
+
* Refused while a turn is active (`TurnInProgressError`), unless a manual
|
|
73
|
+
* pass opts into closing an interrupted turn. `null` when there was nothing
|
|
74
|
+
* to compact.
|
|
65
75
|
*/
|
|
66
76
|
export async function compactSession(
|
|
67
77
|
params: CompactSessionParams,
|
|
68
78
|
): Promise<CompactionResult | null> {
|
|
69
|
-
const {
|
|
79
|
+
const {
|
|
80
|
+
sessionId,
|
|
81
|
+
locator = {},
|
|
82
|
+
trigger = 'manual',
|
|
83
|
+
hooks,
|
|
84
|
+
preparedSummary,
|
|
85
|
+
abandonInterrupted,
|
|
86
|
+
...input
|
|
87
|
+
} = params
|
|
70
88
|
const log = await locateSessionLog(sessionId, locator)
|
|
71
89
|
return withSessionLease(log, locator.lease, async (lease) => {
|
|
72
|
-
|
|
73
|
-
if (active) {
|
|
74
|
-
throw new TurnInProgressError({ sessionId, activeTurnId: active.turnId, state: active.state })
|
|
75
|
-
}
|
|
90
|
+
await prepareCompaction(log, lease, trigger === 'manual' && abandonInterrupted)
|
|
76
91
|
// One summary at a time. A host compacting an idle conversation takes the
|
|
77
92
|
// summary prepared ahead when it is still valid (or waits for the one being
|
|
78
93
|
// written); any other pass stops it first.
|
|
@@ -147,18 +162,15 @@ export interface CompactSessionRangeParams extends CompactSessionParams {
|
|
|
147
162
|
* context (a compaction may already have folded it away), and
|
|
148
163
|
* `invalid_config` when a boundary would split a tool call from its result.
|
|
149
164
|
* `null` when the span holds nothing worth summarising; nothing is appended
|
|
150
|
-
* then
|
|
165
|
+
* then except to close an interrupted turn when explicitly requested.
|
|
151
166
|
*/
|
|
152
167
|
export async function compactSessionRange(
|
|
153
168
|
params: CompactSessionRangeParams,
|
|
154
169
|
): Promise<CompactionResult | null> {
|
|
155
|
-
const { sessionId, locator = {}, from, until, hooks, ...input } = params
|
|
170
|
+
const { sessionId, locator = {}, from, until, hooks, abandonInterrupted, ...input } = params
|
|
156
171
|
const log = await locateSessionLog(sessionId, locator)
|
|
157
172
|
return withSessionLease(log, locator.lease, async (lease) => {
|
|
158
|
-
|
|
159
|
-
if (active) {
|
|
160
|
-
throw new TurnInProgressError({ sessionId, activeTurnId: active.turnId, state: active.state })
|
|
161
|
-
}
|
|
173
|
+
await prepareCompaction(log, lease, abandonInterrupted)
|
|
162
174
|
// One summary at a time: a pass asked for between turns stops one being prepared.
|
|
163
175
|
const store = precomputeStoreFor(sessionId)
|
|
164
176
|
const owed = [...store.drainUnbooked(), ...(await store.cancel())]
|
|
@@ -216,6 +228,29 @@ export async function compactSessionRange(
|
|
|
216
228
|
})
|
|
217
229
|
}
|
|
218
230
|
|
|
231
|
+
/** Check and close an interrupted turn under the same lease used for compaction. */
|
|
232
|
+
async function prepareCompaction(
|
|
233
|
+
log: SessionLog,
|
|
234
|
+
lease: SessionLease,
|
|
235
|
+
abandonInterrupted?: boolean,
|
|
236
|
+
): Promise<void> {
|
|
237
|
+
const active = await log.activeTurn({ lease })
|
|
238
|
+
if (!active) return
|
|
239
|
+
if (active.state === 'interrupted' && abandonInterrupted) {
|
|
240
|
+
await log.abandonTurn(
|
|
241
|
+
lease,
|
|
242
|
+
active.turnId,
|
|
243
|
+
'The reply was interrupted before manual compaction.',
|
|
244
|
+
)
|
|
245
|
+
return
|
|
246
|
+
}
|
|
247
|
+
throw new TurnInProgressError({
|
|
248
|
+
sessionId: log.sessionId,
|
|
249
|
+
activeTurnId: active.turnId,
|
|
250
|
+
state: active.state,
|
|
251
|
+
})
|
|
252
|
+
}
|
|
253
|
+
|
|
219
254
|
/**
|
|
220
255
|
* Run a between-turns pass that owes a ledger what prepared summaries spent
|
|
221
256
|
* (one this pass stopped, one that outlived its turn): the cost joins the
|
|
@@ -124,11 +124,12 @@ export class GuardCoordinator {
|
|
|
124
124
|
}
|
|
125
125
|
|
|
126
126
|
beforeIteration(recorder: TurnRecorder, abortSignal: AbortSignal): GuardCheckResult {
|
|
127
|
+
const cost = recorder.treeCostInfo ?? recorder.costInfo
|
|
127
128
|
const limitState = {
|
|
128
129
|
aborted: abortSignal.aborted,
|
|
129
130
|
totalTokens: recorder.tokenUsage.totalTokens,
|
|
130
|
-
totalCost:
|
|
131
|
-
unpricedTokens:
|
|
131
|
+
totalCost: cost.totalCost,
|
|
132
|
+
unpricedTokens: cost.unpricedTokens,
|
|
132
133
|
currentIteration: recorder.currentIteration,
|
|
133
134
|
startTime: this.startTime,
|
|
134
135
|
}
|
|
@@ -152,6 +153,16 @@ export class GuardCoordinator {
|
|
|
152
153
|
}
|
|
153
154
|
}
|
|
154
155
|
|
|
156
|
+
const ancestorStop = recorder.budget?.ancestorCostStop()
|
|
157
|
+
if (ancestorStop) {
|
|
158
|
+
return {
|
|
159
|
+
shouldStop: true,
|
|
160
|
+
forceFinalize: false,
|
|
161
|
+
stopReason: ancestorStop,
|
|
162
|
+
isCancelled: false,
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
155
166
|
if (limitResult.type === 'warning') {
|
|
156
167
|
return {
|
|
157
168
|
shouldStop: false,
|
|
@@ -1952,6 +1952,7 @@ export async function* query(params: QueryParams): AsyncGenerator<SessionEvent,
|
|
|
1952
1952
|
contributions: promptContributions,
|
|
1953
1953
|
})
|
|
1954
1954
|
|
|
1955
|
+
ctx.recorder.budget?.setCostLimit(turnConfig.costLimitUsd)
|
|
1955
1956
|
const guard = new GuardCoordinator({
|
|
1956
1957
|
tokenBudget: turnConfig.tokenBudget,
|
|
1957
1958
|
timeoutMs: turnConfig.timeoutMs,
|
|
@@ -2109,6 +2110,7 @@ export async function* query(params: QueryParams): AsyncGenerator<SessionEvent,
|
|
|
2109
2110
|
...(params.durableInbound ? { durableInbound: params.durableInbound } : {}),
|
|
2110
2111
|
...(params.resumeFromCheckpoint ? { resumedInput: queuedForThisRun } : {}),
|
|
2111
2112
|
...(params.waitForInbound ? { waitForInbound: params.waitForInbound } : {}),
|
|
2113
|
+
...(params.waitForOperator ? { waitForOperator: params.waitForOperator } : {}),
|
|
2112
2114
|
...(params.projectInstructionContext
|
|
2113
2115
|
? { projectInstructionContext: params.projectInstructionContext }
|
|
2114
2116
|
: {}),
|
|
@@ -136,6 +136,7 @@ import {
|
|
|
136
136
|
streamWithProviderRejectedImageRecovery,
|
|
137
137
|
} from './provider-rejected-image.js'
|
|
138
138
|
import { appendRecordedContext } from './recorded-context.js'
|
|
139
|
+
import { digestRequestPrefix } from './request-prefix.js'
|
|
139
140
|
import { type MediaRemoval, RequestRepair } from './request-repair.js'
|
|
140
141
|
import { placeRequestContext } from './step-context.js'
|
|
141
142
|
import {
|
|
@@ -388,6 +389,7 @@ export class IterationOrchestrator {
|
|
|
388
389
|
private stopHookActive = false
|
|
389
390
|
/** End-of-turn refusals honoured since the last tool call. */
|
|
390
391
|
private consecutiveHookRefusals = 0
|
|
392
|
+
private readonly schemaFailures = new Map<string, number>()
|
|
391
393
|
/** The cap was reached and its notice recorded; refusals are ignored for the rest of the turn. */
|
|
392
394
|
private hookRefusalCapReached = false
|
|
393
395
|
get turnEndHooksFired(): boolean {
|
|
@@ -1508,6 +1510,7 @@ export class IterationOrchestrator {
|
|
|
1508
1510
|
usage: recorder.tokenUsage,
|
|
1509
1511
|
budget: recorder.budget?.summary(),
|
|
1510
1512
|
cost: recorder.costInfo,
|
|
1513
|
+
...(response.usage.billingRoute ? { billingRoute: response.usage.billingRoute } : {}),
|
|
1511
1514
|
...(response.usage.cacheTtlMs !== undefined
|
|
1512
1515
|
? {
|
|
1513
1516
|
cache: {
|
|
@@ -1519,6 +1522,19 @@ export class IterationOrchestrator {
|
|
|
1519
1522
|
...(response.usage.cacheMiss !== undefined
|
|
1520
1523
|
? { cacheMiss: response.usage.cacheMiss }
|
|
1521
1524
|
: {}),
|
|
1525
|
+
requestPrefix: digestRequestPrefix({
|
|
1526
|
+
conversation: recorder.sessionId,
|
|
1527
|
+
model: stepModel,
|
|
1528
|
+
tools: llmTools,
|
|
1529
|
+
messages,
|
|
1530
|
+
wire: response.usage.requestShape,
|
|
1531
|
+
params: {
|
|
1532
|
+
effort: stepEffort,
|
|
1533
|
+
speed: turnConfig.speed,
|
|
1534
|
+
thinking: turnConfig.thinking,
|
|
1535
|
+
choice: step.toolChoice,
|
|
1536
|
+
},
|
|
1537
|
+
}),
|
|
1522
1538
|
...contextFigures,
|
|
1523
1539
|
})
|
|
1524
1540
|
|
|
@@ -2236,18 +2252,19 @@ export class IterationOrchestrator {
|
|
|
2236
2252
|
return
|
|
2237
2253
|
}
|
|
2238
2254
|
|
|
2239
|
-
//
|
|
2240
|
-
// answered. Every `tool_use` has its `tool_result` by now, so the
|
|
2241
|
-
// transcript is whole; what is left is to end the turn and say why.
|
|
2255
|
+
// End only after the batch has answered every tool call.
|
|
2242
2256
|
const hookHalt = this.ctx.toolExecutor.takeHalt?.()
|
|
2243
|
-
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
|
|
2249
|
-
|
|
2250
|
-
|
|
2257
|
+
const validationHalt = this.repeatedValidationFailure(reviewOutcome.results)
|
|
2258
|
+
if (hookHalt !== undefined || validationHalt !== undefined) {
|
|
2259
|
+
if (hookHalt !== undefined) {
|
|
2260
|
+
this.ctx.log.info('A hook stopped the turn', {
|
|
2261
|
+
[NAMZU.TURN_ID]: recorder.turnId,
|
|
2262
|
+
[NAMZU.ITERATION]: iterationNum,
|
|
2263
|
+
'namzu.hook.reason': hookHalt,
|
|
2264
|
+
})
|
|
2265
|
+
recorder.setLastError(`Stopped by a hook: ${hookHalt}`)
|
|
2266
|
+
recorder.setStopReason('stop_condition')
|
|
2267
|
+
}
|
|
2251
2268
|
await this.ctx.emitEvent({
|
|
2252
2269
|
type: 'iteration_completed',
|
|
2253
2270
|
turnId: recorder.turnId,
|
|
@@ -2255,6 +2272,9 @@ export class IterationOrchestrator {
|
|
|
2255
2272
|
hasToolCalls: true,
|
|
2256
2273
|
})
|
|
2257
2274
|
yield* this.ctx.drainPending()
|
|
2275
|
+
if (hookHalt === undefined && validationHalt !== undefined) {
|
|
2276
|
+
throw new Error(validationHalt)
|
|
2277
|
+
}
|
|
2258
2278
|
break
|
|
2259
2279
|
}
|
|
2260
2280
|
|
|
@@ -2963,6 +2983,21 @@ export class IterationOrchestrator {
|
|
|
2963
2983
|
return true
|
|
2964
2984
|
}
|
|
2965
2985
|
|
|
2986
|
+
/** Admission failures have no execution receipt for the repeat-call advisory. */
|
|
2987
|
+
private repeatedValidationFailure(results: readonly ToolCallOutcome[]): string | undefined {
|
|
2988
|
+
for (const { toolName, inputFailure, output } of results) {
|
|
2989
|
+
// Structured output has a separate, configurable correction allowance.
|
|
2990
|
+
if (inputFailure !== 'schema_validation' || toolName === STRUCTURED_OUTPUT_TOOL_NAME) continue
|
|
2991
|
+
const key = JSON.stringify([toolName, output])
|
|
2992
|
+
const count = (this.schemaFailures.get(key) ?? 0) + 1
|
|
2993
|
+
this.schemaFailures.set(key, count)
|
|
2994
|
+
if (count === 4) {
|
|
2995
|
+
return `Stopped after ${count} identical validation failures for "${toolName}" in this turn. ${output}`
|
|
2996
|
+
}
|
|
2997
|
+
}
|
|
2998
|
+
return undefined
|
|
2999
|
+
}
|
|
3000
|
+
|
|
2966
3001
|
private async recordToolStructuredFailure(
|
|
2967
3002
|
results: readonly ToolCallOutcome[],
|
|
2968
3003
|
iteration: number,
|
|
@@ -27,7 +27,7 @@ function estimateContextWindowPercent(ctx: IterationContext): number {
|
|
|
27
27
|
function computeCostBudgetPercent(ctx: IterationContext): number | undefined {
|
|
28
28
|
const limit = ctx.turnConfig.costLimitUsd
|
|
29
29
|
if (limit === undefined || limit <= 0) return undefined
|
|
30
|
-
return (ctx.recorder.costInfo.totalCost / limit) * 100
|
|
30
|
+
return ((ctx.recorder.treeCostInfo ?? ctx.recorder.costInfo).totalCost / limit) * 100
|
|
31
31
|
}
|
|
32
32
|
|
|
33
33
|
function extractLastToolCategory(
|
|
@@ -67,7 +67,7 @@ export async function runAdvisoryPhase(
|
|
|
67
67
|
totalToolCalls: countToolCalls(ctx),
|
|
68
68
|
totalTokens: ctx.recorder.tokenUsage.totalTokens,
|
|
69
69
|
contextWindowPercent: estimateContextWindowPercent(ctx),
|
|
70
|
-
totalCostUsd: ctx.recorder.costInfo.totalCost,
|
|
70
|
+
totalCostUsd: (ctx.recorder.treeCostInfo ?? ctx.recorder.costInfo).totalCost,
|
|
71
71
|
costBudgetPercent: computeCostBudgetPercent(ctx),
|
|
72
72
|
lastError: extractCurrentToolErrors(ctx, response),
|
|
73
73
|
lastToolCategory: extractLastToolCategory(ctx, response),
|
|
@@ -33,6 +33,7 @@ import {
|
|
|
33
33
|
keptInstructionFiles,
|
|
34
34
|
renderRestoredContext,
|
|
35
35
|
} from '../../../../compaction/restore.js'
|
|
36
|
+
import { fitRetainedImages } from '../../../../compaction/retained-images.js'
|
|
36
37
|
import { findRetainedIndices } from '../../../../compaction/retention.js'
|
|
37
38
|
import { serializeState } from '../../../../compaction/serializer.js'
|
|
38
39
|
import {
|
|
@@ -41,7 +42,10 @@ import {
|
|
|
41
42
|
collectRevealedTools,
|
|
42
43
|
isCompactionMessage,
|
|
43
44
|
} from '../../../../compaction/summary.js'
|
|
44
|
-
import {
|
|
45
|
+
import {
|
|
46
|
+
estimateMessagesTokens,
|
|
47
|
+
estimateMessagesTokensForModel,
|
|
48
|
+
} from '../../../../compaction/token-estimate.js'
|
|
45
49
|
import { clearStaleToolResults } from '../../../../compaction/tool-result-editing.js'
|
|
46
50
|
import { buildVerifiedSummaryWithBoundedProvider } from '../../../../compaction/verifier.js'
|
|
47
51
|
import type { CompactionConfig } from '../../../../config/runtime.js'
|
|
@@ -131,7 +135,12 @@ function estimateToolCatalogTokens(ctx: IterationContext): number {
|
|
|
131
135
|
}
|
|
132
136
|
|
|
133
137
|
function estimateTokens(ctx: IterationContext): number {
|
|
134
|
-
return
|
|
138
|
+
return (
|
|
139
|
+
estimateMessagesTokensForModel(
|
|
140
|
+
ctx.recorder.messages,
|
|
141
|
+
ctx.contextModel ?? ctx.turnConfig.model,
|
|
142
|
+
) + estimateToolCatalogTokens(ctx)
|
|
143
|
+
)
|
|
135
144
|
}
|
|
136
145
|
|
|
137
146
|
type ToolResultClearPlan = Extract<CompactionPlan, { kind: 'cleared' }>
|
|
@@ -366,7 +375,12 @@ export function measureContext(ctx: IterationContext): {
|
|
|
366
375
|
if (reported !== undefined && reported > 0) {
|
|
367
376
|
const measuredThrough = ctx.recorder.lastPromptMessageCount ?? ctx.recorder.messages.length
|
|
368
377
|
const appended = ctx.recorder.messages.slice(measuredThrough)
|
|
369
|
-
return {
|
|
378
|
+
return {
|
|
379
|
+
tokens:
|
|
380
|
+
reported +
|
|
381
|
+
estimateMessagesTokensForModel(appended, ctx.contextModel ?? ctx.turnConfig.model),
|
|
382
|
+
source: 'provider',
|
|
383
|
+
}
|
|
370
384
|
}
|
|
371
385
|
return { tokens: estimateTokens(ctx), source: 'estimate' }
|
|
372
386
|
}
|
|
@@ -1147,7 +1161,49 @@ async function runCompactionCheckInner(
|
|
|
1147
1161
|
return
|
|
1148
1162
|
}
|
|
1149
1163
|
}
|
|
1164
|
+
const fitWithoutSummary = async (candidate: readonly Message[]): Promise<boolean> => {
|
|
1165
|
+
if (options?.preparedOnly) return false
|
|
1166
|
+
const copy = [...candidate]
|
|
1167
|
+
const fitted = fitRetainedImages(
|
|
1168
|
+
copy,
|
|
1169
|
+
Math.floor(budget * config.resetThreshold) - estimateToolCatalogTokens(ctx),
|
|
1170
|
+
model,
|
|
1171
|
+
)
|
|
1172
|
+
if (fitted === copy) return false
|
|
1173
|
+
|
|
1174
|
+
const live = ctx.recorder.messages
|
|
1175
|
+
await recordShed(ctx, live, fitted, pass.reason)
|
|
1176
|
+
installMessages(live, fitted)
|
|
1177
|
+
ctx.recorder.clearLastPromptTokens?.()
|
|
1178
|
+
const tokensAfter = estimateTokens(ctx)
|
|
1179
|
+
const durationMs = Math.max(0, Math.round(performance.now() - startedAt))
|
|
1180
|
+
ctx.recorder.noteCompaction?.({
|
|
1181
|
+
trigger: 'auto',
|
|
1182
|
+
tokensBefore: estimatedTokens,
|
|
1183
|
+
tokensAfter,
|
|
1184
|
+
durationMs,
|
|
1185
|
+
})
|
|
1186
|
+
await ctx.emitEvent?.({
|
|
1187
|
+
type: 'compaction_completed',
|
|
1188
|
+
turnId: ctx.recorder.turnId,
|
|
1189
|
+
iteration: ctx.recorder.currentIteration,
|
|
1190
|
+
messagesBefore: live.length,
|
|
1191
|
+
messagesAfter: live.length,
|
|
1192
|
+
tokensBefore: estimatedTokens,
|
|
1193
|
+
tokensAfter,
|
|
1194
|
+
measuredBy: measured.source,
|
|
1195
|
+
contextWindowTokens: budget,
|
|
1196
|
+
windowSource: window.source,
|
|
1197
|
+
reachedResetThreshold: tokensAfter / budget <= config.resetThreshold,
|
|
1198
|
+
trigger: 'auto',
|
|
1199
|
+
durationMs,
|
|
1200
|
+
})
|
|
1201
|
+
await emitContextUsageSnapshot(ctx, tokensAfter, budget, window.source)
|
|
1202
|
+
breaker?.recordRelief()
|
|
1203
|
+
return true
|
|
1204
|
+
}
|
|
1150
1205
|
const clearPlan = planCompaction({
|
|
1206
|
+
model,
|
|
1151
1207
|
messages: ctx.recorder.messages,
|
|
1152
1208
|
config,
|
|
1153
1209
|
contextWindowTokens: budget,
|
|
@@ -1176,6 +1232,7 @@ async function runCompactionCheckInner(
|
|
|
1176
1232
|
const stagedClear = clearPlan.kind === 'cleared' ? clearPlan : undefined
|
|
1177
1233
|
const messages = stagedClear?.messages ?? ctx.recorder.messages
|
|
1178
1234
|
const plan = planCompaction({
|
|
1235
|
+
model,
|
|
1179
1236
|
messages,
|
|
1180
1237
|
config,
|
|
1181
1238
|
contextWindowTokens: budget,
|
|
@@ -1186,6 +1243,7 @@ async function runCompactionCheckInner(
|
|
|
1186
1243
|
})
|
|
1187
1244
|
|
|
1188
1245
|
if (plan.kind !== 'plan') {
|
|
1246
|
+
if (await fitWithoutSummary(messages)) return
|
|
1189
1247
|
// One log line per reason, with the fields each one was already
|
|
1190
1248
|
// reporting. The planner names the reason; what it means to an
|
|
1191
1249
|
// operator reading a turn is this file's to say.
|
|
@@ -1440,7 +1498,17 @@ async function runCompactionCheckInner(
|
|
|
1440
1498
|
},
|
|
1441
1499
|
)
|
|
1442
1500
|
|
|
1443
|
-
const newMessages =
|
|
1501
|
+
const newMessages = fitRetainedImages(
|
|
1502
|
+
[...preservedSystem, compactionMessage, ...retainedOlder, ...recentMessages],
|
|
1503
|
+
Math.floor(budget * config.resetThreshold) - estimateToolCatalogTokens(ctx),
|
|
1504
|
+
model,
|
|
1505
|
+
config.keepRecentTokens === undefined
|
|
1506
|
+
? undefined
|
|
1507
|
+
: {
|
|
1508
|
+
start: preservedSystem.length + 1 + retainedOlder.length,
|
|
1509
|
+
tokens: config.keepRecentTokens,
|
|
1510
|
+
},
|
|
1511
|
+
)
|
|
1444
1512
|
|
|
1445
1513
|
// OPAQUE survival guard: the pinned working-memory slot is a
|
|
1446
1514
|
// leading system message, so it is kept in `preservedSystem` (the compaction
|
|
@@ -1471,7 +1539,11 @@ async function runCompactionCheckInner(
|
|
|
1471
1539
|
// comparing provider usage against an estimate or trusting message count.
|
|
1472
1540
|
// When a clear was staged, require the summary itself to improve on it;
|
|
1473
1541
|
// otherwise publish the useful clear without consuming its savings.
|
|
1474
|
-
if (
|
|
1542
|
+
if (
|
|
1543
|
+
estimateMessagesTokensForModel(newMessages, model) >=
|
|
1544
|
+
estimateMessagesTokensForModel(messages, model)
|
|
1545
|
+
) {
|
|
1546
|
+
if (await fitWithoutSummary(messages)) return
|
|
1475
1547
|
if (stagedClear && stagedClear.reclaimedTokens > 0) {
|
|
1476
1548
|
await commitToolResultClear(ctx, stagedClear, budget, window.source, pass.reason)
|
|
1477
1549
|
} else {
|
|
@@ -269,6 +269,8 @@ export interface IterationContext {
|
|
|
269
269
|
readonly resumedInput?: readonly import('../../../../types/message/index.js').Message[]
|
|
270
270
|
/** Observes pending input without draining it; abort releases the waiter. */
|
|
271
271
|
readonly waitForInbound?: (signal: AbortSignal) => Promise<void>
|
|
272
|
+
/** Resolves when the person wrote to this turn; handed to resume handlers, see `ResumeContext`. */
|
|
273
|
+
readonly waitForOperator?: (signal: AbortSignal) => Promise<void>
|
|
272
274
|
readonly durableInbound?: DurableInboundSource
|
|
273
275
|
|
|
274
276
|
/** Live project policy; separate from human inbound continuation. */
|
|
@@ -481,6 +483,7 @@ function resumeContextOf(ctx: IterationContext, scope?: AskScope): ResumeContext
|
|
|
481
483
|
return {
|
|
482
484
|
transcript: () => ctx.recorder.messages,
|
|
483
485
|
...(signal ? { signal } : {}),
|
|
486
|
+
...(ctx.waitForOperator ? { waitForOperator: ctx.waitForOperator } : {}),
|
|
484
487
|
...(typeof ctx.toolExecutor?.launchedScripts === 'function'
|
|
485
488
|
? {
|
|
486
489
|
launchedScripts: (callId, line, dialect) =>
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
import type { RequestWireShape } from '../../../types/common/index.js'
|
|
4
|
+
import type { Message } from '../../../types/message/index.js'
|
|
5
|
+
import type { RequestPrefixDigest } from '../../../types/session/events.js'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Where a conversation's prompt cache can break, readable from the log
|
|
9
|
+
* without its content.
|
|
10
|
+
*
|
|
11
|
+
* A provider cache reads the start of a request: the model, the tools, the
|
|
12
|
+
* system text, then each message in order. Each of those is reduced here to a
|
|
13
|
+
* short hash, and each request is compared with the one before it for the same
|
|
14
|
+
* conversation. When the cached share of a request falls, the record beside it
|
|
15
|
+
* says whether the model, the tools or the system text moved, or the first
|
|
16
|
+
* earlier message that was not repeated in place. Nothing of the content is
|
|
17
|
+
* kept: a hash of a message says only whether it changed.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/** What the next request of a conversation is compared with. */
|
|
21
|
+
interface Earlier {
|
|
22
|
+
readonly model: string
|
|
23
|
+
readonly tools: string
|
|
24
|
+
readonly system: string
|
|
25
|
+
readonly params: string
|
|
26
|
+
/** Hash of the reported wire shape; empty when the driver reported none. */
|
|
27
|
+
readonly wire: string
|
|
28
|
+
readonly items: readonly string[]
|
|
29
|
+
/** How many of the last items were request-only: the next request does not repeat them. */
|
|
30
|
+
readonly tail: number
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Conversations kept, oldest dropped first. A long-running host holds many, a turn needs one. */
|
|
34
|
+
const MAX_CONVERSATIONS = 64
|
|
35
|
+
const earlier = new Map<string, Earlier>()
|
|
36
|
+
|
|
37
|
+
const hex = (text: string, length: number): string =>
|
|
38
|
+
createHash('sha256').update(text).digest('hex').slice(0, length)
|
|
39
|
+
|
|
40
|
+
/** The parts of a message the model is sent; bookkeeping (time, id, cache hints) is left out. */
|
|
41
|
+
function wireOf(message: Message): string {
|
|
42
|
+
const { role, content } = message
|
|
43
|
+
const extra = message as unknown as Record<string, unknown>
|
|
44
|
+
return JSON.stringify([
|
|
45
|
+
role,
|
|
46
|
+
content,
|
|
47
|
+
extra.toolCalls,
|
|
48
|
+
extra.toolCallId,
|
|
49
|
+
extra.textParts,
|
|
50
|
+
extra.attachments,
|
|
51
|
+
(extra.source as { replayState?: unknown } | undefined)?.replayState,
|
|
52
|
+
])
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* A message the next request does not repeat: a request-only note, or the step's own
|
|
57
|
+
* guidance, a system message sent after the history (a system message that opens the
|
|
58
|
+
* conversation is part of the system text instead).
|
|
59
|
+
*/
|
|
60
|
+
const isRequestOnly = (message: Message): boolean => {
|
|
61
|
+
if (message.role === 'system') return true
|
|
62
|
+
const source = (message as { source?: { type?: string; kind?: string } }).source
|
|
63
|
+
return source?.type === 'runtime-context' && source.kind === 'step-context'
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface RequestPrefixInput {
|
|
67
|
+
readonly conversation: string
|
|
68
|
+
readonly model: string
|
|
69
|
+
readonly tools: readonly unknown[] | undefined
|
|
70
|
+
readonly messages: readonly Message[]
|
|
71
|
+
/**
|
|
72
|
+
* What the driver reports it sent (see `TokenUsage.requestShape`); undefined when it does
|
|
73
|
+
* not say. The digest is computed from the SDK-level request, before the driver builds the
|
|
74
|
+
* wire request, so this is the only record of what the driver then kept or dropped.
|
|
75
|
+
*/
|
|
76
|
+
readonly wire?: RequestWireShape
|
|
77
|
+
/** The request's settings that are not part of its start but can still move a cache (effort, speed, choice). */
|
|
78
|
+
readonly params: unknown
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function digestRequestPrefix(input: RequestPrefixInput): RequestPrefixDigest {
|
|
82
|
+
let opening = 0
|
|
83
|
+
while (input.messages[opening]?.role === 'system') opening++
|
|
84
|
+
const system = hex(
|
|
85
|
+
input.messages
|
|
86
|
+
.slice(0, opening)
|
|
87
|
+
.map((message) => String(message.content))
|
|
88
|
+
.join('\n\n'),
|
|
89
|
+
12,
|
|
90
|
+
)
|
|
91
|
+
const rest = input.messages.slice(opening)
|
|
92
|
+
const items = rest.map((message) => hex(wireOf(message), 6))
|
|
93
|
+
let tail = 0
|
|
94
|
+
while (tail < rest.length && isRequestOnly(rest[rest.length - 1 - tail] as Message)) tail++
|
|
95
|
+
const model = hex(input.model, 12)
|
|
96
|
+
const tools = hex(JSON.stringify(input.tools ?? []), 12)
|
|
97
|
+
const params = hex(JSON.stringify(input.params ?? null), 12)
|
|
98
|
+
// Only these three move `wire`: a developer item appearing for the first time in a
|
|
99
|
+
// healthy conversation is not a change of how the driver talks to the backend.
|
|
100
|
+
const wire = input.wire
|
|
101
|
+
? hex(
|
|
102
|
+
JSON.stringify([
|
|
103
|
+
input.wire.cacheKey,
|
|
104
|
+
input.wire.sessionHeader,
|
|
105
|
+
input.wire.developerRefused === true,
|
|
106
|
+
]),
|
|
107
|
+
12,
|
|
108
|
+
)
|
|
109
|
+
: ''
|
|
110
|
+
|
|
111
|
+
const before = earlier.get(input.conversation)
|
|
112
|
+
let changed: RequestPrefixDigest['changed']
|
|
113
|
+
let firstChangedItem: number | undefined
|
|
114
|
+
if (before) {
|
|
115
|
+
const moved: NonNullable<RequestPrefixDigest['changed']> = []
|
|
116
|
+
if (before.model !== model) moved.push('model')
|
|
117
|
+
if (before.tools !== tools) moved.push('tools')
|
|
118
|
+
if (before.system !== system) moved.push('system')
|
|
119
|
+
if (before.params !== params) moved.push('params')
|
|
120
|
+
if (before.wire !== wire && before.wire !== '' && wire !== '') moved.push('wire')
|
|
121
|
+
changed = moved
|
|
122
|
+
// Only what the earlier request kept for good can be rewritten: its own request-only
|
|
123
|
+
// tail is gone from this one by design.
|
|
124
|
+
const stable = before.items.length - before.tail
|
|
125
|
+
for (let at = 0; at < stable; at++) {
|
|
126
|
+
if (items[at] !== before.items[at]) {
|
|
127
|
+
firstChangedItem = at
|
|
128
|
+
break
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
earlier.delete(input.conversation)
|
|
133
|
+
earlier.set(input.conversation, { model, tools, system, params, wire, items, tail })
|
|
134
|
+
while (earlier.size > MAX_CONVERSATIONS) {
|
|
135
|
+
const oldest = earlier.keys().next().value
|
|
136
|
+
if (oldest === undefined) break
|
|
137
|
+
earlier.delete(oldest)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
model,
|
|
142
|
+
tools,
|
|
143
|
+
system,
|
|
144
|
+
params,
|
|
145
|
+
items: items.join(''),
|
|
146
|
+
...(input.wire
|
|
147
|
+
? {
|
|
148
|
+
cacheKey: input.wire.cacheKey,
|
|
149
|
+
sessionHeader: input.wire.sessionHeader,
|
|
150
|
+
developerRefused: input.wire.developerRefused === true,
|
|
151
|
+
}
|
|
152
|
+
: {}),
|
|
153
|
+
...(changed ? { changed } : {}),
|
|
154
|
+
...(firstChangedItem !== undefined ? { firstChangedItem } : {}),
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Test seam: forget what earlier requests held. */
|
|
159
|
+
export function resetRequestPrefixDigests(): void {
|
|
160
|
+
earlier.clear()
|
|
161
|
+
}
|
|
@@ -192,7 +192,8 @@ function assertBudgetIsMeasurable(params: QueryParams): void {
|
|
|
192
192
|
// brought one has answered the question themselves.
|
|
193
193
|
if (params.pricing !== undefined) return
|
|
194
194
|
// A driver that reports each call's billed cost measures the limit itself.
|
|
195
|
-
if (params.provider.capabilities?.reportsRequestCost === true)
|
|
195
|
+
if (params.provider.capabilities?.reportsRequestCost === true || params.provider.id === 'codex')
|
|
196
|
+
return
|
|
196
197
|
const model = params.turnConfig.model
|
|
197
198
|
if (resolveModelPricing(params.provider.id, model) !== undefined) return
|
|
198
199
|
|