@shuind/dsh-codex-harness 0.3.2 → 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 (82) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +21 -41
  3. package/docs/preset-library.md +2 -2
  4. package/docs/tool-policy.md +1 -1
  5. package/lib/client.js +1826 -545
  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 +1229 -17
  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 +184 -127
  15. package/lib/types/client/index.d.ts +104 -39
  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 +81 -32
  20. package/lib/types/client/policy-locale.js +197 -107
  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 +6 -15
  26. package/lib/types/client/tool-policy.js +24 -39
  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 +48 -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/fetch-transport.js +24 -9
  49. package/lib/types/responses/wire-rewrite.d.ts +4 -0
  50. package/lib/types/responses/wire-rewrite.js +30 -4
  51. package/lib/types/tools/codex-subagent.d.ts +14 -0
  52. package/lib/types/tools/codex-subagent.js +269 -0
  53. package/lib/types/update/checker.d.ts +14 -0
  54. package/lib/types/update/checker.js +166 -0
  55. package/locale/en.json +1 -1
  56. package/locale/hybrid-executor/en.json +1 -1
  57. package/locale/hybrid-executor/zh.json +1 -1
  58. package/locale/zh.json +1 -1
  59. package/package.json +6 -2
  60. package/src/client/desktop.tsx +359 -160
  61. package/src/client/index.tsx +122 -22
  62. package/src/client/policy-drafts.ts +45 -0
  63. package/src/client/policy-locale.ts +198 -106
  64. package/src/client/preset-manager.tsx +125 -4
  65. package/src/client/preset-requests.ts +185 -1
  66. package/src/client/tool-policy.tsx +29 -63
  67. package/src/contracts/preset-editor-schema.ts +44 -0
  68. package/src/contracts/settings.ts +20 -1
  69. package/src/contracts/ui-contracts.ts +87 -0
  70. package/src/contracts/update.ts +307 -0
  71. package/src/entries/index.ts +25 -2
  72. package/src/entries/preferences.ts +9 -0
  73. package/src/hybrid/hybrid-sdk.ts +28 -12
  74. package/src/presets/preset-editor.ts +31 -3
  75. package/src/presets/pro-mode-store.ts +80 -0
  76. package/src/responses/background-sse-codec.ts +237 -0
  77. package/src/responses/background-stream.ts +371 -0
  78. package/src/responses/fetch-transport.ts +28 -9
  79. package/src/responses/wire-rewrite.ts +34 -3
  80. package/src/tools/codex-subagent.ts +290 -0
  81. package/src/update/checker.ts +193 -0
  82. package/tsdown.config.ts +4 -0
@@ -1,7 +1,7 @@
1
1
  /** Pure Responses wire transformations for hosted search, custom `apply_patch`, and compaction items. */
2
2
 
3
3
  import type { GenerateOptions } from '@deepseek-ai/dsh-llm'
4
- import { isGptModel } from '../contracts/settings.ts'
4
+ import { isGptModel, supportsApiProMode } from '../contracts/settings.ts'
5
5
  import { APPLY_PATCH_DESCRIPTION, APPLY_PATCH_GRAMMAR } from '../tools/patch.ts'
