@jbkjr/relay 0.0.0-stage → 1.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/LICENSES/Apache-2.0.txt +201 -0
- package/LICENSES/README.md +19 -0
- package/LICENSES/codex-NOTICE.txt +6 -0
- package/README.md +393 -2
- package/SECURITY.md +145 -0
- package/adapters/briefs/claude.md +43 -0
- package/adapters/briefs/codex.md +56 -0
- package/adapters/briefs/models.json +33 -0
- package/adapters/build.mjs +8 -0
- package/adapters/claude/.claude-plugin/marketplace.json +13 -0
- package/adapters/claude/relay/.claude-plugin/plugin.json +5 -0
- package/adapters/claude/relay/agents/codex.md +21 -0
- package/adapters/claude/relay/agents/operator.md +21 -0
- package/adapters/claude/relay/skills/ask/SKILL.md +20 -0
- package/adapters/claude/relay/skills/chat/SKILL.md +13 -0
- package/adapters/claude/relay/skills/delegate/SKILL.md +21 -0
- package/adapters/claude/relay/skills/discuss/SKILL.md +19 -0
- package/adapters/claude/relay/skills/review/SKILL.md +21 -0
- package/adapters/claude/relay/skills/tree/SKILL.md +10 -0
- package/adapters/claude/relay/skills/write-for-codex/SKILL.md +78 -0
- package/adapters/codex/.agents/plugins/marketplace.json +20 -0
- package/adapters/codex/AGENTS.snippet.md +5 -0
- package/adapters/codex/relay/.codex-plugin/plugin.json +6 -0
- package/adapters/codex/relay/skills/relay-ask/SKILL.md +20 -0
- package/adapters/codex/relay/skills/relay-chat/SKILL.md +13 -0
- package/adapters/codex/relay/skills/relay-delegate/SKILL.md +21 -0
- package/adapters/codex/relay/skills/relay-discuss/SKILL.md +19 -0
- package/adapters/codex/relay/skills/relay-review/SKILL.md +21 -0
- package/adapters/codex/relay/skills/relay-tree/SKILL.md +10 -0
- package/adapters/codex/relay/skills/relay-write-for-claude/SKILL.md +66 -0
- package/adapters/generate.mjs +124 -0
- package/bin/relay +59 -0
- package/codex-pin.json +12 -0
- package/dist/backends/acp.js +1424 -0
- package/dist/backends/claude.js +890 -0
- package/dist/backends/cli-version.js +112 -0
- package/dist/backends/codex-app.js +1539 -0
- package/dist/backends/codex-daybreak.js +75 -0
- package/dist/backends/codex-env.js +656 -0
- package/dist/backends/codex-network.js +304 -0
- package/dist/backends/codex-pin.js +345 -0
- package/dist/backends/codex-shell-policy.js +182 -0
- package/dist/backends/codex-stage2.js +998 -0
- package/dist/backends/codex-subagents.js +47 -0
- package/dist/backends/codex.js +641 -0
- package/dist/backends/copilot.js +246 -0
- package/dist/backends/env.js +147 -0
- package/dist/backends/gemini.js +607 -0
- package/dist/backends/grok.js +337 -0
- package/dist/backends/index.js +8 -0
- package/dist/backends/native-temp.js +187 -0
- package/dist/backends/never-admission.js +90 -0
- package/dist/backends/run.js +67 -0
- package/dist/backends/stream.js +230 -0
- package/dist/backends/tool-discovery.js +15 -0
- package/dist/backends/types.js +264 -0
- package/dist/build-info.json +5 -0
- package/dist/cli.js +344 -0
- package/dist/confine/bridge.js +113 -0
- package/dist/confine/broker-core.js +76 -0
- package/dist/confine/broker-http.js +650 -0
- package/dist/confine/broker-names.js +9 -0
- package/dist/confine/broker.js +258 -0
- package/dist/confine/canary.js +380 -0
- package/dist/confine/diagnostics.js +122 -0
- package/dist/confine/gemini-tools-main.js +8 -0
- package/dist/confine/gemini-tools.js +181 -0
- package/dist/confine/hardlinks.js +58 -0
- package/dist/confine/harness-config.js +16 -0
- package/dist/confine/index.js +117 -0
- package/dist/confine/leases.js +217 -0
- package/dist/confine/paths.js +6 -0
- package/dist/confine/peer.js +115 -0
- package/dist/confine/port-policy.js +8 -0
- package/dist/confine/ports.js +365 -0
- package/dist/confine/private-root.js +208 -0
- package/dist/confine/probe-stage2.js +501 -0
- package/dist/confine/probe.js +1109 -0
- package/dist/confine/proxy.js +783 -0
- package/dist/confine/sbcheck.js +208 -0
- package/dist/confine/seatbelt-never.js +41 -0
- package/dist/confine/seatbelt-stage2.js +139 -0
- package/dist/confine/seatbelt.js +1129 -0
- package/dist/confine/sockets.js +36 -0
- package/dist/confine/turn-probe.js +19 -0
- package/dist/confine/turn.js +86 -0
- package/dist/core/adoption.js +124 -0
- package/dist/core/api-keys.js +423 -0
- package/dist/core/approvals.js +740 -0
- package/dist/core/build-identity.js +248 -0
- package/dist/core/caller.js +749 -0
- package/dist/core/calls.js +102 -0
- package/dist/core/claude-settings.js +1045 -0
- package/dist/core/config.js +453 -0
- package/dist/core/context.js +186 -0
- package/dist/core/db.js +753 -0
- package/dist/core/dispatch.js +110 -0
- package/dist/core/env-broker.js +505 -0
- package/dist/core/env-policy.js +182 -0
- package/dist/core/escalation-authority.js +76 -0
- package/dist/core/escalation-contract.js +13 -0
- package/dist/core/escalation-person-path.js +131 -0
- package/dist/core/escalation-policy.js +79 -0
- package/dist/core/escalation-runtime.js +135 -0
- package/dist/core/escalation-state.js +42 -0
- package/dist/core/escalations.js +191 -0
- package/dist/core/events.js +235 -0
- package/dist/core/executables.js +147 -0
- package/dist/core/extensions.js +645 -0
- package/dist/core/families.js +204 -0
- package/dist/core/git.js +657 -0
- package/dist/core/identity.js +113 -0
- package/dist/core/liveness.js +68 -0
- package/dist/core/mediated-network-provider.js +81 -0
- package/dist/core/never-checkpoint.js +76 -0
- package/dist/core/never-coverage.js +97 -0
- package/dist/core/never-network.js +49 -0
- package/dist/core/never-policy.js +302 -0
- package/dist/core/never-proxy-policy.js +109 -0
- package/dist/core/never-schema.js +61 -0
- package/dist/core/never-tools.js +56 -0
- package/dist/core/notices.js +48 -0
- package/dist/core/ops.js +959 -0
- package/dist/core/outcome.js +224 -0
- package/dist/core/params.js +32 -0
- package/dist/core/presence.js +174 -0
- package/dist/core/procs.js +546 -0
- package/dist/core/prompts.js +363 -0
- package/dist/core/protected-config.js +238 -0
- package/dist/core/raw-network.js +192 -0
- package/dist/core/redact.js +152 -0
- package/dist/core/refusal.js +33 -0
- package/dist/core/relay-command.js +310 -0
- package/dist/core/reported.js +3 -0
- package/dist/core/restart-overlay.js +651 -0
- package/dist/core/retention.js +1135 -0
- package/dist/core/secrets.js +329 -0
- package/dist/core/session-token.js +175 -0
- package/dist/core/session.js +744 -0
- package/dist/core/shell.js +2 -0
- package/dist/core/shipped-pin.js +47 -0
- package/dist/core/shown.js +42 -0
- package/dist/core/slots.js +67 -0
- package/dist/core/stage2-executors.js +453 -0
- package/dist/core/stage2-switch.js +5 -0
- package/dist/core/steering.js +149 -0
- package/dist/core/storage.js +358 -0
- package/dist/core/toml.js +175 -0
- package/dist/core/views.js +324 -0
- package/dist/core/wait.js +114 -0
- package/dist/core/wake.js +207 -0
- package/dist/core/watch.js +247 -0
- package/dist/core/worktree.js +213 -0
- package/dist/hosts/claude-desktop.js +274 -0
- package/dist/hosts/claude.js +249 -0
- package/dist/hosts/codex.js +345 -0
- package/dist/hosts/desktop-shared.js +20 -0
- package/dist/hosts/index.js +11 -0
- package/dist/hosts/types.js +4 -0
- package/dist/install/basics.js +18 -0
- package/dist/install/claude-init.js +133 -0
- package/dist/install/common.js +655 -0
- package/dist/install/doctor.js +635 -0
- package/dist/install/qualify-codex.js +205 -0
- package/dist/install.js +524 -0
- package/dist/mcp/elicit.js +209 -0
- package/dist/mcp/gateway.js +218 -0
- package/dist/mcp/host.js +253 -0
- package/dist/mcp/server.js +1124 -0
- package/dist/mcp/stdio.js +37 -0
- package/dist/modes/discussion.js +393 -0
- package/dist/modes/review.js +722 -0
- package/dist/native/relay-sbcheck +0 -0
- package/dist/targets/briefs.js +86 -0
- package/dist/targets/claude.js +94 -0
- package/dist/targets/codex.js +66 -0
- package/dist/targets/copilot.js +93 -0
- package/dist/targets/gemini.js +119 -0
- package/dist/targets/grok.js +126 -0
- package/dist/targets/index.js +192 -0
- package/dist/targets/types.js +18 -0
- package/dist/targets/verified.js +35 -0
- package/dist/worker.js +113 -0
- package/docs/UPGRADING.md +1518 -0
- package/docs/pinned-codex.md +333 -0
- package/experiments/stage2-redteam/lib/oracles.mjs +214 -0
- package/experiments/stage2-redteam/lib/report.mjs +35 -0
- package/npm-shrinkwrap.json +1632 -0
- package/package.json +82 -4
- package/scripts/codex-qualify/codex-pin-store.mjs +353 -0
- package/scripts/codex-qualify/codex-qualifier-process.mjs +265 -0
- package/scripts/codex-qualify/codex-qualifier.example.json +5 -0
- package/scripts/codex-qualify/codex-qualifier.mjs +281 -0
- package/scripts/codex-qualify/codex-shipped-pin.mjs +158 -0
- package/scripts/codex-qualify/codex-stage2-pin.mjs +48 -0
- package/scripts/codex-qualify/codex-stage2.mjs +2381 -0
- package/scripts/codex-qualify/install-codex-qualifier.mjs +98 -0
- package/scripts/codex-qualify/main-module.mjs +14 -0
- package/scripts/codex-qualify/relay-codex-qualifier.plist +37 -0
- package/scripts/codex-qualify/scratch-env.mjs +31 -0
- package/scripts/codex-qualify/session.mjs +96 -0
- package/scripts/codex-qualify/stage2-escalation-cases.mjs +125 -0
- package/test/codex-permissions.test.ts +875 -0
- package/test/fixtures/boundary-probes.mjs +17 -0
- package/test/fixtures/denial-stream-host.mjs +7 -0
- package/test/fixtures/families.json +246 -0
- package/test/fixtures/install-snapshots/claude-desktop-foreign.txt +158 -0
- package/test/fixtures/install-snapshots/claude-desktop-fresh.txt +101 -0
- package/test/fixtures/install-snapshots/claude-desktop-installed.txt +161 -0
- package/test/fixtures/install-snapshots/claude-foreign.txt +133 -0
- package/test/fixtures/install-snapshots/claude-fresh.txt +77 -0
- package/test/fixtures/install-snapshots/claude-installed.txt +133 -0
- package/test/fixtures/install-snapshots/codex-foreign.txt +159 -0
- package/test/fixtures/install-snapshots/codex-fresh.txt +107 -0
- package/test/fixtures/install-snapshots/codex-installed.txt +161 -0
- package/test/fixtures/link-parent.mjs +6 -0
- package/test/fixtures/mediated-command.cjs +72 -0
- package/test/fixtures/native-skill-isolation.json +280 -0
- package/test/fixtures/pinned-codex-app-server.mjs +25 -0
- package/test/fixtures/qualified-ext-adapters.mjs +36 -0
- package/test/fixtures/refusals/README.md +52 -0
- package/test/fixtures/refusals/claude-source-result.json +7 -0
- package/test/fixtures/refusals/openai-app-capacity.json +24 -0
- package/test/fixtures/refusals/openai-app-cyberPolicy.json +24 -0
- package/test/fixtures/refusals/openai-gpt-6-astra-max.json +12 -0
- package/test/fixtures/refusals/openai-gpt-6.1-sol-xhigh.json +12 -0
- package/test/fixtures/refusals/openai-review-capacity.json +24 -0
- package/test/fixtures/relay-0.2.0.sql +57 -0
- package/test/fixtures/relay-0.9.1.gen.mjs +212 -0
- package/test/fixtures/relay-0.9.1.sql +340 -0
- package/test/fixtures/slow-boundary-probes.mjs +37 -0
- package/test/fixtures/stable-surfaces/config.json +1122 -0
- package/test/fixtures/stable-surfaces/escalation.json +128 -0
- package/test/fixtures/stable-surfaces/events.json +37 -0
- package/test/fixtures/stable-surfaces/gemini-native-resume.json +4 -0
- package/test/fixtures/stable-surfaces/inbox.jsonl +2 -0
- package/test/fixtures/stable-surfaces/notice.txt +1 -0
- package/test/fixtures/stable-surfaces/refusal-item.json +28 -0
- package/test/fixtures/stable-surfaces/refusal-review.json +23 -0
- package/test/fixtures/stable-surfaces/registry.json +49 -0
- package/test/fixtures/stable-surfaces/tools-desktop.json +575 -0
- package/test/fixtures/stable-surfaces/tools.json +716 -0
- package/test/fixtures/stable-surfaces/usage.txt +46 -0
- package/test/fixtures/stage2-acp-native.mjs +138 -0
- package/test/fixtures/stage2-app-server.mjs +23 -0
- package/test/fixtures/stage2-catalog.json +91 -0
- package/test/fixtures/stage2-hostile-web.mjs +35 -0
- package/test/fixtures/stage2-native-network.mjs +62 -0
- package/test/fixtures/stage2-worker.ts +87 -0
- package/test/fixtures/status-views/expected.json +7825 -0
- package/test/fixtures/status-views/registries.json +1 -0
- package/test/fixtures/steering.json +209 -0
- package/test/helpers.ts +740 -0
- package/test/host-env.ts +7 -0
- package/test/keychain-decoy.ts +197 -0
- package/test/live-scope.ts +44 -0
- package/test/mediated-network.test.ts +192 -0
- package/test/mediated-proxy.test.ts +264 -0
- package/test/native-temp-alias.ts +10 -0
- package/test/never-policy.test.ts +629 -0
- package/test/never-tools.test.ts +136 -0
- package/test/process-home.ts +18 -0
- package/test/proxy.test.ts +531 -0
- package/test/restart-overlay-live.test.ts +85 -0
- package/test/restart-overlay-profile.test.ts +66 -0
- package/test/restart-overlay.test.ts +416 -0
- package/test/stable-surfaces.test.ts +249 -0
- package/test/stage2-escalation-live.test.ts +544 -0
- package/test/stage2-escalation-qualification.test.ts +170 -0
- package/test/stage2-escalation.test.ts +747 -0
- package/test/stage2-executor.test.ts +849 -0
- package/test/stage2-grant.test.ts +603 -0
- package/test/stage2-native-live.test.ts +647 -0
- package/test/stage2-network-decisions.test.ts +70 -0
- package/test/stage2-probe.test.ts +845 -0
- package/test/stage2-standing-live.test.ts +203 -0
- package/test/stubs/broker-host.mjs +59 -0
- package/test/stubs/broker-peer.mjs +20 -0
- package/test/stubs/confined-harness.mjs +91 -0
- package/test/stubs/ext-broken-server.mjs +2 -0
- package/test/stubs/ext-odd-server.mjs +21 -0
- package/test/stubs/ext-server.mjs +31 -0
- package/test/stubs/fake-host-cli.mjs +218 -0
- package/test/stubs/procargs.mjs +30 -0
- package/test/stubs/stub-acp +4 -0
- package/test/stubs/stub-agent.mjs +322 -0
- package/test/stubs/stub-claude +4 -0
- package/test/stubs/stub-codex +4 -0
- package/test/stubs/targets/acp.mjs +307 -0
- package/test/stubs/targets/claude.mjs +149 -0
- package/test/stubs/targets/codex.mjs +479 -0
- package/test/stubs/targets/gemini.mjs +604 -0
- package/test/temp-root.ts +11 -0
- package/test/wp4-adapters.test.ts +353 -0
- package/test/wp4-interlock.test.ts +136 -0
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
// What install, uninstall and doctor share, whichever host they are working on: deciding whose an
|
|
2
|
+
// entry is, the record of what a run changed, running a host's CLI, writing its files, and its
|
|
3
|
+
// plugin kit. Each host's own part is in src/hosts/.
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { canonical, configPath, loadConfig } from "../core/config.js";
|
|
10
|
+
import { findExecutable, spawnFound } from "../core/executables.js";
|
|
11
|
+
import { installRecordPath, installBackupsPath as savedDir } from "../core/protected-config.js";
|
|
12
|
+
import { isTable, sameData } from "../core/toml.js";
|
|
13
|
+
import { targetDef } from "../targets/index.js";
|
|
14
|
+
import { probeVersion } from "../backends/cli-version.js";
|
|
15
|
+
const SELF = fileURLToPath(import.meta.url);
|
|
16
|
+
export const ROOT = path.resolve(path.dirname(SELF), "..", "..");
|
|
17
|
+
/** Hosts register the launcher script, which finds a suitable Node at start, not a pinned Node path. */
|
|
18
|
+
export const LAUNCHER = path.join(ROOT, "bin", "relay");
|
|
19
|
+
// ---- install, uninstall, doctor ----------------------------------------------------------------
|
|
20
|
+
//
|
|
21
|
+
// These three edit or inspect other programs' configuration, so they follow one rule throughout:
|
|
22
|
+
// find out what is there, decide whether it is relay's, and refuse when unsure. Nothing called
|
|
23
|
+
// "relay" is replaced or removed unless it is relay's own or the user passes --force, what is
|
|
24
|
+
// replaced is saved first where it will never be overwritten, and a failed step stops the run.
|
|
25
|
+
export const MARKETPLACE = "relay-local";
|
|
26
|
+
export const PLUGIN = `relay@${MARKETPLACE}`;
|
|
27
|
+
/** A refusal or a failed step. The message is for the user, and nothing further is attempted. */
|
|
28
|
+
export class Stop extends Error {
|
|
29
|
+
}
|
|
30
|
+
export const say = (text) => console.log(text);
|
|
31
|
+
export const sh = (argv) => argv.map((a) => (/^[\w@%+=:,./-]+$/.test(a) ? a : `'${a.replace(/'/g, `'\\''`)}'`)).join(" ");
|
|
32
|
+
/** Whether `dir` is on PATH. */
|
|
33
|
+
export const onPath = (dir) => (process.env.PATH ?? "").split(path.delimiter).some((d) => d && canonical(d) === canonical(dir));
|
|
34
|
+
/** The command that installs or uninstalls relay for a host from this checkout, as relay tells the user to run it. */
|
|
35
|
+
export const reinstallCommand = (verb, host) => sh([LAUNCHER, verb, host, "--write"]);
|
|
36
|
+
const stamp = () => new Date().toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
|
|
37
|
+
export const errCode = (err) => err.code;
|
|
38
|
+
export const errText = (err) => (err instanceof Error ? err.message : String(err));
|
|
39
|
+
/** The first line of a command's output. */
|
|
40
|
+
export const first = (text) => text.trim().split(/\r?\n/)[0] ?? "";
|
|
41
|
+
export const linkPath = () => path.join(os.homedir(), ".local", "bin", "relay");
|
|
42
|
+
/** What install changed, per host. It sits beside relay's config, and so does everything install saves. */
|
|
43
|
+
export const recordFile = installRecordPath;
|
|
44
|
+
export { usageError } from "./basics.js";
|
|
45
|
+
// What is there, and whose is it
|
|
46
|
+
/**
|
|
47
|
+
* relay's package names: "@jbkjr/relay", its npm name since the first public release, and
|
|
48
|
+
* "relay", which a checkout from before then still carries.
|
|
49
|
+
*/
|
|
50
|
+
const RELAY_PACKAGE_NAMES = ["@jbkjr/relay", "relay"];
|
|
51
|
+
/** Whether a path is bin/relay inside a relay checkout or npm install, going by its package.json. */
|
|
52
|
+
export function isRelayLauncher(file) {
|
|
53
|
+
if (!file.endsWith("/bin/relay"))
|
|
54
|
+
return false;
|
|
55
|
+
try {
|
|
56
|
+
return RELAY_PACKAGE_NAMES.includes(JSON.parse(fs.readFileSync(path.join(path.dirname(path.dirname(file)), "package.json"), "utf8")).name);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** The launchers relay's installation record says it registered, for any host. */
|
|
63
|
+
function recordedLaunchers() {
|
|
64
|
+
try {
|
|
65
|
+
return Object.values(loadRecord().hosts).flatMap((h) => (h ? [h.launcher] : []));
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return [];
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Whose an MCP entry's command is. Relay's own entry runs a relay launcher as a server,
|
|
73
|
+
* `<relay>/bin/relay mcp …`; the shape alone does not make it relay's, since another program can
|
|
74
|
+
* have a bin/relay too. "relay": this launcher, a launcher in a relay package (its package.json,
|
|
75
|
+
* as the link check goes by), or one relay's installation record says it registered.
|
|
76
|
+
* "ambiguous": the shape, with none of that (a checkout since deleted, say): treated as not
|
|
77
|
+
* relay's, so replacing or removing it takes --force. "foreign": anything else.
|
|
78
|
+
*/
|
|
79
|
+
export function relayCommandIdentity(command, args) {
|
|
80
|
+
if (typeof command !== "string" || !command.endsWith("/bin/relay") || !Array.isArray(args) || args[0] !== "mcp")
|
|
81
|
+
return "foreign";
|
|
82
|
+
return command === LAUNCHER || isRelayLauncher(command) || recordedLaunchers().includes(command) ? "relay" : "ambiguous";
|
|
83
|
+
}
|
|
84
|
+
/** Why an entry of relay's shape is not taken as relay's (relayCommandIdentity "ambiguous"). */
|
|
85
|
+
export const ambiguousNote = (command) => `it runs ${String(command)} mcp, which has the shape of relay's entry, but relay cannot confirm it is relay's: there is no relay package there, and relay's installation record does not name it`;
|
|
86
|
+
export const isRelayCommand = (command, args) => relayCommandIdentity(command, args) === "relay";
|
|
87
|
+
/** A host's server entry (a table with command and args) that runs relay (isRelayCommand). */
|
|
88
|
+
export const isRelayEntry = (entry) => isTable(entry) && isRelayCommand(entry.command, entry.args);
|
|
89
|
+
/** Whether relay is registered through these entries, as `registered()` says it: an ambiguous one is "unknown". */
|
|
90
|
+
export function entriesState(...entries) {
|
|
91
|
+
const ids = entries.filter(isTable).map((e) => relayCommandIdentity(e.command, e.args));
|
|
92
|
+
return ids.includes("relay") ? "registered" : ids.includes("ambiguous") ? "unknown" : "none";
|
|
93
|
+
}
|
|
94
|
+
/** JSON as relay writes the files it generates: indented, with a final newline. */
|
|
95
|
+
export const jsonText = (v) => JSON.stringify(v, null, 2) + "\n";
|
|
96
|
+
/** The part of an existing entry that relay itself writes. */
|
|
97
|
+
function managed(existing, intended) {
|
|
98
|
+
if (!isTable(existing) || !isTable(intended))
|
|
99
|
+
return existing;
|
|
100
|
+
return Object.fromEntries(Object.keys(intended).filter((k) => Object.hasOwn(existing, k)).map((k) => [k, managed(existing[k], intended[k])]));
|
|
101
|
+
}
|
|
102
|
+
/** What relay rewrites as a matter of course: where the launcher is, how it is started, and the desktop entry's PATH. */
|
|
103
|
+
const REWRITTEN = new Set(["command", "args", "env.PATH"]);
|
|
104
|
+
/**
|
|
105
|
+
* What replacing an existing entry would lose, as dotted names: settings relay does not write,
|
|
106
|
+
* and settings it does write that have been given another value (a timeout, an approval mode).
|
|
107
|
+
*/
|
|
108
|
+
function extras(existing, intended, prefix = "") {
|
|
109
|
+
if (!isTable(existing))
|
|
110
|
+
return [];
|
|
111
|
+
return Object.keys(existing).flatMap((k) => {
|
|
112
|
+
const name = prefix ? `${prefix}.${k}` : k;
|
|
113
|
+
const known = isTable(intended) && Object.hasOwn(intended, k);
|
|
114
|
+
const want = known ? intended[k] : undefined;
|
|
115
|
+
if (isTable(existing[k]) && (!known || isTable(want)))
|
|
116
|
+
return extras(existing[k], want, name);
|
|
117
|
+
if (!known)
|
|
118
|
+
return [name];
|
|
119
|
+
return REWRITTEN.has(name) || sameData(existing[k], want) ? [] : [`${name} changed`];
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
export const ownNote = (command, older) => command === LAUNCHER ? (older ? "an earlier form of relay's entry" : "relay's entry with other settings") : `relay registered from another checkout, ${command}`;
|
|
123
|
+
/** Judges an entry held as data: Codex's table or the desktop app's JSON entry. */
|
|
124
|
+
export function judge(existing, intended) {
|
|
125
|
+
if (existing === undefined)
|
|
126
|
+
return { state: "absent" };
|
|
127
|
+
if (!isTable(existing) || !isRelayCommand(existing.command, existing.args)) {
|
|
128
|
+
if (isTable(existing) && relayCommandIdentity(existing.command, existing.args) === "ambiguous")
|
|
129
|
+
return { state: "foreign", note: ambiguousNote(existing.command) };
|
|
130
|
+
return { state: "foreign", note: isTable(existing) && typeof existing.command === "string" ? `its command is ${existing.command}` : "it does not run a relay launcher" };
|
|
131
|
+
}
|
|
132
|
+
if (sameData(managed(existing, intended), intended))
|
|
133
|
+
return { state: "identical" };
|
|
134
|
+
const added = extras(existing, intended);
|
|
135
|
+
if (added.length)
|
|
136
|
+
return { state: "customised", extras: added };
|
|
137
|
+
return { state: "own", note: ownNote(existing.command, !existing.args.includes("--host")) };
|
|
138
|
+
}
|
|
139
|
+
/** Why relay will not go ahead, or null. An uninstall never objects to something foreign: it leaves it where it is. */
|
|
140
|
+
export function objection(what, found, force, verb) {
|
|
141
|
+
if (found.state === "blocked")
|
|
142
|
+
return found.note;
|
|
143
|
+
if (verb === "remove" || force)
|
|
144
|
+
return null;
|
|
145
|
+
if (found.state === "foreign") {
|
|
146
|
+
return `${what} is not relay's (${found.note}), so relay will not replace it. If it should go, run this again with --force: what is there now is saved first.`;
|
|
147
|
+
}
|
|
148
|
+
if (found.state === "customised") {
|
|
149
|
+
return `${what} is relay's, but it carries settings relay did not write (${found.extras.join(", ")}), and replacing it would put relay's own in their place. `
|
|
150
|
+
+ "Run this again with --force to replace it anyway (what is there now is saved first), then make those changes again.";
|
|
151
|
+
}
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Whether uninstall may take an entry out. Where install left a record, an entry that still runs
|
|
156
|
+
* the launcher the record names is the one relay put there. Otherwise, and for installations made
|
|
157
|
+
* before there was a record, the ownership test decides. Anything else stays unless --force is given.
|
|
158
|
+
*/
|
|
159
|
+
export function removable(run, found, command) {
|
|
160
|
+
if (found.state === "absent" || found.state === "blocked")
|
|
161
|
+
return false;
|
|
162
|
+
if (found.state !== "foreign" || run.force)
|
|
163
|
+
return true;
|
|
164
|
+
return typeof command === "string" && command === run.record.hosts[run.host]?.launcher;
|
|
165
|
+
}
|
|
166
|
+
export function readText(file) {
|
|
167
|
+
let bytes;
|
|
168
|
+
try {
|
|
169
|
+
bytes = fs.readFileSync(file);
|
|
170
|
+
}
|
|
171
|
+
catch (err) {
|
|
172
|
+
if (errCode(err) === "ENOENT")
|
|
173
|
+
return null;
|
|
174
|
+
throw new Stop(`${file} cannot be read (${errText(err)}).`);
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
// Kept exactly: a file that is not UTF-8 would not survive being read and written back.
|
|
178
|
+
return { bytes, text: new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes) };
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
throw new Stop(`${file} is not valid UTF-8, so relay will not edit it.`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Replaces a file in one step: a temporary file beside it, then a rename. A symlinked config
|
|
186
|
+
* (a dotfiles checkout, say) is written through, not replaced, and the file keeps its mode. If
|
|
187
|
+
* the file no longer holds what relay read, it is left alone.
|
|
188
|
+
*/
|
|
189
|
+
export function writeAtomic(file, text, before) {
|
|
190
|
+
let target = file;
|
|
191
|
+
try {
|
|
192
|
+
target = fs.realpathSync(file);
|
|
193
|
+
}
|
|
194
|
+
catch (err) {
|
|
195
|
+
if (errCode(err) !== "ENOENT")
|
|
196
|
+
throw new Stop(`${file} cannot be resolved (${errText(err)}).`);
|
|
197
|
+
if (fs.lstatSync(file, { throwIfNoEntry: false })?.isSymbolicLink())
|
|
198
|
+
throw new Stop(`${file} is a symbolic link to a file that does not exist; relay will not write through it.`);
|
|
199
|
+
}
|
|
200
|
+
const tmp = path.join(path.dirname(target), `.${path.basename(target)}.relay-${process.pid}-${Date.now().toString(36)}.tmp`);
|
|
201
|
+
try {
|
|
202
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
203
|
+
const mode = before ? fs.statSync(target).mode & 0o7777 : 0o600;
|
|
204
|
+
const fd = fs.openSync(tmp, "wx", mode);
|
|
205
|
+
try {
|
|
206
|
+
fs.writeFileSync(fd, text);
|
|
207
|
+
fs.fchmodSync(fd, mode);
|
|
208
|
+
fs.fsyncSync(fd);
|
|
209
|
+
}
|
|
210
|
+
finally {
|
|
211
|
+
fs.closeSync(fd);
|
|
212
|
+
}
|
|
213
|
+
const now = fs.existsSync(target) ? fs.readFileSync(target) : null;
|
|
214
|
+
if (before ? !now?.equals(before) : now !== null)
|
|
215
|
+
throw new Stop(`${file} changed while relay was working on it, so it was left as it is. Run this again.`);
|
|
216
|
+
fs.renameSync(tmp, target);
|
|
217
|
+
}
|
|
218
|
+
catch (err) {
|
|
219
|
+
fs.rmSync(tmp, { force: true });
|
|
220
|
+
throw err instanceof Stop ? err : new Stop(`${file} could not be written (${errText(err)}); it was left as it is.`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
/** A name beside `base` that nothing has yet: base itself the first time, timestamped after that. */
|
|
224
|
+
export function unusedName(base, attempt) {
|
|
225
|
+
return attempt === 0 ? base : `${base}-${stamp()}${attempt > 1 ? `-${attempt}` : ""}`;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Saves a file as relay read it to <file>.bak-relay, or to a timestamped name if that exists.
|
|
229
|
+
* An existing backup is never overwritten: the file is created only if nothing has the name.
|
|
230
|
+
*/
|
|
231
|
+
export function backupFile(file, bytes) {
|
|
232
|
+
for (let n = 0;; n++) {
|
|
233
|
+
const dest = unusedName(`${file}.bak-relay`, n);
|
|
234
|
+
try {
|
|
235
|
+
const mode = fs.statSync(file).mode & 0o7777;
|
|
236
|
+
fs.writeFileSync(dest, bytes, { flag: "wx", mode });
|
|
237
|
+
fs.chmodSync(dest, mode);
|
|
238
|
+
return dest;
|
|
239
|
+
}
|
|
240
|
+
catch (err) {
|
|
241
|
+
if (errCode(err) !== "EEXIST" || n > 50)
|
|
242
|
+
throw new Stop(`${file} could not be backed up (${errText(err)}), so it was not changed.`);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
/** Saves a description of something that is not a file (a registration, a marketplace entry) before relay replaces or removes it. */
|
|
247
|
+
export function saveJson(run, name, data) {
|
|
248
|
+
if (!run.write)
|
|
249
|
+
return null;
|
|
250
|
+
const dir = savedDir();
|
|
251
|
+
try {
|
|
252
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
253
|
+
for (let n = 1;; n++) {
|
|
254
|
+
const file = path.join(dir, `${name}-${stamp()}${n > 1 ? `-${n}` : ""}.json`);
|
|
255
|
+
try {
|
|
256
|
+
// It can hold another server's environment, so it is readable by the user only.
|
|
257
|
+
fs.writeFileSync(file, JSON.stringify({ saved_at: new Date().toISOString(), ...data }, null, 2) + "\n", { flag: "wx", mode: 0o600 });
|
|
258
|
+
return file;
|
|
259
|
+
}
|
|
260
|
+
catch (err) {
|
|
261
|
+
if (errCode(err) !== "EEXIST" || n > 50)
|
|
262
|
+
throw err;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
catch (err) {
|
|
267
|
+
throw new Stop(`could not save what is there now under ${dir} (${errText(err)}), so it was not touched.`);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
export function loadRecord() {
|
|
271
|
+
const file = recordFile();
|
|
272
|
+
if (!fs.existsSync(file))
|
|
273
|
+
return { version: 1, hosts: {} };
|
|
274
|
+
try {
|
|
275
|
+
const rec = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
276
|
+
if (!isTable(rec) || rec.version !== 1 || !isTable(rec.hosts))
|
|
277
|
+
throw new Error("it is not a version 1 record");
|
|
278
|
+
for (const [host, h] of Object.entries(rec.hosts)) {
|
|
279
|
+
if (!isTable(h) || typeof h.launcher !== "string" || typeof h.at !== "string" || !isTable(h.resources))
|
|
280
|
+
throw new Error(`its entry for ${host} is incomplete`);
|
|
281
|
+
}
|
|
282
|
+
if (rec.link !== undefined && (!isTable(rec.link) || typeof rec.link.target !== "string"))
|
|
283
|
+
throw new Error("its entry for the link is incomplete");
|
|
284
|
+
return rec;
|
|
285
|
+
}
|
|
286
|
+
catch (err) {
|
|
287
|
+
throw new Stop(`relay's installation record at ${file} cannot be used (${errText(err)}). Move it aside and run this again; relay then goes by what it finds installed.`);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
export function saveRecord(rec) {
|
|
291
|
+
const file = recordFile();
|
|
292
|
+
if (!Object.keys(rec.hosts).length && !rec.link)
|
|
293
|
+
return void fs.rmSync(file, { force: true });
|
|
294
|
+
const text = jsonText(rec);
|
|
295
|
+
const before = fs.existsSync(file) ? fs.readFileSync(file) : null;
|
|
296
|
+
if (before?.toString() !== text)
|
|
297
|
+
writeAtomic(file, text, before);
|
|
298
|
+
}
|
|
299
|
+
/** Records one change on disk at once, so that a run that dies half-way still leaves a true account of what it did. */
|
|
300
|
+
export function note(run, resource, c) {
|
|
301
|
+
const change = { ...c, at: new Date().toISOString() };
|
|
302
|
+
if (c.action !== "kept")
|
|
303
|
+
run.made.push(change);
|
|
304
|
+
if (!run.write)
|
|
305
|
+
return;
|
|
306
|
+
if (resource === "link") {
|
|
307
|
+
if (c.action === "removed")
|
|
308
|
+
delete run.record.link;
|
|
309
|
+
else if (c.action !== "kept" || !run.record.link)
|
|
310
|
+
run.record.link = { ...change, path: linkPath(), target: LAUNCHER };
|
|
311
|
+
}
|
|
312
|
+
else {
|
|
313
|
+
const host = run.record.hosts[run.host];
|
|
314
|
+
if (host && c.action !== "kept")
|
|
315
|
+
host.complete = false;
|
|
316
|
+
// Something already in place keeps the account of the run that put it there. A removal stays
|
|
317
|
+
// on record, with what it saved, until something takes its place or the host is uninstalled.
|
|
318
|
+
if (host && (c.action !== "kept" || !host.resources[resource] || host.resources[resource].action === "removed"))
|
|
319
|
+
host.resources[resource] = change;
|
|
320
|
+
}
|
|
321
|
+
if (c.action === "kept")
|
|
322
|
+
return;
|
|
323
|
+
run.recorded = false;
|
|
324
|
+
saveRecord(run.record);
|
|
325
|
+
run.recorded = Boolean(run.record.hosts[run.host]) || resource === "link";
|
|
326
|
+
}
|
|
327
|
+
/** The record has to be writable before anything else is changed: it is what a run that stops half-way leaves to go by. */
|
|
328
|
+
export function requireRecord(create) {
|
|
329
|
+
const dir = path.dirname(recordFile());
|
|
330
|
+
if (!create && !fs.existsSync(recordFile()))
|
|
331
|
+
return;
|
|
332
|
+
try {
|
|
333
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
334
|
+
fs.accessSync(dir, fs.constants.W_OK);
|
|
335
|
+
}
|
|
336
|
+
catch (err) {
|
|
337
|
+
throw new Stop(`relay could not prepare its installation record at ${recordFile()} (${errText(err)}).`);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
/** Runs one command of a host's CLI. It is printed either way, run only with --write, and a failure ends the run. */
|
|
341
|
+
export function step(run, argv, resource, change) {
|
|
342
|
+
say(`$ ${sh(argv)}`);
|
|
343
|
+
if (!run.write)
|
|
344
|
+
return void note(run, resource, change);
|
|
345
|
+
const r = spawnFound(argv[0], argv.slice(1), { stdio: "inherit", encoding: "utf8" });
|
|
346
|
+
if (r.error || r.status !== 0)
|
|
347
|
+
throw new Stop(`\`${sh(argv)}\` failed (${r.error ? errText(r.error) : r.signal ? `stopped by ${r.signal}` : `exit ${r.status}`}).`);
|
|
348
|
+
note(run, resource, change);
|
|
349
|
+
}
|
|
350
|
+
/** Backs a config file up and replaces it. */
|
|
351
|
+
export function writeFile(run, file, before, text, resource, change) {
|
|
352
|
+
if (!run.write)
|
|
353
|
+
return void note(run, resource, { ...change, file, backup: null });
|
|
354
|
+
const backup = before ? backupFile(file, before.bytes) : null;
|
|
355
|
+
try {
|
|
356
|
+
writeAtomic(file, text, before?.bytes ?? null);
|
|
357
|
+
}
|
|
358
|
+
catch (err) {
|
|
359
|
+
// Nothing was written, so the copy just made records no change. It is this run's own and goes again.
|
|
360
|
+
if (backup)
|
|
361
|
+
fs.rmSync(backup, { force: true });
|
|
362
|
+
throw err;
|
|
363
|
+
}
|
|
364
|
+
say(` written${backup ? `; the file as it was is at ${backup}` : ""}`);
|
|
365
|
+
note(run, resource, { ...change, file, backup });
|
|
366
|
+
}
|
|
367
|
+
/** Removes a whole file relay installed, saving it first and refusing if it changed since planning. */
|
|
368
|
+
export function removeFile(run, file, before, resource, change) {
|
|
369
|
+
if (!run.write)
|
|
370
|
+
return void note(run, resource, { ...change, file, backup: null });
|
|
371
|
+
const backup = backupFile(file, before.bytes);
|
|
372
|
+
try {
|
|
373
|
+
if (!fs.readFileSync(file).equals(before.bytes))
|
|
374
|
+
throw new Stop(`${file} changed while relay was working on it, so it was left as it is. Run this again.`);
|
|
375
|
+
fs.unlinkSync(file);
|
|
376
|
+
}
|
|
377
|
+
catch (err) {
|
|
378
|
+
fs.rmSync(backup, { force: true });
|
|
379
|
+
throw err instanceof Stop ? err : new Stop(`${file} could not be removed (${errText(err)}).`);
|
|
380
|
+
}
|
|
381
|
+
say(` removed; the file as it was is at ${backup}`);
|
|
382
|
+
note(run, resource, { ...change, file, backup });
|
|
383
|
+
}
|
|
384
|
+
// The CLIs
|
|
385
|
+
export function config() {
|
|
386
|
+
try {
|
|
387
|
+
return loadConfig();
|
|
388
|
+
}
|
|
389
|
+
catch (err) {
|
|
390
|
+
throw new Stop(`${errText(err)}. Fix or remove it first.`);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
/** The absolute path of an executable, as relay would run it (executables.ts findExecutable). */
|
|
394
|
+
export function locate(bin) {
|
|
395
|
+
return findExecutable(bin);
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Whose `relay` command `found` (a path on PATH) is, from where it leads and where it sits, never
|
|
399
|
+
* from its name: "launcher" when it resolves to `<root>/bin/relay` (the link install makes, or the
|
|
400
|
+
* launcher itself); "npm" when it is npm's global command for the package installed at `root`,
|
|
401
|
+
* that is, it sits in `<prefix>/bin`, resolves to the package's own `bin.relay` entry inside
|
|
402
|
+
* `root`, and `<prefix>/lib/node_modules/<package name>` is `root` (npm's layout for every prefix
|
|
403
|
+
* on macOS: /opt/homebrew, /usr/local, a custom one such as ~/.npm-global, a version manager's);
|
|
404
|
+
* null for anything else, including another checkout, another npm install, an entry that leads out
|
|
405
|
+
* of `root`, and a manifest relay cannot read.
|
|
406
|
+
*/
|
|
407
|
+
export function relayCommandKind(found, root = ROOT) {
|
|
408
|
+
const home = canonical(root);
|
|
409
|
+
const real = canonical(found);
|
|
410
|
+
// A file of this install, reached without leaving it: its real path is the install's own path
|
|
411
|
+
// joined with the name, so a link inside the install that leads elsewhere does not count.
|
|
412
|
+
const inside = (rel) => !path.isAbsolute(rel) && path.join(home, path.normalize(rel)).startsWith(home + path.sep) &&
|
|
413
|
+
canonical(path.join(home, rel)) === path.join(home, path.normalize(rel));
|
|
414
|
+
if (inside(path.join("bin", "relay")) && real === path.join(home, "bin", "relay"))
|
|
415
|
+
return "launcher";
|
|
416
|
+
let pkg;
|
|
417
|
+
try {
|
|
418
|
+
pkg = JSON.parse(fs.readFileSync(path.join(home, "package.json"), "utf8"));
|
|
419
|
+
}
|
|
420
|
+
catch {
|
|
421
|
+
return null;
|
|
422
|
+
}
|
|
423
|
+
if (!isTable(pkg))
|
|
424
|
+
return null;
|
|
425
|
+
const entry = typeof pkg.bin === "string" ? pkg.bin : isTable(pkg.bin) ? pkg.bin.relay : undefined;
|
|
426
|
+
if (typeof pkg.name !== "string" || !/^(?:@[\w~-][\w.~-]*\/)?[\w~-][\w.~-]*$/.test(pkg.name) || typeof entry !== "string")
|
|
427
|
+
return null;
|
|
428
|
+
if (!inside(entry) || real !== path.join(home, path.normalize(entry)))
|
|
429
|
+
return null;
|
|
430
|
+
const binDir = canonical(path.dirname(found));
|
|
431
|
+
if (path.basename(binDir) !== "bin")
|
|
432
|
+
return null;
|
|
433
|
+
return canonical(path.join(path.dirname(binDir), "lib", "node_modules", ...pkg.name.split("/"))) === home ? "npm" : null;
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* The package name when relay's package root sits where npm installs a package, at
|
|
437
|
+
* `node_modules/<name>` (a global install's `<prefix>/lib/node_modules/@jbkjr/relay`, or a project's
|
|
438
|
+
* own node_modules), going by its package.json; null otherwise: a git checkout (one with its own .git,
|
|
439
|
+
* wherever it sits), `npm link`ed or not
|
|
440
|
+
* (Node runs a linked package from its real path), or a copy elsewhere.
|
|
441
|
+
*/
|
|
442
|
+
export function npmInstallName(root = ROOT) {
|
|
443
|
+
let pkg;
|
|
444
|
+
try {
|
|
445
|
+
pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
|
|
446
|
+
}
|
|
447
|
+
catch {
|
|
448
|
+
return null;
|
|
449
|
+
}
|
|
450
|
+
if (!isTable(pkg) || typeof pkg.name !== "string" || !/^(?:@[\w~-][\w.~-]*\/)?[\w~-][\w.~-]*$/.test(pkg.name))
|
|
451
|
+
return null;
|
|
452
|
+
// A checkout (or worktree, whose .git is a file) wherever it sits is a checkout: its HEAD is compared.
|
|
453
|
+
if (fs.existsSync(path.join(root, ".git")))
|
|
454
|
+
return null;
|
|
455
|
+
const parts = canonical(root).split(path.sep);
|
|
456
|
+
const want = ["node_modules", ...pkg.name.split("/")];
|
|
457
|
+
return parts.slice(-want.length).join("/") === want.join("/") ? pkg.name : null;
|
|
458
|
+
}
|
|
459
|
+
/** What relay runs from, for messages that name it: "npm install" or "checkout". */
|
|
460
|
+
export const installKind = () => (npmInstallName() ? "npm install" : "checkout");
|
|
461
|
+
/**
|
|
462
|
+
* The first relative or empty PATH entry ahead of `dir`, or null. A shell searches such an entry
|
|
463
|
+
* from its current directory, so a `relay` there runs first in some directories; relay's own
|
|
464
|
+
* lookup (findExecutable) skips them, so doctor names them instead.
|
|
465
|
+
*/
|
|
466
|
+
export function relativePathEntryBefore(dir, searchPath = process.env.PATH ?? "") {
|
|
467
|
+
for (const d of searchPath.split(path.delimiter)) {
|
|
468
|
+
if (!d || !path.isAbsolute(d))
|
|
469
|
+
return d || "(an empty entry)";
|
|
470
|
+
if (canonical(d) === canonical(dir))
|
|
471
|
+
return null;
|
|
472
|
+
}
|
|
473
|
+
return null;
|
|
474
|
+
}
|
|
475
|
+
/** Checks that a host's CLI exists and runs, before anything is changed, and returns what it says its version is. */
|
|
476
|
+
export function requireCli(cli, bin) {
|
|
477
|
+
const r = probeVersion(cli, bin, process.env);
|
|
478
|
+
if (!r.error && r.status === 0)
|
|
479
|
+
return r.stdout.trim();
|
|
480
|
+
const why = r.error ? (errCode(r.error) === "ENOENT" ? `\`${bin}\` was not found` : `\`${bin}\` could not be started (${errText(r.error)})`) : `\`${bin} --version\` failed (exit ${r.status})`;
|
|
481
|
+
throw new Stop(`This needs the ${cli} CLI, and ${why}. Install ${targetDef(cli).product} and make sure \`${cli}\` is on PATH, or set \`targets.${cli}.bin\` in ${configPath()} to its full path.`);
|
|
482
|
+
}
|
|
483
|
+
/** Asks a CLI for something in JSON. These calls only read. */
|
|
484
|
+
export function queryJson(argv) {
|
|
485
|
+
const r = spawnFound(argv[0], argv.slice(1), { encoding: "utf8" });
|
|
486
|
+
if (r.error || r.status !== 0) {
|
|
487
|
+
throw new Stop(`relay could not see what is installed: \`${sh(argv)}\` failed (${r.error ? errText(r.error) : `exit ${r.status}`})${r.stderr?.trim() ? `: ${r.stderr.trim()}` : ""}.`);
|
|
488
|
+
}
|
|
489
|
+
try {
|
|
490
|
+
return JSON.parse(r.stdout);
|
|
491
|
+
}
|
|
492
|
+
catch {
|
|
493
|
+
throw new Stop(`relay could not see what is installed: \`${sh(argv)}\` did not print JSON.`);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
/** How both CLIs say that no server has the name. Any other failure is not an answer, and is not read as one. */
|
|
497
|
+
export const NO_SERVER = /no mcp server (named|found)/i;
|
|
498
|
+
const kit = (format, bin) => ({
|
|
499
|
+
marketAdd: (dir) => [bin, "plugin", "marketplace", "add", dir],
|
|
500
|
+
marketRemove: [bin, "plugin", "marketplace", "remove", MARKETPLACE],
|
|
501
|
+
pluginAdd: [bin, "plugin", format.verbs.add, PLUGIN],
|
|
502
|
+
pluginRemove: [bin, "plugin", format.verbs.remove, PLUGIN],
|
|
503
|
+
});
|
|
504
|
+
/** The plugin marketplace named relay-local, if the CLI has one, and whether it is one of relay's adapter directories. */
|
|
505
|
+
export function marketState(format, bin) {
|
|
506
|
+
const argv = [bin, "plugin", "marketplace", "list", "--json"];
|
|
507
|
+
const all = format.marketplaces(queryJson(argv));
|
|
508
|
+
if (!Array.isArray(all))
|
|
509
|
+
throw new Stop(`relay could not see what is installed: \`${sh(argv)}\` printed something relay does not understand.`);
|
|
510
|
+
const raw = all.find((m) => isTable(m) && m.name === MARKETPLACE);
|
|
511
|
+
if (!raw)
|
|
512
|
+
return { state: "absent", source: "", raw: null };
|
|
513
|
+
const from = format.localSource(raw);
|
|
514
|
+
if (typeof from !== "string")
|
|
515
|
+
return { state: "foreign", source: JSON.stringify(raw), raw };
|
|
516
|
+
const source = from.replace(/\/+$/, "");
|
|
517
|
+
if (canonical(source) === canonical(path.join(ROOT, "adapters", format.dir)))
|
|
518
|
+
return { state: "identical", source, raw };
|
|
519
|
+
return { state: source.endsWith(`/adapters/${format.dir}`) ? "own" : "foreign", source, raw };
|
|
520
|
+
}
|
|
521
|
+
/** The plugin as the host has it: whether it is installed, at which version if the host says, and where the host keeps its copy. */
|
|
522
|
+
export function pluginInstalled(format, bin) {
|
|
523
|
+
const argv = [bin, "plugin", "list", "--json"];
|
|
524
|
+
const all = format.plugins(queryJson(argv));
|
|
525
|
+
if (!Array.isArray(all))
|
|
526
|
+
throw new Stop(`relay could not see what is installed: \`${sh(argv)}\` printed something relay does not understand.`);
|
|
527
|
+
// Relay installs at user scope; a copy someone enabled for one project is theirs.
|
|
528
|
+
const found = all.find((p) => isTable(p) && format.isRelayPlugin(p));
|
|
529
|
+
return {
|
|
530
|
+
installed: Boolean(found),
|
|
531
|
+
version: isTable(found) && typeof found.version === "string" ? found.version : null,
|
|
532
|
+
copy: isTable(found) ? format.copyOf(found) : null,
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
/** A version as a host names a plugin's directory after it: one path component, nothing that climbs. */
|
|
536
|
+
export const versionDir = (v) => (typeof v === "string" && /^[\w.+-]+$/.test(v) && v !== "." && v !== ".." ? v : null);
|
|
537
|
+
/**
|
|
538
|
+
* A digest of what a plugin directory holds: each file's path inside it and its bytes, and each
|
|
539
|
+
* symbolic link's path and target, in a fixed order (directories themselves, modes and times do
|
|
540
|
+
* not count, nor Finder's .DS_Store). Null if the directory is not there or cannot be read.
|
|
541
|
+
*/
|
|
542
|
+
function treeDigest(dir) {
|
|
543
|
+
if (!dir)
|
|
544
|
+
return null;
|
|
545
|
+
const h = createHash("sha256");
|
|
546
|
+
const walk = (rel) => {
|
|
547
|
+
const names = fs.readdirSync(path.join(dir, rel), { withFileTypes: true }).filter((e) => e.name !== ".DS_Store");
|
|
548
|
+
names.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
549
|
+
for (const e of names) {
|
|
550
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
551
|
+
if (e.isDirectory())
|
|
552
|
+
walk(r);
|
|
553
|
+
else if (e.isSymbolicLink())
|
|
554
|
+
h.update(`link ${r}\0${fs.readlinkSync(path.join(dir, r))}\0`);
|
|
555
|
+
else if (e.isFile()) {
|
|
556
|
+
const bytes = fs.readFileSync(path.join(dir, r));
|
|
557
|
+
h.update(`file ${r}\0${bytes.length}\0`);
|
|
558
|
+
h.update(bytes);
|
|
559
|
+
}
|
|
560
|
+
else
|
|
561
|
+
h.update(`other ${r}\0`);
|
|
562
|
+
}
|
|
563
|
+
};
|
|
564
|
+
try {
|
|
565
|
+
if (!fs.statSync(dir).isDirectory())
|
|
566
|
+
return null;
|
|
567
|
+
walk("");
|
|
568
|
+
return h.digest("hex");
|
|
569
|
+
}
|
|
570
|
+
catch {
|
|
571
|
+
return null;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
/** The version of the plugin this checkout would install. */
|
|
575
|
+
export function pluginVersion(format) {
|
|
576
|
+
try {
|
|
577
|
+
return String(JSON.parse(fs.readFileSync(path.join(ROOT, "adapters", format.dir, "relay", format.manifestDir, "plugin.json"), "utf8")).version);
|
|
578
|
+
}
|
|
579
|
+
catch {
|
|
580
|
+
return null;
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
// The pieces of an installation
|
|
584
|
+
/** The plugin (skills and slash commands) and the marketplace entry that points at this checkout's adapters. */
|
|
585
|
+
export function planKit(run, format, bin) {
|
|
586
|
+
const c = kit(format, bin);
|
|
587
|
+
const dir = path.join(ROOT, "adapters", format.dir);
|
|
588
|
+
const market = marketState(format, bin);
|
|
589
|
+
const has = pluginInstalled(format, bin);
|
|
590
|
+
let installed = has.installed;
|
|
591
|
+
// A host keeps its own copy of the plugin. After an update of this checkout that copy is the
|
|
592
|
+
// old skills, so a plugin whose version is not this checkout's is put in again; and so is one at
|
|
593
|
+
// this version whose copy holds anything but this checkout's adapter (a release candidate respun
|
|
594
|
+
// at the same version), or whose copy relay cannot find or read to tell.
|
|
595
|
+
const mine = pluginVersion(format);
|
|
596
|
+
const source = path.join(dir, "relay");
|
|
597
|
+
const otherVersion = installed && has.version !== null && mine !== null && has.version !== mine;
|
|
598
|
+
const ours = otherVersion || !installed || market.state !== "identical" ? null : treeDigest(source);
|
|
599
|
+
const theirs = ours === null ? null : treeDigest(has.copy);
|
|
600
|
+
const otherContent = ours !== null && theirs !== ours;
|
|
601
|
+
const stale = otherVersion || otherContent;
|
|
602
|
+
const copyNote = !otherContent ? null : theirs === null
|
|
603
|
+
? `relay could not ${has.copy ? `read ${format.hostName}'s copy of the plugin (${has.copy})` : `find ${format.hostName}'s copy of the plugin`} to compare it with this checkout's adapters/${format.dir}/relay`
|
|
604
|
+
: `${format.hostName}'s copy of the plugin (${has.copy}) is not this checkout's adapters/${format.dir}/relay (the same version, other content)`;
|
|
605
|
+
const what = `${format.hostName}'s plugin marketplace "${MARKETPLACE}"`;
|
|
606
|
+
if (run.verb === "uninstall") {
|
|
607
|
+
const leave = market.state === "foreign" && !run.force;
|
|
608
|
+
return {
|
|
609
|
+
problems: [],
|
|
610
|
+
apply() {
|
|
611
|
+
if (leave)
|
|
612
|
+
return void say(`# left alone: ${what} is not relay's (its source is ${market.source}), nor is the plugin from it. --force removes them.`);
|
|
613
|
+
if (installed)
|
|
614
|
+
step(run, c.pluginRemove, "plugin", { action: "removed", what: `uninstalled the plugin ${PLUGIN} from ${format.hostName}`, backup: null, undo: sh(c.pluginAdd) });
|
|
615
|
+
if (market.state === "absent")
|
|
616
|
+
return;
|
|
617
|
+
const backup = market.state === "foreign" ? saveJson(run, `${format.dir}-marketplace`, { what: `${what}, as it was before relay removed it`, entry: market.raw }) : null;
|
|
618
|
+
step(run, c.marketRemove, "marketplace", { action: "removed", what: `removed ${what} (${market.source})`, backup, undo: market.state === "foreign" ? null : sh(c.marketAdd(market.source)) });
|
|
619
|
+
},
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
return {
|
|
623
|
+
problems: market.state === "foreign" && !run.force ? [`${what} is not relay's (its source is ${market.source}), so relay will not replace it. If it should go, run this again with --force: what is there now is saved first.`] : [],
|
|
624
|
+
apply() {
|
|
625
|
+
if (market.state === "identical" && stale) {
|
|
626
|
+
if (copyNote)
|
|
627
|
+
say(`# ${copyNote}, so it is put in again`);
|
|
628
|
+
const why = copyNote ? `: ${copyNote}` : ` at version ${has.version}, to put in ${mine}`;
|
|
629
|
+
step(run, c.pluginRemove, "plugin", { action: "removed", what: `uninstalled the plugin ${PLUGIN}${why}`, backup: null, undo: sh(c.pluginAdd) });
|
|
630
|
+
step(run, c.marketRemove, "marketplace", { action: "removed", what: `removed ${what} so that the host reads it afresh`, backup: null, undo: sh(c.marketAdd(dir)) });
|
|
631
|
+
step(run, c.marketAdd(dir), "marketplace", { action: "replaced", what: `added ${what} (${dir})`, backup: null, undo: sh(c.marketRemove) });
|
|
632
|
+
installed = false;
|
|
633
|
+
}
|
|
634
|
+
else if (market.state === "identical") {
|
|
635
|
+
note(run, "marketplace", { action: "kept", what: `${what} already points at ${dir}`, backup: null, undo: sh(c.marketRemove) });
|
|
636
|
+
}
|
|
637
|
+
else {
|
|
638
|
+
let backup = null;
|
|
639
|
+
if (market.state !== "absent") {
|
|
640
|
+
// Another checkout's marketplace, or with --force someone else's: the plugin that came from it goes with it.
|
|
641
|
+
backup = saveJson(run, `${format.dir}-marketplace`, { what: `${what}, as it was before relay replaced it`, entry: market.raw });
|
|
642
|
+
if (installed)
|
|
643
|
+
step(run, c.pluginRemove, "plugin", { action: "removed", what: `uninstalled the plugin ${PLUGIN} that came from ${market.source}`, backup: null, undo: sh(c.pluginAdd) });
|
|
644
|
+
step(run, c.marketRemove, "marketplace", { action: "removed", what: `removed ${what} (${market.source})`, backup, undo: market.state === "own" ? sh(c.marketAdd(market.source)) : null });
|
|
645
|
+
installed = false;
|
|
646
|
+
}
|
|
647
|
+
step(run, c.marketAdd(dir), "marketplace", { action: market.state === "absent" ? "added" : "replaced", what: `added ${what} (${dir})`, backup, undo: sh(c.marketRemove) });
|
|
648
|
+
}
|
|
649
|
+
if (installed)
|
|
650
|
+
note(run, "plugin", { action: "kept", what: `the plugin ${PLUGIN} was already installed in ${format.hostName}`, backup: null, undo: sh(c.pluginRemove) });
|
|
651
|
+
else
|
|
652
|
+
step(run, c.pluginAdd, "plugin", { action: "added", what: `installed the plugin ${PLUGIN} in ${format.hostName}`, backup: null, undo: sh(c.pluginRemove) });
|
|
653
|
+
},
|
|
654
|
+
};
|
|
655
|
+
}
|