@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,79 @@
1
+ /** Shared host-side Codex settings contract. */
2
+
3
+ import z from '@deepseek-ai/schemastery'
4
+ import type { SettingsNamespace } from '@deepseek-ai/dsh-settings'
5
+ import { CODEX_CONTEXT_MAX } from './context.ts'
6
+ import {
7
+ DEFAULT_CODEX_PERSONA,
8
+ DEFAULT_CODEX_SYSTEM_PROMPT,
9
+ DEFAULT_DSH_CORE_SOURCE_PROMPT,
10
+ DEFAULT_DSH_CORE_WEB_PROMPT,
11
+ } from './prompt.ts'
12
+
13
+ /** Live Codex controls shared by the Web UI and agent layer. */
14
+ export const CODEX_SETTINGS_NAMESPACE = 'codex' as SettingsNamespace
15
+
16
+ export interface CodexSettings {
17
+ /** Use the Responses priority service tier for GPT requests. */
18
+ fast: boolean
19
+ /** Show the Fast mode switch in the conversation composer. */
20
+ fastModeControlEnabled: boolean
21
+ /** Optional context capacity override, in tokens. */
22
+ contextWindow?: number
23
+ /** Deployment Persona template; supports the host's prompt variables. */
24
+ persona?: string
25
+ /** DSH Core source-checkout guidance template. */
26
+ harnessSourcePrompt?: string
27
+ /** DSH Core Web GUI guidance template. */
28
+ webSurfacePrompt?: string
29
+ /** Complete plugin-owned Codex operating prompt. */
30
+ systemPrompt?: string
31
+ /** Inject the plugin-owned Codex operating prompt. */
32
+ promptEnabled: boolean
33
+ /** Deprecated compatibility baseline, snapshotted into future Agent tool plans. */
34
+ terminalToolsEnabled: boolean
35
+ /** Deprecated tool baseline; also retains the legacy JSON/custom wire-format preference. */
36
+ patchToolEnabled: boolean
37
+ /** Deprecated compatibility baseline, not a live veto of a compiled plan. */
38
+ planToolEnabled: boolean
39
+ /** Upgrade local web_search declarations to the hosted Responses tool. */
40
+ hostedWebSearchEnabled: boolean
41
+ /** Prefer the provider's Responses compact endpoint. */
42
+ remoteCompactionEnabled: boolean
43
+ /** Show the Codex request/compaction activity indicator. */
44
+ activityIndicatorEnabled: boolean
45
+ }
46
+
47
+ /** Default settings exposed even before a Codex session is opened. */
48
+ export const CODEX_SETTINGS_ENTRY: CodexSettings = {
49
+ fast: false,
50
+ fastModeControlEnabled: true,
51
+ persona: DEFAULT_CODEX_PERSONA,
52
+ harnessSourcePrompt: DEFAULT_DSH_CORE_SOURCE_PROMPT,
53
+ webSurfacePrompt: DEFAULT_DSH_CORE_WEB_PROMPT,
54
+ systemPrompt: DEFAULT_CODEX_SYSTEM_PROMPT,
55
+ promptEnabled: true,
56
+ terminalToolsEnabled: true,
57
+ patchToolEnabled: true,
58
+ planToolEnabled: true,
59
+ hostedWebSearchEnabled: true,
60
+ remoteCompactionEnabled: true,
61
+ activityIndicatorEnabled: true,
62
+ }
63
+
64
+ export const CODEX_SETTINGS_SCHEMA: z<CodexSettings> = z.object({
65
+ fast: z.boolean().default(false),
66
+ fastModeControlEnabled: z.boolean().default(true),
67
+ contextWindow: z.number().step(1).min(1).max(CODEX_CONTEXT_MAX),
68
+ persona: z.string().default(DEFAULT_CODEX_PERSONA),
69
+ harnessSourcePrompt: z.string().default(DEFAULT_DSH_CORE_SOURCE_PROMPT),
70
+ webSurfacePrompt: z.string().default(DEFAULT_DSH_CORE_WEB_PROMPT),
71
+ systemPrompt: z.string().default(DEFAULT_CODEX_SYSTEM_PROMPT),
72
+ promptEnabled: z.boolean().default(true),
73
+ terminalToolsEnabled: z.boolean().default(true).hidden(),
74
+ patchToolEnabled: z.boolean().default(true).hidden(),
75
+ planToolEnabled: z.boolean().default(true).hidden(),
76
+ hostedWebSearchEnabled: z.boolean().default(true),
77
+ remoteCompactionEnabled: z.boolean().default(true),
78
+ activityIndicatorEnabled: z.boolean().default(true),
79
+ })
@@ -0,0 +1,76 @@
1
+ /** Host-only ownership marks and the optional Agent-snapshot availability seam. */
2
+ import type { Context } from '@deepseek-ai/cordis'
3
+ import type { Agent } from '@deepseek-ai/dsh-agent'
4
+ import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
5
+ import type { ScopeKey } from '@deepseek-ai/dsh-scope'
6
+ import type { AssembleContext } from '@deepseek-ai/dsh-system-prompt'
7
+ import { CODEX_SETTINGS_ENTRY, CODEX_SETTINGS_NAMESPACE } from './settings.ts'
8
+ import type { CodexSettings } from './settings.ts'
9
+ import { readHostSettings } from './host-settings.ts'
10
+ import type { CodexCapability, CodexToolMetadata, LegacyCapabilities } from './tool-policy-contract.ts'
11
+
12
+ // Core and policy are bundled separately. A global symbol survives that boundary;
13
+ // matching an unmarked third-party tool by name would not establish ownership.
14
+ const OWNED_TOOL = Symbol.for('@shuind/dsh-codex-harness:tool-capability:v1')
15
+ const CAPABILITIES: readonly CodexCapability[] = ['terminalToolsEnabled', 'planToolEnabled', 'patchToolEnabled']
16
+
17
+ export interface CodexToolPolicyResolver {
18
+ /** Undefined means an older, unsnapshotted Agent retains the compatibility path. */
19
+ enabled(agent: Agent, name: string, metadata: CodexToolMetadata): boolean | undefined
20
+ hasPromptOverride?(scope: ScopeKey, name: string): boolean
21
+ }
22
+
23
+ declare module '@deepseek-ai/dsh-system-prompt' {
24
+ interface AssembleContext {
25
+ /** Read-only own-plugin probe: do not reapply obsolete Codex prompt preferences. */
26
+ codexPresetPromptProbe?: true
27
+ }
28
+ }
29
+
30
+ /** Only our old presentation hooks consume this; registrations remain provider-owned. */
31
+ export function hasPresetPromptOverride(ctx: Context, context: AssembleContext, name: string): boolean {
32
+ if (context.codexPresetPromptProbe === true) return ['deployment:persona-prefix', 'deployment:persona-suffix', 'codex:base'].includes(name)
33
+ return context.scope !== undefined && ctx.get('codexToolPolicy')?.hasPromptOverride?.(context.scope, name) === true
34
+ }
35
+
36
+ declare module '@deepseek-ai/cordis' {
37
+ interface Context {
38
+ codexToolPolicy: CodexToolPolicyResolver
39
+ }
40
+ }
41
+
42
+ export function markCodexTool<T extends ToolDefinition>(definition: T, metadata: CodexToolMetadata): T {
43
+ Object.defineProperty(definition, OWNED_TOOL, { value: Object.freeze({ ...metadata }) })
44
+ return definition
45
+ }
46
+
47
+ export function codexToolMetadata(definition: ToolDefinition): CodexToolMetadata | undefined {
48
+ const value = (definition as unknown as Record<symbol, unknown>)[OWNED_TOOL]
49
+ if (value === null || typeof value !== 'object') return undefined
50
+ const data = value as Partial<CodexToolMetadata>
51
+ if (!CAPABILITIES.includes(data.capability as CodexCapability) || typeof data.presetEnabled !== 'boolean'
52
+ || data.presetOverridesLegacy !== undefined && typeof data.presetOverridesLegacy !== 'boolean') return undefined
53
+ return { capability: data.capability as CodexCapability, presetEnabled: data.presetEnabled,
54
+ ...(data.presetOverridesLegacy === undefined ? {} : { presetOverridesLegacy: data.presetOverridesLegacy }) }
55
+ }
56
+
57
+ /** Read once for a new Agent or catalog. No caller keeps the live preference object. */
58
+ export function readLegacyCapabilities(ctx: Context): Readonly<Required<LegacyCapabilities>> {
59
+ const current = readHostSettings<Partial<CodexSettings>>(ctx, CODEX_SETTINGS_NAMESPACE)
60
+ return Object.freeze(Object.fromEntries(CAPABILITIES.map(key => [key, current?.[key] ?? CODEX_SETTINGS_ENTRY[key]]))) as Required<LegacyCapabilities>
61
+ }
62
+
63
+ export function codexToolEnabled(
64
+ ctx: Context,
65
+ agent: Agent | undefined,
66
+ name: string,
67
+ metadata: CodexToolMetadata,
68
+ fallback: () => CodexSettings,
69
+ authority?: boolean,
70
+ ): boolean {
71
+ if (!metadata.presetEnabled) return false
72
+ // Only a successfully compiled adapter plan supplies this authority.
73
+ if (authority !== undefined) return authority
74
+ const decision = agent === undefined ? undefined : ctx.get('codexToolPolicy')?.enabled(agent, name, metadata)
75
+ return decision ?? fallback()[metadata.capability] !== false
76
+ }
@@ -0,0 +1,76 @@
1
+ /** Client-safe tool choices. The concrete adapters remain Host-owned. */
2
+ import type { PresetPromptOverride } from './preset-prompt-contract.ts'
3
+ export { PRESET_PROMPT_NAMES } from './preset-prompt-contract.ts'
4
+ export type { PresetPromptName, PresetPromptOverride, PresetPromptEntry, PresetPromptCatalog } from './preset-prompt-contract.ts'
5
+ export type ToolAction = 'keep' | 'hide' | 'codex-exec' | 'codex-plan'
6
+ export type ReplacementAction = Extract<ToolAction, 'codex-exec' | 'codex-plan'>
7
+ export type CodexCapability = 'terminalToolsEnabled' | 'planToolEnabled' | 'patchToolEnabled'
8
+ export type LegacyCapabilities = Partial<Record<CodexCapability, boolean>>
9
+ /** Ownership metadata, not a promise that `keep` admits a locally disabled tool. */
10
+ export interface CodexToolMetadata {
11
+ readonly capability: CodexCapability
12
+ readonly presetEnabled: boolean
13
+ /** An explicit old per-preset boolean already overrode the shared baseline. */
14
+ readonly presetOverridesLegacy?: boolean
15
+ }
16
+ export interface ToolActionContext {
17
+ readonly legacyCapabilities?: LegacyCapabilities
18
+ readonly codexTool?: CodexToolMetadata
19
+ }
20
+ export interface ToolActionRule {
21
+ readonly name: string
22
+ readonly action: ToolAction
23
+ }
24
+ export interface ToolPolicyRule {
25
+ readonly preset: string
26
+ readonly allow?: readonly string[]
27
+ readonly deny?: readonly string[]
28
+ /** Legacy category defaults; new UI rules explicitly set both to false. */
29
+ readonly replaceShell?: boolean
30
+ readonly replacePlan?: boolean
31
+ /** Explicit per-source choices override the legacy masks and category defaults. */
32
+ readonly tools?: readonly ToolActionRule[]
33
+ /** Exact reviewed section replacements, scoped to future Agents of this preset. */
34
+ readonly promptOverrides?: readonly PresetPromptOverride[]
35
+ }
36
+ export interface PresetToolReplacement {
37
+ readonly action: ReplacementAction
38
+ readonly tools: readonly string[]
39
+ readonly available: boolean
40
+ readonly reason?: 'conditional' | 'target-exists'
41
+ }
42
+ export interface PresetToolEntry {
43
+ readonly name: string
44
+ readonly description: string
45
+ readonly conditional: boolean
46
+ readonly replacements: readonly PresetToolReplacement[]
47
+ readonly codexTool?: CodexToolMetadata
48
+ }
49
+ export interface PresetToolCatalog {
50
+ readonly preset: string
51
+ /** Registration snapshot, not admission for a particular Agent/model step. */
52
+ readonly registeredOnly: true
53
+ readonly tools: readonly PresetToolEntry[]
54
+ readonly legacyCapabilities?: LegacyCapabilities
55
+ }
56
+
57
+ /** Legacy configuration remains a baseline, never a live second veto of an explicit choice. */
58
+ export function legacyToolAction(rule: ToolPolicyRule | undefined, name: string, context: ToolActionContext = {}): ToolAction {
59
+ let action: ToolAction = 'keep'
60
+ if (rule !== undefined) {
61
+ if ((rule.allow !== undefined && !rule.allow.includes(name)) || rule.deny?.includes(name)) return 'hide'
62
+ if ((name === 'bash' || name === 'pwsh') && rule.replaceShell !== false) action = 'codex-exec'
63
+ if (name === 'todo_write' && rule.replacePlan !== false) action = 'codex-plan'
64
+ }
65
+ const capability = context.codexTool?.capability
66
+ ?? (action === 'codex-exec' ? 'terminalToolsEnabled' : action === 'codex-plan' ? 'planToolEnabled' : undefined)
67
+ // Only owned definitions and chosen Codex adapters consume the legacy baseline.
68
+ // A third-party tool with the same name does not become a Codex capability.
69
+ const presetOverride = context.codexTool?.presetOverridesLegacy === true && context.codexTool.presetEnabled
70
+ if (!presetOverride && capability !== undefined && context.legacyCapabilities?.[capability] === false) return 'hide'
71
+ return action
72
+ }
73
+ /** Policy action only: `keep` still respects the original preset's local enablement. */
74
+ export function effectiveToolAction(rule: ToolPolicyRule | undefined, name: string, context: ToolActionContext = {}): ToolAction {
75
+ return rule?.tools?.find(tool => tool.name === name)?.action ?? legacyToolAction(rule, name, context)
76
+ }
@@ -0,0 +1,388 @@
1
+ /** Opt-in Host overlays for future Agents; source presets and Persona stay untouched. */
2
+
3
+ import type { Context } from '@deepseek-ai/cordis'
4
+ import z from '@deepseek-ai/schemastery'
5
+ import type { Agent } from '@deepseek-ai/dsh-agent'
6
+ import type {} from '@deepseek-ai/dsh-agent-preset-registry'
7
+ import { scopeOf, scopeParentOf } from '@deepseek-ai/dsh-scope'
8
+ import type {} from '@deepseek-ai/dsh-tools'
9
+ import { registerCodexExecAndPlan } from './index.ts'
10
+ import { effectiveToolAction, legacyToolAction } from './tool-policy-contract.ts'
11
+ import type { ToolActionRule, ToolPolicyRule, LegacyCapabilities } from './tool-policy-contract.ts'
12
+ import { codexToolMetadata, readLegacyCapabilities } from './tool-capabilities.ts'
13
+ import { PRESET_PROMPT_NAMES } from './preset-prompt-contract.ts'
14
+ import type { PresetPromptOverride } from './preset-prompt-contract.ts'
15
+ import { probePresetPrompts, preparePromptOverrides, matchesPromptRevision } from './preset-prompt-catalog.ts'
16
+ import type { PreparedPromptOverride } from './preset-prompt-catalog.ts'
17
+
18
+ export type { ToolAction, ToolActionRule, ToolPolicyRule } from './tool-policy-contract.ts'
19
+
20
+ export const name = 'codex-tool-policy'
21
+ export const inject = ['tools', 'agents', 'agentPresets']
22
+
23
+ export interface Config {
24
+ /** Empty by default: no preset or existing Agent is changed implicitly. */
25
+ rules?: readonly ToolPolicyRule[]
26
+ }
27
+
28
+ // Root volatility keeps saving future-Agent rules from unloading live overlays.
29
+ export const Config = z.object({
30
+ rules: z.array(z.object({
31
+ preset: z.string().required().description('Exact preset id; only Agents created after this plugin loads are affected.'),
32
+ // Bare Schemastery arrays default to []; a union preserves omitted masks.
33
+ allow: z.union([z.array(z.string())]).description('Inherited source names to keep. Omit for no allowlist; [] removes all inherited tools, including file tools.'),
34
+ deny: z.union([z.array(z.string())]).description('Inherited source names to remove; unknown and Agent-local names are rejected.'),
35
+ 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.'),
36
+ replacePlan: z.boolean().default(true).description('Legacy default: replace permitted builtin todo_write with update_plan; explicit source choices override it.'),
37
+ tools: z.union([z.array(z.object({
38
+ name: z.string().required().description('Exact inherited source tool name.'),
39
+ action: z.union([z.const('keep'), z.const('hide'), z.const('codex-exec'), z.const('codex-plan')]).required()
40
+ .description('Per-tool override: keep/hide any inherited tool; codex-exec only for bash/pwsh and codex-plan only for todo_write.'),
41
+ }))]).description('Individual source choices, overriding allow/deny and legacy replacement defaults. Omission preserves legacy behavior.'),
42
+ promptOverrides: z.union([z.array(z.object({
43
+ name: z.union(PRESET_PROMPT_NAMES.map(name => z.const(name))).required(),
44
+ text: z.string().max(1_000_000).required(),
45
+ }))]).description('Exact current-preset prompt replacements. Order, interpolation and complete semantics remain Host-owned.'),
46
+ })).default([]),
47
+ }).volatile()
48
+
49
+ /** Loader activations receive a volatile reference; direct callers may pass plain rules. */
50
+ export type ToolPolicyConfigSource = Config | ReturnType<typeof Config>
51
+
52
+ interface ResolvedRule extends ToolPolicyRule {
53
+ readonly replaceShell: boolean
54
+ readonly replacePlan: boolean
55
+ }
56
+
57
+ interface AgentToolSnapshot {
58
+ readonly rules: ReadonlyMap<string, ResolvedRule>
59
+ readonly legacyCapabilities: Readonly<LegacyCapabilities>
60
+ activeRule?: ResolvedRule
61
+ readonly promptPlans: Map<string, PreparedPromptOverride | Error>
62
+ activePromptNames?: ReadonlySet<string>
63
+ }
64
+
65
+ interface Overlay {
66
+ readonly preset: string
67
+ readonly dispose: () => void
68
+ }
69
+
70
+ /** Reject ambiguous/unsupported overrides before any Agent registrations change. */
71
+ function resolveToolChoices(input: readonly ToolActionRule[] | undefined): readonly ToolActionRule[] | undefined {
72
+ if (input === undefined) return undefined
73
+ if (!Array.isArray(input)) throw new TypeError('codex-tool-policy: tools must be an array of source choices')
74
+ const seen = new Set<string>()
75
+ const choices: ToolActionRule[] = []
76
+ for (const choice of input) {
77
+ if (choice === null || typeof choice !== 'object'
78
+ || typeof choice.name !== 'string' || choice.name.trim().length === 0) {
79
+ throw new TypeError('codex-tool-policy: every tool choice requires a non-empty source name')
80
+ }
81
+ if (seen.has(choice.name)) {
82
+ throw new Error(`codex-tool-policy: duplicate tool choice ${JSON.stringify(choice.name)}`)
83
+ }
84
+ seen.add(choice.name)
85
+ if (!['keep', 'hide', 'codex-exec', 'codex-plan'].includes(choice.action)) {
86
+ throw new TypeError(`codex-tool-policy: invalid action for source tool ${JSON.stringify(choice.name)}`)
87
+ }
88
+ if (choice.action === 'codex-exec' && choice.name !== 'bash' && choice.name !== 'pwsh'
89
+ || choice.action === 'codex-plan' && choice.name !== 'todo_write') {
90
+ throw new Error(`codex-tool-policy: unsupported replacement ${JSON.stringify(choice.action)} for source tool ${JSON.stringify(choice.name)}`)
91
+ }
92
+ choices.push({ name: choice.name, action: choice.action })
93
+ }
94
+ return choices
95
+ }
96
+
97
+ function resolvePromptChoices(input: readonly PresetPromptOverride[] | undefined): readonly PresetPromptOverride[] | undefined {
98
+ if (input === undefined) return undefined
99
+ if (!Array.isArray(input) || input.length > PRESET_PROMPT_NAMES.length) throw new Error('invalid-preset-prompt-overrides')
100
+ const seen = new Set<string>()
101
+ return input.map(value => {
102
+ if (value === null || typeof value !== 'object' || !PRESET_PROMPT_NAMES.includes(value.name)
103
+ || typeof value.text !== 'string' || value.text.length > 1_000_000
104
+ || Object.keys(value).some(key => key !== 'name' && key !== 'text') || seen.has(value.name)) {
105
+ throw new Error('invalid-preset-prompt-override')
106
+ }
107
+ seen.add(value.name)
108
+ return { name: value.name, text: value.text }
109
+ })
110
+ }
111
+
112
+ /** Validate direct callers too, and detach configuration from later form mutations. */
113
+ function resolveRules(config: Config): ReadonlyMap<string, ResolvedRule> {
114
+ const input = config.rules ?? []
115
+ if (!Array.isArray(input)) throw new TypeError('codex-tool-policy: rules must be an array')
116
+ const rules = new Map<string, ResolvedRule>()
117
+ for (const rule of input) {
118
+ if (rule === null || typeof rule !== 'object'
119
+ || typeof rule.preset !== 'string' || rule.preset.trim().length === 0) {
120
+ throw new TypeError('codex-tool-policy: every rule requires a non-empty preset id')
121
+ }
122
+ if (rules.has(rule.preset)) throw new Error(`codex-tool-policy: duplicate preset rule ${JSON.stringify(rule.preset)}`)
123
+ for (const key of ['allow', 'deny'] as const) {
124
+ const names = rule[key]
125
+ if (names !== undefined && (!Array.isArray(names)
126
+ || names.some(tool => typeof tool !== 'string' || tool.trim().length === 0))) {
127
+ throw new TypeError(`codex-tool-policy: ${key} must be an array of non-empty tool names`)
128
+ }
129
+ }
130
+ for (const key of ['replaceShell', 'replacePlan'] as const) {
131
+ if (rule[key] !== undefined && typeof rule[key] !== 'boolean') {
132
+ throw new TypeError(`codex-tool-policy: ${key} must be a boolean`)
133
+ }
134
+ }
135
+ const choices = resolveToolChoices(rule.tools)
136
+ const prompts = resolvePromptChoices(rule.promptOverrides)
137
+ rules.set(rule.preset, {
138
+ preset: rule.preset,
139
+ ...(rule.allow === undefined ? {} : { allow: [...rule.allow] }),
140
+ ...(rule.deny === undefined ? {} : { deny: [...rule.deny] }),
141
+ replaceShell: rule.replaceShell !== false,
142
+ replacePlan: rule.replacePlan !== false,
143
+ ...(choices === undefined ? {} : { tools: choices }),
144
+ ...(prompts === undefined ? {} : { promptOverrides: prompts }),
145
+ })
146
+ }
147
+ return rules
148
+ }
149
+
150
+ /**
151
+ * Install only through an exact Agent scope. Replacement is deliberately limited
152
+ * to builtin source names: arbitrary tools, argument adapters, and third-party
153
+ * name-specific tools/pre-execute policy are not made equivalent by this overlay.
154
+ */
155
+ function installOverlay(
156
+ agent: Agent,
157
+ rule: ResolvedRule,
158
+ legacyCapabilities: Readonly<LegacyCapabilities>,
159
+ preparedPrompts: PreparedPromptOverride | undefined,
160
+ onDispose: () => void,
161
+ ): () => void {
162
+ if (scopeOf(agent.ctx) !== agent) {
163
+ throw new Error('codex-tool-policy: an exact Agent scope is required')
164
+ }
165
+ if (preparedPrompts !== undefined && (scopeParentOf(agent) !== preparedPrompts.scope
166
+ || !matchesPromptRevision(agent.ctx, rule.preset, preparedPrompts))) throw new Error('preset-prompt-revision-mismatch')
167
+ const tools = agent.ctx.get('tools')
168
+ if (tools === undefined) throw new Error('codex-tool-policy: the Agent has no tools service')
169
+ const upstream = scopeParentOf(agent)
170
+ for (const choice of rule.tools ?? []) {
171
+ if (tools.get(choice.name, agent) === undefined) {
172
+ throw new Error(`codex-tool-policy: unknown or unavailable source tool ${JSON.stringify(choice.name)} in explicit choice`)
173
+ }
174
+ }
175
+ for (const tool of [...rule.allow ?? [], ...rule.deny ?? [], ...rule.tools?.map(choice => choice.name) ?? []]) {
176
+ const visible = tools.get(tool, agent)
177
+ if (visible !== undefined && tools.get(tool, upstream) !== visible) {
178
+ throw new Error(`codex-tool-policy: cannot restrict Agent-local tool ${JSON.stringify(tool)}`)
179
+ }
180
+ }
181
+
182
+ // Explicit source choices override both legacy masks and category defaults.
183
+ // They can widen this rule's own allowlist, never another owner's restriction.
184
+ const allow = rule.allow === undefined ? undefined : new Set(rule.allow)
185
+ const deny = new Set(rule.deny)
186
+ let hasDeny = rule.deny !== undefined
187
+ for (const choice of rule.tools ?? []) {
188
+ if (choice.action === 'hide') {
189
+ deny.add(choice.name)
190
+ hasDeny = true
191
+ allow?.delete(choice.name)
192
+ } else {
193
+ deny.delete(choice.name)
194
+ allow?.add(choice.name)
195
+ }
196
+ }
197
+ const actionFor = (name: string) => {
198
+ const definition = tools.get(name, agent)
199
+ const codexTool = definition === undefined ? undefined : codexToolMetadata(definition)
200
+ return effectiveToolAction(rule, name, { legacyCapabilities, ...(codexTool === undefined ? {} : { codexTool }) })
201
+ }
202
+ // Preserve an old replacement whose shared Codex capability was off: its
203
+ // source stays hidden, but no unavailable adapter is installed. Explicit
204
+ // per-source replacements bypass that compatibility baseline as one plan.
205
+ for (const name of ['bash', 'pwsh', 'todo_write']) {
206
+ const oldAction = legacyToolAction(rule, name)
207
+ if (tools.get(name, agent) !== undefined && (oldAction === 'codex-exec' || oldAction === 'codex-plan') && actionFor(name) === 'hide') {
208
+ deny.add(name)
209
+ hasDeny = true
210
+ allow?.delete(name)
211
+ }
212
+ }
213
+ const mask = {
214
+ ...(allow === undefined ? {} : { allow: [...allow] }),
215
+ ...(!hasDeny ? {} : { deny: [...deny] }),
216
+ }
217
+ const permitted = (tool: string): boolean => (allow === undefined || allow.has(tool)) && !deny.has(tool)
218
+ const shells = ['bash', 'pwsh'].filter(tool => actionFor(tool) === 'codex-exec'
219
+ && permitted(tool) && tools.get(tool, agent) !== undefined)
220
+ const plan = actionFor('todo_write') === 'codex-plan'
221
+ && permitted('todo_write') && tools.get('todo_write', agent) !== undefined
222
+ const sources = [...shells, ...(plan ? ['todo_write'] : [])]
223
+
224
+ for (const tool of sources) {
225
+ const definition = tools.get(tool, agent)
226
+ // `when` is registration-owned and cannot be copied from a ToolDefinition.
227
+ // Without a step toolSet, executable() rejects every conditional registration.
228
+ if (tools.executable(tool, agent) !== definition) {
229
+ throw new Error(`codex-tool-policy: cannot replace conditional source tool ${JSON.stringify(tool)}; its activation condition must not be discarded`)
230
+ }
231
+ if (tools.get(tool, upstream) !== definition) {
232
+ throw new Error(`codex-tool-policy: cannot replace Agent-local source tool ${JSON.stringify(tool)}`)
233
+ }
234
+ }
235
+ const additions = [
236
+ ...(shells.length > 0 ? ['exec_command', 'write_stdin'] : []),
237
+ ...(plan ? ['update_plan'] : []),
238
+ ]
239
+ for (const tool of additions) {
240
+ if (tools.get(tool, agent) !== undefined) {
241
+ throw new Error(`codex-tool-policy: replacement tool ${JSON.stringify(tool)} already exists; refusing to shadow another implementation`)
242
+ }
243
+ }
244
+ if (shells.length > 0 && agent.ctx.get('shell') === undefined) {
245
+ throw new Error('codex-tool-policy: builtin shell replacement requires the mounted shell capability')
246
+ }
247
+ const needsPrompt = sources.length > 0 || (preparedPrompts?.sections.length ?? 0) > 0
248
+ const systemPrompt = needsPrompt ? agent.ctx.get('systemPrompt') : undefined
249
+ if (needsPrompt && systemPrompt === undefined) {
250
+ throw new Error('codex-tool-policy: replacements require the mounted systemPrompt service')
251
+ }
252
+ const guidance = [
253
+ ...(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.`]),
254
+ ...(plan ? ['For this Agent, todo_write is replaced by update_plan. Follow its current schema; at most one plan item may be in_progress.'] : []),
255
+ ].join('\n')
256
+
257
+ // These registrations and the helper have synchronous disposers. Yield exact
258
+ // effects so a later refusal rolls back every earlier mask before it escapes.
259
+ const dispose = agent.ctx.effect(function* () {
260
+ yield onDispose
261
+ for (const section of preparedPrompts?.sections ?? []) yield systemPrompt!.section(section)
262
+ if (mask.allow !== undefined || mask.deny !== undefined) yield tools.restrict(mask)
263
+ // Own registrations are exempt from restrict(). Never leave an unhidden
264
+ // Agent-local source alongside a newly granted Codex capability.
265
+ for (const tool of mask.deny ?? []) {
266
+ if (tools.get(tool, agent) !== undefined) {
267
+ throw new Error(`codex-tool-policy: cannot hide Agent-local tool ${JSON.stringify(tool)}`)
268
+ }
269
+ }
270
+ if (sources.length > 0) {
271
+ yield tools.restrict({ deny: sources })
272
+ for (const tool of sources) {
273
+ if (tools.get(tool, agent) !== undefined) {
274
+ throw new Error(`codex-tool-policy: cannot hide Agent-local source tool ${JSON.stringify(tool)}`)
275
+ }
276
+ }
277
+ yield registerCodexExecAndPlan(agent.ctx, { terminal: shells.length > 0, plan,
278
+ capabilityAuthority: { terminalToolsEnabled: shells.length > 0, planToolEnabled: plan } })
279
+ yield systemPrompt!.section({ name: 'codex:tool-policy', order: 1015, text: guidance })
280
+ }
281
+ }, `codex-tool-policy:${rule.preset}`)
282
+ return () => { void dispose() }
283
+ }
284
+
285
+ /**
286
+ * Affect future Agent lifecycles only. No existing-agent scan, polling, prompt
287
+ * rewrite, source-preset edit, or executor replacement is performed.
288
+ */
289
+ export function apply(ctx: Context, config: ToolPolicyConfigSource = {}): void {
290
+ const currentConfig = (): Config => 'get' in config ? config.get() ?? {} : config
291
+ resolveRules(currentConfig())
292
+ // A save changes only future Agents, including their later blank-preset switches.
293
+ const snapshots = new WeakMap<Agent, AgentToolSnapshot>()
294
+ const overlays = new Map<Agent, Overlay>()
295
+ let active = true
296
+ ctx.provide('codexToolPolicy', {
297
+ enabled(agent, name, metadata) {
298
+ const snapshot = snapshots.get(agent)
299
+ if (snapshot === undefined) return undefined
300
+ if (!metadata.presetEnabled) return false
301
+ return effectiveToolAction(snapshot.activeRule, name, {
302
+ legacyCapabilities: snapshot.legacyCapabilities, codexTool: metadata,
303
+ }) !== 'hide'
304
+ },
305
+ hasPromptOverride(scope, name) { return snapshots.get(scope as Agent)?.activePromptNames?.has(name) === true },
306
+ })
307
+
308
+ const remove = (agent: Agent): void => {
309
+ const snapshot = snapshots.get(agent)
310
+ if (snapshot !== undefined) { delete snapshot.activeRule; delete snapshot.activePromptNames }
311
+ const previous = overlays.get(agent)
312
+ if (previous === undefined) return
313
+ overlays.delete(agent)
314
+ previous.dispose()
315
+ }
316
+ const reconcile = (agent: Agent): void => {
317
+ const preset = ctx.agentPresets.composedPreset(agent.ctx)
318
+ ?? ctx.agentPresets.presetForSession(agent.session)
319
+ ?? undefined
320
+ if (overlays.get(agent)?.preset === preset) return
321
+ remove(agent)
322
+ const snapshot = snapshots.get(agent)
323
+ const rule = preset === undefined ? undefined : snapshot?.rules.get(preset)
324
+ if (rule === undefined || snapshot === undefined) return
325
+ const prepared = snapshot.promptPlans.get(rule.preset)
326
+ if (prepared instanceof Error) throw prepared
327
+ if ((rule.promptOverrides?.length ?? 0) > 0 && prepared === undefined) throw new Error('preset-prompt-plan-unavailable')
328
+ let installed: Overlay | undefined
329
+ const dispose = installOverlay(agent, rule, snapshot.legacyCapabilities, prepared, () => {
330
+ if (installed !== undefined && overlays.get(agent) === installed) {
331
+ overlays.delete(agent)
332
+ delete snapshot.activeRule
333
+ delete snapshot.activePromptNames
334
+ }
335
+ })
336
+ installed = { preset: rule.preset, dispose }
337
+ overlays.set(agent, installed)
338
+ snapshot.activeRule = rule
339
+ if (prepared !== undefined) snapshot.activePromptNames = new Set(prepared.sections.map(section => section.name))
340
+ }
341
+
342
+ ctx.on('agent/created', ({ agent, signal }) => {
343
+ if (!active) return
344
+ signal?.throwIfAborted()
345
+ const snapshot: AgentToolSnapshot = { rules: resolveRules(currentConfig()), legacyCapabilities: readLegacyCapabilities(ctx), promptPlans: new Map() }
346
+ snapshots.set(agent, snapshot)
347
+ const targets = [...snapshot.rules.values()].filter(rule => (rule.promptOverrides?.length ?? 0) > 0)
348
+ // Factory setup is finished; queued model work is held until this returns.
349
+ if (targets.length === 0) { reconcile(agent); return }
350
+ return (async () => {
351
+ const bound = ctx.agentPresets.composedPreset(agent.ctx) ?? ctx.agentPresets.presetForSession(agent.session)
352
+ for (const rule of targets) {
353
+ try {
354
+ const probe = await probePresetPrompts(ctx, rule.preset, rule.preset === bound ? scopeParentOf(agent) : undefined)
355
+ snapshot.promptPlans.set(rule.preset, preparePromptOverrides(probe, rule.promptOverrides!))
356
+ } catch (error) {
357
+ // A stale/unsupported sibling target cannot block the current preset.
358
+ snapshot.promptPlans.set(rule.preset, error instanceof Error ? error : new Error(String(error)))
359
+ }
360
+ }
361
+ signal?.throwIfAborted()
362
+ if (active) reconcile(agent)
363
+ return undefined
364
+ })()
365
+ })
366
+ ctx.on('agent-preset/selected', sessionId => {
367
+ if (!active) return
368
+ const agent = ctx.agents.get(sessionId)
369
+ if (agent === undefined || !snapshots.has(agent) || agent.status !== 'idle') return
370
+ const boundary = ctx.agents.turnBoundaryOf(agent.session)
371
+ if (boundary.openTurnStartSeq !== null || boundary.lastTurn > 0) return
372
+ // This event is emit, not serial: keep reconciliation entirely synchronous.
373
+ // A rejected new overlay leaves the newly selected preset's baseline intact.
374
+ try {
375
+ reconcile(agent)
376
+ } catch (error) {
377
+ ctx.logger.warn(`codex-tool-policy: preset selection overlay refused for ${agent.id}: ${String(error)}`)
378
+ }
379
+ })
380
+ ctx.on('agent/disposed', ({ agent }) => { remove(agent); snapshots.delete(agent) })
381
+ // Registrations belong to agent.ctx, but must also unwind on Host-plugin unload.
382
+ ctx.effect(() => () => {
383
+ active = false
384
+ for (const agent of [...overlays.keys()].reverse()) remove(agent)
385
+ }, 'codex-tool-policy: Host overlay ownership')
386
+ }
387
+
388
+ export default { name, inject, Config, apply }