@bitkyc08/opencodex 2.31.0 → 2.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/ocx.mjs +99 -70
- package/gui/dist/assets/{index-DkcRs1fL.js → index-BJwu-ldX.js} +14 -14
- package/gui/dist/assets/index-DcBbHIAz.css +1 -0
- package/gui/dist/index.html +2 -2
- package/package.json +1 -1
- package/src/adapters/anthropic.ts +6 -8
- package/src/adapters/base.ts +2 -0
- package/src/adapters/command-code.ts +2 -3
- package/src/adapters/cursor/tool-definitions.ts +1 -1
- package/src/adapters/google.ts +6 -7
- package/src/adapters/kiro.ts +0 -3
- package/src/adapters/openai-responses.ts +3 -0
- package/src/adapters/tool-catalog-nudge.ts +1 -1
- package/src/adapters/xai-web-search.ts +7 -2
- package/src/bridge.ts +21 -15
- package/src/cli/dispatch.ts +50 -2
- package/src/cli/doctor.ts +24 -11
- package/src/cli/help.ts +4 -3
- package/src/cli/index.ts +11 -4
- package/src/cli/models.ts +13 -3
- package/src/cli/observe.ts +20 -5
- package/src/cli/provider.ts +2 -1
- package/src/cli/registry.ts +7 -5
- package/src/cli/status.ts +2 -1
- package/src/cli/system-restart-client.ts +1 -1
- package/src/cli/usage-report.ts +134 -0
- package/src/codex/app-server-processes.ts +3 -1
- package/src/codex/catalog/parsing.ts +18 -0
- package/src/codex/catalog/sync.ts +5 -4
- package/src/codex/desktop-app-restart.ts +342 -0
- package/src/codex/history-job.ts +32 -3
- package/src/codex/history-manifest.ts +112 -0
- package/src/codex/history-migration-guardian.ts +5 -5
- package/src/codex/history-provider.ts +825 -247
- package/src/codex/history-worker.ts +8 -5
- package/src/codex/inject.ts +49 -21
- package/src/codex/injected-marker.ts +1 -1
- package/src/codex/internal/history-writer.ts +4 -3
- package/src/codex/native-profile-startup.ts +157 -27
- package/src/codex/native-residue.ts +26 -33
- package/src/combos/failover.ts +27 -0
- package/src/compatibility/index.ts +26 -0
- package/src/compatibility/manifest.ts +253 -0
- package/src/compatibility/openai-responses.ts +81 -0
- package/src/config/atomic-write.ts +219 -0
- package/src/config/paths.ts +40 -0
- package/src/config/process-state.ts +308 -0
- package/src/config/provider-validation.ts +177 -0
- package/src/config.ts +75 -812
- package/src/generated/compatibility-version.json +135 -79
- package/src/images/plan.ts +5 -4
- package/src/integrations/ownership-policy.ts +141 -0
- package/src/integrations/ownership.ts +10 -0
- package/src/integrations/state.ts +44 -5
- package/src/integrations/writer.ts +6 -0
- package/src/lib/bounded-body.ts +14 -2
- package/src/lib/process-control.ts +2 -1
- package/src/lib/tool-argument-integers.ts +56 -5
- package/src/oauth/health.ts +1 -1
- package/src/providers/registry.ts +1 -1
- package/src/reasoning-effort.ts +19 -2
- package/src/responses/apply-patch-envelope.ts +63 -0
- package/src/responses/custom-tool-compat.ts +132 -38
- package/src/responses/parser.ts +3 -2
- package/src/responses/reasoning-replay-cache.ts +81 -3
- package/src/server/auth-cors.ts +9 -7
- package/src/server/index.ts +102 -21
- package/src/server/local-management-read-client.ts +1 -1
- package/src/server/local-provider-reload-client.ts +1 -1
- package/src/server/management/agent-settings-routes.ts +1 -1
- package/src/server/management/config-routes.ts +4 -1
- package/src/server/management/context.ts +1 -1
- package/src/server/management/logs-usage-routes.ts +27 -6
- package/src/server/management/model-routes.ts +8 -4
- package/src/server/management/native-integration-routes.ts +2 -1
- package/src/server/management/provider-capability-config.ts +1 -1
- package/src/server/management/system-restart.ts +1 -1
- package/src/server/port-reclaim.ts +1 -1
- package/src/server/proxy-liveness.ts +2 -1
- package/src/server/request-log-conversation.ts +30 -0
- package/src/server/responses/codex-auth-error.ts +55 -0
- package/src/server/responses/combo-stream-preflight.ts +171 -0
- package/src/server/responses/compact.ts +6 -21
- package/src/server/responses/core.ts +225 -94
- package/src/server/responses/fetch-helpers.ts +2 -97
- package/src/server/responses-custom-tool-repair.ts +41 -5
- package/src/server/responses-undeclared-tool-guard.ts +156 -15
- package/src/service.ts +8 -4
- package/src/types/request.ts +6 -1
- package/src/types/tools.ts +87 -11
- package/src/types.ts +1 -1
- package/src/update/index.ts +5 -4
- package/src/update/job.ts +3 -1
- package/src/update/transactional-install.mjs +8 -1
- package/src/usage/log.ts +16 -8
- package/src/usage/summary.ts +201 -8
- package/src/vision/describe.ts +18 -13
- package/src/web-search/executor.ts +10 -3
- package/gui/dist/assets/index-CH7ncHCC.css +0 -1
package/src/config.ts
CHANGED
|
@@ -1,11 +1,22 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { homedir } from "node:os";
|
|
5
|
-
import { dirname, join, resolve } from "node:path";
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { chmodSync, constants as fsConstants, copyFileSync, existsSync, linkSync, mkdirSync, readFileSync, truncateSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
6
4
|
import { Database } from "bun:sqlite";
|
|
7
5
|
import * as z from "zod/v4";
|
|
8
6
|
import { isValidProviderName, hasOwnProvider } from "./config/provider-name";
|
|
7
|
+
import {
|
|
8
|
+
apiKeyTransportConfigError,
|
|
9
|
+
booleanRecordConfigError,
|
|
10
|
+
modelAdapterRecordConfigError,
|
|
11
|
+
nonBlankStringArrayConfigError,
|
|
12
|
+
normalizeNonBlankStringArray,
|
|
13
|
+
positiveIntegerConfigError,
|
|
14
|
+
positiveIntegerRecordConfigError,
|
|
15
|
+
providerBaseUrlConfigError,
|
|
16
|
+
providerHeadersConfigError,
|
|
17
|
+
reasoningSummaryDeliveryRecordConfigError,
|
|
18
|
+
upstreamHttpVersionConfigError,
|
|
19
|
+
} from "./config/provider-validation";
|
|
9
20
|
import {
|
|
10
21
|
bumpConfigGenerationAtPath,
|
|
11
22
|
bumpCurrentConfigGeneration,
|
|
@@ -42,25 +53,17 @@ import {
|
|
|
42
53
|
forgetEphemeralSecretPath,
|
|
43
54
|
hardenSecretDir,
|
|
44
55
|
hardenSecretPath,
|
|
45
|
-
hardenSecretPathAsync,
|
|
46
56
|
windowsSecretAclApplies,
|
|
47
57
|
} from "./lib/windows-secret-acl";
|
|
48
58
|
import { recordOwnedConfigPath } from "./lib/config-ownership";
|
|
49
59
|
import { assertNotRealHomeUnderTest } from "./lib/test-home-guard";
|
|
50
|
-
import { isLocalAttestationSecret } from "./lib/local-management-attestation";
|
|
51
60
|
import { providerDestinationConfigError } from "./lib/destination-policy";
|
|
52
61
|
import { redactSecretString } from "./lib/redact";
|
|
53
|
-
import {
|
|
54
|
-
resolveTrustedWindowsPowerShellExe,
|
|
55
|
-
resolveTrustedWindowsSystemDirectory,
|
|
56
|
-
} from "./lib/windows-elevation";
|
|
57
62
|
import { openRouterRoutingConfigError } from "./providers/openrouter-routing";
|
|
58
63
|
import {
|
|
59
|
-
isWirePinnedModel,
|
|
60
64
|
MODEL_ADAPTER_OVERRIDE_ALLOWED,
|
|
61
65
|
OPENAI_PROVIDER_TIER_VERSION,
|
|
62
66
|
pinnedWireAdapter,
|
|
63
|
-
REASONING_SUMMARY_DELIVERY_VALUES,
|
|
64
67
|
UPSTREAM_HTTP_VERSION_VALUES,
|
|
65
68
|
type OcxClaudeCodeConfig,
|
|
66
69
|
type OcxConfig,
|
|
@@ -69,7 +72,7 @@ import {
|
|
|
69
72
|
type FastWire,
|
|
70
73
|
type ProviderCostOverlay,
|
|
71
74
|
} from "./types";
|
|
72
|
-
import {
|
|
75
|
+
import { OPENAI_CODEX_PROVIDER_ID } from "./providers/openai-tiers";
|
|
73
76
|
import { fastWireDeclarationError, hasFastWireCapabilityConflict } from "./providers/fastwire";
|
|
74
77
|
import {
|
|
75
78
|
getProviderRegistryEntry,
|
|
@@ -79,7 +82,7 @@ import {
|
|
|
79
82
|
} from "./providers/registry";
|
|
80
83
|
import { resolveOpenAiVirtualModel } from "./providers/openai-virtual-models";
|
|
81
84
|
import { parseDesktopProfile } from "./claude/desktop-profile";
|
|
82
|
-
import { isCodexReasoningEffort
|
|
85
|
+
import { isCodexReasoningEffort } from "./reasoning-effort";
|
|
83
86
|
import {
|
|
84
87
|
COST4_RATE_KEYS,
|
|
85
88
|
isValidCost4Rate,
|
|
@@ -94,244 +97,49 @@ import {
|
|
|
94
97
|
MIN_APP_OWNED_MEMORY_BUDGET_MB,
|
|
95
98
|
} from "./lib/app-owned-memory";
|
|
96
99
|
import { isHostedToolUnsupportedForModel } from "./responses/hosted-tool-policy";
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
*
|
|
141
|
-
* rename(2) replaces a directory ENTRY. When the entry is itself a symlink
|
|
142
|
-
* (a dotfiles-managed `~/.codex/config.toml` -> `~/dotfiles/.codex/config.toml`,
|
|
143
|
-
* say), renaming a sibling temp file over it destroys the link and leaves a plain
|
|
144
|
-
* file behind — the repo silently stops receiving writes. Resolving first puts both
|
|
145
|
-
* the temp file and the rename target inside the link's real directory, so the entry
|
|
146
|
-
* being replaced is the real file and the symlink survives.
|
|
147
|
-
*
|
|
148
|
-
* Same-filesystem atomicity is preserved because the temp file stays beside its
|
|
149
|
-
* resolved target. A genuinely absent destination (not yet created) falls back to
|
|
150
|
-
* the literal path, which is the correct target for a first write.
|
|
151
|
-
*
|
|
152
|
-
* An EXISTING symlink that cannot be resolved — dangling because its target volume
|
|
153
|
-
* is unmounted, an ELOOP chain, an EACCES parent — is refused instead. Falling back
|
|
154
|
-
* to the literal path there would let the rename replace the link, recreating the
|
|
155
|
-
* exact dotfiles-divergence failure this helper exists to prevent (audit: wt4 wp2).
|
|
156
|
-
*/
|
|
157
|
-
export function resolveWriteTarget(path: string): string {
|
|
158
|
-
try {
|
|
159
|
-
return realpathSync(path);
|
|
160
|
-
} catch (cause) {
|
|
161
|
-
let entry;
|
|
162
|
-
try {
|
|
163
|
-
entry = lstatSync(path);
|
|
164
|
-
} catch (error) {
|
|
165
|
-
if (isMissingPathError(error)) return path; // no entry at all — first write
|
|
166
|
-
throw error;
|
|
167
|
-
}
|
|
168
|
-
if (entry.isSymbolicLink()) {
|
|
169
|
-
throw new Error(`refusing to replace unresolvable symlinked write target: ${path}`, { cause });
|
|
170
|
-
}
|
|
171
|
-
return path;
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
/**
|
|
176
|
-
* Re-apply the real-home guard to a RESOLVED write target.
|
|
177
|
-
*
|
|
178
|
-
* Callers such as saveConfig check only their logical config dir, which passes when
|
|
179
|
-
* OPENCODEX_HOME points at a temp fixture. Following a symlink out of that fixture
|
|
180
|
-
* would land on the protected home the caller's own check just cleared, so the guard
|
|
181
|
-
* has to run again on wherever the write actually terminates. Inert in production,
|
|
182
|
-
* where the guard is disarmed.
|
|
183
|
-
*/
|
|
184
|
-
function assertResolvedTargetAllowed(path: string, target: string): void {
|
|
185
|
-
// The file itself may resolve literally while its PARENT is a symlink out
|
|
186
|
-
// of the fixture (a first write beneath a symlinked config dir). Guard the
|
|
187
|
-
// directory the write actually lands in either way.
|
|
188
|
-
if (target === path) {
|
|
189
|
-
let realParent: string;
|
|
190
|
-
try {
|
|
191
|
-
realParent = realpathSync(dirname(target));
|
|
192
|
-
} catch {
|
|
193
|
-
return; // unresolvable parent: resolveWriteTarget already owns that refusal
|
|
194
|
-
}
|
|
195
|
-
if (realParent !== dirname(target)) assertNotRealHomeUnderTest(realParent);
|
|
196
|
-
return;
|
|
197
|
-
}
|
|
198
|
-
assertNotRealHomeUnderTest(dirname(target));
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
export function atomicWriteFile(path: string, content: string, io: AtomicWriteIO = {
|
|
202
|
-
write: (target, value) => writeFileSync(target, value, { encoding: "utf-8", mode: 0o600 }),
|
|
203
|
-
harden: target => {
|
|
204
|
-
try { chmodSync(target, 0o600); } catch { /* platform may ignore chmod */ }
|
|
205
|
-
// Timeout memo keyed by the stable destination (matches the async writer):
|
|
206
|
-
// a failed temp harden must not mint a new unique-temp key on every write.
|
|
207
|
-
if (process.platform === "win32") hardenSecretPath(target, { required: true, timeoutMemoKey: path });
|
|
208
|
-
},
|
|
209
|
-
rename: renameAtomicFile,
|
|
210
|
-
truncate: target => truncateSync(target, 0),
|
|
211
|
-
unlink: unlinkSync,
|
|
212
|
-
}): void {
|
|
213
|
-
recordOwnedConfigPath(resolveConfigDir(), path);
|
|
214
|
-
const target = resolveWriteTarget(path);
|
|
215
|
-
assertResolvedTargetAllowed(path, target);
|
|
216
|
-
const tmp = `${target}.ocx.${process.pid}.${++_atomicSeq}.tmp`;
|
|
217
|
-
let hardened = false;
|
|
218
|
-
try {
|
|
219
|
-
io.write(tmp, content);
|
|
220
|
-
io.harden(tmp);
|
|
221
|
-
hardened = true;
|
|
222
|
-
io.rename(tmp, target);
|
|
223
|
-
forgetEphemeralSecretPath(tmp);
|
|
224
|
-
} catch (cause) {
|
|
225
|
-
let scrubbed = false;
|
|
226
|
-
try {
|
|
227
|
-
io.truncate(tmp);
|
|
228
|
-
scrubbed = true;
|
|
229
|
-
} catch (error) {
|
|
230
|
-
if (isMissingPathError(error)) scrubbed = true;
|
|
231
|
-
else {
|
|
232
|
-
try { io.write(tmp, ""); scrubbed = true; } catch { /* removal may still succeed */ }
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
let removed = false;
|
|
236
|
-
try {
|
|
237
|
-
io.unlink(tmp);
|
|
238
|
-
removed = true;
|
|
239
|
-
} catch (error) {
|
|
240
|
-
if (isMissingPathError(error)) removed = true;
|
|
241
|
-
else {
|
|
242
|
-
try { io.unlink(tmp); removed = true; }
|
|
243
|
-
catch (retryError) { if (isMissingPathError(retryError)) removed = true; }
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
if (!removed && !scrubbed) throw new AtomicWriteSecretResidualError(tmp, { cause });
|
|
247
|
-
if (!removed && !hardened) {
|
|
248
|
-
try { io.harden(tmp); hardened = true; } catch { /* zero-byte residual is reported honestly */ }
|
|
249
|
-
}
|
|
250
|
-
if (removed) forgetEphemeralSecretPath(tmp);
|
|
251
|
-
if (!removed) throw new AtomicWriteResidualTempError(tmp, hardened, { cause });
|
|
252
|
-
throw cause;
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
/** Async atomic-write I/O: harden may await icacls without blocking the event loop (#612). */
|
|
257
|
-
export interface AtomicWriteAsyncIO {
|
|
258
|
-
write: (path: string, content: string) => void | Promise<void>;
|
|
259
|
-
harden: (path: string) => void | Promise<void>;
|
|
260
|
-
rename: (source: string, destination: string) => void | Promise<void>;
|
|
261
|
-
truncate: (path: string) => void | Promise<void>;
|
|
262
|
-
unlink: (path: string) => void | Promise<void>;
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
/** Test-only crash seam. Production callers leave this undefined. */
|
|
266
|
-
export interface AtomicWriteAsyncTestSeam {
|
|
267
|
-
afterTempWrite?: (tempPath: string) => void | Promise<void>;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
/**
|
|
271
|
-
* Async atomic write (#612): same temp+harden+rename and residual-temp policy as
|
|
272
|
-
* atomicWriteFile, but Windows ACL harden yields the event loop. Timeout memo is keyed
|
|
273
|
-
* by the final destination path (not the unique temp, not the parent directory).
|
|
274
|
-
*/
|
|
275
|
-
export async function atomicWriteFileAsync(
|
|
276
|
-
path: string,
|
|
277
|
-
content: string,
|
|
278
|
-
io?: AtomicWriteAsyncIO,
|
|
279
|
-
testSeam?: AtomicWriteAsyncTestSeam,
|
|
280
|
-
): Promise<void> {
|
|
281
|
-
const effective: AtomicWriteAsyncIO = io ?? {
|
|
282
|
-
write: (target, value) => writeFileSync(target, value, { encoding: "utf-8", mode: 0o600 }),
|
|
283
|
-
harden: async target => {
|
|
284
|
-
try { chmodSync(target, 0o600); } catch { /* platform may ignore chmod */ }
|
|
285
|
-
if (process.platform === "win32") {
|
|
286
|
-
await hardenSecretPathAsync(target, { required: true, timeoutMemoKey: path });
|
|
287
|
-
}
|
|
288
|
-
},
|
|
289
|
-
rename: renameAtomicFileAsync,
|
|
290
|
-
truncate: target => truncateSync(target, 0),
|
|
291
|
-
unlink: unlinkSync,
|
|
292
|
-
};
|
|
293
|
-
const target = resolveWriteTarget(path);
|
|
294
|
-
assertResolvedTargetAllowed(path, target);
|
|
295
|
-
const tmp = `${target}.ocx.${process.pid}.${++_atomicSeq}.tmp`;
|
|
296
|
-
let hardened = false;
|
|
297
|
-
try {
|
|
298
|
-
await effective.write(tmp, content);
|
|
299
|
-
await testSeam?.afterTempWrite?.(tmp);
|
|
300
|
-
await effective.harden(tmp);
|
|
301
|
-
hardened = true;
|
|
302
|
-
await effective.rename(tmp, target);
|
|
303
|
-
forgetEphemeralSecretPath(tmp);
|
|
304
|
-
} catch (cause) {
|
|
305
|
-
let scrubbed = false;
|
|
306
|
-
try {
|
|
307
|
-
await effective.truncate(tmp);
|
|
308
|
-
scrubbed = true;
|
|
309
|
-
} catch (error) {
|
|
310
|
-
if (isMissingPathError(error)) scrubbed = true;
|
|
311
|
-
else {
|
|
312
|
-
try { await effective.write(tmp, ""); scrubbed = true; } catch { /* removal may still succeed */ }
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
let removed = false;
|
|
316
|
-
try {
|
|
317
|
-
await effective.unlink(tmp);
|
|
318
|
-
removed = true;
|
|
319
|
-
} catch (error) {
|
|
320
|
-
if (isMissingPathError(error)) removed = true;
|
|
321
|
-
else {
|
|
322
|
-
try { await effective.unlink(tmp); removed = true; }
|
|
323
|
-
catch (retryError) { if (isMissingPathError(retryError)) removed = true; }
|
|
324
|
-
}
|
|
325
|
-
}
|
|
326
|
-
if (!removed && !scrubbed) throw new AtomicWriteSecretResidualError(tmp, { cause });
|
|
327
|
-
if (!removed && !hardened) {
|
|
328
|
-
try { await effective.harden(tmp); hardened = true; } catch { /* zero-byte residual is reported honestly */ }
|
|
329
|
-
}
|
|
330
|
-
if (removed) forgetEphemeralSecretPath(tmp);
|
|
331
|
-
if (!removed) throw new AtomicWriteResidualTempError(tmp, hardened, { cause });
|
|
332
|
-
throw cause;
|
|
333
|
-
}
|
|
334
|
-
}
|
|
100
|
+
import {
|
|
101
|
+
atomicWriteFile,
|
|
102
|
+
isMissingPathError,
|
|
103
|
+
nextAtomicTempSequence,
|
|
104
|
+
} from "./config/atomic-write";
|
|
105
|
+
export {
|
|
106
|
+
AtomicWriteResidualTempError,
|
|
107
|
+
AtomicWriteSecretResidualError,
|
|
108
|
+
atomicWriteFile,
|
|
109
|
+
atomicWriteFileAsync,
|
|
110
|
+
renameAtomicFile,
|
|
111
|
+
resolveWriteTarget,
|
|
112
|
+
type AtomicRenameIO,
|
|
113
|
+
type AtomicWriteAsyncIO,
|
|
114
|
+
type AtomicWriteAsyncTestSeam,
|
|
115
|
+
type AtomicWriteIO,
|
|
116
|
+
} from "./config/atomic-write";
|
|
117
|
+
import { getConfigDir, getConfigPath, hardenConfigDir } from "./config/paths";
|
|
118
|
+
export { expandUserPath, getConfigDir, getConfigPath, hardenConfigDir } from "./config/paths";
|
|
119
|
+
export {
|
|
120
|
+
getPidPath,
|
|
121
|
+
getRuntimePortPath,
|
|
122
|
+
isOcxStartCommandLine,
|
|
123
|
+
ocxStartProcessCacheSizeForTests,
|
|
124
|
+
parsePidFile,
|
|
125
|
+
readAlivePid,
|
|
126
|
+
readPid,
|
|
127
|
+
readPidFileValue,
|
|
128
|
+
readRuntimePort,
|
|
129
|
+
removePid,
|
|
130
|
+
removePidIfValueIs,
|
|
131
|
+
removeRuntimePort,
|
|
132
|
+
removeRuntimePortIfPidIs,
|
|
133
|
+
setOcxStartProcessCacheForTests,
|
|
134
|
+
setOcxStartProcessProbeForTests,
|
|
135
|
+
setProcessCommandLineExecForTests,
|
|
136
|
+
setProcessCommandLinePlatformForTests,
|
|
137
|
+
sweepDeadOcxStartProcessCache,
|
|
138
|
+
verifyPidIdentity,
|
|
139
|
+
writePid,
|
|
140
|
+
writeRuntimePort,
|
|
141
|
+
type RuntimePortState,
|
|
142
|
+
} from "./config/process-state";
|
|
335
143
|
|
|
336
144
|
export class OpenAiTierBackupCleanupError extends Error {
|
|
337
145
|
constructor() { super("OpenAI tier backup temporary cleanup failed"); this.name = "OpenAiTierBackupCleanupError"; }
|
|
@@ -452,7 +260,7 @@ export function backupConfigBeforeOpenAiTierMigration(
|
|
|
452
260
|
return "reused";
|
|
453
261
|
}
|
|
454
262
|
}
|
|
455
|
-
const temp = `${backup}.ocx.${process.pid}.${
|
|
263
|
+
const temp = `${backup}.ocx.${process.pid}.${nextAtomicTempSequence()}.tmp`;
|
|
456
264
|
let published = false;
|
|
457
265
|
let cleanupAttempted = false;
|
|
458
266
|
|
|
@@ -596,39 +404,6 @@ export function preserveOpenAiTierRollbackSnapshot(
|
|
|
596
404
|
throw new OpenAiTierRollbackPreserveError("Unable to find a unique rollback snapshot path", { code: "exhausted" });
|
|
597
405
|
}
|
|
598
406
|
|
|
599
|
-
/**
|
|
600
|
-
* Expand a leading `~` to the home directory in user-supplied paths
|
|
601
|
-
* (OPENCODEX_HOME/CODEX_HOME set from GUIs/service files where no shell expanded it).
|
|
602
|
-
* `~user` and `%VAR%`/`$VAR` forms pass through untouched — those belong to the shell.
|
|
603
|
-
*/
|
|
604
|
-
export function expandUserPath(raw: string): string {
|
|
605
|
-
if (raw === "~") return homedir();
|
|
606
|
-
if (raw.startsWith("~/") || raw.startsWith("~\\")) return join(homedir(), raw.slice(2));
|
|
607
|
-
return raw;
|
|
608
|
-
}
|
|
609
|
-
|
|
610
|
-
let resolvedConfigDirCache: { raw: string | undefined; path: string } | null = null;
|
|
611
|
-
|
|
612
|
-
function resolveConfigDir(): string {
|
|
613
|
-
const raw = process.env["OPENCODEX_HOME"]?.trim() || undefined;
|
|
614
|
-
if (resolvedConfigDirCache && resolvedConfigDirCache.raw === raw) return resolvedConfigDirCache.path;
|
|
615
|
-
const path = raw ? resolve(expandUserPath(raw)) : join(homedir(), ".opencodex");
|
|
616
|
-
resolvedConfigDirCache = { raw, path };
|
|
617
|
-
return path;
|
|
618
|
-
}
|
|
619
|
-
|
|
620
|
-
function resolveConfigPath(): string {
|
|
621
|
-
return join(resolveConfigDir(), "config.json");
|
|
622
|
-
}
|
|
623
|
-
|
|
624
|
-
function resolvePidPath(): string {
|
|
625
|
-
return join(resolveConfigDir(), "ocx.pid");
|
|
626
|
-
}
|
|
627
|
-
|
|
628
|
-
function resolveRuntimePortPath(): string {
|
|
629
|
-
return join(resolveConfigDir(), "runtime-port.json");
|
|
630
|
-
}
|
|
631
|
-
|
|
632
407
|
const warnedConfigFallbacks = new Set<string>();
|
|
633
408
|
const warnedInheritedFastWireConflicts = new Set<string>();
|
|
634
409
|
let lastWarningReconciledGeneration = 0;
|
|
@@ -743,30 +518,20 @@ const providerConfigSchema = z.object({
|
|
|
743
518
|
responsesSnapshotRepair: z.boolean().optional(),
|
|
744
519
|
}).passthrough();
|
|
745
520
|
|
|
746
|
-
const HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
747
|
-
const SENSITIVE_PROVIDER_HEADERS = new Set([
|
|
748
|
-
"authorization",
|
|
749
|
-
"cookie",
|
|
750
|
-
"set-cookie",
|
|
751
|
-
"proxy-authorization",
|
|
752
|
-
"x-api-key",
|
|
753
|
-
"x-goog-api-key",
|
|
754
|
-
"x-amz-security-token",
|
|
755
|
-
]);
|
|
756
|
-
|
|
757
521
|
export { isValidProviderName, hasOwnProvider } from "./config/provider-name";
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
522
|
+
export {
|
|
523
|
+
apiKeyTransportConfigError,
|
|
524
|
+
booleanRecordConfigError,
|
|
525
|
+
modelAdapterRecordConfigError,
|
|
526
|
+
nonBlankStringArrayConfigError,
|
|
527
|
+
normalizeNonBlankStringArray,
|
|
528
|
+
positiveIntegerConfigError,
|
|
529
|
+
positiveIntegerRecordConfigError,
|
|
530
|
+
providerBaseUrlConfigError,
|
|
531
|
+
providerHeadersConfigError,
|
|
532
|
+
reasoningSummaryDeliveryRecordConfigError,
|
|
533
|
+
upstreamHttpVersionConfigError,
|
|
534
|
+
} from "./config/provider-validation";
|
|
770
535
|
|
|
771
536
|
function providerResponsesPathConfigError(responsesPath: string | undefined): string | null {
|
|
772
537
|
if (responsesPath === undefined) return null;
|
|
@@ -780,19 +545,6 @@ function providerResponsesPathConfigError(responsesPath: string | undefined): st
|
|
|
780
545
|
return null;
|
|
781
546
|
}
|
|
782
547
|
|
|
783
|
-
export function providerHeadersConfigError(headers: unknown): string | null {
|
|
784
|
-
if (headers === undefined) return null;
|
|
785
|
-
if (!headers || typeof headers !== "object" || Array.isArray(headers)) return "headers must be an object";
|
|
786
|
-
for (const [name, value] of Object.entries(headers)) {
|
|
787
|
-
const normalized = name.trim().toLowerCase();
|
|
788
|
-
if (!normalized || !HEADER_NAME_PATTERN.test(name)) return "headers must use valid HTTP header names";
|
|
789
|
-
if (SENSITIVE_PROVIDER_HEADERS.has(normalized)) return `headers must not include sensitive header "${name}"; use apiKey/authMode instead`;
|
|
790
|
-
if (typeof value !== "string") return `header "${name}" value must be a string`;
|
|
791
|
-
if (/[\r\n]/.test(value)) return `header "${name}" value must not include line breaks`;
|
|
792
|
-
}
|
|
793
|
-
return null;
|
|
794
|
-
}
|
|
795
|
-
|
|
796
548
|
/**
|
|
797
549
|
* Validate `providers.<name>.modelCosts`: a plain object keyed by exact model
|
|
798
550
|
* id, each value a 4-tuple of non-negative finite USD-per-1M-token rates.
|
|
@@ -862,119 +614,6 @@ export function sanitizeModelCostsForDisplay(costs: unknown): Record<string, Pro
|
|
|
862
614
|
return Object.keys(out).length > 0 ? out : undefined;
|
|
863
615
|
}
|
|
864
616
|
|
|
865
|
-
/** Keep the configured API-key header style scoped to Anthropic-compatible key auth. */
|
|
866
|
-
export function apiKeyTransportConfigError(
|
|
867
|
-
provider: Pick<OcxProviderConfig, "adapter" | "authMode" | "apiKeyTransport">,
|
|
868
|
-
): string | null {
|
|
869
|
-
if (provider.apiKeyTransport === undefined) return null;
|
|
870
|
-
if (provider.apiKeyTransport !== "x-api-key" && provider.apiKeyTransport !== "bearer") {
|
|
871
|
-
return 'apiKeyTransport must be "x-api-key" or "bearer"';
|
|
872
|
-
}
|
|
873
|
-
if (provider.adapter !== "anthropic") {
|
|
874
|
-
return "apiKeyTransport is supported only by the anthropic adapter";
|
|
875
|
-
}
|
|
876
|
-
if (provider.authMode === "oauth" || provider.authMode === "forward" || provider.authMode === "local") {
|
|
877
|
-
return "apiKeyTransport requires Anthropic API-key authentication";
|
|
878
|
-
}
|
|
879
|
-
return null;
|
|
880
|
-
}
|
|
881
|
-
|
|
882
|
-
/**
|
|
883
|
-
* Shared runtime boundary for the per-provider upstream HTTP-version pin (#1668). Used by
|
|
884
|
-
* the management write path (providerManagementConfigError / PATCH) so it can never disagree
|
|
885
|
-
* with the strict zod load schema: a value that survives POST/PATCH is always loadable, and
|
|
886
|
-
* a value the loader rejects is rejected at write time too.
|
|
887
|
-
*/
|
|
888
|
-
export function upstreamHttpVersionConfigError(value: unknown): string | null {
|
|
889
|
-
if (value === undefined || value === null) return null;
|
|
890
|
-
if (typeof value !== "string" || !(UPSTREAM_HTTP_VERSION_VALUES as readonly string[]).includes(value)) {
|
|
891
|
-
return 'upstreamHttpVersion must be one of "auto", "http1.1", "h1", "http2", "h2", or null to clear';
|
|
892
|
-
}
|
|
893
|
-
return null;
|
|
894
|
-
}
|
|
895
|
-
|
|
896
|
-
export function positiveIntegerRecordConfigError(value: unknown, field: string): string | null {
|
|
897
|
-
if (value === undefined) return null;
|
|
898
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return `${field} must be a plain object`;
|
|
899
|
-
const prototype = Object.getPrototypeOf(value);
|
|
900
|
-
if (prototype !== Object.prototype && prototype !== null) return `${field} must be a plain object with own properties`;
|
|
901
|
-
for (const [key, entry] of Object.entries(value)) {
|
|
902
|
-
if (!key.trim()) return `${field} keys must be nonblank model ids`;
|
|
903
|
-
if (typeof entry !== "number" || !Number.isFinite(entry) || !Number.isInteger(entry) || entry <= 0) {
|
|
904
|
-
return `${field}.${key} must be a positive finite integer`;
|
|
905
|
-
}
|
|
906
|
-
}
|
|
907
|
-
return null;
|
|
908
|
-
}
|
|
909
|
-
|
|
910
|
-
export function positiveIntegerConfigError(value: unknown, field: string): string | null {
|
|
911
|
-
if (value === undefined) return null;
|
|
912
|
-
if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value) || value <= 0) {
|
|
913
|
-
return `${field} must be a positive finite integer`;
|
|
914
|
-
}
|
|
915
|
-
return null;
|
|
916
|
-
}
|
|
917
|
-
|
|
918
|
-
export function nonBlankStringArrayConfigError(value: unknown, field: string): string | null {
|
|
919
|
-
if (value === undefined) return null;
|
|
920
|
-
if (!Array.isArray(value)) return `${field} must be an array`;
|
|
921
|
-
for (const [index, entry] of value.entries()) {
|
|
922
|
-
if (typeof entry !== "string" || !entry.trim()) {
|
|
923
|
-
return `${field}.${index} must be a nonblank model id`;
|
|
924
|
-
}
|
|
925
|
-
}
|
|
926
|
-
return null;
|
|
927
|
-
}
|
|
928
|
-
|
|
929
|
-
/**
|
|
930
|
-
* Keep hand-edited config and management writes on one canonical model-id list.
|
|
931
|
-
* Validation happens separately so an all-whitespace value is rejected rather than
|
|
932
|
-
* normalized into a model id that can never match at runtime.
|
|
933
|
-
*/
|
|
934
|
-
export function normalizeNonBlankStringArray(value: readonly string[]): string[] {
|
|
935
|
-
return [...new Set(value.map(entry => entry.trim()))];
|
|
936
|
-
}
|
|
937
|
-
|
|
938
|
-
export function booleanRecordConfigError(value: unknown, field: string): string | null {
|
|
939
|
-
if (value === undefined) return null;
|
|
940
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return `${field} must be a plain object`;
|
|
941
|
-
const prototype = Object.getPrototypeOf(value);
|
|
942
|
-
if (prototype !== Object.prototype && prototype !== null) return `${field} must be a plain object with own properties`;
|
|
943
|
-
for (const [key, entry] of Object.entries(value)) {
|
|
944
|
-
if (!key.trim()) return `${field} keys must be nonblank model ids`;
|
|
945
|
-
if (typeof entry !== "boolean") return `${field}.${key} must be a boolean`;
|
|
946
|
-
}
|
|
947
|
-
return null;
|
|
948
|
-
}
|
|
949
|
-
|
|
950
|
-
const REASONING_SUMMARY_DELIVERY_SET = new Set<string>(REASONING_SUMMARY_DELIVERY_VALUES);
|
|
951
|
-
|
|
952
|
-
export function reasoningSummaryDeliveryRecordConfigError(
|
|
953
|
-
value: unknown,
|
|
954
|
-
supportsReasoningSummaries: unknown,
|
|
955
|
-
field = "modelReasoningSummaryDelivery",
|
|
956
|
-
): string | null {
|
|
957
|
-
if (value === undefined) return null;
|
|
958
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return `${field} must be a plain object`;
|
|
959
|
-
const prototype = Object.getPrototypeOf(value);
|
|
960
|
-
if (prototype !== Object.prototype && prototype !== null) return `${field} must be a plain object with own properties`;
|
|
961
|
-
|
|
962
|
-
const supports = booleanRecordConfigError(supportsReasoningSummaries, "modelSupportsReasoningSummaries") === null
|
|
963
|
-
&& supportsReasoningSummaries && typeof supportsReasoningSummaries === "object"
|
|
964
|
-
? supportsReasoningSummaries as Record<string, boolean>
|
|
965
|
-
: undefined;
|
|
966
|
-
for (const [key, entry] of Object.entries(value)) {
|
|
967
|
-
if (!key.trim()) return `${field} keys must be nonblank model ids`;
|
|
968
|
-
if (typeof entry !== "string" || !REASONING_SUMMARY_DELIVERY_SET.has(entry)) {
|
|
969
|
-
return `${field}.${key} must be one of: ${REASONING_SUMMARY_DELIVERY_VALUES.join(", ")}`;
|
|
970
|
-
}
|
|
971
|
-
if (modelRecordValue(supports, key) === false) {
|
|
972
|
-
return `${field}.${key} conflicts with modelSupportsReasoningSummaries=false`;
|
|
973
|
-
}
|
|
974
|
-
}
|
|
975
|
-
return null;
|
|
976
|
-
}
|
|
977
|
-
|
|
978
617
|
const SUPPORTED_PREFERRED_HOSTED_TOOLS = new Set(["image_generation"]);
|
|
979
618
|
|
|
980
619
|
export function modelPreferHostedToolsConfigError(
|
|
@@ -1069,41 +708,6 @@ export function modelPreferHostedToolsConfigError(
|
|
|
1069
708
|
return null;
|
|
1070
709
|
}
|
|
1071
710
|
|
|
1072
|
-
/**
|
|
1073
|
-
* Validate a provider's per-model wire override map (#404).
|
|
1074
|
-
*
|
|
1075
|
-
* Rejects, rather than silently ignoring, configurations the resolver would refuse:
|
|
1076
|
-
* a value outside the allowed wires, a model the upstream pins to one wire, and any
|
|
1077
|
-
* override on a canonical forward provider (where switching wires would drop the
|
|
1078
|
-
* caller's forwarded credential). Silently dropping them would leave the user
|
|
1079
|
-
* believing an override is in effect.
|
|
1080
|
-
*/
|
|
1081
|
-
export function modelAdapterRecordConfigError(
|
|
1082
|
-
value: unknown,
|
|
1083
|
-
field: string,
|
|
1084
|
-
providerName: string,
|
|
1085
|
-
provider: { adapter?: unknown; authMode?: unknown; baseUrl?: unknown },
|
|
1086
|
-
): string | null {
|
|
1087
|
-
if (value === undefined) return null;
|
|
1088
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return `${field} must be a plain object`;
|
|
1089
|
-
const prototype = Object.getPrototypeOf(value);
|
|
1090
|
-
if (prototype !== Object.prototype && prototype !== null) return `${field} must be a plain object with own properties`;
|
|
1091
|
-
const entries = Object.entries(value);
|
|
1092
|
-
if (entries.length > 0 && isCanonicalOpenAiForwardProvider(provider as OcxProviderConfig)) {
|
|
1093
|
-
return `${field} is not supported on the canonical ChatGPT forward provider`;
|
|
1094
|
-
}
|
|
1095
|
-
for (const [key, entry] of entries) {
|
|
1096
|
-
if (!key.trim()) return `${field} keys must be nonblank model ids`;
|
|
1097
|
-
if (typeof entry !== "string" || !MODEL_ADAPTER_OVERRIDE_ALLOWED.has(entry)) {
|
|
1098
|
-
return `${field}.${key} must be one of: ${[...MODEL_ADAPTER_OVERRIDE_ALLOWED].join(", ")}`;
|
|
1099
|
-
}
|
|
1100
|
-
if (isWirePinnedModel(providerName, key.trim())) {
|
|
1101
|
-
return `${field}.${key} cannot be overridden: the upstream only speaks one wire for this model`;
|
|
1102
|
-
}
|
|
1103
|
-
}
|
|
1104
|
-
return null;
|
|
1105
|
-
}
|
|
1106
|
-
|
|
1107
711
|
const CODEX_ACCOUNT_NAMESPACES_RECORD_ERROR =
|
|
1108
712
|
"codexAccountNamespaces must be a plain object mapping account selectors to Codex account ids";
|
|
1109
713
|
const CODEX_ACCOUNT_NAMESPACE_KEY_ERROR =
|
|
@@ -1652,35 +1256,6 @@ const configSchema = z.object({
|
|
|
1652
1256
|
*/
|
|
1653
1257
|
export const DEFAULT_SUBAGENT_MODELS = ["gpt-5.5", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.4-mini"];
|
|
1654
1258
|
|
|
1655
|
-
export function getConfigDir(): string {
|
|
1656
|
-
return resolveConfigDir();
|
|
1657
|
-
}
|
|
1658
|
-
|
|
1659
|
-
export function getConfigPath(): string {
|
|
1660
|
-
return resolveConfigPath();
|
|
1661
|
-
}
|
|
1662
|
-
|
|
1663
|
-
export function getPidPath(): string {
|
|
1664
|
-
return resolvePidPath();
|
|
1665
|
-
}
|
|
1666
|
-
|
|
1667
|
-
export function getRuntimePortPath(): string {
|
|
1668
|
-
return resolveRuntimePortPath();
|
|
1669
|
-
}
|
|
1670
|
-
|
|
1671
|
-
export function hardenConfigDir(): void {
|
|
1672
|
-
const dir = getConfigDir();
|
|
1673
|
-
// The guard runs BEFORE any mutation: refusing the write after chmod/ACL
|
|
1674
|
-
// would already have changed the protected directory (review round 2).
|
|
1675
|
-
assertNotRealHomeUnderTest(dir);
|
|
1676
|
-
if (existsSync(dir)) {
|
|
1677
|
-
try { chmodSync(dir, 0o700); } catch { /* best-effort */ }
|
|
1678
|
-
if (process.platform === "win32") {
|
|
1679
|
-
hardenSecretDir(dir, { required: false });
|
|
1680
|
-
}
|
|
1681
|
-
}
|
|
1682
|
-
}
|
|
1683
|
-
|
|
1684
1259
|
export function hardenExistingSecret(path: string): void {
|
|
1685
1260
|
if (existsSync(path)) {
|
|
1686
1261
|
try { chmodSync(path, 0o600); } catch { /* best-effort */ }
|
|
@@ -3443,91 +3018,6 @@ export function applyProxyEnv(config: OcxConfig): void {
|
|
|
3443
3018
|
process.env.NO_PROXY = entries.join(",");
|
|
3444
3019
|
}
|
|
3445
3020
|
|
|
3446
|
-
export function writePid(pid: number): void {
|
|
3447
|
-
const dir = getConfigDir();
|
|
3448
|
-
// Guard before ANY directory mutation (mkdir or chmod), not just the write.
|
|
3449
|
-
assertNotRealHomeUnderTest(dir);
|
|
3450
|
-
if (!existsSync(dir)) {
|
|
3451
|
-
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
3452
|
-
} else {
|
|
3453
|
-
hardenConfigDir();
|
|
3454
|
-
}
|
|
3455
|
-
atomicWriteFile(getPidPath(), String(pid));
|
|
3456
|
-
}
|
|
3457
|
-
|
|
3458
|
-
export type RuntimePortState = {
|
|
3459
|
-
pid: number;
|
|
3460
|
-
port: number;
|
|
3461
|
-
hostname?: string;
|
|
3462
|
-
/** Per-process proof key; protected by the config directory and never served. */
|
|
3463
|
-
attestationSecret?: string;
|
|
3464
|
-
};
|
|
3465
|
-
|
|
3466
|
-
function isValidRuntimePortState(value: unknown): value is RuntimePortState {
|
|
3467
|
-
if (!value || typeof value !== "object") return false;
|
|
3468
|
-
const state = value as Record<string, unknown>;
|
|
3469
|
-
const hostnameOk = state.hostname === undefined || typeof state.hostname === "string";
|
|
3470
|
-
const attestationOk = state.attestationSecret === undefined || isLocalAttestationSecret(state.attestationSecret);
|
|
3471
|
-
return Number.isSafeInteger(state.pid)
|
|
3472
|
-
&& Number(state.pid) > 0
|
|
3473
|
-
&& Number.isInteger(state.port)
|
|
3474
|
-
&& Number(state.port) > 0
|
|
3475
|
-
&& Number(state.port) <= 65535
|
|
3476
|
-
&& hostnameOk
|
|
3477
|
-
&& attestationOk;
|
|
3478
|
-
}
|
|
3479
|
-
|
|
3480
|
-
export function writeRuntimePort(state: RuntimePortState): void {
|
|
3481
|
-
const dir = getConfigDir();
|
|
3482
|
-
// Guard before ANY directory mutation (mkdir or chmod), not just the write.
|
|
3483
|
-
assertNotRealHomeUnderTest(dir);
|
|
3484
|
-
if (!existsSync(dir)) {
|
|
3485
|
-
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
3486
|
-
} else {
|
|
3487
|
-
hardenConfigDir();
|
|
3488
|
-
}
|
|
3489
|
-
atomicWriteFile(getRuntimePortPath(), JSON.stringify(state, null, 2) + "\n");
|
|
3490
|
-
}
|
|
3491
|
-
|
|
3492
|
-
export function readPid(): number | null {
|
|
3493
|
-
const pidPath = getPidPath();
|
|
3494
|
-
if (!existsSync(pidPath)) return null;
|
|
3495
|
-
try {
|
|
3496
|
-
const raw = readFileSync(pidPath, "utf-8").trim();
|
|
3497
|
-
const pid = parsePidFile(raw);
|
|
3498
|
-
if (pid === null) return null;
|
|
3499
|
-
try {
|
|
3500
|
-
process.kill(pid, 0);
|
|
3501
|
-
return isLikelyOcxStartProcess(pid) ? pid : null;
|
|
3502
|
-
} catch (e: unknown) {
|
|
3503
|
-
if ((e as NodeJS.ErrnoException).code === "EPERM") {
|
|
3504
|
-
return isLikelyOcxStartProcess(pid) ? pid : null;
|
|
3505
|
-
}
|
|
3506
|
-
return null;
|
|
3507
|
-
}
|
|
3508
|
-
} catch {
|
|
3509
|
-
return null;
|
|
3510
|
-
}
|
|
3511
|
-
}
|
|
3512
|
-
|
|
3513
|
-
export function readRuntimePort(expectedPid?: number): RuntimePortState | null {
|
|
3514
|
-
try {
|
|
3515
|
-
const parsed = JSON.parse(readFileSync(getRuntimePortPath(), "utf-8"));
|
|
3516
|
-
if (!isValidRuntimePortState(parsed)) return null;
|
|
3517
|
-
if (expectedPid !== undefined && parsed.pid !== expectedPid) return null;
|
|
3518
|
-
return parsed;
|
|
3519
|
-
} catch {
|
|
3520
|
-
return null;
|
|
3521
|
-
}
|
|
3522
|
-
}
|
|
3523
|
-
|
|
3524
|
-
export function removePid(expectedPid?: number): void {
|
|
3525
|
-
if (expectedPid !== undefined && readPidFileValue() !== expectedPid) return;
|
|
3526
|
-
try {
|
|
3527
|
-
unlinkSync(getPidPath());
|
|
3528
|
-
} catch { /* ignore */ }
|
|
3529
|
-
}
|
|
3530
|
-
|
|
3531
3021
|
function warnConfigRepaired(configPath: string, error: z.ZodError): void {
|
|
3532
3022
|
if (warnedConfigFallbacks.has(configPath)) return;
|
|
3533
3023
|
warnedConfigFallbacks.add(configPath);
|
|
@@ -3723,233 +3213,6 @@ function warnDroppedConfigSections(configPath: string, dropped: string[], issues
|
|
|
3723
3213
|
);
|
|
3724
3214
|
}
|
|
3725
3215
|
|
|
3726
|
-
export function readPidFileValue(): number | null {
|
|
3727
|
-
try {
|
|
3728
|
-
return parsePidFile(readFileSync(getPidPath(), "utf-8"));
|
|
3729
|
-
} catch {
|
|
3730
|
-
return null;
|
|
3731
|
-
}
|
|
3732
|
-
}
|
|
3733
|
-
|
|
3734
|
-
export function removeRuntimePort(expectedPid?: number): void {
|
|
3735
|
-
if (expectedPid !== undefined && readRuntimePort(expectedPid) === null) return;
|
|
3736
|
-
try {
|
|
3737
|
-
unlinkSync(getRuntimePortPath());
|
|
3738
|
-
} catch { /* ignore */ }
|
|
3739
|
-
}
|
|
3740
|
-
|
|
3741
|
-
/**
|
|
3742
|
-
* Snapshot-guarded stale-state purge: remove the pid/runtime files only when their content
|
|
3743
|
-
* still matches what the caller saw BEFORE its liveness probe. A concurrent `ocx start` can
|
|
3744
|
-
* write fresh records mid-probe; an unconditional purge would erase the new proxy's state.
|
|
3745
|
-
*/
|
|
3746
|
-
export function removePidIfValueIs(snapshot: number | null): void {
|
|
3747
|
-
if (!existsSync(getPidPath())) return;
|
|
3748
|
-
if (readPidFileValue() !== snapshot) return;
|
|
3749
|
-
try {
|
|
3750
|
-
unlinkSync(getPidPath());
|
|
3751
|
-
} catch { /* ignore */ }
|
|
3752
|
-
}
|
|
3753
|
-
|
|
3754
|
-
export function removeRuntimePortIfPidIs(snapshotPid: number | null): void {
|
|
3755
|
-
const current = readRuntimePort();
|
|
3756
|
-
if ((current?.pid ?? null) !== snapshotPid) return;
|
|
3757
|
-
try {
|
|
3758
|
-
unlinkSync(getRuntimePortPath());
|
|
3759
|
-
} catch { /* ignore */ }
|
|
3760
|
-
}
|
|
3761
|
-
|
|
3762
|
-
export function parsePidFile(raw: string): number | null {
|
|
3763
|
-
const trimmed = raw.trim();
|
|
3764
|
-
if (!/^\d+$/.test(trimmed)) return null;
|
|
3765
|
-
const pid = Number.parseInt(trimmed, 10);
|
|
3766
|
-
return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
|
|
3767
|
-
}
|
|
3768
|
-
|
|
3769
|
-
export function isOcxStartCommandLine(commandLine: string): boolean {
|
|
3770
|
-
const normalized = commandLine.toLowerCase().replace(/\\/g, "/");
|
|
3771
|
-
// "src/cli.ts" matches pre-restructure installs still running; "src/cli/index.ts" is current.
|
|
3772
|
-
// `@bitkyc08/.opencodex-*` is npm's in-place rename of the global package during
|
|
3773
|
-
// `npm install -g` — a Windows service wrapper can respawn from that temp tree
|
|
3774
|
-
// mid-update, and must still count as ocx for port reclaim.
|
|
3775
|
-
const hasOcxEntrypoint = normalized.includes("src/cli.ts")
|
|
3776
|
-
|| normalized.includes("src/cli/index.ts")
|
|
3777
|
-
|| normalized.includes("@bitkyc08/opencodex")
|
|
3778
|
-
|| /@bitkyc08\/\.opencodex-/.test(normalized)
|
|
3779
|
-
|| /(?:^|[\s/"'])(?:ocx|opencodex)(?:\.cmd)?(?:$|[\s"'])/.test(normalized);
|
|
3780
|
-
return hasOcxEntrypoint && /(?:^|[\s"'])start(?:$|[\s"'])/.test(normalized);
|
|
3781
|
-
}
|
|
3782
|
-
|
|
3783
|
-
/** Per-process memo: waitForProxy/findLiveProxy used to spawn powershell on every 150ms poll. */
|
|
3784
|
-
const ocxStartProcessCache = new Map<number, boolean>();
|
|
3785
|
-
let ocxStartProcessSweepCursor = 0;
|
|
3786
|
-
let ocxStartProcessProbe: (pid: number) => void = pid => { process.kill(pid, 0); };
|
|
3787
|
-
|
|
3788
|
-
export function setOcxStartProcessProbeForTests(probe: ((pid: number) => void) | null): void {
|
|
3789
|
-
ocxStartProcessProbe = probe ?? (pid => { process.kill(pid, 0); });
|
|
3790
|
-
}
|
|
3791
|
-
|
|
3792
|
-
export function setOcxStartProcessCacheForTests(entries: Iterable<readonly [number, boolean]>): void {
|
|
3793
|
-
ocxStartProcessCache.clear();
|
|
3794
|
-
for (const [pid, value] of entries) ocxStartProcessCache.set(pid, value);
|
|
3795
|
-
ocxStartProcessSweepCursor = 0;
|
|
3796
|
-
}
|
|
3797
|
-
|
|
3798
|
-
export function sweepDeadOcxStartProcessCache(maxProbes = 64): number {
|
|
3799
|
-
const pids: number[] = [];
|
|
3800
|
-
let removed = 0;
|
|
3801
|
-
for (const pid of ocxStartProcessCache.keys()) {
|
|
3802
|
-
if (Number.isSafeInteger(pid) && pid > 0) pids.push(pid);
|
|
3803
|
-
else if (ocxStartProcessCache.delete(pid)) removed += 1;
|
|
3804
|
-
}
|
|
3805
|
-
if (pids.length === 0 || maxProbes <= 0) {
|
|
3806
|
-
ocxStartProcessSweepCursor = 0;
|
|
3807
|
-
return removed;
|
|
3808
|
-
}
|
|
3809
|
-
const probeCount = Math.min(Math.floor(maxProbes), pids.length);
|
|
3810
|
-
const start = ocxStartProcessSweepCursor % pids.length;
|
|
3811
|
-
for (let offset = 0; offset < probeCount; offset += 1) {
|
|
3812
|
-
const pid = pids[(start + offset) % pids.length]!;
|
|
3813
|
-
try {
|
|
3814
|
-
ocxStartProcessProbe(pid);
|
|
3815
|
-
} catch (error) {
|
|
3816
|
-
if ((error as NodeJS.ErrnoException).code !== "ESRCH") continue;
|
|
3817
|
-
if (ocxStartProcessCache.delete(pid)) removed += 1;
|
|
3818
|
-
}
|
|
3819
|
-
}
|
|
3820
|
-
ocxStartProcessSweepCursor = (start + probeCount) % pids.length;
|
|
3821
|
-
return removed;
|
|
3822
|
-
}
|
|
3823
|
-
|
|
3824
|
-
export function ocxStartProcessCacheSizeForTests(): number {
|
|
3825
|
-
return ocxStartProcessCache.size;
|
|
3826
|
-
}
|
|
3827
|
-
|
|
3828
|
-
function isLikelyOcxStartProcess(pid: number): boolean {
|
|
3829
|
-
const cached = ocxStartProcessCache.get(pid);
|
|
3830
|
-
if (cached !== undefined) return cached;
|
|
3831
|
-
const commandLine = readProcessCommandLine(pid);
|
|
3832
|
-
if (commandLine === undefined) return false;
|
|
3833
|
-
const ok = isOcxStartCommandLine(commandLine);
|
|
3834
|
-
ocxStartProcessCache.set(pid, ok);
|
|
3835
|
-
return ok;
|
|
3836
|
-
}
|
|
3837
|
-
|
|
3838
|
-
/**
|
|
3839
|
-
* Alive pid from the pid file without the expensive Windows command-line probe.
|
|
3840
|
-
* Safe for liveness polls: callers still identity-check /healthz before trusting the proxy.
|
|
3841
|
-
* Destructive stop/kill paths should keep using {@link readPid}, which verifies the cmdline.
|
|
3842
|
-
*/
|
|
3843
|
-
export function readAlivePid(): number | null {
|
|
3844
|
-
const pid = readPidFileValue();
|
|
3845
|
-
if (pid === null) return null;
|
|
3846
|
-
try {
|
|
3847
|
-
process.kill(pid, 0);
|
|
3848
|
-
return pid;
|
|
3849
|
-
} catch (e: unknown) {
|
|
3850
|
-
if ((e as NodeJS.ErrnoException).code === "EPERM") return pid;
|
|
3851
|
-
return null;
|
|
3852
|
-
}
|
|
3853
|
-
}
|
|
3854
|
-
|
|
3855
|
-
/**
|
|
3856
|
-
* Full identity check of a KNOWN candidate pid (alive + ocx-start command line).
|
|
3857
|
-
* Companion to {@link readAlivePid}: liveness discovery may be cheap, but any pid
|
|
3858
|
-
* handed to a destructive caller must pass this check — and must equal the candidate
|
|
3859
|
-
* it was asked about, so a pidfile rewrite between discovery and verification can
|
|
3860
|
-
* never swap in a different process (TOCTOU guard).
|
|
3861
|
-
*/
|
|
3862
|
-
export function verifyPidIdentity(candidatePid: number): number | null {
|
|
3863
|
-
try {
|
|
3864
|
-
process.kill(candidatePid, 0);
|
|
3865
|
-
} catch (e: unknown) {
|
|
3866
|
-
if ((e as NodeJS.ErrnoException).code !== "EPERM") return null;
|
|
3867
|
-
}
|
|
3868
|
-
return isLikelyOcxStartProcess(candidatePid) ? candidatePid : null;
|
|
3869
|
-
}
|
|
3870
|
-
|
|
3871
|
-
type ProcessCommandLineExec = (
|
|
3872
|
-
executable: string,
|
|
3873
|
-
args: string[],
|
|
3874
|
-
options: {
|
|
3875
|
-
encoding: BufferEncoding;
|
|
3876
|
-
stdio: ["ignore", "pipe", "ignore"];
|
|
3877
|
-
timeout: number;
|
|
3878
|
-
windowsHide: boolean;
|
|
3879
|
-
},
|
|
3880
|
-
) => string;
|
|
3881
|
-
|
|
3882
|
-
const defaultProcessCommandLineExec: ProcessCommandLineExec = (executable, args, options) =>
|
|
3883
|
-
execFileSync(executable, args, options);
|
|
3884
|
-
let processCommandLineExec = defaultProcessCommandLineExec;
|
|
3885
|
-
let processCommandLinePlatformForTests: NodeJS.Platform | null = null;
|
|
3886
|
-
|
|
3887
|
-
/** Test-only seam for verifying the exact system executable selected by pid identity probes. */
|
|
3888
|
-
export function setProcessCommandLineExecForTests(next: ProcessCommandLineExec | null): void {
|
|
3889
|
-
processCommandLineExec = next ?? defaultProcessCommandLineExec;
|
|
3890
|
-
}
|
|
3891
|
-
|
|
3892
|
-
/** Test-only seam so cross-platform tests do not mutate process.platform. */
|
|
3893
|
-
export function setProcessCommandLinePlatformForTests(next: NodeJS.Platform | null): void {
|
|
3894
|
-
processCommandLinePlatformForTests = next;
|
|
3895
|
-
}
|
|
3896
|
-
|
|
3897
|
-
function readProcessCommandLine(pid: number): string | undefined {
|
|
3898
|
-
if (!Number.isSafeInteger(pid) || pid <= 0) return undefined;
|
|
3899
|
-
const platform = processCommandLinePlatformForTests ?? process.platform;
|
|
3900
|
-
try {
|
|
3901
|
-
if (platform === "linux") {
|
|
3902
|
-
try {
|
|
3903
|
-
const output = readFileSync(`/proc/${pid}/cmdline`, "utf-8");
|
|
3904
|
-
const value = output.replace(/\0/g, " ").trim();
|
|
3905
|
-
if (value) return value;
|
|
3906
|
-
} catch {
|
|
3907
|
-
/* procfs unavailable — use the fixed ps fallback below */
|
|
3908
|
-
}
|
|
3909
|
-
}
|
|
3910
|
-
if (platform === "win32") {
|
|
3911
|
-
// Prefer WMIC over PowerShell: much faster cold start, and windowsHide avoids console flash.
|
|
3912
|
-
// Fall back to PowerShell when WMIC is absent (newer Windows images).
|
|
3913
|
-
const wmic = join(resolveTrustedWindowsSystemDirectory(), "wbem", "WMIC.exe");
|
|
3914
|
-
try {
|
|
3915
|
-
const output = processCommandLineExec(wmic, [
|
|
3916
|
-
"process", "where", `ProcessId=${pid}`, "get", "CommandLine", "/VALUE",
|
|
3917
|
-
], { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 3000, windowsHide: true });
|
|
3918
|
-
const match = /^CommandLine=(.*)$/m.exec(output.replace(/\r/g, ""));
|
|
3919
|
-
const value = match?.[1]?.trim();
|
|
3920
|
-
if (value) return value;
|
|
3921
|
-
} catch {
|
|
3922
|
-
/* WMIC missing or failed — fall through */
|
|
3923
|
-
}
|
|
3924
|
-
const output = processCommandLineExec(resolveTrustedWindowsPowerShellExe(), [
|
|
3925
|
-
"-NoProfile",
|
|
3926
|
-
"-NoLogo",
|
|
3927
|
-
"-NonInteractive",
|
|
3928
|
-
"-Command",
|
|
3929
|
-
`(Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}").CommandLine`,
|
|
3930
|
-
], { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 3000, windowsHide: true });
|
|
3931
|
-
return output.trim() || undefined;
|
|
3932
|
-
}
|
|
3933
|
-
for (const ps of ["/bin/ps", "/usr/bin/ps"]) {
|
|
3934
|
-
try {
|
|
3935
|
-
const output = processCommandLineExec(ps, ["-p", String(pid), "-o", "command="], {
|
|
3936
|
-
encoding: "utf-8",
|
|
3937
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
3938
|
-
timeout: 1000,
|
|
3939
|
-
windowsHide: true,
|
|
3940
|
-
});
|
|
3941
|
-
const value = output.trim();
|
|
3942
|
-
if (value) return value;
|
|
3943
|
-
} catch {
|
|
3944
|
-
/* try the other fixed system path */
|
|
3945
|
-
}
|
|
3946
|
-
}
|
|
3947
|
-
return undefined;
|
|
3948
|
-
} catch {
|
|
3949
|
-
return undefined;
|
|
3950
|
-
}
|
|
3951
|
-
}
|
|
3952
|
-
|
|
3953
3216
|
function warnAndBackupInvalidConfig(configPath: string, error: unknown): void {
|
|
3954
3217
|
if (warnedConfigFallbacks.has(configPath)) return;
|
|
3955
3218
|
warnedConfigFallbacks.add(configPath);
|