@shuind/dsh-codex-harness 0.3.1 → 0.3.3

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 (86) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +21 -43
  3. package/docs/preset-library.md +2 -2
  4. package/docs/tool-policy.md +1 -1
  5. package/lib/client.js +1738 -327
  6. package/lib/compact-command.js +7 -1
  7. package/lib/compaction.js +7 -1
  8. package/lib/hybrid-executor.js +23 -12
  9. package/lib/index.js +1266 -36
  10. package/lib/preferences.js +21 -2
  11. package/lib/tool-policy.js +11 -2
  12. package/lib/typert.js +42 -1
  13. package/lib/types/client/desktop.d.ts +20 -42
  14. package/lib/types/client/desktop.js +191 -126
  15. package/lib/types/client/index.d.ts +104 -28
  16. package/lib/types/client/index.js +97 -15
  17. package/lib/types/client/policy-drafts.d.ts +18 -0
  18. package/lib/types/client/policy-drafts.js +27 -0
  19. package/lib/types/client/policy-locale.d.ts +80 -20
  20. package/lib/types/client/policy-locale.js +197 -80
  21. package/lib/types/client/preset-manager.d.ts +25 -2
  22. package/lib/types/client/preset-manager.js +89 -5
  23. package/lib/types/client/preset-requests.d.ts +44 -1
  24. package/lib/types/client/preset-requests.js +150 -0
  25. package/lib/types/client/tool-policy.d.ts +7 -2
  26. package/lib/types/client/tool-policy.js +48 -6
  27. package/lib/types/contracts/preset-editor-schema.d.ts +35 -0
  28. package/lib/types/contracts/preset-editor-schema.js +39 -0
  29. package/lib/types/contracts/settings.d.ts +12 -0
  30. package/lib/types/contracts/settings.js +10 -1
  31. package/lib/types/contracts/ui-contracts.d.ts +52 -0
  32. package/lib/types/contracts/ui-contracts.js +58 -0
  33. package/lib/types/contracts/update.d.ts +73 -0
  34. package/lib/types/contracts/update.js +291 -0
  35. package/lib/types/entries/index.js +20 -2
  36. package/lib/types/entries/preferences.d.ts +2 -0
  37. package/lib/types/entries/preferences.js +9 -0
  38. package/lib/types/hybrid/hybrid-sdk.d.ts +1 -1
  39. package/lib/types/hybrid/hybrid-sdk.js +27 -13
  40. package/lib/types/presets/preset-editor.d.ts +13 -1
  41. package/lib/types/presets/preset-editor.js +24 -1
  42. package/lib/types/presets/pro-mode-store.d.ts +13 -0
  43. package/lib/types/presets/pro-mode-store.js +69 -0
  44. package/lib/types/responses/background-sse-codec.d.ts +23 -0
  45. package/lib/types/responses/background-sse-codec.js +230 -0
  46. package/lib/types/responses/background-stream.d.ts +28 -0
  47. package/lib/types/responses/background-stream.js +351 -0
  48. package/lib/types/responses/compact-checkpoint.js +3 -10
  49. package/lib/types/responses/fetch-transport.js +24 -9
  50. package/lib/types/responses/remote-compact.js +39 -11
  51. package/lib/types/responses/wire-rewrite.d.ts +4 -0
  52. package/lib/types/responses/wire-rewrite.js +30 -4
  53. package/lib/types/tools/codex-subagent.d.ts +14 -0
  54. package/lib/types/tools/codex-subagent.js +269 -0
  55. package/lib/types/update/checker.d.ts +14 -0
  56. package/lib/types/update/checker.js +166 -0
  57. package/locale/en.json +1 -1
  58. package/locale/hybrid-executor/en.json +1 -1
  59. package/locale/hybrid-executor/zh.json +1 -1
  60. package/locale/zh.json +1 -1
  61. package/package.json +6 -2
  62. package/src/client/desktop.tsx +370 -153
  63. package/src/client/index.tsx +122 -22
  64. package/src/client/policy-drafts.ts +45 -0
  65. package/src/client/policy-locale.ts +197 -80
  66. package/src/client/preset-manager.tsx +125 -4
  67. package/src/client/preset-requests.ts +185 -1
  68. package/src/client/tool-policy.tsx +63 -9
  69. package/src/contracts/preset-editor-schema.ts +44 -0
  70. package/src/contracts/settings.ts +20 -1
  71. package/src/contracts/ui-contracts.ts +91 -0
  72. package/src/contracts/update.ts +307 -0
  73. package/src/entries/index.ts +25 -2
  74. package/src/entries/preferences.ts +9 -0
  75. package/src/hybrid/hybrid-sdk.ts +28 -12
  76. package/src/presets/preset-editor.ts +31 -3
  77. package/src/presets/pro-mode-store.ts +80 -0
  78. package/src/responses/background-sse-codec.ts +237 -0
  79. package/src/responses/background-stream.ts +371 -0
  80. package/src/responses/compact-checkpoint.ts +2 -8
  81. package/src/responses/fetch-transport.ts +28 -9
  82. package/src/responses/remote-compact.ts +41 -11
  83. package/src/responses/wire-rewrite.ts +34 -3
  84. package/src/tools/codex-subagent.ts +290 -0
  85. package/src/update/checker.ts +193 -0
  86. package/tsdown.config.ts +4 -0
package/lib/index.js CHANGED
@@ -6,15 +6,16 @@ import { createScope, scopeChainOf, scopeOf } from "@deepseek-ai/dsh-scope";
6
6
  import { PERSONA_PREFIX_SECTION, PERSONA_SUFFIX_SECTION } from "@deepseek-ai/dsh-system-prompt";
7
7
  import { YAMLMap, isMap, isScalar, isSeq, parseDocument } from "yaml";
8
8
  import { defineTool } from "@deepseek-ai/dsh-tools";
