@bitkyc08/opencodex 2.100.4 → 2.100.5
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/gui/dist/assets/{App-DcpyI78f.js → App-BRExzhwL.js} +21 -21
- package/gui/dist/assets/{Tray-CzjPJprT.js → Tray-DHCWAn8V.js} +1 -1
- package/gui/dist/assets/{brand-mark-BTIi7e69.js → brand-mark-C70PuQ3j.js} +1 -1
- package/gui/dist/assets/index-Dy1jIGty.js +138 -0
- package/gui/dist/assets/{segment-thumb-features-Bn6Y-g3R.js → segment-thumb-features-Bquysdn5.js} +1 -1
- package/gui/dist/classic/assets/{App-eYJAyNHM.js → App-CaC-E6Vl.js} +20 -20
- package/gui/dist/classic/assets/{Tray-xHMYxLkV.js → Tray-BG253fiL.js} +1 -1
- package/gui/dist/classic/assets/index-CR_AThOp.js +138 -0
- package/gui/dist/classic/assets/{quota-summary-DyzHlkFl.js → quota-summary-B7KQPpEC.js} +1 -1
- package/gui/dist/classic/index.html +1 -1
- package/gui/dist/index.html +1 -1
- package/native/ocx-child/src/link_ws.rs +24 -19
- package/native/ocx-child/src/link_ws_frame.rs +136 -50
- package/package.json +3 -3
- package/src/adapters/anthropic-input-schema.ts +270 -0
- package/src/adapters/anthropic.ts +1 -63
- package/src/adapters/command-code-tool-text.ts +9 -1
- package/src/adapters/command-code.ts +18 -2
- package/src/adapters/devin/cloud-direct/chat.ts +24 -0
- package/src/adapters/devin/live-models.ts +11 -1
- package/src/adapters/kiro/reasoning.ts +3 -0
- package/src/adapters/kiro-tools.ts +14 -9
- package/src/adapters/openai-responses/passthrough.ts +3 -1
- package/src/adapters/openai-responses/request-strips.ts +1 -0
- package/src/adapters/tool-catalog-nudge.ts +1 -1
- package/src/claude/chat-tool-dispatch.ts +4 -1
- package/src/cli/logout-command.ts +23 -4
- package/src/cli/provider.ts +3 -2
- package/src/client/connect.ts +10 -2
- package/src/clients/config-export.ts +12 -7
- package/src/codex/account-lifecycle.ts +3 -1
- package/src/codex/catalog/metadata.ts +8 -0
- package/src/codex/catalog/native-models.ts +16 -6
- package/src/codex/catalog/pinned-models.ts +1 -0
- package/src/codex/catalog/provider-models.ts +5 -5
- package/src/codex/catalog-auto-refresh.ts +13 -2
- package/src/codex/config-drift-heal.ts +40 -12
- package/src/codex/config-write-lock.ts +39 -1
- package/src/codex/data/roster-pinned-models.json +346 -1
- package/src/codex/inject/config-write-section.ts +39 -1
- package/src/codex/inject/plan.ts +10 -8
- package/src/codex/inject/remove.ts +21 -19
- package/src/codex/inject/restore.ts +5 -1
- package/src/codex/inject-coordination.ts +58 -7
- package/src/codex/inject.ts +10 -12
- package/src/codex/journal-config-restore.ts +42 -0
- package/src/codex/journal.ts +62 -8
- package/src/codex/main-account.ts +7 -2
- package/src/codex/native-main-credentials.ts +11 -5
- package/src/combos/failover.ts +183 -0
- package/src/config/subagent-models.ts +20 -12
- package/src/generated/compatibility-version.json +99 -83
- package/src/generated/model-metadata.ts +3 -3
- package/src/lib/client-error-body.ts +6 -0
- package/src/lib/developer-role-rejection.ts +15 -0
- package/src/lib/upstream-retry.ts +1 -1
- package/src/messaging/remote-ports.ts +22 -10
- package/src/oauth/credential-siblings.ts +32 -0
- package/src/oauth/generic-account-failover.ts +25 -13
- package/src/oauth/index.ts +22 -14
- package/src/oauth/store.ts +38 -7
- package/src/providers/anthropic-reset-grants.ts +4 -0
- package/src/providers/claude-cli-usage.ts +2 -0
- package/src/providers/codebuddy-models.ts +11 -0
- package/src/providers/google-vertex-model-discovery.ts +43 -14
- package/src/providers/kiro-models.ts +5 -0
- package/src/providers/registry/entries-core.ts +9 -3
- package/src/providers/registry/entries-extended.ts +20 -9
- package/src/providers/registry/model-seeds.ts +4 -1
- package/src/providers/stale-context-window-migration.ts +2 -0
- package/src/responses/citation-markers.ts +26 -23
- package/src/server/management/link-enrollment.ts +3 -3
- package/src/server/management/link-route-request.ts +11 -5
- package/src/server/management/oauth-account-routes.ts +21 -8
- package/src/server/management/provider-credential-release.ts +44 -0
- package/src/server/management/provider-routes.ts +8 -8
- package/src/server/management/usage-aggregate-cache.ts +6 -3
- package/src/server/messages-native.ts +16 -2
- package/src/server/request-log-conversation.ts +6 -2
- package/src/server/request-log-failure-detail.ts +26 -9
- package/src/server/responses/adapter-continuation.ts +59 -25
- package/src/server/responses/adapter-dispatch.ts +8 -8
- package/src/server/responses/codex-tool-catalog.ts +47 -10
- package/src/server/responses/combo-session-recall.ts +26 -1
- package/src/server/responses/combo-stream-preflight.ts +35 -26
- package/src/server/responses/core-combo-failure.ts +6 -0
- package/src/server/responses/core-combo-native.ts +2 -1
- package/src/server/responses/core-combo.ts +43 -19
- package/src/server/responses/core-options.ts +2 -0
- package/src/server/responses/input-admission.ts +41 -3
- package/src/server/responses/request-send-budget.ts +1 -1
- package/src/server/responses/request-transport.ts +10 -2
- package/src/server/responses/sidecar-execution.ts +6 -4
- package/src/service/windows-checked-stop-live.ts +28 -5
- package/src/types/request.ts +4 -3
- package/src/usage/expected-prices.ts +35 -0
- package/src/usage/ledger-scanner.ts +44 -10
- package/src/web-search/loop.ts +20 -2
- package/src/web-search/parse.ts +2 -12
- package/src/web-search/sources.ts +13 -0
- package/gui/dist/assets/index-DVgU6S3y.js +0 -138
- package/gui/dist/classic/assets/index-DSaVRW4F.js +0 -138
|
@@ -120,7 +120,7 @@ import {
|
|
|
120
120
|
import type { CodexAuthContext } from "../../codex/auth-context";
|
|
121
121
|
import type { ResponsesTerminalStatus } from "../../bridge";
|
|
122
122
|
import { beginRequestAttempt, sealRequestAttemptIdentity, finishRequestAttempt } from "../request-log";
|
|
123
|
-
import { rememberComboForLane } from "./combo-session-recall";
|
|
123
|
+
import { recallComboTurnEffortForLane, rememberComboForLane, type ComboTurnEffort } from "./combo-session-recall";
|
|
124
124
|
import { COMBO_TOOL_LOOP_PIN_REASON, toolLoopPinnedPick } from "./combo-tool-loop-pin";
|
|
125
125
|
import { JEV_SESSION_PIN_ROUTE_REASON, jevSessionPinScope } from "./jev-session-pin";
|
|
126
126
|
import { runTurnAdapterSseResponses } from "./core-lifetime";
|
|
@@ -716,6 +716,17 @@ export async function executeComboResponses(
|
|
|
716
716
|
const jevPin = options.compactionRoutingOverride || options.mainHardLockFallbackOverride
|
|
717
717
|
? undefined
|
|
718
718
|
: jevSessionPinScope({ combo, comboId, admission: options.admission, lane: sessionLaneIdFromRequest(req.headers) });
|
|
719
|
+
// A tool-loop continuation never asks JEV again, so under `decide` it keeps the effort the
|
|
720
|
+
// decision set for its turn while the target still offers it. Without this the rest of the
|
|
721
|
+
// turn ran at the caller's effort and only the first request at the decided one.
|
|
722
|
+
let toolLoopTurnEffort: ComboTurnEffort | undefined;
|
|
723
|
+
if (toolLoopPin && combo.strategy === "jev" && combo.jevEffortMode !== "client") {
|
|
724
|
+
const carried = recallComboTurnEffortForLane(sessionLaneIdFromRequest(req.headers), comboId, toolLoopPin.target);
|
|
725
|
+
const offered = carried ? jevChoiceEfforts(config, toolLoopPin.target, false)?.reasoningEfforts : undefined;
|
|
726
|
+
if (carried && offered && (carried.effort === null ? offered.length === 0 : offered.includes(carried.effort))) {
|
|
727
|
+
toolLoopTurnEffort = carried;
|
|
728
|
+
}
|
|
729
|
+
}
|
|
719
730
|
|
|
720
731
|
if (unreadableEncryptedAgentTask && !pick) {
|
|
721
732
|
pick = await pickWithWait({
|
|
@@ -1113,10 +1124,14 @@ export async function executeComboResponses(
|
|
|
1113
1124
|
modelId: targetRoute.modelId,
|
|
1114
1125
|
});
|
|
1115
1126
|
const initialJevDecision = firstComboTarget ? jevDecision : undefined;
|
|
1127
|
+
// The effort a decision owns on this dispatch: its own first request, or the turn a
|
|
1128
|
+
// tool-loop continuation resumes. Failover targets keep ordinary Combo policy either way.
|
|
1129
|
+
const turnEffort: ComboTurnEffort | undefined = initialJevDecision
|
|
1130
|
+
?? (firstComboTarget ? toolLoopTurnEffort : undefined);
|
|
1116
1131
|
// `client` keeps the decision's target but not its tier: the caller and the target ladder
|
|
1117
1132
|
// own the wire effort, so a provider whose effort swaps the upstream model id is never
|
|
1118
1133
|
// re-tiered mid-session and its prompt cache survives the turn.
|
|
1119
|
-
const jevEffortApplies =
|
|
1134
|
+
const jevEffortApplies = turnEffort !== undefined && combo.jevEffortMode !== "client";
|
|
1120
1135
|
const childInput = options.droidDefaultEffort && isPlainObject(body) ? { ...body } : body;
|
|
1121
1136
|
applyDroidResponsesReasoningDefault(childInput, options.droidDefaultEffort, {
|
|
1122
1137
|
provider: targetRoute.provider,
|
|
@@ -1125,21 +1140,21 @@ export async function executeComboResponses(
|
|
|
1125
1140
|
const childBody = concreteComboRequestBody(
|
|
1126
1141
|
childInput,
|
|
1127
1142
|
pick.target,
|
|
1128
|
-
jevEffortApplies ?
|
|
1129
|
-
jevEffortApplies &&
|
|
1143
|
+
jevEffortApplies ? turnEffort.effort : comboDefaultEffort(config, comboId),
|
|
1144
|
+
jevEffortApplies && turnEffort.effort === null ? [] : targetReasoningEfforts,
|
|
1130
1145
|
combo.reasoningEffortMode,
|
|
1131
1146
|
jevEffortApplies
|
|
1132
|
-
? (
|
|
1147
|
+
? (turnEffort.effort === null ? "fallback" : "force")
|
|
1133
1148
|
: combo.defaultEffortMode,
|
|
1134
1149
|
);
|
|
1135
|
-
if (
|
|
1150
|
+
if (turnEffort) {
|
|
1136
1151
|
if (jevEffortApplies) delete childBody.service_tier;
|
|
1137
|
-
if (jevEffortApplies &&
|
|
1152
|
+
if (jevEffortApplies && turnEffort.effort !== null) {
|
|
1138
1153
|
const childReasoning = childBody.reasoning;
|
|
1139
1154
|
const preservedReasoning = childReasoning && typeof childReasoning === "object" && !Array.isArray(childReasoning)
|
|
1140
1155
|
? childReasoning as Record<string, unknown>
|
|
1141
1156
|
: {};
|
|
1142
|
-
childBody.reasoning = { ...preservedReasoning, effort:
|
|
1157
|
+
childBody.reasoning = { ...preservedReasoning, effort: turnEffort.effort };
|
|
1143
1158
|
delete childBody.reasoning_effort;
|
|
1144
1159
|
delete childBody.thinking_budget;
|
|
1145
1160
|
delete childBody.thinking;
|
|
@@ -1173,6 +1188,10 @@ export async function executeComboResponses(
|
|
|
1173
1188
|
childLog.activeAttemptStartedAt = started;
|
|
1174
1189
|
childLog.attempts = logCtx.attempts ??= [];
|
|
1175
1190
|
childLog.attempts.push(attempt);
|
|
1191
|
+
// A key or account rotation inside this target seals the previous segment as its own attempt
|
|
1192
|
+
// and moves `childLog.activeAttemptStartedAt` forward (noteProviderAttemptSend). Timing the
|
|
1193
|
+
// live segment from the target's start would count every sealed segment a second time.
|
|
1194
|
+
const segmentStartedAt = (): number => childLog.activeAttemptStartedAt ?? started;
|
|
1176
1195
|
let attemptRetained = false;
|
|
1177
1196
|
const retainCancelledAttempt = (): void => {
|
|
1178
1197
|
if (attemptRetained) return;
|
|
@@ -1182,7 +1201,7 @@ export async function executeComboResponses(
|
|
|
1182
1201
|
childLog.providerAdapter ?? attempt.adapter,
|
|
1183
1202
|
childLog.accountLogLabel,
|
|
1184
1203
|
);
|
|
1185
|
-
finishRequestAttempt(attempt, 499, Date.now() -
|
|
1204
|
+
finishRequestAttempt(attempt, 499, Date.now() - segmentStartedAt(), childLog.usage);
|
|
1186
1205
|
attemptRetained = true;
|
|
1187
1206
|
};
|
|
1188
1207
|
// The row is written from `logCtx`, which copies `childLog` only when the child commits. A
|
|
@@ -1212,7 +1231,10 @@ export async function executeComboResponses(
|
|
|
1212
1231
|
&& Object.hasOwn(config.providers, completedTarget.provider)
|
|
1213
1232
|
&& provider && provider.disabled !== true
|
|
1214
1233
|
&& currentCombo?.targets.some(target => targetKey(target) === targetKey(completedTarget))) {
|
|
1215
|
-
rememberComboForLane(
|
|
1234
|
+
rememberComboForLane(
|
|
1235
|
+
sessionLaneIdFromRequest(req.headers), comboId, completedTarget, model, writerGeneration,
|
|
1236
|
+
jevEffortApplies ? turnEffort : undefined,
|
|
1237
|
+
);
|
|
1216
1238
|
jevPin?.complete(targetKey(completedTarget), initialJevDecision, writerGeneration);
|
|
1217
1239
|
}
|
|
1218
1240
|
options.onResponseComplete?.(model);
|
|
@@ -1243,7 +1265,7 @@ export async function executeComboResponses(
|
|
|
1243
1265
|
&& targetEligible(target)
|
|
1244
1266
|
&& !isComboTargetInCooldown(comboId, target),
|
|
1245
1267
|
);
|
|
1246
|
-
const nativeChild = protocolLanes?.nativeChild(pick.target, targetRoute, targetSendBudget,
|
|
1268
|
+
const nativeChild = protocolLanes?.nativeChild(pick.target, targetRoute, targetSendBudget, turnEffort, jevEffortApplies);
|
|
1247
1269
|
response = nativeChild ? await dispatchNativeComboChild({
|
|
1248
1270
|
source: options.protocolSource!,
|
|
1249
1271
|
plan: nativeChild,
|
|
@@ -1256,7 +1278,7 @@ export async function executeComboResponses(
|
|
|
1256
1278
|
// Attempt-relative TTFT, recorded here for the same reason as the bridge child below.
|
|
1257
1279
|
onFirstOutput: () => {
|
|
1258
1280
|
if (attempt.firstOutputMs === undefined) {
|
|
1259
|
-
attempt.firstOutputMs = Math.max(0, Date.now() -
|
|
1281
|
+
attempt.firstOutputMs = Math.max(0, Date.now() - segmentStartedAt());
|
|
1260
1282
|
}
|
|
1261
1283
|
options.onFirstOutput?.();
|
|
1262
1284
|
},
|
|
@@ -1287,7 +1309,7 @@ export async function executeComboResponses(
|
|
|
1287
1309
|
// Object.assign(logCtx, childLog) would overwrite the request-relative value).
|
|
1288
1310
|
onFirstOutput: () => {
|
|
1289
1311
|
if (attempt.firstOutputMs === undefined) {
|
|
1290
|
-
attempt.firstOutputMs = Math.max(0, Date.now() -
|
|
1312
|
+
attempt.firstOutputMs = Math.max(0, Date.now() - segmentStartedAt());
|
|
1291
1313
|
}
|
|
1292
1314
|
options.onFirstOutput?.();
|
|
1293
1315
|
},
|
|
@@ -1300,7 +1322,7 @@ export async function executeComboResponses(
|
|
|
1300
1322
|
onResponseComplete: callbackGate.onResponseComplete,
|
|
1301
1323
|
});
|
|
1302
1324
|
// Both lanes applied the initial choice before provider pins/caps; retain those transitions.
|
|
1303
|
-
restoreOriginalRequestedEffort(childLog, jevEffortApplies ?
|
|
1325
|
+
restoreOriginalRequestedEffort(childLog, jevEffortApplies ? turnEffort?.effort : undefined);
|
|
1304
1326
|
} catch (error) {
|
|
1305
1327
|
callbackGate.discard();
|
|
1306
1328
|
if (options.abortSignal?.aborted) {
|
|
@@ -1308,7 +1330,7 @@ export async function executeComboResponses(
|
|
|
1308
1330
|
return clientCancelledResponse();
|
|
1309
1331
|
}
|
|
1310
1332
|
jevPin?.forget();
|
|
1311
|
-
finishRequestAttempt(attempt, 502, Date.now() -
|
|
1333
|
+
finishRequestAttempt(attempt, 502, Date.now() - segmentStartedAt(), childLog.usage);
|
|
1312
1334
|
throw error;
|
|
1313
1335
|
}
|
|
1314
1336
|
|
|
@@ -1336,7 +1358,7 @@ export async function executeComboResponses(
|
|
|
1336
1358
|
return clientCancelledResponse();
|
|
1337
1359
|
}
|
|
1338
1360
|
jevPin?.forget();
|
|
1339
|
-
finishRequestAttempt(attempt, 502, Date.now() -
|
|
1361
|
+
finishRequestAttempt(attempt, 502, Date.now() - segmentStartedAt(), childLog.usage);
|
|
1340
1362
|
throw error;
|
|
1341
1363
|
}
|
|
1342
1364
|
if (preflight.kind === "failed") {
|
|
@@ -1378,7 +1400,7 @@ export async function executeComboResponses(
|
|
|
1378
1400
|
routeDecision: logCtx.routeDecision,
|
|
1379
1401
|
attempts: logCtx.attempts,
|
|
1380
1402
|
activeAttempt: attempt,
|
|
1381
|
-
activeAttemptStartedAt:
|
|
1403
|
+
activeAttemptStartedAt: segmentStartedAt(),
|
|
1382
1404
|
resolvedModel: childLog.resolvedModel ?? childLog.model,
|
|
1383
1405
|
});
|
|
1384
1406
|
options.onCodexAuthContextResolved?.(resolvedAuth);
|
|
@@ -1406,7 +1428,7 @@ export async function executeComboResponses(
|
|
|
1406
1428
|
return clientCancelledResponse();
|
|
1407
1429
|
}
|
|
1408
1430
|
jevPin?.forget();
|
|
1409
|
-
finishRequestAttempt(attempt, 502, Date.now() -
|
|
1431
|
+
finishRequestAttempt(attempt, 502, Date.now() - segmentStartedAt(), childLog.usage);
|
|
1410
1432
|
throw error;
|
|
1411
1433
|
}
|
|
1412
1434
|
if (options.abortSignal?.aborted) {
|
|
@@ -1426,7 +1448,7 @@ export async function executeComboResponses(
|
|
|
1426
1448
|
finishRequestAttempt(
|
|
1427
1449
|
attempt,
|
|
1428
1450
|
failure.response.status,
|
|
1429
|
-
Date.now() -
|
|
1451
|
+
Date.now() - segmentStartedAt(),
|
|
1430
1452
|
failure.usage ?? childLog.usage,
|
|
1431
1453
|
);
|
|
1432
1454
|
if (isReplayRefusalResponse(failure.response)) {
|
|
@@ -1478,6 +1500,7 @@ export async function executeComboResponses(
|
|
|
1478
1500
|
verifiedPlanRefusal: failure.verifiedPlanRefusal,
|
|
1479
1501
|
malformedResponseFormat: failure.malformedResponseFormat,
|
|
1480
1502
|
openRouterOpaque400: failure.openRouterOpaque400,
|
|
1503
|
+
unofferedToolCallRefusal: failure.unofferedToolCallRefusal,
|
|
1481
1504
|
providerModerationRefusal: failure.providerModerationRefusal,
|
|
1482
1505
|
// The adapter the failed leg actually resolved: a configured `kiro` provider can route a
|
|
1483
1506
|
// model through another wire via `modelAdapters`, and an unresolved leg grants no hop.
|
|
@@ -1557,6 +1580,7 @@ export async function executeComboResponses(
|
|
|
1557
1580
|
code: failure.upstreamCode,
|
|
1558
1581
|
malformedResponseFormat: failure.malformedResponseFormat,
|
|
1559
1582
|
openRouterOpaque400: failure.openRouterOpaque400,
|
|
1583
|
+
unofferedToolCallRefusal: failure.unofferedToolCallRefusal,
|
|
1560
1584
|
providerModerationRefusal: failure.providerModerationRefusal,
|
|
1561
1585
|
});
|
|
1562
1586
|
const failedTargetKey = targetKey(pick.target);
|
|
@@ -37,6 +37,8 @@ export interface ConsumedComboFailure {
|
|
|
37
37
|
malformedResponseFormat?: boolean;
|
|
38
38
|
/** Complete bounded-envelope OpenRouter opaque-400 verdict captured before display truncation. */
|
|
39
39
|
openRouterOpaque400?: boolean;
|
|
40
|
+
/** Complete bounded-envelope unoffered-tool-call verdict captured before display truncation. */
|
|
41
|
+
unofferedToolCallRefusal?: boolean;
|
|
40
42
|
/** Complete bounded-envelope provider moderation verdict captured before display truncation. */
|
|
41
43
|
providerModerationRefusal?: boolean;
|
|
42
44
|
/** Structured upstream `error.code` when present in the failure body. */
|
|
@@ -11,6 +11,7 @@ import { clientFacingModelText, type ClientFacingModelLabel } from "../../lib/er
|
|
|
11
11
|
* catches the pathological case and stays out of the way otherwise. Every uncertainty
|
|
12
12
|
* resolves toward admitting.
|
|
13
13
|
*/
|
|
14
|
+
import { collapseDevinModelUid, DEVIN_MODEL_CONTEXT_WINDOWS } from "../../adapters/devin/live-models";
|
|
14
15
|
import {
|
|
15
16
|
nativeOpenAiContextWindow,
|
|
16
17
|
nativeOpenAiMaxInputTokens,
|
|
@@ -171,6 +172,35 @@ interface ResolvedContextLimits {
|
|
|
171
172
|
ceiling: number | null;
|
|
172
173
|
}
|
|
173
174
|
|
|
175
|
+
/**
|
|
176
|
+
* Devin spells one model dotted in catalog families (`swe-1.7`) and hyphenated in uids
|
|
177
|
+
* (`swe-1-7`), with optional effort suffixes (`swe-2-flash-medium`). A per-model record is
|
|
178
|
+
* matched on the exact id first, then the effort-collapsed id, then both hyphenated forms, and
|
|
179
|
+
* finally on record keys folded the same way (`swe-1.7` serves a `swe-1-7-medium` request), so
|
|
180
|
+
* an operator override on any of those spellings binds before a provider-wide default.
|
|
181
|
+
*/
|
|
182
|
+
function devinRecordValue(record: Record<string, number> | undefined, modelId: string): number | null {
|
|
183
|
+
const normalized = modelId.replace(/\./g, "-");
|
|
184
|
+
// Lower-case before collapsing so an upper-case effort suffix (SWE-1-7-MEDIUM) is removed too.
|
|
185
|
+
const collapsed = collapseDevinModelUid(normalized.toLowerCase());
|
|
186
|
+
for (const key of new Set([modelId, collapseDevinModelUid(modelId), normalized, collapsed])) {
|
|
187
|
+
const value = positive(modelRecordValue(record, key));
|
|
188
|
+
if (value !== null) return value;
|
|
189
|
+
}
|
|
190
|
+
if (!record) return null;
|
|
191
|
+
// Exact spellings missed; fold dotted record keys only now so an exact key always wins.
|
|
192
|
+
for (const target of new Set([normalized, collapsed])) {
|
|
193
|
+
// Fold case too, like modelRecordValue's exact-spelling lookup.
|
|
194
|
+
const folded = target.toLowerCase();
|
|
195
|
+
for (const [key, raw] of Object.entries(record)) {
|
|
196
|
+
if (key.replace(/\./g, "-").toLowerCase() !== folded) continue;
|
|
197
|
+
const value = positive(raw);
|
|
198
|
+
if (value !== null) return value;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
|
|
174
204
|
function resolveContextLimits(
|
|
175
205
|
provider: OcxProviderConfig,
|
|
176
206
|
providerName: string,
|
|
@@ -180,7 +210,10 @@ function resolveContextLimits(
|
|
|
180
210
|
// `modelRecordValue`, not a bare lookup: the catalog resolves these same two maps that
|
|
181
211
|
// way, so a `gpt-oss` entry covers `gpt-oss:120b`. Reading raw here made the gate fall
|
|
182
212
|
// back to the provider-wide window and refuse turns the model can plainly hold.
|
|
183
|
-
const
|
|
213
|
+
const devin = provider.adapter === "devin";
|
|
214
|
+
const configured = (devin
|
|
215
|
+
? devinRecordValue(provider.modelContextWindows, modelId)
|
|
216
|
+
: positive(modelRecordValue(provider.modelContextWindows, modelId)))
|
|
184
217
|
?? positive(provider.contextWindow);
|
|
185
218
|
|
|
186
219
|
// The canonical `openai` registry entry declares no context fields, so without this the
|
|
@@ -202,9 +235,14 @@ function resolveContextLimits(
|
|
|
202
235
|
: null;
|
|
203
236
|
const nativeMaxInput = canonicalNativeBare ? positive(nativeOpenAiMaxInputTokens(modelId, nativeLimits)) : null;
|
|
204
237
|
|
|
205
|
-
|
|
238
|
+
// Devin's live catalog windows reach the Codex model list but never `provider.modelContextWindows`;
|
|
239
|
+
// without the adapter table every devin combo target resolved no window and the strict gate stayed open.
|
|
240
|
+
const window = canonicalNativeBare ? (native ?? generatedNativeWindow(modelId, configured, nativeContextCap))
|
|
241
|
+
: (configured ?? (devin ? devinRecordValue(DEVIN_MODEL_CONTEXT_WINDOWS, modelId) : null));
|
|
206
242
|
// modelMaxInputTokens is an input-only cap, so it can only tighten the window.
|
|
207
|
-
const configuredMaxInput =
|
|
243
|
+
const configuredMaxInput = devin
|
|
244
|
+
? devinRecordValue(provider.modelMaxInputTokens, modelId)
|
|
245
|
+
: positive(modelRecordValue(provider.modelMaxInputTokens, modelId));
|
|
208
246
|
const limits = [window, configuredMaxInput, nativeMaxInput].filter((v): v is number => v !== null);
|
|
209
247
|
return { window, ceiling: limits.length === 0 ? null : Math.min(...limits) };
|
|
210
248
|
}
|
|
@@ -321,7 +321,7 @@ export function createResponsesSendBudget(
|
|
|
321
321
|
/**
|
|
322
322
|
* One credential hop of this logical request, admitted by the INTERSECTION of two bounds.
|
|
323
323
|
*
|
|
324
|
-
* The snapshotted generic OAuth
|
|
324
|
+
* The snapshotted generic OAuth and Anthropic roster caps
|
|
325
325
|
* bound rotation within one credential roster. What neither
|
|
326
326
|
* can see is everything else this request already sent, so three hops layered on a spent
|
|
327
327
|
* budget still reached upstream three more times. A hop now happens only when its own layer
|
|
@@ -36,6 +36,7 @@ import type { AnthropicAccountSelectionReason } from "../../oauth/anthropic-rout
|
|
|
36
36
|
import { resolveAnthropicModelRouteForInstance, routeCandidates, type AnthropicRouteDecision } from "../../oauth/anthropic-model-routes";
|
|
37
37
|
import {
|
|
38
38
|
anthropicRoutingFor,
|
|
39
|
+
ANTHROPIC_POOL_MAX_FAILOVERS_PER_REQUEST,
|
|
39
40
|
AnthropicAccountCooldownError,
|
|
40
41
|
formatAnthropicProviderForLog,
|
|
41
42
|
} from "../../oauth/anthropic-routing";
|
|
@@ -1425,10 +1426,17 @@ export async function prepareResponsesTransport(
|
|
|
1425
1426
|
]).size : 0;
|
|
1426
1427
|
const fundedAccounts = Math.min(genericRosterSize, GENERIC_OAUTH_MAX_ACCOUNTS_PER_REQUEST);
|
|
1427
1428
|
const genericFailoverLimit = Math.max(GENERIC_OAUTH_MAX_FAILOVERS_PER_REQUEST, fundedAccounts - 1);
|
|
1428
|
-
|
|
1429
|
+
const anthropicRosterSize = anthropicRouting && anthropicPoolAccountId ? new Set([
|
|
1430
|
+
anthropicPoolAccountId,
|
|
1431
|
+
...anthropicRouting.getEligibleAnthropicAccounts(Date.now(), route.modelId),
|
|
1432
|
+
]).size : 0;
|
|
1433
|
+
const anthropicFundedAccounts = Math.min(anthropicRosterSize, GENERIC_OAUTH_MAX_ACCOUNTS_PER_REQUEST);
|
|
1434
|
+
const anthropicFailoverLimit = Math.max(ANTHROPIC_POOL_MAX_FAILOVERS_PER_REQUEST, anthropicFundedAccounts - 1);
|
|
1435
|
+
if (fundingAccountId || anthropicPoolAccountId)
|
|
1436
|
+
expandInferenceOAuthSendBudget(options.sendBudget, Math.max(fundedAccounts, anthropicFundedAccounts));
|
|
1429
1437
|
|
|
1430
1438
|
return {
|
|
1431
|
-
genericFailoverLimit,
|
|
1439
|
+
genericFailoverLimit, anthropicFailoverLimit,
|
|
1432
1440
|
isOAuth401ReplayProvider,
|
|
1433
1441
|
get sentOAuthSnapshot(): OAuthAccessSnapshot | undefined {
|
|
1434
1442
|
return sentOAuthSnapshot;
|
|
@@ -44,8 +44,8 @@ import { noteKiroMonthlyRefusal, noteKiroServedSuccess } from "../../providers/k
|
|
|
44
44
|
import { persistKiroAccountState } from "../../providers/kiro-account-state-disk";
|
|
45
45
|
import { anthropicPoolCooldownResponse, readDisplaySafeErrorText } from "./core-errors";
|
|
46
46
|
import { sidecarContextOverflowResponse } from "./context-overflow";
|
|
47
|
+
import { emptyCompletionRetryEnabled } from "./empty-completion-guard";
|
|
47
48
|
import {
|
|
48
|
-
ANTHROPIC_POOL_MAX_FAILOVERS_PER_REQUEST,
|
|
49
49
|
anthropicRoutingFor,
|
|
50
50
|
formatAnthropicProviderForLog,
|
|
51
51
|
} from "../../oauth/anthropic-routing";
|
|
@@ -86,7 +86,7 @@ export async function executeResponsesSidecars(
|
|
|
86
86
|
| "adapter"
|
|
87
87
|
| "genericFailoverAccountId"
|
|
88
88
|
| "genericFailovers"
|
|
89
|
-
| "genericFailoverLimit"
|
|
89
|
+
| "genericFailoverLimit" | "anthropicFailoverLimit"
|
|
90
90
|
| "replayOAuthCredentialSnapshot"
|
|
91
91
|
| "applyFailoverSnapshot"
|
|
92
92
|
| "anthropicInstance"
|
|
@@ -110,7 +110,7 @@ export async function executeResponsesSidecars(
|
|
|
110
110
|
| "notifyResponseComplete"
|
|
111
111
|
| "cancelResponseCompletion"
|
|
112
112
|
>,
|
|
113
|
-
sendBudgetState: Pick<ResponsesSendBudget, "sendBudgetExhausted" | "reserveCredentialHop" | "refundableAdapterDispatchBudget" | "adapterDispatchBudget" | "noteInitialDispatch" | "noteAdapterPhysicalSend" | "noteAdapterRecoveryWithheld" | "pendingHopPermit" | "dispatchSidecarSend">,
|
|
113
|
+
sendBudgetState: Pick<ResponsesSendBudget, "initialSendAllowance" | "sendBudgetExhausted" | "reserveCredentialHop" | "refundableAdapterDispatchBudget" | "adapterDispatchBudget" | "noteInitialDispatch" | "noteAdapterPhysicalSend" | "noteAdapterRecoveryWithheld" | "pendingHopPermit" | "dispatchSidecarSend">,
|
|
114
114
|
) {
|
|
115
115
|
const { config, options, logCtx } = requestContext;
|
|
116
116
|
const antigravityPoolActivated = requestState.route.providerName === "google-antigravity"
|
|
@@ -422,7 +422,7 @@ export async function executeResponsesSidecars(
|
|
|
422
422
|
config, accountId: transportState.anthropicPoolAccountId, sessionKey: anthropicSessionKey,
|
|
423
423
|
model: route.modelId, requestKey: transportState, decision: transportState.anthropicRouteDecision, currentDecision: currentAnthropicRouteDecision, signal: options.abortSignal,
|
|
424
424
|
allow429Recovery: !sidecarHasCommittedOutput(), allowAccountRefusal: !sidecarHasCommittedOutput(),
|
|
425
|
-
canRetry: hop.allowed && transportState.anthropicPoolFailovers <
|
|
425
|
+
canRetry: hop.allowed && transportState.anthropicPoolFailovers < transportState.anthropicFailoverLimit,
|
|
426
426
|
});
|
|
427
427
|
if (!nextAccountId) {
|
|
428
428
|
hop.permit?.release();
|
|
@@ -503,6 +503,7 @@ export async function executeResponsesSidecars(
|
|
|
503
503
|
if (existing) existing();
|
|
504
504
|
else {
|
|
505
505
|
const prepaid = sendBudgetState.pendingHopPermit;
|
|
506
|
+
if (anthropicInstance && !prepaid && sendBudgetState.initialSendAllowance(1) === 0) throw new SendBudgetExhaustedError();
|
|
506
507
|
sendBudgetState.pendingHopPermit = undefined;
|
|
507
508
|
sendBudgetState.noteInitialDispatch(prepaid);
|
|
508
509
|
}
|
|
@@ -701,6 +702,7 @@ export async function executeResponsesSidecars(
|
|
|
701
702
|
...sidecarBudget.fetchOptions(transportState.adapter),
|
|
702
703
|
})(input, init)) as typeof globalThis.fetch;
|
|
703
704
|
const loopResponse = await runWithWebSearch({
|
|
705
|
+
emptyCompletionRetry: emptyCompletionRetryEnabled(config) && !options.comboAttempt && !routedCompaction,
|
|
704
706
|
dispatchSidecarSend: sendBudgetState.dispatchSidecarSend,
|
|
705
707
|
parsed, adapter: transportState.adapter,
|
|
706
708
|
...(webSearchAdvisor ? { advisor: createAdvisorSidecarStep(webSearchAdvisor as Parameters<typeof createAdvisorSidecarStep>[0]) } : {}),
|
|
@@ -121,14 +121,25 @@ export function classifyTaskEnd(result: WindowsStopCommandResult): WindowsTaskEn
|
|
|
121
121
|
return toWindowsSchtasksError(error, ["/end", "/tn", TASK]).reason === "access-denied" ? "denied" : "failed";
|
|
122
122
|
}
|
|
123
123
|
|
|
124
|
-
/**
|
|
124
|
+
/**
|
|
125
|
+
* Status words of `schtasks /query /fo CSV /nh`. schtasks localizes the column from its .mui
|
|
126
|
+
* resources, and the PowerShell fallback cannot start inside Part A's 1 s manager-state cap on a
|
|
127
|
+
* cold machine (#8863), so the words observed from shipped resources are read here: zh-CN from
|
|
128
|
+
* System32\zh-CN\schtasks.exe.mui, ko-KR from two machines. Any other word stays unknown and
|
|
129
|
+
* falls back to Get-ScheduledTask's locale-independent State enum.
|
|
130
|
+
*/
|
|
131
|
+
const TASK_CSV_RUNNING = new Set(["running", "正在运行", "실행 중"]);
|
|
132
|
+
const TASK_CSV_NOT_RUNNING = new Set(["ready", "disabled", "queued", "就绪", "已禁用", "已排队", "준비"]);
|
|
133
|
+
/** ERROR_ACCESS_DENIED in the locales whose status words are read above (zh-CN, ko-KR). */
|
|
134
|
+
const LOCALIZED_ACCESS_DENIED = /拒绝访问|액세스가 거부/;
|
|
135
|
+
|
|
125
136
|
export function parseTaskCsvState(csv: string): "running" | "not-running" | "unknown" {
|
|
126
137
|
for (const line of csv.split(/\r?\n/)) {
|
|
127
138
|
if (!windowsSchedulerCsvIncludesTask(line, TASK)) continue;
|
|
128
139
|
const fields = [...line.matchAll(/"([^"]*)"/g)].map(match => match[1]!.trim());
|
|
129
|
-
const status = fields[fields.length - 1] ?? "";
|
|
130
|
-
if (
|
|
131
|
-
if (
|
|
140
|
+
const status = (fields[fields.length - 1] ?? "").normalize("NFC").toLowerCase();
|
|
141
|
+
if (TASK_CSV_RUNNING.has(status)) return "running";
|
|
142
|
+
if (TASK_CSV_NOT_RUNNING.has(status)) return "not-running";
|
|
132
143
|
return "unknown";
|
|
133
144
|
}
|
|
134
145
|
return "unknown";
|
|
@@ -291,7 +302,19 @@ export function windowsCheckedStopLiveDeps(options: WindowsCheckedStopLiveOption
|
|
|
291
302
|
},
|
|
292
303
|
async endTask(timeoutMs) {
|
|
293
304
|
if (!gate()) return "failed";
|
|
294
|
-
|
|
305
|
+
const started = Date.now();
|
|
306
|
+
const ended = await run("schtasks", ["/end", "/tn", TASK], timeoutMs);
|
|
307
|
+
const verdict = classifyTaskEnd(ended);
|
|
308
|
+
// schtasks localizes "no running instance" as well (#8863). After a real nonzero exit, an
|
|
309
|
+
// idle task is not-running only when its own CSV state says so; a running or unreadable
|
|
310
|
+
// state, a timeout, or an /end that never ran keeps the failure. A localized denial stays a
|
|
311
|
+
// denial: Part A stops at it whatever the task's state.
|
|
312
|
+
if (verdict !== "failed" || ended.timedOut || ended.status === null) return verdict;
|
|
313
|
+
if (LOCALIZED_ACCESS_DENIED.test(ended.stderr + "\n" + ended.stdout)) return "denied";
|
|
314
|
+
const left = Math.floor(timeoutMs - (Date.now() - started));
|
|
315
|
+
if (left < 1) return "failed";
|
|
316
|
+
const csv = await run("schtasks", ["/query", "/tn", TASK, "/fo", "CSV", "/nh"], left);
|
|
317
|
+
return csv.status === 0 && !csv.timedOut && parseTaskCsvState(csv.stdout) === "not-running" ? "not-running" : "failed";
|
|
295
318
|
},
|
|
296
319
|
async taskState(timeoutMs) {
|
|
297
320
|
const started = Date.now();
|
package/src/types/request.ts
CHANGED
|
@@ -38,9 +38,10 @@ export interface OcxReasoningReplayScopeRef {
|
|
|
38
38
|
*/
|
|
39
39
|
readonly clientPrincipalId?: string;
|
|
40
40
|
/**
|
|
41
|
-
* Conversation namespace for replay state.
|
|
42
|
-
*
|
|
43
|
-
*
|
|
41
|
+
* Conversation namespace for replay state. The request's own thread-id wins so a child agent
|
|
42
|
+
* cannot write its route into the parent's record (#8632); otherwise this is the Codex
|
|
43
|
+
* parent-thread id, and headerless Responses callers use a raw sanitized thread/Cursor/session
|
|
44
|
+
* fallback, never the hashed request-log conversation id.
|
|
44
45
|
*/
|
|
45
46
|
readonly clientThreadId: string;
|
|
46
47
|
current?: Readonly<OcxReasoningReplayIdentity>;
|
|
@@ -317,7 +317,26 @@ const DEVIN_PRICING = "https://docs.devin.ai/desktop/models (official modelCostD
|
|
|
317
317
|
const DEVIN_FABLE_52_SOURCE = "https://docs.devin.ai/desktop/models (Claude Fable 5.2 listed at 8 / 40, cache read 0.20, cache write 10, 2026-11-10; uid claude-fable-5-2-<effort>, seed collapses to the base)";
|
|
318
318
|
const DEVIN_SWE2_NOTE = "list rate; $0 self-serve through 2026-10-08 and 75%-off enterprise through 2026-12-31 are time-boxed promos, not baked in";
|
|
319
319
|
|
|
320
|
+
const GPT62_PRICING = [
|
|
321
|
+
{ modelId: "gpt-6.2-sol", cost4: { input: 2, output: 10, cacheRead: 0.1, cacheWrite: 2.5 } },
|
|
322
|
+
{ modelId: "gpt-6.2-astra", cost4: { input: 8, output: 40, cacheRead: 0.4, cacheWrite: 10 } },
|
|
323
|
+
];
|
|
324
|
+
const GPT62_VERIFIED_AT = "2026-11-18";
|
|
325
|
+
|
|
320
326
|
export const EXPECTED_PRICE_OVERLAYS: readonly ExpectedPriceOverlay[] = [
|
|
327
|
+
...GPT62_PRICING.flatMap(({ modelId, cost4 }): ExpectedPriceOverlay[] => {
|
|
328
|
+
const source = `https://developers.openai.com/api/docs/models/${modelId}`;
|
|
329
|
+
return [
|
|
330
|
+
{ provider: "openai-apikey", modelId, cost4, source, verifiedAt: GPT62_VERIFIED_AT, status: "verified" },
|
|
331
|
+
{ provider: "openai", modelId, cost4, source: `API-reference comparison estimate: ${source}`, verifiedAt: GPT62_VERIFIED_AT, status: "verified-derived" },
|
|
332
|
+
{ provider: "openrouter", modelId: `openai/${modelId}`, cost4, source: "https://openrouter.ai/api/v1/models", verifiedAt: GPT62_VERIFIED_AT, status: "verified" },
|
|
333
|
+
// 261118 preemptive: Devin uid follows gpt-6-1-sol; API-reference estimate, not billing.
|
|
334
|
+
...(["devin-cli", "devin"] as const).map((provider): ExpectedPriceOverlay => ({
|
|
335
|
+
provider, modelId: modelId.replaceAll(".", "-"), cost4,
|
|
336
|
+
source: `derived: OpenAI API list price ${source}; Devin uid mirrors gpt-6-1-sol`, verifiedAt: GPT62_VERIFIED_AT, status: "verified-derived",
|
|
337
|
+
})),
|
|
338
|
+
];
|
|
339
|
+
}),
|
|
321
340
|
{ provider: "openai-apikey", modelId: "gpt-6-astra", cost4: GPT6_ASTRA, source: ASTRA_API_PRICING, verifiedAt: "2026-09-05", status: "verified" },
|
|
322
341
|
// Display estimates use API prices for both login and API-key routes, including cache writes.
|
|
323
342
|
{ provider: "openai", modelId: "gpt-6-astra", cost4: GPT6_ASTRA, source: `API-reference comparison estimate: ${ASTRA_API_PRICING}`, verifiedAt: "2026-09-05", status: "verified-derived" },
|
|
@@ -719,6 +738,10 @@ const ANTHROPIC_FAST_PRICING = "https://platform.claude.com/docs/en/about-claude
|
|
|
719
738
|
* because they reuse its model slug. Multipliers apply uniformly after cache discounts.
|
|
720
739
|
*/
|
|
721
740
|
export const PRIORITY_PRICING_RULES: readonly PriorityPricingRule[] = [
|
|
741
|
+
...GPT62_PRICING.flatMap(({ modelId }) => ["openai", "openai-apikey"].map((provider): PriorityPricingRule => ({
|
|
742
|
+
provider, modelId, multiplier: 2,
|
|
743
|
+
source: "https://developers.openai.com/api/docs/pricing", verifiedAt: GPT62_VERIFIED_AT,
|
|
744
|
+
}))),
|
|
722
745
|
...["openai", "openai-apikey"].flatMap(provider =>
|
|
723
746
|
Object.entries(PRIORITY_MULTIPLIERS)
|
|
724
747
|
// Daybreak's `gpt-` selector belongs to ChatGPT/Codex accounts; its bare selector belongs
|
|
@@ -841,6 +864,18 @@ const OPENAI_CONTEXT_MODELS = [
|
|
|
841
864
|
];
|
|
842
865
|
|
|
843
866
|
export const CONTEXT_TIERS: readonly ContextTier[] = [
|
|
867
|
+
...GPT62_PRICING.flatMap(({ modelId }): ContextTier[] => [
|
|
868
|
+
...["openai", "openai-apikey"].map((provider): ContextTier => ({
|
|
869
|
+
provider, modelId, thresholdInputTokens: 272_000, inclusive: false,
|
|
870
|
+
multiplier: OPENAI_LONG_CONTEXT, confirmedPriorityRelation: "stack",
|
|
871
|
+
source: `https://developers.openai.com/api/docs/models/${modelId}`, verifiedAt: GPT62_VERIFIED_AT,
|
|
872
|
+
})),
|
|
873
|
+
{
|
|
874
|
+
provider: "openrouter", modelId: `openai/${modelId}`, thresholdInputTokens: 272_000, inclusive: true,
|
|
875
|
+
multiplier: OPENAI_LONG_CONTEXT,
|
|
876
|
+
source: "https://openrouter.ai/api/v1/models", verifiedAt: GPT62_VERIFIED_AT,
|
|
877
|
+
},
|
|
878
|
+
]),
|
|
844
879
|
// Reference bands on preemptive/subscription surfaces follow their reference price, not billing.
|
|
845
880
|
...[
|
|
846
881
|
...["anthropic", "anthropic-apikey", "opencode-go", "opencode-zen", "venice", "github-copilot", "devin", "devin-cli", "claude-cli"].map(provider => [provider, "claude-haiku-5-5"]),
|
|
@@ -486,6 +486,12 @@ export async function scanUsageLedgerCooperatively(
|
|
|
486
486
|
export interface ReadUsageLedgerRowsOptions {
|
|
487
487
|
/** Ascending, distinct row-start offsets reported by an earlier scan of the same file. */
|
|
488
488
|
offsets: readonly number[];
|
|
489
|
+
/**
|
|
490
|
+
* Folds rows as they are decoded instead of retaining them in `entries`. Callback work shares
|
|
491
|
+
* the cooperative time slice. Results are provisional until this read resolves: discard them
|
|
492
|
+
* if identity or content validation fails, as with the full-ledger scanner's callback.
|
|
493
|
+
*/
|
|
494
|
+
onEntry?: (entry: PersistedUsageEntry, rowStartBytes: number) => void;
|
|
489
495
|
/** Identity those offsets were captured under; a replaced file invalidates all of them. */
|
|
490
496
|
expectedIdentityKey: string;
|
|
491
497
|
/** Revision the offsets were captured under. Any movement re-validates the boundary. */
|
|
@@ -503,6 +509,7 @@ export interface ReadUsageLedgerRowsOptions {
|
|
|
503
509
|
}
|
|
504
510
|
|
|
505
511
|
export interface UsageLedgerRowRead {
|
|
512
|
+
/** Empty when an onEntry callback consumes the rows. */
|
|
506
513
|
entries: PersistedUsageEntry[];
|
|
507
514
|
/** Offsets that no longer frame a complete, normalizable row. */
|
|
508
515
|
unreadableOffsets: number[];
|
|
@@ -626,27 +633,32 @@ export async function readUsageLedgerRowsAtOffsets(
|
|
|
626
633
|
return null;
|
|
627
634
|
};
|
|
628
635
|
|
|
629
|
-
const walk = (visit: (bytes: Buffer, offset: number) => boolean): number[] => {
|
|
636
|
+
const walk = async (visit: (bytes: Buffer, offset: number) => boolean): Promise<number[]> => {
|
|
630
637
|
const unreadableOffsets: number[] = [];
|
|
638
|
+
let lastYieldAt = performance.now();
|
|
631
639
|
for (const offset of options.offsets) {
|
|
632
640
|
throwIfAborted(options.signal);
|
|
633
641
|
if (!Number.isSafeInteger(offset) || offset < 0 || offset >= size) {
|
|
634
642
|
unreadableOffsets.push(offset);
|
|
635
|
-
|
|
643
|
+
} else {
|
|
644
|
+
const bytes = lineAt(offset);
|
|
645
|
+
if (!bytes || !visit(bytes, offset)) unreadableOffsets.push(offset);
|
|
636
646
|
}
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
647
|
+
// A bounded candidate count does not bound decoding or aggregation time. Include the
|
|
648
|
+
// visitor in the same slice as the full scanner, and let timers/cancellation run even
|
|
649
|
+
// within one page. A single row remains atomic.
|
|
650
|
+
if (performance.now() - lastYieldAt >= MAX_SCAN_SLICE_MS) {
|
|
651
|
+
await new Promise<void>(resolve => setTimeout(resolve, 0));
|
|
652
|
+
throwIfAborted(options.signal);
|
|
653
|
+
lastYieldAt = performance.now();
|
|
641
654
|
}
|
|
642
|
-
if (!visit(bytes, offset)) unreadableOffsets.push(offset);
|
|
643
655
|
}
|
|
644
656
|
return unreadableOffsets;
|
|
645
657
|
};
|
|
646
658
|
|
|
647
659
|
const entries: PersistedUsageEntry[] = [];
|
|
648
660
|
const captured = createHash("sha256");
|
|
649
|
-
const unreadableOffsets = walk((bytes, offset) => {
|
|
661
|
+
const unreadableOffsets = await walk((bytes, offset) => {
|
|
650
662
|
captured.update(bytes);
|
|
651
663
|
captured.update("\0");
|
|
652
664
|
captured.update(String(offset));
|
|
@@ -660,7 +672,8 @@ export async function readUsageLedgerRowsAtOffsets(
|
|
|
660
672
|
// normalizes means the ledger moved under the projection, so it is unreadable rather than
|
|
661
673
|
// silently dropped: the caller rebuilds instead of reporting a smaller complete result.
|
|
662
674
|
if (!entry) return false;
|
|
663
|
-
|
|
675
|
+
if (options.onEntry) options.onEntry(entry, offset);
|
|
676
|
+
else entries.push(entry);
|
|
664
677
|
return true;
|
|
665
678
|
});
|
|
666
679
|
const capturedDigest = captured.digest("hex");
|
|
@@ -675,6 +688,7 @@ export async function readUsageLedgerRowsAtOffsets(
|
|
|
675
688
|
if (!pathRevision || usageLogIdentityKey(pathRevision) !== options.expectedIdentityKey) {
|
|
676
689
|
throw rebuildRequired("identity_mismatch");
|
|
677
690
|
}
|
|
691
|
+
if (pathRevision.size < size) throw rebuildRequired("shrink");
|
|
678
692
|
// Any write during the read can be an in-place rewrite, not just an append. Re-read the
|
|
679
693
|
// same offsets and compare, so a rewrite that lands between two batches cannot publish a
|
|
680
694
|
// mixture of old and new rows. A pure append leaves every selected row unchanged.
|
|
@@ -686,8 +700,11 @@ export async function readUsageLedgerRowsAtOffsets(
|
|
|
686
700
|
if (physical !== undefined && endingRevision.size <= physical) {
|
|
687
701
|
throw rebuildRequired("content_changed");
|
|
688
702
|
}
|
|
703
|
+
// Verification must read the file again, not re-hash a small page still in the read cache.
|
|
704
|
+
windowStart = -1;
|
|
705
|
+
windowLength = 0;
|
|
689
706
|
const verified = createHash("sha256");
|
|
690
|
-
const recheck = walk((bytes, offset) => {
|
|
707
|
+
const recheck = await walk((bytes, offset) => {
|
|
691
708
|
verified.update(bytes);
|
|
692
709
|
verified.update("\0");
|
|
693
710
|
verified.update(String(offset));
|
|
@@ -697,7 +714,24 @@ export async function readUsageLedgerRowsAtOffsets(
|
|
|
697
714
|
|| verified.digest("hex") !== capturedDigest) {
|
|
698
715
|
throw rebuildRequired("content_changed");
|
|
699
716
|
}
|
|
717
|
+
const verifiedFdRevision = revisionFromStat(path, fd, fstatSync(fd));
|
|
718
|
+
const verifiedPathRevision = currentUsageLogRevision();
|
|
719
|
+
if (!verifiedPathRevision
|
|
720
|
+
|| usageLogIdentityKey(verifiedFdRevision) !== options.expectedIdentityKey
|
|
721
|
+
|| usageLogIdentityKey(verifiedPathRevision) !== options.expectedIdentityKey) {
|
|
722
|
+
throw rebuildRequired("identity_mismatch");
|
|
723
|
+
}
|
|
724
|
+
if (verifiedFdRevision.size < size || verifiedPathRevision.size < size) {
|
|
725
|
+
throw rebuildRequired("shrink");
|
|
726
|
+
}
|
|
727
|
+
// Verification yields too. A later write could change bytes already checked, so retry
|
|
728
|
+
// rather than publish a result whose verification raced another mutation.
|
|
729
|
+
if (usageLogRevisionKey(verifiedFdRevision) !== usageLogRevisionKey(endingRevision)
|
|
730
|
+
|| usageLogRevisionKey(verifiedPathRevision) !== usageLogRevisionKey(pathRevision)) {
|
|
731
|
+
throw rebuildRequired("content_changed");
|
|
732
|
+
}
|
|
700
733
|
}
|
|
734
|
+
throwIfAborted(options.signal);
|
|
701
735
|
return { entries, unreadableOffsets };
|
|
702
736
|
} finally {
|
|
703
737
|
closeSync(fd);
|