@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,380 @@
1
+ /** One target at a time, with independent revision-fenced drafts. */
2
+ import { useEffect, useRef, useState, useSyncExternalStore } from 'react'
3
+ import type { Context } from '@deepseek-ai/cordis'
4
+ import type { HostObservable, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
5
+ import type { ConfigForm } from '@deepseek-ai/dsh-client-ui-settings/client'
6
+ import { PresetDefinitionCard } from './preset-manager.tsx'
7
+ import type { PresetManagerActions } from './preset-manager.tsx'
8
+ import { cachedPresetCatalog, cachedPresetPrompts, cachedPresetTools, requestPresetCatalog, requestPresetPrompts, requestPresetTools } from './preset-requests.ts'
9
+ import { effectiveToolAction, legacyToolAction, PRESET_PROMPT_NAMES } from '../tool-policy-contract.ts'
10
+ import type { PresetPromptCatalog, PresetPromptEntry, PresetPromptName, PresetToolCatalog, PresetToolEntry, ToolAction, ToolActionContext, ToolPolicyRule } from '../tool-policy-contract.ts'
11
+ import { acceptPresetSave, editPresetDraft, preparePresetSave, presetRules, sameRules } from './policy-drafts.ts'
12
+ import type { PresetDrafts } from './policy-drafts.ts'
13
+ export type { ToolPolicyRule } from '../tool-policy-contract.ts'
14
+
15
+ export const TOOL_POLICY_NAMESPACE = 'codex-tool-policy'
16
+ export interface ToolPolicySettings { readonly rules: readonly ToolPolicyRule[] }
17
+ export type ObservableConfigForm<T> = Pick<ConfigForm<T>, 'getSnapshot' | 'subscribe' | 'mutate'>
18
+ export type ToolPolicyForm = ObservableConfigForm<ToolPolicySettings>
19
+ export type ToolPolicyBinding = HostObservable<ToolPolicyForm | undefined>
20
+ type PolicyForms = Pick<Context['configForms'], 'get' | 'whileServed'>
21
+ export function bindToolPolicy(ctx: Pick<Context, 'effect'>, forms: PolicyForms): ToolPolicyBinding {
22
+ let form: ToolPolicyForm | undefined; const listeners = new Set<() => void>()
23
+ const publish = (next: ToolPolicyForm | undefined) => { form = next; for (const listener of [...listeners]) listener() }
24
+ ctx.effect(() => forms.whileServed([TOOL_POLICY_NAMESPACE], () => { publish(forms.get<ToolPolicySettings>(TOOL_POLICY_NAMESPACE)); return () => publish(undefined) }), 'codex client: tool-policy availability')
25
+ return { getSnapshot: () => form, subscribe: listener => { listeners.add(listener); return () => { listeners.delete(listener) } } }
26
+ }
27
+
28
+ export const toolPolicyEn = {
29
+ settingsTabLabel: 'Codex Harness', settingsToolsPage: 'Tool plans', settingsRuntimePage: 'Runtime preferences', settingsAdvanced: 'Advanced…',
30
+ settingsAdvancedTools: 'Individual tools', settingsPresetPrompts: 'Preset prompts', settingsDefinition: 'Original preset definition (read-only)',
31
+ settingsPreferHostedSearch: 'Prefer model-hosted search', settingsPreferRemoteCompaction: 'Prefer remote compaction',
32
+ settingsSharedFailed: 'Not saved; this page’s draft is kept. Shared settings may have changed—discard this page’s draft to reload.',
33
+ settingsRuntimeScope: 'Shared in this environment',
34
+ settingsSaveRuntime: 'Save runtime preferences', settingsBundleSummary: 'Configure Codex Harness in its dedicated Settings tab.',
35
+ settingsBundlePath: 'Settings → Plugins → Codex Harness', settingsDefinitionAbsent: 'Choose a preset on Tool plans first.',
36
+ globalGroupRequest: 'Model requests', globalGroupTools: 'Tools', globalGroupDisplay: 'Display', globalPrompts: 'Prompts', globalPending: 'Unsaved',
37
+ presetSourcesDetails: 'Original preset definition (read-only)', toolPolicyTitle: 'Tool plan', toolPolicyPresetChoice: 'Preset', toolPolicyInvalidEntry: 'Empty preset ID',
38
+ toolPolicyTiming: 'Applies: new/reloaded session',
39
+ presetPromptsLoading: 'Loading prompts…', presetPromptsFailed: 'Prompts unavailable.', presetPromptsEmpty: 'No prompt sections.', presetPromptsReload: 'Reload prompts',
40
+ presetPromptRestore: 'Restore original', presetPromptReadOnly: 'Read-only', presetPromptOverride: 'Override',
41
+ presetSummaryTools: 'Tools', presetSummaryPrompts: 'Prompts',
42
+ toolPolicyDraftSummary: 'Changes for this save', toolPolicyRuleChanged: 'Preset changes', toolPolicyNoToolDelta: 'No pending changes',
43
+ toolPolicySearch: 'Search all tools', toolPolicyFilter: 'Tool filter', toolPolicyAll: 'All', toolPolicyModified: 'Customized', toolPolicyReplaceable: 'Replaceable',
44
+ toolPolicyAction: 'Tool action', toolPolicyKeep: 'Do not change', toolPolicyHide: 'Hide', toolPolicyRestoreChoice: 'Restore inherited choice', toolPolicyUnsupported: 'Saved replacement unavailable',
45
+ toolPolicyConditional: 'Conditional', toolPolicyTargetExists: 'Replacement target already exists', toolPolicyPresetDisabled: 'Not enabled by the original preset',
46
+ toolPolicyCommandGroup: 'Commands', toolPolicyPlanGroup: 'Planning', toolPolicyFileGroup: 'Files', toolPolicyOtherGroup: 'Other tools', toolPolicyCustomized: 'customized',
47
+ toolLabelPwsh: 'PowerShell commands', toolLabelBash: 'Shell commands', toolLabelExec: 'Run commands', toolLabelStdin: 'Continue an interactive command',
48
+ toolLabelPlan: 'Task planning', toolLabelRead: 'Read files', toolLabelWrite: 'Write files', toolLabelEdit: 'Edit files', toolLabelPatch: 'Patch files',
49
+ toolLabelGlob: 'Find files', toolLabelGrep: 'Search file contents', toolLabelImage: 'View images', toolLabelOther: 'Other tool',
50
+ toolPolicyToolsLoading: 'Loading tools…', toolPolicyToolsEmpty: 'No registered tools.', toolPolicyNoMatches: 'No matching tools.', toolPolicyToolsFailed: 'Tool list unavailable. Saved rules are kept.', toolPolicyToolsRefresh: 'Refresh tools',
51
+ toolPolicyCatalogLoading: 'Loading presets…', toolPolicyCatalogEmpty: 'No presets found.', toolPolicyCatalogFailed: 'Preset list unavailable. Saved IDs remain selectable.', toolPolicyCatalogRetry: 'Reload presets',
52
+ toolPolicyEmpty: 'Choose a preset', toolPolicySave: 'Save this preset', toolPolicySaving: 'Saving…', toolPolicyDiscard: 'Discard this preset’s draft', toolPolicySaved: 'This preset was saved.',
53
+ toolPolicyInvalidPreset: 'An empty preset ID cannot be saved.', toolPolicyDuplicatePreset: 'Duplicate preset IDs cannot be saved.',
54
+ toolPolicyRefused: 'Not saved. This draft started from older settings; discard only this preset’s draft to reload.', toolPolicyFailed: 'Save failed. This preset’s draft is kept.', toolPolicyReadOnly: 'These settings are read-only.',
55
+ } as const
56
+ export const toolPolicyZh: Record<keyof typeof toolPolicyEn, string> = {
57
+ settingsTabLabel: 'Codex Harness', settingsToolsPage: '工具方案', settingsRuntimePage: '运行偏好', settingsAdvanced: '高级…',
58
+ settingsAdvancedTools: '逐项工具', settingsPresetPrompts: '预设提示词', settingsDefinition: '原始预设定义(只读)',
59
+ settingsPreferHostedSearch: '优先使用模型托管搜索', settingsPreferRemoteCompaction: '优先使用远程压缩',
60
+ settingsSharedFailed: '未保存,本页草稿已保留。共享设置可能已更新,请放弃本页草稿后重新读取。',
61
+ settingsRuntimeScope: '本环境共享',
62
+ settingsSaveRuntime: '保存运行偏好', settingsBundleSummary: '请在独立的 Codex Harness 设置页配置。',
63
+ settingsBundlePath: '设置 → 内置插件 → Codex Harness', settingsDefinitionAbsent: '请先在工具方案页选择预设。',
64
+ globalGroupRequest: '模型请求', globalGroupTools: '工具', globalGroupDisplay: '界面', globalPrompts: '提示词', globalPending: '未保存',
65
+ presetSourcesDetails: '原始预设定义(只读)', toolPolicyTitle: '工具方案', toolPolicyPresetChoice: '预设', toolPolicyInvalidEntry: '空预设 ID',
66
+ toolPolicyTiming: '生效:新建/重载会话',
67
+ presetPromptsLoading: '正在读取提示词…', presetPromptsFailed: '提示词暂不可用。', presetPromptsEmpty: '没有提示词段落。', presetPromptsReload: '重新读取提示词',
68
+ presetPromptRestore: '恢复原始', presetPromptReadOnly: '只读', presetPromptOverride: '覆盖',
69
+ presetSummaryTools: '工具', presetSummaryPrompts: '提示词',
70
+ toolPolicyDraftSummary: '本次修改', toolPolicyRuleChanged: '预设方案调整', toolPolicyNoToolDelta: '没有待保存变化',
71
+ toolPolicySearch: '搜索全部工具', toolPolicyFilter: '工具筛选', toolPolicyAll: '全部', toolPolicyModified: '已自定义', toolPolicyReplaceable: '可替换',
72
+ toolPolicyAction: '工具操作', toolPolicyKeep: '不改动', toolPolicyHide: '隐藏', toolPolicyRestoreChoice: '恢复继承选择', toolPolicyUnsupported: '已保存的替换当前不可用',
73
+ toolPolicyConditional: '按条件可用', toolPolicyTargetExists: '替换目标已存在', toolPolicyPresetDisabled: '原预设未启用',
74
+ toolPolicyCommandGroup: '命令执行', toolPolicyPlanGroup: '任务计划', toolPolicyFileGroup: '文件操作', toolPolicyOtherGroup: '其它工具', toolPolicyCustomized: '项自定义',
75
+ toolLabelPwsh: 'PowerShell 命令', toolLabelBash: 'Shell 命令', toolLabelExec: '运行命令', toolLabelStdin: '继续交互式命令',
76
+ toolLabelPlan: '任务计划', toolLabelRead: '读取文件', toolLabelWrite: '写入文件', toolLabelEdit: '修改文件', toolLabelPatch: '补丁修改',
77
+ toolLabelGlob: '查找文件', toolLabelGrep: '搜索文件内容', toolLabelImage: '查看图片', toolLabelOther: '其它工具',
78
+ toolPolicyToolsLoading: '正在读取工具…', toolPolicyToolsEmpty: '没有已注册工具。', toolPolicyNoMatches: '没有匹配工具。', toolPolicyToolsFailed: '工具目录不可用,已保存规则仍保留。', toolPolicyToolsRefresh: '刷新工具',
79
+ toolPolicyCatalogLoading: '正在读取预设…', toolPolicyCatalogEmpty: '没有可选预设。', toolPolicyCatalogFailed: '预设列表不可用,仍可选择已保存 ID。', toolPolicyCatalogRetry: '重新读取预设',
80
+ toolPolicyEmpty: '请选择预设', toolPolicySave: '保存此预设', toolPolicySaving: '正在保存…', toolPolicyDiscard: '放弃此预设草稿', toolPolicySaved: '此预设已保存。',
81
+ toolPolicyInvalidPreset: '预设 ID 为空,无法保存。', toolPolicyDuplicatePreset: '预设 ID 重复,无法保存。',
82
+ toolPolicyRefused: '未保存,草稿基于旧设置。请仅放弃此预设草稿后重新读取。', toolPolicyFailed: '保存失败,此预设草稿已保留。', toolPolicyReadOnly: '当前设置为只读。',
83
+ }
84
+
85
+ type MutableRule = { -readonly [Key in keyof ToolPolicyRule]: ToolPolicyRule[Key] }
86
+ export function validateToolPolicyRules(rules: readonly ToolPolicyRule[]): 'toolPolicyInvalidPreset' | 'toolPolicyDuplicatePreset' | undefined {
87
+ const ids = new Set<string>()
88
+ for (const rule of rules) { const id = rule.preset.trim(); if (!id) return 'toolPolicyInvalidPreset'; if (ids.has(id)) return 'toolPolicyDuplicatePreset'; ids.add(id) }
89
+ return undefined
90
+ }
91
+ export function withToolAction(rule: ToolPolicyRule, name: string, action: ToolAction, context: ToolActionContext = {}): ToolPolicyRule {
92
+ const next: MutableRule = { ...rule }; const tools = [...(rule.tools ?? [])].filter(tool => tool.name !== name)
93
+ if (action !== legacyToolAction(rule, name, context)) tools.push({ name, action })
94
+ if (tools.length) next.tools = tools; else delete next.tools
95
+ return next
96
+ }
97
+ export function saveToolPolicy(form: ToolPolicyForm, rules: readonly ToolPolicyRule[], revision: number | undefined): Promise<boolean> {
98
+ const value = rules.map(rule => {
99
+ const row: Record<string, string | boolean | string[] | Array<{ name: string; action: string }> | Array<{ name: string; text: string }>> = { preset: rule.preset }
100
+ if (rule.allow !== undefined) row.allow = [...rule.allow]; if (rule.deny !== undefined) row.deny = [...rule.deny]
101
+ if (rule.replaceShell !== undefined) row.replaceShell = rule.replaceShell; if (rule.replacePlan !== undefined) row.replacePlan = rule.replacePlan
102
+ if (rule.tools !== undefined) row.tools = rule.tools.map(tool => ({ ...tool }))
103
+ if (rule.promptOverrides !== undefined) row.promptOverrides = rule.promptOverrides.map(override => ({ name: override.name, text: override.text }))
104
+ return row
105
+ })
106
+ return form.mutate([{ op: 'set', path: ['rules'], value }], revision)
107
+ }
108
+ export type ToolPolicyMode = 'tools' | 'details' | 'prompts' | 'definition' | 'inactive'
109
+ type PolicyProps = PropsLocale<'codex'> & { presetManager?: PresetManagerActions | undefined; mode?: ToolPolicyMode }
110
+ type ToolsView = { preset: string; status: 'loading' | 'ready' | 'error'; value?: PresetToolCatalog }
111
+ type PromptsView = { preset: string; status: 'loading' | 'ready' | 'error'; value?: PresetPromptCatalog }
112
+ const isPromptName = (name: string): name is PresetPromptName => (PRESET_PROMPT_NAMES as readonly string[]).includes(name)
113
+ const fileNames = new Set(['read', 'write', 'edit', 'apply_patch', 'glob', 'grep', 'read_image'])
114
+ function groupOf(tool: PresetToolEntry): 'command' | 'plan' | 'file' | 'other' {
115
+ if (['bash', 'pwsh', 'exec_command', 'write_stdin'].includes(tool.name) || tool.replacements.some(item => item.action === 'codex-exec')) return 'command'
116
+ if (['todo_write', 'update_plan'].includes(tool.name) || tool.replacements.some(item => item.action === 'codex-plan')) return 'plan'
117
+ return fileNames.has(tool.name) ? 'file' : 'other'
118
+ }
119
+ const humanLabels = { pwsh: 'toolLabelPwsh', bash: 'toolLabelBash', exec_command: 'toolLabelExec', write_stdin: 'toolLabelStdin', todo_write: 'toolLabelPlan', update_plan: 'toolLabelPlan',
120
+ read: 'toolLabelRead', write: 'toolLabelWrite', edit: 'toolLabelEdit', apply_patch: 'toolLabelPatch', glob: 'toolLabelGlob', grep: 'toolLabelGrep', read_image: 'toolLabelImage' } as const
121
+ const policyStyles = `
122
+ .codex-tool-policy { min-width:0; font-size:14px; color:var(--dsw-alias-label-primary); }
123
+ .codex-tool-policy p, .codex-tool-policy h3 { margin:0; }
124
+ .codex-tool-policy h3 { font-size:14px; }
125
+ .codex-tool-policy .codex-tool-policy-note, .codex-tool-policy code { color:var(--dsw-alias-label-secondary); font-size:12px; line-height:1.5; }
126
+ .codex-tool-policy form, .codex-tool-policy fieldset { min-width:0; margin:0; padding:0; border:0; }
127
+ .codex-tool-policy .codex-tool-policy-head { display:grid; gap:12px; margin-bottom:16px; }
128
+ .codex-tool-policy .codex-tool-policy-picker, .codex-tool-policy .codex-tool-policy-filters { display:grid; grid-template-columns:minmax(0,1fr) auto; align-items:end; gap:8px; }
129
+ .codex-tool-policy .codex-tool-policy-field { display:grid; gap:8px; min-width:0; }
130
+ .codex-tool-policy input[type=text], .codex-tool-policy select, .codex-tool-policy button { box-sizing:border-box; min-width:0; max-width:100%; padding:7px 12px; border:1px solid var(--dsw-alias-border-l2); border-radius:8px; background:var(--dsw-alias-bg-layer-2); color:inherit; font:inherit; }
131
+ .codex-tool-policy input[type=text], .codex-tool-policy select { width:100%; }
132
+ .codex-tool-policy button { cursor:pointer; }
133
+ .codex-tool-policy button:disabled { opacity:.5; cursor:default; }
134
+ .codex-tool-policy :is(input,select,button,summary):focus-visible { outline:2px solid var(--dsw-alias-brand-primary); outline-offset:2px; }
135
+ .codex-tool-policy .codex-tool-policy-table { max-height:360px; overflow:auto; }
136
+ .codex-tool-policy .codex-tool-policy-tool { display:grid; grid-template-columns:minmax(0,1fr) minmax(160px,280px); gap:12px; align-items:center; padding:8px 0; border-bottom:1px solid var(--dsw-alias-border-l1); }
137
+ .codex-tool-policy .codex-tool-policy-name { min-width:0; display:grid; gap:4px; overflow-wrap:anywhere; }
138
+ .codex-tool-policy .codex-tool-policy-identifier { font-size:14px; font-weight:600; color:var(--dsw-alias-label-primary); }
139
+ .codex-tool-policy .codex-tool-policy-description { font-size:12px; line-height:1.5; color:var(--dsw-alias-label-secondary); }
140
+ .codex-tool-policy .codex-tool-policy-action { min-width:0; display:flex; gap:8px; align-items:center; }
141
+ .codex-tool-policy .codex-tool-policy-action select { min-width:0; flex:1; }
142
+ .codex-tool-policy .codex-tool-policy-primary { background:var(--dsw-alias-label-primary); color:var(--dsw-alias-bg-base); }
143
+ .codex-tool-policy details { border-top:1px solid var(--dsw-alias-border-l1); padding:12px 0; }
144
+ .codex-tool-policy summary { cursor:pointer; }
145
+ .codex-tool-policy summary .codex-tool-policy-note { margin-left:8px; }
146
+ .codex-tool-policy .codex-tool-policy-actions { display:flex; gap:8px; align-items:center; flex-wrap:wrap; margin-top:16px; }
147
+ .codex-tool-policy .codex-tool-policy-warning { color:var(--dsw-alias-state-warn-primary); font-size:12px; }
148
+ .codex-tool-policy .codex-tool-policy-error { color:var(--dsw-alias-state-error-primary); font-size:12px; }
149
+ .codex-tool-policy .codex-tool-policy-prompts { display:grid; gap:16px; }
150
+ .codex-tool-policy .codex-tool-policy-prompt { display:grid; gap:8px; padding:12px 0; border-top:1px solid var(--dsw-alias-border-l1); }
151
+ .codex-tool-policy .codex-tool-policy-prompt h4 { margin:0; font-size:14px; font-weight:600; }
152
+ .codex-tool-policy textarea { box-sizing:border-box; width:100%; min-width:0; resize:vertical; padding:8px 12px; border:1px solid var(--dsw-alias-border-l2); border-radius:8px; background:var(--dsw-alias-bg-layer-2); color:inherit; font:inherit; }
153
+ .codex-tool-policy textarea:focus-visible { outline:2px solid var(--dsw-alias-brand-primary); outline-offset:2px; }
154
+ .codex-tool-policy .codex-tool-policy-prompt pre { margin:0; max-height:240px; overflow:auto; white-space:pre-wrap; overflow-wrap:anywhere; font:inherit; }
155
+ @media (max-width:480px) { .codex-tool-policy .codex-tool-policy-tool { grid-template-columns:minmax(0,1fr); gap:8px; } }
156
+ `
157
+ export function ToolPolicySection({ binding, ...props }: { binding: ToolPolicyBinding } & PolicyProps) {
158
+ const form = useSyncExternalStore(binding.subscribe, binding.getSnapshot, binding.getSnapshot)
159
+ return form === undefined ? null : <ToolPolicySettingsCard form={form} {...props} />
160
+ }
161
+
162
+ export function ToolPolicySettingsCard({ form, presetManager, mode = 'tools', t }: { form: ToolPolicyForm } & PolicyProps) {
163
+ const snapshot = useSyncExternalStore(listener => form.subscribe(listener), () => form.getSnapshot(), () => form.getSnapshot())
164
+ const [drafts, setDrafts] = useState<PresetDrafts>(() => new Map())
165
+ const [saving, setSaving] = useState(false); const [error, setError] = useState(''); const [notice, setNotice] = useState('')
166
+ const [selection, setSelection] = useState<string>()
167
+ const [query, setQuery] = useState(''); const [filter, setFilter] = useState('all')
168
+ const [groupOpen, setGroupOpen] = useState<ReadonlyMap<string, boolean>>(() => new Map())
169
+ const [toolsView, setToolsView] = useState<ToolsView>()
170
+ const [promptsView, setPromptsView] = useState<PromptsView>()
171
+ const alive = useRef(true); const catalogRequest = useRef(0); const toolsRequest = useRef(0); const promptsRequest = useRef(0)
172
+ const [catalog, setCatalog] = useState(() => presetManager === undefined ? undefined : cachedPresetCatalog(presetManager))
173
+ const [catalogState, setCatalogState] = useState<'loading' | 'ready' | 'error'>(() => catalog ? 'ready' : presetManager ? 'loading' : 'error')
174
+ function loadCatalog(refresh = false): void {
175
+ const ticket = ++catalogRequest.current; if (presetManager === undefined) { setCatalogState('error'); return }
176
+ setCatalogState('loading'); void requestPresetCatalog(presetManager, refresh).then(value => {
177
+ if (alive.current && ticket === catalogRequest.current) { setCatalog(value); setCatalogState('ready') }
178
+ }).catch(() => { if (alive.current && ticket === catalogRequest.current) setCatalogState('error') })
179
+ }
180
+ useEffect(() => { alive.current = true; loadCatalog(); return () => { alive.current = false; catalogRequest.current++; toolsRequest.current++; promptsRequest.current++ } }, [presetManager])
181
+ const acceptedRules = snapshot.value?.rules ?? []
182
+ const ids = [...new Set([...(catalog?.presets.map(preset => preset.id) ?? []), ...acceptedRules.map(rule => rule.preset), ...drafts.keys()])].filter(id => id.trim())
183
+ const selectedId = selection ?? ids[0] ?? ''
184
+ const currentDraft = drafts.get(selectedId)
185
+ const currentRules = currentDraft?.rules ?? presetRules(acceptedRules, selectedId)
186
+ const rule = currentRules[0]
187
+ const duplicate = currentRules.length > 1
188
+ const presetLabel = catalog?.presets.find(preset => preset.id === selectedId)?.name ?? selectedId
189
+ function loadTools(refresh = false): void {
190
+ const ticket = ++toolsRequest.current
191
+ if (!selectedId || presetManager === undefined) { setToolsView({ preset: selectedId, status: 'error' }); return }
192
+ setToolsView({ preset: selectedId, status: 'loading' }); void requestPresetTools(presetManager, selectedId, refresh).then(value => {
193
+ if (alive.current && ticket === toolsRequest.current) setToolsView({ preset: selectedId, status: 'ready', value })
194
+ }).catch(() => { if (alive.current && ticket === toolsRequest.current) setToolsView({ preset: selectedId, status: 'error' }) })
195
+ }
196
+ useEffect(() => { loadTools(); return () => { toolsRequest.current++ } }, [presetManager, selectedId])
197
+ const cached = presetManager && selectedId ? cachedPresetTools(presetManager, selectedId) : undefined
198
+ const inventory = toolsView?.preset === selectedId && toolsView.status === 'error' ? undefined : toolsView?.preset === selectedId && toolsView.status === 'ready' ? toolsView.value : cached
199
+ const toolsStatus = inventory ? 'ready' : toolsView?.preset === selectedId ? toolsView.status : selectedId ? 'loading' : 'error'
200
+ function loadPrompts(refresh = false): void {
201
+ const ticket = ++promptsRequest.current
202
+ if (!selectedId || presetManager === undefined) { setPromptsView({ preset: selectedId, status: 'error' }); return }
203
+ setPromptsView({ preset: selectedId, status: 'loading' })
204
+ void requestPresetPrompts(presetManager, selectedId, refresh).then(value => {
205
+ if (alive.current && ticket === promptsRequest.current) setPromptsView({ preset: selectedId, status: 'ready', value })
206
+ }).catch(() => { if (alive.current && ticket === promptsRequest.current) setPromptsView({ preset: selectedId, status: 'error' }) })
207
+ }
208
+ useEffect(() => {
209
+ if (mode === 'prompts') loadPrompts()
210
+ return () => { promptsRequest.current++ }
211
+ }, [presetManager, selectedId, mode === 'prompts'])
212
+ const cachedPrompts = presetManager && selectedId ? cachedPresetPrompts(presetManager, selectedId) : undefined
213
+ const promptCatalog = promptsView?.preset === selectedId && promptsView.status === 'error' ? undefined
214
+ : promptsView?.preset === selectedId && promptsView.status === 'ready' ? promptsView.value : cachedPrompts
215
+ const promptsStatus = promptCatalog ? 'ready' : promptsView?.preset === selectedId ? promptsView.status : selectedId ? 'loading' : 'error'
216
+ const contextFor = (tool: PresetToolEntry): ToolActionContext => ({ ...(inventory?.legacyCapabilities === undefined ? {} : { legacyCapabilities: inventory.legacyCapabilities }), ...(tool.codexTool === undefined ? {} : { codexTool: tool.codexTool }) })
217
+ const chosen = (tool: PresetToolEntry) => effectiveToolAction(rule, tool.name, contextFor(tool))
218
+ const customized = (tool: PresetToolEntry) => chosen(tool) !== effectiveToolAction(undefined, tool.name, contextFor(tool)) || !!rule?.tools?.some(choice => choice.name === tool.name)
219
+ const inventoryNames = new Set(inventory?.tools.map(tool => tool.name) ?? [])
220
+ const stage = (change: (rules: readonly ToolPolicyRule[]) => readonly ToolPolicyRule[]): void => {
221
+ if (snapshot.status !== 'ready' || !snapshot.writable || saving) return
222
+ const latest = form.getSnapshot(); setError(''); setNotice('')
223
+ setDrafts(previous => editPresetDraft(previous, selectedId, { revision: latest.revision, rules: latest.value?.rules ?? [] }, change))
224
+ }
225
+ const editRule = (change: (value: ToolPolicyRule) => ToolPolicyRule): void => stage(previous => {
226
+ const base = previous[0] ?? { preset: selectedId, replaceShell: false, replacePlan: false }
227
+ const next = change(base)
228
+ const neutralNew = presetRules(currentDraft?.baseline ?? acceptedRules, selectedId).length === 0 && !next.tools?.length && !next.promptOverrides?.length && next.allow === undefined && !next.deny?.length && next.replaceShell === false && next.replacePlan === false
229
+ if (neutralNew) return []
230
+ if (previous.length === 0) return [next]
231
+ return previous.map((value, position) => position === 0 ? next : value)
232
+ })
233
+ const chooseAction = (tool: PresetToolEntry, action: string): void => {
234
+ if (duplicate || !selectedId || (action !== 'keep' && action !== 'hide' && action !== 'codex-exec' && action !== 'codex-plan')) return
235
+ if (action !== 'keep' && action !== 'hide' && !tool.replacements.some(replacement => replacement.action === action && replacement.available)) return
236
+ const context = contextFor(tool)
237
+ if (rule === undefined && action === legacyToolAction(undefined, tool.name, context)) return
238
+ editRule(value => withToolAction(value, tool.name, action, context))
239
+ }
240
+ const removeChoice = (name: string): void => editRule(value => {
241
+ const next: MutableRule = { ...value }; const tools = (value.tools ?? []).filter(choice => choice.name !== name)
242
+ if (tools.length) next.tools = tools; else delete next.tools; return next
243
+ })
244
+ const changePrompt = (section: PresetPromptEntry, text: string): void => {
245
+ if (duplicate || !section.editable || !isPromptName(section.name) || promptCatalog?.preset !== selectedId) return
246
+ const name = section.name
247
+ editRule(value => ({ ...value, promptOverrides: [...(value.promptOverrides ?? []).filter(entry => entry.name !== name), { name, text }] }))
248
+ }
249
+ const restorePrompt = (section: PresetPromptEntry): void => {
250
+ if (duplicate || !section.editable || !isPromptName(section.name) || promptCatalog?.preset !== selectedId) return
251
+ editRule(value => {
252
+ const next: MutableRule = { ...value }; const remaining = (value.promptOverrides ?? []).filter(entry => entry.name !== section.name)
253
+ if (remaining.length) next.promptOverrides = remaining; else delete next.promptOverrides
254
+ return next
255
+ })
256
+ }
257
+ const saveCurrent = (): void => {
258
+ if (!currentDraft || saving || !snapshot.writable || snapshot.status !== 'ready') return
259
+ const latest = form.getSnapshot()
260
+ const target = selectedId
261
+ const targetName = presetLabel && presetLabel !== target ? `${presetLabel} (${target})` : target || t('toolPolicyInvalidEntry')
262
+ const message = (key: 'toolPolicyInvalidPreset' | 'toolPolicyDuplicatePreset' | 'toolPolicyRefused' | 'toolPolicyFailed' | 'toolPolicySaved') => `${targetName}: ${t(key)}`
263
+ let prepared: ReturnType<typeof preparePresetSave>
264
+ try {
265
+ prepared = preparePresetSave(currentDraft, { revision: latest.revision, rules: latest.value?.rules ?? [] })
266
+ const invalid = validateToolPolicyRules(currentDraft.rules)
267
+ const otherIds = new Set((latest.value?.rules ?? []).filter(value => value.preset !== selectedId).map(value => value.preset.trim()))
268
+ if (invalid || currentDraft.rules.some(value => otherIds.has(value.preset.trim()))) { setError(message(invalid ?? 'toolPolicyDuplicatePreset')); return }
269
+ } catch { setError(message('toolPolicyRefused')); return }
270
+ setSaving(true); setError(''); setNotice('')
271
+ void saveToolPolicy(form, prepared.rules, prepared.revision).then(accepted => {
272
+ if (!alive.current) return
273
+ if (!accepted) { setError(message('toolPolicyRefused')); return }
274
+ const after = form.getSnapshot()
275
+ setDrafts(previous => acceptPresetSave(previous, prepared, { revision: after.revision, rules: after.value?.rules ?? [] }))
276
+ setNotice(message('toolPolicySaved'))
277
+ }).catch(() => { if (alive.current) setError(message('toolPolicyFailed')) }).finally(() => { if (alive.current) setSaving(false) })
278
+ }
279
+ const human = (tool: PresetToolEntry): string => {
280
+ const key = humanLabels[tool.name as keyof typeof humanLabels]
281
+ return key ? t(key) : tool.description.split(/[\n。.!]/u)[0]?.trim().slice(0, 60) || t('toolLabelOther')
282
+ }
283
+ const beforeTarget = currentDraft ? presetRules(currentDraft.baseline, selectedId) : []
284
+ const beforeRule = beforeTarget[0]
285
+ const choiceFor = (value: ToolPolicyRule | undefined, name: string) => value?.tools?.find(choice => choice.name === name)
286
+ const changedNames = currentDraft ? [...new Set([
287
+ ...(inventory?.tools.filter(tool => effectiveToolAction(beforeRule, tool.name, contextFor(tool)) !== chosen(tool)
288
+ || JSON.stringify(choiceFor(beforeRule, tool.name)) !== JSON.stringify(choiceFor(rule, tool.name))).map(tool => tool.name) ?? []),
289
+ ...[...(beforeRule?.tools ?? []), ...(rule?.tools ?? [])].filter(choice => !inventoryNames.has(choice.name)
290
+ && JSON.stringify(choiceFor(beforeRule, choice.name)) !== JSON.stringify(choiceFor(rule, choice.name))).map(choice => choice.name),
291
+ ])] : []
292
+ const changedPrompts = currentDraft ? [...new Set([...(beforeRule?.promptOverrides ?? []), ...(rule?.promptOverrides ?? [])].map(entry => entry.name))]
293
+ .filter(name => JSON.stringify(beforeRule?.promptOverrides?.find(entry => entry.name === name)) !== JSON.stringify(rule?.promptOverrides?.find(entry => entry.name === name))) : []
294
+ const summaryParts = [
295
+ ...(changedNames.length ? [`${t('presetSummaryTools')}: ${changedNames.slice(0, 4).join(', ')}${changedNames.length > 4 ? ` (+${changedNames.length - 4})` : ''}`] : []),
296
+ ...(changedPrompts.length ? [`${t('presetSummaryPrompts')}: ${changedPrompts.map(name => promptCatalog?.sections.find(section => section.name === name)?.label || name).join(', ')}`] : []),
297
+ ]
298
+ const changeSummary = summaryParts.join(' · ') || t(currentDraft && !sameRules(beforeTarget, currentDraft.rules) ? 'toolPolicyRuleChanged' : 'toolPolicyNoToolDelta')
299
+ const unavailable = (reason: 'conditional' | 'target-exists' | undefined) => t(reason === 'conditional' ? 'toolPolicyConditional' : reason === 'target-exists' ? 'toolPolicyTargetExists' : 'toolPolicyUnsupported')
300
+ const rows = (tools: readonly PresetToolEntry[]) => <div className="codex-tool-policy-table" role="table" aria-label={t('toolPolicyTitle')}>
301
+ {tools.map(tool => { const action = chosen(tool); const supported = action === 'keep' || action === 'hide' || tool.replacements.some(option => option.action === action)
302
+ return <div key={tool.name} role="row" className="codex-tool-policy-tool" data-tool-name={tool.name}>
303
+ <div role="cell" className="codex-tool-policy-name"><code className="codex-tool-policy-identifier">{tool.name}</code><span className="codex-tool-policy-description" title={tool.description}>{human(tool)}</span>
304
+ {tool.codexTool?.presetEnabled === false && <span className="codex-tool-policy-note">{t('toolPolicyPresetDisabled')}</span>}
305
+ {tool.conditional && <span className="codex-tool-policy-note">{t('toolPolicyConditional')}</span>}
306
+ </div>
307
+ <div role="cell" className="codex-tool-policy-action"><select aria-label={`${t('toolPolicyAction')} ${tool.name}`} value={action} disabled={duplicate} onChange={event => chooseAction(tool, event.target.value)}>
308
+ <option value="keep">{t('toolPolicyKeep')}</option><option value="hide">{t('toolPolicyHide')}</option>
309
+ {tool.replacements.map(option => <option key={option.action} value={option.action} disabled={!option.available} title={!option.available ? unavailable(option.reason) : undefined}>
310
+ {option.tools.join(' + ')}{option.available ? '' : ` · ${unavailable(option.reason)}`}</option>)}
311
+ {!supported && <option value={action} disabled>{t('toolPolicyUnsupported')} ({action})</option>}
312
+ </select>{rule?.tools?.some(choice => choice.name === tool.name) && <button type="button" aria-label={`${t('toolPolicyRestoreChoice')} ${tool.name}`}
313
+ title={t('toolPolicyRestoreChoice')} onClick={() => removeChoice(tool.name)}>↶</button>}</div>
314
+ </div> })}
315
+ {tools.length === 0 && <p className="codex-tool-policy-note">{t('toolPolicyNoMatches')}</p>}
316
+ </div>
317
+ if (snapshot.status !== 'ready' || snapshot.value === undefined || mode === 'inactive') return null
318
+ if (mode === 'definition') return !selectedId || presetManager === undefined ? <p>{t('settingsDefinitionAbsent')}</p>
319
+ : <PresetDefinitionCard presetManager={presetManager} id={selectedId} t={t} />
320
+ const isDetails = mode === 'details'
321
+ const text = query.trim().toLowerCase()
322
+ const shown = (inventory?.tools ?? []).filter(tool => (!text || `${human(tool)} ${tool.name} ${tool.description}`.toLowerCase().includes(text))
323
+ && (filter !== 'modified' || customized(tool)) && (filter !== 'replaceable' || tool.replacements.some(replacement => replacement.available)))
324
+ return <section className="codex-tool-policy" aria-label={t(mode === 'prompts' ? 'settingsPresetPrompts' : 'toolPolicyTitle')}>
325
+ <style>{policyStyles}</style>
326
+ <div className="codex-tool-policy-head">
327
+ {mode === 'prompts' && <h3>{presetLabel || t('toolPolicyInvalidEntry')}<span className="codex-tool-policy-note"> · {t('settingsPresetPrompts')}</span></h3>}
328
+ {mode === 'tools' || mode === 'prompts' ? <div className="codex-tool-policy-picker"><label className="codex-tool-policy-field"><span>{t('toolPolicyPresetChoice')}</span>
329
+ <select aria-label={t('toolPolicyPresetChoice')} value={selectedId} onChange={event => { setSelection(event.target.value); setError(''); setNotice('') }}>
330
+ {!ids.length && <option value="">{t('toolPolicyEmpty')}</option>}{ids.map(id => <option key={id} value={id} data-preset-id={id}>{catalog?.presets.find(preset => preset.id === id)?.name ?? id}{drafts.has(id) ? ` · ${t('globalPending')}` : ''}</option>)}
331
+ </select></label>{presetManager && <button type="button" disabled={catalogState === 'loading'} onClick={() => loadCatalog(true)}>{t('toolPolicyCatalogRetry')}</button>}</div>
332
+ : <h3>{presetLabel || t('toolPolicyInvalidEntry')} <code>{selectedId}</code></h3>}
333
+ {(mode === 'tools' || mode === 'prompts') && <>
334
+ {catalogState !== 'ready' && <p className="codex-tool-policy-note" role="status">{t(catalogState === 'loading' ? 'toolPolicyCatalogLoading' : 'toolPolicyCatalogFailed')}</p>}
335
+ {catalogState === 'ready' && !ids.length && <p className="codex-tool-policy-note">{t('toolPolicyCatalogEmpty')}</p>}
336
+ </>}
337
+ {isDetails && <div className="codex-tool-policy-filters"><input type="text" aria-label={t('toolPolicySearch')} placeholder={t('toolPolicySearch')} value={query} onChange={event => setQuery(event.target.value)} />
338
+ <select aria-label={t('toolPolicyFilter')} value={filter} onChange={event => setFilter(event.target.value)}><option value="all">{t('toolPolicyAll')}</option><option value="modified">{t('toolPolicyModified')}</option><option value="replaceable">{t('toolPolicyReplaceable')}</option></select></div>}
339
+ {mode !== 'prompts' && toolsStatus !== 'ready' && <p className="codex-tool-policy-note" role="status">{t(toolsStatus === 'loading' ? 'toolPolicyToolsLoading' : 'toolPolicyToolsFailed')}</p>}
340
+ {mode !== 'prompts' && inventory?.tools.length === 0 && <p className="codex-tool-policy-note" role="status">{t('toolPolicyToolsEmpty')}</p>}
341
+ {mode === 'prompts' && <>
342
+ {presetManager && selectedId && <button type="button" disabled={promptsStatus === 'loading'} onClick={() => loadPrompts(true)}>{t('presetPromptsReload')}</button>}
343
+ {promptsStatus !== 'ready' && <p className="codex-tool-policy-note" role="status">{t(promptsStatus === 'loading' ? 'presetPromptsLoading' : 'presetPromptsFailed')}</p>}
344
+ {promptCatalog?.sections.length === 0 && <p className="codex-tool-policy-note">{t('presetPromptsEmpty')}</p>}
345
+ </>}
346
+ {isDetails && presetManager && selectedId && <button type="button" disabled={toolsStatus === 'loading'} onClick={() => loadTools(true)}>{t('toolPolicyToolsRefresh')}</button>}
347
+ {duplicate && <p className="codex-tool-policy-warning">{t('toolPolicyDuplicatePreset')}</p>}
348
+ </div>
349
+ <form onSubmit={event => { event.preventDefault(); saveCurrent() }}><fieldset disabled={!snapshot.writable || saving}>
350
+ {mode === 'tools' && inventory && !duplicate && (['command', 'plan', 'file', 'other'] as const).map(group => {
351
+ const tools = inventory.tools.filter(tool => groupOf(tool) === group); if (!tools.length) return null
352
+ const changes = tools.filter(customized).length; const key = `${selectedId}/${group}`
353
+ return <details key={group} data-tool-group={group} open={groupOpen.get(key) ?? (group === 'command' || group === 'plan' || changes > 0)} onToggle={event => { const open = event.currentTarget.open; setGroupOpen(previous => new Map(previous).set(key, open)) }}>
354
+ <summary>{t(group === 'command' ? 'toolPolicyCommandGroup' : group === 'plan' ? 'toolPolicyPlanGroup' : group === 'file' ? 'toolPolicyFileGroup' : 'toolPolicyOtherGroup')}
355
+ <span className="codex-tool-policy-note">{tools.length}{changes ? ` · ${changes} ${t('toolPolicyCustomized')}` : ''}</span></summary>{rows(tools)}
356
+ </details>
357
+ })}
358
+ {isDetails && inventory && !duplicate && rows(shown)}
359
+ {mode === 'prompts' && promptCatalog && <div className="codex-tool-policy-prompts">
360
+ {promptCatalog.sections.map(section => {
361
+ const editable = section.editable && isPromptName(section.name)
362
+ const override = rule?.promptOverrides?.find(entry => entry.name === section.name)
363
+ return <section key={section.name} className="codex-tool-policy-prompt" data-prompt-section={section.name}>
364
+ <h4>{section.label || section.name}</h4><code>{section.name}</code>
365
+ {editable ? <>
366
+ <textarea aria-label={`${t('settingsPresetPrompts')} ${section.name}`} rows={6} maxLength={1_000_000}
367
+ disabled={duplicate || !snapshot.writable || saving} value={override?.text ?? section.text} onChange={event => changePrompt(section, event.target.value)} />
368
+ <button type="button" aria-label={`${t('presetPromptRestore')} ${section.name}`} disabled={!override || duplicate || !snapshot.writable || saving} onClick={() => restorePrompt(section)}>{t('presetPromptRestore')}</button>
369
+ </> : <><span className="codex-tool-policy-note" title={section.reason}>{t('presetPromptReadOnly')}</span><pre>{section.text}</pre></>}
370
+ </section>
371
+ })}
372
+ </div>}
373
+ {currentDraft && <p className="codex-tool-policy-note" aria-label={t('toolPolicyDraftSummary')}>{t('toolPolicyDraftSummary')}: {changeSummary}</p>}
374
+ <div className="codex-tool-policy-actions"><button className="codex-tool-policy-primary" type="submit" disabled={!currentDraft}>{t(saving ? 'toolPolicySaving' : 'toolPolicySave')}</button>
375
+ <button type="button" disabled={!currentDraft} onClick={() => { setDrafts(previous => { const next = new Map(previous); next.delete(selectedId); return next }); setError(''); setNotice('') }}>{t('toolPolicyDiscard')}</button>
376
+ <span className="codex-tool-policy-note">{t('toolPolicyTiming')}</span></div>
377
+ </fieldset></form>
378
+ {!snapshot.writable && <p className="codex-tool-policy-note">{t('toolPolicyReadOnly')}</p>}{error && <p className="codex-tool-policy-error" role="alert">{error}</p>}{notice && <p className="codex-tool-policy-note" role="status">{notice}</p>}
379
+ </section>
380
+ }
@@ -0,0 +1,112 @@
1
+ /** Codex-aware `/compact` command with an optional transport preference. */
2
+
3
+ import type { Context } from '@deepseek-ai/cordis'
4
+ import { ManualCompactionError } from '@deepseek-ai/dsh-compaction'
5
+ import type { Agent } from '@deepseek-ai/dsh-agent'
6
+ import { runCodexCompactionMode, type CodexCompactionMode } from './compaction.ts'
7
+
8
+ const USAGE = 'Usage: /compact [remote|local]'
9
+
10
+ interface CommandInvocation {
11
+ commandId: string
12
+ agent: Agent
13
+ rawInput: string
14
+ signal: AbortSignal
15
+ }
16
+
17
+ type CommandResult = {
18
+ kind: 'success'
19
+ text?: string
20
+ sourceEventSeq?: number
21
+ } | {
22
+ kind: 'error'
23
+ text: string
24
+ }
25
+
26
+ interface CommandsRuntime {
27
+ register(definition: {
28
+ name: string
29
+ description: string
30
+ input: { hint: string }
31
+ handler: (invocation: CommandInvocation) => CommandResult | Promise<CommandResult>
32
+ }): () => void
33
+ }
34
+
35
+ type CommandContext = Context & { commands: CommandsRuntime }
36
+
37
+ /** Convert expected backend failures into the same concise command results as DSH Core. */
38
+ function expectedFailure(error: ManualCompactionError): CommandResult {
39
+ switch (error.code) {
40
+ case 'busy':
41
+ return { kind: 'error', text: 'Compaction is unavailable because this process has an active compaction, or the agent is not idle.' }
42
+ case 'cancelled':
43
+ return { kind: 'error', text: 'Compaction cancelled.' }
44
+ case 'changed':
45
+ return { kind: 'error', text: 'Compaction could not replace the selected history because it changed. The conversation is unchanged.' }
46
+ case 'summary':
47
+ return { kind: 'error', text: 'Compaction could not produce a useful summary. The conversation is unchanged; the attempt is recorded in the session log.' }
48
+ case 'commit':
49
+ return { kind: 'error', text: 'Compaction did not finish cleanly; inspect the current session state before retrying.' }
50
+ case 'persistence':
51
+ return { kind: 'error', text: 'Compaction finished, but the session could not be saved.' }
52
+ default:
53
+ return { kind: 'error', text: `Unknown compaction failure: ${String(error.code)}` }
54
+ }
55
+ }
56
+
57
+ function modeOf(rawInput: string): CodexCompactionMode | undefined | 'invalid' {
58
+ const value = rawInput.trim().toLowerCase()
59
+ if (value === '') return undefined
60
+ if (value === 'remote' || value === 'local') return value
61
+ return 'invalid'
62
+ }
63
+
64
+ async function executeCompact(ctx: Context, invocation: CommandInvocation): Promise<CommandResult> {
65
+ const mode = modeOf(invocation.rawInput)
66
+ if (mode === 'invalid') return { kind: 'error', text: USAGE }
67
+ const compact = () => ctx.compaction.compactNow(
68
+ invocation.agent,
69
+ invocation.signal,
70
+ invocation.commandId as Parameters<NonNullable<Context['compaction']>['compactNow']>[2],
71
+ )
72
+ try {
73
+ const result = mode === undefined ? await compact() : await runCodexCompactionMode(mode, compact)
74
+ if (result === null) return { kind: 'success', text: 'No compactable history yet.' }
75
+ return {
76
+ kind: 'success',
77
+ text: `Compacted ${result.shadowedSeqs.length} history items (~${result.shadowedTokenCount} tokens).`,
78
+ sourceEventSeq: result.summarySeq,
79
+ }
80
+ } catch (error) {
81
+ if (invocation.signal.aborted) return { kind: 'error', text: 'Compaction cancelled.' }
82
+ if (error instanceof ManualCompactionError) return expectedFailure(error)
83
+ throw error
84
+ }
85
+ }
86
+
87
+ /** Replace the Core command inside the Codex compaction scope. */
88
+ export function apply(ctx: Context): void {
89
+ const commands = (ctx as CommandContext).commands
90
+ const active = new Set<Promise<CommandResult>>()
91
+ const handler = (invocation: CommandInvocation): Promise<CommandResult> => {
92
+ const operation = executeCompact(ctx, invocation)
93
+ active.add(operation)
94
+ const retire = (): void => { active.delete(operation) }
95
+ operation.then(retire, retire)
96
+ return operation
97
+ }
98
+ ctx.effect(function* () {
99
+ yield async () => { await Promise.allSettled(active) }
100
+ yield commands.register({
101
+ name: 'compact',
102
+ description: 'Compact older conversation history, optionally using remote or local mode',
103
+ input: { hint: '[remote|local]' },
104
+ handler,
105
+ })
106
+ }, 'codex compact command lifecycle')
107
+ }
108
+
109
+ export const name = 'compact-command'
110
+ export const inject = ['commands', 'compaction']
111
+
112
+ export default { name, inject, apply }