@hasna/switcher 0.2.6 → 0.2.8

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.
@@ -0,0 +1,24 @@
1
+ import type { PreparedLaunch } from "./harness-types";
2
+ type Thread = {
3
+ id: string;
4
+ name?: string | null;
5
+ preview?: string;
6
+ cwd: string;
7
+ };
8
+ type Page = {
9
+ data: Thread[];
10
+ nextCursor: string | null;
11
+ };
12
+ type Query = {
13
+ cursor?: string;
14
+ searchTerm?: string;
15
+ cwd?: string;
16
+ limit: number;
17
+ };
18
+ /** A metadata-only app-server process. Never starts/resumes a thread or sends
19
+ * inference; every page has a finite deadline and the owned process is reaped. */
20
+ export declare function listCodexSessions(prepared: PreparedLaunch, cwd: string, query: Query): Promise<Page>;
21
+ /** Switcher's picker asks the native catalog for all providers, then resumes
22
+ * the selected exact native ID. The original transcript is never rewritten. */
23
+ export declare function resolveCodexResumeArguments(prepared: PreparedLaunch, nativeArgs: string[], cwd: string, list?: (prepared: PreparedLaunch, cwd: string, query: Query) => Promise<Page>): Promise<string[]>;
24
+ export {};
@@ -0,0 +1,14 @@
1
+ import { Transform } from "node:stream";
2
+ type ObjectValue = Record<string, unknown>;
3
+ export type CodexStateRouting = {
4
+ model: string;
5
+ config: ObjectValue;
6
+ };
7
+ /** Supported native RPC only: catalog read-repair and current launch routing.
8
+ * Thread IDs, histories, tool calls, permissions and response bytes are intact. */
9
+ export declare function rewriteCodexStateRequest(line: Buffer, routing: CodexStateRouting): Buffer;
10
+ export declare function codexStateRequestStream(routing: CodexStateRouting): Transform;
11
+ /** The native app-server owns inference and state. This process only adapts
12
+ * requests over its supported stdio API, with no retry or conversation replay. */
13
+ export declare function runCodexStateBridge(executable: string, args: string[], routing: CodexStateRouting): Promise<number>;
14
+ export {};
@@ -0,0 +1,568 @@
1
+ // @bun
2
+ // src/codex-state-bridge.ts
3
+ import { spawn } from "child_process";
4
+ import { Transform } from "stream";
5
+ import { once } from "events";
6
+
7
+ // src/kilo-config.ts
8
+ import { parse, parseTree } from "jsonc-parser";
9
+ import { parseDocument } from "yaml";
10
+ import { z } from "zod";
11
+ var maxFileBytes = 1024 * 1024;
12
+ var maxTotalBytes = 8 * 1024 * 1024;
13
+
14
+ // src/domain.ts
15
+ import { z as z4 } from "zod";
16
+
17
+ // src/reasoning.ts
18
+ import { z as z2 } from "zod";
19
+ var reasoningEffortSchema = z2.enum(["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"]);
20
+
21
+ // src/model-policy-schema.ts
22
+ import { z as z3 } from "zod";
23
+ var policyModelIdSchema = z3.string().min(1).max(300).regex(/^[^\u0000-\u001f\u007f]+$/);
24
+ var modelPolicyRoleSchema = z3.enum(["subagent", "fast", "planning", "review", "summary", "compaction", "weak", "editor"]);
25
+ var boundedModelList = z3.array(policyModelIdSchema).max(500);
26
+ var aliasSchema = z3.string().regex(/^[A-Za-z0-9._/-]{1,120}$/).refine((v) => !["__proto__", "prototype", "constructor"].includes(v));
27
+ var boundedModelMap = z3.record(aliasSchema, policyModelIdSchema).superRefine((value, ctx) => {
28
+ if (Object.keys(value).length > 200)
29
+ ctx.addIssue({ code: "custom", message: "Model policy maps may contain at most 200 entries." });
30
+ });
31
+ var fallbacksSchema = z3.record(policyModelIdSchema, z3.array(policyModelIdSchema).max(20)).superRefine((value, ctx) => {
32
+ if (Object.keys(value).length > 200)
33
+ ctx.addIssue({ code: "custom", message: "Model policy fallback maps may contain at most 200 entries." });
34
+ });
35
+ var modelPolicySchema = z3.object({
36
+ version: z3.literal(1).default(1),
37
+ selection: z3.enum(["restricted", "catalog"]).optional(),
38
+ roles: z3.object({
39
+ subagent: policyModelIdSchema.optional(),
40
+ fast: policyModelIdSchema.optional(),
41
+ planning: policyModelIdSchema.optional(),
42
+ review: policyModelIdSchema.optional(),
43
+ summary: policyModelIdSchema.optional(),
44
+ compaction: policyModelIdSchema.optional(),
45
+ weak: policyModelIdSchema.optional(),
46
+ editor: policyModelIdSchema.optional()
47
+ }).strict().optional(),
48
+ allowedModels: boundedModelList.optional(),
49
+ aliases: boundedModelMap.optional(),
50
+ fallbacks: fallbacksSchema.optional()
51
+ }).strict();
52
+ var routingDecisionSchema = z3.enum(["allow", "alias", "reject", "fallback"]);
53
+ var routingEventRoleSchema = z3.enum(["main", ...modelPolicyRoleSchema.options]);
54
+ var routingEventSchema = z3.object({
55
+ at: z3.string().datetime({ offset: true }),
56
+ requestId: z3.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/),
57
+ requestedModel: policyModelIdSchema,
58
+ resolvedModel: policyModelIdSchema.optional(),
59
+ reportedModel: policyModelIdSchema.optional(),
60
+ reasoningEffort: reasoningEffortSchema.optional(),
61
+ decision: routingDecisionSchema,
62
+ role: routingEventRoleSchema.optional(),
63
+ reason: z3.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),
64
+ upstreamStatus: z3.number().int().min(100).max(599).optional()
65
+ }).strict();
66
+ var routingEventsSchema = z3.array(routingEventSchema).max(1000);
67
+ // src/domain.ts
68
+ var harnessSchema = z4.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "antigravity", "junie", "aider", "kilo"]);
69
+ var protocolSchema = z4.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
70
+ var idSchema = z4.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
71
+ var label = z4.string().min(1).max(200);
72
+ var envRef = z4.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/);
73
+ function endpoint(value) {
74
+ let url;
75
+ try {
76
+ url = new URL(value);
77
+ } catch {
78
+ throw new Fault(400, "invalid_url", "Use an absolute HTTPS URL (HTTP is allowed on loopback).");
79
+ }
80
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
81
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local) || url.username || url.password || url.search || url.hash)
82
+ throw new Fault(400, "invalid_url", "URL must use HTTPS, contain no credentials/query/fragment, or use HTTP on loopback.");
83
+ return url.href.replace(/\/+$/, "");
84
+ }
85
+ var urlSchema = z4.string().max(2000).superRefine((v, ctx) => {
86
+ try {
87
+ endpoint(v);
88
+ } catch {
89
+ ctx.addIssue({ code: "custom", message: "Invalid endpoint URL" });
90
+ }
91
+ }).transform(endpoint);
92
+ var credentialCheckPath = z4.string().min(1).max(200).regex(/^[a-zA-Z0-9_~!$&'()*+,;=:@%./-]+$/).refine((value) => !value.startsWith("/") && !value.split("/").some((part) => part === "." || part === ".."), "credentialCheck.path must be relative without dot segments");
93
+ var credentialCheckSchema = z4.object({ method: z4.enum(["GET", "HEAD"]).default("GET"), path: credentialCheckPath }).strict();
94
+ var expiresOnSchema = z4.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine((value) => {
95
+ const day = new Date(`${value}T00:00:00.000Z`);
96
+ return Number.isFinite(day.getTime()) && day.toISOString().slice(0, 10) === value;
97
+ }, "Use a real calendar date in YYYY-MM-DD format.");
98
+ var modelSchema = z4.object({
99
+ id: z4.string().min(1).max(300).refine((value) => value === value.trim() && !/[\x00-\x1f\x7f-\x9f]/.test(value), "Use a nonblank model ID without surrounding whitespace or control characters."),
100
+ name: label,
101
+ description: z4.string().max(8000).optional(),
102
+ available: z4.boolean().optional(),
103
+ expiresOn: expiresOnSchema.optional(),
104
+ contextWindow: z4.number().int().positive().optional(),
105
+ maxOutputTokens: z4.number().int().positive().optional(),
106
+ inputModalities: z4.array(z4.string().max(50)).max(20).optional(),
107
+ outputModalities: z4.array(z4.string().max(50)).max(20).optional(),
108
+ supportedParameters: z4.array(z4.string().max(100)).max(100).optional(),
109
+ reasoningEfforts: z4.array(reasoningEffortSchema).max(8).optional(),
110
+ supportedGenerationMethods: z4.array(z4.string().min(1).max(100)).max(100).optional()
111
+ }).strict();
112
+ var providerInputSchema = z4.object({
113
+ id: idSchema,
114
+ name: label,
115
+ baseUrl: urlSchema,
116
+ protocol: protocolSchema,
117
+ credentialEnv: envRef.optional(),
118
+ authStyle: z4.enum(["bearer", "x-api-key", "api-key"]).default("bearer"),
119
+ credentialCheck: credentialCheckSchema.optional(),
120
+ catalogBaseUrl: urlSchema.optional(),
121
+ catalogFormat: z4.enum(["openai", "ollama", "mistral", "together", "fireworks", "dashscope", "gemini", "none"]).optional(),
122
+ catalogAuthStyle: z4.enum(["bearer", "x-api-key", "api-key", "none"]).optional(),
123
+ catalogCredentialEnv: envRef.optional(),
124
+ catalogAccountId: z4.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/).optional(),
125
+ modelsPath: z4.string().regex(/^[a-zA-Z0-9_/-]+$/).max(200).default("models"),
126
+ manualModels: z4.array(modelSchema).max(1e4).default([]),
127
+ additionalModels: z4.array(modelSchema).max(1e4).optional()
128
+ }).strict().refine((p) => !p.modelsPath.split("/").includes("..") && !p.modelsPath.startsWith("/"), "modelsPath must be relative");
129
+ var providerPresetSchema = z4.object({
130
+ id: idSchema,
131
+ name: label,
132
+ credentialEnv: envRef.optional(),
133
+ credentialAliases: z4.array(z4.string().regex(/^[A-Z][A-Z0-9_]+$/)),
134
+ protocols: z4.array(z4.object({
135
+ protocol: protocolSchema,
136
+ baseUrl: urlSchema.optional(),
137
+ authStyle: z4.enum(["bearer", "x-api-key", "api-key"]),
138
+ credentialCheck: credentialCheckSchema.optional(),
139
+ catalogBaseUrl: urlSchema.optional(),
140
+ catalogFormat: z4.enum(["openai", "ollama", "mistral", "together", "fireworks", "dashscope", "gemini", "none"]),
141
+ catalogAuthStyle: z4.enum(["bearer", "x-api-key", "api-key", "none"]).optional(),
142
+ modelsPath: z4.string(),
143
+ notes: z4.array(z4.string())
144
+ }).strict()).min(1),
145
+ sources: z4.array(z4.string().url()),
146
+ verification: z4.literal("documented")
147
+ }).strict();
148
+ var profileInputSchema = z4.object({
149
+ id: idSchema,
150
+ name: label,
151
+ providerId: idSchema,
152
+ harness: harnessSchema,
153
+ model: z4.string().min(1).max(300),
154
+ modelPolicy: modelPolicySchema.optional()
155
+ }).strict();
156
+ var runInputSchema = z4.object({
157
+ modelPolicyVersion: z4.literal(1),
158
+ profileId: idSchema,
159
+ harness: harnessSchema,
160
+ model: z4.string().min(1).max(300),
161
+ modelPolicy: modelPolicySchema.optional(),
162
+ planToken: z4.string().regex(/^[a-f0-9]{64}$/)
163
+ }).strict();
164
+ var runUpdateSchema = z4.object({
165
+ status: z4.enum(["exited", "failed", "interrupted"]),
166
+ exitCode: z4.number().int().min(0).max(255),
167
+ routingEvents: routingEventsSchema.optional(),
168
+ routingEventsDropped: z4.number().int().min(0).max(1e6).optional()
169
+ }).strict();
170
+ var catalogSchema = z4.object({ models: z4.array(modelSchema).max(1e4), refreshedAt: z4.string().datetime(), source: z4.enum(["remote", "manual"]) }).strict();
171
+
172
+ class Fault extends Error {
173
+ status;
174
+ code;
175
+ constructor(status, code, message) {
176
+ super(message);
177
+ this.status = status;
178
+ this.code = code;
179
+ }
180
+ }
181
+
182
+ // src/aider-args.ts
183
+ var reserved = `model weak-model editor-model openai-api-key anthropic-api-key openai-api-base openai-api-type openai-api-version openai-api-deployment-id openai-organization-id set-env api-key model-settings-file model-metadata-file alias config env-file load input-history-file chat-history-file llm-history-file encoding gui browser opus sonnet haiku 4 4o mini 4-turbo 35turbo 35-turbo 3 deepseek o1-mini o1-preview`.split(" ");
184
+ var required = `list-models models reasoning-effort thinking-tokens timeout edit-format chat-mode editor-edit-format max-chat-history-tokens cache-keepalive-pings map-tokens map-refresh map-multiplier-no-files user-input-color tool-output-color tool-error-color tool-warning-color assistant-output-color completion-menu-color completion-menu-bg-color completion-menu-current-color completion-menu-current-bg-color code-theme aiderignore commit-prompt lint-cmd test-cmd analytics-log analytics-posthog-host analytics-posthog-project-api-key message message-file apply voice-format voice-language voice-input-device file read chat-language commit-language line-endings notifications-command editor shell-completions`.split(" ");
185
+ var toggles = `verify-ssl auto-accept-architect show-model-warnings check-model-accepts-settings cache-prompts restore-chat-history pretty stream git gitignore add-gitignore-files auto-commits dirty-commits attribute-author attribute-committer attribute-commit-message-author attribute-commit-message-committer attribute-co-authored-by git-commit-verify dry-run watch-files auto-lint auto-test analytics check-update show-release-notes gui browser copy-paste suggest-shell-commands fancy-input multiline notifications detect-urls`.split(" ");
186
+ var booleans = [...`help architect dark-mode light-mode show-diffs subtree-only commit skip-sanity-check-repo lint test analytics-disable just-check-update install-main-branch upgrade version apply-clipboard-edits exit show-repo-map show-prompts disable-playwright vim yes-always verbose`.split(" "), ...toggles, ...toggles.map((k) => `no-${k}`)];
187
+ var all = [...reserved, ...required, ...booleans];
188
+
189
+ // src/harness-arguments.ts
190
+ var providerKeys = new Set(["model", "model_provider", "provider", "model_providers", "model_catalog_json", "review_model", "agents", "memories"]);
191
+ function codexConfigPath(key) {
192
+ if (key.length > 4096 || /[\r\n\0]/.test(key))
193
+ throw new Error("Invalid Codex configuration key.");
194
+ let value = Bun.TOML.parse(`${key} = 0`);
195
+ const path = [];
196
+ while (value !== 0) {
197
+ if (value === null || typeof value !== "object" || Array.isArray(value))
198
+ throw new Error("Invalid Codex configuration key.");
199
+ const entries = Object.entries(value);
200
+ if (entries.length !== 1)
201
+ throw new Error("Ambiguous Codex configuration key.");
202
+ path.push(entries[0][0]);
203
+ value = entries[0][1];
204
+ }
205
+ if (!path.length)
206
+ throw new Error("Invalid Codex configuration key.");
207
+ return path;
208
+ }
209
+
210
+ // src/codex-model-policy.ts
211
+ var codexRoutingKeys = new Set(["model", "model_provider", "provider", "model_providers", "model_catalog_json", "base_url", "wire_api", "env_key", "env_http_headers", "http_headers", "auth_command", "include"]);
212
+ var codexTransportKeys = new Set(["mcp_servers", "mcp_server", "transport", "transports", "plugins"]);
213
+
214
+ // src/codex-state-bridge.ts
215
+ var MAX_FRAME = 8 * 1024 * 1024;
216
+ var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
217
+ var decoder = new TextDecoder("utf-8", { fatal: true });
218
+ var credentialKeys = new Set(["env_key", "env_http_headers", "http_headers", "auth_command"]);
219
+ var routingAliases = new Set(["modelProvider", "modelProviders", "modelCatalogJson", "reviewModel", "modelId", "providerId", "providers", "baseUrl", "baseURL", "wireApi", "wireAPI", "requires_openai_auth", "requiresOpenaiAuth", "requiresOpenAIAuth"]);
220
+ var credentialAliases = new Set(["envKey", "envHttpHeaders", "httpHeaders", "httpHeader", "header", "headers", "authCommand", "auth", "authorization", "Authorization", "api_key", "apiKey", "api-key", "x-api-key"]);
221
+ var stateOwnedKeys = new Set(["review_model", "sqlite_home", "config_file", "extract_model", "consolidation_model", "sqliteHome", "configFile", "extractModel", "consolidationModel"]);
222
+ var agentOwnedKeys = new Set(["default_subagent_model", "default_subagent_reasoning_effort", "default_subagent_reasoning_summary", "defaultSubagentModel", "defaultSubagentReasoningEffort", "defaultSubagentReasoningSummary"]);
223
+ var prototypeKeys = new Set(["__proto__", "prototype", "constructor"]);
224
+ var forbiddenKeys = new Set([...codexTransportKeys, ...credentialKeys, ...credentialAliases, "plugin", "mcpServer", "mcpServers", "profile", "profiles", "include", ...prototypeKeys]);
225
+ var ownedKeys = new Set([...codexRoutingKeys, ...routingAliases, ...stateOwnedKeys, ...agentOwnedKeys]);
226
+ var unsafeKeys = new Set([...forbiddenKeys, ...ownedKeys]);
227
+ var managedParamKeys = new Set(["config", "model", "modelProvider", "modelProviders", "allowProviderModelFallback"]);
228
+ var unsafeParamKeys = new Set([...forbiddenKeys, ...ownedKeys, ...managedParamKeys, "provider", "plugins"]);
229
+ function configKeySegments(key) {
230
+ const parts = codexConfigPath(key).flatMap((part) => part.split(".")).filter(Boolean);
231
+ if (!parts.length)
232
+ throw new Error("codex_state_config_key");
233
+ return parts;
234
+ }
235
+ function securityKeySegments(key) {
236
+ try {
237
+ return configKeySegments(key);
238
+ } catch {
239
+ return key.match(/[A-Za-z_][A-Za-z0-9_]*/g) ?? [];
240
+ }
241
+ }
242
+ function safePath(value) {
243
+ if (typeof value !== "string" || !value.startsWith("/") || /[\r\n\0]/.test(value))
244
+ return false;
245
+ const parts = value.split("/").slice(1);
246
+ return parts.length > 0 && parts.every((part) => part !== "" && part !== "." && part !== "..");
247
+ }
248
+ function merge(base, overlay) {
249
+ const result = { ...base };
250
+ for (const [key, value] of Object.entries(overlay))
251
+ result[key] = object(value) && object(result[key]) ? merge(result[key], value) : value;
252
+ return result;
253
+ }
254
+ function sanitizeOwnedTree(value, additionalOwned, path) {
255
+ if (Array.isArray(value))
256
+ return value.map((item, index) => sanitizeOwnedTree(item, additionalOwned, `${path}[${index}]`));
257
+ if (!object(value))
258
+ return value;
259
+ const result = {};
260
+ for (const [key, item] of Object.entries(value)) {
261
+ const segments = securityKeySegments(key);
262
+ if (segments.some((part) => forbiddenKeys.has(part)))
263
+ throw new Error(`codex_state_unsafe_config:${path}.${key}`);
264
+ if (segments.some((part) => ownedKeys.has(part) || additionalOwned.has(part)))
265
+ continue;
266
+ result[key] = sanitizeOwnedTree(item, additionalOwned, `${path}.${key}`);
267
+ }
268
+ return result;
269
+ }
270
+ function safeAgents(value) {
271
+ if (!object(value))
272
+ throw new Error("codex_state_agents");
273
+ const result = {};
274
+ for (const [name, item] of Object.entries(value)) {
275
+ if (prototypeKeys.has(name))
276
+ throw new Error(`codex_state_unsafe_config:agents.${name}`);
277
+ if (agentOwnedKeys.has(name))
278
+ continue;
279
+ if (object(item)) {
280
+ result[name] = sanitizeOwnedTree(item, new Set, `agents.${name}`);
281
+ continue;
282
+ }
283
+ if (securityKeySegments(name).some((part) => unsafeKeys.has(part)))
284
+ throw new Error(`codex_state_unsafe_config:agents.${name}`);
285
+ result[name] = item;
286
+ }
287
+ return result;
288
+ }
289
+ function safeMemories(value) {
290
+ if (!object(value))
291
+ throw new Error("codex_state_memories");
292
+ return sanitizeOwnedTree(value, new Set, "memories");
293
+ }
294
+ function validateRouting(routing) {
295
+ if (typeof routing.model !== "string" || !routing.model || routing.model.length > 4096 || /[\r\n\0]/.test(routing.model))
296
+ throw new Error("codex_state_routing");
297
+ const allowed = new Set(["model_provider", "model_providers", "model_catalog_json", "review_model", "agents", "memories", "sqlite_home"]);
298
+ if (Object.keys(routing.config).some((key) => !allowed.has(key)) || routing.config.model_provider !== "switcher")
299
+ throw new Error("codex_state_routing");
300
+ const providers = routing.config.model_providers;
301
+ if (!object(providers) || Object.keys(providers).length !== 1 || !object(providers.switcher))
302
+ throw new Error("codex_state_routing");
303
+ const provider = providers.switcher, providerKeys2 = new Set(["name", "base_url", "wire_api", "requires_openai_auth", "env_key", "env_http_headers"]);
304
+ if (Object.keys(provider).some((key) => !providerKeys2.has(key)) || provider.name !== "Switcher" || provider.wire_api !== "responses" || provider.requires_openai_auth !== false)
305
+ throw new Error("codex_state_routing");
306
+ const url = new URL(String(provider.base_url));
307
+ if (url.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname) || !url.port || url.pathname !== "/v1" || url.username || url.password || url.search || url.hash)
308
+ throw new Error("codex_state_routing");
309
+ if (provider.env_key !== undefined && provider.env_key !== "SWITCHER_HARNESS_API_KEY")
310
+ throw new Error("codex_state_routing");
311
+ if (provider.env_http_headers !== undefined) {
312
+ if (!object(provider.env_http_headers) || Object.keys(provider.env_http_headers).length !== 1 || Object.keys(provider.env_http_headers).some((key) => !["x-api-key", "api-key"].includes(key)) || Object.values(provider.env_http_headers).some((value) => value !== "SWITCHER_HARNESS_API_KEY"))
313
+ throw new Error("codex_state_routing");
314
+ }
315
+ if (provider.env_key === undefined === (provider.env_http_headers === undefined))
316
+ throw new Error("codex_state_routing");
317
+ for (const key of ["model_catalog_json", "sqlite_home"])
318
+ if (!safePath(routing.config[key]))
319
+ throw new Error("codex_state_routing");
320
+ if (routing.config.review_model !== undefined && (typeof routing.config.review_model !== "string" || /[\r\n\0]/.test(routing.config.review_model)))
321
+ throw new Error("codex_state_routing");
322
+ if (routing.config.agents !== undefined) {
323
+ const agents = routing.config.agents;
324
+ if (!object(agents))
325
+ throw new Error("codex_state_routing");
326
+ for (const [name, item] of Object.entries(agents)) {
327
+ if (prototypeKeys.has(name))
328
+ throw new Error("codex_state_routing");
329
+ if (name === "default_subagent_model") {
330
+ if (typeof item !== "string" || /[\r\n\0]/.test(item))
331
+ throw new Error("codex_state_routing");
332
+ continue;
333
+ }
334
+ if (!object(item)) {
335
+ assertSafeRetained({ [name]: item }, "routing.agents");
336
+ continue;
337
+ }
338
+ const copy = structuredClone(item);
339
+ if (copy.config_file !== undefined) {
340
+ if (!safePath(copy.config_file))
341
+ throw new Error("codex_state_routing");
342
+ delete copy.config_file;
343
+ }
344
+ assertSafeRetained(copy, `routing.agents.${name}`);
345
+ }
346
+ }
347
+ if (routing.config.memories !== undefined) {
348
+ if (!object(routing.config.memories))
349
+ throw new Error("codex_state_routing");
350
+ const memories = structuredClone(routing.config.memories);
351
+ for (const key of ["extract_model", "consolidation_model"]) {
352
+ if (memories[key] !== undefined && (typeof memories[key] !== "string" || /[\r\n\0]/.test(memories[key])))
353
+ throw new Error("codex_state_routing");
354
+ delete memories[key];
355
+ }
356
+ assertSafeRetained(memories, "routing.memories");
357
+ }
358
+ }
359
+ function assertSafeRetained(value, path = "config") {
360
+ if (Array.isArray(value)) {
361
+ value.forEach((item, index) => assertSafeRetained(item, `${path}[${index}]`));
362
+ return;
363
+ }
364
+ if (!object(value))
365
+ return;
366
+ for (const [key, item] of Object.entries(value)) {
367
+ if (securityKeySegments(key).some((part) => unsafeKeys.has(part)))
368
+ throw new Error(`codex_state_unsafe_config:${path}.${key}`);
369
+ assertSafeRetained(item, `${path}.${key}`);
370
+ }
371
+ }
372
+ function safeManagedParams(params) {
373
+ const safe = {};
374
+ for (const [key, value] of Object.entries(params)) {
375
+ if (managedParamKeys.has(key))
376
+ continue;
377
+ if (securityKeySegments(key).some((part) => unsafeParamKeys.has(part)))
378
+ throw new Error("codex_state_param_override");
379
+ safe[key] = value;
380
+ }
381
+ return safe;
382
+ }
383
+ function rewriteCodexStateRequest(line, routing) {
384
+ validateRouting(routing);
385
+ if (line.length > MAX_FRAME)
386
+ throw new Error("codex_state_frame_limit");
387
+ const request = JSON.parse(decoder.decode(line));
388
+ if (!object(request))
389
+ throw new Error("codex_state_protocol");
390
+ const managed = ["thread/list", "thread/start", "thread/resume", "thread/fork"].includes(String(request.method));
391
+ if (managed && !Object.hasOwn(request, "id"))
392
+ throw new Error("codex_state_protocol");
393
+ if (!managed)
394
+ return line;
395
+ if (request.params != null && !object(request.params))
396
+ throw new Error("codex_state_protocol");
397
+ const params = request.params ?? {}, safeParams = safeManagedParams(params);
398
+ if (request.method === "thread/list") {
399
+ request.params = { ...safeParams, modelProviders: [], useStateDbOnly: false };
400
+ } else {
401
+ if (params.config != null && !object(params.config))
402
+ throw new Error("codex_state_protocol");
403
+ const retained = {};
404
+ for (const [key, value] of Object.entries(params.config ?? {})) {
405
+ const path = configKeySegments(key), root = path[0];
406
+ if (path.some((item) => forbiddenKeys.has(item)))
407
+ throw new Error("codex_state_transport_override");
408
+ if (path.some((item) => ownedKeys.has(item)))
409
+ continue;
410
+ if ((root === "agents" || root === "memories") && path.length > 1)
411
+ throw new Error("codex_state_config_ambiguous");
412
+ if (root === "agents") {
413
+ if (Object.hasOwn(retained, root))
414
+ throw new Error("codex_state_config_ambiguous");
415
+ retained[root] = safeAgents(value);
416
+ } else if (root === "memories") {
417
+ if (Object.hasOwn(retained, root))
418
+ throw new Error("codex_state_config_ambiguous");
419
+ retained[root] = safeMemories(value);
420
+ } else {
421
+ assertSafeRetained({ [key]: value });
422
+ retained[key] = value;
423
+ }
424
+ }
425
+ request.params = {
426
+ ...safeParams,
427
+ modelProvider: "switcher",
428
+ model: routing.model,
429
+ ...request.method === "thread/start" ? { allowProviderModelFallback: false } : {},
430
+ config: merge(retained, routing.config)
431
+ };
432
+ }
433
+ return Buffer.from(JSON.stringify(request));
434
+ }
435
+ function codexStateRequestStream(routing) {
436
+ let pending = Buffer.alloc(0);
437
+ return new Transform({
438
+ transform(chunk, _encoding, callback) {
439
+ try {
440
+ const joined = pending.length ? Buffer.concat([pending, chunk]) : chunk;
441
+ let start = 0, end;
442
+ while ((end = joined.indexOf(10, start)) >= 0) {
443
+ const line = joined.subarray(start, end);
444
+ if (line.length)
445
+ this.push(Buffer.concat([rewriteCodexStateRequest(line, routing), Buffer.from(`
446
+ `)]));
447
+ start = end + 1;
448
+ }
449
+ pending = Buffer.from(joined.subarray(start));
450
+ if (pending.length > MAX_FRAME)
451
+ throw new Error("codex_state_frame_limit");
452
+ callback();
453
+ } catch {
454
+ callback(new Error("codex_state_protocol"));
455
+ }
456
+ },
457
+ flush(callback) {
458
+ callback(pending.length ? new Error("codex_state_truncated_frame") : undefined);
459
+ }
460
+ });
461
+ }
462
+ async function runCodexStateBridge(executable, args, routing) {
463
+ const grouped = process.platform !== "win32";
464
+ const child = spawn(executable, args, { stdio: ["pipe", "pipe", "inherit"], detached: grouped });
465
+ const requests = codexStateRequestStream(routing);
466
+ let stopping = false, failed = false, timer;
467
+ const signal = (value) => {
468
+ try {
469
+ if (grouped && child.pid)
470
+ process.kill(-child.pid, value);
471
+ else
472
+ child.kill(value);
473
+ } catch (error) {
474
+ if (error.code !== "ESRCH")
475
+ failed = true;
476
+ }
477
+ };
478
+ const groupExists = () => {
479
+ if (!grouped || !child.pid)
480
+ return false;
481
+ try {
482
+ process.kill(-child.pid, 0);
483
+ return true;
484
+ } catch {
485
+ return false;
486
+ }
487
+ };
488
+ const reapGroup = async () => {
489
+ if (!groupExists())
490
+ return;
491
+ signal("SIGTERM");
492
+ const deadline = Date.now() + 1000;
493
+ while (groupExists() && Date.now() < deadline)
494
+ await new Promise((resolve) => setTimeout(resolve, 25));
495
+ if (groupExists()) {
496
+ signal("SIGKILL");
497
+ const killed = Date.now() + 1000;
498
+ while (groupExists() && Date.now() < killed)
499
+ await new Promise((resolve) => setTimeout(resolve, 25));
500
+ }
501
+ if (groupExists())
502
+ failed = true;
503
+ };
504
+ const stop = () => {
505
+ if (stopping)
506
+ return;
507
+ stopping = true;
508
+ child.stdin.destroy();
509
+ signal("SIGTERM");
510
+ timer = setTimeout(() => signal("SIGKILL"), 5000);
511
+ timer.unref();
512
+ };
513
+ const fail = () => {
514
+ failed = true;
515
+ stop();
516
+ };
517
+ child.on("error", fail);
518
+ child.stdin.on("error", fail);
519
+ requests.on("error", fail);
520
+ process.stdout.on("error", fail);
521
+ process.on("SIGINT", stop);
522
+ process.on("SIGTERM", stop);
523
+ process.on("SIGHUP", stop);
524
+ const endInput = () => {
525
+ timer ??= setTimeout(stop, 5000);
526
+ timer.unref();
527
+ };
528
+ process.stdin.once("end", endInput);
529
+ process.stdin.pipe(requests).pipe(child.stdin);
530
+ child.stdout.pipe(process.stdout, { end: false });
531
+ let code;
532
+ try {
533
+ [code] = await once(child, "exit");
534
+ } catch {
535
+ failed = true;
536
+ } finally {
537
+ await reapGroup();
538
+ if (timer)
539
+ clearTimeout(timer);
540
+ process.stdin.unpipe(requests);
541
+ requests.destroy();
542
+ child.stdout.unpipe(process.stdout);
543
+ process.stdin.pause();
544
+ process.stdin.off("end", endInput);
545
+ process.stdout.off("error", fail);
546
+ process.off("SIGINT", stop);
547
+ process.off("SIGTERM", stop);
548
+ process.off("SIGHUP", stop);
549
+ }
550
+ return failed ? 1 : typeof code === "number" ? code : 1;
551
+ }
552
+ if (import.meta.main) {
553
+ try {
554
+ const [executable, model, config, ...args] = process.argv.slice(2);
555
+ const parsed = JSON.parse(config);
556
+ if (!executable?.startsWith("/") || !model || !object(parsed) || args[0] !== "app-server")
557
+ throw new Error;
558
+ process.exitCode = await runCodexStateBridge(executable, args, { model, config: parsed });
559
+ } catch {
560
+ console.error("Switcher native session bridge failed.");
561
+ process.exitCode = 1;
562
+ }
563
+ }
564
+ export {
565
+ runCodexStateBridge,
566
+ rewriteCodexStateRequest,
567
+ codexStateRequestStream
568
+ };