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

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 (220) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +37 -59
  3. package/RELEASE.md +1 -1
  4. package/cordis.patch.yml +42 -11
  5. package/docs/preset-library.md +6 -12
  6. package/docs/tool-policy-benchmark.json +89 -89
  7. package/docs/tool-policy.md +11 -7
  8. package/lib/client.js +3780 -2950
  9. package/lib/compact-command.js +416 -0
  10. package/lib/compaction.js +129 -15
  11. package/lib/hybrid-executor.js +1196 -0
  12. package/lib/index.js +3554 -2841
  13. package/lib/preferences.js +17 -11
  14. package/lib/tool-policy.js +1930 -1743
  15. package/lib/typert.js +49 -89
  16. package/lib/types/client/activity.js +4 -3
  17. package/lib/types/client/desktop.d.ts +26 -2
  18. package/lib/types/client/desktop.js +143 -35
  19. package/lib/types/client/index.d.ts +136 -129
  20. package/lib/types/client/index.js +92 -466
  21. package/lib/types/client/policy-drafts.d.ts +1 -1
  22. package/lib/types/client/policy-locale.d.ts +260 -0
  23. package/lib/types/client/policy-locale.js +357 -0
  24. package/lib/types/client/preset-manager.d.ts +33 -15
  25. package/lib/types/client/preset-manager.js +220 -215
  26. package/lib/types/client/preset-requests.d.ts +2 -2
  27. package/lib/types/client/tool-policy.d.ts +6 -93
  28. package/lib/types/client/tool-policy.js +85 -143
  29. package/lib/types/contracts/preset-editor-schema.d.ts +78 -0
  30. package/lib/types/contracts/preset-editor-schema.js +95 -0
  31. package/lib/types/{prompt.js → contracts/prompt.js} +9 -5
  32. package/lib/types/{settings.d.ts → contracts/settings.d.ts} +8 -1
  33. package/lib/types/{settings.js → contracts/settings.js} +19 -3
  34. package/lib/types/{tool-policy-contract.d.ts → contracts/tool-policy-contract.d.ts} +9 -6
  35. package/lib/types/{tool-policy-contract.js → contracts/tool-policy-contract.js} +9 -2
  36. package/lib/types/contracts/ui-contracts.d.ts +92 -0
  37. package/lib/types/contracts/ui-contracts.js +83 -0
  38. package/lib/types/{client/entry.d.ts → entries/client.d.ts} +2 -2
  39. package/lib/types/{client/entry.js → entries/client.js} +2 -4
  40. package/lib/types/{compact-command.d.ts → entries/compact-command.d.ts} +2 -0
  41. package/lib/types/entries/compact-command.js +176 -0
  42. package/lib/types/{compaction.d.ts → entries/compaction.d.ts} +12 -0
  43. package/lib/types/{compaction.js → entries/compaction.js} +43 -11
  44. package/lib/types/entries/hybrid-executor.d.ts +19 -0
  45. package/lib/types/entries/hybrid-executor.js +57 -0
  46. package/lib/types/entries/index.d.ts +66 -0
  47. package/lib/types/entries/index.js +192 -0
  48. package/lib/types/{preferences.d.ts → entries/preferences.d.ts} +1 -1
  49. package/lib/types/{preferences.js → entries/preferences.js} +1 -1
  50. package/lib/types/entries/tool-policy.d.ts +97 -0
  51. package/lib/types/entries/tool-policy.js +158 -0
  52. package/lib/types/entries/typert.host.d.ts +23 -0
  53. package/lib/types/entries/typert.host.js +24 -0
  54. package/lib/types/hybrid/codex-hybrid-executor.d.ts +44 -0
  55. package/lib/types/hybrid/codex-hybrid-executor.js +257 -0
  56. package/lib/types/hybrid/hybrid-sdk.d.ts +13 -0
  57. package/lib/types/hybrid/hybrid-sdk.js +196 -0
  58. package/lib/types/hybrid/program-calls.d.ts +28 -0
  59. package/lib/types/hybrid/program-calls.js +193 -0
  60. package/lib/types/hybrid/subcall-scheduler.d.ts +90 -0
  61. package/lib/types/hybrid/subcall-scheduler.js +343 -0
  62. package/lib/types/policy/deferred-tools.d.ts +42 -0
  63. package/lib/types/policy/deferred-tools.js +264 -0
  64. package/lib/types/policy/overlay-installer.d.ts +12 -0
  65. package/lib/types/policy/overlay-installer.js +179 -0
  66. package/lib/types/policy/rule-resolver.d.ts +94 -0
  67. package/lib/types/policy/rule-resolver.js +114 -0
  68. package/lib/types/{tool-capabilities.d.ts → policy/tool-capabilities.d.ts} +3 -2
  69. package/lib/types/{tool-capabilities.js → policy/tool-capabilities.js} +6 -2
  70. package/lib/types/{activity.d.ts → presets/activity.d.ts} +2 -4
  71. package/lib/types/{activity.js → presets/activity.js} +2 -14
  72. package/lib/types/{desktop-preset.d.ts → presets/desktop-preset.d.ts} +3 -1
  73. package/lib/types/{desktop-preset.js → presets/desktop-preset.js} +6 -2
  74. package/lib/types/presets/preset-editor.d.ts +47 -0
  75. package/lib/types/presets/preset-editor.js +81 -0
  76. package/lib/types/{preset-prompt-catalog.d.ts → presets/preset-prompt-catalog.d.ts} +3 -1
  77. package/lib/types/{preset-prompt-catalog.js → presets/preset-prompt-catalog.js} +27 -4
  78. package/lib/types/{preset-tool-catalog.d.ts → presets/preset-tool-catalog.d.ts} +1 -1
  79. package/lib/types/{preset-tool-catalog.js → presets/preset-tool-catalog.js} +11 -4
  80. package/lib/types/presets/runtime-enhancements.d.ts +45 -0
  81. package/lib/types/presets/runtime-enhancements.js +349 -0
  82. package/lib/types/presets/small-window-compaction.d.ts +15 -0
  83. package/lib/types/presets/small-window-compaction.js +121 -0
  84. package/lib/types/responses/compact-checkpoint.d.ts +27 -0
  85. package/lib/types/responses/compact-checkpoint.js +257 -0
  86. package/lib/types/responses/fetch-transport.d.ts +16 -0
  87. package/lib/types/responses/fetch-transport.js +257 -0
  88. package/lib/types/responses/remote-compact.d.ts +13 -0
  89. package/lib/types/responses/remote-compact.js +319 -0
  90. package/lib/types/responses/sse-diagnostics.d.ts +9 -0
  91. package/lib/types/responses/sse-diagnostics.js +157 -0
  92. package/lib/types/responses/wire-rewrite.d.ts +35 -0
  93. package/lib/types/responses/wire-rewrite.js +237 -0
  94. package/lib/types/tools/exec-output.d.ts +58 -0
  95. package/lib/types/tools/exec-output.js +173 -0
  96. package/lib/types/tools/exec-plan-tools.d.ts +37 -0
  97. package/lib/types/tools/exec-plan-tools.js +265 -0
  98. package/lib/types/tools/exec-runner.d.ts +21 -0
  99. package/lib/types/tools/exec-runner.js +385 -0
  100. package/lib/types/tools/patch-tool.d.ts +16 -0
  101. package/lib/types/tools/patch-tool.js +258 -0
  102. package/lib/types/{patch.d.ts → tools/patch.d.ts} +1 -1
  103. package/lib/types/{patch.js → tools/patch.js} +96 -21
  104. package/locale/hybrid-executor/en.json +6 -0
  105. package/locale/hybrid-executor/zh.json +6 -0
  106. package/package.json +211 -289
  107. package/presets/{codex-collaboration → codex-hybrid}/agent.cordis.yml +45 -48
  108. package/presets/codex-hybrid/preset.yml +3 -0
  109. package/scripts/benchmark-tool-policy.mjs +3 -3
  110. package/scripts/build-preset.mjs +5 -5
  111. package/src/client/activity.ts +4 -3
  112. package/src/client/desktop.tsx +165 -51
  113. package/src/client/index.tsx +128 -709
  114. package/src/client/policy-drafts.ts +1 -1
  115. package/src/client/policy-locale.ts +362 -0
  116. package/src/client/preset-manager.tsx +331 -236
  117. package/src/client/preset-requests.ts +2 -2
  118. package/src/client/tool-policy.tsx +225 -203
  119. package/src/contracts/preset-editor-schema.ts +110 -0
  120. package/src/{prompt.ts → contracts/prompt.ts} +9 -5
  121. package/src/{settings.ts → contracts/settings.ts} +27 -3
  122. package/src/{tool-policy-contract.ts → contracts/tool-policy-contract.ts} +24 -7
  123. package/src/contracts/ui-contracts.ts +173 -0
  124. package/src/{client/entry.tsx → entries/client.tsx} +2 -4
  125. package/src/entries/compact-command.ts +256 -0
  126. package/src/{compaction.ts → entries/compaction.ts} +47 -19
  127. package/src/entries/hybrid-executor.ts +76 -0
  128. package/src/entries/index.ts +298 -0
  129. package/src/{preferences.ts → entries/preferences.ts} +1 -1
  130. package/src/entries/tool-policy.ts +162 -0
  131. package/src/entries/typert.host.ts +29 -0
  132. package/src/hybrid/codex-hybrid-executor.ts +310 -0
  133. package/src/hybrid/hybrid-sdk.ts +217 -0
  134. package/src/hybrid/program-calls.ts +202 -0
  135. package/src/hybrid/subcall-scheduler.ts +446 -0
  136. package/src/policy/deferred-tools.ts +331 -0
  137. package/src/policy/overlay-installer.ts +191 -0
  138. package/src/policy/rule-resolver.ts +128 -0
  139. package/src/{tool-capabilities.ts → policy/tool-capabilities.ts} +16 -4
  140. package/src/{activity.ts → presets/activity.ts} +4 -16
  141. package/src/{desktop-preset.ts → presets/desktop-preset.ts} +7 -2
  142. package/src/presets/preset-editor.ts +101 -0
  143. package/src/{preset-prompt-catalog.ts → presets/preset-prompt-catalog.ts} +35 -5
  144. package/src/{preset-tool-catalog.ts → presets/preset-tool-catalog.ts} +12 -5
  145. package/src/presets/runtime-enhancements.ts +415 -0
  146. package/src/presets/small-window-compaction.ts +166 -0
  147. package/src/responses/compact-checkpoint.ts +264 -0
  148. package/src/responses/fetch-transport.ts +290 -0
  149. package/src/responses/remote-compact.ts +393 -0
  150. package/src/responses/sse-diagnostics.ts +156 -0
  151. package/src/responses/wire-rewrite.ts +261 -0
  152. package/src/tools/exec-output.ts +211 -0
  153. package/src/tools/exec-plan-tools.ts +307 -0
  154. package/src/tools/exec-runner.ts +445 -0
  155. package/src/tools/patch-tool.ts +331 -0
  156. package/src/{patch.ts → tools/patch.ts} +90 -20
  157. package/tsdown.config.ts +8 -8
  158. package/lib/installer.js +0 -281
  159. package/lib/invariant.js +0 -23
  160. package/lib/types/activity-types.d.ts +0 -6
  161. package/lib/types/activity-types.js +0 -3
  162. package/lib/types/client/preset-copy.d.ts +0 -43
  163. package/lib/types/client/preset-copy.js +0 -83
  164. package/lib/types/client/session.d.ts +0 -6
  165. package/lib/types/client/session.js +0 -9
  166. package/lib/types/compact-command.js +0 -79
  167. package/lib/types/context.d.ts +0 -8
  168. package/lib/types/context.js +0 -14
  169. package/lib/types/exec.d.ts +0 -50
  170. package/lib/types/exec.js +0 -491
  171. package/lib/types/host-settings.d.ts +0 -4
  172. package/lib/types/host-settings.js +0 -13
  173. package/lib/types/index.d.ts +0 -113
  174. package/lib/types/index.js +0 -851
  175. package/lib/types/installer.d.ts +0 -27
  176. package/lib/types/installer.js +0 -155
  177. package/lib/types/invariant.d.ts +0 -16
  178. package/lib/types/invariant.js +0 -22
  179. package/lib/types/preset-contract.d.ts +0 -69
  180. package/lib/types/preset-contract.js +0 -22
  181. package/lib/types/preset-editor-remote.d.ts +0 -32
  182. package/lib/types/preset-editor-remote.js +0 -41
  183. package/lib/types/preset-editor.d.ts +0 -74
  184. package/lib/types/preset-editor.js +0 -587
  185. package/lib/types/preset-prompt-catalog-schema.d.ts +0 -16
  186. package/lib/types/preset-prompt-catalog-schema.js +0 -11
  187. package/lib/types/preset-prompt-contract.d.ts +0 -22
  188. package/lib/types/preset-prompt-contract.js +0 -3
  189. package/lib/types/preset-tool-catalog-schema.d.ts +0 -38
  190. package/lib/types/preset-tool-catalog-schema.js +0 -28
  191. package/lib/types/prompt-sections.d.ts +0 -15
  192. package/lib/types/prompt-sections.js +0 -29
  193. package/lib/types/remote.d.ts +0 -40
  194. package/lib/types/remote.js +0 -698
  195. package/lib/types/tool-policy.d.ts +0 -171
  196. package/lib/types/tool-policy.js +0 -367
  197. package/lib/types/typert.host.d.ts +0 -47
  198. package/lib/types/typert.host.js +0 -109
  199. package/presets/codex-collaboration/preset.yml +0 -3
  200. package/src/activity-types.ts +0 -7
  201. package/src/client/preset-copy.ts +0 -83
  202. package/src/client/session.ts +0 -11
  203. package/src/compact-command.ts +0 -112
  204. package/src/context.ts +0 -15
  205. package/src/exec.ts +0 -570
  206. package/src/host-settings.ts +0 -17
  207. package/src/index.ts +0 -1097
  208. package/src/installer.ts +0 -172
  209. package/src/invariant.ts +0 -34
  210. package/src/preset-contract.ts +0 -85
  211. package/src/preset-editor-remote.ts +0 -41
  212. package/src/preset-editor.ts +0 -502
  213. package/src/preset-prompt-catalog-schema.ts +0 -10
  214. package/src/preset-prompt-contract.ts +0 -21
  215. package/src/preset-tool-catalog-schema.ts +0 -28
  216. package/src/prompt-sections.ts +0 -33
  217. package/src/remote.ts +0 -748
  218. package/src/tool-policy.ts +0 -388
  219. package/src/typert.host.ts +0 -119
  220. /package/lib/types/{prompt.d.ts → contracts/prompt.d.ts} +0 -0
