@bitkyc08/opencodex 2.98.0-preview.20261107 → 2.99.0-preview.20261108
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/bin/ocx.mjs +6 -19
- package/gui/dist/assets/{App-6TFtZsUF.css → App-C1hGwaN1.css} +1 -1
- package/gui/dist/assets/App-CWz0areF.js +59 -0
- package/gui/dist/assets/Tray-BosDoskm.js +1 -0
- package/gui/dist/assets/{brand-mark-VPhzz-WE.js → brand-mark-DpiBmFGI.js} +1 -1
- package/gui/dist/assets/{index-BWKBeK77.js → index-CAxjGWkm.js} +13 -13
- package/gui/dist/assets/index-bnUWypyz.css +2 -0
- package/gui/dist/assets/{segment-thumb-features-BQYzrze9.js → segment-thumb-features-JcszQ18T.js} +1 -1
- package/gui/dist/classic/assets/App-BOEsFmiN.js +58 -0
- package/gui/dist/classic/assets/Tray-5v86r9Az.js +1 -0
- package/gui/dist/classic/assets/{index-Dp2j8bSc.js → index-ClZ_zZ77.js} +13 -13
- package/gui/dist/classic/assets/{quota-summary-CvamtHjB.js → quota-summary-xwvDtvu7.js} +1 -1
- package/gui/dist/classic/index.html +1 -1
- package/gui/dist/index.html +2 -2
- package/package.json +1 -1
- package/src/adapters/coding-agent/protocol.ts +8 -3
- package/src/adapters/coding-agent/turn.ts +6 -2
- package/src/adapters/command-code.ts +8 -5
- package/src/adapters/devin.ts +11 -1
- package/src/adapters/kiro/stream.ts +5 -4
- package/src/adapters/openai-chat/destination-policy.ts +25 -0
- package/src/adapters/openai-chat/native-content.ts +32 -0
- package/src/adapters/openai-chat/passthrough.ts +14 -1
- package/src/adapters/openai-chat/reasoning-wire.ts +42 -1
- package/src/adapters/openai-chat.ts +2 -2
- package/src/adapters/qoder/adapter.ts +9 -0
- package/src/bridge/response-json.ts +13 -1
- package/src/bridge/sse.ts +112 -22
- package/src/cli/account-affinity-reset.ts +42 -0
- package/src/cli/account.ts +5 -0
- package/src/cli/capabilities-accounts.ts +8 -0
- package/src/cli/capabilities-agents-routing.ts +5 -4
- package/src/cli/message-command.ts +1 -1
- package/src/cli/message-mcp-command.ts +8 -5
- package/src/client/orphan-token-recovery.ts +1 -1
- package/src/codex/autostart-health.ts +4 -2
- package/src/generated/compatibility-version.json +128 -76
- package/src/lib/desktop-cli-handoff.mjs +5 -8
- package/src/lib/failure-detail.ts +5 -2
- package/src/lib/launcher-signal-forwarding.d.mts +8 -0
- package/src/lib/launcher-signal-forwarding.mjs +36 -0
- package/src/lib/privacy.ts +6 -0
- package/src/lib/request-execution-budget.ts +188 -33
- package/src/lib/upstream-validation-detail.ts +47 -0
- package/src/lib/workflow-budget.ts +35 -16
- package/src/messaging/mcp-queue-rpc.ts +7 -3
- package/src/messaging/mcp-queue-server.ts +6 -0
- package/src/messaging/mcp-reply-cursor.ts +34 -0
- package/src/messaging/mcp-reply-tools.ts +93 -0
- package/src/oauth/anthropic-routing.ts +46 -3
- package/src/oauth/anthropic-session-affinity-store.ts +23 -10
- package/src/protocols/codecs/ollama.ts +22 -12
- package/src/providers/registry/entries-extended.ts +14 -0
- package/src/remote/hub-usage.ts +7 -0
- package/src/responses/parser.ts +27 -0
- package/src/responses/reasoning-envelope.ts +4 -0
- package/src/responses/schema.ts +1 -0
- package/src/server/chat-completions.ts +3 -0
- package/src/server/chat-native-sse.ts +14 -10
- package/src/server/chat-native.ts +24 -11
- package/src/server/index/websocket-handler.ts +12 -1
- package/src/server/management/oauth-account-routes.ts +65 -13
- package/src/server/management/route-registry.ts +1 -0
- package/src/server/messages-native.ts +21 -5
- package/src/server/request-log-attempt-recovery.ts +17 -0
- package/src/server/request-log-failure-detail.ts +18 -1
- package/src/server/request-log.ts +5 -18
- package/src/server/responses/account-auto-pause-recovery.ts +29 -1
- package/src/server/responses/adapter-continuation.ts +12 -5
- package/src/server/responses/adapter-dispatch.ts +50 -51
- package/src/server/responses/antigravity-model-denial-recovery.ts +4 -2
- package/src/server/responses/codex-ws-exchange.ts +13 -4
- package/src/server/responses/combo-required-tool-contract.ts +22 -3
- package/src/server/responses/core-codex-account.ts +92 -86
- package/src/server/responses/core-combo-failure.ts +7 -0
- package/src/server/responses/core-combo.ts +11 -4
- package/src/server/responses/core-lifetime.ts +3 -0
- package/src/server/responses/deferred-send-reporter.ts +18 -1
- package/src/server/responses/fetch-helpers.ts +9 -3
- package/src/server/responses/native-continuation-refusal.ts +8 -0
- package/src/server/responses/native-continuation-send.ts +34 -0
- package/src/server/responses/passthrough-delivery.ts +6 -2
- package/src/server/responses/passthrough-dispatch.ts +48 -33
- package/src/server/responses/passthrough-execution.ts +1 -0
- package/src/server/responses/policy-fallback.ts +32 -5
- package/src/server/responses/policy-request-scope.ts +26 -0
- package/src/server/responses/request-prepare.ts +11 -2
- package/src/server/responses/request-send-budget.ts +96 -14
- package/src/server/responses/request-spend-target.ts +19 -0
- package/src/server/responses/request-spend.ts +80 -28
- package/src/server/responses/request-transport.ts +106 -53
- package/src/server/responses/run-turn-execution.ts +3 -0
- package/src/server/responses/sidecar-execution.ts +2 -1
- package/src/server/responses/ws-upstream.ts +2 -1
- package/src/server/workflow-refusal.ts +38 -4
- package/src/server/ws-bridge.ts +10 -3
- package/src/service/desktop-startup.ts +76 -13
- package/src/types/request.ts +2 -1
- package/src/usage/app-breakdown.ts +23 -0
- package/src/usage/summary.ts +34 -1
- package/src/web-search/anthropic-executor.ts +25 -9
- package/src/web-search/loop.ts +3 -1
- package/src/web-search/passthrough-bridge.ts +3 -0
- package/src/web-search/run-turn-loop.ts +3 -1
- package/gui/dist/assets/App-B8_sOxoz.js +0 -59
- package/gui/dist/assets/Tray-DpWEp6ee.js +0 -1
- package/gui/dist/assets/index-5REODpG3.css +0 -2
- package/gui/dist/classic/assets/App-Bz65x1J6.js +0 -58
- package/gui/dist/classic/assets/Tray-kk7mdO6I.js +0 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
+
import { forwardLauncherSignals } from "./launcher-signal-forwarding.mjs";
|
|
2
3
|
import { accessSync, constants, realpathSync, statSync } from "node:fs";
|
|
3
4
|
import { posix, win32 } from "node:path";
|
|
4
5
|
import { readDesktopCliRecord } from "./desktop-cli-record.mjs";
|
|
@@ -60,24 +61,20 @@ export function runDesktopCliHandoff(plan, launch, deps = {}) {
|
|
|
60
61
|
delete env.OCX_BUN_RUNTIME_SOURCE;
|
|
61
62
|
delete env.OCX_BUN_RUNTIME_PATH;
|
|
62
63
|
return new Promise(resolveExit => {
|
|
64
|
+
const forwarding = forwardLauncherSignals({ parent, platform });
|
|
63
65
|
let child;
|
|
64
66
|
try {
|
|
65
67
|
child = spawnChild(plan.target, [`${PROOF_PREFIX}${launch.proof}`, ...argv], {
|
|
66
68
|
stdio: "inherit", shell: false, windowsHide: true, env,
|
|
67
69
|
});
|
|
68
70
|
} catch {
|
|
71
|
+
forwarding.clear();
|
|
69
72
|
resolveExit(spawnFailure());
|
|
70
73
|
return;
|
|
71
74
|
}
|
|
72
|
-
|
|
73
|
-
const handlers = forwarded.map(signal => {
|
|
74
|
-
const handler = () => { try { child.kill(signal); } catch { /* child already exited */ } };
|
|
75
|
-
parent.on(signal, handler);
|
|
76
|
-
return [signal, handler];
|
|
77
|
-
});
|
|
78
|
-
const clear = () => { for (const [signal, handler] of handlers) parent.removeListener(signal, handler); };
|
|
75
|
+
forwarding.attach(child);
|
|
79
76
|
let done = false;
|
|
80
|
-
const finish = result => { if (done) return; done = true; clear(); resolveExit(result); };
|
|
77
|
+
const finish = result => { if (done) return; done = true; forwarding.clear(); resolveExit(result); };
|
|
81
78
|
child.once("error", () => finish(spawnFailure()));
|
|
82
79
|
let delegateError = false;
|
|
83
80
|
child.once("exit", (code, signal) => finish(delegateError ? { kind: "error", issue: "spawn-failed" } : { kind: "exit", code: code ?? 1, signal }));
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { boundedValidationIssues, type ValidationIssue } from "./upstream-validation-detail";
|
|
1
2
|
/**
|
|
2
3
|
* Failure detail a request-log row may carry: a closed code plus bounded numeric or closed parameters.
|
|
3
4
|
* The dashboard renders each code as localized text; rows never hold free-form failure text.
|
|
@@ -35,6 +36,7 @@ export interface FailureDetail {
|
|
|
35
36
|
/** Milliseconds for timeouts and stalls, bytes for an overflow. */
|
|
36
37
|
value?: number;
|
|
37
38
|
type?: FailureDetailProviderType;
|
|
39
|
+
validation?: ValidationIssue[];
|
|
38
40
|
}
|
|
39
41
|
|
|
40
42
|
const CODES: ReadonlySet<string> = new Set(FAILURE_DETAIL_CODES);
|
|
@@ -59,8 +61,9 @@ export function boundedFailureDetail(value: unknown): FailureDetail | undefined
|
|
|
59
61
|
const valid = typeof number === "number" && Number.isSafeInteger(number) && number >= 0 && number <= MAX_VALUE && VALUED.has(code);
|
|
60
62
|
const type = code === "provider_error" && typeof record.type === "string" && TYPES.has(record.type)
|
|
61
63
|
? record.type as FailureDetailProviderType : undefined;
|
|
64
|
+
const validation = code === "provider_error" ? boundedValidationIssues(record.validation) : undefined;
|
|
62
65
|
const keys = Object.keys(record);
|
|
63
|
-
const exact = keys.every(key => key === "code" || (key === "value" && valid) || (key === "type" && type !== undefined));
|
|
66
|
+
const exact = keys.every(key => key === "code" || (key === "value" && valid) || (key === "type" && type !== undefined) || (key === "validation" && validation !== undefined && validation === record.validation));
|
|
64
67
|
if (exact) return record as unknown as FailureDetail;
|
|
65
|
-
return { code, ...(valid ? { value: number as number } : {}), ...(type ? { type } : {}) };
|
|
68
|
+
return { code, ...(valid ? { value: number as number } : {}), ...(type ? { type } : {}), ...(validation ? { validation } : {}) };
|
|
66
69
|
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export function launcherForwardedSignals(platform?: NodeJS.Platform): NodeJS.Signals[];
|
|
2
|
+
export interface LauncherSignalForwarding {
|
|
3
|
+
attach(child: { kill(signal: NodeJS.Signals): unknown }): void;
|
|
4
|
+
clear(): void;
|
|
5
|
+
}
|
|
6
|
+
export function forwardLauncherSignals(deps?: {
|
|
7
|
+
parent?: Pick<NodeJS.Process, "on" | "removeListener">; platform?: NodeJS.Platform;
|
|
8
|
+
}): LauncherSignalForwarding;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Termination signals a Node launcher relays to the child it starts. Windows has no real POSIX
|
|
2
|
+
// signals (no SIGHUP), so forwarding there is best-effort.
|
|
3
|
+
export function launcherForwardedSignals(platform = process.platform) {
|
|
4
|
+
return platform === "win32" ? ["SIGINT", "SIGTERM"] : ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
// Install the forwarders BEFORE spawning the child, then attach() the child once it exists.
|
|
8
|
+
// A listener registered only after spawn() returns leaves a window in which the child has already
|
|
9
|
+
// started (and may have written output a supervisor treats as ready) while a signal to the
|
|
10
|
+
// launcher still takes the default action: the launcher dies, its exit cleanup never runs, and
|
|
11
|
+
// the child is orphaned without ever seeing the signal. A signal observed before attach() is held
|
|
12
|
+
// and delivered to the child as soon as it is attached.
|
|
13
|
+
export function forwardLauncherSignals(deps = {}) {
|
|
14
|
+
const parent = deps.parent ?? process;
|
|
15
|
+
let child = null;
|
|
16
|
+
let cleared = false;
|
|
17
|
+
const pending = [];
|
|
18
|
+
const send = signal => { try { child.kill(signal); } catch { /* child already exited */ } };
|
|
19
|
+
const handlers = launcherForwardedSignals(deps.platform ?? process.platform).map(signal => {
|
|
20
|
+
const handler = () => { if (child) send(signal); else pending.push(signal); };
|
|
21
|
+
parent.on(signal, handler);
|
|
22
|
+
return [signal, handler];
|
|
23
|
+
});
|
|
24
|
+
return {
|
|
25
|
+
attach(spawned) {
|
|
26
|
+
if (cleared || child) return;
|
|
27
|
+
child = spawned;
|
|
28
|
+
for (const signal of pending.splice(0)) send(signal);
|
|
29
|
+
},
|
|
30
|
+
clear() {
|
|
31
|
+
if (cleared) return;
|
|
32
|
+
cleared = true;
|
|
33
|
+
for (const [signal, handler] of handlers) parent.removeListener(signal, handler);
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
}
|
package/src/lib/privacy.ts
CHANGED
|
@@ -10,6 +10,12 @@ export function maskEmail(value: string | null | undefined): string | null {
|
|
|
10
10
|
return `${local[0]}***${local[local.length - 1]}@${domain}`;
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
/** A display label that never falls back to an unmasked or malformed identity. */
|
|
14
|
+
export function maskedAccountLabel(value: string | null | undefined): string | undefined {
|
|
15
|
+
if (!value || value.length > 254 || !/^[A-Za-z0-9_%+\-]+(?:\.[A-Za-z0-9_%+\-]+)*@[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*$/.test(value)) return undefined;
|
|
16
|
+
return maskEmail(value) ?? undefined;
|
|
17
|
+
}
|
|
18
|
+
|
|
13
19
|
/**
|
|
14
20
|
* Whether stored account emails are masked in management and CLI projections (#3859).
|
|
15
21
|
*
|
|
@@ -25,8 +25,15 @@ export type SendClass =
|
|
|
25
25
|
| "repair"
|
|
26
26
|
| "account-failover"
|
|
27
27
|
| "combo-failover"
|
|
28
|
+
| "auxiliary"
|
|
28
29
|
| "prewarm";
|
|
29
30
|
|
|
31
|
+
/** A helper inference owns its admission and never consumes a routed leg's permit. */
|
|
32
|
+
export type AuxiliaryModelSend = <T>(
|
|
33
|
+
target: Pick<SpendScopes, "identityId"> & { poolId: string; targetKey: string; estimate: { inputTokens: number; outputCeilingTokens: number } },
|
|
34
|
+
dispatch: () => Promise<T>,
|
|
35
|
+
) => Promise<T>;
|
|
36
|
+
|
|
30
37
|
export interface RequestExecutionBudgetPolicy {
|
|
31
38
|
/** Every model send of one logical request, including the reserve. */
|
|
32
39
|
readonly maxTotalModelSends: number;
|
|
@@ -68,6 +75,9 @@ export interface DispatchIntent {
|
|
|
68
75
|
* different thing and must not be folded in here.
|
|
69
76
|
*/
|
|
70
77
|
readonly targetKey: string;
|
|
78
|
+
/** Auxiliary inference uses its own provider scopes without rebasing the routed target. */
|
|
79
|
+
readonly spendScopes?: Pick<SpendScopes, "identityId" | "poolId">;
|
|
80
|
+
readonly spendEstimate?: { inputTokens: number; outputCeilingTokens: number };
|
|
71
81
|
/**
|
|
72
82
|
* False refuses the dispatch outright. A request whose execution state upstream is unknown
|
|
73
83
|
* is not replayable just because budget remains (RFC 9110 9.2.2).
|
|
@@ -140,6 +150,10 @@ export type DispatchDecision =
|
|
|
140
150
|
* send rather than merely describe one.
|
|
141
151
|
*/
|
|
142
152
|
export interface RequestSendObserver {
|
|
153
|
+
/** Atomically claim the root workflow count at physical admission, before inference I/O. */
|
|
154
|
+
beforePhysicalSend?(auxiliary?: boolean): boolean;
|
|
155
|
+
/** Record an already-sent legacy receipt without booking its durable spend twice. */
|
|
156
|
+
recordWorkflowSend?(): void;
|
|
143
157
|
/**
|
|
144
158
|
* Book one physical send. False refuses the dispatch before the budget charges it.
|
|
145
159
|
*
|
|
@@ -149,14 +163,16 @@ export interface RequestSendObserver {
|
|
|
149
163
|
* would cross a ceiling never joins the total, the total stays just under, and the ceiling
|
|
150
164
|
* never fires for any later request either.
|
|
151
165
|
*/
|
|
152
|
-
charge(options?: { alreadySent?: boolean; deferDispatch?: boolean; onReserved?: (proof: SpendReservationProof) => void; targetKey?: string }): boolean;
|
|
166
|
+
charge(options?: { alreadySent?: boolean; deferDispatch?: boolean; workflowAlreadyCounted?: boolean; onReserved?: (proof: SpendReservationProof) => void; targetKey?: string; scopes?: Pick<SpendScopes, "identityId" | "poolId">; auxiliary?: boolean; estimate?: { inputTokens: number; outputCeilingTokens: number } }): boolean;
|
|
153
167
|
/** Confirm the exact reservation once its dispatch is known. */
|
|
154
168
|
readonly enforced?: boolean;
|
|
155
169
|
readonly policyStarted?: boolean;
|
|
156
170
|
readonly spendAdmissionPolicy?: SpendAdmissionPolicy;
|
|
157
171
|
/** Capture request policy at its first admission or actual physical start. */
|
|
158
172
|
startRequest?(target?: SpendScopes & { targetKey?: string }): void;
|
|
159
|
-
ensureSeed?(target: SpendScopes & { targetKey?: string }, proof?: SpendReservationProof): SpendSeed | undefined;
|
|
173
|
+
ensureSeed?(target: SpendScopes & { targetKey?: string; auxiliary?: boolean; estimate?: { inputTokens: number; outputCeilingTokens: number }; explicitEstimate?: boolean }, proof?: SpendReservationProof): SpendSeed | undefined;
|
|
174
|
+
/** Release only this tracker's unstarted seed when physical admission refuses it. */
|
|
175
|
+
releaseSeed?(seed: SpendSeed): void;
|
|
160
176
|
beginReporter?(): { start(seed: SpendSeed, ordinal: number): void; rebindTarget(target: SpendScopes & { targetKey?: string }, ordinal: number): boolean; report(sends: number): void; close(): void };
|
|
161
177
|
dispatch?(proof: SpendReservationProof): void;
|
|
162
178
|
/** Give back a booking whose send never happened. */
|
|
@@ -172,10 +188,16 @@ export interface RequestExecutionBudget extends TransientSendBudget {
|
|
|
172
188
|
readonly physicalStarted?: number;
|
|
173
189
|
readonly physicalLimit?: number;
|
|
174
190
|
readonly spendEnforced?: boolean;
|
|
191
|
+
/** True when physical admission owns this budget's root workflow accounting. */
|
|
192
|
+
readonly workflowCountObserved?: boolean;
|
|
175
193
|
readonly spendPolicyStarted?: boolean;
|
|
176
194
|
readonly spendAdmissionPolicy?: SpendAdmissionPolicy;
|
|
177
195
|
startRequest?(target?: SpendScopes & { targetKey?: string }): void;
|
|
178
|
-
claimPhysicalSend?(): number | undefined;
|
|
196
|
+
claimPhysicalSend?(auxiliary?: boolean): number | undefined;
|
|
197
|
+
/** A validated explicit successor still pays root/spend admission, not the recovery allowance. */
|
|
198
|
+
claimContinuationPhysicalSend?(): number | undefined;
|
|
199
|
+
/** Claim one root workflow send at physical admission; false refuses the send. */
|
|
200
|
+
claimWorkflowSend?(auxiliary?: boolean): boolean;
|
|
179
201
|
beginSpendProducer?(): { close(): void } | undefined;
|
|
180
202
|
readonly logicalRequestId: string;
|
|
181
203
|
readonly policyVersion: string;
|
|
@@ -247,7 +269,10 @@ let logicalRequestSeq = 0;
|
|
|
247
269
|
interface SharedSendLedger {
|
|
248
270
|
spent: number;
|
|
249
271
|
physicalStarted: number;
|
|
272
|
+
explicitPhysicalStarted: number;
|
|
250
273
|
physicalLimit?: number;
|
|
274
|
+
/** Foreign legacy views retain one bounded recovery owner across derived bridges. */
|
|
275
|
+
recoveryOwner?: RequestExecutionBudget;
|
|
251
276
|
pendingExternalSends: Set<object>;
|
|
252
277
|
/**
|
|
253
278
|
* Spend one of this logical request's replacements for an ambiguous failure. Beside `spent`
|
|
@@ -264,6 +289,23 @@ interface SharedSendLedger {
|
|
|
264
289
|
}
|
|
265
290
|
|
|
266
291
|
const sharedSendLedgers = new WeakMap<RequestExecutionBudget, SharedSendLedger>();
|
|
292
|
+
interface SameTargetRecoveryScope {
|
|
293
|
+
targetKey: string;
|
|
294
|
+
maxAdditionalSends: number;
|
|
295
|
+
physicalLimit: number;
|
|
296
|
+
reservationPrefix: string;
|
|
297
|
+
reservationSequence: number;
|
|
298
|
+
}
|
|
299
|
+
export interface BoundedSameTargetRecovery {
|
|
300
|
+
readonly workflowCountObserved: boolean;
|
|
301
|
+
/** Reserve an additional same-target send within the fixed, shared recovery grant. */
|
|
302
|
+
reserve(): DispatchDecision;
|
|
303
|
+
}
|
|
304
|
+
const sameTargetRecoveries = new WeakMap<object, { targetKey: string; recovery: BoundedSameTargetRecovery }>();
|
|
305
|
+
/** Whether physical admission owns this budget's workflow accounting. */
|
|
306
|
+
export function hasWorkflowSendObserver(budget: TransientSendBudget): boolean {
|
|
307
|
+
return (budget as RequestExecutionBudget).workflowCountObserved === true;
|
|
308
|
+
}
|
|
267
309
|
const dispatchSpendProofs = new WeakMap<SingleUseDispatchPermit, {
|
|
268
310
|
owner: SharedSendLedger;
|
|
269
311
|
claim(): SpendReservationProof | undefined;
|
|
@@ -276,11 +318,17 @@ export function claimDispatchSpendProof(budget: RequestExecutionBudget, permit?:
|
|
|
276
318
|
return proof && proof.owner === sharedSendLedgers.get(budget) ? proof.claim() : undefined;
|
|
277
319
|
}
|
|
278
320
|
|
|
279
|
-
/**
|
|
321
|
+
/**
|
|
322
|
+
* Reports actual sends against only the named permit on this shared ledger.
|
|
323
|
+
* `workflowAlreadyCounted` marks starts already charged at physical admission:
|
|
324
|
+
* non-enforced observers then record request-ledger spend without charging the root again.
|
|
325
|
+
* Enforced sends remain reconciled through their producer's claimed starts.
|
|
326
|
+
*/
|
|
280
327
|
export function reportDispatchSends(
|
|
281
328
|
budget: TransientSendBudget,
|
|
282
329
|
sends: number,
|
|
283
330
|
permit?: SingleUseDispatchPermit,
|
|
331
|
+
workflowAlreadyCounted = false,
|
|
284
332
|
): void {
|
|
285
333
|
const count = Number.isFinite(sends) ? Math.max(0, Math.trunc(sends)) : 0;
|
|
286
334
|
if (count === 0) return;
|
|
@@ -288,7 +336,12 @@ export function reportDispatchSends(
|
|
|
288
336
|
const prepaid = receipt && receipt.owner === sharedSendLedgers.get(budget as RequestExecutionBudget)
|
|
289
337
|
&& receipt.report() ? 1 : 0;
|
|
290
338
|
// Unnamed, foreign, released or already-reported permits cannot consume another receipt.
|
|
291
|
-
|
|
339
|
+
const counter = sharedSendLedgers.get(budget as RequestExecutionBudget);
|
|
340
|
+
if (!workflowAlreadyCounted && prepaid > 0) counter?.observer?.recordWorkflowSend?.();
|
|
341
|
+
if (workflowAlreadyCounted && counter && counter.observer?.enforced !== true) {
|
|
342
|
+
counter.spent += count - prepaid;
|
|
343
|
+
for (let index = prepaid; index < count; index++) counter.observer?.charge({ alreadySent: true, workflowAlreadyCounted: true });
|
|
344
|
+
} else budget.used += count - prepaid;
|
|
292
345
|
}
|
|
293
346
|
|
|
294
347
|
/** A helper owns its starts and can never consume another helper's receipts. */
|
|
@@ -304,11 +357,17 @@ export function rebindPhysicalSend(budget: TransientSendBudget | undefined, targ
|
|
|
304
357
|
if (!(budget as RequestExecutionBudget | undefined)?.spendEnforced) return true;
|
|
305
358
|
return activePhysicalReporters.getStore()?.bind?.(target) ?? true;
|
|
306
359
|
}
|
|
360
|
+
/**
|
|
361
|
+
* Bind observations to this helper's starts and matching permit receipt.
|
|
362
|
+
* `beforeSend` refuses disallowed starts. Producer-backed reports are capped to
|
|
363
|
+
* unreported starts; excess legacy reports remain charged as observed sends.
|
|
364
|
+
*/
|
|
307
365
|
export function createPhysicalSendReporter(
|
|
308
366
|
budget: TransientSendBudget,
|
|
309
|
-
target: () => SpendScopes & { targetKey?: string },
|
|
367
|
+
target: () => SpendScopes & { targetKey?: string; estimate?: { inputTokens: number; outputCeilingTokens: number }; explicitEstimate?: boolean },
|
|
310
368
|
permit?: SingleUseDispatchPermit,
|
|
311
369
|
telemetry?: (sends: number) => void,
|
|
370
|
+
options: { explicitContinuation?: boolean } = {},
|
|
312
371
|
): PhysicalSendReporter {
|
|
313
372
|
const counter = sharedSendLedgers.get(budget as RequestExecutionBudget);
|
|
314
373
|
const observer = counter?.observer;
|
|
@@ -319,7 +378,16 @@ export function createPhysicalSendReporter(
|
|
|
319
378
|
let currentOrdinal: number | undefined;
|
|
320
379
|
const report: PhysicalSendReporter = (sends) => {
|
|
321
380
|
if (closed) return;
|
|
322
|
-
if (!producer) {
|
|
381
|
+
if (!producer) {
|
|
382
|
+
if (observer?.enforced === true) return;
|
|
383
|
+
const count = Number.isFinite(sends) ? Math.max(0, Math.trunc(sends)) : 0;
|
|
384
|
+
const admitted = Math.min(count, started - reported);
|
|
385
|
+
if (admitted > 0) reportDispatchSends(budget, admitted, permit, true);
|
|
386
|
+
if (count > admitted) reportDispatchSends(budget, count - admitted, permit);
|
|
387
|
+
reported += admitted;
|
|
388
|
+
telemetry?.(count);
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
323
391
|
const count = Math.min(Math.max(0, Math.trunc(sends)), started - reported);
|
|
324
392
|
try { producer.report(count); }
|
|
325
393
|
finally {
|
|
@@ -335,14 +403,20 @@ export function createPhysicalSendReporter(
|
|
|
335
403
|
const selected = target();
|
|
336
404
|
if ((budget as RequestExecutionBudget).startRequest) (budget as RequestExecutionBudget).startRequest!(selected);
|
|
337
405
|
else observer?.startRequest?.(selected);
|
|
338
|
-
if (observer?.enforced !== true)
|
|
406
|
+
if (observer?.enforced !== true) {
|
|
407
|
+
if (observer?.beforePhysicalSend?.() === false) return false;
|
|
408
|
+
started++;
|
|
409
|
+
return true;
|
|
410
|
+
}
|
|
339
411
|
producer ??= observer.beginReporter?.();
|
|
340
412
|
const receipt = permit && dispatchSpendProofs.get(permit);
|
|
341
413
|
const proof = receipt?.owner === counter ? receipt?.claim() : undefined;
|
|
342
414
|
const seed = observer.ensureSeed?.(selected, proof);
|
|
343
415
|
if (!seed) return false;
|
|
344
|
-
const ordinal =
|
|
345
|
-
|
|
416
|
+
const ordinal = options.explicitContinuation
|
|
417
|
+
? (budget as RequestExecutionBudget).claimContinuationPhysicalSend?.()
|
|
418
|
+
: (budget as RequestExecutionBudget).claimPhysicalSend?.();
|
|
419
|
+
if (ordinal === undefined) { observer.releaseSeed?.(seed); return false; }
|
|
346
420
|
producer?.start(seed, ordinal);
|
|
347
421
|
currentOrdinal = ordinal;
|
|
348
422
|
started++;
|
|
@@ -397,18 +471,24 @@ function createRequestExecutionBudgetWithLedger(
|
|
|
397
471
|
policy: RequestExecutionBudgetPolicy,
|
|
398
472
|
logicalRequestId: string | undefined,
|
|
399
473
|
counter: SharedSendLedger,
|
|
474
|
+
recovery?: SameTargetRecoveryScope,
|
|
400
475
|
): RequestExecutionBudget {
|
|
401
476
|
const observer = counter.observer;
|
|
402
477
|
let reserveSpent = false;
|
|
403
478
|
let alternateTargetSends = 0;
|
|
404
479
|
let targetTransitions = 0;
|
|
405
|
-
let
|
|
480
|
+
let recoverySends = 0;
|
|
481
|
+
let lastTargetKey: string | undefined = recovery?.targetKey;
|
|
406
482
|
const targetReservations: Array<{ targetKey: string }> = [];
|
|
407
483
|
|
|
408
484
|
const budget: RequestExecutionBudget = {
|
|
409
485
|
get physicalStarted(): number { return counter.physicalStarted; },
|
|
410
|
-
get physicalLimit(): number | undefined {
|
|
486
|
+
get physicalLimit(): number | undefined {
|
|
487
|
+
const limit = recovery?.physicalLimit ?? counter.physicalLimit;
|
|
488
|
+
return limit === undefined ? undefined : limit + counter.explicitPhysicalStarted;
|
|
489
|
+
},
|
|
411
490
|
get spendEnforced(): boolean { return observer?.enforced === true; },
|
|
491
|
+
get workflowCountObserved(): boolean { return observer?.beforePhysicalSend !== undefined; },
|
|
412
492
|
get spendPolicyStarted(): boolean { return observer?.policyStarted === true; },
|
|
413
493
|
get spendAdmissionPolicy(): SpendAdmissionPolicy | undefined { return observer?.spendAdmissionPolicy; },
|
|
414
494
|
startRequest(target) {
|
|
@@ -418,10 +498,22 @@ function createRequestExecutionBudgetWithLedger(
|
|
|
418
498
|
}
|
|
419
499
|
},
|
|
420
500
|
beginSpendProducer() { return observer?.enforced ? observer.beginReporter?.() : undefined; },
|
|
421
|
-
|
|
501
|
+
claimWorkflowSend(auxiliary = false): boolean {
|
|
422
502
|
budget.startRequest?.();
|
|
423
|
-
|
|
424
|
-
|
|
503
|
+
return (auxiliary ? observer?.beforePhysicalSend?.(true) : observer?.beforePhysicalSend?.()) ?? true;
|
|
504
|
+
},
|
|
505
|
+
claimPhysicalSend(auxiliary = false): number | undefined {
|
|
506
|
+
budget.startRequest?.();
|
|
507
|
+
const limit = recovery?.physicalLimit ?? counter.physicalLimit;
|
|
508
|
+
if (observer?.enforced !== true || limit === undefined) return undefined;
|
|
509
|
+
if (counter.physicalStarted - counter.explicitPhysicalStarted >= limit
|
|
510
|
+
|| !(auxiliary ? budget.claimWorkflowSend!(true) : budget.claimWorkflowSend!())) return undefined;
|
|
511
|
+
return ++counter.physicalStarted;
|
|
512
|
+
},
|
|
513
|
+
claimContinuationPhysicalSend(): number | undefined {
|
|
514
|
+
budget.startRequest?.();
|
|
515
|
+
if (recovery || observer?.enforced !== true || !budget.claimWorkflowSend!()) return undefined;
|
|
516
|
+
counter.explicitPhysicalStarted++;
|
|
425
517
|
return ++counter.physicalStarted;
|
|
426
518
|
},
|
|
427
519
|
get used(): number { return counter.spent; },
|
|
@@ -458,10 +550,16 @@ function createRequestExecutionBudgetWithLedger(
|
|
|
458
550
|
},
|
|
459
551
|
get ambiguousResendSpent(): boolean { return counter.ambiguousResendSpent; },
|
|
460
552
|
reserveDispatch(intent: DispatchIntent): DispatchDecision {
|
|
553
|
+
if (recovery && (intent.targetKey !== recovery.targetKey || intent.sendClass !== "transient")) {
|
|
554
|
+
return { allowed: false, reason: "target-transition-exhausted" };
|
|
555
|
+
}
|
|
556
|
+
if (recovery && recoverySends >= recovery.maxAdditionalSends) return { allowed: false, reason: "total-exhausted" };
|
|
461
557
|
if (intent.replaySafe === false) return { allowed: false, reason: "not-replay-safe" };
|
|
462
558
|
if (counter.spent >= policy.maxTotalModelSends) return { allowed: false, reason: "total-exhausted" };
|
|
463
559
|
|
|
464
|
-
const
|
|
560
|
+
const auxiliary = intent.sendClass === "auxiliary";
|
|
561
|
+
const countedExternally = !auxiliary && intent.countedExternally === true;
|
|
562
|
+
const changesTarget = !auxiliary && lastTargetKey !== undefined && lastTargetKey !== intent.targetKey;
|
|
465
563
|
const isAlternateTarget = changesTarget || intent.sendClass === "account-failover"
|
|
466
564
|
|| intent.sendClass === "combo-failover";
|
|
467
565
|
const chargesTransition = changesTarget && intent.rebasedTarget !== true;
|
|
@@ -489,9 +587,17 @@ function createRequestExecutionBudgetWithLedger(
|
|
|
489
587
|
// Consulted last, because it is the only bound here that WRITES. A ledger entry booked
|
|
490
588
|
// for a dispatch a cheaper check above would have refused is spend this request never
|
|
491
589
|
// makes, and it would hold those tokens against the scope until retention expired.
|
|
492
|
-
|
|
590
|
+
// Extra same-target recovery is outside the request's original physical allowance.
|
|
591
|
+
// Each rung therefore needs fresh normal-capacity spend admission; it cannot reuse
|
|
592
|
+
// an earlier seed to turn a request-total exception into a token-ceiling exception.
|
|
593
|
+
const spendTargetKey = recovery
|
|
594
|
+
? `${recovery.reservationPrefix}:${++recovery.reservationSequence}` : intent.targetKey;
|
|
595
|
+
const spendTarget = { ...(auxiliary ? { ...intent.spendScopes, estimate: intent.spendEstimate, auxiliary: true } : {}), targetKey: spendTargetKey };
|
|
596
|
+
budget.startRequest?.(spendTarget);
|
|
493
597
|
let spendProof: SpendReservationProof | undefined;
|
|
494
|
-
if (observer && !observer.charge({ targetKey:
|
|
598
|
+
if (observer && !observer.charge({ targetKey: spendTargetKey,
|
|
599
|
+
...(auxiliary ? { scopes: intent.spendScopes, estimate: intent.spendEstimate, auxiliary: true } : {}),
|
|
600
|
+
deferDispatch: true, onReserved: proof => { spendProof = proof; } })) {
|
|
495
601
|
return { allowed: false, reason: "spend-exhausted" };
|
|
496
602
|
}
|
|
497
603
|
|
|
@@ -500,23 +606,24 @@ function createRequestExecutionBudgetWithLedger(
|
|
|
500
606
|
// one remaining send admitted two physical sends, which is the per-request multiplication
|
|
501
607
|
// this budget exists to stop. Everything is booked now; `release()` is the way back.
|
|
502
608
|
counter.spent += 1;
|
|
609
|
+
if (recovery) recoverySends += 1;
|
|
503
610
|
const receipt = { targetKey: intent.targetKey };
|
|
504
|
-
targetReservations.push(receipt);
|
|
505
|
-
if (
|
|
611
|
+
if (!auxiliary) targetReservations.push(receipt);
|
|
612
|
+
if (countedExternally) counter.pendingExternalSends.add(receipt);
|
|
506
613
|
if (drawsReserve) reserveSpent = true;
|
|
507
614
|
if (chargesAlternateTarget) alternateTargetSends += 1;
|
|
508
615
|
if (chargesTransition) targetTransitions += 1;
|
|
509
|
-
lastTargetKey = intent.targetKey;
|
|
616
|
+
if (!auxiliary) lastTargetKey = intent.targetKey;
|
|
510
617
|
|
|
511
618
|
let producer: ReturnType<NonNullable<RequestSendObserver["beginReporter"]>> | undefined;
|
|
512
619
|
let executing = false;
|
|
513
620
|
let physicalOrdinal: number | undefined;
|
|
514
621
|
const startPhysical = (): boolean => {
|
|
515
|
-
if (observer?.enforced !== true) return true;
|
|
516
|
-
const seed = observer.ensureSeed?.(
|
|
622
|
+
if (observer?.enforced !== true) return auxiliary ? budget.claimWorkflowSend!(true) : budget.claimWorkflowSend!();
|
|
623
|
+
const seed = observer.ensureSeed?.(spendTarget, spendProof);
|
|
517
624
|
if (!seed) return false;
|
|
518
|
-
const ordinal = budget.claimPhysicalSend?.();
|
|
519
|
-
if (ordinal === undefined) return false;
|
|
625
|
+
const ordinal = auxiliary ? budget.claimPhysicalSend?.(true) : budget.claimPhysicalSend?.();
|
|
626
|
+
if (ordinal === undefined) { observer.releaseSeed?.(seed); return false; }
|
|
520
627
|
producer = observer.beginReporter?.();
|
|
521
628
|
producer?.start(seed, ordinal);
|
|
522
629
|
physicalOrdinal = ordinal;
|
|
@@ -540,18 +647,18 @@ function createRequestExecutionBudgetWithLedger(
|
|
|
540
647
|
},
|
|
541
648
|
use(): boolean {
|
|
542
649
|
if (settled !== "open") return false;
|
|
543
|
-
if (
|
|
650
|
+
if (!countedExternally && !startPhysical()) return false;
|
|
544
651
|
settled = "used";
|
|
545
|
-
if (
|
|
652
|
+
if (!countedExternally && spendProof) observer?.dispatch?.(spendProof);
|
|
546
653
|
return true;
|
|
547
654
|
},
|
|
548
655
|
assumeCharge(): boolean {
|
|
549
|
-
if (settled !== "open" || (
|
|
656
|
+
if (settled !== "open" || (countedExternally && !counter.pendingExternalSends.has(receipt))) return false;
|
|
550
657
|
if (!startPhysical()) return false;
|
|
551
658
|
settled = "used";
|
|
552
659
|
// The booking this reservation made for an external reporter is now owned by the
|
|
553
660
|
// caller. Close only its own receipt so a later reporter cannot spend it again.
|
|
554
|
-
if (
|
|
661
|
+
if (countedExternally) counter.pendingExternalSends.delete(receipt);
|
|
555
662
|
if (spendProof) observer?.dispatch?.(spendProof);
|
|
556
663
|
return true;
|
|
557
664
|
},
|
|
@@ -560,16 +667,19 @@ function createRequestExecutionBudgetWithLedger(
|
|
|
560
667
|
settled = "released";
|
|
561
668
|
// An externally counted reservation the reporter already settled paid for a send
|
|
562
669
|
// that physically happened. Refunding it would hand the request a free send back.
|
|
563
|
-
if (
|
|
670
|
+
if (countedExternally) {
|
|
564
671
|
if (!counter.pendingExternalSends.delete(receipt)) return;
|
|
565
672
|
}
|
|
566
673
|
counter.spent -= 1;
|
|
674
|
+
if (recovery) recoverySends -= 1;
|
|
567
675
|
observer?.refund(spendProof ?? null);
|
|
568
676
|
if (drawsReserve) reserveSpent = false;
|
|
569
677
|
if (chargesAlternateTarget) alternateTargetSends -= 1;
|
|
570
678
|
if (chargesTransition) targetTransitions -= 1;
|
|
571
|
-
|
|
572
|
-
|
|
679
|
+
if (!auxiliary) {
|
|
680
|
+
targetReservations.splice(targetReservations.indexOf(receipt), 1);
|
|
681
|
+
lastTargetKey = targetReservations.at(-1)?.targetKey;
|
|
682
|
+
}
|
|
573
683
|
},
|
|
574
684
|
};
|
|
575
685
|
let preflightClaimed = false;
|
|
@@ -582,7 +692,7 @@ function createRequestExecutionBudgetWithLedger(
|
|
|
582
692
|
return true;
|
|
583
693
|
}, claim: () => {
|
|
584
694
|
if (preflightClaimed || settled === "released"
|
|
585
|
-
|| (
|
|
695
|
+
|| (countedExternally ? !counter.pendingExternalSends.has(receipt) : settled !== "open")) return undefined;
|
|
586
696
|
preflightClaimed = true;
|
|
587
697
|
return spendProof;
|
|
588
698
|
} });
|
|
@@ -602,6 +712,7 @@ export function createRequestExecutionBudget(
|
|
|
602
712
|
return createRequestExecutionBudgetWithLedger(policy, logicalRequestId, {
|
|
603
713
|
spent: 0,
|
|
604
714
|
physicalStarted: 0,
|
|
715
|
+
explicitPhysicalStarted: 0,
|
|
605
716
|
pendingExternalSends: new Set(),
|
|
606
717
|
claimAmbiguousResend: grant.claimAmbiguousResend,
|
|
607
718
|
get ambiguousResendSpent(): boolean { return grant.ambiguousResendSpent; },
|
|
@@ -627,6 +738,48 @@ export function deriveRequestExecutionBudget(
|
|
|
627
738
|
return createRequestExecutionBudgetWithLedger(policy, parent.logicalRequestId, ledgerFor(parent));
|
|
628
739
|
}
|
|
629
740
|
|
|
741
|
+
/**
|
|
742
|
+
* A validated same-target recovery may own a bounded exception to the request send total.
|
|
743
|
+
* It shares all spend/root accounting, but never raises the parent's ordinary allowances.
|
|
744
|
+
* The first grant is fixed for this shared ledger; another target or caller cannot replenish it.
|
|
745
|
+
*/
|
|
746
|
+
export function createBoundedSameTargetRecovery(
|
|
747
|
+
parent: RequestExecutionBudget,
|
|
748
|
+
targetKey: string,
|
|
749
|
+
maxAdditionalSends: number,
|
|
750
|
+
): BoundedSameTargetRecovery {
|
|
751
|
+
const counter = sharedSendLedgers.get(parent);
|
|
752
|
+
const owner = counter?.recoveryOwner ?? counter ?? parent;
|
|
753
|
+
const existing = sameTargetRecoveries.get(owner);
|
|
754
|
+
const refused = (reason: BudgetDenial): BoundedSameTargetRecovery => ({
|
|
755
|
+
workflowCountObserved: false, reserve: () => ({ allowed: false, reason }),
|
|
756
|
+
});
|
|
757
|
+
if (existing) return existing.targetKey === targetKey ? existing.recovery : refused("target-transition-exhausted");
|
|
758
|
+
// A foreign budget cannot transfer a private durable-spend observer to this exception,
|
|
759
|
+
// including when it reaches this owner through a derived legacy bridge.
|
|
760
|
+
const foreignParent = counter?.recoveryOwner ?? (!counter ? parent : undefined);
|
|
761
|
+
if (foreignParent && (foreignParent.spendEnforced || hasWorkflowSendObserver(foreignParent))) return refused("spend-exhausted");
|
|
762
|
+
if (!Number.isSafeInteger(maxAdditionalSends) || maxAdditionalSends <= 0
|
|
763
|
+
|| !Number.isSafeInteger(parent.used + maxAdditionalSends)) return refused("total-exhausted");
|
|
764
|
+
// Freeze the ordinary limit through its original owner before constructing the exception.
|
|
765
|
+
parent.startRequest?.();
|
|
766
|
+
const shared = counter ?? ledgerFor(parent);
|
|
767
|
+
const allowance = parent.used + maxAdditionalSends;
|
|
768
|
+
const budget = createRequestExecutionBudgetWithLedger({
|
|
769
|
+
maxTotalModelSends: allowance, baseSendAllowance: allowance, finalRecoveryAllowance: 0,
|
|
770
|
+
maxAlternateTargetSends: 0, maxTargetTransitions: 0,
|
|
771
|
+
}, parent.logicalRequestId, shared, {
|
|
772
|
+
targetKey, maxAdditionalSends, physicalLimit: shared.physicalStarted - shared.explicitPhysicalStarted + maxAdditionalSends,
|
|
773
|
+
reservationPrefix: `${targetKey}|same-target-recovery:${++logicalRequestSeq}`, reservationSequence: 0,
|
|
774
|
+
});
|
|
775
|
+
const recovery: BoundedSameTargetRecovery = {
|
|
776
|
+
get workflowCountObserved() { return hasWorkflowSendObserver(budget); },
|
|
777
|
+
reserve: () => budget.reserveDispatch({ sendClass: "transient", targetKey }),
|
|
778
|
+
};
|
|
779
|
+
sameTargetRecoveries.set(owner, { targetKey, recovery });
|
|
780
|
+
return recovery;
|
|
781
|
+
}
|
|
782
|
+
|
|
630
783
|
/**
|
|
631
784
|
* A budget that did not come from this factory still honors the public `used` contract, so
|
|
632
785
|
* bridge onto it rather than failing the request. `isRequestExecutionBudget` is a shape test,
|
|
@@ -656,8 +809,10 @@ function ledgerFor(parent: RequestExecutionBudget): SharedSendLedger {
|
|
|
656
809
|
return {
|
|
657
810
|
get spent(): number { return parent.used; },
|
|
658
811
|
set spent(next: number) { parent.used = next; },
|
|
812
|
+
recoveryOwner: parent,
|
|
659
813
|
pendingExternalSends,
|
|
660
814
|
physicalStarted: 0,
|
|
815
|
+
explicitPhysicalStarted: 0,
|
|
661
816
|
// Asked of the parent rather than counted here. A local counter is a SECOND grant: two
|
|
662
817
|
// scopes derived from one bridged parent, or one scope beside the parent it was derived
|
|
663
818
|
// from, each replaced an unknown-state send once. Pending bookings and the durable-spend
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** Schema diagnostics are closed tokens, never upstream messages, inputs or arbitrary location keys. */
|
|
2
|
+
const ROOT_FIELDS = [
|
|
3
|
+
"max_completion_tokens", "max_tokens", "user", "store", "thinking", "include_reasoning", "reasoning",
|
|
4
|
+
"reasoning_effort", "top_k", "messages", "tools", "response_format", "temperature",
|
|
5
|
+
"top_p", "stream_options", "parallel_tool_calls", "metadata", "service_tier", "prompt_cache_key",
|
|
6
|
+
] as const;
|
|
7
|
+
const NESTED_FIELDS = ["messages.role", "messages.content", "tools.function", "tools.function.strict",
|
|
8
|
+
"stream_options.include_usage", "reasoning.effort", "reasoning.enabled", "thinking.type"] as const;
|
|
9
|
+
const FIELDS = [...ROOT_FIELDS, ...NESTED_FIELDS, ...ROOT_FIELDS.map(field => `${field}.*` as const)] as const;
|
|
10
|
+
const TYPES = ["extra_forbidden", "union_tag_invalid", "literal_error", "enum", "value_error"] as const;
|
|
11
|
+
export interface ValidationIssue { field: typeof FIELDS[number]; type: typeof TYPES[number] }
|
|
12
|
+
export const MAX_VALIDATION_ISSUES = 8;
|
|
13
|
+
const isRecord = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
|
|
14
|
+
|
|
15
|
+
/** Revalidate on append, hydration and UI rendering, including edited or legacy usage rows. */
|
|
16
|
+
export function boundedValidationIssues(value: unknown): ValidationIssue[] | undefined {
|
|
17
|
+
if (!Array.isArray(value)) return undefined;
|
|
18
|
+
const issues: ValidationIssue[] = [];
|
|
19
|
+
for (const item of value.slice(0, 64)) {
|
|
20
|
+
if (!isRecord(item)) continue;
|
|
21
|
+
const field = FIELDS.find(field => field === item.field);
|
|
22
|
+
const type = TYPES.find(type => type === item.type);
|
|
23
|
+
if (!field || !type || issues.some(issue => issue.field === field && issue.type === type)) continue;
|
|
24
|
+
issues.push({ field, type });
|
|
25
|
+
if (issues.length === MAX_VALIDATION_ISSUES) break;
|
|
26
|
+
}
|
|
27
|
+
if (!issues.length) return undefined;
|
|
28
|
+
if (issues.length === value.length && value.every((item, i) => isRecord(item)
|
|
29
|
+
&& Object.keys(item).length === 2 && item.field === issues[i]!.field && item.type === issues[i]!.type)) return value as ValidationIssue[];
|
|
30
|
+
return issues;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Extract only schema field identities, collapsing message locations without retaining values. */
|
|
34
|
+
export function upstreamValidationIssues(payload: unknown): ValidationIssue[] | undefined {
|
|
35
|
+
if (!isRecord(payload) || !Array.isArray(payload.detail)) return undefined;
|
|
36
|
+
return boundedValidationIssues(payload.detail.slice(0, 64).map(item => {
|
|
37
|
+
if (!isRecord(item) || !Array.isArray(item.loc)) return undefined;
|
|
38
|
+
const loc = item.loc;
|
|
39
|
+
const start = loc[0] === "body" ? 1 : 0;
|
|
40
|
+
const root = ROOT_FIELDS.find(field => field === loc[start]);
|
|
41
|
+
if (!root) return undefined;
|
|
42
|
+
const nested = loc.length > start + 1;
|
|
43
|
+
const path = loc.slice(start, start + 16).filter(part => typeof part !== "number").join(".");
|
|
44
|
+
const field = nested ? NESTED_FIELDS.find(field => field === path) ?? `${root}.*` : root;
|
|
45
|
+
return { field, type: item.type };
|
|
46
|
+
}));
|
|
47
|
+
}
|