@sublang/spex 4.0.0 → 4.1.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.
package/README.md CHANGED
@@ -10,7 +10,8 @@
10
10
  *The essential spec layer AI agents need to build software reliably.*
11
11
 
12
12
  Scaffolds a `specs/` directory so AI coding agents can read and follow
13
- your project's requirements and design.
13
+ your project's requirements and design. It also attaches to a running local
14
+ Spex server for project, Space sign-in and package operations.
14
15
 
15
16
  ## Install
16
17
 
@@ -24,6 +25,68 @@ Or run once without installing:
24
25
  npx @sublang/spex scaffold
25
26
  ```
26
27
 
28
+ ## Use a running Spex server
29
+
30
+ These commands require Node.js 22 or later and a local Spex App server from
31
+ 0.9.0-beta.18 or later, with attached CLI version 1 support and a matching
32
+ protocol.
33
+ Start the server from a Spex checkout with `npm run start:server`. Copy its
34
+ private access URL into `SPEX_SERVER_URL`, or pass it with `--server` on a
35
+ command. Keep the URL private: it grants access to that server's home.
36
+ The CLI connects only to literal loopback addresses; it starts no server and
37
+ stores no separate credentials or package state.
38
+
39
+ ```sh
40
+ export SPEX_SERVER_URL='<access URL printed by the local server>'
41
+ spex project add /absolute/path/to/project
42
+ cd /absolute/path/to/project
43
+ spex project list
44
+ spex auth login --instance https://spex.sublang.ai
45
+ spex auth status
46
+ spex package search toolkit
47
+ spex package status
48
+ ```
49
+
50
+ Open the displayed sign-in URL and approve with the displayed code when asked.
51
+ The CLI waits for that sign-in's result. Sign-in success does not mean the
52
+ later catalog read or records Sync succeeded.
53
+ Package commands select the registered project at the exact current working
54
+ directory; run from its root, or pass `--project <registered-folder>`.
55
+ An unmatched folder is an error, never an implicit project registration.
56
+
57
+ ```sh
58
+ spex package add my-org/toolkit --version '^1.0.0'
59
+ spex package install
60
+ spex package resolve
61
+ spex package remove my-org/toolkit
62
+ ```
63
+
64
+ `install` uses the existing lock. `resolve` selects versions again and installs.
65
+ For a package you are authoring inside the project, request its relative folder:
66
+
67
+ ```sh
68
+ spex package add my-org/toolkit --path packages/toolkit
69
+ spex package publish packages/toolkit --dry-run
70
+ spex package publish packages/toolkit
71
+ ```
72
+
73
+ `add` requires exactly one of `--version` or `--path`. Core validates package
74
+ folders and performs resolution, installation and native exports.
75
+ Publishing requires the server's Space sign-in and an eligible claimed org.
76
+ The dry run shows the actual destination, identity, version and declared files
77
+ without uploading; a later direct publish performs its own current checks.
78
+ The explicit publish command uploads without an interactive confirmation.
79
+ It reports the server's actual publication receipt.
80
+
81
+ Commands wait for their own terminal result, normally for up to ten minutes.
82
+ Use `--timeout <positive-seconds>` to change that observation limit.
83
+ A rejection exits 1. A lost connection or timeout after dispatch exits 2 with
84
+ an unknown result: the operation may still complete. Inspect its state before
85
+ manually retrying; the CLI never reconnects or resends mutations.
86
+ Ctrl+C exits 130: package work may continue, while sign-in requests cancellation
87
+ of its own attempt where still connected. Neither promises rollback.
88
+ Use `spex --help` for command forms. Scaffold and lint remain usable without a server.
89
+
27
90
  ## Usage
28
91
 
29
92
  ```sh
