@scp-dev/cli 0.1.3 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/README.md +1 -0
  2. package/dist/{chunk-ABP5AKFH.js → chunk-25ZVL5LD.js} +8 -10
  3. package/dist/{chunk-ABR5UABL.js → chunk-HF4KP6AR.js} +229 -13
  4. package/dist/{chunk-QQZF5TQD.js → chunk-KC5AV5NQ.js} +3 -5
  5. package/dist/{chunk-M2DCR2J4.js → chunk-MNTIEWKF.js} +13 -3
  6. package/dist/{chunk-5UWLTO2Y.js → chunk-MXQ7B3CQ.js} +3 -5
  7. package/dist/{chunk-IH2RJRIW.js → chunk-NJLFHBSS.js} +20 -10
  8. package/dist/chunk-ZLL5EGI2.js +805 -0
  9. package/dist/{claude-5WTICOYS.js → claude-WTCPUYU3.js} +21 -11
  10. package/dist/cli.js +1 -1
  11. package/dist/codex-YZZNH6IQ.js +565 -0
  12. package/dist/{daemon-SUTLTY5U.js → daemon-OMJY7T2F.js} +1 -1
  13. package/dist/{hooks-4YVIPZKE.js → hooks-4B5NOH7X.js} +19 -3
  14. package/dist/install-2ZM3IYXG.js +14 -0
  15. package/dist/join-BH5CS6SL.js +45 -0
  16. package/dist/{login-5Y3HPSVC.js → login-UB72MU7W.js} +4 -7
  17. package/dist/{main-PZQAJGHQ.js → main-I4F53MMA.js} +81 -30
  18. package/dist/{mcp-GI5OMTUT.js → mcp-RXAVQBMP.js} +11 -11
  19. package/dist/{peek-X4SEGEUB.js → peek-M2HQVO4O.js} +2 -3
  20. package/dist/pi-IAVFVOOO.js +71 -0
  21. package/dist/{relay-W2NFUE2U.js → relay-QDX2BNZH.js} +6 -4
  22. package/dist/{remote-GC4XN44U.js → remote-2OWBWLJH.js} +3 -5
  23. package/dist/{setup-UF4AA6RO.js → setup-HPH7HE6O.js} +5 -6
  24. package/dist/{spawn-KT5235WX.js → spawn-V66GYUNC.js} +6 -7
  25. package/dist/{up-VA54QWA6.js → up-2YGEDA5J.js} +6 -9
  26. package/package.json +7 -5
  27. package/dist/chunk-3PGDKPRN.js +0 -304
  28. package/dist/chunk-BUC5G5PY.js +0 -147
  29. package/dist/chunk-URSBFDR6.js +0 -340
  30. package/dist/install-4KQQWGGB.js +0 -15
@@ -1,12 +1,9 @@
1
1
  import {
2
+ RelayUsage,
2
3
  activeRelay,
3
4
  relayCredential
4
- } from "./chunk-BUC5G5PY.js";
5
- import {
6
- RelayUsage
7
- } from "./chunk-URSBFDR6.js";
8
- import "./chunk-3PGDKPRN.js";
9
- import "./chunk-M2DCR2J4.js";
5
+ } from "./chunk-ZLL5EGI2.js";
6
+ import "./chunk-MNTIEWKF.js";
10
7
 
11
8
  // src/up.ts
12
9
  import { CLI_NAME } from "@scp-dev/core";
