@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
@@ -0,0 +1,307 @@
1
+ /** Node-free update constants, SemVer helpers, and browser update store for Codex Harness. */
2
+
3
+ declare const __CODEX_HARNESS_VERSION__: string | undefined
4
+
5
+ export const CODEX_HARNESS_PACKAGE_NAME = '@shuind/dsh-codex-harness'
6
+ export const CODEX_HARNESS_REPO_URL = 'https://github.com/shuind/dsh-codex-harness'
7
+ export const CODEX_HARNESS_RELEASES_URL = 'https://github.com/shuind/dsh-codex-harness/releases'
8
+ export const CODEX_HARNESS_RELEASE_TAG_BASE = 'https://github.com/shuind/dsh-codex-harness/releases/tag/v'
9
+ export const CODEX_HARNESS_NPM_METADATA_URL = `https://registry.npmjs.org/-/package/${CODEX_HARNESS_PACKAGE_NAME}/dist-tags`
10
+ export const CODEX_HARNESS_GITHUB_LATEST_RELEASE_URL = 'https://api.github.com/repos/shuind/dsh-codex-harness/releases/latest'
11
+
12
+ export const CODEX_CONNECT_PACKAGE_NAME = '@shuind/dsh-codex-connect'
13
+ export const CODEX_CONNECT_REPO_URL = 'https://github.com/shuind/dsh-codex-connect'
14
+
15
+ export const CODEX_HARNESS_UPDATE_CACHE_KEY = '@shuind/dsh-codex-harness:update-check'
16
+ export const CODEX_HARNESS_UPDATE_DISMISSED_KEY = '@shuind/dsh-codex-harness:update-seen'
17
+ export const CODEX_HARNESS_UPDATE_CACHE_TTL_MS = 24 * 60 * 60 * 1_000
18
+ export const CODEX_HARNESS_UPDATE_RECHECK_MS = 5 * 60 * 1_000
19
+
20
+ export type HarnessUpdateResult =
21
+ | {
22
+ status: 'up-to-date'
23
+ currentVersion: string
24
+ latestVersion: string
25
+ }
26
+ | {
27
+ status: 'update-available'
28
+ currentVersion: string
29
+ latestVersion: string
30
+ releaseUrl: string
31
+ }
32
+ | {
33
+ status: 'unavailable'
34
+ currentVersion: string
35
+ reason: 'invalid-current-version' | 'registry-unavailable' | 'invalid-registry-response'
36
+ }
37
+
38
+ export interface HarnessUpdateSnapshot {
39
+ readonly status: 'idle' | 'checking' | HarnessUpdateResult['status']
40
+ readonly currentVersion?: string
41
+ readonly checkedAt?: number
42
+ readonly latestVersion?: string
43
+ readonly releaseUrl?: string
44
+ readonly dismissedNotice?: string
45
+ }
46
+
47
+ interface ParsedVersion {
48
+ major: number
49
+ minor: number
50
+ patch: number
51
+ prerelease: Array<number | string>
52
+ }
53
+
54
+ export function normalizeHarnessVersion(raw: string): string {
55
+ return raw.startsWith('v') ? raw.slice(1) : raw
56
+ }
57
+
58
+ export function harnessReleaseUrl(version: string): string {
59
+ return `${CODEX_HARNESS_RELEASE_TAG_BASE}${normalizeHarnessVersion(version)}`
60
+ }
61
+
62
+ export function parseHarnessVersion(raw: string): ParsedVersion | undefined {
63
+ if (typeof raw !== 'string') return undefined
64
+ const normalized = normalizeHarnessVersion(raw.trim())
65
+ 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)
66
+ if (match === null) return undefined
67
+ const rawPrerelease = match[4] === undefined ? [] : match[4].split('.')
68
+ if (rawPrerelease.some(part => /^\d+$/u.test(part) && !/^(0|[1-9]\d*)$/u.test(part))) return undefined
69
+ const prerelease = rawPrerelease.map(part => /^(0|[1-9]\d*)$/u.test(part) ? Number(part) : part)
70
+ if (prerelease.some(part => typeof part === 'number' && !Number.isSafeInteger(part))) return undefined
71
+ const parsed = { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]), prerelease }
72
+ return [parsed.major, parsed.minor, parsed.patch].every(Number.isSafeInteger) ? parsed : undefined
73
+ }
74
+
75
+ function compareIdentifiers(left: number | string, right: number | string): number {
76
+ if (typeof left === 'number' && typeof right === 'number') return left < right ? -1 : left > right ? 1 : 0
77
+ if (typeof left === 'number') return -1
78
+ if (typeof right === 'number') return 1
79
+ return left < right ? -1 : left > right ? 1 : 0
80
+ }
81
+
82
+ export function compareHarnessVersions(left: string, right: string): number {
83
+ const a = parseHarnessVersion(left)
84
+ const b = parseHarnessVersion(right)
85
+ if (a === undefined || b === undefined) throw new TypeError('invalid Codex Harness version')
86
+ for (const [aPart, bPart] of [[a.major, b.major], [a.minor, b.minor], [a.patch, b.patch]] as const) {
87
+ if (aPart !== bPart) return aPart < bPart ? -1 : 1
88
+ }
89
+ if (a.prerelease.length === 0 && b.prerelease.length !== 0) return 1
90
+ if (a.prerelease.length !== 0 && b.prerelease.length === 0) return -1
91
+ for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i += 1) {
92
+ const aPart = a.prerelease[i]
93
+ const bPart = b.prerelease[i]
94
+ if (aPart === undefined) return -1
95
+ if (bPart === undefined) return 1
96
+ const cmp = compareIdentifiers(aPart, bPart)
97
+ if (cmp !== 0) return cmp
98
+ }
99
+ return 0
100
+ }
101
+
102
+ export function parseHarnessUpdateResult(value: unknown): HarnessUpdateResult | undefined {
103
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined
104
+ const record = value as Record<string, unknown>
105
+ const currentVersion = record['currentVersion']
106
+ if (typeof currentVersion !== 'string' || parseHarnessVersion(currentVersion) === undefined) return undefined
107
+ if (record['status'] === 'unavailable') {
108
+ const reason = record['reason']
109
+ return reason === 'invalid-current-version' || reason === 'registry-unavailable' || reason === 'invalid-registry-response'
110
+ ? { status: 'unavailable', currentVersion: normalizeHarnessVersion(currentVersion), reason }
111
+ : undefined
112
+ }
113
+ const latestVersion = record['latestVersion']
114
+ if (typeof latestVersion !== 'string' || parseHarnessVersion(latestVersion) === undefined) return undefined
115
+ const normalizedCurrent = normalizeHarnessVersion(currentVersion)
116
+ const normalizedLatest = normalizeHarnessVersion(latestVersion)
117
+ if (record['status'] === 'up-to-date') {
118
+ return { status: 'up-to-date', currentVersion: normalizedCurrent, latestVersion: normalizedLatest }
119
+ }
120
+ if (record['status'] !== 'update-available' || compareHarnessVersions(normalizedLatest, normalizedCurrent) <= 0) return undefined
121
+ const expectedUrl = harnessReleaseUrl(normalizedLatest)
122
+ if (record['releaseUrl'] !== expectedUrl) return undefined
123
+ return { status: 'update-available', currentVersion: normalizedCurrent, latestVersion: normalizedLatest, releaseUrl: expectedUrl }
124
+ }
125
+
126
+ export function bundledHarnessVersion(): string | undefined {
127
+ try {
128
+ return typeof __CODEX_HARNESS_VERSION__ === 'string' && parseHarnessVersion(__CODEX_HARNESS_VERSION__) !== undefined
129
+ ? normalizeHarnessVersion(__CODEX_HARNESS_VERSION__)
130
+ : undefined
131
+ } catch {
132
+ return undefined
133
+ }
134
+ }
135
+
136
+ export function harnessUpdateNoticeKey(snapshot: HarnessUpdateSnapshot): string | undefined {
137
+ if (snapshot.status !== 'update-available' || !snapshot.currentVersion || !snapshot.latestVersion) return undefined
138
+ return `${snapshot.currentVersion}:${snapshot.latestVersion}`
139
+ }
140
+
141
+ function browserStorage(): Storage | undefined {
142
+ try {
143
+ return typeof localStorage === 'undefined' ? undefined : localStorage
144
+ } catch {
145
+ return undefined
146
+ }
147
+ }
148
+
149
+ export class HarnessUpdateStore {
150
+ private snapshot: HarnessUpdateSnapshot
151
+ private readonly listeners = new Set<() => void>()
152
+ private readonly shownInSession = new Set<string>()
153
+ private dismissedInSession: string | undefined
154
+ private inFlight = false
155
+ private disposed = false
156
+ private recheckTimer: ReturnType<typeof setTimeout> | undefined
157
+
158
+ constructor(
159
+ private readonly fetchUpdate: () => Promise<HarnessUpdateResult | undefined>,
160
+ private readonly initialVersion: string | undefined = bundledHarnessVersion(),
161
+ ) {
162
+ this.snapshot = {
163
+ status: 'idle',
164
+ ...(initialVersion === undefined ? {} : { currentVersion: initialVersion }),
165
+ }
166
+ }
167
+
168
+ getSnapshot = (): HarnessUpdateSnapshot => this.snapshot
169
+
170
+ subscribe = (listener: () => void): (() => void) => {
171
+ this.listeners.add(listener)
172
+ return () => { this.listeners.delete(listener) }
173
+ }
174
+
175
+ private setSnapshot(next: HarnessUpdateSnapshot): void {
176
+ if (this.disposed) return
177
+ this.snapshot = next
178
+ for (const listener of [...this.listeners]) listener()
179
+ }
180
+
181
+ private effectiveDismissed(): string | undefined {
182
+ if (this.dismissedInSession !== undefined) return this.dismissedInSession
183
+ try {
184
+ const stored = browserStorage()?.getItem(CODEX_HARNESS_UPDATE_DISMISSED_KEY)
185
+ if (!stored) return undefined
186
+ return this.shownInSession.has(stored) ? undefined : stored
187
+ } catch {
188
+ return undefined
189
+ }
190
+ }
191
+
192
+ private readCached(): { result: HarnessUpdateResult; checkedAt: number } | undefined {
193
+ try {
194
+ const raw = browserStorage()?.getItem(CODEX_HARNESS_UPDATE_CACHE_KEY)
195
+ if (!raw) return undefined
196
+ const parsed = JSON.parse(raw) as { checkedAt?: unknown; result?: unknown }
197
+ if (typeof parsed.checkedAt !== 'number' || !Number.isSafeInteger(parsed.checkedAt)) return undefined
198
+ const now = Date.now()
199
+ if (parsed.checkedAt > now || now - parsed.checkedAt > CODEX_HARNESS_UPDATE_CACHE_TTL_MS) return undefined
200
+ const result = parseHarnessUpdateResult(parsed.result)
201
+ if (result === undefined || result.status === 'unavailable') return undefined
202
+ if (this.initialVersion !== undefined && result.currentVersion !== this.initialVersion) return undefined
203
+ return { result, checkedAt: parsed.checkedAt }
204
+ } catch {
205
+ return undefined
206
+ }
207
+ }
208
+
209
+ private writeCached(result: HarnessUpdateResult, checkedAt: number): void {
210
+ try {
211
+ if (result.status === 'unavailable') browserStorage()?.removeItem(CODEX_HARNESS_UPDATE_CACHE_KEY)
212
+ else browserStorage()?.setItem(CODEX_HARNESS_UPDATE_CACHE_KEY, JSON.stringify({ checkedAt, result }))
213
+ } catch {
214
+ // Ignore blocked browser storage.
215
+ }
216
+ }
217
+
218
+ private toSnapshot(result: HarnessUpdateResult, checkedAt: number): HarnessUpdateSnapshot {
219
+ const dismissedNotice = this.effectiveDismissed()
220
+ return {
221
+ status: result.status,
222
+ currentVersion: result.currentVersion,
223
+ checkedAt,
224
+ ...(result.status === 'up-to-date' || result.status === 'update-available' ? { latestVersion: result.latestVersion } : {}),
225
+ ...(result.status === 'update-available' ? { releaseUrl: result.releaseUrl } : {}),
226
+ ...(dismissedNotice === undefined ? {} : { dismissedNotice }),
227
+ }
228
+ }
229
+
230
+ async refresh(force = false): Promise<void> {
231
+ if (this.disposed || this.inFlight) return
232
+ clearTimeout(this.recheckTimer)
233
+ this.recheckTimer = undefined
234
+ this.inFlight = true
235
+ const dismissedNotice = this.effectiveDismissed()
236
+ this.setSnapshot({
237
+ status: 'checking',
238
+ ...(this.snapshot.currentVersion === undefined ? {} : { currentVersion: this.snapshot.currentVersion }),
239
+ ...(dismissedNotice === undefined ? {} : { dismissedNotice }),
240
+ })
241
+ try {
242
+ if (!force) {
243
+ const cached = this.readCached()
244
+ if (cached !== undefined) {
245
+ this.setSnapshot(this.toSnapshot(cached.result, cached.checkedAt))
246
+ return
247
+ }
248
+ }
249
+ const raw = await this.fetchUpdate()
250
+ if (this.disposed) return
251
+ const valid = parseHarnessUpdateResult(raw)
252
+ if (valid !== undefined) {
253
+ const checkedAt = Date.now()
254
+ this.writeCached(valid, checkedAt)
255
+ this.setSnapshot(this.toSnapshot(valid, checkedAt))
256
+ if (valid.status === 'unavailable') {
257
+ this.recheckTimer = setTimeout(() => { void this.refresh(true) }, CODEX_HARNESS_UPDATE_RECHECK_MS)
258
+ }
259
+ return
260
+ }
261
+ const fallbackVersion = this.snapshot.currentVersion ?? this.initialVersion
262
+ this.setSnapshot({
263
+ status: 'unavailable',
264
+ ...(fallbackVersion === undefined ? {} : { currentVersion: fallbackVersion }),
265
+ checkedAt: Date.now(),
266
+ ...(dismissedNotice === undefined ? {} : { dismissedNotice }),
267
+ })
268
+ } catch {
269
+ if (this.disposed) return
270
+ const fallbackVersion = this.snapshot.currentVersion ?? this.initialVersion
271
+ this.setSnapshot({
272
+ status: 'unavailable',
273
+ ...(fallbackVersion === undefined ? {} : { currentVersion: fallbackVersion }),
274
+ checkedAt: Date.now(),
275
+ ...(dismissedNotice === undefined ? {} : { dismissedNotice }),
276
+ })
277
+ } finally {
278
+ this.inFlight = false
279
+ }
280
+ }
281
+
282
+ markShown(notice: string): void {
283
+ this.shownInSession.add(notice)
284
+ try {
285
+ browserStorage()?.setItem(CODEX_HARNESS_UPDATE_DISMISSED_KEY, notice)
286
+ } catch {
287
+ // Fall back to in-session tracking.
288
+ }
289
+ }
290
+
291
+ dismiss(notice: string): void {
292
+ this.dismissedInSession = notice
293
+ try {
294
+ browserStorage()?.setItem(CODEX_HARNESS_UPDATE_DISMISSED_KEY, notice)
295
+ } catch {
296
+ // Keep in-session dismissal.
297
+ }
298
+ this.setSnapshot({ ...this.snapshot, dismissedNotice: notice })
299
+ }
300
+
301
+ dispose(): void {
302
+ this.disposed = true
303
+ clearTimeout(this.recheckTimer)
304
+ this.recheckTimer = undefined
305
+ this.listeners.clear()
306
+ }
307
+ }
@@ -21,9 +21,15 @@ import {
21
21
  readHostSettings,
22
22
  } from '../contracts/settings.ts'
