@sublang/spex 4.1.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +438 -54
  2. package/dist/cli.js +81 -31
  3. package/dist/commands/add.d.ts +12 -0
  4. package/dist/commands/add.js +138 -0
  5. package/dist/commands/auth-target.d.ts +11 -0
  6. package/dist/commands/auth-target.js +50 -0
  7. package/dist/commands/environment.d.ts +123 -0
  8. package/dist/commands/environment.js +411 -0
  9. package/dist/commands/export.d.ts +21 -0
  10. package/dist/commands/export.js +663 -0
  11. package/dist/commands/home.d.ts +56 -0
  12. package/dist/commands/home.js +215 -0
  13. package/dist/commands/install.d.ts +2 -0
  14. package/dist/commands/install.js +48 -0
  15. package/dist/commands/list.d.ts +2 -0
  16. package/dist/commands/list.js +87 -0
  17. package/dist/commands/login.d.ts +2 -0
  18. package/dist/commands/login.js +211 -0
  19. package/dist/commands/logout.d.ts +2 -0
  20. package/dist/commands/logout.js +74 -0
  21. package/dist/commands/publish.d.ts +2 -0
  22. package/dist/commands/publish.js +120 -0
  23. package/dist/commands/remove.d.ts +2 -0
  24. package/dist/commands/remove.js +34 -0
  25. package/dist/commands/run.d.ts +50 -0
  26. package/dist/commands/run.js +309 -0
  27. package/dist/commands/search.d.ts +2 -0
  28. package/dist/commands/search.js +34 -0
  29. package/dist/commands/settle.d.ts +124 -0
  30. package/dist/commands/settle.js +475 -0
  31. package/dist/commands/update.d.ts +2 -0
  32. package/dist/commands/update.js +37 -0
  33. package/dist/commands/whoami.d.ts +2 -0
  34. package/dist/commands/whoami.js +75 -0
  35. package/dist/lib/environment/agent-folders.d.ts +14 -0
  36. package/dist/lib/environment/agent-folders.js +11 -0
  37. package/dist/lib/environment/archive.d.ts +26 -0
  38. package/dist/lib/environment/archive.js +91 -0
  39. package/dist/lib/environment/builtins.d.ts +112 -0
  40. package/dist/lib/environment/builtins.js +539 -0
  41. package/dist/lib/environment/citations.d.ts +75 -0
  42. package/dist/lib/environment/citations.js +267 -0
  43. package/dist/lib/environment/exports.d.ts +190 -0
  44. package/dist/lib/environment/exports.js +1029 -0
  45. package/dist/lib/environment/format.d.ts +133 -0
  46. package/dist/lib/environment/format.js +651 -0
  47. package/dist/lib/environment/git-source.d.ts +41 -0
  48. package/dist/lib/environment/git-source.js +159 -0
  49. package/dist/lib/environment/index.d.ts +20 -0
  50. package/dist/lib/environment/index.js +27 -0
  51. package/dist/lib/environment/install.d.ts +140 -0
  52. package/dist/lib/environment/install.js +694 -0
  53. package/dist/lib/environment/layout.d.ts +15 -0
  54. package/dist/lib/environment/layout.js +50 -0
  55. package/dist/lib/environment/lock.d.ts +87 -0
  56. package/dist/lib/environment/lock.js +305 -0
  57. package/dist/lib/environment/marker.d.ts +15 -0
  58. package/dist/lib/environment/marker.js +31 -0
  59. package/dist/lib/environment/own-paths.d.ts +59 -0
  60. package/dist/lib/environment/own-paths.js +174 -0
  61. package/dist/lib/environment/placed-record.d.ts +32 -0
  62. package/dist/lib/environment/placed-record.js +72 -0
  63. package/dist/lib/environment/registries.d.ts +25 -0
  64. package/dist/lib/environment/registries.js +75 -0
  65. package/dist/lib/environment/registry.d.ts +173 -0
  66. package/dist/lib/environment/registry.js +390 -0
  67. package/dist/lib/environment/requests.d.ts +108 -0
  68. package/dist/lib/environment/requests.js +403 -0
  69. package/dist/lib/environment/resolve.d.ts +70 -0
  70. package/dist/lib/environment/resolve.js +451 -0
  71. package/dist/lib/environment/semver.d.ts +30 -0
  72. package/dist/lib/environment/semver.js +130 -0
  73. package/dist/lib/environment/store.d.ts +23 -0
  74. package/dist/lib/environment/store.js +123 -0
  75. package/dist/lib/environment/tar.d.ts +27 -0
  76. package/dist/lib/environment/tar.js +219 -0
  77. package/dist/lib/files.d.ts +66 -0
  78. package/dist/lib/files.js +233 -0
  79. package/dist/lib/git-host.d.ts +579 -0
  80. package/dist/lib/git-host.js +1363 -0
  81. package/dist/lib/home-file.d.ts +124 -0
  82. package/dist/lib/home-file.js +288 -0
  83. package/dist/lib/instance.d.ts +63 -0
  84. package/dist/lib/instance.js +130 -0
  85. package/dist/lib/words.d.ts +32 -0
  86. package/dist/lib/words.js +27 -0
  87. package/dist/lint.js +8 -0
  88. package/dist/testing/index.d.ts +1 -0
  89. package/dist/testing/index.js +7 -0
  90. package/dist/testing/standin-registry.d.ts +94 -0
  91. package/dist/testing/standin-registry.js +449 -0
  92. package/package.json +37 -3
  93. package/dist/attached-cli.d.ts +0 -13
  94. package/dist/attached-cli.js +0 -247
  95. package/dist/attached-client.d.ts +0 -36
  96. package/dist/attached-client.js +0 -189
  97. package/dist/generated-protocol.d.ts +0 -2
  98. package/dist/generated-protocol.js +0 -6