@@ -17,16 +14,16 @@ async function up(positionals, values, cwd, brokerStatus) {
17
14
  const { url } = activeRelay(process.env);
18
15
  const headless = values.token !== void 0 || Boolean(process.env.SCP_TOKEN?.trim());
19
16
  if (headless || !relayCredential(process.env, url).token) {
20
- const code = await (await import("./login-5Y3HPSVC.js")).login({
17
+ const code = await (await import("./login-UB72MU7W.js")).login({
21
18
  ...values.token !== void 0 ? { token: values.token } : {},
22
19
  ...values.label !== void 0 ? { label: values.label } : {},
23
20
  ...values["no-browser"] ? { "no-browser": true } : {}
24
21
  });
25
22
  if (code !== 0) return code;
26
23
  } else out(`already logged in to ${url}`);
27
- const enabled = await (await import("./remote-GC4XN44U.js")).cloudMain(["enable"], values.machine !== void 0 ? { machine: values.machine } : {}, brokerStatus);
24
+ const enabled = await (await import("./remote-2OWBWLJH.js")).cloudMain(["enable"], values.machine !== void 0 ? { machine: values.machine } : {}, brokerStatus);
28
25
  if (enabled !== 0) return enabled;
29
- const setup = (await import("./setup-UF4AA6RO.js")).relaySetupCommand(["--write"], cwd, out);
26
+ const setup = (await import("./setup-HPH7HE6O.js")).relaySetupCommand(["--write"], cwd, out);
30
27
  if (setup !== 0) return setup;
31
28
  const broker = await brokerStatus();
32
29
  if (!broker.enabled) out(`the broker is still local-only; run \`${CLI_NAME} daemon restart\` to link it to ${url}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scp-dev/cli",
3
- "version": "0.1.3",
3
+ "version": "0.2.1",
4
4
  "description": "The swarm command line tool.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://scp.dev",
@@ -24,13 +24,15 @@
24
24
  "typecheck": "tsc -p ."
25
25
  },
26
26
  "dependencies": {
27
- "@scp-dev/core": "0.1.1",
28
- "@scp-dev/broker": "0.1.2",
29
- "@scp-dev/hub": "0.1.1",
30
- "@scp-dev/mcp": "0.1.2",
27
+ "@scp-dev/core": "0.1.2",
28
+ "@scp-dev/broker": "0.1.3",
29
+ "@scp-dev/hub": "0.2.0",
30
+ "@scp-dev/mcp": "0.1.3",
31
31
  "smol-toml": "^1.9.1"
32
32
  },
33
33
  "devDependencies": {
34
+ "@openai/codex": "0.159.0",
35
+ "opencode-ai": "1.18.34",
34
36
  "tsup": "^8.5.1"
35
37
  },
36
38
  "publishConfig": {
@@ -1,304 +0,0 @@
1
- import {
2
- capture
3
- } from "./chunk-M2DCR2J4.js";
4
-
5
- // src/identity.ts
6
- import { existsSync, realpathSync } from "fs";
7
- import { tmpdir } from "os";
8
- import { basename, dirname, isAbsolute, join, resolve } from "path";
9
- import { shortHostname } from "@scp-dev/broker";
10
- import { LIMITS, validHandle, validHarness } from "@scp-dev/core";
11
- var SHORT = { "claude-code": "claude" };
12
- var SHELLS = /* @__PURE__ */ new Set(["sh", "bash", "zsh", "dash", "fish"]);
13
- var LABEL_KEY = /^[a-z0-9][a-z0-9._-]{0,31}$/;
14
- function detectHarness(env) {
15
- if (env.GROK_SESSION_ID || env.GROK_HOOK_EVENT) return "grok";
16
- if (env.MUSE_SESSION_ID) return "muse";
17
- if (env.OPENCODE === "1") return "opencode";
18
- if (env.ANTIGRAVITY_AGENT === "1" || env.ANTIGRAVITY_CONVERSATION_ID) return "agy";
19
- if (env.CLAUDECODE === "1") return "claude-code";
20
- if (env.CODEX_THREAD_ID) return "codex";
21
- return void 0;
22
- }
23
- function normalizeHarness(raw, fallback) {
24
- const name = (raw ?? "").toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+/, "").slice(0, 32).replace(/-+$/, "");
25
- if (name === "claude") return "claude-code";
26
- return validHarness(name) ? name : fallback;
27
- }
28
- function hookHarness(argument, env) {
29
- if (!argument) return detectHarness(env) ?? "hook";
30
- const named = normalizeHarness(argument, "hook");
31
- return named === "claude-code" && (env.GROK_SESSION_ID || env.GROK_HOOK_EVENT) ? "grok" : named;
32
- }
33
- function resolveHarness(explicit, env, fallback) {
34
- const named = explicit ?? env.SCP_HARNESS;
35
- return named ? normalizeHarness(named, fallback) : detectHarness(env) ?? normalizeHarness(fallback, "mcp");
36
- }
37
- function gitToplevel(cwd) {
38
- for (let dir = resolve(cwd); ; dir = dirname(dir)) {
39
- if (existsSync(join(dir, ".git"))) return dir;
40
- if (dirname(dir) === dir) return void 0;
41
- }
42
- }
43
- function toHandle(raw) {
44
- let handle = raw.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[^a-z0-9]+/, "").slice(0, 63).replace(/[-.]+$/, "");
45
- if (!handle) handle = "agent";
46
- if (!validHandle(handle)) handle = `${handle.slice(0, 56)}-agent`;
47
- return handle;
48
- }
49
- function deriveHandle(harness, cwd) {
50
- const top = gitToplevel(cwd) ?? resolve(cwd);
51
- return toHandle(`${SHORT[harness] ?? harness}-${basename(top) || "root"}`);
52
- }
53
- function parseLabels(value) {
54
- const labels = {};
55
- for (const pair of (value ?? "").split(",")) {
56
- const eq = pair.indexOf("=");
57
- const key = pair.slice(0, eq).trim();
58
- if (eq > 0 && LABEL_KEY.test(key)) labels[key] = pair.slice(eq + 1).trim();
59
- }
60
- return labels;
61
- }
62
- function labelsFor(env, host = shortHostname()) {
63
- const labels = parseLabels(env.SCP_LABELS);
64
- labels.machine ??= host;
65
- return labels;
66
- }
67
- function processKey(harnessPid2, startOf = psStart) {
68
- const started = startOf(harnessPid2);
69
- return started ? `pid:${harnessPid2}:${started}` : `pid:${harnessPid2}`;
70
- }
71
- function sessionKey(env, harnessProcess) {
72
- return env.SCP_SESSION ? `env:${env.SCP_SESSION}` : harnessProcess;
73
- }
74
- function psStart(pid) {
75
- try {
76
- const started = (capture(["ps", "-o", "lstart=", "-p", String(pid)], { PATH: process.env.PATH ?? "/usr/bin:/bin", LC_ALL: "C" }) ?? "").trim().replace(/\s+/g, "-");
77
- return /^[A-Za-z0-9:-]{1,64}$/.test(started) ? started : void 0;
78
- } catch {
79
- return void 0;
80
- }
81
- }
82
- function parsePsCommTable(text) {
83
- const table = /* @__PURE__ */ new Map();
84
- for (const line of text.split("\n")) {
85
- const match = /^\s*(\d+)\s+(\d+)\s+(\S+\s+\S+\s+\S+\s+\S+\s+\S+)\s+(\S.*?)\s*$/.exec(line);
86
- if (match) table.set(Number(match[1]), { ppid: Number(match[2]), start: match[3].replace(/\s+/g, "-"), args: match[4] });
87
- }
88
- return table;
89
- }
90
- function readPsTable() {
91
- try {
92
- const table = capture(["ps", "-ww", "-axo", "pid=,ppid=,lstart=,args="], { PATH: process.env.PATH ?? "/usr/bin:/bin", LC_ALL: "C" });
93
- return table === void 0 ? void 0 : parsePsCommTable(table);
94
- } catch {
95
- return void 0;
96
- }
97
- }
98
- var PASS_THROUGH = /* @__PURE__ */ new Set([
99
- ...SHELLS,
100
- "ash",
101
- "ksh",
102
- "env",
103
- "timeout",
104
- "nohup",
105
- "nice",
106
- "time",
107
- "stdbuf",
108
- "xargs",
109
- "script",
110
- "caffeinate",
111
- "flock",
112
- "sandbox-exec",
113
- "bwrap",
114
- "codex-linux-sandbox",
115
- "codex-linux-san"
116
- ]);
117
- var INTERPRETERS = /* @__PURE__ */ new Set(["node", "nodejs", "bun", "deno", "ruby", "perl"]);
118
- var RUNNERS = /* @__PURE__ */ new Set(["npm", "pnpm", "yarn"]);
119
- var FETCHERS = /* @__PURE__ */ new Set(["npx", "bunx", "pnpx", "uvx"]);
120
- var SCRIPT_RUNNERS = /* @__PURE__ */ new Set(["tsx", "ts-node", "vite-node", "esno"]);
121
- var INLINE = /* @__PURE__ */ new Set(["-c", "-e", "--eval", "-p", "--print", "-"]);
122
- var VALUED = /* @__PURE__ */ new Set(["-r", "--require", "--import", "--loader", "--experimental-loader", "-I", "-M", "-W", "-X", "-C", "--conditions", "--preload"]);
123
- var HARNESSES = /* @__PURE__ */ new Set([
124
- "claude",
125
- "claude-code",
126
- "codex",
127
- "opencode",
128
- "opencode-ai",
129
- "grok",
130
- "grok-cli",
131
- "muse",
132
- "agy",
133
- "antigravity",
134
- "gemini",
135
- "gemini-cli"
136
- ]);
137
- var INSTALLED = /(^|\/)(node_modules|site-packages|dist-packages|\.npm|\.bun|\.cache|\.local|\.cargo|\.volta|\.nvm|\.pyenv|\.rbenv|Cellar|Applications)(\/|$)|^\/(opt|usr|Library|nix)\//;
138
- function command(args) {
139
- return basename(args.split(/\s+/)[0].replace(/^-/, "")).toLowerCase();
140
- }
141
- var namesHarness = (words) => words.some((word) => !word.startsWith("-") && word.split("/").some((part) => HARNESSES.has(part.toLowerCase().replace(/\..*$/, ""))));
142
- var roots;
143
- function workspaceRoots() {
144
- if (roots) return roots;
145
- const real = (path) => {
146
- try {
147
- return realpathSync(path);
148
- } catch {
149
- return path;
150
- }
151
- };
152
- const found = [process.cwd(), tmpdir(), "/tmp", "/private/tmp", "/var/folders", "/private/var/folders"];
153
- try {
154
- const top = capture(["git", "rev-parse", "--show-toplevel"]);
155
- if (top !== void 0) found.push(top.trim());
156
- } catch {
157
- }
158
- roots = [...new Set(found.filter(Boolean).map(real))];
159
- return roots;
160
- }
161
- function ownScript(operand) {
162
- if (operand === void 0 || operand === "-") return true;
163
- if (/^[a-z][a-z0-9+.-]*:/i.test(operand) || operand.startsWith("~") || INSTALLED.test(operand)) return false;
164
- if (!isAbsolute(operand)) return !operand.split("/").includes("..");
165
- let path = operand;
166
- try {
167
- path = realpathSync(operand);
168
- } catch {
169
- }
170
- if (INSTALLED.test(path)) return false;
171
- return workspaceRoots().some((root) => path === root || path.startsWith(`${root}/`));
172
- }
173
- function helper(args) {
174
- const words = args.split(/\s+/);
175
- if (namesHarness(words.slice(1))) return false;
176
- const name = command(args);
177
- let rest = words.slice(1);
178
- if (FETCHERS.has(name)) {
179
- while (rest[0]?.startsWith("-")) rest = rest.slice(1);
180
- return SCRIPT_RUNNERS.has(rest[0] ?? "") && rest.slice(1).every((word) => word.startsWith("-") || ownScript(word));
181
- }
182
- if (name === "uv" || RUNNERS.has(name)) {
183
- if (rest[0] !== "run") return false;
184
- if (name === "uv") {
185
- rest = rest.slice(1);
186
- while (rest[0]?.startsWith("-")) rest = rest.slice(1);
187
- if (rest[0] === void 0) return true;
188
- const inner = rest.join(" ");
189
- return /^python[0-9.]*$/.test(command(inner)) || INTERPRETERS.has(command(inner)) ? helper(inner) : ownScript(rest[0]);
190
- }
191
- return true;
192
- }
193
- if (!INTERPRETERS.has(name) && !/^python[0-9.]*$/.test(name)) return false;
194
- if (name === "bun" && rest[0] === "x") return false;
195
- if ((name === "bun" || name === "deno") && rest[0] === "run") {
196
- rest = rest.slice(1);
197
- if (name === "deno") while (rest[0]?.startsWith("-")) rest = rest.slice(1);
198
- const target = rest.find((word) => !word.startsWith("-"));
199
- if (target !== void 0 && !/[/.]/.test(target)) return false;
200
- }
201
- for (let i = 0; i < rest.length; i++) {
202
- const word = rest[i];
203
- if (word === "-m") return false;
204
- if (INLINE.has(word)) return true;
205
- if (VALUED.has(word)) {
206
- if (!ownScript(rest[++i])) return false;
207
- continue;
208
- }
209
- if (!word.startsWith("-")) return ownScript(word);
210
- }
211
- return true;
212
- }
213
- function harnessLineage(pid, table = readPsTable()) {
214
- const keys = lineage(pid, table);
215
- let first = -1;
216
- for (let i = 0, at = pid; i < keys.length; i++, at = table.get(at).ppid) {
217
- const args = table.get(at).args;
218
- if (PASS_THROUGH.has(command(args))) continue;
219
- if (!helper(args)) return keys.slice(0, i + 1);
220
- if (first < 0) first = i;
221
- }
222
- return first < 0 ? [] : keys;
223
- }
224
- var INITS = /* @__PURE__ */ new Set(["init", "systemd", "launchd"]);
225
- function hiddenHarness(pid, table = readPsTable()) {
226
- if (!table || harnessLineage(pid, table).length) return false;
227
- const seen = /* @__PURE__ */ new Set();
228
- let at = pid;
229
- while (at > 1 && !seen.has(at)) {
230
- seen.add(at);
231
- const entry = table.get(at);
232
- if (!entry) return false;
233
- at = entry.ppid;
234
- }
235
- const init = table.get(1);
236
- return at === 1 && init !== void 0 && !INITS.has(command(init.args));
237
- }
238
- function lineage(harnessPid2, table = readPsTable()) {
239
- const keys = [];
240
- const seen = /* @__PURE__ */ new Set();
241
- for (let pid = harnessPid2; pid > 1 && keys.length < LIMITS.lineageMax && !seen.has(pid); ) {
242
- const entry = table?.get(pid);
243
- if (!entry) break;
244
- seen.add(pid);
245
- keys.push(/^[A-Za-z0-9:-]{1,64}$/.test(entry.start) ? `pid:${pid}:${entry.start}` : `pid:${pid}`);
246
- pid = entry.ppid;
247
- }
248
- return keys;
249
- }
250
- function spawnerKey(pid = process.pid, table = readPsTable()) {
251
- const key = lineage(pid, table)[0];
252
- return key?.startsWith(`pid:${pid}:`) ? key : void 0;
253
- }
254
- function psParent(pid) {
255
- const match = /^\s*(\d+)\s+(.+?)\s*$/.exec(capture(["ps", "-o", "ppid=,comm=", "-p", String(pid)], { PATH: process.env.PATH ?? "/usr/bin:/bin" }) ?? "");
256
- return match ? { ppid: Number(match[1]), comm: match[2] } : void 0;
257
- }
258
- function harnessPid(ppid = process.ppid, parentOf = psParent) {
259
- const parent = parentOf(ppid);
260
- if (parent && parent.ppid > 1 && SHELLS.has(basename(parent.comm.replace(/^-/, "")))) return parent.ppid;
261
- return ppid;
262
- }
263
- function hookHarnessPid(env, harness, ppid = process.ppid, parentOf = psParent) {
264
- const named = harness === "claude-code" ? env.CLAUDE_PID : harness === "opencode" ? env.OPENCODE_PID : void 0;
265
- const pid = Number(named);
266
- if (Number.isInteger(pid) && pid > 1) return pid;
267
- return harnessPid(ppid, parentOf);
268
- }
269
- function relayIdentity(input) {
270
- const harness = resolveHarness(input.harness, input.env, input.fallbackHarness);
271
- const cwd = isAbsolute(input.cwd) ? input.cwd : resolve(input.cwd);
272
- const handle = input.as ?? input.env.SCP_NAME ?? deriveHandle(harness, cwd);
273
- const pid = input.harnessPid(harness);
274
- const harnessProcess = processKey(pid, input.startOf);
275
- const keys = input.lineageOf ? input.lineageOf(pid) : lineage(pid);
276
- return {
277
- handle,
278
- harness,
279
- cwd,
280
- session: sessionKey(input.env, harnessProcess),
281
- process: harnessProcess,
282
- labels: labelsFor(input.env),
283
- ...input.env.SCP_PARENT ? { parent: input.env.SCP_PARENT } : {},
284
- ...keys.length ? { lineage: keys } : {},
285
- ...input.env.SCP_GRANT ? { grant: input.env.SCP_GRANT } : {}
286
- };
287
- }
288
-
289
- export {
290
- shortHostname,
291
- detectHarness,
292
- hookHarness,
293
- gitToplevel,
294
- labelsFor,
295
- readPsTable,
296
- harnessLineage,
297
- hiddenHarness,
298
- lineage,
299
- spawnerKey,
300
- psParent,
301
- harnessPid,
302
- hookHarnessPid,
303
- relayIdentity
304
- };
@@ -1,147 +0,0 @@
1
- import {
2
- RelayUsage
3
- } from "./chunk-URSBFDR6.js";
4
- import {
5
- note
6
- } from "./chunk-M2DCR2J4.js";
7
-
8
- // src/relay.ts
9
- import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "fs";
10
- import { join, dirname } from "path";
11
- import { randomUUID } from "crypto";
12
- import { CLI_NAME } from "@scp-dev/core";
13
- var DEFAULT_RELAY = "https://app.scp.dev";
14
- function configDir(env = process.env) {
15
- const base = env.XDG_CONFIG_HOME || (env.HOME ? join(env.HOME, ".config") : void 0);
16
- if (!base) throw new RelayUsage("neither XDG_CONFIG_HOME nor HOME is set, so there is no place for the relay configuration");
17
- return join(base, "scp");
18
- }
19
- function checkRelayUrl(text, what = "relay URL") {
20
- let url;
21
- try {
22
- url = new URL(text);
23
- } catch {
24
- throw new RelayUsage(`${what} must be an absolute https URL (http is allowed only for localhost)`);
25
- }
26
- if (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) || url.username || url.password) {
27
- throw new RelayUsage(`${what} must be an absolute https URL without credentials (http is allowed only for localhost)`);
28
- }
29
- return url.origin;
30
- }
31
- function readObject(path) {
32
- let text;
33
- try {
34
- text = readFileSync(path, "utf8");
35
- } catch (error) {
36
- if (error.code === "ENOENT") return void 0;
37
- throw new RelayUsage(`could not read ${path}`);
38
- }
39
- try {
40
- const value = JSON.parse(text);
41
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error();
42
- return value;
43
- } catch {
44
- throw new RelayUsage(`${path} must contain a JSON object`);
45
- }
46
- }
47
- function writePrivateJson(path, value) {
48
- const dir = dirname(path);
49
- mkdirSync(dir, { recursive: true, mode: 448 });
50
- chmodSync(dir, 448);
51
- const temp = join(dir, `.${randomUUID()}.tmp`);
52
- try {
53
- writeFileSync(temp, `${JSON.stringify(value, null, 2)}
54
- `, { mode: 384, flag: "wx" });
55
- chmodSync(temp, 384);
56
- renameSync(temp, path);
57
- } finally {
58
- rmSync(temp, { force: true });
59
- }
60
- }
61
- function activeRelay(env = process.env) {
62
- if (env.SCP_RELAY !== void 0) return { url: checkRelayUrl(env.SCP_RELAY, "$SCP_RELAY"), source: "SCP_RELAY" };
63
- const path = join(configDir(env), "config.json");
64
- const config = readObject(path);
65
- if (config?.relay !== void 0) {
66
- if (typeof config.relay !== "string") throw new RelayUsage(`relay in ${path} must be a URL`);
67
- return { url: checkRelayUrl(config.relay, `relay in ${path}`), source: "config" };
68
- }
69
- return { url: DEFAULT_RELAY, source: "default" };
70
- }
71
- function readCredentials(env = process.env) {
72
- const path = join(configDir(env), "credentials.json");
73
- const entries = readObject(path) ?? {};
74
- for (const entry of Object.values(entries)) {
75
- if (!entry || typeof entry !== "object" || typeof entry.token !== "string" || !entry.token.trim() || typeof entry.saved_at !== "string") {
76
- throw new RelayUsage(`${path} contains an invalid credential`);
77
- }
78
- }
79
- return entries;
80
- }
81
- function saveCredential(env, origin, credential) {
82
- const url = checkRelayUrl(origin);
83
- writePrivateJson(join(configDir(env), "credentials.json"), { ...readCredentials(env), [url]: { ...credential, saved_at: (/* @__PURE__ */ new Date()).toISOString() } });
84
- }
85
- function removeCredential(env, origin) {
86
- const entries = readCredentials(env);
87
- const url = checkRelayUrl(origin);
88
- if (!Object.hasOwn(entries, url)) return false;
89
- delete entries[url];
90
- writePrivateJson(join(configDir(env), "credentials.json"), entries);
91
- return true;
92
- }
93
- function relayCredential(env, origin) {
94
- const token = env.SCP_TOKEN?.trim();
95
- if (token) return { token, source: "SCP_TOKEN", problem: null };
96
- const stored = readCredentials(env)[checkRelayUrl(origin)];
97
- if (stored) return { token: stored.token, source: "credentials", problem: null };
98
- return { token: null, source: null, problem: `no login for ${origin}: run ${CLI_NAME} login, or set SCP_TOKEN` };
99
- }
100
- function relayVerb(positionals, asJson, env = process.env) {
101
- const [action, text] = positionals;
102
- if (action === "use" && text !== void 0 && positionals.length === 2) {
103
- const url = checkRelayUrl(text);
104
- writePrivateJson(join(configDir(env), "config.json"), { relay: url });
105
- if (asJson) console.log(JSON.stringify({ url }));
106
- else console.log(`saved relay ${url}`);
107
- if (env.SCP_RELAY !== void 0) note("$SCP_RELAY still selects the active relay");
108
- return 0;
109
- }
110
- if (action === "show" && positionals.length === 1) {
111
- const relay = activeRelay(env);
112
- const credential = relayCredential(env, relay.url);
113
- const result = { ...relay, credential: credential.token ? "found" : "missing", credential_source: credential.source };
114
- if (asJson) console.log(JSON.stringify(result));
115
- else console.log(`${relay.url} (${relay.source}); credential ${result.credential}${credential.source ? ` (${credential.source})` : ""}`);
116
- return 0;
117
- }
118
- throw new RelayUsage(`${CLI_NAME} relay takes use <url> or show`);
119
- }
120
- async function loginMain(positionals, values) {
121
- if (positionals.length) throw new RelayUsage(`${CLI_NAME} login takes only flags`);
122
- return (await import("./login-5Y3HPSVC.js")).login(values);
123
- }
124
- function logoutMain(positionals, asJson, env = process.env) {
125
- if (positionals.length) throw new RelayUsage(`${CLI_NAME} logout takes no arguments`);
126
- const { url } = activeRelay(env);
127
- const removed = removeCredential(env, url);
128
- if (asJson) console.log(JSON.stringify({ url, removed, env_token: !!env.SCP_TOKEN?.trim() }));
129
- else console.log(removed ? `logged out of ${url}` : `no stored login for ${url}`);
130
- if (env.SCP_TOKEN?.trim()) note("$SCP_TOKEN still applies");
131
- return 0;
132
- }
133
-
134
- export {
135
- DEFAULT_RELAY,
136
- configDir,
137
- checkRelayUrl,
138
- writePrivateJson,
139
- activeRelay,
140
- readCredentials,
141
- saveCredential,
142
- removeCredential,
143
- relayCredential,
144
- relayVerb,
145
- loginMain,
146
- logoutMain
147
- };