dsh-taskbridge 0.0.0-stage → 1.3.2

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 (75) hide show
  1. package/CHANGELOG.md +763 -0
  2. package/LICENSE +21 -0
  3. package/README.md +622 -3
  4. package/bin/dsh-delegate-codex-agent.js +115 -0
  5. package/bin/dsh-delegate-control.d.ts +90 -0
  6. package/bin/dsh-delegate-control.js +450 -0
  7. package/bin/dsh-delegate-mcp.d.ts +121 -0
  8. package/bin/dsh-delegate-mcp.js +273 -0
  9. package/codex/dsh-taskbridge.toml +247 -0
  10. package/cordis.patch.yml +6 -0
  11. package/docs/INTRODUCTION.md +15 -0
  12. package/docs/INTRODUCTION.zh.md +34 -0
  13. package/docs/auth-contract.md +138 -0
  14. package/docs/claude-code.md +31 -0
  15. package/docs/codex-integration.md +937 -0
  16. package/docs/contracts-stage-b.md +443 -0
  17. package/docs/conversation-placement.md +304 -0
  18. package/docs/plugin-market.md +30 -0
  19. package/docs/redaction-contract.md +127 -0
  20. package/docs/runtime-compatibility.md +223 -0
  21. package/docs/silent-wait.md +191 -0
  22. package/docs/taskbridge-upgrade.md +28 -0
  23. package/docs/taskdispatch-upgrade.md +25 -0
  24. package/docs/worker-permissions.md +347 -0
  25. package/docs/workspace-contract.md +538 -0
  26. package/icon.svg +1 -0
  27. package/lib/client.d.ts +118 -0
  28. package/lib/client.js +3232 -0
  29. package/locale/en.json +7 -0
  30. package/locale/zh.json +7 -0
  31. package/package.json +138 -4
  32. package/src/auth/fence.js +361 -0
  33. package/src/auth/grants.js +789 -0
  34. package/src/client/api.js +2322 -0
  35. package/src/client/index.jsx +2333 -0
  36. package/src/client/styles.js +251 -0
  37. package/src/codex/installer.js +3299 -0
  38. package/src/codex/seam.js +429 -0
  39. package/src/codex/toml.js +784 -0
  40. package/src/config/defaults.js +164 -0
  41. package/src/config/redact.js +184 -0
  42. package/src/config/settings.js +629 -0
  43. package/src/config/store.js +186 -0
  44. package/src/config/validate.js +763 -0
  45. package/src/credentials/seam.js +202 -0
  46. package/src/http/execution-plane.js +456 -0
  47. package/src/http/respond.js +175 -0
  48. package/src/http/user-plane.js +1122 -0
  49. package/src/index.d.ts +332 -0
  50. package/src/index.js +657 -0
  51. package/src/jobs/activity.js +1008 -0
  52. package/src/jobs/engine.js +3614 -0
  53. package/src/jobs/history.js +1467 -0
  54. package/src/jobs/title.js +17 -0
  55. package/src/mcp/server.js +1821 -0
  56. package/src/mcp/wait.js +536 -0
  57. package/src/model/connectivity.js +371 -0
  58. package/src/model/discovery.js +582 -0
  59. package/src/model/native-catalog.js +68 -0
  60. package/src/model/openai-adapter.js +671 -0
  61. package/src/model/probe.js +264 -0
  62. package/src/model/providers.js +756 -0
  63. package/src/model/routing.js +321 -0
  64. package/src/review/preset.js +868 -0
  65. package/src/review/prompts.js +126 -0
  66. package/src/review/reviewer.js +933 -0
  67. package/src/runtime/agent-runner.js +1740 -0
  68. package/src/runtime/endpoint-discovery.js +118 -0
  69. package/src/runtime/permissions.js +1429 -0
  70. package/src/runtime/sandbox.js +358 -0
  71. package/src/runtime/session-placement.js +1121 -0
  72. package/src/workspace/audit.js +775 -0
  73. package/src/workspace/locks.js +167 -0
  74. package/src/workspace/preflight.js +424 -0
  75. package/src/workspace/worktrees.js +613 -0