9
+ import { HarnessError, ReasoningEffortId, offloadedImageText, resolveImageAttachmentAccess } from "@deepseek-ai/dsh-llm";
10
+ import { mkdir, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
11
+ import { dirname, isAbsolute, join, resolve } from "node:path";
12
+ import { fileURLToPath } from "node:url";
9
13
  import { ManualCompactionError, isCompactCheckpointSource, toolPairingBalancedBefore } from "@deepseek-ai/dsh-compaction";
10
14
  import { AsyncLocalStorage } from "node:async_hooks";
11
15
  import { zstdCompressSync, zstdDecompressSync } from "node:zlib";
12
- import { mkdir, readdir, rename, unlink, writeFile } from "node:fs/promises";
13
16
  import { homedir } from "node:os";
14
- import { isAbsolute, join, resolve } from "node:path";
15
17
  import { credentialRef } from "@deepseek-ai/dsh-credentials";
16
18
  import { ESCALATION_TARGETS, approveEscalation, escalationHintMarker, sandboxDenialMarker, sandboxPermissionsDescription, validateEscalationArgs } from "@deepseek-ai/dsh-sandbox";
17
- import { HarnessError } from "@deepseek-ai/dsh-llm";
18
19
  import { FsError } from "@deepseek-ai/dsh-fs";
19
20
  import BasicCompactionEngine from "@deepseek-ai/dsh-compaction-basic";
20
21
  //#region lib/types/contracts/prompt.js
@@ -85,6 +86,49 @@ function resolveCodexSystemPrompt(systemPrompt) {
85
86
  const CODEX_CONTEXT_MAX = 1e6;
86
87
  const OPENAI_CODEX_PROVIDER = "openai-codex";
87
88
  const OPENAI_CODEX_SETTINGS_NAMESPACE = "llm-openai-codex";
89
+ const CODEX_SUBAGENT_TOOL_NAME = "codex_subagent";
90
+ const CODEX_SUBAGENT_DEFAULT_PRESET = "codex-hybrid";
91
+ const API_PRO_MODE_MODEL = /^gpt-(?:5\.6|[6-9]|\d{2,})(?:[._-]|$)/i;
92
+ const LEGACY_PRO_MODEL_SLUG = /(?:^|[-_.])pro(?:$|[-_.])/i;
93
+ /**
94
+ * Models on the OpenAI Responses API that accept `reasoning.mode = "pro"`.
95
+ * Excludes standalone legacy `*-pro` slugs (e.g. `gpt-5.4-pro`, `gpt-5.5-pro`).
96
+ */
97
+ function supportsApiProMode(model) {
98
+ if (typeof model !== "string") return false;
99
+ const trimmed = model.trim();
100
+ if (trimmed.length === 0) return false;
101
+ const base = trimmed.includes("/") ? trimmed.slice(trimmed.lastIndexOf("/") + 1) : trimmed;
102
+ return API_PRO_MODE_MODEL.test(base) && !LEGACY_PRO_MODEL_SLUG.test(base);
103
+ }
104
+ /** True only when `url` is an HTTPS official OpenAI API endpoint (`api.openai.com`). */
105
+ function isOfficialOpenAiBaseUrl(url) {
106
+ if (typeof url !== "string") return false;
107
+ const trimmed = url.trim();
108
+ if (trimmed.length === 0) return false;
109
+ try {
110
+ const parsed = new URL(trimmed);
111
+ return parsed.protocol === "https:" && parsed.hostname.toLowerCase() === "api.openai.com";
112
+ } catch {
113
+ return false;
114
+ }
115
+ }
116
+ /**
117
+ * True only when `(provider, model)` routes to the official OpenAI Responses API
118
+ * (`https://api.openai.com`) on a Pro-capable GPT-5.6 / 6+ model.
119
+ */
120
+ function isOfficialOpenAiApiRoute(provider, model, providers) {
121
+ if (typeof provider !== "string" || provider.length === 0 || provider === "openai-codex") return false;
122
+ if (!supportsApiProMode(model)) return false;
123
+ const profile = providers?.[provider];
124
+ const override = model !== void 0 ? profile?.modelOverrides?.[model] : void 0;
125
+ const modelEntry = model !== void 0 && Array.isArray(profile?.models) ? profile.models.find((item) => item?.id === model) : void 0;
126
+ const effectiveApi = override?.api ?? modelEntry?.api ?? profile?.api;
127
+ if (effectiveApi !== void 0 && effectiveApi !== "openai-responses") return false;
128
+ const effectiveBaseUrl = override?.baseURL ?? override?.baseUrl ?? modelEntry?.baseURL ?? modelEntry?.baseUrl ?? profile?.baseURL ?? profile?.baseUrl;
129
+ if (typeof effectiveBaseUrl === "string" && effectiveBaseUrl.trim().length > 0) return isOfficialOpenAiBaseUrl(effectiveBaseUrl);
130
+ return provider === "openai";
131
+ }
88
132
  const OPENAI_CODEX_MODEL_LIMITS = {
89
133
  "gpt-6.1-sol": {
90
134
  defaultTokens: 5e5,
@@ -140,6 +184,7 @@ const CODEX_SETTINGS_NAMESPACE = "codex";
140
184
  const CODEX_SETTINGS_ENTRY = {
141
185
  fast: false,
142
186
  fastModeControlEnabled: true,
187
+ proModeControlEnabled: true,
143
188
  contextWindowControlEnabled: true,
144
189
  persona: DEFAULT_CODEX_PERSONA,
145
190
  harnessSourcePrompt: DEFAULT_DSH_CORE_SOURCE_PROMPT,
@@ -151,11 +196,14 @@ const CODEX_SETTINGS_ENTRY = {
151
196
  planToolEnabled: true,
152
197
  hostedWebSearchEnabled: true,
153
198
  remoteCompactionEnabled: true,
154
- activityIndicatorEnabled: true
199
+ activityIndicatorEnabled: true,
200
+ codexSubagentEnabled: false,
201
+ codexSubagentPreset: CODEX_SUBAGENT_DEFAULT_PRESET
155
202
  };
156
203
  const CODEX_SETTINGS_SCHEMA = z.object({
157
204
  fast: z.boolean().default(false),
158
205
  fastModeControlEnabled: z.boolean().default(true),
206
+ proModeControlEnabled: z.boolean().default(true),
159
207
  contextWindowControlEnabled: z.boolean().default(true),
160
208
  contextWindow: z.number().step(1).min(1).max(CODEX_CONTEXT_MAX).hidden(),
161
209
  persona: z.string().default(DEFAULT_CODEX_PERSONA),
@@ -168,7 +216,11 @@ const CODEX_SETTINGS_SCHEMA = z.object({
168
216
  planToolEnabled: z.boolean().default(true).hidden(),
169
217
  hostedWebSearchEnabled: z.boolean().default(true),
170
218
  remoteCompactionEnabled: z.boolean().default(true),
171
- activityIndicatorEnabled: z.boolean().default(true)
219
+ activityIndicatorEnabled: z.boolean().default(true),
220
+ codexSubagentEnabled: z.boolean().default(false),
221
+ codexSubagentModel: z.string(),
222
+ codexSubagentEffort: z.string(),
223
+ codexSubagentPreset: z.string().default(CODEX_SUBAGENT_DEFAULT_PRESET)
172
224
  });
173
225
  /** Host-only reads: never expose the unredacted provider configuration to clients. */
174
226
  function readHostSettings(ctx, namespace) {
@@ -328,11 +380,109 @@ function registerCodexActivityProjection(ctx) {
328
380
  });
329
381
  }
330
382
  //#endregion
383
+ //#region lib/types/presets/pro-mode-store.js
384
+ /** Ephemeral in-memory per-session OpenAI API Pro mode flags (never persisted). */
385
+ const MAX_SESSION_ENTRIES = 256;
386
+ const MAX_SESSION_ID_LENGTH = 256;
387
+ function normalizeSessionId(sessionId) {
388
+ if (typeof sessionId !== "string") return void 0;
389
+ const trimmed = sessionId.trim();
390
+ if (trimmed.length === 0 || trimmed.length > MAX_SESSION_ID_LENGTH) return void 0;
391
+ return trimmed;
392
+ }
393
+ function createSessionProModeStore(maxEntries = MAX_SESSION_ENTRIES) {
394
+ const enabledSessions = /* @__PURE__ */ new Map();
395
+ return {
396
+ get(sessionId) {
397
+ const key = normalizeSessionId(sessionId);
398
+ if (key === void 0) return false;
399
+ if (!enabledSessions.has(key)) return false;
400
+ enabledSessions.delete(key);
401
+ enabledSessions.set(key, true);
402
+ return true;
403
+ },
404
+ set(sessionId, enabled) {
405
+ const key = normalizeSessionId(sessionId);
406
+ if (key === void 0) throw new Error("invalid-session-id");
407
+ if (!enabled) {
408
+ enabledSessions.delete(key);
409
+ return false;
410
+ }
411
+ if (enabledSessions.has(key)) enabledSessions.delete(key);
412
+ while (enabledSessions.size >= maxEntries) {
413
+ const oldest = enabledSessions.keys().next().value;
414
+ if (oldest === void 0) break;
415
+ enabledSessions.delete(oldest);
416
+ }
417
+ enabledSessions.set(key, true);
418
+ return true;
419
+ },
420
+ delete(sessionId) {
421
+ const key = normalizeSessionId(sessionId);
422
+ if (key !== void 0) enabledSessions.delete(key);
423
+ },
424
+ clear() {
425
+ enabledSessions.clear();
426
+ },
427
+ get size() {
428
+ return enabledSessions.size;
429
+ }
430
+ };
431
+ }
432
+ const storesByRoot = /* @__PURE__ */ new WeakMap();
433
+ /** Resolve the ephemeral Pro-mode store bound to this Cordis root context. */
434
+ function proModeStoreFor(ctx) {
435
+ const root = ctx.root ?? ctx;
436
+ let store = storesByRoot.get(root);
437
+ if (store === void 0) {
438
+ store = createSessionProModeStore();
439
+ storesByRoot.set(root, store);
440
+ }
441
+ return store;
442
+ }
443
+ //#endregion
331
444
  //#region lib/types/contracts/preset-editor-schema.js
332
445
  /** Shared wire codecs and RPC descriptors for Host/Client preset inspection. */
333
446
  const PRESET_EDITOR_PACKAGE = "@shuind/dsh-codex-harness";
334
447
  const PRESET_EDITOR_SERVICE = "codexPresetEditor";
335
448
  const presetIdSchema = z$1.string().min(1).max(256);
449
+ const proModeSessionIdSchema = z$1.string().min(1).max(256);
450
+ const proModeSetInputSchema = z$1.object({
451
+ sessionId: proModeSessionIdSchema,
452
+ enabled: z$1.boolean()
453
+ });
454
+ const proModeStateSchema = z$1.object({ enabled: z$1.boolean() });
455
+ const harnessUpdateResultSchema = z$1.discriminatedUnion("status", [
456
+ z$1.object({
457
+ status: z$1.literal("up-to-date"),
458
+ currentVersion: z$1.string(),
459
+ latestVersion: z$1.string()
460
+ }),
461
+ z$1.object({
462
+ status: z$1.literal("update-available"),
463
+ currentVersion: z$1.string(),
464
+ latestVersion: z$1.string(),
465
+ releaseUrl: z$1.string()
466
+ }),
467
+ z$1.object({
468
+ status: z$1.literal("unavailable"),
469
+ currentVersion: z$1.string(),
470
+ reason: z$1.enum([
471
+ "invalid-current-version",
472
+ "registry-unavailable",
473
+ "invalid-registry-response"
474
+ ])
475
+ })
476
+ ]);
477
+ const codexSubagentModelsSchema = z$1.object({
478
+ available: z$1.boolean(),
479
+ models: z$1.array(z$1.object({
480
+ id: z$1.string(),
481
+ name: z$1.string(),
482
+ efforts: z$1.array(z$1.string()),
483
+ defaultEffort: z$1.string().optional()
484
+ }))
485
+ });
336
486
  const presetCatalogSchema = z$1.object({
337
487
  presets: z$1.array(z$1.object({
338
488
  id: z$1.string(),
@@ -422,7 +572,11 @@ function buildPresetEditorDescriptors() {
422
572
  descriptor("catalog", void 0, z$1.unknown(), presetCatalogSchema),
423
573
  descriptor("tools", "id", presetIdSchema, presetToolCatalogSchema),
424
574
  descriptor("prompts", "id", presetIdSchema, presetPromptCatalogSchema),
425
- descriptor("read", "id", presetIdSchema, presetDefinitionSchema)
575
+ descriptor("read", "id", presetIdSchema, presetDefinitionSchema),
576
+ descriptor("proModeGet", "sessionId", proModeSessionIdSchema, proModeStateSchema),
577
+ descriptor("proModeSet", "input", proModeSetInputSchema, proModeStateSchema),
578
+ descriptor("updateCheck", void 0, z$1.unknown(), harnessUpdateResultSchema),
579
+ descriptor("codexSubagentModels", void 0, z$1.unknown(), codexSubagentModelsSchema)
426
580
  ];
427
581
  }
428
582
  buildPresetEditorDescriptors();
@@ -751,6 +905,474 @@ async function readPresetToolCatalog(ctx, preset) {
751
905
  }
752
906
  }
753
907
  //#endregion
908
+ //#region lib/types/tools/codex-subagent.js
909
+ /** Opt-in global `codex_subagent` tool backed by Codex Connect (`openai-codex`) + DSH `spawn`. */
910
+ const SPAWN_PROVIDER = "spawn";
911
+ function delegationDepthOf(agent) {
912
+ const runtime = agent.options?.subagentDepth ?? 0;
913
+ const persisted = agent.session?.header?.delegationDepth ?? 0;
914
+ return Math.max(persisted, runtime);
915
+ }
916
+ function hasOpenAICodexProvider(ctx) {
917
+ const llm = ctx.get("llm");
918
+ if (llm === void 0 || typeof llm.listProviders !== "function") return false;
919
+ try {
920
+ return llm.listProviders().some((provider) => provider.id === OPENAI_CODEX_PROVIDER);
921
+ } catch {
922
+ return false;
923
+ }
924
+ }
925
+ /** Query live `openai-codex` models and advertised reasoning efforts from the Host LLM registry. */
926
+ async function readCodexSubagentModels(ctx) {
927
+ const llm = ctx.get("llm");
928
+ if (llm === void 0 || !hasOpenAICodexProvider(ctx) || typeof llm.listModels !== "function") return {
929
+ available: false,
930
+ models: []
931
+ };
932
+ try {
933
+ const listed = await llm.listModels(OPENAI_CODEX_PROVIDER);
934
+ return {
935
+ available: true,
936
+ models: await Promise.all(listed.map(async (model) => {
937
+ let efforts = [];
938
+ let defaultEffort;
939
+ if (typeof llm.resolveModelInfo === "function") try {
940
+ const resolved = await llm.resolveModelInfo(OPENAI_CODEX_PROVIDER, model.id);
941
+ efforts = (resolved.reasoning?.efforts ?? []).map((effort) => effort.id);
942
+ defaultEffort = resolved.reasoning?.defaultEffort;
943
+ } catch {}
944
+ return {
945
+ id: model.id,
946
+ name: model.name || model.id,
947
+ efforts,
948
+ ...defaultEffort !== void 0 ? { defaultEffort } : {}
949
+ };
950
+ }))
951
+ };
952
+ } catch {
953
+ return {
954
+ available: true,
955
+ models: []
956
+ };
957
+ }
958
+ }
959
+ async function resolveChildPreset(ctx, spawnProvider, configured) {
960
+ const trimmed = configured?.trim();
961
+ if (trimmed === "inherit") return void 0;
962
+ const target = trimmed && trimmed.length > 0 ? trimmed : CODEX_SUBAGENT_DEFAULT_PRESET;
963
+ if (!spawnProvider.capabilities.agentPreset || spawnProvider.inheritsParentContext) return void 0;
964
+ const presets = ctx.get("agentPresets");
965
+ if (presets === void 0 || typeof presets.resolve !== "function") return void 0;
966
+ try {
967
+ const resolved = await presets.resolve(target);
968
+ return resolved.broken === void 0 ? resolved.id : void 0;
969
+ } catch {
970
+ return;
971
+ }
972
+ }
973
+ function buildCodexSubagentTool(ctx, currentSettings) {
974
+ return defineTool({
975
+ name: CODEX_SUBAGENT_TOOL_NAME,
976
+ description: "Delegate a self-contained task to an isolated subagent powered by the configured Codex subscription model (openai-codex), running in its own context without consuming this conversation's context or main-model API quota. Starts the subagent immediately and returns its name; when it finishes, the runtime delivers its completion notice automatically. Use `send_message` to steer it while running or continue it afterward.",
977
+ parameters: {
978
+ cwd: {
979
+ type: "string",
980
+ description: "Initial child working directory. Relative paths use your current directory; omitted inherits it."
981
+ },
982
+ description: {
983
+ type: "string",
984
+ required: true,
985
+ description: "A short (3-5 word) description of the delegated task, for display. Use the language of the user's current request."
986
+ },
987
+ name: {
988
+ type: "string",
989
+ description: "Optional short name for the subagent, unique among the subagents you create: lower-case letters, digits, and hyphens, starting with a letter, at most 32 characters; lead is reserved for the root agent."
990
+ },
991
+ prompt: {
992
+ type: "string",
993
+ required: true,
994
+ description: "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs."
995
+ }
996
+ },
997
+ output: {
998
+ schema: {
999
+ type: "object",
1000
+ additionalProperties: false,
1001
+ properties: {
1002
+ kind: {
1003
+ type: "string",
1004
+ required: true,
1005
+ const: "activation"
1006
+ },
1007
+ name: {
1008
+ type: "string",
1009
+ required: true
1010
+ }
1011
+ }
1012
+ },
1013
+ render: (_args, value) => [{
1014
+ type: "text",
1015
+ text: `started subagent ${value.name}`
1016
+ }],
1017
+ presentationMeta: (_args, value) => ({
1018
+ kind: value.kind,
1019
+ name: value.name
1020
+ })
1021
+ },
1022
+ isConcurrencySafe: () => true,
1023
+ async execute(args, exec) {
1024
+ const parent = exec.agent;
1025
+ if (parent === void 0) throw new Error("codex_subagent requires a calling agent (exec.agent was undefined)");
1026
+ const subagents = ctx.get("subagents");
1027
+ const spawnProvider = subagents?.getProvider(SPAWN_PROVIDER);
1028
+ if (subagents === void 0 || spawnProvider === void 0) throw new Error("codex_subagent requires the native `spawn` subagent provider");
1029
+ const llm = ctx.get("llm");
1030
+ if (llm === void 0 || !hasOpenAICodexProvider(ctx)) throw new Error("codex_subagent requires Codex Connect (openai-codex) to be enabled");
1031
+ const settings = currentSettings();
1032
+ let model = settings.codexSubagentModel?.trim() || "";
1033
+ if (model.length === 0) {
1034
+ const available = await llm.listModels(OPENAI_CODEX_PROVIDER);
1035
+ exec.signal.throwIfAborted();
1036
+ model = available[0]?.id ?? "";
1037
+ if (model.length === 0) throw new Error("codex_subagent has no enabled openai-codex models available");
1038
+ }
1039
+ const effortText = settings.codexSubagentEffort?.trim() || "";
1040
+ const reasoningEffort = effortText.length > 0 ? ReasoningEffortId(effortText) : void 0;
1041
+ await llm.resolveCallConfig({
1042
+ provider: OPENAI_CODEX_PROVIDER,
1043
+ model,
1044
+ ...reasoningEffort === void 0 ? {} : { reasoningEffort }
1045
+ }, exec.signal);
1046
+ exec.signal.throwIfAborted();
1047
+ if (subagents.getProvider(SPAWN_PROVIDER) !== spawnProvider) throw new Error("subagent provider \"spawn\" changed while resolving codex_subagent; retry the delegation");
1048
+ const agentPreset = await resolveChildPreset(ctx, spawnProvider, settings.codexSubagentPreset);
1049
+ exec.signal.throwIfAborted();
1050
+ const maxDepth = subagents.resolveMaxDepth(void 0);
1051
+ return {
1052
+ kind: "activation",
1053
+ name: (await subagents.startActivation({
1054
+ provider: SPAWN_PROVIDER,
1055
+ label: args.description,
1056
+ ...args.name === void 0 ? {} : { name: args.name },
1057
+ ...args.cwd === void 0 ? {} : { cwd: args.cwd },
1058
+ prompt: [{
1059
+ type: "text",
1060
+ text: args.prompt
1061
+ }],
1062
+ parent,
1063
+ ...agentPreset === void 0 ? {} : { agentPreset },
1064
+ agentOptions: {
1065
+ provider: OPENAI_CODEX_PROVIDER,
1066
+ model,
1067
+ ...reasoningEffort === void 0 ? {} : { reasoningEffort }
1068
+ },
1069
+ ...maxDepth === void 0 ? {} : { maxDepth },
1070
+ signal: exec.signal,
1071
+ delivery: "parent"
1072
+ })).name
1073
+ };
1074
+ }
1075
+ });
1076
+ }
1077
+ /**
1078
+ * Mount a reactive global registration controller for `codex_subagent`.
1079
+ * Registers immediately when enabled + `spawn` + `openai-codex` are ready, and unregisters on disable.
1080
+ */
1081
+ function installCodexSubagent(ctx, currentSettings) {
1082
+ if (typeof ctx.inject !== "function") return;
1083
+ ctx.inject(["subagents", "tools"], (subagentCtx) => {
1084
+ let mounted;
1085
+ let stopped = false;
1086
+ const unmount = () => {
1087
+ if (mounted === void 0) return;
1088
+ const current = mounted;
1089
+ mounted = void 0;
1090
+ try {
1091
+ current.dispose();
1092
+ } catch {}
1093
+ };
1094
+ const reconcile = () => {
1095
+ if (stopped) return;
1096
+ if (!(currentSettings().codexSubagentEnabled === true && subagentCtx.subagents.getProvider(SPAWN_PROVIDER) !== void 0 && hasOpenAICodexProvider(subagentCtx))) {
1097
+ unmount();
1098
+ return;
1099
+ }
1100
+ if (mounted !== void 0) return;
1101
+ try {
1102
+ const definition = buildCodexSubagentTool(subagentCtx, currentSettings);
1103
+ mounted = {
1104
+ definition,
1105
+ dispose: subagentCtx.tools.register(definition)
1106
+ };
1107
+ } catch (error) {
1108
+ subagentCtx.logger.warn(`codex: could not register global ${CODEX_SUBAGENT_TOOL_NAME} tool`);
1109
+ subagentCtx.logger.warn(error);
1110
+ }
1111
+ };
1112
+ subagentCtx.on("subagent/provider-added", (provider) => {
1113
+ if (provider.name === SPAWN_PROVIDER) reconcile();
1114
+ });
1115
+ subagentCtx.on("subagent/provider-removed", (providerName) => {
1116
+ if (providerName === SPAWN_PROVIDER) reconcile();
1117
+ });
1118
+ subagentCtx.on?.("llm/adapters-updated", () => {
1119
+ reconcile();
1120
+ });
1121
+ subagentCtx.on("settings/document-updated", (ns) => {
1122
+ if (ns === "codex") reconcile();
1123
+ });
1124
+ subagentCtx.inject(["codexPreferences"], (prefCtx) => {
1125
+ const preferences = prefCtx.get("codexPreferences");
1126
+ if (typeof preferences?.subscribe !== "function") return;
1127
+ const unsubscribe = preferences.subscribe(() => reconcile());
1128
+ prefCtx.effect(() => unsubscribe, "codex: codex_subagent preferences listener");
1129
+ reconcile();
1130
+ });
1131
+ const systemPrompt = subagentCtx.get("systemPrompt");
1132
+ if (systemPrompt !== void 0) systemPrompt.context({
1133
+ name: `tool:${CODEX_SUBAGENT_TOOL_NAME}:depth`,
1134
+ order: systemPrompt.getContextOrder("SUBAGENT_DELEGATION"),
1135
+ text: (context) => {
1136
+ if (context.agent === void 0 || mounted === void 0) return "";
1137
+ if (subagentCtx.tools.get("codex_subagent", context.scope) !== mounted.definition) return "";
1138
+ const maxDepth = subagentCtx.subagents.resolveMaxDepth(void 0);
1139
+ if (maxDepth === void 0) return "";
1140
+ const depth = delegationDepthOf(context.agent);
1141
+ if (depth < maxDepth) return "";
1142
+ return `Delegation depth for \`${CODEX_SUBAGENT_TOOL_NAME}\`: current ${depth}, maximum ${maxDepth}, remaining levels 0. Do not call \`${CODEX_SUBAGENT_TOOL_NAME}\` at this depth; carry out the work directly.`;
1143
+ }
1144
+ });
1145
+ subagentCtx.effect(() => () => {
1146
+ stopped = true;
1147
+ unmount();
1148
+ }, "codex: global codex_subagent lifecycle");
1149
+ reconcile();
1150
+ });
1151
+ }
1152
+ //#endregion
1153
+ //#region lib/types/contracts/update.js
1154
+ /** Node-free update constants, SemVer helpers, and browser update store for Codex Harness. */
1155
+ const CODEX_HARNESS_PACKAGE_NAME = "@shuind/dsh-codex-harness";
1156
+ const CODEX_HARNESS_RELEASE_TAG_BASE = "https://github.com/shuind/dsh-codex-harness/releases/tag/v";
1157
+ const CODEX_HARNESS_NPM_METADATA_URL = `https://registry.npmjs.org/-/package/${CODEX_HARNESS_PACKAGE_NAME}/dist-tags`;
1158
+ const CODEX_HARNESS_GITHUB_LATEST_RELEASE_URL = "https://api.github.com/repos/shuind/dsh-codex-harness/releases/latest";
1159
+ function normalizeHarnessVersion(raw) {
1160
+ return raw.startsWith("v") ? raw.slice(1) : raw;
1161
+ }
1162
+ function harnessReleaseUrl(version) {
1163
+ return `${CODEX_HARNESS_RELEASE_TAG_BASE}${normalizeHarnessVersion(version)}`;
1164
+ }
1165
+ function parseHarnessVersion(raw) {
1166
+ if (typeof raw !== "string") return void 0;
1167
+ const normalized = normalizeHarnessVersion(raw.trim());
1168
+ const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.exec(normalized);
1169
+ if (match === null) return void 0;
1170
+ const rawPrerelease = match[4] === void 0 ? [] : match[4].split(".");
1171
+ if (rawPrerelease.some((part) => /^\d+$/u.test(part) && !/^(0|[1-9]\d*)$/u.test(part))) return void 0;
1172
+ const prerelease = rawPrerelease.map((part) => /^(0|[1-9]\d*)$/u.test(part) ? Number(part) : part);
1173
+ if (prerelease.some((part) => typeof part === "number" && !Number.isSafeInteger(part))) return void 0;
1174
+ const parsed = {
1175
+ major: Number(match[1]),
1176
+ minor: Number(match[2]),
1177
+ patch: Number(match[3]),
1178
+ prerelease
1179
+ };
1180
+ return [
1181
+ parsed.major,
1182
+ parsed.minor,
1183
+ parsed.patch
1184
+ ].every(Number.isSafeInteger) ? parsed : void 0;
1185
+ }
1186
+ function compareIdentifiers(left, right) {
1187
+ if (typeof left === "number" && typeof right === "number") return left < right ? -1 : left > right ? 1 : 0;
1188
+ if (typeof left === "number") return -1;
1189
+ if (typeof right === "number") return 1;
1190
+ return left < right ? -1 : left > right ? 1 : 0;
1191
+ }
1192
+ function compareHarnessVersions(left, right) {
1193
+ const a = parseHarnessVersion(left);
1194
+ const b = parseHarnessVersion(right);
1195
+ if (a === void 0 || b === void 0) throw new TypeError("invalid Codex Harness version");
1196
+ for (const [aPart, bPart] of [
1197
+ [a.major, b.major],
1198
+ [a.minor, b.minor],
1199
+ [a.patch, b.patch]
1200
+ ]) if (aPart !== bPart) return aPart < bPart ? -1 : 1;
1201
+ if (a.prerelease.length === 0 && b.prerelease.length !== 0) return 1;
1202
+ if (a.prerelease.length !== 0 && b.prerelease.length === 0) return -1;
1203
+ for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i += 1) {
1204
+ const aPart = a.prerelease[i];
1205
+ const bPart = b.prerelease[i];
1206
+ if (aPart === void 0) return -1;
1207
+ if (bPart === void 0) return 1;
1208
+ const cmp = compareIdentifiers(aPart, bPart);
1209
+ if (cmp !== 0) return cmp;
1210
+ }
1211
+ return 0;
1212
+ }
1213
+ const CODEX_HARNESS_UPDATE_MAX_BYTES = 65536;
1214
+ const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
1215
+ const MAX_ROOT_WALK_DEPTH = 6;
1216
+ let cachedPackageVersion;
1217
+ async function readCurrentHarnessVersion(startDir = MODULE_DIR) {
1218
+ if (startDir === MODULE_DIR && cachedPackageVersion !== void 0) return cachedPackageVersion;
1219
+ let current = startDir;
1220
+ for (let depth = 0; depth <= MAX_ROOT_WALK_DEPTH; depth += 1) {
1221
+ try {
1222
+ const raw = await readFile(join(current, "package.json"), "utf8");
1223
+ const parsed = JSON.parse(raw);
1224
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
1225
+ const record = parsed;
1226
+ if (record["name"] === "@shuind/dsh-codex-harness" && typeof record["version"] === "string" && parseHarnessVersion(record["version"]) !== void 0) {
1227
+ const normalized = normalizeHarnessVersion(record["version"]);
1228
+ if (startDir === MODULE_DIR) cachedPackageVersion = normalized;
1229
+ return normalized;
1230
+ }
1231
+ }
1232
+ } catch {}
1233
+ const parent = dirname(current);
1234
+ if (parent === current) break;
1235
+ current = parent;
1236
+ }
1237
+ }
1238
+ async function readBoundedText(response, maxBytes) {
1239
+ if (response.body === null) {
1240
+ const text = await response.text();
1241
+ if (new TextEncoder().encode(text).byteLength > maxBytes) throw new RangeError("update response too large");
1242
+ return text;
1243
+ }
1244
+ const reader = response.body.getReader();
1245
+ const decoder = new TextDecoder();
1246
+ const chunks = [];
1247
+ let total = 0;
1248
+ try {
1249
+ while (true) {
1250
+ const next = await reader.read();
1251
+ if (next.done) break;
1252
+ total += next.value.byteLength;
1253
+ if (total > maxBytes) {
1254
+ await reader.cancel();
1255
+ throw new RangeError("update response too large");
1256
+ }
1257
+ chunks.push(decoder.decode(next.value, { stream: true }));
1258
+ }
1259
+ chunks.push(decoder.decode());
1260
+ return chunks.join("");
1261
+ } finally {
1262
+ reader.releaseLock();
1263
+ }
1264
+ }
1265
+ async function fetchBounded(fetchImpl, url, timeoutMs, headers) {
1266
+ const controller = new AbortController();
1267
+ const timer = setTimeout(() => {
1268
+ controller.abort(/* @__PURE__ */ new Error("update request timed out"));
1269
+ }, timeoutMs);
1270
+ try {
1271
+ const response = await fetchImpl(url, {
1272
+ headers,
1273
+ signal: controller.signal
1274
+ });
1275
+ return {
1276
+ response,
1277
+ text: await readBoundedText(response, CODEX_HARNESS_UPDATE_MAX_BYTES)
1278
+ };
1279
+ } finally {
1280
+ clearTimeout(timer);
1281
+ }
1282
+ }
1283
+ function registryCandidates(value) {
1284
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return [];
1285
+ const record = value;
1286
+ const tags = record["dist-tags"] ?? record;
1287
+ if (typeof tags !== "object" || tags === null || Array.isArray(tags)) return [];
1288
+ return ["latest", "alpha"].map((tag) => tags[tag]).filter((candidate) => typeof candidate === "string" && parseHarnessVersion(candidate) !== void 0).map(normalizeHarnessVersion);
1289
+ }
1290
+ async function lookupNpmLatest(fetchImpl, timeoutMs) {
1291
+ try {
1292
+ const { response, text } = await fetchBounded(fetchImpl, CODEX_HARNESS_NPM_METADATA_URL, timeoutMs, { accept: "application/json" });
1293
+ if (!response.ok) return {
1294
+ ok: false,
1295
+ reason: "registry-unavailable"
1296
+ };
1297
+ const candidates = registryCandidates(JSON.parse(text));
1298
+ if (candidates.length === 0) return {
1299
+ ok: false,
1300
+ reason: "invalid-registry-response"
1301
+ };
1302
+ return {
1303
+ ok: true,
1304
+ latestVersion: candidates.reduce((best, item) => compareHarnessVersions(item, best) > 0 ? item : best)
1305
+ };
1306
+ } catch (error) {
1307
+ return {
1308
+ ok: false,
1309
+ reason: error instanceof SyntaxError || error instanceof RangeError ? "invalid-registry-response" : "registry-unavailable"
1310
+ };
1311
+ }
1312
+ }
1313
+ async function lookupGitHubLatest(fetchImpl, timeoutMs) {
1314
+ try {
1315
+ const { response, text } = await fetchBounded(fetchImpl, CODEX_HARNESS_GITHUB_LATEST_RELEASE_URL, timeoutMs, { accept: "application/vnd.github+json" });
1316
+ if (!response.ok) return {
1317
+ ok: false,
1318
+ reason: "registry-unavailable"
1319
+ };
1320
+ const value = JSON.parse(text);
1321
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return {
1322
+ ok: false,
1323
+ reason: "invalid-registry-response"
1324
+ };
1325
+ const tag = value["tag_name"];
1326
+ if (typeof tag !== "string" || parseHarnessVersion(tag) === void 0) return {
1327
+ ok: false,
1328
+ reason: "invalid-registry-response"
1329
+ };
1330
+ return {
1331
+ ok: true,
1332
+ latestVersion: normalizeHarnessVersion(tag)
1333
+ };
1334
+ } catch (error) {
1335
+ return {
1336
+ ok: false,
1337
+ reason: error instanceof SyntaxError || error instanceof RangeError ? "invalid-registry-response" : "registry-unavailable"
1338
+ };
1339
+ }
1340
+ }
1341
+ async function checkForHarnessUpdate(options = {}) {
1342
+ const rawCurrent = options.currentVersion ?? await readCurrentHarnessVersion();
1343
+ if (rawCurrent === void 0 || parseHarnessVersion(rawCurrent) === void 0) return {
1344
+ status: "unavailable",
1345
+ currentVersion: rawCurrent ?? "0.0.0",
1346
+ reason: "invalid-current-version"
1347
+ };
1348
+ const currentVersion = normalizeHarnessVersion(rawCurrent);
1349
+ const fetchImpl = options.fetchImpl ?? fetch;
1350
+ const timeoutMs = options.timeoutMs ?? 8e3;
1351
+ const npmResult = await lookupNpmLatest(fetchImpl, timeoutMs);
1352
+ let latestVersion;
1353
+ if (npmResult.ok) latestVersion = npmResult.latestVersion;
1354
+ else {
1355
+ const githubResult = await lookupGitHubLatest(fetchImpl, timeoutMs);
1356
+ if (!githubResult.ok) return {
1357
+ status: "unavailable",
1358
+ currentVersion,
1359
+ reason: githubResult.reason === "invalid-registry-response" || npmResult.reason === "invalid-registry-response" ? "invalid-registry-response" : "registry-unavailable"
1360
+ };
1361
+ latestVersion = githubResult.latestVersion;
1362
+ }
1363
+ if (compareHarnessVersions(latestVersion, currentVersion) <= 0) return {
1364
+ status: "up-to-date",
1365
+ currentVersion,
1366
+ latestVersion: currentVersion
1367
+ };
1368
+ return {
1369
+ status: "update-available",
1370
+ currentVersion,
1371
+ latestVersion,
1372
+ releaseUrl: harnessReleaseUrl(latestVersion)
1373
+ };
1374
+ }
1375
+ //#endregion
754
1376
  //#region lib/types/presets/preset-editor.js
755
1377
  var CodexPresetEditor = class extends TypertRemoteService {
756
1378
  static inject = ["agentPresets"];
@@ -808,6 +1430,20 @@ var CodexPresetEditor = class extends TypertRemoteService {
808
1430
  composition: doc.content
809
1431
  };
810
1432
  }
1433
+ async proModeGet(sessionId) {
1434
+ if (typeof sessionId !== "string" || !sessionId.trim() || sessionId.length > 256) throw new Error("invalid-session-id");
1435
+ return { enabled: proModeStoreFor(this.toolContext ?? this).get(sessionId) };
1436
+ }
1437
+ async proModeSet(input) {
1438
+ if (typeof input !== "object" || input === null || typeof input.enabled !== "boolean") throw new Error("invalid-pro-mode-input");
1439
+ return { enabled: proModeStoreFor(this.toolContext ?? this).set(input.sessionId, input.enabled) };
1440
+ }
1441
+ async updateCheck() {
1442
+ return checkForHarnessUpdate();
1443
+ }
1444
+ async codexSubagentModels() {
1445
+ return readCodexSubagentModels(this.toolContext);
1446
+ }
811
1447
  };
812
1448
  function markRemoteMethod(methodName) {
813
1449
  const descriptor = Object.getOwnPropertyDescriptor(CodexPresetEditor.prototype, methodName);
@@ -828,7 +1464,11 @@ for (const method of [
828
1464
  "catalog",
829
1465
  "tools",
830
1466
  "prompts",
831
- "read"
1467
+ "read",
1468
+ "proModeGet",
1469
+ "proModeSet",
1470
+ "updateCheck",
1471
+ "codexSubagentModels"
832
1472
  ]) markRemoteMethod(method);
833
1473
  //#endregion
834
1474
  //#region lib/types/presets/runtime-enhancements.js
@@ -1335,14 +1975,8 @@ async function parseCompactResponsePayload(response) {
1335
1975
  const output = Array.isArray(body.output) ? body.output : [];
1336
1976
  const compactions = [];
1337
1977
  for (const item of output) {
1338
- if (!isJsonObject(item) || typeof item.encrypted_content !== "string") continue;
1339
- const encrypted = item.encrypted_content.trim();
1340
- if (encrypted.length === 0) continue;
1341
- compactions.push({
1342
- type: "compaction",
1343
- encrypted_content: encrypted,
1344
- ...typeof item.id === "string" && item.id.length > 0 ? { id: item.id } : {}
1345
- });
1978
+ const compaction = asCompactionItem(item);
1979
+ if (compaction !== void 0) compactions.push(compaction);
1346
1980
  }
1347
1981
  return {
1348
1982
  compactions,
@@ -1400,6 +2034,539 @@ async function parseCompactResponsePayload(response) {
1400
2034
  };
1401
2035
  }
1402
2036
  //#endregion
2037
+ //#region lib/types/responses/background-sse-codec.js
2038
+ /** Pure OpenAI Responses background SSE helpers: URL/body predicates, frame parsing, and poll synthesis. */
2039
+ const ENCODER = new TextEncoder();
2040
+ const KEEPALIVE_WIRE_CHUNK = ENCODER.encode(": keepalive\n\n");
2041
+ const SYNTHETIC_KEEPALIVE_OUTPUT_INDEX = 999999;
2042
+ const STREAM_EXPIRED_PATTERN = /no longer be streamed|more than 5 minutes|cannot be streamed|not streamable|stream.*expired/i;
2043
+ const HOP_BY_HOP_OR_BODY_HEADERS = /* @__PURE__ */ new Set([
2044
+ "accept",
2045
+ "connection",
2046
+ "content-encoding",
2047
+ "content-length",
2048
+ "content-type",
2049
+ "host",
2050
+ "transfer-encoding"
2051
+ ]);
2052
+ const PIAI_VISIBLE_EVENT_TYPES = /* @__PURE__ */ new Set([
2053
+ "response.output_item.added",
2054
+ "response.reasoning_summary_text.delta",
2055
+ "response.reasoning_summary_part.done",
2056
+ "response.reasoning_text.delta",
2057
+ "response.output_text.delta",
2058
+ "response.refusal.delta",
2059
+ "response.function_call_arguments.delta",
2060
+ "response.function_call_arguments.done",
2061
+ "response.custom_tool_call_input.delta",
2062
+ "response.custom_tool_call_input.done",
2063
+ "response.output_item.done",
2064
+ "response.completed",
2065
+ "response.incomplete",
2066
+ "response.failed",
2067
+ "error"
2068
+ ]);
2069
+ const TERMINAL_EVENT_TYPES = /* @__PURE__ */ new Set([
2070
+ "response.completed",
2071
+ "response.incomplete",
2072
+ "response.failed",
2073
+ "response.cancelled",
2074
+ "error"
2075
+ ]);
2076
+ /** True only for the official OpenAI Platform Responses API over HTTPS. */
2077
+ function isOfficialOpenAiResponsesUrl(url) {
2078
+ try {
2079
+ const parsed = new URL(url);
2080
+ return parsed.protocol === "https:" && parsed.hostname.toLowerCase() === "api.openai.com" && parsed.pathname.replace(/\/+$/, "").endsWith("/responses");
2081
+ } catch {
2082
+ return false;
2083
+ }
2084
+ }
2085
+ /** Enable background+store alongside streaming on eligible OpenAI Pro bodies. */
2086
+ function applyBackgroundStreamBody(body) {
2087
+ if (body.stream !== true || body.background === false) return body;
2088
+ return {
2089
+ ...body,
2090
+ background: true,
2091
+ store: true,
2092
+ stream: true
2093
+ };
2094
+ }
2095
+ function normalizeResponsesBaseUrl(url) {
2096
+ const parsed = new URL(url);
2097
+ parsed.search = "";
2098
+ parsed.hash = "";
2099
+ parsed.pathname = parsed.pathname.replace(/\/+$/, "");
2100
+ return parsed.toString();
2101
+ }
2102
+ function buildBackgroundControlHeaders(source, accept) {
2103
+ const headers = new Headers();
2104
+ source.forEach((value, key) => {
2105
+ if (!HOP_BY_HOP_OR_BODY_HEADERS.has(key.toLowerCase())) headers.set(key, value);
2106
+ });
2107
+ headers.set("accept", accept);
2108
+ return headers;
2109
+ }
2110
+ function encodeSseEvent(eventType, payload) {
2111
+ return ENCODER.encode(`event: ${eventType}\ndata: ${JSON.stringify(payload)}\n\n`);
2112
+ }
2113
+ function asObject(value) {
2114
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2115
+ }
2116
+ function parseSseEventJson(frame) {
2117
+ const dataLines = [];
2118
+ for (const rawLine of frame.split(/\r?\n/)) if (rawLine.startsWith("data:")) {
2119
+ const rest = rawLine.slice(5);
2120
+ dataLines.push(rest.startsWith(" ") ? rest.slice(1) : rest);
2121
+ }
2122
+ if (dataLines.length === 0) return void 0;
2123
+ const data = dataLines.join("\n");
2124
+ if (data === "" || data === "[DONE]") return void 0;
2125
+ try {
2126
+ return asObject(JSON.parse(data));
2127
+ } catch {
2128
+ return;
2129
+ }
2130
+ }
2131
+ function isSseContentType(headers) {
2132
+ const contentType = headers.get("content-type");
2133
+ return contentType === null || contentType.toLowerCase().includes("text/event-stream");
2134
+ }
2135
+ function shouldFallbackToPolling(status, errorText) {
2136
+ if (status === 410) return true;
2137
+ if ((status === 400 || status === 422) && STREAM_EXPIRED_PATTERN.test(errorText)) return true;
2138
+ return status === 400 && errorText.trim().length > 0;
2139
+ }
2140
+ function isRetryableStatus(status) {
2141
+ return status === 408 || status === 429 || status >= 500;
2142
+ }
2143
+ function cancelledFailureEvent(response) {
2144
+ const record = asObject(response) ?? {};
2145
+ const existingError = asObject(record.error);
2146
+ return {
2147
+ type: "response.failed",
2148
+ response: {
2149
+ ...record,
2150
+ status: "cancelled",
2151
+ error: existingError ?? {
2152
+ code: "cancelled",
2153
+ message: "Response was cancelled"
2154
+ }
2155
+ }
2156
+ };
2157
+ }
2158
+ function skeletonForAddedItem(item) {
2159
+ switch (item.type) {
2160
+ case "reasoning": return {
2161
+ ...item,
2162
+ summary: [],
2163
+ content: []
2164
+ };
2165
+ case "message": return {
2166
+ ...item,
2167
+ content: []
2168
+ };
2169
+ case "function_call": return {
2170
+ ...item,
2171
+ arguments: ""
2172
+ };
2173
+ case "custom_tool_call": return {
2174
+ ...item,
2175
+ input: ""
2176
+ };
2177
+ default: return item;
2178
+ }
2179
+ }
2180
+ function deltaFramesForNewItem(index, item) {
2181
+ const frames = [];
2182
+ if (item.type === "reasoning") {
2183
+ const summaries = Array.isArray(item.summary) ? item.summary.map((part) => asObject(part)?.text).filter((text) => typeof text === "string" && text.length > 0) : [];
2184
+ const contents = Array.isArray(item.content) ? item.content.map((part) => asObject(part)?.text).filter((text) => typeof text === "string" && text.length > 0) : [];
2185
+ const text = summaries.length > 0 ? summaries.join("\n\n") : contents.join("\n\n");
2186
+ if (text.length > 0) frames.push(encodeSseEvent("response.reasoning_summary_text.delta", {
2187
+ type: "response.reasoning_summary_text.delta",
2188
+ output_index: index,
2189
+ delta: text
2190
+ }));
2191
+ } else if (item.type === "message" && Array.isArray(item.content)) for (const rawPart of item.content) {
2192
+ const part = asObject(rawPart);
2193
+ if (part === void 0) continue;
2194
+ if (part.type === "output_text" && typeof part.text === "string" && part.text.length > 0) frames.push(encodeSseEvent("response.output_text.delta", {
2195
+ type: "response.output_text.delta",
2196
+ output_index: index,
2197
+ delta: part.text
2198
+ }));
2199
+ else if (part.type === "refusal" && typeof part.refusal === "string" && part.refusal.length > 0) frames.push(encodeSseEvent("response.refusal.delta", {
2200
+ type: "response.refusal.delta",
2201
+ output_index: index,
2202
+ delta: part.refusal
2203
+ }));
2204
+ }
2205
+ else if (item.type === "function_call" && typeof item.arguments === "string" && item.arguments.length > 0) frames.push(encodeSseEvent("response.function_call_arguments.delta", {
2206
+ type: "response.function_call_arguments.delta",
2207
+ output_index: index,
2208
+ delta: item.arguments
2209
+ }));
2210
+ else if (item.type === "custom_tool_call" && typeof item.input === "string" && item.input.length > 0) frames.push(encodeSseEvent("response.custom_tool_call_input.delta", {
2211
+ type: "response.custom_tool_call_input.delta",
2212
+ output_index: index,
2213
+ delta: item.input
2214
+ }));
2215
+ return frames;
2216
+ }
2217
+ /** Synthesize SSE events for a polled terminal Responses object without duplicating completed items. */
2218
+ function synthesizePolledResponseSseFrames(polled, openedOutputIndices, completedOutputIndices) {
2219
+ const frames = [];
2220
+ const output = Array.isArray(polled.output) ? polled.output : [];
2221
+ for (let index = 0; index < output.length; index++) {
2222
+ if (completedOutputIndices.has(index)) continue;
2223
+ const item = asObject(output[index]);
2224
+ if (item === void 0) continue;
2225
+ if (!openedOutputIndices.has(index)) {
2226
+ frames.push(encodeSseEvent("response.output_item.added", {
2227
+ type: "response.output_item.added",
2228
+ output_index: index,
2229
+ item: skeletonForAddedItem(item)
2230
+ }));
2231
+ frames.push(...deltaFramesForNewItem(index, item));
2232
+ }
2233
+ frames.push(encodeSseEvent("response.output_item.done", {
2234
+ type: "response.output_item.done",
2235
+ output_index: index,
2236
+ item
2237
+ }));
2238
+ }
2239
+ const status = typeof polled.status === "string" ? polled.status : "completed";
2240
+ if (status === "completed") frames.push(encodeSseEvent("response.completed", {
2241
+ type: "response.completed",
2242
+ response: polled
2243
+ }));
2244
+ else if (status === "incomplete") frames.push(encodeSseEvent("response.incomplete", {
2245
+ type: "response.incomplete",
2246
+ response: polled
2247
+ }));
2248
+ else if (status === "cancelled") frames.push(encodeSseEvent("response.failed", cancelledFailureEvent(polled)));
2249
+ else frames.push(encodeSseEvent("response.failed", {
2250
+ type: "response.failed",
2251
+ response: polled
2252
+ }));
2253
+ return frames;
2254
+ }
2255
+ //#endregion
2256
+ //#region lib/types/responses/background-stream.js
2257
+ /**
2258
+ * Resilient OpenAI Responses background+streaming transport for API Pro mode.
2259
+ *
2260
+ * Wraps official `api.openai.com/v1/responses` SSE streams with:
2261
+ * 1. Mid-stream SSE resume via `GET /responses/{id}?stream=true&starting_after={seq}`;
2262
+ * 2. Seamless fallback to `GET /responses/{id}` polling after OpenAI's 5-minute
2263
+ * streaming replay window expires, synthesizing only missing SSE events;
2264
+ * 3. Wire (`: keepalive`) + DSH watchdog keepalives so 5-minute idle timeouts
2265
+ * do not abort active Pro reasoning;
2266
+ * 4. Best-effort `POST /responses/{id}/cancel` on user abort before completion.
2267
+ */
2268
+ const DEFAULT_WIRE_KEEPALIVE_MS = 25e3;
2269
+ const DEFAULT_WATCHDOG_KEEPALIVE_MS = 12e4;
2270
+ const DEFAULT_POLL_INTERVAL_MS = 3e3;
2271
+ const DEFAULT_RECONNECT_BASE_DELAY_MS = 500;
2272
+ const DEFAULT_MAX_RECONNECT_DELAY_MS = 5e3;
2273
+ const DEFAULT_MAX_TRANSIENT_ERRORS = 5;
2274
+ const DEFAULT_CANCEL_TIMEOUT_MS = 5e3;
2275
+ function sleepWithSignal(ms, signal) {
2276
+ if (ms <= 0) return Promise.resolve();
2277
+ if (signal.aborted) return Promise.reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
2278
+ return new Promise((resolve, reject) => {
2279
+ const onAbort = () => {
2280
+ clearTimeout(timer);
2281
+ reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
2282
+ };
2283
+ const timer = setTimeout(() => {
2284
+ signal.removeEventListener("abort", onAbort);
2285
+ resolve();
2286
+ }, ms);
2287
+ signal.addEventListener("abort", onAbort, { once: true });
2288
+ });
2289
+ }
2290
+ /**
2291
+ * Wrap an initial 200 SSE `POST /v1/responses` response with transparent
2292
+ * sequence-tracked SSE resume, >5-minute poll fallback, keepalives, and cancel.
2293
+ */
2294
+ function wrapResilientBackgroundSseResponse(initialResponse, request, fetchImpl, timing = {}) {
2295
+ if (!initialResponse.ok || initialResponse.body === null || !isSseContentType(initialResponse.headers)) return initialResponse;
2296
+ const baseUrl = normalizeResponsesBaseUrl(request.url);
2297
+ const wireKeepaliveIntervalMs = timing.wireKeepaliveIntervalMs ?? DEFAULT_WIRE_KEEPALIVE_MS;
2298
+ const watchdogKeepaliveIntervalMs = timing.watchdogKeepaliveIntervalMs ?? DEFAULT_WATCHDOG_KEEPALIVE_MS;
2299
+ const pollIntervalMs = timing.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
2300
+ const reconnectBaseDelayMs = timing.reconnectBaseDelayMs ?? DEFAULT_RECONNECT_BASE_DELAY_MS;
2301
+ const maxReconnectDelayMs = timing.maxReconnectDelayMs ?? DEFAULT_MAX_RECONNECT_DELAY_MS;
2302
+ const maxTransientErrors = timing.maxTransientErrors ?? DEFAULT_MAX_TRANSIENT_ERRORS;
2303
+ const cancelTimeoutMs = timing.cancelTimeoutMs ?? DEFAULT_CANCEL_TIMEOUT_MS;
2304
+ let responseId;
2305
+ let lastSequenceNumber;
2306
+ const openedOutputIndices = /* @__PURE__ */ new Set();
2307
+ const completedOutputIndices = /* @__PURE__ */ new Set();
2308
+ let openReasoningOutputIndex;
2309
+ let syntheticKeepaliveSlotOpened = false;
2310
+ let sawTerminal = false;
2311
+ let closed = false;
2312
+ let cancelRequested = false;
2313
+ let activeReader;
2314
+ const internalAbort = new AbortController();
2315
+ const signal = request.signal ? AbortSignal.any([request.signal, internalAbort.signal]) : internalAbort.signal;
2316
+ const fireServerCancel = () => {
2317
+ if (sawTerminal || cancelRequested || responseId === void 0) return;
2318
+ cancelRequested = true;
2319
+ fetchImpl(`${baseUrl}/${encodeURIComponent(responseId)}/cancel`, {
2320
+ method: "POST",
2321
+ headers: buildBackgroundControlHeaders(request.headers, "application/json"),
2322
+ ...typeof AbortSignal.timeout === "function" ? { signal: AbortSignal.timeout(cancelTimeoutMs) } : {}
2323
+ }).then((res) => res.body?.cancel?.().catch(() => {})).catch(() => {});
2324
+ };
2325
+ const onRequestAbort = () => {
2326
+ fireServerCancel();
2327
+ activeReader?.cancel?.().catch(() => {});
2328
+ };
2329
+ request.signal?.addEventListener("abort", onRequestAbort, { once: true });
2330
+ const backoffDelay = (attempt) => Math.min(reconnectBaseDelayMs * 2 ** (attempt - 1), maxReconnectDelayMs);
2331
+ const stream = new ReadableStream({
2332
+ async start(controller) {
2333
+ let lastFrameSentAt = Date.now();
2334
+ let lastPiAiEventAt = Date.now();
2335
+ const safeEnqueue = (chunk) => {
2336
+ if (closed) return;
2337
+ controller.enqueue(chunk);
2338
+ lastFrameSentAt = Date.now();
2339
+ };
2340
+ const safeClose = () => {
2341
+ if (!closed) {
2342
+ closed = true;
2343
+ controller.close();
2344
+ }
2345
+ };
2346
+ const safeError = (error) => {
2347
+ if (!closed) {
2348
+ closed = true;
2349
+ controller.error(error);
2350
+ }
2351
+ };
2352
+ const emitWatchdogKeepalive = () => {
2353
+ if (closed || sawTerminal) return;
2354
+ const targetIndex = openReasoningOutputIndex ?? 999999;
2355
+ if (openReasoningOutputIndex === void 0 && !syntheticKeepaliveSlotOpened) {
2356
+ syntheticKeepaliveSlotOpened = true;
2357
+ safeEnqueue(encodeSseEvent("response.output_item.added", {
2358
+ type: "response.output_item.added",
2359
+ output_index: SYNTHETIC_KEEPALIVE_OUTPUT_INDEX,
2360
+ item: {
2361
+ type: "reasoning",
2362
+ id: "rs_codex_keepalive",
2363
+ summary: []
2364
+ }
2365
+ }));
2366
+ }
2367
+ safeEnqueue(encodeSseEvent("response.reasoning_summary_text.delta", {
2368
+ type: "response.reasoning_summary_text.delta",
2369
+ output_index: targetIndex,
2370
+ delta: ""
2371
+ }));
2372
+ lastPiAiEventAt = Date.now();
2373
+ };
2374
+ const keepaliveTimer = setInterval(() => {
2375
+ if (closed || sawTerminal || signal.aborted) return;
2376
+ const now = Date.now();
2377
+ if (now - lastPiAiEventAt >= watchdogKeepaliveIntervalMs) {
2378
+ emitWatchdogKeepalive();
2379
+ return;
2380
+ }
2381
+ if (now - lastFrameSentAt >= wireKeepaliveIntervalMs) safeEnqueue(KEEPALIVE_WIRE_CHUNK);
2382
+ }, Math.max(5, Math.min(wireKeepaliveIntervalMs, watchdogKeepaliveIntervalMs)));
2383
+ keepaliveTimer.unref?.();
2384
+ const processFrame = (rawFrame, deduplicate) => {
2385
+ if (closed || rawFrame.trim().length === 0) return;
2386
+ const event = parseSseEventJson(rawFrame);
2387
+ if (event === void 0) {
2388
+ safeEnqueue(ENCODER.encode(`${rawFrame}\n\n`));
2389
+ return;
2390
+ }
2391
+ const seq = typeof event.sequence_number === "number" ? event.sequence_number : void 0;
2392
+ if (deduplicate && seq !== void 0 && lastSequenceNumber !== void 0 && seq <= lastSequenceNumber) return;
2393
+ if (seq !== void 0) lastSequenceNumber = lastSequenceNumber === void 0 ? seq : Math.max(lastSequenceNumber, seq);
2394
+ const responseObj = asObject(event.response);
2395
+ if (typeof responseObj?.id === "string" && responseObj.id.length > 0) responseId = responseObj.id;
2396
+ const type = typeof event.type === "string" ? event.type : "";
2397
+ const outputIndex = typeof event.output_index === "number" ? event.output_index : void 0;
2398
+ const item = asObject(event.item);
2399
+ if (type === "response.output_item.added" && outputIndex !== void 0) {
2400
+ openedOutputIndices.add(outputIndex);
2401
+ if (item?.type === "reasoning") openReasoningOutputIndex = outputIndex;
2402
+ } else if (type === "response.output_item.done" && outputIndex !== void 0) {
2403
+ completedOutputIndices.add(outputIndex);
2404
+ if (openReasoningOutputIndex === outputIndex) openReasoningOutputIndex = void 0;
2405
+ }
2406
+ if (PIAI_VISIBLE_EVENT_TYPES.has(type)) lastPiAiEventAt = Date.now();
2407
+ if (TERMINAL_EVENT_TYPES.has(type)) {
2408
+ sawTerminal = true;
2409
+ if (type === "response.cancelled") {
2410
+ safeEnqueue(encodeSseEvent("response.failed", cancelledFailureEvent(event.response)));
2411
+ return;
2412
+ }
2413
+ }
2414
+ safeEnqueue(ENCODER.encode(`${rawFrame}\n\n`));
2415
+ };
2416
+ const pumpSseBody = async (body, deduplicate) => {
2417
+ const reader = body.getReader();
2418
+ activeReader = reader;
2419
+ const decoder = new TextDecoder();
2420
+ let buffer = "";
2421
+ try {
2422
+ while (!closed && !signal.aborted) {
2423
+ const { done, value } = await reader.read();
2424
+ if (done) break;
2425
+ buffer += decoder.decode(value, { stream: true });
2426
+ let match = /\r?\n\r?\n/.exec(buffer);
2427
+ while (match !== null) {
2428
+ const frame = buffer.slice(0, match.index);
2429
+ buffer = buffer.slice(match.index + match[0].length);
2430
+ processFrame(frame, deduplicate);
2431
+ if (sawTerminal || closed) return;
2432
+ match = /\r?\n\r?\n/.exec(buffer);
2433
+ }
2434
+ }
2435
+ buffer += decoder.decode();
2436
+ if (!sawTerminal && !closed && buffer.trim().length > 0 && parseSseEventJson(buffer) !== void 0) processFrame(buffer, deduplicate);
2437
+ } finally {
2438
+ activeReader = void 0;
2439
+ await reader.cancel().catch(() => {});
2440
+ reader.releaseLock();
2441
+ }
2442
+ };
2443
+ const pollUntilTerminal = async () => {
2444
+ if (responseId === void 0) throw new Error("Cannot poll OpenAI background response without response_id");
2445
+ const pollUrl = `${baseUrl}/${encodeURIComponent(responseId)}`;
2446
+ let transientErrors = 0;
2447
+ while (!sawTerminal && !closed && !signal.aborted) {
2448
+ let pollResponse;
2449
+ try {
2450
+ pollResponse = await fetchImpl(pollUrl, {
2451
+ method: "GET",
2452
+ headers: buildBackgroundControlHeaders(request.headers, "application/json"),
2453
+ signal
2454
+ });
2455
+ } catch (error) {
2456
+ if (signal.aborted || ++transientErrors > maxTransientErrors) throw error;
2457
+ await sleepWithSignal(backoffDelay(transientErrors), signal);
2458
+ continue;
2459
+ }
2460
+ if (!pollResponse.ok) {
2461
+ const errorText = await pollResponse.text().catch(() => "");
2462
+ if (isRetryableStatus(pollResponse.status) && ++transientErrors <= maxTransientErrors) {
2463
+ await sleepWithSignal(backoffDelay(transientErrors), signal);
2464
+ continue;
2465
+ }
2466
+ throw new Error(`OpenAI background poll failed (${pollResponse.status}): ${errorText || pollResponse.statusText}`);
2467
+ }
2468
+ transientErrors = 0;
2469
+ const polled = asObject(await pollResponse.json());
2470
+ if (polled === void 0) throw new Error("OpenAI background poll returned a non-object JSON payload");
2471
+ const status = typeof polled.status === "string" ? polled.status : void 0;
2472
+ if (status === "queued" || status === "in_progress") {
2473
+ await sleepWithSignal(pollIntervalMs, signal);
2474
+ continue;
2475
+ }
2476
+ if (status === "completed" || status === "incomplete" || status === "failed" || status === "cancelled") {
2477
+ const syntheticFrames = synthesizePolledResponseSseFrames(polled, openedOutputIndices, completedOutputIndices);
2478
+ sawTerminal = true;
2479
+ for (const frame of syntheticFrames) safeEnqueue(frame);
2480
+ return;
2481
+ }
2482
+ throw new Error(`Unexpected OpenAI background response status: ${String(status)}`);
2483
+ }
2484
+ };
2485
+ const resumeOrPoll = async () => {
2486
+ let transientErrors = 0;
2487
+ let usePolling = false;
2488
+ while (!sawTerminal && !closed && !signal.aborted) {
2489
+ if (usePolling) {
2490
+ await pollUntilTerminal();
2491
+ return;
2492
+ }
2493
+ if (responseId === void 0) return;
2494
+ const query = lastSequenceNumber === void 0 ? "stream=true" : `stream=true&starting_after=${lastSequenceNumber}`;
2495
+ const resumeUrl = `${baseUrl}/${encodeURIComponent(responseId)}?${query}`;
2496
+ let resumeResponse;
2497
+ try {
2498
+ resumeResponse = await fetchImpl(resumeUrl, {
2499
+ method: "GET",
2500
+ headers: buildBackgroundControlHeaders(request.headers, "text/event-stream"),
2501
+ signal
2502
+ });
2503
+ } catch (error) {
2504
+ if (signal.aborted || ++transientErrors > maxTransientErrors) throw error;
2505
+ await sleepWithSignal(backoffDelay(transientErrors), signal);
2506
+ continue;
2507
+ }
2508
+ if (!resumeResponse.ok) {
2509
+ const errorText = await resumeResponse.text().catch(() => "");
2510
+ if (shouldFallbackToPolling(resumeResponse.status, errorText)) {
2511
+ usePolling = true;
2512
+ continue;
2513
+ }
2514
+ if (isRetryableStatus(resumeResponse.status) && ++transientErrors <= maxTransientErrors) {
2515
+ await sleepWithSignal(backoffDelay(transientErrors), signal);
2516
+ continue;
2517
+ }
2518
+ throw new Error(`OpenAI background stream resume failed (${resumeResponse.status}): ${errorText || resumeResponse.statusText}`);
2519
+ }
2520
+ if (resumeResponse.body === null) {
2521
+ usePolling = true;
2522
+ continue;
2523
+ }
2524
+ transientErrors = 0;
2525
+ try {
2526
+ await pumpSseBody(resumeResponse.body, true);
2527
+ } catch (error) {
2528
+ if (signal.aborted || ++transientErrors > maxTransientErrors) throw error;
2529
+ await sleepWithSignal(backoffDelay(transientErrors), signal);
2530
+ }
2531
+ }
2532
+ };
2533
+ try {
2534
+ try {
2535
+ await pumpSseBody(initialResponse.body, false);
2536
+ } catch (error) {
2537
+ if (signal.aborted || responseId === void 0) throw error;
2538
+ }
2539
+ if (!sawTerminal && !closed && !signal.aborted && responseId !== void 0) await resumeOrPoll();
2540
+ if (signal.aborted) {
2541
+ fireServerCancel();
2542
+ safeError(signal.reason ?? new DOMException("Aborted", "AbortError"));
2543
+ return;
2544
+ }
2545
+ safeClose();
2546
+ } catch (error) {
2547
+ if (signal.aborted) fireServerCancel();
2548
+ safeError(error);
2549
+ } finally {
2550
+ clearInterval(keepaliveTimer);
2551
+ request.signal?.removeEventListener("abort", onRequestAbort);
2552
+ }
2553
+ },
2554
+ cancel() {
2555
+ closed = true;
2556
+ fireServerCancel();
2557
+ internalAbort.abort(new DOMException("Stream cancelled", "AbortError"));
2558
+ activeReader?.cancel?.().catch(() => {});
2559
+ }
2560
+ });
2561
+ const headers = new Headers(initialResponse.headers);
2562
+ headers.delete("content-length");
2563
+ return new Response(stream, {
2564
+ status: initialResponse.status,
2565
+ statusText: initialResponse.statusText,
2566
+ headers
2567
+ });
2568
+ }
2569
+ //#endregion
1403
2570
  //#region lib/types/responses/sse-diagnostics.js
1404
2571
  /** SSE error frame capture and legacy pi-ai context-overflow stream repair. */
1405
2572
  const CONTEXT_WINDOW_EXCEEDED_CODE = "CONTEXT_WINDOW_EXCEEDED";
@@ -1956,12 +3123,32 @@ function hasRemoteCompaction(body, trustedCheckpoints) {
1956
3123
  if (!Array.isArray(body.input)) return false;
1957
3124
  return body.input.some((item) => trustedMarkerInInputItem(item, trustedCheckpoints) !== void 0);
1958
3125
  }
3126
+ function withEncryptedReasoningInclude(include) {
3127
+ if (!Array.isArray(include)) return ["reasoning.encrypted_content"];
3128
+ return include.includes("reasoning.encrypted_content") ? include : [...include, "reasoning.encrypted_content"];
3129
+ }
1959
3130
  function applyRequestWireOptions(body, options) {
1960
- if (options.serviceTier === void 0 || !isGptModel(body.model) || body.service_tier !== void 0) return body;
1961
- return {
1962
- ...body,
3131
+ let next = body;
3132
+ if (options.serviceTier !== void 0 && isGptModel(next.model) && next.service_tier === void 0) next = {
3133
+ ...next,
1963
3134
  service_tier: options.serviceTier
1964
3135
  };
3136
+ if (options.reasoningMode === "pro" && supportsApiProMode(next.model)) {
3137
+ const existing = typeof next.reasoning === "object" && next.reasoning !== null && !Array.isArray(next.reasoning) ? next.reasoning : void 0;
3138
+ if (existing?.mode === void 0) {
3139
+ const reasoning = {
3140
+ ...existing,
3141
+ mode: "pro",
3142
+ ...existing?.summary === void 0 ? { summary: "auto" } : {}
3143
+ };
3144
+ next = {
3145
+ ...next,
3146
+ reasoning,
3147
+ include: withEncryptedReasoningInclude(next.include)
3148
+ };
3149
+ }
3150
+ }
3151
+ return next;
1965
3152
  }
1966
3153
  //#endregion
1967
3154
  //#region lib/types/responses/fetch-transport.js
@@ -1969,6 +3156,7 @@ function applyRequestWireOptions(body, options) {
1969
3156
  const CAPABILITY_CACHE_TTL_MS = 6e5;
1970
3157
  const CAPABILITY_CACHE_MAX_ENTRIES = 64;
1971
3158
  const CONTEXT_LIMIT_ERROR = /context_length_exceeded|maximum context length|context window|too many tokens/i;
3159
+ const REASONING_MODE_ERROR = /reasoning\.mode|reasoning_mode|['"`]mode['"`].*\bpro\b/i;
1972
3160
  const WEB_SEARCH_ERROR = /web_search|external_web_access/i;
1973
3161
  const CUSTOM_PATCH_ERROR = /apply_patch|custom_tool|custom\s+tool|grammar|lark/i;
1974
3162
  const HOSTED_REQUESTS = new AsyncLocalStorage();
@@ -2034,7 +3222,7 @@ function isCompactUnsupported(key) {
2034
3222
  }
2035
3223
  function shouldFallbackResponse(response, errorText) {
2036
3224
  if (response.status !== 400 && response.status !== 404 && response.status !== 415 && response.status !== 422) return false;
2037
- return !CONTEXT_LIMIT_ERROR.test(errorText);
3225
+ return !CONTEXT_LIMIT_ERROR.test(errorText) && !REASONING_MODE_ERROR.test(errorText);
2038
3226
  }
2039
3227
  function isAbortError(error, signal) {
2040
3228
  if (signal.aborted) return true;
@@ -2088,18 +3276,24 @@ function installGlobalHostedWebSearchPatch() {
2088
3276
  }
2089
3277
  if (isNativeCompactionTriggerBody(body)) return requestAndCapture(input, init);
2090
3278
  const requestBody = applyRequestWireOptions(body, options);
2091
- const baseBody = isGptModel(requestBody.model) && hasRemoteCompaction(requestBody, options.trustedCheckpoints) ? replaceRemoteCompactions(requestBody, options.trustedCheckpoints) : requestBody;
3279
+ const useBackgroundStream = options.reasoningMode === "pro" && options.backgroundStream === true && isOfficialOpenAiResponsesUrl(request.url) && requestBody.stream === true && requestBody.background !== false;
3280
+ const transportBody = useBackgroundStream ? applyBackgroundStreamBody(requestBody) : requestBody;
3281
+ const sendResponsesRequest = async (target, requestInit) => {
3282
+ const response = await original(target, requestInit);
3283
+ return captureCodexErrors(useBackgroundStream ? wrapResilientBackgroundSseResponse(response, request, original) : response);
3284
+ };
3285
+ const baseBody = isGptModel(transportBody.model) && hasRemoteCompaction(transportBody, options.trustedCheckpoints) ? replaceRemoteCompactions(transportBody, options.trustedCheckpoints) : transportBody;
2092
3286
  const key = capabilityKey(request.url, baseBody.model);
2093
3287
  const activeOptions = effectiveWireOptions(key, options);
2094
3288
  const usesHostedWebSearch = isGptModel(baseBody.model) && activeOptions.hostedWebSearch !== false && hasWebSearchTool(baseBody);
2095
3289
  const usesCustomApplyPatch = isGptModel(baseBody.model) && activeOptions.customApplyPatch !== false && hasFunctionApplyPatchTool(baseBody) && canRewriteApplyPatchHistory(baseBody);
2096
- if (!usesHostedWebSearch && !usesCustomApplyPatch) return baseBody === body ? requestAndCapture(input, init) : requestAndCapture(jsonRequest(request, baseBody));
3290
+ if (!usesHostedWebSearch && !usesCustomApplyPatch) return baseBody === body ? sendResponsesRequest(input, init) : sendResponsesRequest(jsonRequest(request, baseBody));
2097
3291
  const hostedRequest = jsonRequest(request, rewriteCodexResponsesBody(baseBody, activeOptions));
2098
3292
  const fallbackRequest = baseBody === body ? request.clone() : jsonRequest(request, baseBody);
2099
- const sendPlainFallback = () => requestAndCapture(fallbackRequest);
3293
+ const sendPlainFallback = () => sendResponsesRequest(fallbackRequest);
2100
3294
  let response;
2101
3295
  try {
2102
- response = await requestAndCapture(hostedRequest);
3296
+ response = await sendResponsesRequest(hostedRequest);
2103
3297
  } catch (error) {
2104
3298
  if (isAbortError(error, request.signal)) throw error;
2105
3299
  return sendPlainFallback();
@@ -2119,7 +3313,7 @@ function installGlobalHostedWebSearchPatch() {
2119
3313
  };
2120
3314
  recordUnsupportedCapability(key, mentionsWebSearch ? { hostedWebSearch: false } : { customApplyPatch: false });
2121
3315
  try {
2122
- const reducedResponse = await requestAndCapture(jsonRequest(request, rewriteCodexResponsesBody(baseBody, reducedOptions)));
3316
+ const reducedResponse = await sendResponsesRequest(jsonRequest(request, rewriteCodexResponsesBody(baseBody, reducedOptions)));
2123
3317
  if (reducedResponse.ok) return reducedResponse;
2124
3318
  if (!shouldFallbackResponse(reducedResponse, await reducedResponse.clone().text().catch(() => ""))) return reducedResponse;
2125
3319
  recordUnsupportedCapability(key, mentionsWebSearch ? { customApplyPatch: false } : { hostedWebSearch: false });
@@ -2217,29 +3411,53 @@ async function apiHeaders(ctx, profile, isV2Responses) {
2217
3411
  }
2218
3412
  return headers;
2219
3413
  }
2220
- function textOf(message) {
2221
- return message.content.map((block) => block.type === "text" ? block.text : block.type === "image" ? "[image omitted]" : "").join("");
3414
+ const VALID_IMAGE_MEDIA_TYPES = /* @__PURE__ */ new Set([
3415
+ "image/png",
3416
+ "image/jpeg",
3417
+ "image/webp",
3418
+ "image/gif"
3419
+ ]);
3420
+ function hasValidImageRef(attachment) {
3421
+ if (typeof attachment !== "object" || attachment === null) return false;
3422
+ const record = attachment;
3423
+ return typeof record.attachmentId === "string" && record.attachmentId.length > 0 && typeof record.mediaType === "string" && VALID_IMAGE_MEDIA_TYPES.has(record.mediaType) && typeof record.width === "number" && typeof record.height === "number";
3424
+ }
3425
+ function formatOffloadedImage(ctx, block) {
3426
+ const attachments = ctx.get("attachments");
3427
+ const fs = ctx.get("fs");
3428
+ const access = typeof attachments?.imageHostPath === "function" && typeof fs?.processPathFromHostPath === "function" ? resolveImageAttachmentAccess(attachments, (hostPath) => fs.processPathFromHostPath(hostPath), block.attachment) : void 0;
3429
+ return offloadedImageText(block.attachment, access);
3430
+ }
3431
+ function textOf(ctx, message) {
3432
+ return message.content.map((block) => {
3433
+ if (block.type === "text") return block.text;
3434
+ if (block.type === "image") {
3435
+ if (block.offloaded !== true || !hasValidImageRef(block.attachment)) throw new Error("Codex remote compaction requires the DSH adapter for image attachments");
3436
+ return formatOffloadedImage(ctx, block);
3437
+ }
3438
+ return "";
3439
+ }).join("");
2222
3440
  }
2223
3441
  function stripCompactionPrompt(messages) {
2224
3442
  const last = messages.at(-1);
2225
3443
  if (last !== void 0 && last.role === "user" && !("id" in last && last.id !== void 0)) return messages.slice(0, -1);
2226
3444
  return messages;
2227
3445
  }
2228
- function extractInstructions(options, messages) {
3446
+ function extractInstructions(ctx, options, messages) {
2229
3447
  if (options.system !== void 0) return options.system;
2230
3448
  for (let index = messages.length - 1; index >= 0; index -= 1) {
2231
3449
  const message = messages[index];
2232
3450
  if (message.role !== "system") continue;
2233
- const text = textOf(message);
3451
+ const text = textOf(ctx, message);
2234
3452
  return text.length > 0 ? text : void 0;
2235
3453
  }
2236
3454
  }
2237
- function responsesInput(messages) {
3455
+ function responsesInput(ctx, messages) {
2238
3456
  const result = [];
2239
3457
  for (const message of messages) {
2240
3458
  if (message.content.some((block) => block.type === "file")) throw new Error("Codex remote compaction requires the DSH adapter for attachments");
2241
3459
  if (message.role === "system") continue;
2242
- const text = textOf(message);
3460
+ const text = textOf(ctx, message);
2243
3461
  if (message.role === "tool") {
2244
3462
  result.push({
2245
3463
  type: "function_call_output",
@@ -2286,14 +3504,14 @@ function responsesTools(tools) {
2286
3504
  parameters: tool.parameters
2287
3505
  }));
2288
3506
  }
2289
- function compactBody(options, wireOptions, isV2Responses) {
3507
+ function compactBody(ctx, options, wireOptions, isV2Responses) {
2290
3508
  const messages = stripCompactionPrompt(options.messages);
2291
- const instructions = extractInstructions(options, messages);
3509
+ const instructions = extractInstructions(ctx, options, messages);
2292
3510
  const tools = responsesTools(options.tools);
2293
3511
  const serviceTier = wireOptions.serviceTier ?? serviceTierOf(options);
2294
3512
  const rewritten = rewriteCodexResponsesBody(replaceRemoteCompactions(applyRequestWireOptions({
2295
3513
  model: options.model,
2296
- input: responsesInput(messages),
3514
+ input: responsesInput(ctx, messages),
2297
3515
  ...instructions !== void 0 ? { instructions } : isV2Responses ? { instructions: "" } : {},
2298
3516
  ...tools === void 0 ? {} : { tools },
2299
3517
  ...typeof options.sessionId === "string" && options.sessionId.length > 0 ? { prompt_cache_key: options.sessionId.slice(0, 64) } : {},
@@ -2406,13 +3624,13 @@ async function remoteCompact(ctx, options, wireOptions = {}) {
2406
3624
  ...wireOptions,
2407
3625
  trustedCheckpoints: wireOptions.trustedCheckpoints ?? collectTrustedCompactionMarkers(options.messages)
2408
3626
  };
2409
- const initial = compactBody(options, compactWireOptions, isV2Responses);
3627
+ const initial = compactBody(ctx, options, compactWireOptions, isV2Responses);
2410
3628
  let preCompactInput = initial.preCompactInput;
2411
3629
  let response = await sendWithRetry(endpoint, headers, initial.body, options.signal);
2412
3630
  if (!response.ok && (response.status === 400 || response.status === 422) && canRewriteCompactTools(options, wireOptions)) {
2413
3631
  const errorText = await response.clone().text().catch(() => "");
2414
3632
  if (!CONTEXT_LIMIT_ERROR.test(errorText)) {
2415
- const reduced = compactBody(options, {
3633
+ const reduced = compactBody(ctx, options, {
2416
3634
  ...compactWireOptions,
2417
3635
  hostedWebSearch: false,
2418
3636
  customApplyPatch: false
@@ -4016,6 +5234,7 @@ function apply(ctx, config = {}) {
4016
5234
  if (resolved.globalEnhancements) {
4017
5235
  installPresetEditor(ctx);
4018
5236
  installGlobalCompactCommand(ctx);
5237
+ installCodexSubagent(ctx, codexSettings.current);
4019
5238
  watchConfiguredGptModels(ctx);
4020
5239
  registerCodexActivityProjection(ctx);
4021
5240
  installCodexContextProjection(ctx, codexSettings.current);
@@ -4027,13 +5246,20 @@ function apply(ctx, config = {}) {
4027
5246
  if (agent !== null && typeof agent === "object") lastRequestByAgent.set(agent, updated);
4028
5247
  return updated;
4029
5248
  });
5249
+ const proModeStore = proModeStoreFor(ctx);
4030
5250
  if (typeof ctx.effect === "function") {
4031
5251
  const disposeHostedWebSearch = installHostedWebSearch();
4032
- ctx.effect(() => disposeHostedWebSearch, "codex: Responses transport wrapper");
5252
+ ctx.effect(() => () => {
5253
+ disposeHostedWebSearch();
5254
+ proModeStore.clear();
5255
+ }, "codex: Responses transport wrapper");
4033
5256
  }
4034
5257
  ctx.on("llm/stream", ((options, next) => {
4035
5258
  const settings = codexSettings.current();
4036
5259
  const isCodexConnect = options.provider === "openai-codex";
5260
+ const sessionId = typeof options.sessionId === "string" ? options.sessionId : options.sessionId !== void 0 && options.sessionId !== null ? String(options.sessionId) : void 0;
5261
+ const llmProviders = readHostSettings(ctx, "llm-pi-ai")?.providers;
5262
+ const proModeEnabled = options.purpose === void 0 && !isCodexConnect && isOfficialOpenAiApiRoute(options.provider, options.model, llmProviders) && proModeStore.get(sessionId);
4037
5263
  const contextWindow = options.contextWindow ?? (isCodexConnect ? void 0 : settings.contextWindow);
4038
5264
  const modelMax = typeof options.model === "string" ? OPENAI_CODEX_MODEL_LIMITS[options.model]?.maxTokens : void 0;
4039
5265
  const repairCeiling = isCodexConnect ? modelMax ?? 1e6 : options.purpose === "compaction" ? Math.max(contextWindow ?? 0, modelMax ?? 1e6) : contextWindow;
@@ -4060,6 +5286,10 @@ function apply(ctx, config = {}) {
4060
5286
  }
4061
5287
  if (options.purpose === void 0 && isGptModel(options.model)) return repairLegacyPiAiContextOverflow(hostedWebSearchStream(next, {
4062
5288
  ...serviceTier === void 0 ? {} : { serviceTier },
5289
+ ...proModeEnabled ? {
5290
+ reasoningMode: "pro",
5291
+ backgroundStream: true
5292
+ } : {},
4063
5293
  hostedWebSearch: !isCodexConnect && resolved.hostedWebSearch && settings.hostedWebSearchEnabled,
4064
5294
  customApplyPatch: settings.patchToolEnabled,
4065
5295
  ...trustedCheckpoints === void 0 ? {} : { trustedCheckpoints }