@@ -0,0 +1,13 @@
1
+ type Flags = Record<string, string | boolean>;
2
+ type Invocation = {
3
+ group: string;
4
+ action: string;
5
+ positional: string[];
6
+ flags: Flags;
7
+ timeoutMs: number;
8
+ };
9
+ export declare const ATTACHED_USAGE = "Attached commands (an already-running local Spex server is required):\n auth login --instance <origin> Sign in through the browser/device instructions\n auth status Show instance sign-in standing\n project list List registered projects\n project add <folder> Register a project working folder\n package search <query> Search the selected project's registry\n package status Show its requests and installed packages\n package add <org/name> --version <requirement>\n package add <org/name> --path <relative-folder>\n package remove <org/name>\n package install Install the locked selections\n package resolve Resolve requests and install\n package publish <relative-folder> [--dry-run]\n\nConnection: --server <access-url> or SPEX_SERVER_URL (literal loopback only).\nObservation: --timeout <positive seconds> (default 600); no reconnect or replay.\nPackages: --project <registered-folder>, otherwise the exact current directory.\nPublishing is explicit; --dry-run checks without uploading.";
10
+ /** Parse the whole invocation before opening a connection or sending a command. */
11
+ export declare function parseAttached(args: string[]): Invocation;
12
+ export declare function runAttached(args: string[], env?: NodeJS.ProcessEnv): Promise<number>;
13
+ export {};
@@ -0,0 +1,247 @@
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 { AttachedClient, accessEndpoint, CliFailure } 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 (an already-running local Spex server is required):
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: --server <access-url> or SPEX_SERVER_URL (literal loopback only).
22
+ Observation: --timeout <positive seconds> (default 600); no reconnect or replay.
23
+ Packages: --project <registered-folder>, otherwise the exact current directory.
24
+ Publishing is explicit; --dry-run checks without uploading.`;
25
+ function usageError(message) { throw new CliFailure(1, message); }
26
+ function relativeFolder(value) {
27
+ if (!value || /[\x00-\x1f\x7f]/.test(value) || isAbsolute(value) || win32.isAbsolute(value) || value.split(/[\\/]/).includes(".."))
28
+ usageError("Package folder must be a relative folder inside the selected project.");
29
+ return value;
30
+ }
31
+ /** Parse the whole invocation before opening a connection or sending a command. */
32
+ export function parseAttached(args) {
33
+ const flags = {};
34
+ const words = [];
35
+ for (let i = 0; i < args.length; i++) {
36
+ const arg = args[i];
37
+ if (!arg.startsWith("-")) {
38
+ words.push(arg);
39
+ continue;
40
+ }
41
+ const match = /^--([a-z-]+)(?:=(.*))?$/.exec(arg);
42
+ const key = match?.[1];
43
+ if (!key || (!VALUES.has(key) && key !== "dry-run"))
44
+ usageError("Unknown option. Use spex --help for supported flags.");
45
+ if (Object.hasOwn(flags, key))
46
+ usageError(`Option --${key} was repeated.`);
47
+ if (key === "dry-run") {
48
+ if (match[2] !== undefined)
49
+ usageError("--dry-run takes no value.");
50
+ flags[key] = true;
51
+ }
52
+ else {
53
+ const value = match[2] ?? args[++i];
54
+ if (!value || value.startsWith("-"))
55
+ usageError(`--${key} requires a value.`);
56
+ flags[key] = value;
57
+ }
58
+ }
59
+ const [group, action, ...positional] = words;
60
+ const allowed = {
61
+ "auth login": ["instance"], "auth status": [], "project list": [], "project add": [],
62
+ "package search": ["project"], "package status": ["project"],
63
+ "package add": ["project", "version", "path"], "package remove": ["project"],
64
+ "package install": ["project"], "package resolve": ["project"], "package publish": ["project", "dry-run"],
65
+ };
66
+ const entry = allowed[`${group} ${action}`];
67
+ if (!entry)
68
+ usageError("Unknown attached command. Use spex --help.");
69
+ for (const key of Object.keys(flags))
70
+ if (!["server", "timeout", ...entry].includes(key))
71
+ usageError(`--${key} is not valid for this command.`);
72
+ const needsArgument = action === "add" || action === "remove" || action === "search" || action === "publish";
73
+ if (positional.length !== (needsArgument ? 1 : 0))
74
+ usageError(needsArgument ? "This command requires exactly one argument." : "This command takes no positional arguments.");
75
+ if (group === "auth" && action === "login") {
76
+ if (typeof flags.instance !== "string")
77
+ usageError("auth login requires --instance <origin>.");
78
+ try {
79
+ const origin = new URL(flags.instance);
80
+ if (!["http:", "https:"].includes(origin.protocol) || origin.username || origin.password || origin.pathname !== "/" || origin.search || flags.instance.includes("#"))
81
+ throw new Error();
82
+ flags.instance = origin.origin;
83
+ }
84
+ catch {
85
+ usageError("--instance must name an HTTP(S) Space origin, without credentials, path, query or fragment.");
86
+ }
87
+ }
88
+ if (group === "package") {
89
+ if (["add", "remove"].includes(action) && !NAME.test(positional[0]))
90
+ usageError("Package name must be org/name using lowercase letters, digits and hyphens.");
91
+ if (action === "search" && positional[0].length > 200)
92
+ usageError("Search query must be at most 200 characters.");
93
+ if (action === "add" && (typeof flags.version === "string") === (typeof flags.path === "string"))
94
+ usageError("package add requires exactly one of --version or --path.");
95
+ if (typeof flags.path === "string")
96
+ relativeFolder(flags.path);
97
+ if (action === "publish")
98
+ relativeFolder(positional[0]);
99
+ }
100
+ let seconds = 600;
101
+ if (flags.timeout !== undefined) {
102
+ if (typeof flags.timeout !== "string" || !/^(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)$/.test(flags.timeout))
103
+ usageError("--timeout must be positive seconds.");
104
+ seconds = Number(flags.timeout);
105
+ if (!Number.isFinite(seconds) || seconds <= 0 || seconds * 1000 > 2_147_483_647)
106
+ usageError("--timeout must be positive seconds within the supported timer range.");
107
+ }
108
+ if (typeof flags.project === "string")
109
+ flags.project = resolve(flags.project);
110
+ if (group === "project" && action === "add")
111
+ positional[0] = resolve(positional[0]);
112
+ return { group: group, action: action, positional, flags, timeoutMs: Math.max(1, Math.ceil(seconds * 1000)) };
113
+ }
114
+ function object(value) { return value !== null && typeof value === "object" && !Array.isArray(value); }
115
+ function malformed() { throw new CliFailure(2, "The server returned an incomplete result. Outcome is unknown; inspect its state before retrying. Nothing was resent."); }
116
+ export async function runAttached(args, env = process.env) {
117
+ if (args.includes("--help") || args.includes("-h")) {
118
+ process.stdout.write(ATTACHED_USAGE + "\n");
119
+ return 0;
120
+ }
121
+ let client;
122
+ let token = "";
123
+ let endpoint = "";
124
+ const clean = (value) => {
125
+ let text = String(value);
126
+ if (endpoint)
127
+ text = text.split(endpoint).join("[server access URL redacted]");
128
+ if (token) {
129
+ text = text.split(token).join("[redacted]").split(encodeURIComponent(token)).join("[redacted]");
130
+ }
131
+ return text;
132
+ };
133
+ const print = (value) => process.stdout.write(clean(value) + "\n");
134
+ const interrupt = () => client?.interrupt();
135
+ try {
136
+ const invocation = parseAttached(args);
137
+ const { group, action, positional, flags } = invocation;
138
+ const access = accessEndpoint(typeof flags.server === "string" ? flags.server : env.SPEX_SERVER_URL);
139
+ token = access.token;
140
+ endpoint = access.url;
141
+ client = new AttachedClient(access.url, invocation.timeoutMs);
142
+ process.on("SIGINT", interrupt);
143
+ await client.connect();
144
+ if (group === "project") {
145
+ const result = await client.command(action === "list" ? "project.list" : "project.register", action === "add" ? { path: positional[0] } : {});
146
+ const projects = action === "list" ? result : [result];
147
+ if (!Array.isArray(projects) || projects.some((p) => !object(p) || typeof p.name !== "string" || typeof p.path !== "string"))
148
+ malformed();
149
+ print(projects.length ? projects.map((p) => `${p.name}\t${p.path}`).join("\n") : "No registered projects.");
150
+ }
151
+ else if (group === "auth") {
152
+ if (action === "status") {
153
+ const result = await client.command("space.get");
154
+ 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")))
155
+ malformed();
156
+ 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>.");
157
+ }
158
+ else {
159
+ const result = await client.signIn(String(flags.instance), (instruction) => {
160
+ if (instruction?.flow === "device" && typeof instruction.verificationUri === "string" && typeof instruction.userCode === "string")
161
+ print(`Open ${instruction.verificationUri}\nEnter code: ${instruction.userCode}\nWaiting for this sign-in to complete…`);
162
+ else if (instruction?.flow === "browser" && typeof instruction.url === "string")
163
+ print(`Open ${instruction.url}\nWaiting for this sign-in to complete…`);
164
+ else
165
+ malformed();
166
+ });
167
+ print(`Signed in as @${result.account.login}. Catalog reading and Sync are separate operations.`);
168
+ }
169
+ }
170
+ else {
171
+ const listed = await client.command("project.list");
172
+ if (!Array.isArray(listed))
173
+ malformed();
174
+ const target = typeof flags.project === "string" ? flags.project : process.cwd();
175
+ const matching = listed.filter((p) => p?.path === target);
176
+ if (matching.length !== 1 || typeof matching[0]?.repository?.key !== "string")
177
+ usageError("No unique registered project matches this folder. Use spex project add <folder>, then run from its root or pass --project <folder>.");
178
+ const project = matching[0];
179
+ const repository = project.repository.key;
180
+ if (action === "search") {
181
+ const result = await client.command("environment.search", { repository, query: positional[0] });
182
+ 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")))
183
+ malformed();
184
+ print(result.packages.length ? result.packages.map((p) => `${p.name}\t${p.versions?.join(", ") ?? ""}\t${p.description ?? ""}`).join("\n") : "No packages found.");
185
+ }
186
+ else if (action === "status") {
187
+ const result = await client.command("environment.get", { repository });
188
+ 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"))
189
+ malformed();
190
+ print(`Project: ${project.name}\nRequests:`);
191
+ for (const [name, request] of Object.entries(result.requests))
192
+ print(` ${name}\t${request.kind}\t${request.version ?? request.path ?? request.repository ?? ""}`);
193
+ print("Packages:");
194
+ for (const p of result.packages)
195
+ print(` ${p.name}\t${p.version ?? "unresolved"}\t${p.installed ? "installed" : "not installed"}`);
196
+ if (result.stale?.length)
197
+ print(`Stale: ${result.stale.join("; ")}`);
198
+ if (result.error)
199
+ print(`Last environment error: ${result.error}`);
200
+ }
201
+ else if (action === "publish") {
202
+ const dryRun = flags["dry-run"] === true;
203
+ const result = await client.command("environment.publish", { repository, path: positional[0], ...(dryRun ? { dryRun: true } : { wait: true }) });
204
+ const receipt = dryRun ? result?.preview : result?.published;
205
+ if ((dryRun ? result?.accepted !== true : result?.completed !== true) || !object(receipt?.instance) || typeof receipt.name !== "string" || typeof receipt.version !== "string" || typeof receipt.instance.origin !== "string")
206
+ malformed();
207
+ if (dryRun ? !Array.isArray(receipt.files) || receipt.files.some((f) => typeof f !== "string" && (!object(f) || typeof f.path !== "string")) : typeof receipt.url !== "string")
208
+ malformed();
209
+ print(`${dryRun ? "Would publish" : "Published"} ${receipt.name}@${receipt.version}\nDestination: ${receipt.instance.name ?? receipt.instance.origin} (${receipt.instance.origin})`);
210
+ if (dryRun) {
211
+ if (!Array.isArray(receipt.files))
212
+ malformed();
213
+ for (const file of receipt.files)
214
+ print(` ${typeof file === "string" ? file : file.path}`);
215
+ }
216
+ else if (typeof receipt.url === "string")
217
+ print(receipt.url);
218
+ }
219
+ else {
220
+ let type = `environment.${action}`;
221
+ const fields = { repository, wait: true };
222
+ if (action === "add") {
223
+ type = "environment.request";
224
+ fields.name = positional[0];
225
+ fields.request = typeof flags.path === "string" ? { kind: "path", path: flags.path } : { kind: "registry", version: flags.version };
226
+ }
227
+ else if (action === "remove")
228
+ fields.name = positional[0];
229
+ const result = await client.command(type, fields);
230
+ if (result?.completed !== true)
231
+ malformed();
232
+ print(`Package ${action} completed for ${project.name}.`);
233
+ }
234
+ }
235
+ return 0;
236
+ }
237
+ catch (error) {
238
+ const failure = error instanceof CliFailure ? error : new CliFailure(1, "Command failed. Check the running server and command arguments.");
239
+ process.stderr.write(clean(failure.message) + "\n");
240
+ return failure.exitCode;
241
+ }
242
+ finally {
243
+ process.off("SIGINT", interrupt);
244
+ client?.close();
245
+ }
246
+ }
247
+ //# sourceMappingURL=attached-cli.js.map
@@ -0,0 +1,36 @@
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
+ /** Validate before opening a socket; WHATWG normalization must not admit
7
+ * numeric aliases, wildcard addresses or DNS names other than localhost. */
8
+ export declare function accessEndpoint(input: string | undefined): {
9
+ url: string;
10
+ token: string;
11
+ };
12
+ /** One invocation, one connection. Core owns validation and operation state. */
13
+ export declare class AttachedClient {
14
+ private readonly endpoint;
15
+ private readonly timeoutMs;
16
+ private socket?;
17
+ private ready?;
18
+ private pending;
19
+ private completion;
20
+ private earlyCompletion;
21
+ private sent;
22
+ private stopped;
23
+ private failure?;
24
+ private timer?;
25
+ signInId?: string;
26
+ constructor(endpoint: string, timeoutMs: number);
27
+ connect(): Promise<void>;
28
+ private observationFailure;
29
+ private message;
30
+ command(type: string, fields?: Message, id?: `${string}-${string}-${string}-${string}-${string}`): Promise<any>;
31
+ signIn(instance: string, instructions: (result: any) => void): Promise<Message>;
32
+ interrupt(): void;
33
+ private fail;
34
+ close(): void;
35
+ }
36
+ export {};
@@ -0,0 +1,189 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ import { randomUUID } from "node:crypto";
4
+ import { PROTOCOL_VERSION, ATTACHED_CLI_VERSION } from "./generated-protocol.js";
5
+ export class CliFailure extends Error {
6
+ exitCode;
7
+ constructor(exitCode, message) {
8
+ super(message);
9
+ this.exitCode = exitCode;
10
+ }
11
+ }
12
+ /** Validate before opening a socket; WHATWG normalization must not admit
13
+ * numeric aliases, wildcard addresses or DNS names other than localhost. */
14
+ export function accessEndpoint(input) {
15
+ const guidance = "Use --server <loopback access-url> or SPEX_SERVER_URL from the running local Spex server.";
16
+ if (!input)
17
+ throw new CliFailure(1, guidance);
18
+ try {
19
+ const rawHost = /^[a-z]+:\/\/(\[[^\]]+\]|[^/:?#]+)(?::[0-9]+)?(?:[/?#]|$)/i.exec(input)?.[1]?.toLowerCase();
20
+ const url = new URL(input);
21
+ if (!rawHost || !["localhost", "127.0.0.1", "[::1]"].includes(rawHost) ||
22
+ !["http:", "https:", "ws:", "wss:"].includes(url.protocol) || url.username || url.password ||
23
+ input.includes("#") || url.pathname !== "/" || [...url.searchParams.keys()].some((k) => k !== "token") ||
24
+ url.searchParams.getAll("token").length !== 1 || !url.searchParams.get("token"))
25
+ throw new Error();
26
+ const token = url.searchParams.get("token");
27
+ url.protocol = url.protocol === "http:" ? "ws:" : url.protocol === "https:" ? "wss:" : url.protocol;
28
+ return { url: url.href, token };
29
+ }
30
+ catch {
31
+ throw new CliFailure(1, `Invalid server access URL. ${guidance}`);
32
+ }
33
+ }
34
+ /** One invocation, one connection. Core owns validation and operation state. */
35
+ export class AttachedClient {
36
+ endpoint;
37
+ timeoutMs;
38
+ socket;
39
+ ready;
40
+ pending = new Map();
41
+ completion = new Map();
42
+ earlyCompletion = new Map();
43
+ sent = false;
44
+ stopped = false;
45
+ failure;
46
+ timer;
47
+ signInId;
48
+ constructor(endpoint, timeoutMs) {
49
+ this.endpoint = endpoint;
50
+ this.timeoutMs = timeoutMs;
51
+ }
52
+ async connect() {
53
+ if (typeof globalThis.WebSocket !== "function")
54
+ throw new CliFailure(1, "This Node.js runtime needs WebSocket support. Use Node.js 22 or later without disabling WebSocket.");
55
+ this.timer = setTimeout(() => this.fail(this.observationFailure("Observation timed out")), this.timeoutMs);
56
+ await new Promise((resolve, reject) => {
57
+ this.ready = { resolve, reject };
58
+ try {
59
+ this.socket = new WebSocket(this.endpoint);
60
+ }
61
+ catch {
62
+ this.fail(new CliFailure(1, "Could not connect. Check the running server and its access URL."));
63
+ return;
64
+ }
65
+ this.socket.addEventListener("message", (event) => this.message(event.data));
66
+ this.socket.addEventListener("error", () => this.fail(this.observationFailure("Connection failed; check the running server and its access URL")));
67
+ this.socket.addEventListener("close", () => {
68
+ if (!this.stopped)
69
+ this.fail(this.observationFailure("Connection closed"));
70
+ });
71
+ });
72
+ }
73
+ observationFailure(reason) {
74
+ return new CliFailure(this.sent ? 2 : 1, this.sent
75
+ ? `${reason}. The result is unknown; the operation may still complete. Inspect its state before retrying; nothing was resent.`
76
+ : `${reason}. No command was sent.`);
77
+ }
78
+ message(data) {
79
+ if (this.stopped)
80
+ return;
81
+ let message;
82
+ try {
83
+ message = JSON.parse(String(data));
84
+ if (!message || typeof message !== "object" || Array.isArray(message))
85
+ throw new Error();
86
+ }
87
+ catch {
88
+ this.fail(this.observationFailure("Invalid server message"));
89
+ return;
90
+ }
91
+ if (this.ready) {
92
+ if (message.type !== "hello" || message.protocolVersion !== PROTOCOL_VERSION || message.attachedCliVersion !== ATTACHED_CLI_VERSION) {
93
+ this.fail(new CliFailure(1, "Incompatible server. Update the CLI and running Spex server together; no command was sent."));
94
+ return;
95
+ }
96
+ const ready = this.ready;
97
+ this.ready = undefined;
98
+ ready.resolve(undefined);
99
+ return;
100
+ }
101
+ if (message.type === "reply" && typeof message.id === "string") {
102
+ const pending = this.pending.get(message.id);
103
+ if (!pending)
104
+ return;
105
+ this.pending.delete(message.id);
106
+ if (message.ok === true && Object.hasOwn(message, "result"))
107
+ pending.resolve(message.result);
108
+ else if (message.ok === false && typeof message.error?.code === "string" && typeof message.error?.message === "string")
109
+ pending.reject(new CliFailure(1, `${message.error.code}: ${message.error.message}${message.error.details ? `\n${JSON.stringify(message.error.details)}` : ""}`));
110
+ else
111
+ pending.reject(this.observationFailure("Invalid terminal reply"));
112
+ }
113
+ else if (message.type === "space.signin.completed" && typeof message.id === "string" && message.id === this.signInId) {
114
+ const pending = this.completion.get(message.id);
115
+ if (pending) {
116
+ this.completion.delete(message.id);
117
+ pending.resolve(message);
118
+ }
119
+ else
120
+ this.earlyCompletion.set(message.id, message);
121
+ }
122
+ // Aggregate state is deliberately ignored: it cannot complete a request.
123
+ }
124
+ command(type, fields = {}, id = randomUUID()) {
125
+ if (this.failure)
126
+ return Promise.reject(this.failure);
127
+ if (!this.socket || this.socket.readyState !== WebSocket.OPEN || this.ready)
128
+ return Promise.reject(this.observationFailure("Server is not connected"));
129
+ return new Promise((resolve, reject) => {
130
+ this.pending.set(id, { resolve, reject });
131
+ try {
132
+ this.socket.send(JSON.stringify({ type, id, ...fields }));
133
+ this.sent = true;
134
+ }
135
+ catch {
136
+ this.fail(this.observationFailure("Could not send command"));
137
+ }
138
+ });
139
+ }
140
+ async signIn(instance, instructions) {
141
+ const id = randomUUID();
142
+ this.signInId = id;
143
+ const result = await this.command("space.signin.start", { url: instance, reportCompletion: true }, id);
144
+ instructions(result);
145
+ if (this.failure)
146
+ throw this.failure;
147
+ const early = this.earlyCompletion.get(id);
148
+ const terminal = early ?? await new Promise((resolve, reject) => this.completion.set(id, { resolve, reject }));
149
+ this.signInId = undefined;
150
+ if (terminal.instance !== instance)
151
+ throw this.observationFailure("Sign-in completion named another instance");
152
+ if (terminal.ok === true && typeof terminal.account?.login === "string")
153
+ return terminal;
154
+ if (terminal.ok === false && typeof terminal.error?.code === "string" && typeof terminal.error?.message === "string")
155
+ throw new CliFailure(1, `${terminal.error.code}: ${terminal.error.message}`);
156
+ throw this.observationFailure("Invalid sign-in completion");
157
+ }
158
+ interrupt() {
159
+ const signingIn = this.signInId;
160
+ if (signingIn && this.socket?.readyState === WebSocket.OPEN) {
161
+ // Ordered before close on the same connection; never cancels another start.
162
+ try {
163
+ this.socket.send(JSON.stringify({ type: "space.signin.cancel", id: randomUUID(), startId: signingIn }));
164
+ }
165
+ catch { /* connection already lost */ }
166
+ }
167
+ this.fail(new CliFailure(130, signingIn
168
+ ? "Interrupted. Requested cancellation of this sign-in where connected; no rollback is promised."
169
+ : "Interrupted observation. Work may still complete; inspect its state before retrying. No rollback is promised."));
170
+ }
171
+ fail(error) {
172
+ if (this.stopped)
173
+ return;
174
+ this.failure = error;
175
+ this.ready?.reject(error);
176
+ this.ready = undefined;
177
+ for (const waiter of [...this.pending.values(), ...this.completion.values()])
178
+ waiter.reject(error);
179
+ this.pending.clear();
180
+ this.completion.clear();
181
+ this.close();
182
+ }
183
+ close() {
184
+ this.stopped = true;
185
+ clearTimeout(this.timer);
186
+ this.socket?.close();
187
+ }
188
+ }
189
+ //# sourceMappingURL=attached-client.js.map
package/dist/cli.js CHANGED
@@ -3,6 +3,7 @@
3
3
  // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
4
4
  import { lint } from "./lint.js";
5
5
  import { scaffold } from "./scaffold.js";
6
+ import { ATTACHED_USAGE, runAttached } from "./attached-cli.js";
6
7
  const USAGE = `Usage: spex <command> [options]
