@sublang/spex 4.2.0 → 6.0.0

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 (100) hide show
  1. package/README.md +438 -89
  2. package/dist/cli.js +80 -42
  3. package/dist/commands/add.d.ts +12 -0
  4. package/dist/commands/add.js +138 -0
  5. package/dist/commands/auth-target.d.ts +12 -0
  6. package/dist/commands/auth-target.js +52 -0
  7. package/dist/commands/environment.d.ts +117 -0
  8. package/dist/commands/environment.js +399 -0
  9. package/dist/commands/export.d.ts +21 -0
  10. package/dist/commands/export.js +663 -0
  11. package/dist/commands/home.d.ts +56 -0
  12. package/dist/commands/home.js +215 -0
  13. package/dist/commands/install.d.ts +2 -0
  14. package/dist/commands/install.js +48 -0
  15. package/dist/commands/list.d.ts +2 -0
  16. package/dist/commands/list.js +87 -0
  17. package/dist/commands/login.d.ts +2 -0
  18. package/dist/commands/login.js +211 -0
  19. package/dist/commands/logout.d.ts +2 -0
  20. package/dist/commands/logout.js +74 -0
  21. package/dist/commands/publish.d.ts +2 -0
  22. package/dist/commands/publish.js +120 -0
  23. package/dist/commands/remove.d.ts +2 -0
  24. package/dist/commands/remove.js +34 -0
  25. package/dist/commands/run.d.ts +50 -0
  26. package/dist/commands/run.js +312 -0
  27. package/dist/commands/search.d.ts +2 -0
  28. package/dist/commands/search.js +34 -0
  29. package/dist/commands/settle.d.ts +124 -0
  30. package/dist/commands/settle.js +475 -0
  31. package/dist/commands/update.d.ts +2 -0
  32. package/dist/commands/update.js +37 -0
  33. package/dist/commands/whoami.d.ts +2 -0
  34. package/dist/commands/whoami.js +71 -0
  35. package/dist/lib/environment/agent-folders.d.ts +14 -0
  36. package/dist/lib/environment/agent-folders.js +11 -0
  37. package/dist/lib/environment/archive.d.ts +39 -0
  38. package/dist/lib/environment/archive.js +122 -0
  39. package/dist/lib/environment/builtins.d.ts +112 -0
  40. package/dist/lib/environment/builtins.js +539 -0
  41. package/dist/lib/environment/citations.d.ts +75 -0
  42. package/dist/lib/environment/citations.js +267 -0
  43. package/dist/lib/environment/exports.d.ts +190 -0
  44. package/dist/lib/environment/exports.js +1029 -0
  45. package/dist/lib/environment/format.d.ts +133 -0
  46. package/dist/lib/environment/format.js +651 -0
  47. package/dist/lib/environment/git-source.d.ts +41 -0
  48. package/dist/lib/environment/git-source.js +159 -0
  49. package/dist/lib/environment/index.d.ts +20 -0
  50. package/dist/lib/environment/index.js +27 -0
  51. package/dist/lib/environment/install.d.ts +140 -0
  52. package/dist/lib/environment/install.js +694 -0
  53. package/dist/lib/environment/layout.d.ts +15 -0
  54. package/dist/lib/environment/layout.js +50 -0
  55. package/dist/lib/environment/lock.d.ts +87 -0
  56. package/dist/lib/environment/lock.js +305 -0
  57. package/dist/lib/environment/marker.d.ts +15 -0
  58. package/dist/lib/environment/marker.js +31 -0
  59. package/dist/lib/environment/own-paths.d.ts +59 -0
  60. package/dist/lib/environment/own-paths.js +174 -0
  61. package/dist/lib/environment/placed-record.d.ts +32 -0
  62. package/dist/lib/environment/placed-record.js +72 -0
  63. package/dist/lib/environment/registries.d.ts +23 -0
  64. package/dist/lib/environment/registries.js +48 -0
  65. package/dist/lib/environment/registry.d.ts +172 -0
  66. package/dist/lib/environment/registry.js +390 -0
  67. package/dist/lib/environment/requests.d.ts +109 -0
  68. package/dist/lib/environment/requests.js +401 -0
  69. package/dist/lib/environment/resolve.d.ts +70 -0
  70. package/dist/lib/environment/resolve.js +451 -0
  71. package/dist/lib/environment/semver.d.ts +30 -0
  72. package/dist/lib/environment/semver.js +130 -0
  73. package/dist/lib/environment/store.d.ts +23 -0
  74. package/dist/lib/environment/store.js +123 -0
  75. package/dist/lib/environment/tar.d.ts +27 -0
  76. package/dist/lib/environment/tar.js +219 -0
  77. package/dist/lib/files.d.ts +66 -0
  78. package/dist/lib/files.js +233 -0
  79. package/dist/lib/git-host.d.ts +579 -0
  80. package/dist/lib/git-host.js +1363 -0
  81. package/dist/lib/home-file.d.ts +124 -0
  82. package/dist/lib/home-file.js +288 -0
  83. package/dist/lib/instance.d.ts +63 -0
  84. package/dist/lib/instance.js +130 -0
  85. package/dist/lib/words.d.ts +32 -0
  86. package/dist/lib/words.js +27 -0
  87. package/dist/lint.js +8 -0
  88. package/dist/testing/index.d.ts +1 -0
  89. package/dist/testing/index.js +7 -0
  90. package/dist/testing/standin-registry.d.ts +94 -0
  91. package/dist/testing/standin-registry.js +449 -0
  92. package/package.json +37 -3
  93. package/dist/attached-cli.d.ts +0 -13
  94. package/dist/attached-cli.js +0 -249
  95. package/dist/attached-client.d.ts +0 -53
  96. package/dist/attached-client.js +0 -237
  97. package/dist/generated-protocol.d.ts +0 -2
  98. package/dist/generated-protocol.js +0 -6
  99. package/dist/package-init.d.ts +0 -21
  100. package/dist/package-init.js +0 -442
