@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
|
@@ -169,6 +169,9 @@ type OpenItem = {
|
|
|
169
169
|
/** The gateway sent content_part.done for this item. */
|
|
170
170
|
partDone: boolean;
|
|
171
171
|
text: string;
|
|
172
|
+
/** Exact UTF-8 size and boundary unit, without rescanning the accumulated text. */
|
|
173
|
+
textBytes: number;
|
|
174
|
+
lastCodeUnit: number;
|
|
172
175
|
item: Record<string, unknown>;
|
|
173
176
|
};
|
|
174
177
|
|
|
@@ -219,7 +222,7 @@ export function createResponsesSnapshotBlockRewrite(
|
|
|
219
222
|
const closeOpenItem = (index: number): void => {
|
|
220
223
|
const open = openItems.get(index);
|
|
221
224
|
if (!open) return;
|
|
222
|
-
aggregateOpenTextBytes -=
|
|
225
|
+
aggregateOpenTextBytes -= open.textBytes;
|
|
223
226
|
openItems.delete(index);
|
|
224
227
|
};
|
|
225
228
|
|
|
@@ -313,6 +316,8 @@ export function createResponsesSnapshotBlockRewrite(
|
|
|
313
316
|
textDone: false,
|
|
314
317
|
partDone: false,
|
|
315
318
|
text: "",
|
|
319
|
+
textBytes: 0,
|
|
320
|
+
lastCodeUnit: -1,
|
|
316
321
|
item: event.item,
|
|
317
322
|
});
|
|
318
323
|
}
|
|
@@ -407,12 +412,19 @@ export function createResponsesSnapshotBlockRewrite(
|
|
|
407
412
|
return [changed ? jsonBlock(nextEvent) : block];
|
|
408
413
|
}
|
|
409
414
|
if (open && (itemId === undefined || itemId === open.itemId)) {
|
|
410
|
-
|
|
415
|
+
let deltaBytes = Buffer.byteLength(event.delta, "utf8");
|
|
416
|
+
const first = event.delta.charCodeAt(0);
|
|
417
|
+
// Joining two isolated surrogate halves replaces two 3-byte replacements with 4 bytes.
|
|
418
|
+
if (open.lastCodeUnit >= 0xd800 && open.lastCodeUnit <= 0xdbff && first >= 0xdc00 && first <= 0xdfff) {
|
|
419
|
+
deltaBytes -= 2;
|
|
420
|
+
}
|
|
421
|
+
if (event.delta.length > 0) open.lastCodeUnit = event.delta.charCodeAt(event.delta.length - 1);
|
|
411
422
|
open.text += event.delta;
|
|
423
|
+
open.textBytes += deltaBytes;
|
|
412
424
|
aggregateOpenTextBytes += deltaBytes;
|
|
413
425
|
// Unbounded text accumulation is a retention hole (#893 review):
|
|
414
426
|
// overshoot per-item or aggregate caps and the stream goes fail-closed.
|
|
415
|
-
if (
|
|
427
|
+
if (open.textBytes > MAX_COMPLETED_OUTPUT_ITEM_SOURCE_BYTES
|
|
416
428
|
|| aggregateOpenTextBytes > MAX_OPEN_ITEM_AGGREGATE_TEXT_BYTES) {
|
|
417
429
|
taintAndRelease();
|
|
418
430
|
}
|
|
@@ -437,9 +449,11 @@ export function createResponsesSnapshotBlockRewrite(
|
|
|
437
449
|
if (typeof event.text === "string") {
|
|
438
450
|
// Replacement must keep the aggregate honest and bounded, the
|
|
439
451
|
// same as delta accumulation (#893 review).
|
|
440
|
-
const previousBytes =
|
|
452
|
+
const previousBytes = open.textBytes;
|
|
441
453
|
const nextBytes = Buffer.byteLength(event.text, "utf8");
|
|
442
454
|
open.text = event.text;
|
|
455
|
+
open.textBytes = nextBytes;
|
|
456
|
+
open.lastCodeUnit = event.text.charCodeAt(event.text.length - 1);
|
|
443
457
|
aggregateOpenTextBytes += nextBytes - previousBytes;
|
|
444
458
|
if (nextBytes > MAX_COMPLETED_OUTPUT_ITEM_SOURCE_BYTES
|
|
445
459
|
|| aggregateOpenTextBytes > MAX_OPEN_ITEM_AGGREGATE_TEXT_BYTES) {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { UNDECLARED_TOOL_CALL_ERROR_CODE } from "../lib/errors";
|
|
2
|
+
import { hasItemProvenance, isHistoricalItem } from "../responses/item-provenance";
|
|
2
3
|
import {
|
|
3
4
|
collectAmbiguousDottedAliases,
|
|
4
5
|
dottedAliasIsUnambiguous,
|
|
@@ -136,6 +137,9 @@ export function currentTurnWireToolCatalogBody(
|
|
|
136
137
|
replayPrefixLength: number | undefined,
|
|
137
138
|
): unknown {
|
|
138
139
|
if (!isPlainObject(body) || !Array.isArray(body.input)) return body;
|
|
140
|
+
if (body.input.some(hasItemProvenance)) {
|
|
141
|
+
return { ...body, input: body.input.filter(item => !isHistoricalItem(item)) };
|
|
142
|
+
}
|
|
139
143
|
if (typeof replayPrefixLength !== "number" || !Number.isFinite(replayPrefixLength)) return body;
|
|
140
144
|
const start = Math.min(body.input.length, Math.max(0, Math.trunc(replayPrefixLength)));
|
|
141
145
|
if (start === 0) return body;
|
package/src/server/search.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/alpha/search relay.
|
|
3
5
|
*
|
|
@@ -159,6 +161,7 @@ export async function handleSearch(
|
|
|
159
161
|
? `${upstream.providerName}-${accountNamespace}`
|
|
160
162
|
: formatCodexProviderForLog(upstream.providerName, codexLogAccountId(upstream.authContext), config);
|
|
161
163
|
} catch (err) {
|
|
164
|
+
if (err instanceof CodexInstallationIdUnavailableError) return formatErrorResponse(503, "server_busy", err.message);
|
|
162
165
|
if (err instanceof CodexAccountCooldownError) {
|
|
163
166
|
return cooldownErrorResponse(err, Date.now(), accountNamespace);
|
|
164
167
|
}
|
|
@@ -194,9 +197,9 @@ export async function handleSearch(
|
|
|
194
197
|
}
|
|
195
198
|
}
|
|
196
199
|
|
|
197
|
-
const headers
|
|
198
|
-
|
|
199
|
-
|
|
200
|
+
const headers = mergeCodexSelectedHeaders(
|
|
201
|
+
{ "content-type": "application/json", ...upstream.provider.headers }, upstream.headers,
|
|
202
|
+
);
|
|
200
203
|
const url = `${upstream.provider.baseUrl}/alpha/search`;
|
|
201
204
|
const timeoutMs = config.search?.timeoutMs ?? SEARCH_UPSTREAM_TIMEOUT_MS;
|
|
202
205
|
const linkedSignal = signalWithTimeout(timeoutMs, req.signal);
|
|
@@ -207,7 +210,9 @@ export async function handleSearch(
|
|
|
207
210
|
upstreamResponse = await fetch(url, {
|
|
208
211
|
method: "POST",
|
|
209
212
|
headers,
|
|
210
|
-
body: JSON.stringify(
|
|
213
|
+
body: JSON.stringify(isolateCodexPoolClientMetadata(
|
|
214
|
+
relayBody, upstream.authContext.kind === "pool" ? upstream.authContext.chatgptAccountId : undefined,
|
|
215
|
+
)),
|
|
211
216
|
signal: linkedSignal.signal,
|
|
212
217
|
// Credential-bearing: do not follow a cross-origin 3xx. Bun strips `Authorization`
|
|
213
218
|
// across origins but forwards nonstandard headers such as `chatgpt-account-id`,
|
|
@@ -232,6 +237,10 @@ export async function handleSearch(
|
|
|
232
237
|
if (contentType) relayHeaders["content-type"] = contentType;
|
|
233
238
|
return new Response(observed.bytes, { status: upstreamResponse.status, headers: relayHeaders });
|
|
234
239
|
} catch (err) {
|
|
240
|
+
if (err instanceof CodexInstallationIdUnavailableError) {
|
|
241
|
+
upstream.releaseProbeLease?.();
|
|
242
|
+
return formatErrorResponse(503, "server_busy", err.message);
|
|
243
|
+
}
|
|
235
244
|
if (req.signal.aborted) {
|
|
236
245
|
return formatErrorResponse(499, "client_closed_request", "search request canceled by client");
|
|
237
246
|
}
|
|
@@ -27,6 +27,7 @@ import {
|
|
|
27
27
|
type WorkflowLane,
|
|
28
28
|
type WorkflowSpendDenialDetail,
|
|
29
29
|
} from "../lib/workflow-budget";
|
|
30
|
+
import { currentWorkflowBudgetPolicy } from "../lib/workflow-budget-config";
|
|
30
31
|
|
|
31
32
|
/**
|
|
32
33
|
* What a caller needs to hand over for the refusal to become a row on `/api/logs`.
|
|
@@ -142,7 +143,7 @@ export function admitHttpWorkflowTurn(headers: Headers): WorkflowDecision | unde
|
|
|
142
143
|
const lane: WorkflowLane = rootId !== undefined && threadId !== undefined && threadId !== rootId
|
|
143
144
|
? "worker"
|
|
144
145
|
: "interactive";
|
|
145
|
-
return admitWorkflowTurn(rootId, lane,
|
|
146
|
+
return admitWorkflowTurn(rootId, lane, currentWorkflowBudgetPolicy(), threadId);
|
|
146
147
|
}
|
|
147
148
|
|
|
148
149
|
/**
|
package/src/server/ws-bridge.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isolateCodexPoolAccountHeaders } from "../codex/forward-transport-headers";
|
|
1
2
|
import type { NativeResponseControl } from "./responses/native-response-control";
|
|
2
3
|
import type { ServerWebSocket } from "bun";
|
|
3
4
|
import { responsesJsonEventSequence } from "./responses-json-events";
|
|
@@ -122,16 +123,18 @@ export class WsSendDroppedError extends Error {
|
|
|
122
123
|
|
|
123
124
|
export function selectForwardHeaders(
|
|
124
125
|
headers: Headers,
|
|
125
|
-
codexOverride?: { accessToken: string; chatgptAccountId: string },
|
|
126
|
+
codexOverride?: { accessToken: string; chatgptAccountId: string; kind?: "pool" | "main-pool" },
|
|
126
127
|
): Headers {
|
|
127
128
|
const selected = new Headers();
|
|
128
129
|
for (const name of FORWARD_HEADERS) {
|
|
129
130
|
const value = headers.get(name);
|
|
130
|
-
if (value) selected.set(name, value);
|
|
131
|
+
if (value !== null) selected.set(name, value);
|
|
131
132
|
}
|
|
132
133
|
if (codexOverride) {
|
|
133
134
|
selected.set("authorization", `Bearer ${codexOverride.accessToken}`);
|
|
134
135
|
selected.set("chatgpt-account-id", codexOverride.chatgptAccountId);
|
|
136
|
+
if (codexOverride.kind !== "main-pool") isolateCodexPoolAccountHeaders(selected, codexOverride.chatgptAccountId);
|
|
137
|
+
else selected.delete("x-oai-attestation");
|
|
135
138
|
} else {
|
|
136
139
|
// Kept for the WS turn pipeline, which drops it again everywhere except first-party Direct.
|
|
137
140
|
const assertion = headers.get(AGENT_ASSERTION_HEADER);
|
|
@@ -12,9 +12,10 @@ import {
|
|
|
12
12
|
rmdirSync,
|
|
13
13
|
unlinkSync,
|
|
14
14
|
writeFileSync,
|
|
15
|
-
type
|
|
15
|
+
type BigIntStats,
|
|
16
16
|
} from "node:fs";
|
|
17
17
|
import { basename, dirname, join } from "node:path";
|
|
18
|
+
import { statTimeMs } from "../lib/file-identity";
|
|
18
19
|
|
|
19
20
|
const SERVICE_STATE_LOCK_WAIT_MS = 2_000;
|
|
20
21
|
const SERVICE_STATE_LOCK_POLL_MS = 20;
|
|
@@ -32,8 +33,8 @@ interface ServiceStateLockRecord {
|
|
|
32
33
|
interface ServiceStateLockSnapshot {
|
|
33
34
|
readonly record: ServiceStateLockRecord;
|
|
34
35
|
readonly ownerPath: string;
|
|
35
|
-
readonly lockIdentity: Pick<
|
|
36
|
-
readonly ownerIdentity: Pick<
|
|
36
|
+
readonly lockIdentity: Pick<BigIntStats, "dev" | "ino">;
|
|
37
|
+
readonly ownerIdentity: Pick<BigIntStats, "dev" | "ino" | "size">;
|
|
37
38
|
readonly mtimeMs: number;
|
|
38
39
|
}
|
|
39
40
|
|
|
@@ -72,8 +73,8 @@ function lockOwnerProcessAlive(pid: number): boolean {
|
|
|
72
73
|
}
|
|
73
74
|
|
|
74
75
|
function sameIdentity(
|
|
75
|
-
left: Pick<
|
|
76
|
-
right: Pick<
|
|
76
|
+
left: Pick<BigIntStats, "dev" | "ino">,
|
|
77
|
+
right: Pick<BigIntStats, "dev" | "ino">,
|
|
77
78
|
): boolean {
|
|
78
79
|
return left.dev === right.dev && left.ino === right.ino;
|
|
79
80
|
}
|
|
@@ -90,10 +91,10 @@ function parseOwnerFileName(name: string): { pid: number; pathToken: string } |
|
|
|
90
91
|
}
|
|
91
92
|
|
|
92
93
|
function readLockSnapshot(lockPath: string): ServiceStateLockSnapshot | null {
|
|
93
|
-
let lockIdentity:
|
|
94
|
+
let lockIdentity: BigIntStats;
|
|
94
95
|
let entries: string[];
|
|
95
96
|
try {
|
|
96
|
-
lockIdentity = lstatSync(lockPath);
|
|
97
|
+
lockIdentity = lstatSync(lockPath, { bigint: true });
|
|
97
98
|
if (!lockIdentity.isDirectory()) return null;
|
|
98
99
|
entries = readdirSync(lockPath);
|
|
99
100
|
} catch {
|
|
@@ -102,7 +103,7 @@ function readLockSnapshot(lockPath: string): ServiceStateLockSnapshot | null {
|
|
|
102
103
|
if (entries.length !== 1 || !parseOwnerFileName(entries[0]!)) return null;
|
|
103
104
|
const ownerPath = join(lockPath, entries[0]!);
|
|
104
105
|
try {
|
|
105
|
-
const ownerIdentity = lstatSync(ownerPath);
|
|
106
|
+
const ownerIdentity = lstatSync(ownerPath, { bigint: true });
|
|
106
107
|
if (!ownerIdentity.isFile() || ownerIdentity.size > 4096) return null;
|
|
107
108
|
const value = JSON.parse(readFileSync(ownerPath, "utf8")) as Partial<ServiceStateLockRecord>;
|
|
108
109
|
if (value.version !== 1 || !Number.isSafeInteger(value.pid) || (value.pid ?? 0) <= 0
|
|
@@ -111,12 +112,12 @@ function readLockSnapshot(lockPath: string): ServiceStateLockSnapshot | null {
|
|
|
111
112
|
|| typeof value.createdAt !== "number" || !Number.isFinite(value.createdAt)) return null;
|
|
112
113
|
const record = value as ServiceStateLockRecord;
|
|
113
114
|
if (entries[0] !== ownerFileName(record)) return null;
|
|
114
|
-
const currentLock = lstatSync(lockPath);
|
|
115
|
-
const currentOwner = lstatSync(ownerPath);
|
|
115
|
+
const currentLock = lstatSync(lockPath, { bigint: true });
|
|
116
|
+
const currentOwner = lstatSync(ownerPath, { bigint: true });
|
|
116
117
|
if (!currentLock.isDirectory() || !sameIdentity(lockIdentity, currentLock)
|
|
117
118
|
|| !currentOwner.isFile() || !sameIdentity(ownerIdentity, currentOwner)
|
|
118
119
|
|| currentOwner.size !== ownerIdentity.size) return null;
|
|
119
|
-
return { record, ownerPath, lockIdentity, ownerIdentity, mtimeMs: ownerIdentity.
|
|
120
|
+
return { record, ownerPath, lockIdentity, ownerIdentity, mtimeMs: statTimeMs(ownerIdentity.mtimeNs) };
|
|
120
121
|
} catch {
|
|
121
122
|
return null;
|
|
122
123
|
}
|
|
@@ -76,7 +76,7 @@ export type ServiceManagerInstallation =
|
|
|
76
76
|
|
|
77
77
|
/** Injected so a test can observe the EXACT argv production emits. */
|
|
78
78
|
export interface ProbeRunner {
|
|
79
|
-
(file: string, args: readonly string[]): {
|
|
79
|
+
(file: string, args: readonly string[], options?: { readonly input?: string }): {
|
|
80
80
|
status: number | null;
|
|
81
81
|
stdout: string;
|
|
82
82
|
stderr: string;
|
|
@@ -152,9 +152,10 @@ export function createWindowsTaskListingCache(): WindowsTaskListingCache {
|
|
|
152
152
|
};
|
|
153
153
|
}
|
|
154
154
|
|
|
155
|
-
export const defaultProbeRunner: ProbeRunner = (file, args) => {
|
|
155
|
+
export const defaultProbeRunner: ProbeRunner = (file, args, options) => {
|
|
156
156
|
const result = spawnSync(file, [...args], {
|
|
157
157
|
encoding: "utf8",
|
|
158
|
+
input: options?.input,
|
|
158
159
|
windowsHide: true,
|
|
159
160
|
timeout: SERVICE_PROBE_TIMEOUT_MS,
|
|
160
161
|
});
|
|
@@ -220,6 +221,12 @@ const LAUNCHCTL_NO_SUCH_SERVICE = 113;
|
|
|
220
221
|
* headless Mac — no GUI domain, and no installation either.
|
|
221
222
|
*/
|
|
222
223
|
const LAUNCHCTL_NO_SUCH_DOMAIN = 112;
|
|
224
|
+
/**
|
|
225
|
+
* Observed on a headless Mac (#7697), but unsupported action is not proof that
|
|
226
|
+
* no GUI login exists. Only independent session evidence can qualify GUI 125;
|
|
227
|
+
* a user-domain 125 remains unknown because its services are independent.
|
|
228
|
+
*/
|
|
229
|
+
const LAUNCHCTL_DOMAIN_UNSUPPORTED_ACTION = 125;
|
|
223
230
|
|
|
224
231
|
/**
|
|
225
232
|
* Residue on disk, distinguished from a path that could not be read.
|
|
@@ -338,6 +345,36 @@ function inspectSystemdOffline(home: string): ServiceManagerInstallation {
|
|
|
338
345
|
};
|
|
339
346
|
}
|
|
340
347
|
|
|
348
|
+
/**
|
|
349
|
+
* TN2083: /dev/console identifies only the foreground user; switched-out GUI
|
|
350
|
+
* sessions survive. XNU's IOService::updateConsoleUsers publishes the complete
|
|
351
|
+
* supplied array on the registry root, with UID separate from OnConsole:
|
|
352
|
+
* https://github.com/apple-oss-distributions/xnu/blob/main/iokit/Kernel/IOService.cpp
|
|
353
|
+
* https://github.com/apple-oss-distributions/xnu/blob/main/iokit/IOKit/IOKitKeysPrivate.h
|
|
354
|
+
* Both commands inherit the runner's 2s bound. Missing or malformed evidence
|
|
355
|
+
* cannot prove absence; do not cache session evidence across admissions.
|
|
356
|
+
*/
|
|
357
|
+
function launchdGuiSessionAbsent(run: ProbeRunner, uid: number): boolean {
|
|
358
|
+
try {
|
|
359
|
+
const registry = run("/usr/sbin/ioreg", ["-a", "-r", "-d", "1", "-n", "Root"]);
|
|
360
|
+
if (registry.spawnFailed || registry.timedOut || registry.status !== 0 || !registry.stdout.trim()) return false;
|
|
361
|
+
const converted = run("/usr/bin/plutil", ["-extract", "0.IOConsoleUsers", "json", "-o", "-", "-"], {
|
|
362
|
+
input: registry.stdout,
|
|
363
|
+
});
|
|
364
|
+
if (converted.spawnFailed || converted.timedOut || converted.status !== 0) return false;
|
|
365
|
+
const sessions: unknown = JSON.parse(converted.stdout);
|
|
366
|
+
if (!Array.isArray(sessions)) return false;
|
|
367
|
+
return sessions.every(session => {
|
|
368
|
+
if (!session || typeof session !== "object" || Array.isArray(session)) return false;
|
|
369
|
+
const sessionUid: unknown = session.kCGSSessionUserIDKey;
|
|
370
|
+
return typeof sessionUid === "number" && Number.isInteger(sessionUid)
|
|
371
|
+
&& sessionUid >= 0 && sessionUid < 0xffff_ffff && sessionUid !== uid;
|
|
372
|
+
});
|
|
373
|
+
} catch {
|
|
374
|
+
return false;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
341
378
|
function inspectLaunchd(deps: Required<Pick<ProbeDeps, "run" | "uid" | "home">>): ServiceManagerInstallation {
|
|
342
379
|
const definitionPath = join(deps.home, "Library", "LaunchAgents", `${LABEL}.plist`);
|
|
343
380
|
|
|
@@ -357,6 +394,16 @@ function inspectLaunchd(deps: Required<Pick<ProbeDeps, "run" | "uid" | "home">>)
|
|
|
357
394
|
if (printed.status === 0) { registration = "present"; break; }
|
|
358
395
|
if (printed.status === LAUNCHCTL_NO_SUCH_SERVICE) continue;
|
|
359
396
|
if (printed.status === LAUNCHCTL_NO_SUCH_DOMAIN) { unreachableDomains += 1; continue; }
|
|
397
|
+
/*
|
|
398
|
+
* Unsupported action alone says nothing about loaded jobs. Qualify GUI
|
|
399
|
+
* 125 only with independent evidence excluding this UID's GUI sessions;
|
|
400
|
+
* the separate user-domain query and plist checks remain mandatory.
|
|
401
|
+
*/
|
|
402
|
+
if (printed.status === LAUNCHCTL_DOMAIN_UNSUPPORTED_ACTION && domain.startsWith("gui/")) {
|
|
403
|
+
if (!launchdGuiSessionAbsent(deps.run, deps.uid)) return unknown("GUI login session absence could not be established");
|
|
404
|
+
unreachableDomains += 1;
|
|
405
|
+
continue;
|
|
406
|
+
}
|
|
360
407
|
return unknown(`launchctl print exited ${String(printed.status)}: ${printed.stderr.trim()}`);
|
|
361
408
|
}
|
|
362
409
|
|
|
@@ -368,12 +415,10 @@ function inspectLaunchd(deps: Required<Pick<ProbeDeps, "run" | "uid" | "home">>)
|
|
|
368
415
|
return unknown("launchd has a job loaded but its plist is missing");
|
|
369
416
|
}
|
|
370
417
|
/*
|
|
371
|
-
* Nothing staged, and every domain either answered
|
|
372
|
-
* not exist
|
|
373
|
-
*
|
|
374
|
-
*
|
|
375
|
-
* instead would refuse every write on a fresh headless Mac, which has no
|
|
376
|
-
* GUI domain and no installation either.
|
|
418
|
+
* Nothing staged, and every domain either answered service-scoped 113,
|
|
419
|
+
* did not exist (112), or returned GUI 125 corroborated by independent
|
|
420
|
+
* evidence of no GUI session for this UID. A user-domain 113 alone cannot
|
|
421
|
+
* exclude a job in the GUI domain's separate service set.
|
|
377
422
|
*/
|
|
378
423
|
void unreachableDomains;
|
|
379
424
|
return { kind: "absent" };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { AdmissionModelScope } from "../server/admission-model-scope";
|
|
2
|
+
import type { OcxFallbackConfig } from "./fallback";
|
|
3
|
+
|
|
4
|
+
/** Credential-free, immutable decision inputs captured for an internal child. */
|
|
5
|
+
export interface CapturedAdmissionPolicy {
|
|
6
|
+
readonly modelScope: AdmissionModelScope;
|
|
7
|
+
readonly allowMeteredComboTargets: boolean;
|
|
8
|
+
readonly meteredRequiresComboOptIn: boolean;
|
|
9
|
+
readonly fallbackPolicies: readonly {
|
|
10
|
+
readonly config: { readonly fallback?: OcxFallbackConfig };
|
|
11
|
+
readonly deviceIds: readonly string[];
|
|
12
|
+
}[];
|
|
13
|
+
}
|
package/src/types/config.ts
CHANGED
|
@@ -264,6 +264,18 @@ export interface OcxClaudeCodeConfig {
|
|
|
264
264
|
* Routing-sidecar alias decoding is unchanged — only the Desktop model list writer.
|
|
265
265
|
*/
|
|
266
266
|
desktopNativeModels?: boolean;
|
|
267
|
+
/**
|
|
268
|
+
* Which models the Claude Desktop 3P list carries (src/claude/desktop-model-visibility.ts).
|
|
269
|
+
* Unset lists every available model. Independent of desktopProfile tiers and of
|
|
270
|
+
* provider-wide disabledModels; other clients are unaffected.
|
|
271
|
+
*/
|
|
272
|
+
desktopModelVisibility?: OcxClaudeDesktopModelVisibility;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** `include`: only `routes` (new models hidden). `exclude`: all but `routes` (new models listed). */
|
|
276
|
+
export interface OcxClaudeDesktopModelVisibility {
|
|
277
|
+
mode: "include" | "exclude";
|
|
278
|
+
routes: string[];
|
|
267
279
|
}
|
|
268
280
|
|
|
269
281
|
export type OcxClaudeDesktopFamily = "opus" | "fable" | "sonnet" | "haiku";
|
|
@@ -571,6 +583,8 @@ export interface OcxConfig {
|
|
|
571
583
|
emptyCompletionRetry?: boolean;
|
|
572
584
|
/** Suppress allowlisted client-facing Codex transport hints; provider enforcement is unchanged. */
|
|
573
585
|
dropCodexSafetyBuffering?: boolean;
|
|
586
|
+
/** Opt in to completing truncated plain-text translated Responses turns; default off. */
|
|
587
|
+
completeOnMaxOutputTokens?: boolean;
|
|
574
588
|
/**
|
|
575
589
|
* Whether a login may open a browser on the machine running the proxy.
|
|
576
590
|
*
|
|
@@ -702,6 +716,8 @@ export interface OcxConfig {
|
|
|
702
716
|
* See {@link OcxOpencodeClientExportConfig}.
|
|
703
717
|
*/
|
|
704
718
|
opencodeClientExport?: OcxOpencodeClientExportConfig;
|
|
719
|
+
/** Opt-in dialect for the managed Pi-based omo block; omitted keeps `openai-completions` (#7431). */
|
|
720
|
+
omoClientExport?: { api?: "openai-completions" | "openai-responses" };
|
|
705
721
|
/** Aside account-backed profile synchronization; individual overrides survive bulk refresh. */
|
|
706
722
|
asideProfileSync?: {
|
|
707
723
|
allProfiles?: boolean;
|
|
@@ -754,6 +770,11 @@ export interface OcxConfig {
|
|
|
754
770
|
* classification. Models no list names and no price covers are never proposed.
|
|
755
771
|
*/
|
|
756
772
|
codexRoleTiers?: { fast?: string[]; standard?: string[]; frontier?: string[] };
|
|
773
|
+
/**
|
|
774
|
+
* Measured-capability source for Codex role auto-assign. With an Artificial Analysis API key
|
|
775
|
+
* (a literal, ${ENV} or keychain reference) its indexes inform measured tiers.
|
|
776
|
+
*/
|
|
777
|
+
codexRoleCapability?: { artificialAnalysis?: { apiKey?: string } };
|
|
757
778
|
/**
|
|
758
779
|
* TTL (ms) for cached sub-agent model availability probes. Default 60_000.
|
|
759
780
|
*/
|
|
@@ -859,6 +880,8 @@ export interface OcxConfig {
|
|
|
859
880
|
reasoningRetention?: { enabled?: boolean; maxContextPercent?: number; maxTokens?: number };
|
|
860
881
|
/** Canonical ChatGPT reasoning replay allowances; both default off. */
|
|
861
882
|
nativeReasoningRetention?: { modelSwitch?: boolean; accountSwitch?: boolean };
|
|
883
|
+
/** Per-root fan-out ceilings (src/lib/workflow-budget.ts); omitted fields keep 8 / 256 / 64. */
|
|
884
|
+
workflowBudget?: { maxConcurrentChildren?: number; maxPhysicalSends?: number; maxDistinctChildren?: number };
|
|
862
885
|
/** Explicit opt-in; resumes Observe only using an existing trusted certificate and endpoints. */
|
|
863
886
|
desktopCompatibility?: { startOnProxyStart: boolean };
|
|
864
887
|
/**
|
|
@@ -889,6 +912,8 @@ export interface OcxConfig {
|
|
|
889
912
|
* the bare row plus every generated selector row and omit that model family from raw discovery.
|
|
890
913
|
*/
|
|
891
914
|
disabledModels?: string[];
|
|
915
|
+
/** Omit explicitly disabled native catalog rows, retaining their validated inheritance template. Default: false; direct routing is unchanged. */
|
|
916
|
+
omitDisabledNativeModels?: boolean;
|
|
892
917
|
/** 사용자가 대시보드에서 직접 추가한 커스텀 모델 목록. */
|
|
893
918
|
customModels?: OcxCustomModel[];
|
|
894
919
|
/**
|
package/src/types/provider.ts
CHANGED
|
@@ -434,6 +434,14 @@ export interface OcxProviderConfig {
|
|
|
434
434
|
fastEnabled?: boolean;
|
|
435
435
|
/** Exact upstream model ids that override the provider-level service-tier capability. */
|
|
436
436
|
modelSupportsServiceTier?: Record<string, boolean>;
|
|
437
|
+
/**
|
|
438
|
+
* Whether to promote Codex Desktop's `additional_tools` input items into top-level `tools`
|
|
439
|
+
* and strip the wrapper from `input`. Enabled automatically for OpenCode Go and xAI
|
|
440
|
+
* (`api.x.ai` and `cli-chat-proxy.grok.com`) except on forward-auth routes, which need an
|
|
441
|
+
* explicit `true`; other strict gateways that return HTTP 422 for unknown item types in
|
|
442
|
+
* `input` can opt in here.
|
|
443
|
+
*/
|
|
444
|
+
promoteAdditionalTools?: boolean;
|
|
437
445
|
/**
|
|
438
446
|
* Responses upstream whose native contract accepts plaintext reasoning replay
|
|
439
447
|
* (DeepSeek documents reasoning items with plaintext content). When set, the
|
|
@@ -1011,6 +1019,8 @@ export interface OcxProviderConfig {
|
|
|
1011
1019
|
* keeps its slot in the conversation.
|
|
1012
1020
|
*/
|
|
1013
1021
|
foldDeveloperRoleToSystem?: boolean;
|
|
1022
|
+
/** Merge text-only Chat instruction messages into one leading system message. LM Studio seeds true. */
|
|
1023
|
+
singleLeadingSystemMessage?: boolean;
|
|
1014
1024
|
/**
|
|
1015
1025
|
* Opt-in: forward `prompt_cache_key` to the upstream `/chat/completions` body.
|
|
1016
1026
|
* OpenAI-specific extension; strict backends (Groq, Cerebras, etc.) reject unknown
|
package/src/types/request.ts
CHANGED
|
@@ -573,6 +573,13 @@ export interface OcxUsage {
|
|
|
573
573
|
cacheCreation1hInputTokens?: number;
|
|
574
574
|
reasoningOutputTokens?: number;
|
|
575
575
|
estimated?: boolean;
|
|
576
|
+
/**
|
|
577
|
+
* The adapter read these counts off the upstream's own usage frame. Only an adapter whose
|
|
578
|
+
* provider is estimated by default (usageForFinalLog) sets it, and a merge keeps it only when
|
|
579
|
+
* every leg had it. A figure taken off a bridged wire or guessed never carries it, so the
|
|
580
|
+
* provider default still marks those as estimated.
|
|
581
|
+
*/
|
|
582
|
+
upstreamReported?: true;
|
|
576
583
|
/**
|
|
577
584
|
* The raw upstream usage object for Responses-shaped upstreams (openai/codex#41980 parity):
|
|
578
585
|
* codex-rs preserves the complete `response.usage` object through its own pipeline, so fields
|
package/src/types.ts
CHANGED
package/src/update/job.ts
CHANGED
|
@@ -527,6 +527,26 @@ export function staleActiveUpdateJobReason(
|
|
|
527
527
|
return null;
|
|
528
528
|
}
|
|
529
529
|
|
|
530
|
+
/**
|
|
531
|
+
* Status view of an active record whose worker is gone (#7967). A worker killed with its service
|
|
532
|
+
* cgroup never writes a terminal state, so the persisted record stays `running`. The view reports
|
|
533
|
+
* it as `failed` with the reason so the dashboard stops waiting, without writing: the persisted
|
|
534
|
+
* record is settled only by the next run's existing stale recovery, which holds the start path,
|
|
535
|
+
* so a status poll can never overwrite a job another process started meanwhile.
|
|
536
|
+
*/
|
|
537
|
+
export function readUpdateJobForStatus(
|
|
538
|
+
jobId?: string | null,
|
|
539
|
+
now = Date.now(),
|
|
540
|
+
isAlive: (pid: number) => boolean = isProcessAlive,
|
|
541
|
+
): UpdateJobState | null {
|
|
542
|
+
const job = readUpdateJob(jobId);
|
|
543
|
+
if (!job) return null;
|
|
544
|
+
const reason = staleActiveUpdateJobReason(job, now, isAlive);
|
|
545
|
+
if (!reason) return job;
|
|
546
|
+
const line = `Update worker stopped before finishing: ${reason}.`;
|
|
547
|
+
return { ...job, status: "failed", error: line, exitCode: null, log: [...job.log, line] };
|
|
548
|
+
}
|
|
549
|
+
|
|
530
550
|
/**
|
|
531
551
|
* Spawn the GUI update worker without inheriting the proxy's LISTEN socket.
|
|
532
552
|
*
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { probeSpawn, probeSpawnSync } from "./mutation-guard.mjs";
|
|
2
|
-
import { accessSync, constants, realpathSync, statSync } from "node:fs";
|
|
2
|
+
import { accessSync, constants, readFileSync, realpathSync, statSync } from "node:fs";
|
|
3
3
|
import { dirname, isAbsolute } from "node:path";
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -171,6 +171,76 @@ export function resetSystemdRunProbeForTests(): void {
|
|
|
171
171
|
systemdRunProbePending = undefined;
|
|
172
172
|
}
|
|
173
173
|
|
|
174
|
+
export interface DashboardRestartContext {
|
|
175
|
+
platform?: NodeJS.Platform;
|
|
176
|
+
env?: NodeJS.ProcessEnv;
|
|
177
|
+
/** The resolved scope launcher, or undefined when none is usable. */
|
|
178
|
+
systemdRun: string | undefined;
|
|
179
|
+
/** The OpenCodex-managed user unit (`TASK` in src/service/state.ts) without `.service`. */
|
|
180
|
+
unitName: string;
|
|
181
|
+
readCgroup?: () => string;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function cgroupPaths(cgroup: string): string[] {
|
|
185
|
+
const rows = cgroup.split("\n").map(line => line.split(":")).filter(parts => parts.length >= 3);
|
|
186
|
+
// cgroup v2 ("0::") or the v1 systemd hierarchy name the unit; controller lines are noise.
|
|
187
|
+
const unified = rows.filter(parts => parts[1] === "" || parts[1] === "name=systemd");
|
|
188
|
+
return (unified.length > 0 ? unified : rows).map(parts => parts.slice(2).join(":").trim()).filter(Boolean);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** The innermost systemd unit named by a cgroup path: its last `.service` or `.scope` component. */
|
|
192
|
+
function innermostUnit(path: string): { unit: string; index: number; parts: string[] } | null {
|
|
193
|
+
const parts = path.split("/");
|
|
194
|
+
for (let index = parts.length - 1; index >= 0; index--) {
|
|
195
|
+
const part = parts[index]!;
|
|
196
|
+
if (part.endsWith(".service") || part.endsWith(".scope")) return { unit: part, index, parts };
|
|
197
|
+
}
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Why a dashboard update must not run against this proxy, or null when it may (#7967).
|
|
203
|
+
*
|
|
204
|
+
* A dashboard update stops the proxy before it replaces the package, with or without a requested
|
|
205
|
+
* restart, and the worker survives that stop only from its own transient scope. Only OpenCodex's
|
|
206
|
+
* own user unit is restarted by the updater. A proxy inside any systemd service -- detected from
|
|
207
|
+
* `INVOCATION_ID` or from a `.service` cgroup, so a unit that unsets the variable is still seen
|
|
208
|
+
* -- is therefore refused unless the scope launcher works and the cgroup places it in
|
|
209
|
+
* `<unitName>.service` under a per-user manager (a delegated child cgroup below it is fine). A
|
|
210
|
+
* custom system unit with `User=` would lose the worker with its cgroup, and the restart would aim
|
|
211
|
+
* at an unrelated, possibly inactive user unit. Outside systemd nothing changes.
|
|
212
|
+
*/
|
|
213
|
+
export function dashboardRestartRefusal(context: DashboardRestartContext): string | null {
|
|
214
|
+
const platform = context.platform ?? process.platform;
|
|
215
|
+
const env = context.env ?? process.env;
|
|
216
|
+
if (platform !== "linux") return null;
|
|
217
|
+
let cgroup: string | null;
|
|
218
|
+
try { cgroup = (context.readCgroup ?? (() => readFileSync("/proc/self/cgroup", "utf8")))(); }
|
|
219
|
+
catch { cgroup = null; }
|
|
220
|
+
const paths = cgroup === null ? [] : cgroupPaths(cgroup);
|
|
221
|
+
// The innermost unit decides: a terminal or app scope below the per-user manager
|
|
222
|
+
// (user@<uid>.service/app.slice/vte-spawn-1.scope) is not a service; a system or user service is.
|
|
223
|
+
const units: ReturnType<typeof innermostUnit>[] = paths.map(innermostUnit);
|
|
224
|
+
const observed = units.filter((found): found is NonNullable<typeof found> => found !== null);
|
|
225
|
+
// The observed cgroup wins over an inherited INVOCATION_ID (a shell moved into its own scope
|
|
226
|
+
// keeps the variable); without an observation the variable alone fails closed.
|
|
227
|
+
const inService = observed.length > 0
|
|
228
|
+
? observed.some(found => found.unit.endsWith(".service") && !found.unit.startsWith("user@"))
|
|
229
|
+
: Boolean(env.INVOCATION_ID);
|
|
230
|
+
if (!inService) return null;
|
|
231
|
+
const manual = "Stop the service with its own manager, update the package from a shell (for example `ocx update`), then start the service again.";
|
|
232
|
+
if (!context.systemdRun || !env.INVOCATION_ID) {
|
|
233
|
+
return `Dashboard update is unavailable: this proxy runs inside a systemd service, and the update worker cannot leave the service's cgroup (no usable \`systemd-run --user --scope\`), so stopping the proxy for the update would stop the update too. ${manual}`;
|
|
234
|
+
}
|
|
235
|
+
const ownUnit = `${context.unitName}.service`;
|
|
236
|
+
const managedByOwnUnit = units.some((found): boolean => found !== null && found.unit === ownUnit
|
|
237
|
+
&& found.parts.slice(0, found.index).some((part: string) => part.startsWith("user@") && part.endsWith(".service")));
|
|
238
|
+
if (!managedByOwnUnit) {
|
|
239
|
+
return `Dashboard update is unavailable: this proxy runs under a systemd unit that is not OpenCodex's own \`${context.unitName}.service\` user unit, so the updater can neither keep its worker alive nor restart that unit safely. ${manual}`;
|
|
240
|
+
}
|
|
241
|
+
return null;
|
|
242
|
+
}
|
|
243
|
+
|
|
174
244
|
export function guiUpdateWorkerCommand(
|
|
175
245
|
execPath: string,
|
|
176
246
|
args: readonly string[],
|