@@ -0,0 +1,74 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ // `spex logout [--registry <url> | --space <url>]` (cli-11, git-host-10,
4
+ // DR-168): revoke this computer's sign-in for one purpose alone — this
5
+ // folder's registry for its packages by default, or the registry or
6
+ // Space named — and, for a Space, in the turn its pair is removed, mark
7
+ // its entry signed out in `home.yaml`, keeping the entry and every other
8
+ // Space's. One line says so, in whoami's grammar (cli-12).
9
+ import { authTarget } from "./auth-target.js";
10
+ import { CredentialChanged } from "../lib/git-host.js";
11
+ import { instanceAt, updateHomeFile, withSignOut } from "../lib/home-file.js";
12
+ import { clientOf, credentialsOf, homeDir, hostCause, hostOf, nameOf, readHome, registryName, signedIn } from "./home.js";
13
+ import { options, Refusal } from "./run.js";
14
+ export const logout = async (args) => {
15
+ const values = options("logout", args, { space: { type: "string" }, registry: { type: "string" } });
16
+ const dir = homeDir();
17
+ const home = readHome(dir);
18
+ const { target, scope } = authTarget(home, values);
19
+ if (scope === "registry") {
20
+ const credentials = credentialsOf(dir, target.origin, scope);
21
+ const name = await registryName(dir, target.origin);
22
+ let held;
23
+ try {
24
+ held = await credentials.read();
25
+ }
26
+ catch {
27
+ held = undefined;
28
+ }
29
+ if (held === null) {
30
+ console.log(`Already signed out at ${name}.`);
31
+ return;
32
+ }
33
+ try {
34
+ await clientOf(target.origin, credentials, undefined, scope).signOut();
35
+ }
36
+ catch (error) {
37
+ if (error instanceof CredentialChanged)
38
+ throw new Refusal(`your sign-in at ${name} changed meanwhile — spex logout again`);
39
+ throw new Refusal(`not signed out at ${name}: ${hostCause(error, name, "spex logout again")}`);
40
+ }
41
+ console.log(`Signed out at ${name}.`);
42
+ return;
43
+ }
44
+ const entry = home ? instanceAt(home, target.origin) : undefined;
45
+ if (!entry)
46
+ throw new Refusal(`${hostOf(target.origin)}: not signed in on this computer — spex whoami`);
47
+ const name = nameOf(entry);
48
+ if (!signedIn(entry)) {
49
+ console.log(`Already signed out at ${name}.`);
50
+ return;
51
+ }
52
+ const client = clientOf(entry.origin, credentialsOf(dir, entry.origin));
53
+ let marked = null;
54
+ try {
55
+ // The pair's removal and the entry's mark are one step (git-host-10).
56
+ await client.signOut(() => {
57
+ try {
58
+ updateHomeFile(dir, (current) => withSignOut(current, entry.origin));
59
+ }
60
+ catch (error) {
61
+ marked = error;
62
+ }
63
+ });
64
+ }
65
+ catch (error) {
66
+ if (error instanceof CredentialChanged)
67
+ throw new Refusal(`your sign-in at ${name} changed meanwhile — spex logout again`);
68
+ throw new Refusal(`not signed out at ${name}: ${hostCause(error, name, "spex logout again")}`);
69
+ }
70
+ if (marked)
71
+ throw new Refusal(`signed out at ${name}, but home.yaml was not updated: ${marked.message} — spex logout again`);
72
+ console.log(`Signed out at ${name}.`);
73
+ };
74
+ //# sourceMappingURL=logout.js.map
@@ -0,0 +1,2 @@
1
+ import { type Command } from "./run.js";
2
+ export declare const publish: Command;
@@ -0,0 +1,120 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ // `spex publish [<org>/<pkg>] [--dry-run]` (cli-9, environments-10):
4
+ // publish a package's folder — the folder `spex.yaml` adds that name
5
+ // from, else `spex-packages/<org>/<pkg>/` under the root, and with no
6
+ // name the one package under `spex-packages/` — to this folder's
7
+ // registry as the account signed in there for publishing. It says what
8
+ // it publishes to which registry, by the registry's name (cli-22); a dry
9
+ // run lists the declared files and publishes nothing; a publish prints
10
+ // the package's page at the registry. Every refusal comes before
11
+ // anything is sent.
12
+ import { readdirSync } from "node:fs";
13
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
14
+ import { FormatError, isPackageName, isPathRequest, packageNameRefusal, publishIssues, publishRelease, readRelease, } from "../lib/environment/index.js";
15
+ import { Environment, isDirectory } from "./environment.js";
16
+ import { parsed, Refusal } from "./run.js";
17
+ /** Every package folder under `spex-packages/`: `<org>/<pkg>` names of
18
+ * the folders two levels down holding `meta.yaml`. */
19
+ function developed(root) {
20
+ const out = [];
21
+ const base = join(root, "spex-packages");
22
+ const entries = (dir) => {
23
+ try {
24
+ return readdirSync(dir).filter((entry) => !entry.startsWith(".") && isDirectory(join(dir, entry))).sort();
25
+ }
26
+ catch {
27
+ return [];
28
+ }
29
+ };
30
+ for (const org of entries(base)) {
31
+ for (const pkg of entries(join(base, org))) {
32
+ if (isPackageName(`${org}/${pkg}`))
33
+ out.push(`${org}/${pkg}`);
34
+ }
35
+ }
36
+ return out;
37
+ }
38
+ const issuesText = (issues) => issues.map((issue) => (issue.path ? `${issue.path}: ${issue.message}` : issue.message)).join("; ");
39
+ export const publish = async (args) => {
40
+ const { values, positionals } = parsed("publish", args, { "dry-run": { type: "boolean" } }, { min: 0, max: 1 });
41
+ const dryRun = values["dry-run"] === true;
42
+ const env = new Environment();
43
+ const read = env.readRequests();
44
+ let name = positionals[0];
45
+ if (name === undefined) {
46
+ const found = developed(env.root);
47
+ if (found.length === 0)
48
+ throw new Refusal("no package in spex-packages/ here — spex export <org>/<pkg> --spec <file> | --skill <folder> builds one");
49
+ if (found.length > 1)
50
+ throw new Refusal(`spex-packages/ holds ${found.length} packages: ${found.join(", ")} — name one: spex publish <org>/<pkg>`);
51
+ name = found[0];
52
+ }
53
+ if (!isPackageName(name))
54
+ throw new Refusal(packageNameRefusal(name));
55
+ // The folder: the one spex.yaml adds that name from, else
56
+ // spex-packages/<org>/<pkg>/ under the root (environments-10).
57
+ const request = read?.requests.packages[name];
58
+ const path = request !== undefined && isPathRequest(request) ? request.path : `spex-packages/${name}`;
59
+ const folder = resolve(env.root, path);
60
+ const inside = relative(env.root, folder);
61
+ if (inside === "" || isAbsolute(inside) || inside.split(sep).includes(".."))
62
+ throw new Refusal(`${path} lies outside this project folder, ${env.root} — keep the package inside it`);
63
+ if (!isDirectory(folder))
64
+ throw new Refusal(`no folder for ${name} at ${path} — spex export ${name} --spec <file> | --skill <folder> builds one`);
65
+ // The registry: this folder's, as the account signed in
66
+ // there for publishing (environments-10, DR-168), named by its own
67
+ // display name, never a Space entry's (cli-22).
68
+ const target = env.registryOf(read?.requests ?? null);
69
+ const instance = target.origin;
70
+ const registryName = await env.registryName(instance);
71
+ const signedIn = (await env.tokenAt(instance, "registry").catch(() => "")) !== null;
72
+ if (!dryRun && !signedIn) {
73
+ // `spex login` from this folder signs in at its registry for
74
+ // publishing (cli-10).
75
+ throw new Refusal(`not signed in at ${registryName} to publish — spex login, then retry`);
76
+ }
77
+ let manifest;
78
+ let files;
79
+ try {
80
+ const release = await readRelease(folder);
81
+ manifest = release.manifest;
82
+ files = release.files.map((file) => file.path).sort();
83
+ }
84
+ catch (error) {
85
+ if (error instanceof FormatError)
86
+ throw new Refusal(`${path} is not a package: ${issuesText(error.issues)} — fix it, then retry`);
87
+ throw new Refusal(error instanceof Error ? error.message : String(error));
88
+ }
89
+ const held = `${manifest.org}/${manifest.name}`;
90
+ if (held !== name)
91
+ throw new Refusal(`${path} holds ${held}, not ${name} — fix the name in its meta.yaml, or publish ${held}`);
92
+ const missing = publishIssues(manifest);
93
+ if (missing.length > 0)
94
+ throw new Refusal(`${path} cannot be published: ${issuesText(missing)} — add it to its meta.yaml`);
95
+ if (signedIn) {
96
+ try {
97
+ await env.registryClientAt(instance).checkPublishOrg(held);
98
+ }
99
+ catch (error) {
100
+ throw await env.registryRefusal(error, { origin: instance, scope: "registry", operation: "publish", version: manifest.version });
101
+ }
102
+ }
103
+ console.log(`Publishing ${held}@${manifest.version} to ${registryName}`);
104
+ if (dryRun) {
105
+ if (!signedIn)
106
+ console.log(`Org not checked — sign in to ${registryName} with spex login to check publishing rights`);
107
+ console.log(["Files (dry run, nothing published):", ...files.map((file) => ` ${file}`)].join("\n"));
108
+ return;
109
+ }
110
+ const registry = env.registryAt(instance, "registry");
111
+ try {
112
+ await publishRelease(registry, folder);
113
+ }
114
+ catch (error) {
115
+ throw await env.registryRefusal(error, { origin: instance, scope: "registry", operation: "publish", version: manifest.version });
116
+ }
117
+ // The package's page at the registry.
118
+ console.log(`Published: ${registry.url}/${held}`);
119
+ };
120
+ //# sourceMappingURL=publish.js.map
@@ -0,0 +1,2 @@
1
+ import { type Command } from "./run.js";
2
+ export declare const remove: Command;
@@ -0,0 +1,34 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ // `spex remove <org>/<pkg>`, or `spex rm` (cli-3, environments-15): take
4
+ // the package out of `spex.yaml`, resolve, install and export what
5
+ // remains, and print each package removed, an edited copy of its spec
6
+ // left in `specs/` as the project's own and read as edited, in the words
7
+ // `spex list` uses (environments-41, DR-172). A package
8
+ // `spex.yaml` does not add is refused before any write; the built-in
9
+ // one is removed as any other (DR-176).
10
+ import { RequestsError, setRequest } from "../lib/environment/index.js";
11
+ import { VersionConflictError } from "../lib/files.js";
12
+ import { settleAndTell } from "./add.js";
13
+ import { Environment, shown } from "./environment.js";
14
+ import { parsed, Refusal } from "./run.js";
15
+ export const remove = async (args) => {
16
+ const { positionals } = parsed("remove", args, {}, { min: 1, max: 1 });
17
+ const name = positionals[0];
18
+ const env = new Environment();
19
+ const read = env.readRequests();
20
+ if (!read || !Object.hasOwn(read.requests.packages, name))
21
+ throw new Refusal(`${name} is not in spex.yaml — spex list shows what is added`);
22
+ try {
23
+ await setRequest(env.requestsFile, name, null);
24
+ }
25
+ catch (error) {
26
+ if (error instanceof VersionConflictError)
27
+ throw new Refusal(`${shown(env.root, error.file)} changed meanwhile — retry`);
28
+ if (error instanceof RequestsError)
29
+ throw new Refusal(`${error.message} — fix the file, then retry`);
30
+ throw error;
31
+ }
32
+ await settleAndTell(env);
33
+ };
34
+ //# sourceMappingURL=remove.js.map
@@ -0,0 +1,50 @@
1
+ import { type ParseArgsConfig } from "node:util";
2
+ /** The usage, as cli-21 writes it. */
3
+ export declare const USAGE = "Usage: spex <command> [options]\n\nPackages in this folder (spex.yaml, spex.lock, .spex/)\n add <org>/<pkg>[@<version>] Add a package (newest by default)\n add <org>/<pkg> --path <folder> Add a package from a folder in this project\n remove, rm <org>/<pkg> Remove a package\n install, i Install what spex.lock records\n update Update to the newest versions spex.yaml allows\n list, ls What is added, installed, and placed for your agents\n search <query> Find packages at the registry\n\nYour packages\n export <org>/<pkg> [--spec <file>] [--skill <folder>]\u2026 Build it in spex-packages/<org>/<pkg>/ from your files\n publish [<org>/<pkg>] [--dry-run] Publish it to the registry\n\nSign-in\n login [--registry <url> | --space <url>] Sign in with a code in your browser\n logout [--registry <url> | --space <url>] Sign out\n whoami [--registry <url> | --space <url>] Who you are signed in as, and where\n\nSpecs\n scaffold [<path> | --update] Start specs/ and point your agents at it\n lint [<path>] Check specs/ for structure, IDs and citations\n\nspex --version \u00B7 spex <command> --help \u00B7 Home: $SPEX_HOME or ~/.spex";
4
+ /** The command a word of the command line names, by its own name or an
5
+ * alias, if any. */
6
+ export declare function commandNamed(word: string): string | undefined;
7
+ /** A command's help: its one-line usage, its lines of the usage and
8
+ * every option it takes (cli-21); none for a word naming no command. */
9
+ export declare function commandHelp(word: string): string | undefined;
10
+ /** A refusal of how a command was called: the cause, then the
11
+ * command's one-line usage (cli-13, cli-21). */
12
+ export declare function misuse(name: string, cause: string): Refusal;
13
+ type Spec = NonNullable<ParseArgsConfig["options"]>;
14
+ /** What a command's option `--<key>` needs as its value, in words. */
15
+ export declare function needs(name: string, key: string): string;
16
+ /** A refusal or failure the reader is told about, in the CLI's words. */
17
+ export declare class Refusal extends Error {
18
+ constructor(message: string);
19
+ }
20
+ /** The command was interrupted while it waited. */
21
+ export declare class Interrupted extends Error {
22
+ constructor(message?: string);
23
+ }
24
+ /** How a command meets an interrupt: while a hook is registered, an
25
+ * interrupt calls it in place of ending the process, so the command
26
+ * cancels what it waits on and ends itself; with none, the process ends
27
+ * at once, 130. */
28
+ export interface Interrupt {
29
+ /** Whether an interrupt arrived. */
30
+ readonly requested: boolean;
31
+ /** Register `hook` until the returned release is called. */
32
+ hold(hook: () => void): () => void;
33
+ }
34
+ export type Command = (args: string[], interrupt: Interrupt) => Promise<void>;
35
+ /** A command's own options, parsed strictly: an unknown option or a
36
+ * stray argument refuses the command with its one-line usage. */
37
+ export declare function options<T extends Spec>(name: string, args: string[], spec: T): T extends import("node:util").ParseArgsOptionsConfig ? { -readonly [LongOption in keyof T]?: { [LongOption_1 in keyof T]: T[LongOption_1]["multiple"] extends infer T_1 ? T_1 extends T[LongOption_1]["multiple"] ? T_1 extends false ? T[LongOption_1]["type"] extends "string" ? string : T[LongOption_1]["type"] extends "boolean" ? boolean : string | boolean : T_1 extends true ? (T[LongOption_1]["type"] extends "string" ? string : T[LongOption_1]["type"] extends "boolean" ? boolean : string | boolean)[] : T[LongOption_1]["type"] extends "string" ? string : T[LongOption_1]["type"] extends "boolean" ? boolean : string | boolean : never : never; }[LongOption] | undefined; } & { [LongOption in keyof T as T[LongOption]["default"] extends {} ? LongOption : never]: { [LongOption_1 in keyof T]: T[LongOption_1]["multiple"] extends infer T_1 ? T_1 extends T[LongOption_1]["multiple"] ? T_1 extends false ? T[LongOption_1]["type"] extends "string" ? string : T[LongOption_1]["type"] extends "boolean" ? boolean : string | boolean : T_1 extends true ? (T[LongOption_1]["type"] extends "string" ? string : T[LongOption_1]["type"] extends "boolean" ? boolean : string | boolean)[] : T[LongOption_1]["type"] extends "string" ? string : T[LongOption_1]["type"] extends "boolean" ? boolean : string | boolean : never : never; }[LongOption]; } extends infer P ? { [K in keyof P]: P[K]; } : never : {};
38
+ /** A command's options and its words, parsed strictly: an unknown
39
+ * option, or fewer or more words than it takes, refuses the command
40
+ * with its one-line usage. */
41
+ export declare function parsed<T extends Spec>(name: string, args: string[], spec: T, words: {
42
+ min: number;
43
+ max: number;
44
+ }): {
45
+ values: T extends import("node:util").ParseArgsOptionsConfig ? { -readonly [LongOption in keyof T]?: { [LongOption_1 in keyof T]: T[LongOption_1]["multiple"] extends infer T_1 ? T_1 extends T[LongOption_1]["multiple"] ? T_1 extends false ? T[LongOption_1]["type"] extends "string" ? string : T[LongOption_1]["type"] extends "boolean" ? boolean : string | boolean : T_1 extends true ? (T[LongOption_1]["type"] extends "string" ? string : T[LongOption_1]["type"] extends "boolean" ? boolean : string | boolean)[] : T[LongOption_1]["type"] extends "string" ? string : T[LongOption_1]["type"] extends "boolean" ? boolean : string | boolean : never : never; }[LongOption] | undefined; } & { [LongOption in keyof T as T[LongOption]["default"] extends {} ? LongOption : never]: { [LongOption_1 in keyof T]: T[LongOption_1]["multiple"] extends infer T_1 ? T_1 extends T[LongOption_1]["multiple"] ? T_1 extends false ? T[LongOption_1]["type"] extends "string" ? string : T[LongOption_1]["type"] extends "boolean" ? boolean : string | boolean : T_1 extends true ? (T[LongOption_1]["type"] extends "string" ? string : T[LongOption_1]["type"] extends "boolean" ? boolean : string | boolean)[] : T[LongOption_1]["type"] extends "string" ? string : T[LongOption_1]["type"] extends "boolean" ? boolean : string | boolean : never : never; }[LongOption]; } extends infer P ? { [K in keyof P]: P[K]; } : never : {};
46
+ positionals: string[];
47
+ };
48
+ /** Run one command to its exit code, printing a cause on standard error. */
49
+ export declare function runCommand(name: string, command: Command, args: string[]): Promise<number>;
50
+ export {};
@@ -0,0 +1,309 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ // The runner of the package commands (cli-13, DR-165): a command's
4
+ // success exits 0; a refusal or failure prints its cause on standard
5
+ // error and exits 1; an interrupt exits 130 once whatever the command
6
+ // was waiting on is cancelled. A command prints no secret: it names
7
+ // accounts, registries, Spaces and the device flow's user code, never
8
+ // a token.
9
+ //
10
+ // It also holds the usage and each command's help (cli-21, DR-172):
11
+ // a refusal of how a command was called names the cause in the CLI's
12
+ // words, never Node's, followed by the command's one-line usage.
13
+ import { parseArgs } from "node:util";
14
+ import { AGENT_TARGETS } from "../append-agent-specs.js";
15
+ import { SUPPORTED_LANGUAGES } from "../copy-templates.js";
16
+ /** The usage, as cli-21 writes it. */
17
+ export const USAGE = `Usage: spex <command> [options]
18
+
19
+ Packages in this folder (spex.yaml, spex.lock, .spex/)
20
+ add <org>/<pkg>[@<version>] Add a package (newest by default)
21
+ add <org>/<pkg> --path <folder> Add a package from a folder in this project
22
+ remove, rm <org>/<pkg> Remove a package
23
+ install, i Install what spex.lock records
24
+ update Update to the newest versions spex.yaml allows
25
+ list, ls What is added, installed, and placed for your agents
26
+ search <query> Find packages at the registry
27
+
28
+ Your packages
29
+ export <org>/<pkg> [--spec <file>] [--skill <folder>]… Build it in spex-packages/<org>/<pkg>/ from your files
30
+ publish [<org>/<pkg>] [--dry-run] Publish it to the registry
31
+
32
+ Sign-in
33
+ login [--registry <url> | --space <url>] Sign in with a code in your browser
34
+ logout [--registry <url> | --space <url>] Sign out
35
+ whoami [--registry <url> | --space <url>] Who you are signed in as, and where
36
+
37
+ Specs
38
+ scaffold [<path> | --update] Start specs/ and point your agents at it
39
+ lint [<path>] Check specs/ for structure, IDs and citations
40
+
41
+ spex --version · spex <command> --help · Home: $SPEX_HOME or ~/.spex`;
42
+ const AGENTS = AGENT_TARGETS.flatMap((target) => target.agents).sort();
43
+ /** "a or b", "a, b or c". */
44
+ function either(words) {
45
+ return words.length < 2 ? words.join("") : `${words.slice(0, -1).join(", ")} or ${words.at(-1)}`;
46
+ }
47
+ /** Each command's help, under its own name (cli-21). */
48
+ const HELP = {
49
+ add: {
50
+ usage: "spex add <org>/<pkg>[@<version>] | <org>/<pkg> --path <folder>",
51
+ words: "<org>/<pkg>",
52
+ options: [["--path <folder>", "Add the package in this folder of the project", "a folder"]],
53
+ },
54
+ remove: { usage: "spex remove <org>/<pkg>", words: "<org>/<pkg>", options: [] },
55
+ install: { usage: "spex install", options: [] },
56
+ update: { usage: "spex update", options: [] },
57
+ list: { usage: "spex list", options: [] },
58
+ search: { usage: "spex search <query>", words: "<query>", options: [] },
59
+ export: {
60
+ usage: "spex export <org>/<pkg> [--spec <file>] [--skill <folder>]… [options]",
61
+ words: "<org>/<pkg>",
62
+ options: [
63
+ ["--spec <file>", "Your spec file to build it from, named <pkg>.md", "a file"],
64
+ ["--skill <folder>", "Your skill folder to build it from; repeat for more", "a folder"],
65
+ ["--language <tag>", "The language of what it adds (en by default)", "a language tag"],
66
+ ["--description <text>", "What it is for, on a first export (by default from its first skill, else its spec)", "a description"],
67
+ ["--license <id>", "Its license, on a first export (by default from this project's LICENSE, else Apache-2.0)", "a license id"],
68
+ ],
69
+ },
70
+ publish: {
71
+ usage: "spex publish [<org>/<pkg>] [--dry-run]",
72
+ options: [["--dry-run", "List the files it would publish, and publish nothing"]],
73
+ },
74
+ login: {
75
+ usage: "spex login [--registry <url> | --space <url>] [--force]",
76
+ options: [
77
+ ["--registry <url>", "Sign in at this registry, not this folder's", "a URL"],
78
+ ["--space <url>", "Sign in at this Space", "a URL"],
79
+ ["--force", "Sign in again where already signed in"],
80
+ ],
81
+ },
82
+ logout: {
83
+ usage: "spex logout [--registry <url> | --space <url>]",
84
+ options: [
85
+ ["--registry <url>", "Sign out at this registry, not this folder's", "a URL"],
86
+ ["--space <url>", "Sign out at this Space", "a URL"],
87
+ ],
88
+ },
89
+ whoami: {
90
+ usage: "spex whoami [--registry <url> | --space <url>]",
91
+ options: [
92
+ ["--registry <url>", "Show this registry alone", "a URL"],
93
+ ["--space <url>", "Show this Space alone", "a URL"],
94
+ ],
95
+ },
96
+ scaffold: {
97
+ usage: "spex scaffold [<path> | --update] [--lang <code>] [--agents <names>]",
98
+ options: [
99
+ ["<path>", "The folder to create it in (the Git repository's top level by default)"],
100
+ ["--update", "Refresh the templates of this repository's specs/"],
101
+ ["--lang <code>", `The language of the specs: ${either(SUPPORTED_LANGUAGES)}`],
102
+ ["--agents <names>", `The agents to point at specs/, separated by commas: ${AGENTS.join(", ")}, or all`],
103
+ ],
104
+ },
105
+ lint: {
106
+ usage: "spex lint [<path>]",
107
+ options: [["<path>", "The folder holding specs/ (the Git repository's top level by default)"]],
108
+ },
109
+ };
110
+ /** The aliases the usage names beside a command. */
111
+ const ALIASES = { rm: "remove", i: "install", ls: "list" };
112
+ /** The command a word of the command line names, by its own name or an
113
+ * alias, if any. */
114
+ export function commandNamed(word) {
115
+ if (Object.hasOwn(HELP, word))
116
+ return word;
117
+ return Object.hasOwn(ALIASES, word) ? ALIASES[word] : undefined;
118
+ }
119
+ /** The commands a usage line names: its leading words, up to its first
120
+ * argument. */
121
+ function namesOf(line) {
122
+ const names = [];
123
+ for (const word of line.trim().split(/\s{2,}/)[0].split(" ")) {
124
+ if (!/^[a-z]+,?$/.test(word))
125
+ break;
126
+ names.push(word.replace(",", ""));
127
+ }
128
+ return names;
129
+ }
130
+ /** A command's lines of the usage, under their heading. */
131
+ function usageLinesOf(name) {
132
+ const lines = USAGE.split("\n").slice(1, -1);
133
+ let heading = "";
134
+ const found = [];
135
+ for (const line of lines) {
136
+ if (line === "")
137
+ continue;
138
+ if (!line.startsWith(" "))
139
+ heading = line;
140
+ else if (namesOf(line).includes(name)) {
141
+ if (found.length === 0)
142
+ found.push(heading);
143
+ found.push(line);
144
+ }
145
+ }
146
+ return found;
147
+ }
148
+ /** A command's help: its one-line usage, its lines of the usage and
149
+ * every option it takes (cli-21); none for a word naming no command. */
150
+ export function commandHelp(word) {
151
+ const name = commandNamed(word);
152
+ if (name === undefined)
153
+ return undefined;
154
+ const help = HELP[name];
155
+ const rows = [...help.options, ["-h, --help", "Show this help"]];
156
+ const width = Math.max(...rows.map(([label]) => label.length)) + 2;
157
+ return [
158
+ `Usage: ${help.usage}`,
159
+ "",
160
+ ...usageLinesOf(name),
161
+ "",
162
+ "Options",
163
+ ...rows.map(([label, text]) => ` ${label.padEnd(width)}${text}`),
164
+ ].join("\n");
165
+ }
166
+ /** A refusal of how a command was called: the cause, then the
167
+ * command's one-line usage (cli-13, cli-21). */
168
+ export function misuse(name, cause) {
169
+ const command = commandNamed(name);
170
+ return new Refusal(command === undefined ? cause : `${cause}\nUsage: ${HELP[command].usage}`);
171
+ }
172
+ /** What a command's option `--<key>` needs as its value, in words. */
173
+ export function needs(name, key) {
174
+ const command = commandNamed(name);
175
+ const option = command === undefined ? undefined : HELP[command].options.find(([label]) => label.split(" ")[0] === `--${key}`);
176
+ return option?.[2] ?? "a value";
177
+ }
178
+ /** Why `parseArgs` refused `args`, in the CLI's words: the first
179
+ * argument it could not take, read by the same rules. */
180
+ function parseCause(name, args, spec, positionals) {
181
+ const shorts = new Map(Object.entries(spec).flatMap(([key, option]) => (option.short === undefined ? [] : [[option.short, key]])));
182
+ for (let i = 0; i < args.length; i++) {
183
+ const arg = args[i];
184
+ if (arg === "--") {
185
+ if (!positionals && i + 1 < args.length)
186
+ return `unexpected argument ${args[i + 1]}`;
187
+ break;
188
+ }
189
+ if (arg === "-" || !arg.startsWith("-")) {
190
+ if (!positionals)
191
+ return `unexpected argument ${arg}`;
192
+ continue;
193
+ }
194
+ const equals = arg.indexOf("=");
195
+ const shown = arg.startsWith("--") && equals >= 0 ? arg.slice(0, equals) : arg;
196
+ const key = arg.startsWith("--") ? shown.slice(2) : shorts.get(arg.slice(1));
197
+ if (key === undefined || !Object.hasOwn(spec, key))
198
+ return `unknown option ${shown}`;
199
+ const inline = shown !== arg;
200
+ if (spec[key].type === "boolean") {
201
+ if (inline)
202
+ return `${shown} takes no value`;
203
+ continue;
204
+ }
205
+ if (inline)
206
+ continue;
207
+ const next = args[i + 1];
208
+ if (next === undefined || (next.length > 1 && next.startsWith("-")))
209
+ return `${shown} needs ${needs(name, key)}`;
210
+ i++;
211
+ }
212
+ return "cannot read these options";
213
+ }
214
+ /** Refuse an option given an empty value, as one given none. */
215
+ function refuseEmpty(name, values, spec) {
216
+ for (const [key, value] of Object.entries(values)) {
217
+ if (spec[key]?.type === "string" && (value === "" || (Array.isArray(value) && value.includes("")))) {
218
+ throw misuse(name, `--${key} needs ${needs(name, key)}`);
219
+ }
220
+ }
221
+ }
222
+ /** A refusal or failure the reader is told about, in the CLI's words. */
223
+ export class Refusal extends Error {
224
+ constructor(message) {
225
+ super(message);
226
+ this.name = "Refusal";
227
+ }
228
+ }
229
+ /** The command was interrupted while it waited. */
230
+ export class Interrupted extends Error {
231
+ constructor(message = "interrupted") {
232
+ super(message);
233
+ this.name = "Interrupted";
234
+ }
235
+ }
236
+ /** A command's own options, parsed strictly: an unknown option or a
237
+ * stray argument refuses the command with its one-line usage. */
238
+ export function options(name, args, spec) {
239
+ const parse = () => parseArgs({ args, options: spec, strict: true, allowPositionals: false });
240
+ let result;
241
+ try {
242
+ result = parse();
243
+ }
244
+ catch {
245
+ throw misuse(name, parseCause(name, args, spec, false));
246
+ }
247
+ refuseEmpty(name, result.values, spec);
248
+ return result.values;
249
+ }
250
+ /** A command's options and its words, parsed strictly: an unknown
251
+ * option, or fewer or more words than it takes, refuses the command
252
+ * with its one-line usage. */
253
+ export function parsed(name, args, spec, words) {
254
+ let result;
255
+ try {
256
+ result = parseArgs({ args, options: spec, strict: true, allowPositionals: true });
257
+ }
258
+ catch {
259
+ throw misuse(name, parseCause(name, args, spec, true));
260
+ }
261
+ refuseEmpty(name, result.values, spec);
262
+ const { positionals } = result;
263
+ if (positionals.length > words.max)
264
+ throw misuse(name, `unexpected argument ${positionals[words.max]}`);
265
+ if (positionals.length < words.min) {
266
+ const command = commandNamed(name);
267
+ throw misuse(name, `missing ${(command === undefined ? undefined : HELP[command].words) ?? "an argument"}`);
268
+ }
269
+ return { values: result.values, positionals };
270
+ }
271
+ /** Run one command to its exit code, printing a cause on standard error. */
272
+ export async function runCommand(name, command, args) {
273
+ const hooks = new Set();
274
+ let requested = false;
275
+ const interrupt = {
276
+ get requested() { return requested; },
277
+ hold(hook) {
278
+ hooks.add(hook);
279
+ return () => { hooks.delete(hook); };
280
+ },
281
+ };
282
+ const onSignal = () => {
283
+ requested = true;
284
+ if (hooks.size === 0) {
285
+ process.stderr.write(`spex ${name}: interrupted\n`);
286
+ process.exit(130);
287
+ }
288
+ for (const hook of [...hooks])
289
+ hook();
290
+ };
291
+ process.on("SIGINT", onSignal);
292
+ try {
293
+ await command(args, interrupt);
294
+ return 0;
295
+ }
296
+ catch (error) {
297
+ if (error instanceof Interrupted) {
298
+ process.stderr.write(`spex ${name}: ${error.message}\n`);
299
+ return 130;
300
+ }
301
+ const message = error instanceof Error ? error.message : String(error);
302
+ process.stderr.write(`spex ${name}: ${message}\n`);
303
+ return 1;
304
+ }
305
+ finally {
306
+ process.off("SIGINT", onSignal);
307
+ }
308
+ }
309
+ //# sourceMappingURL=run.js.map
@@ -0,0 +1,2 @@
1
+ import { type Command } from "./run.js";
2
+ export declare const search: Command;
@@ -0,0 +1,34 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ // `spex search <query>` (cli-7, environments-12): ask this folder's
4
+ // registry, presenting its sign-in as resolving does, for the packages
5
+ // matching the query, and print each with its description and versions,
6
+ // newest first.
7
+ import { compareVersions, isVersion } from "../lib/environment/index.js";
8
+ import { Environment } from "./environment.js";
9
+ import { parsed } from "./run.js";
10
+ export const search = async (args) => {
11
+ const { positionals } = parsed("search", args, {}, { min: 1, max: Infinity });
12
+ const query = positionals.join(" ");
13
+ const env = new Environment();
14
+ const target = env.registryOf(env.readRequests()?.requests ?? null);
15
+ let found;
16
+ try {
17
+ found = await env.registryAt(target.origin, target.scope).search(query);
18
+ }
19
+ catch (error) {
20
+ throw await env.registryRefusal(error, { origin: target.origin, scope: target.scope });
21
+ }
22
+ if (found.length === 0) {
23
+ console.log(`No package at ${await env.registryName(target.origin)} matches "${query}"`);
24
+ return;
25
+ }
26
+ const lines = [];
27
+ for (const result of found) {
28
+ const versions = result.versions.filter(isVersion).sort((a, b) => compareVersions(b, a));
29
+ lines.push(result.description ? `${result.name} ${result.description}` : result.name);
30
+ lines.push(` ${versions.length > 0 ? versions.join(", ") : "no versions listed"}`);
31
+ }
32
+ console.log(lines.join("\n"));
33
+ };
34
+ //# sourceMappingURL=search.js.map