@shuind/dsh-codex-harness 0.2.21 → 0.2.32-dsh-v0.2.2-rc.1

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 (128) hide show
  1. package/CHANGELOG.md +121 -0
  2. package/README.md +48 -38
  3. package/RELEASE.md +61 -0
  4. package/assets/codex.svg +5 -0
  5. package/cordis.patch.yml +150 -6
  6. package/docs/preset-library.md +39 -23
  7. package/docs/tool-policy-benchmark.json +310 -0
  8. package/docs/tool-policy.md +144 -0
  9. package/lib/client.js +1639 -111
  10. package/lib/compaction.js +17 -2
  11. package/lib/index.js +799 -188
  12. package/lib/installer.js +50 -6
  13. package/lib/preferences.js +111 -0
  14. package/lib/tool-policy.js +2235 -0
  15. package/lib/typert.js +57 -10
  16. package/lib/types/activity.d.ts +1 -1
  17. package/lib/types/activity.js +50 -14
  18. package/lib/types/client/activity.d.ts +33 -9
  19. package/lib/types/client/desktop.d.ts +43 -0
  20. package/lib/types/client/desktop.js +121 -0
  21. package/lib/types/client/entry.d.ts +10 -0
  22. package/lib/types/client/entry.js +12 -0
  23. package/lib/types/client/index.d.ts +109 -19
  24. package/lib/types/client/index.js +21 -40
  25. package/lib/types/client/policy-drafts.d.ts +25 -0
  26. package/lib/types/client/policy-drafts.js +47 -0
  27. package/lib/types/client/preset-copy.d.ts +1 -0
  28. package/lib/types/client/preset-copy.js +2 -0
  29. package/lib/types/client/preset-manager.d.ts +12 -2
  30. package/lib/types/client/preset-manager.js +70 -25
  31. package/lib/types/client/preset-requests.d.ts +12 -0
  32. package/lib/types/client/preset-requests.js +101 -0
  33. package/lib/types/client/session.d.ts +6 -0
  34. package/lib/types/client/session.js +9 -0
  35. package/lib/types/client/tool-policy.d.ts +120 -0
  36. package/lib/types/client/tool-policy.js +394 -0
  37. package/lib/types/compaction.d.ts +3 -3
  38. package/lib/types/compaction.js +6 -2
  39. package/lib/types/desktop-preset.d.ts +20 -0
  40. package/lib/types/desktop-preset.js +39 -0
  41. package/lib/types/exec.d.ts +4 -0
  42. package/lib/types/exec.js +192 -66
  43. package/lib/types/host-settings.d.ts +4 -0
  44. package/lib/types/host-settings.js +13 -0
  45. package/lib/types/index.d.ts +20 -2
  46. package/lib/types/index.js +181 -68
  47. package/lib/types/installer.js +11 -2
  48. package/lib/types/preferences.d.ts +11 -0
  49. package/lib/types/preferences.js +16 -0
  50. package/lib/types/preset-editor-remote.d.ts +2 -0
  51. package/lib/types/preset-editor-remote.js +6 -2
  52. package/lib/types/preset-editor.d.ts +12 -7
  53. package/lib/types/preset-editor.js +43 -13
  54. package/lib/types/preset-prompt-catalog-schema.d.ts +16 -0
  55. package/lib/types/preset-prompt-catalog-schema.js +11 -0
  56. package/lib/types/preset-prompt-catalog.d.ts +21 -0
  57. package/lib/types/preset-prompt-catalog.js +192 -0
  58. package/lib/types/preset-prompt-contract.d.ts +22 -0
  59. package/lib/types/preset-prompt-contract.js +3 -0
  60. package/lib/types/preset-tool-catalog-schema.d.ts +38 -0
  61. package/lib/types/preset-tool-catalog-schema.js +28 -0
  62. package/lib/types/preset-tool-catalog.d.ts +5 -0
  63. package/lib/types/preset-tool-catalog.js +51 -0
  64. package/lib/types/prompt-sections.d.ts +1 -1
  65. package/lib/types/prompt-sections.js +9 -3
  66. package/lib/types/prompt.js +4 -2
  67. package/lib/types/remote.js +23 -8
  68. package/lib/types/settings.d.ts +3 -3
  69. package/lib/types/settings.js +3 -3
  70. package/lib/types/tool-capabilities.d.ts +32 -0
  71. package/lib/types/tool-capabilities.js +42 -0
  72. package/lib/types/tool-policy-contract.d.ts +60 -0
  73. package/lib/types/tool-policy-contract.js +26 -0
  74. package/lib/types/tool-policy.d.ts +171 -0
  75. package/lib/types/tool-policy.js +367 -0
  76. package/lib/types/typert.host.d.ts +2 -2
  77. package/lib/types/typert.host.js +12 -2
  78. package/locale/en.json +6 -0
  79. package/locale/tool-policy/en.json +6 -0
  80. package/locale/tool-policy/zh.json +6 -0
  81. package/locale/zh.json +6 -0
  82. package/package.json +375 -299
  83. package/scripts/benchmark-tool-policy.mjs +186 -0
  84. package/scripts/build-preset.mjs +19 -0
  85. package/scripts/clean-build.mjs +11 -0
  86. package/src/activity-types.ts +7 -0
  87. package/src/activity.ts +158 -0
  88. package/src/client/activity.ts +82 -0
  89. package/src/client/desktop.tsx +162 -0
  90. package/src/client/entry.tsx +16 -0
  91. package/src/client/index.tsx +972 -0
  92. package/src/client/policy-drafts.ts +56 -0
  93. package/src/client/preset-copy.ts +83 -0
  94. package/src/client/preset-manager.tsx +281 -0
  95. package/src/client/preset-requests.ts +113 -0
  96. package/src/client/session.ts +11 -0
  97. package/src/client/tool-policy.tsx +380 -0
  98. package/src/compact-command.ts +112 -0
  99. package/src/compaction.ts +190 -0
  100. package/src/context.ts +15 -0
  101. package/src/desktop-preset.ts +55 -0
  102. package/src/exec.ts +570 -0
  103. package/src/host-settings.ts +17 -0
  104. package/src/index.ts +1097 -0
  105. package/src/installer.ts +172 -0
  106. package/src/invariant.ts +34 -0
  107. package/src/patch.ts +258 -0
  108. package/src/preferences.ts +17 -0
  109. package/src/preset-contract.ts +85 -0
  110. package/src/preset-editor-remote.ts +41 -0
  111. package/src/preset-editor.ts +502 -0
  112. package/src/preset-prompt-catalog-schema.ts +10 -0
  113. package/src/preset-prompt-catalog.ts +191 -0
  114. package/src/preset-prompt-contract.ts +21 -0
  115. package/src/preset-tool-catalog-schema.ts +28 -0
  116. package/src/preset-tool-catalog.ts +51 -0
  117. package/src/prompt-sections.ts +33 -0
  118. package/src/prompt.ts +62 -0
  119. package/src/remote.ts +748 -0
  120. package/src/settings.ts +79 -0
  121. package/src/tool-capabilities.ts +76 -0
  122. package/src/tool-policy-contract.ts +76 -0
  123. package/src/tool-policy.ts +388 -0
  124. package/src/typert.host.ts +119 -0
  125. package/tsconfig.json +29 -0
  126. package/tsdown.config.ts +110 -0
  127. package/lib/types/preset-templates.d.ts +0 -36
  128. package/lib/types/preset-templates.js +0 -12