7
8
 
8
9
  Commands:
@@ -13,14 +14,20 @@ Commands:
13
14
  lint [<path>] Check the specs tree structure, item IDs,
14
15
  and citations
15
16
 
16
- Agent names: claude, codex, gemini, kimi, opencode, or all`;
17
- function main() {
17
+ Agent names: claude, codex, gemini, kimi, opencode, or all
18
+
19
+ ${ATTACHED_USAGE}`;
20
+ async function main() {
18
21
  const args = process.argv.slice(2);
19
22
  const command = args[0];
20
23
  if (!command || command === "--help" || command === "-h") {
21
24
  console.log(USAGE);
22
25
  process.exit(0);
23
26
  }
27
+ if (["auth", "project", "package", "--server", "--timeout"].includes(command) || command.startsWith("--server=") || command.startsWith("--timeout=")) {
28
+ process.exitCode = await runAttached(args);
29
+ return;
30
+ }
24
31
  switch (command) {
25
32
  case "scaffold":
26
33
  scaffold(args.slice(1));
@@ -34,5 +41,5 @@ function main() {
34
41
  process.exit(1);
35
42
  }
36
43
  }
37
- main();
44
+ void main();
38
45
  //# sourceMappingURL=cli.js.map
@@ -0,0 +1,2 @@
1
+ export declare const PROTOCOL_VERSION = 28;
2
+ export declare const ATTACHED_CLI_VERSION = 1;
@@ -0,0 +1,6 @@
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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sublang/spex",
3
- "version": "4.0.0",
3
+ "version": "4.1.0",
4
4
  "description": "The essential spec layer AI agents need to build software reliably",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -29,7 +29,7 @@
29
29
  "scaffold/"
30
30
  ],