@@ -0,0 +1,331 @@
1
+ /** Progressive deferred tool activation (`deferLoading: true`) and preset defaults. */
2
+ import type { Context } from '@deepseek-ai/cordis'
3
+ import type { Agent } from '@deepseek-ai/dsh-agent'
4
+ import type {} from '@deepseek-ai/dsh-compaction/types'
5
+ import { scopeChainOf, scopeOf } from '@deepseek-ai/dsh-scope'
6
+ import type { ScopeKey } from '@deepseek-ai/dsh-scope'
7
+ import type {} from '@deepseek-ai/dsh-session'
8
+ import type {} from '@deepseek-ai/dsh-system-prompt'
9
+ import { defineTool } from '@deepseek-ai/dsh-tools'
10
+ import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
11
+
12
+ export const ACTIVATE_TOOLS_NAME = 'activate_tools'
13
+ export const CODEX_HYBRID_DEFAULTS_SERVICE = 'codexHybridDefaults' as const
14
+ export const DEFERRED_RECENT_TURN_WINDOW = 2
15
+
16
+ export interface CodexHybridDefaults {
17
+ readonly deferredTools: ReadonlySet<string>
18
+ readonly hiddenTools?: ReadonlySet<string>
19
+ }
20
+
21
+ declare module '@deepseek-ai/cordis' {
22
+ interface Context {
23
+ codexHybridDefaults?: CodexHybridDefaults
24
+ }
25
+ }
26
+
27
+ type SystemPromptService = Context['systemPrompt']
28
+ type ToolsService = Context['tools']
29
+
30
+ // Bundled entry points (`hybrid-executor.js`, `tool-policy.js`, `index.js`) load
31
+ // separately in DSH; share preset scope defaults on globalThis just like tool ownership.
32
+ const HYBRID_DEFAULTS_KEY = Symbol.for('@shuind/dsh-codex-harness:hybrid-defaults:v1')
33
+ const HYBRID_HIDDEN_KEY = Symbol.for('@shuind/dsh-codex-harness:hybrid-hidden:v1')
34
+
35
+ function scopeSetMap(registryKey: symbol): WeakMap<ScopeKey, ReadonlySet<string>> {
36
+ const registry = globalThis as unknown as Record<PropertyKey, unknown>
37
+ const existing = registry[registryKey]
38
+ if (existing instanceof WeakMap) return existing as WeakMap<ScopeKey, ReadonlySet<string>>
39
+ const created = new WeakMap<ScopeKey, ReadonlySet<string>>()
40
+ registry[registryKey] = created
41
+ return created
42
+ }
43
+
44
+ function registerScopedToolSet(
45
+ ctx: Context,
46
+ registryKey: symbol,
47
+ toolNames: ReadonlySet<string>,
48
+ serviceKey?: 'deferredTools' | 'hiddenTools',
49
+ ): () => void {
50
+ const copy = new Set(toolNames)
51
+ const scope = scopeOf(ctx)
52
+ const disposers: Array<() => void> = []
53
+ if (scope !== undefined) {
54
+ const map = scopeSetMap(registryKey)
55
+ map.set(scope, copy)
56
+ disposers.push(() => {
57
+ if (map.get(scope) === copy) map.delete(scope)
58
+ })
59
+ } else if (serviceKey === 'deferredTools' && typeof (ctx as Partial<Context>).provide === 'function') {
60
+ ctx.provide(CODEX_HYBRID_DEFAULTS_SERVICE, { deferredTools: copy })
61
+ }
62
+ return () => {
63
+ for (const dispose of disposers.splice(0).reverse()) dispose()
64
+ }
65
+ }
66
+
67
+ function readScopedToolSet(
68
+ ctx: Context,
69
+ registryKey: symbol,
70
+ serviceKey: 'deferredTools' | 'hiddenTools',
71
+ scope: ScopeKey | undefined = scopeOf(ctx),
72
+ ): ReadonlySet<string> | undefined {
73
+ const service = typeof (ctx as Partial<Context>).get === 'function'
74
+ ? ctx.get(CODEX_HYBRID_DEFAULTS_SERVICE)
75
+ : undefined
76
+ const direct = service?.[serviceKey]
77
+ if (direct !== undefined) return direct
78
+ if (scope === undefined) return undefined
79
+ const map = scopeSetMap(registryKey)
80
+ for (const key of scopeChainOf(scope)) {
81
+ const entry = map.get(key)
82
+ if (entry !== undefined) return entry
83
+ }
84
+ return undefined
85
+ }
86
+
87
+ /** Register preset-level default deferred tools for descendant Agent and catalog scopes. */
88
+ export function registerHybridDefaultDeferredTools(
89
+ ctx: Context,
90
+ deferredTools: ReadonlySet<string>,
91
+ ): () => void {
92
+ return registerScopedToolSet(ctx, HYBRID_DEFAULTS_KEY, deferredTools, 'deferredTools')
93
+ }
94
+
95
+ /** Read default deferred tool names from ancestor scopes or injected defaults service. */
96
+ export function readDefaultDeferredTools(
97
+ ctx: Context,
98
+ scope: ScopeKey | undefined = scopeOf(ctx),
99
+ ): ReadonlySet<string> | undefined {
100
+ return readScopedToolSet(ctx, HYBRID_DEFAULTS_KEY, 'deferredTools', scope)
101
+ }
102
+
103
+ /** Register preset-level hidden tools for descendant Agent and catalog scopes. */
104
+ export function registerHybridDefaultHiddenTools(
105
+ ctx: Context,
106
+ hiddenTools: ReadonlySet<string>,
107
+ ): () => void {
108
+ return registerScopedToolSet(ctx, HYBRID_HIDDEN_KEY, hiddenTools, 'hiddenTools')
109
+ }
110
+
111
+ /** Read default hidden tool names from ancestor scopes or injected defaults service. */
112
+ export function readDefaultHiddenTools(
113
+ ctx: Context,
114
+ scope: ScopeKey | undefined = scopeOf(ctx),
115
+ ): ReadonlySet<string> | undefined {
116
+ return readScopedToolSet(ctx, HYBRID_HIDDEN_KEY, 'hiddenTools', scope)
117
+ }
118
+
119
+ const MAX_SUMMARY_CHARS = 140
120
+
121
+ /** Collapse a tool description to a single-line summary capped for prompt stability. */
122
+ export function summarizeToolDescription(description: string): string {
123
+ const firstLine = description.trim().split(/\r?\n/u)[0] ?? ''
124
+ const collapsed = firstLine.replace(/\s+/gu, ' ').trim()
125
+ if (collapsed.length === 0) return 'No description provided.'
126
+ const sentenceEnd = collapsed.search(/[.!?。!?](?:\s|$)/u)
127
+ const sentence = sentenceEnd >= 0 ? collapsed.slice(0, sentenceEnd + 1).trim() : collapsed
128
+ if (sentence.length <= MAX_SUMMARY_CHARS) return sentence
129
+ return `${sentence.slice(0, MAX_SUMMARY_CHARS - 3).trimEnd()}...`
130
+ }
131
+
132
+ /** Deterministic catalog guidance naming every deferred tool for `activate_tools`. */
133
+ export function buildDeferredToolsGuidance(definitions: readonly ToolDefinition[]): string {
134
+ const sorted = [...definitions].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
135
+ const lines = [
136
+ `Deferred tools are omitted until activated. Call \`${ACTIVATE_TOOLS_NAME}\` with exact names to enable them on the next model step (do not call a deferred tool in the same step):`,
137
+ ...sorted.map(def => `- \`${def.name}\`: ${summarizeToolDescription(def.description)}`),
138
+ ]
139
+ return lines.join('\n')
140
+ }
141
+
142
+ interface ActivateToolsOutput {
143
+ activated: string[]
144
+ alreadyActive: string[]
145
+ unknown: string[]
146
+ }
147
+
148
+ interface PendingDeferredCompaction {
149
+ compactionId: string
150
+ cold: Set<string>
151
+ hasSummary: boolean
152
+ }
153
+
154
+ function wrapDeferredExecution(
155
+ definition: ToolDefinition,
156
+ onTouch: (name: string) => void,
157
+ ): ToolDefinition {
158
+ const descriptors = Object.getOwnPropertyDescriptors(definition)
159
+ descriptors.execute = {
160
+ value(this: unknown, args: unknown, exec: Parameters<ToolDefinition['execute']>[1]) {
161
+ onTouch(definition.name)
162
+ return Reflect.apply(definition.execute, this, [args, exec])
163
+ },
164
+ enumerable: true,
165
+ configurable: true,
166
+ }
167
+ return Object.defineProperties(
168
+ Object.create(Object.getPrototypeOf(definition)) as object,
169
+ descriptors,
170
+ ) as ToolDefinition
171
+ }
172
+
173
+ /** Build the per-Agent `activate_tools` capability that flips `when` admission on next step. */
174
+ export function createActivateToolsDefinition(
175
+ allowedDefinitions: ReadonlyMap<string, ToolDefinition>,
176
+ activated: Set<string>,
177
+ onTouch?: (name: string) => void,
178
+ ): ToolDefinition {
179
+ const availableNames = [...allowedDefinitions.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
180
+ return defineTool({
181
+ name: ACTIVATE_TOOLS_NAME,
182
+ description: 'Activate deferred tools by name so their schemas become callable on the next model step.',
183
+ parameters: {
184
+ names: {
185
+ type: 'array',
186
+ required: true,
187
+ items: { type: 'string' },
188
+ description: 'Exact deferred tool names to activate (1-32).',
189
+ },
190
+ },
191
+ isConcurrencySafe: () => true,
192
+ output: {
193
+ schema: {
194
+ type: 'object',
195
+ additionalProperties: false,
196
+ properties: {
197
+ activated: { type: 'array', required: true, items: { type: 'string' } },
198
+ alreadyActive: { type: 'array', required: true, items: { type: 'string' } },
199
+ unknown: { type: 'array', required: true, items: { type: 'string' } },
200
+ },
201
+ },
202
+ render: (_args, value): Array<{ type: 'text'; text: string }> => {
203
+ const lines: string[] = []
204
+ if (value.activated.length > 0) {
205
+ lines.push(`Activated for the next step: ${value.activated.join(', ')}. Wait for the next step before calling them.`)
206
+ }
207
+ if (value.alreadyActive.length > 0) {
208
+ lines.push(`Already active: ${value.alreadyActive.join(', ')}.`)
209
+ }
210
+ if (value.unknown.length > 0) {
211
+ const valid = availableNames.length > 0 ? availableNames.join(', ') : '(none)'
212
+ lines.push(`Unknown deferred tools: ${value.unknown.join(', ')}. Available: ${valid}.`)
213
+ }
214
+ return [{ type: 'text', text: lines.length > 0 ? lines.join('\n') : 'No tools activated.' }]
215
+ },
216
+ },
217
+ async execute(args): Promise<ActivateToolsOutput> {
218
+ const names = args.names
219
+ if (!Array.isArray(names) || names.length < 1 || names.length > 32) {
220
+ throw new Error(`${ACTIVATE_TOOLS_NAME}: names must contain between 1 and 32 tool names`)
221
+ }
222
+ const seen = new Set<string>()
223
+ const newlyActivated: string[] = []
224
+ const alreadyActive: string[] = []
225
+ const unknown: string[] = []
226
+ for (const raw of names) {
227
+ if (typeof raw !== 'string') {
228
+ throw new Error(`${ACTIVATE_TOOLS_NAME}: every entry in names must be a string`)
229
+ }
230
+ const name = raw.trim()
231
+ if (name.length === 0) {
232
+ throw new Error(`${ACTIVATE_TOOLS_NAME}: tool names must be non-empty strings`)
233
+ }
234
+ if (seen.has(name)) continue
235
+ seen.add(name)
236
+ if (!allowedDefinitions.has(name)) {
237
+ unknown.push(name)
238
+ } else if (activated.has(name)) {
239
+ onTouch?.(name)
240
+ alreadyActive.push(name)
241
+ } else {
242
+ activated.add(name)
243
+ onTouch?.(name)
244
+ newlyActivated.push(name)
245
+ }
246
+ }
247
+ return { activated: newlyActivated, alreadyActive, unknown }
248
+ },
249
+ })
250
+ }
251
+
252
+ /**
253
+ * Shadow deferred definitions with step-conditional admission and publish
254
+ * `activate_tools` + a deterministic prompt section inside the Agent scope.
255
+ * Cold tools untouched for more than `DEFERRED_RECENT_TURN_WINDOW` turns are
256
+ * reclaimed after local or remote compaction completes.
257
+ */
258
+ export function* yieldDeferredToolsOverlay(
259
+ tools: ToolsService,
260
+ systemPrompt: SystemPromptService,
261
+ definitions: readonly ToolDefinition[],
262
+ agent?: Pick<Agent, 'ctx' | 'session'>,
263
+ ): Generator<() => void, void, unknown> {
264
+ const sorted = [...definitions].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
265
+ if (sorted.length === 0) return
266
+ const activated = new Set<string>()
267
+ const allowedDefinitions = new Map<string, ToolDefinition>()
268
+ let currentTurn = typeof (agent?.ctx as Partial<Context> | undefined)?.get === 'function'
269
+ ? (agent!.ctx.get('agents')?.turnBoundaryOf(agent!.session).lastTurn ?? 0)
270
+ : 0
271
+ const lastTouchTurn = new Map<string, number>()
272
+ const touch = (name: string): void => {
273
+ lastTouchTurn.set(name, currentTurn)
274
+ }
275
+ const isCold = (name: string): boolean => {
276
+ const touched = lastTouchTurn.get(name)
277
+ return touched === undefined || currentTurn - touched > DEFERRED_RECENT_TURN_WINDOW
278
+ }
279
+ for (const definition of sorted) {
280
+ allowedDefinitions.set(definition.name, definition)
281
+ yield tools.register(wrapDeferredExecution(definition, touch), { when: () => activated.has(definition.name) })
282
+ }
283
+ yield tools.register(createActivateToolsDefinition(allowedDefinitions, activated, touch))
284
+ yield systemPrompt.section({
285
+ name: 'codex:deferred-tools',
286
+ order: 1018,
287
+ interpolate: false,
288
+ text: buildDeferredToolsGuidance(sorted),
289
+ })
290
+ if (agent !== undefined && typeof (agent.ctx as Partial<Context>).on === 'function') {
291
+ let pending: PendingDeferredCompaction | undefined
292
+ yield agent.ctx.on('session/event', (session, event) => {
293
+ if (session.id !== agent.session.id) return
294
+ if (event.type === 'turn/start') {
295
+ if (typeof event.data.turn === 'number' && event.data.turn > currentTurn) {
296
+ currentTurn = event.data.turn
297
+ }
298
+ return
299
+ }
300
+ if (event.type === 'compaction/start') {
301
+ if (typeof event.data.turn === 'number' && event.data.turn > currentTurn) {
302
+ currentTurn = event.data.turn
303
+ }
304
+ // Snapshot cold candidates before compaction; keep activated unchanged
305
+ // until compaction/end so the compaction request retains its warm KV prefix.
306
+ pending = {
307
+ compactionId: event.data.compactionId,
308
+ cold: new Set([...activated].filter(isCold)),
309
+ hasSummary: false,
310
+ }
311
+ return
312
+ }
313
+ if (event.type === 'compaction/summary') {
314
+ if (pending === undefined || event.data.compactionId !== pending.compactionId) return
315
+ pending.hasSummary = true
316
+ return
317
+ }
318
+ if (event.type === 'compaction/end') {
319
+ if (pending === undefined || event.data.compactionId !== pending.compactionId) return
320
+ const current = pending
321
+ pending = undefined
322
+ if (event.data.error !== undefined || !current.hasSummary) return
323
+ for (const name of current.cold) {
324
+ if (!isCold(name)) continue
325
+ activated.delete(name)
326
+ lastTouchTurn.delete(name)
327
+ }
328
+ }
329
+ }, { global: true })
330
+ }
331
+ }
@@ -0,0 +1,191 @@
1
+ /** Atomic per-Agent tool mask, Codex adapter replacement, prompt override, and defer overlay installer. */
2
+
3
+ import type { Agent } from '@deepseek-ai/dsh-agent'
4
+ import { scopeOf, scopeParentOf } from '@deepseek-ai/dsh-scope'
5
+ import type {} from '@deepseek-ai/dsh-tools'
6
+ import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
7
+ import { effectiveToolAction, legacyToolAction } from '../contracts/tool-policy-contract.ts'
8
+ import type { LegacyCapabilities } from '../contracts/tool-policy-contract.ts'
9
+ import { matchesPromptRevision } from '../presets/preset-prompt-catalog.ts'
10
+ import type { PreparedPromptOverride } from '../presets/preset-prompt-catalog.ts'
11
+ import { registerCodexExecAndPlan } from '../tools/exec-plan-tools.ts'
12
+ import { ACTIVATE_TOOLS_NAME, readDefaultDeferredTools, readDefaultHiddenTools, yieldDeferredToolsOverlay } from './deferred-tools.ts'
13
+ import type { ResolvedRule } from './rule-resolver.ts'
14
+ import { codexToolMetadata } from './tool-capabilities.ts'
15
+
16
+ /**
17
+ * Install only through an exact Agent scope. Replacement is deliberately limited
18
+ * to builtin source names: arbitrary tools, argument adapters, and third-party
19
+ * name-specific tools/pre-execute policy are not made equivalent by this overlay.
20
+ */
21
+ export function installOverlay(
22
+ agent: Agent,
23
+ rule: ResolvedRule,
24
+ legacyCapabilities: Readonly<LegacyCapabilities>,
25
+ preparedPrompts: PreparedPromptOverride | undefined,
26
+ onDispose: () => void,
27
+ ): () => void {
28
+ if (scopeOf(agent.ctx) !== agent) {
29
+ throw new Error('codex-tool-policy: an exact Agent scope is required')
30
+ }
31
+ if (preparedPrompts !== undefined && (scopeParentOf(agent) !== preparedPrompts.scope
32
+ || !matchesPromptRevision(agent.ctx, rule.preset, preparedPrompts))) throw new Error('preset-prompt-revision-mismatch')
33
+ const tools = agent.ctx.get('tools')
34
+ if (tools === undefined) throw new Error('codex-tool-policy: the Agent has no tools service')
35
+ const upstream = scopeParentOf(agent)
36
+ for (const choice of rule.tools ?? []) {
37
+ if (tools.get(choice.name, agent) === undefined) {
38
+ throw new Error(`codex-tool-policy: unknown or unavailable source tool ${JSON.stringify(choice.name)} in explicit choice`)
39
+ }
40
+ }
41
+ for (const tool of [...rule.allow ?? [], ...rule.deny ?? [], ...rule.tools?.map(choice => choice.name) ?? []]) {
42
+ const visible = tools.get(tool, agent)
43
+ if (visible !== undefined && tools.get(tool, upstream) !== visible) {
44
+ throw new Error(`codex-tool-policy: cannot restrict Agent-local tool ${JSON.stringify(tool)}`)
45
+ }
46
+ }
47
+
48
+ // Explicit source choices override both legacy masks and category defaults.
49
+ // They can widen this rule's own allowlist, never another owner's restriction.
50
+ const allow = rule.allow === undefined ? undefined : new Set(rule.allow)
51
+ const deny = new Set(rule.deny)
52
+ let hasDeny = rule.deny !== undefined
53
+ for (const choice of rule.tools ?? []) {
54
+ if (choice.action === 'hide') {
55
+ deny.add(choice.name)
56
+ hasDeny = true
57
+ allow?.delete(choice.name)
58
+ } else {
59
+ deny.delete(choice.name)
60
+ allow?.add(choice.name)
61
+ }
62
+ }
63
+ const defaultHiddenSet = readDefaultHiddenTools(agent.ctx, agent)
64
+ for (const hiddenName of defaultHiddenSet ?? []) {
65
+ const visible = tools.get(hiddenName, agent)
66
+ if (visible !== undefined && tools.get(hiddenName, upstream) === visible
67
+ && !rule.tools?.some(choice => choice.name === hiddenName)) {
68
+ deny.add(hiddenName)
69
+ hasDeny = true
70
+ allow?.delete(hiddenName)
71
+ }
72
+ }
73
+ const defaultDeferredSet = readDefaultDeferredTools(agent.ctx, agent)
74
+ const actionFor = (name: string) => {
75
+ const definition = tools.get(name, agent)
76
+ const codexTool = definition === undefined ? undefined : codexToolMetadata(definition)
77
+ return effectiveToolAction(rule, name, {
78
+ legacyCapabilities,
79
+ ...(codexTool === undefined ? {} : { codexTool }),
80
+ ...(defaultDeferredSet?.has(name) ? { defaultDeferred: true } : {}),
81
+ })
82
+ }
83
+ // Preserve an old replacement whose shared Codex capability was off: its
84
+ // source stays hidden, but no unavailable adapter is installed. Explicit
85
+ // per-source replacements bypass that compatibility baseline as one plan.
86
+ for (const name of ['bash', 'pwsh', 'todo_write', 'edit', 'write']) {
87
+ const oldAction = legacyToolAction(rule, name)
88
+ if (tools.get(name, agent) !== undefined
89
+ && (oldAction === 'codex-exec' || oldAction === 'codex-plan' || oldAction === 'codex-patch')
90
+ && actionFor(name) === 'hide') {
91
+ deny.add(name)
92
+ hasDeny = true
93
+ allow?.delete(name)
94
+ }
95
+ }
96
+ const mask = {
97
+ ...(allow === undefined ? {} : { allow: [...allow] }),
98
+ ...(!hasDeny ? {} : { deny: [...deny] }),
99
+ }
100
+ const permitted = (tool: string): boolean => (allow === undefined || allow.has(tool)) && !deny.has(tool)
101
+ const shells = ['bash', 'pwsh'].filter(tool => actionFor(tool) === 'codex-exec'
102
+ && permitted(tool) && tools.get(tool, agent) !== undefined)
103
+ const plan = actionFor('todo_write') === 'codex-plan'
104
+ && permitted('todo_write') && tools.get('todo_write', agent) !== undefined
105
+ const patches = ['edit', 'write'].filter(tool => actionFor(tool) === 'codex-patch'
106
+ && permitted(tool) && tools.get(tool, agent) !== undefined)
107
+ const sources = [...shells, ...(plan ? ['todo_write'] : []), ...patches]
108
+ const deferredDefinitions: ToolDefinition[] = tools.definitions(upstream).filter(definition =>
109
+ definition.name !== ACTIVATE_TOOLS_NAME
110
+ && actionFor(definition.name) === 'defer'
111
+ && permitted(definition.name)
112
+ && !sources.includes(definition.name)
113
+ && tools.get(definition.name, agent) !== undefined)
114
+
115
+ for (const tool of sources) {
116
+ const definition = tools.get(tool, agent)
117
+ // `when` is registration-owned and cannot be copied from a ToolDefinition.
118
+ // Without a step toolSet, executable() rejects every conditional registration.
119
+ if (tools.executable(tool, agent) !== definition) {
120
+ throw new Error(`codex-tool-policy: cannot replace conditional source tool ${JSON.stringify(tool)}; its activation condition must not be discarded`)
121
+ }
122
+ if (tools.get(tool, upstream) !== definition) {
123
+ throw new Error(`codex-tool-policy: cannot replace Agent-local source tool ${JSON.stringify(tool)}`)
124
+ }
125
+ }
126
+ for (const definition of deferredDefinitions) {
127
+ if (tools.executable(definition.name, agent) !== definition) {
128
+ throw new Error(`codex-tool-policy: cannot defer conditional source tool ${JSON.stringify(definition.name)}; its activation condition must not be discarded`)
129
+ }
130
+ if (tools.get(definition.name, upstream) !== definition) {
131
+ throw new Error(`codex-tool-policy: cannot defer Agent-local source tool ${JSON.stringify(definition.name)}`)
132
+ }
133
+ }
134
+ const additions = [
135
+ ...(shells.length > 0 ? ['exec_command', 'write_stdin'] : []),
136
+ ...(plan ? ['update_plan'] : []),
137
+ ...(patches.length > 0 ? ['apply_patch'] : []),
138
+ ...(deferredDefinitions.length > 0 ? [ACTIVATE_TOOLS_NAME] : []),
139
+ ]
140
+ for (const tool of additions) {
141
+ if (tools.get(tool, agent) !== undefined) {
142
+ throw new Error(`codex-tool-policy: replacement tool ${JSON.stringify(tool)} already exists; refusing to shadow another implementation`)
143
+ }
144
+ }
145
+ if (shells.length > 0 && agent.ctx.get('shell') === undefined) {
146
+ throw new Error('codex-tool-policy: builtin shell replacement requires the mounted shell capability')
147
+ }
148
+ if (patches.length > 0 && agent.ctx.get('fs') === undefined) {
149
+ throw new Error('codex-tool-policy: builtin file-edit replacement requires the mounted fs capability')
150
+ }
151
+ const needsPrompt = sources.length > 0 || deferredDefinitions.length > 0 || (preparedPrompts?.sections.length ?? 0) > 0
152
+ const systemPrompt = needsPrompt ? agent.ctx.get('systemPrompt') : undefined
153
+ if (needsPrompt && systemPrompt === undefined) {
154
+ throw new Error('codex-tool-policy: replacements require the mounted systemPrompt service')
155
+ }
156
+ const guidance = [
157
+ ...(shells.length === 0 ? [] : [`For this Agent, ${shells.join('/')} is replaced by exec_command and write_stdin. Follow their current schemas; command status uses exit_code (rendered as Process exited with code N), not the old shell status markers.`]),
158
+ ...(plan ? ['For this Agent, todo_write is replaced by update_plan. Follow its current schema; at most one plan item may be in_progress.'] : []),
159
+ ...(patches.length === 0 ? [] : [`For this Agent, ${patches.join('/')} is replaced by apply_patch. Edit or create files with Codex Begin/End Patch hunks instead of calling ${patches.join('/')}.`]),
160
+ ].join('\n')
161
+
162
+ // These registrations and the helper have synchronous disposers. Yield exact
163
+ // effects so a later refusal rolls back every earlier mask before it escapes.
164
+ const dispose = agent.ctx.effect(function* () {
165
+ yield onDispose
166
+ for (const section of preparedPrompts?.sections ?? []) yield systemPrompt!.section(section)
167
+ if (mask.allow !== undefined || mask.deny !== undefined) yield tools.restrict(mask)
168
+ // Own registrations are exempt from restrict(). Never leave an unhidden
169
+ // Agent-local source alongside a newly granted Codex capability.
170
+ for (const tool of mask.deny ?? []) {
171
+ if (tools.get(tool, agent) !== undefined) {
172
+ throw new Error(`codex-tool-policy: cannot hide Agent-local tool ${JSON.stringify(tool)}`)
173
+ }
174
+ }
175
+ if (sources.length > 0) {
176
+ yield tools.restrict({ deny: sources })
177
+ for (const tool of sources) {
178
+ if (tools.get(tool, agent) !== undefined) {
179
+ throw new Error(`codex-tool-policy: cannot hide Agent-local source tool ${JSON.stringify(tool)}`)
180
+ }
181
+ }
182
+ yield registerCodexExecAndPlan(agent.ctx, { terminal: shells.length > 0, plan, patch: patches.length > 0,
183
+ capabilityAuthority: { terminalToolsEnabled: shells.length > 0, planToolEnabled: plan, patchToolEnabled: patches.length > 0 } })
184
+ yield systemPrompt!.section({ name: 'codex:tool-policy', order: 1015, text: guidance })
185
+ }
186
+ if (deferredDefinitions.length > 0) {
187
+ yield* yieldDeferredToolsOverlay(tools, systemPrompt!, deferredDefinitions, agent)
188
+ }
189
+ }, `codex-tool-policy:${rule.preset}`)
190
+ return () => { void dispose() }
191
+ }
@@ -0,0 +1,128 @@
1
+ /** Schema, choice validation, and rule detaching for `codex-tool-policy`. */
2
+
3
+ import z from '@deepseek-ai/schemastery'
4
+ import { PRESET_PROMPT_NAMES } from '../contracts/ui-contracts.ts'
5
+ import type { PresetPromptOverride } from '../contracts/ui-contracts.ts'
6
+ import type { ToolActionRule, ToolPolicyRule } from '../contracts/tool-policy-contract.ts'
7
+ import { ACTIVATE_TOOLS_NAME } from './deferred-tools.ts'
8
+
9
+ export interface Config {
10
+ /** Empty by default: no preset or existing Agent is changed implicitly. */
11
+ rules?: readonly ToolPolicyRule[]
12
+ }
13
+
14
+ // Root volatility keeps saving future-Agent rules from unloading live overlays.
15
+ export const Config = z.object({
16
+ rules: z.array(z.object({
17
+ preset: z.string().required().description('Exact preset id; only Agents created after this plugin loads are affected.'),
18
+ // Bare Schemastery arrays default to []; a union preserves omitted masks.
19
+ allow: z.union([z.array(z.string())]).description('Inherited source names to keep. Omit for no allowlist; [] removes all inherited tools, including file tools.'),
20
+ deny: z.union([z.array(z.string())]).description('Inherited source names to remove; unknown and Agent-local names are rejected.'),
21
+ replaceShell: z.boolean().default(true).description('Legacy default: replace permitted builtin bash/pwsh with exec_command/write_stdin. Explicit source choices override it; third-party name-specific policy is not transferred.'),
22
+ replacePlan: z.boolean().default(true).description('Legacy default: replace permitted builtin todo_write with update_plan; explicit source choices override it.'),
23
+ replacePatch: z.boolean().default(false).description('Legacy default: replace permitted builtin edit/write with apply_patch; explicit source choices override it.'),
24
+ tools: z.union([z.array(z.object({
25
+ name: z.string().required().description('Exact inherited source tool name.'),
26
+ action: z.union([z.const('keep'), z.const('hide'), z.const('defer'), z.const('codex-exec'), z.const('codex-plan'), z.const('codex-patch')]).required()
27
+ .description('Per-tool override: keep/hide/defer any inherited tool; codex-exec only for bash/pwsh, codex-plan only for todo_write, and codex-patch only for edit/write.'),
28
+ }))]).description('Individual source choices, overriding allow/deny and legacy replacement defaults. Omission preserves legacy behavior.'),
29
+ promptOverrides: z.union([z.array(z.object({
30
+ name: z.union(PRESET_PROMPT_NAMES.map(name => z.const(name))).required(),
31
+ text: z.string().max(1_000_000).required(),
32
+ }))]).description('Exact current-preset prompt replacements. Order, interpolation and complete semantics remain Host-owned.'),
33
+ })).default([]),
34
+ }).volatile()
35
+
36
+ /** Loader activations receive a volatile reference; direct callers may pass plain rules. */
37
+ export type ToolPolicyConfigSource = Config | ReturnType<typeof Config>
38
+
39
+ export interface ResolvedRule extends ToolPolicyRule {
40
+ readonly replaceShell: boolean
41
+ readonly replacePlan: boolean
42
+ readonly replacePatch: boolean
43
+ }
44
+
45
+ /** Reject ambiguous/unsupported overrides before any Agent registrations change. */
46
+ function resolveToolChoices(input: readonly ToolActionRule[] | undefined): readonly ToolActionRule[] | undefined {
47
+ if (input === undefined) return undefined
48
+ if (!Array.isArray(input)) throw new TypeError('codex-tool-policy: tools must be an array of source choices')
49
+ const seen = new Set<string>()
50
+ const choices: ToolActionRule[] = []
51
+ for (const choice of input) {
52
+ if (choice === null || typeof choice !== 'object'
53
+ || typeof choice.name !== 'string' || choice.name.trim().length === 0) {
54
+ throw new TypeError('codex-tool-policy: every tool choice requires a non-empty source name')
55
+ }
56
+ if (seen.has(choice.name)) {
57
+ throw new Error(`codex-tool-policy: duplicate tool choice ${JSON.stringify(choice.name)}`)
58
+ }
59
+ seen.add(choice.name)
60
+ if (!['keep', 'hide', 'defer', 'codex-exec', 'codex-plan', 'codex-patch'].includes(choice.action)) {
61
+ throw new TypeError(`codex-tool-policy: invalid action for source tool ${JSON.stringify(choice.name)}`)
62
+ }
63
+ if (choice.action === 'defer' && choice.name === ACTIVATE_TOOLS_NAME) {
64
+ throw new Error(`codex-tool-policy: cannot defer reserved tool ${JSON.stringify(ACTIVATE_TOOLS_NAME)}`)
65
+ }
66
+ if (choice.action === 'codex-exec' && choice.name !== 'bash' && choice.name !== 'pwsh'
67
+ || choice.action === 'codex-plan' && choice.name !== 'todo_write'
68
+ || choice.action === 'codex-patch' && choice.name !== 'edit' && choice.name !== 'write') {
69
+ throw new Error(`codex-tool-policy: unsupported replacement ${JSON.stringify(choice.action)} for source tool ${JSON.stringify(choice.name)}`)
70
+ }
71
+ choices.push({ name: choice.name, action: choice.action })
72
+ }
73
+ return choices
74
+ }
75
+
76
+ function resolvePromptChoices(input: readonly PresetPromptOverride[] | undefined): readonly PresetPromptOverride[] | undefined {
77
+ if (input === undefined) return undefined
78
+ if (!Array.isArray(input) || input.length > PRESET_PROMPT_NAMES.length) throw new Error('invalid-preset-prompt-overrides')
79
+ const seen = new Set<string>()
80
+ return input.map(value => {
81
+ if (value === null || typeof value !== 'object' || !PRESET_PROMPT_NAMES.includes(value.name)
82
+ || typeof value.text !== 'string' || value.text.length > 1_000_000
83
+ || Object.keys(value).some(key => key !== 'name' && key !== 'text') || seen.has(value.name)) {
84
+ throw new Error('invalid-preset-prompt-override')
85
+ }
86
+ seen.add(value.name)
87
+ return { name: value.name, text: value.text }
88
+ })
89
+ }
90
+
91
+ /** Validate direct callers too, and detach configuration from later form mutations. */
92
+ export function resolveRules(config: Config): ReadonlyMap<string, ResolvedRule> {
93
+ const input = config.rules ?? []
94
+ if (!Array.isArray(input)) throw new TypeError('codex-tool-policy: rules must be an array')
95
+ const rules = new Map<string, ResolvedRule>()
96
+ for (const rule of input) {
97
+ if (rule === null || typeof rule !== 'object'
98
+ || typeof rule.preset !== 'string' || rule.preset.trim().length === 0) {
99
+ throw new TypeError('codex-tool-policy: every rule requires a non-empty preset id')
100
+ }
101
+ if (rules.has(rule.preset)) throw new Error(`codex-tool-policy: duplicate preset rule ${JSON.stringify(rule.preset)}`)
102
+ for (const key of ['allow', 'deny'] as const) {
103
+ const names = rule[key]
104
+ if (names !== undefined && (!Array.isArray(names)
105
+ || names.some(tool => typeof tool !== 'string' || tool.trim().length === 0))) {
106
+ throw new TypeError(`codex-tool-policy: ${key} must be an array of non-empty tool names`)
107
+ }
108
+ }
109
+ for (const key of ['replaceShell', 'replacePlan', 'replacePatch'] as const) {
110
+ if (rule[key] !== undefined && typeof rule[key] !== 'boolean') {
111
+ throw new TypeError(`codex-tool-policy: ${key} must be a boolean`)
112
+ }
113
+ }
114
+ const choices = resolveToolChoices(rule.tools)
115
+ const prompts = resolvePromptChoices(rule.promptOverrides)
116
+ rules.set(rule.preset, {
117
+ preset: rule.preset,
118
+ ...(rule.allow === undefined ? {} : { allow: [...rule.allow] }),
119
+ ...(rule.deny === undefined ? {} : { deny: [...rule.deny] }),
120
+ replaceShell: rule.replaceShell !== false,
121
+ replacePlan: rule.replacePlan !== false,
122
+ replacePatch: rule.replacePatch === true,
123
+ ...(choices === undefined ? {} : { tools: choices }),
124
+ ...(prompts === undefined ? {} : { promptOverrides: prompts }),
125
+ })
126
+ }
127
+ return rules
128
+ }