@shuind/dsh-codex-harness 0.2.21 → 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 (200) hide show
  1. package/CHANGELOG.md +185 -0
  2. package/README.md +38 -50
  3. package/RELEASE.md +61 -0
  4. package/assets/codex.svg +5 -0
  5. package/cordis.patch.yml +181 -6
  6. package/docs/preset-library.md +33 -23
  7. package/docs/tool-policy-benchmark.json +310 -0
  8. package/docs/tool-policy.md +148 -0
  9. package/lib/client.js +4774 -2416
  10. package/lib/compact-command.js +416 -0
  11. package/lib/compaction.js +141 -12
  12. package/lib/hybrid-executor.js +1196 -0
  13. package/lib/index.js +3658 -2334
  14. package/lib/preferences.js +117 -0
  15. package/lib/tool-policy.js +2422 -0
  16. package/lib/typert.js +86 -79
  17. package/lib/types/client/activity.d.ts +33 -9
  18. package/lib/types/client/activity.js +4 -3
  19. package/lib/types/client/desktop.d.ts +67 -0
  20. package/lib/types/client/desktop.js +229 -0
  21. package/lib/types/client/index.d.ts +207 -110
  22. package/lib/types/client/index.js +99 -492
  23. package/lib/types/client/policy-drafts.d.ts +25 -0
  24. package/lib/types/client/policy-drafts.js +47 -0
  25. package/lib/types/client/policy-locale.d.ts +260 -0
  26. package/lib/types/client/policy-locale.js +357 -0
  27. package/lib/types/client/preset-manager.d.ts +38 -10
  28. package/lib/types/client/preset-manager.js +235 -185
  29. package/lib/types/client/preset-requests.d.ts +12 -0
  30. package/lib/types/client/preset-requests.js +101 -0
  31. package/lib/types/client/tool-policy.d.ts +33 -0
  32. package/lib/types/client/tool-policy.js +336 -0
  33. package/lib/types/contracts/preset-editor-schema.d.ts +78 -0
  34. package/lib/types/contracts/preset-editor-schema.js +95 -0
  35. package/lib/types/{prompt.js → contracts/prompt.js} +13 -7
  36. package/lib/types/{settings.d.ts → contracts/settings.d.ts} +11 -4
  37. package/lib/types/{settings.js → contracts/settings.js} +22 -6
  38. package/lib/types/contracts/tool-policy-contract.d.ts +63 -0
  39. package/lib/types/contracts/tool-policy-contract.js +33 -0
  40. package/lib/types/contracts/ui-contracts.d.ts +92 -0
  41. package/lib/types/contracts/ui-contracts.js +83 -0
  42. package/lib/types/entries/client.d.ts +10 -0
  43. package/lib/types/entries/client.js +10 -0
  44. package/lib/types/{compact-command.d.ts → entries/compact-command.d.ts} +2 -0
  45. package/lib/types/entries/compact-command.js +176 -0
  46. package/lib/types/{compaction.d.ts → entries/compaction.d.ts} +15 -3
  47. package/lib/types/{compaction.js → entries/compaction.js} +47 -11
  48. package/lib/types/entries/hybrid-executor.d.ts +19 -0
  49. package/lib/types/entries/hybrid-executor.js +57 -0
  50. package/lib/types/entries/index.d.ts +66 -0
  51. package/lib/types/entries/index.js +192 -0
  52. package/lib/types/entries/preferences.d.ts +11 -0
  53. package/lib/types/entries/preferences.js +16 -0
  54. package/lib/types/entries/tool-policy.d.ts +97 -0
  55. package/lib/types/entries/tool-policy.js +158 -0
  56. package/lib/types/entries/typert.host.d.ts +23 -0
  57. package/lib/types/entries/typert.host.js +24 -0
  58. package/lib/types/hybrid/codex-hybrid-executor.d.ts +44 -0
  59. package/lib/types/hybrid/codex-hybrid-executor.js +257 -0
  60. package/lib/types/hybrid/hybrid-sdk.d.ts +13 -0
  61. package/lib/types/hybrid/hybrid-sdk.js +196 -0
  62. package/lib/types/hybrid/program-calls.d.ts +28 -0
  63. package/lib/types/hybrid/program-calls.js +193 -0
  64. package/lib/types/hybrid/subcall-scheduler.d.ts +90 -0
  65. package/lib/types/hybrid/subcall-scheduler.js +343 -0
  66. package/lib/types/policy/deferred-tools.d.ts +42 -0
  67. package/lib/types/policy/deferred-tools.js +264 -0
  68. package/lib/types/policy/overlay-installer.d.ts +12 -0
  69. package/lib/types/policy/overlay-installer.js +179 -0
  70. package/lib/types/policy/rule-resolver.d.ts +94 -0
  71. package/lib/types/policy/rule-resolver.js +114 -0
  72. package/lib/types/policy/tool-capabilities.d.ts +33 -0
  73. package/lib/types/policy/tool-capabilities.js +46 -0
  74. package/lib/types/{activity.d.ts → presets/activity.d.ts} +3 -5
  75. package/lib/types/{activity.js → presets/activity.js} +51 -27
  76. package/lib/types/presets/desktop-preset.d.ts +22 -0
  77. package/lib/types/presets/desktop-preset.js +43 -0
  78. package/lib/types/presets/preset-editor.d.ts +47 -0
  79. package/lib/types/presets/preset-editor.js +81 -0
  80. package/lib/types/presets/preset-prompt-catalog.d.ts +23 -0
  81. package/lib/types/presets/preset-prompt-catalog.js +215 -0
  82. package/lib/types/presets/preset-tool-catalog.d.ts +5 -0
  83. package/lib/types/presets/preset-tool-catalog.js +58 -0
  84. package/lib/types/presets/runtime-enhancements.d.ts +45 -0
  85. package/lib/types/presets/runtime-enhancements.js +349 -0
  86. package/lib/types/presets/small-window-compaction.d.ts +15 -0
  87. package/lib/types/presets/small-window-compaction.js +121 -0
  88. package/lib/types/responses/compact-checkpoint.d.ts +27 -0
  89. package/lib/types/responses/compact-checkpoint.js +257 -0
  90. package/lib/types/responses/fetch-transport.d.ts +16 -0
  91. package/lib/types/responses/fetch-transport.js +257 -0
  92. package/lib/types/responses/remote-compact.d.ts +13 -0
  93. package/lib/types/responses/remote-compact.js +319 -0
  94. package/lib/types/responses/sse-diagnostics.d.ts +9 -0
  95. package/lib/types/responses/sse-diagnostics.js +157 -0
  96. package/lib/types/responses/wire-rewrite.d.ts +35 -0
  97. package/lib/types/responses/wire-rewrite.js +237 -0
  98. package/lib/types/tools/exec-output.d.ts +58 -0
  99. package/lib/types/tools/exec-output.js +173 -0
  100. package/lib/types/tools/exec-plan-tools.d.ts +37 -0
  101. package/lib/types/tools/exec-plan-tools.js +265 -0
  102. package/lib/types/tools/exec-runner.d.ts +21 -0
  103. package/lib/types/tools/exec-runner.js +385 -0
  104. package/lib/types/tools/patch-tool.d.ts +16 -0
  105. package/lib/types/tools/patch-tool.js +258 -0
  106. package/lib/types/{patch.d.ts → tools/patch.d.ts} +1 -1
  107. package/lib/types/{patch.js → tools/patch.js} +96 -21
  108. package/locale/en.json +6 -0
  109. package/locale/hybrid-executor/en.json +6 -0
  110. package/locale/hybrid-executor/zh.json +6 -0
  111. package/locale/tool-policy/en.json +6 -0
  112. package/locale/tool-policy/zh.json +6 -0
  113. package/locale/zh.json +6 -0
  114. package/package.json +297 -299
  115. package/presets/{codex-collaboration → codex-hybrid}/agent.cordis.yml +45 -48
  116. package/presets/codex-hybrid/preset.yml +3 -0
  117. package/scripts/benchmark-tool-policy.mjs +186 -0
  118. package/scripts/build-preset.mjs +19 -0
  119. package/scripts/clean-build.mjs +11 -0
  120. package/src/client/activity.ts +83 -0
  121. package/src/client/desktop.tsx +276 -0
  122. package/src/client/index.tsx +391 -0
  123. package/src/client/policy-drafts.ts +56 -0
  124. package/src/client/policy-locale.ts +362 -0
  125. package/src/client/preset-manager.tsx +376 -0
  126. package/src/client/preset-requests.ts +113 -0
  127. package/src/client/tool-policy.tsx +402 -0
  128. package/src/contracts/preset-editor-schema.ts +110 -0
  129. package/src/contracts/prompt.ts +66 -0
  130. package/src/contracts/settings.ts +103 -0
  131. package/src/contracts/tool-policy-contract.ts +93 -0
  132. package/src/contracts/ui-contracts.ts +173 -0
  133. package/src/entries/client.tsx +14 -0
  134. package/src/entries/compact-command.ts +256 -0
  135. package/src/entries/compaction.ts +218 -0
  136. package/src/entries/hybrid-executor.ts +76 -0
  137. package/src/entries/index.ts +298 -0
  138. package/src/entries/preferences.ts +17 -0
  139. package/src/entries/tool-policy.ts +162 -0
  140. package/src/entries/typert.host.ts +29 -0
  141. package/src/hybrid/codex-hybrid-executor.ts +310 -0
  142. package/src/hybrid/hybrid-sdk.ts +217 -0
  143. package/src/hybrid/program-calls.ts +202 -0
  144. package/src/hybrid/subcall-scheduler.ts +446 -0
  145. package/src/policy/deferred-tools.ts +331 -0
  146. package/src/policy/overlay-installer.ts +191 -0
  147. package/src/policy/rule-resolver.ts +128 -0
  148. package/src/policy/tool-capabilities.ts +88 -0
  149. package/src/presets/activity.ts +146 -0
  150. package/src/presets/desktop-preset.ts +60 -0
  151. package/src/presets/preset-editor.ts +101 -0
  152. package/src/presets/preset-prompt-catalog.ts +221 -0
  153. package/src/presets/preset-tool-catalog.ts +58 -0
  154. package/src/presets/runtime-enhancements.ts +415 -0
  155. package/src/presets/small-window-compaction.ts +166 -0
  156. package/src/responses/compact-checkpoint.ts +264 -0
  157. package/src/responses/fetch-transport.ts +290 -0
  158. package/src/responses/remote-compact.ts +393 -0
  159. package/src/responses/sse-diagnostics.ts +156 -0
  160. package/src/responses/wire-rewrite.ts +261 -0
  161. package/src/tools/exec-output.ts +211 -0
  162. package/src/tools/exec-plan-tools.ts +307 -0
  163. package/src/tools/exec-runner.ts +445 -0
  164. package/src/tools/patch-tool.ts +331 -0
  165. package/src/tools/patch.ts +328 -0
  166. package/tsconfig.json +29 -0
  167. package/tsdown.config.ts +110 -0
  168. package/lib/installer.js +0 -237
  169. package/lib/invariant.js +0 -23
  170. package/lib/types/activity-types.d.ts +0 -6
  171. package/lib/types/activity-types.js +0 -3
  172. package/lib/types/client/preset-copy.d.ts +0 -42
  173. package/lib/types/client/preset-copy.js +0 -81
  174. package/lib/types/compact-command.js +0 -79
  175. package/lib/types/context.d.ts +0 -8
  176. package/lib/types/context.js +0 -14
  177. package/lib/types/exec.d.ts +0 -46
  178. package/lib/types/exec.js +0 -365
  179. package/lib/types/index.d.ts +0 -95
  180. package/lib/types/index.js +0 -738
  181. package/lib/types/installer.d.ts +0 -27
  182. package/lib/types/installer.js +0 -146
  183. package/lib/types/invariant.d.ts +0 -16
  184. package/lib/types/invariant.js +0 -22
  185. package/lib/types/preset-contract.d.ts +0 -69
  186. package/lib/types/preset-contract.js +0 -22
  187. package/lib/types/preset-editor-remote.d.ts +0 -30
  188. package/lib/types/preset-editor-remote.js +0 -37
  189. package/lib/types/preset-editor.d.ts +0 -69
  190. package/lib/types/preset-editor.js +0 -557
  191. package/lib/types/preset-templates.d.ts +0 -36
  192. package/lib/types/preset-templates.js +0 -12
  193. package/lib/types/prompt-sections.d.ts +0 -15
  194. package/lib/types/prompt-sections.js +0 -23
  195. package/lib/types/remote.d.ts +0 -40
  196. package/lib/types/remote.js +0 -683
  197. package/lib/types/typert.host.d.ts +0 -47
  198. package/lib/types/typert.host.js +0 -99
  199. package/presets/codex-collaboration/preset.yml +0 -3
  200. /package/lib/types/{prompt.d.ts → contracts/prompt.d.ts} +0 -0
