@anhlp/alp-core 0.0.1-beta.5 → 0.0.1-beta.7
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/dist/bridges.d.ts +5 -6
- package/dist/bridges.js +3 -4
- package/dist/packaged.d.ts +37 -44
- package/dist/packaged.js +42 -156
- package/dist/profiles.js +3 -3
- package/dist/providers.d.ts +0 -1
- package/dist/providers.js +2 -2
- package/dist/tasks.d.ts +2 -1
- package/dist/tasks.js +8 -2
- package/dist/template-path.d.ts +2 -2
- package/dist/template-path.js +0 -5
- package/dist/types.d.ts +2 -0
- package/dist/validation.js +4 -3
- package/package.json +2 -2
- package/src/bridges.js +9 -10
- package/src/packaged.js +74 -191
- package/src/profiles.js +3 -3
- package/src/providers.js +2 -3
- package/src/tasks.d.ts +2 -1
- package/src/tasks.js +16 -5
- package/src/template-path.js +1 -6
- package/src/types.d.ts +2 -0
- package/src/validation.js +5 -3
package/dist/bridges.d.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
/** Runs a bridge in this process, as `node -e` would. @param {string} kind */
|
|
2
2
|
export function runBridge(kind: string): void;
|
|
3
3
|
/**
|
|
4
|
-
* The command an agent CLI runs to start a bridge: `node -e <source>` under Node
|
|
5
|
-
* `bridge <kind>` subcommand when packaged.
|
|
4
|
+
* The command an agent CLI runs to start a bridge: `node -e <source>` under this Node.
|
|
6
5
|
* @param {'acp' | 'antigravity'} kind
|
|
7
6
|
* @returns {{ command: string, args: string[] }}
|
|
8
7
|
*/
|
|
@@ -11,8 +10,8 @@ export function bridgeCommand(kind: "acp" | "antigravity"): {
|
|
|
11
10
|
args: string[];
|
|
12
11
|
};
|
|
13
12
|
/**
|
|
14
|
-
* Whether an MCP server entry is one of ALP's bridge launchers: the `-e` source, or
|
|
15
|
-
* executable
|
|
13
|
+
* Whether an MCP server entry is one of ALP's bridge launchers: the `-e` source, or `alp bridge <kind>`
|
|
14
|
+
* as the single-file executable of 0.0.1-beta.5/6 wrote it (only when its command is named alp, so another server is kept).
|
|
16
15
|
* @param {'acp' | 'antigravity'} kind
|
|
17
16
|
* @param {unknown} args
|
|
18
17
|
* @param {unknown} [command]
|
|
@@ -20,8 +19,8 @@ export function bridgeCommand(kind: "acp" | "antigravity"): {
|
|
|
20
19
|
export function isBridgeArgs(kind: "acp" | "antigravity", args: unknown, command?: unknown): boolean;
|
|
21
20
|
/**
|
|
22
21
|
* The stdio MCP bridges an agent CLI starts to reach alpd's tools (ACP agents and Antigravity).
|
|
23
|
-
*
|
|
24
|
-
*
|
|
22
|
+
* They run as `node -e <source>`; `alp bridge acp|antigravity` (which calls runBridge) remains for
|
|
23
|
+
* the MCP entries the single-file executable of 0.0.1-beta.5/6 wrote.
|
|
25
24
|
*/
|
|
26
25
|
export const ACP_BRIDGE: "\nconst net = require('node:net');\nconst readline = require('node:readline');\nconst socket = net.connect(process.env.ALP_BRIDGE_SOCKET);\nconst waiting = new Map();\nlet sequence = 0;\nlet buffer = '';\nsocket.setEncoding('utf8');\nsocket.write(JSON.stringify({ token: process.env.ALP_BRIDGE_TOKEN }) + '\\n');\nsocket.on('data', data => {\n buffer += data;\n for (let index; (index = buffer.indexOf('\\n')) >= 0;) {\n const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);\n try { const message = JSON.parse(line); const waiter = waiting.get(message.id); if (waiter) { waiting.delete(message.id); waiter(message); } } catch {}\n }\n});\nsocket.on('close', () => process.exit(0));\nsocket.on('error', () => process.exit(1));\nconst ask = message => new Promise(resolve => { const id = ++sequence; waiting.set(id, resolve); socket.write(JSON.stringify({ ...message, id }) + '\\n'); });\nconst send = value => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...value }) + '\\n');\nreadline.createInterface({ input: process.stdin }).on('line', async line => {\n let message; try { message = JSON.parse(line); } catch { return; }\n if (message.id === undefined || message.id === null) return;\n try {\n if (message.method === 'initialize') return send({ id: message.id, result: { protocolVersion: (message.params && message.params.protocolVersion) || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'alp', version: '1' } } });\n if (message.method === 'ping') return send({ id: message.id, result: {} });\n if (message.method === 'tools/list') { const reply = await ask({ op: 'list' }); return send({ id: message.id, result: { tools: reply.tools } }); }\n if (message.method === 'tools/call') { const reply = await ask({ op: 'call', name: message.params.name, arguments: message.params.arguments || {} }); return send({ id: message.id, result: reply.result }); }\n send({ id: message.id, error: { code: -32601, message: 'Method not found' } });\n } catch (error) { send({ id: message.id, error: { code: -32603, message: String((error && error.message) || error) } }); }\n});\nprocess.stdin.on('end', () => process.exit(0));\n";
|
|
27
26
|
export const ANTIGRAVITY_BRIDGE: "// ALP Antigravity bridge v1\n\nconst net = require('node:net');\nconst readline = require('node:readline');\nconst socket = process.env.ALP_BRIDGE_SOCKET ? net.connect(process.env.ALP_BRIDGE_SOCKET) : null;\nconst waiting = new Map();\nlet sequence = 0;\nlet buffer = '';\nsocket?.setEncoding('utf8');\nsocket?.write(JSON.stringify({ token: process.env.ALP_BRIDGE_TOKEN }) + '\\n');\nsocket?.on('data', data => {\n buffer += data;\n for (let index; (index = buffer.indexOf('\\n')) >= 0;) {\n const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);\n try { const message = JSON.parse(line); const waiter = waiting.get(message.id); if (waiter) { waiting.delete(message.id); waiter(message); } } catch {}\n }\n});\nsocket?.on('close', () => process.exit(0));\nsocket?.on('error', () => process.exit(1));\nconst ask = message => !socket ? Promise.resolve({ tools: [], result: { content: [{ type: 'text', text: 'No ALP session' }], isError: true } }) : new Promise(resolve => { const id = ++sequence; waiting.set(id, resolve); socket.write(JSON.stringify({ ...message, id }) + '\\n'); });\nconst send = value => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...value }) + '\\n');\nreadline.createInterface({ input: process.stdin }).on('line', async line => {\n let message; try { message = JSON.parse(line); } catch { return; }\n if (message.id === undefined || message.id === null) return;\n try {\n if (message.method === 'initialize') return send({ id: message.id, result: { protocolVersion: (message.params && message.params.protocolVersion) || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'alp', version: '1' } } });\n if (message.method === 'ping') return send({ id: message.id, result: {} });\n if (message.method === 'tools/list') { const reply = await ask({ op: 'list' }); return send({ id: message.id, result: { tools: reply.tools } }); }\n if (message.method === 'tools/call') { const reply = await ask({ op: 'call', name: message.params.name, arguments: message.params.arguments || {} }); return send({ id: message.id, result: reply.result }); }\n send({ id: message.id, error: { code: -32601, message: 'Method not found' } });\n } catch (error) { send({ id: message.id, error: { code: -32603, message: String((error && error.message) || error) } }); }\n});\nprocess.stdin.on('end', () => process.exit(0));\n";
|
package/dist/bridges.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// packages/core/src/bridges.js
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
|
-
import { isExecutableName,
|
|
3
|
+
import { isExecutableName, stablePath } from "./packaged.js";
|
|
4
4
|
var ACP_BRIDGE = `
|
|
5
5
|
const net = require('node:net');
|
|
6
6
|
const readline = require('node:readline');
|
|
@@ -79,14 +79,13 @@ function runBridge(kind) {
|
|
|
79
79
|
}
|
|
80
80
|
function bridgeCommand(kind) {
|
|
81
81
|
if (!Object.hasOwn(BRIDGES, kind)) throw new Error(`Unknown bridge: ${kind}; expected acp or antigravity`);
|
|
82
|
-
|
|
83
|
-
return { command: process.execPath, args: ["-e", BRIDGES[kind]] };
|
|
82
|
+
return { command: stablePath(process.execPath), args: ["-e", BRIDGES[kind]] };
|
|
84
83
|
}
|
|
85
84
|
function isBridgeArgs(kind, args, command = void 0) {
|
|
86
85
|
if (!Array.isArray(args)) return false;
|
|
87
86
|
const marker = kind === "antigravity" ? "// ALP Antigravity bridge v1" : void 0;
|
|
88
87
|
if (marker && args.some((arg) => typeof arg === "string" && arg.startsWith(marker))) return true;
|
|
89
|
-
return typeof command === "string" &&
|
|
88
|
+
return typeof command === "string" && isExecutableName(command) && args.length === 2 && args[0] === "bridge" && args[1] === kind;
|
|
90
89
|
}
|
|
91
90
|
export {
|
|
92
91
|
ACP_BRIDGE,
|
package/dist/packaged.d.ts
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
* @
|
|
2
|
+
* The ALP bundle this Node belongs to, or undefined for any other Node (an npm install).
|
|
3
|
+
* @param {string} [execPath]
|
|
4
|
+
* @returns {BundleInfo | undefined}
|
|
5
|
+
*/
|
|
6
|
+
export function bundleInfo(execPath?: string): BundleInfo | undefined;
|
|
7
|
+
/**
|
|
8
|
+
* `file` named through `<app>/current` when it lies inside this process's bundle and `current` points
|
|
9
|
+
* at that bundle; otherwise `file` unchanged. For paths written to disk for later processes.
|
|
10
|
+
* @param {string} file
|
|
11
|
+
* @param {{ bundle?: BundleInfo | undefined }} [options]
|
|
4
12
|
*/
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
export function packagedInfo(): PackagedRegistration | undefined;
|
|
9
|
-
/** Whether this process is the self-contained ALP executable. */
|
|
10
|
-
export function isPackaged(): boolean;
|
|
13
|
+
export function stablePath(file: string, { bundle }?: {
|
|
14
|
+
bundle?: BundleInfo | undefined;
|
|
15
|
+
}): string;
|
|
11
16
|
/**
|
|
12
|
-
* The command that starts ALP's `role` from this process:
|
|
13
|
-
* else `script` under this Node, exactly as before.
|
|
17
|
+
* The command that starts ALP's `role` from this process: `script` under this Node.
|
|
14
18
|
* @param {keyof typeof ROLE_ARGS} role
|
|
15
19
|
* @param {{ script: string, args?: string[] }} options
|
|
16
20
|
* @returns {{ command: string, args: string[] }}
|
|
@@ -24,7 +28,8 @@ export function selfCommand(role: keyof typeof ROLE_ARGS, { script, args }: {
|
|
|
24
28
|
};
|
|
25
29
|
/**
|
|
26
30
|
* The command that runs an `entry` found on disk (an install record, a service definition, a CLI
|
|
27
|
-
* on PATH): a script runs under `execPath`; an
|
|
31
|
+
* on PATH): a script runs under `execPath`; an `alp` command (the bundle's launcher, or what a
|
|
32
|
+
* 0.0.1-beta.5/6 single-file install recorded) runs its role subcommand.
|
|
28
33
|
* @param {string} entry
|
|
29
34
|
* @param {keyof typeof ROLE_ARGS} role
|
|
30
35
|
* @param {string[]} [args]
|
|
@@ -39,8 +44,7 @@ export function entryCommand(entry: string, role: keyof typeof ROLE_ARGS, args?:
|
|
|
39
44
|
args: string[];
|
|
40
45
|
};
|
|
41
46
|
/**
|
|
42
|
-
* The command that runs a user's JavaScript file (a fake provider, an npm cmd shim on Windows)
|
|
43
|
-
* with this process's runtime. The executable runs it as Bun does when BUN_BE_BUN is set.
|
|
47
|
+
* The command that runs a user's JavaScript file (a fake provider, an npm cmd shim on Windows) with this Node.
|
|
44
48
|
* @param {string} script
|
|
45
49
|
* @param {string[]} [args]
|
|
46
50
|
* @returns {{ command: string, args: string[], env?: Record<string, string> }}
|
|
@@ -50,47 +54,36 @@ export function scriptCommand(script: string, args?: string[]): {
|
|
|
50
54
|
args: string[];
|
|
51
55
|
env?: Record<string, string>;
|
|
52
56
|
};
|
|
53
|
-
/**
|
|
54
|
-
export function executablePath(): string | undefined;
|
|
55
|
-
/** Where this process's own entry lives: the executable when packaged, else `script`. @param {string} script */
|
|
57
|
+
/** Where this process's own entry lives, for records that later processes read: `script`, through `current` in a bundle. @param {string} script */
|
|
56
58
|
export function selfEntry(script: string): string;
|
|
57
|
-
/** The directory the executable's assets are extracted to. @param {string} version @param {NodeJS.ProcessEnv} [env] */
|
|
58
|
-
export function assetCacheDir(version: string, env?: NodeJS.ProcessEnv): string;
|
|
59
59
|
/**
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
60
|
+
* How ALP starts its own processes, and where its bundle lives. ALP always runs under Node: from npm
|
|
61
|
+
* (`node cli.js`, `node alpd.js`) or from the ALP bundle (t-1807), which is the same npm install
|
|
62
|
+
* beside an official Node release, started by `bin/alp`:
|
|
63
|
+
*
|
|
64
|
+
* <app>/<version>/{bin/alp, node/bin/node, lib/node_modules/@anhlp/alp-cli, alp-bundle.json}
|
|
65
|
+
* <app>/current → <version> (install.sh and `alp update` move it)
|
|
66
|
+
*
|
|
67
|
+
* Paths that outlive this process (a launchd/systemd service, alpd's install record) name the bundle
|
|
68
|
+
* through `current`, so an update never leaves them on a removed version.
|
|
66
69
|
*/
|
|
67
|
-
|
|
68
|
-
env?: NodeJS.ProcessEnv;
|
|
69
|
-
info?: PackagedRegistration;
|
|
70
|
-
}): string | undefined;
|
|
71
|
-
/** Subcommands of the executable that run each ALP role (the npm CLI understands them too). */
|
|
70
|
+
/** Subcommands of `alp` that run each ALP role in that process (`alp daemon run`, `alp web serve`, `alp bridge acp`). */
|
|
72
71
|
export const ROLE_ARGS: Readonly<{
|
|
73
72
|
daemon: readonly string[];
|
|
74
73
|
web: readonly string[];
|
|
75
74
|
'bridge-acp': readonly string[];
|
|
76
75
|
'bridge-antigravity': readonly string[];
|
|
77
76
|
}>;
|
|
78
|
-
/**
|
|
79
|
-
* A string only ALP's executable carries: its generated entry embeds it, so discovery can tell ALP
|
|
80
|
-
* from an unrelated native program that happens to be called `alp` without running it.
|
|
81
|
-
*/
|
|
82
|
-
export const EXECUTABLE_MARKER: "alp-standalone-executable:v1:2b6f0c1e";
|
|
83
77
|
export function isExecutableName(file: string): boolean;
|
|
84
|
-
export function isSelf(file: unknown): boolean;
|
|
85
|
-
export function samePath(a: string, b: string): boolean;
|
|
86
78
|
export function isScript(file: string): boolean;
|
|
87
|
-
export
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
79
|
+
export function samePath(a: string, b: string): boolean;
|
|
80
|
+
/**
|
|
81
|
+
* root: the bundle directory (real path); app: its parent; current: `<app>/current` when it points at root.
|
|
82
|
+
*/
|
|
83
|
+
export type BundleInfo = {
|
|
84
|
+
root: string;
|
|
93
85
|
version: string;
|
|
94
|
-
|
|
95
|
-
|
|
86
|
+
platform: string;
|
|
87
|
+
app: string;
|
|
88
|
+
current?: string;
|
|
96
89
|
};
|
package/dist/packaged.js
CHANGED
|
@@ -1,31 +1,14 @@
|
|
|
1
1
|
// packages/core/src/packaged.js
|
|
2
|
-
import {
|
|
3
|
-
import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
-
import os from "node:os";
|
|
2
|
+
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
|
5
3
|
import path from "node:path";
|
|
6
|
-
var KEY = Symbol.for("alp.packaged");
|
|
7
4
|
var ROLE_ARGS = Object.freeze({
|
|
8
5
|
daemon: Object.freeze(["daemon", "run"]),
|
|
9
6
|
web: Object.freeze(["web", "serve"]),
|
|
10
7
|
"bridge-acp": Object.freeze(["bridge", "acp"]),
|
|
11
8
|
"bridge-antigravity": Object.freeze(["bridge", "antigravity"])
|
|
12
9
|
});
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
Object.defineProperty(globalThis, KEY, { value: Object.freeze({ ...registration, assetDir: () => assetDir() }), configurable: true, enumerable: false, writable: false });
|
|
16
|
-
}
|
|
17
|
-
function packagedInfo() {
|
|
18
|
-
return (
|
|
19
|
-
/** @type {any} */
|
|
20
|
-
globalThis[KEY]
|
|
21
|
-
);
|
|
22
|
-
}
|
|
23
|
-
function isPackaged() {
|
|
24
|
-
return packagedInfo() !== void 0;
|
|
25
|
-
}
|
|
26
|
-
var EXECUTABLE_MARKER = "alp-standalone-executable:v1:2b6f0c1e";
|
|
27
|
-
var isExecutableName = (file) => /^alp(\.exe)?$/i.test(file.split(/[\\/]/).pop() ?? "");
|
|
28
|
-
var isSelf = (file) => isPackaged() && typeof file === "string" && samePath(file, process.execPath);
|
|
10
|
+
var isExecutableName = (file) => /^alp(\.exe|\.cmd)?$/i.test(file.split(/[\\/]/).pop() ?? "");
|
|
11
|
+
var isScript = (file) => /\.[cm]?js$/i.test(file);
|
|
29
12
|
var canonical = (file) => {
|
|
30
13
|
let resolved = path.resolve(file);
|
|
31
14
|
try {
|
|
@@ -35,164 +18,67 @@ var canonical = (file) => {
|
|
|
35
18
|
return process.platform === "darwin" || process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
36
19
|
};
|
|
37
20
|
var samePath = (a, b) => canonical(a) === canonical(b);
|
|
38
|
-
var isScript = (file) => /\.[cm]?js$/i.test(file);
|
|
39
21
|
function roleArgs(role) {
|
|
40
22
|
const args = ROLE_ARGS[role];
|
|
41
23
|
if (!args) throw new TypeError(`Unknown ALP role: ${role}`);
|
|
42
24
|
return [...args];
|
|
43
25
|
}
|
|
26
|
+
var bundles = /* @__PURE__ */ new Map();
|
|
27
|
+
function bundleInfo(execPath = process.execPath) {
|
|
28
|
+
if (bundles.has(execPath)) return bundles.get(execPath);
|
|
29
|
+
let info;
|
|
30
|
+
try {
|
|
31
|
+
const real = realpathSync(execPath);
|
|
32
|
+
const nodeDir = path.basename(path.dirname(real)) === "bin" ? path.dirname(path.dirname(real)) : path.dirname(real);
|
|
33
|
+
const root = path.dirname(nodeDir);
|
|
34
|
+
if (path.basename(nodeDir) === "node") {
|
|
35
|
+
const manifest = JSON.parse(readFileSync(path.join(root, "alp-bundle.json"), "utf8"));
|
|
36
|
+
if (manifest?.name === "alp" && typeof manifest.version === "string") {
|
|
37
|
+
const app = path.dirname(root);
|
|
38
|
+
const current = path.join(app, "current");
|
|
39
|
+
info = { root, version: manifest.version, platform: String(manifest.platform ?? ""), app, ...existsSync(current) && samePath(current, root) ? { current } : {} };
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
} catch {
|
|
43
|
+
}
|
|
44
|
+
bundles.set(execPath, info);
|
|
45
|
+
return info;
|
|
46
|
+
}
|
|
47
|
+
function stablePath(file, { bundle = bundleInfo() } = {}) {
|
|
48
|
+
if (!bundle?.current) return file;
|
|
49
|
+
let real;
|
|
50
|
+
try {
|
|
51
|
+
real = realpathSync(file);
|
|
52
|
+
} catch {
|
|
53
|
+
return file;
|
|
54
|
+
}
|
|
55
|
+
const relative = path.relative(bundle.root, real);
|
|
56
|
+
if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) return file;
|
|
57
|
+
return path.join(bundle.current, relative);
|
|
58
|
+
}
|
|
44
59
|
function selfCommand(role, { script, args = [] }) {
|
|
45
|
-
|
|
60
|
+
roleArgs(role);
|
|
46
61
|
return { command: process.execPath, args: [script, ...args] };
|
|
47
62
|
}
|
|
48
63
|
function entryCommand(entry, role, args = [], execPath = process.execPath, { scriptOnly = false } = {}) {
|
|
49
|
-
if (scriptOnly || isScript(entry) || !
|
|
50
|
-
if (isPackaged() && execPath === process.execPath) return { command: "node", args: [entry, ...args] };
|
|
51
|
-
return { command: execPath, args: [entry, ...args] };
|
|
52
|
-
}
|
|
64
|
+
if (scriptOnly || isScript(entry) || !isExecutableName(entry)) return { command: execPath, args: [entry, ...args] };
|
|
53
65
|
return { command: entry, args: [...roleArgs(role), ...args] };
|
|
54
66
|
}
|
|
55
67
|
function scriptCommand(script, args = []) {
|
|
56
|
-
if (isPackaged()) return { command: process.execPath, args: [script, ...args], env: { BUN_BE_BUN: "1" } };
|
|
57
68
|
return { command: process.execPath, args: [script, ...args] };
|
|
58
69
|
}
|
|
59
|
-
function executablePath() {
|
|
60
|
-
return isPackaged() ? process.execPath : void 0;
|
|
61
|
-
}
|
|
62
70
|
function selfEntry(script) {
|
|
63
|
-
return
|
|
64
|
-
}
|
|
65
|
-
var sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
66
|
-
var MARKER = ".alp-assets.json";
|
|
67
|
-
function assetCacheDir(version, env = process.env) {
|
|
68
|
-
if (!/^[0-9A-Za-z][0-9A-Za-z.+-]*$/.test(version)) throw new TypeError(`Invalid ALP version for the asset cache: ${JSON.stringify(version)}`);
|
|
69
|
-
const home = env.ALP_HOME ? path.resolve(env.ALP_HOME) : path.join(os.homedir(), ".alp");
|
|
70
|
-
return path.join(home, "cache", version);
|
|
71
|
-
}
|
|
72
|
-
var manifestDigest = (assets) => sha256(Buffer.from(JSON.stringify(Object.keys(assets).sort().map((name) => [name, assets[name].sha256, assets[name].size]))));
|
|
73
|
-
function assertAssetName(name) {
|
|
74
|
-
if (!name || path.isAbsolute(name) || name.split(/[\\/]/).some((part) => part === ".." || part === "" || part === ".") || name === MARKER) throw new Error(`Invalid packaged asset name: ${JSON.stringify(name)}`);
|
|
75
|
-
}
|
|
76
|
-
function assertPrivate(directory) {
|
|
77
|
-
const info = lstatSync(directory);
|
|
78
|
-
if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`ALP asset cache is not a directory: ${directory}`);
|
|
79
|
-
if (process.platform !== "win32" && (info.uid !== process.getuid?.() || (info.mode & 63) !== 0)) throw new Error(`ALP asset cache must be private to the current user (0700): ${directory}`);
|
|
80
|
-
}
|
|
81
|
-
function assertParent(directory) {
|
|
82
|
-
const info = lstatSync(directory);
|
|
83
|
-
if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`ALP asset cache parent is not a directory: ${directory}`);
|
|
84
|
-
if (process.platform !== "win32" && (info.uid !== process.getuid?.() || (info.mode & 18) !== 0)) throw new Error(`ALP asset cache parent must belong to the current user and not be group- or world-writable: ${directory}`);
|
|
85
|
-
}
|
|
86
|
-
function extracted(directory, digest, assets) {
|
|
87
|
-
try {
|
|
88
|
-
if (JSON.parse(readFileSync(path.join(directory, MARKER), "utf8")).digest !== digest) return false;
|
|
89
|
-
return Object.entries(assets).every(([name, asset]) => {
|
|
90
|
-
const file = path.join(directory, name);
|
|
91
|
-
const info = lstatSync(file);
|
|
92
|
-
return info.isFile() && info.size === asset.size && sha256(readFileSync(file)) === asset.sha256;
|
|
93
|
-
});
|
|
94
|
-
} catch {
|
|
95
|
-
return false;
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
var STAGING = /^(.+)\.tmp-(\d+)-(\d+)$/;
|
|
99
|
-
var STALE_MS = 60 * 60 * 1e3;
|
|
100
|
-
var SWEEP_MIN_MS = 10 * 60 * 1e3;
|
|
101
|
-
function sweepStaging(parent) {
|
|
102
|
-
let names;
|
|
103
|
-
try {
|
|
104
|
-
names = readdirSync(parent);
|
|
105
|
-
} catch {
|
|
106
|
-
return;
|
|
107
|
-
}
|
|
108
|
-
for (const name of names) {
|
|
109
|
-
const match = STAGING.exec(name);
|
|
110
|
-
if (!match) continue;
|
|
111
|
-
const pid = Number(match[2]);
|
|
112
|
-
if (pid === process.pid) continue;
|
|
113
|
-
const age = Date.now() - Number(match[3]);
|
|
114
|
-
if (age < SWEEP_MIN_MS) continue;
|
|
115
|
-
let alive = false;
|
|
116
|
-
try {
|
|
117
|
-
process.kill(pid, 0);
|
|
118
|
-
alive = true;
|
|
119
|
-
} catch (error) {
|
|
120
|
-
alive = /** @type {any} */
|
|
121
|
-
error?.code === "EPERM";
|
|
122
|
-
}
|
|
123
|
-
if (alive && age < STALE_MS) continue;
|
|
124
|
-
try {
|
|
125
|
-
rmSync(path.join(parent, name), { recursive: true, force: true });
|
|
126
|
-
} catch {
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
function assetDir({ env = process.env, info = packagedInfo() } = {}) {
|
|
131
|
-
if (!info) return void 0;
|
|
132
|
-
const assets = info.assets ?? {};
|
|
133
|
-
const directory = assetCacheDir(info.version, env);
|
|
134
|
-
const digest = manifestDigest(assets);
|
|
135
|
-
const key = `${directory}\0${digest}`;
|
|
136
|
-
if (verified.has(key) && existsSync(path.join(directory, MARKER))) return directory;
|
|
137
|
-
const result = extract(directory, digest, assets, info.version);
|
|
138
|
-
verified.add(key);
|
|
139
|
-
return result;
|
|
140
|
-
}
|
|
141
|
-
var verified = /* @__PURE__ */ new Set();
|
|
142
|
-
function extract(directory, digest, assets, version) {
|
|
143
|
-
const parent = path.dirname(directory);
|
|
144
|
-
mkdirSync(parent, { recursive: true, mode: 448 });
|
|
145
|
-
assertParent(parent);
|
|
146
|
-
sweepStaging(parent);
|
|
147
|
-
if (existsSync(directory)) {
|
|
148
|
-
assertPrivate(directory);
|
|
149
|
-
if (extracted(directory, digest, assets)) return directory;
|
|
150
|
-
}
|
|
151
|
-
const staging = `${directory}.tmp-${process.pid}-${Date.now()}`;
|
|
152
|
-
mkdirSync(staging, { mode: 448 });
|
|
153
|
-
try {
|
|
154
|
-
for (const [name, asset] of Object.entries(assets)) {
|
|
155
|
-
assertAssetName(name);
|
|
156
|
-
const bytes = readFileSync(asset.path);
|
|
157
|
-
if (bytes.length !== asset.size || sha256(bytes) !== asset.sha256) throw new Error(`Packaged asset ${name} does not match its manifest`);
|
|
158
|
-
const target = path.join(staging, name);
|
|
159
|
-
mkdirSync(path.dirname(target), { recursive: true, mode: 448 });
|
|
160
|
-
writeFileSync(target, bytes, { mode: 384 });
|
|
161
|
-
if (/(^|\/)terminal-owner(\.exe)?$/.test(name)) chmodSync(target, 448);
|
|
162
|
-
}
|
|
163
|
-
writeFileSync(path.join(staging, MARKER), JSON.stringify({ version, digest }), { mode: 384 });
|
|
164
|
-
if (existsSync(directory)) {
|
|
165
|
-
assertPrivate(directory);
|
|
166
|
-
if (extracted(directory, digest, assets)) {
|
|
167
|
-
rmSync(staging, { recursive: true, force: true });
|
|
168
|
-
return directory;
|
|
169
|
-
}
|
|
170
|
-
rmSync(directory, { recursive: true, force: true });
|
|
171
|
-
}
|
|
172
|
-
renameSync(staging, directory);
|
|
173
|
-
if (!extracted(directory, digest, assets)) throw new Error(`ALP asset cache ${directory} is incomplete after extraction`);
|
|
174
|
-
} catch (error) {
|
|
175
|
-
rmSync(staging, { recursive: true, force: true });
|
|
176
|
-
if (existsSync(directory) && extracted(directory, digest, assets)) return directory;
|
|
177
|
-
throw error;
|
|
178
|
-
}
|
|
179
|
-
return directory;
|
|
71
|
+
return stablePath(script);
|
|
180
72
|
}
|
|
181
73
|
export {
|
|
182
|
-
EXECUTABLE_MARKER,
|
|
183
74
|
ROLE_ARGS,
|
|
184
|
-
|
|
185
|
-
assetDir,
|
|
75
|
+
bundleInfo,
|
|
186
76
|
entryCommand,
|
|
187
|
-
executablePath,
|
|
188
77
|
isExecutableName,
|
|
189
|
-
isPackaged,
|
|
190
78
|
isScript,
|
|
191
|
-
isSelf,
|
|
192
|
-
packagedInfo,
|
|
193
|
-
registerPackaged,
|
|
194
79
|
samePath,
|
|
195
80
|
scriptCommand,
|
|
196
81
|
selfCommand,
|
|
197
|
-
selfEntry
|
|
82
|
+
selfEntry,
|
|
83
|
+
stablePath
|
|
198
84
|
};
|
package/dist/profiles.js
CHANGED
|
@@ -9,7 +9,7 @@ var oracleProfiles = (config) => config?.profiles ?? [config?.claude, config?.co
|
|
|
9
9
|
var agentProfiles = (config, name) => {
|
|
10
10
|
if (!config) return [];
|
|
11
11
|
if (name === "oracle") return oracleProfiles(config).map(parseProfile);
|
|
12
|
-
const { autocompact, ...legacy } = config;
|
|
12
|
+
const { autocompact, commands, ...legacy } = config;
|
|
13
13
|
return (config.profiles ?? [legacy]).map(parseProfile);
|
|
14
14
|
};
|
|
15
15
|
var parseProfile = (profile) => {
|
|
@@ -31,7 +31,7 @@ function normalizeAgentProfiles(config, name) {
|
|
|
31
31
|
if (config.profiles) return { ...config, profiles: config.profiles.map((profile) => typeof profile === "string" ? profile : profileString(profile)), autocompact: config.autocompact ?? "auto" };
|
|
32
32
|
const profiles = agentProfiles(config, name);
|
|
33
33
|
if (!profiles.length || profiles.some((profile) => !profile.model)) return config;
|
|
34
|
-
return { profiles: profiles.map((profile) => profileString({ ...profile, provider: profile.provider ?? profile.model.split(":")[0] })), autocompact: config.autocompact ?? "auto" };
|
|
34
|
+
return { profiles: profiles.map((profile) => profileString({ ...profile, provider: profile.provider ?? profile.model.split(":")[0] })), autocompact: config.autocompact ?? "auto", ...config.commands ? { commands: config.commands } : {} };
|
|
35
35
|
}
|
|
36
36
|
var profileModel = (config) => config?.model ? config.model.includes(":") ? config.model : `${config.provider}:${config.model}` : void 0;
|
|
37
37
|
var withEffort = (model, effort) => {
|
|
@@ -92,7 +92,7 @@ async function syncTemplateProfiles(settings, options = {}) {
|
|
|
92
92
|
for (const name of /* @__PURE__ */ new Set([...Object.keys(previous[id] ?? {}), ...options.replaceModels ? Object.keys(current) : [], ...Object.keys(desired)])) {
|
|
93
93
|
const config = current[name];
|
|
94
94
|
if (!options.replaceModels && config && profileFingerprint(config, name) !== previous[id]?.[name]) continue;
|
|
95
|
-
if (desired[name]) current[name] = { ...desired[name], autocompact: config?.autocompact ?? desired[name].autocompact };
|
|
95
|
+
if (desired[name]) current[name] = { ...desired[name], autocompact: config?.autocompact ?? desired[name].autocompact, ...config?.commands ? { commands: config.commands } : {} };
|
|
96
96
|
else delete current[name];
|
|
97
97
|
}
|
|
98
98
|
if (Object.keys(current).length) next.team[id] = current;
|
package/dist/providers.d.ts
CHANGED
|
@@ -63,7 +63,6 @@ export function acpModel(model: any): {
|
|
|
63
63
|
* native executable it calls, or the Node script, under this Node. A bare name with an .exe or
|
|
64
64
|
* .com on PATH, any other command, and every command elsewhere are returned as they are.
|
|
65
65
|
* @param {string} command @param {string[]} [args] @param {Record<string, string | undefined>} [env]
|
|
66
|
-
* In the ALP executable a Node script runs with the executable as its Bun runtime, via `env` to add.
|
|
67
66
|
* @returns {{ command: string, args: string[], env?: Record<string, string> }}
|
|
68
67
|
*/
|
|
69
68
|
export function launchCommand(command: string, args?: string[], env?: Record<string, string | undefined>): {
|
package/dist/providers.js
CHANGED
|
@@ -4,7 +4,7 @@ import { readdir, readFile } from "node:fs/promises";
|
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { AlpError } from "./errors.js";
|
|
6
6
|
import { settingsKeys, unknownMessage } from "./validation.js";
|
|
7
|
-
import {
|
|
7
|
+
import { scriptCommand } from "./packaged.js";
|
|
8
8
|
var PROVIDER_SETTINGS = ["$schema", "kind", "label", "description", "command", "args", "env", "models", "additionalModels", "enabled", "params", "readOnlyMode"];
|
|
9
9
|
var BUILTIN_RUNTIMES = ["codex", "claude", "acp", "antigravity"];
|
|
10
10
|
var RESERVED_PROVIDERS = [...BUILTIN_RUNTIMES, "alp"];
|
|
@@ -86,7 +86,7 @@ function launchCommand(command, args = [], env = process.env) {
|
|
|
86
86
|
if (script) {
|
|
87
87
|
const flags = script[1].split(/\s+/).filter(Boolean);
|
|
88
88
|
const run = scriptCommand(path.join(directory, script[2]), args);
|
|
89
|
-
return { command: run.command, args:
|
|
89
|
+
return { command: run.command, args: [...flags, ...run.args] };
|
|
90
90
|
}
|
|
91
91
|
const native = /^\s*"%~?dp0%\\?([^"]+\.(?:exe|com))"\s+%\*/im.exec(text);
|
|
92
92
|
if (native) return { command: path.join(directory, native[1]), args };
|
package/dist/tasks.d.ts
CHANGED
|
@@ -117,12 +117,13 @@ export function gatesOf(task: Task, tasks: Task[]): string[];
|
|
|
117
117
|
export const GATE_OPTIONS: number;
|
|
118
118
|
export const GATE_OPTION_CHARS: number;
|
|
119
119
|
export const GATE_CHANNELS: GateChannel[];
|
|
120
|
+
export const GATE_REJECT_LABELS: string[];
|
|
120
121
|
export function addGate(projectRoot: string, id: string, gate: { kind: GateKind; note?: string; until?: string; ref?: string | number; options?: string[] }, by: string): Promise<Task>;
|
|
121
122
|
export function resolveGate(projectRoot: string, id: string, gateId: string, resolve: { by: string; note?: string; remove?: boolean; ifRev?: number; choice?: string; channel?: GateChannel }): Promise<Task>;
|
|
122
123
|
export function rejectGate(projectRoot: string, id: string, gateId: string, reject: { by: string; reason?: string; ifRev?: number; channel?: GateChannel }): Promise<Task>;
|
|
123
124
|
export type GateDecision = { task: Task; gate: TaskGate; decision: 'approved' | 'rejected'; record: NonNullable<TaskGate['resolved'] | TaskGate['rejected']> };
|
|
124
125
|
export function gateDecisions(tasks: Task[]): GateDecision[];
|
|
125
|
-
export function markGateNotified(projectRoot: string, id: string, gateId: string, decision: 'approved' | 'rejected'): Promise<boolean>;
|
|
126
|
+
export function markGateNotified(projectRoot: string, id: string, gateId: string, decision: 'approved' | 'rejected', at?: string): Promise<boolean>;
|
|
126
127
|
export function checkGates(projectRoot: string, gh: (args: string[], options: { cwd: string }) => Promise<string>): Promise<{ cleared: Array<{ task: string; gate: string; detail: string }>; pending: Array<{ task: string; gate: string; detail: string }>; errors: Array<{ task: string; gate: string; error: string }> }>;
|
|
127
128
|
export function compactTasks(projectRoot: string, options: { days?: number; dryRun?: boolean }, by: string): Promise<Array<{ id: string; before: number; after: number }>>;
|
|
128
129
|
export type TaskBatch = {
|
package/dist/tasks.js
CHANGED
|
@@ -653,10 +653,15 @@ function addGate(projectRoot, id, { kind, note, until, ref, options } = {}, by)
|
|
|
653
653
|
var GATE_OPTIONS = 10;
|
|
654
654
|
var GATE_OPTION_CHARS = 200;
|
|
655
655
|
var GATE_CHANNELS = ["paseo", "web", "cli"];
|
|
656
|
+
var GATE_REJECT_LABELS = ["Reject", "T\u1EEB ch\u1ED1i"];
|
|
657
|
+
var labelKey = (text) => text.normalize("NFC").trim().toLowerCase();
|
|
658
|
+
var REJECT_KEYS = new Set(GATE_REJECT_LABELS.map(labelKey));
|
|
656
659
|
function gateOptions(value) {
|
|
657
660
|
if (!Array.isArray(value) || value.length > GATE_OPTIONS || !value.every((item) => typeof item === "string" && !!item.trim() && item.trim().length <= GATE_OPTION_CHARS)) {
|
|
658
661
|
fail("INVALID_TASK", `options must list at most ${GATE_OPTIONS} nonempty answers of at most ${GATE_OPTION_CHARS} characters`);
|
|
659
662
|
}
|
|
663
|
+
const reserved = value.find((item) => REJECT_KEYS.has(labelKey(item)));
|
|
664
|
+
if (reserved !== void 0) fail("INVALID_TASK", `"${reserved.trim()}" is the Reject answer every gate card already offers; name the options for approving only`);
|
|
660
665
|
return [...new Set(value.map((item) => item.trim()))];
|
|
661
666
|
}
|
|
662
667
|
var checkChannel = (channel) => {
|
|
@@ -716,13 +721,13 @@ function gateDecisions(tasks) {
|
|
|
716
721
|
}
|
|
717
722
|
return found;
|
|
718
723
|
}
|
|
719
|
-
function markGateNotified(projectRoot, id, gateId, decision) {
|
|
724
|
+
function markGateNotified(projectRoot, id, gateId, decision, at) {
|
|
720
725
|
return locked(projectRoot, async () => {
|
|
721
726
|
const { tasks } = await loadTasks(projectRoot);
|
|
722
727
|
const task = tasks.find((entry) => entry.id === id);
|
|
723
728
|
const gate = task?.gates?.find((entry) => entry.id === gateId);
|
|
724
729
|
const record = decision === "approved" ? gate?.resolved : gate?.rejected;
|
|
725
|
-
if (!task || !record?.channel || record.notified) return false;
|
|
730
|
+
if (!task || !record?.channel || record.notified || at !== void 0 && record.at !== at) return false;
|
|
726
731
|
record.notified = now();
|
|
727
732
|
await save(projectRoot, task);
|
|
728
733
|
return true;
|
|
@@ -872,6 +877,7 @@ export {
|
|
|
872
877
|
GATE_KINDS,
|
|
873
878
|
GATE_OPTIONS,
|
|
874
879
|
GATE_OPTION_CHARS,
|
|
880
|
+
GATE_REJECT_LABELS,
|
|
875
881
|
MAX_GATES,
|
|
876
882
|
MAX_LABELS,
|
|
877
883
|
MAX_LINKS,
|
package/dist/template-path.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/** Source packages carry templates beside src; legacy bundles live one directory deeper
|
|
2
|
-
export function shippedTemplateRoot():
|
|
1
|
+
/** Source packages carry templates beside src; legacy bundles live one directory deeper. */
|
|
2
|
+
export function shippedTemplateRoot(): URL;
|
package/dist/template-path.js
CHANGED
|
@@ -1,11 +1,6 @@
|
|
|
1
1
|
// packages/core/src/template-path.js
|
|
2
2
|
import { existsSync } from "node:fs";
|
|
3
|
-
import path from "node:path";
|
|
4
|
-
import { pathToFileURL } from "node:url";
|
|
5
|
-
import { assetDir } from "./packaged.js";
|
|
6
3
|
function shippedTemplateRoot() {
|
|
7
|
-
const assets = assetDir();
|
|
8
|
-
if (assets) return pathToFileURL(path.join(assets, "templates") + path.sep);
|
|
9
4
|
const packaged = new URL("../templates/", import.meta.url);
|
|
10
5
|
const candidates = [packaged, new URL("../../templates/", import.meta.url), new URL("../../../templates/", import.meta.url), new URL("../../../../templates/", import.meta.url), new URL("../../../../../templates/", import.meta.url)];
|
|
11
6
|
return candidates.find((candidate) => existsSync(candidate)) ?? packaged;
|
package/dist/types.d.ts
CHANGED
|
@@ -4,6 +4,8 @@ export type AgentProfilesConfig = {
|
|
|
4
4
|
/** "provider:model", "provider:*" for any model of that provider, or the earlier object form. */
|
|
5
5
|
profiles?: Array<string | AgentModelConfig>;
|
|
6
6
|
autocompact?: AutoCompact;
|
|
7
|
+
/** The runtime's own commands and skills the "/" list offers besides the agent's ALP skills; none by default (t-efa3). */
|
|
8
|
+
commands?: string[];
|
|
7
9
|
claude?: AgentModelConfig;
|
|
8
10
|
codex?: AgentModelConfig;
|
|
9
11
|
} & AgentModelConfig;
|
package/dist/validation.js
CHANGED
|
@@ -98,8 +98,9 @@ function validateSettings(settings, source) {
|
|
|
98
98
|
const where = `${key}.${team}.${agent}`;
|
|
99
99
|
check(object(config), `${where} must be an object`);
|
|
100
100
|
if (config.autocompact !== void 0) validateAutoCompact(config.autocompact, check, `${where}.autocompact`);
|
|
101
|
+
if (config.commands !== void 0) check(Array.isArray(config.commands) && config.commands.every((name) => typeof name === "string" && /^[^\s/]{1,256}$/.test(name)), `${where}.commands must be a list of command names, without whitespace or /`);
|
|
101
102
|
if (Object.hasOwn(config, "profiles")) {
|
|
102
|
-
check(Object.keys(config).every((key2) => ["profiles", "autocompact"].includes(key2)), `${where}: use profiles and
|
|
103
|
+
check(Object.keys(config).every((key2) => ["profiles", "autocompact", "commands"].includes(key2)), `${where}: use profiles, autocompact and commands`);
|
|
103
104
|
check(Array.isArray(config.profiles) && config.profiles.length > 0, `${where}.profiles must be a nonempty list`);
|
|
104
105
|
const models = [];
|
|
105
106
|
for (const [index, entry] of config.profiles.entries()) {
|
|
@@ -123,14 +124,14 @@ function validateSettings(settings, source) {
|
|
|
123
124
|
check(new Set(models).size === models.length, `${where}.profiles must not repeat the same model`);
|
|
124
125
|
check(agent !== "main" || config.profiles.length === 1, `${where}.profiles: main runs on exactly one model`);
|
|
125
126
|
} else if (agent === "oracle") {
|
|
126
|
-
const entries = Object.entries(config).filter(([key2]) => key2 !== "autocompact");
|
|
127
|
+
const entries = Object.entries(config).filter(([key2]) => key2 !== "autocompact" && key2 !== "commands");
|
|
127
128
|
check(entries.length > 0 && entries.every(([provider]) => ["claude", "codex"].includes(provider)), `${where} must define profiles or claude/codex lenses`);
|
|
128
129
|
for (const [provider, lens] of entries) {
|
|
129
130
|
validateChoice(lens, `${where}.${provider}`);
|
|
130
131
|
check(lens.provider === provider && nonempty(lens.model), `${where}.${provider}: specify matching provider and model`);
|
|
131
132
|
}
|
|
132
133
|
} else {
|
|
133
|
-
const { autocompact, ...legacy } = config;
|
|
134
|
+
const { autocompact, commands, ...legacy } = config;
|
|
134
135
|
validateChoice(legacy, where);
|
|
135
136
|
}
|
|
136
137
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anhlp/alp-core",
|
|
3
|
-
"version": "0.0.1-beta.
|
|
3
|
+
"version": "0.0.1-beta.7",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "ALP core module",
|
|
6
6
|
"files": [
|
|
@@ -300,7 +300,7 @@
|
|
|
300
300
|
"node": ">=22.12"
|
|
301
301
|
},
|
|
302
302
|
"dependencies": {
|
|
303
|
-
"@anhlp/alp-protocol": "0.0.1-beta.
|
|
303
|
+
"@anhlp/alp-protocol": "0.0.1-beta.7"
|
|
304
304
|
},
|
|
305
305
|
"scripts": {
|
|
306
306
|
"build": "node ../../scripts/build-workspace.mjs core",
|
package/src/bridges.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
|
-
import { isExecutableName,
|
|
2
|
+
import { isExecutableName, stablePath } from './packaged.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* The stdio MCP bridges an agent CLI starts to reach alpd's tools (ACP agents and Antigravity).
|
|
6
|
-
*
|
|
7
|
-
*
|
|
6
|
+
* They run as `node -e <source>`; `alp bridge acp|antigravity` (which calls runBridge) remains for
|
|
7
|
+
* the MCP entries the single-file executable of 0.0.1-beta.5/6 wrote.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
export const ACP_BRIDGE = `
|
|
@@ -87,20 +87,19 @@ export function runBridge(kind) {
|
|
|
87
87
|
}
|
|
88
88
|
|
|
89
89
|
/**
|
|
90
|
-
* The command an agent CLI runs to start a bridge: `node -e <source>` under Node
|
|
91
|
-
* `bridge <kind>` subcommand when packaged.
|
|
90
|
+
* The command an agent CLI runs to start a bridge: `node -e <source>` under this Node.
|
|
92
91
|
* @param {'acp' | 'antigravity'} kind
|
|
93
92
|
* @returns {{ command: string, args: string[] }}
|
|
94
93
|
*/
|
|
95
94
|
export function bridgeCommand(kind) {
|
|
96
95
|
if (!Object.hasOwn(BRIDGES, kind)) throw new Error(`Unknown bridge: ${kind}; expected acp or antigravity`);
|
|
97
|
-
|
|
98
|
-
return { command: process.execPath, args: ['-e', BRIDGES[kind]] };
|
|
96
|
+
// Agents keep this command in their MCP configuration: name the ALP bundle's Node through app/current.
|
|
97
|
+
return { command: stablePath(process.execPath), args: ['-e', BRIDGES[kind]] };
|
|
99
98
|
}
|
|
100
99
|
|
|
101
100
|
/**
|
|
102
|
-
* Whether an MCP server entry is one of ALP's bridge launchers: the `-e` source, or
|
|
103
|
-
* executable
|
|
101
|
+
* Whether an MCP server entry is one of ALP's bridge launchers: the `-e` source, or `alp bridge <kind>`
|
|
102
|
+
* as the single-file executable of 0.0.1-beta.5/6 wrote it (only when its command is named alp, so another server is kept).
|
|
104
103
|
* @param {'acp' | 'antigravity'} kind
|
|
105
104
|
* @param {unknown} args
|
|
106
105
|
* @param {unknown} [command]
|
|
@@ -109,5 +108,5 @@ export function isBridgeArgs(kind, args, command = undefined) {
|
|
|
109
108
|
if (!Array.isArray(args)) return false;
|
|
110
109
|
const marker = kind === 'antigravity' ? '// ALP Antigravity bridge v1' : undefined;
|
|
111
110
|
if (marker && args.some(arg => typeof arg === 'string' && arg.startsWith(marker))) return true;
|
|
112
|
-
return typeof command === 'string' &&
|
|
111
|
+
return typeof command === 'string' && isExecutableName(command) && args.length === 2 && args[0] === 'bridge' && args[1] === kind;
|
|
113
112
|
}
|
package/src/packaged.js
CHANGED
|
@@ -1,21 +1,19 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
-
import os from 'node:os';
|
|
1
|
+
import { existsSync, readFileSync, realpathSync } from 'node:fs';
|
|
4
2
|
import path from 'node:path';
|
|
5
3
|
|
|
6
4
|
/**
|
|
7
|
-
* ALP
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* another ALP process asks this module for the command instead of spawning `process.execPath`.
|
|
5
|
+
* How ALP starts its own processes, and where its bundle lives. ALP always runs under Node: from npm
|
|
6
|
+
* (`node cli.js`, `node alpd.js`) or from the ALP bundle (t-1807), which is the same npm install
|
|
7
|
+
* beside an official Node release, started by `bin/alp`:
|
|
11
8
|
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
9
|
+
* <app>/<version>/{bin/alp, node/bin/node, lib/node_modules/@anhlp/alp-cli, alp-bundle.json}
|
|
10
|
+
* <app>/current → <version> (install.sh and `alp update` move it)
|
|
11
|
+
*
|
|
12
|
+
* Paths that outlive this process (a launchd/systemd service, alpd's install record) name the bundle
|
|
13
|
+
* through `current`, so an update never leaves them on a removed version.
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
/** Subcommands of the executable that run each ALP role (the npm CLI understands them too). */
|
|
16
|
+
/** Subcommands of `alp` that run each ALP role in that process (`alp daemon run`, `alp web serve`, `alp bridge acp`). */
|
|
19
17
|
export const ROLE_ARGS = Object.freeze({
|
|
20
18
|
daemon: Object.freeze(['daemon', 'run']),
|
|
21
19
|
web: Object.freeze(['web', 'serve']),
|
|
@@ -24,34 +22,15 @@ export const ROLE_ARGS = Object.freeze({
|
|
|
24
22
|
});
|
|
25
23
|
|
|
26
24
|
/**
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
/** Called once by the executable's entry. @param {PackagedRegistration} registration */
|
|
32
|
-
export function registerPackaged(registration) {
|
|
33
|
-
if (!registration || typeof registration.version !== 'string') throw new TypeError('registerPackaged needs a version');
|
|
34
|
-
// assetDir rides along so dependency-free adapters (native-terminal.js) can reach the cache via globalThis alone.
|
|
35
|
-
Object.defineProperty(globalThis, KEY, { value: Object.freeze({ ...registration, assetDir: () => assetDir() }), configurable: true, enumerable: false, writable: false });
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/** The registration when this process is the ALP executable, else undefined. @returns {PackagedRegistration | undefined} */
|
|
39
|
-
export function packagedInfo() { return /** @type {any} */ (globalThis)[KEY]; }
|
|
40
|
-
|
|
41
|
-
/** Whether this process is the self-contained ALP executable. */
|
|
42
|
-
export function isPackaged() { return packagedInfo() !== undefined; }
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* A string only ALP's executable carries: its generated entry embeds it, so discovery can tell ALP
|
|
46
|
-
* from an unrelated native program that happens to be called `alp` without running it.
|
|
25
|
+
* Whether `file` is named like the `alp` command (alp, alp.exe, alp.cmd) rather than a script: an
|
|
26
|
+
* install record or service written by the single-file executable of 0.0.1-beta.5/6 names it, and the
|
|
27
|
+
* bundle's launcher keeps that name.
|
|
28
|
+
* @param {string} file
|
|
47
29
|
*/
|
|
48
|
-
export const
|
|
30
|
+
export const isExecutableName = file => /^alp(\.exe|\.cmd)?$/i.test(file.split(/[\\/]/).pop() ?? '');
|
|
49
31
|
|
|
50
|
-
/**
|
|
51
|
-
export const
|
|
52
|
-
|
|
53
|
-
/** Whether `file` is this process's own ALP executable, whatever it is called (alp-darwin-arm64, a rename). @param {unknown} file */
|
|
54
|
-
export const isSelf = file => isPackaged() && typeof file === 'string' && samePath(file, process.execPath);
|
|
32
|
+
/** A file path that names a JavaScript entry rather than a command. @param {string} file */
|
|
33
|
+
export const isScript = file => /\.[cm]?js$/i.test(file);
|
|
55
34
|
|
|
56
35
|
/** The canonical form of a path: symlinks resolved when it exists, case-folded where the filesystem usually is. @param {string} file */
|
|
57
36
|
const canonical = file => {
|
|
@@ -60,12 +39,9 @@ const canonical = file => {
|
|
|
60
39
|
return process.platform === 'darwin' || process.platform === 'win32' ? resolved.toLowerCase() : resolved;
|
|
61
40
|
};
|
|
62
41
|
|
|
63
|
-
/** Whether two paths name the same file (a symlink
|
|
42
|
+
/** Whether two paths name the same file (a symlink, or a differently cased path on macOS/Windows). @param {string} a @param {string} b */
|
|
64
43
|
export const samePath = (a, b) => canonical(a) === canonical(b);
|
|
65
44
|
|
|
66
|
-
/** A file path that names a JavaScript entry rather than an executable. @param {string} file */
|
|
67
|
-
export const isScript = file => /\.[cm]?js$/i.test(file);
|
|
68
|
-
|
|
69
45
|
/** The role's argument prefix. @param {keyof typeof ROLE_ARGS} role */
|
|
70
46
|
function roleArgs(role) {
|
|
71
47
|
const args = ROLE_ARGS[role];
|
|
@@ -74,20 +50,68 @@ function roleArgs(role) {
|
|
|
74
50
|
}
|
|
75
51
|
|
|
76
52
|
/**
|
|
77
|
-
*
|
|
78
|
-
*
|
|
53
|
+
* @typedef {{ root: string, version: string, platform: string, app: string, current?: string }} BundleInfo
|
|
54
|
+
* root: the bundle directory (real path); app: its parent; current: `<app>/current` when it points at root.
|
|
55
|
+
*/
|
|
56
|
+
|
|
57
|
+
const bundles = new Map();
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The ALP bundle this Node belongs to, or undefined for any other Node (an npm install).
|
|
61
|
+
* @param {string} [execPath]
|
|
62
|
+
* @returns {BundleInfo | undefined}
|
|
63
|
+
*/
|
|
64
|
+
export function bundleInfo(execPath = process.execPath) {
|
|
65
|
+
if (bundles.has(execPath)) return bundles.get(execPath);
|
|
66
|
+
let info;
|
|
67
|
+
try {
|
|
68
|
+
const real = realpathSync(execPath);
|
|
69
|
+
// node/bin/node on macOS and Linux, node/node.exe on Windows.
|
|
70
|
+
const nodeDir = path.basename(path.dirname(real)) === 'bin' ? path.dirname(path.dirname(real)) : path.dirname(real);
|
|
71
|
+
const root = path.dirname(nodeDir);
|
|
72
|
+
if (path.basename(nodeDir) === 'node') {
|
|
73
|
+
const manifest = JSON.parse(readFileSync(path.join(root, 'alp-bundle.json'), 'utf8'));
|
|
74
|
+
if (manifest?.name === 'alp' && typeof manifest.version === 'string') {
|
|
75
|
+
const app = path.dirname(root);
|
|
76
|
+
const current = path.join(app, 'current');
|
|
77
|
+
info = { root, version: manifest.version, platform: String(manifest.platform ?? ''), app, ...(existsSync(current) && samePath(current, root) ? { current } : {}) };
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
} catch {}
|
|
81
|
+
bundles.set(execPath, info);
|
|
82
|
+
return info;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* `file` named through `<app>/current` when it lies inside this process's bundle and `current` points
|
|
87
|
+
* at that bundle; otherwise `file` unchanged. For paths written to disk for later processes.
|
|
88
|
+
* @param {string} file
|
|
89
|
+
* @param {{ bundle?: BundleInfo | undefined }} [options]
|
|
90
|
+
*/
|
|
91
|
+
export function stablePath(file, { bundle = bundleInfo() } = {}) {
|
|
92
|
+
if (!bundle?.current) return file;
|
|
93
|
+
let real;
|
|
94
|
+
try { real = realpathSync(file); } catch { return file; }
|
|
95
|
+
const relative = path.relative(bundle.root, real);
|
|
96
|
+
if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return file;
|
|
97
|
+
return path.join(bundle.current, relative);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The command that starts ALP's `role` from this process: `script` under this Node.
|
|
79
102
|
* @param {keyof typeof ROLE_ARGS} role
|
|
80
103
|
* @param {{ script: string, args?: string[] }} options
|
|
81
104
|
* @returns {{ command: string, args: string[] }}
|
|
82
105
|
*/
|
|
83
106
|
export function selfCommand(role, { script, args = [] }) {
|
|
84
|
-
|
|
107
|
+
roleArgs(role);
|
|
85
108
|
return { command: process.execPath, args: [script, ...args] };
|
|
86
109
|
}
|
|
87
110
|
|
|
88
111
|
/**
|
|
89
112
|
* The command that runs an `entry` found on disk (an install record, a service definition, a CLI
|
|
90
|
-
* on PATH): a script runs under `execPath`; an
|
|
113
|
+
* on PATH): a script runs under `execPath`; an `alp` command (the bundle's launcher, or what a
|
|
114
|
+
* 0.0.1-beta.5/6 single-file install recorded) runs its role subcommand.
|
|
91
115
|
* @param {string} entry
|
|
92
116
|
* @param {keyof typeof ROLE_ARGS} role
|
|
93
117
|
* @param {string[]} [args]
|
|
@@ -96,160 +120,19 @@ export function selfCommand(role, { script, args = [] }) {
|
|
|
96
120
|
* @returns {{ command: string, args: string[] }}
|
|
97
121
|
*/
|
|
98
122
|
export function entryCommand(entry, role, args = [], execPath = process.execPath, { scriptOnly = false } = {}) {
|
|
99
|
-
|
|
100
|
-
// (alpd.js, alpd.ts, a launcher) is a script.
|
|
101
|
-
if (scriptOnly || isScript(entry) || !(isExecutableName(entry) || isSelf(entry))) {
|
|
102
|
-
// The executable cannot run a script itself; a script entry then needs a real Node.
|
|
103
|
-
if (isPackaged() && execPath === process.execPath) return { command: 'node', args: [entry, ...args] };
|
|
104
|
-
return { command: execPath, args: [entry, ...args] };
|
|
105
|
-
}
|
|
123
|
+
if (scriptOnly || isScript(entry) || !isExecutableName(entry)) return { command: execPath, args: [entry, ...args] };
|
|
106
124
|
return { command: entry, args: [...roleArgs(role), ...args] };
|
|
107
125
|
}
|
|
108
126
|
|
|
109
127
|
/**
|
|
110
|
-
* The command that runs a user's JavaScript file (a fake provider, an npm cmd shim on Windows)
|
|
111
|
-
* with this process's runtime. The executable runs it as Bun does when BUN_BE_BUN is set.
|
|
128
|
+
* The command that runs a user's JavaScript file (a fake provider, an npm cmd shim on Windows) with this Node.
|
|
112
129
|
* @param {string} script
|
|
113
130
|
* @param {string[]} [args]
|
|
114
131
|
* @returns {{ command: string, args: string[], env?: Record<string, string> }}
|
|
115
132
|
*/
|
|
116
133
|
export function scriptCommand(script, args = []) {
|
|
117
|
-
if (isPackaged()) return { command: process.execPath, args: [script, ...args], env: { BUN_BE_BUN: '1' } };
|
|
118
134
|
return { command: process.execPath, args: [script, ...args] };
|
|
119
135
|
}
|
|
120
136
|
|
|
121
|
-
/**
|
|
122
|
-
export function
|
|
123
|
-
|
|
124
|
-
/** Where this process's own entry lives: the executable when packaged, else `script`. @param {string} script */
|
|
125
|
-
export function selfEntry(script) { return isPackaged() ? process.execPath : script; }
|
|
126
|
-
|
|
127
|
-
const sha256 = (/** @type {Buffer} */ bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
128
|
-
const MARKER = '.alp-assets.json';
|
|
129
|
-
|
|
130
|
-
/** The directory the executable's assets are extracted to. @param {string} version @param {NodeJS.ProcessEnv} [env] */
|
|
131
|
-
export function assetCacheDir(version, env = process.env) {
|
|
132
|
-
if (!/^[0-9A-Za-z][0-9A-Za-z.+-]*$/.test(version)) throw new TypeError(`Invalid ALP version for the asset cache: ${JSON.stringify(version)}`);
|
|
133
|
-
const home = env.ALP_HOME ? path.resolve(env.ALP_HOME) : path.join(os.homedir(), '.alp');
|
|
134
|
-
return path.join(home, 'cache', version);
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
/** The manifest digest the marker records, so a changed build never reuses an older extraction. @param {Record<string, PackagedAsset>} assets */
|
|
138
|
-
const manifestDigest = assets => sha256(Buffer.from(JSON.stringify(Object.keys(assets).sort().map(name => [name, assets[name].sha256, assets[name].size]))));
|
|
139
|
-
|
|
140
|
-
/** Rejects names that would leave the cache directory. @param {string} name */
|
|
141
|
-
function assertAssetName(name) {
|
|
142
|
-
if (!name || path.isAbsolute(name) || name.split(/[\\/]/).some(part => part === '..' || part === '' || part === '.') || name === MARKER) throw new Error(`Invalid packaged asset name: ${JSON.stringify(name)}`);
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/** A private directory we own, not a symlink. @param {string} directory */
|
|
146
|
-
function assertPrivate(directory) {
|
|
147
|
-
const info = lstatSync(directory);
|
|
148
|
-
if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`ALP asset cache is not a directory: ${directory}`);
|
|
149
|
-
if (process.platform !== 'win32' && (info.uid !== process.getuid?.() || (info.mode & 0o077) !== 0)) throw new Error(`ALP asset cache must be private to the current user (0700): ${directory}`);
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/** The cache parent (<ALP_HOME>/cache): a real directory of ours that nobody else may write into. @param {string} directory */
|
|
153
|
-
function assertParent(directory) {
|
|
154
|
-
const info = lstatSync(directory);
|
|
155
|
-
if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`ALP asset cache parent is not a directory: ${directory}`);
|
|
156
|
-
if (process.platform !== 'win32' && (info.uid !== process.getuid?.() || (info.mode & 0o022) !== 0)) throw new Error(`ALP asset cache parent must belong to the current user and not be group- or world-writable: ${directory}`);
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
/** Whether `directory` holds exactly this manifest's extraction: every file's size and sha256 match. */
|
|
160
|
-
function extracted(/** @type {string} */ directory, /** @type {string} */ digest, /** @type {Record<string, PackagedAsset>} */ assets) {
|
|
161
|
-
try {
|
|
162
|
-
if (JSON.parse(readFileSync(path.join(directory, MARKER), 'utf8')).digest !== digest) return false;
|
|
163
|
-
return Object.entries(assets).every(([name, asset]) => {
|
|
164
|
-
const file = path.join(directory, name);
|
|
165
|
-
const info = lstatSync(file);
|
|
166
|
-
return info.isFile() && info.size === asset.size && sha256(readFileSync(file)) === asset.sha256;
|
|
167
|
-
});
|
|
168
|
-
} catch { return false; }
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
const STAGING = /^(.+)\.tmp-(\d+)-(\d+)$/;
|
|
172
|
-
const STALE_MS = 60 * 60 * 1000;
|
|
173
|
-
const SWEEP_MIN_MS = 10 * 60 * 1000;
|
|
174
|
-
|
|
175
|
-
/** Removes staging directories another process left behind (it crashed, or was killed mid-extraction). @param {string} parent */
|
|
176
|
-
function sweepStaging(parent) {
|
|
177
|
-
let names;
|
|
178
|
-
try { names = readdirSync(parent); } catch { return; }
|
|
179
|
-
for (const name of names) {
|
|
180
|
-
const match = STAGING.exec(name);
|
|
181
|
-
if (!match) continue;
|
|
182
|
-
const pid = Number(match[2]);
|
|
183
|
-
if (pid === process.pid) continue;
|
|
184
|
-
const age = Date.now() - Number(match[3]);
|
|
185
|
-
// Another pid namespace (a bind-mounted ALP_HOME) may hold a live extractor this one cannot see,
|
|
186
|
-
// so even a dead-looking pid's staging is kept for a few minutes; past an hour nothing is running.
|
|
187
|
-
if (age < SWEEP_MIN_MS) continue;
|
|
188
|
-
let alive = false;
|
|
189
|
-
try { process.kill(pid, 0); alive = true; } catch (error) { alive = /** @type {any} */ (error)?.code === 'EPERM'; }
|
|
190
|
-
if (alive && age < STALE_MS) continue;
|
|
191
|
-
try { rmSync(path.join(parent, name), { recursive: true, force: true }); } catch {}
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
/**
|
|
196
|
-
* The directory holding the executable's embedded assets (templates, the web app, the native
|
|
197
|
-
* terminal helper), extracted once per version to `<ALP_HOME or ~/.alp>/cache/<version>/` and
|
|
198
|
-
* checked against the build's sha256 manifest. Undefined when not packaged: callers then use the
|
|
199
|
-
* files beside their scripts, as before.
|
|
200
|
-
* @param {{ env?: NodeJS.ProcessEnv, info?: PackagedRegistration }} [options]
|
|
201
|
-
* @returns {string | undefined}
|
|
202
|
-
*/
|
|
203
|
-
export function assetDir({ env = process.env, info = packagedInfo() } = {}) {
|
|
204
|
-
if (!info) return undefined;
|
|
205
|
-
const assets = info.assets ?? {};
|
|
206
|
-
const directory = assetCacheDir(info.version, env);
|
|
207
|
-
const digest = manifestDigest(assets);
|
|
208
|
-
// Checked once per process and directory; later calls (every template read) reuse the answer.
|
|
209
|
-
const key = `${directory}\0${digest}`;
|
|
210
|
-
if (verified.has(key) && existsSync(path.join(directory, MARKER))) return directory;
|
|
211
|
-
const result = extract(directory, digest, assets, info.version);
|
|
212
|
-
verified.add(key);
|
|
213
|
-
return result;
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
const verified = new Set();
|
|
217
|
-
|
|
218
|
-
/** @param {string} directory @param {string} digest @param {Record<string, PackagedAsset>} assets @param {string} version */
|
|
219
|
-
function extract(directory, digest, assets, version) {
|
|
220
|
-
const parent = path.dirname(directory);
|
|
221
|
-
mkdirSync(parent, { recursive: true, mode: 0o700 });
|
|
222
|
-
assertParent(parent);
|
|
223
|
-
sweepStaging(parent);
|
|
224
|
-
if (existsSync(directory)) {
|
|
225
|
-
assertPrivate(directory);
|
|
226
|
-
if (extracted(directory, digest, assets)) return directory;
|
|
227
|
-
}
|
|
228
|
-
const staging = `${directory}.tmp-${process.pid}-${Date.now()}`;
|
|
229
|
-
mkdirSync(staging, { mode: 0o700 });
|
|
230
|
-
try {
|
|
231
|
-
for (const [name, asset] of Object.entries(assets)) {
|
|
232
|
-
assertAssetName(name);
|
|
233
|
-
const bytes = readFileSync(asset.path);
|
|
234
|
-
if (bytes.length !== asset.size || sha256(bytes) !== asset.sha256) throw new Error(`Packaged asset ${name} does not match its manifest`);
|
|
235
|
-
const target = path.join(staging, name);
|
|
236
|
-
mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
237
|
-
writeFileSync(target, bytes, { mode: 0o600 });
|
|
238
|
-
if (/(^|\/)terminal-owner(\.exe)?$/.test(name)) chmodSync(target, 0o700);
|
|
239
|
-
}
|
|
240
|
-
writeFileSync(path.join(staging, MARKER), JSON.stringify({ version, digest }), { mode: 0o600 });
|
|
241
|
-
// Another ALP process may have finished the same extraction first; its copy is equivalent.
|
|
242
|
-
if (existsSync(directory)) {
|
|
243
|
-
assertPrivate(directory);
|
|
244
|
-
if (extracted(directory, digest, assets)) { rmSync(staging, { recursive: true, force: true }); return directory; }
|
|
245
|
-
rmSync(directory, { recursive: true, force: true });
|
|
246
|
-
}
|
|
247
|
-
renameSync(staging, directory);
|
|
248
|
-
if (!extracted(directory, digest, assets)) throw new Error(`ALP asset cache ${directory} is incomplete after extraction`);
|
|
249
|
-
} catch (error) {
|
|
250
|
-
rmSync(staging, { recursive: true, force: true });
|
|
251
|
-
if (existsSync(directory) && extracted(directory, digest, assets)) return directory;
|
|
252
|
-
throw error;
|
|
253
|
-
}
|
|
254
|
-
return directory;
|
|
255
|
-
}
|
|
137
|
+
/** Where this process's own entry lives, for records that later processes read: `script`, through `current` in a bundle. @param {string} script */
|
|
138
|
+
export function selfEntry(script) { return stablePath(script); }
|
package/src/profiles.js
CHANGED
|
@@ -19,7 +19,7 @@ export const oracleProfiles = config => config?.profiles ?? [config?.claude, con
|
|
|
19
19
|
export const agentProfiles = (config, name) => {
|
|
20
20
|
if (!config) return [];
|
|
21
21
|
if (name === 'oracle') return oracleProfiles(config).map(parseProfile);
|
|
22
|
-
const { autocompact, ...legacy } = config;
|
|
22
|
+
const { autocompact, commands, ...legacy } = config;
|
|
23
23
|
return (config.profiles ?? [legacy]).map(parseProfile);
|
|
24
24
|
};
|
|
25
25
|
|
|
@@ -56,7 +56,7 @@ export function normalizeAgentProfiles(config, name) {
|
|
|
56
56
|
if (config.profiles) return { ...config, profiles: config.profiles.map(profile => typeof profile === 'string' ? profile : profileString(profile)), autocompact: config.autocompact ?? 'auto' };
|
|
57
57
|
const profiles = agentProfiles(config, name);
|
|
58
58
|
if (!profiles.length || profiles.some(profile => !profile.model)) return config;
|
|
59
|
-
return { profiles: profiles.map(profile => profileString({ ...profile, provider: profile.provider ?? profile.model.split(':')[0] })), autocompact: config.autocompact ?? 'auto' };
|
|
59
|
+
return { profiles: profiles.map(profile => profileString({ ...profile, provider: profile.provider ?? profile.model.split(':')[0] })), autocompact: config.autocompact ?? 'auto', ...(config.commands ? { commands: config.commands } : {}) };
|
|
60
60
|
}
|
|
61
61
|
|
|
62
62
|
export const profileModel = config => config?.model ? config.model.includes(':') ? config.model : `${config.provider}:${config.model}` : undefined;
|
|
@@ -128,7 +128,7 @@ export async function syncTemplateProfiles(settings, options = {}) {
|
|
|
128
128
|
for (const name of new Set([...Object.keys(previous[id] ?? {}), ...(options.replaceModels ? Object.keys(current) : []), ...Object.keys(desired)])) {
|
|
129
129
|
const config = current[name];
|
|
130
130
|
if (!options.replaceModels && config && profileFingerprint(config, name) !== previous[id]?.[name]) continue;
|
|
131
|
-
if (desired[name]) current[name] = { ...desired[name], autocompact: config?.autocompact ?? desired[name].autocompact };
|
|
131
|
+
if (desired[name]) current[name] = { ...desired[name], autocompact: config?.autocompact ?? desired[name].autocompact, ...(config?.commands ? { commands: config.commands } : {}) };
|
|
132
132
|
else delete current[name];
|
|
133
133
|
}
|
|
134
134
|
if (Object.keys(current).length) next.team[id] = current;
|
package/src/providers.js
CHANGED
|
@@ -3,7 +3,7 @@ import { readdir, readFile } from 'node:fs/promises';
|
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { AlpError } from './errors.js';
|
|
5
5
|
import { settingsKeys, unknownMessage } from './validation.js';
|
|
6
|
-
import {
|
|
6
|
+
import { scriptCommand } from './packaged.js';
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* ACP providers (ALPD §46): agents that speak the Agent Client Protocol, such as Gemini
|
|
@@ -101,7 +101,6 @@ export function acpModel(model) {
|
|
|
101
101
|
* native executable it calls, or the Node script, under this Node. A bare name with an .exe or
|
|
102
102
|
* .com on PATH, any other command, and every command elsewhere are returned as they are.
|
|
103
103
|
* @param {string} command @param {string[]} [args] @param {Record<string, string | undefined>} [env]
|
|
104
|
-
* In the ALP executable a Node script runs with the executable as its Bun runtime, via `env` to add.
|
|
105
104
|
* @returns {{ command: string, args: string[], env?: Record<string, string> }}
|
|
106
105
|
*/
|
|
107
106
|
export function launchCommand(command, args = [], env = process.env) {
|
|
@@ -115,7 +114,7 @@ export function launchCommand(command, args = [], env = process.env) {
|
|
|
115
114
|
// for a Node script. Anything else (a hand-written batch file) stays refused by spawn, as before.
|
|
116
115
|
const text = readFileSync(shim, 'utf8');
|
|
117
116
|
const script = /"%_prog%"((?:\s+[^\s"]+)*)\s+"%~?dp0%\\?([^"]+)"\s+%\*/i.exec(text);
|
|
118
|
-
if (script) { const flags = script[1].split(/\s+/).filter(Boolean); const run = scriptCommand(path.join(directory, script[2]), args); return { command: run.command, args:
|
|
117
|
+
if (script) { const flags = script[1].split(/\s+/).filter(Boolean); const run = scriptCommand(path.join(directory, script[2]), args); return { command: run.command, args: [...flags, ...run.args] }; }
|
|
119
118
|
const native = /^\s*"%~?dp0%\\?([^"]+\.(?:exe|com))"\s+%\*/im.exec(text);
|
|
120
119
|
if (native) return { command: path.join(directory, native[1]), args };
|
|
121
120
|
break;
|
package/src/tasks.d.ts
CHANGED
|
@@ -117,12 +117,13 @@ export function gatesOf(task: Task, tasks: Task[]): string[];
|
|
|
117
117
|
export const GATE_OPTIONS: number;
|
|
118
118
|
export const GATE_OPTION_CHARS: number;
|
|
119
119
|
export const GATE_CHANNELS: GateChannel[];
|
|
120
|
+
export const GATE_REJECT_LABELS: string[];
|
|
120
121
|
export function addGate(projectRoot: string, id: string, gate: { kind: GateKind; note?: string; until?: string; ref?: string | number; options?: string[] }, by: string): Promise<Task>;
|
|
121
122
|
export function resolveGate(projectRoot: string, id: string, gateId: string, resolve: { by: string; note?: string; remove?: boolean; ifRev?: number; choice?: string; channel?: GateChannel }): Promise<Task>;
|
|
122
123
|
export function rejectGate(projectRoot: string, id: string, gateId: string, reject: { by: string; reason?: string; ifRev?: number; channel?: GateChannel }): Promise<Task>;
|
|
123
124
|
export type GateDecision = { task: Task; gate: TaskGate; decision: 'approved' | 'rejected'; record: NonNullable<TaskGate['resolved'] | TaskGate['rejected']> };
|
|
124
125
|
export function gateDecisions(tasks: Task[]): GateDecision[];
|
|
125
|
-
export function markGateNotified(projectRoot: string, id: string, gateId: string, decision: 'approved' | 'rejected'): Promise<boolean>;
|
|
126
|
+
export function markGateNotified(projectRoot: string, id: string, gateId: string, decision: 'approved' | 'rejected', at?: string): Promise<boolean>;
|
|
126
127
|
export function checkGates(projectRoot: string, gh: (args: string[], options: { cwd: string }) => Promise<string>): Promise<{ cleared: Array<{ task: string; gate: string; detail: string }>; pending: Array<{ task: string; gate: string; detail: string }>; errors: Array<{ task: string; gate: string; error: string }> }>;
|
|
127
128
|
export function compactTasks(projectRoot: string, options: { days?: number; dryRun?: boolean }, by: string): Promise<Array<{ id: string; before: number; after: number }>>;
|
|
128
129
|
export type TaskBatch = {
|
package/src/tasks.js
CHANGED
|
@@ -743,12 +743,22 @@ export function addGate(projectRoot, id, { kind, note, until, ref, options } = {
|
|
|
743
743
|
export const GATE_OPTIONS = 10;
|
|
744
744
|
export const GATE_OPTION_CHARS = 200;
|
|
745
745
|
export const GATE_CHANNELS = ['paseo', 'web', 'cli'];
|
|
746
|
+
/**
|
|
747
|
+
* The Reject answer a gate card adds after its options, in every language ALP writes it
|
|
748
|
+
* (packages/runtime/src/language.ts, `reject`). An option that is one would hide that Reject
|
|
749
|
+
* and approve the gate instead, so no option may be one (t-595d).
|
|
750
|
+
*/
|
|
751
|
+
export const GATE_REJECT_LABELS = ['Reject', 'Từ chối'];
|
|
752
|
+
const labelKey = text => text.normalize('NFC').trim().toLowerCase();
|
|
753
|
+
const REJECT_KEYS = new Set(GATE_REJECT_LABELS.map(labelKey));
|
|
746
754
|
|
|
747
|
-
/** The answers a human gate offers its approver: at most 10 distinct, nonempty, each at most 200 characters. */
|
|
755
|
+
/** The answers a human gate offers its approver: at most 10 distinct, nonempty, each at most 200 characters, none of them Reject. */
|
|
748
756
|
function gateOptions(value) {
|
|
749
757
|
if (!Array.isArray(value) || value.length > GATE_OPTIONS || !value.every(item => typeof item === 'string' && !!item.trim() && item.trim().length <= GATE_OPTION_CHARS)) {
|
|
750
758
|
fail('INVALID_TASK', `options must list at most ${GATE_OPTIONS} nonempty answers of at most ${GATE_OPTION_CHARS} characters`);
|
|
751
759
|
}
|
|
760
|
+
const reserved = value.find(item => REJECT_KEYS.has(labelKey(item)));
|
|
761
|
+
if (reserved !== undefined) fail('INVALID_TASK', `"${reserved.trim()}" is the Reject answer every gate card already offers; name the options for approving only`);
|
|
752
762
|
return [...new Set(value.map(item => item.trim()))];
|
|
753
763
|
}
|
|
754
764
|
|
|
@@ -828,17 +838,18 @@ export function gateDecisions(tasks) {
|
|
|
828
838
|
}
|
|
829
839
|
|
|
830
840
|
/**
|
|
831
|
-
* Marks a decision reported, under the lock, and returns whether this call marked it
|
|
832
|
-
*
|
|
841
|
+
* Marks a decision reported, under the lock, and returns whether this call marked it. alpd marks
|
|
842
|
+
* it once main has taken the mail (t-595d), so a decision is reported at least once; with `at`,
|
|
843
|
+
* only the decision made then is marked, never a later one that replaced it.
|
|
833
844
|
* Marking does not change the task's rev, so an open card's ifRev stays valid.
|
|
834
845
|
*/
|
|
835
|
-
export function markGateNotified(projectRoot, id, gateId, decision) {
|
|
846
|
+
export function markGateNotified(projectRoot, id, gateId, decision, at) {
|
|
836
847
|
return locked(projectRoot, async () => {
|
|
837
848
|
const { tasks } = await loadTasks(projectRoot);
|
|
838
849
|
const task = tasks.find(entry => entry.id === id);
|
|
839
850
|
const gate = task?.gates?.find(entry => entry.id === gateId);
|
|
840
851
|
const record = decision === 'approved' ? gate?.resolved : gate?.rejected;
|
|
841
|
-
if (!task || !record?.channel || record.notified) return false;
|
|
852
|
+
if (!task || !record?.channel || record.notified || (at !== undefined && record.at !== at)) return false;
|
|
842
853
|
record.notified = now();
|
|
843
854
|
await save(projectRoot, task);
|
|
844
855
|
return true;
|
package/src/template-path.js
CHANGED
|
@@ -1,12 +1,7 @@
|
|
|
1
1
|
import { existsSync } from 'node:fs';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import { pathToFileURL } from 'node:url';
|
|
4
|
-
import { assetDir } from './packaged.js';
|
|
5
2
|
|
|
6
|
-
/** Source packages carry templates beside src; legacy bundles live one directory deeper
|
|
3
|
+
/** Source packages carry templates beside src; legacy bundles live one directory deeper. */
|
|
7
4
|
export function shippedTemplateRoot() {
|
|
8
|
-
const assets = assetDir();
|
|
9
|
-
if (assets) return pathToFileURL(path.join(assets, 'templates') + path.sep);
|
|
10
5
|
const packaged = new URL('../templates/', import.meta.url);
|
|
11
6
|
const candidates = [packaged, new URL('../../templates/', import.meta.url), new URL('../../../templates/', import.meta.url), new URL('../../../../templates/', import.meta.url), new URL('../../../../../templates/', import.meta.url)];
|
|
12
7
|
return candidates.find(candidate => existsSync(candidate)) ?? packaged;
|
package/src/types.d.ts
CHANGED
|
@@ -4,6 +4,8 @@ export type AgentProfilesConfig = {
|
|
|
4
4
|
/** "provider:model", "provider:*" for any model of that provider, or the earlier object form. */
|
|
5
5
|
profiles?: Array<string | AgentModelConfig>;
|
|
6
6
|
autocompact?: AutoCompact;
|
|
7
|
+
/** The runtime's own commands and skills the "/" list offers besides the agent's ALP skills; none by default (t-efa3). */
|
|
8
|
+
commands?: string[];
|
|
7
9
|
claude?: AgentModelConfig;
|
|
8
10
|
codex?: AgentModelConfig;
|
|
9
11
|
} & AgentModelConfig;
|
package/src/validation.js
CHANGED
|
@@ -118,8 +118,10 @@ export function validateSettings(settings, source) {
|
|
|
118
118
|
const where = `${key}.${team}.${agent}`;
|
|
119
119
|
check(object(config), `${where} must be an object`);
|
|
120
120
|
if (config.autocompact !== undefined) validateAutoCompact(config.autocompact, check, `${where}.autocompact`);
|
|
121
|
+
// t-efa3: the runtime's own commands and skills its "/" list offers besides the agent's ALP skills.
|
|
122
|
+
if (config.commands !== undefined) check(Array.isArray(config.commands) && config.commands.every(name => typeof name === 'string' && /^[^\s/]{1,256}$/.test(name)), `${where}.commands must be a list of command names, without whitespace or /`);
|
|
121
123
|
if (Object.hasOwn(config, 'profiles')) {
|
|
122
|
-
check(Object.keys(config).every(key => ['profiles', 'autocompact'].includes(key)), `${where}: use profiles and
|
|
124
|
+
check(Object.keys(config).every(key => ['profiles', 'autocompact', 'commands'].includes(key)), `${where}: use profiles, autocompact and commands`);
|
|
123
125
|
check(Array.isArray(config.profiles) && config.profiles.length > 0, `${where}.profiles must be a nonempty list`);
|
|
124
126
|
const models = [];
|
|
125
127
|
for (const [index, entry] of config.profiles.entries()) {
|
|
@@ -143,14 +145,14 @@ export function validateSettings(settings, source) {
|
|
|
143
145
|
check(new Set(models).size === models.length, `${where}.profiles must not repeat the same model`);
|
|
144
146
|
check(agent !== 'main' || config.profiles.length === 1, `${where}.profiles: main runs on exactly one model`);
|
|
145
147
|
} else if (agent === 'oracle') {
|
|
146
|
-
const entries = Object.entries(config).filter(([key]) => key !== 'autocompact');
|
|
148
|
+
const entries = Object.entries(config).filter(([key]) => key !== 'autocompact' && key !== 'commands');
|
|
147
149
|
check(entries.length > 0 && entries.every(([provider]) => ['claude', 'codex'].includes(provider)), `${where} must define profiles or claude/codex lenses`);
|
|
148
150
|
for (const [provider, lens] of entries) {
|
|
149
151
|
validateChoice(lens, `${where}.${provider}`);
|
|
150
152
|
check(lens.provider === provider && nonempty(lens.model), `${where}.${provider}: specify matching provider and model`);
|
|
151
153
|
}
|
|
152
154
|
} else {
|
|
153
|
-
const { autocompact, ...legacy } = config;
|
|
155
|
+
const { autocompact, commands, ...legacy } = config;
|
|
154
156
|
validateChoice(legacy, where);
|
|
155
157
|
}
|
|
156
158
|
}
|