@bitkyc08/opencodex 2.91.0 → 2.93.0-preview.20261027
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/ocx.mjs +47 -8
- package/gui/dist/assets/App-CJZoq-uF.js +58 -0
- package/gui/dist/assets/{Tray-BuLy7hL1.js → Tray-BWQPcgZn.js} +1 -1
- package/gui/dist/assets/index-DRe8Hhfz.css +1 -0
- package/gui/dist/assets/index-Xfct8owH.js +94 -0
- package/gui/dist/assets/quota-summary-DxToX1rV.js +1 -0
- package/gui/dist/index.html +2 -2
- package/gui/dist/provider-icons/workbuddy-color.svg +29 -0
- package/package.json +8 -7
- package/src/adapters/anthropic.ts +28 -5
- package/src/adapters/coding-agent/batch-dispatcher.ts +122 -0
- package/src/adapters/coding-agent/profile.ts +54 -16
- package/src/adapters/coding-agent/turn.ts +30 -2
- package/src/adapters/command-code.ts +114 -7
- package/src/adapters/cursor/native-exec-fs.ts +11 -9
- package/src/adapters/devin/live-models.ts +4 -0
- package/src/adapters/google-vertex-endpoint.ts +9 -1
- package/src/adapters/google-vertex-key-project.ts +223 -0
- package/src/adapters/google-wire-compiler.ts +1 -2
- package/src/adapters/google.ts +13 -3
- package/src/adapters/kiro/reasoning.ts +2 -0
- package/src/adapters/kiro-refusal.ts +6 -1
- package/src/adapters/kiro-wire.ts +1 -1
- package/src/adapters/openai-chat/messages.ts +8 -2
- package/src/adapters/openai-chat/passthrough.ts +35 -14
- package/src/adapters/openai-chat/reasoning-replay.ts +27 -16
- package/src/adapters/openai-chat/reasoning-wire.ts +117 -8
- package/src/adapters/openai-chat/required-tool-result.ts +64 -0
- package/src/adapters/openai-chat/tool-name-registry.ts +3 -1
- package/src/adapters/openai-chat.ts +9 -10
- package/src/adapters/openai-responses/passthrough.ts +7 -4
- package/src/adapters/openai-responses/reasoning.ts +13 -0
- package/src/adapters/openai-responses/request-strips.ts +60 -0
- package/src/adapters/qoder/adapter.ts +129 -8
- package/src/adapters/qoder/scaffold-guard.ts +5 -0
- package/src/adapters/reasoning-controls.ts +16 -0
- package/src/adapters/registry.ts +5 -0
- package/src/adapters/tool-call-id.ts +1 -3
- package/src/adapters/workbuddy-schema.ts +61 -0
- package/src/adapters/workbuddy.ts +68 -0
- package/src/bridge/errors.ts +27 -0
- package/src/bridge/response-json.ts +1 -1
- package/src/bridge/sse.ts +1 -1
- package/src/bridge.ts +1 -1
- package/src/chat/inbound.ts +4 -1
- package/src/chat/outbound.ts +20 -6
- package/src/chat/reasoning-details.ts +28 -5
- package/src/claude/desktop-first-party.ts +54 -4
- package/src/claude/desktop-picker.ts +11 -8
- package/src/claude/first-party-settings.ts +3 -1
- package/src/claude/inbound.ts +2 -1
- package/src/claude/intercept/local-ca.ts +2 -1
- package/src/claude/intercept/picker-ca-cleanup.ts +4 -2
- package/src/claude/intercept/picker-ca-startup.ts +3 -1
- package/src/claude/intercept/picker-models.ts +6 -3
- package/src/claude/intercept/picker-runtime.ts +3 -2
- package/src/claude/intercept/runtime.ts +6 -3
- package/src/claude/model-info.ts +31 -8
- package/src/cli/account-api.ts +11 -0
- package/src/cli/capabilities-agents-routing.ts +3 -3
- package/src/cli/capabilities-base.ts +7 -1
- package/src/cli/capabilities-observe-system.ts +10 -0
- package/src/cli/claude-desktop.ts +9 -8
- package/src/cli/claude.ts +3 -2
- package/src/cli/codex-cli-update.ts +8 -0
- package/src/cli/codex-shim-autorestore.ts +9 -0
- package/src/cli/combo-result.ts +13 -0
- package/src/cli/combo-stats.ts +3 -0
- package/src/cli/combo.ts +83 -41
- package/src/cli/cross-home-owner.ts +13 -1
- package/src/cli/dispatch.ts +25 -6
- package/src/cli/ensure-desired-integrations.ts +8 -6
- package/src/cli/export-command.ts +4 -1
- package/src/cli/help.ts +2 -1
- package/src/cli/index.ts +45 -45
- package/src/cli/integration-plan-dto.ts +4 -0
- package/src/cli/launcher-context.ts +49 -2
- package/src/cli/link.ts +45 -32
- package/src/cli/opencode.ts +20 -9
- package/src/cli/provider.ts +2 -1
- package/src/cli/registry.ts +6 -4
- package/src/cli/root.ts +9 -0
- package/src/cli/status.ts +59 -1
- package/src/cli/stop-restore.ts +113 -0
- package/src/cli/sync-expectation.ts +60 -0
- package/src/cli/uninstall-integrations.ts +41 -7
- package/src/cli/usage-compare.ts +68 -12
- package/src/client/connect.ts +40 -3
- package/src/client/link-home.ts +10 -1
- package/src/client/link-ingress.ts +1 -1
- package/src/client/link-readiness.ts +97 -0
- package/src/client/link-relay-transport.ts +79 -11
- package/src/client/link-relay.ts +74 -15
- package/src/client/link-tunnel.ts +45 -18
- package/src/client/machine-api.ts +3 -1
- package/src/client/machine-listener.ts +20 -2
- package/src/client/runtime.ts +20 -2
- package/src/client/sync-expectation.ts +118 -0
- package/src/clients/config-export/agent-clients.ts +96 -0
- package/src/clients/config-export/contracts.ts +25 -7
- package/src/clients/config-export/qoder.ts +38 -23
- package/src/clients/config-export/reasoning-metadata.ts +55 -8
- package/src/clients/config-export.ts +12 -0
- package/src/clients/lazycodex.ts +7 -2
- package/src/clients/reasoning-controls.ts +49 -0
- package/src/codex/account-store.ts +17 -3
- package/src/codex/app-server-restart-service.ts +6 -5
- package/src/codex/auth-api/account-identity.ts +14 -0
- package/src/codex/auth-api/account-list.ts +29 -2
- package/src/codex/auth-api/http.ts +13 -0
- package/src/codex/auth-api/main-account-probe.ts +2 -2
- package/src/codex/auth-api/pool-mode-gate.ts +16 -3
- package/src/codex/auth-api/pool-quota-probe.ts +15 -0
- package/src/codex/auth-context.ts +15 -12
- package/src/codex/catalog/build-entries.ts +22 -0
- package/src/codex/catalog/configured-tiers.ts +70 -0
- package/src/codex/catalog/effort.ts +52 -11
- package/src/codex/catalog/gather-capture.ts +5 -2
- package/src/codex/catalog/heal-observation.ts +155 -13
- package/src/codex/catalog/metadata.ts +6 -0
- package/src/codex/catalog/model-hints.ts +60 -11
- package/src/codex/catalog/model-visibility.ts +3 -2
- package/src/codex/catalog/native-models.ts +18 -3
- package/src/codex/catalog/parsing.ts +10 -8
- package/src/codex/catalog/pinned-models.ts +2 -1
- package/src/codex/catalog/provider-models.ts +18 -13
- package/src/codex/catalog/retained-sync.ts +2 -1
- package/src/codex/catalog/routed-gather.ts +19 -20
- package/src/codex/catalog/write-audit.ts +3 -2
- package/src/codex/catalog-self-heal.ts +43 -23
- package/src/codex/chatgpt-refresh-failure.ts +6 -2
- package/src/codex/cli-install-provenance.ts +418 -0
- package/src/codex/cli-installation-targets.ts +5 -1
- package/src/codex/cli-update-plan.ts +43 -16
- package/src/codex/collision-identity.ts +30 -5
- package/src/codex/convergence.ts +4 -3
- package/src/codex/data/roster-pinned-models.json +177 -1
- package/src/codex/desired-state.ts +6 -1
- package/src/codex/desktop-app/picker-freshness.ts +10 -8
- package/src/codex/desktop-compatibility/installed-build.ts +88 -12
- package/src/codex/desktop-compatibility/runtime.ts +29 -5
- package/src/codex/desktop-compatibility/usage-activation.ts +2 -1
- package/src/codex/desktop-compatibility/usage-controller.ts +9 -1
- package/src/codex/desktop-compatibility/windows-certificate-trust.ts +46 -12
- package/src/codex/inject/config-toml.ts +0 -18
- package/src/codex/inject/plan.ts +18 -3
- package/src/codex/inject/remove.ts +6 -2
- package/src/codex/inject.ts +1 -1
- package/src/codex/journal.ts +61 -1
- package/src/codex/model-entitlements.ts +1 -1
- package/src/codex/native-main-owner.ts +27 -1
- package/src/codex/native-profile-store.ts +2 -1
- package/src/codex/pool-credit-policy.ts +35 -1
- package/src/codex/pool-refresh-backoff.ts +3 -1
- package/src/codex/quota-types.ts +3 -0
- package/src/codex/quota.ts +24 -4
- package/src/codex/role-auto-assign.ts +6 -2
- package/src/codex/subagent-defaults.ts +49 -4
- package/src/codex/user-identity.ts +35 -6
- package/src/codex/windows-current-sid.ts +162 -0
- package/src/combos/failover.ts +17 -2
- package/src/combos/jev-decision-contract.ts +22 -1
- package/src/combos/jev-quota-activation.ts +5 -1
- package/src/combos/jev-quota-route.ts +1 -1
- package/src/combos/jev-quota.ts +9 -1
- package/src/combos/jev-service-exchange.ts +3 -1
- package/src/combos/jev-session-pin-config.ts +51 -0
- package/src/combos/jev.ts +101 -9
- package/src/combos/resolve.ts +45 -1
- package/src/combos/types.ts +43 -0
- package/src/config/load-degrade.ts +5 -0
- package/src/config/paths.ts +19 -3
- package/src/config/pending-teardown.ts +22 -1
- package/src/config/provider-validation.ts +22 -4
- package/src/config/removed-opencode-free.ts +11 -0
- package/src/config/schema/leaf-validators.ts +6 -0
- package/src/generated/compatibility-version.json +467 -311
- package/src/generated/model-metadata.ts +5 -5
- package/src/images/loop.ts +16 -2
- package/src/integrations/catalog-refresh.ts +1 -1
- package/src/integrations/hermes-profiles.ts +251 -0
- package/src/integrations/merge.ts +8 -0
- package/src/integrations/mutation-plan.ts +19 -4
- package/src/integrations/registry.ts +5 -0
- package/src/integrations/state.ts +36 -1
- package/src/integrations/writer.ts +18 -4
- package/src/lib/bun-path-runtime.mjs +2 -1
- package/src/lib/decision-quota-sink.ts +10 -0
- package/src/lib/errors.ts +62 -0
- package/src/lib/eventstream-decoder.ts +81 -37
- package/src/lib/opaque-proxy-tunnel.ts +32 -8
- package/src/lib/pinned-http.ts +35 -2
- package/src/lib/process-control.ts +13 -1
- package/src/lib/socks5-fetch.ts +59 -64
- package/src/lib/socks5-upload-waiter.ts +50 -0
- package/src/lib/sse-decoder.ts +7 -2
- package/src/lib/state-store-sweeper.ts +40 -14
- package/src/lib/translator-budget.ts +4 -4
- package/src/lib/upstream-retry.ts +4 -1
- package/src/lib/windows-native-principal-worker.ts +14 -0
- package/src/lib/windows-native-principal.ts +188 -0
- package/src/lib/windows-secret-acl.ts +39 -3
- package/src/lib/windows-user-principal.ts +62 -18
- package/src/link/diagnostics.ts +193 -0
- package/src/link/relay-auth.ts +6 -0
- package/src/link/ssh-config.ts +35 -3
- package/src/link/status-projection.ts +39 -0
- package/src/link/supervisor.ts +45 -12
- package/src/link/tunnel-history.ts +109 -0
- package/src/link/tunnel-state.ts +80 -17
- package/src/messaging/remote-files.ts +24 -1
- package/src/oauth/generic-account-failover.ts +91 -7
- package/src/oauth/index.ts +15 -0
- package/src/oauth/model-discovery-auth.ts +5 -0
- package/src/oauth/store.ts +4 -1
- package/src/oauth/token-guardian.ts +7 -0
- package/src/oauth/types.ts +9 -0
- package/src/oauth/workbuddy.ts +139 -0
- package/src/providers/account-quota-disk.ts +12 -4
- package/src/providers/antigravity-quota-identity.ts +37 -0
- package/src/providers/base-url-choices.ts +8 -5
- package/src/providers/codebuddy-models.ts +6 -0
- package/src/providers/codex-capacity.ts +3 -1
- package/src/providers/derive.ts +51 -3
- package/src/providers/kiro-models.ts +3 -0
- package/src/providers/mimo-thinking.ts +12 -0
- package/src/providers/model-discovery.ts +2 -0
- package/src/providers/model-rename-fields.ts +2 -0
- package/src/providers/model-rename-migration.ts +10 -0
- package/src/providers/openai-sidecar-credit.ts +2 -2
- package/src/providers/quota/account-cache.ts +3 -2
- package/src/providers/quota/antigravity.ts +25 -14
- package/src/providers/quota/report-cache.ts +13 -4
- package/src/providers/quota/vendor-probes-key.ts +60 -0
- package/src/providers/quota/workbuddy.ts +83 -0
- package/src/providers/quota-decision-antigravity.ts +64 -0
- package/src/providers/quota-decision-publication.ts +11 -0
- package/src/providers/quota-decision-snapshot.ts +21 -4
- package/src/providers/quota-types.ts +2 -0
- package/src/providers/quota.ts +3 -1
- package/src/providers/reasoning-capabilities.ts +76 -0
- package/src/providers/registry/entries-core.ts +23 -12
- package/src/providers/registry/entries-extended.ts +83 -27
- package/src/providers/registry/model-ids.ts +5 -0
- package/src/providers/registry/model-seeds.ts +120 -56
- package/src/providers/registry/types.ts +29 -2
- package/src/providers/resolved-model-policy.ts +30 -10
- package/src/providers/routed-config.ts +24 -1
- package/src/providers/stale-model-roster-migration.ts +123 -18
- package/src/providers/workbuddy-credit-balance.ts +81 -0
- package/src/providers/workbuddy-models.ts +37 -0
- package/src/providers/workbuddy.ts +60 -0
- package/src/remote-control/workspace-pi-runtime.ts +11 -6
- package/src/responses/compaction-summary.ts +45 -0
- package/src/responses/muse-tool-name-alias.ts +1 -2
- package/src/responses/parser.ts +3 -2
- package/src/responses/reasoning-replay-cache.ts +18 -14
- package/src/responses/schema.ts +1 -0
- package/src/responses/thought-signature-replay.ts +10 -2
- package/src/router.ts +2 -0
- package/src/routing/analytics.ts +2 -3
- package/src/routing/capability.ts +8 -2
- package/src/routing/fallback-policy.ts +3 -3
- package/src/routing/history/ingest.ts +28 -3
- package/src/server/auth-cors.ts +4 -2
- package/src/server/chat-completions.ts +21 -1
- package/src/server/chat-native-eligibility.ts +7 -0
- package/src/server/chat-native-reasoning.ts +24 -7
- package/src/server/chat-native.ts +13 -2
- package/src/server/claude-messages.ts +3 -0
- package/src/server/direct-local-http.ts +5 -2
- package/src/server/effort-policy.ts +5 -1
- package/src/server/index/link-relay-sessions.ts +9 -5
- package/src/server/index/live-sideband.ts +18 -15
- package/src/server/index/optional-listeners.ts +4 -0
- package/src/server/index/serve-options.ts +5 -4
- package/src/server/local-management-read-client.ts +3 -1
- package/src/server/management/agent-settings-routes.ts +27 -15
- package/src/server/management/combo-routes.ts +14 -4
- package/src/server/management/config-routes.ts +2 -2
- package/src/server/management/decision-discovery.ts +12 -2
- package/src/server/management/hermes-profile-routes.ts +156 -0
- package/src/server/management/integration-routes.ts +85 -24
- package/src/server/management/link-routes.ts +5 -2
- package/src/server/management/model-routes.ts +2 -2
- package/src/server/management/model-row-export-metadata.ts +25 -6
- package/src/server/management/model-rows.ts +15 -20
- package/src/server/management/native-integration-routes.ts +11 -8
- package/src/server/management/provider-routes.ts +1 -1
- package/src/server/management/route-registry.ts +4 -0
- package/src/server/management-api.ts +5 -0
- package/src/server/models-capabilities.ts +21 -3
- package/src/server/port-reclaim.ts +51 -9
- package/src/server/request-log-conversation.ts +49 -0
- package/src/server/request-log.ts +2 -0
- package/src/server/responses/adapter-delivery.ts +11 -1
- package/src/server/responses/adapter-dispatch.ts +2 -2
- package/src/server/responses/anthropic-thinking-recovery.ts +1 -0
- package/src/server/responses/codex-ws-exchange.ts +39 -9
- package/src/server/responses/codex-ws-session.ts +38 -4
- package/src/server/responses/codex-ws-wire.ts +6 -1
- package/src/server/responses/combo-required-tool-contract.ts +103 -0
- package/src/server/responses/combo-stream-preflight.ts +8 -1
- package/src/server/responses/compact.ts +14 -5
- package/src/server/responses/context-overflow.ts +8 -1
- package/src/server/responses/core-combo-failure.ts +10 -0
- package/src/server/responses/core-combo.ts +74 -44
- package/src/server/responses/core-lifetime.ts +5 -2
- package/src/server/responses/core-normalize.ts +17 -4
- package/src/server/responses/core-opaque-recovery.ts +1 -0
- package/src/server/responses/core-options.ts +7 -0
- package/src/server/responses/core-replay.ts +2 -1
- package/src/server/responses/jev-combo-choice.ts +39 -0
- package/src/server/responses/jev-session-pin.ts +203 -0
- package/src/server/responses/main-hard-lock-routing.ts +60 -44
- package/src/server/responses/passthrough-delivery.ts +44 -2
- package/src/server/responses/policy-fallback.ts +6 -1
- package/src/server/responses/request-compression.ts +12 -7
- package/src/server/responses/request-prepare.ts +32 -7
- package/src/server/responses/request-sidecar-auth.ts +2 -0
- package/src/server/responses/request-transport.ts +25 -6
- package/src/server/responses/response-effects.ts +22 -10
- package/src/server/responses/run-turn-execution.ts +2 -4
- package/src/server/responses/sidecar-execution.ts +13 -7
- package/src/server/responses-phase-inference.ts +267 -0
- package/src/server/sse-payload-rewrite.ts +14 -1
- package/src/server/stop-teardown.ts +36 -1
- package/src/server/ws-bridge.ts +1 -1
- package/src/service/definition.ts +20 -8
- package/src/service/desktop-supervision.d.mts +7 -4
- package/src/service/desktop-supervision.mjs +90 -13
- package/src/service/ownership-mutation-lease.mjs +21 -7
- package/src/types/config.ts +14 -2
- package/src/types/provider.ts +29 -7
- package/src/types/request.ts +11 -0
- package/src/types/wire.ts +1 -0
- package/src/types.ts +1 -0
- package/src/update/bind-probe.ts +29 -0
- package/src/update/codex-cli-update-launch-policy.d.mts +9 -0
- package/src/update/codex-cli-update-launch-policy.mjs +30 -0
- package/src/update/job.ts +10 -29
- package/src/update/npm-install-job.ps1 +173 -0
- package/src/update/npm-install.mjs +70 -0
- package/src/update/stop-contract.d.mts +1 -0
- package/src/update/stop-contract.mjs +14 -0
- package/src/update/stop-decision.d.mts +1 -1
- package/src/update/stop-decision.mjs +13 -3
- package/src/update/teardown-handover.ts +166 -0
- package/src/update/transactional-install.d.mts +14 -3
- package/src/update/transactional-install.mjs +33 -7
- package/src/usage/expected-prices.ts +64 -31
- package/src/usage/jev-stats.ts +54 -14
- package/src/usage/timeline.ts +19 -9
- package/src/vision/eligibility.ts +15 -5
- package/src/vision/plan.ts +2 -2
- package/src/web-search/loop.ts +16 -2
- package/gui/dist/assets/App-nZ34cR5G.js +0 -58
- package/gui/dist/assets/index-DGXS51sp.js +0 -94
- package/gui/dist/assets/index-DPeB9HpV.css +0 -1
- package/gui/dist/assets/quota-summary-DO1Sx5TM.js +0 -1
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The effective process token's SID, read in-process on Windows x64.
|
|
3
|
+
*
|
|
4
|
+
* The PowerShell helper this replaces is correct but slow to start: a cold
|
|
5
|
+
* `powershell.exe` on a loaded runner spent more than the 30s lookup budget
|
|
6
|
+
* before evaluating one constant of the process token, and `ocx service install`
|
|
7
|
+
* refused (#7544). Widening that budget again would only move the line. The SID
|
|
8
|
+
* itself costs three advapi32 calls, so the x64 path asks the OS directly and the
|
|
9
|
+
* helper keeps running only where `bun:ffi` cannot (Windows ARM64).
|
|
10
|
+
*
|
|
11
|
+
* The answer is the PROCESS token's user. `WindowsIdentity.GetCurrent()` would
|
|
12
|
+
* prefer a thread impersonation token, but nothing in this process impersonates,
|
|
13
|
+
* so the two agree; the process token is also what Task Scheduler and the ACL
|
|
14
|
+
* code grant to.
|
|
15
|
+
*
|
|
16
|
+
* Fail-closed is preserved: when the native API is available and fails, the
|
|
17
|
+
* lookup throws and the caller refuses. It never falls back to the helper, whose
|
|
18
|
+
* environment the native path exists to avoid depending on.
|
|
19
|
+
*/
|
|
20
|
+
import { dlopen, ptr, read, type Pointer } from "bun:ffi";
|
|
21
|
+
import { win32 } from "node:path";
|
|
22
|
+
import { resolveTrustedWindowsSystemDirectory } from "../lib/windows-elevation";
|
|
23
|
+
|
|
24
|
+
const TOKEN_QUERY = 0x0008;
|
|
25
|
+
const TOKEN_USER_INFORMATION_CLASS = 1;
|
|
26
|
+
/**
|
|
27
|
+
* TOKEN_USER is one SID_AND_ATTRIBUTES (an 8-byte SID pointer and a 4-byte
|
|
28
|
+
* attribute word, padded to 16) followed by the SID it points at. A SID is at
|
|
29
|
+
* most SECURITY_MAX_SID_SIZE (68) bytes, so 256 bytes always suffices and a
|
|
30
|
+
* larger reported length is treated as a malformed answer.
|
|
31
|
+
*/
|
|
32
|
+
const TOKEN_USER_BUFFER_BYTES = 256;
|
|
33
|
+
const TOKEN_USER_HEADER_BYTES = 16;
|
|
34
|
+
/** "S-1-" plus at most 15 sub-authorities of up to 10 digits each, with room to spare. */
|
|
35
|
+
const MAX_SID_STRING_CODE_UNITS = 256;
|
|
36
|
+
const SID_PATTERN = /^S-1-(?:\d+-)+\d+$/i;
|
|
37
|
+
|
|
38
|
+
export interface WindowsTokenSidApi {
|
|
39
|
+
/** OpenProcessToken(GetCurrentProcess(), access, &token). Non-zero BOOL is success. */
|
|
40
|
+
openProcessToken(desiredAccess: number, token: BigUint64Array): number;
|
|
41
|
+
/** GetTokenInformation(token, class, buffer, buffer.length, &returnLength). */
|
|
42
|
+
getTokenInformation(
|
|
43
|
+
token: bigint,
|
|
44
|
+
informationClass: number,
|
|
45
|
+
buffer: Uint8Array,
|
|
46
|
+
returnLength: Uint32Array,
|
|
47
|
+
): number;
|
|
48
|
+
/** ConvertSidToStringSidW(sid, &string). The string is LocalAlloc'd on success. */
|
|
49
|
+
convertSidToStringSid(sidAddress: number, output: BigUint64Array): number;
|
|
50
|
+
readCodeUnit(address: number, byteOffset: number): number;
|
|
51
|
+
localFree(address: number): void;
|
|
52
|
+
closeHandle(token: bigint): void;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function lookupError(detail: string): Error {
|
|
56
|
+
return new Error(`Windows effective-account token lookup ${detail}.`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function readSidString(api: WindowsTokenSidApi, address: number): string {
|
|
60
|
+
const units: number[] = [];
|
|
61
|
+
for (let index = 0; index < MAX_SID_STRING_CODE_UNITS; index += 1) {
|
|
62
|
+
const unit = api.readCodeUnit(address, index * 2);
|
|
63
|
+
if (unit === 0) return String.fromCharCode(...units);
|
|
64
|
+
units.push(unit);
|
|
65
|
+
}
|
|
66
|
+
throw lookupError("returned an unterminated SID");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Same token user the PowerShell helper reports, without starting a process. */
|
|
70
|
+
export function readWindowsCurrentSid(api: WindowsTokenSidApi): string {
|
|
71
|
+
const tokenOutput = new BigUint64Array(1);
|
|
72
|
+
if (api.openProcessToken(TOKEN_QUERY, tokenOutput) === 0 || tokenOutput[0] === 0n) {
|
|
73
|
+
throw lookupError("could not open the process token");
|
|
74
|
+
}
|
|
75
|
+
const token = tokenOutput[0]!;
|
|
76
|
+
let stringAddress = 0;
|
|
77
|
+
try {
|
|
78
|
+
// Keep `buffer` referenced until the conversion returns: the SID pointer
|
|
79
|
+
// inside it points back into this same allocation.
|
|
80
|
+
const buffer = new Uint8Array(TOKEN_USER_BUFFER_BYTES);
|
|
81
|
+
const returnLength = new Uint32Array(1);
|
|
82
|
+
if (api.getTokenInformation(token, TOKEN_USER_INFORMATION_CLASS, buffer, returnLength) === 0) {
|
|
83
|
+
throw lookupError("could not read the token user");
|
|
84
|
+
}
|
|
85
|
+
const length = returnLength[0]!;
|
|
86
|
+
if (length <= TOKEN_USER_HEADER_BYTES || length > buffer.byteLength) {
|
|
87
|
+
throw lookupError("returned a malformed token user");
|
|
88
|
+
}
|
|
89
|
+
const sidAddress = Number(
|
|
90
|
+
new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength).getBigUint64(0, true),
|
|
91
|
+
);
|
|
92
|
+
if (!Number.isSafeInteger(sidAddress) || sidAddress <= 0) {
|
|
93
|
+
throw lookupError("returned a null SID");
|
|
94
|
+
}
|
|
95
|
+
const stringOutput = new BigUint64Array(1);
|
|
96
|
+
const converted = api.convertSidToStringSid(sidAddress, stringOutput);
|
|
97
|
+
const candidate = Number(stringOutput[0]);
|
|
98
|
+
if (converted === 0 || !Number.isSafeInteger(candidate) || candidate <= 0) {
|
|
99
|
+
throw lookupError("could not format the SID");
|
|
100
|
+
}
|
|
101
|
+
stringAddress = candidate;
|
|
102
|
+
const sid = readSidString(api, stringAddress);
|
|
103
|
+
if (!SID_PATTERN.test(sid)) throw lookupError("returned an invalid SID");
|
|
104
|
+
return sid.toUpperCase();
|
|
105
|
+
} finally {
|
|
106
|
+
if (stringAddress > 0) api.localFree(stringAddress);
|
|
107
|
+
api.closeHandle(token);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
let nativeLookup: (() => string) | null | undefined;
|
|
112
|
+
|
|
113
|
+
function loadNativeLookup(): (() => string) | null {
|
|
114
|
+
if (nativeLookup !== undefined) return nativeLookup;
|
|
115
|
+
if (process.platform !== "win32" || process.arch !== "x64") return null;
|
|
116
|
+
try {
|
|
117
|
+
const systemDirectory = resolveTrustedWindowsSystemDirectory();
|
|
118
|
+
const advapi = dlopen(win32.join(systemDirectory, "advapi32.dll"), {
|
|
119
|
+
OpenProcessToken: { args: ["u64", "u32", "ptr"], returns: "i32" },
|
|
120
|
+
GetTokenInformation: { args: ["u64", "u32", "ptr", "u32", "ptr"], returns: "i32" },
|
|
121
|
+
ConvertSidToStringSidW: { args: ["ptr", "ptr"], returns: "i32" },
|
|
122
|
+
});
|
|
123
|
+
let kernel;
|
|
124
|
+
try {
|
|
125
|
+
kernel = dlopen(win32.join(systemDirectory, "kernel32.dll"), {
|
|
126
|
+
GetCurrentProcess: { args: [], returns: "u64" },
|
|
127
|
+
CloseHandle: { args: ["u64"], returns: "i32" },
|
|
128
|
+
LocalFree: { args: ["ptr"], returns: "ptr" },
|
|
129
|
+
});
|
|
130
|
+
} catch (error) {
|
|
131
|
+
advapi.close();
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
const api: WindowsTokenSidApi = {
|
|
135
|
+
openProcessToken: (access, token) => advapi.symbols.OpenProcessToken(
|
|
136
|
+
kernel.symbols.GetCurrentProcess(), access, ptr(token),
|
|
137
|
+
),
|
|
138
|
+
getTokenInformation: (token, informationClass, buffer, returnLength) =>
|
|
139
|
+
advapi.symbols.GetTokenInformation(
|
|
140
|
+
token, informationClass, ptr(buffer), buffer.byteLength, ptr(returnLength),
|
|
141
|
+
),
|
|
142
|
+
convertSidToStringSid: (sidAddress, output) => advapi.symbols.ConvertSidToStringSidW(
|
|
143
|
+
sidAddress as Pointer, ptr(output),
|
|
144
|
+
),
|
|
145
|
+
readCodeUnit: (address, offset) => read.u16(address as Pointer, offset),
|
|
146
|
+
localFree: address => { kernel.symbols.LocalFree(address as Pointer); },
|
|
147
|
+
closeHandle: token => { kernel.symbols.CloseHandle(token); },
|
|
148
|
+
};
|
|
149
|
+
nativeLookup = () => readWindowsCurrentSid(api);
|
|
150
|
+
} catch {
|
|
151
|
+
nativeLookup = null;
|
|
152
|
+
}
|
|
153
|
+
return nativeLookup;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Unsupported FFI keeps the bounded trusted helper; an OS API failure still refuses. */
|
|
157
|
+
export function resolveWindowsCurrentSid(
|
|
158
|
+
powershellLookup: () => string,
|
|
159
|
+
lookup: (() => string) | null = loadNativeLookup(),
|
|
160
|
+
): string {
|
|
161
|
+
return lookup ? lookup() : powershellLookup();
|
|
162
|
+
}
|
package/src/combos/failover.ts
CHANGED
|
@@ -313,7 +313,8 @@ export function sweepExpiredComboTargetCooldowns(now = Date.now()): number {
|
|
|
313
313
|
return removed;
|
|
314
314
|
}
|
|
315
315
|
|
|
316
|
-
|
|
316
|
+
/** Clear all cooldowns, one combo, or only the supplied target keys within that combo. */
|
|
317
|
+
export function clearComboTargetCooldowns(comboId?: string, targetKeys?: Iterable<string>): void {
|
|
317
318
|
if (comboId === undefined) {
|
|
318
319
|
targetCooldowns.clear();
|
|
319
320
|
liveComboTargets.clear();
|
|
@@ -321,6 +322,10 @@ export function clearComboTargetCooldowns(comboId?: string): void {
|
|
|
321
322
|
return;
|
|
322
323
|
}
|
|
323
324
|
const prefix = `${comboId}\0`;
|
|
325
|
+
if (targetKeys !== undefined) {
|
|
326
|
+
for (const key of targetKeys) targetCooldowns.delete(`${prefix}${key}`);
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
324
329
|
for (const key of targetCooldowns.keys()) {
|
|
325
330
|
if (key.startsWith(prefix)) targetCooldowns.delete(key);
|
|
326
331
|
}
|
|
@@ -773,7 +778,13 @@ export function codexAccountModelRefusal(
|
|
|
773
778
|
export function comboFailureDecision(
|
|
774
779
|
status: number,
|
|
775
780
|
message: string,
|
|
776
|
-
options?: {
|
|
781
|
+
options?: {
|
|
782
|
+
code?: string | null;
|
|
783
|
+
codexModelRefusal?: CodexAccountModelRefusal;
|
|
784
|
+
failedAdapter?: string;
|
|
785
|
+
/** The caller proved the failure is an adapter-normalized plan refusal (`isModelNotInPlanRefusal`). */
|
|
786
|
+
verifiedPlanRefusal?: boolean;
|
|
787
|
+
},
|
|
777
788
|
): ComboFailureDecision {
|
|
778
789
|
if (status === 499) return "stop";
|
|
779
790
|
if (message.toLowerCase().includes("origin_rejected")) return "stop";
|
|
@@ -846,6 +857,10 @@ export function comboFailureDecision(
|
|
|
846
857
|
if (["model_not_found", "model_unavailable", "unsupported_model", "unsupported_input_modality"].includes(failureCode)) {
|
|
847
858
|
return "hop";
|
|
848
859
|
}
|
|
860
|
+
// So is a plan refusal (#7684): this account's plan excludes THIS model, and it cools only the
|
|
861
|
+
// refused target because `comboFailureCooldownScope` reads a 400 as target-scoped. Unlike the
|
|
862
|
+
// codes above it is honoured only with caller-supplied provenance, never from the code alone.
|
|
863
|
+
if (failureCode === "model_not_in_plan" && options?.verifiedPlanRefusal === true) return "hop";
|
|
849
864
|
if (modelRefusal === "refusal") return "hop";
|
|
850
865
|
// `free_rate_limited` no longer routes through `isProviderScopedQuotaCap` (it is a
|
|
851
866
|
// per-request cap, not provider-wide evidence), so keep its hop verdict explicit here.
|
|
@@ -38,6 +38,27 @@ export function isSystemOneEndpoint(baseUrl: string): boolean {
|
|
|
38
38
|
*/
|
|
39
39
|
export function jevDecisionEndpointUrl(baseUrl: string): string {
|
|
40
40
|
const raw = baseUrl.trim();
|
|
41
|
-
|
|
41
|
+
let stripped = raw.replace(/\/+$/, "");
|
|
42
|
+
try {
|
|
43
|
+
const parsed = new URL(raw);
|
|
44
|
+
if (parsed.hostname === "ai-gateway.vercel.sh") {
|
|
45
|
+
if (!stripped.endsWith("/decisions")) {
|
|
46
|
+
stripped = stripped.replace(/\/systemone$/, "").replace(/\/+$/, "") + "/decisions";
|
|
47
|
+
}
|
|
48
|
+
return stripped;
|
|
49
|
+
}
|
|
50
|
+
} catch {
|
|
51
|
+
return stripped.endsWith("/systemone") ? stripped : raw;
|
|
52
|
+
}
|
|
42
53
|
return stripped.endsWith("/systemone") ? stripped : raw;
|
|
43
54
|
}
|
|
55
|
+
|
|
56
|
+
/** Check if endpoint path targets /decisions or Vercel AI Gateway */
|
|
57
|
+
export function isDecisionsEndpoint(url: string): boolean {
|
|
58
|
+
try {
|
|
59
|
+
const parsed = new URL(url.trim());
|
|
60
|
+
return parsed.hostname === "ai-gateway.vercel.sh";
|
|
61
|
+
} catch {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -15,9 +15,10 @@
|
|
|
15
15
|
*/
|
|
16
16
|
import {
|
|
17
17
|
clearDecisionAccountQuotas, invalidateDecisionKeyQuotas, observeDecisionKeyCredential, publishDecisionAccountQuota,
|
|
18
|
-
publishDecisionKeyQuota, publishDecisionQuotaRoster, readLoadedDecisionKeyQuota, readLoadedDecisionQuotaPool,
|
|
18
|
+
publishDecisionKeyQuota, publishDecisionQuotaRoster, readLoadedDecisionKeyQuota, readLoadedDecisionQuotaPool, replaceDecisionKeyQuotas,
|
|
19
19
|
setDecisionAccountUsable, withdrawDecisionQuotaRoster,
|
|
20
20
|
} from "../providers/quota-decision-snapshot";
|
|
21
|
+
import { captureAntigravityReceipt, observeAntigravityQuotaStore, replaceAntigravityQuotas } from "../providers/quota-decision-antigravity";
|
|
21
22
|
import { registerDecisionQuotaSink, type DecisionQuotaSink, type MainDecisionRow } from "../lib/decision-quota-sink";
|
|
22
23
|
import { registerLiveConfigObserver } from "../lib/state-store-registrations";
|
|
23
24
|
import { getConfigDir } from "../config/paths";
|
|
@@ -32,6 +33,7 @@ const POOL_PROVIDERS = ["anthropic", "codex", "codex-main"] as const;
|
|
|
32
33
|
|
|
33
34
|
/** Project an auth store the owner already read into the secret-free Anthropic roster (primary pool only); a failure withdraws so the pool reads as unknown. The generation is a one-way digest of the credential, never the credential itself. */
|
|
34
35
|
function publishAuthDecisionQuotaRoster(store: AuthStore): void {
|
|
36
|
+
observeAntigravityQuotaStore(store);
|
|
35
37
|
try {
|
|
36
38
|
publishDecisionQuotaRoster("anthropic", (store.anthropic?.accounts ?? []).map(row => ({
|
|
37
39
|
id: row.id,
|
|
@@ -82,6 +84,8 @@ const snapshotSink: DecisionQuotaSink = {
|
|
|
82
84
|
mainRosterChanged: row => publishMainRow(row),
|
|
83
85
|
readKeyQuota: readLoadedDecisionKeyQuota,
|
|
84
86
|
readPool: readLoadedDecisionQuotaPool,
|
|
87
|
+
captureAntigravityReceipt,
|
|
88
|
+
replaceCollectedQuotas: (keys, oauth) => { replaceDecisionKeyQuotas(keys); replaceAntigravityQuotas(oauth); },
|
|
85
89
|
};
|
|
86
90
|
|
|
87
91
|
let active: { detach: () => void; root: string } | undefined;
|
|
@@ -7,7 +7,7 @@ export function jevQuotaCandidates(options: ResolveJevDecisionOptions): readonly
|
|
|
7
7
|
const tiers = normalizeJevQuotaTiers(options.decisionQuotaTiers) ?? JEV_QUOTA_DEFAULT_TIERS;
|
|
8
8
|
const now = (options.now ?? Date.now)();
|
|
9
9
|
return options.candidates.map(candidate => ({ ...candidate,
|
|
10
|
-
quota: jevQuotaSignalForTarget(options.config, candidate.provider, candidate.model, now, tiers) }));
|
|
10
|
+
quota: candidate.quotaIdentity === null ? { tier: "unknown" as const } : jevQuotaSignalForTarget(options.config, candidate.quotaIdentity?.provider ?? candidate.provider, candidate.quotaIdentity?.model ?? candidate.model, now, tiers) }));
|
|
11
11
|
}
|
|
12
12
|
/** Attach the per-tier quota summary to a decision when any candidate carried quota evidence. */
|
|
13
13
|
export function withJevQuotaSummary(decision: JevDecision, candidates: readonly JevCandidate[]): JevDecision {
|
package/src/combos/jev-quota.ts
CHANGED
|
@@ -6,6 +6,7 @@ import type { DecisionQuotaWindow } from "../providers/quota-decision-snapshot";
|
|
|
6
6
|
import { readLoadedDecisionKeyQuota, readLoadedDecisionQuotaPool } from "../lib/decision-quota-sink";
|
|
7
7
|
import { isCanonicalOpenAiForwardProvider } from "../providers/openai-tiers-destination";
|
|
8
8
|
import { providerCodexAccountMode } from "../providers/registry";
|
|
9
|
+
import { isAntigravityArgonIdentity } from "../providers/antigravity-quota-identity";
|
|
9
10
|
import { NATIVE_RESERVE_MODEL } from "../codex/catalog/native-models";
|
|
10
11
|
import { isSelectableCodexPoolAccount, MAIN_CODEX_ACCOUNT_ID } from "../codex/account-id";
|
|
11
12
|
import { JEV_QUOTA_DEFAULT_TIERS, jevQuotaRank, jevQuotaTier, type JevQuotaTier, type ResolvedJevQuotaTiers, type JevQuotaDecisionSummary } from "./jev-quota-config";
|
|
@@ -18,11 +19,18 @@ export interface JevQuotaSignal {
|
|
|
18
19
|
}
|
|
19
20
|
/** Build the signal used when evidence is missing, stale or invalid; it ties healthy. */
|
|
20
21
|
const unknown = (): JevQuotaSignal => ({ tier: "unknown" });
|
|
22
|
+
/** Antigravity quota buckets are metered per model family; Gemini and Claude/3P draw from separate counters. */
|
|
23
|
+
function antigravityFamily(model: string): DecisionQuotaWindow["family"] {
|
|
24
|
+
const id = model.toLowerCase();
|
|
25
|
+
if (isAntigravityArgonIdentity(id)) return undefined;
|
|
26
|
+
return id.startsWith("gemini-") ? "gem" : id.startsWith("claude-") ? "cla" : undefined;
|
|
27
|
+
}
|
|
21
28
|
/** Reduce decision quota windows to the worst applicable window for a model, ignoring cold, stale, future, invalid or reset-expired rows. */
|
|
22
29
|
export function jevQuotaSignalFromWindows(windows: readonly DecisionQuotaWindow[] | undefined, model: string, now: number, tiers = JEV_QUOTA_DEFAULT_TIERS): JevQuotaSignal {
|
|
23
30
|
let worst: DecisionQuotaWindow | undefined;
|
|
24
31
|
for (const row of windows ?? []) {
|
|
25
|
-
if (
|
|
32
|
+
if (row.family !== undefined) { if (row.family !== antigravityFamily(model)) continue; }
|
|
33
|
+
else if (!["5h", "weekly", "monthly"].includes(row.window) && anthropicModelFamily(model)?.toLowerCase() !== row.window) continue;
|
|
26
34
|
if (!Number.isFinite(now) || now < 0 || !Number.isFinite(row.observedAt) || row.observedAt < 0 || row.observedAt > now
|
|
27
35
|
|| now - row.observedAt > JEV_QUOTA_SIGNAL_MAX_AGE_MS || !Number.isFinite(row.percent) || row.percent < 0 || row.percent > 100
|
|
28
36
|
|| row.resetAt !== undefined && (!Number.isFinite(row.resetAt) || row.resetAt < 0 || row.resetAt <= now)) continue;
|
|
@@ -12,6 +12,7 @@ import { providerMatchesRegistryTransport } from "../providers/registry";
|
|
|
12
12
|
import type { OcxConfig, OcxProviderConfig } from "../types";
|
|
13
13
|
import type { JevDecision, ResolveJevDecisionOptions } from "./jev";
|
|
14
14
|
import {
|
|
15
|
+
isDecisionsEndpoint,
|
|
15
16
|
isSystemOneEndpoint,
|
|
16
17
|
jevDecisionEndpointUrl,
|
|
17
18
|
JEV_DECISION_TIMEOUT_DEFAULT_MS,
|
|
@@ -48,6 +49,7 @@ export type JevServiceExchangeOptions = Pick<ResolveJevDecisionOptions,
|
|
|
48
49
|
export interface JevDecisionEndpointShape {
|
|
49
50
|
model: string;
|
|
50
51
|
descriptiveCriteria: boolean;
|
|
52
|
+
url?: string;
|
|
51
53
|
}
|
|
52
54
|
|
|
53
55
|
/** The decision deadline: the configured value when in bounds, otherwise the four-second default. */
|
|
@@ -208,7 +210,7 @@ export async function exchangeJevDecision<T>(
|
|
|
208
210
|
if (endpoint === null) return { gate: "invalid" };
|
|
209
211
|
if (!endpoint) return { gate: "missing_key" };
|
|
210
212
|
|
|
211
|
-
const request = prepareRequestBody(prepare, { model: endpoint.model, descriptiveCriteria: endpoint.descriptiveCriteria });
|
|
213
|
+
const request = prepareRequestBody(prepare, { model: endpoint.model, descriptiveCriteria: endpoint.descriptiveCriteria, ...(isDecisionsEndpoint(endpoint.url) ? { url: endpoint.url } : {}) });
|
|
212
214
|
if (options.signal?.aborted) throw options.signal.reason;
|
|
213
215
|
if ("gate" in request) return request;
|
|
214
216
|
const requestBody = request.body;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Opt-in JEV session pin settings (#7525). Dependency-free so combo validation, the management
|
|
3
|
+
* API and the CLI share one grammar and one range.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** Shortest idle window a pin may be configured with. */
|
|
7
|
+
export const JEV_SESSION_PIN_TTL_MIN_MS = 60_000;
|
|
8
|
+
/** Longest idle window a pin may be configured with (one day). */
|
|
9
|
+
export const JEV_SESSION_PIN_TTL_MAX_MS = 86_400_000;
|
|
10
|
+
|
|
11
|
+
export interface JevSessionPinConfig {
|
|
12
|
+
/** Idle window after the last successful pinned turn; a quieter session is decided afresh. */
|
|
13
|
+
ttlMs: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Closed persisted vocabulary: `session` marks a turn that reused its pin; every other value names
|
|
18
|
+
* why an existing pin was released before a fresh decision.
|
|
19
|
+
*/
|
|
20
|
+
export const JEV_SESSION_PIN_REASONS = [
|
|
21
|
+
"session",
|
|
22
|
+
"expired",
|
|
23
|
+
"config_changed",
|
|
24
|
+
"target_unavailable",
|
|
25
|
+
"effort_unavailable",
|
|
26
|
+
"quota_nearly_exhausted",
|
|
27
|
+
] as const;
|
|
28
|
+
export type JevSessionPinReason = (typeof JEV_SESSION_PIN_REASONS)[number];
|
|
29
|
+
export type JevSessionPinRelease = Exclude<JevSessionPinReason, "session">;
|
|
30
|
+
|
|
31
|
+
/** The canonical pin setting, or undefined for anything that is not exactly `{ ttlMs }` in range. */
|
|
32
|
+
export function normalizeJevSessionPin(value: unknown): JevSessionPinConfig | undefined {
|
|
33
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
34
|
+
const keys = Object.keys(value);
|
|
35
|
+
if (keys.length !== 1 || keys[0] !== "ttlMs") return undefined;
|
|
36
|
+
const ttlMs = (value as { ttlMs?: unknown }).ttlMs;
|
|
37
|
+
return typeof ttlMs === "number" && Number.isSafeInteger(ttlMs)
|
|
38
|
+
&& ttlMs >= JEV_SESSION_PIN_TTL_MIN_MS && ttlMs <= JEV_SESSION_PIN_TTL_MAX_MS
|
|
39
|
+
? { ttlMs }
|
|
40
|
+
: undefined;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const DURATION_UNITS_MS: Readonly<Record<string, number>> = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000 };
|
|
44
|
+
|
|
45
|
+
/** Parse `90s`, `20m`, `1h` or bare milliseconds into an in-range TTL, else undefined. */
|
|
46
|
+
export function parseJevSessionPinDuration(raw: string): number | undefined {
|
|
47
|
+
const match = /^(\d{1,9})(ms|s|m|h)?$/.exec(raw.trim());
|
|
48
|
+
if (!match) return undefined;
|
|
49
|
+
const ttlMs = Number(match[1]) * DURATION_UNITS_MS[match[2] ?? "ms"]!;
|
|
50
|
+
return ttlMs >= JEV_SESSION_PIN_TTL_MIN_MS && ttlMs <= JEV_SESSION_PIN_TTL_MAX_MS ? ttlMs : undefined;
|
|
51
|
+
}
|
package/src/combos/jev.ts
CHANGED
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
JEV_MAX_CANDIDATE_FIELD_CHARS,
|
|
9
9
|
} from "./types";
|
|
10
10
|
|
|
11
|
+
import { isDecisionsEndpoint } from "./jev-decision-contract";
|
|
11
12
|
import {
|
|
12
13
|
exchangeJevDecision,
|
|
13
14
|
JEV_PROVIDER_ID,
|
|
@@ -25,6 +26,8 @@ export const JEV_MAX_CANDIDATES = 64;
|
|
|
25
26
|
/** Ollama's System One choice questions accept 2..26 options; other services share the floor. */
|
|
26
27
|
const SELF_HOSTED_MIN_OPTIONS = 2;
|
|
27
28
|
const SELF_HOSTED_MAX_OPTIONS = 26;
|
|
29
|
+
const DECISIONS_MIN_OPTIONS = 2;
|
|
30
|
+
const DECISIONS_MAX_OPTIONS = 255;
|
|
28
31
|
|
|
29
32
|
const TASK_CHARS = 500;
|
|
30
33
|
const TASK_HEAD_CHARS = 320;
|
|
@@ -80,6 +83,8 @@ export interface JevCandidate {
|
|
|
80
83
|
/** Optional operator note sent as decision evidence for this target only. */
|
|
81
84
|
modelProfile?: string;
|
|
82
85
|
quota?: JevQuotaSignal;
|
|
86
|
+
/** Internal native identity from ordinary routing; never replaces the configured allowlist. */
|
|
87
|
+
quotaIdentity?: { provider: string; model: string } | null;
|
|
83
88
|
}
|
|
84
89
|
|
|
85
90
|
/**
|
|
@@ -107,6 +112,10 @@ export interface JevDecision {
|
|
|
107
112
|
confidence?: number;
|
|
108
113
|
chosenProbability?: number;
|
|
109
114
|
usage?: Record<string, number>;
|
|
115
|
+
/** Set when an opt-in session pin (#7525) supplied this decision without asking the backend. */
|
|
116
|
+
pinned?: true;
|
|
117
|
+
/** `session` with `pinned`; otherwise why an existing session pin was released first. */
|
|
118
|
+
pinReason?: import("./jev-session-pin-config").JevSessionPinReason;
|
|
110
119
|
}
|
|
111
120
|
|
|
112
121
|
export interface ResolveJevDecisionOptions {
|
|
@@ -564,19 +573,46 @@ export function parseJevDecision(
|
|
|
564
573
|
payload: unknown,
|
|
565
574
|
candidates: readonly JevCandidate[],
|
|
566
575
|
): Pick<JevDecision, "targetKey" | "effort" | "confidence" | "chosenProbability" | "usage"> {
|
|
567
|
-
if (!isRecord(payload)
|
|
576
|
+
if (!isRecord(payload)) {
|
|
577
|
+
throw new Error("missing JEV route decision");
|
|
578
|
+
}
|
|
579
|
+
let answer: Record<string, unknown> | undefined;
|
|
580
|
+
if (isRecord(payload.answers) && isRecord(payload.answers.route)) {
|
|
581
|
+
answer = payload.answers.route as Record<string, unknown>;
|
|
582
|
+
} else if (Array.isArray(payload.answers)) {
|
|
583
|
+
const routeAnswers = payload.answers.filter((a): a is Record<string, unknown> => isRecord(a) && a.name === "route");
|
|
584
|
+
if (routeAnswers.length === 1) {
|
|
585
|
+
answer = routeAnswers[0];
|
|
586
|
+
} else if (routeAnswers.length > 1) {
|
|
587
|
+
throw new Error("duplicate JEV route decision");
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
if (!answer) {
|
|
568
591
|
throw new Error("missing JEV route decision");
|
|
569
592
|
}
|
|
570
|
-
const answer = payload.answers.route;
|
|
571
593
|
const options = candidateOptions(candidates);
|
|
572
|
-
|
|
594
|
+
const choiceValue = typeof answer.choice === "string" ? answer.choice : (typeof answer.value === "string" ? answer.value : undefined);
|
|
595
|
+
if (!choiceValue || !options.has(choiceValue)) {
|
|
573
596
|
throw new Error("unknown JEV route choice");
|
|
574
597
|
}
|
|
575
598
|
|
|
576
599
|
let chosenProbability: number | undefined;
|
|
577
600
|
if (answer.probabilities !== undefined) {
|
|
578
|
-
|
|
579
|
-
if (
|
|
601
|
+
let probabilities: Record<string, unknown>;
|
|
602
|
+
if (Array.isArray(answer.probabilities)) {
|
|
603
|
+
probabilities = {};
|
|
604
|
+
for (const item of answer.probabilities) {
|
|
605
|
+
if (!isRecord(item)) throw new Error("invalid JEV route probabilities");
|
|
606
|
+
const k = typeof item.choice === "string" ? item.choice : (typeof item.value === "string" ? item.value : undefined);
|
|
607
|
+
if (!k) throw new Error("invalid JEV route probabilities");
|
|
608
|
+
if (Object.hasOwn(probabilities, k)) throw new Error("invalid JEV route probabilities");
|
|
609
|
+
probabilities[k] = item.probability;
|
|
610
|
+
}
|
|
611
|
+
} else if (isRecord(answer.probabilities)) {
|
|
612
|
+
probabilities = answer.probabilities as Record<string, unknown>;
|
|
613
|
+
} else {
|
|
614
|
+
throw new Error("invalid JEV route probabilities");
|
|
615
|
+
}
|
|
580
616
|
const expected = [...options.keys()].sort();
|
|
581
617
|
const actual = Object.keys(probabilities).sort();
|
|
582
618
|
if (expected.length !== actual.length || expected.some((key, index) => key !== actual[index])) {
|
|
@@ -587,7 +623,7 @@ export function parseJevDecision(
|
|
|
587
623
|
throw new Error("invalid JEV route probabilities");
|
|
588
624
|
}
|
|
589
625
|
const numeric = values as number[];
|
|
590
|
-
const selected = probabilities[
|
|
626
|
+
const selected = probabilities[choiceValue] as number;
|
|
591
627
|
if (Math.abs(numeric.reduce((sum, value) => sum + value, 0) - 1) > 0.02
|
|
592
628
|
|| selected < Math.max(...numeric) - 1e-6) {
|
|
593
629
|
throw new Error("inconsistent JEV route distribution");
|
|
@@ -595,7 +631,7 @@ export function parseJevDecision(
|
|
|
595
631
|
chosenProbability = selected;
|
|
596
632
|
}
|
|
597
633
|
|
|
598
|
-
const option = options.get(
|
|
634
|
+
const option = options.get(choiceValue)!;
|
|
599
635
|
const confidence = typeof answer.confidence === "number"
|
|
600
636
|
&& Number.isFinite(answer.confidence)
|
|
601
637
|
&& answer.confidence >= 0
|
|
@@ -628,6 +664,31 @@ export function fallbackDecision(
|
|
|
628
664
|
* Every operational or response failure returns the supplied first-eligible fallback. A caller
|
|
629
665
|
* abort is the exception: request cancellation remains cancellation and is rethrown by identity.
|
|
630
666
|
*/
|
|
667
|
+
function formatDecisionsInput(state: Record<string, unknown>): string {
|
|
668
|
+
const parts: string[] = [];
|
|
669
|
+
if (typeof state.task === "string" && state.task.trim()) {
|
|
670
|
+
parts.push(`Task: ${state.task.trim()}`);
|
|
671
|
+
}
|
|
672
|
+
if (isRecord(state.signals)) {
|
|
673
|
+
const sigs: string[] = [];
|
|
674
|
+
if (state.signals.has_image === true) sigs.push("has_image");
|
|
675
|
+
if (state.signals.tool_history === true) sigs.push("tool_history");
|
|
676
|
+
if (sigs.length > 0) parts.push(`Signals: ${sigs.join(", ")}`);
|
|
677
|
+
}
|
|
678
|
+
if (typeof state.previous_assistant === "string" && state.previous_assistant.trim()) {
|
|
679
|
+
parts.push(`Recent Assistant: ${state.previous_assistant.trim()}`);
|
|
680
|
+
}
|
|
681
|
+
if (isRecord(state.step) && state.step.type === "tool_step") {
|
|
682
|
+
const step = state.step;
|
|
683
|
+
const toolName = isRecord(step.tool_call) && typeof step.tool_call.name === "string" ? step.tool_call.name : "";
|
|
684
|
+
const toolOutput = typeof step.last_tool_output_tail === "string" ? step.last_tool_output_tail : "";
|
|
685
|
+
if (toolName || toolOutput) {
|
|
686
|
+
parts.push(`Recent Tool Call: ${toolName}\nTool Output: ${toolOutput}`.trim());
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
return parts.length > 0 ? parts.join("\n\n") : JSON.stringify(state);
|
|
690
|
+
}
|
|
691
|
+
|
|
631
692
|
export async function resolveJevDecision(options: ResolveJevDecisionOptions): Promise<JevDecision> {
|
|
632
693
|
const now = options.now ?? Date.now;
|
|
633
694
|
const startedAt = now();
|
|
@@ -641,15 +702,46 @@ export async function resolveJevDecision(options: ResolveJevDecisionOptions): Pr
|
|
|
641
702
|
|
|
642
703
|
let candidates = options.candidates;
|
|
643
704
|
const exchanged = await exchangeJevDecision(options, (endpoint) => {
|
|
644
|
-
|
|
705
|
+
const isDecisions = Boolean(endpoint.url && isDecisionsEndpoint(endpoint.url));
|
|
706
|
+
const optionCount = candidateOptions(options.candidates).size;
|
|
707
|
+
if (isDecisions) {
|
|
708
|
+
if (optionCount < DECISIONS_MIN_OPTIONS) return "no_choices";
|
|
709
|
+
if (optionCount > DECISIONS_MAX_OPTIONS) return "invalid";
|
|
710
|
+
} else if (endpoint.descriptiveCriteria) {
|
|
645
711
|
// Self-hosted choice questions accept 2..26 options; decide locally instead of spending a
|
|
646
712
|
// round-trip on a request the service will refuse.
|
|
647
|
-
const optionCount = candidateOptions(options.candidates).size;
|
|
648
713
|
if (optionCount < SELF_HOSTED_MIN_OPTIONS) return "no_choices";
|
|
649
714
|
if (optionCount > SELF_HOSTED_MAX_OPTIONS) return "invalid";
|
|
650
715
|
}
|
|
651
716
|
const state = buildJevState(options.body, options.candidates);
|
|
652
717
|
if (!hasJevDecisionState(state)) return "no_state";
|
|
718
|
+
if (isDecisions && endpoint.url) {
|
|
719
|
+
const payload = boundedJevQuotaPayload(jevQuotaCandidates(options), rows => {
|
|
720
|
+
const routeOptions = candidateOptions(rows);
|
|
721
|
+
return JSON.stringify({
|
|
722
|
+
model: endpoint.model,
|
|
723
|
+
input: formatDecisionsInput(state),
|
|
724
|
+
questions: [
|
|
725
|
+
{
|
|
726
|
+
name: "route",
|
|
727
|
+
type: "choice",
|
|
728
|
+
instructions: "Which target AND reasoning effort together best fit the next model call? Select sufficient capability and reasoning for a correct next step while avoiding unnecessary resource use.",
|
|
729
|
+
choices: [...routeOptions.entries()].map(([choice, opt]) => {
|
|
730
|
+
const cand = rows.find(r => r.key === opt.targetKey);
|
|
731
|
+
const desc = criterionDescription(opt.criterion, cand?.quota);
|
|
732
|
+
const note = cand?.modelProfile?.trim();
|
|
733
|
+
return {
|
|
734
|
+
value: choice,
|
|
735
|
+
description: note ? `${desc} (${note})` : desc,
|
|
736
|
+
};
|
|
737
|
+
}),
|
|
738
|
+
},
|
|
739
|
+
],
|
|
740
|
+
});
|
|
741
|
+
}, REQUEST_LIMIT);
|
|
742
|
+
candidates = payload.candidates;
|
|
743
|
+
return { body: payload.body };
|
|
744
|
+
}
|
|
653
745
|
const payload = boundedJevQuotaPayload(jevQuotaCandidates(options), rows => JSON.stringify({
|
|
654
746
|
model: endpoint.model, state,
|
|
655
747
|
questions: buildJevRouteQuestion(rows, { descriptiveCriteria: endpoint.descriptiveCriteria }),
|