@@ -0,0 +1,3299 @@
1
+ // Codex integration: install the companion custom agent and register this
2
+ // package's stdio MCP server in Codex.
3
+ //
4
+ // Scope, stated once and enforced below
5
+ // -------------------------------------
6
+ // This module owns exactly two things in a Codex home:
7
+ //
8
+ // 1. `$CODEX_HOME/agents/dsh-taskbridge.toml` — a *managed copy* of the shipped
9
+ // template `codex/dsh-taskbridge.toml`. Ownership is proved by content, never by
10
+ // the file name or a version line alone:
11
+ // * a file that is byte-identical to the template this build would write is
12
+ // `installed` (and removable);
13
+ // * a file that matches one of the *known prior shipped templates* in
14
+ // {@link KNOWN_AGENT_TEMPLATES} byte for byte is `outdated` (refreshable and
15
+ // removable) — a conservative, enumerated list, not a heuristic;
16
+ // * anything else is `modified`/`conflict`: never overwritten, never removed.
17
+ // A first install is *exclusive* (`wx`), so a file that appears between the
18
+ // status read and the write is reported as a conflict instead of replaced.
19
+ // 2. the `mcp_servers.dsh-delegate` table in `$CODEX_HOME/config.toml`, and only
20
+ // when it carries the plugin's marker comment AND the single stdio command
21
+ // this plugin writes (`command = "<node>"`,
22
+ // `args = ["<installed>/bin/dsh-delegate-mcp.js"]`). An unmarked same-name
23
+ // entry is the operator's — even when its values happen to be identical — and
24
+ // is reported as a conflict and left byte-identical. Any other difference
25
+ // (another command, an added `env` key, a `url`, extra arguments) is a
26
+ // conflict too, except for the narrow migration of the old Desktop GUI
27
+ // command documented by `isLegacyDesktopCommand` below.
28
+ //
29
+ // Every other byte of `config.toml` is preserved verbatim, including comments,
30
+ // table order and CRLF line endings (see `src/codex/toml.js`). Nothing here writes on
31
+ // package install: install/repair/remove are operator actions reached through the
32
+ // settings page, and `status` only reads.
33
+ //
34
+ // What CAN write without a click is {@link refreshKnownAgentTemplate}, which plugin
35
+ // startup calls as the installed-integration check. It has two halves and neither is an
36
+ // install:
37
+ //
38
+ // * the agent file, when its complete bytes still match a published template;
39
+ // * an ALREADY INSTALLED `mcp_servers.dsh-delegate` entry that this plugin can prove it
40
+ // wrote (marker + its own Node command + THIS installation's exact entry script) and
41
+ // that is merely stale — a missing `tool_timeout_sec`. A recorded script path that
42
+ // names a DIFFERENT location is never upgraded here: only an explicit install/repair
43
+ // may adopt it, after the filesystem package-identity proof. The write is gated by
44
+ // {@link isOwnedStaleEntry}, re-proved against the exact config digest the plan was
45
+ // made from, and preceded by a backup copy whose whole ancestor chain is proved.
46
+ //
47
+ // It never creates a missing agent or a missing MCP entry, and never rewrites anything
48
+ // it cannot prove is its own.
49
+ //
50
+ // The write sets do not overlap by accident: `install` writes both targets, `repair`
51
+ // writes the MCP entry and nothing else (never creating, refreshing or deleting the
52
+ // agent file), and `remove` deletes only what it can still prove is its own.
53
+ //
54
+ // Where those paths may physically lead
55
+ // -------------------------------------
56
+ // The Codex home itself, and the `agents` directory below it, are boundaries and not
57
+ // just path strings: `lstat` on the final file would happily report "missing" while
58
+ // `mkdir`/`open` walked through a directory junction to a directory somewhere else.
59
+ // Both are therefore inspected without following the link (`lstat`, and a native
60
+ // reparse-point check for the Windows junction `lstat` reports as an ordinary
61
+ // directory), and a link at either one is a stable `conflict` diagnosis that
62
+ // install, repair and remove all refuse. A node_modules-style real directory — the
63
+ // normal case — is unaffected.
64
+ //
65
+ // Removal re-proves ownership at the last moment: the file is read again immediately
66
+ // before it is unlinked and has to be a regular file whose bytes are still exactly
67
+ // the managed content the status read reported, so a file rewritten in between is
68
+ // kept and reported instead of deleted.
69
+ //
70
+ // What it deliberately does NOT do
71
+ // --------------------------------
72
+ // It does not enable the DSH local-call switch, does not edit unrelated Codex
73
+ // settings, and claims no `@`-selection capability for any Codex surface: the agent
74
+ // file's instructions describe the exact dispatch conditions, and the status notes
75
+ // say what the file can and cannot guarantee.
76
+
77
+ import { lstatSync } from 'node:fs';
78
+ import { link, lstat, mkdir, open, readFile, readlink, realpath, stat, unlink } from 'node:fs/promises';
79
+ import { execFile } from 'node:child_process';
80
+ import { createHash, randomBytes } from 'node:crypto';
81
+ import { homedir } from 'node:os';
82
+ import { basename, delimiter, dirname, isAbsolute, join, parse, resolve, sep } from 'node:path';
83
+ import { fileURLToPath } from 'node:url';
84
+
85
+ import { writeFileAtomic } from '../config/store.js';
86
+ import {
87
+ TomlDocument,
88
+ TomlSyntaxError,
89
+ renderKey,
90
+ renderString,
91
+ renderStringArray,
92
+ samePath,
93
+ tomlValueType,
94
+ } from './toml.js';
95
+
96
+ /** Agent file name inside `$CODEX_HOME/agents`. */
97
+ export const AGENT_FILENAME = 'dsh-taskbridge.toml';
98
+ export const LEGACY_AGENT_FILENAME = 'dsh-delegate.toml';
99
+
100
+ /** MCP server entry name inside Codex's `mcp_servers` table. */
101
+ export const MCP_SERVER_NAME = 'dsh-delegate';
102
+
103
+ /** Marker line written above the MCP entry so an operator can find it later. */
104
+ export const MCP_MARKER = '# dsh-delegate: managed by the DSH Delegate plugin settings page';
105
+
106
+ /** Actions the status/action route accepts. */
107
+ export const CODEX_ACTIONS = Object.freeze(['status', 'install', 'repair', 'remove']);
108
+
109
+ /**
110
+ * The exact agent files shipped by earlier releases, as SHA-256 digests of the file
111
+ * *as written* (template with the version marker stamped).
112
+ *
113
+ * This list, not a heuristic, is what makes `outdated` mean "a build this plugin
114
+ * really published". A file that is not byte-identical to one of these is somebody
115
+ * else's file, even if it still carries the managed header and an old version line.
116
+ * Regenerating a digest is a deliberate act: add the entry for a release only after
117
+ * that release has been packed and its agent file verified.
118
+ *
119
+ * The 0.1.6, both 0.1.7 builds, the 0.1.8 and 0.1.9 builds, the published 0.1.10
120
+ * template (in both its packed CRLF and its LF byte form), the published 0.1.11
121
+ * template and the published 0.1.12 template are enumerated here because they are
122
+ * published Codex agent builds. A file that is not byte-identical to one of these
123
+ * releases or the current template is reported as `modified`, rather than guessed as
124
+ * ours.
125
+ * The array is intentionally mutable (not frozen) so a test can pin a temporary
126
+ * entry and prove the "known build is refreshable" path without shipping a fake
127
+ * historical release in the product data.
128
+ * @type {Array<{ version: string, sha256: string }>}
129
+ */
130
+ export const KNOWN_AGENT_TEMPLATES = [
131
+ { version: '1.3.1', sha256: '2793b656be4a1906e16edfdd0103540bfad05681a413c166b578b02333ea2618' },
132
+ { version: '1.3.1', sha256: 'b48558d6d6acca58b94a01029d6c884c4789488c7926cdaca40cb6cd15eea2ae' },
133
+ {
134
+ version: '0.1.6',
135
+ sha256: '6a9d0da5b32d62a2a1f61d1fba37d54789cde0774afb3abccb5dc12b400c82be',
136
+ },
137
+ {
138
+ version: '0.1.7',
139
+ sha256: '3b5a58df0f989e87ae160a2952b7699cd5e2978e43a0f9a86c4eceb155d7af92',
140
+ },
141
+ {
142
+ version: '0.1.7',
143
+ sha256: '75ec5f97452754ba22747680598583b8ab457f64a0a3d487b96d73b3a3cc35c7',
144
+ },
145
+ {
146
+ version: '0.1.8',
147
+ sha256: '56f1cb8ac6460c590e27e3bf44144174dadb09dfd3f904aa9b5ee2a805ae1c4e',
148
+ },
149
+ {
150
+ version: '0.1.9',
151
+ sha256: '3aa3a2e3a621584ebe002d6a7469ce56c85a899f12d63c26d782f02a47d4d4ca',
152
+ },
153
+ // Rebuilds of the 0.1.10–0.1.13 companion body at the older version markers. That
154
+ // release line changed its instructions more than once (the per-task conversation
155
+ // policy, the source-path policy), so a file this plugin published at those markers
156
+ // hashes to these exact bytes. The CURRENT template is a different body (0.1.14
157
+ // changed it), so these digests are fixed published identities rather than something
158
+ // rebuilt from today's file; without them a published installation would be reported
159
+ // `modified` — "somebody else's file" — and never refreshed.
160
+ {
161
+ version: '0.1.7',
162
+ sha256: 'e3689492ee0f24d2defd2a9254b653e7bc54c258dd38fb0c2fc70ce5b386f2b3',
163
+ },
164
+ {
165
+ version: '0.1.8',
166
+ sha256: '5cd02783d0fd5b1ffe5375e5d0e1b009931163e6f4fa87de9ea3c9c399fcd40e',
167
+ },
168
+ {
169
+ version: '0.1.9',
170
+ sha256: 'b5db667d114baf881f59c9367a80137379960b1fccb524c883ab0edcf9f0d516',
171
+ },
172
+ // The published 0.1.10 template. That release shipped the older companion body, and
173
+ // within 0.1.10–0.1.13 the only difference between builds is the version line. That
174
+ // line is still part of the bytes an operator's file is proved against, so the digest
175
+ // is distinct and has to be enumerated on its own: without it, a 0.1.10 install is
176
+ // reported `modified` and is never refreshed by startup migration.
177
+ //
178
+ // Both digests below are enumerated for 0.1.10, because the release exists in two
179
+ // byte forms and either one can be sitting on an operator's disk:
180
+ //
181
+ // * `fc7b2710…` — the packed `dsh-delegate-0.1.10.tgz`, whose
182
+ // `package/codex/dsh-delegate.toml` carries CRLF line endings (the form a Windows
183
+ // install writes).
184
+ // * `6583f08a…` — the same template with LF line endings. It is an exact byte
185
+ // identity like the other, not a normalized comparison: the product hashes the
186
+ // file it finds and never rewrites its line endings, so an LF checkout of that
187
+ // release stays a recognized build.
188
+ //
189
+ // Neither digest is derived from the other: normalization is a defect, not a
190
+ // convenience, because it would also make an edited file hash to a known value.
191
+ {
192
+ version: '0.1.10',
193
+ sha256: 'fc7b27104dbb50f4e614cd4fd8df8db87fd8f59fcf2b3c27b412b49f8b89fbba',
194
+ },
195
+ {
196
+ version: '0.1.10',
197
+ sha256: '6583f08a3ec4912a875249e6b127357b41cc3f8bf388b8e5cadbbeff469349be',
198
+ },
199
+ // The published 0.1.11 template: the bytes of the immediately previous release,
200
+ // which is what an existing installation holds when this build starts. Its body is
201
+ // the same as the 0.1.10 body (0.1.11 changed `package.json`, the permissions
202
+ // contract and the runtime facts, not the companion instructions), so the only
203
+ // difference from the 0.1.10 entry is the stamped version line — and a version
204
+ // line is part of the bytes an operator's file is proved against, so this digest
205
+ // is distinct and has to be enumerated on its own. Without it a 0.1.11
206
+ // installation is reported `modified` ("somebody else's file") and neither startup
207
+ // migration nor an explicit install would ever refresh it.
208
+ {
209
+ version: '0.1.11',
210
+ sha256: 'b6ca7c3258fc00c1c1682abf099994b9f5abe650acc3ecf9635eec4a35520151',
211
+ },
212
+ // The published 0.1.12 template: the file the immediately previous release packed,
213
+ // which is what an existing installation holds when this build starts. It was
214
+ // verified byte for byte against the packed `dsh-delegate-0.1.12.tgz`
215
+ // (`package/codex/dsh-delegate.toml`) and against the saved release baseline, so
216
+ // the digest is an exact identity rather than a reconstruction. Without this entry
217
+ // a 0.1.12 installation is reported `modified` — "somebody else's file" — and
218
+ // neither startup migration nor an explicit install would ever refresh it.
219
+ {
220
+ version: '0.1.12',
221
+ sha256: 'ff04a4bf2c09b97747f835770c837637869581bb13bad3b8a870a3e92218514f',
222
+ },
223
+ // The published 0.1.13 template: the file the immediately previous release packed,
224
+ // which is what an existing installation holds when this build starts. Verified byte
225
+ // for byte against the packed `dsh-delegate-0.1.13.tgz`
226
+ // (`package/codex/dsh-delegate.toml`): 9191 bytes, CRLF, this exact digest. It is an
227
+ // exact content identity like every other entry here, never a heuristic match on the
228
+ // version line — an operator-edited file whose version line still says 0.1.13 hashes
229
+ // differently and stays `modified` (preserved, never refreshed). Without this entry a
230
+ // 0.1.13 installation is reported `modified` — "somebody else's file" — and neither
231
+ // startup migration nor an explicit install would ever refresh it.
232
+ {
233
+ version: '0.1.13',
234
+ sha256: 'b3a1d2f0520774c0067ea733f27fd47c67c5f5ac44394d0eec2564c7959700aa',
235
+ },
236
+ // The published 0.1.14 template. Version 1.0.0 keeps the same companion body
237
+ // while changing the release marker, so an unchanged 0.1.14 installation must
238
+ // remain a byte-proven managed file and migrate automatically.
239
+ {
240
+ version: '0.1.14',
241
+ sha256: '11379c0152f3fb2bd4da1170812e51fe68006d98f6378c720cbadcee9ee4750c',
242
+ },
243
+ // The published 1.0.0 companion — the body an existing 1.0.0 installation holds
244
+ // when 1.1.0 starts. 1.1.0 replaced the repeat-result polling rules with
245
+ // `delegate_wait` and added the explicit "do not implement locally" boundary, so
246
+ // the instruction bytes changed and this is a DISTINCT published build that has to
247
+ // be enumerated: without it, every 1.0.0 installation would be reported `modified`
248
+ // ("somebody else's file") and the settings-page update button would refuse to
249
+ // refresh a file this plugin really published.
250
+ //
251
+ // The digest is the exact 1.0.0 stamped bytes, taken from the release itself:
252
+ // `git show 2750047:codex/dsh-delegate.toml` (the 1.0.0 commit) is byte-for-byte the
253
+ // file that release shipped, it is preserved as `tests/fixtures/codex-agent-1.0.0.toml`,
254
+ // and the test hashes that fixture rather than anything reconstructed.
255
+ {
256
+ version: '1.0.0',
257
+ sha256: 'b1fd531598087564b26df14d3261515e961012f3fd010ea493f222da7bbaf415',
258
+ },
259
+ // The same 1.0.0 body with LF line endings. It is an exact identity, not a
260
+ // normalized comparison: an operator who installed from an LF checkout holds these
261
+ // bytes, and the installer never rewrites line endings. Normalizing would also make
262
+ // an edited file hash to a known value, which is the defect these digests exist to
263
+ // prevent.
264
+ {
265
+ version: '1.0.0',
266
+ sha256: '0cce75574107049413f4ddbdf7d8e6cddea92d45a0c4e0fa41b169cb790e5e13',
267
+ },
268
+ // Two LEGACY pinned identities for 1.0.0 that an earlier build of this plugin shipped.
269
+ //
270
+ // Their provenance is deliberately NOT claimed to be the Git release bytes: the fixture
271
+ // above is what `git show 2750047:codex/dsh-delegate.toml` contains, and these two
272
+ // digests do not match it. They are retained because a released build enumerated them,
273
+ // so an installation created by that build must stay structurally refreshable instead of
274
+ // flipping to "somebody else's file" — and they are labelled `legacy` so nothing here
275
+ // pretends they are a Git-verified archive identity.
276
+ //
277
+ // Keeping them is the conservative choice: an unrecognised file is never adopted and
278
+ // never removable, while a stale file that this plugin once wrote should still be
279
+ // refreshable by an explicit install. The digests are exact content identities like
280
+ // every other entry, so an operator edit still fails to match.
281
+ {
282
+ version: '1.0.0',
283
+ sha256: 'a8c888afaa0a1a6a0abfcb56670ffbdb67697f07e54871ece78c8adffb15c149',
284
+ legacy: true,
285
+ },
286
+ {
287
+ version: '1.0.0',
288
+ sha256: 'f51831e2ff265c9ba63a4760e245787060de7bd91dcc9663a11729fb472e5f62',
289
+ legacy: true,
290
+ },
291
+ // The published 1.1.0 companion — the file an existing 1.1.0 installation holds when
292
+ // 1.2.0 starts. 1.2.0 changed the instruction body (the `interrupted` distinction and
293
+ // the independent control channel), so this is a DISTINCT published build that has to
294
+ // be enumerated: without it every 1.1.0 installation would be reported `modified`
295
+ // ("somebody else's file") and neither startup migration nor an explicit install
296
+ // could refresh bytes this plugin really published.
297
+ //
298
+ // Both byte forms are enumerated, exactly like 0.1.10 and 1.0.0. The bytes come from
299
+ // `git show 2d71708:codex/dsh-delegate.toml` (the 1.1.0 commit), preserved as
300
+ // `tests/fixtures/codex-agent-1.1.0.toml`: CRLF (`7d3ea5c5…`, the form a Windows
301
+ // install writes) and the same template kept as LF text (`93d580bd…`). Each is an
302
+ // exact content identity, never a normalized comparison.
303
+ {
304
+ version: '1.1.0',
305
+ sha256: '7d3ea5c54647a92cebaa0521741eb27f5141f7b2127b47009195fdb976dae4fb',
306
+ },
307
+ {
308
+ version: '1.1.0',
309
+ sha256: '93d580bd849bb6d2c30c2db6286695ef3e0356896a88e552abae5f03eafc7601',
310
+ },
311
+ // Exact published 1.3.0 bytes (archive fixture, LF and CRLF forms).
312
+ { version: '1.3.0', sha256: '63695008f53aa2c19a0df9e2cb37285f631b775cb98f26c1d280cfbc54a0d9e8' },
313
+ { version: '1.3.0', sha256: '31b0ba3149032058fe31e1e884e5c24a9a3d6459b7dd35df6420c7f3756d6257' },
314
+ // Exact published 1.2.0 bytes (archive fixture, LF and CRLF forms).
315
+ { version: '1.2.0', sha256: '8479c8ab418d71b15fb30880aa5149fb1070d194e8444a110a2a614cebf4eaf4' },
316
+ { version: '1.2.0', sha256: '947f3fb8a8e9ae5cc6fb3c9d379c69b595af4c46f89ac77f69aa1edf696a8f8e' },
317
+ ];
318
+
319
+ /** The `version = "…"` line of an agent file, at column 0. */
320
+ const VERSION_LINE = /^version[ \t]*=[ \t]*"([^"]*)"\r?$/mu;
321
+
322
+ /** Stable states reported for the agent file. */
323
+ export const AGENT_STATES = Object.freeze({
324
+ missing: 'not-installed',
325
+ installed: 'installed',
326
+ outdated: 'outdated',
327
+ modified: 'modified',
328
+ conflict: 'conflict',
329
+ });
330
+
331
+ /** Stable states reported for the MCP entry. */
332
+ export const MCP_STATES = Object.freeze({
333
+ missing: 'not-configured',
334
+ configured: 'configured',
335
+ outdated: 'outdated',
336
+ conflict: 'conflict',
337
+ unreadable: 'unreadable',
338
+ });
339
+
340
+ /** How this package is executed (mirrors `bin` in package.json). */
341
+ export const MCP_ENTRY_RELATIVE = join('bin', 'dsh-delegate-mcp.js');
342
+
343
+ /**
344
+ * The `package.json` `bin` key that must map to {@link MCP_ENTRY_RELATIVE}.
345
+ *
346
+ * A manifest that merely declares this package's `name` is not enough: the package
347
+ * could still point its bin entry somewhere else. The moved-install proof therefore
348
+ * requires the manifest to map THIS key to the very entry file being adopted.
349
+ */
350
+ const MCP_BIN_NAME = 'dsh-delegate-mcp';
351
+
352
+ /**
353
+ * The one environment variable this plugin may write on its own MCP entry.
354
+ *
355
+ * It pins the discovery file when DSH runs with a non-default `DSH_HOME`, and it is
356
+ * owned exactly like `tool_timeout_sec`: a managed entry carrying a different value is
357
+ * stale, never foreign.
358
+ */
359
+ export const DISCOVERY_ENV_VAR = 'DSH_DELEGATE_DISCOVERY_FILE';
360
+
361
+ /**
362
+ * States in which an MCP definition may be written: absent, already ours, or a stale
363
+ * copy of ours. Anything else — including an unmarked same-name entry — is refused.
364
+ */
365
+ const MANAGEABLE_MCP_STATES = new Set([MCP_STATES.missing, MCP_STATES.configured, MCP_STATES.outdated]);
366
+ const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..');
367
+
368
+ /**
369
+ * This package's own name, the identity an older installation's `package.json` must
370
+ * declare before its entry point can be adopted by an automatic migration.
371
+ */
372
+ const PACKAGE_NAME = 'dsh-taskbridge';
373
+ const TEMPLATE_PATH = join(PACKAGE_ROOT, 'codex', AGENT_FILENAME);
374
+ const PACKAGE_MANIFEST_PATH = join(PACKAGE_ROOT, 'package.json');
375
+
376
+ /** Bound on a Codex config document this module is willing to edit. */
377
+ const MAX_CONFIG_BYTES = 1024 * 1024;
378
+
379
+ /**
380
+ * Refusal raised by the installer. Carries a stable code so the settings page can
381
+ * explain *why* rather than only *that* something failed.
382
+ */
383
+ export class CodexInstallError extends Error {
384
+ /**
385
+ * @param {string} code - stable machine code.
386
+ * @param {string} message - explanation, already free of secrets.
387
+ * @param {object} [details] - bounded details.
388
+ */
389
+ constructor(code, message, details = {}) {
390
+ super(message);
391
+ this.name = 'CodexInstallError';
392
+ this.code = code;
393
+ this.details = details;
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Resolve the Codex home.
399
+ *
400
+ * `CODEX_HOME` wins when set (Codex's own precedence), otherwise `~/.codex`. A
401
+ * relative override is refused rather than resolved against the DSH working
402
+ * directory, which would write a Codex file into the harness's cwd.
403
+ * @param {object} [options] - `env`, `homeDirectory`.
404
+ * @returns {string} absolute Codex home directory.
405
+ * @throws {CodexInstallError} `CODEX_HOME_INVALID` for a relative override.
406
+ */
407
+ export function resolveCodexHome({ env = process.env, homeDirectory = homedir() } = {}) {
408
+ const configured = typeof env.CODEX_HOME === 'string' ? env.CODEX_HOME.trim() : '';
409
+ if (configured === '') return resolve(join(homeDirectory, '.codex'));
410
+ if (!isAbsolute(configured)) {
411
+ throw new CodexInstallError('CODEX_HOME_INVALID', 'CODEX_HOME must be an absolute path');
412
+ }
413
+ return resolve(configured);
414
+ }
415
+
416
+ /**
417
+ * Normalize an explicit Codex home, refusing a relative one.
418
+ *
419
+ * An explicit path may come from a caller rather than the environment (the seam
420
+ * resolves `CODEX_HOME` for the settings page), and resolving a relative path
421
+ * against the harness's working directory would report on, or write to, a
422
+ * directory the operator never named.
423
+ * @param {string} codexHome - caller-supplied absolute path.
424
+ * @returns {string} absolute path.
425
+ * @throws {CodexInstallError} `CODEX_HOME_INVALID`.
426
+ */
427
+ export function requireCodexHome(codexHome) {
428
+ if (typeof codexHome !== 'string' || codexHome.trim() === '' || !isAbsolute(codexHome)) {
429
+ throw new CodexInstallError('CODEX_HOME_INVALID', 'the Codex home must be an absolute path');
430
+ }
431
+ return resolve(codexHome);
432
+ }
433
+
434
+ /**
435
+ * Read the shipped agent template.
436
+ * @returns {Promise<string>} template text exactly as published.
437
+ */
438
+ export async function readAgentTemplate() {
439
+ return await readFile(TEMPLATE_PATH, 'utf8');
440
+ }
441
+
442
+ /**
443
+ * Read this package's version from its own manifest.
444
+ * @returns {Promise<string>} version string, or `''` when the manifest is unreadable.
445
+ */
446
+ async function readPackageVersion() {
447
+ try {
448
+ const manifest = JSON.parse(await readFile(PACKAGE_MANIFEST_PATH, 'utf8'));
449
+ return typeof manifest.version === 'string' ? manifest.version : '';
450
+ } catch {
451
+ return '';
452
+ }
453
+ }
454
+
455
+ /**
456
+ * Read this package's version, requiring that it is reachable.
457
+ * @returns {Promise<string>} version string.
458
+ */
459
+ export async function packageVersion() {
460
+ return await readPackageVersion();
461
+ }
462
+
463
+ /** Environment overrides that may name the Node.js used for the MCP server. */
464
+ export const MCP_NODE_ENV_VARS = Object.freeze(['DSH_NODE_PATH', 'DSH_NODE_EXECUTABLE', 'CODEX_MCP_NODE_PATH']);
465
+
466
+ /**
467
+ * The Node.js runtime bundled inside a DSH Desktop installation, per platform.
468
+ *
469
+ * DSH Desktop ships its own Node below `<resources>/runtime/primary-runtime/
470
+ * dependencies/node`; the executable is that directory's `bin/node` (`bin/node.exe`
471
+ * on Windows). This is the one runtime a Codex-spawned MCP server may rely on, so
472
+ * it is named in exactly one place.
473
+ * @param {string} resourcesRoot - the Electron `resources` directory.
474
+ * @returns {string} absolute path of the bundled `node`/`node.exe` (existence unchecked).
475
+ */
476
+ export function packagedNodePath(resourcesRoot) {
477
+ return join(
478
+ resolve(resourcesRoot),
479
+ 'runtime',
480
+ 'primary-runtime',
481
+ 'dependencies',
482
+ 'node',
483
+ 'bin',
484
+ process.platform === 'win32' ? 'node.exe' : 'node',
485
+ );
486
+ }
487
+
488
+ /**
489
+ * Is this the Node.js binary itself, rather than the application that embeds it?
490
+ *
491
+ * A packaged Electron application sets `process.execPath` to *its own* executable
492
+ * (`DeepSeek Harness.exe` on Windows, `DeepSeek Harness` on macOS), not to a Node
493
+ * binary. Writing that path into Codex's `config.toml` produces an MCP server that
494
+ * starts the GUI instead of the server, which is the defect this check exists to
495
+ * prevent: the basename test is the last line of defence for hosts that expose no
496
+ * usable Electron signal.
497
+ * @param {string} value - executable path.
498
+ * @returns {boolean} true for `node`, `node.exe` and versioned Node binaries.
499
+ */
500
+ export function isNodeExecutableName(value) {
501
+ // `path.basename` follows the host platform. Config files can contain Windows
502
+ // paths even when the installer is tested or inspected on another platform, so
503
+ // strip both separator spellings before checking the executable name.
504
+ const name = String(value ?? '').replace(/^.*[\\/]/u, '').toLowerCase();
505
+ return name === 'node' || name === 'node.exe' || /^node(?:-[0-9][^/\\]*)?\.exe$/u.test(name);
506
+ }
507
+
508
+ /**
509
+ * How this plugin is hosted: a plain Node.js process, or an application that embeds
510
+ * Electron and therefore has a different executable than its Node runtime.
511
+ *
512
+ * `process.versions.electron` is the authoritative Electron signal. The other two
513
+ * are equivalent, weaker host signals that a desktop wrapper may expose instead:
514
+ * `process.resourcesPath` is installed by Electron's main process, and `electron`
515
+ * in `process.versions` is never present in a plain Node.js process.
516
+ * @param {object} [host] - `versions` and `resourcesPath` of the running host.
517
+ * @returns {'electron' | 'node'} host kind.
518
+ */
519
+ export function hostRuntimeKind({ versions = process.versions, resourcesPath = process.resourcesPath } = {}) {
520
+ const electron = typeof versions?.electron === 'string' ? versions.electron.trim() : '';
521
+ if (electron !== '') return 'electron';
522
+ // A plain Node.js process never sets `resourcesPath`; a packaged Electron app
523
+ // always does. Treating it as a host signal is what makes the resolution work in a
524
+ // desktop build whose `process.versions` was trimmed.
525
+ if (typeof resourcesPath === 'string' && resourcesPath.trim() !== '') return 'electron';
526
+ return 'node';
527
+ }
528
+
529
+ /**
530
+ * The executable used to run the MCP server — never the GUI, never a bare `node`.
531
+ *
532
+ * The value is pinned (an absolute path) because Codex is often launched from a GUI
533
+ * whose `PATH` is much narrower than the shell that started DSH, where a bare `node`
534
+ * fails at spawn time. What is pinned depends on the host:
535
+ *
536
+ * * **A plain Node.js process** keeps `process.execPath`: that *is* the Node that
537
+ * loaded this package, and it is the exact runtime this plugin runs on.
538
+ * * **An Electron/desktop host** (`process.versions.electron`, or an equivalent
539
+ * signal such as `process.resourcesPath`) must *not* use `process.execPath`:
540
+ * there it is the application (`DeepSeek Harness.exe`), and Codex would start a
541
+ * second GUI instead of an MCP server. The DSH packaged runtime
542
+ * `<resources>/runtime/primary-runtime/dependencies/node/bin/node[.exe]` is
543
+ * selected instead — from `process.resourcesPath` when the host exposes it, and
544
+ * otherwise derived from the application executable's directory.
545
+ *
546
+ * A `DSH_NODE_PATH`, `DSH_NODE_EXECUTABLE` or `CODEX_MCP_NODE_PATH` override is
547
+ * accepted only as an **absolute** path to an existing **regular file**; a relative
548
+ * value, a directory, a link or a missing file is ignored (the packaged runtime keeps
549
+ * precedence, and the ordered list below chooses). When nothing qualifies the
550
+ * function fails closed with `MCP_EXECUTABLE_UNRESOLVED`: an entry that names
551
+ * something unlaunchable must never be written, and no diagnosis may substitute a
552
+ * path that merely looks plausible.
553
+ * @param {object} [options] - `env`, `execPath`, `resourcesPath`, `versions`, `platform`.
554
+ * @returns {string} absolute path of a Node.js executable that exists.
555
+ * @throws {CodexInstallError} `MCP_EXECUTABLE_UNRESOLVED` when none can be proved.
556
+ */
557
+ export function resolveNodeExecutable({
558
+ env = process.env,
559
+ execPath = process.execPath,
560
+ resourcesPath = process.resourcesPath,
561
+ versions = process.versions,
562
+ platform = process.platform,
563
+ } = {}) {
564
+ const isWindows = platform === 'win32';
565
+ const executablePath = typeof execPath === 'string' && execPath.trim() !== '' && isAbsolute(execPath)
566
+ ? resolve(execPath)
567
+ : '';
568
+
569
+ /**
570
+ * Inspect a candidate without following a link.
571
+ *
572
+ * `lstat` is used deliberately: a link is reported as a link (and therefore
573
+ * rejected) rather than as the file it points at, so the written command names a
574
+ * file this process can prove still is one.
575
+ * @param {string} value - candidate path.
576
+ * @returns {{ path: string } | { reason: string }} usable file, or why not.
577
+ */
578
+ const inspect = (value) => {
579
+ if (typeof value !== 'string' || value.trim() === '') return { reason: 'unset' };
580
+ if (!isAbsolute(value)) return { reason: 'not-absolute' };
581
+ const candidate = resolve(value);
582
+ if (isNodeExecutableName(candidate) === false) return { reason: 'not-a-node-binary' };
583
+ try {
584
+ const info = lstatSync(candidate);
585
+ if (info.isSymbolicLink()) return { reason: 'link' };
586
+ if (!info.isFile()) return { reason: 'not-a-regular-file' };
587
+ } catch {
588
+ return { reason: 'missing' };
589
+ }
590
+ return { path: candidate };
591
+ };
592
+
593
+ const kind = hostRuntimeKind({ versions, resourcesPath });
594
+
595
+ // A plain Node.js host: the runtime that loaded this package is the answer.
596
+ if (kind === 'node' && executablePath !== '' && isNodeExecutableName(executablePath)) {
597
+ const direct = inspect(executablePath);
598
+ if ('path' in direct) return direct.path;
599
+ }
600
+
601
+ // Everything below is the desktop/Electron path (or a plain-Node process whose
602
+ // `execPath` is not a Node binary — an embedded host that forgot to say so).
603
+ const resourceRoots = [];
604
+ const addRoot = (value) => {
605
+ if (typeof value !== 'string' || value.trim() === '' || !isAbsolute(value)) return;
606
+ const root = resolve(value);
607
+ if (!resourceRoots.includes(root)) resourceRoots.push(root);
608
+ };
609
+ addRoot(resourcesPath);
610
+ // The derived root handles a desktop host that exposes only its own executable:
611
+ // `<install>/resources` sits beside `<install>/DeepSeek Harness.exe`.
612
+ if (executablePath !== '') addRoot(join(dirname(executablePath), 'resources'));
613
+
614
+ /** Every rejected candidate, kept for a diagnosis that names real reasons. */
615
+ const rejected = [];
616
+ for (const root of resourceRoots) {
617
+ const candidate = packagedNodePath(root);
618
+ const verdict = inspect(candidate);
619
+ if ('path' in verdict) return verdict.path;
620
+ rejected.push({ source: 'packaged-runtime', path: candidate, reason: verdict.reason });
621
+ }
622
+
623
+ // Explicit operator/host overrides, in a fixed precedence so two set variables
624
+ // cannot make the answer depend on object key order.
625
+ for (const key of MCP_NODE_ENV_VARS) {
626
+ const candidate = env?.[key];
627
+ const verdict = inspect(candidate);
628
+ if ('path' in verdict) return verdict.path;
629
+ if (verdict.reason === 'unset') continue;
630
+ rejected.push({
631
+ source: key,
632
+ // The rejected value is echoed only as the configured (possibly secret-free)
633
+ // path string; it is a filesystem path, never a credential.
634
+ path: typeof candidate === 'string' && isAbsolute(candidate) ? resolve(candidate) : null,
635
+ reason: verdict.reason,
636
+ });
637
+ }
638
+
639
+ // Fail closed. The message states what is wrong and what would fix it; the details
640
+ // carry only path/reason pairs, so the settings page can explain the refusal
641
+ // without re-deriving it.
642
+ const tried = rejected.map((entry) => {
643
+ const value = entry.path === null ? '' : ` (${entry.path})`;
644
+ return `${entry.source}${value}: ${entry.reason}`;
645
+ });
646
+ throw new CodexInstallError(
647
+ 'MCP_EXECUTABLE_UNRESOLVED',
648
+ `no Node.js executable could be proved for the Codex MCP command; the desktop application executable is never used. `
649
+ + `Set ${MCP_NODE_ENV_VARS[0]} to the absolute path of a node executable. `
650
+ + (tried.length === 0 ? 'No candidate was available to check.' : `Rejected: ${tried.join('; ')}.`),
651
+ {
652
+ host: kind,
653
+ execPath: executablePath === '' ? null : executablePath,
654
+ resourceRoots,
655
+ rejected,
656
+ envVars: [...MCP_NODE_ENV_VARS],
657
+ },
658
+ );
659
+ }
660
+
661
+ /**
662
+ * Classify one file we may need to write.
663
+ *
664
+ * A symlink is a conflict rather than a target: following one would write outside
665
+ * the Codex home this module was asked to manage.
666
+ * @param {string} path - file path.
667
+ * @returns {Promise<{ kind: 'missing' | 'file' | 'other', contents?: string }>} state.
668
+ */
669
+ async function inspectFile(path) {
670
+ let info;
671
+ try {
672
+ info = await lstat(path);
673
+ } catch (error) {
674
+ if (error?.code === 'ENOENT') return { kind: 'missing' };
675
+ throw error;
676
+ }
677
+ if (info.isSymbolicLink()) return { kind: 'other' };
678
+ if (!info.isFile()) return { kind: 'other' };
679
+ if (info.size > MAX_CONFIG_BYTES) return { kind: 'other' };
680
+ return { kind: 'file', contents: await readFile(path, 'utf8') };
681
+ }
682
+
683
+ /**
684
+ * Inspect a directory without following it.
685
+ *
686
+ * `lstat` catches a POSIX symlink, but not a Windows junction: that reparse point is
687
+ * reported as an ordinary directory, and `mkdir`/`open` below it would silently write
688
+ * outside the Codex home. On Windows the file attributes are therefore asked for as
689
+ * well (see {@link windowsDirectoryKinds}).
690
+ * @param {string} path - directory path.
691
+ * @returns {Promise<{ kind: 'missing' | 'directory' | 'link' | 'other' | 'unknown', target?: string }>} state.
692
+ * `target` is the link target when the platform reports one, for the diagnosis only;
693
+ * `unknown` means the platform could not say whether the directory is a link.
694
+ */
695
+ export async function inspectDirectory(path) {
696
+ let info;
697
+ try {
698
+ info = await lstat(path);
699
+ } catch (error) {
700
+ if (error?.code === 'ENOENT') return { kind: 'missing' };
701
+ if (error?.code === 'ENOTDIR') return { kind: 'other' };
702
+ throw error;
703
+ }
704
+ if (info.isSymbolicLink()) return { kind: 'link', target: await readLinkTarget(path) };
705
+ if (!info.isDirectory()) return { kind: 'other' };
706
+ const kinds = await windowsDirectoryKinds([path]);
707
+ const kind = kinds.get(path);
708
+ // A junction is reported by Node as a plain directory; only the attribute proves it.
709
+ // `unknown` (the platform could not answer) is reported as itself: callers must
710
+ // refuse, and must not describe it as a link they never saw.
711
+ if (kind === 'missing') return { kind: 'missing' };
712
+ if (kind === 'unknown') return { kind: 'unknown' };
713
+ if (kind !== 'directory') return { kind: 'link', target: await readLinkTarget(path) };
714
+ return { kind: 'directory' };
715
+ }
716
+
717
+ /**
718
+ * Ask Windows what a set of paths are, as seen through their own directory entries.
719
+ *
720
+ * `lstat` cannot answer for a junction, so the file attributes are read in one
721
+ * `powershell.exe` child (`-NoProfile`, `-NonInteractive`, hidden, 15 s bound) and
722
+ * reported back as one line of comma-separated verdicts, one per input path:
723
+ *
724
+ * * `dir/true` — a directory whose attributes include `ReparsePoint`: a junction,
725
+ * a directory symlink or a directory mount point;
726
+ * * `dir/false` — a real directory, the normal case;
727
+ * * `missing` — nothing exists at that path;
728
+ * * `other/…` — something that is not a directory.
729
+ *
730
+ * The boolean is PowerShell's `Boolean.ToString()` output, whose spelling is not
731
+ * guaranteed (`True` on Windows PowerShell 5.1, `true` elsewhere); it is therefore
732
+ * decoded case-insensitively by {@link parseDirectoryVerdict}. Treating `dir/False`
733
+ * as "not the recognised real-directory answer" would report every ordinary Windows
734
+ * directory as a link, which is the bug this decoding exists to prevent.
735
+ *
736
+ * Paths travel in an environment variable, never interpolated into the script text, so
737
+ * a quote or a space in a Codex home cannot break the command. Off Windows the answer
738
+ * is always `directory` (POSIX links are already caught by `lstat`), and a platform
739
+ * where the helper cannot run answers `unknown`, which callers must treat as "not
740
+ * safely inspectable" rather than as "fine".
741
+ * @param {string[]} paths - absolute paths to inspect.
742
+ * @returns {Promise<Map<string, 'directory' | 'link' | 'missing' | 'other' | 'unknown'>>} verdict per path.
743
+ */
744
+ async function windowsDirectoryKinds(paths) {
745
+ const kinds = new Map();
746
+ for (const path of paths) kinds.set(path, 'directory');
747
+ if (process.platform !== 'win32' || paths.length === 0) return kinds;
748
+ // The declared answer wins when the carrier states it: a host that already knows how
749
+ // to read a file attribute must not be forced to spawn a shell for it.
750
+ if (platformInference !== null) return await platformInference(paths);
751
+ const answers = await runPowershell(KINDS_SCRIPT, { DSH_DELEGATE_CODEX_PATHS: paths.join('\n') });
752
+ if (answers === null) {
753
+ for (const path of paths) kinds.set(path, 'unknown');
754
+ return kinds;
755
+ }
756
+ const verdicts = answers.trimEnd().split(',');
757
+ paths.forEach((path, index) => {
758
+ // Never `unknown` for a verdict that was actually produced: the caller treats
759
+ // `unknown` as "not safely inspectable" and refuses, so an unrecognised answer is
760
+ // reported as the conservative `other` it is (a path that is not a real
761
+ // directory this module may write under), not as a missing platform answer.
762
+ const verdict = parseDirectoryVerdict(verdicts[index]);
763
+ if (verdict !== null) kinds.set(path, verdict);
764
+ else kinds.set(path, 'other');
765
+ });
766
+ return kinds;
767
+ }
768
+
769
+ /**
770
+ * Decode one `dir/<bool>` / `other/<bool>` / `missing` verdict from the helper script.
771
+ *
772
+ * The boolean is whatever PowerShell's `Boolean.ToString()` produced, and that
773
+ * spelling is **not** stable: Windows PowerShell 5.1 prints `True`/`False` while a
774
+ * .NET/PowerShell 7 spelling, or an output redirected through a different culture,
775
+ * can be `true`/`false` or even `TRUE`. Comparing against a lowercase literal (the
776
+ * original implementation) therefore misread an ordinary real directory as
777
+ * `dir/False` → "not `dir/false`" → `other` → a reported **link**. The comparison is
778
+ * case-insensitive for that reason. Only `dir/true` and `other/true` are a link, and
779
+ * only `dir/false` is a directory; every other answer is `other` (never a directory
780
+ * this module would write under), and `null` is reserved for input that is not a
781
+ * verdict at all.
782
+ * @param {string | undefined} raw - one comma-separated verdict, as printed.
783
+ * @returns {'directory' | 'link' | 'missing' | 'other' | null} verdict, or null when unrecognised.
784
+ */
785
+ export function parseDirectoryVerdict(raw) {
786
+ if (typeof raw !== 'string') return null;
787
+ const text = raw.trim().toLowerCase();
788
+ if (text === 'missing') return 'missing';
789
+ if (text === 'dir/true' || text === 'other/true') return 'link';
790
+ if (text === 'dir/false') return 'directory';
791
+ // `other/false` is a regular non-directory; `other/…` is a link-shaped entry this
792
+ // module will not write under. Both are `other`, and so are the script's own
793
+ // `error` (a path whose attributes could not be read) and an empty verdict (the
794
+ // script fell silent): definite "not a directory I may write under" answers, not a
795
+ // failed platform answer — `unknown` is reserved for "the helper could not run".
796
+ if (text === 'error' || text === '' || text.startsWith('other/')) return 'other';
797
+ return null;
798
+ }
799
+
800
+ /**
801
+ * An answer for {@link windowsDirectoryKinds} supplied by the embedding carrier.
802
+ *
803
+ * This is a *capability* declaration, not a knob an operator turns: it exists so a
804
+ * host that can read a file's attributes natively (or a test that must run without a
805
+ * child process) can state the platform answer, and it is `null` everywhere else — the
806
+ * bundled script is then the only source. Nothing this module does may set it.
807
+ * @type {((paths: string[]) => Promise<Map<string, string>>) | null}
808
+ */
809
+ let platformInference = null;
810
+
811
+ /**
812
+ * Use a caller-supplied directory classifier instead of the bundled script.
813
+ *
814
+ * Only a host integration may call this; the returned function restores the previous
815
+ * value, so a test can install one for its own duration.
816
+ * @param {((paths: string[]) => Promise<Map<string, string>>) | null} classify - classifier, or null to reset.
817
+ * @returns {() => void} undo.
818
+ */
819
+ export function useDirectoryClassifier(classify) {
820
+ const previous = platformInference;
821
+ platformInference = typeof classify === 'function' ? classify : null;
822
+ return () => { platformInference = previous; };
823
+ }
824
+
825
+ /** One verdict per path in `$env:DSH_DELEGATE_CODEX_PATHS`, comma-separated. */
826
+ const KINDS_SCRIPT = [
827
+ '$ErrorActionPreference = "Stop"',
828
+ 'if ($env:DSH_DELEGATE_CODEX_PATHS -eq $null) { throw "no paths" }',
829
+ "$targets = $env:DSH_DELEGATE_CODEX_PATHS -split \"`n\"",
830
+ '$verdicts = foreach ($target in $targets) {',
831
+ ' if ($target -eq "") { "error" }',
832
+ ' elseif (-not (Test-Path -LiteralPath $target)) { "missing" }',
833
+ ' else {',
834
+ ' try {',
835
+ ' $attributes = [System.IO.File]::GetAttributes($target)',
836
+ ' $isDirectory = (($attributes -band [System.IO.FileAttributes]::Directory) -ne 0)',
837
+ ' $isLink = (($attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0)',
838
+ ' if (-not $isDirectory) { "other/" + $isLink.ToString().ToLowerInvariant() } else { "dir/" + $isLink.ToString().ToLowerInvariant() }',
839
+ ' } catch { "error" }',
840
+ ' }',
841
+ '}',
842
+ '$verdicts -join ","',
843
+ ].join("\n");
844
+
845
+ /**
846
+ * Run one PowerShell script and return its trimmed standard output.
847
+ *
848
+ * `stdio` is kept quiet (`windowsHide`); the exit status decides success, and any
849
+ * failure — a missing executable, a non-zero exit, a timeout — resolves to `null`
850
+ * rather than throwing, because a check that cannot run must not take an unrelated
851
+ * action down with it. A platform that forbids spawning a child at all (`EPERM`,
852
+ * thrown synchronously by `execFile`) is one such failure.
853
+ * @param {string} script - script text.
854
+ * @param {Record<string, string>} env - extra environment entries for the child only.
855
+ * @returns {Promise<string | null>} output, or null when the script did not succeed.
856
+ */
857
+ async function runPowershell(script, env) {
858
+ return await new Promise((resolveAnswer) => {
859
+ try {
860
+ execFile(
861
+ 'powershell.exe',
862
+ ['-NoProfile', '-NonInteractive', '-Command', script],
863
+ { windowsHide: true, timeout: 15000, env: { ...process.env, ...env }, maxBuffer: 64 * 1024 },
864
+ (error, stdout) => {
865
+ resolveAnswer(error === null ? String(stdout) : null);
866
+ },
867
+ );
868
+ } catch {
869
+ // No child process may be started here (a restricted carrier, a sandbox): the
870
+ // caller reports an unverifiable boundary instead of assuming it is clean.
871
+ resolveAnswer(null);
872
+ }
873
+ });
874
+ }
875
+
876
+ /**
877
+ * Read a link's target for the diagnosis, never to follow it.
878
+ * @param {string} path - link path.
879
+ * @returns {Promise<string | undefined>} target text when the platform reports one.
880
+ */
881
+ async function readLinkTarget(path) {
882
+ try {
883
+ return await readlink(path);
884
+ } catch {
885
+ return undefined;
886
+ }
887
+ }
888
+
889
+ /**
890
+ * Compare the installed agent file with the template this build would write.
891
+ *
892
+ * The order matters. Content equality is checked first, so a byte-identical file is
893
+ * `installed` no matter what its version line says. Only then is the exact
894
+ * known-template list consulted, and only a byte-exact match to a published build is
895
+ * `outdated`. Everything else is `modified`: a body edit, a stray byte, a tampered
896
+ * or invented version line, or a file that merely looks like ours.
897
+ * @param {string} path - agent file path.
898
+ * @param {string} template - template text this build would write.
899
+ * @returns {Promise<{ state: string, present: boolean, reason: string | null, contents: string | null }>} agent state and the exact bytes it was derived from.
900
+ */
901
+ async function readAgentState(path, template) {
902
+ const existing = await inspectFile(path);
903
+ if (existing.kind === 'missing') return { state: AGENT_STATES.missing, present: false, reason: null, contents: null };
904
+ if (existing.kind === 'other') return { state: AGENT_STATES.conflict, present: true, reason: 'not-a-regular-file', contents: null };
905
+ const contents = existing.contents;
906
+ if (contents === template) return { state: AGENT_STATES.installed, present: true, reason: null, contents };
907
+ if (isKnownPriorTemplate(contents)) return { state: AGENT_STATES.outdated, present: true, reason: null, contents };
908
+ return {
909
+ state: AGENT_STATES.modified,
910
+ present: true,
911
+ reason: isKnownPriorTemplate(contents, { ignoreVersion: true }) ? 'edited' : 'unknown-content',
912
+ contents,
913
+ };
914
+ }
915
+
916
+ /**
917
+ * Inspect the two directories that bound what this module may write.
918
+ *
919
+ * `$CODEX_HOME` and `$CODEX_HOME/agents` are the only places the managed files may
920
+ * live. A link at either (a POSIX symlink, or a Windows junction/reparse point that
921
+ * `lstat` reports as a plain directory) means the final path string no longer names
922
+ * a location inside the Codex home, so it is refused before anything is created or
923
+ * removed — `mkdir(recursive)` would otherwise walk through the link.
924
+ *
925
+ * A directory whose identity cannot be established (`unknown`) is refused too: the
926
+ * alternative is to assume it is safe, and an assumption is what this check exists to
927
+ * remove. Both paths are inspected in one batch, so a normal Windows home costs one
928
+ * child process, not two.
929
+ * @param {string} home - resolved Codex home.
930
+ * @returns {Promise<{
931
+ * blocked: boolean,
932
+ * link: 'codex-home' | 'agents' | null,
933
+ * unknown: boolean,
934
+ * home: { kind: string, target?: string },
935
+ * agents: { kind: string, target?: string },
936
+ * }>} boundary state.
937
+ */
938
+ export async function inspectCodexBoundary(home) {
939
+ const agentsPath = join(home, 'agents');
940
+ const homeInfo = await inspectDirectory(home);
941
+ if (homeInfo.kind === 'link') {
942
+ // The agents path is resolved through the link; do not inspect it further, and
943
+ // do not report whether anything below it exists.
944
+ return { blocked: true, link: 'codex-home', unknown: false, home: homeInfo, agents: { kind: 'unchecked' } };
945
+ }
946
+ const agentsInfo = homeInfo.kind === 'directory'
947
+ ? await inspectDirectory(agentsPath)
948
+ : { kind: 'unchecked' };
949
+ if (agentsInfo.kind === 'link') {
950
+ return { blocked: true, link: 'agents', unknown: false, home: homeInfo, agents: agentsInfo };
951
+ }
952
+ // A home that exists but could not be classified, or an `agents` entry that could
953
+ // not be, is reported and refused for the same reason.
954
+ if (homeInfo.kind === 'unknown' || agentsInfo.kind === 'unknown') {
955
+ return { blocked: true, link: null, unknown: true, home: homeInfo, agents: agentsInfo };
956
+ }
957
+ return { blocked: false, link: null, unknown: false, home: homeInfo, agents: agentsInfo };
958
+ }
959
+
960
+ /**
961
+ * Does a link stand between the Codex home and the managed files?
962
+ *
963
+ * The status document carries the answer (`boundary.blocked`) because it is read with
964
+ * exactly the same inspect call; this turns that fact into a refusal in the shape
965
+ * every action reports. Re-reading the status is what makes the check current: it is
966
+ * re-done at the start of every writing action.
967
+ * @param {object} status - a status document from {@link readCodexStatus}.
968
+ * @returns {{ target: string, code: string, message: string, path: string, reason: string }} refusal.
969
+ */
970
+ function linkedBoundaryRefusal(status) {
971
+ if (status.boundary?.unknown === true) {
972
+ return {
973
+ target: 'agent',
974
+ code: 'AGENT_PATH_CONFLICT',
975
+ message: 'the Codex home or agents directory could not be verified as a real directory and was not written',
976
+ path: join(status.codexHome, 'agents'),
977
+ reason: 'boundary-unverified',
978
+ };
979
+ }
980
+ const isHome = status.boundary?.link === 'codex-home';
981
+ return {
982
+ target: 'agent',
983
+ code: 'AGENT_PATH_CONFLICT',
984
+ message: isHome
985
+ ? 'the Codex home is a link or reparse point, so nothing below it is written or removed'
986
+ : 'the agents directory is a link or reparse point, so nothing inside it is written or removed',
987
+ path: isHome ? status.codexHome : join(status.codexHome, 'agents'),
988
+ reason: isHome ? 'codex-home-is-link' : 'agents-dir-is-link',
989
+ };
990
+ }
991
+
992
+ /**
993
+ * Is this file one of the exact agent files an earlier release shipped?
994
+ *
995
+ * The only case where install may replace an existing file. The test is content
996
+ * identity against the enumerated digest list, which cannot be satisfied by an
997
+ * operator edit: a single changed byte changes the digest. The version line is
998
+ * deliberately *not* used as proof — an operator can edit a body while leaving (or
999
+ * lowering) that line, and a heuristic on it is exactly how a customised agent
1000
+ * gets overwritten.
1001
+ * @param {string} contents - installed file text.
1002
+ * @param {object} [options] - `ignoreVersion`: compare with the version line masked,
1003
+ * used only to explain *why* a file is `modified` in the status note.
1004
+ * @returns {boolean} true when the file is a known published build of this template.
1005
+ */
1006
+ export function isKnownPriorTemplate(contents, { ignoreVersion = false } = {}) {
1007
+ if (typeof contents !== 'string') return false;
1008
+ const digestValue = digest(contents);
1009
+ if (KNOWN_AGENT_TEMPLATES.some((entry) => entry.sha256 === digestValue)) return true;
1010
+ if (!ignoreVersion) return false;
1011
+ // Explanation-only path: the same body with the version line stripped still has to
1012
+ // match a known build, which distinguishes "operator edited a managed file" from
1013
+ // "this file was never ours".
1014
+ const stripped = contents.replace(VERSION_LINE, 'version = "\u0000"');
1015
+ return KNOWN_AGENT_TEMPLATES.some((entry) => entry.sha256 === digest(stripped));
1016
+ }
1017
+
1018
+ /**
1019
+ * Write a file that must not exist yet, atomically and exclusively.
1020
+ *
1021
+ * `writeFileAtomic` renames a temp file over the target, which silently replaces a
1022
+ * file that appeared between the status read and the write (a TOCTOU window). This
1023
+ * helper writes the temp file and then *links* it into place: `link` fails with
1024
+ * `EEXIST` when the target exists, so a concurrently created file is never
1025
+ * overwritten. On the (rare) filesystem without hard links it falls back to an
1026
+ * exclusive open, which has the same "fail if it exists" contract.
1027
+ * @param {string} path - destination path (must not exist).
1028
+ * @param {string} contents - file contents.
1029
+ * @returns {Promise<'created' | 'exists'>} outcome; `exists` means nothing was written.
1030
+ */
1031
+ export async function createFileExclusive(path, contents) {
1032
+ const temp = `${path}.${randomBytes(6).toString('hex')}.tmp`;
1033
+ const handle = await open(temp, 'wx', 0o600);
1034
+ try {
1035
+ await handle.writeFile(contents, 'utf8');
1036
+ } finally {
1037
+ await handle.close();
1038
+ }
1039
+ try {
1040
+ await link(temp, path);
1041
+ return 'created';
1042
+ } catch (error) {
1043
+ if (error?.code === 'EEXIST') return 'exists';
1044
+ if (error?.code !== 'EPERM' && error?.code !== 'ENOSYS' && error?.code !== 'EXDEV' && error?.code !== 'EACCES') throw error;
1045
+ // No hard links on this volume: an exclusive create is the remaining option.
1046
+ const exclusive = await open(path, 'wx', 0o600);
1047
+ try {
1048
+ await exclusive.writeFile(contents, 'utf8');
1049
+ } finally {
1050
+ await exclusive.close();
1051
+ }
1052
+ return 'created';
1053
+ } finally {
1054
+ await unlink(temp).catch(() => {});
1055
+ }
1056
+ }
1057
+
1058
+ /**
1059
+ * Locate the installed MCP entry point of *this* package.
1060
+ *
1061
+ * `import.meta.url` is the running file, so a package installed into a DSH profile
1062
+ * resolves to that profile's own copy — not to a repository checkout, and not to a
1063
+ * path that happened to exist when the tarball was built.
1064
+ * @returns {Promise<{ script: string, exists: boolean, fromRealPath: string }>} resolved path and whether it exists.
1065
+ */
1066
+ export async function resolveMcpScript() {
1067
+ const script = resolve(PACKAGE_ROOT, MCP_ENTRY_RELATIVE);
1068
+ let exists = false;
1069
+ try {
1070
+ const info = await stat(script);
1071
+ exists = info.isFile();
1072
+ } catch {
1073
+ exists = false;
1074
+ }
1075
+ let realPath = script;
1076
+ try {
1077
+ realPath = await realpath(script);
1078
+ } catch {
1079
+ realPath = script;
1080
+ }
1081
+ return { script, exists, fromRealPath: realPath };
1082
+ }
1083
+
1084
+ /**
1085
+ * Environment a Codex-spawned MCP server needs in order to find the same DSH.
1086
+ *
1087
+ * The discovery file is how the MCP process learns which loopback port DSH is
1088
+ * listening on. When DSH runs with a non-default `DSH_HOME`, Codex's spawned child
1089
+ * inherits Codex's environment instead, so the resolved path is pinned into the
1090
+ * entry. When the path is the default one it is left implicit: writing an absolute
1091
+ * default would silently override a later `DSH_HOME` change.
1092
+ * @param {object} options - `discoveryFile` (absolute) and `env`.
1093
+ * @returns {{ path: string, pin: boolean }} discovery location and whether to write it.
1094
+ */
1095
+ export function discoveryPin(discoveryFile, env = process.env) {
1096
+ const configured = typeof env[DISCOVERY_ENV_VAR] === 'string' ? env[DISCOVERY_ENV_VAR].trim() : '';
1097
+ if (configured !== '') return { path: resolve(configured), pin: true };
1098
+ return { path: resolve(discoveryFile), pin: false };
1099
+ }
1100
+
1101
+ /**
1102
+ * How long one `delegate_wait` call asks the client to allow, in seconds.
1103
+ *
1104
+ * The default wait is 3600 s (60 minutes) and the tool caps it there, so 3660 s is that
1105
+ * 3600 s plus a minute of slack for one internal observation slice, JSON overhead and
1106
+ * clock skew — never a second wait window. A client that honours the field may let the
1107
+ * whole wait run; a client that applies its own default tool timeout (Codex's historical
1108
+ * default is 60 s) can still end it early, and that client-side limit is not something
1109
+ * this entry can lift. The value is a request, not a guarantee about every client.
1110
+ *
1111
+ * This is written on THIS server's entry only. It is not a Codex-wide setting and it
1112
+ * is never written anywhere else in the operator's config.
1113
+ */
1114
+ export const DELEGATE_TOOL_TIMEOUT_SEC = 3660;
1115
+
1116
+ /**
1117
+ * The exact stdio command and timeout this plugin owns in Codex.
1118
+ * @param {object} options - `node`, `script`, `discoveryFile`, `pinDiscovery`.
1119
+ * @returns {{ command: string, args: string[], env: Record<string, string>, toolTimeoutSec: number }} command description.
1120
+ */
1121
+ export function desiredMcpCommand({ node, script, discoveryFile = null, pinDiscovery = false }) {
1122
+ return {
1123
+ command: node,
1124
+ args: [script],
1125
+ env: pinDiscovery && discoveryFile !== null ? { DSH_DELEGATE_DISCOVERY_FILE: discoveryFile } : {},
1126
+ toolTimeoutSec: DELEGATE_TOOL_TIMEOUT_SEC,
1127
+ };
1128
+ }
1129
+
1130
+ /**
1131
+ * Where the managed `mcp_servers.dsh-delegate` definitions sit in a document.
1132
+ *
1133
+ * A definition is owned only when the plugin's marker comment proves it was written
1134
+ * by this plugin. The marker must be the comment line directly above the definition
1135
+ * (or above a child table of it), so a marker cannot "bless" a table somewhere else.
1136
+ * @param {TomlDocument} document - parsed config.
1137
+ * @returns {{ inline: object | undefined, headerIndex: number, marker: string | null }} locations.
1138
+ */
1139
+ export function locateMcpDefinition(document) {
1140
+ const serverPath = ['mcp_servers', MCP_SERVER_NAME];
1141
+ const inline = document.assignmentAt(serverPath);
1142
+ const headerIndex = document.entries.findIndex((entry) => entry.kind !== 'assignment' && samePath(entry.path, serverPath));
1143
+ /** The header/assignment line the marker has to sit directly above. */
1144
+ const anchored = inline !== undefined ? inline : (headerIndex === -1 ? null : document.entries[headerIndex]);
1145
+ if (anchored === null) return { inline, headerIndex, marker: null };
1146
+ // A definition may be written as `dsh-delegate = { … }` under `[mcp_servers]`, in
1147
+ // which case the marker can sit above either the assignment or its parent header —
1148
+ // both are the plugin's own line, and the operator cannot have written the
1149
+ // assignment without writing (or choosing to keep) the header above it.
1150
+ const candidates = [anchored.startLine - 1];
1151
+ const parent = document.entries.findIndex(
1152
+ (entry) => entry.kind !== 'assignment' && entry.path.length === serverPath.length - 1
1153
+ && entry.startLine < anchored.startLine
1154
+ && entry.path.every((segment, index) => serverPath[index] === segment),
1155
+ );
1156
+ if (parent !== -1) candidates.push(document.entries[parent].startLine - 1);
1157
+ for (const line of candidates) {
1158
+ if (document.isMarkerLine(line, MCP_MARKER)) return { inline, headerIndex, marker: MCP_MARKER };
1159
+ }
1160
+ return { inline, headerIndex, marker: null };
1161
+ }
1162
+
1163
+ /**
1164
+ * Classify the existing `mcp_servers.dsh-delegate` definition.
1165
+ *
1166
+ * Two independent conditions must hold before the entry is treated as managed:
1167
+ * it carries the plugin's marker comment (proof of authorship), and its values are
1168
+ * the exact stdio command this plugin writes. An unmarked entry is the operator's
1169
+ * even when the values coincide, because "identical values" is not "this plugin
1170
+ * wrote it": removing it later would delete a line the operator owns.
1171
+ * @param {TomlDocument} document - parsed config.
1172
+ * @param {object} desired - value from {@link desiredMcpCommand}.
1173
+ * @returns {{ state: string, previous: object | null, reason: string | null, ownedValues: object, marked: boolean }} classification.
1174
+ */
1175
+ export function classifyMcpEntry(document, desired) {
1176
+ const serverPath = ['mcp_servers', MCP_SERVER_NAME];
1177
+ const { inline, headerIndex, marker } = locateMcpDefinition(document);
1178
+ const childAssignments = document.assignmentsUnder(serverPath);
1179
+
1180
+ if (inline === undefined && headerIndex === -1 && childAssignments.length === 0) {
1181
+ return { state: MCP_STATES.missing, previous: null, reason: null, ownedValues: {}, marked: false, drift: null };
1182
+ }
1183
+ if (document.tablesUnder(serverPath).some((entry) => entry.kind === 'array-table')) {
1184
+ return { state: MCP_STATES.conflict, previous: null, reason: 'array-table', ownedValues: {}, marked: marker !== null, drift: null };
1185
+ }
1186
+
1187
+ /** Gather the definition regardless of the two legal spellings. */
1188
+ const values = {};
1189
+ if (inline !== undefined) {
1190
+ if (tomlValueType(inline.raw) !== 'table') {
1191
+ return { state: MCP_STATES.conflict, previous: null, reason: 'not-a-table', ownedValues: {}, marked: marker !== null, drift: null };
1192
+ }
1193
+ Object.assign(values, parseInlineTable(inline.raw));
1194
+ }
1195
+ for (const entry of childAssignments) {
1196
+ if (samePath(entry.path, serverPath)) continue;
1197
+ values[entry.path.slice(serverPath.length).join('.')] = { type: tomlValueType(entry.raw), text: entry.raw };
1198
+ }
1199
+ const shape = describeEntryShape(values);
1200
+ if (shape !== 'stdio') {
1201
+ // A URL entry, a mixed entry or an entry with fields this plugin never writes
1202
+ // is somebody else's definition of the same name.
1203
+ return { state: MCP_STATES.conflict, previous: null, reason: shape, ownedValues: {}, marked: marker !== null, drift: null };
1204
+ }
1205
+ const command = readStringValue(values.command?.text);
1206
+ const args = readArrayValue(values.args?.text);
1207
+ const envKeys = Object.keys(values).filter((key) => key.startsWith('env.')).map((key) => key.slice(4));
1208
+ /** @type {'missing' | 'different' | null} */
1209
+ let timeoutMismatch = null;
1210
+ const previous = { command, args, envKeys, toolTimeoutSec: null, discoveryFile: null };
1211
+ if (marker === null) {
1212
+ // Values that happen to match are still not proof the plugin wrote them; the
1213
+ // marker is the only authorship proof this format carries.
1214
+ return { state: MCP_STATES.conflict, previous, reason: 'unmanaged-entry', ownedValues: {}, marked: false, drift: null };
1215
+ }
1216
+ // A different *command* is a different program: even if the arguments look like
1217
+ // ours, running (or replacing) someone else's wrapper is not this plugin's call.
1218
+ // The one narrow migration exception is the 0.1.6 Desktop defect, which wrote
1219
+ // the host GUI (`DeepSeek Harness.exe`) instead of Node. It is accepted only when
1220
+ // the marker, current package entry point and owned env shape all prove that this
1221
+ // is the old entry this plugin wrote. Any stale args or extra env remains a
1222
+ // conflict, so a similarly named user wrapper is never adopted.
1223
+ const legacyDesktopCommand = isLegacyDesktopCommand(command);
1224
+ if (command !== desired.command && !legacyDesktopCommand) {
1225
+ return { state: MCP_STATES.conflict, previous, reason: 'command-not-ours', ownedValues: {}, marked: true, drift: null };
1226
+ }
1227
+ const mismatched = !sameStrings(args, desired.args);
1228
+ const expectedEnvKeys = Object.keys(desired.env);
1229
+ const envMismatch = expectedEnvKeys.some((key) => {
1230
+ const value = readStringValue(values[`env.${key}`]?.text);
1231
+ return value !== desired.env[key];
1232
+ });
1233
+ const extraEnv = envKeys.filter((key) => !expectedEnvKeys.includes(key));
1234
+ const missingEnv = expectedEnvKeys.filter((key) => !envKeys.includes(key));
1235
+ if (extraEnv.length > 0) {
1236
+ return { state: MCP_STATES.conflict, previous, reason: 'extra-env', ownedValues: { extraEnv }, marked: true, drift: null };
1237
+ }
1238
+ // The tool timeout is an OWNED fact. A managed entry written by an earlier release
1239
+ // has no `tool_timeout_sec` at all, and one an operator (or a future build) changed
1240
+ // has a different integer: both are this plugin's entry with a stale value, so they
1241
+ // migrate in place instead of being reported as somebody else's definition. A
1242
+ // non-integer was already refused by `describeEntryShape`.
1243
+ const recordedTimeout = readIntegerValue(values.tool_timeout_sec?.text);
1244
+ previous.toolTimeoutSec = recordedTimeout;
1245
+ const discoveryEnvKey = DISCOVERY_ENV_VAR;
1246
+ const recordedDiscovery = typeof values[`env.${discoveryEnvKey}`]?.text === 'string'
1247
+ ? readStringValue(values[`env.${discoveryEnvKey}`].text)
1248
+ : null;
1249
+ previous.discoveryFile = recordedDiscovery;
1250
+ if (recordedTimeout === null) timeoutMismatch = 'missing';
1251
+ else if (recordedTimeout !== desired.toolTimeoutSec) timeoutMismatch = 'different';
1252
+
1253
+ // The owned `args[0]` normally names THIS installation's MCP entry point exactly.
1254
+ // It may legitimately differ in ONE conservative way: the plugin was upgraded into a
1255
+ // new directory, so an older build's absolute path still points at a copy of the SAME
1256
+ // package layout. That must be PROVED, not guessed: a basename match alone would let
1257
+ // `args = ["/mine/dsh-delegate-mcp.js"]` — an operator's own wrapper that happens to
1258
+ // reuse the file name — be silently rewritten by a startup migration.
1259
+ //
1260
+ // `staleScript` is therefore only a drift LABEL. It never authorizes a write by
1261
+ // itself: `isOwnedStaleEntry` (below) decides write eligibility from the complete
1262
+ // recorded shape, and anything it cannot prove stays a `conflict` the caller refuses.
1263
+ const scriptDiffers = !sameStrings(args, desired.args);
1264
+ const extraArgs = scriptDiffers && args.length !== desired.args.length;
1265
+ // The classifier is SYNCHRONOUS and can therefore only accept the one proof that needs
1266
+ // no I/O: `args[0]` is the exact same absolute path as this installation's script.
1267
+ //
1268
+ // A DIFFERENT script is a conflict here — never `outdated` — because the only way it
1269
+ // could be ours (an older installation of this same package) requires reading that
1270
+ // root's `package.json` and resolving the file, and a label computed without that proof
1271
+ // must not authorize a write. `isOwnedStaleEntry` performs the real, asynchronous proof
1272
+ // for the explicit repair path, which is allowed to adopt a verified moved install.
1273
+ const scriptIsThisInstallation = scriptDiffers && isExactInstalledScript(args[0], desired.args[0]);
1274
+ const argsShapeNotOurs = extraArgs || (scriptDiffers && !scriptIsThisInstallation);
1275
+ if (argsShapeNotOurs) {
1276
+ return {
1277
+ state: MCP_STATES.conflict,
1278
+ previous,
1279
+ reason: 'args-shape-not-ours',
1280
+ ownedValues: {},
1281
+ marked: true,
1282
+ drift: null,
1283
+ };
1284
+ }
1285
+ const staleScript = scriptDiffers;
1286
+ const envDrift = new Set();
1287
+ if (timeoutMismatch !== null) envDrift.add('tool_timeout_sec');
1288
+ if (staleScript) envDrift.add('args');
1289
+ if (envMismatch) envDrift.add('env');
1290
+ if (missingEnv.length > 0) envDrift.add('env');
1291
+ const drift = envDrift.size === 0 ? null : [...envDrift];
1292
+ if (legacyDesktopCommand && (mismatched || envMismatch || missingEnv.length > 0)) {
1293
+ return {
1294
+ state: MCP_STATES.conflict,
1295
+ previous,
1296
+ reason: 'legacy-command-shape',
1297
+ ownedValues: {},
1298
+ marked: true,
1299
+ drift: null,
1300
+ };
1301
+ }
1302
+ if (mismatched || envMismatch || missingEnv.length > 0 || timeoutMismatch !== null) {
1303
+ return { state: MCP_STATES.outdated, previous, reason: null, ownedValues: {}, marked: true, drift };
1304
+ }
1305
+ return {
1306
+ state: legacyDesktopCommand ? MCP_STATES.outdated : MCP_STATES.configured,
1307
+ previous,
1308
+ reason: null,
1309
+ ownedValues: {},
1310
+ marked: true,
1311
+ drift: legacyDesktopCommand ? ['command'] : null,
1312
+ };
1313
+ }
1314
+
1315
+ /**
1316
+ * Can this recorded entry be REWRITTEN by an automatic migration?
1317
+ *
1318
+ * This is the write gate, deliberately narrower than "the classifier said `outdated`".
1319
+ * An automatic, unreviewed write is only acceptable when the entry is provably the
1320
+ * plugin's own in every owned fact:
1321
+ *
1322
+ * * it is `outdated` (never `conflict`/`missing`/`configured`);
1323
+ * * the marker proved authorship (the classifier only reports `outdated` for a marked
1324
+ * entry, and this re-checks it);
1325
+ * * the command is exactly this plugin's Node command (or the one recognized 0.1.6
1326
+ * Desktop command, which the classifier already narrowed);
1327
+ * * `args[0]` is either this installation's exact script — the core missing-timeout
1328
+ * case — or a path whose FINAL TWO segments are this package's
1329
+ * `bin/dsh-delegate-mcp.js`, i.e. an older installation of the same layout. A bare
1330
+ * file-name match anywhere on disk is not enough;
1331
+ * * there is exactly ONE argument (no wrapper flags), and the env carries no key this
1332
+ * plugin did not write.
1333
+ *
1334
+ * Everything else is refused by the caller with an explanation: it keeps the file and
1335
+ * tells the operator to use the explicit install/repair button.
1336
+ *
1337
+ * The script proof is a FILESYSTEM proof (`isOwnedEntryScript`), so this gate is async and
1338
+ * is re-run at write time — a label computed from the plan is not enough, because the
1339
+ * script could have been replaced between the check and the write.
1340
+ * @param {object} classification - value from {@link classifyMcpEntry}.
1341
+ * @param {object} desired - value from {@link desiredMcpCommand}.
1342
+ * @param {object} [options] - `allowMovedInstall`: accept a DIFFERENT path that is
1343
+ * provably another installation of this package. Only the explicit `repair` path sets
1344
+ * it; the unattended startup migration never does, so it cannot adopt a path it did not
1345
+ * prove in the plan.
1346
+ * @returns {Promise<{ owned: true } | { owned: false, reason: string }>} gate verdict.
1347
+ */
1348
+ export async function isOwnedStaleEntry(classification, desired, options = {}) {
1349
+ if (classification?.marked !== true) return { owned: false, reason: 'unmarked' };
1350
+ const previous = classification.previous ?? null;
1351
+ if (previous === null) return { owned: false, reason: 'no-recorded-shape' };
1352
+ if (previous.command !== desired.command && !isLegacyDesktopCommand(previous.command)) {
1353
+ return { owned: false, reason: 'command-not-ours' };
1354
+ }
1355
+ const args = Array.isArray(previous.args) ? previous.args : [];
1356
+ if (args.length !== 1) return { owned: false, reason: 'args-shape-not-ours' };
1357
+ const recordedEnv = Array.isArray(previous.envKeys) ? previous.envKeys : [];
1358
+ const expectedEnv = Object.keys(desired.env);
1359
+ if (recordedEnv.some((key) => !expectedEnv.includes(key))) return { owned: false, reason: 'extra-env' };
1360
+ // The script proof is a FILESYSTEM proof and runs here, at gate time, so a label
1361
+ // computed earlier cannot stand in for it.
1362
+ if (isExactInstalledScript(args[0], desired.args[0])) {
1363
+ return classification.state === MCP_STATES.outdated
1364
+ ? { owned: true }
1365
+ : { owned: false, reason: `state-${classification.state}` };
1366
+ }
1367
+ if (options.allowMovedInstall !== true) return { owned: false, reason: 'script-not-provably-ours' };
1368
+ if (!(await isOtherInstallationOfThisPackage(args[0], PACKAGE_NAME))) {
1369
+ return { owned: false, reason: 'script-not-provably-ours' };
1370
+ }
1371
+ return classification.state === MCP_STATES.outdated || classification.state === MCP_STATES.conflict
1372
+ ? { owned: true }
1373
+ : { owned: false, reason: `state-${classification.state}` };
1374
+ }
1375
+
1376
+ /**
1377
+ * The native path rules, as a value, so {@link packageEntryRoot} can also be exercised
1378
+ * with an explicit POSIX/Win32 rule set in tests instead of only on the host platform.
1379
+ */
1380
+ const NATIVE_PATH = Object.freeze({ isAbsolute, basename, dirname, parse });
1381
+
1382
+ /**
1383
+ * The `<root>` of an absolute `<root>/bin/dsh-delegate-mcp.js` path, or `null`.
1384
+ *
1385
+ * Derived with `dirname`/`basename` rather than by splitting on `/` and rejoining:
1386
+ * splitting drops the leading empty segment of a POSIX path, so `/opt/pkg/bin/x`
1387
+ * silently became the relative `opt/pkg/bin/x` and the real installation could never be
1388
+ * proved on Linux or macOS. The rules are explicit and platform-shaped:
1389
+ *
1390
+ * * the input must be absolute and name exactly `bin/dsh-delegate-mcp.js`;
1391
+ * * `<root>` must be a real directory NAME below the filesystem root — `/bin/x` and
1392
+ * `C:\bin\x` have `<root>` at the root itself and are refused;
1393
+ * * nothing here touches the filesystem; {@link isOtherInstallationOfThisPackage}
1394
+ * proves the boundaries of the root it returns.
1395
+ * @param {string} script - candidate entry path.
1396
+ * @param {{ isAbsolute: Function, basename: Function, dirname: Function, parse: Function }} [pathApi]
1397
+ * path rules; defaults to the host platform's.
1398
+ * @returns {string | null} the package root, or null when the shape is not ours.
1399
+ */
1400
+ export function packageEntryRoot(script, pathApi = NATIVE_PATH) {
1401
+ if (typeof script !== 'string') return null;
1402
+ const value = script.trim();
1403
+ if (value === '' || !pathApi.isAbsolute(value)) return null;
1404
+ if (pathApi.basename(value) !== 'dsh-delegate-mcp.js') return null;
1405
+ const binDir = pathApi.dirname(value);
1406
+ if (pathApi.basename(binDir) !== 'bin') return null;
1407
+ const root = pathApi.dirname(binDir);
1408
+ if (root === binDir || root === '' || root === pathApi.parse(root).root) return null;
1409
+ return root;
1410
+ }
1411
+
1412
+ /**
1413
+ * Is `candidate` provably this package's MCP entry point on THIS machine?
1414
+ *
1415
+ * There are exactly two accepted proofs, and both are asynchronous because both must
1416
+ * INSPECT the filesystem. A suffix comparison is not a proof: `/mine/bin/
1417
+ * dsh-delegate-mcp.js` has the same last two segments as this package's script and is
1418
+ * still somebody else's program, so accepting it would let a startup migration overwrite
1419
+ * an operator's wrapper.
1420
+ *
1421
+ * 1. **Exact equivalence of the absolute path** to this installation's own script, with
1422
+ * the comparison following the PLATFORM's case rules (`==` on Windows and — by
1423
+ * assumption, because its default volumes are case-insensitive — macOS; exact bytes
1424
+ * on Linux). A relative path is never equivalent: it names no location.
1425
+ * 2. **A different, but real, installation of this package**: an absolute path to a
1426
+ * regular, non-link file, whose directory is `<root>/bin`, where `<root>` is a real
1427
+ * directory, `<root>/bin` is a real directory, `<root>/bin/dsh-delegate-mcp.js` is a
1428
+ * regular non-link file that IS the candidate (compared by real path), and
1429
+ * `<root>/package.json` is a regular non-link file that BOTH declares
1430
+ * `"name": "dsh-delegate"` and maps `bin["dsh-delegate-mcp"]` to that very entry
1431
+ * (a `./` prefix is allowed; an absolute, out-of-package, wrong or missing mapping
1432
+ * is not).
1433
+ *
1434
+ * Anything else — a relative path, a missing file, a link, a directory that is not this
1435
+ * package, a same-layout script whose root's manifest maps its bin elsewhere — is NOT
1436
+ * claimed. The caller keeps the operator's entry and tells them to use the explicit
1437
+ * install/repair button, which is the correct outcome for a path this plugin cannot
1438
+ * account for.
1439
+ * @param {string} candidate - recorded `args[0]`.
1440
+ * @param {string} installed - this installation's script path (absolute).
1441
+ * @param {object} [options] - `rootPackageName` (defaults to `dsh-delegate`) for tests.
1442
+ * @returns {Promise<boolean>} true only when the candidate is provably this package's entry.
1443
+ */
1444
+ export async function isOwnedEntryScript(candidate, installed, options = {}) {
1445
+ if (typeof candidate !== 'string' || typeof installed !== 'string') return false;
1446
+ const recorded = candidate.trim();
1447
+ if (recorded === '' || installed.trim() === '') return false;
1448
+ // A relative path names no location at all, so it can never be proven.
1449
+ if (!isAbsolute(recorded)) return false;
1450
+ if (samePlatformPath(recorded, installed, process.platform)) return true;
1451
+ return await isOtherInstallationOfThisPackage(recorded, options.rootPackageName ?? PACKAGE_NAME);
1452
+ }
1453
+
1454
+ /** Explicit repair also accepts an uninstalled legacy sibling in the same node_modules. */
1455
+ export async function isExplicitlyMigratableScript(candidate, installed) {
1456
+ if (await isOwnedEntryScript(candidate, installed)) return true;
1457
+ const oldRoot = packageEntryRoot(candidate);
1458
+ const newRoot = packageEntryRoot(installed);
1459
+ if (oldRoot === null || newRoot === null) return false;
1460
+ if (!['dsh-delegate', 'dsh-taskdispatch'].includes(basename(oldRoot))) return false;
1461
+ if (basename(newRoot) !== 'dsh-taskbridge' || basename(dirname(newRoot)) !== 'node_modules') return false;
1462
+ if (!samePlatformPath(dirname(oldRoot), dirname(newRoot))) return false;
1463
+ try { await lstat(oldRoot); return false; }
1464
+ catch (error) { return error?.code === 'ENOENT'; }
1465
+ }
1466
+
1467
+ /**
1468
+ * The SYNCHRONOUS proof the classifier may use: the recorded script is this
1469
+ * installation's own file.
1470
+ *
1471
+ * Both paths must be absolute and must be the same location under the platform's case
1472
+ * rules, so a Linux `…/DSH-Delegate-Mcp.js` is not this installation while a Windows
1473
+ * `…\DSH-DELEGATE-MCP.JS` is. A relative path names nothing and is never equal.
1474
+ * @param {string} candidate - recorded `args[0]`.
1475
+ * @param {string} installed - this installation's script.
1476
+ * @returns {boolean} true when the two names are the same absolute location.
1477
+ */
1478
+ function isExactInstalledScript(candidate, installed) {
1479
+ if (typeof candidate !== 'string' || typeof installed !== 'string') return false;
1480
+ const recorded = candidate.trim();
1481
+ if (recorded === '' || !isAbsolute(recorded)) return false;
1482
+ return samePlatformPath(recorded, installed, process.platform);
1483
+ }
1484
+
1485
+ /**
1486
+ * Compare two absolute paths with the PLATFORM's case rules.
1487
+ *
1488
+ * Windows path case is insignificant. Linux is always exact — two case variants are two
1489
+ * different programs there. macOS is treated like Windows because its default volumes
1490
+ * are case-insensitive; that is an ASSUMPTION about the volume, not a promise: a
1491
+ * case-sensitive macOS volume would make two case variants different files. The
1492
+ * adopted-install proof compares `realpath` results (which carry the on-disk spelling),
1493
+ * and the exact-path proof compares two strings derived from the same installation.
1494
+ * @param {string} left - first path.
1495
+ * @param {string} right - second path.
1496
+ * @param {string} [platform] - `process.platform` override for tests.
1497
+ * @returns {boolean} true when the paths name the same location on that platform.
1498
+ */
1499
+ export function samePlatformPath(left, right, platform = process.platform) {
1500
+ if (typeof left !== 'string' || typeof right !== 'string') return false;
1501
+ const normalize = (value) => {
1502
+ const slashed = value.trim().replace(/\\/gu, '/').replace(/\/+$/u, '');
1503
+ return platform === 'linux' ? slashed : slashed.toLowerCase();
1504
+ };
1505
+ return normalize(left) === normalize(right);
1506
+ }
1507
+
1508
+ /**
1509
+ * Does this manifest map its `dsh-delegate-mcp` bin entry to OUR entry file?
1510
+ *
1511
+ * The mapping is the second half of the package identity proof: a `name` alone can be
1512
+ * copied onto a same-layout wrapper, while a manifest that maps the published bin key to
1513
+ * `<root>/bin/dsh-delegate-mcp.js` (with nothing outside the root) is describing the
1514
+ * package this plugin ships. Only a relative in-package path is accepted — `./` is fine,
1515
+ * an absolute path or any `..` segment is not, and neither is a trailing slash.
1516
+ * @param {object} manifest - parsed `package.json`.
1517
+ * @param {string} rootDir - the package root the entry belongs to.
1518
+ * @returns {boolean} true when the mapping names that exact entry.
1519
+ */
1520
+ function doesManifestMapEntry(manifest, rootDir) {
1521
+ const bin = manifest.bin;
1522
+ if (bin === null || typeof bin !== 'object' || Array.isArray(bin)) return false;
1523
+ const declared = bin[MCP_BIN_NAME];
1524
+ if (typeof declared !== 'string' || declared.trim() === '') return false;
1525
+ const slashed = declared.trim().replace(/\\/gu, '/');
1526
+ if (slashed.endsWith('/')) return false;
1527
+ // A POSIX root, a Windows drive letter or a UNC path names a location that is not
1528
+ // relative to the package root at all.
1529
+ if (slashed.startsWith('/') || /^[A-Za-z]:/u.test(slashed)) return false;
1530
+ const segments = slashed.split('/');
1531
+ if (segments.some((segment) => segment === '..')) return false;
1532
+ const relative = segments.filter((segment) => segment !== '' && segment !== '.');
1533
+ if (relative.length === 0) return false;
1534
+ const mapped = resolve(rootDir, ...relative);
1535
+ return samePlatformPath(mapped, join(rootDir, MCP_ENTRY_RELATIVE), process.platform);
1536
+ }
1537
+
1538
+ /**
1539
+ * Is `script` a real entry point of another installation of THIS package?
1540
+ *
1541
+ * The proof is the package's own identity, read from the candidate's root — never a file
1542
+ * name, a suffix or a guess:
1543
+ *
1544
+ * * the path must be absolute and, after normalisation, name `<root>/bin/dsh-delegate-mcp.js`
1545
+ * with a package root below the filesystem root ({@link packageEntryRoot});
1546
+ * * `<root>`, `<root>/bin` and the entry must be real directories/regular files and not
1547
+ * links ({@link lstat} on each, plus the entry compared to the candidate by `realpath`);
1548
+ * * `<root>/package.json` must be a regular, non-link file that declares this package's
1549
+ * name AND maps its `dsh-delegate-mcp` bin key to that entry
1550
+ * ({@link doesManifestMapEntry}).
1551
+ *
1552
+ * A missing root, a root without that manifest, a manifest for another package or with a
1553
+ * wrong/missing/absolute/out-of-package bin mapping, an unreadable or linked path, or a
1554
+ * `bin/` that is a link is all "not provable" — and the caller refuses. Every filesystem
1555
+ * probe here is bounded and never throws.
1556
+ * @param {string} script - absolute candidate path.
1557
+ * @param {string} packageName - package name the root's manifest must declare.
1558
+ * @returns {Promise<boolean>} true only when the root is provably this package.
1559
+ */
1560
+ function isOwnPackageManifest(manifest, packageName) {
1561
+ // A rename must not adopt the unrelated public npm package with our old name.
1562
+ // All accepted identities need our repository provenance in addition to the existing
1563
+ // real-file and exact bin-mapping proof. Custom test identities stay exact.
1564
+ if (packageName !== PACKAGE_NAME) return manifest.name === packageName;
1565
+ if (!['dsh-taskbridge', 'dsh-taskdispatch', 'dsh-delegate'].includes(manifest.name)) return false;
1566
+ const repository = typeof manifest.repository === 'string'
1567
+ ? manifest.repository : manifest.repository?.url;
1568
+ if (typeof repository !== 'string') return false;
1569
+ try {
1570
+ const url = new URL(repository.replace(/^git\+/u, ''));
1571
+ if (url.protocol !== 'https:' || url.hostname !== 'github.com' || url.port
1572
+ || url.username || url.password || url.search || url.hash) return false;
1573
+ const path = url.pathname.replace(/\/$/u, '').replace(/\.git$/u, '');
1574
+ return ['/ranranyya/dsh-delegate', '/ranranyya/dsh-taskdispatch', '/ranranyya/dsh-taskbridge'].includes(path);
1575
+ } catch { return false; }
1576
+ }
1577
+
1578
+ async function isOtherInstallationOfThisPackage(script, packageName) {
1579
+ if (typeof script !== 'string' || !isAbsolute(script)) return false;
1580
+ // Normalise the spelling once: the proof is about the file the path names, and every
1581
+ // probe below must use the same components (`..`, duplicate separators).
1582
+ const normalized = resolve(script);
1583
+ const rootDir = packageEntryRoot(normalized);
1584
+ if (rootDir === null) return false;
1585
+ const binDir = join(rootDir, 'bin');
1586
+ const entry = join(binDir, 'dsh-delegate-mcp.js');
1587
+ const manifestPath = join(rootDir, 'package.json');
1588
+ try {
1589
+ // `<root>` and `<root>/bin` must be REAL directories: on Windows `lstat` reports a
1590
+ // junction as an ordinary directory, so the same attribute read the Codex boundary
1591
+ // uses is what proves it (an `unknown` answer is "cannot be proved", never "fine").
1592
+ const [rootKind, binKind] = await Promise.all([inspectDirectory(rootDir), inspectDirectory(binDir)]);
1593
+ if (rootKind.kind !== 'directory' || binKind.kind !== 'directory') return false;
1594
+ // The candidate must BE that file: a regular file, not a link, and the same file the
1595
+ // package's own `bin` entry names. `realpath` collapses any alias before comparing.
1596
+ const [candidateInfo, entryInfo, manifestInfo] = await Promise.all([
1597
+ lstat(normalized), lstat(entry), lstat(manifestPath),
1598
+ ]);
1599
+ if (!candidateInfo.isFile() || candidateInfo.isSymbolicLink()) return false;
1600
+ if (!entryInfo.isFile() || entryInfo.isSymbolicLink()) return false;
1601
+ if (!manifestInfo.isFile() || manifestInfo.isSymbolicLink()) return false;
1602
+ if (manifestInfo.size > MAX_CONFIG_BYTES) return false;
1603
+ const [realCandidate, realEntry] = await Promise.all([realpath(normalized), realpath(entry)]);
1604
+ if (!samePlatformPath(realCandidate, realEntry, process.platform)) return false;
1605
+ const manifest = JSON.parse(await readFile(manifestPath, 'utf8'));
1606
+ if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) return false;
1607
+ if (!isOwnPackageManifest(manifest, packageName)) return false;
1608
+ return doesManifestMapEntry(manifest, rootDir);
1609
+ } catch {
1610
+ // Anything unreadable, missing or malformed is "cannot be proved", never "assume ours".
1611
+ return false;
1612
+ }
1613
+ }
1614
+
1615
+
1616
+ /**
1617
+ * Recognize only the DSH Desktop executable name used by the 0.1.6 defect.
1618
+ *
1619
+ * The comparison is intentionally basename-only and case-insensitive so a Windows
1620
+ * path remains recognizable when the config is inspected on a different host. A
1621
+ * bare command or any other wrapper is not a migration candidate.
1622
+ * @param {string | null} command - parsed MCP command.
1623
+ * @returns {boolean} whether the command is the old DSH Desktop GUI executable.
1624
+ */
1625
+ function isLegacyDesktopCommand(command) {
1626
+ if (typeof command !== 'string' || command.trim() === '') return false;
1627
+ const value = command.trim();
1628
+ if (!/[/\\]/u.test(value)) return false;
1629
+ const name = value.replace(/^.*[/\\]/u, '').toLowerCase();
1630
+ return name === 'deepseek harness.exe';
1631
+ }
1632
+
1633
+ /**
1634
+ * Summarize which shape an entry has.
1635
+ * @param {Record<string, { type: string }>} values - assignment values keyed by relative path.
1636
+ * @returns {'stdio' | 'url' | 'missing-command' | 'unknown-field'} shape name.
1637
+ */
1638
+ function describeEntryShape(values) {
1639
+ const keys = Object.keys(values);
1640
+ if (keys.some((key) => key === 'url' || key === 'http_url' || key === 'bearer_token_env_var')) return 'url';
1641
+ if (values.command === undefined) return 'missing-command';
1642
+ if (values.command.type !== 'string') return 'command-not-a-string';
1643
+ if (values.args !== undefined && values.args.type !== 'array') return 'args-not-an-array';
1644
+ // `tool_timeout_sec` is an owned scalar: this plugin writes it so one
1645
+ // `delegate_wait` call can span the default 60-minute wait. A non-integer value is
1646
+ // not something this plugin writes, so the entry is somebody else's.
1647
+ if (values.tool_timeout_sec !== undefined && values.tool_timeout_sec.type !== 'integer') return 'timeout-not-an-integer';
1648
+ // `env` may be a table header (`env.KEY = …`) or an inline table; both unpack to
1649
+ // `env.*` keys, so both are accepted. Anything else is a field this plugin does
1650
+ // not own and must not silently drop.
1651
+ const allowed = new Set(['command', 'args', 'tool_timeout_sec']);
1652
+ for (const key of keys) {
1653
+ if (allowed.has(key)) continue;
1654
+ if (key.startsWith('env.')) continue;
1655
+ return 'unknown-field';
1656
+ }
1657
+ return 'stdio';
1658
+ }
1659
+
1660
+ /**
1661
+ * Split an inline table `{ … }` into raw value texts.
1662
+ *
1663
+ * Only used for classification. The editor never round-trips an inline table: it
1664
+ * rewrites the whole owned definition as a `[mcp_servers.dsh-delegate]` block.
1665
+ * @param {string} raw - inline table text.
1666
+ * @returns {Record<string, { type: string, text: string }>} values keyed by key path.
1667
+ */
1668
+ function parseInlineTable(raw) {
1669
+ const text = raw.trim();
1670
+ if (!text.startsWith('{') || !text.endsWith('}')) return {};
1671
+ const body = text.slice(1, -1);
1672
+ const values = {};
1673
+ let cursor = 0;
1674
+ while (cursor < body.length) {
1675
+ while (cursor < body.length && /[\s,]/u.test(body[cursor])) cursor += 1;
1676
+ if (cursor >= body.length) break;
1677
+ let keyText = '';
1678
+ if (body[cursor] === '"' || body[cursor] === "'") {
1679
+ const quote = body[cursor];
1680
+ const end = body.indexOf(quote, cursor + 1);
1681
+ if (end === -1) break;
1682
+ keyText = body.slice(cursor + 1, end);
1683
+ cursor = end + 1;
1684
+ } else {
1685
+ const start = cursor;
1686
+ while (cursor < body.length && /[A-Za-z0-9_.-]/u.test(body[cursor])) cursor += 1;
1687
+ keyText = body.slice(start, cursor);
1688
+ }
1689
+ while (cursor < body.length && (body[cursor] === ' ' || body[cursor] === '\t')) cursor += 1;
1690
+ if (body[cursor] !== '=') break;
1691
+ cursor += 1;
1692
+ while (cursor < body.length && (body[cursor] === ' ' || body[cursor] === '\t')) cursor += 1;
1693
+ const valueStart = cursor;
1694
+ let depth = 0;
1695
+ let quote = null;
1696
+ for (; cursor < body.length; cursor += 1) {
1697
+ const char = body[cursor];
1698
+ if (quote !== null) {
1699
+ if (quote === '"' && char === '\\') {
1700
+ cursor += 1;
1701
+ continue;
1702
+ }
1703
+ if (char === quote) quote = null;
1704
+ continue;
1705
+ }
1706
+ if (char === '"' || char === "'") {
1707
+ // An inline table may hold a nested table, but never a multi-line string.
1708
+ if (body.startsWith(char.repeat(3), cursor)) return values;
1709
+ quote = char;
1710
+ continue;
1711
+ }
1712
+ if (char === '[' || char === '{') depth += 1;
1713
+ else if (char === ']' || char === '}') depth -= 1;
1714
+ else if (char === ',' && depth === 0) break;
1715
+ }
1716
+ const rawValue = body.slice(valueStart, cursor).trim();
1717
+ values[keyText] = { type: tomlValueType(rawValue), text: rawValue };
1718
+ }
1719
+ return values;
1720
+ }
1721
+
1722
+ /**
1723
+ * Decode a TOML integer.
1724
+ *
1725
+ * Only the plain decimal form this plugin writes is accepted: a hex/octal literal, a
1726
+ * float, a quoted value or an expression is `null`, which the classifier treats as
1727
+ * "not a value this plugin wrote" rather than as a number it can compare.
1728
+ * @param {string | undefined} raw - raw value text.
1729
+ * @returns {number | null} the integer, or null.
1730
+ */
1731
+ function readIntegerValue(raw) {
1732
+ if (typeof raw !== 'string') return null;
1733
+ const text = raw.trim();
1734
+ if (!/^[+-]?\d+$/u.test(text)) return null;
1735
+ const value = Number(text);
1736
+ if (!Number.isSafeInteger(value)) return null;
1737
+ return value;
1738
+ }
1739
+
1740
+ /**
1741
+ * Decode a TOML basic or literal string.
1742
+ * @param {string | undefined} raw - raw value text.
1743
+ * @returns {string | null} decoded string, or null when it is not a string.
1744
+ */
1745
+ function readStringValue(raw) {
1746
+ if (typeof raw !== 'string') return null;
1747
+ const text = raw.trim();
1748
+ if (text.length < 2) return null;
1749
+ const quote = text[0];
1750
+ if ((quote !== '"' && quote !== "'") || text[text.length - 1] !== quote) return null;
1751
+ if (text.startsWith(quote.repeat(3))) return null;
1752
+ const inner = text.slice(1, -1);
1753
+ if (quote === "'") return inner;
1754
+ let out = '';
1755
+ for (let index = 0; index < inner.length; index += 1) {
1756
+ const char = inner[index];
1757
+ if (char !== '\\') {
1758
+ out += char;
1759
+ continue;
1760
+ }
1761
+ const next = inner[index + 1];
1762
+ index += 1;
1763
+ if (next === 'n') out += '\n';
1764
+ else if (next === 't') out += '\t';
1765
+ else if (next === 'r') out += '\r';
1766
+ else if (next === undefined) out += '\\';
1767
+ else out += next;
1768
+ }
1769
+ return out;
1770
+ }
1771
+
1772
+ /**
1773
+ * Decode a single-line TOML array of strings.
1774
+ * @param {string | undefined} raw - raw value text.
1775
+ * @returns {string[]} decoded strings; non-string elements are returned as `''`.
1776
+ */
1777
+ function readArrayValue(raw) {
1778
+ if (typeof raw !== 'string') return [];
1779
+ const inner = raw.trim().replace(/^\[/u, '').replace(/\]$/u, '');
1780
+ const out = [];
1781
+ let cursor = 0;
1782
+ while (cursor < inner.length) {
1783
+ while (cursor < inner.length && /[\s,]/u.test(inner[cursor])) cursor += 1;
1784
+ if (cursor >= inner.length) break;
1785
+ if (inner[cursor] === '"' || inner[cursor] === "'") {
1786
+ const quote = inner[cursor];
1787
+ let end = cursor + 1;
1788
+ let escaped = false;
1789
+ while (end < inner.length) {
1790
+ const char = inner[end];
1791
+ if (escaped) {
1792
+ escaped = false;
1793
+ end += 1;
1794
+ continue;
1795
+ }
1796
+ if (quote === '"' && char === '\\') {
1797
+ escaped = true;
1798
+ end += 1;
1799
+ continue;
1800
+ }
1801
+ if (char === quote) break;
1802
+ end += 1;
1803
+ }
1804
+ out.push(readStringValue(inner.slice(cursor, end + 1)) ?? '');
1805
+ cursor = end + 1;
1806
+ continue;
1807
+ }
1808
+ const start = cursor;
1809
+ while (cursor < inner.length && inner[cursor] !== ',') cursor += 1;
1810
+ out.push(inner.slice(start, cursor).trim());
1811
+ }
1812
+ return out;
1813
+ }
1814
+
1815
+ /**
1816
+ * Compare two string arrays element by element.
1817
+ * @param {string[]} left - first array.
1818
+ * @param {string[]} right - second array.
1819
+ * @returns {boolean} true when equal.
1820
+ */
1821
+ function sameStrings(left, right) {
1822
+ return left.length === right.length && left.every((value, index) => value === right[index]);
1823
+ }
1824
+
1825
+ /**
1826
+ * Render the managed `[mcp_servers.dsh-delegate]` block.
1827
+ * @param {object} desired - value from {@link desiredMcpCommand}.
1828
+ * @returns {string[]} lines.
1829
+ */
1830
+ function renderMcpBlock(desired) {
1831
+ const lines = [
1832
+ MCP_MARKER,
1833
+ `[${renderKey(['mcp_servers', MCP_SERVER_NAME])}]`,
1834
+ `command = ${renderString(desired.command)}`,
1835
+ `args = ${renderStringArray(desired.args)}`,
1836
+ // One `delegate_wait` call may legitimately hold for the 60-minute default, so
1837
+ // Codex must allow this entry to run that long. Written on THIS server only.
1838
+ `tool_timeout_sec = ${String(desired.toolTimeoutSec)}`,
1839
+ ];
1840
+ const envKeys = Object.keys(desired.env).sort();
1841
+ for (const key of envKeys) {
1842
+ lines.push(`env.${renderKey([key])} = ${renderString(desired.env[key])}`);
1843
+ }
1844
+ return lines;
1845
+ }
1846
+
1847
+ /**
1848
+ * Apply the managed MCP entry to a config document, preserving everything else.
1849
+ *
1850
+ * Two edits are possible and both are minimal:
1851
+ * * the entry is absent — a marked block is appended at the end;
1852
+ * * the entry exists and is *ours* but stale — the `command`/`args`/managed `env`
1853
+ * values are replaced in place, so a user's surrounding layout survives.
1854
+ * @param {TomlDocument} document - parsed config.
1855
+ * @param {object} desired - desired command.
1856
+ * @param {{ state: string }} classification - current state.
1857
+ * @returns {string | null} the next document text, or null when the document already
1858
+ * matches what this build would write (so the caller writes nothing).
1859
+ */
1860
+ export function applyMcpEntry(document, desired, classification) {
1861
+ const serverPath = ['mcp_servers', MCP_SERVER_NAME];
1862
+ const before = document.text;
1863
+ if (classification.state === MCP_STATES.missing) {
1864
+ document.appendBlock(renderMcpBlock(desired));
1865
+ return document.text === before ? null : document.text;
1866
+ }
1867
+ if (classification.state !== MCP_STATES.configured && classification.state !== MCP_STATES.outdated) {
1868
+ // Only a definition proved to be ours is ever rewritten; the caller reports the
1869
+ // conflict instead of asking for an edit.
1870
+ throw new CodexInstallError(
1871
+ 'MCP_ENTRY_CONFLICT',
1872
+ 'the mcp_servers.dsh-delegate entry is not one this plugin manages and was left untouched',
1873
+ { reason: classification.reason ?? classification.state },
1874
+ );
1875
+ }
1876
+ // Existing and ours (possibly stale): rewrite the owned values in place, and add
1877
+ // anything this build now needs that is absent. A configured entry needs nothing.
1878
+ if (classification.state === MCP_STATES.configured) return null;
1879
+ const inline = document.assignmentAt(serverPath);
1880
+ if (inline !== undefined) {
1881
+ // The inline spelling cannot absorb an `env` table header, so the owned
1882
+ // definition is rewritten in block form. The marker above it is replaced with a
1883
+ // single copy of itself, so the proof of ownership survives exactly once.
1884
+ const markerLine = document.isMarkerLine(inline.startLine - 1, MCP_MARKER) ? inline.startLine - 1 : inline.startLine;
1885
+ document.replaceLines(markerLine, inline.endLine, renderMcpBlock(desired));
1886
+ return document.text;
1887
+ }
1888
+ const block = renderMcpBlock(desired);
1889
+ const blockValue = (key) => {
1890
+ const line = block.find((candidate) => candidate.startsWith(`${key} =`));
1891
+ return line === undefined ? null : line.slice(line.indexOf('=') + 1).trim();
1892
+ };
1893
+ for (const key of ['command', 'args', 'tool_timeout_sec']) {
1894
+ const value = blockValue(key);
1895
+ const entry = document.assignmentAt([...serverPath, key]);
1896
+ if (entry !== undefined && value !== null && entry.raw !== value) document.replaceValue(entry, value);
1897
+ }
1898
+ // An entry written before this field existed has no `tool_timeout_sec` at all, so
1899
+ // it is added inside the owned table, directly after the args line when that line
1900
+ // is present and otherwise after the header. Never appended at the end of the
1901
+ // document, where it could land under a different table.
1902
+ if (document.assignmentAt([...serverPath, 'tool_timeout_sec']) === undefined) {
1903
+ const line = `tool_timeout_sec = ${String(desired.toolTimeoutSec)}`;
1904
+ const argsEntry = document.assignmentAt([...serverPath, 'args']);
1905
+ if (argsEntry !== undefined) {
1906
+ document.replaceLines(argsEntry.endLine + 1, argsEntry.endLine, [line]);
1907
+ } else {
1908
+ const headerIndex = document.entries.findIndex(
1909
+ (candidate) => candidate.kind !== 'assignment' && samePath(candidate.path, serverPath),
1910
+ );
1911
+ const insertAt = headerIndex === -1 ? document.lines.length : document.entries[headerIndex].endLine + 1;
1912
+ document.replaceLines(insertAt, insertAt - 1, [line]);
1913
+ }
1914
+ }
1915
+ for (const [key, value] of Object.entries(desired.env)) {
1916
+ const entry = document.assignmentAt([...serverPath, 'env', key]);
1917
+ if (entry === undefined) {
1918
+ // Append inside the owned table, directly after its header, so the new line
1919
+ // cannot land inside a different table.
1920
+ const headerIndex = document.entries.findIndex(
1921
+ (candidate) => candidate.kind !== 'assignment' && samePath(candidate.path, serverPath),
1922
+ );
1923
+ const insertAt = headerIndex === -1 ? document.lines.length : document.entries[headerIndex].endLine + 1;
1924
+ document.replaceLines(insertAt, insertAt - 1, [`env.${renderKey([key])} = ${renderString(value)}`]);
1925
+ } else {
1926
+ document.replaceValue(entry, renderString(value));
1927
+ }
1928
+ }
1929
+ return document.text === before ? null : document.text;
1930
+ }
1931
+
1932
+ /**
1933
+ * Remove the managed `mcp_servers.dsh-delegate` definition from a document.
1934
+ *
1935
+ * Only reachable for a definition the classifier proved is ours. The removed range
1936
+ * is the table header, its assignments and its child tables, plus the plugin marker
1937
+ * line and nothing else: a comment block the operator wrote above the marker stays,
1938
+ * because it may describe their own settings. A blank line left behind by the
1939
+ * removal is collapsed by {@link TomlDocument#removeLines}, and the document keeps
1940
+ * its original line endings.
1941
+ * @param {TomlDocument} document - parsed config.
1942
+ * @returns {{ text: string, removed: boolean }} next text and whether anything was removed.
1943
+ */
1944
+ export function removeMcpEntry(document) {
1945
+ const { inline, headerIndex, marker } = locateMcpDefinition(document);
1946
+ if (marker === null) {
1947
+ // Nothing proved as ours: refuse rather than guess by name.
1948
+ return { text: document.text, removed: false };
1949
+ }
1950
+ if (inline !== undefined) {
1951
+ const startLine = document.isMarkerLine(inline.startLine - 1, MCP_MARKER) ? inline.startLine - 1 : inline.startLine;
1952
+ document.removeLines(startLine, inline.endLine);
1953
+ return { text: document.text, removed: true };
1954
+ }
1955
+ if (headerIndex === -1) return { text: document.text, removed: false };
1956
+ const range = document.markedTableRange(headerIndex, MCP_MARKER);
1957
+ document.removeLines(range.startLine, range.endLine);
1958
+ return { text: document.text, removed: true };
1959
+ }
1960
+
1961
+ /**
1962
+ * Render the agent file from the shipped template plus this package's version.
1963
+ * @param {string} template - shipped template.
1964
+ * @param {string} version - package version.
1965
+ * @returns {string} file contents.
1966
+ */
1967
+ export function renderAgentFile(template, version) {
1968
+ const marker = `version = ${renderString(version)}`;
1969
+ if (/^version = ".*"$/mu.test(template)) return template.replace(/^version = ".*"$/mu, marker);
1970
+ // Keep the provenance header first, then the version marker, then the rest.
1971
+ const lines = template.split('\n');
1972
+ const insertAt = lines.findIndex((line) => line.trim() !== '' && !line.trimStart().startsWith('#'));
1973
+ const resolved = insertAt === -1 ? lines.length : insertAt;
1974
+ lines.splice(resolved, 0, marker);
1975
+ return lines.join('\n');
1976
+ }
1977
+
1978
+ /**
1979
+ * Read and parse the Codex config, or return an empty document.
1980
+ * @param {string} configPath - config file path.
1981
+ * @returns {Promise<{ document: TomlDocument, exists: boolean, unreadable: boolean }>} parsed config.
1982
+ * @throws {CodexInstallError} `CODEX_CONFIG_UNREADABLE`, `CODEX_CONFIG_UNSUPPORTED`, `CODEX_CONFIG_TOO_LARGE`.
1983
+ */
1984
+ async function loadConfig(configPath) {
1985
+ const existing = await inspectFile(configPath);
1986
+ if (existing.kind === 'missing') return { document: new TomlDocument(''), exists: false, unreadable: false };
1987
+ if (existing.kind === 'other') {
1988
+ return { document: new TomlDocument(''), exists: true, unreadable: true };
1989
+ }
1990
+ try {
1991
+ return { document: new TomlDocument(existing.contents), exists: true, unreadable: false };
1992
+ } catch (error) {
1993
+ if (error instanceof TomlSyntaxError) {
1994
+ throw new CodexInstallError(
1995
+ 'CODEX_CONFIG_UNSUPPORTED',
1996
+ `Codex config.toml could not be read reliably (${error.message}); nothing was changed`,
1997
+ { line: error.line },
1998
+ );
1999
+ }
2000
+ throw error;
2001
+ }
2002
+ }
2003
+
2004
+ /**
2005
+ * Read the Codex state without writing anything.
2006
+ * @param {object} options - `codexHome`, `env`, `discoveryFile`, `version`, `hostNode`.
2007
+ * `hostNode` is an optional object of *host facts* (`execPath`, `resourcesPath`,
2008
+ * `versions`, `platform`) for a host being described rather than the running
2009
+ * process; the action's `env` still supplies `DSH_NODE_PATH` and the other
2010
+ * overrides. It exists so a host integration — and a test proving the desktop
2011
+ * behaviour — can state the process facts instead of mutating them.
2012
+ * @returns {Promise<object>} a status report.
2013
+ */
2014
+ export async function readCodexStatus({
2015
+ codexHome = null,
2016
+ env = process.env,
2017
+ discoveryFile,
2018
+ version = null,
2019
+ hostNode = null,
2020
+ } = {}) {
2021
+ const home = codexHome === null ? resolveCodexHome({ env }) : requireCodexHome(codexHome);
2022
+ const agentPath = join(home, 'agents', AGENT_FILENAME);
2023
+ const configPath = join(home, 'config.toml');
2024
+ const packageVersionValue = version ?? await readPackageVersion();
2025
+ const template = renderAgentFile(await readAgentTemplate(), packageVersionValue);
2026
+ // The boundary first: a link at the Codex home or at `agents` means the agent path
2027
+ // does not name a file this plugin may touch, whatever `lstat` would say about it.
2028
+ const boundary = await inspectCodexBoundary(home);
2029
+ const agent = boundary.blocked
2030
+ ? {
2031
+ state: AGENT_STATES.conflict,
2032
+ present: false,
2033
+ reason: boundary.unknown === true
2034
+ ? 'boundary-unverified'
2035
+ : boundary.link === 'codex-home' ? 'codex-home-is-link' : 'agents-dir-is-link',
2036
+ contents: null,
2037
+ }
2038
+ : await readAgentState(agentPath, template);
2039
+ const script = await resolveMcpScript();
2040
+ // A host with no provable Node.js runtime is a *reported* state, not a thrown
2041
+ // failure: the status still describes the agent file and the operator needs the
2042
+ // diagnosis, while every action refuses the MCP write (`MCP_EXECUTABLE_UNRESOLVED`)
2043
+ // instead of writing a command it could not prove.
2044
+ let node = null;
2045
+ let nodeError = null;
2046
+ try {
2047
+ // `hostNode` states the *host facts* (`execPath`, `resourcesPath`, `versions`,
2048
+ // `platform`) of a host this call is asking about; the environment is never
2049
+ // overridden by it, because `DSH_NODE_PATH` and friends are operator data that
2050
+ // travel in `env`, exactly like `CODEX_HOME` does.
2051
+ node = hostNode === null
2052
+ ? resolveNodeExecutable()
2053
+ : resolveNodeExecutable({ ...hostNode, env: hostNode.env ?? env });
2054
+ } catch (error) {
2055
+ if (!(error instanceof CodexInstallError)) throw error;
2056
+ nodeError = { code: error.code, message: error.message, details: error.details ?? {} };
2057
+ }
2058
+ const discovery = discoveryPin(discoveryFile ?? defaultDiscoveryPath(env), env);
2059
+ // With no executable there is nothing to register: `desired` is `null`, every
2060
+ // classification that needs it is short-circuited below, and install/repair refuse.
2061
+ const desired = node === null
2062
+ ? null
2063
+ : desiredMcpCommand({ node, script: script.script, discoveryFile: discovery.path, pinDiscovery: discovery.pin });
2064
+
2065
+ let mcp = { state: MCP_STATES.unreadable, previous: null, reason: null, ownedValues: {}, marked: false, drift: null };
2066
+ let configError = null;
2067
+ let configPathInfo = { exists: false };
2068
+ /**
2069
+ * SHA-256 of the whole config document this status classified, or null.
2070
+ *
2071
+ * This is the plan's receipt: the automatic upgrade records it and re-checks it before
2072
+ * writing, so a file changed between the check and the write is refused instead of
2073
+ * overwritten. Only the digest is kept — never the text — so no config content,
2074
+ * comment or credential can leave through a status response.
2075
+ */
2076
+ let configFingerprint = null;
2077
+ if (boundary.blocked) {
2078
+ // A link (or an unverifiable directory) at `$CODEX_HOME` or `$CODEX_HOME/agents`
2079
+ // bounds EVERY write this module makes, not only the agent file. The MCP entry is
2080
+ // described by the same verdict instead of by a read-through of the link: reporting
2081
+ // it as `outdated` from inside the linked tree, and then refusing to write, is how a
2082
+ // link would have been followed for a READ. Nothing below the boundary is examined.
2083
+ mcp = {
2084
+ state: MCP_STATES.conflict,
2085
+ previous: null,
2086
+ reason: boundary.unknown === true ? 'boundary-unverified'
2087
+ : (boundary.link === 'codex-home' ? 'codex-home-is-link' : 'agents-dir-is-link'),
2088
+ ownedValues: {},
2089
+ marked: false,
2090
+ drift: null,
2091
+ };
2092
+ } else {
2093
+ try {
2094
+ const loaded = await loadConfig(configPath);
2095
+ configPathInfo = { exists: loaded.exists };
2096
+ // The fingerprint of the WHOLE document this plan was derived from. It is what the
2097
+ // write path re-checks before replacing the file: re-classifying the entry is not
2098
+ // enough, because an owned value can change while the entry still looks stale and
2099
+ // managed. Only the digest is kept — never the file text — so no config content or
2100
+ // credential can travel in a status response.
2101
+ configFingerprint = loaded.unreadable === true ? null : digest(loaded.document.text);
2102
+ if (loaded.unreadable) {
2103
+ configError = { code: 'CODEX_CONFIG_UNREADABLE', message: 'config.toml is not a regular file this plugin may edit' };
2104
+ } else if (desired === null) {
2105
+ // The executable is the subject of this read's refusal, so the entry is not
2106
+ // classified against a command that does not exist.
2107
+ mcp = { state: MCP_STATES.unreadable, previous: null, reason: 'no-executable', ownedValues: {}, marked: false, drift: null };
2108
+ } else {
2109
+ mcp = classifyMcpEntry(loaded.document, desired);
2110
+ }
2111
+ } catch (error) {
2112
+ configError = {
2113
+ code: typeof error?.code === 'string' ? error.code : 'CODEX_CONFIG_UNREADABLE',
2114
+ message: error?.message ?? 'the Codex config could not be read',
2115
+ };
2116
+ }
2117
+ }
2118
+
2119
+ return buildStatus({
2120
+ codexHome: home,
2121
+ agentPath,
2122
+ configPath,
2123
+ packageVersionValue,
2124
+ agent,
2125
+ mcp,
2126
+ desired,
2127
+ script,
2128
+ node,
2129
+ nodeError,
2130
+ discovery,
2131
+ configPathInfo,
2132
+ configError,
2133
+ boundary,
2134
+ configFingerprint,
2135
+ });
2136
+ }
2137
+
2138
+ /**
2139
+ * The default discovery file, resolved the same way the MCP process resolves it.
2140
+ * @param {Record<string, string | undefined>} env - environment.
2141
+ * @returns {string} absolute path.
2142
+ */
2143
+ function defaultDiscoveryPath(env) {
2144
+ const configured = typeof env.DSH_HOME === 'string' ? env.DSH_HOME.trim() : '';
2145
+ const dshHome = configured === '' ? join(homedir(), '.dsh') : configured;
2146
+ return join(resolve(dshHome), 'data', 'dsh-delegate', 'runtime-endpoint.json');
2147
+ }
2148
+
2149
+ /**
2150
+ * Compose the status payload the settings page renders.
2151
+ * @param {object} parts - collected facts.
2152
+ * @returns {object} plain JSON status document.
2153
+ */
2154
+ function buildStatus({
2155
+ codexHome,
2156
+ agentPath,
2157
+ configPath,
2158
+ packageVersionValue,
2159
+ agent,
2160
+ mcp,
2161
+ desired,
2162
+ script,
2163
+ node,
2164
+ nodeError = null,
2165
+ discovery,
2166
+ configPathInfo,
2167
+ configError,
2168
+ boundary = null,
2169
+ configFingerprint = null,
2170
+ }) {
2171
+ const agentOk = agent.state === AGENT_STATES.installed;
2172
+ const mcpOk = mcp.state === MCP_STATES.configured;
2173
+ return {
2174
+ codexHome,
2175
+ packageVersion: packageVersionValue,
2176
+ // Whether the two directories that bound every write are real directories. A link
2177
+ // at either one is a stable diagnosis, not an installation state: install, repair
2178
+ // and remove all refuse while `blocked` is true.
2179
+ boundary: boundary === null
2180
+ ? { blocked: false, link: null, unknown: false, home: 'unknown', agents: 'unknown' }
2181
+ : {
2182
+ blocked: boundary.blocked === true,
2183
+ link: boundary.blocked === true ? boundary.link : null,
2184
+ unknown: boundary.unknown === true,
2185
+ home: boundary.home.kind,
2186
+ agents: boundary.agents.kind,
2187
+ },
2188
+ agent: {
2189
+ path: agentPath,
2190
+ state: agent.state,
2191
+ // Stated once here so no caller has to infer it from a state name.
2192
+ installed: agentOk,
2193
+ managed: agent.state !== AGENT_STATES.conflict && agent.state !== AGENT_STATES.modified,
2194
+ reason: agent.reason ?? null,
2195
+ // The exact bytes a refresh is allowed to replace. Internal: `installManaged`
2196
+ // re-reads the file and compares against this immediately before its rename, so
2197
+ // a file edited between the status read and the write is never replaced.
2198
+ expect: agent.contents ?? null,
2199
+ },
2200
+ mcp: {
2201
+ path: configPath,
2202
+ exists: configPathInfo.exists === true,
2203
+ serverName: MCP_SERVER_NAME,
2204
+ state: mcp.state,
2205
+ configured: mcpOk,
2206
+ previous: mcp.previous,
2207
+ reason: mcp.reason,
2208
+ // WHICH owned facts are stale, as a list of stable names (`tool_timeout_sec`,
2209
+ // `args`, `command`, `env`) — or null when nothing is stale. A state name alone
2210
+ // ("outdated") does not tell an operator, or the panel, what would change.
2211
+ drift: mcp.drift ?? null,
2212
+ // The digest of the whole config this classification was derived from. It travels
2213
+ // with the status only so the write path can prove the file has not changed since;
2214
+ // `publicCodexStatus` strips it, and it is a hash, never the text.
2215
+ fingerprint: configFingerprint,
2216
+ // True only when the entry carries the plugin marker, i.e. when a later
2217
+ // `remove` may delete it. Values alone never establish ownership.
2218
+ marked: mcp.marked === true,
2219
+ // `null` when no Node.js executable could be proved; `resolved: false` says so
2220
+ // explicitly so a consumer never has to test for `null` alone.
2221
+ desired,
2222
+ node,
2223
+ nodeResolved: node !== null,
2224
+ // Why the executable could not be resolved (`MCP_EXECUTABLE_UNRESOLVED`), or
2225
+ // null. The app executable is never substituted for it.
2226
+ nodeError,
2227
+ script: script.script,
2228
+ scriptExists: script.exists,
2229
+ // Only written to the file when DSH uses a non-default location.
2230
+ discoveryFile: discovery.path,
2231
+ discoveryPinned: discovery.pin,
2232
+ },
2233
+ config: configError === null
2234
+ ? { readable: true, error: null }
2235
+ : { readable: false, error: configError },
2236
+ ready: agentOk && mcpOk && configError === null && node !== null,
2237
+ // What this action cannot do, stated where the operator sees the result.
2238
+ notes: buildNotes({ agent, mcp, script, configError, nodeError }),
2239
+ };
2240
+ }
2241
+
2242
+ /**
2243
+ * Operator-facing limitations of the current state.
2244
+ * @param {object} parts - collected facts.
2245
+ * @returns {object[]} `[{ code, text }]`.
2246
+ */
2247
+ function buildNotes({ agent, mcp, script, configError, nodeError = null }) {
2248
+ const notes = [];
2249
+ if (agent.state === AGENT_STATES.modified) {
2250
+ notes.push({
2251
+ code: 'AGENT_USER_MODIFIED',
2252
+ text: `已存在内容不同的 agents/${AGENT_FILENAME},本插件不会覆盖或删除它;如需插件版本请先自行移动该文件。`,
2253
+ });
2254
+ }
2255
+ if (agent.state === AGENT_STATES.conflict) {
2256
+ // `AGENT_PATH_CONFLICT` covers two different physical situations, and the
2257
+ // operator needs to know which one: a link on the way to the file (home or
2258
+ // `agents/`), or a final path that is not a regular file (a link, a directory).
2259
+ const text = agent.reason === 'codex-home-is-link'
2260
+ ? `Codex home 本身是链接(符号链接或 Windows reparse point/junction),本插件不会穿过它写入或删除 agents/${AGENT_FILENAME}。`
2261
+ : agent.reason === 'agents-dir-is-link'
2262
+ ? `agents 目录是链接(符号链接或 Windows reparse point/junction),本插件不会穿过它写入或删除 ${AGENT_FILENAME}。`
2263
+ : agent.reason === 'boundary-unverified'
2264
+ ? 'Codex home 或 agents 目录无法确认是真实目录(可能缺少 Windows PowerShell),本插件不会写入或删除任何文件。'
2265
+ : `agents/${AGENT_FILENAME} 不是普通文件(可能是链接或目录),本插件不会改动它。`;
2266
+ notes.push({ code: 'AGENT_PATH_CONFLICT', text });
2267
+ }
2268
+ if (agent.state === AGENT_STATES.outdated) {
2269
+ notes.push({ code: 'AGENT_OUTDATED', text: '已安装的 agent 是旧版本(与某个已发布版本逐字节相同)。插件下次启动时会自动刷新为当前版本;也可以点「安装 / 更新 Codex 集成」立即更新。' });
2270
+ }
2271
+ if (mcp.state === MCP_STATES.conflict) {
2272
+ notes.push({
2273
+ code: 'MCP_ENTRY_CONFLICT',
2274
+ text: mcp.reason === 'unmanaged-entry'
2275
+ ? `config.toml 中已有同名的 mcp_servers.${MCP_SERVER_NAME} 条目,但没有本插件的托管标记注释,视为你自己写的:本插件不会更新或删除它;请自行删除或改名后再点安装。`
2276
+ : (mcp.reason === 'args-shape-not-ours'
2277
+ ? `config.toml 中已有的 mcp_servers.${MCP_SERVER_NAME} 条目带托管标记,但入口脚本与当前安装不同。若那是本插件的另一处真实安装,点「安装 / 更新 Codex 集成」或「仅修复 MCP 配置」会在证明后采纳;否则本插件不会替换它。`
2278
+ : `config.toml 中已有同名的 mcp_servers.${MCP_SERVER_NAME} 条目,但内容不是本插件写入的形态(${mcp.reason ?? 'unknown'})。本插件不会替换它;请自行删除或改名后再点安装。`),
2279
+ });
2280
+ }
2281
+ if (mcp.state === MCP_STATES.outdated) {
2282
+ // Stated per stale owned fact, because "outdated" alone does not tell an operator
2283
+ // what will change. A missing `tool_timeout_sec` is the core startup migration. (`args`
2284
+ // drift cannot reach this state any more — a differing script is a `conflict` that only
2285
+ // an explicit install/repair may adopt — but the branch is kept truthful for any path
2286
+ // that still reports it.)
2287
+ const drift = Array.isArray(mcp.drift) ? mcp.drift : [];
2288
+ const reasons = [];
2289
+ if (drift.includes('tool_timeout_sec')) {
2290
+ reasons.push(`缺少或不是托管条目应写入的 tool_timeout_sec = ${String(DELEGATE_TOOL_TIMEOUT_SEC)}(客户端可能因此更早结束一次长时间等待;该字段只是请求客户端放宽,客户端自身的超时限制仍然有效)`);
2291
+ }
2292
+ if (drift.includes('args')) reasons.push('入口脚本路径已不是当前安装位置(需用显式安装/修复证明后采纳;启动自检不会改写)');
2293
+ if (drift.includes('command')) reasons.push('command 仍是旧版写下的桌面程序路径');
2294
+ if (drift.includes('env')) reasons.push(`其 env.${DISCOVERY_ENV_VAR} 与当前发现文件不一致`);
2295
+ notes.push({
2296
+ code: 'MCP_ENTRY_OUTDATED',
2297
+ text: `已安装的 mcp_servers.${MCP_SERVER_NAME} 是本插件写入的托管条目,但已经过期:${reasons.length === 0 ? '需要更新' : reasons.join(';')}。插件下次启动时会自动在原地更新它;也可以点「安装 / 更新 Codex 集成」立即更新。`,
2298
+ });
2299
+ }
2300
+ if (configError !== null) {
2301
+ notes.push({ code: configError.code, text: `无法安全读取 config.toml:${configError.message}` });
2302
+ }
2303
+ if (nodeError !== null) {
2304
+ // The exact defect this release fixes: the desktop application executable must
2305
+ // never become the MCP command, so "no Node runtime" is a stated refusal.
2306
+ notes.push({
2307
+ code: 'MCP_EXECUTABLE_UNRESOLVED',
2308
+ text: '无法确定可用的 Node.js 可执行文件(桌面应用自身的 exe 不会被写入 Codex 配置,裸 node 也不会)。'
2309
+ + `请把 ${MCP_NODE_ENV_VARS[0]} 设为 node 可执行文件的绝对路径后重启 DSH;在此之前 MCP 条目不会被写入。`,
2310
+ });
2311
+ }
2312
+ if (!script.exists) {
2313
+ notes.push({ code: 'MCP_SCRIPT_MISSING', text: '包内未找到 bin/dsh-delegate-mcp.js,无法注册成可用的 MCP 入口。' });
2314
+ }
2315
+ return notes;
2316
+ }
2317
+
2318
+ /**
2319
+ * Perform one explicit operator action.
2320
+ *
2321
+ * The four actions have deliberately different write sets, and `repair` is the one an
2322
+ * operator reaches for when only the MCP registration looks wrong:
2323
+ *
2324
+ * * `status` — reads only;
2325
+ * * `install` — writes the agent file (when it is absent, or a byte-exact known
2326
+ * prior build of it) **and** the owned MCP entry;
2327
+ * * `repair` — the MCP entry only. It never creates, refreshes or deletes the
2328
+ * agent file, so a missing or outdated agent is reported by the returned status
2329
+ * and left exactly as it was. This is the contract the settings page's
2330
+ * “仅修复 MCP 配置” button and `docs/codex-integration.md` state;
2331
+ * * `remove` — deletes only an unchanged managed agent file and only an MCP entry
2332
+ * this plugin still owns.
2333
+ *
2334
+ * Every action ends by returning a fresh status report, so the page never has to
2335
+ * guess what happened.
2336
+ * @param {string} action - one of {@link CODEX_ACTIONS}.
2337
+ * @param {object} options - `codexHome`, `env`, `discoveryFile`, `version`, `hostNode`.
2338
+ * @returns {Promise<{ action: string, changed: string[], refused: object[], status: object }>} outcome.
2339
+ * @throws {CodexInstallError} on invalid arguments.
2340
+ */
2341
+ export async function runCodexAction(action, {
2342
+ codexHome = null,
2343
+ env = process.env,
2344
+ discoveryFile,
2345
+ version = null,
2346
+ hostNode = null,
2347
+ } = {}) {
2348
+ if (!CODEX_ACTIONS.includes(action)) {
2349
+ throw new CodexInstallError('CODEX_ACTION_INVALID', `unknown Codex action ${JSON.stringify(action)}`);
2350
+ }
2351
+ // An explicit home must be absolute; otherwise the environment decides, and a
2352
+ // relative `CODEX_HOME` is refused there rather than resolved against the cwd.
2353
+ if (codexHome !== null && (typeof codexHome !== 'string' || codexHome.trim() === '' || !isAbsolute(codexHome))) {
2354
+ throw new CodexInstallError('CODEX_HOME_INVALID', 'the Codex home must be an absolute path');
2355
+ }
2356
+ const home = codexHome === null ? resolveCodexHome({ env }) : requireCodexHome(codexHome);
2357
+ if (action === 'status') {
2358
+ const status = await readCodexStatus({ codexHome: home, env, discoveryFile, version, hostNode });
2359
+ return { action, changed: [], refused: [], status };
2360
+ }
2361
+
2362
+ const before = await readCodexStatus({ codexHome: home, env, discoveryFile, version, hostNode });
2363
+ /** @type {string[]} */
2364
+ const changed = [];
2365
+ /** @type {object[]} */
2366
+ const refused = [];
2367
+
2368
+ // Re-prove the boundary immediately before writing. The status document was read a
2369
+ // moment ago and a link can have replaced the home or `agents/` since; that link is
2370
+ // refused here instead of being followed by `mkdir` or the exclusive create below.
2371
+ const linked = before.boundary?.blocked === true
2372
+ ? linkedBoundaryRefusal(before)
2373
+ : null;
2374
+ if (linked !== null) {
2375
+ refused.push(linked);
2376
+ return { action, changed, refused, status: before };
2377
+ }
2378
+
2379
+ if (action === 'remove') {
2380
+ await removeManaged(before, { changed, refused });
2381
+ await migrateLegacyAgent(before, { changed, refused }, { removeOnly: true });
2382
+ } else if (action === 'repair') {
2383
+ // MCP only: the agent file is not touched at all — not created, not refreshed,
2384
+ // not deleted. The returned status still reports its real (possibly `not-installed`
2385
+ // or `outdated`) state, so the page can tell the operator to run `install`.
2386
+ await installMcpEntry(before, { changed, refused });
2387
+ } else {
2388
+ await installManaged(before, { changed, refused });
2389
+ }
2390
+
2391
+ const status = await readCodexStatus({ codexHome: home, env, discoveryFile, version, hostNode });
2392
+ return { action, changed, refused, status };
2393
+ }
2394
+
2395
+ /**
2396
+ * Install the managed files: the agent file, then the MCP entry.
2397
+ *
2398
+ * Only `install` reaches this. `repair` calls {@link installMcpEntry} directly so it
2399
+ * cannot create or refresh an agent as a side effect.
2400
+ * @param {object} before - status read before the change.
2401
+ * @param {{ changed: string[], refused: object[] }} outcome - mutable outcome.
2402
+ * @returns {Promise<void>} resolves after both targets were attempted.
2403
+ */
2404
+ async function installManaged(before, outcome) {
2405
+ await installManagedAgent(before, outcome);
2406
+ await migrateLegacyAgent(before, outcome);
2407
+ await installMcpEntry(before, outcome);
2408
+ }
2409
+
2410
+ /** Move a previously installed, unchanged companion to the public TaskBridge name. */
2411
+ async function migrateLegacyAgent(before, outcome, { removeOnly = false } = {}) {
2412
+ const legacyPath = join(before.codexHome, 'agents', LEGACY_AGENT_FILENAME);
2413
+ const legacy = await inspectFile(legacyPath);
2414
+ if (legacy.kind !== 'file' || !isKnownPriorTemplate(legacy.contents)) return;
2415
+ if (!removeOnly) {
2416
+ if (before.agent.state === AGENT_STATES.missing) {
2417
+ const current = await inspectFile(before.agent.path);
2418
+ if (current.kind === 'missing') await installManagedAgent(before, outcome);
2419
+ }
2420
+ const template = renderAgentFile(await readAgentTemplate(), before.packageVersion);
2421
+ const current = await inspectFile(before.agent.path);
2422
+ if (current.kind !== 'file' || current.contents !== template) return;
2423
+ }
2424
+ const currentLegacy = await inspectFile(legacyPath);
2425
+ if (currentLegacy.kind !== 'file' || currentLegacy.contents !== legacy.contents) return;
2426
+ await unlink(legacyPath);
2427
+ if (!outcome.changed.includes('agent')) outcome.changed.push('agent');
2428
+ }
2429
+
2430
+ /**
2431
+ * Refresh only an agent file whose complete bytes match a known shipped template.
2432
+ *
2433
+ * This is called during plugin activation so a plugin upgrade can migrate a
2434
+ * previously shipped agent automatically. It never creates a missing file and
2435
+ * never touches config.toml, unless `refreshMcp` is true; all replacement writes
2436
+ * still re-prove the exact bytes immediately before the atomic rename.
2437
+ * @param {object} options - same Codex home and version options as the status reader,
2438
+ * plus `refreshMcp`: also upgrade an OUTDATED managed MCP entry (see
2439
+ * {@link refreshManagedIntegration}); `backupDir`: where a pre-write copy is kept;
2440
+ * `plan`: a status document captured EARLIER, used instead of a fresh read. The plan
2441
+ * seam exists so the check-then-write window can be tested deterministically: the
2442
+ * write path must refuse a file that no longer matches the plan's digest.
2443
+ * @returns {Promise<{ changed: string[], refused: object[], status: object }>} migration result.
2444
+ */
2445
+ export async function refreshKnownAgentTemplate(options = {}) {
2446
+ const {
2447
+ codexHome = null, env = process.env, discoveryFile, version = null, hostNode = null, refreshMcp = false,
2448
+ backupDir = null, plan = null,
2449
+ } = options;
2450
+ if (codexHome !== null && (typeof codexHome !== 'string' || codexHome.trim() === '' || !isAbsolute(codexHome))) {
2451
+ throw new CodexInstallError('CODEX_HOME_INVALID', 'the Codex home must be an absolute path');
2452
+ }
2453
+ const home = codexHome === null ? resolveCodexHome({ env }) : requireCodexHome(codexHome);
2454
+ const before = plan ?? await readCodexStatus({ codexHome: home, env, discoveryFile, version, hostNode });
2455
+ const changed = [];
2456
+ const refused = [];
2457
+
2458
+ if (before.boundary?.blocked === true) {
2459
+ // A link (or an unverifiable directory) at `$CODEX_HOME` or `$CODEX_HOME/agents`
2460
+ // blocks EVERY write, so the check reports that one refusal and writes nothing. It
2461
+ // is reported even when the visible state shows nothing stale: "the boundary cannot
2462
+ // be proved" is itself the diagnosis the operator needs, and staying silent here is
2463
+ // how a startup migration came to look successful while doing nothing.
2464
+ refused.push(linkedBoundaryRefusal(before));
2465
+ } else {
2466
+ if (before.agent.state === AGENT_STATES.outdated) {
2467
+ await installManagedAgent(before, { changed, refused });
2468
+ }
2469
+ await migrateLegacyAgent(before, { changed, refused });
2470
+ if (refreshMcp === true) {
2471
+ // The automatic MCP half: only a provably-owned, merely-stale definition is
2472
+ // rewritten, and only after the boundary and the config digest are re-proved. It
2473
+ // never CREATES the entry: a home without one is left without one, because a
2474
+ // plugin upgrade is not an install.
2475
+ if (before.config?.readable === true && before.mcp.state === MCP_STATES.outdated) {
2476
+ await upgradeOutdatedMcpEntry(before, { changed, refused }, { backupDir });
2477
+ }
2478
+ }
2479
+ }
2480
+
2481
+ const status = await readCodexStatus({ codexHome: home, env, discoveryFile, version, hostNode });
2482
+ return { changed, refused, status };
2483
+ }
2484
+
2485
+ /** Install or refresh the managed agent file without touching the MCP entry. */
2486
+ async function installManagedAgent(before, outcome) {
2487
+ const { agent } = before;
2488
+ if (agent.state === AGENT_STATES.missing || agent.state === AGENT_STATES.outdated) {
2489
+ const template = renderAgentFile(await readAgentTemplate(), before.packageVersion);
2490
+ await mkdir(dirname(agent.path), { recursive: true, mode: 0o700 });
2491
+ if (agent.state === AGENT_STATES.missing) {
2492
+ // First installation: exclusive. A file that appeared between the status read
2493
+ // and this write belongs to whoever created it, and is reported, not replaced.
2494
+ const created = await createFileExclusive(agent.path, template);
2495
+ if (created === 'exists') {
2496
+ outcome.refused.push({
2497
+ target: 'agent',
2498
+ code: 'AGENT_PATH_CONFLICT',
2499
+ message: 'an agent file appeared while installing and was left untouched',
2500
+ path: agent.path,
2501
+ reason: 'created-concurrently',
2502
+ });
2503
+ return;
2504
+ }
2505
+ outcome.changed.push('agent');
2506
+ } else {
2507
+ // A refresh replaces a byte-exact known build of our own file. Re-check right
2508
+ // before writing: if the file changed in the meantime it is no longer that
2509
+ // known build, and the rename must not overwrite it.
2510
+ const current = await inspectFile(agent.path);
2511
+ if (current.kind !== 'file' || current.contents !== before.agent.expect) {
2512
+ outcome.refused.push({
2513
+ target: 'agent',
2514
+ code: 'AGENT_USER_MODIFIED',
2515
+ message: 'the agent file changed while updating and was left untouched',
2516
+ path: agent.path,
2517
+ });
2518
+ return;
2519
+ }
2520
+ await writeFileAtomic(agent.path, template);
2521
+ outcome.changed.push('agent');
2522
+ }
2523
+ } else if (agent.state === AGENT_STATES.modified || agent.state === AGENT_STATES.conflict) {
2524
+ outcome.refused.push({
2525
+ target: 'agent',
2526
+ code: agent.state === AGENT_STATES.modified ? 'AGENT_USER_MODIFIED' : 'AGENT_PATH_CONFLICT',
2527
+ message: 'an agent file with different contents already exists and was left untouched',
2528
+ path: agent.path,
2529
+ });
2530
+ }
2531
+ }
2532
+
2533
+ /**
2534
+ * Register the owned MCP entry, refusing anything this plugin cannot prove is its own.
2535
+ *
2536
+ * This is the whole of `repair`, and the second half of `install`. It reads and writes
2537
+ * `config.toml` only: the agent file is never inspected for writing here, so a
2538
+ * `repair` cannot create the `agents/` directory, refresh a stale agent or remove one.
2539
+ * @param {object} before - status read before the change.
2540
+ * @param {{ changed: string[], refused: object[] }} outcome - mutable outcome.
2541
+ * @returns {Promise<void>} resolves after the target was attempted.
2542
+ */
2543
+ async function installMcpEntry(before, outcome) {
2544
+ const { mcp } = before;
2545
+ if (mcp.scriptExists !== true) {
2546
+ outcome.refused.push({
2547
+ target: 'mcp',
2548
+ code: 'MCP_SCRIPT_MISSING',
2549
+ message: 'the package MCP entry point is missing, so the Codex entry would not start',
2550
+ path: mcp.script,
2551
+ });
2552
+ return;
2553
+ }
2554
+ if (mcp.nodeResolved !== true || mcp.desired === null) {
2555
+ // Fail closed: an entry whose `command` could not be proved to be a Node.js
2556
+ // executable is never written. Writing the desktop application's own path (the
2557
+ // pre-0.1.7 behaviour) would make Codex launch a second GUI.
2558
+ outcome.refused.push({
2559
+ target: 'mcp',
2560
+ code: 'MCP_EXECUTABLE_UNRESOLVED',
2561
+ message: mcp.nodeError?.message
2562
+ ?? 'no Node.js executable could be proved for the Codex MCP command, so no entry was written',
2563
+ path: mcp.path,
2564
+ details: mcp.nodeError?.details ?? {},
2565
+ });
2566
+ return;
2567
+ }
2568
+ if (before.config.readable !== true) {
2569
+ outcome.refused.push({
2570
+ target: 'mcp',
2571
+ code: before.config.error?.code ?? 'CODEX_CONFIG_UNREADABLE',
2572
+ message: before.config.error?.message ?? 'the Codex config could not be read',
2573
+ path: mcp.path,
2574
+ });
2575
+ return;
2576
+ }
2577
+ if (mcp.state === MCP_STATES.conflict) {
2578
+ // The ONE conflict an explicit `install`/`repair` may resolve: a marked entry whose
2579
+ // script is a DIFFERENT path that is provably another installation of this package
2580
+ // (its root's `package.json` declares our name and its `bin` is that very file). This
2581
+ // is the moved-installation upgrade, and it is proved here, on the spot — the bare
2582
+ // classification never grants it, and the unattended startup path never attempts it.
2583
+ const adopted = await adoptProvedMovedInstall(before);
2584
+ if (adopted === null) {
2585
+ outcome.refused.push({
2586
+ target: 'mcp',
2587
+ code: 'MCP_ENTRY_CONFLICT',
2588
+ message: mcp.reason === 'unmanaged-entry'
2589
+ ? 'a same-name mcp_servers.dsh-delegate entry without the plugin marker already exists and was left untouched'
2590
+ : 'a different mcp_servers.dsh-delegate entry already exists and was left untouched',
2591
+ path: mcp.path,
2592
+ reason: mcp.reason,
2593
+ });
2594
+ return;
2595
+ }
2596
+ await adoptMovedInstall(adopted, outcome, before);
2597
+ return;
2598
+ }
2599
+ if (mcp.state === MCP_STATES.configured) return;
2600
+
2601
+ const loaded = await loadConfig(mcp.path);
2602
+ const desired = mcp.desired;
2603
+ const classification = classifyMcpEntry(loaded.document, desired);
2604
+ if (!MANAGEABLE_MCP_STATES.has(classification.state)) {
2605
+ // The file changed between the read and the write; never overwrite a definition
2606
+ // that stopped being ours.
2607
+ outcome.refused.push({
2608
+ target: 'mcp',
2609
+ code: 'MCP_ENTRY_CONFLICT',
2610
+ message: 'the mcp_servers.dsh-delegate entry changed concurrently and was left untouched',
2611
+ path: mcp.path,
2612
+ reason: classification.reason ?? classification.state,
2613
+ });
2614
+ return;
2615
+ }
2616
+ const next = applyMcpEntry(loaded.document, desired, classification);
2617
+ if (next === null) return;
2618
+ await mkdir(dirname(mcp.path), { recursive: true, mode: 0o700 });
2619
+ await writeFileAtomic(mcp.path, next);
2620
+ outcome.changed.push('mcp');
2621
+ }
2622
+
2623
+ /**
2624
+ * Upgrade ONE managed MCP entry that is already installed and merely stale.
2625
+ *
2626
+ * This is the plugin-upgrade paths' shared implementation: startup's
2627
+ * {@link refreshKnownAgentTemplate} (with `refreshMcp`) and the explicit `repair` both
2628
+ * end up here. It writes NOTHING except a definition this plugin can prove is its own,
2629
+ * and it proves that three times over:
2630
+ *
2631
+ * 1. **Ownership** — {@link isOwnedStaleEntry}: marker authorship, exactly this
2632
+ * package's Node command, exactly one argument whose script is PROVED (this
2633
+ * installation's own absolute path, or — for an explicit repair only — a real other
2634
+ * installation of this package, verified through its `package.json`), and no foreign
2635
+ * env key. A wrapper that reuses the file name is refused, not rewritten.
2636
+ * 2. **No concurrent change** — the plan records a SHA-256 of the whole `config.toml`
2637
+ * it was derived from (`fingerprint`), and the write re-reads the file and requires
2638
+ * that digest to match.
2639
+ * 3. **A protected backup first** — the current document is copied to a private,
2640
+ * regular, non-link file before ANY write, and that copy is a PRECONDITION. A backup
2641
+ * that cannot be taken (no destination, a destination that is a file or a link, a
2642
+ * permission failure) refuses the upgrade and keeps the original file: an
2643
+ * unattended migration must never rewrite a config it could not preserve.
2644
+ *
2645
+ * The boundary (`$CODEX_HOME`, `agents/`) is re-inspected and the ownership proof is
2646
+ * re-run against the current bytes before the backup is taken, and AGAIN after the backup
2647
+ * succeeds — the backup performs several asynchronous probes (and a Windows attribute
2648
+ * read), so a config edit or a boundary change in that window must not be overwritten.
2649
+ * The replacement is then written atomically, built from the bytes that were just
2650
+ * re-read. An entry that became `configured` or `missing` is left alone: nothing is
2651
+ * created and nothing is rewritten when nothing is stale.
2652
+ * @param {object} before - status read before the change.
2653
+ * @param {{ changed: string[], refused: object[] }} outcome - mutable outcome.
2654
+ * @param {object} [options] - `backupDir` (required, trusted), `allowMovedInstall`.
2655
+ * @returns {Promise<void>} resolves after the target was attempted.
2656
+ */
2657
+ async function upgradeOutdatedMcpEntry(before, outcome, options = {}) {
2658
+ const { mcp } = before;
2659
+ if (mcp.state !== MCP_STATES.outdated) return;
2660
+ const refuse = (code, message, extra = {}) => {
2661
+ outcome.refused.push({ target: 'mcp', code, message, path: mcp.path, ...extra });
2662
+ };
2663
+ if (mcp.desired === null || mcp.nodeResolved !== true) {
2664
+ refuse('MCP_EXECUTABLE_UNRESOLVED', mcp.nodeError?.message
2665
+ ?? 'no Node.js executable could be proved for the Codex MCP command, so the stale entry was left untouched',
2666
+ { details: mcp.nodeError?.details ?? {} });
2667
+ return;
2668
+ }
2669
+ if (mcp.scriptExists !== true) {
2670
+ outcome.refused.push({
2671
+ target: 'mcp',
2672
+ code: 'MCP_SCRIPT_MISSING',
2673
+ message: 'the package MCP entry point is missing, so the stale Codex entry was left untouched',
2674
+ path: mcp.script,
2675
+ });
2676
+ return;
2677
+ }
2678
+ // A trusted backup destination is a precondition, checked before anything else can be
2679
+ // decided: no destination means no unattended write.
2680
+ if (typeof options.backupDir !== 'string' || options.backupDir.trim() === '') {
2681
+ refuse('MCP_ENTRY_BACKUP_UNAVAILABLE',
2682
+ 'no trusted backup location was supplied, so the stale entry was left untouched');
2683
+ return;
2684
+ }
2685
+ // The write gate: "outdated" is not by itself permission to write, and the script proof
2686
+ // is a filesystem proof re-run HERE (not a label computed earlier).
2687
+ const gate = await isOwnedStaleEntry(
2688
+ { state: mcp.state, marked: mcp.marked, previous: mcp.previous },
2689
+ mcp.desired,
2690
+ { allowMovedInstall: options.allowMovedInstall === true },
2691
+ );
2692
+ if (gate.owned !== true) {
2693
+ refuse('MCP_ENTRY_CONFLICT',
2694
+ 'the stale mcp_servers.dsh-delegate entry is not one this plugin can prove is its own, so it was left untouched; use 安装 / 更新 Codex 集成 to replace it explicitly',
2695
+ { reason: gate.reason });
2696
+ return;
2697
+ }
2698
+ // The boundary is re-inspected right before the write: a link can have replaced the
2699
+ // home or `agents/` since the plan was made, and writing through one would put the
2700
+ // file outside the Codex home.
2701
+ const boundary = await inspectCodexBoundary(before.codexHome);
2702
+ if (boundary.blocked === true) {
2703
+ outcome.refused.push(linkedBoundaryRefusal({ ...before, boundary }));
2704
+ return;
2705
+ }
2706
+ let loaded;
2707
+ try {
2708
+ loaded = await loadConfig(mcp.path);
2709
+ } catch (error) {
2710
+ refuse(typeof error?.code === 'string' ? error.code : 'CODEX_CONFIG_UNREADABLE',
2711
+ typeof error?.message === 'string' ? error.message : 'the Codex config could not be read');
2712
+ return;
2713
+ }
2714
+ // Everything below acts on the CURRENT file, and every fact the plan asserted is
2715
+ // re-proved against it: the digest first (the file is byte-identical to the one the
2716
+ // plan was derived from), then ownership and staleness of that same text.
2717
+ const currentContents = loaded.unreadable === true ? null : loaded.document.text;
2718
+ if (currentContents === null || mcp.fingerprint === null || digest(currentContents) !== mcp.fingerprint) {
2719
+ refuse('MCP_ENTRY_CONFLICT', 'config.toml changed after the upgrade was checked, so nothing was written',
2720
+ { reason: 'config-changed' });
2721
+ return;
2722
+ }
2723
+ const classification = classifyMcpEntry(loaded.document, mcp.desired);
2724
+ const reGate = await isOwnedStaleEntry(classification, mcp.desired, {
2725
+ allowMovedInstall: options.allowMovedInstall === true,
2726
+ });
2727
+ if (reGate.owned !== true) {
2728
+ refuse('MCP_ENTRY_CONFLICT',
2729
+ 'the mcp_servers.dsh-delegate entry is no longer the stale, provably-owned definition that was checked, so nothing was written',
2730
+ { reason: reGate.reason });
2731
+ return;
2732
+ }
2733
+ const planned = applyMcpEntry(loaded.document, mcp.desired, classification);
2734
+ if (planned === null) return;
2735
+ // THE BACKUP IS A PRECONDITION: it is taken, and verified, before the write. A failure
2736
+ // here refuses the upgrade and leaves the file exactly as it was.
2737
+ const backup = await backupConfigBeforeWrite(mcp.path, currentContents, options.backupDir);
2738
+ if (backup.ok !== true) {
2739
+ refuse('MCP_ENTRY_BACKUP_FAILED',
2740
+ `the config could not be backed up before the upgrade (${backup.reason}), so nothing was written`);
2741
+ return;
2742
+ }
2743
+ // THE BACKUP ITSELF TAKES TIME: several asynchronous probes, and on Windows a
2744
+ // PowerShell child for the attribute read. The operator (or another tool) can change
2745
+ // the config, or replace a boundary with a link, during that window. Everything the
2746
+ // plan asserted is therefore re-proved against the filesystem as it is NOW — after the
2747
+ // backup and immediately before the write — and a change is refused with the user's
2748
+ // edit kept. This is not a claim about every OS-level race; it is the observable
2749
+ // window between the plan and this write.
2750
+ const boundaryAfterBackup = await inspectCodexBoundary(before.codexHome);
2751
+ if (boundaryAfterBackup.blocked === true) {
2752
+ outcome.refused.push(linkedBoundaryRefusal({ ...before, boundary: boundaryAfterBackup }));
2753
+ return;
2754
+ }
2755
+ let afterBackup;
2756
+ try {
2757
+ afterBackup = await loadConfig(mcp.path);
2758
+ } catch (error) {
2759
+ refuse(typeof error?.code === 'string' ? error.code : 'CODEX_CONFIG_UNREADABLE',
2760
+ typeof error?.message === 'string' ? error.message : 'the Codex config could not be read after the backup');
2761
+ return;
2762
+ }
2763
+ const afterBackupContents = afterBackup.unreadable === true ? null : afterBackup.document.text;
2764
+ if (afterBackupContents === null || mcp.fingerprint === null || digest(afterBackupContents) !== mcp.fingerprint) {
2765
+ refuse('MCP_ENTRY_CONFLICT',
2766
+ 'config.toml changed while the upgrade was being backed up, so nothing was written',
2767
+ { reason: 'config-changed' });
2768
+ return;
2769
+ }
2770
+ const afterBackupClassification = classifyMcpEntry(afterBackup.document, mcp.desired);
2771
+ const afterBackupGate = await isOwnedStaleEntry(afterBackupClassification, mcp.desired, {
2772
+ allowMovedInstall: options.allowMovedInstall === true,
2773
+ });
2774
+ if (afterBackupGate.owned !== true) {
2775
+ refuse('MCP_ENTRY_CONFLICT',
2776
+ 'the mcp_servers.dsh-delegate entry is no longer the stale, provably-owned definition that was checked, so nothing was written after the backup',
2777
+ { reason: afterBackupGate.reason });
2778
+ return;
2779
+ }
2780
+ const next = applyMcpEntry(afterBackup.document, mcp.desired, afterBackupClassification);
2781
+ if (next === null) return;
2782
+ await mkdir(dirname(mcp.path), { recursive: true, mode: 0o700 });
2783
+ await writeFileAtomic(mcp.path, next);
2784
+ outcome.changed.push('mcp');
2785
+ }
2786
+
2787
+ /**
2788
+ * The absolute directory prefixes of `directory`, root excluded, in order.
2789
+ *
2790
+ * The components come from the host path rules (`parse`/`sep`), so a POSIX leading `/`
2791
+ * and a Windows drive or UNC root are both preserved rather than split away.
2792
+ * @param {string} directory - absolute directory path.
2793
+ * @returns {string[]} each ancestor from the root's child down to `directory` itself.
2794
+ */
2795
+ function directoryPrefixes(directory) {
2796
+ const { root } = parse(directory);
2797
+ const prefixes = [];
2798
+ let current = root;
2799
+ for (const part of directory.slice(root.length).split(sep).filter((part) => part !== '')) {
2800
+ current = join(current, part);
2801
+ prefixes.push(current);
2802
+ }
2803
+ return prefixes;
2804
+ }
2805
+
2806
+ /**
2807
+ * Prove the whole ancestor chain of `directory`, creating missing levels safely.
2808
+ *
2809
+ * Checking only the leaf is not enough: `/safe/backup` can be a real directory while
2810
+ * `/safe` is a junction to somebody else's tree, and writing there would put the complete
2811
+ * `config.toml` outside the plugin's data directory. Every EXISTING component is therefore
2812
+ * inspected — `lstat` catches a POSIX symlink, and the Windows attribute read catches a
2813
+ * junction `lstat` reports as an ordinary directory. A link, a non-directory or an
2814
+ * unverifiable component refuses the whole chain.
2815
+ *
2816
+ * Missing levels are created ONE at a time and inspected immediately afterwards, never
2817
+ * with a recursive `mkdir`: a recursive create would follow a link that appeared in the
2818
+ * window at any depth. This is why the function returns a bounded reason instead of
2819
+ * throwing: the caller must refuse the unattended config write.
2820
+ * @param {string} directory - absolute directory path.
2821
+ * @returns {Promise<{ ok: true } | { ok: false, reason: string }>} verdict.
2822
+ */
2823
+ async function ensureTrustedDirectoryChain(directory) {
2824
+ const prefixes = directoryPrefixes(directory);
2825
+ let firstMissing = prefixes.length;
2826
+ for (let index = 0; index < prefixes.length; index += 1) {
2827
+ const prefix = prefixes[index];
2828
+ let info;
2829
+ try {
2830
+ info = await lstat(prefix);
2831
+ } catch (error) {
2832
+ if (error?.code === 'ENOENT') {
2833
+ firstMissing = index;
2834
+ break;
2835
+ }
2836
+ return { ok: false, reason: 'backup-ancestor-unreadable' };
2837
+ }
2838
+ if (info.isSymbolicLink()) return { ok: false, reason: 'backup-ancestor-is-a-link' };
2839
+ if (!info.isDirectory()) return { ok: false, reason: 'backup-ancestor-not-a-directory' };
2840
+ }
2841
+ // Ask the platform about the components that exist, in ONE child process on Windows: a
2842
+ // junction is a plain directory to `lstat`, so the attribute read is the actual proof.
2843
+ const existing = prefixes.slice(0, firstMissing);
2844
+ if (existing.length > 0) {
2845
+ const verdicts = await windowsDirectoryKinds(existing);
2846
+ for (const prefix of existing) {
2847
+ const verdict = verdicts.get(prefix);
2848
+ if (verdict === 'directory') continue;
2849
+ if (verdict === 'unknown') return { ok: false, reason: 'backup-ancestor-unverified' };
2850
+ if (verdict === 'link') return { ok: false, reason: 'backup-ancestor-is-a-link' };
2851
+ if (verdict === 'other') return { ok: false, reason: 'backup-ancestor-not-a-directory' };
2852
+ if (verdict === 'missing') {
2853
+ firstMissing = Math.min(firstMissing, prefixes.indexOf(prefix));
2854
+ break;
2855
+ }
2856
+ }
2857
+ }
2858
+ for (let index = firstMissing; index < prefixes.length; index += 1) {
2859
+ const prefix = prefixes[index];
2860
+ try {
2861
+ await mkdir(prefix, { mode: 0o700 });
2862
+ } catch (error) {
2863
+ if (error?.code !== 'EEXIST') return { ok: false, reason: 'backup-ancestor-unwritable' };
2864
+ }
2865
+ const kind = await inspectDirectory(prefix);
2866
+ if (kind.kind === 'directory') continue;
2867
+ if (kind.kind === 'link') return { ok: false, reason: 'backup-ancestor-is-a-link' };
2868
+ if (kind.kind === 'unknown') return { ok: false, reason: 'backup-ancestor-unverified' };
2869
+ return { ok: false, reason: 'backup-ancestor-not-a-directory' };
2870
+ }
2871
+ return { ok: true };
2872
+ }
2873
+
2874
+ /**
2875
+ * Keep a protected copy of `config.toml` before an automatic migration rewrites it.
2876
+ *
2877
+ * This is a PRECONDITION, not a best-effort extra: the caller refuses to write when it
2878
+ * fails. The destination is validated before anything is written —
2879
+ *
2880
+ * * the destination must be an ABSOLUTE path;
2881
+ * * every ancestor of the destination is proved to be a real directory — a symlink, a
2882
+ * Windows junction/reparse point, an unverifiable component or a non-directory refuses
2883
+ * the whole chain ({@link ensureTrustedDirectoryChain}); missing levels are created one
2884
+ * by one and re-inspected, and the chain is re-checked immediately before the write;
2885
+ * * the file name is derived from the content digest, so repeated upgrades do not grow
2886
+ * without bound;
2887
+ * * an existing destination that is a link or not a regular file is refused, so a
2888
+ * pre-planted link cannot redirect the config text;
2889
+ *
2890
+ * — and the copy itself is written atomically with owner-only permissions. A failure
2891
+ * returns a bounded REASON (never the config text, never a path a caller could mistake for
2892
+ * a credential) so the refusal can be reported.
2893
+ * @param {string} configPath - the file that is about to change (for the record only).
2894
+ * @param {string} contents - its current bytes.
2895
+ * @param {string} backupDir - trusted destination directory.
2896
+ * @returns {Promise<{ ok: true, path: string } | { ok: false, reason: string }>} outcome.
2897
+ */
2898
+ async function backupConfigBeforeWrite(configPath, contents, backupDir) {
2899
+ void configPath;
2900
+ if (typeof backupDir !== 'string' || backupDir.trim() === '') {
2901
+ return { ok: false, reason: 'no-backup-directory' };
2902
+ }
2903
+ // A relative destination would be resolved against the harness cwd, which is not a
2904
+ // location this plugin may pick for itself.
2905
+ if (!isAbsolute(backupDir)) return { ok: false, reason: 'backup-directory-not-absolute' };
2906
+ const targetDir = resolve(backupDir);
2907
+ const chain = await ensureTrustedDirectoryChain(targetDir);
2908
+ if (chain.ok !== true) return { ok: false, reason: chain.reason };
2909
+ const target = join(targetDir, `codex-config-before-${digest(contents).slice(0, 16)}.toml`);
2910
+ let existing;
2911
+ try {
2912
+ existing = await lstat(target);
2913
+ } catch (error) {
2914
+ if (error?.code !== 'ENOENT') return { ok: false, reason: 'backup-target-unreadable' };
2915
+ existing = null;
2916
+ }
2917
+ if (existing !== null) {
2918
+ // Something already sits there. It is acceptable ONLY as the same regular file with
2919
+ // the same bytes (an idempotent re-check); a link, a directory or different bytes is
2920
+ // refused rather than overwritten.
2921
+ if (existing.isSymbolicLink() || !existing.isFile()) return { ok: false, reason: 'backup-target-not-a-regular-file' };
2922
+ try {
2923
+ const previous = await readFile(target, 'utf8');
2924
+ if (previous !== contents) return { ok: false, reason: 'backup-target-differs' };
2925
+ return { ok: true, path: target };
2926
+ } catch {
2927
+ return { ok: false, reason: 'backup-target-unreadable' };
2928
+ }
2929
+ }
2930
+ // Re-prove the chain at the last moment: the pre-write probes above are asynchronous and
2931
+ // a component can be replaced by a link between the first check and the write.
2932
+ const recheck = await ensureTrustedDirectoryChain(targetDir);
2933
+ if (recheck.ok !== true) return { ok: false, reason: recheck.reason };
2934
+ try {
2935
+ // `writeFileAtomic` writes its temp file with mode `0600` and renames it into place,
2936
+ // so the copy is owner-only and never partial.
2937
+ await writeFileAtomic(target, contents);
2938
+ } catch {
2939
+ return { ok: false, reason: 'backup-write-failed' };
2940
+ }
2941
+ // Re-read what was actually written: a backup nobody verified is not a backup.
2942
+ try {
2943
+ const written = await readFile(target, 'utf8');
2944
+ if (written !== contents) return { ok: false, reason: 'backup-verification-failed' };
2945
+ } catch {
2946
+ return { ok: false, reason: 'backup-verification-failed' };
2947
+ }
2948
+ return { ok: true, path: target };
2949
+ }
2950
+
2951
+ /**
2952
+ * Delete the managed agent file — but only after re-proving it is still that file.
2953
+ *
2954
+ * The status read is already stale by the time a removal runs: the operator, an editor
2955
+ * or another tool may have rewritten the file after it. Deleting on the strength of the
2956
+ * earlier verdict would destroy that file, so ownership is re-proved here, at the last
2957
+ * moment, from the file itself: it must still be a *regular* file (not a link, not a
2958
+ * directory) whose bytes are exactly the managed content the status derived its verdict
2959
+ * from. `agent.expect` is that content, so the comparison is content identity, not a
2960
+ * timestamp or a size that a rewrite could accidentally preserve.
2961
+ *
2962
+ * Exported because it is the smallest unit that implements the guarantee: a test can
2963
+ * call it with a status captured earlier and prove that a file rewritten in between
2964
+ * survives. Every caller must pass the `agent` block of a status document.
2965
+ * @param {{ path: string, expect: string | null }} agent - the agent target of a status read.
2966
+ * @returns {Promise<{ code: string | null, target?: string, message?: string, path?: string, reason?: string }>}
2967
+ * `{ code: null }` when the file was deleted; otherwise the refusal to report.
2968
+ */
2969
+ export async function removeManagedAgentFile(agent) {
2970
+ const current = await inspectFile(agent.path);
2971
+ if (current.kind === 'missing') {
2972
+ // Nothing to delete: the file this read classified is already gone. Reported as a
2973
+ // refusal rather than a change, so the outcome never overstates what happened.
2974
+ return {
2975
+ target: 'agent',
2976
+ code: 'AGENT_PATH_CONFLICT',
2977
+ message: 'the agent file disappeared before it could be removed and nothing was deleted',
2978
+ path: agent.path,
2979
+ reason: 'missing-before-removal',
2980
+ };
2981
+ }
2982
+ if (current.kind !== 'file') {
2983
+ return {
2984
+ target: 'agent',
2985
+ code: 'AGENT_PATH_CONFLICT',
2986
+ message: 'the agent path stopped being a regular file before removal and was left untouched',
2987
+ path: agent.path,
2988
+ reason: 'not-a-regular-file',
2989
+ };
2990
+ }
2991
+ if (typeof agent.expect !== 'string' || current.contents !== agent.expect) {
2992
+ return {
2993
+ target: 'agent',
2994
+ code: 'AGENT_USER_MODIFIED',
2995
+ message: 'the agent file changed after it was inspected and was left untouched',
2996
+ path: agent.path,
2997
+ reason: 'modified-before-removal',
2998
+ };
2999
+ }
3000
+ try {
3001
+ await unlink(agent.path);
3002
+ } catch (error) {
3003
+ if (error?.code === 'ENOENT') {
3004
+ // Raced away between the read and the unlink; still not a change of ours.
3005
+ return {
3006
+ target: 'agent',
3007
+ code: 'AGENT_PATH_CONFLICT',
3008
+ message: 'the agent file disappeared before it could be removed and nothing was deleted',
3009
+ path: agent.path,
3010
+ reason: 'missing-before-removal',
3011
+ };
3012
+ }
3013
+ if (error?.code === 'EPERM' || error?.code === 'EACCES' || error?.code === 'EBUSY') {
3014
+ return {
3015
+ target: 'agent',
3016
+ code: 'AGENT_PATH_CONFLICT',
3017
+ message: 'the agent file could not be removed and was left in place',
3018
+ path: agent.path,
3019
+ reason: 'unlink-refused',
3020
+ };
3021
+ }
3022
+ throw error;
3023
+ }
3024
+ return { code: null };
3025
+ }
3026
+
3027
+ /**
3028
+ * Remove only what this plugin still owns.
3029
+ * @param {object} before - status read before the change.
3030
+ * @param {{ changed: string[], refused: object[] }} outcome - mutable outcome.
3031
+ * @returns {Promise<void>} resolves after both targets were attempted.
3032
+ */
3033
+ async function removeManaged(before, outcome) {
3034
+ const { agent, mcp } = before;
3035
+ if (agent.state === AGENT_STATES.installed || agent.state === AGENT_STATES.outdated) {
3036
+ const verdict = await removeManagedAgentFile(agent);
3037
+ if (verdict.code === null) outcome.changed.push('agent');
3038
+ else outcome.refused.push(verdict);
3039
+ } else if (agent.state === AGENT_STATES.modified) {
3040
+ outcome.refused.push({
3041
+ target: 'agent',
3042
+ code: 'AGENT_USER_MODIFIED',
3043
+ message: 'the agent file differs from the managed template and was left untouched',
3044
+ path: agent.path,
3045
+ });
3046
+ } else if (agent.state === AGENT_STATES.conflict) {
3047
+ outcome.refused.push({
3048
+ target: 'agent',
3049
+ code: 'AGENT_PATH_CONFLICT',
3050
+ message: 'the agent path is not a regular file managed by this plugin and was left untouched',
3051
+ path: agent.path,
3052
+ });
3053
+ }
3054
+
3055
+ if (before.config.readable !== true) {
3056
+ outcome.refused.push({
3057
+ target: 'mcp',
3058
+ code: before.config.error?.code ?? 'CODEX_CONFIG_UNREADABLE',
3059
+ message: before.config.error?.message ?? 'the Codex config could not be read',
3060
+ path: mcp.path,
3061
+ });
3062
+ return;
3063
+ }
3064
+ if (mcp.state !== MCP_STATES.configured && mcp.state !== MCP_STATES.outdated) {
3065
+ if (mcp.state === MCP_STATES.conflict) {
3066
+ outcome.refused.push({
3067
+ target: 'mcp',
3068
+ code: 'MCP_ENTRY_CONFLICT',
3069
+ message: 'the mcp_servers.dsh-delegate entry was not written by this plugin and was left untouched',
3070
+ path: mcp.path,
3071
+ reason: mcp.reason,
3072
+ });
3073
+ }
3074
+ return;
3075
+ }
3076
+
3077
+ const loaded = await loadConfig(mcp.path);
3078
+ const classification = classifyMcpEntry(loaded.document, mcp.desired);
3079
+ if (classification.state !== MCP_STATES.configured && classification.state !== MCP_STATES.outdated) {
3080
+ outcome.refused.push({
3081
+ target: 'mcp',
3082
+ code: 'MCP_ENTRY_CONFLICT',
3083
+ message: 'the mcp_servers.dsh-delegate entry stopped being one this plugin manages and was left untouched',
3084
+ path: mcp.path,
3085
+ reason: classification.reason ?? classification.state,
3086
+ });
3087
+ return;
3088
+ }
3089
+ const { removed } = removeMcpEntry(loaded.document);
3090
+ if (!removed) return;
3091
+ await writeFileAtomic(mcp.path, loaded.document.text);
3092
+ outcome.changed.push('mcp');
3093
+ }
3094
+
3095
+ /**
3096
+ * The status document without the internal ownership bytes.
3097
+ *
3098
+ * `agent.expect` carries the exact file a refresh may replace. It is what the
3099
+ * installer compares against right before its rename, so it must travel with the
3100
+ * status `installManaged` receives — but it is not part of the operator-facing
3101
+ * contract and would only bloat every HTTP response, so transports strip it.
3102
+ * @param {object} status - a document from {@link readCodexStatus}.
3103
+ * @returns {object} a shallow copy with the internal field removed.
3104
+ */
3105
+ export function publicCodexStatus(status) {
3106
+ if (status === null || typeof status !== 'object') return status;
3107
+ const { expect: _ignored, ...agent } = status.agent ?? {};
3108
+ // `mcp.fingerprint` is the write path's receipt for the exact config bytes it plans to
3109
+ // replace. It is a digest, not content, but it is an internal planning fact like
3110
+ // `agent.expect`, so it does not belong in a response an operator or a page reads.
3111
+ const { fingerprint: _receipt, ...mcp } = status.mcp ?? {};
3112
+ return { ...status, agent, mcp };
3113
+ }
3114
+
3115
+ /**
3116
+ * Load the shipped agent template without the version marker, for diagnostics.
3117
+ *
3118
+ * Exported so a test can assert the shipped dispatch rules independently of the
3119
+ * installed copy.
3120
+ * @returns {Promise<{ text: string, instructions: string }>} template text and its developer instructions.
3121
+ */
3122
+ export async function readAgentInstructions() {
3123
+ const text = await readAgentTemplate();
3124
+ const match = /developer_instructions = """([\s\S]*?)"""/u.exec(text);
3125
+ return { text, instructions: match === null ? '' : match[1] };
3126
+ }
3127
+
3128
+ /**
3129
+ * Stable digest of the shipped template, so an installed file can be identified
3130
+ * without shipping the whole text in a response.
3131
+ * @param {string} text - file contents.
3132
+ * @returns {string} lowercase hex sha256.
3133
+ */
3134
+ export function digest(text) {
3135
+ return createHash('sha256').update(text, 'utf8').digest('hex');
3136
+ }
3137
+
3138
+ /** Re-exported for callers that need to render a path list consistently. */
3139
+ export { delimiter };
3140
+
3141
+
3142
+ /**
3143
+ * Detect the ONE conflict an explicit action may resolve: a proved moved installation.
3144
+ *
3145
+ * This is deliberately NOT part of `classifyMcpEntry`, which is synchronous and must never
3146
+ * label a differing script `outdated` without a proof. The proof is the async filesystem
3147
+ * one in {@link isOwnedEntryScript} — a real package root, a `package.json` naming this
3148
+ * package AND mapping its `bin["dsh-delegate-mcp"]` to the entry, and a
3149
+ * `bin/dsh-delegate-mcp.js` that IS the recorded file — so a wrapper that merely reuses
3150
+ * the file name stays refused.
3151
+ *
3152
+ * The proof is made against the config document this action read, and the plan's digest is
3153
+ * required to match it: a document that changed since the plan is not the one the operator
3154
+ * acted on, so no proof from a different state can authorize the write.
3155
+ *
3156
+ * Exported for the deterministic race regression (the async window between this proof and
3157
+ * {@link adoptMovedInstall}); `installMcpEntry` is its only production caller.
3158
+ * @internal
3159
+ * @param {object} before - status read.
3160
+ * @returns {Promise<{ document: object, classification: object, desired: object } | null>}
3161
+ * the current document and its re-classification when the moved install is proved.
3162
+ */
3163
+ export async function adoptProvedMovedInstall(before) {
3164
+ const { mcp } = before;
3165
+ if (mcp.state !== MCP_STATES.conflict || mcp.reason !== 'args-shape-not-ours') return null;
3166
+ if (mcp.marked !== true || mcp.previous === null || mcp.desired === null) return null;
3167
+ const args = Array.isArray(mcp.previous.args) ? mcp.previous.args : [];
3168
+ if (args.length !== 1) return null;
3169
+ if (mcp.previous.command !== mcp.desired.command && !isLegacyDesktopCommand(mcp.previous.command)) return null;
3170
+ if ((await isExplicitlyMigratableScript(args[0], mcp.desired.args[0])) !== true) return null;
3171
+ let loaded;
3172
+ try {
3173
+ loaded = await loadConfig(mcp.path);
3174
+ } catch {
3175
+ return null;
3176
+ }
3177
+ if (loaded.unreadable === true) return null;
3178
+ // The CURRENT bytes must still be the plan's bytes: a config edited after the plan can
3179
+ // describe a different entry, and a proof made from it would authorize a write the
3180
+ // operator never saw.
3181
+ if (typeof mcp.fingerprint !== 'string' || digest(loaded.document.text) !== mcp.fingerprint) return null;
3182
+ const classification = classifyMcpEntry(loaded.document, mcp.desired);
3183
+ // The proof must still hold for the CURRENT text: same conflict, same recorded script.
3184
+ if (classification.marked !== true || classification.reason !== 'args-shape-not-ours') return null;
3185
+ const currentArgs = Array.isArray(classification.previous?.args) ? classification.previous.args : [];
3186
+ if (currentArgs.length !== 1) return null;
3187
+ if ((await isExplicitlyMigratableScript(currentArgs[0], mcp.desired.args[0])) !== true) return null;
3188
+ return { document: loaded.document, classification, desired: mcp.desired };
3189
+ }
3190
+
3191
+ /**
3192
+ * Write a proved moved installation into the owned entry, in one atomic write.
3193
+ *
3194
+ * The edit is the same minimal in-place rewrite `applyMcpEntry` performs; the only
3195
+ * difference is that the classification was established by the async proof above rather
3196
+ * than by the synchronous classifier, so it is re-stated as `outdated` for the apply step
3197
+ * (which refuses a `conflict` by design).
3198
+ *
3199
+ * Everything the proof relied on is re-proved here, immediately before the write, because
3200
+ * proving the old path involves several filesystem probes and the operator (or another
3201
+ * tool) can change the config in that window:
3202
+ *
3203
+ * 1. the `$CODEX_HOME`/`agents` boundary is inspected again;
3204
+ * 2. `config.toml` is read again and its digest must equal the plan's fingerprint;
3205
+ * 3. the entry is re-classified and its recorded script re-proved as a real installation
3206
+ * of this package; anything else is refused, with the file kept.
3207
+ *
3208
+ * Exported for the deterministic race regression; `installMcpEntry` is its only
3209
+ * production caller.
3210
+ * @internal
3211
+ * @param {object} adopted - value from {@link adoptProvedMovedInstall}.
3212
+ * @param {{ changed: string[], refused: object[] }} outcome - mutable outcome.
3213
+ * @param {object} before - the status read the plan and proof came from.
3214
+ * @returns {Promise<void>} resolves after the attempt.
3215
+ */
3216
+ export async function adoptMovedInstall(adopted, outcome, before) {
3217
+ const { mcp } = before;
3218
+ const refuse = (code, message, reason) => {
3219
+ outcome.refused.push({ target: 'mcp', code, message, path: mcp.path, ...(reason === undefined ? {} : { reason }) });
3220
+ };
3221
+ // The proof and this write must still describe the same plan. A mismatched pair would
3222
+ // mean the caller re-entered the path with a proof made for another read.
3223
+ if (typeof adopted?.document?.text !== 'string'
3224
+ || typeof mcp.fingerprint !== 'string'
3225
+ || digest(adopted.document.text) !== mcp.fingerprint) {
3226
+ refuse('MCP_ENTRY_CONFLICT',
3227
+ 'the moved-install proof does not match the plan it is being written for, so nothing was written',
3228
+ 'proof-plan-mismatch');
3229
+ return;
3230
+ }
3231
+ // 1. The boundary can have become a link since the plan; writing through one would put
3232
+ // the entry outside the Codex home.
3233
+ const boundary = await inspectCodexBoundary(before.codexHome);
3234
+ if (boundary.blocked === true) {
3235
+ outcome.refused.push(linkedBoundaryRefusal({ ...before, boundary }));
3236
+ return;
3237
+ }
3238
+ // 2. The plan's digest is the race guard: the proof described those exact bytes.
3239
+ let loaded;
3240
+ try {
3241
+ loaded = await loadConfig(mcp.path);
3242
+ } catch (error) {
3243
+ refuse(
3244
+ typeof error?.code === 'string' ? error.code : 'CODEX_CONFIG_UNREADABLE',
3245
+ typeof error?.message === 'string' ? error.message : 'the Codex config could not be read',
3246
+ );
3247
+ return;
3248
+ }
3249
+ if (loaded.unreadable === true) {
3250
+ refuse('CODEX_CONFIG_UNSUPPORTED', 'the Codex config is not readable as TOML and was left untouched');
3251
+ return;
3252
+ }
3253
+ if (typeof mcp.fingerprint !== 'string' || digest(loaded.document.text) !== mcp.fingerprint) {
3254
+ refuse('MCP_ENTRY_CONFLICT',
3255
+ 'config.toml changed after the moved installation was proved, so nothing was written',
3256
+ 'config-changed');
3257
+ return;
3258
+ }
3259
+ // 3. Re-prove the CURRENT entry: same conflict, same owned facts, same real package.
3260
+ if (mcp.desired === null || mcp.desired === undefined) {
3261
+ refuse('MCP_ENTRY_CONFLICT', 'no owned entry shape is available for the moved installation');
3262
+ return;
3263
+ }
3264
+ const classification = classifyMcpEntry(loaded.document, mcp.desired);
3265
+ if (classification.marked !== true || classification.state !== MCP_STATES.conflict
3266
+ || classification.reason !== 'args-shape-not-ours') {
3267
+ refuse('MCP_ENTRY_CONFLICT',
3268
+ 'the mcp_servers.dsh-delegate entry is no longer the moved installation that was proved, so nothing was written',
3269
+ classification.reason ?? classification.state);
3270
+ return;
3271
+ }
3272
+ if (classification.previous?.command !== mcp.desired.command
3273
+ && !isLegacyDesktopCommand(classification.previous?.command)) {
3274
+ refuse('MCP_ENTRY_CONFLICT', 'the recorded command is not one this plugin wrote, so nothing was written', 'command-not-ours');
3275
+ return;
3276
+ }
3277
+ const currentArgs = Array.isArray(classification.previous?.args) ? classification.previous.args : [];
3278
+ if (currentArgs.length !== 1 || (await isExplicitlyMigratableScript(currentArgs[0], mcp.desired.args[0])) !== true) {
3279
+ refuse('MCP_ENTRY_CONFLICT',
3280
+ 'the recorded entry script is no longer provably an installation of this package, so nothing was written',
3281
+ 'script-not-provably-ours');
3282
+ return;
3283
+ }
3284
+ const asStale = { ...classification, state: MCP_STATES.outdated, reason: null };
3285
+ let next;
3286
+ try {
3287
+ next = applyMcpEntry(loaded.document, mcp.desired, asStale);
3288
+ } catch (error) {
3289
+ refuse(
3290
+ typeof error?.code === 'string' ? error.code : 'MCP_ENTRY_CONFLICT',
3291
+ typeof error?.message === 'string' ? error.message : 'the moved installation could not be adopted',
3292
+ );
3293
+ return;
3294
+ }
3295
+ if (next === null) return;
3296
+ await writeFileAtomic(mcp.path, next);
3297
+ outcome.changed.push('mcp');
3298
+ }
3299
+