@bitkyc08/opencodex 2.95.0 → 2.97.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (276) hide show
  1. package/bin/ocx.mjs +214 -19
  2. package/gui/dist/assets/{App-8yedBkhm.js → App-DuNhggE1.js} +18 -18
  3. package/gui/dist/assets/{Tray-erSMzxPG.js → Tray-CEw0y0jR.js} +1 -1
  4. package/gui/dist/assets/index-CynE_Rue.js +94 -0
  5. package/gui/dist/assets/{quota-summary-BK4VuQNc.js → quota-summary-VHFSlUuM.js} +1 -1
  6. package/gui/dist/index.html +1 -1
  7. package/package.json +1 -1
  8. package/src/adapters/command-code.ts +15 -16
  9. package/src/adapters/cursor/transport-retry.ts +2 -2
  10. package/src/adapters/devin/cloud-direct/chat.ts +15 -6
  11. package/src/adapters/kiro/stream.ts +63 -4
  12. package/src/adapters/kiro-constants.ts +15 -1
  13. package/src/adapters/kiro-events.ts +31 -1
  14. package/src/adapters/kiro-retry.ts +3 -3
  15. package/src/adapters/ollama-native.ts +21 -7
  16. package/src/adapters/openai-responses/canonical-forward.ts +50 -13
  17. package/src/adapters/openai-responses/empty-assistant.ts +15 -3
  18. package/src/adapters/openai-responses/passthrough.ts +8 -8
  19. package/src/adapters/openai-responses/reasoning.ts +9 -4
  20. package/src/adapters/openai-responses/request-strips.ts +1 -1
  21. package/src/adapters/openai-responses/transport.ts +17 -26
  22. package/src/adapters/physical-send.ts +3 -3
  23. package/src/adapters/qoder/adapter.ts +1 -1
  24. package/src/adapters/qoder/image-input.ts +5 -2
  25. package/src/adapters/zed-openai-stream.ts +2 -1
  26. package/src/bridge/errors.ts +11 -2
  27. package/src/bridge/response-json.ts +2 -1
  28. package/src/bridge/sse.ts +14 -6
  29. package/src/chat/failure-verdict.ts +21 -0
  30. package/src/chat/outbound.ts +139 -21
  31. package/src/claude/outbound.ts +49 -2
  32. package/src/cli/agent.ts +44 -15
  33. package/src/cli/capabilities-agents-routing.ts +9 -0
  34. package/src/cli/capabilities-base.ts +25 -3
  35. package/src/cli/capabilities-command.ts +12 -3
  36. package/src/cli/capability-contracts.ts +2 -0
  37. package/src/cli/codex-launch-auth.ts +30 -1
  38. package/src/cli/codex-launcher.ts +12 -5
  39. package/src/cli/codex-shim-autorestore.ts +5 -4
  40. package/src/cli/dispatch.ts +11 -176
  41. package/src/cli/ensure-desired-integrations.ts +4 -3
  42. package/src/cli/help.ts +2 -2
  43. package/src/cli/index.ts +9 -2
  44. package/src/cli/link.ts +1 -1
  45. package/src/cli/message-command.ts +2 -1
  46. package/src/cli/message-mcp-command.ts +29 -0
  47. package/src/cli/registry.ts +12 -4
  48. package/src/cli/root.ts +8 -0
  49. package/src/cli/sync-command.ts +243 -0
  50. package/src/cli/sync-fanout-process.ts +92 -0
  51. package/src/cli/sync-fanout.ts +150 -0
  52. package/src/cli/sync-flags.ts +10 -0
  53. package/src/cli/sync-link-status.ts +39 -0
  54. package/src/cli/sync-update-guard.ts +18 -0
  55. package/src/client/connect.ts +31 -14
  56. package/src/client/link-home.ts +3 -2
  57. package/src/client/machine-listener.ts +3 -0
  58. package/src/client/restore-ownership.ts +19 -1
  59. package/src/client/runtime-restart.ts +12 -4
  60. package/src/client/runtime.ts +40 -11
  61. package/src/client/stop-routing.ts +62 -0
  62. package/src/client/sync-runtime.ts +65 -0
  63. package/src/clients/config-export.ts +32 -3
  64. package/src/codex/account-store.ts +1 -0
  65. package/src/codex/auth-context-provider.ts +15 -0
  66. package/src/codex/auth-context.ts +59 -122
  67. package/src/codex/catalog/antigravity-discovery.ts +16 -5
  68. package/src/codex/catalog/provider-models.ts +6 -8
  69. package/src/codex/forward-transport-headers.ts +65 -36
  70. package/src/codex/inject/config-toml.ts +88 -0
  71. package/src/codex/inject/multi-agent-v2.ts +30 -4
  72. package/src/codex/inject/plan.ts +34 -7
  73. package/src/codex/inject-coordination.ts +11 -0
  74. package/src/codex/inject.ts +18 -7
  75. package/src/codex/installation-id.ts +72 -0
  76. package/src/codex/lineage.ts +13 -7
  77. package/src/codex/quota.ts +22 -6
  78. package/src/codex/request-owned-affinity-key.ts +11 -0
  79. package/src/codex/request-owned-affinity.ts +118 -0
  80. package/src/codex/request-owned-main-pin.ts +86 -0
  81. package/src/codex/role-capability.ts +52 -41
  82. package/src/codex/routing/active-account.ts +13 -5
  83. package/src/codex/routing/selection.ts +40 -1
  84. package/src/codex/routing/thread-affinity-store.ts +916 -0
  85. package/src/codex/routing/thread-affinity.ts +90 -12
  86. package/src/codex/toml-source-lines.ts +72 -13
  87. package/src/combos/failover.ts +6 -109
  88. package/src/combos/request.ts +2 -2
  89. package/src/combos/resolve.ts +29 -11
  90. package/src/config/process-state.ts +5 -0
  91. package/src/config/schema/leaf-validators.ts +1 -0
  92. package/src/generated/compatibility-version.json +496 -192
  93. package/src/grok/sync.ts +10 -1
  94. package/src/images/loop.ts +2 -1
  95. package/src/lib/client-error-body.ts +184 -0
  96. package/src/lib/client-retry-after.ts +66 -0
  97. package/src/lib/config-ownership.ts +4 -0
  98. package/src/lib/context-overflow-verdict.ts +113 -0
  99. package/src/lib/desktop-cli-handoff.d.mts +1 -1
  100. package/src/lib/desktop-cli-handoff.mjs +11 -1
  101. package/src/lib/empty-tool-catalog.ts +25 -3
  102. package/src/lib/error-destination.ts +47 -0
  103. package/src/lib/failure-detail.ts +66 -0
  104. package/src/lib/model-identity.ts +44 -0
  105. package/src/lib/private-sqlite-path.ts +124 -0
  106. package/src/lib/response-service-tier.ts +17 -0
  107. package/src/lib/retry-after.ts +3 -0
  108. package/src/lib/spend-ledger-owner.ts +43 -4
  109. package/src/lib/upstream-condition.ts +142 -0
  110. package/src/lib/upstream-retry.ts +14 -11
  111. package/src/lib/windows-owner-acl.ts +13 -6
  112. package/src/lib/windows-secret-acl.ts +2 -2
  113. package/src/link/remote-platform.ts +14 -0
  114. package/src/link/remote-windows.ts +51 -9
  115. package/src/link/ssh-argv.ts +63 -10
  116. package/src/messaging/mcp-queue-rpc.ts +102 -0
  117. package/src/messaging/mcp-queue-server.ts +42 -0
  118. package/src/messaging/mcp-queue-tools.ts +39 -0
  119. package/src/oauth/anthropic-identity.ts +2 -6
  120. package/src/oauth/generic-account-failover.ts +13 -11
  121. package/src/oauth/index.ts +41 -74
  122. package/src/oauth/oauth-errors.ts +67 -0
  123. package/src/oauth/store.ts +1 -1
  124. package/src/protocols/codecs/ollama.ts +197 -0
  125. package/src/protocols/encoders/adapter-events.ts +4 -0
  126. package/src/protocols/encoders/chat.ts +18 -10
  127. package/src/protocols/trace.ts +18 -0
  128. package/src/providers/anthropic-subscription.ts +25 -0
  129. package/src/providers/claude-cli-usage.ts +15 -67
  130. package/src/providers/fastwire.ts +3 -2
  131. package/src/providers/quota/anthropic-decision-windows.ts +5 -19
  132. package/src/providers/quota/anthropic-usage-windows.ts +65 -0
  133. package/src/providers/quota/vendor-probes-key.ts +60 -24
  134. package/src/providers/request-pacing.ts +3 -2
  135. package/src/responses/apply-patch-envelope.ts +45 -19
  136. package/src/responses/compaction-history-framing.ts +5 -1
  137. package/src/responses/freeform-wrapper-scan.ts +5 -3
  138. package/src/responses/parser-tools.ts +1 -0
  139. package/src/responses/progressive-freeform-input.ts +354 -45
  140. package/src/responses/schema.ts +5 -2
  141. package/src/routing/fallback-policy.ts +3 -1
  142. package/src/server/admission-model-scope.ts +17 -6
  143. package/src/server/admitted-http-turn.ts +56 -0
  144. package/src/server/audio-dictation.ts +3 -0
  145. package/src/server/audio-live.ts +8 -2
  146. package/src/server/audio-upstream.ts +2 -0
  147. package/src/server/auth-cors.ts +5 -0
  148. package/src/server/chat-completions.ts +45 -20
  149. package/src/server/chat-native-sse.ts +52 -7
  150. package/src/server/chat-native.ts +60 -35
  151. package/src/server/claude-bridge-pool-session.ts +59 -0
  152. package/src/server/claude-messages.ts +57 -27
  153. package/src/server/context-history.ts +14 -7
  154. package/src/server/images.ts +14 -5
  155. package/src/server/inbound-body-admission.ts +11 -4
  156. package/src/server/index/live-sideband.ts +16 -2
  157. package/src/server/index/ollama-routes.ts +89 -0
  158. package/src/server/index/serve-options.ts +22 -4
  159. package/src/server/index/websocket-handler.ts +5 -3
  160. package/src/server/index.ts +6 -36
  161. package/src/server/inference/client-encoder-delivery.ts +4 -2
  162. package/src/server/json-serialized-bytes.ts +44 -0
  163. package/src/server/live.ts +30 -5
  164. package/src/server/management/agent-settings-routes.ts +24 -21
  165. package/src/server/management/codex-cli-update-routes.ts +2 -1
  166. package/src/server/management/route-registry.ts +1 -1
  167. package/src/server/messages-native-scope.ts +2 -1
  168. package/src/server/messages-native-tool-guard.ts +1 -1
  169. package/src/server/messages-native.ts +12 -7
  170. package/src/server/messages-shared.ts +6 -2
  171. package/src/server/native-final-log.ts +93 -0
  172. package/src/server/ollama-inbound.ts +349 -0
  173. package/src/server/ollama-native-paths.ts +21 -0
  174. package/src/server/ollama-route-policy.ts +73 -0
  175. package/src/server/relay.ts +22 -3
  176. package/src/server/request-decompress.ts +4 -2
  177. package/src/server/request-log-failure-attribution.ts +22 -0
  178. package/src/server/request-log-failure-detail.ts +80 -0
  179. package/src/server/request-log-terminal-status.ts +4 -2
  180. package/src/server/request-log.ts +79 -42
  181. package/src/server/response-log-body.ts +6 -1
  182. package/src/server/responses/account-change-state.ts +17 -6
  183. package/src/server/responses/adapter-continuation.ts +9 -4
  184. package/src/server/responses/adapter-delivery.ts +5 -4
  185. package/src/server/responses/adapter-dispatch.ts +36 -30
  186. package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
  187. package/src/server/responses/codex-auth-error.ts +22 -17
  188. package/src/server/responses/codex-ws-exchange.ts +11 -8
  189. package/src/server/responses/codex-ws-metadata.ts +94 -21
  190. package/src/server/responses/codex-ws-request.ts +3 -1
  191. package/src/server/responses/combo-required-tool-contract.ts +24 -12
  192. package/src/server/responses/compact.ts +89 -41
  193. package/src/server/responses/compaction-recovery.ts +4 -2
  194. package/src/server/responses/compaction-routing.ts +9 -4
  195. package/src/server/responses/core-auth.ts +32 -14
  196. package/src/server/responses/core-codex-account.ts +34 -12
  197. package/src/server/responses/core-combo-failure.ts +5 -1
  198. package/src/server/responses/core-combo-native.ts +2 -1
  199. package/src/server/responses/core-combo.ts +51 -33
  200. package/src/server/responses/core-errors.ts +22 -20
  201. package/src/server/responses/core-lifetime.ts +6 -3
  202. package/src/server/responses/core-normalize.ts +8 -1
  203. package/src/server/responses/core-options.ts +7 -0
  204. package/src/server/responses/core-pipeline.ts +4 -3
  205. package/src/server/responses/fetch-helpers.ts +7 -1
  206. package/src/server/responses/input-admission.ts +28 -2
  207. package/src/server/responses/native-injection.ts +1 -1
  208. package/src/server/responses/native-response-json.ts +13 -4
  209. package/src/server/responses/native-response-output.ts +1 -2
  210. package/src/server/responses/non-replayable-error.ts +2 -1
  211. package/src/server/responses/pacing-overload.ts +3 -2
  212. package/src/server/responses/passthrough-build-error.ts +36 -0
  213. package/src/server/responses/passthrough-delivery.ts +55 -14
  214. package/src/server/responses/passthrough-dispatch.ts +26 -39
  215. package/src/server/responses/passthrough-error.ts +9 -9
  216. package/src/server/responses/policy-fallback.ts +2 -1
  217. package/src/server/responses/request-prepare.ts +67 -48
  218. package/src/server/responses/request-sidecar-auth.ts +3 -1
  219. package/src/server/responses/request-transport.ts +35 -31
  220. package/src/server/responses/run-turn-execution.ts +6 -6
  221. package/src/server/responses/sidecar-execution.ts +16 -12
  222. package/src/server/responses/spend-storage-error.ts +2 -1
  223. package/src/server/responses/ws-upstream.ts +9 -0
  224. package/src/server/responses-custom-tool-repair.ts +14 -3
  225. package/src/server/responses-terminal-repair.ts +5 -2
  226. package/src/server/responses-undeclared-tool-guard.ts +39 -16
  227. package/src/server/safe-response-headers.ts +162 -13
  228. package/src/server/search.ts +13 -4
  229. package/src/server/turn-state-handles.ts +164 -0
  230. package/src/server/workflow-refusal.ts +2 -1
  231. package/src/server/ws-bridge.ts +5 -2
  232. package/src/service/ownership-mutation-lease.d.mts +11 -2
  233. package/src/service/ownership-mutation-lease.mjs +53 -11
  234. package/src/types/config.ts +2 -0
  235. package/src/update/index.ts +133 -25
  236. package/src/update/npm-install.d.mts +8 -0
  237. package/src/update/npm-install.mjs +20 -1
  238. package/src/update/orchestrated-admission.d.mts +4 -0
  239. package/src/update/orchestrated-admission.mjs +12 -0
  240. package/src/update/orchestrated-arguments.d.mts +12 -0
  241. package/src/update/orchestrated-arguments.mjs +64 -0
  242. package/src/update/orchestrated-child.d.mts +12 -0
  243. package/src/update/orchestrated-child.mjs +70 -0
  244. package/src/update/orchestrated-entry.ts +234 -0
  245. package/src/update/orchestrated-identity-probe-entry.ts +20 -0
  246. package/src/update/orchestrated-identity.ts +53 -0
  247. package/src/update/orchestrated-live-identity.ts +48 -0
  248. package/src/update/orchestrated-node-driver.mjs +99 -0
  249. package/src/update/orchestrated-outcome.d.mts +21 -0
  250. package/src/update/orchestrated-outcome.mjs +40 -0
  251. package/src/update/orchestrated-plan.ts +49 -0
  252. package/src/update/orchestrated-pnpm.d.mts +8 -0
  253. package/src/update/orchestrated-pnpm.mjs +33 -0
  254. package/src/update/orchestrated-session.d.mts +37 -0
  255. package/src/update/orchestrated-session.mjs +264 -0
  256. package/src/update/orchestrated-token.d.mts +10 -0
  257. package/src/update/orchestrated-token.mjs +21 -0
  258. package/src/update/orchestrated-token.ts +3 -0
  259. package/src/update/orchestrated-tree.d.mts +1 -0
  260. package/src/update/orchestrated-tree.mjs +14 -0
  261. package/src/update/pnpm-global-install.d.mts +6 -0
  262. package/src/update/pnpm-global-install.mjs +9 -2
  263. package/src/update/posix-install-supervisor-entry.mjs +6 -0
  264. package/src/update/posix-install-supervisor.d.mts +10 -0
  265. package/src/update/posix-install-supervisor.mjs +88 -0
  266. package/src/update/sync-update-mutex.d.mts +10 -0
  267. package/src/update/sync-update-mutex.mjs +164 -0
  268. package/src/update/sync-update-mutex.ts +1 -0
  269. package/src/update/test-home-guard.mjs +33 -0
  270. package/src/update/transactional-install.mjs +2 -2
  271. package/src/usage/error-detail.ts +225 -0
  272. package/src/usage/log.ts +60 -27
  273. package/src/vision/describe.ts +4 -7
  274. package/src/web-search/executor.ts +4 -7
  275. package/src/web-search/loop.ts +31 -5
  276. package/gui/dist/assets/index-D7DCm5eQ.js +0 -94
