@ramon-sg/runner 0.0.0-stage → 1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ramón Soto
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,83 @@
1
- # Temporary Holding Version
1
+ Lee `.agents/runner.json` y arma el comando para correr cada herramienta con Bun o Node
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Una librería sin dependencias para las herramientas de `@ramon-sg` que se corren con `bunx --bun` o `npx --yes`: guarda en el repo qué runner usar y qué versión de cada herramienta, y construye el comando exacto.
4
+
5
+ ## El archivo
6
+
7
+ `.agents/runner.json` en la raíz del repo:
8
+
9
+ ```json
10
+ {
11
+ "$schema": "https://cdn.jsdelivr.net/npm/@ramon-sg/runner@1.0.0/runner.schema.json",
12
+ "runner": "bun",
13
+ "tools": {
14
+ "@ramon-sg/issue-flow": "0.6.0",
15
+ "@ramon-sg/github-rest": "0.7.0",
16
+ "@ramon-sg/skills-manager": "1.5.0",
17
+ "agent-cloud-kit": "1.0.0",
18
+ "@ramon-sg/claude-repo-guard": "0.8.0"
19
+ }
20
+ }
21
+ ```
22
+
23
+ ## La API
24
+
25
+ - `RUNNER_FILE`: la ruta del archivo, `.agents/runner.json`.
26
+ - `Runner`: el tipo `"bun" | "node"`.
27
+ - `RunnerConfig`: la forma del archivo: `runner`, `tools` y `extra` (las claves desconocidas, que se conservan al escribir).
28
+ - `RunnerFileError`: el error cuando el archivo no se puede leer o no es válido.
29
+ - `readRunnerConfig(root)`: lee el archivo del repo; devuelve `null` si no existe.
30
+ - `writeRunnerConfig(root, config)`: escribe el archivo con formato estable y de forma atómica; lanza `TypeError` si `config` no es válida.
31
+ - `effectiveRunner(config)`: el runner que se usa, con el valor por defecto si falta.
32
+ - `runnerAvailable(runner)`: si ese runner está instalado en la máquina.
33
+ - `chooseRunner({ ask })`: devuelve `"bun"` si `bunx` está disponible; si no, pregunta con `ask` si se pasó (`null` = el usuario eligió salir); sin `ask` devuelve `"node"` junto con `NO_BUN_WARNING`.
34
+ - `NO_BUN_WARNING`: el aviso que acompaña a `"node"` cuando no hay Bun.
35
+ - `setTool(config, pkg, version, { ifMissing, allowLower })`: fija la versión de una herramienta, sin bajarla salvo que se pida.
36
+ - `toolCommand(runner, pkg, version, args)`: el comando como lista de argumentos.
37
+ - `toolCommandText(runner, pkg, version, args)`: el mismo comando como texto para mostrar o poner en un script.
38
+ - `writeScripts(root, runner, scripts, owned)`: escribe los scripts de `package.json` que le pertenecen a la herramienta.
39
+ - `checkRunner(root)`: revisa que el runner del archivo esté disponible.
40
+ - `checkToolPins(root, pkg, texts)`: revisa que los textos usen la versión fijada. Los textos son comandos de hooks o scripts; la prosa de un skill es neutra en versión y no debe pasarse.
41
+ - `Check`: el resultado de una revisión.
42
+ - `VERSION`: la versión de esta librería.
43
+
44
+ ## Compatibilidad
45
+
46
+ El formato del archivo es estable en la 1.x: solo se agregan campos, y todos los campos nuevos son opcionales. Un archivo válido hoy lo seguirá siendo. Los campos desconocidos se conservan al escribir.
47
+
48
+ La 1.x funciona en macOS y Linux (shells POSIX); Windows no está soportado.
49
+
50
+ ## Desarrollo
51
+
52
+ ```sh
53
+ npm install
54
+ npm test
55
+ ```
56
+
57
+ `npm test` compila con `tsc` y corre los tests con `node --test`.
58
+
59
+ Bun corre los mismos tests de `node:test` sin cambios (probado con Bun 1.4.4, fijado en `.tool-versions`), así que no hace falta un smoke test aparte. Para correrlos con Bun hay que compilar antes:
60
+
61
+ ```sh
62
+ npx tsc && bun test --timeout 20000 test/
63
+ ```
64
+
65
+ `--timeout 20000` sube el límite de 5 s por test que trae `bun test`: los tests que lanzan procesos (`npm pack`, ejecutables falsos) pueden pasarlo en una máquina cargada.
66
+
67
+ CI corre los dos: el job `node` con `npm test` y el job `bun` con ese comando (`.github/workflows/test.yml`).
68
+
69
+ ## Publicar una versión
70
+
71
+ Una versión es una release `vX.Y.Z` en GitHub, con el mismo número que `package.json`. Al publicarla, GitHub Actions corre los tests y publica en npm con procedencia (`.github/workflows/publish.yml`).
72
+
73
+ La primera versión va a mano, porque npm solo deja configurar la publicación desde GitHub en un paquete que ya existe:
74
+
75
+ 1. `npm login` y, desde `main`, `npm publish --access public --provenance=false`.
76
+ 2. En npmjs.com, en el paquete, Settings → Trusted publishing: GitHub Actions, repo `ramon-sg/runner`, workflow `publish.yml`.
77
+ 3. Pushear la tag de esa versión sin crear una release: una release volvería a publicar la misma versión y fallaría.
78
+
79
+ Antes de publicar, subir el número en tres lugares: `version` en `package.json`, `VERSION` en `src/version.ts` y el ejemplo de `$schema` de este README.
80
+
81
+ ## Licencia
82
+
83
+ MIT
@@ -0,0 +1,12 @@
1
+ export interface Check {
2
+ name: string;
3
+ status: "ok" | "warn" | "fail";
4
+ detail: string;
5
+ }
6
+ /** Checks that `.agents/runner.json` exists, is valid, and its runner is installed. */
7
+ export declare function checkRunner(root: string): Check[];
8
+ /**
9
+ * Checks that every command text naming `pkg` pins the version in `runner.json`.
10
+ * The texts are hook or script commands; skill prose is version-neutral and must not be passed.
11
+ */
12
+ export declare function checkToolPins(root: string, pkg: string, texts: string[]): Check[];
package/dist/checks.js ADDED
@@ -0,0 +1,85 @@
1
+ import { RUNNER_FILE, RunnerFileError, effectiveRunner, readRunnerConfig } from "./config.js";
2
+ import { runnerAvailable } from "./choose.js";
3
+ const NAME = "runner";
4
+ function check(status, detail) {
5
+ return { name: NAME, status, detail };
6
+ }
7
+ function read(root) {
8
+ try {
9
+ return { config: readRunnerConfig(root) };
10
+ }
11
+ catch (err) {
12
+ if (err instanceof RunnerFileError)
13
+ return { error: err.message };
14
+ throw err;
15
+ }
16
+ }
17
+ /** Checks that `.agents/runner.json` exists, is valid, and its runner is installed. */
18
+ export function checkRunner(root) {
19
+ const result = read(root);
20
+ if ("error" in result)
21
+ return [check("fail", result.error)];
22
+ if (result.config === null)
23
+ return [check("warn", `${RUNNER_FILE} is missing`)];
24
+ const runner = effectiveRunner(result.config);
25
+ const exe = runner === "bun" ? "bunx" : "npx";
26
+ if (runnerAvailable(runner))
27
+ return [check("ok", `runner "${runner}" (${exe} is available)`)];
28
+ const install = runner === "bun" ? "Bun" : "Node.js (npx)";
29
+ return [check("fail", `runner "${runner}" needs ${exe}, which is not available: install ${install}`)];
30
+ }
31
+ const PACKAGE_CHAR = /[a-z0-9\-._~/]/;
32
+ const VERSION_CHAR = /[0-9A-Za-z\-.+]/;
33
+ /** Each occurrence of `pkg` in `text` that is not the prefix of a longer package name. */
34
+ function occurrences(text, pkg) {
35
+ const found = [];
36
+ let from = 0;
37
+ for (;;) {
38
+ const at = text.indexOf(pkg, from);
39
+ if (at === -1)
40
+ return found;
41
+ const prev = text[at - 1];
42
+ const next = text[at + pkg.length];
43
+ const startsName = prev === undefined || !(PACKAGE_CHAR.test(prev) || prev === "@");
44
+ if (startsName && (next === undefined || !PACKAGE_CHAR.test(next)))
45
+ found.push(at);
46
+ from = at + 1;
47
+ }
48
+ }
49
+ /**
50
+ * Checks that every command text naming `pkg` pins the version in `runner.json`.
51
+ * The texts are hook or script commands; skill prose is version-neutral and must not be passed.
52
+ */
53
+ export function checkToolPins(root, pkg, texts) {
54
+ const result = read(root);
55
+ if ("error" in result)
56
+ return [check("fail", result.error)];
57
+ if (result.config === null)
58
+ return [check("fail", `${RUNNER_FILE} is missing`)];
59
+ const pinned = Object.hasOwn(result.config.tools, pkg) ? result.config.tools[pkg] : undefined;
60
+ if (pinned === undefined)
61
+ return [check("fail", `${pkg} has no entry in "tools" of ${RUNNER_FILE}`)];
62
+ const expected = `${pkg}@${pinned}`;
63
+ const fails = [];
64
+ for (const text of texts) {
65
+ const at = occurrences(text, pkg);
66
+ const bad = at.some((i) => {
67
+ if (!text.startsWith(expected, i))
68
+ return true;
69
+ const after = text[i + expected.length];
70
+ if (after === undefined || !VERSION_CHAR.test(after))
71
+ return false;
72
+ // A `.` ends the version unless another version character follows it.
73
+ if (after === ".") {
74
+ const further = text[i + expected.length + 1];
75
+ return further !== undefined && VERSION_CHAR.test(further);
76
+ }
77
+ return true;
78
+ });
79
+ if (bad)
80
+ fails.push(check("fail", `${pkg} is not pinned to ${pinned} in: ${text}`));
81
+ }
82
+ if (fails.length > 0)
83
+ return fails;
84
+ return [check("ok", `${pkg} is pinned to ${pinned} everywhere`)];
85
+ }
@@ -0,0 +1,15 @@
1
+ import type { Runner } from "./config.js";
2
+ export declare const NO_BUN_WARNING = "Bun is not installed: the tools will run with Node (npx). Install Bun and set \"runner\": \"bun\" in .agents/runner.json to change it.";
3
+ /** Whether the executable behind a runner (`bunx` or `npx`) is installed and runs. */
4
+ export declare function runnerAvailable(runner: Runner): boolean;
5
+ /**
6
+ * The runner for a new file: Bun when installed. Without Bun, `ask` decides
7
+ * (`null` means the user declined); with no `ask`, falls back to Node with a
8
+ * warning. Never reads stdin itself.
9
+ */
10
+ export declare function chooseRunner(options: {
11
+ ask?: () => Promise<Runner | null>;
12
+ }): Promise<{
13
+ runner: Runner;
14
+ warning: string | null;
15
+ } | null>;
package/dist/choose.js ADDED
@@ -0,0 +1,23 @@
1
+ import { spawnSync } from "node:child_process";
2
+ export const NO_BUN_WARNING = 'Bun is not installed: the tools will run with Node (npx). Install Bun and set "runner": "bun" in .agents/runner.json to change it.';
3
+ /** Whether the executable behind a runner (`bunx` or `npx`) is installed and runs. */
4
+ export function runnerAvailable(runner) {
5
+ const result = spawnSync(runner === "bun" ? "bunx" : "npx", ["--version"], {
6
+ stdio: "ignore",
7
+ timeout: 15_000,
8
+ });
9
+ return !result.error && result.status === 0;
10
+ }
11
+ /**
12
+ * The runner for a new file: Bun when installed. Without Bun, `ask` decides
13
+ * (`null` means the user declined); with no `ask`, falls back to Node with a
14
+ * warning. Never reads stdin itself.
15
+ */
16
+ export async function chooseRunner(options) {
17
+ if (runnerAvailable("bun"))
18
+ return { runner: "bun", warning: null };
19
+ if (!options.ask)
20
+ return { runner: "node", warning: NO_BUN_WARNING };
21
+ const answer = await options.ask();
22
+ return answer === null ? null : { runner: answer, warning: null };
23
+ }
@@ -0,0 +1,12 @@
1
+ import type { Runner } from "./config.js";
2
+ /**
3
+ * The executable and arguments that run a pinned tool with the given runner:
4
+ * `bunx --bun pkg@version ...` or `npx --yes pkg@version ...`.
5
+ * Does not validate `pkg` or `version`.
6
+ */
7
+ export declare function toolCommand(runner: Runner, pkg: string, version: string, args?: string[]): {
8
+ file: string;
9
+ args: string[];
10
+ };
11
+ /** The same command as one line a POSIX shell parses back into the same arguments. */
12
+ export declare function toolCommandText(runner: Runner, pkg: string, version: string, args?: string[]): string;
@@ -0,0 +1,23 @@
1
+ const SAFE_ARGUMENT = /^[A-Za-z0-9_@%+:,./-][A-Za-z0-9_@%+=:,./-]*$/;
2
+ /** Quotes one argument for a POSIX shell, only when it needs it. */
3
+ function shellQuote(argument) {
4
+ if (SAFE_ARGUMENT.test(argument))
5
+ return argument;
6
+ return `'${argument.replaceAll("'", `'\\''`)}'`;
7
+ }
8
+ /**
9
+ * The executable and arguments that run a pinned tool with the given runner:
10
+ * `bunx --bun pkg@version ...` or `npx --yes pkg@version ...`.
11
+ * Does not validate `pkg` or `version`.
12
+ */
13
+ export function toolCommand(runner, pkg, version, args = []) {
14
+ const spec = `${pkg}@${version}`;
15
+ return runner === "bun"
16
+ ? { file: "bunx", args: ["--bun", spec, ...args] }
17
+ : { file: "npx", args: ["--yes", spec, ...args] };
18
+ }
19
+ /** The same command as one line a POSIX shell parses back into the same arguments. */
20
+ export function toolCommandText(runner, pkg, version, args = []) {
21
+ const command = toolCommand(runner, pkg, version, args);
22
+ return [command.file, ...command.args].map(shellQuote).join(" ");
23
+ }
@@ -0,0 +1,24 @@
1
+ export type Runner = "bun" | "node";
2
+ export declare const RUNNER_FILE = ".agents/runner.json";
3
+ export interface RunnerConfig {
4
+ runner: Runner | null;
5
+ tools: Record<string, string>;
6
+ extra: Record<string, unknown>;
7
+ }
8
+ export declare const SCHEMA_URL = "https://cdn.jsdelivr.net/npm/@ramon-sg/runner@1.0.0/runner.schema.json";
9
+ /** An exact semver version: release plus an optional prerelease, no build metadata. */
10
+ export declare const SEMVER: RegExp;
11
+ export declare const PACKAGE_NAME: RegExp;
12
+ export declare function isExactVersion(v: string): boolean;
13
+ export declare function isPackageName(name: string): boolean;
14
+ /** A `runner.json` that cannot be used. */
15
+ export declare class RunnerFileError extends Error {
16
+ file: string;
17
+ constructor(file: string, problem: string);
18
+ }
19
+ /** Reads `.agents/runner.json` under `root`; `null` when it does not exist. */
20
+ export declare function readRunnerConfig(root: string): RunnerConfig | null;
21
+ /** Writes `.agents/runner.json` under `root`, creating `.agents/` if needed. Throws `TypeError` on a config the reader would reject. */
22
+ export declare function writeRunnerConfig(root: string, config: RunnerConfig): void;
23
+ /** The runner to use: the configured one, or Bun by default. */
24
+ export declare function effectiveRunner(config: RunnerConfig | null): Runner;
package/dist/config.js ADDED
@@ -0,0 +1,96 @@
1
+ import { existsSync, mkdirSync, readFileSync } from "node:fs";
2
+ import { writeAtomic } from "./write.js";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { VERSION } from "./version.js";
5
+ export const RUNNER_FILE = ".agents/runner.json";
6
+ export const SCHEMA_URL = `https://cdn.jsdelivr.net/npm/@ramon-sg/runner@${VERSION}/runner.schema.json`;
7
+ /** An exact semver version: release plus an optional prerelease, no build metadata. */
8
+ export const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?$/;
9
+ export const PACKAGE_NAME = /^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;
10
+ export function isExactVersion(v) {
11
+ return SEMVER.test(v);
12
+ }
13
+ export function isPackageName(name) {
14
+ return PACKAGE_NAME.test(name);
15
+ }
16
+ /** A `runner.json` that cannot be used. */
17
+ export class RunnerFileError extends Error {
18
+ file;
19
+ constructor(file, problem) {
20
+ super(`${file}: ${problem}`);
21
+ this.name = "RunnerFileError";
22
+ this.file = file;
23
+ }
24
+ }
25
+ function isPlainObject(v) {
26
+ return typeof v === "object" && v !== null && !Array.isArray(v);
27
+ }
28
+ /** Reads `.agents/runner.json` under `root`; `null` when it does not exist. */
29
+ export function readRunnerConfig(root) {
30
+ const file = resolve(root, RUNNER_FILE);
31
+ if (!existsSync(file))
32
+ return null;
33
+ let data;
34
+ try {
35
+ data = JSON.parse(readFileSync(file, "utf8").replace(/^\uFEFF/, ""));
36
+ }
37
+ catch (err) {
38
+ throw new RunnerFileError(file, `cannot read or parse: ${err.message}`);
39
+ }
40
+ if (!isPlainObject(data))
41
+ throw new RunnerFileError(file, "must be a JSON object");
42
+ const { $schema: _schema, runner, tools, ...extra } = data;
43
+ if (runner !== undefined && runner !== "bun" && runner !== "node") {
44
+ throw new RunnerFileError(file, `"runner" must be "bun" or "node", got ${JSON.stringify(runner)}`);
45
+ }
46
+ const parsedTools = {};
47
+ if (tools !== undefined) {
48
+ if (!isPlainObject(tools))
49
+ throw new RunnerFileError(file, `"tools" must be an object`);
50
+ for (const [name, version] of Object.entries(tools)) {
51
+ if (!isPackageName(name)) {
52
+ throw new RunnerFileError(file, `"tools": "${name}" is not a valid package name`);
53
+ }
54
+ if (typeof version !== "string" || !isExactVersion(version)) {
55
+ throw new RunnerFileError(file, `"tools": "${name}" must be an exact version like "1.2.3", got ${JSON.stringify(version)}`);
56
+ }
57
+ parsedTools[name] = version;
58
+ }
59
+ }
60
+ return { runner: runner ?? null, tools: parsedTools, extra };
61
+ }
62
+ /** Writes `.agents/runner.json` under `root`, creating `.agents/` if needed. Throws `TypeError` on a config the reader would reject. */
63
+ export function writeRunnerConfig(root, config) {
64
+ const { runner, tools: configTools } = config;
65
+ if (runner !== null && runner !== "bun" && runner !== "node") {
66
+ throw new TypeError(`runner must be null, "bun" or "node", got ${JSON.stringify(runner)}`);
67
+ }
68
+ for (const [name, version] of Object.entries(configTools)) {
69
+ if (!isPackageName(name))
70
+ throw new TypeError(`"${name}" is not a valid package name`);
71
+ if (typeof version !== "string" || !isExactVersion(version)) {
72
+ throw new TypeError(`tool "${name}" must be an exact version like "1.2.3", got ${JSON.stringify(version)}`);
73
+ }
74
+ }
75
+ const file = join(root, RUNNER_FILE);
76
+ // No prototype, so an extra key named `__proto__` stays an own property.
77
+ const out = Object.create(null);
78
+ out.$schema = SCHEMA_URL;
79
+ if (runner !== null)
80
+ out.runner = runner;
81
+ const tools = Object.create(null);
82
+ for (const name of Object.keys(configTools).sort())
83
+ tools[name] = configTools[name];
84
+ out.tools = tools;
85
+ for (const [key, value] of Object.entries(config.extra)) {
86
+ if (key === "$schema" || key === "runner" || key === "tools")
87
+ continue;
88
+ out[key] = value;
89
+ }
90
+ mkdirSync(dirname(file), { recursive: true });
91
+ writeAtomic(file, JSON.stringify(out, null, 2) + "\n");
92
+ }
93
+ /** The runner to use: the configured one, or Bun by default. */
94
+ export function effectiveRunner(config) {
95
+ return config?.runner ?? "bun";
96
+ }
@@ -0,0 +1,9 @@
1
+ export { VERSION } from "./version.js";
2
+ export { RUNNER_FILE, RunnerFileError, readRunnerConfig, writeRunnerConfig, effectiveRunner, } from "./config.js";
3
+ export type { Runner, RunnerConfig } from "./config.js";
4
+ export { setTool } from "./tools.js";
5
+ export { toolCommand, toolCommandText } from "./command.js";
6
+ export { runnerAvailable, chooseRunner, NO_BUN_WARNING } from "./choose.js";
7
+ export { writeScripts } from "./scripts.js";
8
+ export { checkRunner, checkToolPins } from "./checks.js";
9
+ export type { Check } from "./checks.js";
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { VERSION } from "./version.js";
2
+ export { RUNNER_FILE, RunnerFileError, readRunnerConfig, writeRunnerConfig, effectiveRunner, } from "./config.js";
3
+ export { setTool } from "./tools.js";
4
+ export { toolCommand, toolCommandText } from "./command.js";
5
+ export { runnerAvailable, chooseRunner, NO_BUN_WARNING } from "./choose.js";
6
+ export { writeScripts } from "./scripts.js";
7
+ export { checkRunner, checkToolPins } from "./checks.js";
@@ -0,0 +1,11 @@
1
+ import type { Runner } from "./config.js";
2
+ /**
3
+ * Writes the shortcuts of a tool into `package.json` under `root`. A script is
4
+ * the tool's own when its command contains `owned`: those are replaced; any
5
+ * other script with the same name is left alone and returned in `clashes`.
6
+ * `packageManager` is only written when this call creates the file.
7
+ */
8
+ export declare function writeScripts(root: string, runner: Runner, scripts: Record<string, string>, owned: string): {
9
+ changed: boolean;
10
+ clashes: string[];
11
+ };
@@ -0,0 +1,78 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { writeAtomic } from "./write.js";
4
+ import { join } from "node:path";
5
+ const VERSION_OUTPUT = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
6
+ /** `bun@1.3.0` or `npm@11.6.0` for the installed manager, or `null` when it can't be read. */
7
+ function packageManagerField(runner) {
8
+ const name = runner === "bun" ? "bun" : "npm";
9
+ const result = spawnSync(name, ["--version"], {
10
+ encoding: "utf8",
11
+ stdio: ["ignore", "pipe", "ignore"],
12
+ timeout: 15_000,
13
+ });
14
+ if (result.error || result.status !== 0)
15
+ return null;
16
+ const version = String(result.stdout).trim();
17
+ return VERSION_OUTPUT.test(version) ? `${name}@${version}` : null;
18
+ }
19
+ /** The indentation of the first indented line: a tab, or N spaces (default 2). */
20
+ function detectIndent(text) {
21
+ const match = /^([ \t]+)\S/m.exec(text);
22
+ return match ? match[1] : " ";
23
+ }
24
+ /**
25
+ * Writes the shortcuts of a tool into `package.json` under `root`. A script is
26
+ * the tool's own when its command contains `owned`: those are replaced; any
27
+ * other script with the same name is left alone and returned in `clashes`.
28
+ * `packageManager` is only written when this call creates the file.
29
+ */
30
+ export function writeScripts(root, runner, scripts, owned) {
31
+ const file = join(root, "package.json");
32
+ if (!existsSync(file)) {
33
+ const out = { private: true };
34
+ const manager = packageManagerField(runner);
35
+ if (manager !== null)
36
+ out.packageManager = manager;
37
+ out.scripts = { ...scripts };
38
+ writeAtomic(file, JSON.stringify(out, null, 2) + "\n");
39
+ return { changed: true, clashes: [] };
40
+ }
41
+ const text = readFileSync(file, "utf8").replace(/^\uFEFF/, "");
42
+ let data;
43
+ try {
44
+ data = JSON.parse(text);
45
+ }
46
+ catch (err) {
47
+ throw new Error(`${file}: cannot parse: ${err.message}`);
48
+ }
49
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
50
+ throw new Error(`${file}: must be a JSON object`);
51
+ }
52
+ const pkg = data;
53
+ const existing = pkg.scripts;
54
+ if (existing !== undefined && (typeof existing !== "object" || existing === null || Array.isArray(existing))) {
55
+ throw new Error(`${file}: "scripts" must be an object`);
56
+ }
57
+ const current = { ...existing };
58
+ let changed = existing === undefined && Object.keys(scripts).length > 0;
59
+ const clashes = [];
60
+ for (const [name, command] of Object.entries(scripts)) {
61
+ const found = Object.hasOwn(current, name) ? current[name] : undefined;
62
+ if (found === command)
63
+ continue;
64
+ if (found === undefined || (typeof found === "string" && found.includes(owned))) {
65
+ current[name] = command;
66
+ changed = true;
67
+ }
68
+ else {
69
+ clashes.push(name);
70
+ }
71
+ }
72
+ if (!changed)
73
+ return { changed: false, clashes };
74
+ pkg.scripts = current;
75
+ const eol = text.endsWith("\n") ? "\n" : "";
76
+ writeAtomic(file, JSON.stringify(pkg, null, detectIndent(text)) + eol);
77
+ return { changed: true, clashes };
78
+ }
@@ -0,0 +1,14 @@
1
+ import type { RunnerConfig } from "./config.js";
2
+ /**
3
+ * Adds a tool or raises its pinned version; never installs anything.
4
+ * Never lowers a version unless `allowLower` is set; `ifMissing` only adds.
5
+ * Does not mutate `config`.
6
+ * @throws TypeError if `pkg` is not a package name or `version` is not exact.
7
+ */
8
+ export declare function setTool(config: RunnerConfig, pkg: string, version: string, options?: {
9
+ ifMissing?: boolean;
10
+ allowLower?: boolean;
11
+ }): {
12
+ config: RunnerConfig;
13
+ changed: boolean;
14
+ };
package/dist/tools.js ADDED
@@ -0,0 +1,55 @@
1
+ import { SEMVER, isExactVersion, isPackageName } from "./config.js";
2
+ /**
3
+ * Compares two exact versions by semver precedence, prereleases included.
4
+ * @returns Negative if left is older, 0 if equal, positive if newer.
5
+ */
6
+ function compareSemver(left, right) {
7
+ const [a, b] = [SEMVER.exec(left), SEMVER.exec(right)];
8
+ for (let index = 1; index <= 3; index += 1) {
9
+ const diff = Number(a?.[index] ?? 0) - Number(b?.[index] ?? 0);
10
+ if (diff !== 0)
11
+ return diff;
12
+ }
13
+ const [pre, other] = [a?.[4], b?.[4]];
14
+ if (pre === other)
15
+ return 0;
16
+ if (pre === undefined)
17
+ return 1;
18
+ if (other === undefined)
19
+ return -1;
20
+ const [x, y] = [pre.split("."), other.split(".")];
21
+ for (let index = 0; index < Math.min(x.length, y.length); index += 1) {
22
+ const [p, q] = [x[index], y[index]];
23
+ if (p === q)
24
+ continue;
25
+ const [pNumber, qNumber] = [/^\d+$/.test(p), /^\d+$/.test(q)];
26
+ if (pNumber && qNumber)
27
+ return Number(p) - Number(q);
28
+ if (pNumber !== qNumber)
29
+ return pNumber ? -1 : 1;
30
+ return p < q ? -1 : 1;
31
+ }
32
+ return x.length - y.length;
33
+ }
34
+ /**
35
+ * Adds a tool or raises its pinned version; never installs anything.
36
+ * Never lowers a version unless `allowLower` is set; `ifMissing` only adds.
37
+ * Does not mutate `config`.
38
+ * @throws TypeError if `pkg` is not a package name or `version` is not exact.
39
+ */
40
+ export function setTool(config, pkg, version, options = {}) {
41
+ if (!isPackageName(pkg))
42
+ throw new TypeError(`invalid package name "${pkg}"`);
43
+ if (!isExactVersion(version))
44
+ throw new TypeError(`invalid version "${version}" for ${pkg}`);
45
+ const copy = { runner: config.runner, tools: { ...config.tools }, extra: { ...config.extra } };
46
+ const current = Object.hasOwn(config.tools, pkg) ? config.tools[pkg] : undefined;
47
+ let change = current === undefined;
48
+ if (current !== undefined && !options.ifMissing) {
49
+ const order = compareSemver(version, current);
50
+ change = order > 0 || (order < 0 && options.allowLower === true);
51
+ }
52
+ if (change)
53
+ copy.tools[pkg] = version;
54
+ return { config: copy, changed: change };
55
+ }
@@ -0,0 +1 @@
1
+ export declare const VERSION = "1.0.0";
@@ -0,0 +1 @@
1
+ export const VERSION = "1.0.0";
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Writes a file atomically: to a temp file in the same directory, then renamed
3
+ * over the target, so a reader never sees it half written. If either step
4
+ * fails the temp file is removed and the error is rethrown.
5
+ */
6
+ export declare function writeAtomic(file: string, content: string): void;
package/dist/write.js ADDED
@@ -0,0 +1,17 @@
1
+ import { renameSync, rmSync, writeFileSync } from "node:fs";
2
+ /**
3
+ * Writes a file atomically: to a temp file in the same directory, then renamed
4
+ * over the target, so a reader never sees it half written. If either step
5
+ * fails the temp file is removed and the error is rethrown.
6
+ */
7
+ export function writeAtomic(file, content) {
8
+ const temp = `${file}.${process.pid}.tmp`;
9
+ try {
10
+ writeFileSync(temp, content);
11
+ renameSync(temp, file);
12
+ }
13
+ catch (error) {
14
+ rmSync(temp, { force: true });
15
+ throw error;
16
+ }
17
+ }
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@ramon-sg/runner",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Lee `.agents/runner.json` y arma el comando para correr cada herramienta con Bun o Node",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./schema": "./runner.schema.json"
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "runner.schema.json"
17
+ ],
18
+ "publishConfig": {
19
+ "access": "public",
20
+ "provenance": true
21
+ },
22
+ "engines": {
23
+ "node": ">=20"
24
+ },
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/ramon-sg/runner.git"
28
+ },
29
+ "scripts": {
30
+ "build": "tsc",
31
+ "test": "tsc && node --test test/*.test.mjs",
32
+ "prepublishOnly": "npm test"
33
+ },
34
+ "devDependencies": {
35
+ "@types/node": "^24.0.0",
36
+ "typescript": "^5.9.3"
37
+ }
38
+ }
@@ -0,0 +1,20 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "title": "@ramon-sg/runner configuration",
4
+ "type": "object",
5
+ "properties": {
6
+ "$schema": { "type": "string" },
7
+ "runner": { "enum": ["bun", "node"] },
8
+ "tools": {
9
+ "type": "object",
10
+ "propertyNames": {
11
+ "pattern": "^(@[a-z0-9-~][a-z0-9-._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$"
12
+ },
13
+ "additionalProperties": {
14
+ "type": "string",
15
+ "pattern": "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*))*))?$"
16
+ }
17
+ }
18
+ },
19
+ "additionalProperties": true
20
+ }