@bitkyc08/opencodex 2.96.0 → 2.98.0-preview.20261107
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 +215 -20
- package/gui/dist/assets/App-6TFtZsUF.css +1 -0
- package/gui/dist/assets/App-B8_sOxoz.js +59 -0
- package/gui/dist/assets/Tray-DpWEp6ee.js +1 -0
- package/gui/dist/assets/WantedSansVariable.split.0-Dwvb1WRx.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.1-1wKD2RxI.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.10-CAKA6LIP.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.11-k5H85R4b.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.12-BHboLsUv.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.13-9GV377ix.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.14-DovDXnrj.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.15-DTdykCig.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.16-CKz2ccgK.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.17-Z2RD_KRZ.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.18-BcKtfonJ.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.19-DEQPOSZn.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.2-DryboyuA.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.20-Bia5JMls.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.21-Cr4jFw-E.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.22-DjjB69TZ.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.23-CvUzJskt.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.24-i_eMg5ox.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.25-2aKHwPX-.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.26-B6wXoCEL.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.27-D4h1WfGM.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.28-kvRPCStd.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.29-DHAiwleD.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.3-7H--eyZi.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.30-C66cfAY2.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.31-FDmtiNim.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.32-DouHt2Dd.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.33-B8HVvkJX.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.34-BtkRu1FN.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.35-DBylQbtk.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.36-Sg089Kgh.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.37-CYtvbriS.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.38-DKkSLf8Z.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.39-CecotKZD.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.4-Bv8O3ZMb.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.40-DdCvkmOU.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.41-ESn674Hc.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.42-DL9V7NNV.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.43-yipO0cyk.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.44-6rTmLZhm.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.45-BJAj8lrm.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.46-BDTzMn2c.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.47-Bxd4wGgi.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.48-DxnFBLnH.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.49-DnVD0aOD.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.5-B1wI2pp5.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.50-D9JlkZd6.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.51-D9Vw6Bu3.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.52-ClEJk4kn.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.53-BSXU0vh-.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.54-EcuxkR9v.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.55-CYiFhQX8.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.56--Gk9g8BK.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.57-DnkOPZcy.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.58-9MB8504z.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.59-ByxIsN72.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.6-Bmk0dRVw.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.60-Bxwx_aWQ.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.61-DA2z5sm7.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.62-C5iJPJZn.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.63-DAqrmaEc.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.64-BgXFsljb.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.65-DKiWujvu.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.66-8po4vUZ4.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.67-Cy5qyI9O.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.68-BKny7Fy3.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.69-B4VU4u_b.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.7-BuqwNpgA.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.70-BCd4n346.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.71-CkQppaWn.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.72-Db7vaoFs.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.73-DI80TYWl.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.74-tMCtDAHB.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.75-Ciw0D5WG.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.76-DoLjFgp-.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.77-CpT2uvMy.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.78-CkcJ4iZ1.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.79-DsOUJjEM.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.8-DsjypPd6.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.80-C0VwHTte.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.81-DTelu57i.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.82-BiMndGN1.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.83-CVcC6eDG.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.84-DlhZVt_O.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.85-S8I2D3pA.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.86-DozXXpH5.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.87-Dsn0Vuuo.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.88-iNwxxDCr.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.89-B63u_9CZ.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.9-Bi3IzpMI.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.90-ByeH1Pqf.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.91-UQLlagpm.woff2 +0 -0
- package/gui/dist/assets/brand-mark-VPhzz-WE.js +1 -0
- package/gui/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
- package/gui/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
- package/gui/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
- package/gui/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
- package/gui/dist/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
- package/gui/dist/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
- package/gui/dist/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
- package/gui/dist/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
- package/gui/dist/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
- package/gui/dist/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
- package/gui/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
- package/gui/dist/assets/index-5REODpG3.css +2 -0
- package/gui/dist/assets/index-BWKBeK77.js +94 -0
- package/gui/dist/assets/segment-thumb-features-BQYzrze9.js +1 -0
- package/gui/dist/classic/assets/App-Bz65x1J6.js +58 -0
- package/gui/dist/{assets/Tray-BOPQyDbH.js → classic/assets/Tray-kk7mdO6I.js} +1 -1
- package/gui/dist/classic/assets/index-Dp2j8bSc.js +94 -0
- package/gui/dist/classic/assets/quota-summary-CvamtHjB.js +1 -0
- package/gui/dist/classic/index.html +47 -0
- package/gui/dist/favicon.png +0 -0
- package/gui/dist/favicon.svg +14 -0
- package/gui/dist/index.html +15 -2
- package/package.json +1 -1
- package/src/adapters/anthropic.ts +17 -8
- package/src/adapters/command-code.ts +15 -16
- package/src/adapters/cursor/transport-retry.ts +2 -2
- package/src/adapters/devin/cloud-direct/chat.ts +15 -6
- package/src/adapters/google.ts +7 -7
- package/src/adapters/kiro/adapter.ts +18 -3
- package/src/adapters/kiro/conversation.ts +8 -8
- package/src/adapters/kiro/payload.ts +45 -12
- package/src/adapters/kiro/stream.ts +230 -14
- package/src/adapters/kiro/structured-output-json.ts +191 -0
- package/src/adapters/kiro/structured-output-schema.ts +542 -0
- package/src/adapters/kiro/structured-output.ts +367 -0
- package/src/adapters/kiro-constants.ts +24 -1
- package/src/adapters/kiro-events.ts +31 -1
- package/src/adapters/kiro-retry.ts +3 -3
- package/src/adapters/kiro-tools.ts +14 -9
- package/src/adapters/kiro-wire.ts +9 -5
- package/src/adapters/ollama-native.ts +11 -1
- package/src/adapters/openai-chat/messages.ts +58 -5
- package/src/adapters/openai-chat/mistral-image-limit.ts +50 -0
- package/src/adapters/openai-chat/passthrough.ts +5 -3
- package/src/adapters/openai-chat/tool-schema.ts +83 -13
- package/src/adapters/openai-responses/empty-assistant.ts +15 -3
- package/src/adapters/openai-responses/opengateway-input.ts +18 -6
- package/src/adapters/openai-responses/passthrough.ts +5 -4
- package/src/adapters/openai-responses/reasoning.ts +9 -4
- package/src/adapters/openai-responses/request-strips.ts +1 -1
- package/src/adapters/openai-responses/tool-output-recovery.ts +79 -0
- package/src/adapters/physical-send.ts +3 -3
- package/src/adapters/qoder/live-models.ts +115 -1
- package/src/adapters/zed-openai-stream.ts +2 -1
- package/src/bridge/errors.ts +11 -2
- package/src/bridge/response-json.ts +2 -1
- package/src/bridge/sse.ts +14 -6
- package/src/chat/failure-verdict.ts +21 -0
- package/src/chat/outbound.ts +139 -21
- package/src/claude/failure-verdict.ts +21 -0
- package/src/claude/inbound-content-options.ts +15 -2
- package/src/claude/inbound-model-options.ts +2 -1
- package/src/claude/inbound-records.ts +2 -0
- package/src/claude/inbound.ts +17 -11
- package/src/claude/outbound.ts +98 -22
- package/src/cli/capabilities-access-remote.ts +13 -0
- package/src/cli/capabilities-base.ts +26 -3
- package/src/cli/capabilities-command.ts +12 -3
- package/src/cli/capabilities-provider-models.ts +3 -3
- package/src/cli/capability-contracts.ts +2 -0
- package/src/cli/codex-launch-auth.ts +30 -1
- package/src/cli/codex-launcher.ts +12 -5
- package/src/cli/codex-shim-autorestore.ts +12 -4
- package/src/cli/config-command.ts +11 -2
- package/src/cli/connect.ts +17 -2
- package/src/cli/dispatch.ts +14 -177
- package/src/cli/doctor.ts +95 -7
- package/src/cli/help.ts +2 -2
- package/src/cli/index.ts +17 -8
- package/src/cli/link-apply-restart.ts +9 -2
- package/src/cli/link.ts +1 -1
- package/src/cli/models.ts +124 -38
- package/src/cli/registry.ts +12 -4
- package/src/cli/restart-failure.ts +17 -0
- package/src/cli/root.ts +8 -0
- package/src/cli/stop-approval.ts +2 -2
- package/src/cli/sync-command.ts +243 -0
- package/src/cli/sync-fanout-process.ts +92 -0
- package/src/cli/sync-fanout.ts +161 -0
- package/src/cli/sync-flags.ts +10 -0
- package/src/cli/sync-link-status.ts +39 -0
- package/src/cli/sync-update-guard.ts +18 -0
- package/src/cli/system-restart-client.ts +5 -0
- package/src/cli/uninstall-client-state.ts +12 -1
- package/src/cli/update-restart-child.ts +13 -3
- package/src/cli/update-restart-home.ts +6 -3
- package/src/cli/update-restart.ts +36 -19
- package/src/client/connect.ts +35 -15
- package/src/client/hub-client.ts +5 -0
- package/src/client/link-home.ts +3 -2
- package/src/client/link-management-relay.ts +39 -2
- package/src/client/link-readiness.ts +3 -1
- package/src/client/machine-api.ts +2 -1
- package/src/client/machine-listener.ts +10 -0
- package/src/client/orphan-token-recovery.ts +322 -0
- package/src/client/restore-ownership.ts +19 -1
- package/src/client/runtime-restart.ts +12 -4
- package/src/client/runtime.ts +40 -11
- package/src/client/stop-routing.ts +62 -0
- package/src/client/sync-runtime.ts +65 -0
- package/src/clients/config-export.ts +32 -3
- package/src/codex/auth-context.ts +49 -103
- package/src/codex/catalog/antigravity-discovery.ts +16 -5
- package/src/codex/catalog/provider-models.ts +18 -12
- package/src/codex/forward-transport-headers.ts +35 -6
- package/src/codex/inject/config-toml.ts +88 -0
- package/src/codex/inject/multi-agent-v2.ts +30 -4
- package/src/codex/inject/plan.ts +34 -7
- package/src/codex/inject-coordination.ts +11 -0
- package/src/codex/inject.ts +18 -7
- package/src/codex/lineage.ts +13 -7
- package/src/codex/native-profile-api.ts +27 -1
- package/src/codex/quota.ts +22 -6
- package/src/codex/request-owned-affinity-key.ts +11 -0
- package/src/codex/request-owned-affinity.ts +118 -0
- package/src/codex/request-owned-main-pin.ts +86 -0
- package/src/codex/role-capability.ts +52 -41
- package/src/codex/routing/active-account.ts +13 -5
- package/src/codex/routing/selection.ts +40 -1
- package/src/codex/routing/thread-affinity-store.ts +916 -0
- package/src/codex/routing/thread-affinity.ts +90 -12
- package/src/codex/shim-diagnostics.ts +7 -0
- package/src/codex/shim-legacy-record.ts +290 -0
- package/src/codex/shim-windows-refresh.ts +9 -2
- package/src/codex/shim-wrapper-write.ts +7 -0
- package/src/codex/shim.ts +80 -21
- package/src/codex/toml-source-lines.ts +72 -13
- package/src/combos/failover.ts +6 -109
- package/src/combos/request.ts +2 -2
- package/src/combos/resolve.ts +29 -11
- package/src/config/diagnostics.ts +9 -9
- package/src/config/load-degrade.ts +27 -27
- package/src/config/process-state.ts +5 -0
- package/src/config/provider-validation.ts +9 -2
- package/src/config/removed-opencode-free-backup.ts +6 -3
- package/src/config/schema/leaf-validators.ts +1 -0
- package/src/config/tracked-runtime-inspection.ts +3 -3
- package/src/generated/compatibility-version.json +595 -255
- package/src/images/loop.ts +4 -3
- package/src/lib/client-error-body.ts +215 -0
- package/src/lib/client-retry-after.ts +66 -0
- package/src/lib/config-ownership-removal.ts +422 -0
- package/src/lib/config-ownership.ts +650 -81
- package/src/lib/context-overflow-verdict.ts +113 -0
- package/src/lib/crash-guard.ts +4 -2
- package/src/lib/desktop-cli-handoff.d.mts +4 -5
- package/src/lib/desktop-cli-handoff.mjs +18 -17
- package/src/lib/empty-tool-catalog.ts +25 -3
- package/src/lib/error-destination.ts +47 -0
- package/src/lib/errors.ts +1 -0
- package/src/lib/failure-detail.ts +66 -0
- package/src/lib/local-management-capability.ts +3 -1
- package/src/lib/messages-error-body.ts +162 -0
- package/src/lib/messages-sse-error-presentation.ts +93 -0
- package/src/lib/model-identity.ts +44 -0
- package/src/lib/passive-read.ts +9 -4
- package/src/lib/private-sqlite-path.ts +124 -0
- package/src/lib/response-service-tier.ts +17 -0
- package/src/lib/retry-after.ts +3 -0
- package/src/lib/socks5-fetch.ts +21 -9
- package/src/lib/spend-ledger-owner.ts +43 -4
- package/src/lib/upstream-condition.ts +142 -0
- package/src/lib/upstream-retry.ts +95 -12
- package/src/lib/windows-owner-acl.ts +22 -9
- package/src/lib/winsw.ts +5 -5
- package/src/lib/workflow-budget.ts +3 -1
- package/src/link/remote-platform.ts +14 -0
- package/src/link/remote-windows.ts +51 -9
- package/src/link/ssh-argv.ts +63 -10
- package/src/oauth/generic-account-failover.ts +13 -11
- package/src/oauth/index.ts +42 -73
- package/src/oauth/oauth-errors.ts +67 -0
- package/src/oauth/store.ts +21 -11
- package/src/protocols/codecs/messages-ir.ts +15 -9
- package/src/protocols/codecs/ollama.ts +197 -0
- package/src/protocols/encoders/adapter-events.ts +30 -7
- package/src/protocols/encoders/chat.ts +18 -10
- package/src/protocols/encoders/messages.ts +72 -28
- package/src/protocols/trace.ts +18 -0
- package/src/providers/antigravity-models.ts +45 -12
- package/src/providers/fastwire.ts +3 -2
- package/src/providers/free-directory.ts +2 -2
- package/src/providers/quota/anthropic-usage-windows.ts +13 -3
- package/src/providers/quota/vendor-probes-key.ts +60 -24
- package/src/providers/reasoning-metadata.ts +2 -1
- package/src/providers/registry/entries-extended.ts +9 -0
- package/src/providers/request-pacing.ts +3 -2
- package/src/reasoning-effort.ts +7 -2
- package/src/remote/hub-usage.ts +3 -0
- package/src/responses/apply-patch-envelope.ts +45 -19
- package/src/responses/compaction-history-framing.ts +5 -1
- package/src/responses/freeform-wrapper-scan.ts +5 -3
- package/src/responses/progressive-freeform-input.ts +354 -45
- package/src/routing/fallback-policy.ts +3 -1
- package/src/server/admission-model-scope.ts +17 -6
- package/src/server/admitted-http-turn.ts +57 -0
- package/src/server/anthropic-rate-limit-headers.ts +75 -3
- package/src/server/auth-cors.ts +5 -0
- package/src/server/chat-completions.ts +45 -20
- package/src/server/chat-native-sse.ts +52 -7
- package/src/server/chat-native.ts +60 -35
- package/src/server/claude-bridge-pool-session.ts +59 -0
- package/src/server/claude-messages.ts +174 -84
- package/src/server/context-history.ts +5 -1
- package/src/server/gui-static.ts +4 -1
- package/src/server/hub-usage.ts +7 -2
- package/src/server/inbound-body-admission.ts +11 -4
- package/src/server/index/link-management.ts +8 -0
- package/src/server/index/ollama-routes.ts +91 -0
- package/src/server/index/serve-options.ts +44 -24
- package/src/server/index/startup-warnings.ts +5 -12
- package/src/server/index/websocket-handler.ts +5 -2
- package/src/server/index.ts +6 -36
- package/src/server/inference/client-encoder-delivery.ts +9 -3
- package/src/server/json-serialized-bytes.ts +44 -0
- package/src/server/management/agent-settings-routes.ts +24 -21
- package/src/server/management/codex-cli-update-routes.ts +2 -1
- package/src/server/management/logs-usage-routes.ts +89 -4
- package/src/server/management/provider-routes.ts +2 -22
- package/src/server/management/qoder-provider-probe.ts +105 -0
- package/src/server/management/route-registry.ts +4 -1
- package/src/server/management/usage-aggregate-cache.ts +15 -5
- package/src/server/management/usage-source-facets.ts +38 -0
- package/src/server/messages-native-scope.ts +2 -1
- package/src/server/messages-native-tool-guard.ts +12 -4
- package/src/server/messages-native.ts +123 -47
- package/src/server/messages-response-headers.ts +25 -11
- package/src/server/messages-shared.ts +99 -65
- package/src/server/messages-sse-error-filter.ts +199 -0
- package/src/server/native-final-log.ts +93 -0
- package/src/server/ollama-inbound.ts +349 -0
- package/src/server/ollama-native-paths.ts +21 -0
- package/src/server/ollama-route-policy.ts +73 -0
- package/src/server/relay.ts +22 -3
- package/src/server/request-decompress.ts +4 -2
- package/src/server/request-log-failure-attribution.ts +22 -0
- package/src/server/request-log-failure-detail.ts +80 -0
- package/src/server/request-log-terminal-status.ts +4 -2
- package/src/server/request-log.ts +91 -42
- package/src/server/response-log-body.ts +6 -1
- package/src/server/responses/account-change-state.ts +17 -6
- package/src/server/responses/adapter-continuation.ts +17 -6
- package/src/server/responses/adapter-delivery.ts +17 -10
- package/src/server/responses/adapter-dispatch.ts +32 -31
- package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
- package/src/server/responses/codex-auth-error.ts +24 -19
- package/src/server/responses/codex-ws-exchange.ts +11 -8
- package/src/server/responses/codex-ws-metadata.ts +94 -21
- package/src/server/responses/codex-ws-request.ts +3 -1
- package/src/server/responses/codex-ws-wire.ts +19 -3
- package/src/server/responses/compact.ts +57 -24
- package/src/server/responses/compaction-recovery.ts +4 -2
- package/src/server/responses/compaction-routing.ts +9 -4
- package/src/server/responses/core-auth.ts +32 -14
- package/src/server/responses/core-codex-account.ts +17 -6
- package/src/server/responses/core-combo-failure.ts +7 -1
- package/src/server/responses/core-combo-native.ts +2 -1
- package/src/server/responses/core-combo.ts +43 -27
- package/src/server/responses/core-errors.ts +24 -21
- package/src/server/responses/core-lifetime.ts +6 -3
- package/src/server/responses/core-normalize.ts +1 -0
- package/src/server/responses/core-options.ts +9 -0
- package/src/server/responses/core-pipeline.ts +4 -3
- package/src/server/responses/empty-completion-guard.ts +4 -1
- package/src/server/responses/fetch-helpers.ts +7 -1
- package/src/server/responses/input-admission.ts +28 -2
- package/src/server/responses/native-injection.ts +1 -1
- package/src/server/responses/native-response-json.ts +13 -4
- package/src/server/responses/native-response-output.ts +1 -2
- package/src/server/responses/non-replayable-error.ts +2 -1
- package/src/server/responses/pacing-overload.ts +3 -2
- package/src/server/responses/passthrough-delivery.ts +55 -14
- package/src/server/responses/passthrough-dispatch.ts +20 -18
- package/src/server/responses/passthrough-error.ts +9 -9
- package/src/server/responses/policy-fallback.ts +2 -1
- package/src/server/responses/request-prepare.ts +69 -48
- package/src/server/responses/request-transport.ts +36 -31
- package/src/server/responses/response-effects.ts +3 -2
- package/src/server/responses/run-turn-execution.ts +6 -6
- package/src/server/responses/sidecar-execution.ts +16 -12
- package/src/server/responses/spend-storage-error.ts +2 -1
- package/src/server/responses/terminal-guard.ts +30 -0
- package/src/server/responses/ws-upstream.ts +9 -0
- package/src/server/responses-custom-tool-repair.ts +14 -3
- package/src/server/responses-terminal-repair.ts +5 -2
- package/src/server/responses-undeclared-tool-guard.ts +39 -16
- package/src/server/restart-replacement.ts +3 -1
- package/src/server/safe-response-headers.ts +162 -13
- package/src/server/sse-payload-rewrite.ts +23 -11
- package/src/server/turn-state-handles.ts +164 -0
- package/src/server/workflow-refusal.ts +2 -1
- package/src/server/ws-bridge.ts +4 -0
- package/src/service/definition.ts +36 -4
- package/src/service/launchd.ts +89 -32
- package/src/service/logging.ts +34 -7
- package/src/service/ownership-mutation-lease.d.mts +11 -2
- package/src/service/ownership-mutation-lease.mjs +53 -11
- package/src/service/plist-xml.ts +59 -0
- package/src/service/state.ts +8 -0
- package/src/service/systemd-env.ts +2 -0
- package/src/service/systemd.ts +31 -7
- package/src/service/windows-taskxml.ts +16 -7
- package/src/service-manager-probe.ts +4 -10
- package/src/types/config.ts +2 -0
- package/src/types/provider.ts +2 -0
- package/src/types/request.ts +13 -1
- package/src/update/config-preflight.ts +48 -0
- package/src/update/index.ts +148 -26
- package/src/update/npm-install.d.mts +8 -0
- package/src/update/npm-install.mjs +20 -1
- package/src/update/orchestrated-admission.d.mts +4 -0
- package/src/update/orchestrated-admission.mjs +12 -0
- package/src/update/orchestrated-arguments.d.mts +12 -0
- package/src/update/orchestrated-arguments.mjs +64 -0
- package/src/update/orchestrated-child.d.mts +12 -0
- package/src/update/orchestrated-child.mjs +70 -0
- package/src/update/orchestrated-entry.ts +234 -0
- package/src/update/orchestrated-identity-probe-entry.ts +20 -0
- package/src/update/orchestrated-identity.ts +53 -0
- package/src/update/orchestrated-live-identity.ts +48 -0
- package/src/update/orchestrated-node-driver.mjs +99 -0
- package/src/update/orchestrated-outcome.d.mts +21 -0
- package/src/update/orchestrated-outcome.mjs +40 -0
- package/src/update/orchestrated-plan.ts +49 -0
- package/src/update/orchestrated-pnpm.d.mts +8 -0
- package/src/update/orchestrated-pnpm.mjs +33 -0
- package/src/update/orchestrated-session.d.mts +37 -0
- package/src/update/orchestrated-session.mjs +264 -0
- package/src/update/orchestrated-token.d.mts +10 -0
- package/src/update/orchestrated-token.mjs +21 -0
- package/src/update/orchestrated-token.ts +3 -0
- package/src/update/orchestrated-tree.d.mts +1 -0
- package/src/update/orchestrated-tree.mjs +14 -0
- package/src/update/pnpm-global-install.d.mts +6 -0
- package/src/update/pnpm-global-install.mjs +9 -2
- package/src/update/posix-install-supervisor-entry.mjs +6 -0
- package/src/update/posix-install-supervisor.d.mts +10 -0
- package/src/update/posix-install-supervisor.mjs +88 -0
- package/src/update/sync-update-mutex.d.mts +10 -0
- package/src/update/sync-update-mutex.mjs +164 -0
- package/src/update/sync-update-mutex.ts +1 -0
- package/src/update/test-home-guard.mjs +33 -0
- package/src/update/transactional-install.mjs +2 -2
- package/src/usage/client.ts +43 -0
- package/src/usage/error-detail.ts +225 -0
- package/src/usage/log.ts +64 -27
- package/src/usage/source-facets.ts +51 -0
- package/src/usage/source-filter.ts +65 -0
- package/src/usage/summary.ts +50 -8
- package/src/web-search/anthropic-executor.ts +105 -24
- package/src/web-search/executor.ts +5 -3
- package/src/web-search/loop.ts +33 -6
- package/src/web-search/progress-stream.ts +64 -5
- package/gui/dist/assets/App-bwugJRKn.js +0 -58
- package/gui/dist/assets/index-ebuVUtB7.js +0 -94
- package/gui/dist/assets/quota-summary-6HsrHQAy.js +0 -1
- /package/gui/dist/{assets → classic/assets}/App-B4j-Txmb.css +0 -0
- /package/gui/dist/{assets → classic/assets}/index-CHWwDo9L.css +0 -0
|
@@ -0,0 +1,916 @@
|
|
|
1
|
+
import { Database } from "bun:sqlite";
|
|
2
|
+
import { createHash, createHmac, randomBytes } from "node:crypto";
|
|
3
|
+
import {
|
|
4
|
+
chmodSync,
|
|
5
|
+
lstatSync,
|
|
6
|
+
realpathSync,
|
|
7
|
+
} from "node:fs";
|
|
8
|
+
import { resolve } from "node:path";
|
|
9
|
+
import { getConfigDir } from "../../config/paths";
|
|
10
|
+
import { initializeConfigOwnership, recordOwnedConfigPath } from "../../lib/config-ownership";
|
|
11
|
+
import { sameFileIdentity, type FileIdentity } from "../../lib/file-identity";
|
|
12
|
+
import { isPassiveRead } from "../../lib/passive-read";
|
|
13
|
+
import { assertPrivateSqliteEntryOrMissing, assertPrivateSqliteSidecars, preparePrivateSqliteDatabase } from "../../lib/private-sqlite-path";
|
|
14
|
+
import {
|
|
15
|
+
assertStorageOwned,
|
|
16
|
+
currentSpendLedgerOwnerGeneration,
|
|
17
|
+
mintSpendLedgerStorage,
|
|
18
|
+
onSpendLedgerOwnerAcquired,
|
|
19
|
+
onSpendLedgerOwnerReleased,
|
|
20
|
+
onSpendLedgerOwnerReleasing,
|
|
21
|
+
spendLedgerStoragePath,
|
|
22
|
+
type SpendLedgerStorage,
|
|
23
|
+
} from "../../lib/spend-ledger-owner";
|
|
24
|
+
import { assertNotRealHomeUnderTest } from "../../lib/test-home-guard";
|
|
25
|
+
import { hardenSecretPath } from "../../lib/windows-secret-acl";
|
|
26
|
+
import { readCodexAccountRecord } from "../account-store";
|
|
27
|
+
import { isRequestOwnedAffinityKey } from "../request-owned-affinity-key";
|
|
28
|
+
import { setCodexConversationAnchorObserver } from "../lineage";
|
|
29
|
+
import type { CodexQuotaScope } from "./health-store";
|
|
30
|
+
|
|
31
|
+
export type StoredThreadRow = {
|
|
32
|
+
scope: string;
|
|
33
|
+
accountId: string;
|
|
34
|
+
fence: string;
|
|
35
|
+
createdAt: number;
|
|
36
|
+
lastUsedAt: number;
|
|
37
|
+
};
|
|
38
|
+
export const CODEX_UNKNOWN_CONVERSATION_STATE_ISSUER =
|
|
39
|
+
"__unknown_codex_conversation_state_issuer__";
|
|
40
|
+
type LiveReader = {
|
|
41
|
+
thread(
|
|
42
|
+
key: string,
|
|
43
|
+
scope: string,
|
|
44
|
+
):
|
|
45
|
+
| {
|
|
46
|
+
accountId: string;
|
|
47
|
+
identityFence?: string;
|
|
48
|
+
createdAt: number;
|
|
49
|
+
lastUsedAt: number;
|
|
50
|
+
}
|
|
51
|
+
| undefined;
|
|
52
|
+
issuer(
|
|
53
|
+
key: string,
|
|
54
|
+
): { accountId: string; fence?: string; lastUsedAt: number } | undefined;
|
|
55
|
+
clearLive(): void;
|
|
56
|
+
};
|
|
57
|
+
type Op = {
|
|
58
|
+
sql: string;
|
|
59
|
+
args: (string | number | null)[];
|
|
60
|
+
key?: string;
|
|
61
|
+
scope?: string;
|
|
62
|
+
kind: string;
|
|
63
|
+
};
|
|
64
|
+
type Scope = {
|
|
65
|
+
home: string;
|
|
66
|
+
generation: number;
|
|
67
|
+
token: SpendLedgerStorage;
|
|
68
|
+
db?: Database;
|
|
69
|
+
/** The database file the handle was opened on; every write transaction re-checks the path against it. */
|
|
70
|
+
file?: FileIdentity;
|
|
71
|
+
secret?: Uint8Array;
|
|
72
|
+
disabled: boolean;
|
|
73
|
+
poisoned: boolean;
|
|
74
|
+
failures: number;
|
|
75
|
+
log: Op[];
|
|
76
|
+
threads: Map<string, { key: string; scope: string; rowKey: string }>;
|
|
77
|
+
issuers: Map<string, { key: string; rowKey: string }>;
|
|
78
|
+
anchors: Map<string, { family: string; thread: string; at: number }>;
|
|
79
|
+
threadKeys: Map<string, { rowKey: string; scopes: Map<string, string> }>;
|
|
80
|
+
issuerKeys: Map<string, string>;
|
|
81
|
+
consulted: Set<string>;
|
|
82
|
+
timer?: ReturnType<typeof setTimeout>;
|
|
83
|
+
pruneTimer?: ReturnType<typeof setInterval>;
|
|
84
|
+
scheduled: boolean;
|
|
85
|
+
};
|
|
86
|
+
const TTL = 24 * 60 * 60_000;
|
|
87
|
+
const BASE_SCOPES = [
|
|
88
|
+
"shared",
|
|
89
|
+
"reserve",
|
|
90
|
+
] as const satisfies readonly CodexQuotaScope[];
|
|
91
|
+
const BASE_SCOPES_EXHAUSTIVE: Exclude<
|
|
92
|
+
CodexQuotaScope,
|
|
93
|
+
(typeof BASE_SCOPES)[number]
|
|
94
|
+
> extends never
|
|
95
|
+
? true
|
|
96
|
+
: never = true;
|
|
97
|
+
void BASE_SCOPES_EXHAUSTIVE;
|
|
98
|
+
let current: Scope | undefined;
|
|
99
|
+
let observedHome: string | undefined;
|
|
100
|
+
/** The home whose database the most recent scope in this process actually opened. */
|
|
101
|
+
let persistedHome: string | undefined;
|
|
102
|
+
/**
|
|
103
|
+
* A persistable change to pins or issuers happened while that home's database was not writable
|
|
104
|
+
* (between leases, or while a scope could not open it). The database may still hold the row the
|
|
105
|
+
* change replaced or deleted, so the next scope that opens it clears it first. Live memory keeps
|
|
106
|
+
* routing as before; a later restart then restores nothing rather than something stale. Only a
|
|
107
|
+
* process that releases and reacquires its lease reaches this: a serving proxy holds one lease for
|
|
108
|
+
* its whole life.
|
|
109
|
+
*/
|
|
110
|
+
let needsClear = false;
|
|
111
|
+
/** Anchors of the last retired scope, handed to the next scope of the same home. */
|
|
112
|
+
let carried: { home: string; anchors: Scope["anchors"]; threadKeys: Scope["threadKeys"]; issuerKeys: Scope["issuerKeys"] } | undefined;
|
|
113
|
+
let reader: LiveReader | undefined;
|
|
114
|
+
|
|
115
|
+
export function registerCodexAffinityLiveState(value: LiveReader): void {
|
|
116
|
+
reader = value;
|
|
117
|
+
setCodexConversationAnchorObserver(observeAnchor);
|
|
118
|
+
}
|
|
119
|
+
function warning(): void {
|
|
120
|
+
console.warn("Codex affinity persistence unavailable; continuing in memory.");
|
|
121
|
+
}
|
|
122
|
+
/** Retire the lease-scoped handle without discarding in-memory affinity. */
|
|
123
|
+
function retire(): void {
|
|
124
|
+
const s = current;
|
|
125
|
+
if (!s) return;
|
|
126
|
+
current = undefined;
|
|
127
|
+
// Anchors are process-local facts about this home's conversations; the next scope of the same
|
|
128
|
+
// home needs them to re-derive row keys for pins that are still live in memory.
|
|
129
|
+
// Row keys too: after an anchor is evicted they are the only way a delete can still reach its row.
|
|
130
|
+
if (s.db && !s.poisoned) carried = { home: s.home, anchors: s.anchors, threadKeys: s.threadKeys, issuerKeys: s.issuerKeys };
|
|
131
|
+
if (s.timer) clearTimeout(s.timer);
|
|
132
|
+
if (s.pruneTimer) clearInterval(s.pruneTimer);
|
|
133
|
+
try {
|
|
134
|
+
s.db?.close();
|
|
135
|
+
} catch {
|
|
136
|
+
warning();
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
// BigInt stats: NTFS file IDs exceed Number.MAX_SAFE_INTEGER, and a rounded identity can match a
|
|
140
|
+
// different file.
|
|
141
|
+
function checkFile(path: string) {
|
|
142
|
+
const stat = lstatSync(path, { bigint: true });
|
|
143
|
+
if (
|
|
144
|
+
!stat.isFile() ||
|
|
145
|
+
stat.isSymbolicLink() ||
|
|
146
|
+
stat.nlink !== 1n ||
|
|
147
|
+
(process.platform !== "win32" && stat.uid !== BigInt(process.getuid!()))
|
|
148
|
+
)
|
|
149
|
+
throw new Error("unsafe file");
|
|
150
|
+
return stat;
|
|
151
|
+
}
|
|
152
|
+
function open(s: Scope): void {
|
|
153
|
+
const path = spendLedgerStoragePath(s.token);
|
|
154
|
+
let db: Database | undefined;
|
|
155
|
+
try {
|
|
156
|
+
assertNotRealHomeUnderTest(s.home);
|
|
157
|
+
// An owned home must list these files before they exist, so uninstall removes them. A home with
|
|
158
|
+
// no ownership manifest (one that predates ownership tracking) cannot record anything, and
|
|
159
|
+
// uninstall refuses to remove anything from it; like the spend-ledger owner database, the store
|
|
160
|
+
// still works there rather than silently losing persistence.
|
|
161
|
+
for (const suffix of ["", "-journal", "-wal", "-shm"])
|
|
162
|
+
if (!recordOwnedConfigPath(s.home, path + suffix) && initializeConfigOwnership(s.home))
|
|
163
|
+
throw new Error("ownership");
|
|
164
|
+
// Refuses a link or reparse point at the database or a sidecar before anything is created:
|
|
165
|
+
// Windows creates a new file through a link at its name.
|
|
166
|
+
preparePrivateSqliteDatabase(path);
|
|
167
|
+
const before = checkFile(path);
|
|
168
|
+
if (before.size > 8n * 1024n * 1024n) throw new Error("oversized");
|
|
169
|
+
if (process.platform !== "win32") chmodSync(path, 0o600);
|
|
170
|
+
if (!hardenSecretPath(path, { required: true }).ok) throw new Error("acl");
|
|
171
|
+
checkFile(path);
|
|
172
|
+
assertStorageOwned(s.token);
|
|
173
|
+
// SQLite creates sidecars in the private, hardened config directory, as with
|
|
174
|
+
// spend-ledger-owner.sqlite and config-mutation.sqlite.
|
|
175
|
+
assertPrivateSqliteSidecars(path);
|
|
176
|
+
db = new Database(path);
|
|
177
|
+
db.exec("PRAGMA busy_timeout = 0; BEGIN IMMEDIATE");
|
|
178
|
+
const version = (
|
|
179
|
+
db.query("PRAGMA user_version").get() as { user_version: number }
|
|
180
|
+
).user_version;
|
|
181
|
+
const objects = db
|
|
182
|
+
.query("SELECT type, name FROM sqlite_master ORDER BY name")
|
|
183
|
+
.all() as { type: string; name: string }[];
|
|
184
|
+
const tables = objects.filter((o) => o.type === "table");
|
|
185
|
+
if (version === 0 && objects.length === 0) {
|
|
186
|
+
db.exec(
|
|
187
|
+
"CREATE TABLE meta(name TEXT PRIMARY KEY, value BLOB); CREATE TABLE threads(row_key TEXT, scope TEXT, account_id TEXT, fence TEXT, created_at INTEGER, last_used_at INTEGER, PRIMARY KEY(row_key, scope)); CREATE TABLE issuers(row_key TEXT PRIMARY KEY, account_id TEXT, fence TEXT, last_used_at INTEGER); PRAGMA user_version = 1",
|
|
188
|
+
);
|
|
189
|
+
db.query("INSERT INTO meta VALUES ('secret', ?), ('clean', 0)").run(
|
|
190
|
+
randomBytes(32),
|
|
191
|
+
);
|
|
192
|
+
} else {
|
|
193
|
+
if (
|
|
194
|
+
version !== 1 ||
|
|
195
|
+
tables.map((t) => t.name).join(",") !== "issuers,meta,threads"
|
|
196
|
+
)
|
|
197
|
+
throw new Error("version");
|
|
198
|
+
const expected: Record<string, string> = {
|
|
199
|
+
meta: "name:TEXT:1,value:BLOB:0",
|
|
200
|
+
threads:
|
|
201
|
+
"row_key:TEXT:1,scope:TEXT:2,account_id:TEXT:0,fence:TEXT:0,created_at:INTEGER:0,last_used_at:INTEGER:0",
|
|
202
|
+
issuers:
|
|
203
|
+
"row_key:TEXT:1,account_id:TEXT:0,fence:TEXT:0,last_used_at:INTEGER:0",
|
|
204
|
+
};
|
|
205
|
+
for (const [table, columns] of Object.entries(expected)) {
|
|
206
|
+
const actual = db.query(`PRAGMA table_info(${table})`).all() as {
|
|
207
|
+
name: string;
|
|
208
|
+
type: string;
|
|
209
|
+
pk: number;
|
|
210
|
+
notnull: number;
|
|
211
|
+
dflt_value: unknown;
|
|
212
|
+
}[];
|
|
213
|
+
if (
|
|
214
|
+
actual.map((c) => `${c.name}:${c.type}:${c.pk}`).join(",") !==
|
|
215
|
+
columns ||
|
|
216
|
+
actual.some((c) => c.notnull !== 0 || c.dflt_value !== null)
|
|
217
|
+
)
|
|
218
|
+
throw new Error("shape");
|
|
219
|
+
}
|
|
220
|
+
const indexes = objects
|
|
221
|
+
.filter((o) => o.type === "index")
|
|
222
|
+
.map((o) => o.name)
|
|
223
|
+
.join(",");
|
|
224
|
+
if (
|
|
225
|
+
objects.length !== 6 ||
|
|
226
|
+
indexes !==
|
|
227
|
+
"sqlite_autoindex_issuers_1,sqlite_autoindex_meta_1,sqlite_autoindex_threads_1"
|
|
228
|
+
)
|
|
229
|
+
throw new Error("shape");
|
|
230
|
+
const rows = db.query("SELECT name, value FROM meta").all() as {
|
|
231
|
+
name: string;
|
|
232
|
+
value: unknown;
|
|
233
|
+
}[];
|
|
234
|
+
const secret = rows.find((r) => r.name === "secret")?.value;
|
|
235
|
+
const clean = rows.find((r) => r.name === "clean")?.value;
|
|
236
|
+
if (
|
|
237
|
+
!(secret instanceof Uint8Array) ||
|
|
238
|
+
secret.length !== 32 ||
|
|
239
|
+
rows.length !== 2 ||
|
|
240
|
+
!rows.some((r) => r.name === "clean")
|
|
241
|
+
)
|
|
242
|
+
throw new Error("meta");
|
|
243
|
+
db.exec("PRAGMA secure_delete = ON");
|
|
244
|
+
// Only a completed final flush permits the next owner to restore rows.
|
|
245
|
+
if (clean !== 1) db.exec("DELETE FROM threads; DELETE FROM issuers");
|
|
246
|
+
db.exec("UPDATE meta SET value=0 WHERE name='clean'");
|
|
247
|
+
}
|
|
248
|
+
db.exec("PRAGMA secure_delete = ON");
|
|
249
|
+
const pageSize = (db.query("PRAGMA page_size").get() as { page_size: number }).page_size;
|
|
250
|
+
db.exec(`PRAGMA max_page_count = ${Math.floor(8 * 1024 * 1024 / pageSize)}`);
|
|
251
|
+
prune(db, Date.now());
|
|
252
|
+
const secret = (
|
|
253
|
+
db.query("SELECT value FROM meta WHERE name='secret'").get() as {
|
|
254
|
+
value: Uint8Array;
|
|
255
|
+
}
|
|
256
|
+
).value;
|
|
257
|
+
db.exec("COMMIT");
|
|
258
|
+
const after = checkFile(path);
|
|
259
|
+
if (!sameFileIdentity(before, after)) throw new Error("replaced");
|
|
260
|
+
s.db = db;
|
|
261
|
+
s.file = after;
|
|
262
|
+
s.secret = secret;
|
|
263
|
+
s.pruneTimer = setInterval(() => {
|
|
264
|
+
if (current === s) {
|
|
265
|
+
if (s.poisoned || isPassiveRead()) pruneOnly(s);
|
|
266
|
+
else flush(s, false);
|
|
267
|
+
}
|
|
268
|
+
}, 60 * 60_000);
|
|
269
|
+
s.pruneTimer.unref();
|
|
270
|
+
} catch {
|
|
271
|
+
try {
|
|
272
|
+
db?.exec("ROLLBACK");
|
|
273
|
+
} catch {
|
|
274
|
+
/* no transaction */
|
|
275
|
+
}
|
|
276
|
+
try {
|
|
277
|
+
db?.close();
|
|
278
|
+
} catch {
|
|
279
|
+
/* preserve open failure */
|
|
280
|
+
}
|
|
281
|
+
s.disabled = true;
|
|
282
|
+
warning();
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Refuse a write unless the database is still the single-link private file this handle opened and
|
|
287
|
+
* no sidecar name holds a link: the rollback journal is created per transaction, and a link added
|
|
288
|
+
* to the database since open would expose every later write.
|
|
289
|
+
*/
|
|
290
|
+
function assertWritable(s: Scope): void {
|
|
291
|
+
const path = spendLedgerStoragePath(s.token);
|
|
292
|
+
assertPrivateSqliteSidecars(path);
|
|
293
|
+
if (!assertPrivateSqliteEntryOrMissing(path)) throw new Error("missing");
|
|
294
|
+
const now = checkFile(path);
|
|
295
|
+
if (!s.file || !sameFileIdentity(now, s.file)) throw new Error("replaced");
|
|
296
|
+
}
|
|
297
|
+
function resolvedHome(acquiredHome?: string): string {
|
|
298
|
+
let home = resolve(acquiredHome ?? getConfigDir());
|
|
299
|
+
try {
|
|
300
|
+
home = realpathSync.native(home);
|
|
301
|
+
} catch {
|
|
302
|
+
/* ownership check below refuses it */
|
|
303
|
+
}
|
|
304
|
+
return process.platform === "win32" ? home.toLowerCase() : home;
|
|
305
|
+
}
|
|
306
|
+
function scope(acquiredHome?: string): Scope | undefined {
|
|
307
|
+
if (!acquiredHome && isPassiveRead()) return undefined;
|
|
308
|
+
const home = resolvedHome(acquiredHome);
|
|
309
|
+
// A lease ends a store scope; only a change of home invalidates live maps.
|
|
310
|
+
if (observedHome !== undefined && observedHome !== home) {
|
|
311
|
+
retire();
|
|
312
|
+
carried = undefined;
|
|
313
|
+
persistedHome = undefined;
|
|
314
|
+
needsClear = false;
|
|
315
|
+
reader?.clearLive();
|
|
316
|
+
}
|
|
317
|
+
observedHome = home;
|
|
318
|
+
const generation = currentSpendLedgerOwnerGeneration();
|
|
319
|
+
if (current && (current.home !== home || current.generation !== generation))
|
|
320
|
+
retire();
|
|
321
|
+
if (current) {
|
|
322
|
+
try {
|
|
323
|
+
assertStorageOwned(current.token);
|
|
324
|
+
return current;
|
|
325
|
+
} catch {
|
|
326
|
+
retire();
|
|
327
|
+
return undefined;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
let token: SpendLedgerStorage;
|
|
331
|
+
try {
|
|
332
|
+
token = mintSpendLedgerStorage("codex-affinity.sqlite");
|
|
333
|
+
assertStorageOwned(token);
|
|
334
|
+
} catch {
|
|
335
|
+
return undefined;
|
|
336
|
+
}
|
|
337
|
+
const s: Scope = {
|
|
338
|
+
home,
|
|
339
|
+
generation,
|
|
340
|
+
token,
|
|
341
|
+
disabled: false,
|
|
342
|
+
poisoned: false,
|
|
343
|
+
failures: 0,
|
|
344
|
+
log: [],
|
|
345
|
+
threads: new Map(),
|
|
346
|
+
issuers: new Map(),
|
|
347
|
+
anchors: carried?.home === home ? carried.anchors : new Map(),
|
|
348
|
+
threadKeys: carried?.home === home ? carried.threadKeys : new Map(),
|
|
349
|
+
issuerKeys: carried?.home === home ? carried.issuerKeys : new Map(),
|
|
350
|
+
consulted: new Set(),
|
|
351
|
+
scheduled: false,
|
|
352
|
+
};
|
|
353
|
+
const prior = carried;
|
|
354
|
+
carried = undefined;
|
|
355
|
+
current = s;
|
|
356
|
+
open(s);
|
|
357
|
+
// A scope that could not open never touched the carried maps; keep them for the next one.
|
|
358
|
+
if (!s.db && prior?.home === home) carried = prior;
|
|
359
|
+
if (s.db) {
|
|
360
|
+
if (needsClear && persistedHome === home) recordAllCleared();
|
|
361
|
+
needsClear = false;
|
|
362
|
+
persistedHome = home;
|
|
363
|
+
}
|
|
364
|
+
return s;
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* The scope for a change to which pins or issuers exist. When the change could have been persisted
|
|
368
|
+
* but this home's database is not writable right now, remember that the database is stale.
|
|
369
|
+
*/
|
|
370
|
+
function writableScope(persistable: boolean): Scope | undefined {
|
|
371
|
+
const s = usable();
|
|
372
|
+
if (!s && persistable && persistedHome !== undefined && !isPassiveRead() && persistedHome === resolvedHome())
|
|
373
|
+
needsClear = true;
|
|
374
|
+
return s;
|
|
375
|
+
}
|
|
376
|
+
function usable(): Scope | undefined {
|
|
377
|
+
const s = scope();
|
|
378
|
+
return s && !s.disabled && !s.poisoned && s.db ? s : undefined;
|
|
379
|
+
}
|
|
380
|
+
function observeAnchor(key: string, family: string, thread: string): void {
|
|
381
|
+
// Caller-owned keys are process-local by contract (structure/providers/codex-request-owned-affinity.md).
|
|
382
|
+
if (isRequestOwnedAffinityKey(key)) return;
|
|
383
|
+
const s = usable();
|
|
384
|
+
if (!s) return;
|
|
385
|
+
const now = Date.now();
|
|
386
|
+
for (const [k, a] of s.anchors) {
|
|
387
|
+
if (now - a.at <= TTL) break;
|
|
388
|
+
s.anchors.delete(k);
|
|
389
|
+
}
|
|
390
|
+
s.anchors.delete(key);
|
|
391
|
+
s.anchors.set(key, { family, thread, at: now });
|
|
392
|
+
while (s.anchors.size > 4096)
|
|
393
|
+
s.anchors.delete(s.anchors.keys().next().value!);
|
|
394
|
+
}
|
|
395
|
+
setCodexConversationAnchorObserver(observeAnchor);
|
|
396
|
+
function rowKey(
|
|
397
|
+
s: Scope,
|
|
398
|
+
key: string,
|
|
399
|
+
kind: "conversation" | "issuer",
|
|
400
|
+
): string | undefined {
|
|
401
|
+
// The single choke point for every bind, touch, delete, adoption and issuer path: a request-owned
|
|
402
|
+
// key never has a durable row key, so nothing for it is ever written or restored.
|
|
403
|
+
if (isRequestOwnedAffinityKey(key)) return undefined;
|
|
404
|
+
const a = s.anchors.get(key);
|
|
405
|
+
if (!a || Date.now() - a.at > TTL) {
|
|
406
|
+
s.anchors.delete(key);
|
|
407
|
+
return kind === "conversation" ? s.threadKeys.get(key)?.rowKey : s.issuerKeys.get(key);
|
|
408
|
+
}
|
|
409
|
+
return createHmac("sha256", s.secret!)
|
|
410
|
+
.update(`opencodex/codex-affinity/${kind}/v1\0`)
|
|
411
|
+
.update(a.family)
|
|
412
|
+
.update("\0")
|
|
413
|
+
.update(a.thread)
|
|
414
|
+
.digest("hex");
|
|
415
|
+
}
|
|
416
|
+
export function codexAffinityIdentityFence(
|
|
417
|
+
accountId: string,
|
|
418
|
+
): string | undefined {
|
|
419
|
+
if (accountId === "__main__") return undefined;
|
|
420
|
+
const record = readCodexAccountRecord(accountId);
|
|
421
|
+
if (
|
|
422
|
+
!record?.credential ||
|
|
423
|
+
record.deletedAt != null ||
|
|
424
|
+
!record.quotaHistoryIdentity
|
|
425
|
+
)
|
|
426
|
+
return undefined;
|
|
427
|
+
return identityFence(record.quotaHistoryIdentity);
|
|
428
|
+
}
|
|
429
|
+
export function identityFence(identity: string | undefined): string | undefined {
|
|
430
|
+
if (!identity) return undefined;
|
|
431
|
+
return createHash("sha256")
|
|
432
|
+
.update("opencodex/codex-affinity/identity/v1\0")
|
|
433
|
+
.update(identity)
|
|
434
|
+
.digest("hex");
|
|
435
|
+
}
|
|
436
|
+
function rememberThreadKey(s: Scope, key: string, rk: string, scopeName: string, accountId: string): void {
|
|
437
|
+
let entry = s.threadKeys.get(key);
|
|
438
|
+
if (!entry) s.threadKeys.set(key, entry = { rowKey: rk, scopes: new Map() });
|
|
439
|
+
entry.scopes.set(scopeName, accountId);
|
|
440
|
+
if (s.threadKeys.size + s.issuerKeys.size > 8192) poison(s);
|
|
441
|
+
}
|
|
442
|
+
function rememberIssuerKey(s: Scope, key: string, rk: string): void {
|
|
443
|
+
s.issuerKeys.set(key, rk);
|
|
444
|
+
if (s.threadKeys.size + s.issuerKeys.size > 8192) poison(s);
|
|
445
|
+
}
|
|
446
|
+
/** A poisoned scope cannot safely declare itself clean on release. */
|
|
447
|
+
function poison(s: Scope): void {
|
|
448
|
+
s.poisoned = true;
|
|
449
|
+
s.log = [];
|
|
450
|
+
s.threads.clear();
|
|
451
|
+
s.issuers.clear();
|
|
452
|
+
s.threadKeys.clear();
|
|
453
|
+
s.issuerKeys.clear();
|
|
454
|
+
if (s.timer) clearTimeout(s.timer);
|
|
455
|
+
warning();
|
|
456
|
+
}
|
|
457
|
+
function enqueue(s: Scope, op: Op): void {
|
|
458
|
+
// Preserve structural ordering; only clearAll supersedes the whole log.
|
|
459
|
+
if (op.kind === "clearAll") s.log = [];
|
|
460
|
+
s.log.push(op);
|
|
461
|
+
if (s.log.length > 16384) {
|
|
462
|
+
poison(s);
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
if (!s.scheduled) {
|
|
466
|
+
s.scheduled = true;
|
|
467
|
+
queueMicrotask(() => {
|
|
468
|
+
s.scheduled = false;
|
|
469
|
+
if (current === s && !isPassiveRead()) flush(s, false);
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
function scheduleTouch(s: Scope): void {
|
|
474
|
+
if (s.timer) return;
|
|
475
|
+
s.timer = setTimeout(() => {
|
|
476
|
+
s.timer = undefined;
|
|
477
|
+
if (current === s && !isPassiveRead()) flush(s, false);
|
|
478
|
+
}, 1000);
|
|
479
|
+
s.timer.unref();
|
|
480
|
+
}
|
|
481
|
+
function prune(db: Database, now: number): void {
|
|
482
|
+
for (const table of ["threads", "issuers"])
|
|
483
|
+
db.query(`DELETE FROM ${table} WHERE last_used_at < ? OR last_used_at > ?`).run(now - TTL, now);
|
|
484
|
+
db.query("DELETE FROM threads WHERE created_at > ?").run(now);
|
|
485
|
+
db.exec("DELETE FROM threads WHERE rowid IN (SELECT rowid FROM threads ORDER BY (scope LIKE 'model-detour:%') ASC, last_used_at DESC, row_key, scope LIMIT -1 OFFSET 2048); DELETE FROM issuers WHERE rowid IN (SELECT rowid FROM issuers ORDER BY last_used_at DESC, row_key LIMIT -1 OFFSET 2048)");
|
|
486
|
+
}
|
|
487
|
+
function pruneOnly(s: Scope): boolean {
|
|
488
|
+
if (!s.db || s.disabled) return false;
|
|
489
|
+
try {
|
|
490
|
+
assertStorageOwned(s.token);
|
|
491
|
+
assertWritable(s);
|
|
492
|
+
s.db.exec("BEGIN IMMEDIATE");
|
|
493
|
+
// Pending touches first, so a pin used since its last persisted timestamp is not evicted as idle.
|
|
494
|
+
if (!s.poisoned) applyTouches(s, s.db);
|
|
495
|
+
prune(s.db, Date.now());
|
|
496
|
+
s.db.exec("COMMIT");
|
|
497
|
+
return true;
|
|
498
|
+
} catch {
|
|
499
|
+
try { s.db.exec("ROLLBACK"); } catch { /* no transaction */ }
|
|
500
|
+
warning();
|
|
501
|
+
return false;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
/** Write the live last-used time of every touched row; UPDATE-only, so it never creates or revives a row. */
|
|
505
|
+
function applyTouches(s: Scope, db: Database): void {
|
|
506
|
+
for (const t of s.threads.values()) {
|
|
507
|
+
const row = reader?.thread(t.key, t.scope);
|
|
508
|
+
if (row?.identityFence)
|
|
509
|
+
db.query(
|
|
510
|
+
"UPDATE threads SET last_used_at=max(last_used_at, ?) WHERE row_key=? AND scope=? AND account_id=? AND fence=?",
|
|
511
|
+
).run(
|
|
512
|
+
row.lastUsedAt,
|
|
513
|
+
t.rowKey,
|
|
514
|
+
t.scope,
|
|
515
|
+
row.accountId,
|
|
516
|
+
row.identityFence,
|
|
517
|
+
);
|
|
518
|
+
}
|
|
519
|
+
for (const t of s.issuers.values()) {
|
|
520
|
+
const row = reader?.issuer(t.key);
|
|
521
|
+
if (row)
|
|
522
|
+
db.query(
|
|
523
|
+
"UPDATE issuers SET last_used_at=max(last_used_at, ?) WHERE row_key=? AND account_id=? AND fence IS ?",
|
|
524
|
+
).run(row.lastUsedAt, t.rowKey, row.accountId, row.fence ?? null);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Commit the ordered log and touches. The final release flush (clean=true) commits work that was
|
|
529
|
+
* logged outside any passive read, so it runs even if the release happens inside one.
|
|
530
|
+
*/
|
|
531
|
+
function flush(s: Scope, clean: boolean): boolean {
|
|
532
|
+
if (!s.db || s.disabled || s.poisoned || (!clean && isPassiveRead())) return false;
|
|
533
|
+
const db = s.db;
|
|
534
|
+
for (let attempt = 0; attempt < 2; attempt++) try {
|
|
535
|
+
assertStorageOwned(s.token);
|
|
536
|
+
assertWritable(s);
|
|
537
|
+
db.exec("BEGIN IMMEDIATE");
|
|
538
|
+
// Touches go before the log as well as after it, so the pruning between chunks sees the live
|
|
539
|
+
// last-used times and cannot evict a pin that is in use but persisted with an old timestamp.
|
|
540
|
+
applyTouches(s, db);
|
|
541
|
+
for (let i = 0; i < s.log.length; i++) {
|
|
542
|
+
const op = s.log[i]!;
|
|
543
|
+
if (op.args.length) db.query(op.sql).run(...op.args);
|
|
544
|
+
else db.exec(op.sql);
|
|
545
|
+
// Touches before every chunk prune, so rows this chunk inserted carry their live last-used time.
|
|
546
|
+
if ((i + 1) % 256 === 0) {
|
|
547
|
+
applyTouches(s, db);
|
|
548
|
+
prune(db, Date.now());
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
// Again after the log: rows the log just inserted take their live last-used time.
|
|
552
|
+
applyTouches(s, db);
|
|
553
|
+
prune(db, Date.now());
|
|
554
|
+
if (clean) db.exec("UPDATE meta SET value=1 WHERE name='clean'");
|
|
555
|
+
db.exec("COMMIT");
|
|
556
|
+
s.log = [];
|
|
557
|
+
s.threads.clear();
|
|
558
|
+
s.issuers.clear();
|
|
559
|
+
s.failures = 0;
|
|
560
|
+
return true;
|
|
561
|
+
} catch (error) {
|
|
562
|
+
try {
|
|
563
|
+
db.exec("ROLLBACK");
|
|
564
|
+
} catch {
|
|
565
|
+
/* preserve failure */
|
|
566
|
+
}
|
|
567
|
+
if (attempt === 0 && error instanceof Error && "code" in error && error.code === "SQLITE_FULL" && pruneOnly(s)) continue;
|
|
568
|
+
if (++s.failures >= 3) poison(s);
|
|
569
|
+
else warning();
|
|
570
|
+
// Deleting expired rows does not depend on the failed batch; keep the retention bound.
|
|
571
|
+
pruneOnly(s);
|
|
572
|
+
return false;
|
|
573
|
+
}
|
|
574
|
+
return false;
|
|
575
|
+
}
|
|
576
|
+
// Open eagerly so the startup prune runs without traffic; a passive read never opens the store.
|
|
577
|
+
onSpendLedgerOwnerAcquired((home) => { if (!isPassiveRead()) scope(home); });
|
|
578
|
+
// Commit clean before closing; a later close failure cannot undo that commit.
|
|
579
|
+
onSpendLedgerOwnerReleasing(() => {
|
|
580
|
+
const s = current;
|
|
581
|
+
if (s) {
|
|
582
|
+
flush(s, true);
|
|
583
|
+
retire();
|
|
584
|
+
}
|
|
585
|
+
});
|
|
586
|
+
onSpendLedgerOwnerReleased(() => retire());
|
|
587
|
+
function pending(s: Scope, row: string, issuer: boolean): boolean {
|
|
588
|
+
return s.log.some(
|
|
589
|
+
(op) =>
|
|
590
|
+
op.kind === "clearAll" ||
|
|
591
|
+
(issuer
|
|
592
|
+
? op.kind === "clearIssuers" ||
|
|
593
|
+
(op.kind === "issuerDelete" && op.key === row)
|
|
594
|
+
: op.kind === "clearThreads" || (op.kind === "deleteKey" && op.key === row)),
|
|
595
|
+
);
|
|
596
|
+
}
|
|
597
|
+
function consulted(s: Scope, key: string): boolean {
|
|
598
|
+
if (s.consulted.has(key)) return true;
|
|
599
|
+
s.consulted.add(key);
|
|
600
|
+
if (s.consulted.size > 8192)
|
|
601
|
+
s.consulted.delete(s.consulted.values().next().value!);
|
|
602
|
+
return false;
|
|
603
|
+
}
|
|
604
|
+
function validScope(value: string): boolean {
|
|
605
|
+
const bases: readonly string[] = ["legacy", ...BASE_SCOPES];
|
|
606
|
+
if (bases.includes(value)) return true;
|
|
607
|
+
const m = /^model-detour:([^:]+):(.+)$/s.exec(value);
|
|
608
|
+
return (
|
|
609
|
+
!!m && bases.includes(m[1]!) && Buffer.byteLength(m[2]!, "utf8") <= 512
|
|
610
|
+
);
|
|
611
|
+
}
|
|
612
|
+
export function adoptStoredThreadRows(
|
|
613
|
+
key: string,
|
|
614
|
+
now: number,
|
|
615
|
+
scopeName?: string,
|
|
616
|
+
): StoredThreadRow[] {
|
|
617
|
+
const s = usable();
|
|
618
|
+
if (!s) return [];
|
|
619
|
+
const rk = rowKey(s, key, "conversation");
|
|
620
|
+
// A completed unscoped read (marker "*") already adopted every stored scope for this key.
|
|
621
|
+
if (
|
|
622
|
+
!rk
|
|
623
|
+
|| pending(s, rk, false)
|
|
624
|
+
|| s.consulted.has(`t:${rk}:*`)
|
|
625
|
+
|| (scopeName !== undefined && s.consulted.has(`t:${rk}:${scopeName}`))
|
|
626
|
+
) return [];
|
|
627
|
+
try {
|
|
628
|
+
// Enumerating every scope matters: routing decides account-wide release from this view. The
|
|
629
|
+
// table itself is trimmed to 2048 rows at open and on every flush, which bounds the read.
|
|
630
|
+
const rows = s
|
|
631
|
+
.db!.query(
|
|
632
|
+
scopeName === undefined
|
|
633
|
+
? "SELECT scope, account_id, fence, created_at, last_used_at FROM threads WHERE row_key=? ORDER BY last_used_at DESC, scope LIMIT 2048"
|
|
634
|
+
: "SELECT scope, account_id, fence, created_at, last_used_at FROM threads WHERE row_key=? AND scope=? LIMIT 1",
|
|
635
|
+
)
|
|
636
|
+
.all(...(scopeName === undefined ? [rk] : [rk, scopeName])) as {
|
|
637
|
+
scope: string;
|
|
638
|
+
account_id: string;
|
|
639
|
+
fence: string;
|
|
640
|
+
created_at: number;
|
|
641
|
+
last_used_at: number;
|
|
642
|
+
}[];
|
|
643
|
+
const result: StoredThreadRow[] = [];
|
|
644
|
+
for (const r of rows) {
|
|
645
|
+
if (
|
|
646
|
+
s.log.some(
|
|
647
|
+
(op) =>
|
|
648
|
+
op.kind === "deleteScope" && op.key === rk && op.scope === r.scope,
|
|
649
|
+
) ||
|
|
650
|
+
s.log.some(
|
|
651
|
+
(op) => (op.kind === "deleteAccount" && op.args[0] === r.account_id) ||
|
|
652
|
+
(op.kind === "deleteKeyAccount" && op.key === rk && op.args[1] === r.account_id),
|
|
653
|
+
)
|
|
654
|
+
)
|
|
655
|
+
continue;
|
|
656
|
+
if (
|
|
657
|
+
!validScope(r.scope) ||
|
|
658
|
+
!Number.isFinite(r.created_at) ||
|
|
659
|
+
!Number.isFinite(r.last_used_at) ||
|
|
660
|
+
r.created_at > now ||
|
|
661
|
+
r.last_used_at > now ||
|
|
662
|
+
now - r.last_used_at > TTL ||
|
|
663
|
+
!r.fence ||
|
|
664
|
+
codexAffinityIdentityFence(r.account_id) !== r.fence
|
|
665
|
+
) {
|
|
666
|
+
enqueue(s, {
|
|
667
|
+
kind: "deleteScope",
|
|
668
|
+
key: rk,
|
|
669
|
+
scope: r.scope,
|
|
670
|
+
sql: "DELETE FROM threads WHERE row_key=? AND scope=?",
|
|
671
|
+
args: [rk, r.scope],
|
|
672
|
+
});
|
|
673
|
+
continue;
|
|
674
|
+
}
|
|
675
|
+
rememberThreadKey(s, key, rk, r.scope, r.account_id);
|
|
676
|
+
if (s.poisoned) return [];
|
|
677
|
+
result.push({
|
|
678
|
+
scope: r.scope,
|
|
679
|
+
accountId: r.account_id,
|
|
680
|
+
fence: r.fence,
|
|
681
|
+
createdAt: r.created_at,
|
|
682
|
+
lastUsedAt: r.last_used_at,
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
for (const row of rows) consulted(s, `t:${rk}:${row.scope}`);
|
|
686
|
+
if (scopeName !== undefined) consulted(s, `t:${rk}:${scopeName}`);
|
|
687
|
+
else consulted(s, `t:${rk}:*`);
|
|
688
|
+
return result;
|
|
689
|
+
} catch {
|
|
690
|
+
warning();
|
|
691
|
+
return [];
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
export function adoptStoredIssuer(
|
|
695
|
+
key: string,
|
|
696
|
+
now: number,
|
|
697
|
+
): { issuer: string; storedAccountId: string; storedFence: string | null } | undefined {
|
|
698
|
+
const s = usable();
|
|
699
|
+
if (!s) return;
|
|
700
|
+
const rk = rowKey(s, key, "issuer");
|
|
701
|
+
if (!rk || pending(s, rk, true) || s.consulted.has(`i:${rk}`)) return;
|
|
702
|
+
try {
|
|
703
|
+
const r = s
|
|
704
|
+
.db!.query(
|
|
705
|
+
"SELECT account_id, fence, last_used_at FROM issuers WHERE row_key=?",
|
|
706
|
+
)
|
|
707
|
+
.get(rk) as {
|
|
708
|
+
account_id: string;
|
|
709
|
+
fence: string | null;
|
|
710
|
+
last_used_at: number;
|
|
711
|
+
} | null;
|
|
712
|
+
if (!r) {
|
|
713
|
+
consulted(s, `i:${rk}`);
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
if (
|
|
717
|
+
!Number.isFinite(r.last_used_at) ||
|
|
718
|
+
r.last_used_at > now ||
|
|
719
|
+
now - r.last_used_at > TTL
|
|
720
|
+
) {
|
|
721
|
+
enqueue(s, {
|
|
722
|
+
kind: "issuerDelete",
|
|
723
|
+
key: rk,
|
|
724
|
+
sql: "DELETE FROM issuers WHERE row_key=?",
|
|
725
|
+
args: [rk],
|
|
726
|
+
});
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
const result =
|
|
730
|
+
r.fence && codexAffinityIdentityFence(r.account_id) === r.fence
|
|
731
|
+
? r.account_id
|
|
732
|
+
: CODEX_UNKNOWN_CONVERSATION_STATE_ISSUER;
|
|
733
|
+
rememberIssuerKey(s, key, rk);
|
|
734
|
+
if (s.poisoned) return;
|
|
735
|
+
consulted(s, `i:${rk}`);
|
|
736
|
+
return { issuer: result, storedAccountId: r.account_id, storedFence: r.fence };
|
|
737
|
+
} catch {
|
|
738
|
+
warning();
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
export function recordThreadBind(
|
|
743
|
+
key: string,
|
|
744
|
+
scopeName: string,
|
|
745
|
+
row: StoredThreadRow,
|
|
746
|
+
): void {
|
|
747
|
+
if (isRequestOwnedAffinityKey(key)) return;
|
|
748
|
+
const s = writableScope(row.accountId !== "__main__" && !!row.fence);
|
|
749
|
+
if (!s || row.accountId === "__main__" || !row.fence) return;
|
|
750
|
+
const rk = rowKey(s, key, "conversation");
|
|
751
|
+
if (!rk) return;
|
|
752
|
+
rememberThreadKey(s, key, rk, scopeName, row.accountId);
|
|
753
|
+
if (s.poisoned) return;
|
|
754
|
+
enqueue(s, {
|
|
755
|
+
kind: "bind",
|
|
756
|
+
key: rk,
|
|
757
|
+
scope: scopeName,
|
|
758
|
+
sql: "INSERT INTO threads VALUES (?,?,?,?,?,?) ON CONFLICT(row_key,scope) DO UPDATE SET account_id=excluded.account_id,fence=excluded.fence,created_at=excluded.created_at,last_used_at=excluded.last_used_at",
|
|
759
|
+
args: [
|
|
760
|
+
rk,
|
|
761
|
+
scopeName,
|
|
762
|
+
row.accountId,
|
|
763
|
+
row.fence,
|
|
764
|
+
row.createdAt,
|
|
765
|
+
row.lastUsedAt,
|
|
766
|
+
],
|
|
767
|
+
});
|
|
768
|
+
}
|
|
769
|
+
export function recordThreadTouch(key: string, scopeName: string): void {
|
|
770
|
+
const s = usable();
|
|
771
|
+
if (!s) return;
|
|
772
|
+
const rk = rowKey(s, key, "conversation");
|
|
773
|
+
if (!rk) return;
|
|
774
|
+
s.threads.set(`${rk}\0${scopeName}`, { key, scope: scopeName, rowKey: rk });
|
|
775
|
+
scheduleTouch(s);
|
|
776
|
+
}
|
|
777
|
+
export function recordThreadDelete(key: string, scopeName?: string): void {
|
|
778
|
+
if (isRequestOwnedAffinityKey(key)) return;
|
|
779
|
+
const s = writableScope(true);
|
|
780
|
+
if (!s) return;
|
|
781
|
+
const rk = rowKey(s, key, "conversation");
|
|
782
|
+
if (!rk) return;
|
|
783
|
+
const known = s.threadKeys.get(key);
|
|
784
|
+
if (scopeName === undefined) s.threadKeys.delete(key);
|
|
785
|
+
else if (known) { known.scopes.delete(scopeName); if (!known.scopes.size) s.threadKeys.delete(key); }
|
|
786
|
+
enqueue(
|
|
787
|
+
s,
|
|
788
|
+
scopeName === undefined
|
|
789
|
+
? {
|
|
790
|
+
kind: "deleteKey",
|
|
791
|
+
key: rk,
|
|
792
|
+
sql: "DELETE FROM threads WHERE row_key=?",
|
|
793
|
+
args: [rk],
|
|
794
|
+
}
|
|
795
|
+
: {
|
|
796
|
+
kind: "deleteScope",
|
|
797
|
+
key: rk,
|
|
798
|
+
scope: scopeName,
|
|
799
|
+
sql: "DELETE FROM threads WHERE row_key=? AND scope=?",
|
|
800
|
+
args: [rk, scopeName],
|
|
801
|
+
},
|
|
802
|
+
);
|
|
803
|
+
}
|
|
804
|
+
export function recordThreadAccountDeleted(key: string, id: string): void {
|
|
805
|
+
if (isRequestOwnedAffinityKey(key)) return;
|
|
806
|
+
const s = writableScope(true);
|
|
807
|
+
if (!s) return;
|
|
808
|
+
const rk = rowKey(s, key, "conversation");
|
|
809
|
+
if (!rk) return;
|
|
810
|
+
const known = s.threadKeys.get(key);
|
|
811
|
+
if (known) {
|
|
812
|
+
for (const [scopeName, account] of known.scopes) if (account === id) known.scopes.delete(scopeName);
|
|
813
|
+
if (!known.scopes.size) s.threadKeys.delete(key);
|
|
814
|
+
}
|
|
815
|
+
enqueue(s, { kind: "deleteKeyAccount", key: rk, sql: "DELETE FROM threads WHERE row_key=? AND account_id=?", args: [rk, id] });
|
|
816
|
+
}
|
|
817
|
+
export function recordAccountPinsCleared(id: string): void {
|
|
818
|
+
const s = writableScope(true);
|
|
819
|
+
if (s) {
|
|
820
|
+
for (const [key, entry] of s.threadKeys) {
|
|
821
|
+
for (const [scopeName, account] of entry.scopes) if (account === id) entry.scopes.delete(scopeName);
|
|
822
|
+
if (!entry.scopes.size) s.threadKeys.delete(key);
|
|
823
|
+
}
|
|
824
|
+
enqueue(s, {
|
|
825
|
+
kind: "deleteAccount",
|
|
826
|
+
sql: "DELETE FROM threads WHERE account_id=?",
|
|
827
|
+
args: [id],
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
export function recordAllCleared(): void {
|
|
832
|
+
const s = writableScope(true);
|
|
833
|
+
if (s) {
|
|
834
|
+
s.threadKeys.clear(); s.issuerKeys.clear();
|
|
835
|
+
enqueue(s, {
|
|
836
|
+
kind: "clearAll",
|
|
837
|
+
sql: "DELETE FROM threads; DELETE FROM issuers",
|
|
838
|
+
args: [],
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
/** A manual account switch clears pins but keeps the issuers of carried state. */
|
|
843
|
+
export function recordThreadsCleared(): void {
|
|
844
|
+
const s = writableScope(true);
|
|
845
|
+
if (s) {
|
|
846
|
+
s.threadKeys.clear();
|
|
847
|
+
enqueue(s, { kind: "clearThreads", sql: "DELETE FROM threads", args: [] });
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
/** Test seam: feed the anchor observer directly, as a future derivation path might. */
|
|
851
|
+
export function noteCodexAffinityAnchorForTests(key: string, family: string, thread: string): void {
|
|
852
|
+
observeAnchor(key, family, thread);
|
|
853
|
+
}
|
|
854
|
+
export function recordIssuerSet(
|
|
855
|
+
key: string,
|
|
856
|
+
id: string,
|
|
857
|
+
fence: string | null,
|
|
858
|
+
lastUsedAt: number,
|
|
859
|
+
): void {
|
|
860
|
+
if (isRequestOwnedAffinityKey(key)) return;
|
|
861
|
+
const s = writableScope(id !== "__main__");
|
|
862
|
+
if (!s || id === "__main__") return;
|
|
863
|
+
const rk = rowKey(s, key, "issuer");
|
|
864
|
+
if (!rk) return;
|
|
865
|
+
rememberIssuerKey(s, key, rk);
|
|
866
|
+
if (s.poisoned) return;
|
|
867
|
+
enqueue(s, {
|
|
868
|
+
kind: "issuerSet",
|
|
869
|
+
key: rk,
|
|
870
|
+
sql: "INSERT INTO issuers VALUES (?,?,?,?) ON CONFLICT(row_key) DO UPDATE SET account_id=excluded.account_id,fence=excluded.fence,last_used_at=excluded.last_used_at",
|
|
871
|
+
args: [rk, id, fence, lastUsedAt],
|
|
872
|
+
});
|
|
873
|
+
}
|
|
874
|
+
export function recordIssuerTouch(key: string): void {
|
|
875
|
+
const s = usable();
|
|
876
|
+
if (!s) return;
|
|
877
|
+
const rk = rowKey(s, key, "issuer");
|
|
878
|
+
if (!rk) return;
|
|
879
|
+
s.issuers.set(rk, { key, rowKey: rk });
|
|
880
|
+
scheduleTouch(s);
|
|
881
|
+
}
|
|
882
|
+
export function recordIssuerDelete(key: string): void {
|
|
883
|
+
if (isRequestOwnedAffinityKey(key)) return;
|
|
884
|
+
const s = writableScope(true);
|
|
885
|
+
if (!s) return;
|
|
886
|
+
const rk = rowKey(s, key, "issuer");
|
|
887
|
+
if (rk) {
|
|
888
|
+
s.issuerKeys.delete(key);
|
|
889
|
+
enqueue(s, {
|
|
890
|
+
kind: "issuerDelete",
|
|
891
|
+
key: rk,
|
|
892
|
+
sql: "DELETE FROM issuers WHERE row_key=?",
|
|
893
|
+
args: [rk],
|
|
894
|
+
});
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
export function recordIssuersCleared(): void {
|
|
898
|
+
const s = writableScope(true);
|
|
899
|
+
if (s) {
|
|
900
|
+
s.issuerKeys.clear();
|
|
901
|
+
enqueue(s, { kind: "clearIssuers", sql: "DELETE FROM issuers", args: [] });
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
export function flushCodexAffinityStoreForTests(): void {
|
|
905
|
+
if (current && !isPassiveRead()) flush(current, false);
|
|
906
|
+
}
|
|
907
|
+
export function resetCodexAffinityStoreForTests(): void {
|
|
908
|
+
if (current) {
|
|
909
|
+
flush(current, false);
|
|
910
|
+
retire();
|
|
911
|
+
}
|
|
912
|
+
// Model a fresh process: nothing carried from an earlier scope, nothing known to be stale.
|
|
913
|
+
carried = undefined;
|
|
914
|
+
persistedHome = undefined;
|
|
915
|
+
needsClear = false;
|
|
916
|
+
}
|