31
31
  "scripts": {
32
- "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc && node scripts/stage-scaffold.mjs",
32
+ "build": "node scripts/stage-protocol.mjs && node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc && node scripts/stage-scaffold.mjs",
33
33
  "prepublishOnly": "npm run build && npm test",
34
34
  "test": "node scripts/stage-scaffold.mjs && node scripts/run-tests.cjs",
35
35
  "test:integration": "node scripts/stage-scaffold.mjs && node scripts/run-tests.cjs \"\\.integration\\.test\\.js$\""
@@ -49,7 +49,8 @@
49
49
  "sha256-f0690fbe5613097f3d0d1196fec5323a21a6b62bc3875068c38d09c74c5658c4",
50
50
  "sha256-3ea1ba444666c05895c05d7f33056137b5dab8f6cdbdb80eb057a338fdf8eb4b",
51
51
  "sha256-7a08e109f0314e9b3297d2d791b635afb183c0815775690690497a9ac720a95b",
52
- "sha256-0fdea7c594fe52e33c78f30afd2edc3e53414a8ee666a1a4acdaf64ee05487b0"
52
+ "sha256-0fdea7c594fe52e33c78f30afd2edc3e53414a8ee666a1a4acdaf64ee05487b0",
53
+ "sha256-b059af6fb2ddc8ec81628bab0b14d0deb1974b6ec840d5b9cabdfeebcab0f077"
53
54
  ],