23
23
  import type { CodexSettings } from '../contracts/settings.ts'
24
- import { CODEX_CONTEXT_MAX, OPENAI_CODEX_MODEL_LIMITS } from '../contracts/ui-contracts.ts'
24
+ import {
25
+ CODEX_CONTEXT_MAX,
26
+ isOfficialOpenAiApiRoute,
27
+ OPENAI_CODEX_MODEL_LIMITS,
28
+ } from '../contracts/ui-contracts.ts'
29
+ import type { LlmProvidersMap } from '../contracts/ui-contracts.ts'
25
30
  import { hasPresetPromptOverride } from '../policy/tool-capabilities.ts'
26
31
  import { registerCodexActivityProjection } from '../presets/activity.ts'
32
+ import { proModeStoreFor } from '../presets/pro-mode-store.ts'
27
33
  import {
28
34
  applyCodexPresentationSettings,
29
35
  applyCodexRequestSettings,
@@ -50,6 +56,7 @@ import {
50
56
  } from '../tools/exec-plan-tools.ts'
51
57
  import type { CodexExecAndPlanOptions } from '../tools/exec-plan-tools.ts'
52
58
  import { registerPatchTool } from '../tools/patch-tool.ts'
59
+ import { installCodexSubagent } from '../tools/codex-subagent.ts'
53
60
  import { installGlobalCompactCommand } from './compact-command.ts'
54
61
  import { codexCompactionMode, withExplicitLocalCompactionInstruction } from './compaction.ts'
55
62
 
@@ -194,6 +201,7 @@ export function apply(ctx: Context, config: Config = {}): void {
194
201
  // Native presets reject host services in their isolated composition.
195
202
  installPresetEditor(ctx)
196
203
  installGlobalCompactCommand(ctx)
204
+ installCodexSubagent(ctx, codexSettings.current)
197
205
  // The generic pi-ai plugin remains the owner of provider routes. This
198
206
  // layer adds only request metadata and remote-first transport behavior.
199
207
  watchConfiguredGptModels(ctx)
@@ -208,13 +216,27 @@ export function apply(ctx: Context, config: Config = {}): void {
208
216
  if (agent !== null && typeof agent === 'object') lastRequestByAgent.set(agent, updated)
209
217
  return updated
210
218
  })
219
+ const proModeStore = proModeStoreFor(ctx)
211
220
  if (typeof (ctx as unknown as { effect?: unknown }).effect === 'function') {
212
221
  const disposeHostedWebSearch = installHostedWebSearch()
213
- ctx.effect(() => disposeHostedWebSearch, 'codex: Responses transport wrapper')
222
+ ctx.effect(() => () => {
223
+ disposeHostedWebSearch()
224
+ proModeStore.clear()
225
+ }, 'codex: Responses transport wrapper')
214
226
  }
215
227
  ctx.on('llm/stream', ((options: any, next: any) => {
216
228
  const settings = codexSettings.current()
217
229
  const isCodexConnect = options.provider === 'openai-codex'
230
+ const sessionId = typeof options.sessionId === 'string'
231
+ ? options.sessionId
232
+ : options.sessionId !== undefined && options.sessionId !== null
233
+ ? String(options.sessionId)
234
+ : undefined
235
+ const llmProviders = readHostSettings<{ providers?: LlmProvidersMap }>(ctx, 'llm-pi-ai')?.providers
236
+ const proModeEnabled = options.purpose === undefined
237
+ && !isCodexConnect
238
+ && isOfficialOpenAiApiRoute(options.provider, options.model, llmProviders)
239
+ && proModeStore.get(sessionId)
218
240
  const contextWindow = options.contextWindow ?? (isCodexConnect ? undefined : settings.contextWindow)
219
241
  const modelMax = typeof options.model === 'string'
220
242
  ? OPENAI_CODEX_MODEL_LIMITS[options.model]?.maxTokens
@@ -264,6 +286,7 @@ export function apply(ctx: Context, config: Config = {}): void {
264
286
  return repairLegacyPiAiContextOverflow(
265
287
  hostedWebSearchStream(next, {
266
288
  ...serviceTier === undefined ? {} : { serviceTier },
289
+ ...proModeEnabled ? { reasoningMode: 'pro' as const, backgroundStream: true } : {},
267
290
  hostedWebSearch: !isCodexConnect && resolved.hostedWebSearch && settings.hostedWebSearchEnabled,
268
291
  customApplyPatch: settings.patchToolEnabled,
269
292
  ...trustedCheckpoints === undefined ? {} : { trustedCheckpoints },
@@ -7,12 +7,21 @@ export const Config: z<CodexSettings, CodexSettings, 'volatile-defined'> = CODEX
7
7
 
8
8
  export default class CodexPreferences extends Service {
9
9
  static Config = Config
10
+ private readonly listeners = new Set<() => void>()
10
11
 
11
12
  constructor(ctx: Context, private readonly value: ReturnType<typeof Config>) {
12
13
  super(ctx, 'codexPreferences')
14
+ ;(ctx as unknown as { on?: (event: string, listener: () => void) => void }).on?.('loader/volatile-update', () => {
15
+ for (const listener of [...this.listeners]) listener()
16
+ })
13
17
  }
14
18
 
15
19
  current(): CodexSettings {
16
20
  return this.value.get() ?? CODEX_SETTINGS_ENTRY
17
21
  }
22
+
23
+ subscribe(listener: () => void): () => void {
24
+ this.listeners.add(listener)
25
+ return () => { this.listeners.delete(listener) }
26
+ }
18
27
  }
@@ -19,11 +19,27 @@ function pad(indent: number): string {
19
19
  return ' '.repeat(indent)
20
20
  }
21
21
 
22
- function docLines(description: unknown, indent: number): string[] {
23
- if (typeof description !== 'string' || description.length === 0) return []
24
- const collapsed = description.replace(/\s+/gu, ' ').trim()
25
- if (collapsed.length === 0) return []
26
- return [`${pad(indent)}/** ${collapsed.replaceAll('*/', String.raw`*\/`)} */`]
22
+ const READ_DEFAULT_LIMIT_PATTERN = /\bDefaults to (\d+)\b/i
23
+ const ALREADY_HAS_UPPER_BOUND = /<=|≤|at most|less than or equal|hard max/i
24
+
25
+ function propertyConstraintHint(node: JsonSchemaNode, toolName?: string, propName?: string): string | undefined {
26
+ if (toolName === 'read' && propName === 'limit') {
27
+ const desc = typeof node.description === 'string' ? node.description : ''
28
+ if (!ALREADY_HAS_UPPER_BOUND.test(desc)) {
29
+ const match = READ_DEFAULT_LIMIT_PATTERN.exec(desc)
30
+ if (match?.[1] !== undefined) return `Hard max: <= ${match[1]} (paginate with offset)`
31
+ }
32
+ }
33
+ return undefined
34
+ }
35
+
36
+ function docLines(description: unknown, indent: number, hint?: string): string[] {
37
+ const base = typeof description === 'string' ? description.replace(/\s+/gu, ' ').trim() : ''
38
+ const combined = base && hint
39
+ ? `${base.endsWith('.') ? base : `${base}.`} ${hint}.`
40
+ : base || (hint ? `${hint}.` : '')
41
+ if (combined.length === 0) return []
42
+ return [`${pad(indent)}/** ${combined.replaceAll('*/', String.raw`*\/`)} */`]
27
43
  }
28
44
 
29
45
  function renderScalar(node: JsonSchemaNode, type: string): string {
@@ -39,7 +55,7 @@ function containsUnion(text: string): boolean {
39
55
  return text.includes(' | ')
40
56
  }
41
57
 
42
- function renderObjectNode(node: JsonSchemaNode, indent: number): string {
58
+ function renderObjectNode(node: JsonSchemaNode, indent: number, toolName?: string): string {
43
59
  const properties = node.properties ?? {}
44
60
  const required = new Set(node.required ?? [])
45
61
  const keys = Object.keys(properties).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
@@ -47,7 +63,7 @@ function renderObjectNode(node: JsonSchemaNode, indent: number): string {
47
63
  for (const key of keys) {
48
64
  const child = properties[key]
49
65
  if (child === undefined) continue
50
- lines.push(...docLines(child.description, indent + 1))
66
+ lines.push(...docLines(child.description, indent + 1, propertyConstraintHint(child, toolName, key)))
51
67
  const optional = required.has(key) ? '' : '?'
52
68
  lines.push(`${pad(indent + 1)}${renderKey(key)}${optional}: ${renderNode(child, indent + 1)};`)
53
69
  }
@@ -58,7 +74,7 @@ function renderObjectNode(node: JsonSchemaNode, indent: number): string {
58
74
  return `{\n${lines.join('\n')}\n${pad(indent)}}`
59
75
  }
60
76
 
61
- function renderNode(node: JsonSchemaNode, indent: number): string {
77
+ function renderNode(node: JsonSchemaNode, indent: number, toolName?: string): string {
62
78
  if (Array.isArray(node.oneOf) && node.oneOf.length > 0) {
63
79
  return node.oneOf.map(branch => renderNode(branch, indent)).join(' | ')
64
80
  }
@@ -66,7 +82,7 @@ function renderNode(node: JsonSchemaNode, indent: number): string {
66
82
  case undefined:
67
83
  return 'JsonValue'
68
84
  case 'object':
69
- return renderObjectNode(node, indent)
85
+ return renderObjectNode(node, indent, toolName)
70
86
  case 'array': {
71
87
  const itemText = node.items === undefined ? 'JsonValue' : renderNode(node.items, indent)
72
88
  return containsUnion(itemText) ? `(${itemText})[]` : `${itemText}[]`
@@ -83,10 +99,10 @@ function renderNode(node: JsonSchemaNode, indent: number): string {
83
99
  }
84
100
 
85
101
  /** Render one supported JSON Schema node to TypeScript, degrading invalid schemas safely. */
86
- export function jsonSchemaToTs(schema: unknown, indent = 0): string {
102
+ export function jsonSchemaToTs(schema: unknown, indent = 0, toolName?: string): string {
87
103
  try {
88
104
  assertSupportedJsonSchema(schema)
89
- return renderNode(schema, indent)
105
+ return renderNode(schema, indent, toolName)
90
106
  } catch {
91
107
  return 'unknown'
92
108
  }
@@ -186,7 +202,7 @@ export function renderHybridToolsSdk(
186
202
  const outputMembers: string[] = []
187
203
  for (const schema of sorted) {
188
204
  argsMembers.push(...docLines(schema.description, 1))
189
- argsMembers.push(`${pad(1)}${renderKey(schema.name)}: ${jsonSchemaToTs(schema.parameters, 1)};`)
205
+ argsMembers.push(`${pad(1)}${renderKey(schema.name)}: ${jsonSchemaToTs(schema.parameters, 1, schema.name)};`)
190
206
  outputMembers.push(`${pad(1)}${renderKey(schema.name)}: ${jsonSchemaToTs(schema.output, 1)};`)
191
207
  }
192
208
 
@@ -1,11 +1,15 @@
1
1
  /** Read-only Host Remote service for inspecting declarative agent presets. */
2
2
  import type { Context } from '@deepseek-ai/cordis'
3
3
  import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
4
- import type { PresetCatalog, PresetDefinitionDocument, PresetPromptCatalog } from '../contracts/ui-contracts.ts'
4
+ import type { CodexSubagentModelCatalog, PresetCatalog, PresetDefinitionDocument, PresetPromptCatalog } from '../contracts/ui-contracts.ts'
5
5
  import { PRESET_EDITOR_SERVICE } from '../contracts/preset-editor-schema.ts'
6
6
  import type { PresetToolCatalog } from '../contracts/tool-policy-contract.ts'
7
7
  import { readPresetPromptCatalog } from './preset-prompt-catalog.ts'
8
8
  import { readPresetToolCatalog } from './preset-tool-catalog.ts'
9
+ import { proModeStoreFor } from './pro-mode-store.ts'
10
+ import { readCodexSubagentModels } from '../tools/codex-subagent.ts'
11
+ import { checkForHarnessUpdate } from '../update/checker.ts'
12
+ import type { HarnessUpdateResult } from '../contracts/update.ts'
9
13
 
10
14
  export type { PresetDefinitionDocument } from '../contracts/ui-contracts.ts'
11
15
 
@@ -76,10 +80,34 @@ export class CodexPresetEditor extends TypertRemoteService {
76
80
  composition: doc.content,
77
81
  }
78
82
  }
83
+
84
+ async proModeGet(sessionId: string): Promise<{ enabled: boolean }> {
85
+ if (typeof sessionId !== 'string' || !sessionId.trim() || sessionId.length > 256) {
86
+ throw new Error('invalid-session-id')
87
+ }
88
+ const store = proModeStoreFor(this.toolContext ?? this)
89
+ return { enabled: store.get(sessionId) }
90
+ }
91
+
92
+ async proModeSet(input: { sessionId: string; enabled: boolean }): Promise<{ enabled: boolean }> {
93
+ if (typeof input !== 'object' || input === null || typeof input.enabled !== 'boolean') {
94
+ throw new Error('invalid-pro-mode-input')
95
+ }
96
+ const store = proModeStoreFor(this.toolContext ?? this)
97
+ return { enabled: store.set(input.sessionId, input.enabled) }
98
+ }
99
+
100
+ async updateCheck(): Promise<HarnessUpdateResult> {
101
+ return checkForHarnessUpdate()
102
+ }
103
+
104
+ async codexSubagentModels(): Promise<CodexSubagentModelCatalog> {
105
+ return readCodexSubagentModels(this.toolContext)
106
+ }
79
107
  }
80
108
 
81
109
  // Same decorator registration as the host, consumable by the Vitest transform.
82
- function markRemoteMethod(methodName: 'catalog' | 'tools' | 'prompts' | 'read'): void {
110
+ function markRemoteMethod(methodName: 'catalog' | 'tools' | 'prompts' | 'read' | 'proModeGet' | 'proModeSet' | 'updateCheck' | 'codexSubagentModels'): void {
83
111
  const descriptor = Object.getOwnPropertyDescriptor(CodexPresetEditor.prototype, methodName)!
84
112
  const initializers: Array<(this: object) => void> = []
85
113
  const decorator = Remote(methodName) as unknown as (method: unknown, context: {
@@ -96,6 +124,6 @@ function markRemoteMethod(methodName: 'catalog' | 'tools' | 'prompts' | 'read'):
96
124
  for (const initializer of initializers) initializer.call(receiver)
97
125
  }
98
126
 
99
- for (const method of ['catalog', 'tools', 'prompts', 'read'] as const) markRemoteMethod(method)
127
+ for (const method of ['catalog', 'tools', 'prompts', 'read', 'proModeGet', 'proModeSet', 'updateCheck', 'codexSubagentModels'] as const) markRemoteMethod(method)
100
128
 
101
129
  export default CodexPresetEditor
@@ -0,0 +1,80 @@
1
+ /** Ephemeral in-memory per-session OpenAI API Pro mode flags (never persisted). */
2
+
3
+ import type { Context } from '@deepseek-ai/cordis'
4
+
5
+ const MAX_SESSION_ENTRIES = 256
6
+ const MAX_SESSION_ID_LENGTH = 256
7
+
8
+ export interface SessionProModeStore {
9
+ get(sessionId: string | undefined): boolean
10
+ set(sessionId: string, enabled: boolean): boolean
11
+ delete(sessionId: string): void
12
+ clear(): void
13
+ readonly size: number
14
+ }
15
+
16
+ function normalizeSessionId(sessionId: unknown): string | undefined {
17
+ if (typeof sessionId !== 'string') return undefined
18
+ const trimmed = sessionId.trim()
19
+ if (trimmed.length === 0 || trimmed.length > MAX_SESSION_ID_LENGTH) return undefined
20
+ return trimmed
21
+ }
22
+
23
+ export function createSessionProModeStore(maxEntries = MAX_SESSION_ENTRIES): SessionProModeStore {
24
+ const enabledSessions = new Map<string, true>()
25
+
26
+ return {
27
+ get(sessionId: string | undefined): boolean {
28
+ const key = normalizeSessionId(sessionId)
29
+ if (key === undefined) return false
30
+ if (!enabledSessions.has(key)) return false
31
+ // Refresh LRU position on active lookup.
32
+ enabledSessions.delete(key)
33
+ enabledSessions.set(key, true)
34
+ return true
35
+ },
36
+
37
+ set(sessionId: string, enabled: boolean): boolean {
38
+ const key = normalizeSessionId(sessionId)
39
+ if (key === undefined) throw new Error('invalid-session-id')
40
+ if (!enabled) {
41
+ enabledSessions.delete(key)
42
+ return false
43
+ }
44
+ if (enabledSessions.has(key)) enabledSessions.delete(key)
45
+ while (enabledSessions.size >= maxEntries) {
46
+ const oldest = enabledSessions.keys().next().value
47
+ if (oldest === undefined) break
48
+ enabledSessions.delete(oldest)
49
+ }
50
+ enabledSessions.set(key, true)
51
+ return true
52
+ },
53
+
54
+ delete(sessionId: string): void {
55
+ const key = normalizeSessionId(sessionId)
56
+ if (key !== undefined) enabledSessions.delete(key)
57
+ },
58
+
59
+ clear(): void {
60
+ enabledSessions.clear()
61
+ },
62
+
63
+ get size(): number {
64
+ return enabledSessions.size
65
+ },
66
+ }
67
+ }
68
+
69
+ const storesByRoot = new WeakMap<object, SessionProModeStore>()
70
+
71
+ /** Resolve the ephemeral Pro-mode store bound to this Cordis root context. */
72
+ export function proModeStoreFor(ctx: Context | object): SessionProModeStore {
73
+ const root = (ctx as { root?: object }).root ?? ctx
74
+ let store = storesByRoot.get(root)
75
+ if (store === undefined) {
76
+ store = createSessionProModeStore()
77
+ storesByRoot.set(root, store)
78
+ }
79
+ return store
80
+ }