@sublang/spex 4.1.0 → 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,8 +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. It also attaches to a running local
14
- Spex server for project, Space sign-in and package operations.
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.
15
16
 
16
17
  ## Install
17
18
 
@@ -25,19 +26,56 @@ Or run once without installing:
25
26
  npx @sublang/spex scaffold
26
27
  ```
27
28
 
28
- ## Use a running Spex server
29
+ ## Make a package folder
29
30
 
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.
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.
36
74
  The CLI connects only to literal loopback addresses; it starts no server and
37
- stores no separate credentials or package state.
75
+ stores no separate credentials or package state. Without a running app it
76
+ says so and exits 1.
38
77
 
39
78
  ```sh
40
- export SPEX_SERVER_URL='<access URL printed by the local server>'
41
79
  spex project add /absolute/path/to/project
42
80
  cd /absolute/path/to/project
43
81
  spex project list
@@ -62,12 +100,13 @@ spex package remove my-org/toolkit
62
100
  ```
63
101
 
64
102
  `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:
103
+ For a package you are authoring inside the project, such as one
104
+ `spex package init` made, request its relative folder:
66
105
 
67
106
  ```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
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
71
110
  ```
72
111
 
73
112
  `add` requires exactly one of `--version` or `--path`. Core validates package
@@ -85,7 +124,8 @@ an unknown result: the operation may still complete. Inspect its state before
85
124
  manually retrying; the CLI never reconnects or resends mutations.
86
125
  Ctrl+C exits 130: package work may continue, while sign-in requests cancellation
87
126
  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.
127
+ Use `spex --help` for command forms. Scaffold, lint and `package init` remain
128
+ usable without a server.
89
129
 
90
130
  ## Usage
91
131
 
@@ -6,7 +6,7 @@ type Invocation = {
6
6
  flags: Flags;
7
7
  timeoutMs: number;
8
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.";
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
10
  /** Parse the whole invocation before opening a connection or sending a command. */
11
11
  export declare function parseAttached(args: string[]): Invocation;
12
12
  export declare function runAttached(args: string[], env?: NodeJS.ProcessEnv): Promise<number>;
@@ -1,10 +1,10 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
3
  import { resolve, isAbsolute, win32 } from "node:path";
4
- import { AttachedClient, accessEndpoint, CliFailure } from "./attached-client.js";
4
+ import { APP_GUIDANCE, AttachedClient, CliFailure, selectEndpoint } from "./attached-client.js";
5
5
  const NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:-[a-z0-9]+)*$/;
6
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):
7
+ export const ATTACHED_USAGE = `Attached commands (need the running Spex app, or a server named below):
8
8
  auth login --instance <origin> Sign in through the browser/device instructions
9
9
  auth status Show instance sign-in standing
10
10
  project list List registered projects
@@ -18,7 +18,9 @@ export const ATTACHED_USAGE = `Attached commands (an already-running local Spex
18
18
  package resolve Resolve requests and install
19
19
  package publish <relative-folder> [--dry-run]
20
20
 
21
- Connection: --server <access-url> or SPEX_SERVER_URL (literal loopback only).
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).
22
24
  Observation: --timeout <positive seconds> (default 600); no reconnect or replay.
23
25
  Packages: --project <registered-folder>, otherwise the exact current directory.
