@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
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { websocketsEnabled } from "../config";
|
|
2
|
+
import { omitDisabledNativeCatalogEntries } from "../codex/catalog/native-omission";
|
|
2
3
|
import type { OcxConfig } from "../types";
|
|
3
4
|
import { buildCatalogEntries } from "../codex/catalog/build-entries";
|
|
4
5
|
import { loadCatalogTemplate } from "../codex/catalog/bundled";
|
|
@@ -42,5 +43,5 @@ export function buildCodexModelList({
|
|
|
42
43
|
accountNativeSlugsBySelector, config.keepNativeChatGptOnV1 === true, config.modelPickerOrder,
|
|
43
44
|
nativeSource,
|
|
44
45
|
);
|
|
45
|
-
return { models: applyNativeVisibility(entries, disabledModels, accountSelectors.length > 0, new Set(accountNativeSlugs)) };
|
|
46
|
+
return { models: omitDisabledNativeCatalogEntries(applyNativeVisibility(entries, disabledModels, accountSelectors.length > 0, new Set(accountNativeSlugs)), config) };
|
|
46
47
|
}
|
|
@@ -163,6 +163,11 @@ function build(configRead: StoreRead, authRead: StoreRead, signature: string, no
|
|
|
163
163
|
|| (config.value.providers !== undefined && !isRecord(config.value.providers)))) complete = false;
|
|
164
164
|
if (authSig !== "absent" && auth.ok && !isRecord(auth.value)) complete = false;
|
|
165
165
|
if (isRecord(config.value) && isRecord(config.value.providers)) walkProvider(config.value.providers, 0);
|
|
166
|
+
if (isRecord(config.value) && isRecord(config.value.codexRoleCapability)
|
|
167
|
+
&& isRecord(config.value.codexRoleCapability.artificialAnalysis)) {
|
|
168
|
+
const key = config.value.codexRoleCapability.artificialAnalysis.apiKey;
|
|
169
|
+
addReference(typeof key === "string" ? key.trim() : key);
|
|
170
|
+
}
|
|
166
171
|
if (isRecord(auth.value)) walkAuth(auth.value, 0);
|
|
167
172
|
|
|
168
173
|
const names = [...envNames].sort();
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { isolateCodexPoolClientMetadata, mergeCodexSelectedHeaders } from "../codex/forward-transport-headers";
|
|
2
|
+
import { CodexInstallationIdUnavailableError } from "../codex/installation-id";
|
|
1
3
|
/** Native history/notes JSON relay. No interpretation of encrypted tool arguments or retries. */
|
|
2
4
|
import { formatErrorResponse } from "../bridge";
|
|
3
5
|
import {
|
|
@@ -109,7 +111,8 @@ async function relayContextHistory(
|
|
|
109
111
|
"Context account ownership is unavailable; start a new session and preserve needed state before resetting context");
|
|
110
112
|
}
|
|
111
113
|
let authContext: Awaited<ReturnType<typeof resolveCodexAuthContext>>;
|
|
112
|
-
|
|
114
|
+
let upstreamBody: unknown = body;
|
|
115
|
+
let headers = new Headers(candidate.provider.headers);
|
|
113
116
|
try {
|
|
114
117
|
authContext = await resolveCodexAuthContext(contextSelectionHeaders(req.headers, sessionId), config, owner.kind === "stored" ? "pool" : "direct", {
|
|
115
118
|
// The same deadline bounds credential selection and refresh waits.
|
|
@@ -131,11 +134,10 @@ async function relayContextHistory(
|
|
|
131
134
|
logCtx.provider = formatCodexProviderForLog(candidate.providerName, codexLogAccountId(authContext), config);
|
|
132
135
|
// Materialization rechecks the current account policy after async selection.
|
|
133
136
|
// Synthetic lane IDs are local selection metadata, never upstream headers.
|
|
134
|
-
|
|
137
|
+
headers = mergeCodexSelectedHeaders(candidate.provider.headers, materializeCodexUpstreamAuth(req.headers, authContext, {
|
|
135
138
|
config, modelId: "context_history", admission, substituteMainCredential,
|
|
136
|
-
}))
|
|
137
|
-
|
|
138
|
-
}
|
|
139
|
+
}));
|
|
140
|
+
if (authContext.kind === "pool") upstreamBody = isolateCodexPoolClientMetadata(body, authContext.chatgptAccountId);
|
|
139
141
|
// Check the assembled outbound headers, including configured provider headers.
|
|
140
142
|
validateForwardAdmissionCredential(headers, config);
|
|
141
143
|
// Recheck actual wire identity after async selection/materialization. A replaced
|
|
@@ -148,6 +150,7 @@ async function relayContextHistory(
|
|
|
148
150
|
} catch (err) {
|
|
149
151
|
const cancelled = cancellationResponse(req, deadline);
|
|
150
152
|
if (cancelled) return cancelled;
|
|
153
|
+
if (err instanceof CodexInstallationIdUnavailableError) return formatErrorResponse(503, "server_busy", err.message);
|
|
151
154
|
if (err instanceof CodexAccountCooldownError) return cooldownErrorResponse(err);
|
|
152
155
|
if (err instanceof CodexMainProfileDrainingError) return codexMainProfileDrainingResponse();
|
|
153
156
|
if (err instanceof CodexThreadAffinityExpiredError) return formatErrorResponse(409, "invalid_request_error", "Codex thread account affinity expired; start a new session");
|
|
@@ -176,7 +179,7 @@ async function relayContextHistory(
|
|
|
176
179
|
let response: Response | undefined;
|
|
177
180
|
try {
|
|
178
181
|
response = await fetch(`${candidate.provider.baseUrl}/${endpoint}`, {
|
|
179
|
-
method: "POST", headers, body: JSON.stringify(
|
|
182
|
+
method: "POST", headers, body: JSON.stringify(upstreamBody), signal: deadline.signal, redirect: "manual",
|
|
180
183
|
});
|
|
181
184
|
const result = await readBoundedResponseBytes(response, {maxBytes: MAX_RESPONSE_BYTES, signal: deadline.signal});
|
|
182
185
|
if (result.oversized) return formatErrorResponse(502, "upstream_error", "Context response exceeded 16 MiB");
|
package/src/server/images.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { CodexInstallationIdUnavailableError } from "../codex/installation-id";
|
|
2
|
+
import { isolateCodexPoolClientMetadata, mergeCodexSelectedHeaders } from "../codex/forward-transport-headers";
|
|
1
3
|
/**
|
|
2
4
|
* /v1/images/{generations,edits} relay (issue #83).
|
|
3
5
|
*
|
|
@@ -730,7 +732,9 @@ export async function handleImages(
|
|
|
730
732
|
});
|
|
731
733
|
if (forward) logCtx.provider = formatCodexProviderForLog(forward.providerName, codexLogAccountId(forward.authContext), config);
|
|
732
734
|
} catch (err) {
|
|
733
|
-
if (err instanceof
|
|
735
|
+
if (err instanceof CodexInstallationIdUnavailableError) {
|
|
736
|
+
forwardAuthError = formatErrorResponse(503, "server_busy", err.message);
|
|
737
|
+
} else if (err instanceof CodexAccountCooldownError) {
|
|
734
738
|
forwardAuthError = cooldownErrorResponse(err);
|
|
735
739
|
} else if (err instanceof CodexMainProfileDrainingError) {
|
|
736
740
|
forwardAuthError = codexMainProfileDrainingResponse();
|
|
@@ -752,7 +756,7 @@ export async function handleImages(
|
|
|
752
756
|
}
|
|
753
757
|
}
|
|
754
758
|
|
|
755
|
-
|
|
759
|
+
let headers = new Headers({ "content-type": "application/json" });
|
|
756
760
|
const releaseForwardProbe = (): void => {
|
|
757
761
|
try { forward?.releaseProbeLease?.(); }
|
|
758
762
|
catch { console.error("[images] Failed to release probe lease"); }
|
|
@@ -773,8 +777,7 @@ export async function handleImages(
|
|
|
773
777
|
}
|
|
774
778
|
const { provider } = forward;
|
|
775
779
|
try {
|
|
776
|
-
|
|
777
|
-
for (const [name, value] of forward.headers) headers.set(name, value);
|
|
780
|
+
headers = mergeCodexSelectedHeaders({ "content-type": "application/json", ...provider.headers }, forward.headers);
|
|
778
781
|
assertImagesUpstreamAuthorization(headers, config);
|
|
779
782
|
} catch {
|
|
780
783
|
releaseForwardProbe();
|
|
@@ -866,7 +869,9 @@ export async function handleImages(
|
|
|
866
869
|
upstreamResponse = await fetch(url, {
|
|
867
870
|
method: "POST",
|
|
868
871
|
headers,
|
|
869
|
-
body: JSON.stringify(
|
|
872
|
+
body: JSON.stringify(isolateCodexPoolClientMetadata(
|
|
873
|
+
body, forward?.authContext.kind === "pool" ? forward.authContext.chatgptAccountId : undefined,
|
|
874
|
+
)),
|
|
870
875
|
signal: linkedSignal.signal,
|
|
871
876
|
// Do not follow a cross-origin 3xx while carrying Codex credentials. Bun strips
|
|
872
877
|
// `Authorization` across origins but forwards nonstandard headers, so
|
|
@@ -911,6 +916,10 @@ export async function handleImages(
|
|
|
911
916
|
releaseForwardProbe();
|
|
912
917
|
return formatErrorResponse(499, "client_closed_request", `image ${endpoint} request canceled by client`);
|
|
913
918
|
}
|
|
919
|
+
if (err instanceof CodexInstallationIdUnavailableError) {
|
|
920
|
+
releaseForwardProbe();
|
|
921
|
+
return formatErrorResponse(503, "server_busy", err.message);
|
|
922
|
+
}
|
|
914
923
|
if (linkedSignal.signal.aborted || (err instanceof Error && err.name === "TimeoutError")) {
|
|
915
924
|
forward?.recordOutcome?.("timeout");
|
|
916
925
|
// codex retries 5xx up to 4 more times; a retried 504 is acceptable for a transient hang.
|
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
resolveLiveSidebandUpgrade,
|
|
20
20
|
} from "../live";
|
|
21
21
|
import { RESPONSE_TTL_MS } from "../../responses/state";
|
|
22
|
+
import { isolateCodexPoolClientMetadata } from "../../codex/forward-transport-headers";
|
|
22
23
|
|
|
23
24
|
export const MAX_WS_FRAME_BYTES = 50 * 1024 * 1024;
|
|
24
25
|
/**
|
|
@@ -124,7 +125,20 @@ function releaseLiveSidebandAdmission(ws: ServerWebSocket<WsData>): void {
|
|
|
124
125
|
* `Uint8Array.from` copies into a fresh `ArrayBuffer`-backed view, so a frame
|
|
125
126
|
* arriving from `node:buffer` still round-trips byte-for-byte.
|
|
126
127
|
*/
|
|
127
|
-
export function sendUpstreamFrame(upstream: WebSocket, frame: string | Buffer): void {
|
|
128
|
+
export function sendUpstreamFrame(upstream: WebSocket, frame: string | Buffer, context?: WsData["authContext"]): void {
|
|
129
|
+
if (context?.kind === "pool") {
|
|
130
|
+
let parsed: unknown;
|
|
131
|
+
try { parsed = JSON.parse(typeof frame === "string" ? frame : new TextDecoder("utf-8", { fatal: true }).decode(frame)); }
|
|
132
|
+
catch { /* Non-JSON frames retain their original bytes. */ }
|
|
133
|
+
const account = context.chatgptAccountId;
|
|
134
|
+
let isolated = isolateCodexPoolClientMetadata(parsed, account);
|
|
135
|
+
if (isolated && typeof isolated === "object" && !Array.isArray(isolated)) {
|
|
136
|
+
const record = isolated as Record<string, unknown>;
|
|
137
|
+
const session = isolateCodexPoolClientMetadata(record.session, account);
|
|
138
|
+
if (session !== record.session) isolated = { ...record, session };
|
|
139
|
+
}
|
|
140
|
+
if (isolated !== parsed) frame = typeof frame === "string" ? JSON.stringify(isolated) : Buffer.from(JSON.stringify(isolated));
|
|
141
|
+
}
|
|
128
142
|
if (typeof frame === "string") {
|
|
129
143
|
upstream.send(frame);
|
|
130
144
|
return;
|
|
@@ -574,7 +588,7 @@ export function attachLiveSidebandUpstream(
|
|
|
574
588
|
ws.data.livePendingBytes = undefined;
|
|
575
589
|
for (const frame of pending) {
|
|
576
590
|
try {
|
|
577
|
-
sendUpstreamFrame(upstream, frame);
|
|
591
|
+
sendUpstreamFrame(upstream, frame, ws.data.authContext);
|
|
578
592
|
} catch {
|
|
579
593
|
closeLiveSideband(ws, 1011, "upstream send failed");
|
|
580
594
|
return;
|
|
@@ -109,6 +109,7 @@ import {
|
|
|
109
109
|
} from "../auth-cors";
|
|
110
110
|
import { managementSessionIssuance } from "../management-auth";
|
|
111
111
|
import { resolveAdmissionModelScope, routeAllowedByScope } from "../admission-model-scope";
|
|
112
|
+
import { captureAdmissionPolicy } from "../capture-admission-policy";
|
|
112
113
|
import {
|
|
113
114
|
disableResponsesRequestTimeout,
|
|
114
115
|
handleResponses,
|
|
@@ -1323,10 +1324,12 @@ export function createServeOptions(ctx: ServeOptionsContext) {
|
|
|
1323
1324
|
...admissionFields(admission),
|
|
1324
1325
|
inboundProtocol: "responses",
|
|
1325
1326
|
};
|
|
1327
|
+
const advisorAdmissionPolicy = captureAdmissionPolicy(config, admission);
|
|
1326
1328
|
return runAdmittedHttpTurn(req, policy, async turnAdmissionLease => {
|
|
1327
1329
|
let response: Response;
|
|
1328
1330
|
try {
|
|
1329
1331
|
response = await handleResponsesCompact(req, config, logCtx, turnAdmissionLease, admission, {
|
|
1332
|
+
advisorAdmissionPolicy,
|
|
1330
1333
|
onRequestBodyRead: () => disableResponsesRequestTimeout(req, requestServer),
|
|
1331
1334
|
});
|
|
1332
1335
|
} catch (error) {
|
|
@@ -1482,12 +1485,15 @@ export function createServeOptions(ctx: ServeOptionsContext) {
|
|
|
1482
1485
|
addFinalRequestLog(requestId, start, logCtx, status, meta);
|
|
1483
1486
|
};
|
|
1484
1487
|
const sessionReq = withCallerSessionIdentity(withGrokSessionIdentity(req), admission);
|
|
1488
|
+
// Capture at authentication: runAdmittedHttpTurn can wait for body capacity first (#7859).
|
|
1489
|
+
const advisorAdmissionPolicy = captureAdmissionPolicy(config, admission);
|
|
1485
1490
|
return runAdmittedHttpTurn(sessionReq, policy, async turnAdmissionLease => {
|
|
1486
1491
|
let response: Response;
|
|
1487
1492
|
try {
|
|
1488
1493
|
response = await handleResponses(sessionReq, config, logCtx, {
|
|
1489
1494
|
turnAdmissionLease,
|
|
1490
1495
|
admission,
|
|
1496
|
+
advisorAdmissionPolicy,
|
|
1491
1497
|
onRequestBodyRead: () => disableResponsesRequestTimeout(req, requestServer),
|
|
1492
1498
|
abortSignal: req.signal,
|
|
1493
1499
|
onFirstOutput: () => recordFirstOutput(logCtx, start),
|
|
@@ -1571,8 +1577,10 @@ export function createServeOptions(ctx: ServeOptionsContext) {
|
|
|
1571
1577
|
let ownsRequestLog = false;
|
|
1572
1578
|
const claimRequestLog = (work: (lease: ActiveTurnLease) => Promise<Response>) =>
|
|
1573
1579
|
(lease: ActiveTurnLease) => { ownsRequestLog = true; return work(lease); };
|
|
1580
|
+
// Capture at authentication: runAdmittedHttpTurn can wait for body capacity first (#7859).
|
|
1581
|
+
const advisorAdmissionPolicy = captureAdmissionPolicy(config, admission);
|
|
1574
1582
|
const response = await runAdmittedHttpTurn(sessionReq, policy, claimRequestLog(async turnAdmissionLease => withCors(
|
|
1575
|
-
await handleClaudeMessages(sessionReq, config, logCtx, { requestId, start, turnAdmissionLease, admission }, policy, { claudeIntercept: ingress === "claude-intercept" }),
|
|
1583
|
+
await handleClaudeMessages(sessionReq, config, logCtx, { requestId, start, turnAdmissionLease, admission, advisorAdmissionPolicy }, policy, { claudeIntercept: ingress === "claude-intercept" }),
|
|
1576
1584
|
req,
|
|
1577
1585
|
policy,
|
|
1578
1586
|
)), { requestId, start, logCtx, onLogged: () => { ownsRequestLog = true; } });
|
|
@@ -1607,10 +1615,12 @@ export function createServeOptions(ctx: ServeOptionsContext) {
|
|
|
1607
1615
|
const sessionReq = withCallerSessionIdentity(req, admission);
|
|
1608
1616
|
// Only expose an id when the handler or a logged refusal owns its history row.
|
|
1609
1617
|
let ownsRequestLog = false;
|
|
1618
|
+
// Capture at authentication: runAdmittedHttpTurn can wait for body capacity first (#7859).
|
|
1619
|
+
const advisorAdmissionPolicy = captureAdmissionPolicy(config, admission);
|
|
1610
1620
|
const response = await runAdmittedHttpTurn(sessionReq, policy, async turnAdmissionLease => {
|
|
1611
1621
|
ownsRequestLog = true;
|
|
1612
1622
|
return withCors(
|
|
1613
|
-
await handleChatCompletions(sessionReq, config, logCtx, { requestId, start, turnAdmissionLease, admission }),
|
|
1623
|
+
await handleChatCompletions(sessionReq, config, logCtx, { requestId, start, turnAdmissionLease, admission, advisorAdmissionPolicy }),
|
|
1614
1624
|
req,
|
|
1615
1625
|
policy,
|
|
1616
1626
|
);
|
|
@@ -1828,6 +1838,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
|
|
|
1828
1838
|
...(audioClient?.protocol ? { headers: { "sec-websocket-protocol": audioClient.protocol } } : {}),
|
|
1829
1839
|
data: {
|
|
1830
1840
|
kind: "live-sideband",
|
|
1841
|
+
authContext: resolved.authContext,
|
|
1831
1842
|
liveUpstream: upstreamHandshake.socket,
|
|
1832
1843
|
liveUpstreamUrl: resolved.upstreamWsUrl,
|
|
1833
1844
|
liveUpstreamHeaders: resolved.headers,
|
|
@@ -3,6 +3,7 @@ import { NativeInjectionChannel } from "../responses/native-injection";
|
|
|
3
3
|
import { NativeSteeringChannel, NativeSteeringError } from "../responses/native-steering";
|
|
4
4
|
import { createNativeSteeringLogObserver } from "../responses/native-steering-log";
|
|
5
5
|
import { reasoningArchiveErrorResponse } from "../responses/reasoning-archive-error";
|
|
6
|
+
import { captureAdmissionPolicy } from "../capture-admission-policy";
|
|
6
7
|
import type { Server, ServerWebSocket } from "bun";
|
|
7
8
|
import {
|
|
8
9
|
LIVE_SIDEBAND_UPSTREAM_OPEN_TIMEOUT_MS,
|
|
@@ -178,7 +179,7 @@ export function createWebsocketHandler(
|
|
|
178
179
|
return;
|
|
179
180
|
}
|
|
180
181
|
try {
|
|
181
|
-
sendUpstreamFrame(upstream, raw);
|
|
182
|
+
sendUpstreamFrame(upstream, raw, ws.data.authContext);
|
|
182
183
|
if (ws.data.liveMaxSessionMs !== undefined && upstream.bufferedAmount > MAX_WS_FRAME_BYTES) {
|
|
183
184
|
closeLiveSideband(ws, 1013, "audio upstream backpressure");
|
|
184
185
|
}
|
|
@@ -303,6 +304,7 @@ export function createWebsocketHandler(
|
|
|
303
304
|
}
|
|
304
305
|
|
|
305
306
|
// Only a genuinely admitted turn may receive steering or continuations.
|
|
307
|
+
const advisorAdmissionPolicy = captureAdmissionPolicy(config, ws.data.admission);
|
|
306
308
|
const finishActivity = ws.data.responsesActivity?.beginTurn(frame.input);
|
|
307
309
|
ws.data.nativeControl = nativeControl;
|
|
308
310
|
const payload: Record<string, unknown> = { ...frame };
|
|
@@ -343,6 +345,7 @@ export function createWebsocketHandler(
|
|
|
343
345
|
try {
|
|
344
346
|
let terminalRecorder: ((status: ResponsesTerminalStatus, httpStatusOverride?: number) => void) | undefined;
|
|
345
347
|
const response = await handleResponses(req, config, logCtx, {
|
|
348
|
+
advisorAdmissionPolicy,
|
|
346
349
|
...(wsAdmission ? { admission: wsAdmission } : {}),
|
|
347
350
|
forceEmptyResponseId: true,
|
|
348
351
|
inboundTransport: "websocket",
|
package/src/server/live.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { CodexInstallationIdUnavailableError } from "../codex/installation-id";
|
|
2
|
+
import { isolateCodexPoolClientMetadata, mergeCodexSelectedHeaders } from "../codex/forward-transport-headers";
|
|
1
3
|
import { codexCompatibleUrl } from "../codex/context-compat";
|
|
2
4
|
/**
|
|
3
5
|
* /v1/live and /v1/realtime/calls relay (issue #371).
|
|
@@ -38,6 +40,7 @@ import {
|
|
|
38
40
|
CodexModelAvailabilityError,
|
|
39
41
|
CodexPoolAuthenticationError,
|
|
40
42
|
CodexThreadAffinityExpiredError,
|
|
43
|
+
type CodexAuthContext,
|
|
41
44
|
} from "../codex/auth-context";
|
|
42
45
|
import { formatCodexProviderForLog } from "../codex/routing";
|
|
43
46
|
import { cancelBodyOnAbort, signalWithTimeout } from "../lib/abort";
|
|
@@ -315,10 +318,12 @@ export type LiveSidebandTarget =
|
|
|
315
318
|
|
|
316
319
|
export type LiveRelayTarget = {
|
|
317
320
|
headers: Record<string, string>;
|
|
321
|
+
authContext?: CodexAuthContext;
|
|
318
322
|
providerBaseUrl: string;
|
|
319
323
|
usesBackendShape: boolean;
|
|
320
324
|
keyed: boolean;
|
|
321
325
|
recordOutcome?: (status: number | "timeout" | "connect_error") => void;
|
|
326
|
+
releaseProbeLease?: () => void;
|
|
322
327
|
};
|
|
323
328
|
|
|
324
329
|
function isChatGptBackendBaseUrl(baseUrl: string): boolean {
|
|
@@ -723,7 +728,9 @@ export async function resolveLiveRelay(
|
|
|
723
728
|
);
|
|
724
729
|
}
|
|
725
730
|
} catch (err) {
|
|
726
|
-
if (err instanceof
|
|
731
|
+
if (err instanceof CodexInstallationIdUnavailableError) {
|
|
732
|
+
forwardAuthError = formatErrorResponse(503, "server_busy", err.message);
|
|
733
|
+
} else if (err instanceof CodexAccountCooldownError) {
|
|
727
734
|
forwardAuthError = cooldownErrorResponse(err);
|
|
728
735
|
} else if (err instanceof CodexMainProfileDrainingError) {
|
|
729
736
|
forwardAuthError = codexMainProfileDrainingResponse();
|
|
@@ -769,11 +776,12 @@ export async function resolveLiveRelay(
|
|
|
769
776
|
forward.releaseProbeLease?.();
|
|
770
777
|
return denial;
|
|
771
778
|
}
|
|
772
|
-
|
|
773
|
-
for (const [name, value] of forward.headers) headers[name] = value;
|
|
779
|
+
const selectedHeaders = mergeCodexSelectedHeaders({ ...headers, ...provider.headers }, forward.headers);
|
|
774
780
|
logCtx.model = "gpt-live";
|
|
775
781
|
return {
|
|
776
|
-
headers,
|
|
782
|
+
headers: Object.fromEntries(selectedHeaders),
|
|
783
|
+
authContext: forward.authContext,
|
|
784
|
+
releaseProbeLease: forward.releaseProbeLease,
|
|
777
785
|
providerBaseUrl: provider.baseUrl,
|
|
778
786
|
usesBackendShape: isChatGptBackendBaseUrl(provider.baseUrl),
|
|
779
787
|
keyed: false,
|
|
@@ -855,6 +863,18 @@ export async function handleLive(
|
|
|
855
863
|
const linkedSignal = signalWithTimeout(LIVE_UPSTREAM_TIMEOUT_MS, req.signal);
|
|
856
864
|
const sidecarExit = sidecarEnter("live");
|
|
857
865
|
try {
|
|
866
|
+
if (relay.authContext?.kind === "pool") {
|
|
867
|
+
let parsed: unknown;
|
|
868
|
+
try { parsed = JSON.parse(new TextDecoder().decode(outboundBody)); } catch { /* Upstream owns invalid JSON. */ }
|
|
869
|
+
const accountId = relay.authContext.chatgptAccountId;
|
|
870
|
+
let isolated = isolateCodexPoolClientMetadata(parsed, accountId);
|
|
871
|
+
if (isolated && typeof isolated === "object" && !Array.isArray(isolated)) {
|
|
872
|
+
const record = isolated as Record<string, unknown>;
|
|
873
|
+
const session = isolateCodexPoolClientMetadata(record.session, accountId);
|
|
874
|
+
if (session !== record.session) isolated = { ...record, session };
|
|
875
|
+
}
|
|
876
|
+
if (isolated !== parsed) outboundBody = new TextEncoder().encode(JSON.stringify(isolated)).buffer as ArrayBuffer;
|
|
877
|
+
}
|
|
858
878
|
const upstreamResponse = await fetch(url, {
|
|
859
879
|
method: "POST",
|
|
860
880
|
headers,
|
|
@@ -901,6 +921,10 @@ export async function handleLive(
|
|
|
901
921
|
if (req.signal.aborted) {
|
|
902
922
|
return formatErrorResponse(499, "client_closed_request", "live request canceled by client");
|
|
903
923
|
}
|
|
924
|
+
if (err instanceof CodexInstallationIdUnavailableError) {
|
|
925
|
+
relay.releaseProbeLease?.();
|
|
926
|
+
return formatErrorResponse(503, "server_busy", err.message);
|
|
927
|
+
}
|
|
904
928
|
if (err instanceof Error && err.name === "TimeoutError") {
|
|
905
929
|
relay.recordOutcome?.("timeout");
|
|
906
930
|
return formatErrorResponse(504, "upstream_error", "live upstream timed out");
|
|
@@ -925,7 +949,7 @@ export async function resolveLiveSidebandUpgrade(
|
|
|
925
949
|
target: LiveSidebandTarget,
|
|
926
950
|
turnAdmissionLease?: AdmissionLease,
|
|
927
951
|
admission?: DataPlaneAdmission,
|
|
928
|
-
): Promise<{ headers: Record<string, string>; upstreamWsUrl: string; recordOutcome?: LiveRelayTarget["recordOutcome"] } | Response> {
|
|
952
|
+
): Promise<{ headers: Record<string, string>; upstreamWsUrl: string; authContext?: CodexAuthContext; recordOutcome?: LiveRelayTarget["recordOutcome"] } | Response> {
|
|
929
953
|
const relay = await resolveLiveRelay(req, config, logCtx, turnAdmissionLease, {
|
|
930
954
|
admission,
|
|
931
955
|
model: liveSidebandModel(target),
|
|
@@ -933,6 +957,7 @@ export async function resolveLiveSidebandUpgrade(
|
|
|
933
957
|
});
|
|
934
958
|
if (relay instanceof Response) return relay;
|
|
935
959
|
return {
|
|
960
|
+
authContext: relay.authContext,
|
|
936
961
|
headers: relay.headers,
|
|
937
962
|
upstreamWsUrl: buildLiveSidebandUpstreamWsUrl(target, config.experimentalRealtimeWsBaseUrl),
|
|
938
963
|
recordOutcome: relay.recordOutcome,
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { prepareClaudeCodePatch } from "./claude-code-settings-patch";
|
|
2
|
+
import { beginCodexCliSelectionParentWriteAsync, withCodexCliSelectionParentWriteAsync,
|
|
3
|
+
CodexCliSelectionMutationBusyError, type CodexCliSelectionAsyncParentWrite } from "../../codex/cli-update-selection-gate";
|
|
2
4
|
import { readConfigForAdmittedMutation } from "../../config/persisted-mutation";
|
|
3
5
|
import { mirrorDesiredEnabledOntoSnapshot, persistDesktopModeField, persistDesktopProfileField } from "./claude-desktop-config-writers";
|
|
4
6
|
import { getConfigDir as configRoot, withConfigDirHardeningSettled as settleConfigRoot } from "../../config/paths";
|
|
@@ -205,6 +207,7 @@ export async function injectionModelView(config: OcxConfig, routed: readonly Cat
|
|
|
205
207
|
export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise<Response | null> {
|
|
206
208
|
try { return await handleAgentSettingsRoutesImpl(ctx); }
|
|
207
209
|
catch (error) {
|
|
210
|
+
if (error instanceof CodexCliSelectionMutationBusyError) return jsonResponse({ error: error.message, retryable: true }, 503);
|
|
208
211
|
if (!(error instanceof WindowsSecretAclSettleTimeoutError)) throw error;
|
|
209
212
|
return jsonResponse({ error: "Could not save settings", code: "write_failed", diagnostic: { stage: "ca", cause: "ETIMEDOUT" } }, 500);
|
|
210
213
|
}
|
|
@@ -402,10 +405,8 @@ async function handleAgentSettingsRoutesImpl(ctx: ManagementContext): Promise<Re
|
|
|
402
405
|
// repeats this check, but doing it here prevents an earlier flag/mode/agents
|
|
403
406
|
// write from landing before an unsupported runtime returns 502.
|
|
404
407
|
if (wantsModeHintText && body.multiAgentModeHintText !== null
|
|
405
|
-
&& probeCodexSupportsModeHint
|
|
406
|
-
return jsonResponse({
|
|
407
|
-
error: `writing multiAgentModeHintText failed: ${MODE_HINT_UNSUPPORTED_ERROR}`,
|
|
408
|
-
}, 502);
|
|
408
|
+
&& await withCodexCliSelectionParentWriteAsync(probeCodexSupportsModeHint, { signal: req.signal }) === false) {
|
|
409
|
+
return jsonResponse({ error: `writing multiAgentModeHintText failed: ${MODE_HINT_UNSUPPORTED_ERROR}` }, 502);
|
|
409
410
|
}
|
|
410
411
|
const warnings: string[] = [];
|
|
411
412
|
let requestedFlag: boolean | undefined;
|
|
@@ -428,8 +429,13 @@ async function handleAgentSettingsRoutesImpl(ctx: ManagementContext): Promise<Re
|
|
|
428
429
|
return jsonResponse({ error: configWriteLockFailureMessage(configWriteLock), retryable: configWriteLock.error === "locked" }, 502);
|
|
429
430
|
}
|
|
430
431
|
const heldWriteLock = configWriteLock !== null && configWriteLock.ok ? configWriteLock.handle : undefined;
|
|
432
|
+
let selectionWrite: CodexCliSelectionAsyncParentWrite | undefined;
|
|
431
433
|
try {
|
|
432
|
-
|
|
434
|
+
if (wantsFlag || wantsMode || wantsThreads || wantsKeepNative || (wantsModeHintText && body.multiAgentModeHintText !== null)) {
|
|
435
|
+
selectionWrite = await beginCodexCliSelectionParentWriteAsync({ signal: req.signal });
|
|
436
|
+
if (!selectionWrite.entered) return jsonResponse({ error: "codex_cli_selection_busy", retryable: true }, 503);
|
|
437
|
+
}
|
|
438
|
+
const commit = () => {
|
|
433
439
|
const currentPlan = readModePlan();
|
|
434
440
|
if (currentPlan instanceof Response) return currentPlan;
|
|
435
441
|
const { effectiveMode } = currentPlan;
|
|
@@ -497,9 +503,11 @@ async function handleAgentSettingsRoutesImpl(ctx: ManagementContext): Promise<Re
|
|
|
497
503
|
}
|
|
498
504
|
}
|
|
499
505
|
return null;
|
|
500
|
-
}
|
|
506
|
+
};
|
|
507
|
+
const writeRefusal = await settleConfigRoot(configRoot(), () => selectionWrite ? selectionWrite.commit(commit) : commit());
|
|
501
508
|
if (writeRefusal) return writeRefusal;
|
|
502
509
|
} finally {
|
|
510
|
+
selectionWrite?.exit();
|
|
503
511
|
if (heldWriteLock) releaseConfigWriteLock(heldWriteLock);
|
|
504
512
|
}
|
|
505
513
|
// Derived from fresh post-write readers (readConfigText is uncached): upstream
|
|
@@ -558,9 +566,9 @@ async function handleAgentSettingsRoutesImpl(ctx: ManagementContext): Promise<Re
|
|
|
558
566
|
let toggle = deps.toggleDefaultModeRequestUserInput;
|
|
559
567
|
if (!toggle) {
|
|
560
568
|
try {
|
|
561
|
-
const {
|
|
569
|
+
const { codexFeaturesInvocationAsync, runCodexFeaturesCommand } = await import("../../cli/v2");
|
|
562
570
|
const action = body.enabled ? "enable" : "disable";
|
|
563
|
-
const invocation =
|
|
571
|
+
const invocation = await codexFeaturesInvocationAsync(action, DEFAULT_MODE_REQUEST_USER_INPUT_FEATURE_KEY, process.platform, { requireAvailable: true });
|
|
564
572
|
toggle = (_enabled, env, validate) => runCodexFeaturesCommand(action, DEFAULT_MODE_REQUEST_USER_INPUT_FEATURE_KEY, env, validate, invocation);
|
|
565
573
|
} catch (error) {
|
|
566
574
|
return jsonResponse({ error: `default_mode_request_user_input toggle failed: ${error instanceof Error ? error.message : String(error)}` }, 502);
|
|
@@ -972,13 +980,19 @@ async function handleAgentSettingsRoutesImpl(ctx: ManagementContext): Promise<Re
|
|
|
972
980
|
}
|
|
973
981
|
}
|
|
974
982
|
if (url.pathname === "/api/claude-desktop" && req.method === "PUT") {
|
|
975
|
-
let body: { profile?: unknown };
|
|
983
|
+
let body: { profile?: unknown; visibility?: unknown };
|
|
976
984
|
try { body = await readManagementJsonBody(req); } catch (error) { rethrowManagementBodyTooLarge(error); return jsonResponse({ error: "invalid JSON body" }, 400); }
|
|
977
985
|
try {
|
|
978
986
|
const { parseDesktopProfile, preserveDesktopAppliedState, reconcileDesktopProfile, sameProfileContent } = await import("../../claude/desktop-profile");
|
|
979
987
|
const parsed = parseDesktopProfile(body.profile);
|
|
980
988
|
const initial = loadConfig();
|
|
981
989
|
const current = await buildClaudeDesktopState(initial);
|
|
990
|
+
// #7702: absent keeps the stored selection, null clears it (list every model).
|
|
991
|
+
const { parseDesktopModelVisibility, desktopRouteVisible, readDesktopModelVisibility, sameDesktopModelVisibility } = await import("../../claude/desktop-model-visibility");
|
|
992
|
+
const visibility = body.visibility === undefined || body.visibility === null ? body.visibility : parseDesktopModelVisibility(body.visibility);
|
|
993
|
+
if (visibility && !current.models.some(model => model.available && desktopRouteVisible(visibility, model.route))) {
|
|
994
|
+
throw new Error("Claude Desktop needs at least one visible available model");
|
|
995
|
+
}
|
|
982
996
|
const availableRoutes = new Set(current.models.filter(item => item.available).map(item => item.route));
|
|
983
997
|
for (const route of Object.keys(parsed.assignments)) {
|
|
984
998
|
if (!current.profile.assignments[route] && !availableRoutes.has(route)) {
|
|
@@ -1012,10 +1026,15 @@ async function handleAgentSettingsRoutesImpl(ctx: ManagementContext): Promise<Re
|
|
|
1012
1026
|
|| (latest && expectedProfile && !sameProfileContent(latest, expectedProfile))) {
|
|
1013
1027
|
return { changed: false, value: null };
|
|
1014
1028
|
}
|
|
1029
|
+
if (visibility !== undefined && !sameDesktopModelVisibility(
|
|
1030
|
+
readDesktopModelVisibility(persisted.claudeCode), readDesktopModelVisibility(initial.claudeCode),
|
|
1031
|
+
)) return { changed: false, value: null };
|
|
1015
1032
|
persisted.claudeCode = {
|
|
1016
1033
|
...(persisted.claudeCode ?? {}),
|
|
1017
1034
|
desktopProfile: preserveDesktopAppliedState(latest ?? current.profile, rebuilt),
|
|
1018
1035
|
};
|
|
1036
|
+
if (visibility) persisted.claudeCode.desktopModelVisibility = visibility;
|
|
1037
|
+
else if (visibility === null) delete persisted.claudeCode.desktopModelVisibility;
|
|
1019
1038
|
return { changed: true, value: structuredClone(persisted.claudeCode) };
|
|
1020
1039
|
});
|
|
1021
1040
|
if (outcome.status !== "unavailable" && outcome.value !== null) {
|
|
@@ -1028,6 +1047,10 @@ async function handleAgentSettingsRoutesImpl(ctx: ManagementContext): Promise<Re
|
|
|
1028
1047
|
desktopProfile: structuredClone(outcome.value.desktopProfile),
|
|
1029
1048
|
};
|
|
1030
1049
|
}
|
|
1050
|
+
if (visibility !== undefined && config.claudeCode) {
|
|
1051
|
+
if (outcome.value?.desktopModelVisibility) config.claudeCode.desktopModelVisibility = structuredClone(outcome.value.desktopModelVisibility);
|
|
1052
|
+
else delete config.claudeCode.desktopModelVisibility;
|
|
1053
|
+
}
|
|
1031
1054
|
}
|
|
1032
1055
|
return outcome;
|
|
1033
1056
|
});
|
|
@@ -1383,6 +1406,8 @@ async function handleAgentSettingsRoutesImpl(ctx: ManagementContext): Promise<Re
|
|
|
1383
1406
|
savedFingerprint,
|
|
1384
1407
|
onDiskFingerprint: observed.fingerprint ?? null,
|
|
1385
1408
|
configPath: observed.selectedProfilePath,
|
|
1409
|
+
// The list Desktop runs now (#7702), so the dashboard can count and diff against it.
|
|
1410
|
+
appliedModels: gatewayApplied ? (await import("../../claude/desktop-model-visibility")).readAppliedDesktopModels(observed.selectedProfilePath) : null,
|
|
1386
1411
|
stale,
|
|
1387
1412
|
// Tri-state by ID match, independent of profile health: null =
|
|
1388
1413
|
// undeterminable (no/unreadable metadata or no appliedId); a readable
|
|
@@ -82,6 +82,7 @@ export async function handleCodexAgentRoleRoutes(ctx: ManagementContext): Promis
|
|
|
82
82
|
...(typeof body?.model === "string" ? { sizingModel: body.model } : {}),
|
|
83
83
|
fetchAllModels: deps.fetchAllModels ?? fetchAllModels,
|
|
84
84
|
...(deps.completeCodexRoleSizing ? { completeRoleSizing: deps.completeCodexRoleSizing } : {}),
|
|
85
|
+
...(deps.loadCodexRoleCapability ? { loadCapability: deps.loadCodexRoleCapability } : {}),
|
|
85
86
|
}), 200, req, config);
|
|
86
87
|
} catch (error) {
|
|
87
88
|
if (error instanceof NoSizingModelError) {
|
|
@@ -9,6 +9,8 @@ import { join } from "node:path";
|
|
|
9
9
|
import type { OcxConfig } from "../../types";
|
|
10
10
|
import type { CatalogModel } from "../../codex/catalog";
|
|
11
11
|
import type { RoleModelCandidate } from "../../codex/role-auto-assign";
|
|
12
|
+
import type { LoadCapability } from "../../codex/role-capability";
|
|
13
|
+
import type { SizingDomain } from "../../codex/role-sizing";
|
|
12
14
|
|
|
13
15
|
export interface RoleSizingCall {
|
|
14
16
|
readonly model: string;
|
|
@@ -118,11 +120,13 @@ export async function proposeCodexRoleModels(options: {
|
|
|
118
120
|
sizingModel?: string;
|
|
119
121
|
fetchAllModels: (config: OcxConfig) => Promise<CatalogModel[]>;
|
|
120
122
|
completeRoleSizing?: CompleteRoleSizing;
|
|
123
|
+
loadCapability?: LoadCapability;
|
|
121
124
|
}) {
|
|
122
|
-
const [roles, sizing, assign, { readConfiguredDefaultModel }] = await Promise.all([
|
|
125
|
+
const [roles, sizing, assign, capability, { readConfiguredDefaultModel }] = await Promise.all([
|
|
123
126
|
import("../../codex/agent-role-models"),
|
|
124
127
|
import("../../codex/role-sizing"),
|
|
125
128
|
import("../../codex/role-auto-assign"),
|
|
129
|
+
import("../../codex/role-capability"),
|
|
126
130
|
import("../../codex/catalog/parsing"),
|
|
127
131
|
]);
|
|
128
132
|
const sizingModel = resolveSizingModel(options.sizingModel, readConfiguredDefaultModel);
|
|
@@ -159,15 +163,55 @@ export async function proposeCodexRoleModels(options: {
|
|
|
159
163
|
}
|
|
160
164
|
}
|
|
161
165
|
|
|
162
|
-
const
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
+
const candidates = await roleModelCandidates(options.config, await options.fetchAllModels(options.config));
|
|
167
|
+
const classified = assign.classifyRoleModelCandidates(candidates, options.config.codexRoleTiers);
|
|
168
|
+
// Measured capability is a better tier signal than price, and its absence is not an error: a
|
|
169
|
+
// failed read leaves every role on price rank and says so.
|
|
170
|
+
const domains = new Set([...outcomes.values()].flatMap(outcome => "sizing" in outcome ? [outcome.sizing.domain] : []));
|
|
171
|
+
let table: import("../../codex/role-capability").CapabilityTable | null = null;
|
|
172
|
+
let capabilityError: string | null = null;
|
|
173
|
+
if (domains.size > 0) {
|
|
174
|
+
try {
|
|
175
|
+
table = await (options.loadCapability ?? capability.loadCapabilityTable)(options.config);
|
|
176
|
+
} catch {
|
|
177
|
+
capabilityError = "the measured capability source could not be read";
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
const classifiedByDomain = new Map<SizingDomain, ReturnType<typeof assign.classifyRoleModelCandidates>>();
|
|
181
|
+
for (const domain of domains) {
|
|
182
|
+
const scores = table?.domains[domain];
|
|
183
|
+
if (!scores) continue;
|
|
184
|
+
const measured = new Map(candidates.flatMap(candidate => {
|
|
185
|
+
const score = scores.get(capability.candidateModelKey(candidate.model));
|
|
186
|
+
return score === undefined ? [] : [[candidate.model, score] as const];
|
|
187
|
+
}));
|
|
188
|
+
classifiedByDomain.set(domain, assign.classifyRoleModelCandidates(candidates, options.config.codexRoleTiers, measured));
|
|
189
|
+
}
|
|
166
190
|
return {
|
|
167
191
|
sizingModel,
|
|
168
192
|
sizingError,
|
|
169
|
-
proposals: assign.buildRoleProposals(roleRows, outcomes, classified),
|
|
193
|
+
proposals: assign.buildRoleProposals(roleRows, outcomes, classified, classifiedByDomain),
|
|
170
194
|
candidates: classified.map(({ model, tier, tierSource, unitPrice }) => ({ model, tier, tierSource, unitPrice })),
|
|
195
|
+
capability: capabilityReport(table?.source ?? null, table, capabilityError, classifiedByDomain),
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** The attribution and per-domain tiers; raw scores only from a source whose terms allow it. */
|
|
200
|
+
function capabilityReport(
|
|
201
|
+
source: import("../../codex/role-capability").CapabilitySource | null,
|
|
202
|
+
table: import("../../codex/role-capability").CapabilityTable | null,
|
|
203
|
+
error: string | null,
|
|
204
|
+
classifiedByDomain: ReadonlyMap<SizingDomain, ReturnType<typeof import("../../codex/role-auto-assign").classifyRoleModelCandidates>>,
|
|
205
|
+
) {
|
|
206
|
+
return {
|
|
207
|
+
name: source?.name ?? null,
|
|
208
|
+
url: source?.url ?? null,
|
|
209
|
+
license: source?.license ?? null,
|
|
210
|
+
publishedAt: table?.publishedAt ?? null,
|
|
211
|
+
error: error ?? table?.fallbackReason ?? null,
|
|
212
|
+
domains: Object.fromEntries([...classifiedByDomain].map(([domain, list]) => [domain,
|
|
213
|
+
list.filter(candidate => candidate.tierSource === "measured")
|
|
214
|
+
.map(({ model, tier, score }) => (source?.redistributable ? { model, tier, score } : { model, tier }))])),
|
|
171
215
|
};
|
|
172
216
|
}
|
|
173
217
|
|
|
@@ -972,11 +972,22 @@ async function handleConfigRoutesImpl(ctx: ManagementContext): Promise<Response
|
|
|
972
972
|
// Resolve the systemd-scope launcher before spawning: the first request
|
|
973
973
|
// would otherwise run up to four sequential five-second probes inside
|
|
974
974
|
// spawnSync on the shared event loop.
|
|
975
|
-
const { resolveSystemdRunAsync } = await import("../../update/worker-launch");
|
|
975
|
+
const { resolveSystemdRunAsync, dashboardRestartRefusal } = await import("../../update/worker-launch");
|
|
976
976
|
const systemdRun = process.platform === "linux" && process.env.INVOCATION_ID
|
|
977
977
|
? await resolveSystemdRunAsync()
|
|
978
978
|
: undefined;
|
|
979
|
-
|
|
979
|
+
const restart = body.restart !== false;
|
|
980
|
+
// Refuse before any package mutation, with or without restart: the update stops the proxy
|
|
981
|
+
// first, so a worker that dies with the service cgroup, or a restart aimed at a unit that
|
|
982
|
+
// does not own this proxy, leaves the dashboard down (#7967).
|
|
983
|
+
// Only an update that would actually run is refused; an unavailable update or a source
|
|
984
|
+
// checkout keeps its own refusal from startUpdateJob.
|
|
985
|
+
if (checked.canUpdate) {
|
|
986
|
+
const { TASK } = await import("../../service/state");
|
|
987
|
+
const refusal = (deps.dashboardRestartRefusal ?? dashboardRestartRefusal)({ systemdRun, unitName: TASK });
|
|
988
|
+
if (refusal) return jsonResponse({ error: refusal, code: "update_restart_unsupervised" }, 409);
|
|
989
|
+
}
|
|
990
|
+
return jsonResponse({ ok: true, job: startUpdateJob(channel, restart, {
|
|
980
991
|
checkForUpdateFn: () => checked,
|
|
981
992
|
spawnWorkerFn: (jobId, runChannel, runRestart) =>
|
|
982
993
|
spawnGuiUpdateWorker(jobId, runChannel, runRestart, { resolveSystemdRun: () => systemdRun }),
|
|
@@ -990,8 +1001,8 @@ async function handleConfigRoutesImpl(ctx: ManagementContext): Promise<Response
|
|
|
990
1001
|
}
|
|
991
1002
|
|
|
992
1003
|
if (url.pathname === "/api/update/status" && req.method === "GET") {
|
|
993
|
-
const {
|
|
994
|
-
const job =
|
|
1004
|
+
const { readUpdateJobForStatus } = await import("../../update/job");
|
|
1005
|
+
const job = readUpdateJobForStatus(url.searchParams.get("jobId"));
|
|
995
1006
|
if (!job) return jsonResponse({ error: "update job not found" }, 404);
|
|
996
1007
|
return jsonResponse({ ok: true, job });
|
|
997
1008
|
}
|
|
@@ -59,6 +59,8 @@ export interface ManagementApiDeps {
|
|
|
59
59
|
/** Read-only process-local aggregate metrics; absent keeps the scrape route unavailable. */
|
|
60
60
|
requestMetrics?: RequestMetricsSnapshotter;
|
|
61
61
|
checkPackageUpdate?: (channel: Channel) => Promise<UpdateCheckResult>;
|
|
62
|
+
/** Test seam for the dashboard restart supervisor check (src/update/worker-launch.ts). */
|
|
63
|
+
dashboardRestartRefusal?: typeof import("../../update/worker-launch").dashboardRestartRefusal;
|
|
62
64
|
remoteWorkspaceHub?: RemoteWorkspaceHubApi;
|
|
63
65
|
remoteWorkspaceSessions?: RemoteWorkspaceSessionsApi;
|
|
64
66
|
/** The listener retains and awaits teardown only after this optional subsystem activates. */
|
|
@@ -91,6 +93,7 @@ export interface ManagementApiDeps {
|
|
|
91
93
|
fetchAllModels?: (config: OcxConfig) => Promise<CatalogModel[]>;
|
|
92
94
|
/** Codex role auto-assign's one sizing model call; route tests answer it without a provider. */
|
|
93
95
|
completeCodexRoleSizing?: import("./codex-role-auto-assign").CompleteRoleSizing;
|
|
96
|
+
loadCodexRoleCapability?: import("../../codex/role-capability").LoadCapability;
|
|
94
97
|
/**
|
|
95
98
|
* Writer seam for the Grok toggle: lets a test place the file in any state
|
|
96
99
|
* between the pre-write recheck and the write itself (the r8 post-inspection
|