@scp-dev/cli 0.2.0 → 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-GH7AXFUL.js → chunk-25ZVL5LD.js} +8 -10
  3. package/dist/{chunk-RXKBND3T.js → chunk-HF4KP6AR.js} +229 -13
  4. package/dist/{chunk-5DYFYLAQ.js → chunk-KC5AV5NQ.js} +3 -5
  5. package/dist/{chunk-M2DCR2J4.js → chunk-MNTIEWKF.js} +13 -3
  6. package/dist/{chunk-U2RSSTNW.js → chunk-MXQ7B3CQ.js} +3 -5
  7. package/dist/{chunk-WV5FINTW.js → chunk-NJLFHBSS.js} +20 -10
  8. package/dist/chunk-ZLL5EGI2.js +805 -0
  9. package/dist/{claude-YJLGFQ2P.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-EI7M3YKY.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-V2WT7QX5.js → login-UB72MU7W.js} +4 -7
  17. package/dist/{main-HPBTO3JK.js → main-I4F53MMA.js} +79 -31
  18. package/dist/{mcp-DGAQNFKO.js → mcp-RXAVQBMP.js} +11 -11
  19. package/dist/{peek-WLG3ZROU.js → peek-M2HQVO4O.js} +2 -3
  20. package/dist/{pi-HMESQA64.js → pi-IAVFVOOO.js} +2 -3
  21. package/dist/{relay-5Z7IEXKD.js → relay-QDX2BNZH.js} +6 -4
  22. package/dist/{remote-FYN5ZXE4.js → remote-2OWBWLJH.js} +3 -5
  23. package/dist/{setup-LXG346FJ.js → setup-HPH7HE6O.js} +5 -6
  24. package/dist/{spawn-DLPMAS5M.js → spawn-V66GYUNC.js} +6 -7
  25. package/dist/{up-GPM4LWY3.js → up-2YGEDA5J.js} +6 -9
  26. package/package.json +7 -5
  27. package/dist/chunk-3RRPUYTE.js +0 -147
  28. package/dist/chunk-3V3DRXB2.js +0 -340
  29. package/dist/chunk-E53YHYEP.js +0 -305
  30. package/dist/install-MYHVFKT4.js +0 -15