24
26
  Publishing is explicit; --dry-run checks without uploading.`;
@@ -135,10 +137,10 @@ export async function runAttached(args, env = process.env) {
135
137
  try {
136
138
  const invocation = parseAttached(args);
137
139
  const { group, action, positional, flags } = invocation;
138
- const access = accessEndpoint(typeof flags.server === "string" ? flags.server : env.SPEX_SERVER_URL);
140
+ const access = selectEndpoint(typeof flags.server === "string" ? flags.server : undefined, env);
139
141
  token = access.token;
140
142
  endpoint = access.url;
141
- client = new AttachedClient(access.url, invocation.timeoutMs);
143
+ client = new AttachedClient(access.url, invocation.timeoutMs, access.fromApp ? `Could not reach the Spex app at the endpoint it recorded. ${APP_GUIDANCE}` : undefined);
142
144
  process.on("SIGINT", interrupt);
143
145
  await client.connect();
144
146
  if (group === "project") {
@@ -3,6 +3,18 @@ export declare class CliFailure extends Error {
3
3
  constructor(exitCode: number, message: string);
4
4
  }
5
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
+ };
6
18
  /** Validate before opening a socket; WHATWG normalization must not admit
7
19
  * numeric aliases, wildcard addresses or DNS names other than localhost. */
8
20
  export declare function accessEndpoint(input: string | undefined): {
@@ -13,17 +25,22 @@ export declare function accessEndpoint(input: string | undefined): {
13
25
  export declare class AttachedClient {
14
26
  private readonly endpoint;
15
27
  private readonly timeoutMs;
28
+ private readonly unreachable?;
16
29
  private socket?;
17
30
  private ready?;
18
31
  private pending;
19
32
  private completion;
20
33
  private earlyCompletion;
21
34
  private sent;
35
+ private opened;
22
36
  private stopped;
23
37
  private failure?;
24
38
  private timer?;
25
39
  signInId?: string;
26
- constructor(endpoint: string, timeoutMs: number);
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);
27
44
  connect(): Promise<void>;
28
45
  private observationFailure;
29
46
  private message;
@@ -1,6 +1,9 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
3
  import { randomUUID } from "node:crypto";
4
+ import { readFileSync } from "node:fs";
5
+ import { homedir } from "node:os";
6
+ import { join } from "node:path";
4
7
  import { PROTOCOL_VERSION, ATTACHED_CLI_VERSION } from "./generated-protocol.js";
5
8
  export class CliFailure extends Error {
6
9
  exitCode;
@@ -9,12 +12,49 @@ export class CliFailure extends Error {
9
12
  this.exitCode = exitCode;
10
13
  }
11
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
+ }
12
53
  /** Validate before opening a socket; WHATWG normalization must not admit
13
54
  * numeric aliases, wildcard addresses or DNS names other than localhost. */
14
55
  export function accessEndpoint(input) {
15
- const guidance = "Use --server <loopback access-url> or SPEX_SERVER_URL from the running local Spex server.";
16
56
  if (!input)
17
- throw new CliFailure(1, guidance);
57
+ throw new CliFailure(1, EXPLICIT_GUIDANCE);
18
58
  try {
19
59
  const rawHost = /^[a-z]+:\/\/(\[[^\]]+\]|[^/:?#]+)(?::[0-9]+)?(?:[/?#]|$)/i.exec(input)?.[1]?.toLowerCase();
20
60
  const url = new URL(input);
@@ -28,26 +68,32 @@ export function accessEndpoint(input) {
28
68
  return { url: url.href, token };
29
69
  }
30
70
  catch {
31
- throw new CliFailure(1, `Invalid server access URL. ${guidance}`);
71
+ throw new CliFailure(1, `Invalid server access URL. ${EXPLICIT_GUIDANCE}`);
32
72
  }
33
73
  }
34
74
  /** One invocation, one connection. Core owns validation and operation state. */
35
75
  export class AttachedClient {
36
76
  endpoint;
37
77
  timeoutMs;
78
+ unreachable;
38
79
  socket;
39
80
  ready;
40
81
  pending = new Map();
41
82
  completion = new Map();
42
83
  earlyCompletion = new Map();
43
84
  sent = false;
85
+ opened = false;
44
86
  stopped = false;
45
87
  failure;
46
88
  timer;
47
89
  signInId;
48
- constructor(endpoint, timeoutMs) {
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) {
49
94
  this.endpoint = endpoint;
50
95
  this.timeoutMs = timeoutMs;
96
+ this.unreachable = unreachable;
51
97
  }
52
98
  async connect() {
53
99
  if (typeof globalThis.WebSocket !== "function")
@@ -55,18 +101,20 @@ export class AttachedClient {
55
101
  this.timer = setTimeout(() => this.fail(this.observationFailure("Observation timed out")), this.timeoutMs);
56
102
  await new Promise((resolve, reject) => {
57
103
  this.ready = { resolve, reject };
104
+ const lost = (reason) => this.fail(!this.opened && this.unreachable ? new CliFailure(1, this.unreachable) : this.observationFailure(reason));
58
105
  try {
59
106
  this.socket = new WebSocket(this.endpoint);
60
107
  }
61
108
  catch {
62
- this.fail(new CliFailure(1, "Could not connect. Check the running server and its access URL."));
109
+ this.fail(new CliFailure(1, this.unreachable ?? "Could not connect. Check the running server and its access URL."));
63
110
  return;
64
111
  }
112
+ this.socket.addEventListener("open", () => { this.opened = true; });
65
113
  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")));
114
+ this.socket.addEventListener("error", () => lost("Connection failed; check the running server and its access URL"));
67
115
  this.socket.addEventListener("close", () => {
68
116
  if (!this.stopped)
69
- this.fail(this.observationFailure("Connection closed"));
117
+ lost("Connection closed");
70
118
  });
71
119
  });
72
120
  }
package/dist/cli.js CHANGED
@@ -4,6 +4,7 @@
4
4
  import { lint } from "./lint.js";
5
5
  import { scaffold } from "./scaffold.js";
6
6
  import { ATTACHED_USAGE, runAttached } from "./attached-cli.js";
7
+ import { packageInit } from "./package-init.js";
7
8
  const USAGE = `Usage: spex <command> [options]
8
9
 
9
10
  Commands:
@@ -13,6 +14,11 @@ Commands:
13
14
  Refresh scaffold-provided specs templates
14
15
  lint [<path>] Check the specs tree structure, item IDs,
15
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
16
22
 
17
23
  Agent names: claude, codex, gemini, kimi, opencode, or all
18
24
 
@@ -24,6 +30,12 @@ async function main() {
24
30
  console.log(USAGE);
25
31
  process.exit(0);
26
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
+ }
27
39
  if (["auth", "project", "package", "--server", "--timeout"].includes(command) || command.startsWith("--server=") || command.startsWith("--timeout=")) {
28
40
  process.exitCode = await runAttached(args);
29
41
  return;
@@ -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.1.0",
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",