@@ -1,249 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
- import { resolve, isAbsolute, win32 } from "node:path";
4
- import { APP_GUIDANCE, AttachedClient, CliFailure, selectEndpoint } from "./attached-client.js";
5
- const NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:-[a-z0-9]+)*$/;
6
- const VALUES = new Set(["server", "timeout", "project", "instance", "version", "path"]);
7
- export const ATTACHED_USAGE = `Attached commands (need the running Spex app, or a server named below):
8
- auth login --instance <origin> Sign in through the browser/device instructions
9
- auth status Show instance sign-in standing
10
- project list List registered projects
11
- project add <folder> Register a project working folder
12
- package search <query> Search the selected project's registry
13
- package status Show its requests and installed packages
14
- package add <org/name> --version <requirement>
15
- package add <org/name> --path <relative-folder>
16
- package remove <org/name>
17
- package install Install the locked selections
18
- package resolve Resolve requests and install
19
- package publish <relative-folder> [--dry-run]
20
-
21
- Connection: the running Spex app (desktop or server shell) is found through
22
- local/endpoint.json in SPEX_HOME or ~/.spex; --server <access-url> or
23
- SPEX_SERVER_URL names another server instead (literal loopback only).
24
- Observation: --timeout <positive seconds> (default 600); no reconnect or replay.
25
- Packages: --project <registered-folder>, otherwise the exact current directory.
26
- Publishing is explicit; --dry-run checks without uploading.`;
27
- function usageError(message) { throw new CliFailure(1, message); }
28
- function relativeFolder(value) {
29
- if (!value || /[\x00-\x1f\x7f]/.test(value) || isAbsolute(value) || win32.isAbsolute(value) || value.split(/[\\/]/).includes(".."))
30
- usageError("Package folder must be a relative folder inside the selected project.");
31
- return value;
32
- }
33
- /** Parse the whole invocation before opening a connection or sending a command. */
34
- export function parseAttached(args) {
35
- const flags = {};
36
- const words = [];
37
- for (let i = 0; i < args.length; i++) {
38
- const arg = args[i];
39
- if (!arg.startsWith("-")) {
40
- words.push(arg);
41
- continue;
42
- }
43
- const match = /^--([a-z-]+)(?:=(.*))?$/.exec(arg);
44
- const key = match?.[1];
45
- if (!key || (!VALUES.has(key) && key !== "dry-run"))
46
- usageError("Unknown option. Use spex --help for supported flags.");
47
- if (Object.hasOwn(flags, key))
48
- usageError(`Option --${key} was repeated.`);
49
- if (key === "dry-run") {
50
- if (match[2] !== undefined)
51
- usageError("--dry-run takes no value.");
52
- flags[key] = true;
53
- }
54
- else {
55
- const value = match[2] ?? args[++i];
56
- if (!value || value.startsWith("-"))
57
- usageError(`--${key} requires a value.`);
58
- flags[key] = value;
59
- }
60
- }
61
- const [group, action, ...positional] = words;
62
- const allowed = {
63
- "auth login": ["instance"], "auth status": [], "project list": [], "project add": [],
64
- "package search": ["project"], "package status": ["project"],
65
- "package add": ["project", "version", "path"], "package remove": ["project"],
66
- "package install": ["project"], "package resolve": ["project"], "package publish": ["project", "dry-run"],
67
- };
68
- const entry = allowed[`${group} ${action}`];
69
- if (!entry)
70
- usageError("Unknown attached command. Use spex --help.");
71
- for (const key of Object.keys(flags))
72
- if (!["server", "timeout", ...entry].includes(key))
73
- usageError(`--${key} is not valid for this command.`);
74
- const needsArgument = action === "add" || action === "remove" || action === "search" || action === "publish";
75
- if (positional.length !== (needsArgument ? 1 : 0))
76
- usageError(needsArgument ? "This command requires exactly one argument." : "This command takes no positional arguments.");
77
- if (group === "auth" && action === "login") {
78
- if (typeof flags.instance !== "string")
79
- usageError("auth login requires --instance <origin>.");
80
- try {
81
- const origin = new URL(flags.instance);
82
- if (!["http:", "https:"].includes(origin.protocol) || origin.username || origin.password || origin.pathname !== "/" || origin.search || flags.instance.includes("#"))
83
- throw new Error();
84
- flags.instance = origin.origin;
85
- }
86
- catch {
87
- usageError("--instance must name an HTTP(S) Space origin, without credentials, path, query or fragment.");
88
- }
89
- }
90
- if (group === "package") {
91
- if (["add", "remove"].includes(action) && !NAME.test(positional[0]))
92
- usageError("Package name must be org/name using lowercase letters, digits and hyphens.");
93
- if (action === "search" && positional[0].length > 200)
94
- usageError("Search query must be at most 200 characters.");
95
- if (action === "add" && (typeof flags.version === "string") === (typeof flags.path === "string"))
96
- usageError("package add requires exactly one of --version or --path.");
97
- if (typeof flags.path === "string")
98
- relativeFolder(flags.path);
99
- if (action === "publish")
100
- relativeFolder(positional[0]);
101
- }
102
- let seconds = 600;
103
- if (flags.timeout !== undefined) {
104
- if (typeof flags.timeout !== "string" || !/^(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)$/.test(flags.timeout))
105
- usageError("--timeout must be positive seconds.");
106
- seconds = Number(flags.timeout);
107
- if (!Number.isFinite(seconds) || seconds <= 0 || seconds * 1000 > 2_147_483_647)
108
- usageError("--timeout must be positive seconds within the supported timer range.");
109
- }
110
- if (typeof flags.project === "string")
111
- flags.project = resolve(flags.project);
112
- if (group === "project" && action === "add")
113
- positional[0] = resolve(positional[0]);
114
- return { group: group, action: action, positional, flags, timeoutMs: Math.max(1, Math.ceil(seconds * 1000)) };
115
- }
116
- function object(value) { return value !== null && typeof value === "object" && !Array.isArray(value); }
117
- function malformed() { throw new CliFailure(2, "The server returned an incomplete result. Outcome is unknown; inspect its state before retrying. Nothing was resent."); }
118
- export async function runAttached(args, env = process.env) {
119
- if (args.includes("--help") || args.includes("-h")) {
120
- process.stdout.write(ATTACHED_USAGE + "\n");
121
- return 0;
122
- }
123
- let client;
124
- let token = "";
125
- let endpoint = "";
126
- const clean = (value) => {
127
- let text = String(value);
128
- if (endpoint)
129
- text = text.split(endpoint).join("[server access URL redacted]");
130
- if (token) {
131
- text = text.split(token).join("[redacted]").split(encodeURIComponent(token)).join("[redacted]");
132
- }
133
- return text;
134
- };
135
- const print = (value) => process.stdout.write(clean(value) + "\n");
136
- const interrupt = () => client?.interrupt();
137
- try {
138
- const invocation = parseAttached(args);
139
- const { group, action, positional, flags } = invocation;
140
- const access = selectEndpoint(typeof flags.server === "string" ? flags.server : undefined, env);
141
- token = access.token;
142
- endpoint = access.url;
143
- client = new AttachedClient(access.url, invocation.timeoutMs, access.fromApp ? `Could not reach the Spex app at the endpoint it recorded. ${APP_GUIDANCE}` : undefined);
144
- process.on("SIGINT", interrupt);
145
- await client.connect();
146
- if (group === "project") {
147
- const result = await client.command(action === "list" ? "project.list" : "project.register", action === "add" ? { path: positional[0] } : {});
148
- const projects = action === "list" ? result : [result];
149
- if (!Array.isArray(projects) || projects.some((p) => !object(p) || typeof p.name !== "string" || typeof p.path !== "string"))
150
- malformed();
151
- print(projects.length ? projects.map((p) => `${p.name}\t${p.path}`).join("\n") : "No registered projects.");
152
- }
153
- else if (group === "auth") {
154
- if (action === "status") {
155
- const result = await client.command("space.get");
156
- if (!Array.isArray(result?.instances) || result.instances.some((i) => !object(i) || typeof i.origin !== "string" || typeof i.signedIn !== "boolean" || (i.signedIn && typeof i.account?.login !== "string")))
157
- malformed();
158
- print(result.instances.length ? result.instances.map((i) => `${i.displayName ?? i.host ?? i.origin}\t${i.signedIn ? `Signed in${i.account?.login ? ` as @${i.account.login}` : ""}` : "Signed out"}`).join("\n") : "No instances. Sign in with spex auth login --instance <origin>.");
159
- }
160
- else {
161
- const result = await client.signIn(String(flags.instance), (instruction) => {
162
- if (instruction?.flow === "device" && typeof instruction.verificationUri === "string" && typeof instruction.userCode === "string")
163
- print(`Open ${instruction.verificationUri}\nEnter code: ${instruction.userCode}\nWaiting for this sign-in to complete…`);
164
- else if (instruction?.flow === "browser" && typeof instruction.url === "string")
165
- print(`Open ${instruction.url}\nWaiting for this sign-in to complete…`);
166
- else
167
- malformed();
168
- });
169
- print(`Signed in as @${result.account.login}. Catalog reading and Sync are separate operations.`);
170
- }
171
- }
172
- else {
173
- const listed = await client.command("project.list");
174
- if (!Array.isArray(listed))
175
- malformed();
176
- const target = typeof flags.project === "string" ? flags.project : process.cwd();
177
- const matching = listed.filter((p) => p?.path === target);
178
- if (matching.length !== 1 || typeof matching[0]?.repository?.key !== "string")
179
- usageError("No unique registered project matches this folder. Use spex project add <folder>, then run from its root or pass --project <folder>.");
180
- const project = matching[0];
181
- const repository = project.repository.key;
182
- if (action === "search") {
183
- const result = await client.command("environment.search", { repository, query: positional[0] });
184
- if (!Array.isArray(result?.packages) || result.packages.some((p) => !object(p) || typeof p.name !== "string" || !Array.isArray(p.versions) || p.versions.some((v) => typeof v !== "string")))
185
- malformed();
186
- print(result.packages.length ? result.packages.map((p) => `${p.name}\t${p.versions?.join(", ") ?? ""}\t${p.description ?? ""}`).join("\n") : "No packages found.");
187
- }
188
- else if (action === "status") {
189
- const result = await client.command("environment.get", { repository });
190
- if (!object(result?.requests) || Object.values(result.requests).some((r) => !object(r) || typeof r.kind !== "string") || !Array.isArray(result?.packages) || result.packages.some((p) => !object(p) || typeof p.name !== "string" || typeof p.installed !== "boolean"))
191
- malformed();
192
- print(`Project: ${project.name}\nRequests:`);
193
- for (const [name, request] of Object.entries(result.requests))
194
- print(` ${name}\t${request.kind}\t${request.version ?? request.path ?? request.repository ?? ""}`);
195
- print("Packages:");
196
- for (const p of result.packages)
197
- print(` ${p.name}\t${p.version ?? "unresolved"}\t${p.installed ? "installed" : "not installed"}`);
198
- if (result.stale?.length)
199
- print(`Stale: ${result.stale.join("; ")}`);
200
- if (result.error)
201
- print(`Last environment error: ${result.error}`);
202
- }
203
- else if (action === "publish") {
204
- const dryRun = flags["dry-run"] === true;
205
- const result = await client.command("environment.publish", { repository, path: positional[0], ...(dryRun ? { dryRun: true } : { wait: true }) });
206
- const receipt = dryRun ? result?.preview : result?.published;
207
- if ((dryRun ? result?.accepted !== true : result?.completed !== true) || !object(receipt?.instance) || typeof receipt.name !== "string" || typeof receipt.version !== "string" || typeof receipt.instance.origin !== "string")
208
- malformed();
209
- if (dryRun ? !Array.isArray(receipt.files) || receipt.files.some((f) => typeof f !== "string" && (!object(f) || typeof f.path !== "string")) : typeof receipt.url !== "string")
210
- malformed();
211
- print(`${dryRun ? "Would publish" : "Published"} ${receipt.name}@${receipt.version}\nDestination: ${receipt.instance.name ?? receipt.instance.origin} (${receipt.instance.origin})`);
212
- if (dryRun) {
213
- if (!Array.isArray(receipt.files))
214
- malformed();
215
- for (const file of receipt.files)
216
- print(` ${typeof file === "string" ? file : file.path}`);
217
- }
218
- else if (typeof receipt.url === "string")
219
- print(receipt.url);
220
- }
221
- else {
222
- let type = `environment.${action}`;
223
- const fields = { repository, wait: true };
224
- if (action === "add") {
225
- type = "environment.request";
226
- fields.name = positional[0];
227
- fields.request = typeof flags.path === "string" ? { kind: "path", path: flags.path } : { kind: "registry", version: flags.version };
228
- }
229
- else if (action === "remove")
230
- fields.name = positional[0];
231
- const result = await client.command(type, fields);
232
- if (result?.completed !== true)
233
- malformed();
234
- print(`Package ${action} completed for ${project.name}.`);
235
- }
236
- }
237
- return 0;
238
- }
239
- catch (error) {
240
- const failure = error instanceof CliFailure ? error : new CliFailure(1, "Command failed. Check the running server and command arguments.");
241
- process.stderr.write(clean(failure.message) + "\n");
242
- return failure.exitCode;
243
- }
244
- finally {
245
- process.off("SIGINT", interrupt);
246
- client?.close();
247
- }
248
- }
249
- //# sourceMappingURL=attached-cli.js.map
@@ -1,53 +0,0 @@
1
- export declare class CliFailure extends Error {
2
- readonly exitCode: number;
3
- constructor(exitCode: number, message: string);
4
- }
5
- type Message = Record<string, any>;
6
- /** What a failure to find or reach the running app tells the reader. */
7
- export declare const APP_GUIDANCE = "The Spex app must be running on this computer: start it, then run this again. To use another server, pass --server <access-url> or set SPEX_SERVER_URL.";
8
- /** The access URL an invocation connects to: `--server`, else
9
- * `SPEX_SERVER_URL`, else the URL the running app keeps in the home's
10
- * `local/endpoint.json` (attached-cli-1, DR-163). Each is held to the
11
- * same loopback rule before any socket opens; the file's URL is never
12
- * repeated in a failure. */
13
- export declare function selectEndpoint(server: string | undefined, env: NodeJS.ProcessEnv): {
14
- url: string;
15
- token: string;
16
- fromApp: boolean;
17
- };
18
- /** Validate before opening a socket; WHATWG normalization must not admit
19
- * numeric aliases, wildcard addresses or DNS names other than localhost. */
20
- export declare function accessEndpoint(input: string | undefined): {
21
- url: string;
22
- token: string;
23
- };
24
- /** One invocation, one connection. Core owns validation and operation state. */
25
- export declare class AttachedClient {
26
- private readonly endpoint;
27
- private readonly timeoutMs;
28
- private readonly unreachable?;
29
- private socket?;
30
- private ready?;
31
- private pending;
32
- private completion;
33
- private earlyCompletion;
34
- private sent;
35
- private opened;
36
- private stopped;
37
- private failure?;
38
- private timer?;
39
- signInId?: string;
40
- /** `unreachable` replaces the failure of a connection that never
41
- * opened: for the running app's own endpoint, that the app must be
42
- * running (attached-cli-1). */
43
- constructor(endpoint: string, timeoutMs: number, unreachable?: string | undefined);
44
- connect(): Promise<void>;
45
- private observationFailure;
46
- private message;
47
- command(type: string, fields?: Message, id?: `${string}-${string}-${string}-${string}-${string}`): Promise<any>;
48
- signIn(instance: string, instructions: (result: any) => void): Promise<Message>;
49
- interrupt(): void;
50
- private fail;
51
- close(): void;
52
- }
53
- export {};
@@ -1,237 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
- import { randomUUID } from "node:crypto";
4
- import { readFileSync } from "node:fs";
5
- import { homedir } from "node:os";
6
- import { join } from "node:path";
7
- import { PROTOCOL_VERSION, ATTACHED_CLI_VERSION } from "./generated-protocol.js";
8
- export class CliFailure extends Error {
9
- exitCode;
10
- constructor(exitCode, message) {
11
- super(message);
12
- this.exitCode = exitCode;
13
- }
14
- }
15
- /** What a failure to find or reach the running app tells the reader. */
16
- export const APP_GUIDANCE = "The Spex app must be running on this computer: start it, then run this again. To use another server, pass --server <access-url> or set SPEX_SERVER_URL.";
17
- const EXPLICIT_GUIDANCE = "Use --server <loopback access-url> or SPEX_SERVER_URL from a running Spex server.";
18
- /** The access URL an invocation connects to: `--server`, else
19
- * `SPEX_SERVER_URL`, else the URL the running app keeps in the home's
20
- * `local/endpoint.json` (attached-cli-1, DR-163). Each is held to the
21
- * same loopback rule before any socket opens; the file's URL is never
22
- * repeated in a failure. */
23
- export function selectEndpoint(server, env) {
24
- if (server !== undefined)
25
- return { ...accessEndpoint(server), fromApp: false };
26
- const named = env.SPEX_SERVER_URL;
27
- if (named !== undefined && named !== "")
28
- return { ...accessEndpoint(named), fromApp: false };
29
- return { ...appEndpoint(env), fromApp: true };
30
- }
31
- /** The running app's endpoint file under the home `SPEX_HOME` names,
32
- * else `~/.spex`, read as `{format: 1, url, pid}` (core-service-143). */
33
- function appEndpoint(env) {
34
- const home = env.SPEX_HOME?.trim() ? env.SPEX_HOME : join(homedir(), ".spex");
35
- let doc;
36
- try {
37
- doc = JSON.parse(readFileSync(join(home, "local", "endpoint.json"), "utf8"));
38
- }
39
- catch {
40
- throw new CliFailure(1, `No running Spex app was found. ${APP_GUIDANCE}`);
41
- }
42
- const file = doc;
43
- if (!file || typeof file !== "object" || Array.isArray(file) || file.format !== 1 || typeof file.url !== "string" ||
44
- typeof file.pid !== "number" || !Number.isSafeInteger(file.pid) || file.pid <= 0)
45
- throw new CliFailure(1, `The running Spex app's endpoint file is not one this CLI reads. ${APP_GUIDANCE}`);
46
- try {
47
- return accessEndpoint(file.url);
48
- }
49
- catch {
50
- throw new CliFailure(1, `The running Spex app's endpoint file names no loopback access URL, so it was not used. ${APP_GUIDANCE}`);
51
- }
52
- }
53
- /** Validate before opening a socket; WHATWG normalization must not admit
54
- * numeric aliases, wildcard addresses or DNS names other than localhost. */
55
- export function accessEndpoint(input) {
56
- if (!input)
57
- throw new CliFailure(1, EXPLICIT_GUIDANCE);
58
- try {
59
- const rawHost = /^[a-z]+:\/\/(\[[^\]]+\]|[^/:?#]+)(?::[0-9]+)?(?:[/?#]|$)/i.exec(input)?.[1]?.toLowerCase();
60
- const url = new URL(input);
61
- if (!rawHost || !["localhost", "127.0.0.1", "[::1]"].includes(rawHost) ||
62
- !["http:", "https:", "ws:", "wss:"].includes(url.protocol) || url.username || url.password ||
63
- input.includes("#") || url.pathname !== "/" || [...url.searchParams.keys()].some((k) => k !== "token") ||
64
- url.searchParams.getAll("token").length !== 1 || !url.searchParams.get("token"))
65
- throw new Error();
66
- const token = url.searchParams.get("token");
67
- url.protocol = url.protocol === "http:" ? "ws:" : url.protocol === "https:" ? "wss:" : url.protocol;
68
- return { url: url.href, token };
69
- }
70
- catch {
71
- throw new CliFailure(1, `Invalid server access URL. ${EXPLICIT_GUIDANCE}`);
72
- }
73
- }
74
- /** One invocation, one connection. Core owns validation and operation state. */
75
- export class AttachedClient {
76
- endpoint;
77
- timeoutMs;
78
- unreachable;
79
- socket;
80
- ready;
81
- pending = new Map();
82
- completion = new Map();
83
- earlyCompletion = new Map();
84
- sent = false;
85
- opened = false;
86
- stopped = false;
87
- failure;
88
- timer;
89
- signInId;
90
- /** `unreachable` replaces the failure of a connection that never
91
- * opened: for the running app's own endpoint, that the app must be
92
- * running (attached-cli-1). */
93
- constructor(endpoint, timeoutMs, unreachable) {
94
- this.endpoint = endpoint;
95
- this.timeoutMs = timeoutMs;
96
- this.unreachable = unreachable;
97
- }
98
- async connect() {
99
- if (typeof globalThis.WebSocket !== "function")
100
- throw new CliFailure(1, "This Node.js runtime needs WebSocket support. Use Node.js 22 or later without disabling WebSocket.");
101
- this.timer = setTimeout(() => this.fail(this.observationFailure("Observation timed out")), this.timeoutMs);
102
- await new Promise((resolve, reject) => {
103
- this.ready = { resolve, reject };
104
- const lost = (reason) => this.fail(!this.opened && this.unreachable ? new CliFailure(1, this.unreachable) : this.observationFailure(reason));
105
- try {
106
- this.socket = new WebSocket(this.endpoint);
107
- }
108
- catch {
109
- this.fail(new CliFailure(1, this.unreachable ?? "Could not connect. Check the running server and its access URL."));
110
- return;
111
- }
112
- this.socket.addEventListener("open", () => { this.opened = true; });
113
- this.socket.addEventListener("message", (event) => this.message(event.data));
114
- this.socket.addEventListener("error", () => lost("Connection failed; check the running server and its access URL"));
115
- this.socket.addEventListener("close", () => {
116
- if (!this.stopped)
117
- lost("Connection closed");
118
- });
119
- });
120
- }
121
- observationFailure(reason) {
122
- return new CliFailure(this.sent ? 2 : 1, this.sent
123
- ? `${reason}. The result is unknown; the operation may still complete. Inspect its state before retrying; nothing was resent.`
124
- : `${reason}. No command was sent.`);
125
- }
126
- message(data) {
127
- if (this.stopped)
128
- return;
129
- let message;
130
- try {
131
- message = JSON.parse(String(data));
132
- if (!message || typeof message !== "object" || Array.isArray(message))
133
- throw new Error();
134
- }
135
- catch {
136
- this.fail(this.observationFailure("Invalid server message"));
137
- return;
138
- }
139
- if (this.ready) {
140
- if (message.type !== "hello" || message.protocolVersion !== PROTOCOL_VERSION || message.attachedCliVersion !== ATTACHED_CLI_VERSION) {
141
- this.fail(new CliFailure(1, "Incompatible server. Update the CLI and running Spex server together; no command was sent."));
142
- return;
143
- }
144
- const ready = this.ready;
145
- this.ready = undefined;
146
- ready.resolve(undefined);
147
- return;
148
- }
149
- if (message.type === "reply" && typeof message.id === "string") {
150
- const pending = this.pending.get(message.id);
151
- if (!pending)
152
- return;
153
- this.pending.delete(message.id);
154
- if (message.ok === true && Object.hasOwn(message, "result"))
155
- pending.resolve(message.result);
156
- else if (message.ok === false && typeof message.error?.code === "string" && typeof message.error?.message === "string")
157
- pending.reject(new CliFailure(1, `${message.error.code}: ${message.error.message}${message.error.details ? `\n${JSON.stringify(message.error.details)}` : ""}`));
158
- else
159
- pending.reject(this.observationFailure("Invalid terminal reply"));
160
- }
161
- else if (message.type === "space.signin.completed" && typeof message.id === "string" && message.id === this.signInId) {
162
- const pending = this.completion.get(message.id);
163
- if (pending) {
164
- this.completion.delete(message.id);
165
- pending.resolve(message);
166
- }
167
- else
168
- this.earlyCompletion.set(message.id, message);
169
- }
170
- // Aggregate state is deliberately ignored: it cannot complete a request.
171
- }
172
- command(type, fields = {}, id = randomUUID()) {
173
- if (this.failure)
174
- return Promise.reject(this.failure);
175
- if (!this.socket || this.socket.readyState !== WebSocket.OPEN || this.ready)
176
- return Promise.reject(this.observationFailure("Server is not connected"));
177
- return new Promise((resolve, reject) => {
178
- this.pending.set(id, { resolve, reject });
179
- try {
180
- this.socket.send(JSON.stringify({ type, id, ...fields }));
181
- this.sent = true;
182
- }
183
- catch {
184
- this.fail(this.observationFailure("Could not send command"));
185
- }
186
- });
187
- }
188
- async signIn(instance, instructions) {
189
- const id = randomUUID();
190
- this.signInId = id;
191
- const result = await this.command("space.signin.start", { url: instance, reportCompletion: true }, id);
192
- instructions(result);
193
- if (this.failure)
194
- throw this.failure;
195
- const early = this.earlyCompletion.get(id);
196
- const terminal = early ?? await new Promise((resolve, reject) => this.completion.set(id, { resolve, reject }));
197
- this.signInId = undefined;
198
- if (terminal.instance !== instance)
199
- throw this.observationFailure("Sign-in completion named another instance");
200
- if (terminal.ok === true && typeof terminal.account?.login === "string")
201
- return terminal;
202
- if (terminal.ok === false && typeof terminal.error?.code === "string" && typeof terminal.error?.message === "string")
203
- throw new CliFailure(1, `${terminal.error.code}: ${terminal.error.message}`);
204
- throw this.observationFailure("Invalid sign-in completion");
205
- }
206
- interrupt() {
207
- const signingIn = this.signInId;
208
- if (signingIn && this.socket?.readyState === WebSocket.OPEN) {
209
- // Ordered before close on the same connection; never cancels another start.
210
- try {
211
- this.socket.send(JSON.stringify({ type: "space.signin.cancel", id: randomUUID(), startId: signingIn }));
212
- }
213
- catch { /* connection already lost */ }
214
- }
215
- this.fail(new CliFailure(130, signingIn
216
- ? "Interrupted. Requested cancellation of this sign-in where connected; no rollback is promised."
217
- : "Interrupted observation. Work may still complete; inspect its state before retrying. No rollback is promised."));
218
- }
219
- fail(error) {
220
- if (this.stopped)
221
- return;
222
- this.failure = error;
223
- this.ready?.reject(error);
224
- this.ready = undefined;
225
- for (const waiter of [...this.pending.values(), ...this.completion.values()])
226
- waiter.reject(error);
227
- this.pending.clear();
228
- this.completion.clear();
229
- this.close();
230
- }
231
- close() {
232
- this.stopped = true;
233
- clearTimeout(this.timer);
234
- this.socket?.close();
235
- }
236
- }
237
- //# sourceMappingURL=attached-client.js.map
@@ -1,2 +0,0 @@
1
- export declare const PROTOCOL_VERSION = 28;
2
- export declare const ATTACHED_CLI_VERSION = 1;
@@ -1,6 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
- // Generated from core/src/protocol.ts; do not edit.
4
- export const PROTOCOL_VERSION = 28;
5
- export const ATTACHED_CLI_VERSION = 1;
6
- //# sourceMappingURL=generated-protocol.js.map
@@ -1,21 +0,0 @@
1
- export declare const PACKAGE_INIT_USAGE = "Usage: spex package init <org>/<name> [--skill <folder>]... [--spec <file>]\n [--language <tag>] [--description <text>]\n [--license <id>] [--move]\n\nMake spex-packages/<name>/ in the current directory from skill folders\nand/or a spec file, with no server:\n --skill <folder> An Agent Skills folder holding SKILL.md; repeatable\n --spec <file> The spec file, named <name>.md\n --language <tag> The artifacts' language (default en)\n --description <text> Default: the first skill's description, else the\n first paragraph under the spec's Intent heading\n --license <id> Default: read from ./LICENSE, else Apache-2.0\n --move Move the skill folders instead of copying them";
2
- interface Frontmatter {
3
- name?: string;
4
- description?: string;
5
- /** The field whose unquoted value YAML refuses (`: ` inside it). */
6
- unreadable?: "name" | "description";
7
- }
8
- /** The top-level string fields of a SKILL.md's YAML frontmatter that
9
- * matter here — `name` and `description` — read from the common YAML
10
- * forms: plain, single- or double-quoted, and `|` or `>` blocks. A field
11
- * of another form reads as absent. The frontmatter is found as a
12
- * release's readers find it, from the text's first character: nothing
13
- * before `---`, a byte order mark included, is skipped. */
14
- export declare function skillFrontmatter(text: string): Frontmatter;
15
- /** The first paragraph under a spec's Intent heading, its lines joined. */
16
- export declare function intentParagraph(text: string): string | undefined;
17
- /** The license a project's root LICENSE names (attached-cli-12). */
18
- export declare function detectLicense(text: string | undefined): string;
19
- /** Make the package folder (attached-cli-12); the exit code. */
20
- export declare function packageInit(args: string[], cwd?: string): number;
21
- export {};