@@ -1,147 +0,0 @@
1
- import {
2
- RelayUsage
3
- } from "./chunk-3V3DRXB2.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-V2WT7QX5.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
- };
@@ -1,340 +0,0 @@
1
- import {
2
- harnessLineage,
3
- hiddenHarness,
4
- labelsFor,
5
- lineage,
6
- readPsTable
7
- } from "./chunk-E53YHYEP.js";
8
- import {
9
- SELF,
10
- parseSeconds
11
- } from "./chunk-M2DCR2J4.js";
12
-
13
- // src/common.ts
14
- import { spawn } from "child_process";
15
- import { closeSync, openSync, statSync, truncateSync } from "fs";
16
- import { join } from "path";
17
- import { CLI_NAME } from "@scp-dev/core";
18
- import { connectBroker, privateDir, relayDir } from "@scp-dev/broker";
19
- var RelayUsage = class extends Error {
20
- };
21
- var OPTIONS = {
22
- cloud: { type: "boolean" },
23
- machine: { type: "string" },
24
- token: { type: "string" },
25
- label: { type: "string" },
26
- "no-browser": { type: "boolean" },
27
- json: { type: "boolean" },
28
- channels: { type: "boolean" },
29
- write: { type: "boolean" },
30
- print: { type: "boolean" },
31
- "block-stop-on-unread": { type: "boolean" },
32
- "push-wait": { type: "string" },
33
- all: { type: "boolean" },
34
- as: { type: "string" },
35
- harness: { type: "string" },
36
- wait: { type: "string" },
37
- ack: { type: "boolean" },
38
- keep: { type: "boolean" },
39
- "reply-to": { type: "string" },
40
- "require-reply": { type: "boolean" },
41
- thread: { type: "string" },
42
- private: { type: "boolean" },
43
- attach: { type: "string", multiple: true },
44
- tool: { type: "string" },
45
- summary: { type: "string" },
46
- since: { type: "string" },
47
- limit: { type: "string" },
48
- idle: { type: "string" },
49
- policy: { type: "string" },
50
- human: { type: "boolean" },
51
- help: { type: "boolean", short: "h" },
52
- scope: { type: "string" },
53
- tree: { type: "boolean" },
54
- roots: { type: "boolean" },
55
- contacts: { type: "boolean" },
56
- activity: { type: "boolean" },
57
- in: { type: "string" },
58
- out: { type: "string" },
59
- allow: { type: "string", multiple: true },
60
- rules: { type: "string" },
61
- group: { type: "string" },
62
- under: { type: "string" },
63
- ttl: { type: "string" },
64
- labels: { type: "string" },
65
- "handback-bytes": { type: "string" },
66
- "no-push": { type: "boolean" },
67
- bg: { type: "boolean" },
68
- fg: { type: "boolean" },
69
- name: { type: "string" },
70
- title: { type: "string" },
71
- judge: { type: "boolean" },
72
- redacted: { type: "boolean" },
73
- reason: { type: "string" },
74
- turns: { type: "string" },
75
- full: { type: "boolean" },
76
- who: { type: "boolean" },
77
- peek: { type: "string" }
78
- };
79
- var SPAWN_OPTIONS = [
80
- "as",
81
- "harness",
82
- "human",
83
- "name",
84
- "title",
85
- "scope",
86
- "rules",
87
- "in",
88
- "out",
89
- "allow",
90
- "group",
91
- "under",
92
- "ttl",
93
- "labels",
94
- "peek",
95
- "handback-bytes",
96
- "no-push",
97
- "bg",
98
- "fg"
99
- ];
100
- var OBSERVE = /* @__PURE__ */ new Set([
101
- "list",
102
- "status",
103
- "watch",
104
- "log",
105
- "policy",
106
- "machines",
107
- "rules",
108
- "group",
109
- "admin",
110
- "spawn-env",
111
- "spawn",
112
- "why",
113
- "peek",
114
- "set-peek"
115
- ]);
116
- var CLOUD_OBSERVE = /* @__PURE__ */ new Set(["list", "status", "watch", "log", "machines"]);
117
- var GRANT_TOKEN = /^krt_[0-9a-f]{64}$/;
118
- var DAEMON_ENV = [
119
- "PATH",
120
- "LANG",
121
- "LC_ALL",
122
- "LC_CTYPE",
123
- "TZ",
124
- "TMPDIR",
125
- "USER",
126
- "LOGNAME",
127
- "SCP_IDLE",
128
- "HOME",
129
- "XDG_CONFIG_HOME",
130
- "SCP_TOKEN",
131
- "SCP_RELAY",
132
- "SCP_MACHINE"
133
- ];
134
- var LOG_MAX_BYTES = 1024 * 1024;
135
- function startDaemon(dir) {
136
- privateDir(dir);
137
- const logFile = join(dir, "broker.log");
138
- if ((statSync(logFile, { throwIfNoEntry: false })?.size ?? 0) > LOG_MAX_BYTES) truncateSync(logFile, 0);
139
- const log = openSync(logFile, "a", 384);
140
- try {
141
- const env = { SCP_DIR: dir };
142
- for (const key of DAEMON_ENV) if (process.env[key] !== void 0) env[key] = process.env[key];
143
- const child = spawn(SELF[0], [...SELF.slice(1), "daemon"], {
144
- detached: true,
145
- stdio: ["ignore", log, log],
146
- env,
147
- cwd: dir
148
- });
149
- child.unref();
150
- } finally {
151
- closeSync(log);
152
- }
153
- }
154
- function terminalAttached(streams, bodyFromStdin) {
155
- if (streams.stdin.isTTY === true) return true;
156
- return !bodyFromStdin && (streams.stdout.isTTY === true || streams.stderr.isTTY === true);
157
- }
158
- function localHandle(raw) {
159
- const handle = raw.startsWith("me/") ? raw.slice(3) : raw;
160
- if (!handle) throw new RelayUsage("--as me/ names your own human inbox: use --human");
161
- if (handle.includes("/")) throw new RelayUsage(`--as names a local handle, not ${JSON.stringify(raw)}`);
162
- return handle;
163
- }
164
- function walkNow() {
165
- const table = readPsTable();
166
- return { keys: lineage(process.ppid, table), self: harnessLineage(process.ppid, table) };
167
- }
168
- async function open(verb, values, cwd, bodyFromStdin, walk) {
169
- const named = values.as ?? process.env.SCP_NAME;
170
- const tty = terminalAttached(process, bodyFromStdin);
171
- if (named && values.human) throw new RelayUsage("--human and --as (or $SCP_NAME) name two identities; pick one");
172
- const grant = process.env.SCP_GRANT || void 0;
173
- const cloud = values.cloud || process.env.SCP_TRANSPORT === "cloud" || verb === "machines";
174
- if (grant !== void 0) {
175
- if (!GRANT_TOKEN.test(grant)) {
176
- throw new RelayUsage(
177
- `$SCP_GRANT is not one spawn-env grant: pass spawn-env's lines as separate words: env $(${CLI_NAME} spawn-env ...) cmd; in zsh env \${=G} cmd`
178
- );
179
- }
180
- if (values.human) throw new RelayUsage("--human and $SCP_GRANT name two identities: unset the grant to act as me/");
181
- if (cloud) throw new RelayUsage("a spawn-env grant is for this machine's relay broker, not the cloud transport");
182
- }
183
- if (cloud) {
184
- if (!named && !values.human && !tty && !OBSERVE.has(verb)) {
185
- throw new RelayUsage(
186
- `${CLI_NAME} ${verb} needs an identity: --as HANDLE (or $SCP_NAME) for an agent, or --human for your own inbox me/ (no terminal is attached, so me/ is not assumed)`
187
- );
188
- }
189
- const { machineName, openCloud } = await import("./remote-FYN5ZXE4.js");
190
- const handle2 = named ? localHandle(named) : void 0;
191
- const claim = handle2 ? {
192
- handle: handle2,
193
- harness: values.harness ?? process.env.SCP_HARNESS ?? "cli",
194
- cwd,
195
- ...process.env.SCP_PARENT ? { parent: process.env.SCP_PARENT } : {},
196
- labels: labelsFor(process.env, machineName(values.machine))
197
- } : void 0;
198
- const observe = !handle2 && !values.human && CLOUD_OBSERVE.has(verb);
199
- return {
200
- ...await openCloud({
201
- ...values.machine !== void 0 ? { machine: values.machine } : {},
202
- ...handle2 ? { handle: handle2 } : {},
203
- ...claim ? { claim } : {},
204
- tty,
205
- observe
206
- }),
207
- broker: null,
208
- bound: handle2 ? "as" : observe ? null : "human"
209
- };
210
- }
211
- if (values.machine !== void 0) throw new RelayUsage("--machine names the machine of the cloud transport: add --cloud");
212
- const handle = named ? localHandle(named) : void 0;
213
- const { keys, self } = walk ?? walkNow();
214
- const harnessPid = self.length ? Number(/^pid:(\d+)/.exec(self.at(-1))?.[1]) : void 0;
215
- const lineageClaim = keys.length ? { lineage: keys } : {};
216
- const dir = relayDir();
217
- const client = await connectBroker(dir, () => startDaemon(dir));
218
- try {
219
- let bound;
220
- let hello;
221
- if (handle) {
222
- bound = "as";
223
- hello = await client.hello({
224
- claim: {
225
- handle,
226
- exact: true,
227
- harness: values.harness ?? process.env.SCP_HARNESS ?? "cli",
228
- cwd,
229
- ...process.env.SCP_PARENT ? { parent: process.env.SCP_PARENT } : {},
230
- labels: labelsFor(process.env),
231
- ...lineageClaim,
232
- ...grant ? { grant } : {}
233
- },
234
- ...self.length ? { self } : {},
235
- brief: true
236
- });
237
- } else if (grant) {
238
- hello = await client.hello({ observe: true, ...lineageClaim, ...self.length ? { self } : {}, grant, cwd, brief: true });
239
- if (!hello.grant_bound) throw new RelayUsage(`the running ${CLI_NAME} broker does not check spawn-env grants: let it exit (it stops when idle) and retry`);
240
- bound = "lineage";
241
- } else if (values.human || tty) {
242
- hello = await client.hello({ human: true, tty, cwd, brief: true, ...lineageClaim });
243
- bound = hello.endpoint?.kind === "human" ? "human" : "lineage";
244
- } else {
245
- hello = await client.hello({ observe: true, ...lineageClaim, ...self.length ? { self } : {}, cwd, brief: true });
246
- bound = hello.endpoint ? "lineage" : null;
247
- if (!hello.endpoint && !OBSERVE.has(verb)) {
248
- if (hiddenHarness(process.ppid, readPsTable()))
249
- throw new RelayUsage(`${CLI_NAME} ${verb}: sandbox pid namespace: this shell cannot see its harness; use the scp MCP tools`);
250
- throw new RelayUsage(
251
- `${CLI_NAME} ${verb}: no relay agent runs this shell's harness process (${harnessPid ? `pid ${harnessPid}` : "none found"}); pass --as HANDLE or --human (no terminal is attached, so me/ is not assumed)`
252
- );
253
- }
254
- }
255
- return { client, me: hello.endpoint, broker: hello.broker, where: brokerLine(hello.broker), bound, harnessPid };
256
- } catch (error) {
257
- client.close();
258
- throw error;
259
- }
260
- }
261
- function localClient(client, broker, verb) {
262
- if (!broker) throw new RelayUsage(`${CLI_NAME} ${verb} is the local broker's; it has no --cloud form`);
263
- return client;
264
- }
265
- function brokerLine(broker) {
266
- const policy = broker.policy.state === "open" ? `no policy at ${broker.policy.file}, open` : broker.policy.state === "loaded" ? `policy ${broker.policy.file}` : `policy ${broker.policy.file} unusable, sends refused`;
267
- return `broker ${broker.socket} (pid ${broker.pid}); ${policy}`;
268
- }
269
- function selectorList(value) {
270
- if (value === void 0 || typeof value === "boolean") return void 0;
271
- return (Array.isArray(value) ? value : [value]).flatMap((v) => v.split(",")).map((v) => v.trim()).filter(Boolean);
272
- }
273
- var PRESETS = /* @__PURE__ */ new Set(["open", "tree", "parent", "none"]);
274
- function preset(value) {
275
- if (value === void 0) return void 0;
276
- if (typeof value !== "string" || !PRESETS.has(value)) throw new RelayUsage("--scope takes open, tree, parent or none");
277
- return value;
278
- }
279
- function peekGrant(value) {
280
- if (value === void 0) return {};
281
- if (value !== "local") throw new RelayUsage(`--peek takes local (peekable on this machine from its start), not ${JSON.stringify(value)}`);
282
- return { peek: "local" };
283
- }
284
- function grantParams(values) {
285
- const rules = selectorList(values.rules);
286
- if (rules && values.scope !== void 0) throw new RelayUsage("--rules and --scope both set a preset; pick one");
287
- const allow = [...rules ?? [], ...selectorList(values.allow) ?? []];
288
- const scope = rules ? "none" : preset(values.scope);
289
- const groups = selectorList(values.group);
290
- const incoming = selectorList(values.in);
291
- const outgoing = selectorList(values.out);
292
- return {
293
- ...values.name ? { name: values.name } : {},
294
- ...values.title !== void 0 ? { title: values.title } : {},
295
- ...values.under ? { under: values.under } : {},
296
- ...scope ? { scope } : {},
297
- ...incoming ? { in: incoming } : {},
298
- ...outgoing ? { out: outgoing } : {},
299
- ...allow.length ? { allow } : {},
300
- ...groups?.length ? { groups } : {},
301
- ...values.ttl !== void 0 ? { ttl_s: ttlSeconds(values.ttl) } : {},
302
- ...values["no-push"] === true ? { no_push: true } : {},
303
- ...peekGrant(values.peek)
304
- };
305
- }
306
- function ttlSeconds(text) {
307
- try {
308
- return parseSeconds(text, "--ttl");
309
- } catch (error) {
310
- throw new RelayUsage(error instanceof Error ? error.message : String(error));
311
- }
312
- }
313
- var pad = (n) => String(n).padStart(2, "0");
314
- function time(iso) {
315
- const at = new Date(iso);
316
- return Number.isNaN(at.getTime()) ? iso : `${pad(at.getHours())}:${pad(at.getMinutes())}:${pad(at.getSeconds())}`;
317
- }
318
- function stamp(iso) {
319
- const at = new Date(iso);
320
- return Number.isNaN(at.getTime()) ? iso : `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())} ${time(iso)}`;
321
- }
322
- var CHANNELS_ENV = "SCP_CHANNELS";
323
-
324
- export {
325
- RelayUsage,
326
- OPTIONS,
327
- SPAWN_OPTIONS,
328
- startDaemon,
329
- walkNow,
330
- open,
331
- localClient,
332
- brokerLine,
333
- selectorList,
334
- preset,
335
- peekGrant,
336
- grantParams,
337
- time,
338
- stamp,
339
- CHANNELS_ENV
340
- };