@@ -0,0 +1,44 @@
1
+ import { redactSecretString } from "./redact";
2
+ import { pinnedNativeModelRows } from "../codex/catalog/pinned-models";
3
+ import { getModelMetadata, resolveMetadataProvider } from "../generated/model-metadata";
4
+
5
+ /** Longest model identity a row or relayed header may carry. */
6
+ export const MAX_MODEL_IDENTITY_LENGTH = 128;
7
+
8
+ /**
9
+ * A model identity (served, resolved, or a relayed model header) is an identifier, never free-form
10
+ * text to truncate into one: `[A-Za-z0-9._:/@-]`, at most 128 characters. A value the secret redactor
11
+ * would change is dropped, because credential-shaped text can fit the identifier alphabet.
12
+ */
13
+ export function boundedModelIdentity(value: unknown): string | undefined {
14
+ return typeof value === "string"
15
+ && value.length <= MAX_MODEL_IDENTITY_LENGTH
16
+ && /^[A-Za-z0-9._:/@-]+$/.test(value)
17
+ && redactSecretString(value) === value
18
+ ? value
19
+ : undefined;
20
+ }
21
+
22
+ /** Model ids this build pins for the Codex catalog; a known id a route can be served without config. */
23
+ const PINNED_MODEL_IDS: ReadonlyMap<string, string> = new Map(
24
+ pinnedNativeModelRows().flatMap(row => typeof row.slug === "string" ? [[row.slug, row.slug] as [string, string]] : []),
25
+ );
26
+
27
+ /**
28
+ * An upstream-reported model string is kept only when it exactly equals a model id this proxy
29
+ * already knows: one of `known` (the requested model, the routed target, the wire model, a
30
+ * configured target), a model the bundled Codex catalog pins, or a model in the bundled metadata
31
+ * catalog for `provider` (the selected provider). The identity grammar still applies first. What is
32
+ * returned is the proxy's own copy of the matched id; anything else is undefined, because no grammar
33
+ * can tell a prefixless credential from a model name.
34
+ */
35
+ export function knownModelIdentity(value: unknown, known: Iterable<unknown> = [], provider?: string): string | undefined {
36
+ const bounded = boundedModelIdentity(value);
37
+ if (bounded === undefined) return undefined;
38
+ for (const candidate of known) {
39
+ if (typeof candidate === "string" && candidate === bounded) return candidate;
40
+ }
41
+ const pinned = PINNED_MODEL_IDS.get(bounded);
42
+ if (pinned !== undefined || !provider) return pinned;
43
+ return getModelMetadata(resolveMetadataProvider(provider) ?? provider, bounded)?.id;
44
+ }
@@ -0,0 +1,124 @@
1
+ import { closeSync, lstatSync, openSync } from "node:fs";
2
+
3
+ /** The files SQLite opens next to a database: the rollback journal, and the WAL and its index. */
4
+ export const SQLITE_SIDECAR_SUFFIXES = ["-journal", "-wal", "-shm"] as const;
5
+
6
+ /** A database or sidecar name holds something other than a private regular file. Carries no path. */
7
+ export class UnsafeSqlitePathError extends Error {
8
+ constructor() {
9
+ super("SQLite storage path is not a private regular file");
10
+ this.name = "UnsafeSqlitePathError";
11
+ }
12
+ }
13
+
14
+ const FILE_ATTRIBUTE_REPARSE_POINT = 0x400;
15
+ const INVALID_FILE_ATTRIBUTES = 0xffffffff;
16
+ type ReparseProbe = (path: string) => boolean;
17
+ let nativeAttributes: ((path: string) => number) | undefined;
18
+ let probeForTests: ReparseProbe | null = null;
19
+ /**
20
+ * Whether the native attribute query runs: on Windows, except ARM64, whose Bun build cannot execute
21
+ * `bun:ffi` (the limitation src/lib/windows-user-principal.ts works around). There `lstat` still
22
+ * reports symbolic links, junctions and app execution aliases as links; other reparse tags are not
23
+ * visible without native code.
24
+ */
25
+ export function nativeReparseProbeApplies(platform: string, arch: string): boolean {
26
+ return platform === "win32" && arch !== "arm64";
27
+ }
28
+ // Read once at load: tests replace `process.platform` to drive Windows-only branches on POSIX, and
29
+ // the native query must follow the system the process actually runs on.
30
+ const NATIVE_ATTRIBUTES = nativeReparseProbeApplies(process.platform, process.arch);
31
+
32
+ function errorCode(error: unknown): unknown {
33
+ return error !== null && typeof error === "object" && "code" in error ? error.code : undefined;
34
+ }
35
+
36
+ /**
37
+ * Whether the entry at `path` itself is a Windows reparse point: a symbolic link, a junction, or any
38
+ * other tag. `GetFileAttributesW` reports the named entry rather than what it points to, so this
39
+ * sees what `lstat` cannot classify. Throws when the attribute cannot be read.
40
+ */
41
+ export function isWindowsReparsePoint(path: string): boolean {
42
+ if (!nativeAttributes) {
43
+ // Loaded on first use, only on Windows; the repository's other Windows file checks use the same call.
44
+ const ffi = require("bun:ffi") as typeof import("bun:ffi");
45
+ const kernel = ffi.dlopen("kernel32.dll", {
46
+ GetFileAttributesW: { args: [ffi.FFIType.ptr], returns: ffi.FFIType.u32 },
47
+ });
48
+ nativeAttributes = (name: string) => {
49
+ const wide = Buffer.from(`${name}\0`, "utf16le");
50
+ return kernel.symbols.GetFileAttributesW(ffi.ptr(wide)) >>> 0;
51
+ };
52
+ }
53
+ const attributes = nativeAttributes(path);
54
+ if (attributes === INVALID_FILE_ATTRIBUTES) throw new Error("file attributes unavailable");
55
+ return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) !== 0;
56
+ }
57
+
58
+ /** Test seam: replace the reparse-point probe on every platform; null restores the default. */
59
+ export function setSqlitePathReparseProbeForTests(probe: ReparseProbe | null): void {
60
+ probeForTests = probe;
61
+ }
62
+
63
+ function isReparsePoint(path: string): boolean {
64
+ if (probeForTests) return probeForTests(path);
65
+ return NATIVE_ATTRIBUTES && isWindowsReparsePoint(path);
66
+ }
67
+
68
+ /**
69
+ * Refuse unless nothing is at `path` or it is a private regular file: not a link or other reparse
70
+ * point, not a directory, a single directory entry, and on POSIX owned by this user. Returns
71
+ * whether an entry exists. A probe that cannot answer refuses.
72
+ */
73
+ export function assertPrivateSqliteEntryOrMissing(path: string): boolean {
74
+ let stat;
75
+ try {
76
+ stat = lstatSync(path);
77
+ } catch (error) {
78
+ if (errorCode(error) === "ENOENT") return false;
79
+ throw error;
80
+ }
81
+ let reparse: boolean;
82
+ try {
83
+ reparse = isReparsePoint(path);
84
+ } catch {
85
+ throw new UnsafeSqlitePathError();
86
+ }
87
+ if (
88
+ reparse
89
+ || !stat.isFile()
90
+ || stat.isSymbolicLink()
91
+ || stat.nlink !== 1
92
+ || (process.platform !== "win32" && stat.uid !== process.getuid!())
93
+ ) throw new UnsafeSqlitePathError();
94
+ return true;
95
+ }
96
+
97
+ /**
98
+ * Refuse unless every sidecar of `databasePath` is absent or a private regular file. SQLite's POSIX
99
+ * VFS opens them with O_NOFOLLOW; its Windows VFS opens them by name with CreateFileW, which follows
100
+ * a link planted there. Check before opening the database and before every write transaction: the
101
+ * rollback journal is created and deleted per transaction. Something planted after the check, while
102
+ * SQLite opens the file, is outside what this can see.
103
+ */
104
+ export function assertPrivateSqliteSidecars(databasePath: string): void {
105
+ for (const suffix of SQLITE_SIDECAR_SUFFIXES) assertPrivateSqliteEntryOrMissing(databasePath + suffix);
106
+ }
107
+
108
+ /**
109
+ * Make sure `databasePath` is a private regular file without creating anything through a link at
110
+ * its name or at a sidecar's. POSIX O_CREAT|O_EXCL refuses a link at the final component, but
111
+ * Windows CREATE_NEW follows a dangling file symlink and creates its target, so every entry is
112
+ * checked before the create. An entry planted between the check and the create is not covered;
113
+ * callers check the file again after hardening it.
114
+ */
115
+ export function preparePrivateSqliteDatabase(databasePath: string): void {
116
+ assertPrivateSqliteSidecars(databasePath);
117
+ if (assertPrivateSqliteEntryOrMissing(databasePath)) return;
118
+ try {
119
+ closeSync(openSync(databasePath, "wx", 0o600));
120
+ } catch (error) {
121
+ if (errorCode(error) !== "EEXIST") throw error;
122
+ }
123
+ if (!assertPrivateSqliteEntryOrMissing(databasePath)) throw new UnsafeSqlitePathError();
124
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Response service tiers a request-log row may record. A provider can return any string in
3
+ * `service_tier` (or an Anthropic `speed`), so only these closed members are kept; anything else
4
+ * is omitted. Pricing and Fast confirmation read the raw observation separately.
5
+ */
6
+ export const RESPONSE_SERVICE_TIERS = ["auto", "default", "flex", "scale", "priority", "fast", "standard", "ultrafast"] as const;
7
+
8
+ export type ResponseServiceTier = typeof RESPONSE_SERVICE_TIERS[number];
9
+
10
+ const TIERS: ReadonlySet<string> = new Set(RESPONSE_SERVICE_TIERS);
11
+
12
+ /** The closed member a tier names (case-insensitive), or undefined. */
13
+ export function boundedServiceTier(value: unknown): ResponseServiceTier | undefined {
14
+ if (typeof value !== "string") return undefined;
15
+ const folded = value.trim().toLowerCase();
16
+ return TIERS.has(folded) ? folded as ResponseServiceTier : undefined;
17
+ }
@@ -1,5 +1,8 @@
1
1
  import { parseRetryAfterMs } from "../combos";
2
2
  import { classifyError, parseRetryAfterFromMessage } from "./errors";
3
+ import { formatClientRetryAfter } from "./client-retry-after";
4
+
5
+ export { formatClientRetryAfter, MAX_CLIENT_RETRY_AFTER_SECONDS } from "./client-retry-after";
3
6
 
4
7
  /** Small default when a retryable 429 has no upstream Retry-After (#507). */
5
8
  export const DEFAULT_RETRYABLE_429_RETRY_AFTER_SEC = "2";
@@ -1,9 +1,10 @@
1
1
  /** Process-lifetime single-writer ownership for the shared spend journal. */
2
2
  import { Database } from "bun:sqlite";
3
- import { chmodSync, closeSync, lstatSync, mkdirSync, openSync, realpathSync } from "node:fs";
3
+ import { chmodSync, lstatSync, mkdirSync, realpathSync } from "node:fs";
4
4
  import { join, resolve } from "node:path";
5
5
  import { getConfigDir } from "../config/paths";
6
6
  import { recordOwnedConfigPath } from "./config-ownership";
7
+ import { assertPrivateSqliteSidecars, preparePrivateSqliteDatabase } from "./private-sqlite-path";
7
8
  import { assertNotRealHomeUnderTest } from "./test-home-guard";
8
9
  import { hardenSecretDir, hardenSecretPath } from "./windows-secret-acl";
9
10
 
@@ -47,6 +48,26 @@ let boundLedgerHome: string | null = null;
47
48
  */
48
49
  let ownerGeneration = 0;
49
50
  const releaseHooks: Array<() => void> = [];
51
+ const acquiredHooks: Array<(home: string) => void> = [];
52
+
53
+ /** Run once after each new ownership generation is acquired. */
54
+ export function onSpendLedgerOwnerAcquired(hook: (home: string) => void): void {
55
+ acquiredHooks.push(hook);
56
+ }
57
+ const releasingHooks: Array<() => void> = [];
58
+ let releasing = false;
59
+
60
+ /** Run before the final lease is released, while existing storage tokens remain valid. */
61
+ export function onSpendLedgerOwnerReleasing(hook: () => void): void {
62
+ releasingHooks.push(hook);
63
+ }
64
+
65
+ function assertNotReleasing(): void {
66
+ if (releasing) throw new SpendLedgerOwnerError(
67
+ "SPEND_LEDGER_OWNER_NOT_HELD",
68
+ "Spend-ledger ownership is required before the shared ledger can be used.",
69
+ );
70
+ }
50
71
 
51
72
  /**
52
73
  * Run when the last lease on a state directory goes away.
@@ -95,8 +116,9 @@ function prepareOwnerPath(configDir: string): { home: string; path: string } {
95
116
  // its sidecars were left behind by a later uninstall because nothing recorded them.
96
117
  recordOwnedConfigPath(home, path);
97
118
  for (const suffix of OWNER_SIDECARS) recordOwnedConfigPath(home, `${path}${suffix}`);
98
- try { closeSync(openSync(path, "wx", 0o600)); }
99
- catch (error) { if (errorCode(error) !== "EEXIST") throw error; }
119
+ // Refuses a link or reparse point at the database or a sidecar before anything is created:
120
+ // Windows creates a new file through a link at its name.
121
+ preparePrivateSqliteDatabase(path);
100
122
  assertPrivateFile(path);
101
123
  if (process.platform !== "win32") chmodSync(path, 0o600);
102
124
  hardenSecretPath(path, { required: true });
@@ -142,6 +164,7 @@ export function spendLedgerRestartEnvironment(
142
164
  * can evict a live owner or mistake a reused process identity for this lease.
143
165
  */
144
166
  export function acquireSpendLedgerOwner(configDir = getConfigDir()): SpendLedgerOwnerLease {
167
+ assertNotReleasing();
145
168
  const requestedHome = stateDirectoryIdentity(configDir);
146
169
  const busyTimeout = restartHandoffWaitMs();
147
170
  if (boundLedgerHome !== null && boundLedgerHome !== requestedHome) {
@@ -175,6 +198,7 @@ export function acquireSpendLedgerOwner(configDir = getConfigDir()): SpendLedger
175
198
 
176
199
  let database: Database | undefined;
177
200
  try {
201
+ assertPrivateSqliteSidecars(prepared.path);
178
202
  database = new Database(prepared.path, { create: true });
179
203
  database.exec(`PRAGMA locking_mode = NORMAL; PRAGMA busy_timeout = ${busyTimeout}; BEGIN IMMEDIATE`);
180
204
  } catch (cause) {
@@ -194,7 +218,11 @@ export function acquireSpendLedgerOwner(configDir = getConfigDir()): SpendLedger
194
218
 
195
219
  activeOwner = { home: prepared.home, database, references: 1 };
196
220
  ownerGeneration += 1;
197
- return leaseFor(activeOwner);
221
+ const owner = activeOwner;
222
+ for (const hook of acquiredHooks) {
223
+ try { hook(owner.home); } catch { /* one hook must not prevent acquisition */ }
224
+ }
225
+ return leaseFor(owner);
198
226
  }
199
227
 
200
228
  function leaseFor(owner: ActiveOwner): SpendLedgerOwnerLease {
@@ -204,6 +232,16 @@ function leaseFor(owner: ActiveOwner): SpendLedgerOwnerLease {
204
232
  if (released) return;
205
233
  released = true;
206
234
  if (activeOwner !== owner || owner.references < 1) return;
235
+ if (owner.references === 1) {
236
+ releasing = true;
237
+ try {
238
+ for (const hook of releasingHooks) {
239
+ try { hook(); } catch { /* a flush hook must not prevent release */ }
240
+ }
241
+ } finally {
242
+ releasing = false;
243
+ }
244
+ }
207
245
  owner.references -= 1;
208
246
  if (owner.references > 0) return;
209
247
  activeOwner = null;
@@ -265,6 +303,7 @@ function trustedStorage(storage: SpendLedgerStorage): { readonly path: string; r
265
303
  * choose the destination, which is the thing ownership is supposed to decide.
266
304
  */
267
305
  export function mintSpendLedgerStorage(fileName: string): SpendLedgerStorage {
306
+ assertNotReleasing();
268
307
  if (fileName.includes("/") || fileName.includes("\\") || fileName === "." || fileName === "..") {
269
308
  throw new SpendLedgerOwnerError(
270
309
  "SPEND_LEDGER_OWNER_UNAVAILABLE",
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Presentation-only classification of an upstream failure into a small closed set of conditions.
3
+ *
4
+ * The output is what request logs and client-facing error text may name. It never carries input
5
+ * bytes: callers pass bounded structured tokens (status, type, code, reason) and optionally the
6
+ * upstream message, which is read here only through fixed lowercase keyword sets and never stored
7
+ * or returned. Routing, retry and recovery keep using their own classifiers (src/lib/errors.ts);
8
+ * this module must not feed them.
9
+ */
10
+
11
+ import { isDefiniteContextOverflow } from "./context-overflow-verdict";
12
+
13
+ export const UPSTREAM_CONDITIONS = [
14
+ "auth_failed",
15
+ "access_denied",
16
+ "context_overflow",
17
+ "location_unsupported",
18
+ "account_verification_required",
19
+ "billing_exhausted",
20
+ "model_unavailable",
21
+ "rate_limited",
22
+ "upstream_unavailable",
23
+ "upstream_failed",
24
+ "request_rejected",
25
+ ] as const;
26
+
27
+ export type UpstreamCondition = typeof UPSTREAM_CONDITIONS[number];
28
+
29
+ const CONDITION_SET: ReadonlySet<string> = new Set(UPSTREAM_CONDITIONS);
30
+
31
+ export function isUpstreamCondition(value: unknown): value is UpstreamCondition {
32
+ return typeof value === "string" && CONDITION_SET.has(value);
33
+ }
34
+
35
+ export interface UpstreamConditionEvidence {
36
+ status: number;
37
+ type?: string;
38
+ code?: string;
39
+ reason?: string;
40
+ message?: string;
41
+ }
42
+
43
+ // Structured tokens are compared after lowercasing; anything longer than this is not a token.
44
+ const MAX_TOKEN_LENGTH = 128;
45
+ // Keyword matching reads at most this much of the message.
46
+ const MAX_MESSAGE_SCAN = 4096;
47
+
48
+ const STRUCTURED: ReadonlyArray<readonly [UpstreamCondition, ReadonlySet<string>]> = [
49
+ ["context_overflow", new Set(["context_length_exceeded", "string_above_max_length", "context_window_exceeded", "prompt_too_long"])],
50
+ ["location_unsupported", new Set(["location_not_supported", "unsupported_country_region_territory", "unsupported_country", "user_location_is_not_supported"])],
51
+ ["account_verification_required", new Set(["validation_required", "verification_required", "organization_verification_required"])],
52
+ ["billing_exhausted", new Set(["insufficient_quota", "billing_hard_limit_reached", "usage_limit_reached", "usage_limit_exceeded", "1308", "monthly_request_count", "overage_request_limit_exceeded", "payment_required", "insufficient_balance", "credit_balance_too_low"])],
53
+ ["model_unavailable", new Set(["model_not_found", "unsupported_model", "model_not_available", "model_not_supported", "deployment_not_found"])],
54
+ ["rate_limited", new Set(["rate_limit_exceeded", "rate_limit_error", "too_many_requests", "throttling", "throttled", "rate_limited"])],
55
+ ["upstream_unavailable", new Set(["server_is_overloaded", "overloaded_error", "service_unavailable", "unavailable"])],
56
+ ];
57
+
58
+ // Context overflow from message text uses the same verdict the combo router trusts, so a validation
59
+ // error that merely quotes "prompt is too long" (an invalid tool name, for example) is not an overflow.
60
+ const KEYWORDS: Readonly<Record<"location_unsupported" | "account_verification_required" | "billing_exhausted" | "model_unavailable" | "rate_limited", readonly string[]>> = {
61
+ location_unsupported: ["location is not supported", "unsupported location", "not supported in your region", "region is not supported", "country, region, or territory", "not available in your country", "not available in your region"],
62
+ account_verification_required: ["verify your organization", "organization must be verified", "verification required", "verify your account", "account verification"],
63
+ billing_exhausted: ["insufficient quota", "quota exceeded", "quota exhausted", "exceeded your current quota", "run out of credits", "out of credits", "insufficient credits", "credit balance", "insufficient balance", "billing", "payment required"],
64
+ model_unavailable: ["model not found", "model does not exist", "unsupported model", "not allowed to use this model", "does not have access to model", "model is not available", "no such model"],
65
+ rate_limited: ["rate limit", "too many requests", "throttl"],
66
+ };
67
+
68
+ function token(value: string | undefined): string | undefined {
69
+ if (typeof value !== "string") return undefined;
70
+ const trimmed = value.trim();
71
+ return trimmed && trimmed.length <= MAX_TOKEN_LENGTH ? trimmed.toLowerCase() : undefined;
72
+ }
73
+
74
+ function structuredCondition(tokens: readonly string[]): UpstreamCondition | undefined {
75
+ for (const [condition, set] of STRUCTURED) {
76
+ if (tokens.some(value => set.has(value))) return condition;
77
+ }
78
+ return undefined;
79
+ }
80
+
81
+ function mentions(message: string, condition: keyof typeof KEYWORDS): boolean {
82
+ return KEYWORDS[condition].some(keyword => message.includes(keyword));
83
+ }
84
+
85
+ function statusFallback(status: number): UpstreamCondition | undefined {
86
+ if (status === 401) return "auth_failed";
87
+ if (status === 403) return "access_denied";
88
+ if (status === 402) return "billing_exhausted";
89
+ if (status === 404) return "model_unavailable";
90
+ if (status === 429) return "rate_limited";
91
+ if (status === 503 || status === 529) return "upstream_unavailable";
92
+ if (status >= 500) return "upstream_failed";
93
+ if (status >= 400) return "request_rejected";
94
+ return undefined;
95
+ }
96
+
97
+ /**
98
+ * Precedence: 401 is authoritative; structured tokens next; keyword evidence only for 4xx
99
+ * statuses (a 5xx stays a server failure whatever its text says); a bare status last.
100
+ */
101
+ export function classifyUpstreamCondition(evidence: UpstreamConditionEvidence): UpstreamCondition | undefined {
102
+ const { status } = evidence;
103
+ if (!Number.isInteger(status)) return undefined;
104
+ if (status === 401) return "auth_failed";
105
+ const tokens = [token(evidence.code), token(evidence.type), token(evidence.reason)].filter((value): value is string => value !== undefined);
106
+ const structured = structuredCondition(tokens);
107
+ if (structured) return structured;
108
+ const message = typeof evidence.message === "string" ? evidence.message.slice(0, MAX_MESSAGE_SCAN).toLowerCase() : "";
109
+ if (message && status >= 400 && status < 500) {
110
+ if (isDefiniteContextOverflow(status, evidence.message!.slice(0, MAX_MESSAGE_SCAN))) return "context_overflow";
111
+ if (mentions(message, "location_unsupported")) return "location_unsupported";
112
+ if (mentions(message, "account_verification_required")) return "account_verification_required";
113
+ // A 429 that names a rate limit is a rate limit even when it also mentions quota.
114
+ if (status === 429 && mentions(message, "rate_limited")) return "rate_limited";
115
+ if (mentions(message, "billing_exhausted")) return "billing_exhausted";
116
+ if (mentions(message, "model_unavailable")) return "model_unavailable";
117
+ if (mentions(message, "rate_limited")) return "rate_limited";
118
+ }
119
+ return statusFallback(status);
120
+ }
121
+
122
+ const MESSAGES: Readonly<Record<UpstreamCondition, string>> = {
123
+ auth_failed: "The provider rejected the configured credentials.",
124
+ access_denied: "The provider denied access to this request.",
125
+ context_overflow: "The request exceeds the model's context window.",
126
+ location_unsupported: "The provider does not serve this request from the current location.",
127
+ account_verification_required: "The provider requires account verification before serving this model.",
128
+ billing_exhausted: "The provider account has no remaining quota or credits.",
129
+ model_unavailable: "The requested model is not available from the provider.",
130
+ rate_limited: "The provider rate limit was reached; retry later.",
131
+ upstream_unavailable: "The provider is temporarily unavailable; retry later.",
132
+ upstream_failed: "The provider failed to complete the request.",
133
+ request_rejected: "The provider rejected the request.",
134
+ };
135
+
136
+ const PROVIDER_ID = /^[A-Za-z0-9._-]{1,64}$/;
137
+
138
+ /** Proxy-written text for a condition; the provider id comes from configuration, never from an error. */
139
+ export function upstreamConditionMessage(condition: UpstreamCondition, providerId?: string): string {
140
+ const base = MESSAGES[condition];
141
+ return providerId !== undefined && PROVIDER_ID.test(providerId) ? `${base} (provider: ${providerId})` : base;
142
+ }
@@ -16,6 +16,8 @@
16
16
  * the shared abort helpers from here).
17
17
  */
18
18
  import { clearableDeadline } from "./abort";
19
+ import { errorDestinationLabel, errorDestinationText, type ErrorDestinationLabel } from "./error-destination";
20
+ export { errorDestinationLabel, providerErrorDestinationLabel, errorDestinationText } from "./error-destination";
19
21
  import { redactSecretString } from "./redact";
20
22
 
21
23
  /**
@@ -198,9 +200,9 @@ export function createTransientSendBudget(): TransientSendBudget {
198
200
  */
199
201
  export class SendBudgetExhaustedError extends Error {
200
202
  readonly code = "request_send_budget_exhausted";
201
- constructor(label?: string) {
202
- super(label
203
- ? `request send budget exhausted before dispatch (${label})`
203
+ constructor(label?: ErrorDestinationLabel) {
204
+ super(label !== undefined
205
+ ? `request send budget exhausted before dispatch (${errorDestinationText(label)})`
204
206
  : "request send budget exhausted before dispatch");
205
207
  this.name = "SendBudgetExhaustedError";
206
208
  }
@@ -215,7 +217,7 @@ export class SendBudgetExhaustedError extends Error {
215
217
  */
216
218
  export class InvalidSendBudgetError extends Error {
217
219
  constructor(value: unknown) {
218
- super(`invalid upstream send budget: ${String(value)}`);
220
+ super(`invalid upstream send budget: ${typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : "invalid"}`);
219
221
  this.name = "InvalidSendBudgetError";
220
222
  }
221
223
  }
@@ -516,6 +518,8 @@ export interface ResetRetryOptions {
516
518
  abortSignal?: AbortSignal;
517
519
  /** Short host/path label for the retry warn log (no secrets/query strings). */
518
520
  label?: string;
521
+ /** Client error labels are separate from the operational retry-log label. */
522
+ destination?: ErrorDestinationLabel;
519
523
  /** Total upstream sends allowed, including the first one. Not a per-layer retry count. */
520
524
  attempts?: number;
521
525
  /**
@@ -585,14 +589,13 @@ export class UpstreamRetryEvidenceError extends Error {
585
589
  /** True when a connection-reset retry already reached the origin. */
586
590
  public readonly resetSeen = false,
587
591
  ) {
588
- const detail = cause instanceof Error ? cause.message : String(cause);
589
592
  const kinds: string[] = [];
590
593
  if (transientStatuses.length > 0) kinds.push("transient 5xx response(s)");
591
594
  if (resetSeen) kinds.push("a credential-visible connection reset");
592
595
  super(
593
596
  kinds.length > 0
594
- ? `upstream fetch failed after ${kinds.join(" and ")}: ${detail}`
595
- : `upstream fetch failed: ${detail}`,
597
+ ? `upstream fetch failed after ${kinds.join(" and ")}`
598
+ : "upstream fetch failed",
596
599
  { cause },
597
600
  );
598
601
  this.name = "UpstreamRetryEvidenceError";
@@ -652,7 +655,7 @@ export async function fetchWithResetRetry(
652
655
  // Zero is zero. The old Math.max(1, ...) floor meant an exhausted budget still bought one
653
656
  // more send on every recovery leg, which is most of what made a bounded per-layer retry
654
657
  // compose into an unbounded per-request count.
655
- if (attempts === 0) throw new SendBudgetExhaustedError(opts.label);
658
+ if (attempts === 0) throw new SendBudgetExhaustedError(opts.destination ?? (opts.label ? errorDestinationLabel(opts.label) : undefined));
656
659
  try {
657
660
  let lastError: unknown;
658
661
  let sawReset = false;
@@ -665,7 +668,7 @@ export async function fetchWithResetRetry(
665
668
  // Reported before the await, one physical send at a time: a send that rejects has still
666
669
  // been made, and this helper leaves through four exits (return, reset give-up, non-reset
667
670
  // rethrow, abort), so a per-send report is the only shape that is correct on all of them.
668
- if (opts.onSendsConsumed?.beforeSend && !opts.onSendsConsumed.beforeSend()) throw new SendBudgetExhaustedError(opts.label);
671
+ if (opts.onSendsConsumed?.beforeSend && !opts.onSendsConsumed.beforeSend()) throw new SendBudgetExhaustedError(opts.destination ?? (opts.label ? errorDestinationLabel(opts.label) : undefined));
669
672
  if (!opts.onSendsConsumed?.beforeSend) opts.onSendsConsumed?.(1);
670
673
  try {
671
674
  let response: Response;
@@ -747,7 +750,7 @@ export async function fetchWithTransientRetry(
747
750
  const countedFetch: ReplayableFetch = (recovery) => {
748
751
  // Incremented BEFORE the await so a rejected send still consumes budget; counting only
749
752
  // successes would let a reset storm loop without bound.
750
- if (opts.onSendsConsumed?.beforeSend && !opts.onSendsConsumed.beforeSend()) throw new SendBudgetExhaustedError(opts.label);
753
+ if (opts.onSendsConsumed?.beforeSend && !opts.onSendsConsumed.beforeSend()) throw new SendBudgetExhaustedError(opts.destination ?? (opts.label ? errorDestinationLabel(opts.label) : undefined));
751
754
  sent += 1;
752
755
  const run = () => doFetch(recovery);
753
756
  return opts.onSendsConsumed?.execute ? opts.onSendsConsumed.execute(run) : run();
@@ -769,7 +772,7 @@ export async function fetchWithTransientRetry(
769
772
  // and throws from one, and a caller sharing the budget across request legs must be told the
770
773
  // real count on every one of them.
771
774
  try {
772
- if (budget === 0) throw new SendBudgetExhaustedError(opts.label);
775
+ if (budget === 0) throw new SendBudgetExhaustedError(opts.destination ?? (opts.label ? errorDestinationLabel(opts.label) : undefined));
773
776
  let attemptStart = Date.now();
774
777
  let res = await fetchWithResetRetry(countedFetch, innerResetOptions());
775
778
  for (let attempt = 0; sent < budget; attempt++) {
@@ -17,7 +17,8 @@ export interface WindowsPrivateEntry {
17
17
  * - "write-private": the POSIX mode&022==0 analog for objects we did NOT create — the
18
18
  * serving token or a kernel-equivalent owner (SYSTEM, Administrators, TrustedInstaller)
19
19
  * must own the object, and no grantee outside the trusted write set may hold write,
20
- * create, delete or DACL/owner control. Read grants to anyone are fine.
20
+ * create, delete or DACL/owner control, including inherit-only templates for
21
+ * children this process may create. Read grants to anyone are fine.
21
22
  * - "trusted-ancestry": the POSIX uid∈{euid,0} + non-shared-writable ancestor analog.
22
23
  * The owner must be the serving token or a kernel-equivalent owner (SYSTEM,
23
24
  * Administrators, TrustedInstaller — each can already take ownership of any object,
@@ -26,6 +27,9 @@ export interface WindowsPrivateEntry {
26
27
  * (FILE_ADD_FILE / FILE_ADD_SUBDIRECTORY without delete or write-existing): that is
27
28
  * the closest NTFS analog of a root-owned sticky directory such as C:\, whose stock
28
29
  * ACL grants Authenticated Users add-subdirectory while refusing every other write.
30
+ * This policy checks existing ancestors only and ignores inherit-only templates;
31
+ * callers must use write-private or the stricter private policy for every direct
32
+ * parent of a new child.
29
33
  */
30
34
  export type WindowsAclPolicy = "private" | "private-runtime-directory" | "write-private" | "trusted-ancestry";
31
35
  export interface WindowsAclEntry extends WindowsPrivateEntry {
@@ -243,9 +247,9 @@ function privateEntryOk(entry: ParsedEntry | null, directory: boolean, run: Pars
243
247
  * Confined-write and trusted-ancestry policies for objects this process did not create.
244
248
  *
245
249
  * Deny ACEs are permitted because they can only remove access; allow ACEs must be
246
- * ordinary non-callback CommonAce entries. Inherit-only ACEs are skipped: they are
247
- * templates for children, and every object this module protects carries its own
248
- * hardened protected DACL, so an ancestor's template cannot grant anything inside it.
250
+ * ordinary non-callback CommonAce entries. Write-private also checks inherit-only
251
+ * templates: newly created children receive those grants before hardening. Existing
252
+ * trusted ancestors are not creation parents; each descendant is checked separately.
249
253
  */
250
254
  function confinedEntryOk(entry: ParsedEntry | null, run: ParsedAclRun, policy: WindowsAclPolicy): boolean {
251
255
  if (!entry || entry.aces === null || (entry.controlFlags & 0x4 /* SE_DACL_PRESENT */) === 0) return false;
@@ -262,9 +266,12 @@ function confinedEntryOk(entry: ParsedEntry | null, run: ParsedAclRun, policy: W
262
266
  if (ace.type === 1) continue; // ACCESS_DENIED: removes access, never grants it.
263
267
  if (ace.type !== 0) return false; // only ACCESS_ALLOWED records can be evaluated.
264
268
  if (ace.flags === null || ace.mask === null || ace.sid === null) return false;
265
- if ((ace.flags & INHERIT_ONLY_ACE) !== 0) continue;
269
+ if (policy === "trusted-ancestry" && (ace.flags & INHERIT_ONLY_ACE) !== 0) continue;
266
270
  if (ace.sid === run.user || TRUSTED_WRITE_SIDS.has(ace.sid)) continue;
267
- const createOk = policy === "trusted-ancestry" && STICKY_OWNERS.has(owner) ? CREATE_MASK : 0;
271
+ // Create rights on a sticky trusted ancestor are safe for that ancestor itself,
272
+ // but an inherit-only template would grant them inside a newly created child.
273
+ const createOk = policy === "trusted-ancestry" && STICKY_OWNERS.has(owner)
274
+ && (ace.flags & INHERIT_ONLY_ACE) === 0 ? CREATE_MASK : 0;
268
275
  const allowed = (READ_MASK | createOk) >>> 0;
269
276
  if (((ace.mask >>> 0) & ~allowed) !== 0) return false;
270
277
  }
@@ -660,10 +660,10 @@ export function windowsSecretAclReapPendingForPath(targetPath: string): boolean
660
660
  }
661
661
 
662
662
  /** Non-blocking removal guard for callers that must refuse rather than wait for a stuck child. */
663
- export function windowsSecretAclReapPendingAtOrBelow(rootPath: string): boolean {
663
+ export function windowsSecretAclReapPendingAtOrBelow(rootPath: string, includeAncestors = false): boolean {
664
664
  const root = captureRemovalIdentity(rootPath);
665
665
  return [...activeAsyncAclWork.values(), ...pendingAsyncIcaclsReaps.values()]
666
- .some(entries => [...entries].some(entry => retainedWorkIsAtOrBelow(entry, root)));
666
+ .some(entries => [...entries].some(entry => retainedWorkIsAtOrBelow(entry, root, includeAncestors)));
667
667
  }
668
668
 
669
669
  /**
@@ -14,6 +14,7 @@ const SSH_TRANSPORT_FAILURE = 255;
14
14
 
15
15
  /** Remote argv that prints the kernel name; under cmd or PowerShell, `sh` itself is refused. */
16
16
  export const REMOTE_UNAME_ARGV: readonly string[] = ["sh", "-c", "uname -s 2>/dev/null", "ocx-platform"];
17
+ const REMOTE_FRAMED_UNAME_ARGV: readonly string[] = ["sh", "-c", "printf 'ocx-platform:%s\\n' \"$(uname -s 2>/dev/null)\"", "ocx-platform"];
17
18
 
18
19
  /** Does this output come from cmd.exe or PowerShell refusing a POSIX command? */
19
20
  export function isWindowsShellRefusal(output: string): boolean {
@@ -64,3 +65,16 @@ export async function requireRemotePlatform(runner: Pick<SshRunner, "run">, alia
64
65
  if (platform === "unknown") throw new Error("Remote platform could not be determined");
65
66
  return platform;
66
67
  }
68
+
69
+ /** Fan-out ignores login-shell output and trusts only one framed uname line. */
70
+ export async function requireRemotePlatformFramed(runner: Pick<SshRunner, "run">, alias: string, knownHostsFile: string): Promise<"posix" | "windows"> {
71
+ const windows = await runner.run(buildWindowsProbeArgv({ alias, knownHostsFile }), { timeoutMs: 10_000 });
72
+ if (windows.code === SSH_TRANSPORT_FAILURE) throw new Error("SSH platform discovery failed");
73
+ if (windows.code === 0 && windows.stdout.split(/\r?\n/).some(line => line.trim() === "Windows_NT")) return "windows";
74
+ const result = await runner.run(buildExecArgv({ alias, knownHostsFile, argv: REMOTE_FRAMED_UNAME_ARGV }), { timeoutMs: 10_000 });
75
+ if (result.code === SSH_TRANSPORT_FAILURE) throw new Error("SSH platform discovery failed");
76
+ const frames = result.stdout.split(/\r?\n/).filter(line => line.startsWith("ocx-platform:"));
77
+ const name = frames.length === 1 ? frames[0]!.slice("ocx-platform:".length) : "";
78
+ if (result.code !== 0 || !POSIX_UNAME.test(name)) throw new Error("Remote platform could not be determined");
79
+ return WINDOWS_UNAME.test(name) ? "windows" : "posix";
80
+ }