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