@bitkyc08/opencodex 2.94.0 → 2.96.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/gui/dist/assets/App-B4j-Txmb.css +1 -0
- package/gui/dist/assets/App-bwugJRKn.js +58 -0
- package/gui/dist/assets/{Tray-CZatQdoF.js → Tray-BOPQyDbH.js} +1 -1
- package/gui/dist/assets/index-ebuVUtB7.js +94 -0
- package/gui/dist/assets/quota-summary-6HsrHQAy.js +1 -0
- package/gui/dist/index.html +1 -1
- package/package.json +1 -1
- package/src/adapters/anthropic.ts +10 -3
- package/src/adapters/command-code-project-context.ts +3 -3
- package/src/adapters/kiro/adapter.ts +4 -1
- package/src/adapters/kiro/stream.ts +1 -0
- package/src/adapters/kiro-events.ts +1 -0
- package/src/adapters/ollama-native.ts +10 -6
- package/src/adapters/openai-chat/messages.ts +20 -7
- package/src/adapters/openai-chat/passthrough.ts +4 -2
- package/src/adapters/openai-chat/single-system.ts +24 -0
- package/src/adapters/openai-responses/canonical-forward.ts +50 -13
- package/src/adapters/openai-responses/muse-tool-catalog.ts +87 -0
- package/src/adapters/openai-responses/passthrough.ts +45 -11
- package/src/adapters/openai-responses/prompt-cache.ts +3 -1
- package/src/adapters/openai-responses/request-strips.ts +23 -4
- package/src/adapters/openai-responses/tool-output-recovery.ts +21 -8
- package/src/adapters/openai-responses/tool-schema.ts +20 -8
- package/src/adapters/openai-responses/transport.ts +17 -26
- package/src/adapters/opencode-go-additional-tools.ts +39 -6
- package/src/adapters/qoder/adapter.ts +1 -1
- package/src/adapters/qoder/image-input.ts +5 -2
- package/src/adapters/routed-agent-messages.ts +3 -0
- package/src/adapters/xai-web-search.ts +6 -3
- package/src/adapters/zed-additional-tools.ts +7 -7
- package/src/adapters/zed.ts +1 -6
- package/src/advisor/consult.ts +22 -10
- package/src/advisor/runtime.ts +10 -4
- package/src/bridge/max-output-completion.ts +41 -0
- package/src/bridge/response-json.ts +9 -4
- package/src/bridge/sse.ts +13 -2
- package/src/chatgpt/app-server-shim/bundle-trust-policy.ts +5 -0
- package/src/chatgpt/app-server-shim/launcher.ts +40 -6
- package/src/claude/compatibility.ts +5 -1
- package/src/claude/desktop-3p.ts +27 -6
- package/src/claude/desktop-model-visibility.ts +141 -0
- package/src/claude/desktop-remote-store-io.ts +8 -8
- package/src/claude/inbound-content-options.ts +11 -1
- package/src/claude/intercept/proxy-auth.ts +16 -16
- package/src/cli/account-main.ts +3 -2
- package/src/cli/agent.ts +44 -15
- package/src/cli/capabilities-agents-routing.ts +9 -0
- package/src/cli/capabilities-provider-models.ts +7 -0
- package/src/cli/chatgpt-command.ts +1 -1
- package/src/cli/codex-launcher.ts +20 -8
- package/src/cli/codex-shim-autorestore.ts +19 -1
- package/src/cli/dispatch.ts +6 -6
- package/src/cli/doctor.ts +5 -5
- package/src/cli/ensure-desired-integrations.ts +4 -3
- package/src/cli/index.ts +8 -10
- package/src/cli/init.ts +2 -2
- package/src/cli/internal-command.ts +29 -2
- package/src/cli/message-command.ts +2 -1
- package/src/cli/message-mcp-command.ts +29 -0
- package/src/cli/provider-cc-switch-import.ts +185 -0
- package/src/cli/provider.ts +5 -0
- package/src/cli/registry.ts +2 -1
- package/src/cli/restart-scope.ts +2 -2
- package/src/cli/root.ts +6 -6
- package/src/cli/stop-approval.ts +15 -1
- package/src/cli/v2.ts +69 -19
- package/src/client/machine-api.ts +2 -2
- package/src/clients/config-export.ts +14 -3
- package/src/codex/account-cooldown-response.ts +18 -0
- package/src/codex/account-store.ts +1 -0
- package/src/codex/app-server-restart-service.ts +2 -2
- package/src/codex/auth-api/login-flow.ts +2 -2
- package/src/codex/auth-api/pool-quota-probe.ts +2 -2
- package/src/codex/auth-context-provider.ts +15 -0
- package/src/codex/auth-context.ts +14 -23
- package/src/codex/catalog/bundled.ts +10 -3
- package/src/codex/catalog/metadata.ts +4 -5
- package/src/codex/catalog/native-omission.ts +28 -0
- package/src/codex/catalog/native-template.ts +58 -0
- package/src/codex/catalog/parsing.ts +3 -29
- package/src/codex/catalog/provider-models.ts +2 -1
- package/src/codex/catalog/retained-sync.ts +15 -5
- package/src/codex/catalog/write-audit.ts +18 -18
- package/src/codex/cli-install-provenance.ts +46 -45
- package/src/codex/cli-update-artifacts.ts +8 -6
- package/src/codex/cli-update-job-store-windows.ts +99 -27
- package/src/codex/cli-update-job-worker.ts +3 -11
- package/src/codex/cli-update-recovery.ts +54 -8
- package/src/codex/cli-update-selection-gate.ts +74 -4
- package/src/codex/cli-windows-plan-provenance.ts +37 -19
- package/src/codex/codex-home-owner.ts +9 -8
- package/src/codex/convergence.ts +13 -3
- package/src/codex/coordinator-doctor.ts +14 -8
- package/src/codex/desktop-app/handoff.ts +1 -1
- package/src/codex/desktop-app-restart.ts +11 -1
- package/src/codex/exec-boundary.ts +26 -5
- package/src/codex/forward-transport-headers.ts +33 -33
- package/src/codex/history-provider.ts +11 -10
- package/src/codex/inject/bounded-config-reader.ts +14 -13
- package/src/codex/installation-id.ts +72 -0
- package/src/codex/main-account.ts +6 -6
- package/src/codex/native-main-lock-file.ts +13 -12
- package/src/codex/native-residue.ts +18 -14
- package/src/codex/orca-auth-source.ts +8 -7
- package/src/codex/quota-types.ts +5 -0
- package/src/codex/quota.ts +49 -7
- package/src/codex/role-auto-assign.ts +50 -26
- package/src/codex/role-capability.ts +160 -0
- package/src/codex/role-sizing.ts +24 -6
- package/src/codex/routing/cooldown-math.ts +3 -2
- package/src/codex/runtime.ts +43 -3
- package/src/codex/shim-fingerprint.ts +11 -9
- package/src/codex/shim-inspect.ts +3 -2
- package/src/codex/shim-restore-lock.ts +11 -14
- package/src/codex/shim-state-file.ts +22 -14
- package/src/codex/shim-wrapper-write.ts +7 -6
- package/src/codex/shim.ts +25 -2
- package/src/codex/transition-state.ts +5 -4
- package/src/combos/failover.ts +43 -4
- package/src/config/atomic-write.ts +38 -7
- package/src/config/diagnostics.ts +3 -0
- package/src/config/initialize.ts +6 -6
- package/src/config/load-degrade.ts +2 -0
- package/src/config/process-state.ts +23 -5
- package/src/config/salvage.ts +1 -0
- package/src/config/schema/config-schema.ts +29 -1
- package/src/config/schema/leaf-validators.ts +7 -0
- package/src/config/schema/workflow-budget.ts +43 -0
- package/src/config/tracked-runtime-inspection.ts +188 -0
- package/src/generated/compatibility-version.json +380 -244
- package/src/grok/sync.ts +10 -1
- package/src/integrations/aside-profile-context.ts +1 -1
- package/src/integrations/droid-settings.ts +4 -4
- package/src/integrations/hermes-profiles.ts +3 -3
- package/src/lib/bounded-file-read.ts +3 -9
- package/src/lib/bun-runtime-preflight.ts +9 -8
- package/src/lib/file-identity.ts +15 -0
- package/src/lib/local-chat-completion.ts +8 -6
- package/src/lib/local-destinations.ts +32 -3
- package/src/lib/redact-folding.ts +9 -0
- package/src/lib/spend-pool-alias-validation.ts +6 -6
- package/src/lib/state-store-registrations.ts +2 -0
- package/src/lib/test-home-guard.ts +37 -9
- package/src/lib/windows-secret-acl.ts +49 -31
- package/src/lib/workflow-budget-config.ts +39 -0
- package/src/local-credentials/generation.ts +6 -2
- package/src/local-credentials/inventory.ts +132 -8
- package/src/messaging/mcp-queue-rpc.ts +102 -0
- package/src/messaging/mcp-queue-server.ts +42 -0
- package/src/messaging/mcp-queue-tools.ts +39 -0
- package/src/messaging/remote-forward-failure.ts +35 -0
- package/src/messaging/remote-ports.ts +27 -5
- package/src/messaging/remote-process.ts +30 -4
- package/src/messaging/remote-tunnels.ts +80 -15
- package/src/oauth/anthropic-identity.ts +2 -6
- package/src/oauth/antigravity-discovery-diagnostics.ts +65 -0
- package/src/oauth/google-antigravity.ts +23 -10
- package/src/oauth/index.ts +7 -0
- package/src/oauth/kiro-device-login.ts +87 -30
- package/src/oauth/kiro-iam-identity-center.ts +107 -0
- package/src/oauth/store.ts +9 -7
- package/src/providers/account-quota-disk.ts +18 -4
- package/src/providers/anthropic-subscription.ts +25 -0
- package/src/providers/cc-switch-import-bytes.ts +991 -0
- package/src/providers/cc-switch-import-source.ts +1083 -0
- package/src/providers/cc-switch-import.ts +942 -0
- package/src/providers/claude-cli-usage.ts +15 -67
- package/src/providers/derive.ts +6 -0
- package/src/providers/model-discovery-diagnostic.ts +4 -0
- package/src/providers/model-discovery.ts +4 -4
- package/src/providers/model-rename-fields.ts +2 -0
- package/src/providers/model-rename-migration.ts +41 -6
- package/src/providers/quota/anthropic-decision-windows.ts +5 -19
- package/src/providers/quota/anthropic-usage-windows.ts +55 -0
- package/src/providers/quota/report-cache.ts +17 -4
- package/src/providers/quota.ts +2 -2
- package/src/providers/reasoning-metadata.ts +31 -15
- package/src/providers/registry/entries-core.ts +1 -1
- package/src/providers/registry/entries-extended.ts +1 -1
- package/src/providers/registry/model-ids.ts +1 -0
- package/src/providers/registry/model-seeds.ts +2 -1
- package/src/providers/registry/types.ts +3 -1
- package/src/providers/resolved-model-policy.ts +2 -2
- package/src/providers/routed-config.ts +2 -0
- package/src/providers/stale-model-roster-migration.ts +5 -1
- package/src/providers/xai-transport.ts +4 -4
- package/src/remote-control/workspace-codex-runtime.ts +2 -2
- package/src/remote-control/workspace-executor.ts +14 -13
- package/src/responses/custom-tool-compat.ts +2 -1
- package/src/responses/item-provenance.ts +79 -0
- package/src/responses/namespace-tool-compat.ts +21 -3
- package/src/responses/parser-tools.ts +1 -0
- package/src/responses/schema.ts +5 -2
- package/src/router.ts +21 -2
- package/src/routing/analytics.ts +3 -5
- package/src/routing/fallback-policy.ts +7 -3
- package/src/routing/health.ts +5 -3
- package/src/routing/history/build-file.ts +6 -0
- package/src/routing/history/indexer.ts +158 -31
- package/src/routing/history/ingest.ts +1 -1
- package/src/routing/history/integrity.ts +208 -0
- package/src/routing/history/rebuild-job.ts +20 -6
- package/src/routing/history/rebuild-protocol.ts +2 -1
- package/src/routing/history/rebuild-worker.ts +18 -0
- package/src/routing/history/sqlite-errors.ts +9 -0
- package/src/server/admission-model-scope.ts +21 -4
- package/src/server/advisor-admission-scope.ts +29 -0
- package/src/server/audio-dictation.ts +3 -0
- package/src/server/audio-live.ts +8 -2
- package/src/server/audio-upstream.ts +2 -0
- package/src/server/auth-cors.ts +5 -2
- package/src/server/capture-admission-policy.ts +91 -0
- package/src/server/chat-completions.ts +33 -7
- package/src/server/claude-messages.ts +93 -2
- package/src/server/codex-model-list.ts +2 -1
- package/src/server/configured-credentials.ts +5 -0
- package/src/server/context-history.ts +9 -6
- package/src/server/images.ts +14 -5
- package/src/server/index/live-sideband.ts +16 -2
- package/src/server/index/serve-options.ts +13 -2
- package/src/server/index/websocket-handler.ts +4 -1
- package/src/server/live.ts +30 -5
- package/src/server/management/agent-settings-routes.ts +34 -9
- package/src/server/management/codex-agent-role-routes.ts +1 -0
- package/src/server/management/codex-role-auto-assign.ts +50 -6
- package/src/server/management/config-routes.ts +15 -4
- package/src/server/management/context.ts +3 -0
- package/src/server/management/native-integration-routes.ts +22 -0
- package/src/server/management/oauth-account-routes.ts +20 -4
- package/src/server/management/provider-overwrite-carry.ts +21 -0
- package/src/server/management/provider-routes.ts +3 -1
- package/src/server/management/route-registry.ts +2 -0
- package/src/server/management/shared.ts +17 -1
- package/src/server/management/workflow-budget-routes.ts +70 -3
- package/src/server/messages-native-eligibility.ts +6 -5
- package/src/server/messages-native-scope.ts +6 -1
- package/src/server/messages-shared.ts +57 -17
- package/src/server/persistent-gui-session.ts +4 -4
- package/src/server/request-log.ts +30 -2
- package/src/server/responses/adapter-delivery.ts +4 -0
- package/src/server/responses/adapter-dispatch.ts +5 -0
- package/src/server/responses/advisor-plan-slot.ts +4 -0
- package/src/server/responses/advisor-slot.ts +73 -46
- package/src/server/responses/codex-auth-error.ts +9 -1
- package/src/server/responses/combo-required-tool-contract.ts +39 -0
- package/src/server/responses/compact.ts +41 -20
- package/src/server/responses/core-codex-account.ts +17 -6
- package/src/server/responses/core-combo-failure.ts +2 -0
- package/src/server/responses/core-combo.ts +70 -5
- package/src/server/responses/core-lifetime.ts +4 -0
- package/src/server/responses/core-normalize.ts +7 -1
- package/src/server/responses/core-options.ts +9 -0
- package/src/server/responses/core.ts +2 -0
- package/src/server/responses/jev-model-invoke.ts +4 -2
- package/src/server/responses/passthrough-build-error.ts +36 -0
- package/src/server/responses/passthrough-dispatch.ts +10 -24
- package/src/server/responses/policy-fallback.ts +2 -0
- package/src/server/responses/request-prepare.ts +4 -5
- package/src/server/responses/request-send-budget.ts +2 -1
- package/src/server/responses/request-sidecar-auth.ts +4 -1
- package/src/server/responses/request-transport.ts +2 -3
- package/src/server/responses/run-turn-execution.ts +4 -0
- package/src/server/responses/sidecar-execution.ts +21 -5
- package/src/server/responses-snapshot-repair.ts +18 -4
- package/src/server/responses-undeclared-tool-guard.ts +4 -0
- package/src/server/search.ts +13 -4
- package/src/server/workflow-refusal.ts +2 -1
- package/src/server/ws-bridge.ts +5 -2
- package/src/service/state-lock.ts +12 -11
- package/src/service-manager-probe.ts +53 -8
- package/src/types/admission-policy.ts +13 -0
- package/src/types/config.ts +25 -0
- package/src/types/provider.ts +10 -0
- package/src/types/request.ts +7 -0
- package/src/types.ts +1 -0
- package/src/update/job.ts +20 -0
- package/src/update/worker-launch.ts +71 -1
- package/src/usage/log.ts +25 -4
- package/src/vision/describe.ts +4 -7
- package/src/vision/index.ts +2 -0
- package/src/vision/plan.ts +4 -0
- package/src/vision/routed-describe.ts +38 -23
- package/src/web-search/executor.ts +4 -7
- package/src/web-search/loop.ts +104 -9
- package/src/web-search/parse.ts +10 -2
- package/gui/dist/assets/App-DMps4OLk.css +0 -1
- package/gui/dist/assets/App-DmvwlhQq.js +0 -58
- package/gui/dist/assets/index-3EPO_KbX.js +0 -94
- package/gui/dist/assets/quota-summary-BHvWg9mi.js +0 -1
|
@@ -13,6 +13,7 @@ import { RequestHistoryIndexStaleError } from "./ingest";
|
|
|
13
13
|
import type { RebuildWorkerReply, RebuildWorkerRequest } from "./rebuild-protocol";
|
|
14
14
|
|
|
15
15
|
const CLOSE_TIMEOUT_MS = 5_000;
|
|
16
|
+
type WorkerSuccess = Exclude<RebuildWorkerReply, { type: "error" }>;
|
|
16
17
|
|
|
17
18
|
function delay(ms: number): Promise<void> {
|
|
18
19
|
return new Promise(resolve => setTimeout(resolve, ms));
|
|
@@ -34,7 +35,7 @@ function errorFromReply(reply: Extract<RebuildWorkerReply, { type: "error" }>):
|
|
|
34
35
|
|
|
35
36
|
export class RebuildWorkerJob {
|
|
36
37
|
private readonly worker: Worker;
|
|
37
|
-
private pending: { resolve: (
|
|
38
|
+
private pending: { resolve: (reply: WorkerSuccess) => void; reject: (error: unknown) => void } | null = null;
|
|
38
39
|
private exited = false;
|
|
39
40
|
private exitedCleanly = false;
|
|
40
41
|
private disposal: Promise<void> | null = null;
|
|
@@ -49,8 +50,8 @@ export class RebuildWorkerJob {
|
|
|
49
50
|
this.pending = null;
|
|
50
51
|
if (!pending) return;
|
|
51
52
|
const reply = event.data;
|
|
52
|
-
if (reply.type === "
|
|
53
|
-
else pending.
|
|
53
|
+
if (reply.type === "error") pending.reject(errorFromReply(reply));
|
|
54
|
+
else pending.resolve(reply);
|
|
54
55
|
});
|
|
55
56
|
this.worker.addEventListener("error", (event: Event) => {
|
|
56
57
|
this.fail(new Error((event as ErrorEvent).message || "request-history rebuild worker failed"));
|
|
@@ -68,16 +69,29 @@ export class RebuildWorkerJob {
|
|
|
68
69
|
pending?.reject(error);
|
|
69
70
|
}
|
|
70
71
|
|
|
71
|
-
|
|
72
|
-
build(indexPath: string, buildPath: string, reason: string, revision: UsageLogRevision): Promise<number> {
|
|
72
|
+
private send(request: RebuildWorkerRequest): Promise<WorkerSuccess> {
|
|
73
73
|
if (this.exited || this.disposal) return Promise.reject(new Error("request-history rebuild worker is not running"));
|
|
74
74
|
if (this.pending) return Promise.reject(new Error("request-history rebuild worker is busy"));
|
|
75
75
|
return new Promise((resolve, reject) => {
|
|
76
76
|
this.pending = { resolve, reject };
|
|
77
|
-
this.worker.postMessage(
|
|
77
|
+
this.worker.postMessage(request);
|
|
78
78
|
});
|
|
79
79
|
}
|
|
80
80
|
|
|
81
|
+
/** Build the complete private file; resolves with the ingested row count. */
|
|
82
|
+
async build(indexPath: string, buildPath: string, reason: string, revision: UsageLogRevision): Promise<number> {
|
|
83
|
+
const reply = await this.send({ type: "build", indexPath, buildPath, reason, revision });
|
|
84
|
+
if (reply.type !== "built") throw new Error("unexpected request-history build reply");
|
|
85
|
+
return reply.rows;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Scan a read-only connection off-loop; operational errors are not corruption. */
|
|
89
|
+
async check(indexPath: string): Promise<boolean> {
|
|
90
|
+
const reply = await this.send({ type: "check", indexPath });
|
|
91
|
+
if (reply.type !== "checked") throw new Error("unexpected request-history integrity reply");
|
|
92
|
+
return reply.healthy;
|
|
93
|
+
}
|
|
94
|
+
|
|
81
95
|
/** Stop the thread; waits a bounded time for it to exit. */
|
|
82
96
|
dispose(): Promise<void> {
|
|
83
97
|
this.disposal ??= this.shutDown();
|
|
@@ -8,8 +8,9 @@ export type RebuildWorkerRequest = {
|
|
|
8
8
|
buildPath: string;
|
|
9
9
|
reason: string;
|
|
10
10
|
revision: UsageLogRevision;
|
|
11
|
-
};
|
|
11
|
+
} | { type: "check"; indexPath: string };
|
|
12
12
|
|
|
13
13
|
export type RebuildWorkerReply =
|
|
14
14
|
| { type: "built"; rows: number }
|
|
15
|
+
| { type: "checked"; healthy: boolean }
|
|
15
16
|
| { type: "error"; name: string; message: string };
|
|
@@ -8,12 +8,30 @@
|
|
|
8
8
|
* closes it. The serving thread then swaps the finished file in.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
+
import { Database } from "bun:sqlite";
|
|
11
12
|
import { buildIndexFile, removeAbandonedBuilds } from "./build-file";
|
|
13
|
+
import { isHistoryIndexCorruption } from "./sqlite-errors";
|
|
12
14
|
import type { RebuildWorkerReply, RebuildWorkerRequest } from "./rebuild-protocol";
|
|
13
15
|
|
|
14
16
|
declare const self: Worker;
|
|
15
17
|
|
|
16
18
|
function handle(request: RebuildWorkerRequest): RebuildWorkerReply {
|
|
19
|
+
if (request.type === "check") {
|
|
20
|
+
let handle: Database | undefined;
|
|
21
|
+
try {
|
|
22
|
+
handle = new Database(request.indexPath, { readonly: true });
|
|
23
|
+
handle.exec("PRAGMA busy_timeout = 5000");
|
|
24
|
+
const row = handle.query("PRAGMA quick_check").get() as { quick_check?: string } | undefined;
|
|
25
|
+
return { type: "checked", healthy: row?.quick_check === "ok" };
|
|
26
|
+
} catch (error) {
|
|
27
|
+
if (isHistoryIndexCorruption(error)) return { type: "checked", healthy: false };
|
|
28
|
+
throw error;
|
|
29
|
+
} finally {
|
|
30
|
+
// Release the live index before posting a verdict: the serving thread
|
|
31
|
+
// may immediately replace it, including on Windows.
|
|
32
|
+
handle?.close();
|
|
33
|
+
}
|
|
34
|
+
}
|
|
17
35
|
removeAbandonedBuilds(request.indexPath);
|
|
18
36
|
const rows = buildIndexFile(request.buildPath, request.reason, request.revision);
|
|
19
37
|
return { type: "built", rows };
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Only structural SQLite damage justifies discarding the derived index. */
|
|
2
|
+
export function isHistoryIndexCorruption(error: unknown): boolean {
|
|
3
|
+
if (!error || typeof error !== "object") return false;
|
|
4
|
+
const { code, errno } = error as { code?: unknown; errno?: unknown };
|
|
5
|
+
// Bun exposes extended result codes too; the low byte is the primary code.
|
|
6
|
+
if (typeof errno === "number" && ((errno & 0xff) === 11 || (errno & 0xff) === 26)) return true;
|
|
7
|
+
return typeof code === "string"
|
|
8
|
+
&& /^(SQLITE_CORRUPT(?:_[A-Z]+)?|SQLITE_NOTADB)$/.test(code);
|
|
9
|
+
}
|
|
@@ -25,6 +25,8 @@ import { markResponseNonReplayable } from "../lib/upstream-retry";
|
|
|
25
25
|
* the management credential.
|
|
26
26
|
*/
|
|
27
27
|
export interface AdmissionModelScope {
|
|
28
|
+
/** Every inherited scope must also admit the final destination. */
|
|
29
|
+
readonly allOf?: readonly AdmissionModelScope[];
|
|
28
30
|
/** Resolved provider names this key may reach. Empty means every provider. */
|
|
29
31
|
readonly providers: readonly string[];
|
|
30
32
|
/** Resolved destinations this key may reach. Empty means every model. */
|
|
@@ -44,6 +46,11 @@ function providerAllowedByScope(scope: AdmissionModelScope, providerName: string
|
|
|
44
46
|
return scope.providers.length === 0 || scope.providers.includes(normalize(providerName));
|
|
45
47
|
}
|
|
46
48
|
|
|
49
|
+
function unnamedDestinationAllowedByScope(scope: AdmissionModelScope, providerName: string): boolean {
|
|
50
|
+
return providerAllowedByScope(scope, providerName) && scope.models.length === 0
|
|
51
|
+
&& (scope.allOf?.every(part => unnamedDestinationAllowedByScope(part, providerName)) ?? true);
|
|
52
|
+
}
|
|
53
|
+
|
|
47
54
|
function normalizedList(values: readonly string[] | undefined): readonly string[] {
|
|
48
55
|
if (!Array.isArray(values)) return [];
|
|
49
56
|
const seen = new Set<string>();
|
|
@@ -73,9 +80,13 @@ export function resolveAdmissionModelScope(
|
|
|
73
80
|
config: Pick<OcxConfig, "apiKeys">,
|
|
74
81
|
admission: DataPlaneAdmission | undefined,
|
|
75
82
|
): AdmissionModelScope | undefined {
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
return entry ? admissionModelScopeOf(entry) : undefined;
|
|
83
|
+
const entry = admission?.kind === "configured"
|
|
84
|
+
? (config.apiKeys ?? []).find(key => key.id === admission.keyId) : undefined;
|
|
85
|
+
return intersectAdmissionModelScopes(entry ? admissionModelScopeOf(entry) : undefined, admission?.callerPolicy?.modelScope);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function intersectAdmissionModelScopes(a: AdmissionModelScope | undefined, b: AdmissionModelScope | undefined): AdmissionModelScope | undefined {
|
|
89
|
+
return a && b ? { providers: [], models: [], allOf: [a, b] } : a ?? b;
|
|
79
90
|
}
|
|
80
91
|
|
|
81
92
|
/** Consent comes from stored operator config, never request headers. Use the full listener config. */
|
|
@@ -84,10 +95,15 @@ export function admissionMayUseMeteredComboTargets(
|
|
|
84
95
|
admission: DataPlaneAdmission | undefined,
|
|
85
96
|
combo?: { allowMeteredTargets?: boolean },
|
|
86
97
|
): boolean {
|
|
98
|
+
const caller = admission?.callerPolicy;
|
|
99
|
+
if (caller && (!caller.allowMeteredComboTargets || caller.meteredRequiresComboOptIn && combo?.allowMeteredTargets !== true)) return false;
|
|
87
100
|
if (admission?.kind === "configured") {
|
|
88
101
|
const entry = (config.apiKeys ?? []).find(key => key.id === admission.keyId);
|
|
89
102
|
return entry?.allowMeteredComboTargets === true;
|
|
90
103
|
}
|
|
104
|
+
// A loopback-admitted internal hop's captured policy already holds this branch's decision for
|
|
105
|
+
// its listener, or the consent of the validated key it presented (#7894); it was checked above.
|
|
106
|
+
if (admission?.kind === "loopback" && caller) return true;
|
|
91
107
|
// Linked ingress always carries keyed admission, even when the primary bind is loopback.
|
|
92
108
|
// A secondary loopback listener on a public proxy does not qualify either.
|
|
93
109
|
return (!admission || admission.kind === "loopback")
|
|
@@ -111,6 +127,7 @@ export function routeAllowedByScope(
|
|
|
111
127
|
route: ScopedRoute,
|
|
112
128
|
): boolean {
|
|
113
129
|
if (!scope) return true;
|
|
130
|
+
if (scope.allOf?.some(part => !routeAllowedByScope(part, route))) return false;
|
|
114
131
|
const model = normalize(route.modelId);
|
|
115
132
|
if (!providerAllowedByScope(scope, route.providerName)) return false;
|
|
116
133
|
if (scope.models.length === 0) return true;
|
|
@@ -226,7 +243,7 @@ export function admissionScopeDenial(
|
|
|
226
243
|
const scope = resolveAdmissionModelScope(config, admission);
|
|
227
244
|
if (!scope) return undefined;
|
|
228
245
|
const allowed = destination.modelId === undefined
|
|
229
|
-
?
|
|
246
|
+
? unnamedDestinationAllowedByScope(scope, destination.providerName)
|
|
230
247
|
: routeAllowedByScope(scope, { providerName: destination.providerName, modelId: destination.modelId });
|
|
231
248
|
if (allowed) return undefined;
|
|
232
249
|
return admissionModelDeniedResponse(new AdmissionModelDeniedError(
|
|
@@ -1,4 +1,33 @@
|
|
|
1
1
|
import type { AdmissionModelScope } from "./admission-model-scope";
|
|
2
|
+
import type { CapturedAdmissionPolicy } from "../types/admission-policy";
|
|
3
|
+
import { internalCallCapability, isInternalCallCapability } from "../lib/local-internal-call-capability";
|
|
4
|
+
import { immutableAdmissionPolicy } from "./capture-admission-policy";
|
|
5
|
+
|
|
6
|
+
export const ADVISOR_ADMISSION_POLICY_HEADER = "x-opencodex-advisor-admission-policy";
|
|
7
|
+
/** Routed helpers inherit policy without acquiring the Advisor recursion-suppression flag. */
|
|
8
|
+
export const SIDECAR_ADMISSION_POLICY_HEADER = "x-opencodex-sidecar-admission-policy";
|
|
9
|
+
export const SIDECAR_INTERNAL_CAPABILITY_HEADER = "x-opencodex-sidecar-internal";
|
|
10
|
+
const policies = new Map<string, { capability: string; policy: CapturedAdmissionPolicy }>();
|
|
11
|
+
|
|
12
|
+
/** A consult owns its registry entry until completion, failure or cancellation. */
|
|
13
|
+
export function registerAdvisorAdmissionPolicy(policy: CapturedAdmissionPolicy, signal?: AbortSignal) {
|
|
14
|
+
const token = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url");
|
|
15
|
+
const release = () => {
|
|
16
|
+
policies.delete(token);
|
|
17
|
+
signal?.removeEventListener("abort", release);
|
|
18
|
+
};
|
|
19
|
+
if (!signal?.aborted) {
|
|
20
|
+
policies.set(token, { capability: internalCallCapability(), policy: immutableAdmissionPolicy(policy) });
|
|
21
|
+
signal?.addEventListener("abort", release, { once: true });
|
|
22
|
+
}
|
|
23
|
+
return { token, release };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function readAdvisorAdmissionPolicy(token: string | null, capability: string | null): CapturedAdmissionPolicy | undefined {
|
|
27
|
+
if (!token || !isInternalCallCapability(capability)) return undefined;
|
|
28
|
+
const entry = policies.get(token);
|
|
29
|
+
return entry?.capability === capability ? entry.policy : undefined;
|
|
30
|
+
}
|
|
2
31
|
|
|
3
32
|
/** Scope metadata accepted only alongside the process-owned Advisor capability. */
|
|
4
33
|
export const ADVISOR_ADMISSION_SCOPE_HEADER = "x-opencodex-advisor-admission-scope";
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { formatErrorResponse } from "../bridge";
|
|
2
|
+
import type { CodexAuthContext } from "../codex/auth-context";
|
|
2
3
|
import type { AdmissionLease } from "../lib/admission";
|
|
3
4
|
import type { OcxConfig } from "../types";
|
|
4
5
|
import type { AudioClient } from "./audio-client";
|
|
@@ -47,6 +48,7 @@ export function createDictationFrameValidator(): (frame: string | Buffer) => boo
|
|
|
47
48
|
}
|
|
48
49
|
|
|
49
50
|
export interface AudioSocketTarget {
|
|
51
|
+
authContext?: CodexAuthContext;
|
|
50
52
|
headers: Record<string, string>;
|
|
51
53
|
upstreamWsUrl: string;
|
|
52
54
|
protocols?: string[];
|
|
@@ -82,6 +84,7 @@ export async function resolveDictationSocket(
|
|
|
82
84
|
}
|
|
83
85
|
headers.delete("authorization");
|
|
84
86
|
return {
|
|
87
|
+
authContext: relay.authContext,
|
|
85
88
|
upstreamWsUrl: "wss://chatgpt.com/backend-api/dictation/stream",
|
|
86
89
|
headers: Object.fromEntries(headers),
|
|
87
90
|
protocols: ["chatgpt-dictation", `openai-bearer.${token}`, "codex-desktop"],
|
package/src/server/audio-live.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { formatErrorResponse } from "../bridge";
|
|
3
3
|
import { MAIN_CODEX_ACCOUNT_ID } from "../codex/account-id";
|
|
4
|
+
import { isolateCodexPoolClientMetadata } from "../codex/forward-transport-headers";
|
|
5
|
+
import { CodexInstallationIdUnavailableError } from "../codex/installation-id";
|
|
4
6
|
import { cancelBodyOnAbort, clearableDeadline } from "../lib/abort";
|
|
5
7
|
import type { AdmissionLease } from "../lib/admission";
|
|
6
8
|
import { captureExplicitOpenAiCallerAuth } from "../providers/openai-sidecar";
|
|
@@ -73,7 +75,7 @@ export async function handleExternalLive(
|
|
|
73
75
|
if (offer instanceof Response) return offer;
|
|
74
76
|
if (!options.bindings.hasCapacity()) return formatErrorResponse(503, "server_busy", "Live call capacity reached");
|
|
75
77
|
const frameless = new URL(req.url).pathname === "/v1/live";
|
|
76
|
-
|
|
78
|
+
let session = offer.session ? { ...offer.session } : frameless ? {
|
|
77
79
|
model: LIVE_AUDIO_MODEL, instructions: "", audio: { output: { voice: "cove" } }, delegation: { type: "client" },
|
|
78
80
|
} : undefined;
|
|
79
81
|
if (session?.model === "gpt-live-1") session.model = LIVE_AUDIO_MODEL;
|
|
@@ -85,6 +87,8 @@ export async function handleExternalLive(
|
|
|
85
87
|
deadline.signal.throwIfAborted();
|
|
86
88
|
if (resolved instanceof Response) return resolved;
|
|
87
89
|
relay = resolved;
|
|
90
|
+
session = isolateCodexPoolClientMetadata(session, relay.authContext?.kind === "pool"
|
|
91
|
+
? relay.authContext.chatgptAccountId : undefined) as typeof session;
|
|
88
92
|
const headers = protocolHeaders(options.client, relay, frameless);
|
|
89
93
|
let body: BodyInit;
|
|
90
94
|
if (relay.keyed) {
|
|
@@ -129,7 +133,8 @@ export async function handleExternalLive(
|
|
|
129
133
|
"content-type": upstream.headers.get("content-type") ?? "application/sdp",
|
|
130
134
|
location: `/v1/${frameless ? "live" : "realtime/calls"}/${alias}`,
|
|
131
135
|
} });
|
|
132
|
-
} catch {
|
|
136
|
+
} catch (error) {
|
|
137
|
+
if (error instanceof CodexInstallationIdUnavailableError) return formatErrorResponse(503, "server_busy", error.message);
|
|
133
138
|
if (req.signal.aborted || controller.signal.aborted) {
|
|
134
139
|
outcome = undefined;
|
|
135
140
|
return formatErrorResponse(req.signal.aborted ? 499 : 503, "client_closed_request", "Live call canceled");
|
|
@@ -178,6 +183,7 @@ export async function resolveExternalLiveSocket(
|
|
|
178
183
|
return formatErrorResponse(409, "authentication_error", "Live call account is no longer available");
|
|
179
184
|
}
|
|
180
185
|
return {
|
|
186
|
+
authContext: relay.authContext,
|
|
181
187
|
headers: Object.fromEntries(protocolHeaders(client, relay, frameless)),
|
|
182
188
|
upstreamWsUrl: buildLiveSidebandUpstreamWsUrl(upstreamTarget, binding ? binding.sidebandBaseUrl : config.experimentalRealtimeWsBaseUrl),
|
|
183
189
|
maxSessionMs: LIVE_CALL_TTL_MS,
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { CodexInstallationIdUnavailableError } from "../codex/installation-id";
|
|
1
2
|
import { formatErrorResponse } from "../bridge";
|
|
2
3
|
import {
|
|
3
4
|
CodexAccountCooldownError,
|
|
@@ -175,6 +176,7 @@ export async function resolveAudioUpstream(
|
|
|
175
176
|
return formatErrorResponse(400, "invalid_request_error", "Audio requires a connected ChatGPT account or OpenAI API provider");
|
|
176
177
|
} catch (error) {
|
|
177
178
|
releaseCodexAuthContextProbeLease(context);
|
|
179
|
+
if (error instanceof CodexInstallationIdUnavailableError) return formatErrorResponse(503, "server_busy", error.message);
|
|
178
180
|
if (error instanceof CodexAccountCooldownError) return cooldownErrorResponse(error);
|
|
179
181
|
if (error instanceof CodexMainProfileDrainingError) return codexMainProfileDrainingResponse();
|
|
180
182
|
const mainCause = error instanceof CodexAuthContextError && error.accountId === MAIN_CODEX_ACCOUNT_ID ? error.cause : error;
|
package/src/server/auth-cors.ts
CHANGED
|
@@ -433,10 +433,11 @@ function mintContextPrincipal(kind: string, keyId: string, credential: string):
|
|
|
433
433
|
.digest("hex");
|
|
434
434
|
}
|
|
435
435
|
|
|
436
|
-
export type DataPlaneAdmission =
|
|
436
|
+
export type DataPlaneAdmission = (
|
|
437
437
|
| { kind: "configured"; keyId: string; source: DataPlaneAdmissionSource; contextPrincipalId?: string }
|
|
438
438
|
| { kind: "environment"; source: DataPlaneAdmissionSource; contextPrincipalId?: string }
|
|
439
|
-
| { kind: "loopback"; source: "loopback" }
|
|
439
|
+
| { kind: "loopback"; source: "loopback" }
|
|
440
|
+
) & { readonly callerPolicy?: import("../types/admission-policy").CapturedAdmissionPolicy };
|
|
440
441
|
|
|
441
442
|
/**
|
|
442
443
|
* Which admission secret `token` is, or null when it is none of them.
|
|
@@ -1088,6 +1089,7 @@ const PROVIDER_CONFIG_FIELD_POLICY = {
|
|
|
1088
1089
|
annotateEmptyToolOutputs: "editor",
|
|
1089
1090
|
supportsServiceTier: "editor",
|
|
1090
1091
|
modelSupportsServiceTier: "editor",
|
|
1092
|
+
promoteAdditionalTools: "editor",
|
|
1091
1093
|
preserveResponsesReasoningContent: "editor",
|
|
1092
1094
|
preserveResponsesInputItemIds: "editor",
|
|
1093
1095
|
preserveResponsesMessageMetadata: "editor",
|
|
@@ -1193,6 +1195,7 @@ const PROVIDER_CONFIG_FIELD_POLICY = {
|
|
|
1193
1195
|
terminalContinuationGuard: "editor",
|
|
1194
1196
|
openaiChatEofTolerance: "editor",
|
|
1195
1197
|
foldDeveloperRoleToSystem: "editor",
|
|
1198
|
+
singleLeadingSystemMessage: "editor",
|
|
1196
1199
|
promptCacheKey: "editor",
|
|
1197
1200
|
chatServiceTier: "editor",
|
|
1198
1201
|
responsesItemIdRepair: "editor",
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { OcxConfig } from "../types";
|
|
2
|
+
import type { CapturedAdmissionPolicy } from "../types/admission-policy";
|
|
3
|
+
import type { DataPlaneAdmission } from "./auth-cors";
|
|
4
|
+
import { resolveDataPlaneAdmissionSecret } from "./auth-cors";
|
|
5
|
+
import { admissionMayUseMeteredComboTargets, intersectAdmissionModelScopes, resolveAdmissionModelScope } from "./admission-model-scope";
|
|
6
|
+
import { fallbackDeviceIds } from "../routing/fallback-policy";
|
|
7
|
+
|
|
8
|
+
function freeze<T>(value: T): T {
|
|
9
|
+
if (value && typeof value === "object") {
|
|
10
|
+
for (const child of Object.values(value)) freeze(child);
|
|
11
|
+
Object.freeze(value);
|
|
12
|
+
}
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function immutableAdmissionPolicy(policy: CapturedAdmissionPolicy): CapturedAdmissionPolicy {
|
|
17
|
+
return freeze(structuredClone(policy));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Combine already captured inputs without reading mutable caller or host configuration. */
|
|
21
|
+
export function intersectAdmissionPolicies(host: CapturedAdmissionPolicy, caller: CapturedAdmissionPolicy): CapturedAdmissionPolicy {
|
|
22
|
+
return immutableAdmissionPolicy({
|
|
23
|
+
modelScope: intersectAdmissionModelScopes(host.modelScope, caller.modelScope)!,
|
|
24
|
+
allowMeteredComboTargets: host.allowMeteredComboTargets && caller.allowMeteredComboTargets,
|
|
25
|
+
meteredRequiresComboOptIn: host.meteredRequiresComboOptIn || caller.meteredRequiresComboOptIn,
|
|
26
|
+
fallbackPolicies: [...host.fallbackPolicies, ...caller.fallbackPolicies],
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function captureAdmissionPolicy(
|
|
31
|
+
config: Pick<OcxConfig, "apiKeys" | "hostname" | "fallback">,
|
|
32
|
+
admission?: DataPlaneAdmission,
|
|
33
|
+
modelScope = resolveAdmissionModelScope(config, admission),
|
|
34
|
+
): CapturedAdmissionPolicy {
|
|
35
|
+
return immutableAdmissionPolicy({
|
|
36
|
+
modelScope: modelScope ?? { providers: [], models: [] },
|
|
37
|
+
allowMeteredComboTargets: admissionMayUseMeteredComboTargets(config, admission, { allowMeteredTargets: true }),
|
|
38
|
+
meteredRequiresComboOptIn: !admission || admission.kind === "loopback"
|
|
39
|
+
|| admission.callerPolicy?.meteredRequiresComboOptIn === true,
|
|
40
|
+
fallbackPolicies: [
|
|
41
|
+
...(admission?.callerPolicy?.fallbackPolicies ?? []),
|
|
42
|
+
{ config: { fallback: config.fallback }, deviceIds: fallbackDeviceIds(config, admission) },
|
|
43
|
+
],
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Attach constraints without changing the host's transport/principal identity. */
|
|
48
|
+
export function inheritAdmissionPolicy(
|
|
49
|
+
admission: DataPlaneAdmission | undefined,
|
|
50
|
+
callerPolicy: CapturedAdmissionPolicy,
|
|
51
|
+
): DataPlaneAdmission {
|
|
52
|
+
return Object.freeze({ ...(admission ?? { kind: "loopback", source: "loopback" }), callerPolicy }) as DataPlaneAdmission;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Host policy of the data-plane credential an internal self-fetch presents (#7894).
|
|
57
|
+
*
|
|
58
|
+
* A loopback listener admits the self-fetch before it reads any token, so the listener snapshot
|
|
59
|
+
* says "loopback" and carries none of the selected key's model scope, paid-combo consent or
|
|
60
|
+
* device fallback identity. Call only after the internal capability and policy registration have
|
|
61
|
+
* been validated. Returns undefined when no credential is presented, and null when the data plane
|
|
62
|
+
* does not recognize it, which the caller must refuse rather than treat as unrestricted.
|
|
63
|
+
*/
|
|
64
|
+
export function captureSelfFetchCredentialPolicy(
|
|
65
|
+
req: Request,
|
|
66
|
+
config: Pick<OcxConfig, "apiKeys" | "hostname" | "fallback">,
|
|
67
|
+
): CapturedAdmissionPolicy | null | undefined {
|
|
68
|
+
const presented = req.headers.get("x-opencodex-api-key")?.trim();
|
|
69
|
+
if (!presented) return undefined;
|
|
70
|
+
const admission = resolveDataPlaneAdmissionSecret(presented, config, "dedicated");
|
|
71
|
+
return admission ? captureAdmissionPolicy(config, admission) : null;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Host policy of an internal self-fetch whose presented credential was validated (#7894).
|
|
76
|
+
*
|
|
77
|
+
* Scope and fallback limits of the listener snapshot and the key both apply. Paid-combo consent
|
|
78
|
+
* is the key's own when a loopback listener admitted the hop: that snapshot holds only the
|
|
79
|
+
* loopback default, which a public proxy always refuses, so a consenting key would otherwise be
|
|
80
|
+
* weaker over Advisor than on a direct request. The loopback snapshot still demands the combo's
|
|
81
|
+
* own opt-in, and the caller's consent is intersected afterwards.
|
|
82
|
+
*/
|
|
83
|
+
export function selfFetchHostPolicy(
|
|
84
|
+
listener: CapturedAdmissionPolicy,
|
|
85
|
+
presented: CapturedAdmissionPolicy,
|
|
86
|
+
listenerAdmission: DataPlaneAdmission | undefined,
|
|
87
|
+
): CapturedAdmissionPolicy {
|
|
88
|
+
const merged = intersectAdmissionPolicies(listener, presented);
|
|
89
|
+
if (listenerAdmission && listenerAdmission.kind !== "loopback") return merged;
|
|
90
|
+
return immutableAdmissionPolicy({ ...merged, allowMeteredComboTargets: presented.allowMeteredComboTargets });
|
|
91
|
+
}
|
|
@@ -23,7 +23,11 @@ import {
|
|
|
23
23
|
responsesSseToChatCompletionsSse,
|
|
24
24
|
} from "../chat/outbound";
|
|
25
25
|
import { ADVISOR_INTERNAL_CAPABILITY_HEADER, isInternalCallCapability } from "../lib/local-internal-call-capability";
|
|
26
|
-
import {
|
|
26
|
+
import type { CapturedAdmissionPolicy } from "../types/admission-policy";
|
|
27
|
+
import { ADVISOR_ADMISSION_SCOPE_HEADER, decodeAdvisorAdmissionScope, ADVISOR_ADMISSION_POLICY_HEADER, readAdvisorAdmissionPolicy, SIDECAR_ADMISSION_POLICY_HEADER, SIDECAR_INTERNAL_CAPABILITY_HEADER } from "./advisor-admission-scope";
|
|
28
|
+
import {
|
|
29
|
+
captureAdmissionPolicy, captureSelfFetchCredentialPolicy, inheritAdmissionPolicy, intersectAdmissionPolicies, selfFetchHostPolicy,
|
|
30
|
+
} from "./capture-admission-policy";
|
|
27
31
|
import { classifyError, cyberPolicyErrorType, CYBER_POLICY_ERROR_CODE, isCyberPolicyCode, UNDECLARED_TOOL_CALL_ERROR_CODE } from "../lib/errors";
|
|
28
32
|
import { redactSecretString } from "../lib/redact";
|
|
29
33
|
import { resolveClientRetryAfter } from "../lib/retry-after";
|
|
@@ -118,7 +122,10 @@ export async function handleChatCompletions(
|
|
|
118
122
|
req: Request,
|
|
119
123
|
config: OcxConfig,
|
|
120
124
|
logCtx: RequestLogContext,
|
|
121
|
-
logIds?: {
|
|
125
|
+
logIds?: {
|
|
126
|
+
requestId: string; start: number; turnAdmissionLease?: AdmissionLease; admission?: DataPlaneAdmission;
|
|
127
|
+
advisorAdmissionPolicy?: CapturedAdmissionPolicy;
|
|
128
|
+
},
|
|
122
129
|
): Promise<Response> {
|
|
123
130
|
// Set before routing so pre-dispatch refusals stay correlated. A Hermes-only id is marked as a
|
|
124
131
|
// fallback, so a native id resolved later on the Responses bridge still replaces it.
|
|
@@ -152,17 +159,35 @@ async function handleChatCompletionsWithBudget(
|
|
|
152
159
|
config: OcxConfig,
|
|
153
160
|
logCtx: RequestLogContext,
|
|
154
161
|
translatorBudget: TranslatorBudget,
|
|
155
|
-
logIds?: {
|
|
162
|
+
logIds?: {
|
|
163
|
+
requestId: string; start: number; turnAdmissionLease?: AdmissionLease; admission?: DataPlaneAdmission;
|
|
164
|
+
advisorAdmissionPolicy?: CapturedAdmissionPolicy;
|
|
165
|
+
},
|
|
156
166
|
): Promise<Response> {
|
|
157
167
|
const advisorInternal = isInternalCallCapability(req.headers.get(ADVISOR_INTERNAL_CAPABILITY_HEADER));
|
|
158
|
-
const
|
|
168
|
+
const sidecarInternal = isInternalCallCapability(req.headers.get(SIDECAR_INTERNAL_CAPABILITY_HEADER));
|
|
169
|
+
const callerPolicy = advisorInternal
|
|
170
|
+
? readAdvisorAdmissionPolicy(req.headers.get(ADVISOR_ADMISSION_POLICY_HEADER), req.headers.get(ADVISOR_INTERNAL_CAPABILITY_HEADER))
|
|
171
|
+
: readAdvisorAdmissionPolicy(req.headers.get(SIDECAR_ADMISSION_POLICY_HEADER), req.headers.get(SIDECAR_INTERNAL_CAPABILITY_HEADER));
|
|
172
|
+
const decodedScope = advisorInternal
|
|
159
173
|
? decodeAdvisorAdmissionScope(req.headers.get(ADVISOR_ADMISSION_SCOPE_HEADER))
|
|
160
174
|
: undefined;
|
|
161
|
-
|
|
175
|
+
// Only a validated internal hop gets its presented credential resolved; loopback admission for
|
|
176
|
+
// every other caller is untouched. An unknown credential fails closed (#7894).
|
|
177
|
+
const selfFetchPolicy = callerPolicy ? captureSelfFetchCredentialPolicy(req, config) : undefined;
|
|
178
|
+
if ((advisorInternal || sidecarInternal) && (!callerPolicy || selfFetchPolicy === null
|
|
179
|
+
|| advisorInternal && req.headers.has(ADVISOR_ADMISSION_SCOPE_HEADER) && !decodedScope)) {
|
|
162
180
|
// Refused requests still own a final log row like every other early rejection.
|
|
163
181
|
if (logIds) addFinalRequestLog(logIds.requestId, logIds.start, logCtx, 403, { closeReason: "non_stream" });
|
|
164
182
|
return chatCompletionsErrorResponse(403, "invalid inherited advisor admission scope", "permission_error", MODEL_NOT_ALLOWED_FOR_KEY);
|
|
165
183
|
}
|
|
184
|
+
// The listener snapshot was captured at authentication; internal hops add the policy of the
|
|
185
|
+
// credential they selected (which loopback admission never read) and their frozen registration.
|
|
186
|
+
const listenerPolicy = logIds?.advisorAdmissionPolicy ?? captureAdmissionPolicy(config, logIds?.admission);
|
|
187
|
+
const hostPolicy = selfFetchPolicy ? selfFetchHostPolicy(listenerPolicy, selfFetchPolicy, logIds?.admission) : listenerPolicy;
|
|
188
|
+
const advisorAdmissionPolicy = callerPolicy ? intersectAdmissionPolicies(hostPolicy, callerPolicy) : hostPolicy;
|
|
189
|
+
const admission = callerPolicy ? inheritAdmissionPolicy(logIds?.admission, advisorAdmissionPolicy) : logIds?.admission;
|
|
190
|
+
const inheritedAdmissionScope = callerPolicy ? advisorAdmissionPolicy.modelScope : undefined;
|
|
166
191
|
let chatBody: Rec;
|
|
167
192
|
try {
|
|
168
193
|
const rawBody = await readChatBody(req, translatorBudget, resolveInboundBodyLimitBytes(config.maxInboundBodyBytes));
|
|
@@ -525,7 +550,8 @@ async function handleChatCompletionsWithBudget(
|
|
|
525
550
|
...(logIds?.turnAdmissionLease ? { turnAdmissionLease: logIds.turnAdmissionLease } : {}),
|
|
526
551
|
// #1686: the Chat surface translates its body and replays here, so the admission fact has
|
|
527
552
|
// to ride along or a bearer-admitted Chat caller would still be refused by Direct.
|
|
528
|
-
...(
|
|
553
|
+
...(admission ? { admission } : {}),
|
|
554
|
+
advisorAdmissionPolicy,
|
|
529
555
|
// The bridge request carries no caller credential, so resolve the replay principal here.
|
|
530
556
|
replayPrincipal: { clientPrincipalId: resolveContextPrincipal(req, config, logIds?.admission) },
|
|
531
557
|
abortSignal: req.signal,
|
|
@@ -545,7 +571,7 @@ async function handleChatCompletionsWithBudget(
|
|
|
545
571
|
req, config, envelope, requestedModel, requestedStream: stream, translatorBudget,
|
|
546
572
|
// Children run without logIds; the request's admission rides the source so their
|
|
547
573
|
// replay scope resolves the same caller principal as every other surface.
|
|
548
|
-
...(
|
|
574
|
+
...(admission ? { admission } : {}),
|
|
549
575
|
}),
|
|
550
576
|
} : {}),
|
|
551
577
|
// Terminal vision-describe marker (roadmap 180): the bridge rebuilds
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { CodexInstallationIdUnavailableError } from "../codex/installation-id";
|
|
1
2
|
/**
|
|
2
3
|
* Anthropic Messages inbound (/v1/messages + /v1/messages/count_tokens) for Claude Code.
|
|
3
4
|
*
|
|
@@ -32,6 +33,8 @@ import { isKnownDesktop3pModelId, resolveDesktop3pAlias } from "../claude/deskto
|
|
|
32
33
|
import { resolveAlias, claudeCodeNativeAlias, legacyAliasForNative } from "../claude/alias";
|
|
33
34
|
import { recordDesktopRequest } from "../claude/desktop-health";
|
|
34
35
|
import { stripOneMillionMarker } from "../claude/context-windows";
|
|
36
|
+
import { captureAdmissionPolicy } from "./capture-admission-policy";
|
|
37
|
+
import type { CapturedAdmissionPolicy } from "../types/admission-policy";
|
|
35
38
|
import { captureClaudeInbound } from "../claude/inbound-debug";
|
|
36
39
|
import { declaredAnthropicServerTools, replayedAnthropicServerBlocks } from "../claude/inbound-content-options";
|
|
37
40
|
import { claudeCodeForIngress } from "../claude/intercept/model-bindings";
|
|
@@ -543,7 +546,10 @@ export async function handleClaudeMessages(
|
|
|
543
546
|
req: Request,
|
|
544
547
|
config: OcxConfig,
|
|
545
548
|
logCtx: RequestLogContext,
|
|
546
|
-
logIds?: {
|
|
549
|
+
logIds?: {
|
|
550
|
+
requestId: string; start: number; turnAdmissionLease?: AdmissionLease; admission?: DataPlaneAdmission;
|
|
551
|
+
advisorAdmissionPolicy?: CapturedAdmissionPolicy;
|
|
552
|
+
},
|
|
547
553
|
requestPolicy: RequestPolicyView = config,
|
|
548
554
|
ingress: ClaudeIngressOptions = {},
|
|
549
555
|
): Promise<Response> {
|
|
@@ -586,7 +592,10 @@ async function handleClaudeMessagesWithBudget(
|
|
|
586
592
|
config: OcxConfig,
|
|
587
593
|
logCtx: RequestLogContext,
|
|
588
594
|
translatorBudget: TranslatorBudget,
|
|
589
|
-
logIds?: {
|
|
595
|
+
logIds?: {
|
|
596
|
+
requestId: string; start: number; turnAdmissionLease?: AdmissionLease; admission?: DataPlaneAdmission;
|
|
597
|
+
advisorAdmissionPolicy?: CapturedAdmissionPolicy;
|
|
598
|
+
},
|
|
590
599
|
requestPolicy: RequestPolicyView = config,
|
|
591
600
|
ingress: ClaudeIngressOptions = {},
|
|
592
601
|
): Promise<Response> {
|
|
@@ -618,6 +627,8 @@ async function handleClaudeMessagesWithBudget(
|
|
|
618
627
|
// Built only under the reject policy; the legacy default leaves this request untouched.
|
|
619
628
|
let envelope: ProtocolEnvelope | undefined;
|
|
620
629
|
let messagesFeatures: () => Iterable<ProtocolFeature> = () => [];
|
|
630
|
+
// The Advisor caller policy is the admitted snapshot: capture it before the first await (#7859).
|
|
631
|
+
const advisorAdmissionPolicy = logIds?.advisorAdmissionPolicy ?? captureAdmissionPolicy(config, logIds?.admission);
|
|
621
632
|
try {
|
|
622
633
|
anthropicBody = await readAnthropicBody(req, translatorBudget, resolveInboundBodyLimitBytes(config.maxInboundBodyBytes));
|
|
623
634
|
// Defensive [1m] strip (devlog 138): clients normally remove the context-variant
|
|
@@ -960,6 +971,85 @@ async function handleClaudeMessagesWithBudget(
|
|
|
960
971
|
...(settledRoute?.provider.authMode === "oauth" && settledInstance
|
|
961
972
|
? { oauthFailoverQuorum: anthropicRoutingFor(settledInstance).hasAnthropicFailoverQuorum() } : {}),
|
|
962
973
|
};
|
|
974
|
+
if (settledRoute && isRec(anthropicBody)
|
|
975
|
+
&& nativeMessagesDeclineReason(settledRoute, anthropicBody, config, nativeSelector) === "bridge-only-policy"
|
|
976
|
+
&& nativeMessagesDeclineReason(settledRoute, anthropicBody, config, { ...nativeSelector, webSearchBackendAvailable: false }) === undefined) {
|
|
977
|
+
const { parseRequest } = await import("../responses/parser");
|
|
978
|
+
const { planWebSearch, shouldResolveOpenAiWebSearchSidecar } = await import("../web-search");
|
|
979
|
+
const replayConfig = buildClaudeReplayConfig(config);
|
|
980
|
+
const parsed = parseRequest(internalBody);
|
|
981
|
+
let openAiSidecar: import("../providers/openai-sidecar").ResolvedOpenAiForwardSidecar | undefined;
|
|
982
|
+
if (shouldResolveOpenAiWebSearchSidecar(replayConfig, parsed, false)) {
|
|
983
|
+
const { listOpenAiForwardSidecarCandidates, captureExplicitOpenAiCallerAuth, resolveFirstUsableOpenAiSidecar } = await import("../providers/openai-sidecar");
|
|
984
|
+
const candidates = listOpenAiForwardSidecarCandidates(replayConfig);
|
|
985
|
+
const headers = new Headers();
|
|
986
|
+
for (const name of FORWARD_HEADERS) {
|
|
987
|
+
if (name === "authorization" || name === "chatgpt-account-id") continue;
|
|
988
|
+
const value = req.headers.get(name);
|
|
989
|
+
if (value) headers.set(name, value);
|
|
990
|
+
}
|
|
991
|
+
const { codexAccountSelectionForTurn, tryAdmitTurn } = await import("./lifecycle");
|
|
992
|
+
// The probe owns its claim only until selection completes, not for the client turn.
|
|
993
|
+
const probeLease = logIds?.turnAdmissionLease && candidates.length ? tryAdmitTurn() : undefined;
|
|
994
|
+
const errors = await import("../codex/auth-context");
|
|
995
|
+
try {
|
|
996
|
+
req.signal.throwIfAborted();
|
|
997
|
+
if (logIds?.turnAdmissionLease && candidates.length && !probeLease) {
|
|
998
|
+
// No independent admission means availability is unknown; preserve the bridge.
|
|
999
|
+
nativeSelector.webSearchBackendAvailable = true;
|
|
1000
|
+
} else {
|
|
1001
|
+
if (candidates.some(candidate => candidate.accountMode === "direct") && probeLease) {
|
|
1002
|
+
if (!tryClaimNativeMainProfileForTurn(probeLease)) {
|
|
1003
|
+
nativeSelector.webSearchBackendAvailable = true;
|
|
1004
|
+
} else {
|
|
1005
|
+
const { getMainAccountToken } = await import("../codex/main-account");
|
|
1006
|
+
const token = getMainAccountToken();
|
|
1007
|
+
if (token) {
|
|
1008
|
+
const auth = captureExplicitOpenAiCallerAuth(new Headers({ authorization: `Bearer ${token.accessToken}`, "chatgpt-account-id": token.chatgptAccountId }), replayConfig);
|
|
1009
|
+
if (auth) { headers.set("authorization", auth.authorization); headers.set("chatgpt-account-id", auth.chatgptAccountId); }
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
openAiSidecar = await resolveFirstUsableOpenAiSidecar(candidates, headers, replayConfig, {
|
|
1014
|
+
admission: logIds?.admission, codexAuthPolicy: config, signal: req.signal,
|
|
1015
|
+
beginCodexAccountSelection: codexAccountSelectionForTurn(probeLease ?? undefined),
|
|
1016
|
+
});
|
|
1017
|
+
req.signal.throwIfAborted();
|
|
1018
|
+
// The bridge can inject main auth into pool selection. Only a negative pool probe
|
|
1019
|
+
// needs this extra read; an unavailable claim or present token leaves it uncertain.
|
|
1020
|
+
if (!openAiSidecar && probeLease && candidates.some(candidate => candidate.accountMode === "pool")) {
|
|
1021
|
+
if (!tryClaimNativeMainProfileForTurn(probeLease)) nativeSelector.webSearchBackendAvailable = true;
|
|
1022
|
+
else {
|
|
1023
|
+
const { getMainAccountToken } = await import("../codex/main-account");
|
|
1024
|
+
if (getMainAccountToken()) nativeSelector.webSearchBackendAvailable = true;
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
} catch (err) {
|
|
1029
|
+
// Refresh wraps cancellation in CodexAuthContextError; a cancelled request must not continue.
|
|
1030
|
+
if (req.signal.aborted) {
|
|
1031
|
+
openAiSidecar?.releaseProbeLease?.();
|
|
1032
|
+
throw req.signal.reason ?? err;
|
|
1033
|
+
}
|
|
1034
|
+
if (err instanceof CodexInstallationIdUnavailableError) {
|
|
1035
|
+
// An unavailable optional helper cannot displace an independent native route.
|
|
1036
|
+
nativeSelector.webSearchBackendAvailable = false;
|
|
1037
|
+
} else if (!(err instanceof errors.CodexPoolAuthenticationError) && !(err instanceof errors.CodexAuthContextError)
|
|
1038
|
+
&& !(err instanceof errors.CodexAccountCooldownError) && !(err instanceof errors.CodexThreadAffinityExpiredError)
|
|
1039
|
+
&& !(err instanceof errors.CodexMainProfileDrainingError)) {
|
|
1040
|
+
openAiSidecar?.releaseProbeLease?.();
|
|
1041
|
+
throw err;
|
|
1042
|
+
} else if (probeLease && candidates.some(candidate => candidate.accountMode === "pool")) nativeSelector.webSearchBackendAvailable = true;
|
|
1043
|
+
} finally { probeLease?.release(); }
|
|
1044
|
+
}
|
|
1045
|
+
try {
|
|
1046
|
+
nativeSelector.webSearchBackendAvailable ??= !!planWebSearch(replayConfig, parsed, false, settledRoute.provider, settledRoute.modelId, openAiSidecar, {
|
|
1047
|
+
admission: logIds?.admission, codexAuthPolicy: config, providerName: settledRoute.providerName,
|
|
1048
|
+
});
|
|
1049
|
+
} finally {
|
|
1050
|
+
openAiSidecar?.releaseProbeLease?.();
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
963
1053
|
const nativeDecline = settledRoute && isRec(anthropicBody)
|
|
964
1054
|
? nativeMessagesDeclineReason(settledRoute, anthropicBody, config, nativeSelector)
|
|
965
1055
|
: "rollout-disabled";
|
|
@@ -1122,6 +1212,7 @@ async function handleClaudeMessagesWithBudget(
|
|
|
1122
1212
|
// Routing keeps Claude-only sidecar overrides; admission policy must follow the live owner.
|
|
1123
1213
|
codexAuthPolicy: config,
|
|
1124
1214
|
...(logIds?.admission ? { admission: logIds.admission } : {}),
|
|
1215
|
+
advisorAdmissionPolicy,
|
|
1125
1216
|
// The translated request never forwards the caller credential; resolve the principal first.
|
|
1126
1217
|
replayPrincipal: { clientPrincipalId: resolveContextPrincipal(req, config, logIds?.admission) },
|
|
1127
1218
|
...(logIds?.turnAdmissionLease ? { turnAdmissionLease: logIds.turnAdmissionLease } : {}),
|