@foundocs/foundocs-setup 0.3.3 → 0.3.4
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/README.md +39 -5
- package/dist/bridge.mjs +107 -98
- package/package.json +3 -3
- package/src/bridge.mjs +10 -1
- package/src/cli.mjs +8 -4
- package/src/runtime.mjs +68 -0
- package/src/setup.mjs +149 -22
package/README.md
CHANGED
|
@@ -2,21 +2,22 @@
|
|
|
2
2
|
|
|
3
3
|
Use the installation prompt from your project's Foundocs integration guide. It contains a ten-minute, one-use connection code, never an API key. The coding agent fixes an absolute project root and sends the prompt's JSON to the installer's **private stdin** using a process tool. Do not paste the JSON into shell command text, argv, logs, or a committed file.
|
|
4
4
|
|
|
5
|
-
Version **0.3.
|
|
5
|
+
Version **0.3.4** makes Codex MCP settings portable across teammates while keeping each installation key in private local storage. Existing owned absolute-path configurations can migrate without exchanging a code or rotating a key. For local development verification, build this package and run from its directory:
|
|
6
6
|
|
|
7
7
|
```text
|
|
8
8
|
node src/cli.mjs install --root /absolute/project
|
|
9
9
|
node src/cli.mjs doctor --root /absolute/project
|
|
10
10
|
node src/cli.mjs rollback --root /absolute/project
|
|
11
|
+
node src/cli.mjs migrate --root /absolute/project
|
|
11
12
|
```
|
|
12
13
|
|
|
13
14
|
The install command reads stdin until EOF. Commands never take codes or API keys as arguments. This package requires Node.js 22.19.0+ and a locally installed Claude Code or Codex CLI. Before exchanging the code it inspects the installed CLI's actual helper support, parses existing settings and checks private storage permissions. Missing or incompatible CLIs require installation/update or the manual guide. Codex's desktop app without its CLI cannot pass this automatic feature check.
|
|
14
15
|
|
|
15
16
|
Input JSON follows `SetupInstallInput` version 1: `client` (`claude` or `codex`), `projectId`, `workspaceId`, `attemptId`, `code`, `exchangeUrl`, `mcpUrl`, and `version: 1`. The code is exchanged once for an installation key; same-attempt reruns reuse that private key. A newly issued attempt can replace a revoked key while retaining the previous key privately. Existing keys are never automatically revoked.
|
|
16
17
|
|
|
17
|
-
Configuration is local to the exact `--root`: `foundocs.json`, a marked `AGENTS.md` block, and either `.codex/config.toml` or `.mcp.json`. Claude additionally receives a marked `CLAUDE.md` reference to `AGENTS.md`. The package also installs its English Foundocs skill at `.agents/skills/foundocs/` for Codex or `.claude/skills/foundocs/` for Claude, including the Dreaming protocol reference. The managed instruction block points to the selected client’s discoverable skill. Existing instructions and foreign MCP entries are preserved. Skill files are updated only when unchanged from the installer’s recorded version; foreign or user-edited skills stop preflight, and rollback preserves later user edits. Run `update-skills` to add the bundled skills to an older installation without a new connection code. Dreaming itself requires the connected server to expose `dream_memory` and `get_dream`; installation does not enable unavailable server capabilities. Conflicting project IDs, malformed files, symlinks, or a different same-name `foundocs` server stop installation before exchanging the code. Resolve a conflict explicitly; this installer does not overwrite it.
|
|
18
|
+
Configuration is local to the exact `--root`: `foundocs.json`, a marked `AGENTS.md` block, and either `.codex/config.toml` or `.mcp.json`. Claude additionally receives a marked `CLAUDE.md` reference to `AGENTS.md`. The package also installs its English Foundocs skill at `.agents/skills/foundocs/` for Codex or `.claude/skills/foundocs/` for Claude, including the Dreaming protocol reference. The managed instruction block points to the selected client’s discoverable skill. Existing instructions and foreign MCP entries are preserved. Skill files are updated only when unchanged from the installer’s recorded version. Byte-identical packaged files in a new clone are adopted locally; other foreign or user-edited skills stop preflight, and rollback preserves later user edits. Run `update-skills` to add the bundled skills to an older installation without a new connection code. Dreaming itself requires the connected server to expose `dream_memory` and `get_dream`; installation does not enable unavailable server capabilities. Conflicting project IDs, malformed files, symlinks, or a different same-name `foundocs` server stop installation before exchanging the code. Resolve a conflict explicitly; this installer does not overwrite it.
|
|
18
19
|
|
|
19
|
-
Keys, backups and installation journals live in `~/.local/share/foundocs/setup`, outside the project. `FOUNDOCS_SETUP_HOME` may select another absolute private directory outside the target project, including isolated test fixtures. Keep using that same value for doctor/rollback. Credentials are isolated by workspace, project, and canonical project root.
|
|
20
|
+
Keys, backups and installation journals live in `~/.local/share/foundocs/setup`, outside the project. `FOUNDOCS_SETUP_HOME` may select another absolute private directory outside the target project, including isolated test fixtures. Keep using that same value for doctor/rollback. Credentials are isolated by workspace, project, and canonical project root. Claude Code continues using a durable copied HTTP `headersHelper` with its original absolute Node and helper paths. Codex uses the exact-version npm package’s `mcp` command through `npx` on PATH; its project settings contain no user-specific path. Its stdio adapter forwards MCP tool discovery and calls to the same Remote HTTP endpoint with the saved Bearer key. This adapter preserves remote schemas, annotations, structured results and errors, and requires an explicit valid project ID on every call. A changed valid project ID is forwarded unchanged; the remote server enforces workspace access. It adds no remote service. macOS/Linux use user-only directories/files (0700/0600). Windows uses PowerShell to apply and verify a protected current-user-only ACL; unsupported ACL filesystems stop before code exchange.
|
|
20
21
|
|
|
21
22
|
The helper prefers the saved installation credential. To explicitly use a process-provided `FOUNDOCS_API_KEY`, also provide matching `FOUNDOCS_PROJECT_ID` and `FOUNDOCS_WORKSPACE_ID`. An unrelated shell key never silently overrides the saved workspace key. The helper's stdout contains authentication headers solely for the host MCP client; do not invoke it through tools that log stdout.
|
|
22
23
|
|
|
@@ -28,9 +29,42 @@ Doctor performs MCP initialize, tool discovery, and `get_project_context` with t
|
|
|
28
29
|
|
|
29
30
|
For response loss or failure before private key storage, the error reports the attempt ID and guide recovery route: inspect/revoke only that attempt's issued key and generate a new code. After key storage, rerun the same installation input. `rollback` restores only files still matching the installer-written content; concurrent edits are retained and reported. It preserves private credentials for retry. A stale operation lock after process interruption is never automatically deleted: confirm no installer is running before removing the reported private lock file.
|
|
30
31
|
|
|
32
|
+
## Shared Codex projects
|
|
33
|
+
|
|
34
|
+
Commit `foundocs.json`, the project `.codex/config.toml`, and the managed instructions/skills when the team shares them. A newly generated entry uses this transport (the actual file also lists supported environment variable **names**, never their values):
|
|
35
|
+
|
|
36
|
+
```toml
|
|
37
|
+
[mcp_servers.foundocs]
|
|
38
|
+
command = "npx"
|
|
39
|
+
args = ["--yes", "@foundocs/foundocs-setup@0.3.4", "mcp", "--project-id", "YOUR-PROJECT-UUID"]
|
|
40
|
+
env_vars = ["FOUNDOCS_SETUP_HOME", "FOUNDOCS_API_KEY", "FOUNDOCS_PROJECT_ID", "FOUNDOCS_WORKSPACE_ID", "STEERDOCS_SETUP_HOME", "STEERDOCS_API_KEY", "STEERDOCS_PROJECT_ID", "STEERDOCS_WORKSPACE_ID"]
|
|
41
|
+
startup_timeout_sec = 60
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Each teammate runs the integration prompt once for their own clone. This creates a local private manifest/key scoped to that canonical checkout; it retains the existing valid portable TOML byte for byte. Copying, moving or cloning a checkout does not transfer its authentication. A missing local installation returns a redacted error explaining how to install or diagnose it. No `.env` loader is needed, and the agent never reads the API key.
|
|
45
|
+
|
|
46
|
+
The host must have Node.js 22.19.0+ and npm/npx on its PATH. A desktop launched without your shell's PATH may need its environment configured or a restart. The first uncached `npx` launch requires npm registry access; later launches use npm's normal cache. The runtime version is pinned to an exact release for reproducibility. Reinstalling/authenticating with a newer installer preserves an existing valid pin; `update-skills` never upgrades the MCP runtime. An intentional runtime update is a reviewed change to the shared pin, followed by local install/migrate and host verification. A pinned registry command requires that release to have been published; local pre-release verification uses a packed artifact installed in an isolated fixture.
|
|
47
|
+
|
|
48
|
+
The runtime starts from the host's working directory and selects the nearest `foundocs.json`. It stops at a Git checkout boundary, a malformed nearer file or a project-ID mismatch. It never searches another checkout for a working credential. It validates the canonical root, project/workspace IDs, endpoint, recorded attempt, expected private credential path and file permissions before opening the remote connection. The explicit `--project-id` protects a nested project from silently inheriting its parent's transport. These are startup identity checks: tool calls still pass their explicit `project_id` unchanged and the remote server retains its existing workspace authorization rules.
|
|
49
|
+
|
|
50
|
+
`FOUNDOCS_SETUP_HOME` selects custom private storage through the host environment. Keep the same value when installing, starting Codex, diagnosing, migrating and rolling back. Supported scoped API-key override names and historical equivalents are forwarded through `env_vars`; values stay outside Git. Per-server `cwd`, `env` and URL overrides are rejected by setup/doctor because they can silently change installation selection. Tool allowlists and timeouts are preserved.
|
|
51
|
+
|
|
52
|
+
### Existing Codex installations
|
|
53
|
+
|
|
54
|
+
After this release is published:
|
|
55
|
+
|
|
56
|
+
```text
|
|
57
|
+
npx --yes @foundocs/foundocs-setup@0.3.4 migrate --root /absolute/project
|
|
58
|
+
npx --yes @foundocs/foundocs-setup@0.3.4 doctor --root /absolute/project
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`migrate` is offline, requires no connection code, and retains the credential bytes. It verifies the private manifest and journal against the original absolute transport, edits only the owned server's transport fields and preserves unrelated TOML, comments, tool settings and timeouts. Missing ownership evidence, changed execution settings and unsupported inline tables stop with the original file intact. An install rerun can perform the same migration while reusing its saved same-attempt key. `update-skills` remains skill-only.
|
|
62
|
+
|
|
63
|
+
Writes use the existing lock, atomic replacement, concurrency check and rollback journal. If interrupted, retain the journal and rerun the same command; confirm no process is running before clearing a stale lock. `rollback` restores unchanged setup edits to the recorded baseline and preserves later user edits and credentials. The baseline may predate migration when an installation already has a journal. After migration, restart/reconnect the trusted Codex project and call `get_project_context` through its MCP server. Doctor reports legacy transport migration separately from conflicting portable configuration; an independent doctor call does not prove the host connected.
|
|
64
|
+
|
|
31
65
|
## Verification status
|
|
32
66
|
|
|
33
|
-
The implementation includes unit/integration tests for both configuration formats, preservation, reruns, conflicts, credential isolation, redaction, recovery, rollback, protocol diagnostics, path quoting and ACL command generation. Local feature checks pass on macOS with Codex CLI 0.149.1 and Claude Code 2.1.284. Windows/Linux command paths are implemented, but real runtime verification on those operating systems is still required before claiming them verified.
|
|
67
|
+
The implementation includes unit/integration tests for both configuration formats, preservation, reruns, conflicts, credential isolation, redaction, recovery, rollback, protocol diagnostics, path quoting and ACL command generation. Local feature checks pass on macOS with Codex CLI 0.149.1 and Claude Code 2.1.284. Windows/Linux command paths are implemented, but real runtime verification on those operating systems is still required before claiming them verified. Package automated tests use isolated host capability fixtures. The 0.3.4 packed artifact was additionally verified in the product repository on macOS with a real Codex host, an isolated trusted CODEX_HOME, the generated project configuration, and an actual HTTP MCP get_project_context call. This does not verify Linux/Windows or a public npm release.
|
|
34
68
|
|
|
35
69
|
Development: `npm ci`, `npm test`, and `npm run typecheck`.
|
|
36
70
|
|
|
@@ -45,7 +79,7 @@ Existing recorded installations can update the skill and managed instructions wi
|
|
|
45
79
|
node /absolute/path/to/foundocs-setup/src/cli.mjs update-skills --root /absolute/project
|
|
46
80
|
```
|
|
47
81
|
|
|
48
|
-
The equivalent command for this release is `npx --yes @foundocs/foundocs-setup@0.3.
|
|
82
|
+
The equivalent command for this release is `npx --yes @foundocs/foundocs-setup@0.3.4 update-skills --root /absolute/project`. The local commands above run this checkout; a pinned npm command requires that registry release to exist.
|
|
49
83
|
|
|
50
84
|
Updates preserve MCP settings, project configuration, authentication helpers and private keys, including installations that still use the historical configuration filename. The private `skills.json` records installed/pending asset hashes for interruption recovery. Foreign same-name files and local skill edits stop installation/update before project writes; move or reconcile the reported file explicitly, then retry. Unrelated skills and instructions are retained. `rollback` includes skill assets and preserves concurrent edits.
|
|
51
85
|
|
package/dist/bridge.mjs
CHANGED
|
@@ -3481,7 +3481,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
|
|
|
3481
3481
|
var NONE = 0;
|
|
3482
3482
|
var ASSUMED = 1;
|
|
3483
3483
|
var PROVEN = 2;
|
|
3484
|
-
function isRecursive(inst, stack,
|
|
3484
|
+
function isRecursive(inst, stack, resolve3) {
|
|
3485
3485
|
const cached2 = recursive.get(inst);
|
|
3486
3486
|
if (cached2 !== void 0)
|
|
3487
3487
|
return cached2 ? PROVEN : NONE;
|
|
@@ -3491,7 +3491,7 @@ function isRecursive(inst, stack, resolve2) {
|
|
|
3491
3491
|
let result = NONE;
|
|
3492
3492
|
const check = (child) => {
|
|
3493
3493
|
if (result !== PROVEN && child?._zod) {
|
|
3494
|
-
const answer = isRecursive(child, stack,
|
|
3494
|
+
const answer = isRecursive(child, stack, resolve3);
|
|
3495
3495
|
if (answer > result)
|
|
3496
3496
|
result = answer;
|
|
3497
3497
|
}
|
|
@@ -3502,7 +3502,7 @@ function isRecursive(inst, stack, resolve2) {
|
|
|
3502
3502
|
const desc = Object.getOwnPropertyDescriptor(sh, key);
|
|
3503
3503
|
if (spread && !desc.enumerable)
|
|
3504
3504
|
continue;
|
|
3505
|
-
const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack,
|
|
3505
|
+
const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve3) : NONE;
|
|
3506
3506
|
if (child > answer)
|
|
3507
3507
|
answer = child;
|
|
3508
3508
|
}
|
|
@@ -3566,7 +3566,7 @@ function isRecursive(inst, stack, resolve2) {
|
|
|
3566
3566
|
break;
|
|
3567
3567
|
// `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
|
|
3568
3568
|
case "lazy": {
|
|
3569
|
-
const inner = def._cachedInner ?? (
|
|
3569
|
+
const inner = def._cachedInner ?? (resolve3 ? inst._zod.innerType : void 0);
|
|
3570
3570
|
merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
|
|
3571
3571
|
break;
|
|
3572
3572
|
}
|
|
@@ -11084,8 +11084,8 @@ function datetimeReferenceSchemas(pattern) {
|
|
|
11084
11084
|
0
|
|
11085
11085
|
];
|
|
11086
11086
|
if (fractionDigits) precisions.push(Number(fractionDigits[1]));
|
|
11087
|
-
return [false, true].flatMap((
|
|
11088
|
-
local
|
|
11087
|
+
return [false, true].flatMap((local) => [false, true].flatMap((offset) => precisions.map((precision) => iso_exports.datetime({
|
|
11088
|
+
local,
|
|
11089
11089
|
offset,
|
|
11090
11090
|
precision
|
|
11091
11091
|
}))));
|
|
@@ -11266,14 +11266,14 @@ function inputRequiredRoundsExceededMessage(method, maxRounds) {
|
|
|
11266
11266
|
return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`;
|
|
11267
11267
|
}
|
|
11268
11268
|
function sleep(ms, signal) {
|
|
11269
|
-
return new Promise((
|
|
11269
|
+
return new Promise((resolve3, reject) => {
|
|
11270
11270
|
if (signal?.aborted) {
|
|
11271
11271
|
reject(signal.reason instanceof SdkError ? signal.reason : new SdkError(SdkErrorCode.RequestTimeout, String(signal.reason)));
|
|
11272
11272
|
return;
|
|
11273
11273
|
}
|
|
11274
11274
|
const timer = setTimeout(() => {
|
|
11275
11275
|
signal?.removeEventListener("abort", onAbort);
|
|
11276
|
-
|
|
11276
|
+
resolve3();
|
|
11277
11277
|
}, ms);
|
|
11278
11278
|
const onAbort = () => {
|
|
11279
11279
|
clearTimeout(timer);
|
|
@@ -12117,7 +12117,7 @@ var Protocol = class {
|
|
|
12117
12117
|
const flowStartedAt = Date.now();
|
|
12118
12118
|
let onAbort;
|
|
12119
12119
|
let cleanupMessageId;
|
|
12120
|
-
return new Promise((
|
|
12120
|
+
return new Promise((resolve3, reject) => {
|
|
12121
12121
|
const earlyReject = (error2) => {
|
|
12122
12122
|
reject(error2);
|
|
12123
12123
|
};
|
|
@@ -12186,7 +12186,7 @@ var Protocol = class {
|
|
|
12186
12186
|
}
|
|
12187
12187
|
if (decoded.kind === "invalid") return reject(decoded.error);
|
|
12188
12188
|
if (decoded.kind === "input_required") {
|
|
12189
|
-
if (options?.allowInputRequired === true) return
|
|
12189
|
+
if (options?.allowInputRequired === true) return resolve3(manualInputRequiredValue(decoded));
|
|
12190
12190
|
const flow = {
|
|
12191
12191
|
codec,
|
|
12192
12192
|
request,
|
|
@@ -12198,11 +12198,11 @@ var Protocol = class {
|
|
|
12198
12198
|
params
|
|
12199
12199
|
}, resultSchema, legOptions)
|
|
12200
12200
|
};
|
|
12201
|
-
return
|
|
12201
|
+
return resolve3(this._resolveNonCompleteResult(decoded, flow));
|
|
12202
12202
|
}
|
|
12203
12203
|
const result = decoded.result;
|
|
12204
12204
|
validateStandardSchema(resultSchema, result).then((parseResult) => {
|
|
12205
|
-
if (parseResult.success)
|
|
12205
|
+
if (parseResult.success) resolve3(parseResult.data);
|
|
12206
12206
|
else reject(new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`));
|
|
12207
12207
|
}, reject);
|
|
12208
12208
|
});
|
|
@@ -15186,7 +15186,7 @@ var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
|
15186
15186
|
ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
|
|
15187
15187
|
const schOrFunc = root.refs[ref];
|
|
15188
15188
|
if (schOrFunc) return schOrFunc;
|
|
15189
|
-
let _sch =
|
|
15189
|
+
let _sch = resolve3.call(this, root, ref);
|
|
15190
15190
|
if (_sch === void 0) {
|
|
15191
15191
|
const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref];
|
|
15192
15192
|
const { schemaId } = this.opts;
|
|
@@ -15212,7 +15212,7 @@ var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
|
15212
15212
|
function sameSchemaEnv(s1, s2) {
|
|
15213
15213
|
return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
|
|
15214
15214
|
}
|
|
15215
|
-
function
|
|
15215
|
+
function resolve3(root, ref) {
|
|
15216
15216
|
let sch;
|
|
15217
15217
|
while (typeof (sch = this.refs[ref]) == "string") ref = sch;
|
|
15218
15218
|
return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
|
|
@@ -15662,7 +15662,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
15662
15662
|
else if (typeof uri === "object") uri = parse2(serialize(uri, options), options);
|
|
15663
15663
|
return uri;
|
|
15664
15664
|
}
|
|
15665
|
-
function
|
|
15665
|
+
function resolve3(baseURI, relativeURI, options) {
|
|
15666
15666
|
const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
|
|
15667
15667
|
const resolved = resolveComponent(parse2(baseURI, schemelessOptions), parse2(relativeURI, schemelessOptions), schemelessOptions, true);
|
|
15668
15668
|
schemelessOptions.skipEscape = true;
|
|
@@ -15836,7 +15836,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
15836
15836
|
const fastUri = {
|
|
15837
15837
|
SCHEMES,
|
|
15838
15838
|
normalize,
|
|
15839
|
-
resolve:
|
|
15839
|
+
resolve: resolve3,
|
|
15840
15840
|
resolveComponent,
|
|
15841
15841
|
equal,
|
|
15842
15842
|
serialize,
|
|
@@ -21404,14 +21404,14 @@ var ProbeWindow = class ProbeWindow2 {
|
|
|
21404
21404
|
*/
|
|
21405
21405
|
async exchange(buildRequest, timeoutMs) {
|
|
21406
21406
|
const id = `server-discover-probe-${++this._probeCounter}`;
|
|
21407
|
-
return new Promise((
|
|
21407
|
+
return new Promise((resolve3) => {
|
|
21408
21408
|
let settled = false;
|
|
21409
21409
|
const settle2 = (reply) => {
|
|
21410
21410
|
if (settled) return;
|
|
21411
21411
|
settled = true;
|
|
21412
21412
|
clearTimeout(timer);
|
|
21413
21413
|
if (this._pending?.id === id) this._pending = void 0;
|
|
21414
|
-
|
|
21414
|
+
resolve3(reply);
|
|
21415
21415
|
};
|
|
21416
21416
|
const timer = setTimeout(() => settle2({ kind: "timeout" }), timeoutMs);
|
|
21417
21417
|
this._pending = {
|
|
@@ -22625,13 +22625,13 @@ var Client = class extends Protocol {
|
|
|
22625
22625
|
let onCallerAbort;
|
|
22626
22626
|
let resolveOpening;
|
|
22627
22627
|
let rejectOpening;
|
|
22628
|
-
const opening = new Promise((
|
|
22629
|
-
resolveOpening =
|
|
22628
|
+
const opening = new Promise((resolve3, reject) => {
|
|
22629
|
+
resolveOpening = resolve3;
|
|
22630
22630
|
rejectOpening = reject;
|
|
22631
22631
|
});
|
|
22632
22632
|
let resolveClosed;
|
|
22633
|
-
const closed = new Promise((
|
|
22634
|
-
resolveClosed =
|
|
22633
|
+
const closed = new Promise((resolve3) => {
|
|
22634
|
+
resolveClosed = resolve3;
|
|
22635
22635
|
});
|
|
22636
22636
|
const settle2 = (outcome) => {
|
|
22637
22637
|
if (state === "closed") return;
|
|
@@ -22660,7 +22660,7 @@ var Client = class extends Protocol {
|
|
|
22660
22660
|
}).catch(() => {
|
|
22661
22661
|
});
|
|
22662
22662
|
};
|
|
22663
|
-
const
|
|
22663
|
+
const close = async () => {
|
|
22664
22664
|
if (state === "closed") return;
|
|
22665
22665
|
settle2({ cause: "local" });
|
|
22666
22666
|
await wireTeardown();
|
|
@@ -22717,7 +22717,7 @@ var Client = class extends Protocol {
|
|
|
22717
22717
|
}
|
|
22718
22718
|
return {
|
|
22719
22719
|
honoredFilter: await opening,
|
|
22720
|
-
close
|
|
22720
|
+
close,
|
|
22721
22721
|
closed
|
|
22722
22722
|
};
|
|
22723
22723
|
}
|
|
@@ -26865,8 +26865,8 @@ function datetimeReferenceSchemas2(pattern) {
|
|
|
26865
26865
|
0
|
|
26866
26866
|
];
|
|
26867
26867
|
if (fractionDigits) precisions.push(Number(fractionDigits[1]));
|
|
26868
|
-
return [false, true].flatMap((
|
|
26869
|
-
local
|
|
26868
|
+
return [false, true].flatMap((local) => [false, true].flatMap((offset) => precisions.map((precision) => iso_exports.datetime({
|
|
26869
|
+
local,
|
|
26870
26870
|
offset,
|
|
26871
26871
|
precision
|
|
26872
26872
|
}))));
|
|
@@ -27030,14 +27030,14 @@ function inputRequiredRoundsExceededMessage2(method, maxRounds) {
|
|
|
27030
27030
|
return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`;
|
|
27031
27031
|
}
|
|
27032
27032
|
function sleep2(ms, signal) {
|
|
27033
|
-
return new Promise((
|
|
27033
|
+
return new Promise((resolve3, reject) => {
|
|
27034
27034
|
if (signal?.aborted) {
|
|
27035
27035
|
reject(signal.reason instanceof SdkError2 ? signal.reason : new SdkError2(SdkErrorCode2.RequestTimeout, String(signal.reason)));
|
|
27036
27036
|
return;
|
|
27037
27037
|
}
|
|
27038
27038
|
const timer = setTimeout(() => {
|
|
27039
27039
|
signal?.removeEventListener("abort", onAbort);
|
|
27040
|
-
|
|
27040
|
+
resolve3();
|
|
27041
27041
|
}, ms);
|
|
27042
27042
|
const onAbort = () => {
|
|
27043
27043
|
clearTimeout(timer);
|
|
@@ -27833,7 +27833,7 @@ var Protocol2 = class {
|
|
|
27833
27833
|
const flowStartedAt = Date.now();
|
|
27834
27834
|
let onAbort;
|
|
27835
27835
|
let cleanupMessageId;
|
|
27836
|
-
return new Promise((
|
|
27836
|
+
return new Promise((resolve3, reject) => {
|
|
27837
27837
|
const earlyReject = (error2) => {
|
|
27838
27838
|
reject(error2);
|
|
27839
27839
|
};
|
|
@@ -27902,7 +27902,7 @@ var Protocol2 = class {
|
|
|
27902
27902
|
}
|
|
27903
27903
|
if (decoded.kind === "invalid") return reject(decoded.error);
|
|
27904
27904
|
if (decoded.kind === "input_required") {
|
|
27905
|
-
if (options?.allowInputRequired === true) return
|
|
27905
|
+
if (options?.allowInputRequired === true) return resolve3(manualInputRequiredValue2(decoded));
|
|
27906
27906
|
const flow = {
|
|
27907
27907
|
codec,
|
|
27908
27908
|
request,
|
|
@@ -27914,11 +27914,11 @@ var Protocol2 = class {
|
|
|
27914
27914
|
params
|
|
27915
27915
|
}, resultSchema, legOptions)
|
|
27916
27916
|
};
|
|
27917
|
-
return
|
|
27917
|
+
return resolve3(this._resolveNonCompleteResult(decoded, flow));
|
|
27918
27918
|
}
|
|
27919
27919
|
const result = decoded.result;
|
|
27920
27920
|
validateStandardSchema2(resultSchema, result).then((parseResult) => {
|
|
27921
|
-
if (parseResult.success)
|
|
27921
|
+
if (parseResult.success) resolve3(parseResult.data);
|
|
27922
27922
|
else reject(new SdkError2(SdkErrorCode2.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`));
|
|
27923
27923
|
}, reject);
|
|
27924
27924
|
});
|
|
@@ -30777,7 +30777,7 @@ var require_compile2 = /* @__PURE__ */ __commonJSMin2(((exports) => {
|
|
|
30777
30777
|
ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
|
|
30778
30778
|
const schOrFunc = root.refs[ref];
|
|
30779
30779
|
if (schOrFunc) return schOrFunc;
|
|
30780
|
-
let _sch =
|
|
30780
|
+
let _sch = resolve3.call(this, root, ref);
|
|
30781
30781
|
if (_sch === void 0) {
|
|
30782
30782
|
const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref];
|
|
30783
30783
|
const { schemaId } = this.opts;
|
|
@@ -30803,7 +30803,7 @@ var require_compile2 = /* @__PURE__ */ __commonJSMin2(((exports) => {
|
|
|
30803
30803
|
function sameSchemaEnv(s1, s2) {
|
|
30804
30804
|
return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
|
|
30805
30805
|
}
|
|
30806
|
-
function
|
|
30806
|
+
function resolve3(root, ref) {
|
|
30807
30807
|
let sch;
|
|
30808
30808
|
while (typeof (sch = this.refs[ref]) == "string") ref = sch;
|
|
30809
30809
|
return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
|
|
@@ -31253,7 +31253,7 @@ var require_fast_uri2 = /* @__PURE__ */ __commonJSMin2(((exports, module) => {
|
|
|
31253
31253
|
else if (typeof uri === "object") uri = parse2(serialize(uri, options), options);
|
|
31254
31254
|
return uri;
|
|
31255
31255
|
}
|
|
31256
|
-
function
|
|
31256
|
+
function resolve3(baseURI, relativeURI, options) {
|
|
31257
31257
|
const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
|
|
31258
31258
|
const resolved = resolveComponent(parse2(baseURI, schemelessOptions), parse2(relativeURI, schemelessOptions), schemelessOptions, true);
|
|
31259
31259
|
schemelessOptions.skipEscape = true;
|
|
@@ -31427,7 +31427,7 @@ var require_fast_uri2 = /* @__PURE__ */ __commonJSMin2(((exports, module) => {
|
|
|
31427
31427
|
const fastUri = {
|
|
31428
31428
|
SCHEMES,
|
|
31429
31429
|
normalize,
|
|
31430
|
-
resolve:
|
|
31430
|
+
resolve: resolve3,
|
|
31431
31431
|
resolveComponent,
|
|
31432
31432
|
equal,
|
|
31433
31433
|
serialize,
|
|
@@ -36050,7 +36050,7 @@ var StdioServerTransport = class {
|
|
|
36050
36050
|
}
|
|
36051
36051
|
send(message) {
|
|
36052
36052
|
if (this._closed) return Promise.reject(/* @__PURE__ */ new Error("StdioServerTransport is closed"));
|
|
36053
|
-
return new Promise((
|
|
36053
|
+
return new Promise((resolve3, reject) => {
|
|
36054
36054
|
const json = serializeMessage2(message);
|
|
36055
36055
|
let settled = false;
|
|
36056
36056
|
const onError = (error2) => {
|
|
@@ -36065,14 +36065,14 @@ var StdioServerTransport = class {
|
|
|
36065
36065
|
settled = true;
|
|
36066
36066
|
this._stdout.off("error", onError);
|
|
36067
36067
|
this._stdout.off("drain", onDrain);
|
|
36068
|
-
|
|
36068
|
+
resolve3();
|
|
36069
36069
|
};
|
|
36070
36070
|
this._stdout.once("error", onError);
|
|
36071
36071
|
if (this._stdout.write(json)) {
|
|
36072
36072
|
if (settled) return;
|
|
36073
36073
|
settled = true;
|
|
36074
36074
|
this._stdout.off("error", onError);
|
|
36075
|
-
|
|
36075
|
+
resolve3();
|
|
36076
36076
|
} else if (!settled) this._stdout.once("drain", onDrain);
|
|
36077
36077
|
});
|
|
36078
36078
|
}
|
|
@@ -36096,8 +36096,8 @@ var legacy = Object.freeze({
|
|
|
36096
36096
|
projectEnv: "STEERDOCS_PROJECT_ID",
|
|
36097
36097
|
workspaceEnv: "STEERDOCS_WORKSPACE_ID"
|
|
36098
36098
|
});
|
|
36099
|
-
function legacyCredential(env,
|
|
36100
|
-
return env[legacy.projectEnv] ===
|
|
36099
|
+
function legacyCredential(env, projectId, workspaceId) {
|
|
36100
|
+
return env[legacy.projectEnv] === projectId && env[legacy.workspaceEnv] === workspaceId ? env[legacy.keyEnv] : void 0;
|
|
36101
36101
|
}
|
|
36102
36102
|
|
|
36103
36103
|
// src/auth.mjs
|
|
@@ -36106,23 +36106,23 @@ async function windowsPrivateAcl(path, { directory = false, apply = false, execu
|
|
|
36106
36106
|
const script = `$ErrorActionPreference='Stop'; $p=[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('${target}')); $sid=[Security.Principal.WindowsIdentity]::GetCurrent().User; $acl=Get-Acl -LiteralPath $p; ${apply ? `$acl.SetAccessRuleProtection($true,$false); foreach($rule in @($acl.Access)) { [void]$acl.RemoveAccessRuleSpecific($rule) }; $acl.SetOwner($sid); $rule=New-Object Security.AccessControl.FileSystemAccessRule($sid,'FullControl','${directory ? "ContainerInherit,ObjectInherit" : "None"}','None','Allow'); $acl.AddAccessRule($rule); Set-Acl -LiteralPath $p -AclObject $acl; $acl=Get-Acl -LiteralPath $p;` : ""} if(!$acl.AreAccessRulesProtected -or $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $sid.Value) { throw 'Unsafe owner or inheritance' }; $rules=@($acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])); if($rules.Count -eq 0) { throw 'Missing private access' }; foreach($rule in $rules) { if($rule.IdentityReference.Value -ne $sid.Value -or $rule.AccessControlType -ne 'Allow' -or $rule.IsInherited -or ($rule.FileSystemRights -band [Security.AccessControl.FileSystemRights]::FullControl) -ne [Security.AccessControl.FileSystemRights]::FullControl) { throw 'Unsafe access rule' } };`;
|
|
36107
36107
|
await execute("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { timeout: 1e4, windowsHide: true, maxBuffer: 65536 });
|
|
36108
36108
|
}
|
|
36109
|
-
async function readCredential(path,
|
|
36109
|
+
async function readCredential(path, projectId, workspaceId) {
|
|
36110
36110
|
const info = await lstat(path);
|
|
36111
36111
|
if (!info.isFile() || info.isSymbolicLink() || process.platform !== "win32" && info.mode & 63) throw new Error("Credential permissions are unsafe.");
|
|
36112
36112
|
if (process.platform === "win32") await windowsPrivateAcl(path);
|
|
36113
36113
|
const saved = JSON.parse(await readFile(path, "utf8"));
|
|
36114
|
-
if (saved.projectId !==
|
|
36115
|
-
const envMatches = process.env.FOUNDOCS_PROJECT_ID ===
|
|
36114
|
+
if (saved.projectId !== projectId || saved.workspaceId !== workspaceId || typeof saved.value !== "string" || !saved.value || /[\r\n]/.test(saved.value)) throw new Error("Credential identity is invalid.");
|
|
36115
|
+
const envMatches = process.env.FOUNDOCS_PROJECT_ID === projectId && process.env.FOUNDOCS_WORKSPACE_ID === workspaceId;
|
|
36116
36116
|
const hasCurrentScope = ["FOUNDOCS_API_KEY", "FOUNDOCS_PROJECT_ID", "FOUNDOCS_WORKSPACE_ID"].some((name) => process.env[name] !== void 0);
|
|
36117
|
-
const override = hasCurrentScope ? envMatches ? process.env.FOUNDOCS_API_KEY : void 0 : legacyCredential(process.env,
|
|
36117
|
+
const override = hasCurrentScope ? envMatches ? process.env.FOUNDOCS_API_KEY : void 0 : legacyCredential(process.env, projectId, workspaceId);
|
|
36118
36118
|
const value = override || saved.value;
|
|
36119
36119
|
if (/[\r\n]/.test(value)) throw new Error("Credential is invalid.");
|
|
36120
36120
|
return value;
|
|
36121
36121
|
}
|
|
36122
36122
|
if (process.argv[1] && process.argv[2] === "--headers" && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
|
|
36123
36123
|
try {
|
|
36124
|
-
const [path,
|
|
36125
|
-
const key = await readCredential(path,
|
|
36124
|
+
const [path, projectId, workspaceId] = process.argv.slice(3);
|
|
36125
|
+
const key = await readCredential(path, projectId, workspaceId);
|
|
36126
36126
|
process.stdout.write(JSON.stringify({ Authorization: `Bearer ${key}` }));
|
|
36127
36127
|
} catch {
|
|
36128
36128
|
process.stderr.write("Foundocs authentication unavailable. Run foundocs-setup doctor.\n");
|
|
@@ -36131,55 +36131,64 @@ if (process.argv[1] && process.argv[2] === "--headers" && import.meta.url === pa
|
|
|
36131
36131
|
}
|
|
36132
36132
|
|
|
36133
36133
|
// src/bridge.mjs
|
|
36134
|
-
|
|
36135
|
-
|
|
36136
|
-
|
|
36137
|
-
|
|
36138
|
-
|
|
36139
|
-
|
|
36140
|
-
|
|
36141
|
-
|
|
36142
|
-
}
|
|
36143
|
-
|
|
36144
|
-
|
|
36145
|
-
|
|
36146
|
-
|
|
36147
|
-
|
|
36148
|
-
|
|
36149
|
-
|
|
36150
|
-
|
|
36151
|
-
|
|
36152
|
-
|
|
36153
|
-
|
|
36154
|
-
|
|
36155
|
-
|
|
36156
|
-
|
|
36157
|
-
|
|
36158
|
-
|
|
36159
|
-
|
|
36160
|
-
|
|
36161
|
-
|
|
36162
|
-
|
|
36163
|
-
|
|
36164
|
-
|
|
36165
|
-
|
|
36166
|
-
|
|
36167
|
-
|
|
36168
|
-
|
|
36169
|
-
|
|
36170
|
-
|
|
36171
|
-
|
|
36172
|
-
|
|
36173
|
-
|
|
36174
|
-
|
|
36175
|
-
|
|
36176
|
-
|
|
36177
|
-
|
|
36178
|
-
|
|
36179
|
-
|
|
36180
|
-
|
|
36181
|
-
|
|
36182
|
-
|
|
36183
|
-
|
|
36184
|
-
|
|
36134
|
+
import { pathToFileURL as pathToFileURL2 } from "node:url";
|
|
36135
|
+
import { resolve as resolve2 } from "node:path";
|
|
36136
|
+
async function runBridge({ credentialPath, projectId, workspaceId, mcpUrl: endpoint }) {
|
|
36137
|
+
let remote, local;
|
|
36138
|
+
async function close() {
|
|
36139
|
+
await remote?.close().catch(() => {
|
|
36140
|
+
});
|
|
36141
|
+
await local?.close().catch(() => {
|
|
36142
|
+
});
|
|
36143
|
+
}
|
|
36144
|
+
try {
|
|
36145
|
+
const url2 = new URL(endpoint);
|
|
36146
|
+
if (url2.protocol !== "https:" && !(url2.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url2.hostname)) || url2.username || url2.password || url2.search || url2.hash) throw new Error();
|
|
36147
|
+
const key = await readCredential(credentialPath, projectId, workspaceId);
|
|
36148
|
+
remote = new Client({ name: "foundocs-local-auth", version: "0.2.0" });
|
|
36149
|
+
const transport = new StreamableHTTPClientTransport(url2, {
|
|
36150
|
+
requestInit: { headers: { Authorization: `Bearer ${key}` } },
|
|
36151
|
+
fetch: (target, init) => {
|
|
36152
|
+
if (new URL(typeof target === "string" || target instanceof URL ? target : target.url).origin !== url2.origin) throw new Error("Origin changed");
|
|
36153
|
+
return fetch(target, { ...init, redirect: "error", signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(2e4)]) : AbortSignal.timeout(2e4) });
|
|
36154
|
+
}
|
|
36155
|
+
});
|
|
36156
|
+
await remote.connect(transport, { timeout: 2e4 });
|
|
36157
|
+
local = new Server({ name: "foundocs", version: "0.2.0" }, { capabilities: { tools: {} }, instructions: remote.getInstructions() });
|
|
36158
|
+
local.setRequestHandler("tools/list", async (request) => {
|
|
36159
|
+
try {
|
|
36160
|
+
return await remote.listTools(request.params);
|
|
36161
|
+
} catch {
|
|
36162
|
+
throw new ProtocolError3(ProtocolErrorCode2.InternalError, "Foundocs tool discovery failed. Run foundocs-setup doctor.");
|
|
36163
|
+
}
|
|
36164
|
+
});
|
|
36165
|
+
local.setRequestHandler("tools/call", async (request) => {
|
|
36166
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(request.params.arguments?.project_id)) throw new ProtocolError3(ProtocolErrorCode2.InvalidParams, "Read and pass the explicit project_id from the governing foundocs.json.");
|
|
36167
|
+
try {
|
|
36168
|
+
return await remote.callTool(request.params);
|
|
36169
|
+
} catch {
|
|
36170
|
+
throw new ProtocolError3(ProtocolErrorCode2.InternalError, "Foundocs request failed. Check authentication and connectivity. Retry writes only with the same requestId and input.");
|
|
36171
|
+
}
|
|
36172
|
+
});
|
|
36173
|
+
local.onerror = () => process.stderr.write("Foundocs local MCP transport error.\n");
|
|
36174
|
+
remote.onerror = () => process.stderr.write("Foundocs remote MCP transport error.\n");
|
|
36175
|
+
process.stdin.on("end", () => {
|
|
36176
|
+
void close();
|
|
36177
|
+
});
|
|
36178
|
+
for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => {
|
|
36179
|
+
void close().finally(() => process.exit(0));
|
|
36180
|
+
});
|
|
36181
|
+
await local.connect(new StdioServerTransport());
|
|
36182
|
+
} catch {
|
|
36183
|
+
process.stderr.write("Foundocs authentication bridge unavailable. Run foundocs-setup doctor.\n");
|
|
36184
|
+
await close();
|
|
36185
|
+
process.exitCode = 1;
|
|
36186
|
+
}
|
|
36187
|
+
}
|
|
36188
|
+
if (process.argv[1] && import.meta.url === pathToFileURL2(resolve2(process.argv[1])).href) {
|
|
36189
|
+
const [credentialPath, projectId, workspaceId, mcpUrl] = process.argv.slice(2);
|
|
36190
|
+
await runBridge({ credentialPath, projectId, workspaceId, mcpUrl });
|
|
36185
36191
|
}
|
|
36192
|
+
export {
|
|
36193
|
+
runBridge
|
|
36194
|
+
};
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@foundocs/foundocs-setup",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.4",
|
|
4
4
|
"description": "Repeatable project setup and agent skills for the Foundocs remote MCP server",
|
|
5
5
|
"foundocsRelease": {
|
|
6
|
-
"summary": "
|
|
6
|
+
"summary": "Make Codex MCP configuration portable across teammates with a pinned npm runtime and private per-installation credentials; migrate existing owned configurations without rotating keys."
|
|
7
7
|
},
|
|
8
8
|
"type": "module",
|
|
9
9
|
"bin": {
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"build": "node build.mjs",
|
|
27
27
|
"prepack": "node build.mjs",
|
|
28
28
|
"test": "node build.mjs && node --test test/*.test.mjs",
|
|
29
|
-
"typecheck": "node --check src/cli.mjs && node --check src/setup.mjs && node --check src/auth.mjs && node --check src/bridge.mjs && node --check src/legacy-compat.mjs && node --check src/skill-assets.mjs"
|
|
29
|
+
"typecheck": "node --check src/cli.mjs && node --check src/setup.mjs && node --check src/auth.mjs && node --check src/bridge.mjs && node --check src/legacy-compat.mjs && node --check src/skill-assets.mjs && node --check src/runtime.mjs"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
32
|
"@modelcontextprotocol/client": "2.3.1",
|
package/src/bridge.mjs
CHANGED
|
@@ -5,8 +5,10 @@ import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/cli
|
|
|
5
5
|
import { Server, ProtocolError, ProtocolErrorCode } from '@modelcontextprotocol/server';
|
|
6
6
|
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
|
|
7
7
|
import { readCredential } from './auth.mjs';
|
|
8
|
+
import { pathToFileURL } from 'node:url';
|
|
9
|
+
import { resolve } from 'node:path';
|
|
8
10
|
|
|
9
|
-
|
|
11
|
+
export async function runBridge({ credentialPath, projectId, workspaceId, mcpUrl: endpoint }) {
|
|
10
12
|
let remote, local;
|
|
11
13
|
async function close() {
|
|
12
14
|
await remote?.close().catch(() => {});
|
|
@@ -44,3 +46,10 @@ try {
|
|
|
44
46
|
process.stderr.write('Foundocs authentication bridge unavailable. Run foundocs-setup doctor.\n');
|
|
45
47
|
await close(); process.exitCode = 1;
|
|
46
48
|
}
|
|
49
|
+
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
|
|
53
|
+
const [credentialPath, projectId, workspaceId, mcpUrl] = process.argv.slice(2);
|
|
54
|
+
await runBridge({ credentialPath, projectId, workspaceId, mcpUrl });
|
|
55
|
+
}
|
package/src/cli.mjs
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { install, doctor, rollback, updateSkills, SetupError } from './setup.mjs';
|
|
2
|
+
import { install, doctor, rollback, updateSkills, migrate, SetupError } from './setup.mjs';
|
|
3
3
|
|
|
4
4
|
const [command, ...args] = process.argv.slice(2);
|
|
5
5
|
try {
|
|
6
6
|
if (command === '--help' || command === '-h') {
|
|
7
|
-
process.stdout.write('foundocs-setup install --root ABSOLUTE_PATH < private-input.json\nfoundocs-setup doctor --root ABSOLUTE_PATH\nfoundocs-setup update-skills --root ABSOLUTE_PATH\nfoundocs-setup rollback --root ABSOLUTE_PATH\nInstall reads the one-time code from private stdin only. Never put credentials in argv or shell command text.\n');
|
|
7
|
+
process.stdout.write('foundocs-setup install --root ABSOLUTE_PATH < private-input.json\nfoundocs-setup doctor --root ABSOLUTE_PATH\nfoundocs-setup update-skills --root ABSOLUTE_PATH\nfoundocs-setup rollback --root ABSOLUTE_PATH\nfoundocs-setup migrate --root ABSOLUTE_PATH\nfoundocs-setup mcp --project-id UUID\nInstall reads the one-time code from private stdin only. Never put credentials in argv or shell command text.\n');
|
|
8
|
+
} else if (command === 'mcp') {
|
|
9
|
+
if (args.length !== 2 || args[0] !== '--project-id') throw new SetupError('runtime', 'Use mcp --project-id UUID from the configured project directory.');
|
|
10
|
+
const { startRuntime } = await import('./runtime.mjs');
|
|
11
|
+
await startRuntime(args[1]);
|
|
8
12
|
} else {
|
|
9
|
-
if (!['install', 'doctor', 'rollback', 'update-skills'].includes(command) || args.length !== 2 || args[0] !== '--root') throw new SetupError('input', 'Use install, doctor, rollback, or update-skills with --root ABSOLUTE_PATH.');
|
|
13
|
+
if (!['install', 'doctor', 'rollback', 'update-skills', 'migrate'].includes(command) || args.length !== 2 || args[0] !== '--root') throw new SetupError('input', 'Use install, doctor, rollback, migrate, or update-skills with --root ABSOLUTE_PATH.');
|
|
10
14
|
let result;
|
|
11
15
|
if (command === 'install') {
|
|
12
16
|
if (process.stdin.isTTY) throw new SetupError('input', 'Supply installation JSON through private stdin.');
|
|
@@ -17,7 +21,7 @@ try {
|
|
|
17
21
|
}
|
|
18
22
|
try { input = JSON.parse(input); } catch { throw new SetupError('input', 'Installation input must be JSON.'); }
|
|
19
23
|
result = await install(args[1], input);
|
|
20
|
-
} else result = await (command === 'doctor' ? doctor : command === 'update-skills' ? updateSkills : rollback)(args[1]);
|
|
24
|
+
} else result = await (command === 'doctor' ? doctor : command === 'update-skills' ? updateSkills : command === 'migrate' ? migrate : rollback)(args[1]);
|
|
21
25
|
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
22
26
|
}
|
|
23
27
|
} catch (error) {
|
package/src/runtime.mjs
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { lstat, realpath } from 'node:fs/promises';
|
|
2
|
+
import { dirname, join, isAbsolute } from 'node:path';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
5
|
+
import { legacy } from './legacy-compat.mjs';
|
|
6
|
+
import { readCredential, windowsPrivateAcl } from './auth.mjs';
|
|
7
|
+
import { loadInstallation, textFile, parseJson, validateUrl, SetupError } from './setup.mjs';
|
|
8
|
+
import { runBridge } from './bridge.mjs';
|
|
9
|
+
|
|
10
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
11
|
+
const digest = value => createHash('sha256').update(value).digest('hex');
|
|
12
|
+
const unavailable = () => new SetupError('runtime', 'Foundocs is not configured safely for this project and local user. Run the Foundocs integration install for this clone, or foundocs-setup doctor --root with the governing project root. No other installation was used.');
|
|
13
|
+
|
|
14
|
+
async function privateFile(path) {
|
|
15
|
+
const stat = await lstat(path);
|
|
16
|
+
if (!stat.isFile() || stat.isSymbolicLink() || (process.platform !== 'win32' && ((stat.mode & 0o077) || (typeof process.getuid === 'function' && stat.uid !== process.getuid())))) throw unavailable();
|
|
17
|
+
if (process.platform === 'win32') await windowsPrivateAcl(path);
|
|
18
|
+
let parent = dirname(path);
|
|
19
|
+
while (dirname(parent) !== parent) {
|
|
20
|
+
const info = await lstat(parent);
|
|
21
|
+
if (info.isSymbolicLink() || !info.isDirectory()) throw unavailable();
|
|
22
|
+
parent = dirname(parent);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function validateInstallation(root, directory, manifest) {
|
|
27
|
+
const base = dirname(dirname(directory));
|
|
28
|
+
await privateFile(join(directory, 'installation.json'));
|
|
29
|
+
if (manifest.version !== 1 || manifest.client !== 'codex' || manifest.root !== root || !UUID.test(manifest.projectId) || !UUID.test(manifest.workspaceId) || !UUID.test(manifest.attemptId)) throw unavailable();
|
|
30
|
+
validateUrl(manifest.mcpUrl);
|
|
31
|
+
const expected = join(base, 'credentials', manifest.workspaceId, manifest.projectId, digest(root), 'key.json');
|
|
32
|
+
if (!isAbsolute(manifest.credentialPath) || manifest.credentialPath !== expected) throw unavailable();
|
|
33
|
+
await privateFile(expected);
|
|
34
|
+
const saved = parseJson(await textFile(expected), 'private credential');
|
|
35
|
+
if (saved.projectId !== manifest.projectId || saved.workspaceId !== manifest.workspaceId || saved.mcpUrl !== manifest.mcpUrl || saved.attemptId !== manifest.attemptId) throw unavailable();
|
|
36
|
+
await readCredential(expected, manifest.projectId, manifest.workspaceId);
|
|
37
|
+
return manifest;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function resolveRuntime(projectId, options = {}) {
|
|
41
|
+
try {
|
|
42
|
+
if (!UUID.test(projectId)) throw unavailable();
|
|
43
|
+
let root = await realpath(options.cwd ?? process.cwd());
|
|
44
|
+
while (true) {
|
|
45
|
+
const text = await textFile(join(root, 'foundocs.json'));
|
|
46
|
+
const historical = await textFile(join(root, legacy.config));
|
|
47
|
+
if (historical !== null && text === null) throw unavailable();
|
|
48
|
+
if (text !== null) {
|
|
49
|
+
const config = parseJson(text, 'foundocs.json');
|
|
50
|
+
if (!UUID.test(config.project_id) || config.project_id !== projectId) throw unavailable();
|
|
51
|
+
if (historical !== null && !isDeepStrictEqual(config, parseJson(historical, legacy.config))) throw unavailable();
|
|
52
|
+
break;
|
|
53
|
+
}
|
|
54
|
+
let boundary = false;
|
|
55
|
+
try { await lstat(join(root, '.git')); boundary = true; } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
56
|
+
if (boundary || dirname(root) === root) throw unavailable();
|
|
57
|
+
root = dirname(root);
|
|
58
|
+
}
|
|
59
|
+
const { directory, manifest } = await loadInstallation(root, options);
|
|
60
|
+
if (manifest.projectId !== projectId) throw unavailable();
|
|
61
|
+
return await validateInstallation(root, directory, manifest);
|
|
62
|
+
} catch { throw unavailable(); }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function startRuntime(projectId, options = {}) {
|
|
66
|
+
const manifest = await resolveRuntime(projectId, options);
|
|
67
|
+
await runBridge(manifest);
|
|
68
|
+
}
|
package/src/setup.mjs
CHANGED
|
@@ -13,6 +13,7 @@ import { legacy, legacyInstructions } from './legacy-compat.mjs';
|
|
|
13
13
|
import { knowledgePolicy, dreamingPolicy, updatePolicy, skillAssets } from './skill-assets.mjs';
|
|
14
14
|
|
|
15
15
|
const exec = promisify(execFile);
|
|
16
|
+
const PACKAGE_VERSION = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
16
17
|
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
17
18
|
const START = '<!-- foundocs:setup:start -->';
|
|
18
19
|
const END = '<!-- foundocs:setup:end -->';
|
|
@@ -75,7 +76,7 @@ export function markedBlock(existing, content, oldFormat = false) {
|
|
|
75
76
|
return existing.slice(0, existing.indexOf(start)) + block + existing.slice(existing.indexOf(end) + end.length);
|
|
76
77
|
}
|
|
77
78
|
|
|
78
|
-
async function textFile(path) {
|
|
79
|
+
export async function textFile(path) {
|
|
79
80
|
try {
|
|
80
81
|
const stat = await lstat(path);
|
|
81
82
|
if (!stat.isFile() || stat.isSymbolicLink()) fail('preflight', 'Configuration must be a regular file.', { path });
|
|
@@ -84,7 +85,7 @@ async function textFile(path) {
|
|
|
84
85
|
} catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
85
86
|
}
|
|
86
87
|
|
|
87
|
-
function parseJson(text, path) {
|
|
88
|
+
export function parseJson(text, path) {
|
|
88
89
|
let value;
|
|
89
90
|
try { value = JSON.parse(text); } catch { fail('preflight', 'Malformed JSON; existing content was preserved.', { path }); }
|
|
90
91
|
if (!plainObject(value)) fail('preflight', 'Configuration must be a JSON object.', { path });
|
|
@@ -196,7 +197,116 @@ function sameConfig(a, b) {
|
|
|
196
197
|
return JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));
|
|
197
198
|
}
|
|
198
199
|
|
|
199
|
-
export
|
|
200
|
+
export const RUNTIME_ENV = ['FOUNDOCS_SETUP_HOME', 'FOUNDOCS_API_KEY', 'FOUNDOCS_PROJECT_ID', 'FOUNDOCS_WORKSPACE_ID', 'STEERDOCS_SETUP_HOME', 'STEERDOCS_API_KEY', 'STEERDOCS_PROJECT_ID', 'STEERDOCS_WORKSPACE_ID'];
|
|
201
|
+
|
|
202
|
+
export function portableTransport(projectId, version = PACKAGE_VERSION) {
|
|
203
|
+
return { command: 'npx', args: ['--yes', `@foundocs/foundocs-setup@${version}`, 'mcp', '--project-id', projectId], env_vars: [...RUNTIME_ENV], startup_timeout_sec: 60 };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function transportOf(server) { return server && { command: server.command, args: server.args }; }
|
|
207
|
+
|
|
208
|
+
export function portableVersion(server, projectId) {
|
|
209
|
+
if (!plainObject(server) || server.command !== 'npx' || !Array.isArray(server.args) || server.args.length !== 5) return null;
|
|
210
|
+
if (server.cwd !== undefined || server.env !== undefined || server.url !== undefined || !Array.isArray(server.env_vars) || !RUNTIME_ENV.every(name => server.env_vars.includes(name))) return null;
|
|
211
|
+
const version = /^@foundocs\/foundocs-setup@(\d+\.\d+\.\d+)$/.exec(server.args[1])?.[1];
|
|
212
|
+
if (!version || !sameConfig(transportOf(server), transportOf(portableTransport(projectId, version)))) return null;
|
|
213
|
+
const [major, minor, patch] = version.split('.').map(Number);
|
|
214
|
+
if (major === 0 && (minor < 3 || (minor === 3 && patch < 4))) return null;
|
|
215
|
+
return version;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// The journal must record this installation's exact absolute transport. A server
|
|
219
|
+
// name or an instruction marker alone never authorizes replacing it.
|
|
220
|
+
async function recordedTransport(root, directory, manifest) {
|
|
221
|
+
const text = await textFile(join(directory, 'rollback.json'));
|
|
222
|
+
if (manifest.client !== 'codex') return null;
|
|
223
|
+
// A completed rollback removes its journal. Keep using the exact transport
|
|
224
|
+
// previously verified and saved privately by migration, never current file data.
|
|
225
|
+
const previous = manifest.previousTransport;
|
|
226
|
+
if (isAbsolute(previous?.command ?? '') && sameConfig(previous?.args, [join(dirname(manifest.helperPath), 'bridge-v1.mjs'), manifest.credentialPath, manifest.projectId, manifest.workspaceId, manifest.mcpUrl])) return transportOf(previous);
|
|
227
|
+
if (text === null) return null;
|
|
228
|
+
const journal = parseJson(text, 'rollback.json');
|
|
229
|
+
if (journal.root !== root || !Array.isArray(journal.entries)) fail('preflight', 'Invalid rollback journal.');
|
|
230
|
+
const entry = journal.entries.find(entry => entry.path === join(root, '.codex/config.toml'));
|
|
231
|
+
if (!entry) return null;
|
|
232
|
+
for (const [source, candidate] of [['after', entry.after], ['before', entry.before]]) {
|
|
233
|
+
if (typeof candidate !== 'string') continue;
|
|
234
|
+
let config; try { config = parseToml(candidate); } catch { continue; }
|
|
235
|
+
for (const name of ['foundocs', legacy.name]) {
|
|
236
|
+
const server = config.mcp_servers?.[name];
|
|
237
|
+
if ((source === 'after' || sameConfig(transportOf(server), manifest.previousTransport)) && isAbsolute(server?.command ?? '') && sameConfig(server?.args, [join(dirname(manifest.helperPath), 'bridge-v1.mjs'), manifest.credentialPath, manifest.projectId, manifest.workspaceId, manifest.mcpUrl])) return transportOf(server);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return null;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// Edit standalone assignments only; retain unrelated tables, custom server
|
|
244
|
+
// settings, and comments. Reject unusual TOML forms instead of reserializing.
|
|
245
|
+
function replaceTransport(text, oldName, newName, desired, path) {
|
|
246
|
+
const lines = text.split(/(?<=\n)/);
|
|
247
|
+
const heading = new RegExp(`^\\s*\\[mcp_servers\\.${oldName}\\]\\s*(?:#[^\\n]*)?(?:\\n)?$`);
|
|
248
|
+
const start = lines.findIndex(line => heading.test(line));
|
|
249
|
+
if (start < 0) fail('preflight', 'Use a standalone MCP server table before migration; existing TOML was preserved.', { path });
|
|
250
|
+
let end = start + 1;
|
|
251
|
+
while (end < lines.length && !/^\s*\[/.test(lines[end])) end++;
|
|
252
|
+
const original = parseToml(text).mcp_servers[oldName];
|
|
253
|
+
const body = lines.slice(start + 1, end);
|
|
254
|
+
if (original.cwd !== undefined || original.env !== undefined || original.url !== undefined) fail('preflight', 'Custom cwd, env or URL overrides must be reconciled before migration; existing configuration was preserved.', { path });
|
|
255
|
+
if (original.env_vars !== undefined && !Array.isArray(original.env_vars)) fail('preflight', 'MCP env_vars must be an array.', { path });
|
|
256
|
+
const envVars = [...new Set([...(original.env_vars ?? []), ...RUNTIME_ENV])];
|
|
257
|
+
desired = { ...desired, env_vars: envVars };
|
|
258
|
+
for (const key of ['command', 'args', ...(original.env_vars ? ['env_vars'] : [])]) {
|
|
259
|
+
const index = body.findIndex(line => new RegExp(`^\\s*${key}\\s*=`).test(line));
|
|
260
|
+
if (index < 0) fail('preflight', 'MCP command and args must be standalone assignments before migration.', { path });
|
|
261
|
+
let count = 1, value;
|
|
262
|
+
for (; index + count <= body.length; count++) {
|
|
263
|
+
try { value = parseToml(body.slice(index, index + count).join('')); if (Object.hasOwn(value, key)) break; } catch {}
|
|
264
|
+
}
|
|
265
|
+
if (!value || !sameConfig(value[key], original[key])) fail('preflight', 'MCP assignment cannot be migrated safely.', { path });
|
|
266
|
+
const comments = body.slice(index, index + count).flatMap(line => {
|
|
267
|
+
// Comments outside quoted strings survive replacement, including multiline arrays.
|
|
268
|
+
let quote = null, escaped = false;
|
|
269
|
+
for (let i = 0; i < line.length; i++) {
|
|
270
|
+
const c = line[i];
|
|
271
|
+
if (escaped) { escaped = false; continue; }
|
|
272
|
+
if (quote === '"' && c === '\\') { escaped = true; continue; }
|
|
273
|
+
if (quote) { if (c === quote) quote = null; continue; }
|
|
274
|
+
if (c === '"' || c === "'") quote = c;
|
|
275
|
+
else if (c === '#') return [line.slice(i).replace(/\r?\n$/, '') + '\n'];
|
|
276
|
+
}
|
|
277
|
+
return [];
|
|
278
|
+
});
|
|
279
|
+
body.splice(index, count, ...comments, `${key} = ${JSON.stringify(desired[key])}\n`);
|
|
280
|
+
}
|
|
281
|
+
if (body.length && !body.at(-1).endsWith('\n')) body[body.length - 1] += '\n';
|
|
282
|
+
if (!Object.hasOwn(original, 'env_vars')) body.push(`env_vars = ${JSON.stringify(envVars)}\n`);
|
|
283
|
+
if (!Object.hasOwn(original, 'startup_timeout_sec')) body.push('startup_timeout_sec = 60\n');
|
|
284
|
+
const after = [...lines.slice(0, start), lines[start].replace(`[mcp_servers.${oldName}]`, `[mcp_servers.${newName}]`), ...body, ...lines.slice(end)].join('');
|
|
285
|
+
const expected = { ...original, ...transportOf(desired), env_vars: envVars, startup_timeout_sec: original.startup_timeout_sec ?? desired.startup_timeout_sec };
|
|
286
|
+
const parsed = parseToml(after);
|
|
287
|
+
if (!sameConfig(parsed.mcp_servers?.[newName], expected) || (oldName !== newName && parsed.mcp_servers?.[oldName])) fail('preflight', 'TOML migration verification failed; existing content was preserved.', { path });
|
|
288
|
+
return after;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
export async function migrate(rootPath, options = {}) {
|
|
292
|
+
const { root, directory, manifest } = await loadInstallation(rootPath, options);
|
|
293
|
+
if (manifest.client !== 'codex') return { ok: true, status: 'not_required', changedFiles: [] };
|
|
294
|
+
await checkGitRoot(root);
|
|
295
|
+
return withLock(directory, async () => {
|
|
296
|
+
if (await installedFormat(root, manifest)) fail('preflight', 'First rerun install to migrate the historical project configuration.');
|
|
297
|
+
const { validateInstallation } = await import('./runtime.mjs');
|
|
298
|
+
await validateInstallation(root, directory, manifest, options);
|
|
299
|
+
const ownedTransport = await recordedTransport(root, directory, manifest);
|
|
300
|
+
const entries = (await plan(root, manifest, manifest.credentialPath, manifest.helperPath, { owned: true, ownedTransport })).filter(entry => entry.path === join(root, '.codex/config.toml'));
|
|
301
|
+
const version = portableVersion(parseToml(entries[0].after).mcp_servers.foundocs, manifest.projectId);
|
|
302
|
+
const updated = { ...manifest, runtimeVersion: version, ...(ownedTransport ? { previousTransport: ownedTransport } : {}) };
|
|
303
|
+
await atomicWrite(join(directory, 'installation.json'), json(updated));
|
|
304
|
+
const changes = await applyProjectChanges(root, directory, entries);
|
|
305
|
+
return { ok: true, status: changes.length ? 'migrated' : 'already_portable', changedFiles: changes.map(entry => entry.path), credentialRetained: true, next: 'Restart or reconnect Codex MCP, then call get_project_context to verify the host connection.' };
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
export async function plan(root, input, credentialPath, helperPath, { oldFormat = false, owned = false, includeSkills = false, ownedTransport = null } = {}) {
|
|
200
310
|
const command = helperCommand([process.execPath, helperPath, '--headers', credentialPath, input.projectId, input.workspaceId]);
|
|
201
311
|
const entries = [];
|
|
202
312
|
const add = async (name, transform) => {
|
|
@@ -248,23 +358,22 @@ export async function plan(root, input, credentialPath, helperPath, { oldFormat
|
|
|
248
358
|
let config;
|
|
249
359
|
try { config = text === null ? {} : parseToml(text); } catch { fail('preflight', 'Malformed TOML; existing content was preserved.', { path }); }
|
|
250
360
|
if (config.mcp_servers !== undefined && !plainObject(config.mcp_servers)) fail('preflight', 'mcp_servers must be a TOML table.', { path });
|
|
251
|
-
const desired = { command: process.execPath, args: [join(dirname(helperPath), 'bridge-v1.mjs'), credentialPath, input.projectId, input.workspaceId, input.mcpUrl] };
|
|
252
361
|
const old = config.mcp_servers?.[serverName];
|
|
253
362
|
const historicalServer = oldFormat ? undefined : config.mcp_servers?.[legacy.name];
|
|
254
|
-
if (historicalServer !== undefined) {
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
if (
|
|
263
|
-
|
|
264
|
-
|
|
363
|
+
if (historicalServer !== undefined && old !== undefined) fail('preflight', 'Both current and historical MCP servers exist. Preserve them and resolve the conflict.', { path });
|
|
364
|
+
const existing = old ?? historicalServer;
|
|
365
|
+
const existingName = old === undefined && historicalServer !== undefined ? legacy.name : serverName;
|
|
366
|
+
const pinned = portableVersion(existing, input.projectId);
|
|
367
|
+
const desired = portableTransport(input.projectId, pinned ?? input.runtimeVersion ?? PACKAGE_VERSION);
|
|
368
|
+
if (existing !== undefined) {
|
|
369
|
+
if (pinned) {
|
|
370
|
+
if (existingName === serverName) return text;
|
|
371
|
+
if (!owned) fail('preflight', 'Historical MCP configuration is not owned by this installation.', { path });
|
|
372
|
+
return replaceTransport(text, existingName, serverName, desired, path);
|
|
373
|
+
}
|
|
374
|
+
if (!ownedTransport || !sameConfig(transportOf(existing), ownedTransport)) fail('preflight', 'An existing Foundocs MCP server is not a verified installer-owned transport. Preserve it and resolve the conflict before retrying.', { path });
|
|
375
|
+
return replaceTransport(text, existingName, serverName, desired, path);
|
|
265
376
|
}
|
|
266
|
-
if (old !== undefined && !sameConfig(old, desired)) fail('preflight', 'An existing Foundocs MCP server differs. Preserve it and resolve the name conflict before retrying.', { path });
|
|
267
|
-
if (old) return text;
|
|
268
377
|
const after = `${text ?? ''}${text?.endsWith('\n') ? '' : '\n'}\n${stringifyToml({ mcp_servers: { [serverName]: desired } })}`;
|
|
269
378
|
try { const parsed = parseToml(after); if (!sameConfig(parsed.mcp_servers[serverName], desired)) throw new Error(); }
|
|
270
379
|
catch { fail('preflight', 'TOML cannot be extended safely (possibly an inline mcp_servers table). Convert that table or use the manual guide.', { path }); }
|
|
@@ -361,7 +470,7 @@ async function skillPlan(root, client, directory) {
|
|
|
361
470
|
await safeParent(root, path);
|
|
362
471
|
await writableParent(path);
|
|
363
472
|
const before = await textFile(path), owned = state.files[asset.name];
|
|
364
|
-
if (before !== null && (!owned || ![owned.installedHash, owned.pendingHash].includes(digest(before)))) {
|
|
473
|
+
if (before !== null && before !== asset.content && (!owned || ![owned.installedHash, owned.pendingHash].includes(digest(before)))) {
|
|
365
474
|
fail('preflight', 'A Foundocs skill file is unowned or modified. Preserve your changes and move or reconcile this file before retrying.', { path, skills: { status: 'conflict' } });
|
|
366
475
|
}
|
|
367
476
|
const afterHash = digest(asset.content);
|
|
@@ -485,7 +594,8 @@ export async function install(rootPath, rawInput, options = {}) {
|
|
|
485
594
|
&& previousManifest.mcpUrl === input.mcpUrl && previousManifest.credentialPath === credentialPath && previousManifest.helperPath === helperPath;
|
|
486
595
|
if (previousManifest !== null && !owned) fail('preflight', 'Saved installation identity differs. Preserve the existing installation and resolve the conflict before retrying.');
|
|
487
596
|
const skills = await skillPlan(root, input.client, rootDirectory);
|
|
488
|
-
const
|
|
597
|
+
const ownedTransport = owned ? await recordedTransport(root, rootDirectory, previousManifest) : null;
|
|
598
|
+
const entries = [...await plan(root, input, credentialPath, helperPath, { owned, ownedTransport, includeSkills: true }), ...skills.entries];
|
|
489
599
|
let bridgeSource;
|
|
490
600
|
if (input.client === 'codex') {
|
|
491
601
|
try { bridgeSource = await readFile(BRIDGE_SOURCE, 'utf8'); } catch { fail('preflight', 'The packaged authentication adapter is missing. Reinstall the published package. No code was exchanged.'); }
|
|
@@ -517,7 +627,8 @@ export async function install(rootPath, rawInput, options = {}) {
|
|
|
517
627
|
await atomicWrite(join(base, 'legacy-compat.mjs'), await readFile(COMPAT_SOURCE, 'utf8'));
|
|
518
628
|
await atomicWrite(helperPath, await readFile(AUTH_SOURCE, 'utf8'));
|
|
519
629
|
if (bridgeSource) await atomicWrite(join(base, 'bridge-v1.mjs'), bridgeSource);
|
|
520
|
-
const
|
|
630
|
+
const portable = input.client === 'codex' ? parseToml(entries.find(entry => entry.path === join(root, '.codex/config.toml')).after).mcp_servers.foundocs : null;
|
|
631
|
+
const manifest = { version: 1, brandingVersion: 2, ...(portable ? { runtimeVersion: portableVersion(portable, input.projectId) } : {}), ...(ownedTransport ? { previousTransport: ownedTransport } : previousManifest?.previousTransport ? { previousTransport: previousManifest.previousTransport } : {}), root, client: input.client, projectId: input.projectId, workspaceId: input.workspaceId, attemptId: saved.attemptId, mcpUrl: input.mcpUrl, credentialPath, helperPath };
|
|
521
632
|
// Persist metadata before project writes so doctor and rollback survive interruption.
|
|
522
633
|
await atomicWrite(manifestPath, json(manifest));
|
|
523
634
|
await stageSkills(skills);
|
|
@@ -532,7 +643,7 @@ export async function install(rootPath, rawInput, options = {}) {
|
|
|
532
643
|
});
|
|
533
644
|
}
|
|
534
645
|
|
|
535
|
-
async function loadInstallation(rootPath, options) {
|
|
646
|
+
export async function loadInstallation(rootPath, options) {
|
|
536
647
|
await runtime(); const root = await canonicalRoot(rootPath);
|
|
537
648
|
const base = await storageBase(options, root);
|
|
538
649
|
const storageRelative = relative(root, base);
|
|
@@ -547,10 +658,26 @@ async function loadInstallation(rootPath, options) {
|
|
|
547
658
|
|
|
548
659
|
export async function doctor(rootPath, options = {}) {
|
|
549
660
|
const { root, directory, manifest } = await loadInstallation(rootPath, options);
|
|
550
|
-
const runtimeFiles = [manifest.helperPath, ...(manifest.brandingVersion === 2 ? [join(dirname(manifest.helperPath), 'legacy-compat.mjs')] : []), ...(manifest.client === 'codex' ? [join(dirname(manifest.helperPath), 'bridge-v1.mjs')] : [])];
|
|
661
|
+
const runtimeFiles = manifest.client === 'codex' && manifest.runtimeVersion ? [] : [manifest.helperPath, ...(manifest.brandingVersion === 2 ? [join(dirname(manifest.helperPath), 'legacy-compat.mjs')] : []), ...(manifest.client === 'codex' ? [join(dirname(manifest.helperPath), 'bridge-v1.mjs')] : [])];
|
|
551
662
|
for (const path of runtimeFiles) if (await textFile(path) === null) fail('diagnostic', 'A durable authentication helper is missing. Rerun install to repair it.', { path });
|
|
552
663
|
const oldFormat = await textFile(join(root, 'foundocs.json')) === null && await textFile(join(root, legacy.config)) !== null;
|
|
553
664
|
const skills = await checkSkills(root, directory, manifest, oldFormat);
|
|
665
|
+
if (manifest.client === 'codex') {
|
|
666
|
+
let config;
|
|
667
|
+
try { config = parseToml(await textFile(join(root, '.codex/config.toml')) ?? ''); }
|
|
668
|
+
catch { fail('diagnostic', 'MCP configuration is malformed or unsafe. Resolve the configuration conflict before retrying.'); }
|
|
669
|
+
const server = config.mcp_servers?.foundocs;
|
|
670
|
+
const version = portableVersion(server, manifest.projectId);
|
|
671
|
+
if (server?.command === 'npx' && (!version || version !== manifest.runtimeVersion)) fail('diagnostic', 'Portable MCP configuration differs from the recorded runtime or contains unsupported execution overrides. Reconcile this configuration before retrying.');
|
|
672
|
+
if (!version) {
|
|
673
|
+
const ownedTransport = await recordedTransport(root, directory, manifest);
|
|
674
|
+
const legacyServer = server ?? config.mcp_servers?.[legacy.name];
|
|
675
|
+
if (!ownedTransport || !sameConfig(transportOf(legacyServer), ownedTransport) || legacyServer.cwd !== undefined || legacyServer.env !== undefined || legacyServer.url !== undefined) fail('diagnostic', 'MCP configuration differs from the recorded transport. Resolve the configuration conflict before retrying.');
|
|
676
|
+
fail('diagnostic', 'This Codex installation uses a machine-specific transport. Run foundocs-setup migrate --root with this exact root; no new connection code is needed.');
|
|
677
|
+
}
|
|
678
|
+
const { resolveRuntime } = await import('./runtime.mjs');
|
|
679
|
+
await resolveRuntime(manifest.projectId, { ...options, cwd: root });
|
|
680
|
+
}
|
|
554
681
|
const entries = await plan(root, manifest, manifest.credentialPath, manifest.helperPath, { oldFormat, owned: true, includeSkills: true });
|
|
555
682
|
if (entries.some((entry) => entry.before !== entry.after)) fail('diagnostic', 'Installation files are incomplete or modified. Rerun install to repair them.');
|
|
556
683
|
const client = await (options.probeClient ?? probeClient)(manifest.client);
|