6
6
  import {
7
7
  REMOTE_COMPACTION_OPEN,
@@ -17,6 +17,10 @@ export type { JsonObject }
17
17
  export interface CodexRequestWireOptions {
18
18
  /** Provider-facing request option preserved by older DSH LLM adapters. */
19
19
  serviceTier?: string
20
+ /** Optional Responses reasoning mode override (e.g. 'pro' for GPT-5.6/6+). */
21
+ reasoningMode?: 'standard' | 'pro'
22
+ /** Enable background+stream resilient execution on the official OpenAI Responses API. */
23
+ backgroundStream?: boolean
20
24
  /** Whether local web_search should become the hosted Responses tool. */
21
25
  hostedWebSearch?: boolean
22
26
  /** Whether apply_patch should use the Responses custom grammar tool. */
@@ -255,7 +259,34 @@ export function hasRemoteCompaction(
255
259
  return body.input.some(item => trustedMarkerInInputItem(item, trustedCheckpoints) !== undefined)
256
260
  }
257
261
 
262
+ function withEncryptedReasoningInclude(include: unknown): unknown[] {
263
+ if (!Array.isArray(include)) return ['reasoning.encrypted_content']
264
+ return include.includes('reasoning.encrypted_content')
265
+ ? include
266
+ : [...include, 'reasoning.encrypted_content']
267
+ }
268
+
258
269
  export function applyRequestWireOptions(body: JsonObject, options: CodexRequestWireOptions): JsonObject {
259
- if (options.serviceTier === undefined || !isGptModel(body.model) || body.service_tier !== undefined) return body
260
- return { ...body, service_tier: options.serviceTier }
270
+ let next = body
271
+ if (options.serviceTier !== undefined && isGptModel(next.model) && next.service_tier === undefined) {
272
+ next = { ...next, service_tier: options.serviceTier }
273
+ }
274
+ if (options.reasoningMode === 'pro' && supportsApiProMode(next.model)) {
275
+ const existing = typeof next.reasoning === 'object' && next.reasoning !== null && !Array.isArray(next.reasoning)
276
+ ? next.reasoning as JsonObject
277
+ : undefined
278
+ if (existing?.mode === undefined) {
279
+ const reasoning: JsonObject = {
280
+ ...existing,
281
+ mode: 'pro',
282
+ ...(existing?.summary === undefined ? { summary: 'auto' } : {}),
283
+ }
284
+ next = {
285
+ ...next,
286
+ reasoning,
287
+ include: withEncryptedReasoningInclude(next.include),
288
+ }
289
+ }
290
+ }
291
+ return next
261
292
  }
@@ -0,0 +1,290 @@
1
+ /** Opt-in global `codex_subagent` tool backed by Codex Connect (`openai-codex`) + DSH `spawn`. */
2
+
3
+ import type { Context } from '@deepseek-ai/cordis'
4
+ import { ReasoningEffortId } from '@deepseek-ai/dsh-llm'
5
+ import type {} from '@deepseek-ai/dsh-llm'
6
+ import type { SubagentProvider } from '@deepseek-ai/dsh-subagent'
7
+ import type {} from '@deepseek-ai/dsh-system-prompt'
8
+ import { defineTool } from '@deepseek-ai/dsh-tools'
9
+ import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
10
+ import { CODEX_SETTINGS_NAMESPACE } from '../contracts/settings.ts'
11
+ import type { CodexSettings } from '../contracts/settings.ts'
12
+ import {
13
+ CODEX_SUBAGENT_DEFAULT_PRESET,
14
+ CODEX_SUBAGENT_PRESET_INHERIT,
15
+ CODEX_SUBAGENT_TOOL_NAME,
16
+ OPENAI_CODEX_PROVIDER,
17
+ } from '../contracts/ui-contracts.ts'
18
+ import type { CodexSubagentModelCatalog, CodexSubagentModelOption } from '../contracts/ui-contracts.ts'
19
+
20
+ export {
21
+ CODEX_SUBAGENT_DEFAULT_PRESET,
22
+ CODEX_SUBAGENT_PRESET_INHERIT,
23
+ CODEX_SUBAGENT_TOOL_NAME,
24
+ }
25
+
26
+ const SPAWN_PROVIDER = 'spawn'
27
+
28
+ function delegationDepthOf(agent: { options?: { subagentDepth?: number }; session?: { header?: { delegationDepth?: number } } }): number {
29
+ const runtime = agent.options?.subagentDepth ?? 0
30
+ const persisted = agent.session?.header?.delegationDepth ?? 0
31
+ return Math.max(persisted, runtime)
32
+ }
33
+
34
+ interface AgentPresetsResolver {
35
+ resolve?(id: string): Promise<{ readonly id: string; readonly broken?: string }>
36
+ }
37
+
38
+ interface SubscribablePreferences {
39
+ subscribe?(listener: () => void): () => void
40
+ }
41
+
42
+ function hasOpenAICodexProvider(ctx: Context): boolean {
43
+ const llm = ctx.get('llm')
44
+ if (llm === undefined || typeof llm.listProviders !== 'function') return false
45
+ try {
46
+ return llm.listProviders().some(provider => provider.id === OPENAI_CODEX_PROVIDER)
47
+ } catch {
48
+ return false
49
+ }
50
+ }
51
+
52
+ /** Query live `openai-codex` models and advertised reasoning efforts from the Host LLM registry. */
53
+ export async function readCodexSubagentModels(ctx: Context): Promise<CodexSubagentModelCatalog> {
54
+ const llm = ctx.get('llm')
55
+ if (llm === undefined || !hasOpenAICodexProvider(ctx) || typeof llm.listModels !== 'function') {
56
+ return { available: false, models: [] }
57
+ }
58
+ try {
59
+ const listed = await llm.listModels(OPENAI_CODEX_PROVIDER)
60
+ const models: CodexSubagentModelOption[] = await Promise.all(listed.map(async model => {
61
+ let efforts: string[] = []
62
+ let defaultEffort: string | undefined
63
+ if (typeof llm.resolveModelInfo === 'function') {
64
+ try {
65
+ const resolved = await llm.resolveModelInfo(OPENAI_CODEX_PROVIDER, model.id)
66
+ efforts = (resolved.reasoning?.efforts ?? []).map(effort => effort.id)
67
+ defaultEffort = resolved.reasoning?.defaultEffort
68
+ } catch {}
69
+ }
70
+ return {
71
+ id: model.id,
72
+ name: model.name || model.id,
73
+ efforts,
74
+ ...(defaultEffort !== undefined ? { defaultEffort } : {}),
75
+ }
76
+ }))
77
+ return { available: true, models }
78
+ } catch {
79
+ return { available: true, models: [] }
80
+ }
81
+ }
82
+
83
+ async function resolveChildPreset(
84
+ ctx: Context,
85
+ spawnProvider: SubagentProvider,
86
+ configured: string | undefined,
87
+ ): Promise<string | undefined> {
88
+ const trimmed = configured?.trim()
89
+ if (trimmed === CODEX_SUBAGENT_PRESET_INHERIT) return undefined
90
+ const target = trimmed && trimmed.length > 0 ? trimmed : CODEX_SUBAGENT_DEFAULT_PRESET
91
+ if (!spawnProvider.capabilities.agentPreset || spawnProvider.inheritsParentContext) return undefined
92
+ const presets = ctx.get('agentPresets') as AgentPresetsResolver | undefined
93
+ if (presets === undefined || typeof presets.resolve !== 'function') return undefined
94
+ try {
95
+ const resolved = await presets.resolve(target)
96
+ return resolved.broken === undefined ? resolved.id : undefined
97
+ } catch {
98
+ return undefined
99
+ }
100
+ }
101
+
102
+ function buildCodexSubagentTool(
103
+ ctx: Context,
104
+ currentSettings: () => CodexSettings,
105
+ ): ToolDefinition {
106
+ return defineTool({
107
+ name: CODEX_SUBAGENT_TOOL_NAME,
108
+ 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.',
109
+ parameters: {
110
+ cwd: {
111
+ type: 'string',
112
+ description: 'Initial child working directory. Relative paths use your current directory; omitted inherits it.',
113
+ },
114
+ description: {
115
+ type: 'string',
116
+ required: true,
117
+ description: 'A short (3-5 word) description of the delegated task, for display. Use the language of the user\'s current request.',
118
+ },
119
+ name: {
120
+ type: 'string',
121
+ 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.',
122
+ },
123
+ prompt: {
124
+ type: 'string',
125
+ required: true,
126
+ description: 'The complete, self-contained task for the subagent. It does not share this conversation\'s context, so include everything it needs.',
127
+ },
128
+ },
129
+ output: {
130
+ schema: {
131
+ type: 'object',
132
+ additionalProperties: false,
133
+ properties: {
134
+ kind: { type: 'string', required: true, const: 'activation' },
135
+ name: { type: 'string', required: true },
136
+ },
137
+ },
138
+ render: (_args, value) => [{
139
+ type: 'text',
140
+ text: `started subagent ${value.name}`,
141
+ }],
142
+ presentationMeta: (_args, value) => ({
143
+ kind: value.kind,
144
+ name: value.name,
145
+ }),
146
+ },
147
+ isConcurrencySafe: () => true,
148
+ async execute(args, exec) {
149
+ const parent = exec.agent
150
+ if (parent === undefined) {
151
+ throw new Error('codex_subagent requires a calling agent (exec.agent was undefined)')
152
+ }
153
+ const subagents = ctx.get('subagents')
154
+ const spawnProvider = subagents?.getProvider(SPAWN_PROVIDER)
155
+ if (subagents === undefined || spawnProvider === undefined) {
156
+ throw new Error('codex_subagent requires the native `spawn` subagent provider')
157
+ }
158
+ const llm = ctx.get('llm')
159
+ if (llm === undefined || !hasOpenAICodexProvider(ctx)) {
160
+ throw new Error('codex_subagent requires Codex Connect (openai-codex) to be enabled')
161
+ }
162
+ const settings = currentSettings()
163
+ let model = settings.codexSubagentModel?.trim() || ''
164
+ if (model.length === 0) {
165
+ const available = await llm.listModels(OPENAI_CODEX_PROVIDER)
166
+ exec.signal.throwIfAborted()
167
+ model = available[0]?.id ?? ''
168
+ if (model.length === 0) {
169
+ throw new Error('codex_subagent has no enabled openai-codex models available')
170
+ }
171
+ }
172
+ const effortText = settings.codexSubagentEffort?.trim() || ''
173
+ const reasoningEffort = effortText.length > 0 ? ReasoningEffortId(effortText) : undefined
174
+ await llm.resolveCallConfig({
175
+ provider: OPENAI_CODEX_PROVIDER,
176
+ model,
177
+ ...(reasoningEffort === undefined ? {} : { reasoningEffort }),
178
+ }, exec.signal)
179
+ exec.signal.throwIfAborted()
180
+ if (subagents.getProvider(SPAWN_PROVIDER) !== spawnProvider) {
181
+ throw new Error('subagent provider "spawn" changed while resolving codex_subagent; retry the delegation')
182
+ }
183
+ const agentPreset = await resolveChildPreset(ctx, spawnProvider, settings.codexSubagentPreset)
184
+ exec.signal.throwIfAborted()
185
+ const maxDepth = subagents.resolveMaxDepth(undefined)
186
+ const activation = await subagents.startActivation({
187
+ provider: SPAWN_PROVIDER,
188
+ label: args.description,
189
+ ...(args.name === undefined ? {} : { name: args.name }),
190
+ ...(args.cwd === undefined ? {} : { cwd: args.cwd }),
191
+ prompt: [{ type: 'text', text: args.prompt }],
192
+ parent,
193
+ ...(agentPreset === undefined ? {} : { agentPreset }),
194
+ agentOptions: {
195
+ provider: OPENAI_CODEX_PROVIDER,
196
+ model,
197
+ ...(reasoningEffort === undefined ? {} : { reasoningEffort }),
198
+ },
199
+ ...(maxDepth === undefined ? {} : { maxDepth }),
200
+ signal: exec.signal,
201
+ delivery: 'parent',
202
+ })
203
+ return { kind: 'activation' as const, name: activation.name }
204
+ },
205
+ })
206
+ }
207
+
208
+ /**
209
+ * Mount a reactive global registration controller for `codex_subagent`.
210
+ * Registers immediately when enabled + `spawn` + `openai-codex` are ready, and unregisters on disable.
211
+ */
212
+ export function installCodexSubagent(ctx: Context, currentSettings: () => CodexSettings): void {
213
+ if (typeof (ctx as unknown as { inject?: unknown }).inject !== 'function') return
214
+ ctx.inject(['subagents', 'tools'], subagentCtx => {
215
+ let mounted: { definition: ToolDefinition; dispose: () => void } | undefined
216
+ let stopped = false
217
+
218
+ const unmount = (): void => {
219
+ if (mounted === undefined) return
220
+ const current = mounted
221
+ mounted = undefined
222
+ try { current.dispose() } catch {}
223
+ }
224
+
225
+ const reconcile = (): void => {
226
+ if (stopped) return
227
+ const settings = currentSettings()
228
+ const ready = settings.codexSubagentEnabled === true
229
+ && subagentCtx.subagents.getProvider(SPAWN_PROVIDER) !== undefined
230
+ && hasOpenAICodexProvider(subagentCtx)
231
+ if (!ready) {
232
+ unmount()
233
+ return
234
+ }
235
+ if (mounted !== undefined) return
236
+ try {
237
+ const definition = buildCodexSubagentTool(subagentCtx, currentSettings)
238
+ const dispose = subagentCtx.tools.register(definition)
239
+ mounted = { definition, dispose }
240
+ } catch (error) {
241
+ subagentCtx.logger.warn(`codex: could not register global ${CODEX_SUBAGENT_TOOL_NAME} tool`)
242
+ subagentCtx.logger.warn(error)
243
+ }
244
+ }
245
+
246
+ subagentCtx.on('subagent/provider-added', provider => {
247
+ if (provider.name === SPAWN_PROVIDER) reconcile()
248
+ })
249
+ subagentCtx.on('subagent/provider-removed', providerName => {
250
+ if (providerName === SPAWN_PROVIDER) reconcile()
251
+ })
252
+ ;(subagentCtx as unknown as { on?: (event: string, listener: (...args: any[]) => void) => void }).on?.('llm/adapters-updated', () => {
253
+ reconcile()
254
+ })
255
+ subagentCtx.on('settings/document-updated', ns => {
256
+ if (ns === CODEX_SETTINGS_NAMESPACE) reconcile()
257
+ })
258
+ subagentCtx.inject(['codexPreferences'], prefCtx => {
259
+ const preferences = prefCtx.get('codexPreferences') as SubscribablePreferences | undefined
260
+ if (typeof preferences?.subscribe !== 'function') return
261
+ const unsubscribe = preferences.subscribe(() => reconcile())
262
+ prefCtx.effect(() => unsubscribe, 'codex: codex_subagent preferences listener')
263
+ reconcile()
264
+ })
265
+
266
+ const systemPrompt = subagentCtx.get('systemPrompt')
267
+ if (systemPrompt !== undefined) {
268
+ systemPrompt.context({
269
+ name: `tool:${CODEX_SUBAGENT_TOOL_NAME}:depth`,
270
+ order: systemPrompt.getContextOrder('SUBAGENT_DELEGATION'),
271
+ text: context => {
272
+ if (context.agent === undefined || mounted === undefined) return ''
273
+ if (subagentCtx.tools.get(CODEX_SUBAGENT_TOOL_NAME, context.scope) !== mounted.definition) return ''
274
+ const maxDepth = subagentCtx.subagents.resolveMaxDepth(undefined)
275
+ if (maxDepth === undefined) return ''
276
+ const depth = delegationDepthOf(context.agent)
277
+ if (depth < maxDepth) return ''
278
+ 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.`
279
+ },
280
+ })
281
+ }
282
+
283
+ subagentCtx.effect(() => () => {
284
+ stopped = true
285
+ unmount()
286
+ }, 'codex: global codex_subagent lifecycle')
287
+
288
+ reconcile()
289
+ })
290
+ }
@@ -0,0 +1,193 @@
1
+ /** Host-side update checker: npm dist-tags first, GitHub Releases fallback. */
2
+
3
+ import { readFile } from 'node:fs/promises'
4
+ import { dirname, join } from 'node:path'
5
+ import { fileURLToPath } from 'node:url'
6
+ import {
7
+ CODEX_HARNESS_GITHUB_LATEST_RELEASE_URL,
8
+ CODEX_HARNESS_NPM_METADATA_URL,
9
+ CODEX_HARNESS_PACKAGE_NAME,
10
+ compareHarnessVersions,
11
+ harnessReleaseUrl,
12
+ normalizeHarnessVersion,
13
+ parseHarnessVersion,
14
+ } from '../contracts/update.ts'
15
+ import type { HarnessUpdateResult } from '../contracts/update.ts'
16
+
17
+ export const CODEX_HARNESS_UPDATE_TIMEOUT_MS = 8_000
18
+ export const CODEX_HARNESS_UPDATE_MAX_BYTES = 64 * 1024
19
+
20
+ const MODULE_DIR = dirname(fileURLToPath(import.meta.url))
21
+ const MAX_ROOT_WALK_DEPTH = 6
22
+
23
+ type FetchImpl = (input: string, init?: RequestInit) => Promise<Response>
24
+
25
+ export interface HarnessUpdateCheckOptions {
26
+ currentVersion?: string
27
+ fetchImpl?: FetchImpl
28
+ timeoutMs?: number
29
+ }
30
+
31
+ type SourceLookup =
32
+ | { ok: true; latestVersion: string }
33
+ | { ok: false; reason: 'registry-unavailable' | 'invalid-registry-response' }
34
+
35
+ let cachedPackageVersion: string | undefined
36
+
37
+ export async function readCurrentHarnessVersion(startDir = MODULE_DIR): Promise<string | undefined> {
38
+ if (startDir === MODULE_DIR && cachedPackageVersion !== undefined) return cachedPackageVersion
39
+ let current = startDir
40
+ for (let depth = 0; depth <= MAX_ROOT_WALK_DEPTH; depth += 1) {
41
+ try {
42
+ const raw = await readFile(join(current, 'package.json'), 'utf8')
43
+ const parsed: unknown = JSON.parse(raw)
44
+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
45
+ const record = parsed as Record<string, unknown>
46
+ if (record['name'] === CODEX_HARNESS_PACKAGE_NAME && typeof record['version'] === 'string' && parseHarnessVersion(record['version']) !== undefined) {
47
+ const normalized = normalizeHarnessVersion(record['version'])
48
+ if (startDir === MODULE_DIR) cachedPackageVersion = normalized
49
+ return normalized
50
+ }
51
+ }
52
+ } catch {
53
+ // Keep walking upward.
54
+ }
55
+ const parent = dirname(current)
56
+ if (parent === current) break
57
+ current = parent
58
+ }
59
+ return undefined
60
+ }
61
+
62
+ async function readBoundedText(response: Response, maxBytes: number): Promise<string> {
63
+ if (response.body === null) {
64
+ const text = await response.text()
65
+ if (new TextEncoder().encode(text).byteLength > maxBytes) throw new RangeError('update response too large')
66
+ return text
67
+ }
68
+ const reader = response.body.getReader()
69
+ const decoder = new TextDecoder()
70
+ const chunks: string[] = []
71
+ let total = 0
72
+ try {
73
+ while (true) {
74
+ const next = await reader.read()
75
+ if (next.done) break
76
+ total += next.value.byteLength
77
+ if (total > maxBytes) {
78
+ await reader.cancel()
79
+ throw new RangeError('update response too large')
80
+ }
81
+ chunks.push(decoder.decode(next.value, { stream: true }))
82
+ }
83
+ chunks.push(decoder.decode())
84
+ return chunks.join('')
85
+ } finally {
86
+ reader.releaseLock()
87
+ }
88
+ }
89
+
90
+ async function fetchBounded(
91
+ fetchImpl: FetchImpl,
92
+ url: string,
93
+ timeoutMs: number,
94
+ headers: Record<string, string>,
95
+ ): Promise<{ response: Response; text: string }> {
96
+ const controller = new AbortController()
97
+ const timer = setTimeout(() => { controller.abort(new Error('update request timed out')) }, timeoutMs)
98
+ try {
99
+ const response = await fetchImpl(url, { headers, signal: controller.signal })
100
+ const text = await readBoundedText(response, CODEX_HARNESS_UPDATE_MAX_BYTES)
101
+ return { response, text }
102
+ } finally {
103
+ clearTimeout(timer)
104
+ }
105
+ }
106
+
107
+ function registryCandidates(value: unknown): string[] {
108
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return []
109
+ const record = value as Record<string, unknown>
110
+ const tags = record['dist-tags'] ?? record
111
+ if (typeof tags !== 'object' || tags === null || Array.isArray(tags)) return []
112
+ return ['latest', 'alpha']
113
+ .map(tag => (tags as Record<string, unknown>)[tag])
114
+ .filter((candidate): candidate is string => typeof candidate === 'string' && parseHarnessVersion(candidate) !== undefined)
115
+ .map(normalizeHarnessVersion)
116
+ }
117
+
118
+ async function lookupNpmLatest(fetchImpl: FetchImpl, timeoutMs: number): Promise<SourceLookup> {
119
+ try {
120
+ const { response, text } = await fetchBounded(fetchImpl, CODEX_HARNESS_NPM_METADATA_URL, timeoutMs, { accept: 'application/json' })
121
+ if (!response.ok) return { ok: false, reason: 'registry-unavailable' }
122
+ const candidates = registryCandidates(JSON.parse(text) as unknown)
123
+ if (candidates.length === 0) return { ok: false, reason: 'invalid-registry-response' }
124
+ const latestVersion = candidates.reduce((best, item) => compareHarnessVersions(item, best) > 0 ? item : best)
125
+ return { ok: true, latestVersion }
126
+ } catch (error: unknown) {
127
+ return {
128
+ ok: false,
129
+ reason: error instanceof SyntaxError || error instanceof RangeError ? 'invalid-registry-response' : 'registry-unavailable',
130
+ }
131
+ }
132
+ }
133
+
134
+ async function lookupGitHubLatest(fetchImpl: FetchImpl, timeoutMs: number): Promise<SourceLookup> {
135
+ try {
136
+ const { response, text } = await fetchBounded(
137
+ fetchImpl,
138
+ CODEX_HARNESS_GITHUB_LATEST_RELEASE_URL,
139
+ timeoutMs,
140
+ { accept: 'application/vnd.github+json' },
141
+ )
142
+ if (!response.ok) return { ok: false, reason: 'registry-unavailable' }
143
+ const value = JSON.parse(text) as unknown
144
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
145
+ return { ok: false, reason: 'invalid-registry-response' }
146
+ }
147
+ const tag = (value as Record<string, unknown>)['tag_name']
148
+ if (typeof tag !== 'string' || parseHarnessVersion(tag) === undefined) {
149
+ return { ok: false, reason: 'invalid-registry-response' }
150
+ }
151
+ return { ok: true, latestVersion: normalizeHarnessVersion(tag) }
152
+ } catch (error: unknown) {
153
+ return {
154
+ ok: false,
155
+ reason: error instanceof SyntaxError || error instanceof RangeError ? 'invalid-registry-response' : 'registry-unavailable',
156
+ }
157
+ }
158
+ }
159
+
160
+ export async function checkForHarnessUpdate(options: HarnessUpdateCheckOptions = {}): Promise<HarnessUpdateResult> {
161
+ const rawCurrent = options.currentVersion ?? await readCurrentHarnessVersion()
162
+ if (rawCurrent === undefined || parseHarnessVersion(rawCurrent) === undefined) {
163
+ return { status: 'unavailable', currentVersion: rawCurrent ?? '0.0.0', reason: 'invalid-current-version' }
164
+ }
165
+ const currentVersion = normalizeHarnessVersion(rawCurrent)
166
+ const fetchImpl = options.fetchImpl ?? fetch
167
+ const timeoutMs = options.timeoutMs ?? CODEX_HARNESS_UPDATE_TIMEOUT_MS
168
+
169
+ const npmResult = await lookupNpmLatest(fetchImpl, timeoutMs)
170
+ let latestVersion: string
171
+ if (npmResult.ok) {
172
+ latestVersion = npmResult.latestVersion
173
+ } else {
174
+ const githubResult = await lookupGitHubLatest(fetchImpl, timeoutMs)
175
+ if (!githubResult.ok) {
176
+ const reason = githubResult.reason === 'invalid-registry-response' || npmResult.reason === 'invalid-registry-response'
177
+ ? 'invalid-registry-response'
178
+ : 'registry-unavailable'
179
+ return { status: 'unavailable', currentVersion, reason }
180
+ }
181
+ latestVersion = githubResult.latestVersion
182
+ }
183
+
184
+ if (compareHarnessVersions(latestVersion, currentVersion) <= 0) {
185
+ return { status: 'up-to-date', currentVersion, latestVersion: currentVersion }
186
+ }
187
+ return {
188
+ status: 'update-available',
189
+ currentVersion,
190
+ latestVersion,
191
+ releaseUrl: harnessReleaseUrl(latestVersion),
192
+ }
193
+ }
package/tsdown.config.ts CHANGED
@@ -1,5 +1,8 @@
1
+ import { readFileSync } from 'node:fs'
1
2
  import { defineConfig } from 'tsdown'
2
3
 
4
+ const PACKAGE_VERSION = (JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')) as { version: string }).version
5
+
3
6
  // DSH's browser module table owns these identities. Bundling either one would
4
7
  // give slot components a second React runtime and make their Hooks invalid in
5
8
  // the host renderer.
@@ -94,6 +97,7 @@ export default defineConfig([
94
97
  'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV ?? 'production'),
95
98
  'import.meta.env.MODE': JSON.stringify(process.env.NODE_ENV ?? 'production'),
96
99
  'import.meta.env': JSON.stringify({ MODE: process.env.NODE_ENV ?? 'production' }),
100
+ __CODEX_HARNESS_VERSION__: JSON.stringify(PACKAGE_VERSION),
97
101
  },
98
102
  deps: {
99
103
  neverBundle: (specifier: string) => CLIENT_EXTERNALS.has(specifier),