@@ -0,0 +1,2422 @@
1
+ import { createScope, scopeChainOf, scopeOf, scopeParentOf } from "@deepseek-ai/dsh-scope";
2
+ import { defineTool } from "@deepseek-ai/dsh-tools";
3
+ import { randomBytes, randomUUID } from "node:crypto";
4
+ import { PERSONA_PREFIX_SECTION, PERSONA_SUFFIX_SECTION } from "@deepseek-ai/dsh-system-prompt";
5
+ import { YAMLMap, isMap, isScalar, isSeq, parseDocument } from "yaml";
6
+ import { ESCALATION_TARGETS, approveEscalation, escalationHintMarker, sandboxDenialMarker, sandboxPermissionsDescription, validateEscalationArgs } from "@deepseek-ai/dsh-sandbox";
7
+ import { isAbsolute, resolve } from "node:path";
8
+ import { HarnessError } from "@deepseek-ai/dsh-llm";
9
+ import { FsError } from "@deepseek-ai/dsh-fs";
10
+ import z from "@deepseek-ai/schemastery";
11
+ //#region lib/types/contracts/ui-contracts.js
12
+ const CODEX_CONTEXT_MAX = 1e6;
13
+ /** Client-safe current-preset prompt catalog; editable targets have reviewed native contracts. */
14
+ const PRESET_PROMPT_NAMES = [
15
+ "deployment:persona-prefix",
16
+ "deployment:persona-suffix",
17
+ "codex:base"
18
+ ];
19
+ //#endregion
20
+ //#region lib/types/contracts/tool-policy-contract.js
21
+ /** Legacy configuration remains a baseline, never a live second veto of an explicit choice. */
22
+ function legacyToolAction(rule, name, context = {}) {
23
+ let action = "keep";
24
+ if (rule !== void 0) {
25
+ if (rule.allow !== void 0 && !rule.allow.includes(name) || rule.deny?.includes(name)) return "hide";
26
+ if ((name === "bash" || name === "pwsh") && rule.replaceShell !== false) action = "codex-exec";
27
+ if (name === "todo_write" && rule.replacePlan !== false) action = "codex-plan";
28
+ if ((name === "edit" || name === "write") && rule.replacePatch === true) action = "codex-patch";
29
+ }
30
+ if (action === "keep" && context.defaultDeferred === true) action = "defer";
31
+ const capability = context.codexTool?.capability ?? (action === "codex-exec" ? "terminalToolsEnabled" : action === "codex-plan" ? "planToolEnabled" : action === "codex-patch" ? "patchToolEnabled" : void 0);
32
+ if (!(context.codexTool?.presetOverridesLegacy === true && context.codexTool.presetEnabled) && capability !== void 0 && context.legacyCapabilities?.[capability] === false) return "hide";
33
+ return action;
34
+ }
35
+ /** Policy action only: `keep` still respects the original preset's local enablement. */
36
+ function effectiveToolAction(rule, name, context = {}) {
37
+ return rule?.tools?.find((tool) => tool.name === name)?.action ?? legacyToolAction(rule, name, context);
38
+ }
39
+ //#endregion
40
+ //#region lib/types/policy/deferred-tools.js
41
+ const ACTIVATE_TOOLS_NAME = "activate_tools";
42
+ const CODEX_HYBRID_DEFAULTS_SERVICE = "codexHybridDefaults";
43
+ const HYBRID_DEFAULTS_KEY = Symbol.for("@shuind/dsh-codex-harness:hybrid-defaults:v1");
44
+ const HYBRID_HIDDEN_KEY = Symbol.for("@shuind/dsh-codex-harness:hybrid-hidden:v1");
45
+ function scopeSetMap(registryKey) {
46
+ const registry = globalThis;
47
+ const existing = registry[registryKey];
48
+ if (existing instanceof WeakMap) return existing;
49
+ const created = /* @__PURE__ */ new WeakMap();
50
+ registry[registryKey] = created;
51
+ return created;
52
+ }
53
+ function readScopedToolSet(ctx, registryKey, serviceKey, scope = scopeOf(ctx)) {
54
+ const direct = (typeof ctx.get === "function" ? ctx.get(CODEX_HYBRID_DEFAULTS_SERVICE) : void 0)?.[serviceKey];
55
+ if (direct !== void 0) return direct;
56
+ if (scope === void 0) return void 0;
57
+ const map = scopeSetMap(registryKey);
58
+ for (const key of scopeChainOf(scope)) {
59
+ const entry = map.get(key);
60
+ if (entry !== void 0) return entry;
61
+ }
62
+ }
63
+ /** Read default deferred tool names from ancestor scopes or injected defaults service. */
64
+ function readDefaultDeferredTools(ctx, scope = scopeOf(ctx)) {
65
+ return readScopedToolSet(ctx, HYBRID_DEFAULTS_KEY, "deferredTools", scope);
66
+ }
67
+ /** Read default hidden tool names from ancestor scopes or injected defaults service. */
68
+ function readDefaultHiddenTools(ctx, scope = scopeOf(ctx)) {
69
+ return readScopedToolSet(ctx, HYBRID_HIDDEN_KEY, "hiddenTools", scope);
70
+ }
71
+ const MAX_SUMMARY_CHARS = 140;
72
+ /** Collapse a tool description to a single-line summary capped for prompt stability. */
73
+ function summarizeToolDescription(description) {
74
+ const collapsed = (description.trim().split(/\r?\n/u)[0] ?? "").replace(/\s+/gu, " ").trim();
75
+ if (collapsed.length === 0) return "No description provided.";
76
+ const sentenceEnd = collapsed.search(/[.!?。!?](?:\s|$)/u);
77
+ const sentence = sentenceEnd >= 0 ? collapsed.slice(0, sentenceEnd + 1).trim() : collapsed;
78
+ if (sentence.length <= MAX_SUMMARY_CHARS) return sentence;
79
+ return `${sentence.slice(0, 137).trimEnd()}...`;
80
+ }
81
+ /** Deterministic catalog guidance naming every deferred tool for `activate_tools`. */
82
+ function buildDeferredToolsGuidance(definitions) {
83
+ const sorted = [...definitions].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
84
+ return [`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):`, ...sorted.map((def) => `- \`${def.name}\`: ${summarizeToolDescription(def.description)}`)].join("\n");
85
+ }
86
+ function wrapDeferredExecution(definition, onTouch) {
87
+ const descriptors = Object.getOwnPropertyDescriptors(definition);
88
+ descriptors.execute = {
89
+ value(args, exec) {
90
+ onTouch(definition.name);
91
+ return Reflect.apply(definition.execute, this, [args, exec]);
92
+ },
93
+ enumerable: true,
94
+ configurable: true
95
+ };
96
+ return Object.defineProperties(Object.create(Object.getPrototypeOf(definition)), descriptors);
97
+ }
98
+ /** Build the per-Agent `activate_tools` capability that flips `when` admission on next step. */
99
+ function createActivateToolsDefinition(allowedDefinitions, activated, onTouch) {
100
+ const availableNames = [...allowedDefinitions.keys()].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
101
+ return defineTool({
102
+ name: ACTIVATE_TOOLS_NAME,
103
+ description: "Activate deferred tools by name so their schemas become callable on the next model step.",
104
+ parameters: { names: {
105
+ type: "array",
106
+ required: true,
107
+ items: { type: "string" },
108
+ description: "Exact deferred tool names to activate (1-32)."
109
+ } },
110
+ isConcurrencySafe: () => true,
111
+ output: {
112
+ schema: {
113
+ type: "object",
114
+ additionalProperties: false,
115
+ properties: {
116
+ activated: {
117
+ type: "array",
118
+ required: true,
119
+ items: { type: "string" }
120
+ },
121
+ alreadyActive: {
122
+ type: "array",
123
+ required: true,
124
+ items: { type: "string" }
125
+ },
126
+ unknown: {
127
+ type: "array",
128
+ required: true,
129
+ items: { type: "string" }
130
+ }
131
+ }
132
+ },
133
+ render: (_args, value) => {
134
+ const lines = [];
135
+ if (value.activated.length > 0) lines.push(`Activated for the next step: ${value.activated.join(", ")}. Wait for the next step before calling them.`);
136
+ if (value.alreadyActive.length > 0) lines.push(`Already active: ${value.alreadyActive.join(", ")}.`);
137
+ if (value.unknown.length > 0) {
138
+ const valid = availableNames.length > 0 ? availableNames.join(", ") : "(none)";
139
+ lines.push(`Unknown deferred tools: ${value.unknown.join(", ")}. Available: ${valid}.`);
140
+ }
141
+ return [{
142
+ type: "text",
143
+ text: lines.length > 0 ? lines.join("\n") : "No tools activated."
144
+ }];
145
+ }
146
+ },
147
+ async execute(args) {
148
+ const names = args.names;
149
+ if (!Array.isArray(names) || names.length < 1 || names.length > 32) throw new Error(`${ACTIVATE_TOOLS_NAME}: names must contain between 1 and 32 tool names`);
150
+ const seen = /* @__PURE__ */ new Set();
151
+ const newlyActivated = [];
152
+ const alreadyActive = [];
153
+ const unknown = [];
154
+ for (const raw of names) {
155
+ if (typeof raw !== "string") throw new Error(`${ACTIVATE_TOOLS_NAME}: every entry in names must be a string`);
156
+ const name = raw.trim();
157
+ if (name.length === 0) throw new Error(`${ACTIVATE_TOOLS_NAME}: tool names must be non-empty strings`);
158
+ if (seen.has(name)) continue;
159
+ seen.add(name);
160
+ if (!allowedDefinitions.has(name)) unknown.push(name);
161
+ else if (activated.has(name)) {
162
+ onTouch?.(name);
163
+ alreadyActive.push(name);
164
+ } else {
165
+ activated.add(name);
166
+ onTouch?.(name);
167
+ newlyActivated.push(name);
168
+ }
169
+ }
170
+ return {
171
+ activated: newlyActivated,
172
+ alreadyActive,
173
+ unknown
174
+ };
175
+ }
176
+ });
177
+ }
178
+ /**
179
+ * Shadow deferred definitions with step-conditional admission and publish
180
+ * `activate_tools` + a deterministic prompt section inside the Agent scope.
181
+ * Cold tools untouched for more than `DEFERRED_RECENT_TURN_WINDOW` turns are
182
+ * reclaimed after local or remote compaction completes.
183
+ */
184
+ function* yieldDeferredToolsOverlay(tools, systemPrompt, definitions, agent) {
185
+ const sorted = [...definitions].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
186
+ if (sorted.length === 0) return;
187
+ const activated = /* @__PURE__ */ new Set();
188
+ const allowedDefinitions = /* @__PURE__ */ new Map();
189
+ let currentTurn = typeof agent?.ctx?.get === "function" ? agent.ctx.get("agents")?.turnBoundaryOf(agent.session).lastTurn ?? 0 : 0;
190
+ const lastTouchTurn = /* @__PURE__ */ new Map();
191
+ const touch = (name) => {
192
+ lastTouchTurn.set(name, currentTurn);
193
+ };
194
+ const isCold = (name) => {
195
+ const touched = lastTouchTurn.get(name);
196
+ return touched === void 0 || currentTurn - touched > 2;
197
+ };
198
+ for (const definition of sorted) {
199
+ allowedDefinitions.set(definition.name, definition);
200
+ yield tools.register(wrapDeferredExecution(definition, touch), { when: () => activated.has(definition.name) });
201
+ }
202
+ yield tools.register(createActivateToolsDefinition(allowedDefinitions, activated, touch));
203
+ yield systemPrompt.section({
204
+ name: "codex:deferred-tools",
205
+ order: 1018,
206
+ interpolate: false,
207
+ text: buildDeferredToolsGuidance(sorted)
208
+ });
209
+ if (agent !== void 0 && typeof agent.ctx.on === "function") {
210
+ let pending;
211
+ yield agent.ctx.on("session/event", (session, event) => {
212
+ if (session.id !== agent.session.id) return;
213
+ if (event.type === "turn/start") {
214
+ if (typeof event.data.turn === "number" && event.data.turn > currentTurn) currentTurn = event.data.turn;
215
+ return;
216
+ }
217
+ if (event.type === "compaction/start") {
218
+ if (typeof event.data.turn === "number" && event.data.turn > currentTurn) currentTurn = event.data.turn;
219
+ pending = {
220
+ compactionId: event.data.compactionId,
221
+ cold: new Set([...activated].filter(isCold)),
222
+ hasSummary: false
223
+ };
224
+ return;
225
+ }
226
+ if (event.type === "compaction/summary") {
227
+ if (pending === void 0 || event.data.compactionId !== pending.compactionId) return;
228
+ pending.hasSummary = true;
229
+ return;
230
+ }
231
+ if (event.type === "compaction/end") {
232
+ if (pending === void 0 || event.data.compactionId !== pending.compactionId) return;
233
+ const current = pending;
234
+ pending = void 0;
235
+ if (event.data.error !== void 0 || !current.hasSummary) return;
236
+ for (const name of current.cold) {
237
+ if (!isCold(name)) continue;
238
+ activated.delete(name);
239
+ lastTouchTurn.delete(name);
240
+ }
241
+ }
242
+ }, { global: true });
243
+ }
244
+ }
245
+ //#endregion
246
+ //#region lib/types/presets/preset-prompt-catalog.js
247
+ /** Public, read-only preset prompt discovery. No private registry, Agent, or JS/YAML evaluation. */
248
+ function literal(map, key) {
249
+ const node = map.get(key, true);
250
+ return isScalar(node) && !node.tag ? node.value : void 0;
251
+ }
252
+ /** Native Persona's public source owns these exact names/placements/complete semantics. */
253
+ function candidates(content, placement) {
254
+ const doc = parseDocument(content, {
255
+ strict: true,
256
+ uniqueKeys: true,
257
+ logLevel: "silent"
258
+ });
259
+ if (doc.errors.length || !isSeq(doc.contents)) throw new Error("invalid-preset-prompt-declaration");
260
+ const found = [];
261
+ const readonly = [];
262
+ function visit(rows, parent = "", conditionalParent = false, isolatedParent = false) {
263
+ if (!isSeq(rows)) return;
264
+ for (const [index, row] of rows.items.entries()) {
265
+ if (!isMap(row) || literal(row, "disabled") === true) continue;
266
+ const module = literal(row, "name");
267
+ const path = `${parent}/${String(literal(row, "id") ?? index)}`;
268
+ const conditionalRow = conditionalParent || row.has("disabled") && literal(row, "disabled") === void 0;
269
+ const isolation = row.get("isolate", true);
270
+ const isolated = isolatedParent || row.has("isolate") && (!isMap(isolation) || isolation.has("systemPrompt"));
271
+ let config = row.get("config", true);
272
+ if (isSeq(config)) {
273
+ visit(config, path, conditionalRow, isolated);
274
+ continue;
275
+ }
276
+ if (config === void 0 && module === "@shuind/dsh-codex-harness") config = new YAMLMap();
277
+ if (typeof module !== "string" || !isMap(config)) continue;
278
+ if (module === "@deepseek-ai/dsh-persona") {
279
+ const completeNode = config.get("complete", true);
280
+ const complete = literal(config, "complete");
281
+ const uncertain = conditionalRow || completeNode !== void 0 && typeof complete !== "boolean";
282
+ for (const [key, name, order, label] of [[
283
+ "prefix",
284
+ PERSONA_PREFIX_SECTION,
285
+ placement("DEPLOYMENT_PERSONA_PREFIX"),
286
+ "Persona"
287
+ ], [
288
+ "suffix",
289
+ PERSONA_SUFFIX_SECTION,
290
+ placement("DEPLOYMENT_PERSONA_SUFFIX"),
291
+ "Persona · suffix"
292
+ ]]) {
293
+ const text = literal(config, key);
294
+ const missingSuffix = key === "suffix" && !config.has(key);
295
+ const reason = isolated ? "isolated-prompt-registry" : uncertain ? "dynamic-declaration" : void 0;
296
+ found.push({
297
+ name,
298
+ label,
299
+ module,
300
+ order,
301
+ complete: key === "prefix" && complete === true,
302
+ interpolate: true,
303
+ ...typeof text === "string" ? { literal: text } : missingSuffix ? { literal: "" } : {},
304
+ ...reason === void 0 ? {} : { reason }
305
+ });
306
+ }
307
+ } else if (module === "@shuind/dsh-codex-harness" && literal(config, "codexCore") !== false) found.push({
308
+ name: "codex:base",
309
+ label: "Codex 操作提示词",
310
+ module,
311
+ order: 10,
312
+ complete: false,
313
+ interpolate: true,
314
+ ...isolated ? { reason: "isolated-prompt-registry" } : conditionalRow || config.has("codexCore") && literal(config, "codexCore") === void 0 ? { reason: "dynamic-declaration" } : {}
315
+ });
316
+ else for (const key of [
317
+ "prefix",
318
+ "suffix",
319
+ "text",
320
+ "section",
321
+ "prompt",
322
+ "systemPrompt",
323
+ "instructions"
324
+ ]) {
325
+ if (!config.has(key) || module === "@deepseek-ai/dsh-plan-mode") continue;
326
+ const text = literal(config, key);
327
+ readonly.push({
328
+ name: `declaration:${path}:${key}`,
329
+ label: `${module} · ${key}`,
330
+ text: typeof text === "string" ? text : "",
331
+ editable: false,
332
+ reason: typeof text === "string" ? "unknown-section-contract" : "dynamic-declaration"
333
+ });
334
+ }
335
+ }
336
+ }
337
+ visit(doc.contents);
338
+ return {
339
+ found,
340
+ readonly
341
+ };
342
+ }
343
+ function moduleSignature(rows) {
344
+ return JSON.stringify(rows.map((row) => [
345
+ row.moduleName,
346
+ row.baseUrl ?? "",
347
+ row.useHostBase
348
+ ]));
349
+ }
350
+ const probeCache = /* @__PURE__ */ new WeakMap();
351
+ async function runProbePresetPrompts(ctx, preset, expectedScope, useCache) {
352
+ if (typeof preset !== "string" || !preset.trim() || preset.length > 256) throw new Error("invalid-preset-id");
353
+ const registry = ctx.get("agentPresets");
354
+ const prompt = ctx.get("systemPrompt");
355
+ if (registry === void 0 || prompt === void 0 || typeof registry.acquireScope !== "function" || typeof registry.readDocument !== "function" || typeof registry.inspectCompositions !== "function") throw new Error("preset-prompt-catalog-unavailable");
356
+ const document = await registry.readDocument(preset);
357
+ const lease = await registry.acquireScope(preset);
358
+ let view;
359
+ try {
360
+ if (expectedScope !== void 0 && lease.key !== expectedScope) throw new Error("preset-prompt-revision-mismatch");
361
+ const key = {};
362
+ view = createScope(ctx, key, { parent: lease.key });
363
+ const inspection = registry.inspectCompositions(view.ctx);
364
+ if (inspection.length !== 1 || inspection[0]?.id !== preset) throw new Error("preset-prompt-revision-unavailable");
365
+ const modules = moduleSignature(inspection[0].modules);
366
+ const cacheKey = `${preset}\0${modules}\0${document.content}`;
367
+ if (useCache) {
368
+ const cached = probeCache.get(lease.key)?.get(cacheKey);
369
+ if (cached !== void 0) return cached;
370
+ }
371
+ const active = new Set(inspection[0].modules.map((row) => row.moduleName));
372
+ const declared = candidates(document.content, (name) => prompt.getSectionOrder(name));
373
+ const definitions = /* @__PURE__ */ new Map();
374
+ const sections = [];
375
+ let baseline;
376
+ try {
377
+ baseline = await prompt.assemble({ scope: key });
378
+ } catch {
379
+ return {
380
+ scope: lease.key,
381
+ modules,
382
+ definitions,
383
+ catalog: {
384
+ preset,
385
+ sections: [...declared.found.map((row) => ({
386
+ name: row.name,
387
+ label: row.label,
388
+ text: row.literal ?? "",
389
+ editable: false,
390
+ reason: "assembly-unavailable"
391
+ })), ...declared.readonly].slice(0, 200)
392
+ }
393
+ };
394
+ }
395
+ const seen = /* @__PURE__ */ new Set();
396
+ for (const row of declared.found) {
397
+ if (seen.has(row.name)) continue;
398
+ seen.add(row.name);
399
+ const actual = baseline.sections.find((section) => section.name === row.name);
400
+ let reason = row.reason ?? (!active.has(row.module) ? "inactive-contribution" : void 0) ?? (declared.found.filter((candidate) => candidate.name === row.name).length !== 1 ? "ambiguous-contribution" : void 0) ?? (actual === void 0 ? "not-effective-or-complete-suppressed" : void 0);
401
+ if (reason === void 0 && row.complete && (baseline.sections.length !== 1 || baseline.sections[0]?.name !== row.name)) reason = "complete-contract-mismatch";
402
+ if (reason === void 0) {
403
+ const marker = `preset-prompt-probe:${randomUUID()}`;
404
+ const undo = view.ctx.get("systemPrompt").section({
405
+ name: row.name,
406
+ order: row.order,
407
+ complete: row.complete,
408
+ interpolate: row.interpolate,
409
+ text: marker
410
+ });
411
+ try {
412
+ const probed = await prompt.assemble({
413
+ scope: key,
414
+ codexPresetPromptProbe: true
415
+ });
416
+ if (probed.sections.find((section) => section.name === row.name)?.text !== marker || JSON.stringify(probed.sections.map((section) => section.name)) !== JSON.stringify(baseline.sections.map((section) => section.name)) || row.complete && (probed.sections.length !== 1 || probed.sections[0]?.name !== row.name)) reason = "not-directly-overridable";
417
+ } catch {
418
+ reason = "not-directly-overridable";
419
+ } finally {
420
+ undo();
421
+ }
422
+ }
423
+ const text = actual?.text ?? row.literal ?? "";
424
+ if (text.length > 1e6) reason = "prompt-too-large";
425
+ sections.push({
426
+ name: row.name,
427
+ label: row.label,
428
+ text: text.slice(0, 1e6),
429
+ editable: reason === void 0,
430
+ order: row.order,
431
+ complete: row.complete,
432
+ interpolate: row.interpolate,
433
+ ...reason === void 0 ? {} : { reason }
434
+ });
435
+ if (reason === void 0) definitions.set(row.name, {
436
+ name: row.name,
437
+ order: row.order,
438
+ complete: row.complete,
439
+ interpolate: row.interpolate,
440
+ text
441
+ });
442
+ }
443
+ for (const row of baseline.sections) if (!seen.has(row.name)) sections.push({
444
+ name: row.name,
445
+ label: row.name,
446
+ text: row.text.slice(0, 1e6),
447
+ editable: false,
448
+ reason: "unknown-or-host-owned-section"
449
+ });
450
+ sections.push(...declared.readonly);
451
+ if ((await registry.readDocument(preset)).content !== document.content) throw new Error("preset-prompt-revision-mismatch");
452
+ const probe = {
453
+ scope: lease.key,
454
+ modules,
455
+ definitions,
456
+ catalog: {
457
+ preset,
458
+ sections: sections.slice(0, 200)
459
+ }
460
+ };
461
+ if (useCache) {
462
+ let byKey = probeCache.get(lease.key);
463
+ if (byKey === void 0) {
464
+ byKey = /* @__PURE__ */ new Map();
465
+ probeCache.set(lease.key, byKey);
466
+ }
467
+ byKey.set(cacheKey, probe);
468
+ }
469
+ return probe;
470
+ } finally {
471
+ try {
472
+ await view?.dispose();
473
+ } finally {
474
+ await lease[Symbol.asyncDispose]();
475
+ }
476
+ }
477
+ }
478
+ /** Cached variant keyed by live scope identity, active modules, and document content. */
479
+ async function probePresetPromptsCached(ctx, preset, expectedScope) {
480
+ return runProbePresetPrompts(ctx, preset, expectedScope, true);
481
+ }
482
+ function preparePromptOverrides(probe, overrides) {
483
+ const sections = overrides.map((override) => {
484
+ const original = probe.definitions.get(override.name);
485
+ if (original === void 0) throw new Error(`unsupported-preset-prompt-override: ${override.name}`);
486
+ return {
487
+ ...original,
488
+ text: override.text
489
+ };
490
+ });
491
+ return {
492
+ scope: probe.scope,
493
+ modules: probe.modules,
494
+ sections
495
+ };
496
+ }
497
+ function matchesPromptRevision(ctx, preset, prepared) {
498
+ const inspection = ctx.get("agentPresets")?.inspectCompositions(ctx);
499
+ return inspection?.length === 1 && inspection[0]?.id === preset && moduleSignature(inspection[0].modules) === prepared.modules;
500
+ }
501
+ //#endregion
502
+ //#region lib/types/tools/exec-output.js
503
+ /** Output truncation, `\r` sanitization, timing bounds, and rendering for unified exec. */
504
+ const MIN_YIELD_TIME_MS = 250;
505
+ const WINDOWS_INITIAL_EXEC_YIELD_TIME_MS = 1e4;
506
+ const MIN_EMPTY_YIELD_TIME_MS = 5e3;
507
+ const MAX_YIELD_TIME_MS = 3e4;
508
+ const MAX_EMPTY_YIELD_TIME_MS = 3e5;
509
+ const DEFAULT_OUTPUT_TOKENS = 1e4;
510
+ const APPROX_BYTES_PER_TOKEN = 4;
511
+ const INTERACTIVE_PROMPT_RE = /(?:\[(?:y\/n|yes\/no)\]|\((?:y\/n|yes\/no)\)|(?:password|passphrase|overwrite|continue)\s*[?:]\s*$)/i;
512
+ function positiveFinite(name, value) {
513
+ if (value !== void 0 && (!Number.isFinite(value) || value < 0)) throw new Error(`${name} must be a non-negative finite number`);
514
+ }
515
+ function normalizeWaitMs(value, fallback, empty = false, initialExec = false) {
516
+ const lower = empty ? MIN_EMPTY_YIELD_TIME_MS : initialExec && process.platform === "win32" ? WINDOWS_INITIAL_EXEC_YIELD_TIME_MS : MIN_YIELD_TIME_MS;
517
+ return Math.max(lower, Math.min(empty ? MAX_EMPTY_YIELD_TIME_MS : MAX_YIELD_TIME_MS, Math.trunc(value ?? fallback)));
518
+ }
519
+ function outputLimit(maxOutputBytes, maxOutputTokens) {
520
+ const tokens = maxOutputTokens ?? DEFAULT_OUTPUT_TOKENS;
521
+ if (maxOutputTokens !== void 0) positiveFinite("max_output_tokens", maxOutputTokens);
522
+ return Math.max(1, Math.min(maxOutputBytes, Math.trunc(tokens * APPROX_BYTES_PER_TOKEN)));
523
+ }
524
+ /** O(N) symmetric head+tail UTF-8 truncation that never splits a code point. */
525
+ function truncateOutput(text, maxBytes) {
526
+ const totalBytes = Buffer.byteLength(text, "utf8");
527
+ if (totalBytes <= maxBytes) return { text };
528
+ const buf = Buffer.from(text, "utf8");
529
+ const headBudget = Math.ceil(maxBytes / 2);
530
+ const tailBudget = Math.floor(maxBytes / 2);
531
+ let headEnd = Math.min(headBudget, buf.length);
532
+ while (headEnd > 0 && headEnd < buf.length && (buf[headEnd] & 192) === 128) headEnd--;
533
+ let tailStart = Math.max(headEnd, buf.length - tailBudget);
534
+ while (tailStart < buf.length && (buf[tailStart] & 192) === 128) tailStart++;
535
+ const omittedBytes = tailStart - headEnd;
536
+ if (omittedBytes <= 0) return { text };
537
+ const marker = `…${Math.ceil(omittedBytes / APPROX_BYTES_PER_TOKEN)} tokens truncated…`;
538
+ const head = headEnd > 0 ? buf.subarray(0, headEnd).toString("utf8") : "";
539
+ const tail = tailStart < buf.length ? buf.subarray(tailStart).toString("utf8") : "";
540
+ return {
541
+ text: head.length > 0 && tail.length > 0 ? `${head}\n${marker}\n${tail}` : head.length > 0 ? `${head}\n${marker}` : tail.length > 0 ? `${marker}\n${tail}` : marker,
542
+ originalTokenCount: Math.ceil(totalBytes / APPROX_BYTES_PER_TOKEN)
543
+ };
544
+ }
545
+ /** Strip NULs and collapse bare `\r` progress overwrites on pipe output while preserving `\r\n`. */
546
+ function sanitizePipeOutput(delta) {
547
+ if (!delta.includes("\0") && !delta.includes("\r")) return delta;
548
+ const withoutNulls = delta.includes("\0") ? delta.replaceAll("\0", "") : delta;
549
+ if (!/\r(?!\n)/.test(withoutNulls)) return withoutNulls;
550
+ const lines = withoutNulls.split("\n");
551
+ return lines.map((line, index) => {
552
+ const hasCrlf = index < lines.length - 1 && line.endsWith("\r");
553
+ const body = hasCrlf ? line.slice(0, -1) : line;
554
+ if (!body.includes("\r")) return hasCrlf ? `${body}\r` : body;
555
+ const collapsed = body.split("\r").findLast((segment) => segment.length > 0) ?? "";
556
+ return hasCrlf ? `${collapsed}\r` : collapsed;
557
+ }).join("\n");
558
+ }
559
+ function hasInteractivePrompt(output) {
560
+ const lines = output.split(/\r?\n/);
561
+ for (let i = lines.length - 1; i >= 0; i--) {
562
+ const line = lines[i].trimEnd();
563
+ if (line.length === 0) continue;
564
+ return INTERACTIVE_PROMPT_RE.test(line);
565
+ }
566
+ return false;
567
+ }
568
+ function withChunkId(result) {
569
+ return {
570
+ chunk_id: randomBytes(3).toString("hex"),
571
+ ...result
572
+ };
573
+ }
574
+ /** Render the ordinary Responses tool result text used by Codex's unified exec tools. */
575
+ function renderExecResult(result) {
576
+ const sections = [];
577
+ if (result.chunk_id !== void 0) sections.push(`Chunk ID: ${result.chunk_id}`);
578
+ sections.push(`Wall time: ${result.wall_time_seconds.toFixed(4)} seconds`);
579
+ if (result.exit_code !== void 0) sections.push(`Process exited with code ${result.exit_code}`);
580
+ if (result.session_id !== void 0) sections.push(`Process running with session ID ${result.session_id}`);
581
+ if (result.job_id !== void 0) sections.push(`Background job ID: ${result.job_id}`);
582
+ if (result.original_token_count !== void 0) sections.push(`Original token count: ${result.original_token_count}`);
583
+ sections.push("Output:", result.output);
584
+ return sections.join("\n");
585
+ }
586
+ /** Preserve policy/runner facts after bounding command output; never truncate these markers. */
587
+ function sandboxNotes(sandbox, escalationAvailable) {
588
+ if (sandbox?.runnerFailed) return [`[sandbox: the sandbox runner itself failed under ${sandbox.mode} mode — the command did not run; this is a sandbox problem, not a command failure]`];
589
+ if (!sandbox?.denied) return [];
590
+ return [sandboxDenialMarker(sandbox.mode), ...escalationAvailable ? [escalationHintMarker("command")] : []];
591
+ }
592
+ /** Surface infrastructure failures from the execution handle without reclassifying nonzero exits. */
593
+ async function assertShellCompleted(process, escalationAvailable = false) {
594
+ const result = process.result;
595
+ if (typeof result !== "function") return void 0;
596
+ try {
597
+ return await result.call(process);
598
+ } catch (error) {
599
+ const notes = sandboxNotes(process.sandbox, escalationAvailable);
600
+ if (notes.length === 0) throw error;
601
+ const message = [error instanceof Error ? error.message : String(error), ...notes].join("\n");
602
+ const failure = error instanceof HarnessError ? new HarnessError(message, error.code, { cause: error }) : new Error(message, { cause: error });
603
+ if (error instanceof Error) failure.name = error.name;
604
+ throw failure;
605
+ }
606
+ }
607
+ function readShellOutput(read, maxBytes, sandbox, escalationAvailable = false) {
608
+ const truncated = truncateOutput(sanitizePipeOutput(read.delta), maxBytes);
609
+ const notes = sandboxNotes(sandbox, escalationAvailable);
610
+ const output = notes.length === 0 ? truncated.text : `${truncated.text}${truncated.text.length > 0 && !truncated.text.endsWith("\n") ? "\n" : ""}${notes.join("\n")}`;
611
+ return truncated.originalTokenCount === void 0 ? { output } : {
612
+ output,
613
+ originalTokenCount: truncated.originalTokenCount
614
+ };
615
+ }
616
+ function terminalResult(result, maxBytes, startedAt) {
617
+ const truncated = truncateOutput(result.viewport, maxBytes);
618
+ return withChunkId({
619
+ wall_time_seconds: (performance.now() - startedAt) / 1e3,
620
+ output: truncated.text,
621
+ ...truncated.originalTokenCount === void 0 ? {} : { original_token_count: truncated.originalTokenCount },
622
+ ...result.sessionStatus.kind === "exited" ? { ...result.sessionStatus.exitCode === null ? {} : { exit_code: result.sessionStatus.exitCode } } : {}
623
+ });
624
+ }
625
+ /** Map a detached shell process onto the generic DSH job outcome contract. */
626
+ function backgroundOutcome(process, escalationAvailable, sandbox = process.sandbox) {
627
+ const base = process.status === "killed" ? {
628
+ status: "killed",
629
+ detail: process.signal !== null ? `signal: ${process.signal}` : "killed before exit"
630
+ } : {
631
+ status: "completed",
632
+ detail: `exit code: ${process.exitCode ?? 0}`
633
+ };
634
+ const notes = sandboxNotes(sandbox, escalationAvailable);
635
+ return notes.length === 0 ? base : {
636
+ ...base,
637
+ detail: `${base.detail}; ${notes.join(" ")}`
638
+ };
639
+ }
640
+ //#endregion
641
+ //#region lib/types/tools/exec-runner.js
642
+ /** Codex `exec_command` and `write_stdin` execution over DSH 0.2.2+ capability seams. */
643
+ const STATES = /* @__PURE__ */ new WeakMap();
644
+ const MAX_UNIFIED_EXEC_SESSIONS = 64;
645
+ const PROTECTED_RECENT_SESSIONS = 8;
646
+ function stateFor(agent) {
647
+ const current = STATES.get(agent);
648
+ if (current !== void 0) return current;
649
+ const created = {
650
+ nextId: 0,
651
+ clock: 0,
652
+ sessions: /* @__PURE__ */ new Map()
653
+ };
654
+ STATES.set(agent, created);
655
+ return created;
656
+ }
657
+ function sessionCwd$1(ctx, exec, workdir) {
658
+ const directories = ctx.get("workingDirectory");
659
+ const cwd = exec.agent === void 0 ? void 0 : directories?.get(exec.agent.session) ?? exec.agent.session.header.cwd;
660
+ return workdir === void 0 ? cwd : resolve(cwd ?? process.cwd(), workdir);
661
+ }
662
+ async function startShell(ctx, request) {
663
+ const shell = ctx.get("shell");
664
+ if (shell === void 0) throw new Error("exec_command requires ctx.shell");
665
+ return shell.execute(shell.resolve(request));
666
+ }
667
+ async function waitForShell(process, ms, signal) {
668
+ let timer;
669
+ let onAbort = () => {};
670
+ const elapsed = new Promise((resolve) => {
671
+ onAbort = () => resolve(false);
672
+ if (signal.aborted) {
673
+ onAbort();
674
+ return;
675
+ }
676
+ signal.addEventListener("abort", onAbort, { once: true });
677
+ timer = setTimeout(() => resolve(void 0), ms);
678
+ });
679
+ try {
680
+ const completed = await Promise.race([process.done.then(() => true), elapsed]);
681
+ if (signal.aborted) signal.throwIfAborted();
682
+ return completed === true || process.status !== "running";
683
+ } finally {
684
+ if (timer !== void 0) clearTimeout(timer);
685
+ signal.removeEventListener("abort", onAbort);
686
+ }
687
+ }
688
+ /** Stop a pipe-backed session when the current Codex tool is cancelled. */
689
+ async function stopShellOnAbort(process, signal) {
690
+ if (!signal.aborted || process.status !== "running") return;
691
+ process.kill();
692
+ await process.done;
693
+ }
694
+ function allocateSession(ctx, agent, session) {
695
+ const state = stateFor(agent);
696
+ while (state.sessions.size >= MAX_UNIFIED_EXEC_SESSIONS) {
697
+ const byRecency = [...state.sessions.entries()].sort((a, b) => b[1].lastUsed - a[1].lastUsed);
698
+ const protectedIds = new Set(byRecency.slice(0, PROTECTED_RECENT_SESSIONS).map(([id]) => id));
699
+ const unprotected = byRecency.filter(([id]) => !protectedIds.has(id));
700
+ const victim = [...unprotected].reverse().find(([, entry]) => entry.kind === "shell" && entry.process.status !== "running") ?? unprotected.at(-1);
701
+ if (victim === void 0) break;
702
+ const [victimId, evicted] = victim;
703
+ state.sessions.delete(victimId);
704
+ if (evicted.kind === "shell") {
705
+ if (evicted.process.status === "running") evicted.process.kill();
706
+ } else ctx.get("terminals")?.kill(evicted.owner, evicted.id, "Codex session cap reached")?.catch(() => {});
707
+ }
708
+ const id = ++state.nextId;
709
+ state.sessions.set(id, {
710
+ ...session,
711
+ lastUsed: ++state.clock
712
+ });
713
+ return id;
714
+ }
715
+ function storedSession(agent, id) {
716
+ const state = stateFor(agent);
717
+ const session = state.sessions.get(id);
718
+ if (session === void 0) throw new Error(`unknown unified exec session ${id}`);
719
+ session.lastUsed = ++state.clock;
720
+ return session;
721
+ }
722
+ function forgetSession(agent, id) {
723
+ const state = STATES.get(agent);
724
+ if (state === void 0) return;
725
+ state.sessions.delete(id);
726
+ if (state.sessions.size === 0) STATES.delete(agent);
727
+ }
728
+ /** Kill any yielded pipe-backed shell processes retained by a disposed Agent. */
729
+ function disposeAgentExecSessions(agent) {
730
+ const state = STATES.get(agent);
731
+ if (state === void 0) return;
732
+ STATES.delete(agent);
733
+ for (const session of state.sessions.values()) if (session.kind === "shell" && session.process.status === "running") session.process.kill();
734
+ state.sessions.clear();
735
+ }
736
+ async function runTtyCommand(ctx, args, exec, workdir, maxBytes, startedAt) {
737
+ const agent = exec.agent;
738
+ const terminals = ctx.get("terminals");
739
+ if (agent === void 0 || terminals === void 0) throw new Error("exec_command with tty=true requires the dsh terminal capability and an owning agent session");
740
+ const spawnRequest = {
741
+ type: "shell",
742
+ ...workdir === void 0 ? {} : { cwd: workdir }
743
+ };
744
+ const spawned = await terminals.spawn(agent, spawnRequest, exec.signal);
745
+ let retained = false;
746
+ let closeReason = "Codex command failed";
747
+ try {
748
+ const sendRequest = {
749
+ text: args.cmd,
750
+ submit: true,
751
+ signal: exec.signal
752
+ };
753
+ const result = await terminals.startSend(agent, spawned.sessionId, sendRequest).done;
754
+ const output = terminalResult(result, maxBytes, startedAt);
755
+ if (result.sessionStatus.kind === "running") {
756
+ output.session_id = allocateSession(ctx, agent, {
757
+ kind: "terminal",
758
+ owner: agent,
759
+ id: spawned.sessionId
760
+ });
761
+ retained = true;
762
+ } else closeReason = "Codex command exited";
763
+ return output;
764
+ } finally {
765
+ if (!retained) await terminals.kill(agent, spawned.sessionId, closeReason);
766
+ }
767
+ }
768
+ function startBackgroundJob(ctx, args, exec, shellRequest, confines, maxBytes, startedAt) {
769
+ const owner = exec.agent;
770
+ if (owner === void 0) throw new Error("run_in_background requires an owning agent session");
771
+ const jobs = ctx.get("jobs");
772
+ if (jobs === void 0) throw new Error("background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs");
773
+ if (exec.signal.aborted) {
774
+ exec.signal.throwIfAborted();
775
+ throw new Error("tool call aborted");
776
+ }
777
+ let process;
778
+ let cancelled = false;
779
+ const lifetime = new AbortController();
780
+ const jobSpec = {
781
+ kind: "bash",
782
+ label: args.cmd,
783
+ owner: owner.id,
784
+ outputLimitBytes: maxBytes,
785
+ output: ["stdout", "stderr"].map((channel) => ({
786
+ channel,
787
+ read: (fromByte) => process?.observed?.[channel].readFrom(fromByte) ?? {
788
+ text: "",
789
+ nextOffset: fromByte,
790
+ lossy: false
791
+ }
792
+ })),
793
+ run: () => {
794
+ const prepared = startShell(ctx, {
795
+ ...shellRequest,
796
+ signal: lifetime.signal
797
+ });
798
+ return {
799
+ cancel: () => {
800
+ cancelled = true;
801
+ lifetime.abort();
802
+ process?.kill();
803
+ },
804
+ done: (async () => {
805
+ try {
806
+ process = await prepared;
807
+ if (cancelled) process.kill();
808
+ await process.done;
809
+ const completed = await assertShellCompleted(process, confines);
810
+ return backgroundOutcome(process, confines, completed?.sandbox ?? process.sandbox);
811
+ } catch (error) {
812
+ if (cancelled) return {
813
+ status: "killed",
814
+ detail: "cancelled during shell preparation"
815
+ };
816
+ return {
817
+ status: "failed",
818
+ detail: [error instanceof Error ? error.message : String(error), ...sandboxNotes(process?.sandbox, confines)].join("; ")
819
+ };
820
+ }
821
+ })()
822
+ };
823
+ }
824
+ };
825
+ const id = jobs.start(jobSpec);
826
+ return withChunkId({
827
+ wall_time_seconds: (performance.now() - startedAt) / 1e3,
828
+ job_id: id,
829
+ output: `Started background job ${id}. Use job_output with job_id "${id}" to read output.`
830
+ });
831
+ }
832
+ /** Execute one Codex command through the configured pipe or PTY capability. */
833
+ async function runExecCommand(ctx, args, exec, config) {
834
+ if (args.cmd.trim().length === 0) throw new Error("cmd must be a non-empty string");
835
+ positiveFinite("yield_time_ms", args.yield_time_ms);
836
+ const maxBytes = outputLimit(config.maxOutputBytes, args.max_output_tokens);
837
+ validateEscalationArgs(args.sandbox_permissions, args.justification);
838
+ const confines = ctx.get("shell")?.sandboxMode !== void 0;
839
+ const policyService = ctx.get("sandboxPolicy");
840
+ if (confines && policyService === void 0) throw new Error("exec_command: a sandboxing shell requires ctx.sandboxPolicy");
841
+ if (confines && args.tty === true) throw new Error("exec_command: tty=true cannot carry the sandbox policy; use pipe-backed execution on this host");
842
+ let policy = policyService?.resolve(exec.agent === void 0 ? {} : { session: exec.agent.session });
843
+ if (args.sandbox_permissions !== void 0) {
844
+ if (!confines) throw new Error("sandbox_permissions is not available in this composition (no sandboxing executor to escalate)");
845
+ const approvedMode = await approveEscalation({
846
+ requestedMode: args.sandbox_permissions,
847
+ justification: args.justification,
848
+ effectiveMode: policy.mode,
849
+ subject: "command"
850
+ }, {
851
+ approver: ctx.get("approval"),
852
+ agent: exec.agent,
853
+ callId: exec.callId,
854
+ toolName: "exec_command",
855
+ signal: exec.signal
856
+ });
857
+ exec.signal.throwIfAborted();
858
+ policy = {
859
+ ...policy,
860
+ mode: approvedMode
861
+ };
862
+ }
863
+ const workdir = sessionCwd$1(ctx, exec, args.workdir);
864
+ const startedAt = performance.now();
865
+ if (args.run_in_background === true && args.tty === true) throw new Error("run_in_background is only supported for pipe-backed commands; omit tty");
866
+ if (args.tty === true) return runTtyCommand(ctx, args, exec, workdir, maxBytes, startedAt);
867
+ const dshEnv = ctx.get("shellEnv")?.collect(exec);
868
+ const shellRequest = {
869
+ command: args.cmd,
870
+ onExpiry: "none",
871
+ ...workdir === void 0 ? {} : { workdir },
872
+ stdoutMaxBytes: maxBytes,
873
+ ...dshEnv === void 0 ? {} : { dshEnv },
874
+ ...policy === void 0 ? {} : { sandboxPolicy: policy }
875
+ };
876
+ if (args.run_in_background === true) return startBackgroundJob(ctx, args, exec, shellRequest, confines, maxBytes, startedAt);
877
+ const process = await startShell(ctx, {
878
+ ...shellRequest,
879
+ signal: exec.signal
880
+ });
881
+ try {
882
+ await waitForShell(process, normalizeWaitMs(args.yield_time_ms, config.defaultYieldTimeMs, false, true), exec.signal);
883
+ const read = process.readOutput();
884
+ if (process.status === "running") {
885
+ if (exec.agent === void 0) {
886
+ process.kill();
887
+ await process.done;
888
+ const completed = await assertShellCompleted(process, confines);
889
+ const formatted = readShellOutput({
890
+ ...read,
891
+ delta: read.delta + process.readOutput().delta
892
+ }, maxBytes, completed?.sandbox ?? process.sandbox, confines);
893
+ return withChunkId({
894
+ wall_time_seconds: (performance.now() - startedAt) / 1e3,
895
+ output: formatted.output,
896
+ ...formatted.originalTokenCount === void 0 ? {} : { original_token_count: formatted.originalTokenCount }
897
+ });
898
+ }
899
+ const formatted = readShellOutput(read, maxBytes, process.sandbox, confines);
900
+ const output = hasInteractivePrompt(formatted.output) ? `${formatted.output}${formatted.output.length > 0 && !formatted.output.endsWith("\n") ? "\n" : ""}[exec: command appears waiting on interactive stdin over pipes; interrupt with write_stdin chars="\\u0003" and rerun with a non-interactive flag or tty=true]` : formatted.output;
901
+ return withChunkId({
902
+ wall_time_seconds: (performance.now() - startedAt) / 1e3,
903
+ output,
904
+ ...formatted.originalTokenCount === void 0 ? {} : { original_token_count: formatted.originalTokenCount },
905
+ session_id: allocateSession(ctx, exec.agent, {
906
+ kind: "shell",
907
+ process,
908
+ escalationAvailable: confines
909
+ })
910
+ });
911
+ }
912
+ const formatted = readShellOutput(read, maxBytes, (await assertShellCompleted(process, confines))?.sandbox ?? process.sandbox, confines);
913
+ return withChunkId({
914
+ wall_time_seconds: (performance.now() - startedAt) / 1e3,
915
+ output: formatted.output,
916
+ ...formatted.originalTokenCount === void 0 ? {} : { original_token_count: formatted.originalTokenCount },
917
+ ...process.exitCode === null ? {} : { exit_code: process.exitCode }
918
+ });
919
+ } finally {
920
+ await stopShellOnAbort(process, exec.signal);
921
+ }
922
+ }
923
+ /** Poll or write to one session returned by {@link runExecCommand}. */
924
+ async function runWriteStdin(ctx, args, exec, config) {
925
+ const escalation = args;
926
+ if (escalation.sandbox_permissions !== void 0 || escalation.justification !== void 0) throw new Error("write_stdin cannot change an existing command sandbox; use exec_command for an approved one-shot retry");
927
+ positiveFinite("yield_time_ms", args.yield_time_ms);
928
+ if (!Number.isSafeInteger(args.session_id) || args.session_id <= 0) throw new Error("session_id must be a positive integer");
929
+ const agent = exec.agent;
930
+ if (agent === void 0) throw new Error("write_stdin requires an owning agent session");
931
+ const session = storedSession(agent, args.session_id);
932
+ const maxBytes = outputLimit(config.maxOutputBytes, args.max_output_tokens);
933
+ const startedAt = performance.now();
934
+ const chars = args.chars ?? "";
935
+ if (session.kind === "shell") {
936
+ if (chars === "") session.process.kill();
937
+ else if (chars.length > 0) throw new Error("this unified exec session uses pipes and does not accept stdin; send \"\\u0003\" to interrupt or rerun exec_command with tty=true");
938
+ try {
939
+ const waitMs = normalizeWaitMs(args.yield_time_ms, chars === "" ? config.writeYieldTimeMs : config.pollYieldTimeMs, chars.length === 0);
940
+ await waitForShell(session.process, waitMs, exec.signal);
941
+ const read = session.process.readOutput();
942
+ if (session.process.status !== "running") {
943
+ forgetSession(agent, args.session_id);
944
+ const formatted = readShellOutput(read, maxBytes, (await assertShellCompleted(session.process, session.escalationAvailable))?.sandbox ?? session.process.sandbox, session.escalationAvailable);
945
+ return withChunkId({
946
+ wall_time_seconds: (performance.now() - startedAt) / 1e3,
947
+ output: formatted.output,
948
+ ...formatted.originalTokenCount === void 0 ? {} : { original_token_count: formatted.originalTokenCount },
949
+ ...session.process.exitCode === null ? {} : { exit_code: session.process.exitCode }
950
+ });
951
+ }
952
+ const formatted = readShellOutput(read, maxBytes, session.process.sandbox, session.escalationAvailable);
953
+ return withChunkId({
954
+ wall_time_seconds: (performance.now() - startedAt) / 1e3,
955
+ output: formatted.output,
956
+ ...formatted.originalTokenCount === void 0 ? {} : { original_token_count: formatted.originalTokenCount },
957
+ session_id: args.session_id
958
+ });
959
+ } finally {
960
+ if (exec.signal.aborted) try {
961
+ await stopShellOnAbort(session.process, exec.signal);
962
+ } finally {
963
+ forgetSession(agent, args.session_id);
964
+ }
965
+ }
966
+ }
967
+ const terminals = ctx.get("terminals");
968
+ if (terminals === void 0) throw new Error("the dsh terminal capability is no longer available");
969
+ const sendRequest = {
970
+ text: chars,
971
+ submit: false,
972
+ signal: exec.signal
973
+ };
974
+ let retained = false;
975
+ let closeReason = "Codex command failed";
976
+ try {
977
+ const result = await terminals.startSend(agent, session.id, sendRequest).done;
978
+ const output = terminalResult(result, maxBytes, startedAt);
979
+ if (result.sessionStatus.kind === "running") {
980
+ output.session_id = args.session_id;
981
+ retained = true;
982
+ } else {
983
+ closeReason = "Codex command exited";
984
+ forgetSession(agent, args.session_id);
985
+ }
986
+ return output;
987
+ } finally {
988
+ if (!retained) {
989
+ forgetSession(agent, args.session_id);
990
+ await terminals.kill(agent, session.id, closeReason);
991
+ }
992
+ }
993
+ }
994
+ //#endregion
995
+ //#region lib/types/tools/patch.js
996
+ /** Parser and line-oriented applicator for Codex's `apply_patch` language. */
997
+ const APPLY_PATCH_DESCRIPTION = "Edits files using Codex patch syntax with Begin/End Patch markers and file update directives. In hunk lines, the first character is the operation marker; repeat a source-leading marker when the source line itself starts with one.";
998
+ String.raw`start: begin_patch hunk+ end_patch
999
+ begin_patch: "*** Begin Patch" LF
1000
+ end_patch: "*** End Patch" LF?
1001
+ hunk: add_hunk | delete_hunk | update_hunk
1002
+ add_hunk: "*** Add File: " filename LF add_line*
1003
+ delete_hunk: "*** Delete File: " filename LF
1004
+ update_hunk: "*** Update File: " filename LF change_move? change?
1005
+ filename: /(.+)/
1006
+ add_line: "+" /(.*)/ LF -> line
1007
+ change_move: "*** Move to: " filename LF
1008
+ change: (change_context | change_line)+ eof_line?
1009
+ change_context: ("@@" | "@@ " /(.+)/) LF
1010
+ change_line: ("+" | "-" | " ") /(.*)/ LF
1011
+ eof_line: "*** End of File" LF
1012
+ %import common.LF
1013
+ `;
1014
+ function invalid(message) {
1015
+ throw new Error(`apply_patch: ${message}`);
1016
+ }
1017
+ function isHunkFileHeader(line) {
1018
+ const trimmed = line.trimEnd();
1019
+ return trimmed.startsWith("*** Add File: ") || trimmed.startsWith("*** Delete File: ") || trimmed.startsWith("*** Update File: ");
1020
+ }
1021
+ function unwrapHeredoc(input) {
1022
+ const normalized = input.replaceAll("\r\n", "\n").trim();
1023
+ const lines = normalized.split("\n");
1024
+ const first = lines[0]?.trim();
1025
+ const last = lines.at(-1)?.trim();
1026
+ if (lines.length >= 4 && (first === "<<EOF" || first === "<<'EOF'" || first === "<<\"EOF\"") && last === "EOF") return lines.slice(1, -1).join("\n").trim();
1027
+ return normalized;
1028
+ }
1029
+ function pathFrom(line, prefix) {
1030
+ const path = line.slice(prefix.length).trim();
1031
+ if (path.length === 0) invalid(`${prefix.trim()} requires a file path`);
1032
+ return path;
1033
+ }
1034
+ function isChangeMarker(line) {
1035
+ const marker = line.trimEnd();
1036
+ return marker === "@@" || marker.startsWith("@@ ");
1037
+ }
1038
+ function isPotentialChangeMarker(line) {
1039
+ return line.trimEnd().startsWith("@@");
1040
+ }
1041
+ /** Parse one complete Codex patch after normalizing CRLF input to LF. */
1042
+ function parsePatch(input) {
1043
+ const lines = unwrapHeredoc(input).split("\n");
1044
+ if (lines[0]?.trim() !== "*** Begin Patch") invalid("input must start with \"*** Begin Patch\"");
1045
+ if (lines.at(-1)?.trim() !== "*** End Patch") invalid("input must end with \"*** End Patch\"");
1046
+ const files = [];
1047
+ let index = 1;
1048
+ const end = lines.length - 1;
1049
+ if (lines[index]?.trim().startsWith("*** Environment ID:") === true) invalid("environment selection is unavailable in this single-environment DSH plugin");
1050
+ while (index < end) {
1051
+ const header = lines[index++]?.trim();
1052
+ if (header === void 0) invalid("unexpected end of input");
1053
+ if (header.length === 0) continue;
1054
+ if (header.startsWith("*** Add File: ")) {
1055
+ const path = pathFrom(header, "*** Add File: ");
1056
+ const content = [];
1057
+ while (index < end && lines[index]?.startsWith("+") === true) {
1058
+ content.push(lines[index].slice(1));
1059
+ index++;
1060
+ }
1061
+ files.push({
1062
+ kind: "add",
1063
+ path,
1064
+ content: content.length === 0 ? "" : `${content.join("\n")}\n`
1065
+ });
1066
+ continue;
1067
+ }
1068
+ if (header.startsWith("*** Delete File: ")) {
1069
+ files.push({
1070
+ kind: "delete",
1071
+ path: pathFrom(header, "*** Delete File: ")
1072
+ });
1073
+ continue;
1074
+ }
1075
+ if (!header.startsWith("*** Update File: ")) invalid(`unexpected directive ${JSON.stringify(header)}`);
1076
+ const path = pathFrom(header, "*** Update File: ");
1077
+ let moveTo;
1078
+ if (lines[index]?.trim().startsWith("*** Move to: ") === true) {
1079
+ moveTo = pathFrom(lines[index].trim(), "*** Move to: ");
1080
+ index++;
1081
+ }
1082
+ const hunks = [];
1083
+ while (index < end && !isHunkFileHeader(lines[index])) {
1084
+ const patchLines = [];
1085
+ let context;
1086
+ if (isPotentialChangeMarker(lines[index])) {
1087
+ const marker = lines[index].trimEnd();
1088
+ if (!isChangeMarker(marker)) invalid(`invalid update hunk marker ${JSON.stringify(lines[index])}`);
1089
+ index++;
1090
+ context = marker.length === 2 ? void 0 : marker.slice(3);
1091
+ }
1092
+ while (index < end && !isHunkFileHeader(lines[index]) && !isPotentialChangeMarker(lines[index]) && lines[index].trimEnd() !== "*** End of File") {
1093
+ const line = lines[index++];
1094
+ if (line === "") {
1095
+ patchLines.push({
1096
+ kind: "context",
1097
+ text: ""
1098
+ });
1099
+ continue;
1100
+ }
1101
+ const kind = line[0];
1102
+ if (kind !== " " && kind !== "+" && kind !== "-") invalid(`unexpected update line ${JSON.stringify(line)}`);
1103
+ patchLines.push({
1104
+ kind: kind === " " ? "context" : kind === "+" ? "add" : "delete",
1105
+ text: line.slice(1)
1106
+ });
1107
+ }
1108
+ const endOfFile = lines[index]?.trimEnd() === "*** End of File";
1109
+ if (endOfFile) {
1110
+ index++;
1111
+ while (index < end && lines[index] === "") index++;
1112
+ }
1113
+ if (patchLines.length === 0) {
1114
+ if (context !== void 0 || endOfFile) invalid("an update hunk needs context or changed lines");
1115
+ break;
1116
+ }
1117
+ hunks.push({
1118
+ ...context === void 0 ? {} : { context },
1119
+ lines: patchLines,
1120
+ endOfFile
1121
+ });
1122
+ }
1123
+ if (hunks.length === 0 && moveTo === void 0) invalid(`update file ${JSON.stringify(path)} has no changes`);
1124
+ files.push({
1125
+ kind: "update",
1126
+ path,
1127
+ ...moveTo === void 0 ? {} : { moveTo },
1128
+ hunks
1129
+ });
1130
+ }
1131
+ if (files.length === 0) invalid("no files were modified");
1132
+ return files;
1133
+ }
1134
+ function splitText(text) {
1135
+ if (text.length === 0) return {
1136
+ lines: [],
1137
+ trailingNewline: true
1138
+ };
1139
+ const trailingNewline = text.endsWith("\n");
1140
+ const lines = text.split("\n");
1141
+ if (trailingNewline) lines.pop();
1142
+ return {
1143
+ lines,
1144
+ trailingNewline
1145
+ };
1146
+ }
1147
+ function joinText(value, eol) {
1148
+ if (value.lines.length === 0) return "";
1149
+ const body = value.lines.join(eol);
1150
+ return value.trailingNewline ? `${body}${eol}` : body;
1151
+ }
1152
+ function normalizePatchPunctuation(line) {
1153
+ return line.trim().replaceAll(/[\u2010-\u2015\u2212]/gu, "-").replaceAll(/[\u2018-\u201B]/gu, "'").replaceAll(/[\u201C-\u201F]/gu, "\"").replaceAll(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/gu, " ");
1154
+ }
1155
+ function contextAnchor(context) {
1156
+ if (context === void 0) return void 0;
1157
+ const trimmed = context.trim();
1158
+ if (trimmed.length === 0) return void 0;
1159
+ const unified = /^-\d+(?:,\d+)?\s+\+\d+(?:,\d+)?(?:\s+@@(?:\s*(.*))?|$)/u.exec(trimmed);
1160
+ const anchor = (unified ? unified[1] ?? "" : trimmed).trim();
1161
+ return anchor.length === 0 ? void 0 : anchor;
1162
+ }
1163
+ function findSequence(lines, expected, from, endOfFile) {
1164
+ if (expected.length === 0) return lines.length;
1165
+ if (expected.length > lines.length) return -1;
1166
+ const first = endOfFile ? Math.max(from, lines.length - expected.length) : from;
1167
+ const last = lines.length - expected.length;
1168
+ const matchers = [
1169
+ (actual, wanted) => actual === wanted,
1170
+ (actual, wanted) => actual.trimEnd() === wanted.trimEnd(),
1171
+ (actual, wanted) => actual.trim() === wanted.trim(),
1172
+ (actual, wanted) => normalizePatchPunctuation(actual) === normalizePatchPunctuation(wanted)
1173
+ ];
1174
+ for (const matchesLine of matchers) for (let index = first; index <= last; index++) {
1175
+ let matches = true;
1176
+ for (let offset = 0; offset < expected.length; offset++) if (!matchesLine(lines[index + offset], expected[offset])) {
1177
+ matches = false;
1178
+ break;
1179
+ }
1180
+ if (matches) return index;
1181
+ }
1182
+ return -1;
1183
+ }
1184
+ function displayPatchLine(line) {
1185
+ if (line.length === 0) return "<empty>";
1186
+ return line.replaceAll(" ", "[space]").replaceAll(" ", "[tab]");
1187
+ }
1188
+ function formatPatchExcerpt(lines, start, count) {
1189
+ if (lines.length === 0) return " <empty file>";
1190
+ const first = Math.max(0, Math.min(start, lines.length - 1));
1191
+ return lines.slice(first, first + count).map((line, offset) => ` ${first + offset + 1}: ${displayPatchLine(line)}`).join("\n");
1192
+ }
1193
+ function mismatchMessage(label, hunkIndex, expected, actual, from, endOfFile) {
1194
+ const expectedPreview = expected.slice(0, 12).map((line, index) => ` ${index + 1}: ${displayPatchLine(line)}`).join("\n");
1195
+ const expectedSuffix = expected.length > 12 ? "\n ..." : "";
1196
+ const excerptStart = endOfFile ? Math.max(0, actual.length - 6) : Math.max(0, from - 2);
1197
+ const earlier = from > 0 && expected.length > 0 ? findSequence(actual, expected, 0, false) : -1;
1198
+ const orderHint = earlier >= 0 && earlier < from ? `\nHint: expected lines match earlier at line ${earlier + 1}, before the previous hunk ended (line ${from + 1}); order hunks top-to-bottom.` : "";
1199
+ const markerHint = expected.some((wanted) => wanted.length > 0 && actual.includes(`-${wanted}`)) ? "\nHint: if a source line starts with a patch marker, repeat that marker after the operation marker; for example, `-- item` deletes the source line `- item`." : "";
1200
+ return `could not find expected lines in ${label} hunk ${hunkIndex + 1} (search starts at line ${from + 1})\nExpected:\n${expectedPreview}${expectedSuffix}\nFile excerpt:\n${formatPatchExcerpt(actual, excerptStart, 10)}${orderHint}${markerHint}`;
1201
+ }
1202
+ function dominantEol(text) {
1203
+ let crlf = 0;
1204
+ let lf = 0;
1205
+ for (let i = 0; i < text.length; i++) if (text[i] === "\n") {
1206
+ if (text[i - 1] === "\r") crlf++;
1207
+ else lf++;
1208
+ }
1209
+ return crlf > lf ? "\r\n" : "\n";
1210
+ }
1211
+ /** Apply parsed update hunks while preserving BOM, line endings, and trailing newline. */
1212
+ function applyPatchHunks(original, hunks, label = "file") {
1213
+ const hasBom = original.startsWith("");
1214
+ const raw = hasBom ? original.slice(1) : original;
1215
+ const eol = dominantEol(raw);
1216
+ const value = splitText(raw.replaceAll("\r\n", "\n"));
1217
+ let cursor = 0;
1218
+ for (const [hunkIndex, hunk] of hunks.entries()) {
1219
+ const expected = hunk.lines.filter((line) => line.kind !== "add").map((line) => line.text);
1220
+ const anchor = contextAnchor(hunk.context);
1221
+ const anchorIndex = anchor === void 0 ? -1 : findSequence(value.lines, [anchor], cursor, false);
1222
+ let start;
1223
+ if (expected.length === 0) start = anchorIndex >= 0 ? Math.min(anchorIndex + 1, value.lines.length) : value.lines.length;
1224
+ else {
1225
+ start = anchorIndex >= 0 ? findSequence(value.lines, expected, anchorIndex + 1, hunk.endOfFile) : -1;
1226
+ if (start < 0 && anchorIndex >= 0) start = findSequence(value.lines, expected, anchorIndex, hunk.endOfFile);
1227
+ if (start < 0) start = findSequence(value.lines, expected, cursor, hunk.endOfFile);
1228
+ }
1229
+ if (start < 0) invalid(mismatchMessage(label, hunkIndex, expected, value.lines, cursor, hunk.endOfFile));
1230
+ const replacement = [];
1231
+ let oldOffset = 0;
1232
+ for (const line of hunk.lines) if (line.kind === "context") {
1233
+ replacement.push(value.lines[start + oldOffset]);
1234
+ oldOffset++;
1235
+ } else if (line.kind === "delete") oldOffset++;
1236
+ else replacement.push(line.text);
1237
+ value.lines.splice(start, expected.length, ...replacement);
1238
+ cursor = start + replacement.length;
1239
+ }
1240
+ const result = joinText(value, eol);
1241
+ return hasBom ? `\uFEFF${result}` : result;
1242
+ }
1243
+ //#endregion
1244
+ //#region lib/types/contracts/prompt.js
1245
+ /** Default plugin-owned Codex operating prompt. */
1246
+ const DEFAULT_CODEX_SYSTEM_PROMPT = String.raw`## General
1247
+
1248
+ - Follow the current tool catalog, not assumptions from another Codex client. For unknown paths, use the available list/search tools instead of guessing and reuse the returned paths. If only shell search is available, prefer rg or rg --files.
1249
+
1250
+ ## Editing constraints
1251
+
1252
+ - Default to ASCII when editing or creating files. Only introduce non-ASCII or other Unicode characters when there is a clear justification and the file already uses them.
1253
+ - Prefer apply_patch (or dedicated file tools when present) over shell heredocs or redirection for file edits; do not re-read a file immediately after apply_patch succeeds unless checking external changes.
1254
+ - Add succinct code comments that explain non-obvious code. Do not add comments that merely narrate assignments or control flow.
1255
+ - You may be in a dirty git worktree. Never revert existing changes you did not make unless the user explicitly requests it, never amend commits unless asked, and avoid interactive git commands such as git rebase -i or git add -p. If unrelated files are changed, leave them alone.
1256
+
1257
+ ## Planning
1258
+
1259
+ - Use update_plan for work with multiple meaningful steps. Keep the plan current as the task progresses.
1260
+ - Do not use a plan for a trivial one-step request.
1261
+
1262
+ ## dsh session
1263
+
1264
+ - The user and you share one workspace. Inspect the repository and every applicable AGENTS.md before editing.
1265
+ - For Harness APIs, first load the relevant Harness skill. When Inspect tools are available, start with cordis_inspect_list, then query the provider's directory before an exact Service contract. Reuse returned names; Inspect is read-only.
1266
+ - A not-found path or unknown Service is a discovery error: check the file list or Service directory before retrying. Preserve actual failures; do not hide them or bypass permission denials.
1267
+
1268
+ ## Task execution
1269
+
1270
+ - Parallelize independent read, search, and check calls. Do not sleep-poll background jobs or subagents; they wake on completion.
1271
+ - When delegating parallel edits, assign disjoint write scopes. Record key paths and facts as you go since older large tool outputs may be pruned.
1272
+ - Never claim unrun checks passed, and keep the user informed with concise progress updates.
1273
+
1274
+ ## Presenting your work
1275
+
1276
+ - Be concise, direct, friendly, and actionable, and lead with the result.
1277
+ - For substantial work, explain what changed and why, then briefly note how the work was verified and what comes next.
1278
+ - For code reviews, lead with concrete findings ordered by severity with file and line references before any brief summary, or state explicitly if no issues were found.
1279
+ - Do not dump large files into the conversation; refer to their paths.
1280
+ - Use plain text with short sections only when they improve scanability.
1281
+
1282
+ ## Working principles
1283
+
1284
+ - Actively establish the user's current context from the repository rather than relying on stale assumptions. Execute tasks directly through implementation and verification using the clearest, most effective path; ask the user only when a user-owned choice or external/destructive action cannot be resolved by inspection.
1285
+ - Keep only the essential logic and core actions. Don't explain or test what was removed or why something wasn't done, especially when writing documentation or communicating. Convey enough valuable information with as few words as possible.
1286
+ - Solve problems by thinking from first principles and at a higher level.
1287
+ `;
1288
+ /** Default deployment Persona template used by the Codex preset. */
1289
+ const DEFAULT_CODEX_PERSONA = String.raw`You are Codex, a coding agent based on the {{model}} model.`;
1290
+ /** Default DSH Core source-checkout guidance template. */
1291
+ const DEFAULT_DSH_CORE_SOURCE_PROMPT = String.raw`The DeepSeek Harness implementation checkout is at {{sourceRoot}}. The checkout location and current working directory are separate values and may differ; never infer the working directory from this path. Use pwd to determine the current working directory. Use this checkout only to inspect or extend DSH itself. If the supplied path is inside app.asar, treat it as a packaged runtime rather than a source checkout. Discover the installed packageDir via Inspect and read its README and package.json exports; do not assume src or individual lib/types filenames exist. Use Host file-read tools for app.asar; native shell search and glob cannot traverse it.`;
1292
+ /** Default DSH Web runtime guidance template. */
1293
+ const DEFAULT_DSH_CORE_WEB_PROMPT = [
1294
+ "You are interacting with the user through the DeepSeek Harness Web GUI at {{webUrl}}.",
1295
+ "When the user refers to \"this page\", \"this GUI\", or \"this app\" without naming another target, they mean this GUI.",
1296
+ "The browser provides no implicit DOM, route, or screenshot context.",
1297
+ "The client-plugin HMR receiver is active, but client-plugin changes reload without a refresh only while `pnpm run dev:web` is also running from this same checkout to rebuild their bundles; verify that watcher before promising automatic updates.",
1298
+ "Every other change - the apps/web shell and plain packages - requires rebuilding the affected Web artifacts and verifying this existing URL after a page refresh.",
1299
+ "Starting another server does not update this GUI.",
1300
+ "The apps/web Vite entry builds the shell but is not a standalone application because only dsh web injects window.__DSH_BOOT__.",
1301
+ "Do not start a replacement server unless the user asks; if one is needed, use a managed background job and verify its exact URL."
1302
+ ].join(" ");
1303
+ //#endregion
1304
+ //#region lib/types/contracts/settings.js
1305
+ /** Shared host-side Codex settings contract, Host reader, and GPT route matcher. */
1306
+ /** Live Codex controls shared by the Web UI and agent layer. */
1307
+ const CODEX_SETTINGS_NAMESPACE = "codex";
1308
+ /** Default settings exposed even before a Codex session is opened. */
1309
+ const CODEX_SETTINGS_ENTRY = {
1310
+ fast: false,
1311
+ fastModeControlEnabled: true,
1312
+ contextWindowControlEnabled: true,
1313
+ persona: DEFAULT_CODEX_PERSONA,
1314
+ harnessSourcePrompt: DEFAULT_DSH_CORE_SOURCE_PROMPT,
1315
+ webSurfacePrompt: DEFAULT_DSH_CORE_WEB_PROMPT,
1316
+ systemPrompt: DEFAULT_CODEX_SYSTEM_PROMPT,
1317
+ promptEnabled: true,
1318
+ terminalToolsEnabled: true,
1319
+ patchToolEnabled: true,
1320
+ planToolEnabled: true,
1321
+ hostedWebSearchEnabled: true,
1322
+ remoteCompactionEnabled: true,
1323
+ activityIndicatorEnabled: true
1324
+ };
1325
+ z.object({
1326
+ fast: z.boolean().default(false),
1327
+ fastModeControlEnabled: z.boolean().default(true),
1328
+ contextWindowControlEnabled: z.boolean().default(true),
1329
+ contextWindow: z.number().step(1).min(1).max(CODEX_CONTEXT_MAX).hidden(),
1330
+ persona: z.string().default(DEFAULT_CODEX_PERSONA),
1331
+ harnessSourcePrompt: z.string().default(DEFAULT_DSH_CORE_SOURCE_PROMPT),
1332
+ webSurfacePrompt: z.string().default(DEFAULT_DSH_CORE_WEB_PROMPT),
1333
+ systemPrompt: z.string().default(DEFAULT_CODEX_SYSTEM_PROMPT),
1334
+ promptEnabled: z.boolean().default(true),
1335
+ terminalToolsEnabled: z.boolean().default(true).hidden(),
1336
+ patchToolEnabled: z.boolean().default(true).hidden(),
1337
+ planToolEnabled: z.boolean().default(true).hidden(),
1338
+ hostedWebSearchEnabled: z.boolean().default(true),
1339
+ remoteCompactionEnabled: z.boolean().default(true),
1340
+ activityIndicatorEnabled: z.boolean().default(true)
1341
+ });
1342
+ /** Host-only reads: never expose the unredacted provider configuration to clients. */
1343
+ function readHostSettings(ctx, namespace) {
1344
+ if (namespace === "codex") {
1345
+ const preferences = ctx.get("codexPreferences");
1346
+ if (preferences !== void 0) return preferences.current();
1347
+ }
1348
+ return ctx.get("settings")?.describe?.().find((row) => row.ns === namespace)?.value;
1349
+ }
1350
+ //#endregion
1351
+ //#region lib/types/policy/tool-capabilities.js
1352
+ const OWNED_TOOL = Symbol.for("@shuind/dsh-codex-harness:tool-capability:v1");
1353
+ const CAPABILITIES = [
1354
+ "terminalToolsEnabled",
1355
+ "planToolEnabled",
1356
+ "patchToolEnabled"
1357
+ ];
1358
+ function markCodexTool(definition, metadata) {
1359
+ Object.defineProperty(definition, OWNED_TOOL, { value: Object.freeze({ ...metadata }) });
1360
+ return definition;
1361
+ }
1362
+ function codexToolMetadata(definition) {
1363
+ const value = definition[OWNED_TOOL];
1364
+ if (value === null || typeof value !== "object") return void 0;
1365
+ const data = value;
1366
+ if (!CAPABILITIES.includes(data.capability) || typeof data.presetEnabled !== "boolean" || data.presetOverridesLegacy !== void 0 && typeof data.presetOverridesLegacy !== "boolean") return void 0;
1367
+ return {
1368
+ capability: data.capability,
1369
+ presetEnabled: data.presetEnabled,
1370
+ ...data.presetOverridesLegacy === void 0 ? {} : { presetOverridesLegacy: data.presetOverridesLegacy }
1371
+ };
1372
+ }
1373
+ /** Read once for a new Agent or catalog. No caller keeps the live preference object. */
1374
+ function readLegacyCapabilities(ctx) {
1375
+ const current = readHostSettings(ctx, CODEX_SETTINGS_NAMESPACE);
1376
+ return Object.freeze(Object.fromEntries(CAPABILITIES.map((key) => [key, current?.[key] ?? CODEX_SETTINGS_ENTRY[key]])));
1377
+ }
1378
+ function codexToolEnabled(ctx, agent, name, metadata, fallback, authority) {
1379
+ if (!metadata.presetEnabled) return false;
1380
+ if (authority !== void 0) return authority;
1381
+ return (agent === void 0 ? void 0 : ctx.get("codexToolPolicy")?.enabled(agent, name, metadata)) ?? fallback()[metadata.capability] !== false;
1382
+ }
1383
+ function assertCapabilityEnabled(ctx, current, toolName, agent, metadata, authority) {
1384
+ if (!codexToolEnabled(ctx, agent, toolName, metadata, current, authority)) throw new Error(`${toolName}: disabled in Codex Harness plugin settings`);
1385
+ }
1386
+ //#endregion
1387
+ //#region lib/types/tools/patch-tool.js
1388
+ /** Shared `apply_patch` tool registration over DSH `ctx.fs` and sandbox policy. */
1389
+ function sessionCwd(ctx, exec) {
1390
+ if (exec.agent === void 0) return void 0;
1391
+ return ctx.get("workingDirectory")?.get(exec.agent.session) ?? exec.agent.session.header.cwd;
1392
+ }
1393
+ function resolvePolicy(ctx, exec) {
1394
+ return ctx.get("sandboxPolicy")?.resolve(exec.agent === void 0 ? {} : { session: exec.agent.session });
1395
+ }
1396
+ async function resolveTarget(ctx, path, exec) {
1397
+ const cwd = sessionCwd(ctx, exec);
1398
+ return {
1399
+ target: await ctx.fs.resolve(path, cwd === void 0 ? { signal: exec.signal } : {
1400
+ cwd,
1401
+ signal: exec.signal
1402
+ }),
1403
+ cwd
1404
+ };
1405
+ }
1406
+ async function observedTarget(ctx, target, exec, rawPath, cwd) {
1407
+ const info = await ctx.fs.stat(target, exec.signal);
1408
+ if (info === void 0) {
1409
+ const cwdHint = !isAbsolute(rawPath) && cwd !== void 0 ? ` (cwd: ${cwd})` : "";
1410
+ throw new Error(`apply_patch: file not found: ${target.displayPath}${cwdHint}`);
1411
+ }
1412
+ if (info.type !== "file") throw new Error(`apply_patch: not a regular file: ${target.displayPath}`);
1413
+ ctx.emit("fs/observed", target, {
1414
+ kind: "present",
1415
+ version: info.version
1416
+ }, exec);
1417
+ return info;
1418
+ }
1419
+ function withSandboxDenialMarker(error, policy) {
1420
+ if (!(error instanceof FsError) || error.code !== "FS_SANDBOX_DENIED" || policy === void 0) return error;
1421
+ const marker = sandboxDenialMarker(policy.mode);
1422
+ if (error.message.includes(marker)) return error;
1423
+ return new FsError(`${error.message}\n${marker}`, "FS_SANDBOX_DENIED", { cause: error });
1424
+ }
1425
+ async function writePatchedFile(ctx, target, content, fallback, exec, policy) {
1426
+ const intent = await ctx.waterfall("fs/write-intent", target, exec, () => fallback);
1427
+ try {
1428
+ const outcome = await ctx.fs.writeText(target, content, intent, exec.signal, policy);
1429
+ ctx.emit("fs/observed", target, {
1430
+ kind: "present",
1431
+ version: outcome.version
1432
+ }, exec);
1433
+ return outcome.version;
1434
+ } catch (error) {
1435
+ throw withSandboxDenialMarker(error, policy);
1436
+ }
1437
+ }
1438
+ async function deletePatchedFile(ctx, target, version, exec, policy) {
1439
+ const expected = await ctx.waterfall("fs/delete-intent", target, exec, () => ({ version }));
1440
+ try {
1441
+ await ctx.fs.deleteFile(target, expected, exec.signal, policy);
1442
+ ctx.emit("fs/observed", target, { kind: "absent" }, exec);
1443
+ } catch (error) {
1444
+ throw withSandboxDenialMarker(error, policy);
1445
+ }
1446
+ }
1447
+ async function preflightPatchFiles(ctx, files, exec) {
1448
+ const virtual = /* @__PURE__ */ new Map();
1449
+ const initialVersions = /* @__PURE__ */ new Map();
1450
+ const ops = [];
1451
+ const applied = [];
1452
+ const ensureAbsent = async (target, messagePrefix) => {
1453
+ const existing = virtual.get(target.targetKey);
1454
+ if (existing !== void 0) {
1455
+ if (existing.exists) throw new Error(`${messagePrefix}: ${target.displayPath}`);
1456
+ return;
1457
+ }
1458
+ if (await ctx.fs.stat(target, exec.signal) !== void 0) throw new Error(`${messagePrefix}: ${target.displayPath}`);
1459
+ ctx.emit("fs/observed", target, { kind: "absent" }, exec);
1460
+ virtual.set(target.targetKey, {
1461
+ target,
1462
+ exists: false,
1463
+ content: ""
1464
+ });
1465
+ };
1466
+ const ensureReadable = async (target, rawPath, cwd) => {
1467
+ const existing = virtual.get(target.targetKey);
1468
+ if (existing !== void 0) {
1469
+ if (!existing.exists) throw new Error(`apply_patch: file not found: ${target.displayPath}`);
1470
+ return existing;
1471
+ }
1472
+ const info = await observedTarget(ctx, target, exec, rawPath, cwd);
1473
+ const content = await ctx.fs.readText(target, exec.signal);
1474
+ initialVersions.set(target.targetKey, info.version);
1475
+ const entry = {
1476
+ target,
1477
+ exists: true,
1478
+ content
1479
+ };
1480
+ virtual.set(target.targetKey, entry);
1481
+ return entry;
1482
+ };
1483
+ for (const file of files) {
1484
+ const { target, cwd } = await resolveTarget(ctx, file.path, exec);
1485
+ if (file.kind === "add") {
1486
+ await ensureAbsent(target, "apply_patch: file already exists");
1487
+ virtual.set(target.targetKey, {
1488
+ target,
1489
+ exists: true,
1490
+ content: file.content
1491
+ });
1492
+ ops.push({
1493
+ kind: "write",
1494
+ target,
1495
+ content: file.content
1496
+ });
1497
+ applied.push({
1498
+ path: file.path,
1499
+ operation: "created"
1500
+ });
1501
+ continue;
1502
+ }
1503
+ const source = await ensureReadable(target, file.path, cwd);
1504
+ if (file.kind === "delete") {
1505
+ virtual.set(target.targetKey, {
1506
+ target,
1507
+ exists: false,
1508
+ content: ""
1509
+ });
1510
+ ops.push({
1511
+ kind: "delete",
1512
+ target
1513
+ });
1514
+ applied.push({
1515
+ path: file.path,
1516
+ operation: "deleted"
1517
+ });
1518
+ continue;
1519
+ }
1520
+ const updated = applyPatchHunks(source.content, file.hunks, file.path);
1521
+ if (file.moveTo === void 0) {
1522
+ virtual.set(target.targetKey, {
1523
+ target,
1524
+ exists: true,
1525
+ content: updated
1526
+ });
1527
+ ops.push({
1528
+ kind: "write",
1529
+ target,
1530
+ content: updated
1531
+ });
1532
+ applied.push({
1533
+ path: file.path,
1534
+ operation: "updated"
1535
+ });
1536
+ continue;
1537
+ }
1538
+ const { target: destination } = await resolveTarget(ctx, file.moveTo, exec);
1539
+ if (destination.targetKey === target.targetKey) {
1540
+ virtual.set(target.targetKey, {
1541
+ target,
1542
+ exists: true,
1543
+ content: updated
1544
+ });
1545
+ ops.push({
1546
+ kind: "write",
1547
+ target,
1548
+ content: updated
1549
+ });
1550
+ applied.push({
1551
+ path: file.path,
1552
+ operation: "updated",
1553
+ moveTo: file.moveTo
1554
+ });
1555
+ continue;
1556
+ }
1557
+ await ensureAbsent(destination, "apply_patch: move destination already exists");
1558
+ virtual.set(target.targetKey, {
1559
+ target,
1560
+ exists: false,
1561
+ content: ""
1562
+ });
1563
+ virtual.set(destination.targetKey, {
1564
+ target: destination,
1565
+ exists: true,
1566
+ content: updated
1567
+ });
1568
+ ops.push({
1569
+ kind: "write",
1570
+ target: destination,
1571
+ content: updated
1572
+ });
1573
+ ops.push({
1574
+ kind: "delete",
1575
+ target
1576
+ });
1577
+ applied.push({
1578
+ path: file.path,
1579
+ operation: "moved",
1580
+ moveTo: file.moveTo
1581
+ });
1582
+ }
1583
+ return {
1584
+ applied,
1585
+ ops,
1586
+ initialVersions
1587
+ };
1588
+ }
1589
+ async function applyPatchBatch(ctx, files, exec, policy) {
1590
+ const { applied, ops, initialVersions } = await preflightPatchFiles(ctx, files, exec);
1591
+ const versions = new Map(initialVersions);
1592
+ for (const op of ops) {
1593
+ if (op.kind === "write") {
1594
+ const currentVersion = versions.get(op.target.targetKey);
1595
+ const fallback = currentVersion === void 0 ? { kind: "createIfAbsent" } : {
1596
+ kind: "replaceIfVersion",
1597
+ version: currentVersion
1598
+ };
1599
+ const nextVersion = await writePatchedFile(ctx, op.target, op.content, fallback, exec, policy);
1600
+ versions.set(op.target.targetKey, nextVersion);
1601
+ continue;
1602
+ }
1603
+ const version = versions.get(op.target.targetKey);
1604
+ if (version === void 0) throw new Error(`apply_patch: missing version for delete: ${op.target.displayPath}`);
1605
+ await deletePatchedFile(ctx, op.target, version, exec, policy);
1606
+ versions.delete(op.target.targetKey);
1607
+ }
1608
+ return applied;
1609
+ }
1610
+ function patchSummary(value) {
1611
+ const letter = (operation) => {
1612
+ switch (operation) {
1613
+ case "created": return "A";
1614
+ case "updated": return "M";
1615
+ case "deleted": return "D";
1616
+ case "moved": return "M";
1617
+ default: return operation;
1618
+ }
1619
+ };
1620
+ return `Success. Updated the following files:\n${value.files.map((file) => `${letter(file.operation)} ${file.operation === "moved" ? file.moveTo : file.path}`).join("\n")}\n`;
1621
+ }
1622
+ function presentPatchCall(input) {
1623
+ try {
1624
+ const files = parsePatch(input);
1625
+ const diffs = files.flatMap((file) => {
1626
+ if (file.kind === "add") return [{
1627
+ path: file.path,
1628
+ oldText: null,
1629
+ newText: file.content
1630
+ }];
1631
+ if (file.kind === "delete") return [];
1632
+ return [{
1633
+ path: file.moveTo ?? file.path,
1634
+ oldText: file.hunks.flatMap((hunk) => hunk.lines.filter((line) => line.kind !== "add").map((line) => line.text)).join("\n") || null,
1635
+ newText: file.hunks.flatMap((hunk) => hunk.lines.filter((line) => line.kind !== "delete").map((line) => line.text)).join("\n")
1636
+ }];
1637
+ });
1638
+ const paths = new Set(files.flatMap((file) => file.kind === "update" && file.moveTo !== void 0 ? [file.path, file.moveTo] : [file.path]));
1639
+ return {
1640
+ card: "diff",
1641
+ title: `Apply patch (${paths.size} ${paths.size === 1 ? "file" : "files"})`,
1642
+ diffs,
1643
+ locations: [...paths].map((path) => ({ path }))
1644
+ };
1645
+ } catch {
1646
+ return {
1647
+ card: "generic",
1648
+ title: "Apply patch",
1649
+ kind: "edit",
1650
+ rawInput: input
1651
+ };
1652
+ }
1653
+ }
1654
+ function registerPatchTool(ctx, currentSettings, presetEnabled = true, authority, presetOverridesLegacy = false) {
1655
+ const tools = ctx.get("tools");
1656
+ if (tools === void 0) throw new Error("Codex patch tools require ctx.tools");
1657
+ const fs = ctx.get("fs") ?? ctx.fs;
1658
+ if (fs === void 0) throw new Error("Codex patch tools require ctx.fs");
1659
+ if (fs.sandboxMode !== void 0 && ctx.get("sandboxPolicy") === void 0) throw new Error("Codex patch tools: a sandboxing filesystem requires ctx.sandboxPolicy");
1660
+ const metadata = {
1661
+ capability: "patchToolEnabled",
1662
+ presetEnabled,
1663
+ ...presetOverridesLegacy ? { presetOverridesLegacy: true } : {}
1664
+ };
1665
+ return tools.register(markCodexTool(defineTool({
1666
+ name: "apply_patch",
1667
+ description: APPLY_PATCH_DESCRIPTION,
1668
+ parameters: { input: {
1669
+ type: "string",
1670
+ required: true,
1671
+ description: "The complete patch text."
1672
+ } },
1673
+ output: {
1674
+ schema: {
1675
+ type: "object",
1676
+ additionalProperties: false,
1677
+ properties: { files: {
1678
+ type: "array",
1679
+ required: true,
1680
+ items: {
1681
+ type: "object",
1682
+ additionalProperties: false,
1683
+ properties: {
1684
+ path: {
1685
+ type: "string",
1686
+ required: true
1687
+ },
1688
+ operation: {
1689
+ type: "string",
1690
+ required: true,
1691
+ enum: [
1692
+ "created",
1693
+ "updated",
1694
+ "deleted",
1695
+ "moved"
1696
+ ]
1697
+ },
1698
+ moveTo: { type: "string" }
1699
+ }
1700
+ }
1701
+ } }
1702
+ },
1703
+ render: (_args, value) => [{
1704
+ type: "text",
1705
+ text: patchSummary(value)
1706
+ }]
1707
+ },
1708
+ async execute(args, exec) {
1709
+ assertCapabilityEnabled(ctx, currentSettings, "apply_patch", exec.agent, metadata, authority);
1710
+ return { files: await applyPatchBatch(ctx, parsePatch(args.input), exec, resolvePolicy(ctx, exec)) };
1711
+ },
1712
+ presentCall(args) {
1713
+ return presentPatchCall(args.input);
1714
+ },
1715
+ presentResult(args, result) {
1716
+ if (result.isError) return void 0;
1717
+ const view = presentPatchCall(args.input);
1718
+ return view.card === "diff" ? {
1719
+ card: "diff",
1720
+ title: view.title,
1721
+ diffs: view.diffs
1722
+ } : void 0;
1723
+ }
1724
+ }), metadata), { when: (context) => codexToolEnabled(ctx, context?.agent, "apply_patch", metadata, currentSettings, authority) });
1725
+ }
1726
+ const EXEC_COMMAND_DESCRIPTION = "Runs a command in the host-configured shell. By default it uses pipes: a running session can be polled for output but does not accept stdin. Set tty=true before starting a command that needs interactive input; background jobs use pipes.";
1727
+ const WRITE_STDIN_DESCRIPTION = "Polls output from an existing unified exec session. Non-empty chars can be sent to a session created with tty=true; pipe-backed sessions accept empty chars for polling or \"\\u0003\" to interrupt.";
1728
+ const UPDATE_PLAN_DESCRIPTION = "Updates the task plan.\nProvide an optional explanation and a list of plan items, each with a step and status.\nAt most one step can be in_progress at a time.";
1729
+ const PLAN_STATUSES = [
1730
+ "pending",
1731
+ "in_progress",
1732
+ "completed"
1733
+ ];
1734
+ function planTodos(args) {
1735
+ const seen = /* @__PURE__ */ new Set();
1736
+ let active = 0;
1737
+ const todos = [];
1738
+ for (const item of args.plan) {
1739
+ const content = item.step.trim();
1740
+ if (content.length === 0) throw new Error("update_plan: every step must be non-empty");
1741
+ if (seen.has(content)) throw new Error(`update_plan: duplicate step ${JSON.stringify(content)}`);
1742
+ seen.add(content);
1743
+ if (item.status === "in_progress") active++;
1744
+ todos.push({
1745
+ content,
1746
+ status: item.status
1747
+ });
1748
+ }
1749
+ if (active > 1) throw new Error("update_plan: at most one step may be in_progress");
1750
+ return todos;
1751
+ }
1752
+ /** Release every registration once, even when one release fails. */
1753
+ function composeToolDisposers(disposers) {
1754
+ return () => {
1755
+ const errors = [];
1756
+ for (const dispose of disposers.splice(0).reverse()) try {
1757
+ dispose();
1758
+ } catch (error) {
1759
+ errors.push(error);
1760
+ }
1761
+ if (errors.length > 0) throw new AggregateError(errors, "Could not unregister Codex tools");
1762
+ };
1763
+ }
1764
+ function terminalResultView(result) {
1765
+ if (result.isError) return void 0;
1766
+ const meta = typeof result.meta === "object" && result.meta !== null && !Array.isArray(result.meta) ? result.meta : void 0;
1767
+ if (typeof meta?.output !== "string") return void 0;
1768
+ return {
1769
+ card: "terminal",
1770
+ output: meta.output,
1771
+ ...typeof meta.exitCode === "number" ? { exitCode: meta.exitCode } : {}
1772
+ };
1773
+ }
1774
+ function registerExecTools(ctx, config) {
1775
+ const tools = ctx.get("tools");
1776
+ if (tools === void 0) throw new Error("Codex execution tools require ctx.tools");
1777
+ const shell = ctx.get("shell");
1778
+ if (shell === void 0) throw new Error("Codex execution tools require ctx.shell");
1779
+ const confines = shell.sandboxMode !== void 0;
1780
+ if (confines && ctx.get("sandboxPolicy") === void 0) throw new Error("Codex execution tools: a sandboxing shell requires ctx.sandboxPolicy");
1781
+ const metadata = {
1782
+ capability: "terminalToolsEnabled",
1783
+ presetEnabled: config.presetEnabled !== false,
1784
+ ...config.presetOverridesLegacy ? { presetOverridesLegacy: true } : {}
1785
+ };
1786
+ const ownedAgents = /* @__PURE__ */ new Set();
1787
+ const offDisposed = typeof ctx.on === "function" ? ctx.on("agent/disposed", ({ agent }) => {
1788
+ ownedAgents.delete(agent);
1789
+ disposeAgentExecSessions(agent);
1790
+ }) : () => {};
1791
+ const cleanupOwned = () => {
1792
+ offDisposed();
1793
+ for (const agent of [...ownedAgents]) {
1794
+ ownedAgents.delete(agent);
1795
+ disposeAgentExecSessions(agent);
1796
+ }
1797
+ };
1798
+ let unregisterExec;
1799
+ try {
1800
+ unregisterExec = tools.register(markCodexTool(defineTool({
1801
+ name: "exec_command",
1802
+ description: EXEC_COMMAND_DESCRIPTION,
1803
+ parameters: {
1804
+ cmd: {
1805
+ type: "string",
1806
+ required: true,
1807
+ description: "Shell command to execute."
1808
+ },
1809
+ workdir: {
1810
+ type: "string",
1811
+ description: "Working directory for the command. Defaults to the turn cwd."
1812
+ },
1813
+ tty: {
1814
+ type: "boolean",
1815
+ description: confines ? "This host cannot carry sandbox policy into a PTY; omit tty or use false." : "True allocates a PTY for the command; false or omitted uses plain pipes."
1816
+ },
1817
+ run_in_background: {
1818
+ type: "boolean",
1819
+ description: "Run as a DSH background job and return its job id immediately; collect output with job_output and stop it with job_kill. Only supported for pipe-backed commands."
1820
+ },
1821
+ yield_time_ms: {
1822
+ type: "number",
1823
+ description: "Wait before yielding output. Defaults to 10000 ms; effective range is 250-30000 ms."
1824
+ },
1825
+ max_output_tokens: {
1826
+ type: "number",
1827
+ description: "Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy."
1828
+ },
1829
+ ...confines ? {
1830
+ sandbox_permissions: {
1831
+ type: "string",
1832
+ enum: [...ESCALATION_TARGETS],
1833
+ description: sandboxPermissionsDescription("command")
1834
+ },
1835
+ justification: {
1836
+ type: "string",
1837
+ description: "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access. Use the language of the user’s current request."
1838
+ }
1839
+ } : {}
1840
+ },
1841
+ output: {
1842
+ schema: {
1843
+ type: "object",
1844
+ additionalProperties: false,
1845
+ properties: {
1846
+ chunk_id: { type: "string" },
1847
+ wall_time_seconds: {
1848
+ type: "number",
1849
+ required: true
1850
+ },
1851
+ exit_code: { type: "number" },
1852
+ session_id: { type: "number" },
1853
+ job_id: { type: "string" },
1854
+ original_token_count: { type: "number" },
1855
+ output: {
1856
+ type: "string",
1857
+ required: true
1858
+ }
1859
+ }
1860
+ },
1861
+ render: (_args, value) => [{
1862
+ type: "text",
1863
+ text: renderExecResult(value)
1864
+ }],
1865
+ presentationMeta: (_args, value) => ({
1866
+ output: value.output,
1867
+ ...value.exit_code === void 0 ? {} : { exitCode: value.exit_code },
1868
+ ...value.job_id === void 0 ? {} : { jobId: value.job_id }
1869
+ })
1870
+ },
1871
+ async execute(args, exec) {
1872
+ assertCapabilityEnabled(ctx, config.currentSettings, "exec_command", exec.agent, metadata, config.authority);
1873
+ const result = await runExecCommand(ctx, args, exec, config);
1874
+ if (result.session_id !== void 0 && exec.agent !== void 0) ownedAgents.add(exec.agent);
1875
+ return result;
1876
+ },
1877
+ presentCall: (args) => args.run_in_background === true ? {
1878
+ card: "generic",
1879
+ title: args.cmd,
1880
+ kind: "execute",
1881
+ rawInput: args.cmd
1882
+ } : {
1883
+ card: "terminal",
1884
+ title: args.cmd,
1885
+ ...args.workdir === void 0 ? {} : { cwd: args.workdir }
1886
+ },
1887
+ presentResult: (args, result) => args.run_in_background === true ? void 0 : terminalResultView(result)
1888
+ }), metadata), { when: (context) => codexToolEnabled(ctx, context?.agent, "exec_command", metadata, config.currentSettings, config.authority) });
1889
+ const unregisterStdin = tools.register(markCodexTool(defineTool({
1890
+ name: "write_stdin",
1891
+ description: WRITE_STDIN_DESCRIPTION,
1892
+ parameters: {
1893
+ session_id: {
1894
+ type: "number",
1895
+ required: true,
1896
+ description: "Identifier of the running unified exec session."
1897
+ },
1898
+ chars: {
1899
+ type: "string",
1900
+ description: "Characters to send to a PTY session created with tty=true. Leave empty to poll output without writing; pipe-backed sessions accept empty chars to poll or \"\\u0003\" to interrupt."
1901
+ },
1902
+ yield_time_ms: {
1903
+ type: "number",
1904
+ description: "Wait before yielding output. Non-empty writes default to 250 ms and cap at 30000 ms; empty polls wait 5000-300000 ms by default."
1905
+ },
1906
+ max_output_tokens: {
1907
+ type: "number",
1908
+ description: "Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy."
1909
+ }
1910
+ },
1911
+ output: {
1912
+ schema: {
1913
+ type: "object",
1914
+ additionalProperties: false,
1915
+ properties: {
1916
+ chunk_id: { type: "string" },
1917
+ wall_time_seconds: {
1918
+ type: "number",
1919
+ required: true
1920
+ },
1921
+ exit_code: { type: "number" },
1922
+ session_id: { type: "number" },
1923
+ original_token_count: { type: "number" },
1924
+ output: {
1925
+ type: "string",
1926
+ required: true
1927
+ }
1928
+ }
1929
+ },
1930
+ render: (_args, value) => [{
1931
+ type: "text",
1932
+ text: renderExecResult(value)
1933
+ }],
1934
+ presentationMeta: (_args, value) => ({
1935
+ output: value.output,
1936
+ ...value.exit_code === void 0 ? {} : { exitCode: value.exit_code }
1937
+ })
1938
+ },
1939
+ async execute(args, exec) {
1940
+ assertCapabilityEnabled(ctx, config.currentSettings, "write_stdin", exec.agent, metadata, config.authority);
1941
+ return runWriteStdin(ctx, args, exec, config);
1942
+ },
1943
+ presentCall: (args) => ({
1944
+ card: "terminal",
1945
+ title: `write_stdin #${args.session_id}`
1946
+ }),
1947
+ presentResult: (_args, result) => terminalResultView(result)
1948
+ }), metadata), { when: (context) => codexToolEnabled(ctx, context?.agent, "write_stdin", metadata, config.currentSettings, config.authority) });
1949
+ return composeToolDisposers([
1950
+ cleanupOwned,
1951
+ unregisterExec,
1952
+ unregisterStdin
1953
+ ]);
1954
+ } catch (error) {
1955
+ cleanupOwned();
1956
+ unregisterExec?.();
1957
+ throw error;
1958
+ }
1959
+ }
1960
+ function registerPlanTool(ctx, currentSettings, presetEnabled = true, authority, presetOverridesLegacy = false) {
1961
+ const tools = ctx.get("tools");
1962
+ if (tools === void 0) throw new Error("Codex plan tools require ctx.tools");
1963
+ const metadata = {
1964
+ capability: "planToolEnabled",
1965
+ presetEnabled,
1966
+ ...presetOverridesLegacy ? { presetOverridesLegacy: true } : {}
1967
+ };
1968
+ return tools.register(markCodexTool(defineTool({
1969
+ name: "update_plan",
1970
+ description: UPDATE_PLAN_DESCRIPTION,
1971
+ parameters: {
1972
+ explanation: {
1973
+ type: "string",
1974
+ description: "Optional explanation for this plan update."
1975
+ },
1976
+ plan: {
1977
+ type: "array",
1978
+ required: true,
1979
+ description: "The list of steps",
1980
+ items: {
1981
+ type: "object",
1982
+ additionalProperties: false,
1983
+ properties: {
1984
+ step: {
1985
+ type: "string",
1986
+ required: true,
1987
+ description: "Task step text."
1988
+ },
1989
+ status: {
1990
+ type: "string",
1991
+ required: true,
1992
+ enum: [...PLAN_STATUSES],
1993
+ description: "Step status."
1994
+ }
1995
+ }
1996
+ }
1997
+ }
1998
+ },
1999
+ output: {
2000
+ schema: {
2001
+ type: "object",
2002
+ additionalProperties: false,
2003
+ properties: {}
2004
+ },
2005
+ render: () => [{
2006
+ type: "text",
2007
+ text: "Plan updated"
2008
+ }]
2009
+ },
2010
+ execute(args, exec) {
2011
+ assertCapabilityEnabled(ctx, currentSettings, "update_plan", exec.agent, metadata, authority);
2012
+ const agent = exec.agent;
2013
+ if (agent === void 0) throw new Error("update_plan requires an owning agent session");
2014
+ if (((typeof agent.session.snapshotEvents === "function" ? agent.session.snapshotEvents() : void 0)?.findLast((event) => event.type === "plan/mode"))?.data?.active === true) throw new Error("update_plan is a task-execution checklist tool and is not allowed in plan mode; submit your plan via exit_plan_mode");
2015
+ agent.session.append("todo/write", { todos: planTodos(args) });
2016
+ return Promise.resolve({});
2017
+ }
2018
+ }), metadata), { when: (context) => codexToolEnabled(ctx, context?.agent, "update_plan", metadata, currentSettings, authority) });
2019
+ }
2020
+ /**
2021
+ * Register selected Codex tools through the existing pipeline, without prompt hooks.
2022
+ * Compiled adapters receive authority once; the disposer supports an additional owner.
2023
+ */
2024
+ function registerCodexExecAndPlan(ctx, options = {}) {
2025
+ const currentSettings = () => ({
2026
+ ...CODEX_SETTINGS_ENTRY,
2027
+ ...readHostSettings(ctx, CODEX_SETTINGS_NAMESPACE)
2028
+ });
2029
+ const disposers = [];
2030
+ const dispose = composeToolDisposers(disposers);
2031
+ try {
2032
+ if (options.terminal !== false) disposers.push(registerExecTools(ctx, {
2033
+ defaultYieldTimeMs: options.defaultYieldTimeMs ?? 1e4,
2034
+ pollYieldTimeMs: options.pollYieldTimeMs ?? 5e3,
2035
+ writeYieldTimeMs: options.writeYieldTimeMs ?? 250,
2036
+ maxOutputBytes: options.maxOutputBytes ?? 1048576,
2037
+ currentSettings,
2038
+ ...options.capabilityAuthority?.terminalToolsEnabled === void 0 ? {} : { authority: options.capabilityAuthority.terminalToolsEnabled }
2039
+ }));
2040
+ if (options.plan !== false) disposers.push(registerPlanTool(ctx, currentSettings, true, options.capabilityAuthority?.planToolEnabled));
2041
+ if (options.patch === true) disposers.push(registerPatchTool(ctx, currentSettings, true, options.capabilityAuthority?.patchToolEnabled));
2042
+ return dispose;
2043
+ } catch (error) {
2044
+ dispose();
2045
+ throw error;
2046
+ }
2047
+ }
2048
+ //#endregion
2049
+ //#region lib/types/policy/overlay-installer.js
2050
+ /** Atomic per-Agent tool mask, Codex adapter replacement, prompt override, and defer overlay installer. */
2051
+ /**
2052
+ * Install only through an exact Agent scope. Replacement is deliberately limited
2053
+ * to builtin source names: arbitrary tools, argument adapters, and third-party
2054
+ * name-specific tools/pre-execute policy are not made equivalent by this overlay.
2055
+ */
2056
+ function installOverlay(agent, rule, legacyCapabilities, preparedPrompts, onDispose) {
2057
+ if (scopeOf(agent.ctx) !== agent) throw new Error("codex-tool-policy: an exact Agent scope is required");
2058
+ if (preparedPrompts !== void 0 && (scopeParentOf(agent) !== preparedPrompts.scope || !matchesPromptRevision(agent.ctx, rule.preset, preparedPrompts))) throw new Error("preset-prompt-revision-mismatch");
2059
+ const tools = agent.ctx.get("tools");
2060
+ if (tools === void 0) throw new Error("codex-tool-policy: the Agent has no tools service");
2061
+ const upstream = scopeParentOf(agent);
2062
+ for (const choice of rule.tools ?? []) if (tools.get(choice.name, agent) === void 0) throw new Error(`codex-tool-policy: unknown or unavailable source tool ${JSON.stringify(choice.name)} in explicit choice`);
2063
+ for (const tool of [
2064
+ ...rule.allow ?? [],
2065
+ ...rule.deny ?? [],
2066
+ ...rule.tools?.map((choice) => choice.name) ?? []
2067
+ ]) {
2068
+ const visible = tools.get(tool, agent);
2069
+ if (visible !== void 0 && tools.get(tool, upstream) !== visible) throw new Error(`codex-tool-policy: cannot restrict Agent-local tool ${JSON.stringify(tool)}`);
2070
+ }
2071
+ const allow = rule.allow === void 0 ? void 0 : new Set(rule.allow);
2072
+ const deny = new Set(rule.deny);
2073
+ let hasDeny = rule.deny !== void 0;
2074
+ for (const choice of rule.tools ?? []) if (choice.action === "hide") {
2075
+ deny.add(choice.name);
2076
+ hasDeny = true;
2077
+ allow?.delete(choice.name);
2078
+ } else {
2079
+ deny.delete(choice.name);
2080
+ allow?.add(choice.name);
2081
+ }
2082
+ const defaultHiddenSet = readDefaultHiddenTools(agent.ctx, agent);
2083
+ for (const hiddenName of defaultHiddenSet ?? []) {
2084
+ const visible = tools.get(hiddenName, agent);
2085
+ if (visible !== void 0 && tools.get(hiddenName, upstream) === visible && !rule.tools?.some((choice) => choice.name === hiddenName)) {
2086
+ deny.add(hiddenName);
2087
+ hasDeny = true;
2088
+ allow?.delete(hiddenName);
2089
+ }
2090
+ }
2091
+ const defaultDeferredSet = readDefaultDeferredTools(agent.ctx, agent);
2092
+ const actionFor = (name) => {
2093
+ const definition = tools.get(name, agent);
2094
+ const codexTool = definition === void 0 ? void 0 : codexToolMetadata(definition);
2095
+ return effectiveToolAction(rule, name, {
2096
+ legacyCapabilities,
2097
+ ...codexTool === void 0 ? {} : { codexTool },
2098
+ ...defaultDeferredSet?.has(name) ? { defaultDeferred: true } : {}
2099
+ });
2100
+ };
2101
+ for (const name of [
2102
+ "bash",
2103
+ "pwsh",
2104
+ "todo_write",
2105
+ "edit",
2106
+ "write"
2107
+ ]) {
2108
+ const oldAction = legacyToolAction(rule, name);
2109
+ if (tools.get(name, agent) !== void 0 && (oldAction === "codex-exec" || oldAction === "codex-plan" || oldAction === "codex-patch") && actionFor(name) === "hide") {
2110
+ deny.add(name);
2111
+ hasDeny = true;
2112
+ allow?.delete(name);
2113
+ }
2114
+ }
2115
+ const mask = {
2116
+ ...allow === void 0 ? {} : { allow: [...allow] },
2117
+ ...!hasDeny ? {} : { deny: [...deny] }
2118
+ };
2119
+ const permitted = (tool) => (allow === void 0 || allow.has(tool)) && !deny.has(tool);
2120
+ const shells = ["bash", "pwsh"].filter((tool) => actionFor(tool) === "codex-exec" && permitted(tool) && tools.get(tool, agent) !== void 0);
2121
+ const plan = actionFor("todo_write") === "codex-plan" && permitted("todo_write") && tools.get("todo_write", agent) !== void 0;
2122
+ const patches = ["edit", "write"].filter((tool) => actionFor(tool) === "codex-patch" && permitted(tool) && tools.get(tool, agent) !== void 0);
2123
+ const sources = [
2124
+ ...shells,
2125
+ ...plan ? ["todo_write"] : [],
2126
+ ...patches
2127
+ ];
2128
+ const deferredDefinitions = tools.definitions(upstream).filter((definition) => definition.name !== "activate_tools" && actionFor(definition.name) === "defer" && permitted(definition.name) && !sources.includes(definition.name) && tools.get(definition.name, agent) !== void 0);
2129
+ for (const tool of sources) {
2130
+ const definition = tools.get(tool, agent);
2131
+ if (tools.executable(tool, agent) !== definition) throw new Error(`codex-tool-policy: cannot replace conditional source tool ${JSON.stringify(tool)}; its activation condition must not be discarded`);
2132
+ if (tools.get(tool, upstream) !== definition) throw new Error(`codex-tool-policy: cannot replace Agent-local source tool ${JSON.stringify(tool)}`);
2133
+ }
2134
+ for (const definition of deferredDefinitions) {
2135
+ if (tools.executable(definition.name, agent) !== definition) throw new Error(`codex-tool-policy: cannot defer conditional source tool ${JSON.stringify(definition.name)}; its activation condition must not be discarded`);
2136
+ if (tools.get(definition.name, upstream) !== definition) throw new Error(`codex-tool-policy: cannot defer Agent-local source tool ${JSON.stringify(definition.name)}`);
2137
+ }
2138
+ const additions = [
2139
+ ...shells.length > 0 ? ["exec_command", "write_stdin"] : [],
2140
+ ...plan ? ["update_plan"] : [],
2141
+ ...patches.length > 0 ? ["apply_patch"] : [],
2142
+ ...deferredDefinitions.length > 0 ? [ACTIVATE_TOOLS_NAME] : []
2143
+ ];
2144
+ for (const tool of additions) if (tools.get(tool, agent) !== void 0) throw new Error(`codex-tool-policy: replacement tool ${JSON.stringify(tool)} already exists; refusing to shadow another implementation`);
2145
+ if (shells.length > 0 && agent.ctx.get("shell") === void 0) throw new Error("codex-tool-policy: builtin shell replacement requires the mounted shell capability");
2146
+ if (patches.length > 0 && agent.ctx.get("fs") === void 0) throw new Error("codex-tool-policy: builtin file-edit replacement requires the mounted fs capability");
2147
+ const needsPrompt = sources.length > 0 || deferredDefinitions.length > 0 || (preparedPrompts?.sections.length ?? 0) > 0;
2148
+ const systemPrompt = needsPrompt ? agent.ctx.get("systemPrompt") : void 0;
2149
+ if (needsPrompt && systemPrompt === void 0) throw new Error("codex-tool-policy: replacements require the mounted systemPrompt service");
2150
+ const guidance = [
2151
+ ...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.`],
2152
+ ...plan ? ["For this Agent, todo_write is replaced by update_plan. Follow its current schema; at most one plan item may be in_progress."] : [],
2153
+ ...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("/")}.`]
2154
+ ].join("\n");
2155
+ const dispose = agent.ctx.effect(function* () {
2156
+ yield onDispose;
2157
+ for (const section of preparedPrompts?.sections ?? []) yield systemPrompt.section(section);
2158
+ if (mask.allow !== void 0 || mask.deny !== void 0) yield tools.restrict(mask);
2159
+ for (const tool of mask.deny ?? []) if (tools.get(tool, agent) !== void 0) throw new Error(`codex-tool-policy: cannot hide Agent-local tool ${JSON.stringify(tool)}`);
2160
+ if (sources.length > 0) {
2161
+ yield tools.restrict({ deny: sources });
2162
+ for (const tool of sources) if (tools.get(tool, agent) !== void 0) throw new Error(`codex-tool-policy: cannot hide Agent-local source tool ${JSON.stringify(tool)}`);
2163
+ yield registerCodexExecAndPlan(agent.ctx, {
2164
+ terminal: shells.length > 0,
2165
+ plan,
2166
+ patch: patches.length > 0,
2167
+ capabilityAuthority: {
2168
+ terminalToolsEnabled: shells.length > 0,
2169
+ planToolEnabled: plan,
2170
+ patchToolEnabled: patches.length > 0
2171
+ }
2172
+ });
2173
+ yield systemPrompt.section({
2174
+ name: "codex:tool-policy",
2175
+ order: 1015,
2176
+ text: guidance
2177
+ });
2178
+ }
2179
+ if (deferredDefinitions.length > 0) yield* yieldDeferredToolsOverlay(tools, systemPrompt, deferredDefinitions, agent);
2180
+ }, `codex-tool-policy:${rule.preset}`);
2181
+ return () => {
2182
+ dispose();
2183
+ };
2184
+ }
2185
+ //#endregion
2186
+ //#region lib/types/policy/rule-resolver.js
2187
+ /** Schema, choice validation, and rule detaching for `codex-tool-policy`. */
2188
+ const Config = z.object({ rules: z.array(z.object({
2189
+ preset: z.string().required().description("Exact preset id; only Agents created after this plugin loads are affected."),
2190
+ allow: z.union([z.array(z.string())]).description("Inherited source names to keep. Omit for no allowlist; [] removes all inherited tools, including file tools."),
2191
+ deny: z.union([z.array(z.string())]).description("Inherited source names to remove; unknown and Agent-local names are rejected."),
2192
+ 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."),
2193
+ replacePlan: z.boolean().default(true).description("Legacy default: replace permitted builtin todo_write with update_plan; explicit source choices override it."),
2194
+ replacePatch: z.boolean().default(false).description("Legacy default: replace permitted builtin edit/write with apply_patch; explicit source choices override it."),
2195
+ tools: z.union([z.array(z.object({
2196
+ name: z.string().required().description("Exact inherited source tool name."),
2197
+ action: z.union([
2198
+ z.const("keep"),
2199
+ z.const("hide"),
2200
+ z.const("defer"),
2201
+ z.const("codex-exec"),
2202
+ z.const("codex-plan"),
2203
+ z.const("codex-patch")
2204
+ ]).required().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.")
2205
+ }))]).description("Individual source choices, overriding allow/deny and legacy replacement defaults. Omission preserves legacy behavior."),
2206
+ promptOverrides: z.union([z.array(z.object({
2207
+ name: z.union(PRESET_PROMPT_NAMES.map((name) => z.const(name))).required(),
2208
+ text: z.string().max(1e6).required()
2209
+ }))]).description("Exact current-preset prompt replacements. Order, interpolation and complete semantics remain Host-owned.")
2210
+ })).default([]) }).volatile();
2211
+ /** Reject ambiguous/unsupported overrides before any Agent registrations change. */
2212
+ function resolveToolChoices(input) {
2213
+ if (input === void 0) return void 0;
2214
+ if (!Array.isArray(input)) throw new TypeError("codex-tool-policy: tools must be an array of source choices");
2215
+ const seen = /* @__PURE__ */ new Set();
2216
+ const choices = [];
2217
+ for (const choice of input) {
2218
+ if (choice === null || typeof choice !== "object" || typeof choice.name !== "string" || choice.name.trim().length === 0) throw new TypeError("codex-tool-policy: every tool choice requires a non-empty source name");
2219
+ if (seen.has(choice.name)) throw new Error(`codex-tool-policy: duplicate tool choice ${JSON.stringify(choice.name)}`);
2220
+ seen.add(choice.name);
2221
+ if (![
2222
+ "keep",
2223
+ "hide",
2224
+ "defer",
2225
+ "codex-exec",
2226
+ "codex-plan",
2227
+ "codex-patch"
2228
+ ].includes(choice.action)) throw new TypeError(`codex-tool-policy: invalid action for source tool ${JSON.stringify(choice.name)}`);
2229
+ if (choice.action === "defer" && choice.name === "activate_tools") throw new Error(`codex-tool-policy: cannot defer reserved tool ${JSON.stringify(ACTIVATE_TOOLS_NAME)}`);
2230
+ if (choice.action === "codex-exec" && choice.name !== "bash" && choice.name !== "pwsh" || choice.action === "codex-plan" && choice.name !== "todo_write" || choice.action === "codex-patch" && choice.name !== "edit" && choice.name !== "write") throw new Error(`codex-tool-policy: unsupported replacement ${JSON.stringify(choice.action)} for source tool ${JSON.stringify(choice.name)}`);
2231
+ choices.push({
2232
+ name: choice.name,
2233
+ action: choice.action
2234
+ });
2235
+ }
2236
+ return choices;
2237
+ }
2238
+ function resolvePromptChoices(input) {
2239
+ if (input === void 0) return void 0;
2240
+ if (!Array.isArray(input) || input.length > PRESET_PROMPT_NAMES.length) throw new Error("invalid-preset-prompt-overrides");
2241
+ const seen = /* @__PURE__ */ new Set();
2242
+ return input.map((value) => {
2243
+ if (value === null || typeof value !== "object" || !PRESET_PROMPT_NAMES.includes(value.name) || typeof value.text !== "string" || value.text.length > 1e6 || Object.keys(value).some((key) => key !== "name" && key !== "text") || seen.has(value.name)) throw new Error("invalid-preset-prompt-override");
2244
+ seen.add(value.name);
2245
+ return {
2246
+ name: value.name,
2247
+ text: value.text
2248
+ };
2249
+ });
2250
+ }
2251
+ /** Validate direct callers too, and detach configuration from later form mutations. */
2252
+ function resolveRules(config) {
2253
+ const input = config.rules ?? [];
2254
+ if (!Array.isArray(input)) throw new TypeError("codex-tool-policy: rules must be an array");
2255
+ const rules = /* @__PURE__ */ new Map();
2256
+ for (const rule of input) {
2257
+ if (rule === null || typeof rule !== "object" || typeof rule.preset !== "string" || rule.preset.trim().length === 0) throw new TypeError("codex-tool-policy: every rule requires a non-empty preset id");
2258
+ if (rules.has(rule.preset)) throw new Error(`codex-tool-policy: duplicate preset rule ${JSON.stringify(rule.preset)}`);
2259
+ for (const key of ["allow", "deny"]) {
2260
+ const names = rule[key];
2261
+ if (names !== void 0 && (!Array.isArray(names) || names.some((tool) => typeof tool !== "string" || tool.trim().length === 0))) throw new TypeError(`codex-tool-policy: ${key} must be an array of non-empty tool names`);
2262
+ }
2263
+ for (const key of [
2264
+ "replaceShell",
2265
+ "replacePlan",
2266
+ "replacePatch"
2267
+ ]) if (rule[key] !== void 0 && typeof rule[key] !== "boolean") throw new TypeError(`codex-tool-policy: ${key} must be a boolean`);
2268
+ const choices = resolveToolChoices(rule.tools);
2269
+ const prompts = resolvePromptChoices(rule.promptOverrides);
2270
+ rules.set(rule.preset, {
2271
+ preset: rule.preset,
2272
+ ...rule.allow === void 0 ? {} : { allow: [...rule.allow] },
2273
+ ...rule.deny === void 0 ? {} : { deny: [...rule.deny] },
2274
+ replaceShell: rule.replaceShell !== false,
2275
+ replacePlan: rule.replacePlan !== false,
2276
+ replacePatch: rule.replacePatch === true,
2277
+ ...choices === void 0 ? {} : { tools: choices },
2278
+ ...prompts === void 0 ? {} : { promptOverrides: prompts }
2279
+ });
2280
+ }
2281
+ return rules;
2282
+ }
2283
+ //#endregion
2284
+ //#region lib/types/entries/tool-policy.js
2285
+ /** Opt-in Host overlays for future Agents; source presets and Persona stay untouched. */
2286
+ const name = "codex-tool-policy";
2287
+ const inject = [
2288
+ "tools",
2289
+ "agents",
2290
+ "agentPresets"
2291
+ ];
2292
+ /**
2293
+ * Affect future Agent lifecycles only. No existing-agent scan, polling, prompt
2294
+ * rewrite, source-preset edit, or executor replacement is performed.
2295
+ */
2296
+ function apply(ctx, config = {}) {
2297
+ const currentConfig = () => "get" in config ? config.get() ?? {} : config;
2298
+ resolveRules(currentConfig());
2299
+ const snapshots = /* @__PURE__ */ new WeakMap();
2300
+ const overlays = /* @__PURE__ */ new Map();
2301
+ let active = true;
2302
+ ctx.provide("codexToolPolicy", {
2303
+ enabled(agent, name, metadata) {
2304
+ const snapshot = snapshots.get(agent);
2305
+ if (snapshot === void 0) return void 0;
2306
+ if (!metadata.presetEnabled) return false;
2307
+ return effectiveToolAction(snapshot.activeRule, name, {
2308
+ legacyCapabilities: snapshot.legacyCapabilities,
2309
+ codexTool: metadata
2310
+ }) !== "hide";
2311
+ },
2312
+ hasPromptOverride(scope, name) {
2313
+ return snapshots.get(scope)?.activePromptNames?.has(name) === true;
2314
+ }
2315
+ });
2316
+ const remove = (agent) => {
2317
+ const snapshot = snapshots.get(agent);
2318
+ if (snapshot !== void 0) {
2319
+ delete snapshot.activeRule;
2320
+ delete snapshot.activePromptNames;
2321
+ }
2322
+ const previous = overlays.get(agent);
2323
+ if (previous === void 0) return;
2324
+ overlays.delete(agent);
2325
+ previous.dispose();
2326
+ };
2327
+ const reconcile = (agent) => {
2328
+ const preset = ctx.agentPresets.composedPreset(agent.ctx) ?? ctx.agentPresets.presetForSession(agent.session) ?? void 0;
2329
+ if (overlays.get(agent)?.preset === preset) return;
2330
+ remove(agent);
2331
+ const snapshot = snapshots.get(agent);
2332
+ const defaultDeferred = readDefaultDeferredTools(agent.ctx, agent);
2333
+ const defaultHidden = readDefaultHiddenTools(agent.ctx, agent);
2334
+ const rule = preset === void 0 ? void 0 : snapshot?.rules.get(preset) ?? (defaultDeferred !== void 0 && defaultDeferred.size > 0 || defaultHidden !== void 0 && defaultHidden.size > 0 ? {
2335
+ preset,
2336
+ replaceShell: false,
2337
+ replacePlan: false,
2338
+ replacePatch: false
2339
+ } : void 0);
2340
+ if (rule === void 0 || snapshot === void 0) return;
2341
+ const prepared = snapshot.promptPlans.get(rule.preset);
2342
+ if (prepared instanceof Error) throw prepared;
2343
+ if ((rule.promptOverrides?.length ?? 0) > 0 && prepared === void 0) throw new Error("preset-prompt-plan-unavailable");
2344
+ let installed;
2345
+ const dispose = installOverlay(agent, rule, snapshot.legacyCapabilities, prepared, () => {
2346
+ if (installed !== void 0 && overlays.get(agent) === installed) {
2347
+ overlays.delete(agent);
2348
+ delete snapshot.activeRule;
2349
+ delete snapshot.activePromptNames;
2350
+ }
2351
+ });
2352
+ installed = {
2353
+ preset: rule.preset,
2354
+ dispose
2355
+ };
2356
+ overlays.set(agent, installed);
2357
+ snapshot.activeRule = rule;
2358
+ if (prepared !== void 0) snapshot.activePromptNames = new Set(prepared.sections.map((section) => section.name));
2359
+ };
2360
+ const isBlankSession = (agent) => {
2361
+ const boundary = ctx.agents.turnBoundaryOf(agent.session);
2362
+ return boundary.openTurnStartSeq === null && boundary.lastTurn === 0;
2363
+ };
2364
+ ctx.on("agent/created", ({ agent, signal }) => {
2365
+ if (!active) return;
2366
+ signal?.throwIfAborted();
2367
+ const snapshot = {
2368
+ rules: resolveRules(currentConfig()),
2369
+ legacyCapabilities: readLegacyCapabilities(ctx),
2370
+ promptPlans: /* @__PURE__ */ new Map()
2371
+ };
2372
+ snapshots.set(agent, snapshot);
2373
+ const targets = [...snapshot.rules.values()].filter((rule) => (rule.promptOverrides?.length ?? 0) > 0);
2374
+ if (targets.length === 0) {
2375
+ reconcile(agent);
2376
+ return;
2377
+ }
2378
+ const bound = ctx.agentPresets.composedPreset(agent.ctx) ?? ctx.agentPresets.presetForSession(agent.session);
2379
+ const activeTargets = isBlankSession(agent) ? targets : bound === void 0 ? [] : targets.filter((rule) => rule.preset === bound);
2380
+ if (activeTargets.length === 0) {
2381
+ reconcile(agent);
2382
+ return;
2383
+ }
2384
+ return (async () => {
2385
+ for (const rule of activeTargets) try {
2386
+ const probe = await probePresetPromptsCached(ctx, rule.preset, rule.preset === bound ? scopeParentOf(agent) : void 0);
2387
+ snapshot.promptPlans.set(rule.preset, preparePromptOverrides(probe, rule.promptOverrides));
2388
+ } catch (error) {
2389
+ snapshot.promptPlans.set(rule.preset, error instanceof Error ? error : new Error(String(error)));
2390
+ }
2391
+ signal?.throwIfAborted();
2392
+ if (active) reconcile(agent);
2393
+ })();
2394
+ });
2395
+ ctx.on("agent-preset/selected", (sessionId) => {
2396
+ if (!active) return;
2397
+ const agent = ctx.agents.get(sessionId);
2398
+ if (agent === void 0 || !snapshots.has(agent) || agent.status !== "idle") return;
2399
+ if (!isBlankSession(agent)) return;
2400
+ try {
2401
+ reconcile(agent);
2402
+ } catch (error) {
2403
+ ctx.logger.warn(`codex-tool-policy: preset selection overlay refused for ${agent.id}: ${String(error)}`);
2404
+ }
2405
+ });
2406
+ ctx.on("agent/disposed", ({ agent }) => {
2407
+ remove(agent);
2408
+ snapshots.delete(agent);
2409
+ });
2410
+ ctx.effect(() => () => {
2411
+ active = false;
2412
+ for (const agent of [...overlays.keys()].reverse()) remove(agent);
2413
+ }, "codex-tool-policy: Host overlay ownership");
2414
+ }
2415
+ var tool_policy_default = {
2416
+ name,
2417
+ inject,
2418
+ Config,
2419
+ apply
2420
+ };
2421
+ //#endregion
2422
+ export { Config, apply, tool_policy_default as default, inject, name };