@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,367 @@
1
+ /** Opt-in Host overlays for future Agents; source presets and Persona stay untouched. */
2
+ import z from '@deepseek-ai/schemastery';
3
+ import { scopeOf, scopeParentOf } from '@deepseek-ai/dsh-scope';
4
+ import { registerCodexExecAndPlan } from "./index.js";
5
+ import { effectiveToolAction, legacyToolAction } from "./tool-policy-contract.js";
6
+ import { codexToolMetadata, readLegacyCapabilities } from "./tool-capabilities.js";
7
+ import { PRESET_PROMPT_NAMES } from "./preset-prompt-contract.js";
8
+ import { probePresetPrompts, preparePromptOverrides, matchesPromptRevision } from "./preset-prompt-catalog.js";
9
+ export const name = 'codex-tool-policy';
10
+ export const inject = ['tools', 'agents', 'agentPresets'];
11
+ // Root volatility keeps saving future-Agent rules from unloading live overlays.
12
+ export const Config = z.object({
13
+ rules: z.array(z.object({
14
+ preset: z.string().required().description('Exact preset id; only Agents created after this plugin loads are affected.'),
15
+ // Bare Schemastery arrays default to []; a union preserves omitted masks.
16
+ allow: z.union([z.array(z.string())]).description('Inherited source names to keep. Omit for no allowlist; [] removes all inherited tools, including file tools.'),
17
+ deny: z.union([z.array(z.string())]).description('Inherited source names to remove; unknown and Agent-local names are rejected.'),
18
+ 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.'),
19
+ replacePlan: z.boolean().default(true).description('Legacy default: replace permitted builtin todo_write with update_plan; explicit source choices override it.'),
20
+ tools: z.union([z.array(z.object({
21
+ name: z.string().required().description('Exact inherited source tool name.'),
22
+ action: z.union([z.const('keep'), z.const('hide'), z.const('codex-exec'), z.const('codex-plan')]).required()
23
+ .description('Per-tool override: keep/hide any inherited tool; codex-exec only for bash/pwsh and codex-plan only for todo_write.'),
24
+ }))]).description('Individual source choices, overriding allow/deny and legacy replacement defaults. Omission preserves legacy behavior.'),
25
+ promptOverrides: z.union([z.array(z.object({
26
+ name: z.union(PRESET_PROMPT_NAMES.map(name => z.const(name))).required(),
27
+ text: z.string().max(1_000_000).required(),
28
+ }))]).description('Exact current-preset prompt replacements. Order, interpolation and complete semantics remain Host-owned.'),
29
+ })).default([]),
30
+ }).volatile();
31
+ /** Reject ambiguous/unsupported overrides before any Agent registrations change. */
32
+ function resolveToolChoices(input) {
33
+ if (input === undefined)
34
+ return undefined;
35
+ if (!Array.isArray(input))
36
+ throw new TypeError('codex-tool-policy: tools must be an array of source choices');
37
+ const seen = new Set();
38
+ const choices = [];
39
+ for (const choice of input) {
40
+ if (choice === null || typeof choice !== 'object'
41
+ || typeof choice.name !== 'string' || choice.name.trim().length === 0) {
42
+ throw new TypeError('codex-tool-policy: every tool choice requires a non-empty source name');
43
+ }
44
+ if (seen.has(choice.name)) {
45
+ throw new Error(`codex-tool-policy: duplicate tool choice ${JSON.stringify(choice.name)}`);
46
+ }
47
+ seen.add(choice.name);
48
+ if (!['keep', 'hide', 'codex-exec', 'codex-plan'].includes(choice.action)) {
49
+ throw new TypeError(`codex-tool-policy: invalid action for source tool ${JSON.stringify(choice.name)}`);
50
+ }
51
+ if (choice.action === 'codex-exec' && choice.name !== 'bash' && choice.name !== 'pwsh'
52
+ || choice.action === 'codex-plan' && choice.name !== 'todo_write') {
53
+ throw new Error(`codex-tool-policy: unsupported replacement ${JSON.stringify(choice.action)} for source tool ${JSON.stringify(choice.name)}`);
54
+ }
55
+ choices.push({ name: choice.name, action: choice.action });
56
+ }
57
+ return choices;
58
+ }
59
+ function resolvePromptChoices(input) {
60
+ if (input === undefined)
61
+ return undefined;
62
+ if (!Array.isArray(input) || input.length > PRESET_PROMPT_NAMES.length)
63
+ throw new Error('invalid-preset-prompt-overrides');
64
+ const seen = new Set();
65
+ return input.map(value => {
66
+ if (value === null || typeof value !== 'object' || !PRESET_PROMPT_NAMES.includes(value.name)
67
+ || typeof value.text !== 'string' || value.text.length > 1_000_000
68
+ || Object.keys(value).some(key => key !== 'name' && key !== 'text') || seen.has(value.name)) {
69
+ throw new Error('invalid-preset-prompt-override');
70
+ }
71
+ seen.add(value.name);
72
+ return { name: value.name, text: value.text };
73
+ });
74
+ }
75
+ /** Validate direct callers too, and detach configuration from later form mutations. */
76
+ function resolveRules(config) {
77
+ const input = config.rules ?? [];
78
+ if (!Array.isArray(input))
79
+ throw new TypeError('codex-tool-policy: rules must be an array');
80
+ const rules = new Map();
81
+ for (const rule of input) {
82
+ if (rule === null || typeof rule !== 'object'
83
+ || typeof rule.preset !== 'string' || rule.preset.trim().length === 0) {
84
+ throw new TypeError('codex-tool-policy: every rule requires a non-empty preset id');
85
+ }
86
+ if (rules.has(rule.preset))
87
+ throw new Error(`codex-tool-policy: duplicate preset rule ${JSON.stringify(rule.preset)}`);
88
+ for (const key of ['allow', 'deny']) {
89
+ const names = rule[key];
90
+ if (names !== undefined && (!Array.isArray(names)
91
+ || names.some(tool => typeof tool !== 'string' || tool.trim().length === 0))) {
92
+ throw new TypeError(`codex-tool-policy: ${key} must be an array of non-empty tool names`);
93
+ }
94
+ }
95
+ for (const key of ['replaceShell', 'replacePlan']) {
96
+ if (rule[key] !== undefined && typeof rule[key] !== 'boolean') {
97
+ throw new TypeError(`codex-tool-policy: ${key} must be a boolean`);
98
+ }
99
+ }
100
+ const choices = resolveToolChoices(rule.tools);
101
+ const prompts = resolvePromptChoices(rule.promptOverrides);
102
+ rules.set(rule.preset, {
103
+ preset: rule.preset,
104
+ ...(rule.allow === undefined ? {} : { allow: [...rule.allow] }),
105
+ ...(rule.deny === undefined ? {} : { deny: [...rule.deny] }),
106
+ replaceShell: rule.replaceShell !== false,
107
+ replacePlan: rule.replacePlan !== false,
108
+ ...(choices === undefined ? {} : { tools: choices }),
109
+ ...(prompts === undefined ? {} : { promptOverrides: prompts }),
110
+ });
111
+ }
112
+ return rules;
113
+ }
114
+ /**
115
+ * Install only through an exact Agent scope. Replacement is deliberately limited
116
+ * to builtin source names: arbitrary tools, argument adapters, and third-party
117
+ * name-specific tools/pre-execute policy are not made equivalent by this overlay.
118
+ */
119
+ function installOverlay(agent, rule, legacyCapabilities, preparedPrompts, onDispose) {
120
+ if (scopeOf(agent.ctx) !== agent) {
121
+ throw new Error('codex-tool-policy: an exact Agent scope is required');
122
+ }
123
+ if (preparedPrompts !== undefined && (scopeParentOf(agent) !== preparedPrompts.scope
124
+ || !matchesPromptRevision(agent.ctx, rule.preset, preparedPrompts)))
125
+ throw new Error('preset-prompt-revision-mismatch');
126
+ const tools = agent.ctx.get('tools');
127
+ if (tools === undefined)
128
+ throw new Error('codex-tool-policy: the Agent has no tools service');
129
+ const upstream = scopeParentOf(agent);
130
+ for (const choice of rule.tools ?? []) {
131
+ if (tools.get(choice.name, agent) === undefined) {
132
+ throw new Error(`codex-tool-policy: unknown or unavailable source tool ${JSON.stringify(choice.name)} in explicit choice`);
133
+ }
134
+ }
135
+ for (const tool of [...rule.allow ?? [], ...rule.deny ?? [], ...rule.tools?.map(choice => choice.name) ?? []]) {
136
+ const visible = tools.get(tool, agent);
137
+ if (visible !== undefined && tools.get(tool, upstream) !== visible) {
138
+ throw new Error(`codex-tool-policy: cannot restrict Agent-local tool ${JSON.stringify(tool)}`);
139
+ }
140
+ }
141
+ // Explicit source choices override both legacy masks and category defaults.
142
+ // They can widen this rule's own allowlist, never another owner's restriction.
143
+ const allow = rule.allow === undefined ? undefined : new Set(rule.allow);
144
+ const deny = new Set(rule.deny);
145
+ let hasDeny = rule.deny !== undefined;
146
+ for (const choice of rule.tools ?? []) {
147
+ if (choice.action === 'hide') {
148
+ deny.add(choice.name);
149
+ hasDeny = true;
150
+ allow?.delete(choice.name);
151
+ }
152
+ else {
153
+ deny.delete(choice.name);
154
+ allow?.add(choice.name);
155
+ }
156
+ }
157
+ const actionFor = (name) => {
158
+ const definition = tools.get(name, agent);
159
+ const codexTool = definition === undefined ? undefined : codexToolMetadata(definition);
160
+ return effectiveToolAction(rule, name, { legacyCapabilities, ...(codexTool === undefined ? {} : { codexTool }) });
161
+ };
162
+ // Preserve an old replacement whose shared Codex capability was off: its
163
+ // source stays hidden, but no unavailable adapter is installed. Explicit
164
+ // per-source replacements bypass that compatibility baseline as one plan.
165
+ for (const name of ['bash', 'pwsh', 'todo_write']) {
166
+ const oldAction = legacyToolAction(rule, name);
167
+ if (tools.get(name, agent) !== undefined && (oldAction === 'codex-exec' || oldAction === 'codex-plan') && actionFor(name) === 'hide') {
168
+ deny.add(name);
169
+ hasDeny = true;
170
+ allow?.delete(name);
171
+ }
172
+ }
173
+ const mask = {
174
+ ...(allow === undefined ? {} : { allow: [...allow] }),
175
+ ...(!hasDeny ? {} : { deny: [...deny] }),
176
+ };
177
+ const permitted = (tool) => (allow === undefined || allow.has(tool)) && !deny.has(tool);
178
+ const shells = ['bash', 'pwsh'].filter(tool => actionFor(tool) === 'codex-exec'
179
+ && permitted(tool) && tools.get(tool, agent) !== undefined);
180
+ const plan = actionFor('todo_write') === 'codex-plan'
181
+ && permitted('todo_write') && tools.get('todo_write', agent) !== undefined;
182
+ const sources = [...shells, ...(plan ? ['todo_write'] : [])];
183
+ for (const tool of sources) {
184
+ const definition = tools.get(tool, agent);
185
+ // `when` is registration-owned and cannot be copied from a ToolDefinition.
186
+ // Without a step toolSet, executable() rejects every conditional registration.
187
+ if (tools.executable(tool, agent) !== definition) {
188
+ throw new Error(`codex-tool-policy: cannot replace conditional source tool ${JSON.stringify(tool)}; its activation condition must not be discarded`);
189
+ }
190
+ if (tools.get(tool, upstream) !== definition) {
191
+ throw new Error(`codex-tool-policy: cannot replace Agent-local source tool ${JSON.stringify(tool)}`);
192
+ }
193
+ }
194
+ const additions = [
195
+ ...(shells.length > 0 ? ['exec_command', 'write_stdin'] : []),
196
+ ...(plan ? ['update_plan'] : []),
197
+ ];
198
+ for (const tool of additions) {
199
+ if (tools.get(tool, agent) !== undefined) {
200
+ throw new Error(`codex-tool-policy: replacement tool ${JSON.stringify(tool)} already exists; refusing to shadow another implementation`);
201
+ }
202
+ }
203
+ if (shells.length > 0 && agent.ctx.get('shell') === undefined) {
204
+ throw new Error('codex-tool-policy: builtin shell replacement requires the mounted shell capability');
205
+ }
206
+ const needsPrompt = sources.length > 0 || (preparedPrompts?.sections.length ?? 0) > 0;
207
+ const systemPrompt = needsPrompt ? agent.ctx.get('systemPrompt') : undefined;
208
+ if (needsPrompt && systemPrompt === undefined) {
209
+ throw new Error('codex-tool-policy: replacements require the mounted systemPrompt service');
210
+ }
211
+ const guidance = [
212
+ ...(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.`]),
213
+ ...(plan ? ['For this Agent, todo_write is replaced by update_plan. Follow its current schema; at most one plan item may be in_progress.'] : []),
214
+ ].join('\n');
215
+ // These registrations and the helper have synchronous disposers. Yield exact
216
+ // effects so a later refusal rolls back every earlier mask before it escapes.
217
+ const dispose = agent.ctx.effect(function* () {
218
+ yield onDispose;
219
+ for (const section of preparedPrompts?.sections ?? [])
220
+ yield systemPrompt.section(section);
221
+ if (mask.allow !== undefined || mask.deny !== undefined)
222
+ yield tools.restrict(mask);
223
+ // Own registrations are exempt from restrict(). Never leave an unhidden
224
+ // Agent-local source alongside a newly granted Codex capability.
225
+ for (const tool of mask.deny ?? []) {
226
+ if (tools.get(tool, agent) !== undefined) {
227
+ throw new Error(`codex-tool-policy: cannot hide Agent-local tool ${JSON.stringify(tool)}`);
228
+ }
229
+ }
230
+ if (sources.length > 0) {
231
+ yield tools.restrict({ deny: sources });
232
+ for (const tool of sources) {
233
+ if (tools.get(tool, agent) !== undefined) {
234
+ throw new Error(`codex-tool-policy: cannot hide Agent-local source tool ${JSON.stringify(tool)}`);
235
+ }
236
+ }
237
+ yield registerCodexExecAndPlan(agent.ctx, { terminal: shells.length > 0, plan,
238
+ capabilityAuthority: { terminalToolsEnabled: shells.length > 0, planToolEnabled: plan } });
239
+ yield systemPrompt.section({ name: 'codex:tool-policy', order: 1015, text: guidance });
240
+ }
241
+ }, `codex-tool-policy:${rule.preset}`);
242
+ return () => { void dispose(); };
243
+ }
244
+ /**
245
+ * Affect future Agent lifecycles only. No existing-agent scan, polling, prompt
246
+ * rewrite, source-preset edit, or executor replacement is performed.
247
+ */
248
+ export function apply(ctx, config = {}) {
249
+ const currentConfig = () => 'get' in config ? config.get() ?? {} : config;
250
+ resolveRules(currentConfig());
251
+ // A save changes only future Agents, including their later blank-preset switches.
252
+ const snapshots = new WeakMap();
253
+ const overlays = new Map();
254
+ let active = true;
255
+ ctx.provide('codexToolPolicy', {
256
+ enabled(agent, name, metadata) {
257
+ const snapshot = snapshots.get(agent);
258
+ if (snapshot === undefined)
259
+ return undefined;
260
+ if (!metadata.presetEnabled)
261
+ return false;
262
+ return effectiveToolAction(snapshot.activeRule, name, {
263
+ legacyCapabilities: snapshot.legacyCapabilities, codexTool: metadata,
264
+ }) !== 'hide';
265
+ },
266
+ hasPromptOverride(scope, name) { return snapshots.get(scope)?.activePromptNames?.has(name) === true; },
267
+ });
268
+ const remove = (agent) => {
269
+ const snapshot = snapshots.get(agent);
270
+ if (snapshot !== undefined) {
271
+ delete snapshot.activeRule;
272
+ delete snapshot.activePromptNames;
273
+ }
274
+ const previous = overlays.get(agent);
275
+ if (previous === undefined)
276
+ return;
277
+ overlays.delete(agent);
278
+ previous.dispose();
279
+ };
280
+ const reconcile = (agent) => {
281
+ const preset = ctx.agentPresets.composedPreset(agent.ctx)
282
+ ?? ctx.agentPresets.presetForSession(agent.session)
283
+ ?? undefined;
284
+ if (overlays.get(agent)?.preset === preset)
285
+ return;
286
+ remove(agent);
287
+ const snapshot = snapshots.get(agent);
288
+ const rule = preset === undefined ? undefined : snapshot?.rules.get(preset);
289
+ if (rule === undefined || snapshot === undefined)
290
+ return;
291
+ const prepared = snapshot.promptPlans.get(rule.preset);
292
+ if (prepared instanceof Error)
293
+ throw prepared;
294
+ if ((rule.promptOverrides?.length ?? 0) > 0 && prepared === undefined)
295
+ throw new Error('preset-prompt-plan-unavailable');
296
+ let installed;
297
+ const dispose = installOverlay(agent, rule, snapshot.legacyCapabilities, prepared, () => {
298
+ if (installed !== undefined && overlays.get(agent) === installed) {
299
+ overlays.delete(agent);
300
+ delete snapshot.activeRule;
301
+ delete snapshot.activePromptNames;
302
+ }
303
+ });
304
+ installed = { preset: rule.preset, dispose };
305
+ overlays.set(agent, installed);
306
+ snapshot.activeRule = rule;
307
+ if (prepared !== undefined)
308
+ snapshot.activePromptNames = new Set(prepared.sections.map(section => section.name));
309
+ };
310
+ ctx.on('agent/created', ({ agent, signal }) => {
311
+ if (!active)
312
+ return;
313
+ signal?.throwIfAborted();
314
+ const snapshot = { rules: resolveRules(currentConfig()), legacyCapabilities: readLegacyCapabilities(ctx), promptPlans: new Map() };
315
+ snapshots.set(agent, snapshot);
316
+ const targets = [...snapshot.rules.values()].filter(rule => (rule.promptOverrides?.length ?? 0) > 0);
317
+ // Factory setup is finished; queued model work is held until this returns.
318
+ if (targets.length === 0) {
319
+ reconcile(agent);
320
+ return;
321
+ }
322
+ return (async () => {
323
+ const bound = ctx.agentPresets.composedPreset(agent.ctx) ?? ctx.agentPresets.presetForSession(agent.session);
324
+ for (const rule of targets) {
325
+ try {
326
+ const probe = await probePresetPrompts(ctx, rule.preset, rule.preset === bound ? scopeParentOf(agent) : undefined);
327
+ snapshot.promptPlans.set(rule.preset, preparePromptOverrides(probe, rule.promptOverrides));
328
+ }
329
+ catch (error) {
330
+ // A stale/unsupported sibling target cannot block the current preset.
331
+ snapshot.promptPlans.set(rule.preset, error instanceof Error ? error : new Error(String(error)));
332
+ }
333
+ }
334
+ signal?.throwIfAborted();
335
+ if (active)
336
+ reconcile(agent);
337
+ return undefined;
338
+ })();
339
+ });
340
+ ctx.on('agent-preset/selected', sessionId => {
341
+ if (!active)
342
+ return;
343
+ const agent = ctx.agents.get(sessionId);
344
+ if (agent === undefined || !snapshots.has(agent) || agent.status !== 'idle')
345
+ return;
346
+ const boundary = ctx.agents.turnBoundaryOf(agent.session);
347
+ if (boundary.openTurnStartSeq !== null || boundary.lastTurn > 0)
348
+ return;
349
+ // This event is emit, not serial: keep reconciliation entirely synchronous.
350
+ // A rejected new overlay leaves the newly selected preset's baseline intact.
351
+ try {
352
+ reconcile(agent);
353
+ }
354
+ catch (error) {
355
+ ctx.logger.warn(`codex-tool-policy: preset selection overlay refused for ${agent.id}: ${String(error)}`);
356
+ }
357
+ });
358
+ ctx.on('agent/disposed', ({ agent }) => { remove(agent); snapshots.delete(agent); });
359
+ // Registrations belong to agent.ctx, but must also unwind on Host-plugin unload.
360
+ ctx.effect(() => () => {
361
+ active = false;
362
+ for (const agent of [...overlays.keys()].reverse())
363
+ remove(agent);
364
+ }, 'codex-tool-policy: Host overlay ownership');
365
+ }
366
+ export default { name, inject, Config, apply };
367
+ //# sourceMappingURL=tool-policy.js.map
@@ -19,13 +19,13 @@ export declare const TYPERT: {
19
19
  codec: {
20
20
  mode: "strict";
21
21
  typeSymbol: string;
22
- schema: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
22
+ create: () => z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
23
23
  };
24
24
  }[];
25
25
  result: {
26
26
  mode: "strict";
27
27
  typeSymbol: string;
28
- schema: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
28
+ create: () => z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
29
29
  };
30
30
  }[];
31
31
  model: {
@@ -1,4 +1,6 @@
1
1
  import { z } from 'zod';
2
+ import { presetToolCatalogSchema } from "./preset-tool-catalog-schema.js";
3
+ import { presetPromptCatalogSchema } from "./preset-prompt-catalog-schema.js";
2
4
  const PACKAGE = '@shuind/dsh-codex-harness';
3
5
  const SERVICE = 'codexPresetEditor';
4
6
  const promptSections = z.array(z.object({ id: z.string(), label: z.string(), text: z.string().max(1_000_000), editable: z.boolean(), suppressed: z.boolean().optional() })).max(200);
@@ -39,6 +41,12 @@ const catalog = z.object({
39
41
  const codexOptionsPatch = codexOptions.partial();
40
42
  function descriptor(method, parameter, input, output) {
41
43
  const id = `${PACKAGE}#${SERVICE}/${method}`;
44
+ const codec = (typeSymbol, schema) => ({
45
+ mode: 'strict',
46
+ typeSymbol,
47
+ // Desktop 0.2 typert-loader instantiates codecs through create().
48
+ create: () => schema,
49
+ });
42
50
  return {
43
51
  id,
44
52
  service: SERVICE,
@@ -49,9 +57,9 @@ function descriptor(method, parameter, input, output) {
49
57
  name: parameter,
50
58
  wire: parameter,
51
59
  source: 'json',
52
- codec: { mode: 'strict', typeSymbol: `${id}:${parameter}`, schema: input },
60
+ codec: codec(`${id}:${parameter}`, input),
53
61
  }],
54
- result: { mode: 'strict', typeSymbol: `${id}:result`, schema: output },
62
+ result: codec(`${id}:result`, output),
55
63
  };
56
64
  }
57
65
  const updateInput = z.object({
@@ -76,6 +84,8 @@ export const TYPERT = {
76
84
  schemas: [],
77
85
  invocations: [
78
86
  descriptor('catalog', undefined, z.unknown(), catalog),
87
+ descriptor('tools', 'id', z.string().min(1).max(256), presetToolCatalogSchema),
88
+ descriptor('prompts', 'id', z.string().min(1).max(256), presetPromptCatalogSchema),
79
89
  descriptor('read', 'id', z.string(), document),
80
90
  descriptor('update', 'rawInput', updateInput, document),
81
91
  descriptor('create', 'rawInput', createInput, document),
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Codex harness",
4
+ "description": "Customizable Codex coding preset, terminal and patch tools, and Responses enhancements for DeepSeek Harness."
5
+ }
6
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Preset tools and prompts",
4
+ "description": "Configure tools and prompt overrides per preset without changing source definitions or other presets."
5
+ }
6
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "预设工具与提示词",
4
+ "description": "按预设配置工具和提示词覆盖,不修改原始定义或其它预设。"
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Codex 编码模式",
4
+ "description": "为 DeepSeek Harness 提供可自定义提示词的 Codex 预设、终端与补丁工具和 Responses 请求增强。"
5
+ }
6
+ }