@shuind/dsh-codex-harness 0.3.0 → 0.3.2

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.
@@ -53,6 +53,17 @@ export const toolPolicyEn = {
53
53
  toolPolicyConditional: 'Conditional',
54
54
  toolPolicyTargetExists: 'Replacement target already exists',
55
55
  toolPolicyPresetDisabled: 'Disabled by original preset',
56
+ toolPolicyGptGroup: 'GPT capabilities',
57
+ toolPolicyGptHostedSearch: 'GPT hosted search',
58
+ toolPolicyGptHostedSearchTitle: 'GPT sessions prefer OpenAI Responses hosted web_search (controlled in Runtime preferences).',
59
+ toolPolicyGptCodexSearch: 'Codex search',
60
+ toolPolicyGptCodexSearchTitle: 'Profile-wide web search owned by Codex Connect.',
61
+ toolPolicyGptDualSearch: 'GPT hosted / Codex search',
62
+ toolPolicyGptDualSearchTitle: 'GPT sessions prefer OpenAI hosted web_search; other models use Codex Connect search.',
63
+ toolPolicyGptImageTitle: 'Provided by Codex Connect (ChatGPT subscription image endpoint; tested to route to GPT-Image-2.6 Sunburst); callable from any tool-capable model.',
64
+ toolPolicyGptCompactionDesc: 'Server-side native context compaction (GPT sessions only; falls back to local summary on failure)',
65
+ toolPolicyGptCompactionBadge: 'GPT native compaction',
66
+ toolPolicyGptCompactionReadOnly: 'Non-tool · Runtime preference',
56
67
  toolPolicyCommandGroup: 'Commands & runtime',
57
68
  toolPolicyFileGroup: 'Files & search',
58
69
  toolPolicyPlanGroup: 'Planning & interaction',
@@ -180,6 +191,17 @@ export const toolPolicyZh: Record<keyof typeof toolPolicyEn, string> = {
180
191
  toolPolicyConditional: '按条件可用',
181
192
  toolPolicyTargetExists: '替换目标已存在',
182
193
  toolPolicyPresetDisabled: '原预设未启用',
194
+ toolPolicyGptGroup: 'GPT 能力',
195
+ toolPolicyGptHostedSearch: 'GPT 托管搜索',
196
+ toolPolicyGptHostedSearchTitle: 'GPT 会话优先使用 OpenAI Responses 原生托管搜索(由「运行偏好」控制)。',
197
+ toolPolicyGptCodexSearch: 'Codex 订阅搜索',
198
+ toolPolicyGptCodexSearchTitle: '由 Codex Connect 接管当前配置全局联网搜索。',
199
+ toolPolicyGptDualSearch: 'GPT 托管 / Codex 搜索',
200
+ toolPolicyGptDualSearchTitle: 'GPT 会话优先使用 OpenAI 原生托管搜索;其他模型走 Codex Connect 订阅搜索。',
201
+ toolPolicyGptImageTitle: '来源于 Codex Connect(ChatGPT 订阅生图接口,实测路由至 GPT-Image-2.6 Sunburst),支持工具调用的模型均可调用。',
202
+ toolPolicyGptCompactionDesc: '使用 OpenAI 服务端原生压缩替代默认文本摘要(仅 GPT 会话,失败自动回退)',
203
+ toolPolicyGptCompactionBadge: 'GPT 原生压缩',
204
+ toolPolicyGptCompactionReadOnly: '非工具 · 运行偏好控制',
183
205
  toolPolicyCommandGroup: '命令与执行',
184
206
  toolPolicyFileGroup: '文件与检索',
185
207
  toolPolicyPlanGroup: '规划与交互',
@@ -269,9 +291,11 @@ const collabNames = new Set([
269
291
  'team_task_list', 'team_task_update',
270
292
  ])
271
293
 
272
- export type ToolGroupId = 'command' | 'file' | 'plan' | 'collab' | 'other'
294
+ export type ToolGroupId = 'gpt' | 'command' | 'file' | 'plan' | 'collab' | 'other'
273
295
 
274
- export function groupOf(tool: PresetToolEntry): ToolGroupId {
296
+ export function groupOf(tool: PresetToolEntry, gptSearchActive = false): ToolGroupId {
297
+ if (tool.name === 'codex_connect_image_generate') return 'gpt'
298
+ if (tool.name === 'web_search' && gptSearchActive) return 'gpt'
275
299
  if (commandNames.has(tool.name) || tool.replacements.some(item => item.action === 'codex-exec')) return 'command'
276
300
  if (fileNames.has(tool.name) || tool.replacements.some(item => item.action === 'codex-patch')) return 'file'
277
301
  if (planNames.has(tool.name) || tool.replacements.some(item => item.action === 'codex-plan')) return 'plan'
@@ -348,6 +372,7 @@ export const policyStyles = `
348
372
  .codex-tool-policy .codex-tool-policy-description { font-size:12px; color:var(--dsw-alias-label-secondary); }
349
373
  .codex-tool-policy .codex-badge { font-size:11px; line-height:16px; padding:1px 6px; border-radius:999px; background:var(--dsw-alias-bg-layer-2); color:var(--dsw-alias-label-secondary); border:0.5px solid var(--dsw-alias-border-l2); }
350
374
  .codex-tool-policy .codex-badge[data-tone=blue] { background:var(--dsw-alias-interactive-bg-selected, rgba(59,130,246,0.12)); color:var(--dsw-static-blue-500, var(--dsw-alias-brand-primary)); border-color:transparent; }
375
+ .codex-tool-policy .codex-badge[data-tone=gpt] { background:var(--dsw-alias-state-success-bg, rgba(16,163,127,0.12)); color:var(--dsw-alias-state-success-primary, #10a37f); border-color:transparent; font-weight:500; }
351
376
  .codex-tool-policy .codex-badge[data-tone=warn] { color:var(--dsw-alias-state-warn-primary); }
352
377
  .codex-tool-policy .codex-tool-policy-action { display:flex; align-items:center; gap:6px; flex-shrink:0; }
353
378
  .codex-tool-policy .codex-tool-policy-prompts { display:flex; flex-direction:column; gap:10px; }
@@ -15,6 +15,7 @@ import type {
15
15
  PresetToolEntry, ToolAction, ToolActionContext, ToolPolicyRule,
16
16
  } from '../contracts/tool-policy-contract.ts'
17
17
  import { PRESET_PROMPT_NAMES } from '../contracts/ui-contracts.ts'
18
+ import type { CodexConnectSnapshot } from '../contracts/ui-contracts.ts'
18
19
  import { acceptPresetSave, editPresetDraft, preparePresetSave, presetRules, sameRules } from './policy-drafts.ts'
19
20
  import type { PresetDrafts } from './policy-drafts.ts'
20
21
  import { groupOf, humanLabels, policyStyles, toolPolicyEn, toolPolicyZh } from './policy-locale.ts'
@@ -86,14 +87,56 @@ export function saveToolPolicy(form: ToolPolicyForm, rules: readonly ToolPolicyR
86
87
  return form.mutate([{ op: 'set', path: ['rules'], value }], revision)
87
88
  }
88
89
 
90
+ export interface GptCapabilitiesState {
91
+ readonly hostedWebSearch: boolean
92
+ readonly codexSearch: boolean
93
+ readonly codexSearchModel?: string | undefined
94
+ readonly remoteCompaction: boolean
95
+ readonly imageGeneration: boolean
96
+ readonly imageModelHint?: string | undefined
97
+ }
98
+
99
+ export function resolveGptCapabilities(
100
+ codexSettings?: { readonly hostedWebSearchEnabled?: boolean; readonly remoteCompactionEnabled?: boolean } | undefined,
101
+ codexConnect?: CodexConnectSnapshot | undefined,
102
+ ): GptCapabilitiesState | undefined {
103
+ const connectReady = codexConnect?.status === 'ready'
104
+ if (codexSettings === undefined && !connectReady) return undefined
105
+ return {
106
+ hostedWebSearch: codexSettings !== undefined ? (codexSettings.hostedWebSearchEnabled ?? true) : false,
107
+ codexSearch: connectReady && codexConnect.searchEnabled === true,
108
+ codexSearchModel: connectReady ? codexConnect.searchModel : undefined,
109
+ remoteCompaction: (codexSettings !== undefined && (codexSettings.remoteCompactionEnabled ?? true))
110
+ || (connectReady && codexConnect.nativeCompaction === true),
111
+ imageGeneration: connectReady && codexConnect.imageGenerationEnabled === true,
112
+ imageModelHint: connectReady ? codexConnect.imageModelHint : undefined,
113
+ }
114
+ }
115
+
116
+ function formatGptImageBadge(hint: string | undefined): string {
117
+ const value = hint?.trim() ?? ''
118
+ if (!value || value === 'gpt-image-2.6-sunburst') return 'GPT-Image-2.6 Sunburst'
119
+ if (value === 'gpt-image-2.6-flare') return 'GPT-Image-2.6 Flare'
120
+ if (value === 'gpt-image-2') return 'GPT-Image-2'
121
+ return value
122
+ }
123
+
89
124
  export type ToolPolicySubMode = 'tools' | 'prompts' | 'definition'
90
125
  export type ToolPolicyMode = ToolPolicySubMode | 'inactive'
91
- type PolicyProps = PropsLocale<'codex'> & { presetManager?: PresetManagerActions | undefined; mode?: ToolPolicyMode }
126
+ type PolicyProps = PropsLocale<'codex'> & {
127
+ presetManager?: PresetManagerActions | undefined
128
+ mode?: ToolPolicyMode
129
+ gptCapabilities?: GptCapabilitiesState | undefined
130
+ }
92
131
  type ToolsView = { preset: string; status: 'loading' | 'ready' | 'error'; value?: PresetToolCatalog }
93
132
  type PromptsView = { preset: string; status: 'loading' | 'ready' | 'error'; value?: PresetPromptCatalog }
94
133
  const isPromptName = (name: string): name is PresetPromptName => (PRESET_PROMPT_NAMES as readonly string[]).includes(name)
95
134
 
96
- const GROUP_META: readonly { id: ToolGroupId; labelKey: 'toolPolicyCommandGroup' | 'toolPolicyFileGroup' | 'toolPolicyPlanGroup' | 'toolPolicyCollabGroup' | 'toolPolicyOtherGroup' }[] = [
135
+ const GROUP_META: readonly {
136
+ id: ToolGroupId
137
+ labelKey: 'toolPolicyGptGroup' | 'toolPolicyCommandGroup' | 'toolPolicyFileGroup' | 'toolPolicyPlanGroup' | 'toolPolicyCollabGroup' | 'toolPolicyOtherGroup'
138
+ }[] = [
139
+ { id: 'gpt', labelKey: 'toolPolicyGptGroup' },
97
140
  { id: 'command', labelKey: 'toolPolicyCommandGroup' },
98
141
  { id: 'file', labelKey: 'toolPolicyFileGroup' },
99
142
  { id: 'plan', labelKey: 'toolPolicyPlanGroup' },
@@ -106,7 +149,7 @@ export function ToolPolicySection({ binding, ...props }: { binding: ToolPolicyBi
106
149
  return form === undefined ? null : <ToolPolicySettingsCard form={form} {...props} />
107
150
  }
108
151
 
109
- export function ToolPolicySettingsCard({ form, presetManager, mode = 'tools', t }: { form: ToolPolicyForm } & PolicyProps) {
152
+ export function ToolPolicySettingsCard({ form, presetManager, mode = 'tools', gptCapabilities, t }: { form: ToolPolicyForm } & PolicyProps) {
110
153
  const snapshot = useSyncExternalStore(listener => form.subscribe(listener), () => form.getSnapshot(), () => form.getSnapshot())
111
154
  const [subMode, setSubMode] = useState<ToolPolicySubMode>(mode === 'prompts' || mode === 'definition' ? mode : 'tools')
112
155
  const prevMode = useRef(mode)
@@ -273,15 +316,41 @@ export function ToolPolicySettingsCard({ form, presetManager, mode = 'tools', t
273
316
  const changeSummary = summaryParts.join(' · ') || t(currentDraft && !sameRules(beforeTarget, currentDraft.rules) ? 'toolPolicyRuleChanged' : 'toolPolicyNoToolDelta')
274
317
  const unavailable = (reason: 'conditional' | 'target-exists' | undefined) => t(reason === 'conditional' ? 'toolPolicyConditional' : reason === 'target-exists' ? 'toolPolicyTargetExists' : 'toolPolicyUnsupported')
275
318
 
276
- const renderRows = (tools: readonly PresetToolEntry[]) => <div className="codex-tool-policy-table" role="table" aria-label={t('toolPolicyTitle')}>
319
+ const gptSearchActive = gptCapabilities?.hostedWebSearch === true || gptCapabilities?.codexSearch === true
320
+ const gptBadgeFor = (tool: PresetToolEntry): { label: string; title: string } | undefined => {
321
+ if (tool.name === 'codex_connect_image_generate') {
322
+ return { label: formatGptImageBadge(gptCapabilities?.imageModelHint), title: t('toolPolicyGptImageTitle') }
323
+ }
324
+ if (tool.name === 'web_search' && gptSearchActive) {
325
+ const model = gptCapabilities?.codexSearchModel
326
+ if (gptCapabilities?.hostedWebSearch && gptCapabilities?.codexSearch) {
327
+ return {
328
+ label: t('toolPolicyGptDualSearch'),
329
+ title: model ? `${t('toolPolicyGptDualSearchTitle')} (${model})` : t('toolPolicyGptDualSearchTitle'),
330
+ }
331
+ }
332
+ if (gptCapabilities?.hostedWebSearch) {
333
+ return { label: t('toolPolicyGptHostedSearch'), title: t('toolPolicyGptHostedSearchTitle') }
334
+ }
335
+ return {
336
+ label: model ? `${t('toolPolicyGptCodexSearch')} · ${model}` : t('toolPolicyGptCodexSearch'),
337
+ title: model ? `${t('toolPolicyGptCodexSearchTitle')} (${model})` : t('toolPolicyGptCodexSearchTitle'),
338
+ }
339
+ }
340
+ return undefined
341
+ }
342
+
343
+ const renderRows = (tools: readonly PresetToolEntry[], includeCompaction = false) => <div className="codex-tool-policy-table" role="table" aria-label={t('toolPolicyTitle')}>
277
344
  {tools.map(tool => {
278
345
  const action = chosen(tool); const deferReason = deferUnavailableReason(tool)
279
346
  const supported = action === 'keep' || action === 'hide' || action === 'defer' || tool.replacements.some(option => option.action === action)
280
347
  const custom = customized(tool); const hasOverride = !!rule?.tools?.some(choice => choice.name === tool.name)
348
+ const gptBadge = gptBadgeFor(tool)
281
349
  return <div key={tool.name} role="row" className="codex-tool-policy-tool" data-tool-name={tool.name} data-tool-action={action}>
282
350
  <div role="cell" className="codex-tool-policy-name">
283
351
  <code className="codex-tool-policy-identifier">{tool.name}</code>
284
352
  <span className="codex-tool-policy-description" title={tool.description}>{human(tool)}</span>
353
+ {gptBadge && <span className="codex-badge" data-tone="gpt" title={gptBadge.title}>{gptBadge.label}</span>}
285
354
  {tool.defaultDeferred && !custom && <span className="codex-badge" data-tone="blue">{t('toolPolicyDefaultDeferred')}</span>}
286
355
  {custom && <span className="codex-badge" data-tone="blue">{t('toolPolicyModified')}</span>}
287
356
  {tool.codexTool?.presetEnabled === false && <span className="codex-badge" data-tone="warn">{t('toolPolicyPresetDisabled')}</span>}
@@ -303,7 +372,17 @@ export function ToolPolicySettingsCard({ form, presetManager, mode = 'tools', t
303
372
  </div>
304
373
  </div>
305
374
  })}
306
- {tools.length === 0 && <p className="codex-tool-policy-note" style={{ padding: '12px 14px' }}>{t('toolPolicyNoMatches')}</p>}
375
+ {includeCompaction && <div key="__gpt_compaction__" role="row" className="codex-tool-policy-tool" data-gpt-capability="compaction">
376
+ <div role="cell" className="codex-tool-policy-name">
377
+ <code className="codex-tool-policy-identifier">/compact</code>
378
+ <span className="codex-tool-policy-description">{t('toolPolicyGptCompactionDesc')}</span>
379
+ <span className="codex-badge" data-tone="gpt">{t('toolPolicyGptCompactionBadge')}</span>
380
+ </div>
381
+ <div role="cell" className="codex-tool-policy-action">
382
+ <span className="codex-badge">{t('toolPolicyGptCompactionReadOnly')}</span>
383
+ </div>
384
+ </div>}
385
+ {tools.length === 0 && !includeCompaction && <p className="codex-tool-policy-note" style={{ padding: '12px 14px' }}>{t('toolPolicyNoMatches')}</p>}
307
386
  </div>
308
387
 
309
388
  if (snapshot.status !== 'ready' || snapshot.value === undefined || mode === 'inactive') return null
@@ -311,8 +390,14 @@ export function ToolPolicySettingsCard({ form, presetManager, mode = 'tools', t
311
390
  const isFiltering = text.length > 0 || filter !== 'all'
312
391
  const allTools = inventory?.tools ?? []
313
392
  const hasReplaceable = allTools.some(tool => tool.replacements.some(option => option.available))
314
- const shown = allTools.filter(tool => (!text || `${human(tool)} ${tool.name} ${tool.description}`.toLowerCase().includes(text))
315
- && (filter === 'all' || (filter === 'modified' ? customized(tool) : filter === 'deferred' ? chosen(tool) === 'defer' : tool.replacements.some(option => option.available))))
393
+ const shown = allTools.filter(tool => {
394
+ const gptBadge = gptBadgeFor(tool)
395
+ const haystack = `${human(tool)} ${tool.name} ${tool.description} ${gptBadge?.label ?? ''}`.toLowerCase()
396
+ return (!text || haystack.includes(text))
397
+ && (filter === 'all' || (filter === 'modified' ? customized(tool) : filter === 'deferred' ? chosen(tool) === 'defer' : tool.replacements.some(option => option.available)))
398
+ })
399
+ const compactionSearchText = `/compact compaction ${t('toolPolicyGptCompactionDesc')} ${t('toolPolicyGptCompactionBadge')} gpt`.toLowerCase()
400
+ const showCompactionRow = gptCapabilities?.remoteCompaction === true && filter === 'all' && (!text || compactionSearchText.includes(text))
316
401
 
317
402
  return <section className="codex-tool-policy" aria-label={t(activeSub === 'prompts' ? 'settingsPresetPrompts' : 'toolPolicyTitle')}>
318
403
  <style>{policyStyles}</style>
@@ -352,15 +437,18 @@ export function ToolPolicySettingsCard({ form, presetManager, mode = 'tools', t
352
437
  </div>
353
438
  {presetManager && selectedId && <button type="button" className="codex-btn" disabled={toolsStatus === 'loading'} onClick={() => loadTools(true)}>{t('toolPolicyToolsRefresh')}</button>}
354
439
  </div>}
355
- {inventory && !duplicate && (isFiltering && shown.length === 0
440
+ {inventory && !duplicate && (isFiltering && shown.length === 0 && !showCompactionRow
356
441
  ? <div className="codex-card">{renderRows(shown)}</div>
357
442
  : GROUP_META.map(group => {
358
- const tools = shown.filter(tool => groupOf(tool) === group.id); if (!tools.length) return null
443
+ const tools = shown.filter(tool => groupOf(tool, gptSearchActive) === group.id)
444
+ const includeCompaction = group.id === 'gpt' && showCompactionRow
445
+ if (!tools.length && !includeCompaction) return null
359
446
  const changes = tools.filter(customized).length; const key = `${selectedId}/${group.id}`
447
+ const count = tools.length + (includeCompaction ? 1 : 0)
360
448
  return <details key={group.id} className="codex-group" data-tool-group={group.id} open={isFiltering ? true : (groupOpen.get(key) ?? true)}
361
449
  onToggle={event => { const open = event.currentTarget.open; setGroupOpen(previous => new Map(previous).set(key, open)) }}>
362
- <summary><span>{t(group.labelKey)}</span><span className="codex-tool-policy-note">{tools.length}{changes ? ` · ${changes} ${t('toolPolicyCustomized')}` : ''}</span></summary>
363
- {renderRows(tools)}
450
+ <summary><span>{t(group.labelKey)}</span><span className="codex-tool-policy-note">{count}{changes ? ` · ${changes} ${t('toolPolicyCustomized')}` : ''}</span></summary>
451
+ {renderRows(tools, includeCompaction)}
364
452
  </details>
365
453
  }))}
366
454
  </>}
@@ -158,6 +158,10 @@ export interface CodexConnectSnapshot {
158
158
  readonly overrides?: Readonly<Record<string, number | null>> | undefined
159
159
  readonly baseOverrides?: Readonly<Record<string, number | null>> | undefined
160
160
  readonly nativeCompaction?: boolean | undefined
161
+ readonly searchEnabled?: boolean | undefined
162
+ readonly searchModel?: string | undefined
163
+ readonly imageGenerationEnabled?: boolean | undefined
164
+ readonly imageModelHint?: string | undefined
161
165
  }
162
166
 
163
167
  export interface CodexConnectScope {
@@ -1,8 +1,9 @@
1
1
  /** Profile-backed live preferences on DSH 0.2; legacy hosts keep settings.yaml. */
2
2
  import { Service, type Context } from '@deepseek-ai/cordis'
3
+ import type z from '@deepseek-ai/schemastery'
3
4
  import { CODEX_SETTINGS_ENTRY, CODEX_SETTINGS_SCHEMA, type CodexSettings } from '../contracts/settings.ts'
4
5
 
5
- export const Config = CODEX_SETTINGS_SCHEMA.default(CODEX_SETTINGS_ENTRY).volatile()
6
+ export const Config: z<CodexSettings, CodexSettings, 'volatile-defined'> = CODEX_SETTINGS_SCHEMA.default(CODEX_SETTINGS_ENTRY).volatile()
6
7
 
7
8
  export default class CodexPreferences extends Service {
8
9
  static Config = Config
@@ -12,7 +12,7 @@ export interface Config {
12
12
  }
13
13
 
14
14
  // Root volatility keeps saving future-Agent rules from unloading live overlays.
15
- export const Config = z.object({
15
+ export const Config: z<Config, Config, 'volatile'> = z.object({
16
16
  rules: z.array(z.object({
17
17
  preset: z.string().required().description('Exact preset id; only Agents created after this plugin loads are affected.'),
18
18
  // Bare Schemastery arrays default to []; a union preserves omitted masks.
@@ -31,7 +31,7 @@ export const Config = z.object({
31
31
  text: z.string().max(1_000_000).required(),
32
32
  }))]).description('Exact current-preset prompt replacements. Order, interpolation and complete semantics remain Host-owned.'),
33
33
  })).default([]),
34
- }).volatile()
34
+ }).volatile() as unknown as z<Config, Config, 'volatile'>
35
35
 
36
36
  /** Loader activations receive a volatile reference; direct callers may pass plain rules. */
37
37
  export type ToolPolicyConfigSource = Config | ReturnType<typeof Config>
@@ -181,14 +181,8 @@ export async function parseCompactResponsePayload(
181
181
  const output = Array.isArray(body.output) ? body.output : []
182
182
  const compactions: JsonObject[] = []
183
183
  for (const item of output) {
184
- if (!isJsonObject(item) || typeof item.encrypted_content !== 'string') continue
185
- const encrypted = item.encrypted_content.trim()
186
- if (encrypted.length === 0) continue
187
- compactions.push({
188
- type: 'compaction',
189
- encrypted_content: encrypted,
190
- ...typeof item.id === 'string' && item.id.length > 0 ? { id: item.id } : {},
191
- })
184
+ const compaction = asCompactionItem(item)
185
+ if (compaction !== undefined) compactions.push(compaction)
192
186
  }
193
187
  return {
194
188
  compactions,
@@ -2,7 +2,8 @@
2
2
 
3
3
  import type { Context } from '@deepseek-ai/cordis'
4
4
  import { credentialRef } from '@deepseek-ai/dsh-credentials'
5
- import type { GenerateOptions, Message, StreamChunk, TokenUsage, ToolSchema } from '@deepseek-ai/dsh-llm'
5
+ import { offloadedImageText, resolveImageAttachmentAccess } from '@deepseek-ai/dsh-llm'
6
+ import type { GenerateOptions, ImageBlock, Message, StreamChunk, TokenUsage, ToolSchema } from '@deepseek-ai/dsh-llm'
6
7
  import { isGptModel, readHostSettings } from '../contracts/settings.ts'
7
8
  import {
8
9
  collectTrustedCompactionMarkers,
@@ -98,9 +99,37 @@ async function apiHeaders(
98
99
  return headers
99
100
  }
100
101
 
101
- function textOf(message: Pick<Message, 'content'>): string {
102
+ const VALID_IMAGE_MEDIA_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif'])
103
+
104
+ function hasValidImageRef(attachment: unknown): attachment is ImageBlock['attachment'] {
105
+ if (typeof attachment !== 'object' || attachment === null) return false
106
+ const record = attachment as Record<string, unknown>
107
+ return typeof record.attachmentId === 'string' && record.attachmentId.length > 0
108
+ && typeof record.mediaType === 'string' && VALID_IMAGE_MEDIA_TYPES.has(record.mediaType)
109
+ && typeof record.width === 'number' && typeof record.height === 'number'
110
+ }
111
+
112
+ function formatOffloadedImage(ctx: Context, block: ImageBlock): string {
113
+ const attachments = ctx.get('attachments' as never) as { imageHostPath?: (ref: ImageBlock['attachment']) => string | undefined } | undefined
114
+ const fs = ctx.get('fs' as never) as { processPathFromHostPath?: (hostPath: string) => string | undefined } | undefined
115
+ const access = typeof attachments?.imageHostPath === 'function' && typeof fs?.processPathFromHostPath === 'function'
116
+ ? resolveImageAttachmentAccess(attachments as never, hostPath => fs.processPathFromHostPath!(hostPath), block.attachment)
117
+ : undefined
118
+ return offloadedImageText(block.attachment, access)
119
+ }
120
+
121
+ function textOf(ctx: Context, message: Pick<Message, 'content'>): string {
102
122
  return message.content
103
- .map(block => block.type === 'text' ? block.text : block.type === 'image' ? '[image omitted]' : '')
123
+ .map(block => {
124
+ if (block.type === 'text') return block.text
125
+ if (block.type === 'image') {
126
+ if (block.offloaded !== true || !hasValidImageRef(block.attachment)) {
127
+ throw new Error('Codex remote compaction requires the DSH adapter for image attachments')
128
+ }
129
+ return formatOffloadedImage(ctx, block)
130
+ }
131
+ return ''
132
+ })
104
133
  .join('')
105
134
  }
106
135
 
@@ -112,18 +141,18 @@ function stripCompactionPrompt(messages: readonly RequestMessage[]): readonly Re
112
141
  return messages
113
142
  }
114
143
 
115
- function extractInstructions(options: GenerateOptions, messages: readonly RequestMessage[]): string | undefined {
144
+ function extractInstructions(ctx: Context, options: GenerateOptions, messages: readonly RequestMessage[]): string | undefined {
116
145
  if (options.system !== undefined) return options.system
117
146
  for (let index = messages.length - 1; index >= 0; index -= 1) {
118
147
  const message = messages[index]!
119
148
  if (message.role !== 'system') continue
120
- const text = textOf(message)
149
+ const text = textOf(ctx, message)
121
150
  return text.length > 0 ? text : undefined
122
151
  }
123
152
  return undefined
124
153
  }
125
154
 
126
- function responsesInput(messages: readonly RequestMessage[]): JsonObject[] {
155
+ function responsesInput(ctx: Context, messages: readonly RequestMessage[]): JsonObject[] {
127
156
  const result: JsonObject[] = []
128
157
  for (const message of messages) {
129
158
  // This compact transport cannot serialize attachment file references losslessly.
@@ -131,7 +160,7 @@ function responsesInput(messages: readonly RequestMessage[]): JsonObject[] {
131
160
  throw new Error('Codex remote compaction requires the DSH adapter for attachments')
132
161
  }
133
162
  if (message.role === 'system') continue
134
- const text = textOf(message)
163
+ const text = textOf(ctx, message)
135
164
  if (message.role === 'tool') {
136
165
  result.push({ type: 'function_call_output', call_id: message.toolCallId.split('|')[0]!, output: text })
137
166
  continue
@@ -175,17 +204,18 @@ function responsesTools(tools: readonly ToolSchema[] | undefined): JsonObject[]
175
204
  }
176
205
 
177
206
  function compactBody(
207
+ ctx: Context,
178
208
  options: GenerateOptions,
179
209
  wireOptions: CodexRequestWireOptions,
180
210
  isV2Responses: boolean,
181
211
  ): { body: JsonObject; preCompactInput: JsonObject[] } {
182
212
  const messages = stripCompactionPrompt(options.messages)
183
- const instructions = extractInstructions(options, messages)
213
+ const instructions = extractInstructions(ctx, options, messages)
184
214
  const tools = responsesTools(options.tools)
185
215
  const serviceTier = wireOptions.serviceTier ?? serviceTierOf(options)
186
216
  const body: JsonObject = {
187
217
  model: options.model,
188
- input: responsesInput(messages),
218
+ input: responsesInput(ctx, messages),
189
219
  ...instructions !== undefined ? { instructions } : isV2Responses ? { instructions: '' } : {},
190
220
  ...tools === undefined ? {} : { tools },
191
221
  ...typeof options.sessionId === 'string' && options.sessionId.length > 0
@@ -325,7 +355,7 @@ async function remoteCompact(
325
355
  ...wireOptions,
326
356
  trustedCheckpoints: wireOptions.trustedCheckpoints ?? collectTrustedCompactionMarkers(options.messages),
327
357
  }
328
- const initial = compactBody(options, compactWireOptions, isV2Responses)
358
+ const initial = compactBody(ctx, options, compactWireOptions, isV2Responses)
329
359
  let preCompactInput = initial.preCompactInput
330
360
  let response = await sendWithRetry(endpoint, headers, initial.body, options.signal)
331
361
 
@@ -334,7 +364,7 @@ async function remoteCompact(
334
364
  && canRewriteCompactTools(options, wireOptions)) {
335
365
  const errorText = await response.clone().text().catch(() => '')
336
366
  if (!CONTEXT_LIMIT_ERROR.test(errorText)) {
337
- const reduced = compactBody(options, {
367
+ const reduced = compactBody(ctx, options, {
338
368
  ...compactWireOptions,
339
369
  hostedWebSearch: false,
340
370
  customApplyPatch: false,