54
55
  "specs/intents/000-spdx-headers.md": [
55
56
  "sha256-a5ae7e8e31e4292a9364ba7947b2fbf27836e9f88dc80436557191550fe1bd34",
@@ -68,6 +69,7 @@
68
69
  "sha256-a22cc1cc543e0fa56cc42be4a96383b7866235d7b9bd1c27e2d4bb95e67b5667"
69
70
  ],
70
71
  "i18n/zh/specs/packages/licensing.md": [
71
- "sha256-b8219306bb5f6e33a548430c96301f0fa6b14bad36f3cb5ef72dc5338ea81aba"
72
+ "sha256-b8219306bb5f6e33a548430c96301f0fa6b14bad36f3cb5ef72dc5338ea81aba",
73
+ "sha256-661cc3ffb6651021ca417eec0e6555315fdea4bcae7d880aa694772634c37bed"
72
74
  ]
73
75
  }
@@ -1,6 +1,6 @@
1
1
  <!-- SPDX-License-Identifier: Apache-2.0 -->
2
2
  <!-- SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai> -->
3
- <!-- spex-i18n-source: specs/packages/licensing.md sha256-0fdea7c594fe52e33c78f30afd2edc3e53414a8ee666a1a4acdaf64ee05487b0 -->
3
+ <!-- spex-i18n-source: specs/packages/licensing.md sha256-b059af6fb2ddc8ec81628bab0b14d0deb1974b6ec840d5b9cabdfeebcab0f077 -->
4
4
 