@@ -0,0 +1,972 @@
1
+ /** Browser controls for Codex requests and the editable operating prompt. */
2
+
3
+ import { useEffect, useLayoutEffect, useRef, useState } from 'react'
4
+ import { createPortal } from 'react-dom'
5
+ import type { HostObservable, InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
6
+ import type { Context } from '@deepseek-ai/cordis'
7
+ import type {} from '@deepseek-ai/dsh-client-locale/client'
8
+ import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
9
+ import type {} from '@deepseek-ai/dsh-client-ui-settings/client'
10
+ import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
11
+ import type {} from '@deepseek-ai/dsh-client-ui-session/client'
12
+ import type {} from '@deepseek-ai/dsh-api-remotes/client'
13
+ import type { TypertClientRemote } from '@deepseek-ai/dsh-typert-protocol'
14
+ import { CODEX_CONTEXT_MAX, CODEX_CONTEXT_UNIT, isCodexPresetId } from '../context.ts'
15
+ import type { CodexActivity } from '../activity-types.ts'
16
+ import { modelActivity, sameModelActivity } from './activity.ts'
17
+ import { agentPresetFromSession } from './session.ts'
18
+ import presetEditorRemote from '../preset-editor-remote.ts'
19
+ import { PresetManagerCard } from './preset-manager.tsx'
20
+ import { presetEn, presetZh } from './preset-copy.ts'
21
+ import { toolPolicyEn, toolPolicyZh } from './tool-policy.tsx'
22
+ import type { PresetClientRemote, PresetManagerActions } from './preset-manager.tsx'
23
+
24
+ interface CompactCommandOption {
25
+ id: string
26
+ label: string
27
+ detail?: string
28
+ }
29
+
30
+ interface CompactCommandSession {
31
+ command(line: string): Promise<{
32
+ ok: true
33
+ value: { matched: boolean }
34
+ } | {
35
+ ok: false
36
+ error: { code: string; message: string }
37
+ }>
38
+ }
39
+
40
+ interface CompactCommandUi {
41
+ decorate(decoration: {
42
+ name: string
43
+ available(session: { sessionId: string }): boolean
44
+ ui: {
45
+ kind: 'popupSelect'
46
+ options(session: { sessionId: string }, signal: AbortSignal): Promise<readonly CompactCommandOption[]>
47
+ onSelect(option: CompactCommandOption, session: { sessionId: string }): void | Promise<void>
48
+ }
49
+ }): () => void
50
+ }
51
+
52
+ interface CompactCommandSessions {
53
+ binding(sessionId: string): { session: CompactCommandSession } | undefined
54
+ }
55
+
56
+ const NS = 'codex' as const
57
+ const SETTINGS_NAMESPACE = 'codex'
58
+ const FAST_FALLBACK_SLOT = 'conversation.input.right' as const
59
+ const LEGACY_OVERLAY_SLOT = 'conversation.input.overlay' as const
60
+ const PLUGIN_SETTINGS_SLOT = 'settings.plugin.item' as const
61
+ const DEFAULT_CONTEXT_WINDOW = 262_144
62
+
63
+ export interface CodexSettings {
64
+ fast: boolean
65
+ fastModeControlEnabled: boolean
66
+ contextWindow?: number
67
+ persona?: string
68
+ harnessSourcePrompt?: string
69
+ webSurfacePrompt?: string
70
+ systemPrompt?: string
71
+ promptEnabled: boolean
72
+ terminalToolsEnabled: boolean
73
+ patchToolEnabled: boolean
74
+ planToolEnabled: boolean
75
+ hostedWebSearchEnabled: boolean
76
+ remoteCompactionEnabled: boolean
77
+ activityIndicatorEnabled: boolean
78
+ }
79
+
80
+ /** Common observable face of legacy settingsScope and current ConfigForms. */
81
+ export interface CodexSettingsSnapshot {
82
+ readonly status: string
83
+ readonly value?: CodexSettings | undefined
84
+ readonly base?: Partial<CodexSettings> | undefined
85
+ readonly user?: Partial<CodexSettings> | undefined
86
+ readonly revision?: number | string | undefined
87
+ readonly writable: boolean
88
+ }
89
+
90
+ export interface CodexScope extends HostObservable<CodexSettingsSnapshot> {
91
+ set(field: string, value: unknown): Promise<void>
92
+ unset(field: string): Promise<void>
93
+ }
94
+
95
+ const en = {
96
+ ...presetEn,
97
+ ...toolPolicyEn,
98
+ fast: 'Fast mode',
99
+ fastModeControl: 'Show fast mode control',
100
+ fastOn: 'Fast mode on (priority tier)',
101
+ fastOff: 'Fast mode off',
102
+ fastStateOn: 'On',
103
+ fastStateOff: 'Off',
104
+ contextSize: 'Context size',
105
+ contextSizeDescription: 'Next request capacity in K tokens.',
106
+ contextRestore: 'Restore model default',
107
+ promptCardTitle: 'Codex Harness',
108
+ promptCardDescription: 'Edit presets, Codex capabilities, and the operating prompt. Activity status is global.',
109
+ otherCapabilitiesLabel: 'Global capabilities',
110
+ capabilityPrompt: 'Codex operating prompt',
111
+ capabilityPromptHint: 'Inject the editable instructions and persona-first prompt layout.',
112
+ compactRemote: 'Remote compaction',
113
+ compactRemoteHint: 'Use the provider remote compaction endpoint first.',
114
+ compactLocal: 'Local compaction',
115
+ compactLocalHint: 'Use the DSH text-summary compaction engine directly.',
116
+ capabilityTerminal: 'Terminal tools',
117
+ capabilityTerminalHint: 'Expose exec_command and write_stdin.',
118
+ capabilityPatch: 'Patch tool',
119
+ capabilityPatchHint: 'Expose apply_patch, using the native Responses grammar when supported.',
120
+ capabilityPlan: 'Plan tool',
121
+ capabilityPlanHint: 'Expose update_plan for implementation task tracking.',
122
+ capabilityWebSearch: 'Hosted web search',
123
+ capabilityWebSearchHint: 'Use the provider-native Responses web_search tool when available.',
124
+ capabilityCompaction: 'Remote compaction',
125
+ capabilityCompactionHint: 'Prefer the provider Responses compact endpoint before local compaction.',
126
+ capabilityActivity: 'Activity indicator',
127
+ capabilityActivityHint: 'Show request, reply, and compaction status beside the conversation.',
128
+ promptDiscard: 'Discard',
129
+ promptSaving: 'Saving...',
130
+ promptReadOnly: 'This settings document is read-only.',
131
+ activityCompacting: 'Compacting context...',
132
+ activityRequestingModel: 'Requesting model...',
133
+ activityModelReply: 'Model replying...',
134
+ } as const
135
+
136
+ const zh = {
137
+ ...presetZh,
138
+ ...toolPolicyZh,
139
+ fastModeControl: 'Show fast mode control',
140
+ fast: 'Fast',
141
+ fastOn: 'Fast mode on (priority tier)',
142
+ fastOff: 'Fast mode off',
143
+ fastStateOn: '\u5f00',
144
+ fastStateOff: '\u5173',
145
+ contextSize: '\u4e0a\u4e0b\u6587\u5927\u5c0f',
146
+ contextSizeDescription: '\u8bbe\u7f6e\u4e0b\u6b21\u8bf7\u6c42\u7684\u4e0a\u4e0b\u6587\u5bb9\u91cf\uff0c\u5355\u4f4d\u4e3a K tokens\u3002',
147
+ contextRestore: '\u6062\u590d\u6a21\u578b\u9ed8\u8ba4\u503c',
148
+ promptCardTitle: 'Codex Harness',
149
+ promptCardDescription: '\u7f16\u8f91\u9884\u8bbe\u3001Codex \u80fd\u529b\u548c\u64cd\u4f5c\u63d0\u793a\u8bcd\uff0c\u6d3b\u52a8\u72b6\u6001\u662f\u5168\u5c40\u8bbe\u7f6e\u3002',
150
+ otherCapabilitiesLabel: '\u5168\u5c40\u80fd\u529b',
151
+ capabilityPrompt: 'Codex \u64cd\u4f5c\u63d0\u793a\u8bcd',
152
+ capabilityPromptHint: '\u6ce8\u5165\u53ef\u7f16\u8f91\u6307\u4ee4\uff0c\u5e76\u5c06 Persona \u653e\u5728\u63d0\u793a\u8bcd\u9996\u4f4d\u3002',
153
+ compactRemote: '\u8fdc\u7a0b\u538b\u7f29',
154
+ compactRemoteHint: '\u4f18\u5148\u4f7f\u7528\u63d0\u4f9b\u5546\u7684\u8fdc\u7a0b\u538b\u7f29\u7aef\u70b9\u3002',
155
+ compactLocal: '\u672c\u5730\u538b\u7f29',
156
+ compactLocalHint: '\u76f4\u63a5\u4f7f\u7528 DSH \u6587\u672c\u6458\u8981\u538b\u7f29\u5f15\u64ce\u3002',
157
+ capabilityTerminal: '\u7ec8\u7aef\u5de5\u5177',
158
+ capabilityTerminalHint: '\u63d0\u4f9b exec_command \u548c write_stdin\u3002',
159
+ capabilityPatch: '\u8865\u4e01\u5de5\u5177',
160
+ capabilityPatchHint: '\u63d0\u4f9b apply_patch\uff0c\u5e76\u5728\u652f\u6301\u65f6\u4f7f\u7528 Responses \u539f\u751f\u8bed\u6cd5\u3002',
161
+ capabilityPlan: '\u8ba1\u5212\u5de5\u5177',
162
+ capabilityPlanHint: '\u63d0\u4f9b update_plan\uff0c\u7528\u4e8e\u8ddf\u8e2a\u5b9e\u65bd\u4efb\u52a1\u3002',
163
+ capabilityWebSearch: '\u6258\u7ba1\u7f51\u7edc\u641c\u7d22',
164
+ capabilityWebSearchHint: '\u53ef\u7528\u65f6\u4f7f\u7528\u63d0\u4f9b\u5546\u539f\u751f\u7684 Responses web_search \u5de5\u5177\u3002',
165
+ capabilityCompaction: '\u8fdc\u7a0b\u4e0a\u4e0b\u6587\u538b\u7f29',
166
+ capabilityCompactionHint: '\u4f18\u5148\u8c03\u7528\u63d0\u4f9b\u5546\u7684 Responses compact \u7aef\u70b9\uff0c\u5931\u8d25\u65f6\u56de\u9000\u672c\u5730\u538b\u7f29\u3002',
167
+ capabilityActivity: '\u6d3b\u52a8\u72b6\u6001',
168
+ capabilityActivityHint: '\u5728\u5bf9\u8bdd\u65c1\u663e\u793a\u8bf7\u6c42\u3001\u56de\u590d\u548c\u538b\u7f29\u72b6\u6001\u3002',
169
+ promptDiscard: '\u653e\u5f03',
170
+ promptSaving: '\u4fdd\u5b58\u4e2d...',
171
+ promptReadOnly: '\u5f53\u524d\u8bbe\u7f6e\u6587\u4ef6\u4e3a\u53ea\u8bfb\u3002',
172
+ activityCompacting: '\u6b63\u5728\u538b\u7f29\u4e0a\u4e0b\u6587...',
173
+ activityRequestingModel: '\u8bf7\u6c42\u4e2d...',
174
+ activityModelReply: '\u56de\u590d\u4e2d...',
175
+ } as const
176
+
177
+ type CodexKey = keyof typeof en
178
+
179
+ declare module '@deepseek-ai/dsh-client-ui-slots' {
180
+ interface LocaleNamespaceMap {
181
+ codex: CodexKey
182
+ }
183
+ interface SlotMap {
184
+ 'conversation.input.overlay': {
185
+ kind: 'list'
186
+ scope: 'session'
187
+ }
188
+ 'settings.plugin.item': {
189
+ kind: 'keyed'
190
+ scope: 'root'
191
+ owner: { children?: never }
192
+ }
193
+ }
194
+ }
195
+
196
+ export interface InputSettingsControlInjected {
197
+ hooks: { settings: HostObservable<ReturnType<CodexScope['getSnapshot']>> }
198
+ setSetting: (field: string, value: unknown) => Promise<void>
199
+ unsetSetting: (field: string) => Promise<void>
200
+ presetManager: PresetManagerActions
201
+ }
202
+
203
+ type BooleanCapabilitySetting = Exclude<
204
+ keyof CodexSettings,
205
+ 'fast' | 'contextWindow' | 'persona' | 'harnessSourcePrompt' | 'webSurfacePrompt' | 'systemPrompt'
206
+ >
207
+
208
+ interface CapabilityToggleProps {
209
+ field: BooleanCapabilitySetting
210
+ label: string
211
+ hint: string
212
+ enabled: boolean
213
+ disabled: boolean
214
+ setSetting: (field: string, value: unknown) => Promise<void>
215
+ }
216
+
217
+ function CapabilityToggle({
218
+ field, label, hint, enabled, disabled, setSetting,
219
+ }: CapabilityToggleProps) {
220
+ return (
221
+ <label style={{
222
+ display: 'flex',
223
+ alignItems: 'flex-start',
224
+ gap: 12,
225
+ padding: '9px 0',
226
+ cursor: disabled ? 'default' : 'pointer',
227
+ }}>
228
+ <span style={{ flex: 1, minWidth: 0, display: 'grid', gap: 2 }}>
229
+ <strong style={{ fontSize: 13, fontWeight: 500 }}>{label}</strong>
230
+ <span style={{ color: 'var(--dsw-alias-label-secondary)', fontSize: 12, lineHeight: 1.45 }}>
231
+ {hint}
232
+ </span>
233
+ </span>
234
+ <input
235
+ type="checkbox"
236
+ role="switch"
237
+ checked={enabled}
238
+ disabled={disabled}
239
+ aria-label={label}
240
+ onChange={event => { void setSetting(field, event.target.checked) }}
241
+ style={{ marginTop: 3, accentColor: 'var(--dsw-static-blue-500)' }}
242
+ />
243
+ </label>
244
+ )
245
+ }
246
+
247
+ /** One editor per preset; only display preferences are global. */
248
+ export function PromptSettingsCard(
249
+ props: PropsRuntime<'settings.plugin.item'> & InjectFace<InputSettingsControlInjected> & PropsLocale<'codex'>,
250
+ ) {
251
+ const { useSettings, setSetting, presetManager, t } = props
252
+ const snapshot = useSettings(state => state as { status: string; value?: CodexSettings; writable: boolean })
253
+ const [open, setOpen] = useState(false)
254
+ if (snapshot.status === 'unavailable') return null
255
+ return <li style={{ listStyle: 'none', border: '1px solid var(--dsw-alias-border-l2)', borderRadius: 12, overflow: 'hidden' }}>
256
+ <button type="button" aria-expanded={open} onClick={() => setOpen(!open)} style={{ width: '100%', padding: 16, textAlign: 'left', border: 0, background: 'none', color: 'inherit', cursor: 'pointer' }}>
257
+ <strong>{t('promptCardTitle')}</strong><span style={{ float: 'right' }}>{open ? '−' : '+'}</span>
258
+ <p style={{ marginBottom: 0 }}>{t('promptCardDescription')}</p>
259
+ </button>
260
+ {open && <div style={{ padding: 16, borderTop: '1px solid var(--dsw-alias-border-l2)' }}>
261
+ <PresetManagerCard presetManager={presetManager} t={t} />
262
+ <details style={{ marginTop: 22, borderTop: '1px solid var(--dsw-alias-border-l2)', paddingTop: 14 }}>
263
+ <summary style={{ cursor: 'pointer', fontWeight: 600 }}>{t('pmGlobalSettings')}</summary>
264
+ <CapabilityToggle field="activityIndicatorEnabled" label={t('capabilityActivity')} hint={t('capabilityActivityHint')}
265
+ enabled={snapshot.value?.activityIndicatorEnabled ?? true} disabled={!snapshot.writable} setSetting={setSetting} />
266
+ </details>
267
+ </div>}
268
+ </li>
269
+ }
270
+
271
+ /** The legacy composer seat is a compact inline row, not a menu panel. */
272
+ function FastModeFallback(
273
+ props: Pick<PropsRuntime<'conversation.input.right'>, 'sessionId' | 'useSessions'>
274
+ & InjectFace<InputSettingsControlInjected>
275
+ & PropsLocale<'codex'>,
276
+ ) {
277
+ const { useSettings, setSetting, t } = props
278
+ const snapshot = useSettings(state => state as { value?: CodexSettings; writable: boolean })
279
+ const visible = snapshot.value?.fastModeControlEnabled ?? true
280
+ const fast = snapshot.value?.fast ?? false
281
+ if (!visible) return null
282
+ return (
283
+ <button
284
+ type="button"
285
+ role="switch"
286
+ disabled={snapshot.writable === false}
287
+ aria-checked={fast}
288
+ aria-label={fast ? t('fastOn') : t('fastOff')}
289
+ title={fast ? t('fastOn') : t('fastOff')}
290
+ onClick={() => { void setSetting('fast', !fast) }}
291
+ style={{
292
+ boxSizing: 'border-box',
293
+ display: 'inline-flex',
294
+ alignItems: 'center',
295
+ gap: 5,
296
+ height: 28,
297
+ border: 0,
298
+ borderRadius: 7,
299
+ padding: '0 6px',
300
+ color: fast ? 'var(--dsw-static-blue-500)' : 'var(--dsw-alias-label-secondary)',
301
+ background: fast ? 'var(--dsw-alias-interactive-bg-selected)' : 'transparent',
302
+ cursor: snapshot.writable === false ? 'default' : 'pointer',
303
+ font: 'inherit',
304
+ fontSize: 12,
305
+ lineHeight: '20px',
306
+ fontWeight: fast ? 600 : 400,
307
+ whiteSpace: 'nowrap',
308
+ }}
309
+ >
310
+ <span>{t('fast')}</span>
311
+ <span style={{ color: 'var(--dsw-alias-label-secondary)', fontSize: 11 }}>
312
+ {fast ? t('fastStateOn') : t('fastStateOff')}
313
+ </span>
314
+ </button>
315
+ )
316
+ }
317
+
318
+ type LegacyOverlayProps = PropsRuntime<typeof LEGACY_OVERLAY_SLOT>
319
+ & InjectFace<InputSettingsControlInjected>
320
+ & PropsLocale<'codex'>
321
+
322
+ type ContextSizeControlProps = Pick<
323
+ LegacyOverlayProps,
324
+ 'sessionId' | 'useSessions' | 'useSettings' | 't'
325
+ > & Pick<InputSettingsControlInjected, 'setSetting' | 'unsetSetting'> & {
326
+ contextWindow: number
327
+ }
328
+
329
+ type ContextPressureReader = (key: 'contextPressure') => { contextWindow?: number } | undefined
330
+
331
+ function contextWindowFromProjection(useProjection: LegacyOverlayProps['useProjection']): number {
332
+ const pressure = (useProjection as unknown as ContextPressureReader)('contextPressure')
333
+ return pressure?.contextWindow !== undefined && pressure.contextWindow > 0
334
+ ? pressure.contextWindow
335
+ : DEFAULT_CONTEXT_WINDOW
336
+ }
337
+
338
+ /** Settings form appended to the old host's context meter panel. */
339
+ function ContextSizeControl({
340
+ contextWindow, sessionId: _sessionId, useSessions: _useSessions, useSettings, setSetting, unsetSetting, t,
341
+ }: ContextSizeControlProps) {
342
+ const snapshot = useSettings(state => state as { value?: CodexSettings; writable: boolean })
343
+ const configured = snapshot.value?.contextWindow
344
+ const maxK = CODEX_CONTEXT_MAX / CODEX_CONTEXT_UNIT
345
+ const valueK = Math.min(maxK, Math.max(1, Math.round((configured ?? contextWindow) / CODEX_CONTEXT_UNIT)))
346
+ const setValueK = (nextK: number): void => {
347
+ if (!Number.isFinite(nextK)) return
348
+ const normalizedK = Math.min(maxK, Math.max(1, Math.trunc(nextK)))
349
+ const normalized = normalizedK * CODEX_CONTEXT_UNIT
350
+ if (normalized === contextWindow) void unsetSetting('contextWindow')
351
+ else void setSetting('contextWindow', normalized)
352
+ }
353
+
354
+ return (
355
+ <div style={{
356
+ display: 'grid',
357
+ gap: 8,
358
+ marginTop: 10,
359
+ paddingTop: 10,
360
+ borderTop: '1px solid var(--dsw-alias-border-l2)',
361
+ }}>
362
+ <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12 }}>
363
+ <strong style={{ color: 'var(--dsw-alias-label-primary)', fontSize: 13 }}>{t('contextSize')}</strong>
364
+ <span style={{ color: 'var(--dsw-alias-label-secondary)', fontSize: 12, fontVariantNumeric: 'tabular-nums' }}>
365
+ {valueK}K
366
+ </span>
367
+ </div>
368
+ <input
369
+ type="range"
370
+ min={1}
371
+ max={maxK}
372
+ step={1}
373
+ value={valueK}
374
+ disabled={snapshot.writable === false}
375
+ aria-label={t('contextSize')}
376
+ onChange={event => { setValueK(Number(event.target.value)) }}
377
+ style={{
378
+ display: 'block',
379
+ width: '100%',
380
+ accentColor: 'var(--dsw-static-blue-500)',
381
+ }}
382
+ />
383
+ <div style={{ display: 'grid', gap: 4 }}>
384
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
385
+ <input
386
+ type="number"
387
+ min={1}
388
+ max={maxK}
389
+ step={1}
390
+ value={valueK}
391
+ disabled={snapshot.writable === false}
392
+ aria-label={t('contextSize')}
393
+ onChange={event => { setValueK(Number(event.target.value)) }}
394
+ style={{
395
+ width: 68,
396
+ border: '1px solid var(--dsw-alias-border-primary)',
397
+ borderRadius: 6,
398
+ padding: '4px 6px',
399
+ color: 'var(--dsw-alias-label-primary)',
400
+ background: 'var(--dsw-alias-fill-primary)',
401
+ font: 'inherit',
402
+ fontSize: 12,
403
+ fontVariantNumeric: 'tabular-nums',
404
+ }}
405
+ />
406
+ <span style={{ color: 'var(--dsw-alias-label-secondary)', fontSize: 11 }}>K</span>
407
+ </div>
408
+ <span style={{ color: 'var(--dsw-alias-label-secondary)', fontSize: 11, lineHeight: '16px' }}>
409
+ {t('contextSizeDescription')}
410
+ </span>
411
+ </div>
412
+ {configured !== undefined && (
413
+ <button
414
+ type="button"
415
+ onClick={() => { void unsetSetting('contextWindow') }}
416
+ style={{
417
+ justifySelf: 'start',
418
+ border: 0,
419
+ padding: 0,
420
+ color: 'var(--dsw-static-blue-500)',
421
+ background: 'transparent',
422
+ cursor: 'pointer',
423
+ font: 'inherit',
424
+ fontSize: 11,
425
+ }}
426
+ >
427
+ {t('contextRestore')}
428
+ </button>
429
+ )}
430
+ </div>
431
+ )
432
+ }
433
+
434
+ /** Detect the host meter so the fallback does not duplicate its ring button. */
435
+ function hasHostContextMeter(): boolean {
436
+ if (typeof document === 'undefined') return false
437
+ return [...document.querySelectorAll<HTMLButtonElement>('button[aria-haspopup="dialog"]')]
438
+ .some(button => button.querySelectorAll('circle').length >= 2)
439
+ }
440
+
441
+ function useHostContextMeter(): boolean {
442
+ const [available, setAvailable] = useState(false)
443
+
444
+ useEffect(() => {
445
+ if (typeof document === 'undefined' || document.body === null) return undefined
446
+ const refresh = (): void => { setAvailable(hasHostContextMeter()) }
447
+ refresh()
448
+ const observer = new MutationObserver(refresh)
449
+ observer.observe(document.body, {
450
+ subtree: true,
451
+ childList: true,
452
+ attributes: true,
453
+ attributeFilter: ['aria-expanded'],
454
+ })
455
+ return () => observer.disconnect()
456
+ }, [])
457
+
458
+ return available
459
+ }
460
+
461
+ type ContextFallbackProps = PropsRuntime<'conversation.input.right'>
462
+ & InjectFace<InputSettingsControlInjected>
463
+ & PropsLocale<'codex'>
464
+
465
+ /** Keep context configuration reachable before the host has a pressure meter. */
466
+ function ContextSizeFallback({
467
+ sessionId, useSessions, useProjection, useSettings, setSetting, unsetSetting, t,
468
+ }: ContextFallbackProps) {
469
+ const agentPreset = useSessions(state => agentPresetFromSession(state.byId[sessionId]))
470
+ const hostMeter = useHostContextMeter()
471
+ const contextWindow = contextWindowFromProjection(useProjection as LegacyOverlayProps['useProjection'])
472
+ const snapshot = useSettings(state => state as { value?: CodexSettings; writable: boolean })
473
+ const configured = snapshot.value?.contextWindow
474
+ const valueK = Math.min(
475
+ CODEX_CONTEXT_MAX / CODEX_CONTEXT_UNIT,
476
+ Math.max(1, Math.round((configured ?? contextWindow) / CODEX_CONTEXT_UNIT)),
477
+ )
478
+ const [open, setOpen] = useState(false)
479
+ const rootRef = useRef<HTMLSpanElement | null>(null)
480
+
481
+ useEffect(() => {
482
+ if (!open) return undefined
483
+ const onPointerDown = (event: PointerEvent): void => {
484
+ if (event.target instanceof Node && rootRef.current?.contains(event.target) === true) return
485
+ setOpen(false)
486
+ }
487
+ const onKeyDown = (event: KeyboardEvent): void => {
488
+ if (event.key === 'Escape') setOpen(false)
489
+ }
490
+ document.addEventListener('pointerdown', onPointerDown)
491
+ document.addEventListener('keydown', onKeyDown)
492
+ return () => {
493
+ document.removeEventListener('pointerdown', onPointerDown)
494
+ document.removeEventListener('keydown', onKeyDown)
495
+ }
496
+ }, [open])
497
+
498
+ if (!isCodexPresetId(agentPreset) || hostMeter) return null
499
+ return (
500
+ <span ref={rootRef} style={{ position: 'relative', display: 'inline-flex', alignItems: 'center' }}>
501
+ <button
502
+ type="button"
503
+ aria-label={`${t('contextSize')}: ${valueK}K`}
504
+ aria-haspopup="dialog"
505
+ aria-expanded={open}
506
+ disabled={snapshot.writable === false}
507
+ title={t('contextSize')}
508
+ onMouseDown={event => { event.preventDefault() }}
509
+ onClick={() => { setOpen(value => !value) }}
510
+ style={{
511
+ boxSizing: 'border-box',
512
+ display: 'inline-flex',
513
+ alignItems: 'center',
514
+ gap: 3,
515
+ height: 28,
516
+ border: 0,
517
+ borderRadius: 7,
518
+ padding: '0 6px',
519
+ color: configured === undefined
520
+ ? 'var(--dsw-alias-label-secondary)'
521
+ : 'var(--dsw-static-blue-500)',
522
+ background: open ? 'var(--dsw-alias-interactive-bg-hover)' : 'transparent',
523
+ cursor: snapshot.writable === false ? 'default' : 'pointer',
524
+ font: 'inherit',
525
+ fontSize: 12,
526
+ lineHeight: '20px',
527
+ fontWeight: configured === undefined ? 400 : 600,
528
+ whiteSpace: 'nowrap',
529
+ }}
530
+ >
531
+ <span>{valueK}K</span>
532
+ <svg viewBox="0 0 12 12" width="12" height="12" aria-hidden>
533
+ <path d="M3 4.5 6 7.5 9 4.5" fill="none" stroke="currentColor" strokeWidth="1.25" strokeLinecap="round" strokeLinejoin="round" />
534
+ </svg>
535
+ </button>
536
+ {open && (
537
+ <div
538
+ role="dialog"
539
+ aria-label={t('contextSize')}
540
+ style={{
541
+ position: 'absolute',
542
+ right: 0,
543
+ bottom: 'calc(100% + 8px)',
544
+ zIndex: 20,
545
+ boxSizing: 'border-box',
546
+ width: 300,
547
+ maxWidth: 'calc(100vw - 24px)',
548
+ padding: '10px 12px 12px',
549
+ border: '1px solid var(--dsw-alias-border-l2)',
550
+ borderRadius: 10,
551
+ color: 'var(--dsw-alias-label-primary)',
552
+ background: 'var(--dsw-alias-bg-base)',
553
+ boxShadow: 'var(--dsw-shadow-lv2)',
554
+ }}
555
+ >
556
+ <ContextSizeControl
557
+ contextWindow={contextWindow}
558
+ sessionId={sessionId}
559
+ useSessions={useSessions}
560
+ useSettings={useSettings}
561
+ setSetting={setSetting}
562
+ unsetSetting={unsetSetting}
563
+ t={t}
564
+ />
565
+ </div>
566
+ )}
567
+ </span>
568
+ )
569
+ }
570
+
571
+ type ActivityProps = Pick<
572
+ LegacyOverlayProps,
573
+ 'sessionId' | 'useSession' | 'useSessions' | 'useProjection' | 'useSettings' | 't'
574
+ >
575
+
576
+ type CodexActivityReader = (key: 'codexActivity') => CodexActivity | null | undefined
577
+ type ActivityFallback = ReturnType<typeof modelActivity>
578
+
579
+ function elapsedSeconds(startedAt: number, now: number): number {
580
+ return Math.max(0, Math.floor((now - startedAt) / 1_000))
581
+ }
582
+
583
+ /** Prefer the session snapshot when an older projection host only exposes null. */
584
+ export function resolveActivity(
585
+ projectedActivity: CodexActivity | null | undefined,
586
+ fallbackActivity: ActivityFallback,
587
+ ): CodexActivity | null {
588
+ if (projectedActivity?.activity === 'awaiting-model') {
589
+ return {
590
+ activity: fallbackActivity?.activity ?? 'requesting-model',
591
+ startedAt: fallbackActivity?.startedAt ?? projectedActivity.startedAt,
592
+ }
593
+ }
594
+ if (projectedActivity === null) return fallbackActivity ?? null
595
+ return projectedActivity ?? fallbackActivity ?? null
596
+ }
597
+
598
+ export function ActivityLine({
599
+ sessionId: _sessionId, useSession, useSessions: _useSessions, useProjection, useSettings, t, position,
600
+ }: ActivityProps & { position?: { left: number; top: number } }) {
601
+ const settings = useSettings(state => state as { value?: CodexSettings })
602
+ const enabled = settings.value?.activityIndicatorEnabled ?? true
603
+ // Keep the projection seam optional: this package must still load when the
604
+ // host has no session-projection registry or has not carried this key.
605
+ const projectedActivity = (useProjection as unknown as CodexActivityReader)('codexActivity')
606
+ // The projection is the authoritative phase and clock. The session snapshot
607
+ // fallback only covers the short wire gap before the next projection frame;
608
+ // tool calls intentionally remain silent because their cards own the status.
609
+ const fallbackActivity = useSession(modelActivity, sameModelActivity)
610
+ const activity = resolveActivity(projectedActivity, fallbackActivity)
611
+ const [now, setNow] = useState(() => Date.now())
612
+
613
+ useEffect(() => {
614
+ if (!enabled || activity === undefined || activity === null) return undefined
615
+ setNow(Date.now())
616
+ const timer = setInterval(() => { setNow(Date.now()) }, 1_000)
617
+ return () => clearInterval(timer)
618
+ }, [enabled, activity?.activity, activity?.startedAt])
619
+
620
+ if (!enabled || activity === undefined || activity === null) return null
621
+ const label = activity.activity === 'compaction'
622
+ ? t('activityCompacting')
623
+ : activity.activity === 'model-reply'
624
+ ? t('activityModelReply')
625
+ : t('activityRequestingModel')
626
+
627
+ return (
628
+ <span
629
+ data-codex-activity
630
+ aria-live="polite"
631
+ style={{
632
+ display: 'inline-flex',
633
+ alignItems: 'center',
634
+ gap: 7,
635
+ minHeight: 26,
636
+ marginLeft: position === undefined ? 10 : 0,
637
+ color: 'var(--dsw-alias-label-secondary)',
638
+ fontSize: 12,
639
+ lineHeight: '20px',
640
+ whiteSpace: 'nowrap',
641
+ WebkitTextFillColor: 'currentColor',
642
+ ...(position === undefined ? {} : {
643
+ position: 'fixed' as const,
644
+ left: position.left,
645
+ top: position.top,
646
+ // Keep the overlay in the conversation layer. The host composer is
647
+ // sticky at z-index 7, so this follows the same occlusion rule as
648
+ // the native Deep diving status instead of floating above the input.
649
+ zIndex: 0,
650
+ pointerEvents: 'none' as const,
651
+ }),
652
+ }}
653
+ >
654
+ <span
655
+ aria-hidden="true"
656
+ style={{
657
+ width: 5,
658
+ height: 5,
659
+ flex: '0 0 auto',
660
+ borderRadius: '50%',
661
+ background: 'var(--dsw-static-blue-500)',
662
+ opacity: 0.55,
663
+ }}
664
+ />
665
+ <span>{label}</span>
666
+ <span style={{ color: 'var(--dsw-alias-label-secondary)' }}>
667
+ {'\u00b7'} {elapsedSeconds(activity.startedAt, now)}s
668
+ </span>
669
+ </span>
670
+ )
671
+ }
672
+
673
+ function findContextMeterDialog(): HTMLElement | null {
674
+ const buttons = document.querySelectorAll<HTMLButtonElement>(
675
+ 'button[aria-haspopup="dialog"][aria-expanded="true"]',
676
+ )
677
+ for (const button of buttons) {
678
+ if (button.querySelectorAll('circle').length < 2) continue
679
+ let ancestor: Element | null = button
680
+ for (let depth = 0; ancestor !== null && depth < 5; depth += 1, ancestor = ancestor.parentElement) {
681
+ const dialog = ancestor.querySelector<HTMLElement>('[role="dialog"]')
682
+ if (dialog !== null) return dialog
683
+ }
684
+ }
685
+ return null
686
+ }
687
+
688
+ function isTurnStatus(status: HTMLElement): boolean {
689
+ return status.textContent?.includes('Deep diving...') === true
690
+ || status.className.toString().includes('turnStatus')
691
+ }
692
+
693
+ function hasLayout(status: HTMLElement): boolean {
694
+ const rect = status.getBoundingClientRect()
695
+ return rect.width > 0 && rect.height > 0
696
+ }
697
+
698
+ /** Prefer the actual Core turn status over unrelated global status nodes. */
699
+ export function selectTurnStatus(statuses: readonly HTMLElement[]): HTMLElement | null {
700
+ const preferred = statuses.filter(isTurnStatus)
701
+ return preferred.findLast(hasLayout)
702
+ ?? preferred.at(-1)
703
+ ?? statuses.filter(status => status.closest('[data-chat-flow]') !== null).findLast(hasLayout)
704
+ ?? statuses.filter(status => status.closest('[data-chat-flow]') !== null).at(-1)
705
+ ?? null
706
+ }
707
+
708
+ function findTurnStatus(): HTMLElement | null {
709
+ return selectTurnStatus([...document.querySelectorAll<HTMLElement>('[role="status"]')])
710
+ }
711
+
712
+ function useTurnStatusPosition(target: HTMLElement | null): { left: number; top: number } | null {
713
+ const [position, setPosition] = useState<{ left: number; top: number } | null>(null)
714
+
715
+ useLayoutEffect(() => {
716
+ if (target === null) {
717
+ setPosition(null)
718
+ return undefined
719
+ }
720
+ let frame: number | undefined
721
+ let previous: { left: number; top: number } | null = null
722
+ const update = (): void => {
723
+ if (!target.isConnected) {
724
+ return
725
+ }
726
+ const rect = target.getBoundingClientRect()
727
+ if (rect.width === 0 && rect.height === 0) {
728
+ if (previous !== null) {
729
+ previous = null
730
+ setPosition(null)
731
+ }
732
+ return
733
+ }
734
+ const next = {
735
+ left: Math.round(rect.right + 10),
736
+ top: Math.round(rect.top + (rect.height - 26) / 2),
737
+ }
738
+ if (previous?.left === next.left && previous.top === next.top) return
739
+ previous = next
740
+ setPosition(next)
741
+ }
742
+ const track = (): void => {
743
+ if (!target.isConnected) {
744
+ previous = null
745
+ setPosition(null)
746
+ return
747
+ }
748
+ // Streaming rows can be inserted above the status without resizing the
749
+ // status element itself; a ResizeObserver alone would leave the overlay
750
+ // at its first position.
751
+ update()
752
+ frame = window.requestAnimationFrame(track)
753
+ }
754
+ update()
755
+ frame = window.requestAnimationFrame(track)
756
+ window.addEventListener('resize', update)
757
+ window.addEventListener('scroll', update, true)
758
+ const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(update)
759
+ observer?.observe(target)
760
+ return () => {
761
+ if (frame !== undefined) window.cancelAnimationFrame(frame)
762
+ window.removeEventListener('resize', update)
763
+ window.removeEventListener('scroll', update, true)
764
+ observer?.disconnect()
765
+ }
766
+ }, [target])
767
+
768
+ return position
769
+ }
770
+
771
+ function useLegacyHostTargets(): {
772
+ contextDialog: HTMLElement | null
773
+ turnStatus: HTMLElement | null
774
+ } {
775
+ const [targets, setTargets] = useState<{
776
+ contextDialog: HTMLElement | null
777
+ turnStatus: HTMLElement | null
778
+ }>({ contextDialog: null, turnStatus: null })
779
+
780
+ useEffect(() => {
781
+ if (typeof document === 'undefined' || document.body === null) return undefined
782
+ const refresh = (): void => {
783
+ const next = {
784
+ contextDialog: findContextMeterDialog(),
785
+ turnStatus: findTurnStatus(),
786
+ }
787
+ setTargets(current => current.contextDialog === next.contextDialog
788
+ && current.turnStatus === next.turnStatus ? current : next)
789
+ }
790
+ refresh()
791
+ const observer = new MutationObserver(refresh)
792
+ observer.observe(document.body, {
793
+ subtree: true,
794
+ childList: true,
795
+ attributes: true,
796
+ attributeFilter: ['aria-expanded'],
797
+ })
798
+ return () => observer.disconnect()
799
+ }, [])
800
+ return targets
801
+ }
802
+
803
+ /** Bridges plugin UI into DOM sites rendered by the legacy conversation host. */
804
+ function LegacyOverlay(props: LegacyOverlayProps) {
805
+ const {
806
+ sessionId, useSession, useSessions, useProjection, useSettings, setSetting, unsetSetting, t,
807
+ } = props
808
+ const { contextDialog, turnStatus } = useLegacyHostTargets()
809
+ const turnStatusPosition = useTurnStatusPosition(turnStatus)
810
+ const contextWindow = contextWindowFromProjection(useProjection)
811
+ return (
812
+ <>
813
+ {contextDialog !== null && createPortal(
814
+ <ContextSizeControl
815
+ contextWindow={contextWindow}
816
+ sessionId={sessionId}
817
+ useSessions={useSessions}
818
+ useSettings={useSettings}
819
+ setSetting={setSetting}
820
+ unsetSetting={unsetSetting}
821
+ t={t}
822
+ />,
823
+ contextDialog,
824
+ 'codex-context-size',
825
+ )}
826
+ {turnStatusPosition !== null && typeof document !== 'undefined' && document.body !== null && createPortal(
827
+ <ActivityLine
828
+ sessionId={sessionId}
829
+ useSession={useSession}
830
+ useSessions={useSessions}
831
+ useProjection={useProjection}
832
+ useSettings={useSettings}
833
+ t={t}
834
+ position={turnStatusPosition}
835
+ />,
836
+ document.body,
837
+ 'codex-activity',
838
+ )}
839
+ </>
840
+ )
841
+ }
842
+
843
+ export const inject = [
844
+ 'commandUi', 'sessions', 'slots', 'locale', 'settingsScope',
845
+ 'remote',
846
+ ]
847
+
848
+ function createPresetManager(ctx: Context): PresetManagerActions {
849
+ const remote = (ctx as unknown as { remote?: TypertClientRemote }).remote
850
+ const ready: Promise<void> = remote === undefined
851
+ ? Promise.resolve()
852
+ : remote.$mount(presetEditorRemote).then(dispose => {
853
+ ctx.effect(() => () => { void dispose() }, 'codex client: preset editor remote')
854
+ })
855
+ // Keep an unavailable optional host remote from becoming an unhandled rejection
856
+ // when the settings card is never opened. The card still awaits the same promise
857
+ // and renders the actual error if the user opens it.
858
+ void ready.catch(() => {})
859
+ return {
860
+ remote: remote as unknown as PresetClientRemote,
861
+ ready,
862
+ }
863
+ }
864
+
865
+ /**
866
+ * The Codex editor contribution is mounted by this client entry itself. Its
867
+ * namespace therefore cannot be a top-level dependency (that would make the
868
+ * entry wait for the contribution it is responsible for mounting). Wait for
869
+ * the namespace in a child fiber instead, and capture that protected Remote
870
+ * face for the settings card.
871
+ */
872
+ function registerPresetSettingsCard(
873
+ ctx: Context,
874
+ settings: CodexScope,
875
+ presetManager: PresetManagerActions,
876
+ ): () => void {
877
+ const settingsPresetManager: PresetManagerActions = {
878
+ ...presetManager,
879
+ remote: (ctx as unknown as { remote: PresetClientRemote }).remote,
880
+ }
881
+ return ctx.slots.inject(PLUGIN_SETTINGS_SLOT, () => ctx.slots.register({
882
+ name: PLUGIN_SETTINGS_SLOT,
883
+ key: SETTINGS_NAMESPACE,
884
+ locale: NS,
885
+ inject: () => ({
886
+ hooks: { settings },
887
+ setSetting: (field: string, value: unknown) => settings.set(field, value),
888
+ unsetSetting: (field: string) => settings.unset(field),
889
+ presetManager: settingsPresetManager,
890
+ }),
891
+ }, PromptSettingsCard))
892
+ }
893
+
894
+ /** Mount request controls and the plugin settings card through shared slots. */
895
+ export interface ClientSettingsApi {
896
+ bind(ctx: Context): CodexScope
897
+ register(ctx: Context, settings: CodexScope, manager: PresetManagerActions): () => void
898
+ }
899
+
900
+ export function applyWithSettingsApi(ctx: Context, api: ClientSettingsApi): void {
901
+ ctx.effect(() => ctx.locale.register(NS, { en, zh }), 'codex client: dictionaries')
902
+ const commandUi = ctx.get('commandUi') as CompactCommandUi
903
+ const sessions = ctx.get('sessions') as unknown as CompactCommandSessions
904
+ const t = ctx.locale.bind(NS)
905
+ const sessionFor = (session: { sessionId: string }): CompactCommandSession | undefined =>
906
+ sessions.binding(session.sessionId)?.session
907
+ ctx.effect(() => commandUi.decorate({
908
+ name: 'compact',
909
+ available: session => sessionFor(session) !== undefined,
910
+ ui: {
911
+ kind: 'popupSelect',
912
+ options: async () => [
913
+ { id: 'remote', label: t('compactRemote'), detail: t('compactRemoteHint') },
914
+ { id: 'local', label: t('compactLocal'), detail: t('compactLocalHint') },
915
+ ],
916
+ onSelect: async (option, session) => {
917
+ const live = sessionFor(session)
918
+ if (live === undefined) throw new Error('this session is not materialized yet')
919
+ const result = await live.command(`/compact ${option.id}`)
920
+ if (!result.ok) throw new Error(`compact mode switch failed: ${result.error.code}: ${result.error.message}`)
921
+ if (!result.value.matched) throw new Error('the host offers no /compact command')
922
+ },
923
+ },
924
+ }), 'codex client: /compact mode picker')
925
+ const settings = api.bind(ctx)
926
+ const presetManager = createPresetManager(ctx)
927
+ const injected = () => ({
928
+ hooks: { settings },
929
+ setSetting: (field: string, value: unknown) => settings.set(field, value),
930
+ unsetSetting: (field: string) => settings.unset(field),
931
+ presetManager,
932
+ })
933
+ ctx.slots.inject(FAST_FALLBACK_SLOT, () => ctx.slots.register({
934
+ name: FAST_FALLBACK_SLOT,
935
+ id: 'codex-fast',
936
+ order: 0,
937
+ locale: NS,
938
+ inject: injected,
939
+ }, FastModeFallback))
940
+ ctx.slots.inject(FAST_FALLBACK_SLOT, () => ctx.slots.register({
941
+ name: FAST_FALLBACK_SLOT,
942
+ id: 'codex-context-size-fallback',
943
+ order: 1,
944
+ locale: NS,
945
+ inject: injected,
946
+ }, ContextSizeFallback))
947
+ ctx.slots.inject(LEGACY_OVERLAY_SLOT, () => ctx.slots.register({
948
+ name: LEGACY_OVERLAY_SLOT,
949
+ id: 'codex-legacy-overlay',
950
+ order: 0,
951
+ locale: NS,
952
+ inject: injected,
953
+ }, LegacyOverlay))
954
+ // `codexPresetEditor` is mounted by createPresetManager above. Keep its
955
+ // namespace dependency local to the settings card so the main client entry
956
+ // can start and perform that mount first.
957
+ ctx.inject(
958
+ ['remote', 'remote.codexPresetEditor'],
959
+ settingsCtx => api.register(settingsCtx, settings, presetManager),
960
+ )
961
+ }
962
+
963
+ export function apply(ctx: Context): void {
964
+ applyWithSettingsApi(ctx, {
965
+ bind: host => (host as unknown as {
966
+ settingsScope: { bind(spec: { namespace: string }): CodexScope }
967
+ }).settingsScope.bind({ namespace: SETTINGS_NAMESPACE }),
968
+ register: registerPresetSettingsCard,
969
+ })
970
+ }
971
+
972
+ export default { inject, apply }