@sublang/spex 4.0.1 → 4.2.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,9 @@
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 makes a spec package folder from
14
+ a skill or a spec you already have, and attaches to the running Spex app for
15
+ project, Space sign-in and package operations.
14
16
 
15
17
  ## Install
16
18
 
@@ -24,6 +26,107 @@ Or run once without installing:
24
26
  npx @sublang/spex scaffold
25
27
  ```
26
28
 
29
+ ## Make a package folder
30
+
31
+ `spex package init` turns a skill folder or a spec file you already have into
32
+ a spec package folder ready to add and publish. It needs no running app.
33
+ From your project's root:
34
+
35
+ ```sh
36
+ spex package init my-org/my-skill --skill .claude/skills/my-skill --move
37
+ spex package init my-org/my-spec --spec specs/packages/my-spec.md
38
+ ```
39
+
40
+ It writes `spex-packages/<name>/` holding `meta.yaml` (format 2, version
41
+ `0.1.0`), a `README.md`, the project's `LICENSE` where there is one, each
42
+ `--skill` folder under `skills/<language>/<id>/` — `<id>` being the `name`
43
+ its `SKILL.md` declares — and the `--spec` file under
44
+ `specs/<language>/<name>.md`. Give `--skill` once per skill; a package holds
45
+ at most one spec, whose file must be named `<name>.md`.
46
+ `--move` moves the skill folders instead of copying them: once the package is
47
+ added, Spex exports the skills back to your agents.
48
+
49
+ | Option | Default |
50
+ | --- | --- |
51
+ | `--language <tag>` | `en` |
52
+ | `--description <text>` | the first skill's `SKILL.md` description, else the first paragraph under the spec's Intent heading |
53
+ | `--license <id>` | `MIT` where `./LICENSE` begins with "MIT License", else `Apache-2.0` |
54
+
55
+ Every rule is checked before anything is written; a refusal writes nothing
56
+ and names the rule. It ends with the next steps: in the app, **Playbooks →
57
+ Add from folder** with the name and `spex-packages/<name>`, then **Publish**
58
+ on its row; or with the CLI, as below,
59
+ `spex package add <org>/<name> --path spex-packages/<name>` and
60
+ `spex package publish spex-packages/<name> --dry-run`.
61
+
62
+ ## Use the running Spex app
63
+
64
+ These commands require Node.js 22 or later and the Spex app from
65
+ 0.9.0-beta.18 or later — the desktop app or the server shell — with attached
66
+ CLI version 1 support and a matching protocol.
67
+ Keep the app running on this computer: the CLI finds it through the
68
+ `local/endpoint.json` file the app keeps in its home, `SPEX_HOME` or
69
+ `~/.spex`, while it serves on a loopback address. Pass
70
+ `--server <access-url>` or set `SPEX_SERVER_URL` only to use another
71
+ server; either wins over the file. App 0.9.0-beta.18 keeps no such file and
72
+ needs that URL, which its server shell started with `npm run start:server`
73
+ prints. Keep the URL private: it grants access to that server's home.
74
+ The CLI connects only to literal loopback addresses; it starts no server and
75
+ stores no separate credentials or package state. Without a running app it
76
+ says so and exits 1.
77
+
78
+ ```sh
79
+ spex project add /absolute/path/to/project
80
+ cd /absolute/path/to/project
81
+ spex project list
82
+ spex auth login --instance https://spex.sublang.ai
83
+ spex auth status
84
+ spex package search toolkit
85
+ spex package status
86
+ ```
87
+
88
+ Open the displayed sign-in URL and approve with the displayed code when asked.
89
+ The CLI waits for that sign-in's result. Sign-in success does not mean the
90
+ later catalog read or records Sync succeeded.
91
+ Package commands select the registered project at the exact current working
92
+ directory; run from its root, or pass `--project <registered-folder>`.
93
+ An unmatched folder is an error, never an implicit project registration.
94
+
95
+ ```sh
96
+ spex package add my-org/toolkit --version '^1.0.0'
97
+ spex package install
98
+ spex package resolve
99
+ spex package remove my-org/toolkit
100
+ ```
101
+
102
+ `install` uses the existing lock. `resolve` selects versions again and installs.
103
+ For a package you are authoring inside the project, such as one
104
+ `spex package init` made, request its relative folder:
105
+
106
+ ```sh
107
+ spex package add my-org/toolkit --path spex-packages/toolkit
108
+ spex package publish spex-packages/toolkit --dry-run
109
+ spex package publish spex-packages/toolkit
110
+ ```
111
+
112
+ `add` requires exactly one of `--version` or `--path`. Core validates package
113
+ folders and performs resolution, installation and native exports.
114
+ Publishing requires the server's Space sign-in and an eligible claimed org.
115
+ The dry run shows the actual destination, identity, version and declared files
116
+ without uploading; a later direct publish performs its own current checks.
117
+ The explicit publish command uploads without an interactive confirmation.
118
+ It reports the server's actual publication receipt.
119
+
120
+ Commands wait for their own terminal result, normally for up to ten minutes.
121
+ Use `--timeout <positive-seconds>` to change that observation limit.
122
+ A rejection exits 1. A lost connection or timeout after dispatch exits 2 with
123
+ an unknown result: the operation may still complete. Inspect its state before
124
+ manually retrying; the CLI never reconnects or resends mutations.
125
+ Ctrl+C exits 130: package work may continue, while sign-in requests cancellation
126
+ of its own attempt where still connected. Neither promises rollback.
127
+ Use `spex --help` for command forms. Scaffold, lint and `package init` remain
128
+ usable without a server.
129
+
27
130
  ## Usage
28
131
 
29
132
  ```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 (need the running Spex app, or a server named below):\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: the running Spex app (desktop or server shell) is found through\n local/endpoint.json in SPEX_HOME or ~/.spex; --server <access-url> or\n SPEX_SERVER_URL names another server instead (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,249 @@
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
@@ -0,0 +1,53 @@
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 {};
@@ -0,0 +1,237 @@
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
package/dist/cli.js CHANGED
@@ -3,6 +3,8 @@
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";
7
+ import { packageInit } from "./package-init.js";
6
8
  const USAGE = `Usage: spex <command> [options]
7
9
 
8
10
  Commands:
@@ -12,15 +14,32 @@ Commands:
12
14
  Refresh scaffold-provided specs templates
13
15
  lint [<path>] Check the specs tree structure, item IDs,
14
16
  and citations
17
+ package init <org>/<name> [--skill <folder>]... [--spec <file>]
18
+ [--language <tag>] [--description <text>] [--license <id>]
19
+ [--move]
20
+ Make spex-packages/<name>/ from skill
21
+ folders and/or a spec file; no server
15
22
 
16
- Agent names: claude, codex, gemini, kimi, opencode, or all`;
17
- function main() {
23
+ Agent names: claude, codex, gemini, kimi, opencode, or all
24
+
25
+ ${ATTACHED_USAGE}`;
26
+ async function main() {
18
27
  const args = process.argv.slice(2);
19
28
  const command = args[0];
20
29
  if (!command || command === "--help" || command === "-h") {
21
30
  console.log(USAGE);
22
31
  process.exit(0);
23
32
  }
33
+ // Made from files at hand, before any attached routing: it never
34
+ // opens a connection (attached-cli-12).
35
+ if (command === "package" && args[1] === "init") {
36
+ process.exitCode = packageInit(args.slice(2));
37
+ return;
38
+ }
39
+ if (["auth", "project", "package", "--server", "--timeout"].includes(command) || command.startsWith("--server=") || command.startsWith("--timeout=")) {
40
+ process.exitCode = await runAttached(args);
41
+ return;
42
+ }
24
43
  switch (command) {
25
44
  case "scaffold":
26
45
  scaffold(args.slice(1));
@@ -34,5 +53,5 @@ function main() {
34
53
  process.exit(1);
35
54
  }
36
55
  }
37
- main();
56
+ void main();
38
57
  //# 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
@@ -0,0 +1,21 @@
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 {};
@@ -0,0 +1,442 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ // `spex package init` (attached-cli-12, DR-162): a spec package folder
4
+ // made from a skill folder or a spec file already at hand, in the
5
+ // release layout the core reads, with no server and no Spex storage.
6
+ // Every rule is checked before anything is written; a refusal writes
7
+ // nothing.
8
+ import { chmodSync, copyFileSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, writeFileSync, } from "node:fs";
9
+ import { randomBytes } from "node:crypto";
10
+ import { basename, isAbsolute, join, relative, resolve, sep } from "node:path";
11
+ export const PACKAGE_INIT_USAGE = `Usage: spex package init <org>/<name> [--skill <folder>]... [--spec <file>]
12
+ [--language <tag>] [--description <text>]
13
+ [--license <id>] [--move]
14
+
15
+ Make spex-packages/<name>/ in the current directory from skill folders
16
+ and/or a spec file, with no server:
17
+ --skill <folder> An Agent Skills folder holding SKILL.md; repeatable
18
+ --spec <file> The spec file, named <name>.md
19
+ --language <tag> The artifacts' language (default en)
20
+ --description <text> Default: the first skill's description, else the
21
+ first paragraph under the spec's Intent heading
22
+ --license <id> Default: read from ./LICENSE, else Apache-2.0
23
+ --move Move the skill folders instead of copying them`;
24
+ class InitRefusal extends Error {
25
+ }
26
+ function refuse(message) {
27
+ throw new InitRefusal(message);
28
+ }
29
+ /** A lowercase kebab-case name of at most 64 characters: an org, a
30
+ * package's name, and an Agent Skills name alike (environments-1). */
31
+ const KEBAB = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
32
+ const isName = (value) => value.length <= 64 && KEBAB.test(value);
33
+ // BCP 47's langtag in its common form, or a private-use tag, as the
34
+ // core reads a release's language folders.
35
+ const LANGTAG = new RegExp("^(?:" +
36
+ "(?:[a-z]{2,3}(?:-[a-z]{3}){0,3}|[a-z]{4}|[a-z]{5,8})" +
37
+ "(?:-[a-z]{4})?" +
38
+ "(?:-(?:[a-z]{2}|\\d{3}))?" +
39
+ "(?:-(?:[a-z\\d]{5,8}|\\d[a-z\\d]{3}))*" +
40
+ "(?:-[\\da-wyz](?:-[a-z\\d]{2,8})+)*" +
41
+ "(?:-x(?:-[a-z\\d]{1,8})+)?" +
42
+ "|x(?:-[a-z\\d]{1,8})+" +
43
+ ")$", "i");
44
+ const VALUED = new Set(["skill", "spec", "language", "description", "license"]);
45
+ // eslint-disable-next-line no-control-regex
46
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
47
+ /** Parse the whole invocation before reading or writing anything. */
48
+ function parseInit(args) {
49
+ const words = [];
50
+ const skills = [];
51
+ const single = {};
52
+ let move = false;
53
+ for (let i = 0; i < args.length; i++) {
54
+ const arg = args[i];
55
+ if (!arg.startsWith("-")) {
56
+ words.push(arg);
57
+ continue;
58
+ }
59
+ const match = /^--([a-z-]+)(?:=([\s\S]*))?$/.exec(arg);
60
+ const key = match?.[1];
61
+ if (key === "move") {
62
+ if (match[2] !== undefined)
63
+ refuse("--move takes no value.");
64
+ if (move)
65
+ refuse("Option --move was repeated.");
66
+ move = true;
67
+ continue;
68
+ }
69
+ if (!key || !VALUED.has(key))
70
+ refuse(`Unknown option ${arg.split("=")[0]}. Use spex package init --help.`);
71
+ const inline = match[2];
72
+ const value = inline ?? args[++i];
73
+ if (value === undefined || value === "" || (inline === undefined && value.startsWith("-")))
74
+ refuse(`--${key} requires a value.`);
75
+ if (key === "skill") {
76
+ skills.push(value);
77
+ continue;
78
+ }
79
+ if (Object.hasOwn(single, key))
80
+ refuse(`Option --${key} was repeated.`);
81
+ single[key] = value;
82
+ }
83
+ if (words.length !== 1)
84
+ refuse("package init takes exactly one <org>/<name> argument. Use spex package init --help.");
85
+ const parts = words[0].split("/");
86
+ if (parts.length !== 2 || !isName(parts[0]) || !isName(parts[1]))
87
+ refuse("The package name must be <org>/<name>, each part lowercase letters, digits and single hyphens, at most 64 characters.");
88
+ const language = single.language ?? "en";
89
+ if (!LANGTAG.test(language) || language.length > 64)
90
+ refuse(`--language ${JSON.stringify(language)} is not a BCP 47 language tag such as en or zh-Hans.`);
91
+ if (single.description !== undefined && CONTROL.test(single.description.replace(/[\n\t]/g, " ")))
92
+ refuse("--description must not hold control characters.");
93
+ if (single.license !== undefined && CONTROL.test(single.license))
94
+ refuse("--license must not hold control characters.");
95
+ if (single.license !== undefined && !single.license.trim())
96
+ refuse("--license requires a value.");
97
+ if (single.description !== undefined && !single.description.trim())
98
+ refuse("--description requires a value.");
99
+ return {
100
+ org: parts[0],
101
+ name: parts[1],
102
+ skills,
103
+ ...(single.spec !== undefined ? { spec: single.spec } : {}),
104
+ language,
105
+ ...(single.description !== undefined ? { description: single.description.trim() } : {}),
106
+ ...(single.license !== undefined ? { license: single.license.trim() } : {}),
107
+ move,
108
+ };
109
+ }
110
+ // -- SKILL.md frontmatter ------------------------------------------------
111
+ /** Plain YAML scalars the core schema reads as no string: a skill named
112
+ * so would be refused by the core's reader. */
113
+ const NON_STRING = /^(?:~|null|Null|NULL|true|True|TRUE|false|False|FALSE|[-+]?[0-9]+|0o[0-7]+|0x[0-9a-fA-F]+|[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)(?:[eE][-+]?[0-9]+)?|[-+]?\.(?:inf|Inf|INF)|\.(?:nan|NaN|NAN))$/;
114
+ /** A plain value YAML refuses in a block mapping, so the core's reader
115
+ * reads no frontmatter at all. */
116
+ const REFUSED = Symbol("refused");
117
+ /** The top-level string fields of a SKILL.md's YAML frontmatter that
118
+ * matter here — `name` and `description` — read from the common YAML
119
+ * forms: plain, single- or double-quoted, and `|` or `>` blocks. A field
120
+ * of another form reads as absent. The frontmatter is found as a
121
+ * release's readers find it, from the text's first character: nothing
122
+ * before `---`, a byte order mark included, is skipped. */
123
+ export function skillFrontmatter(text) {
124
+ const match = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text);
125
+ if (!match)
126
+ return {};
127
+ const lines = match[1].split(/\r?\n/);
128
+ const out = {};
129
+ for (let i = 0; i < lines.length; i++) {
130
+ const field = /^(name|description)[ \t]*:(?:[ \t]+(.*)|)$/.exec(lines[i]);
131
+ if (!field)
132
+ continue;
133
+ const key = field[1];
134
+ // The value's continuation: the lines indented below its key.
135
+ const rest = [];
136
+ while (i + 1 < lines.length && (/^[ \t]/.test(lines[i + 1]) || lines[i + 1].trim() === ""))
137
+ rest.push(lines[++i]);
138
+ while (rest.length && rest[rest.length - 1].trim() === "")
139
+ rest.pop();
140
+ const value = scalar((field[2] ?? "").trim(), rest);
141
+ if (value === REFUSED)
142
+ out.unreadable ??= key;
143
+ else if (value !== undefined)
144
+ out[key] = value;
145
+ }
146
+ return out;
147
+ }
148
+ function scalar(head, rest) {
149
+ const block = /^([|>])[-+]?[1-9]?(?:[ \t]+#.*)?$/.exec(head);
150
+ if (block) {
151
+ const indent = Math.min(...rest.filter((line) => line.trim()).map((line) => /^[ \t]*/.exec(line)[0].length));
152
+ const body = rest.map((line) => line.slice(Math.min(indent, line.length)));
153
+ if (block[1] === "|")
154
+ return body.join("\n").trim() || undefined;
155
+ return body.join("\n").split(/\n[ \t]*\n/).map((p) => p.split("\n").map((l) => l.trim()).join(" ")).join("\n").trim() || undefined;
156
+ }
157
+ // A nested mapping is no string.
158
+ if (head === "" && rest[0] !== undefined && /^[ \t]+[^ \t#'"][^:]*:(?:[ \t]|$)/.test(rest[0]))
159
+ return undefined;
160
+ const joined = [head, ...rest.map((line) => line.trim())].filter((part) => part !== "").join(" ");
161
+ if (joined.startsWith('"')) {
162
+ const end = /^"((?:[^"\\]|\\.)*)"[ \t]*(?:#.*)?$/.exec(joined);
163
+ if (!end)
164
+ return undefined;
165
+ // An escaped space is a space; a tab stands as it is.
166
+ try {
167
+ return JSON.parse(`"${end[1].replace(/\\(?=[ \t])/g, "").replace(/\t/g, "\\t")}"`);
168
+ }
169
+ catch {
170
+ return undefined;
171
+ }
172
+ }
173
+ if (joined.startsWith("'")) {
174
+ const end = /^'((?:[^']|'')*)'[ \t]*(?:#.*)?$/.exec(joined);
175
+ return end ? end[1].replace(/''/g, "'") : undefined;
176
+ }
177
+ const plain = joined.replace(/[ \t]+#.*$/, "").trim();
178
+ if (!plain || NON_STRING.test(plain) || /^[[{&*!|>%@`]/.test(plain))
179
+ return undefined;
180
+ // `key: value: more` is no YAML: the whole frontmatter is refused.
181
+ if (/:[ \t]/.test(plain) || plain.endsWith(":"))
182
+ return REFUSED;
183
+ return plain;
184
+ }
185
+ // -- the spec's Intent ---------------------------------------------------
186
+ /** The first paragraph under a spec's Intent heading, its lines joined. */
187
+ export function intentParagraph(text) {
188
+ const lines = text.replace(/^/, "").split(/\r?\n/);
189
+ let i = lines.findIndex((line) => /^#{1,6}[ \t]+Intent[ \t]*#*[ \t]*$/i.test(line));
190
+ if (i < 0)
191
+ return undefined;
192
+ i++;
193
+ while (i < lines.length && lines[i].trim() === "")
194
+ i++;
195
+ const paragraph = [];
196
+ while (i < lines.length && lines[i].trim() !== "" && !/^#{1,6}(?:[ \t]|$)/.test(lines[i]))
197
+ paragraph.push(lines[i++].trim());
198
+ return paragraph.join(" ") || undefined;
199
+ }
200
+ // -- the license ---------------------------------------------------------
201
+ /** The license a project's root LICENSE names (attached-cli-12). */
202
+ export function detectLicense(text) {
203
+ const head = (text ?? "").replace(/^/, "").trimStart();
204
+ if (head.startsWith("Apache License"))
205
+ return "Apache-2.0";
206
+ if (head.startsWith("MIT License"))
207
+ return "MIT";
208
+ return "Apache-2.0";
209
+ }
210
+ function lstatOrNull(path) {
211
+ try {
212
+ return lstatSync(path);
213
+ }
214
+ catch (error) {
215
+ if (error.code === "ENOENT" || error.code === "ENOTDIR")
216
+ return null;
217
+ throw error;
218
+ }
219
+ }
220
+ /** A skill folder read whole: only folders and regular files, no link. */
221
+ function readSkill(argument, cwd) {
222
+ const folder = resolve(cwd, argument);
223
+ const stat = lstatOrNull(folder);
224
+ if (stat?.isSymbolicLink())
225
+ refuse(`--skill ${argument} is a link; give the skill's own folder.`);
226
+ if (!stat?.isDirectory())
227
+ refuse(`--skill ${argument} is no folder holding a SKILL.md.`);
228
+ const dirs = [];
229
+ const files = [];
230
+ const walk = (relativeDir) => {
231
+ for (const entry of readdirSync(join(folder, relativeDir)).sort()) {
232
+ const path = relativeDir ? `${relativeDir}/${entry}` : entry;
233
+ const entryStat = lstatSync(join(folder, path));
234
+ if (entryStat.isSymbolicLink())
235
+ refuse(`--skill ${argument} holds a link at ${path}; a package holds files only.`);
236
+ if (entryStat.isDirectory()) {
237
+ dirs.push(path);
238
+ walk(path);
239
+ }
240
+ else if (entryStat.isFile())
241
+ files.push(path);
242
+ else
243
+ refuse(`--skill ${argument} holds a special file at ${path}; a package holds files only.`);
244
+ }
245
+ };
246
+ walk("");
247
+ if (!files.includes("SKILL.md"))
248
+ refuse(`--skill ${argument} holds no SKILL.md.`);
249
+ const text = readFileSync(join(folder, "SKILL.md"), "utf8");
250
+ // A release's readers find the frontmatter from the first byte, so a
251
+ // byte order mark would hide the name from the app and the registry.
252
+ if (text.startsWith("\uFEFF"))
253
+ refuse(`--skill ${argument}: its SKILL.md begins with a byte order mark, which hides its frontmatter from a package's readers; save it as UTF-8 without one.`);
254
+ const frontmatter = skillFrontmatter(text);
255
+ if (frontmatter.unreadable)
256
+ refuse(`--skill ${argument}: its SKILL.md frontmatter is no YAML, so its name cannot be read: the ${frontmatter.unreadable} holds ": " unquoted; put the value in quotes.`);
257
+ if (frontmatter.name === undefined || !isName(frontmatter.name))
258
+ refuse(`--skill ${argument}: its SKILL.md declares no Agent Skills name (lowercase letters, digits and single hyphens, at most 64 characters) as its frontmatter's name.`);
259
+ return { folder, id: frontmatter.name, ...(frontmatter.description ? { description: frontmatter.description } : {}), dirs, files };
260
+ }
261
+ /** A string as a YAML double-quoted scalar: JSON's escapes, with the
262
+ * characters YAML takes as unprintable escaped too. */
263
+ function quoted(value) {
264
+ // eslint-disable-next-line no-control-regex
265
+ return JSON.stringify(value).replace(/[\u007f-\u009f]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
266
+ }
267
+ function manifestText(options, description, license, skills) {
268
+ const lines = [
269
+ "format: 2",
270
+ `org: ${quoted(options.org)}`,
271
+ `name: ${quoted(options.name)}`,
272
+ `version: ${quoted("0.1.0")}`,
273
+ `description: ${quoted(description)}`,
274
+ `license: ${quoted(license)}`,
275
+ "artifacts:",
276
+ ];
277
+ for (const skill of skills)
278
+ lines.push(` ${quoted(skill.id)}:`, " kind: skill", ` language: ${quoted(options.language)}`);
279
+ if (options.spec !== undefined)
280
+ lines.push(` ${quoted(options.name)}:`, " kind: spec", ` language: ${quoted(options.language)}`);
281
+ return `${lines.join("\n")}\n`;
282
+ }
283
+ /** Whether the folder `outer` holds `spex-packages/<name>/` of the
284
+ * working folder `cwd`, compared by real paths; a folder that cannot be
285
+ * read holds nothing. */
286
+ function holdsDestination(outer, cwd, name) {
287
+ let path;
288
+ try {
289
+ path = relative(realpathSync(outer), join(realpathSync(cwd), "spex-packages", name));
290
+ }
291
+ catch {
292
+ return false;
293
+ }
294
+ return path === "" || (path !== ".." && !path.startsWith(`..${sep}`) && !isAbsolute(path));
295
+ }
296
+ function copyFile(from, to) {
297
+ copyFileSync(from, to);
298
+ chmodSync(to, statSync(from).mode & 0o777);
299
+ }
300
+ /** Make the package folder (attached-cli-12); the exit code. */
301
+ export function packageInit(args, cwd = process.cwd()) {
302
+ if (args.includes("--help") || args.includes("-h")) {
303
+ process.stdout.write(`${PACKAGE_INIT_USAGE}\n`);
304
+ return 0;
305
+ }
306
+ try {
307
+ const options = parseInit(args);
308
+ const { org, name, language } = options;
309
+ const pkg = `${org}/${name}`;
310
+ if (options.skills.length === 0 && options.spec === undefined)
311
+ refuse("Name at least one artifact: --skill <folder> or --spec <file>.");
312
+ const parent = join(cwd, "spex-packages");
313
+ const destination = join(parent, name);
314
+ const parentStat = lstatOrNull(parent);
315
+ if (parentStat && !parentStat.isDirectory())
316
+ refuse("spex-packages in the current directory is not a folder.");
317
+ if (lstatOrNull(destination))
318
+ refuse(`spex-packages/${name}/ already exists; nothing was written.`);
319
+ const skills = [];
320
+ for (const argument of options.skills) {
321
+ if (options.move && holdsDestination(resolve(cwd, argument), cwd, name))
322
+ refuse(`--move cannot move ${argument}: it holds spex-packages/${name}/.`);
323
+ const skill = readSkill(argument, cwd);
324
+ if (skills.some((other) => other.id === skill.id))
325
+ refuse(`Two skills declare the id ${skill.id}; each skill needs its own name.`);
326
+ if (options.spec !== undefined && skill.id === name)
327
+ refuse(`The skill ${skill.id} has the spec's id ${name}; a package names each artifact once, so rename the skill or the package.`);
328
+ skills.push(skill);
329
+ }
330
+ let specText;
331
+ if (options.spec !== undefined) {
332
+ const file = resolve(cwd, options.spec);
333
+ let stat = null;
334
+ try {
335
+ stat = statSync(file);
336
+ }
337
+ catch {
338
+ stat = null;
339
+ }
340
+ if (!stat?.isFile())
341
+ refuse(`--spec ${options.spec} is no file.`);
342
+ if (basename(file) !== `${name}.md`)
343
+ refuse(`The spec file must be named ${name}.md, since its items are ${name}-<N>; rename it or the package.`);
344
+ specText = readFileSync(file);
345
+ }
346
+ const description = options.description
347
+ ?? skills[0]?.description
348
+ ?? (specText ? intentParagraph(specText.toString("utf8")) : undefined);
349
+ if (!description)
350
+ refuse("No description was found in the first skill's SKILL.md or under the spec's Intent heading; pass --description <text>.");
351
+ const licenseFile = join(cwd, "LICENSE");
352
+ let licenseText;
353
+ try {
354
+ if (statSync(licenseFile).isFile())
355
+ licenseText = readFileSync(licenseFile);
356
+ }
357
+ catch {
358
+ licenseText = undefined;
359
+ }
360
+ const license = options.license ?? detectLicense(licenseText?.toString("utf8"));
361
+ // Everything is written into a staging folder beside the
362
+ // destination, renamed into place whole; only then are moved skill
363
+ // folders removed.
364
+ const madeParent = !parentStat;
365
+ mkdirSync(parent, { recursive: true });
366
+ // Made as any folder is, not owner-only as a temporary one.
367
+ const staging = join(parent, `.${name}.init-${randomBytes(6).toString("hex")}`);
368
+ mkdirSync(staging);
369
+ try {
370
+ writeFileSync(join(staging, "meta.yaml"), manifestText(options, description, license, skills));
371
+ writeFileSync(join(staging, "README.md"), `# ${pkg}\n\n${description}\n`);
372
+ if (licenseText)
373
+ writeFileSync(join(staging, "LICENSE"), licenseText);
374
+ for (const skill of skills) {
375
+ const into = join(staging, "skills", language, skill.id);
376
+ mkdirSync(into, { recursive: true });
377
+ for (const dir of skill.dirs)
378
+ mkdirSync(join(into, ...dir.split("/")), { recursive: true });
379
+ for (const file of skill.files)
380
+ copyFile(join(skill.folder, ...file.split("/")), join(into, ...file.split("/")));
381
+ }
382
+ if (specText) {
383
+ mkdirSync(join(staging, "specs", language), { recursive: true });
384
+ writeFileSync(join(staging, "specs", language, `${name}.md`), specText);
385
+ }
386
+ renameSync(staging, destination);
387
+ }
388
+ catch (error) {
389
+ rmSync(staging, { recursive: true, force: true });
390
+ if (madeParent) {
391
+ try {
392
+ rmdirSync(parent);
393
+ }
394
+ catch { /* holds something else now */ }
395
+ }
396
+ throw error;
397
+ }
398
+ // Each moved skill now stands in the package: its former folder goes.
399
+ const left = [];
400
+ if (options.move) {
401
+ for (const [index, skill] of skills.entries()) {
402
+ try {
403
+ rmSync(skill.folder, { recursive: true, force: true });
404
+ }
405
+ catch (error) {
406
+ left.push(`${options.skills[index]} (${error.code ?? "not removed"})`);
407
+ }
408
+ }
409
+ }
410
+ const folder = `spex-packages/${name}`;
411
+ const made = [
412
+ ...skills.map((skill) => `skill ${skill.id}`),
413
+ ...(options.spec !== undefined ? [`spec ${name}`] : []),
414
+ ].join(", ");
415
+ process.stdout.write([
416
+ `Made ${folder}/ for ${pkg} (${made}${options.move && skills.length ? `; ${skills.length === 1 ? "the skill folder was" : "the skill folders were"} moved into it` : ""}).`,
417
+ "",
418
+ "Next, in the Spex app: Playbooks → Add from folder with",
419
+ ` ${pkg} and ${folder}, then Publish on its row.`,
420
+ "Or with the CLI, from this folder while the Spex app runs:",
421
+ ` spex package add ${pkg} --path ${folder}`,
422
+ ` spex package publish ${folder} --dry-run`,
423
+ " (then publish again without --dry-run)",
424
+ "",
425
+ ].join("\n"));
426
+ if (left.length) {
427
+ process.stderr.write(`The package holds a copy, but these skill folders could not be removed; remove them yourself: ${left.join(", ")}\n`);
428
+ return 1;
429
+ }
430
+ return 0;
431
+ }
432
+ catch (error) {
433
+ if (error instanceof InitRefusal) {
434
+ process.stderr.write(`${error.message}\n`);
435
+ return 1;
436
+ }
437
+ const code = error.code;
438
+ process.stderr.write(`package init failed${code ? ` (${code})` : ""}: ${error instanceof Error ? error.message : String(error)}\n`);
439
+ return 1;
440
+ }
441
+ }
442
+ //# sourceMappingURL=package-init.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sublang/spex",
3
- "version": "4.0.1",
3
+ "version": "4.2.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$\""