5
5
  # licensing: 许可证头
6
6
 
@@ -72,3 +72,7 @@
72
72
  ### licensing-8
73
73
 
74
74
  给定文件已包含上游 SPDX 行且项目许可证不同,当运行纳入准备流程,验证应断言每条上游行均逐字节保留,且任何缺失的必需行均采用上游数据而非项目许可证数据 [[licensing-5](#licensing-5)]。
75
+
76
+ ### licensing-10
77
+
78
+ 给定项目自编文件需要两种 SPDX 头且不含上游 SPDX 行,当运行仓库纳入准备流程,集成验证应断言这些文件在任何 shebang 之后的第一个注释块使用各文件原生的注释语法,注明项目自己的许可证和版权持有人,采用文件首次纳入项目的年份,且不含未解析的许可证或持有人占位符 [[licensing-9](#licensing-9)]。
@@ -71,3 +71,7 @@ Where the file has comment syntax, is included by the licensing scope [[licensin
71
71
  ### licensing-8
72
72
 
73
73
  Where a file already contains upstream SPDX lines and the project license differs, when inclusion preparation runs, the verification shall assert byte-for-byte preservation of every upstream line and use of upstream rather than project license data for any missing required line [[licensing-5](#licensing-5)].
74
+
75
+ ### licensing-10
76
+
77
+ Where project-authored files require both SPDX headers and carry no upstream SPDX lines, when repository inclusion preparation runs, integration verification shall assert that their first comment block after any shebang uses each file's native comment syntax, names the project's license and copyright holder, uses the year of first inclusion, and contains no unresolved license or holder placeholders [[licensing-9](#licensing-9)].