@anhlp/alp-client 0.0.0-beta.2 → 0.0.1-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -1
- package/dist/acp-probe.d.ts +3 -2
- package/dist/acp-probe.js +11 -2
- package/dist/antigravity-probe.d.ts +1 -2
- package/dist/antigravity-probe.js +11 -5
- package/dist/command.js +3 -1
- package/dist/doctor.d.ts +8 -0
- package/dist/doctor.js +276 -13
- package/dist/index.d.ts +123 -8
- package/dist/index.js +332 -52
- package/dist/integration-lock.d.ts +37 -0
- package/dist/integration-lock.js +199 -0
- package/dist/mcp-probe.js +1 -1
- package/dist/portable.d.ts +3 -1
- package/dist/portable.js +11 -2
- package/dist/render.js +3 -0
- package/dist/rpc/handshake.d.ts +6 -1
- package/dist/rpc/handshake.js +4 -2
- package/dist/rpc/registry.d.ts +227 -0
- package/dist/rpc/registry.js +223 -0
- package/dist/rpc/terminal-directory.d.ts +24 -0
- package/dist/rpc/terminal-directory.js +70 -0
- package/dist/service.d.ts +2 -2
- package/dist/service.js +3 -1
- package/dist/setup.d.ts +7 -1
- package/dist/setup.js +159 -32
- package/dist/supervise.d.ts +3 -1
- package/dist/supervise.js +26 -16
- package/package.json +11 -3
- package/src/acp-probe.js +10 -3
- package/src/antigravity-probe.js +12 -5
- package/src/command.js +3 -1
- package/src/doctor.d.ts +8 -0
- package/src/doctor.js +345 -3
- package/src/index.js +411 -55
- package/src/integration-lock.js +203 -0
- package/src/mcp-probe.js +1 -1
- package/src/portable.js +4 -1
- package/src/render.js +3 -0
- package/src/rpc/handshake.js +7 -2
- package/src/rpc/registry.js +229 -0
- package/src/rpc/terminal-directory.js +61 -0
- package/src/service.js +7 -3
- package/src/setup.js +201 -35
- package/src/supervise.d.ts +3 -1
- package/src/supervise.js +31 -19
package/README.md
CHANGED
|
@@ -11,14 +11,36 @@ and setup helpers.
|
|
|
11
11
|
- `@anhlp/alp-client` (Node): everything above plus `connect`, `AlpClient`, `connectSocket`,
|
|
12
12
|
`ensureDaemon`, the private-socket checks and lock helpers, unchanged for existing callers.
|
|
13
13
|
- `@anhlp/alp-client/ipc` (Node): `createSocketTransport` for a Unix socket or named pipe.
|
|
14
|
+
- `@anhlp/alp-client/integration-lock` (Node): `createIntegrationLock(home, name)`, the single-owner
|
|
15
|
+
lock of one integration service at `<home>/integrations/<name>.lock`, serialized by the exclusive
|
|
16
|
+
guard directory `<name>.lock.reclaim`. Each instance is single-use (`acquire`, then `setReady` and
|
|
17
|
+
`release` while it owns the lock); its recovery rules are in
|
|
18
|
+
[docs/modular-monorepo.md](../../docs/modular-monorepo.md).
|
|
14
19
|
|
|
15
20
|
Timeouts and aborts end only the caller's wait, and nothing is ever resent after a disconnect.
|
|
16
21
|
See [docs/alp/client-sdk.md](../../docs/alp/client-sdk.md) for the transport contract, the
|
|
17
22
|
request lifecycle, the old-to-new API table and what still waits on the protocol (Task 06) and
|
|
18
23
|
the gateway (Task 08).
|
|
19
24
|
|
|
20
|
-
`startIntegration` discovers an optional integration's descriptor and starts it detached with `--service`, so the entry writes its own log; discovery and the selected `ALP_HOME` are pinned by tests. Restarting is non-destructive: a daemon left running by an older install is reported as older than the current CLI and is never killed in place.
|
|
25
|
+
`startIntegration({ name, entry, home, args })` (or `startIntegration(name)`; `name` defaults to `web`) discovers an optional integration's descriptor and starts it detached with `--service` and then `args`, so the entry writes its own log; discovery and the selected `ALP_HOME` are pinned by tests. `name` is a single lowercase path segment (`assertIntegrationName`). With `entry`, that script runs with the current Node and no descriptor, environment or PATH discovery happens; a missing entry is an error even when a live owner would be reused. `web` is alp-dashboard, the service of the ALP CLI (`alp dashboard`): it is never discovered, so it needs its `entry`, and `"dashboard": { "enabled": false }` in the home's settings refuses it and no other integration. Everything once registered under `web` (`integrations/web.json`, the `alp-web-integration` binary, `ALP_WEB_INTEGRATION`) is the Paseo integration from before its rename; `discoverIntegration('paseo')` reads `ALP_PASEO_INTEGRATION`, then `ALP_WEB_INTEGRATION` for one release, then `ALP_INTEGRATION_ENTRY`. Errors name the integration, the entry and its log under `<home>/logs/integrations`. Either way a live owner of `integrations/<name>.lock` is reused, and the call resolves once that lock is ready and `<home>/<name>.json` names the same pid. Restarting is non-destructive: a daemon left running by an older install is reported as older than the current CLI and is never killed in place.
|
|
21
26
|
|
|
22
27
|
Build: `npm run build --workspace=@anhlp/alp-client`. Test: `npm run test --workspace=@anhlp/alp-client`.
|
|
23
28
|
|
|
24
29
|
Public imports use the package root and its explicitly exported subpaths. See [architecture, provider extension, compatibility and release instructions](../../docs/modular-monorepo.md).
|
|
30
|
+
|
|
31
|
+
`conversation(client)` from the portable entry wraps the conversation methods (capabilities
|
|
32
|
+
`session.fork`, `session.rewind`, `session.reload`, `session.resumeCommand` and
|
|
33
|
+
`session.configure.live`; docs/protocol/alp-json-rpc-v1.md §12.7–§12.9): `fork`, `rewind`, `reload`,
|
|
34
|
+
`resumeCommand`, `configure` and `configurePreview`. They change only the conversation, never a file.
|
|
35
|
+
`commands` (capability `session.commands`, §12.12) lists the slash commands and skills a composer offers after "/".
|
|
36
|
+
Each mutation is sent once: keep its `requestId` and `ifGeneration` (the generation `session.history`
|
|
37
|
+
answered) and send the identical request again only after a lost answer, which alpd answers with the
|
|
38
|
+
first result and `duplicate: true`. After a rewind, attached clients get `history.reset`: drop the
|
|
39
|
+
cached history and attach again with its generation. See
|
|
40
|
+
[docs/alp/client-sdk.md](../../docs/alp/client-sdk.md).
|
|
41
|
+
|
|
42
|
+
Terminal directory clients can use `watchTerminals(connection, {capabilities, onSnapshot,
|
|
43
|
+
onMode, onError})` from the portable entry. Install one per connection, await `ready`, and call
|
|
44
|
+
`close()` when leaving. It uses atomic scoped snapshots and cursor invalidations on hosts with
|
|
45
|
+
`terminal.watch`; `onMode('polling')` explicitly identifies the five-second older-host fallback.
|
|
46
|
+
Reconnect with a new helper and replace the directory from the reset snapshot.
|
package/dist/acp-probe.d.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* it also opens a session in `cwd`, as Paseo does, to read the models and modes the agent
|
|
6
6
|
* offers (ALPD §65); an agent that offers none leaves them out.
|
|
7
7
|
* @param {{ command: string, args?: string[], env?: Record<string, string>, label?: string, id?: string }} provider
|
|
8
|
-
* @param {{ cwd?: string, timeoutMs?: number, discover?: boolean }} [options]
|
|
8
|
+
* @param {{ cwd?: string, timeoutMs?: number, discover?: boolean, signal?: AbortSignal }} [options]
|
|
9
9
|
* @returns {Promise<{ protocolVersion: number, agent?: { name?: string, title?: string, version?: string }, loadSession: boolean, mcpHttp: boolean, authMethods: string[],
|
|
10
10
|
* models?: Array<{ id: string, label: string, description?: string }>, currentModel?: string, modes?: Array<{ id: string, label: string, description?: string }>, currentMode?: string }>}
|
|
11
11
|
*/
|
|
@@ -15,10 +15,11 @@ export function probeAcp(provider: {
|
|
|
15
15
|
env?: Record<string, string>;
|
|
16
16
|
label?: string;
|
|
17
17
|
id?: string;
|
|
18
|
-
}, { cwd, timeoutMs, discover }?: {
|
|
18
|
+
}, { cwd, timeoutMs, discover, signal }?: {
|
|
19
19
|
cwd?: string;
|
|
20
20
|
timeoutMs?: number;
|
|
21
21
|
discover?: boolean;
|
|
22
|
+
signal?: AbortSignal;
|
|
22
23
|
}): Promise<{
|
|
23
24
|
protocolVersion: number;
|
|
24
25
|
agent?: {
|
package/dist/acp-probe.js
CHANGED
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
// packages/client/src/acp-probe.js
|
|
2
2
|
import { stdioSession } from "./mcp-probe.js";
|
|
3
|
-
async function probeAcp(provider, { cwd, timeoutMs = 2e4, discover = false } = {}) {
|
|
3
|
+
async function probeAcp(provider, { cwd, timeoutMs = 2e4, discover = false, signal } = {}) {
|
|
4
|
+
signal?.throwIfAborted();
|
|
4
5
|
const session = stdioSession({ command: provider.command, args: provider.args ?? [], env: provider.env ?? {} }, cwd, timeoutMs);
|
|
6
|
+
let closing;
|
|
7
|
+
const abort = () => {
|
|
8
|
+
closing ??= session.close();
|
|
9
|
+
};
|
|
10
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
11
|
+
if (signal?.aborted) abort();
|
|
5
12
|
try {
|
|
6
13
|
const result = await session.request("initialize", {
|
|
7
14
|
protocolVersion: 1,
|
|
@@ -29,7 +36,9 @@ async function probeAcp(provider, { cwd, timeoutMs = 2e4, discover = false } = {
|
|
|
29
36
|
authMethods: (result.authMethods ?? []).map((method) => method?.name ?? method?.id).filter(Boolean)
|
|
30
37
|
};
|
|
31
38
|
} finally {
|
|
32
|
-
|
|
39
|
+
signal?.removeEventListener("abort", abort);
|
|
40
|
+
await (closing ?? session.close());
|
|
41
|
+
signal?.throwIfAborted();
|
|
33
42
|
}
|
|
34
43
|
}
|
|
35
44
|
export {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Probes Antigravity CLI for version, status and available models.
|
|
3
|
-
* @param {{ command?: string, args?: string[], env?: Record<string, string>, label?: string, id?: string
|
|
3
|
+
* @param {{ command?: string, args?: string[], env?: Record<string, string>, label?: string, id?: string}} [provider]
|
|
4
4
|
* @param {{ cwd?: string, timeoutMs?: number }} [options]
|
|
5
5
|
*/
|
|
6
6
|
export function probeAntigravity(provider?: {
|
|
@@ -9,7 +9,6 @@ export function probeAntigravity(provider?: {
|
|
|
9
9
|
env?: Record<string, string>;
|
|
10
10
|
label?: string;
|
|
11
11
|
id?: string;
|
|
12
|
-
readOnlyMode?: "instructions" | "reject";
|
|
13
12
|
}, { cwd, timeoutMs }?: {
|
|
14
13
|
cwd?: string;
|
|
15
14
|
timeoutMs?: number;
|
|
@@ -11,6 +11,16 @@ var DEFAULT_ANTIGRAVITY_MODELS = [
|
|
|
11
11
|
{ id: "gpt-oss-120b-medium", label: "GPT-OSS 120B (Medium)" }
|
|
12
12
|
];
|
|
13
13
|
var ANTIGRAVITY_MODES = [
|
|
14
|
+
{
|
|
15
|
+
id: "read-only",
|
|
16
|
+
label: "Read only",
|
|
17
|
+
description: "agy reads and searches; it denies file edits and terminal commands (--sandbox, request-review)."
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
id: "workspace-write",
|
|
21
|
+
label: "Workspace write",
|
|
22
|
+
description: "agy edits files and runs commands in its terminal sandbox inside the workspace (--mode accept-edits --sandbox, proceed-in-sandbox)."
|
|
23
|
+
},
|
|
14
24
|
{
|
|
15
25
|
id: "full-access",
|
|
16
26
|
label: "Full access",
|
|
@@ -82,11 +92,7 @@ async function probeAntigravity(provider = {}, { cwd, timeoutMs = 2e4 } = {}) {
|
|
|
82
92
|
agent: { name: "antigravity", title: "Antigravity", version },
|
|
83
93
|
models,
|
|
84
94
|
currentModel: models[0]?.id,
|
|
85
|
-
modes:
|
|
86
|
-
id: "read-only",
|
|
87
|
-
label: "Read only (instructions)",
|
|
88
|
-
description: "For new sessions: prompt-only read-only behavior. agy still runs with full access; no OS sandbox enforces this mode."
|
|
89
|
-
}] : ANTIGRAVITY_MODES,
|
|
95
|
+
modes: ANTIGRAVITY_MODES,
|
|
90
96
|
currentMode: "full-access"
|
|
91
97
|
};
|
|
92
98
|
}
|
package/dist/command.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
// packages/client/src/command.js
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
|
+
import { scriptCommand } from "@anhlp/alp-core/packaged";
|
|
3
4
|
function runCommand(command, args, { cwd, env = process.env, timeoutMs = 15e3 } = {}) {
|
|
4
5
|
return new Promise((resolve) => {
|
|
5
6
|
let child;
|
|
6
7
|
const script = process.platform === "win32" && /\.[cm]?js$/i.test(command);
|
|
8
|
+
const run = script ? scriptCommand(command, args) : { command, args };
|
|
7
9
|
try {
|
|
8
|
-
child = spawn(
|
|
10
|
+
child = spawn(run.command, run.args, { cwd, env: run.env ? { ...env, ...run.env } : env, stdio: ["ignore", "pipe", "pipe"] });
|
|
9
11
|
} catch (error) {
|
|
10
12
|
resolve({ code: -1, stdout: "", stderr: error.message });
|
|
11
13
|
return;
|
package/dist/doctor.d.ts
CHANGED
|
@@ -10,4 +10,12 @@ export type CommandResult = { code: number; stdout: string; stderr: string };
|
|
|
10
10
|
export type CommandRunner = (command: string, args: string[], options?: { cwd?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number }) => Promise<CommandResult>;
|
|
11
11
|
export const runCommand: CommandRunner;
|
|
12
12
|
export function diagnose(options?: { home?: string; project?: string; env?: NodeJS.ProcessEnv; run?: CommandRunner; sandbox?: boolean; daemonEntry?: string; timeoutMs?: number }): Promise<DoctorCheck[]>;
|
|
13
|
+
export type LeftoverState = 'clean-pushed' | 'dirty' | 'local-only' | 'unpushed' | 'in-use' | 'unknown';
|
|
14
|
+
export type Leftover = { path: string; state: LeftoverState; reason?: string; command?: string };
|
|
15
|
+
export const LEFTOVER_STATES: Record<LeftoverState, string>;
|
|
16
|
+
/** An absolute path of ASCII letters, digits, space and . _ - / \ : in single quotes, for sh or PowerShell; undefined for any other path. */
|
|
17
|
+
export function shellQuote(text: string, platform?: NodeJS.Platform): string | undefined;
|
|
18
|
+
/** A path as alp doctor prints it in a comment line: escaped injectively, on one line. */
|
|
19
|
+
export function printable(text: unknown): string;
|
|
20
|
+
export function diskCheck(home: string, options?: { run?: CommandRunner; env?: NodeJS.ProcessEnv; free?: number; tempDirs?: string[]; cwd?: string; classifyMs?: number; recentMs?: number; platform?: NodeJS.Platform }): Promise<DoctorCheck & { leftovers?: Leftover[] }>;
|
|
13
21
|
export function repair(checks: DoctorCheck[]): Promise<Array<{ id: string; result: string }>>;
|
package/dist/doctor.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
// packages/client/src/doctor.js
|
|
2
|
-
import {
|
|
2
|
+
import { realpathSync } from "node:fs";
|
|
3
|
+
import { access, chmod, constants, lstat, readdir, readFile, statfs, unlink, writeFile } from "node:fs/promises";
|
|
4
|
+
import os from "node:os";
|
|
3
5
|
import path from "node:path";
|
|
4
6
|
import { runCommand } from "./command.js";
|
|
5
7
|
import { assertPrivateSocket, connect, daemonPaths, lockAlive, readLock } from "./index.js";
|
|
@@ -7,6 +9,7 @@ import { installedProgram, serviceFor } from "./service.js";
|
|
|
7
9
|
import { jsonObject, agentSources, resolveAgent } from "@anhlp/alp-core/resolver";
|
|
8
10
|
import { loadHooks } from "@anhlp/alp-core/hooks";
|
|
9
11
|
import { isTrusted } from "@anhlp/alp-core/trust";
|
|
12
|
+
import { validateSkill } from "@anhlp/alp-core/skill-validate";
|
|
10
13
|
import { listProviders } from "@anhlp/alp-core/providers";
|
|
11
14
|
import { settingsWarnings, validateSettings, validateUserSettings } from "@anhlp/alp-core/validation";
|
|
12
15
|
import { readLogTail, scrubText } from "@anhlp/alp-core/log";
|
|
@@ -76,7 +79,7 @@ async function serviceCheck(home, env) {
|
|
|
76
79
|
const program2 = service && await installedProgram(service);
|
|
77
80
|
if (!program2) return void 0;
|
|
78
81
|
const missing = [];
|
|
79
|
-
for (const file of program2) if (!await lstat(file).then(() => true, () => false)) missing.push(file);
|
|
82
|
+
for (const file of program2.filter((arg) => path.isAbsolute(arg))) if (!await lstat(file).then(() => true, () => false)) missing.push(file);
|
|
80
83
|
return missing.length ? { id: "service", status: "fail", summary: `the ${service.kind} service ${service.name} runs files that are gone; run alp daemon install again`, details: missing } : { id: "service", status: "ok", summary: `${service.kind} runs alpd as ${service.name}` };
|
|
81
84
|
}
|
|
82
85
|
var seconds = (ms) => `${Math.round(ms / 1e3)} s`;
|
|
@@ -272,15 +275,15 @@ async function daemonCheck(home) {
|
|
|
272
275
|
};
|
|
273
276
|
}
|
|
274
277
|
async function privateEntries(home) {
|
|
275
|
-
const
|
|
276
|
-
for (const name of ["settings.json", "alpd.lock", "alpd.json", "role-skills.json"])
|
|
278
|
+
const entries2 = [home];
|
|
279
|
+
for (const name of ["settings.json", "alpd.lock", "alpd.json", "role-skills.json"]) entries2.push(path.join(home, name));
|
|
277
280
|
for (const directory of ["state", "runs", "logs", "boards", "worktrees", "copies"]) {
|
|
278
281
|
const full = path.join(home, directory);
|
|
279
|
-
|
|
282
|
+
entries2.push(full);
|
|
280
283
|
if (directory === "worktrees" || directory === "copies") continue;
|
|
281
|
-
for (const name of await readdir(full).catch(() => []))
|
|
284
|
+
for (const name of await readdir(full).catch(() => [])) entries2.push(path.join(full, name));
|
|
282
285
|
}
|
|
283
|
-
return
|
|
286
|
+
return entries2;
|
|
284
287
|
}
|
|
285
288
|
async function permissionsCheck(home) {
|
|
286
289
|
if (process.platform === "win32") return { id: "permissions", status: "ok", summary: `${home} follows your Windows profile access rules` };
|
|
@@ -406,6 +409,29 @@ async function providersCheck(home, env) {
|
|
|
406
409
|
]
|
|
407
410
|
};
|
|
408
411
|
}
|
|
412
|
+
async function skillFormatCheck(home) {
|
|
413
|
+
const directory = path.join(home, "skills");
|
|
414
|
+
const entries2 = await readdir(directory, { withFileTypes: true }).catch(() => []);
|
|
415
|
+
const failed = [];
|
|
416
|
+
const warned = [];
|
|
417
|
+
let checked = 0;
|
|
418
|
+
for (const entry of entries2) {
|
|
419
|
+
if (!entry.isDirectory() && !entry.isSymbolicLink() || !/^[\w.-]+$/.test(entry.name) || entry.name.startsWith(".")) continue;
|
|
420
|
+
if (!await lstat(path.join(directory, entry.name, "SKILL.md")).then(() => true, () => false)) continue;
|
|
421
|
+
checked++;
|
|
422
|
+
try {
|
|
423
|
+
const report = await validateSkill(path.join(directory, entry.name));
|
|
424
|
+
if (!report.ok) failed.push(`${entry.name}: ${report.errors.map((finding) => finding.message).join("; ")}`);
|
|
425
|
+
else if (report.warnings.length) warned.push(`${entry.name}: ${report.warnings.map((finding) => finding.code).join(", ")}`);
|
|
426
|
+
} catch (error) {
|
|
427
|
+
failed.push(`${entry.name}: could not be checked: ${error.message}`);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
if (!checked) return void 0;
|
|
431
|
+
if (failed.length) return { id: "skill-format", status: "fail", summary: `${failed.length} library skill${failed.length > 1 ? "s have" : " has"} an unsafe link or an unreadable file (alp skill check <name> explains)`, details: [...failed, ...warned] };
|
|
432
|
+
if (warned.length) return { id: "skill-format", status: "warn", summary: `${warned.length} library skill${warned.length > 1 ? "s do" : " does"} not fully meet the skill format; they still load (alp skill check <name> explains)`, details: warned };
|
|
433
|
+
return { id: "skill-format", status: "ok", summary: `the library's skills meet the skill format (${directory})` };
|
|
434
|
+
}
|
|
409
435
|
async function librarySkillsCheck(home) {
|
|
410
436
|
const file = path.join(home, "role-skills.json");
|
|
411
437
|
let roles;
|
|
@@ -434,18 +460,18 @@ async function librarySkillsCheck(home) {
|
|
|
434
460
|
}
|
|
435
461
|
async function liveCheck(home, running) {
|
|
436
462
|
const file = path.join(home, "state", "live.json");
|
|
437
|
-
let
|
|
463
|
+
let entries2;
|
|
438
464
|
try {
|
|
439
|
-
|
|
465
|
+
entries2 = JSON.parse(await readFile(file, "utf8"));
|
|
440
466
|
} catch {
|
|
441
467
|
return void 0;
|
|
442
468
|
}
|
|
443
|
-
if (!Array.isArray(
|
|
469
|
+
if (!Array.isArray(entries2)) return { id: "live work", status: "warn", summary: `${file} is not a list; alpd ignores it` };
|
|
444
470
|
const gone = [];
|
|
445
|
-
for (const entry of
|
|
471
|
+
for (const entry of entries2) {
|
|
446
472
|
if (typeof entry?.project !== "string" || !await lstat(entry.project).then(() => true, () => false)) gone.push(entry);
|
|
447
473
|
}
|
|
448
|
-
if (!gone.length) return { id: "live work", status:
|
|
474
|
+
if (!gone.length) return { id: "live work", status: entries2.length && !running ? "info" : "ok", summary: entries2.length ? `${entries2.length} assignment${entries2.length > 1 ? "s" : ""} ${running ? "running" : "waiting for alpd to continue"}` : "no running assignments" };
|
|
449
475
|
return {
|
|
450
476
|
id: "live work",
|
|
451
477
|
status: "warn",
|
|
@@ -533,12 +559,243 @@ async function schemaChecks(home) {
|
|
|
533
559
|
if (await lstat(path.join(home, "restore-journal.json")).then(() => true, () => false)) checks.push({ id: "restore", status: "warn", summary: "a restore was cut short; alpd or the next alp restore moves the earlier data back first" });
|
|
534
560
|
return checks;
|
|
535
561
|
}
|
|
562
|
+
function isInside(target, container) {
|
|
563
|
+
const resolve = (directory) => {
|
|
564
|
+
let current = path.resolve(directory);
|
|
565
|
+
let suffix = "";
|
|
566
|
+
for (; ; ) {
|
|
567
|
+
try {
|
|
568
|
+
return path.join(realpathSync(current), suffix);
|
|
569
|
+
} catch {
|
|
570
|
+
const parent = path.dirname(current);
|
|
571
|
+
if (parent === current) return path.join(current, suffix);
|
|
572
|
+
suffix = path.join(path.basename(current), suffix);
|
|
573
|
+
current = parent;
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
};
|
|
577
|
+
const resolvedTarget = resolve(target);
|
|
578
|
+
const resolvedContainer = resolve(container);
|
|
579
|
+
const relative = path.relative(resolvedContainer, resolvedTarget);
|
|
580
|
+
return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
581
|
+
}
|
|
582
|
+
async function homeLocationCheck(home, project) {
|
|
583
|
+
if (process.platform === "win32" || !home) return { id: "home", status: "ok", summary: home ?? "" };
|
|
584
|
+
if (project && isInside(home, project)) {
|
|
585
|
+
return {
|
|
586
|
+
id: "home",
|
|
587
|
+
status: "warn",
|
|
588
|
+
summary: `ALP_HOME (${home}) is inside this project's workspace, which sandboxed sessions may write: a tool could change staged attachment copies before they are read; keep ALP_HOME outside workspaces (default ~/.alp)`
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
const inTmp = isInside(home, os.tmpdir()) || isInside(home, "/tmp");
|
|
592
|
+
if (inTmp) {
|
|
593
|
+
return {
|
|
594
|
+
id: "home",
|
|
595
|
+
status: "warn",
|
|
596
|
+
summary: `ALP_HOME (${home}) is inside the temp directory, which sandboxed sessions may write: a tool could change staged attachment copies before they are read; keep ALP_HOME outside it (default ~/.alp)`
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
return { id: "home", status: "ok", summary: home };
|
|
600
|
+
}
|
|
601
|
+
var GIB = 1024 ** 3;
|
|
602
|
+
var formatSize = (bytes) => bytes >= GIB ? `${(bytes / GIB).toFixed(1)} GB` : `${Math.round(bytes / 1024 ** 2)} MB`;
|
|
603
|
+
async function entries(directory, prefix = "") {
|
|
604
|
+
const names = await readdir(directory).catch(() => []);
|
|
605
|
+
return names.filter((name) => name.startsWith(prefix)).map((name) => path.join(directory, name));
|
|
606
|
+
}
|
|
607
|
+
var QUOTABLE = /^[A-Za-z0-9._\-/\\: ]+$/;
|
|
608
|
+
function shellQuote(text, platform = process.platform) {
|
|
609
|
+
const value = String(text);
|
|
610
|
+
const absolute = platform === "win32" ? path.win32.isAbsolute(value) : path.posix.isAbsolute(value);
|
|
611
|
+
return absolute && QUOTABLE.test(value) ? `'${value}'` : void 0;
|
|
612
|
+
}
|
|
613
|
+
var printable = (text) => String(text).replace(new RegExp("\\\\|[\\p{C}\\p{Zl}\\p{Zp}]|(?! )\\p{Zs}", "gu"), (char) => char === "\\" ? "\\\\" : `\\u{${char.codePointAt(0).toString(16)}}`);
|
|
614
|
+
var UNQUOTABLE = "no command: its path holds characters other than ASCII letters, digits, space and . _ - / \\ :, which a pasted command might not carry safely; check it and remove it by hand";
|
|
615
|
+
var LEFTOVER_STATES = {
|
|
616
|
+
"clean-pushed": "clean and pushed (no changes, no untracked or ignored files, and every commit and, for a clone, every ref on a remote it last fetched; remove by hand with the command shown, given only for a plain ASCII path)",
|
|
617
|
+
dirty: "dirty (uncommitted changes or untracked files, or a merge or rebase in progress; keep)",
|
|
618
|
+
"local-only": "local-only data (ignored files such as .env, local config, node_modules or build output, which exist only here; keep)",
|
|
619
|
+
unpushed: "unpushed (commits, or for a clone tags, branches or other refs, that no remote-tracking ref mirrors; keep)",
|
|
620
|
+
"in-use": "in use (a running assignment, a retained result, this shell, or changed in the last day; keep)",
|
|
621
|
+
unknown: "unknown (not a git checkout of its own, or git could not tell; check by hand)"
|
|
622
|
+
};
|
|
623
|
+
async function ownedPaths(home) {
|
|
624
|
+
const owned = /* @__PURE__ */ new Set();
|
|
625
|
+
const read = async (file) => JSON.parse(await readFile(file, "utf8"));
|
|
626
|
+
const live = await read(path.join(home, "state", "live.json")).catch(() => []);
|
|
627
|
+
for (const entry of Array.isArray(live) ? live : []) if (typeof entry?.worktree?.path === "string") owned.add(realpathOr(entry.worktree.path));
|
|
628
|
+
const ledger = await read(path.join(home, "state", "assignment-results.json")).catch(() => void 0);
|
|
629
|
+
for (const entry of Array.isArray(ledger?.results) ? ledger.results : []) {
|
|
630
|
+
if (entry?.handled) continue;
|
|
631
|
+
for (const where of [entry?.worktree, entry?.checkout]) if (typeof where === "string") owned.add(realpathOr(where));
|
|
632
|
+
}
|
|
633
|
+
return owned;
|
|
634
|
+
}
|
|
635
|
+
var NOT_CHECKED = "not checked: alp doctor ran out of time; run it again, or check by hand";
|
|
636
|
+
var OutOfTime = class extends Error {
|
|
637
|
+
};
|
|
638
|
+
async function classifyLeftover(directory, { run, env, owned, here, recentMs, deadline, platform }) {
|
|
639
|
+
const real = realpathOr(directory);
|
|
640
|
+
const inside = (outer, inner) => inner === outer || inner.startsWith(outer.endsWith(path.sep) ? outer : outer + path.sep);
|
|
641
|
+
if ([...owned].some((owner) => inside(real, owner) || inside(owner, real)) || inside(real, here)) return { path: directory, state: "in-use" };
|
|
642
|
+
const git = async (args) => {
|
|
643
|
+
const left = deadline - Date.now();
|
|
644
|
+
if (left <= 0) throw new OutOfTime();
|
|
645
|
+
const result = await run("git", ["-C", directory, ...args], { env, timeoutMs: Math.min(1e4, left) });
|
|
646
|
+
if (Date.now() >= deadline) throw new OutOfTime();
|
|
647
|
+
return result;
|
|
648
|
+
};
|
|
649
|
+
const unknown = (reason) => ({ path: directory, state: "unknown", reason });
|
|
650
|
+
if (!await lstat(path.join(directory, ".git")).then(() => true, () => false)) return unknown("not a git checkout");
|
|
651
|
+
const where = await git(["rev-parse", "--show-toplevel", "--absolute-git-dir", "--git-common-dir"]);
|
|
652
|
+
if (where.code !== 0) return unknown("not a git checkout");
|
|
653
|
+
const [top, gitDir, common] = where.stdout.trim().split("\n");
|
|
654
|
+
if (!top || !gitDir || !common || realpathOr(top) !== real) return unknown("not the top of a git checkout");
|
|
655
|
+
const commonDir = realpathOr(path.resolve(top, common));
|
|
656
|
+
const status = await git(["-c", "status.showUntrackedFiles=all", "status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignored=matching"]);
|
|
657
|
+
if (status.code !== 0) return unknown("git status failed");
|
|
658
|
+
const rows = status.stdout.split("\0").filter(Boolean);
|
|
659
|
+
if (rows.some((row) => !row.startsWith("!! "))) return { path: directory, state: "dirty" };
|
|
660
|
+
const ignored = rows.map((row) => row.slice(3));
|
|
661
|
+
if (ignored.length) return { path: directory, state: "local-only", reason: `ignored files: ${ignored.slice(0, 3).join(", ")}${ignored.length > 3 ? `, \u2026 ${ignored.length - 3} more` : ""}` };
|
|
662
|
+
const index = await git(["ls-files", "-z", "-v", "--stage"]);
|
|
663
|
+
if (index.code !== 0) return unknown("git could not list its index");
|
|
664
|
+
const tracked = index.stdout.split("\0").filter(Boolean);
|
|
665
|
+
if (tracked.some((row) => row[0] === "S" || /[a-z]/.test(row[0]))) return unknown("some files are marked assume-unchanged or skip-worktree, which git status does not check");
|
|
666
|
+
if (tracked.some((row) => row.slice(2).startsWith("160000 "))) return unknown("it has submodules, whose own changes and commits this check does not read");
|
|
667
|
+
for (const name of ["MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "rebase-merge", "rebase-apply"]) {
|
|
668
|
+
if (await lstat(path.join(gitDir, name)).then(() => true, () => false)) return { path: directory, state: "dirty" };
|
|
669
|
+
}
|
|
670
|
+
const touched = Math.max(...await Promise.all([directory, path.join(gitDir, "index"), path.join(gitDir, "HEAD")].map((file) => lstat(file).then((info) => info.mtimeMs, () => 0))));
|
|
671
|
+
if (Date.now() - touched < recentMs) return { path: directory, state: "in-use", reason: "changed in the last day" };
|
|
672
|
+
const linked = realpathOr(gitDir) !== commonDir;
|
|
673
|
+
const ahead = await git(["rev-list", "-n", "1", ...linked ? ["HEAD"] : ["HEAD", "--all"], "--not", "--remotes"]);
|
|
674
|
+
if (ahead.code !== 0) return unknown("git could not compare HEAD with the remotes");
|
|
675
|
+
if (ahead.stdout.trim()) return { path: directory, state: "unpushed" };
|
|
676
|
+
if (!linked) {
|
|
677
|
+
const refs = await git(["for-each-ref", "--format=%(objectname) %(refname)"]);
|
|
678
|
+
if (refs.code !== 0) return unknown("git could not list its refs");
|
|
679
|
+
const all = refs.stdout.split("\n").filter(Boolean).map((line) => {
|
|
680
|
+
const at = line.indexOf(" ");
|
|
681
|
+
return [line.slice(at + 1), line.slice(0, at)];
|
|
682
|
+
});
|
|
683
|
+
const remotes = await git(["remote"]);
|
|
684
|
+
if (remotes.code !== 0) return unknown("git could not list its remotes");
|
|
685
|
+
const remoteNames = remotes.stdout.split("\n").map((line) => line.trim()).filter(Boolean);
|
|
686
|
+
const mirrors = new Map(all.filter(([name]) => name.startsWith("refs/remotes/")));
|
|
687
|
+
const mirrored = ([name, object]) => {
|
|
688
|
+
const branch = name.startsWith("refs/heads/");
|
|
689
|
+
const rest = branch ? name.slice("refs/heads/".length) : name.slice("refs/".length);
|
|
690
|
+
return remoteNames.some((remote) => {
|
|
691
|
+
const target = mirrors.get(`refs/remotes/${remote}/${rest}`);
|
|
692
|
+
return target !== void 0 && (branch || target === object);
|
|
693
|
+
});
|
|
694
|
+
};
|
|
695
|
+
const local = all.filter((entry) => !entry[0].startsWith("refs/remotes/") && !mirrored(entry));
|
|
696
|
+
if (local.length) return { path: directory, state: "unpushed", reason: `local refs no remote-tracking ref mirrors: ${local.slice(0, 3).map(([name]) => name).join(", ")}${local.length > 3 ? `, \u2026 ${local.length - 3} more` : ""}` };
|
|
697
|
+
}
|
|
698
|
+
const list = await git(["worktree", "list", "--porcelain"]);
|
|
699
|
+
if (list.code !== 0) return unknown("git could not list its worktrees");
|
|
700
|
+
if (!linked) {
|
|
701
|
+
if ((list.stdout.match(/^worktree /gm) ?? []).length > 1) return { path: directory, state: "in-use", reason: "other worktrees use its repository" };
|
|
702
|
+
const quoted2 = shellQuote(directory, platform);
|
|
703
|
+
if (quoted2 === void 0) return { path: directory, state: "clean-pushed", reason: UNQUOTABLE };
|
|
704
|
+
return { path: directory, state: "clean-pushed", command: platform === "win32" ? `Remove-Item -LiteralPath ${quoted2} -Recurse -Force` : `rm -rf ${quoted2}` };
|
|
705
|
+
}
|
|
706
|
+
const main = list.stdout.match(/^worktree (.*)$/m)?.[1];
|
|
707
|
+
if (!main) return unknown("git could not name its main worktree");
|
|
708
|
+
const [quotedMain, quoted] = [shellQuote(main, platform), shellQuote(directory, platform)];
|
|
709
|
+
if (quotedMain === void 0 || quoted === void 0) return { path: directory, state: "clean-pushed", reason: UNQUOTABLE };
|
|
710
|
+
return { path: directory, state: "clean-pushed", command: `git -C ${quotedMain} worktree remove ${quoted}` };
|
|
711
|
+
}
|
|
712
|
+
async function classifyLeftovers(paths, { budgetMs, ...options }) {
|
|
713
|
+
const results = paths.map((directory) => ({ path: directory, state: "unknown", reason: NOT_CHECKED }));
|
|
714
|
+
const deadline = Date.now() + budgetMs;
|
|
715
|
+
let next = 0, done = false;
|
|
716
|
+
const worker = async () => {
|
|
717
|
+
while (!done && next < paths.length && Date.now() < deadline) {
|
|
718
|
+
const index = next++;
|
|
719
|
+
try {
|
|
720
|
+
const result = await classifyLeftover(paths[index], { ...options, deadline });
|
|
721
|
+
if (!done && Date.now() < deadline) results[index] = result;
|
|
722
|
+
} catch (error) {
|
|
723
|
+
if (!(error instanceof OutOfTime)) results[index] = { path: paths[index], state: "unknown", reason: `could not check: ${error?.message ?? error}` };
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
};
|
|
727
|
+
let timer;
|
|
728
|
+
const expired = new Promise((resolve) => {
|
|
729
|
+
timer = setTimeout(resolve, Math.max(0, budgetMs));
|
|
730
|
+
});
|
|
731
|
+
await Promise.race([Promise.all(Array.from({ length: Math.min(8, paths.length) }, worker)), expired]);
|
|
732
|
+
clearTimeout(timer);
|
|
733
|
+
done = true;
|
|
734
|
+
return results;
|
|
735
|
+
}
|
|
736
|
+
var SHOWN_COMMANDS = 20;
|
|
737
|
+
async function diskCheck(home, { run = runCommand, env = process.env, free, tempDirs = [.../* @__PURE__ */ new Set([os.tmpdir(), ...process.platform === "win32" ? [] : ["/tmp"]])], cwd = process.cwd(), classifyMs = 1e4, recentMs = 24 * 60 * 60 * 1e3, platform = process.platform } = {}) {
|
|
738
|
+
let bytes = free;
|
|
739
|
+
if (bytes === void 0) {
|
|
740
|
+
try {
|
|
741
|
+
const info = await statfs(home);
|
|
742
|
+
bytes = Number(info.bavail) * Number(info.bsize);
|
|
743
|
+
} catch {
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
const worktrees = await entries(path.join(home, "worktrees"));
|
|
747
|
+
const temp = [];
|
|
748
|
+
for (const directory of tempDirs) {
|
|
749
|
+
for (const entry of await entries(directory, "alp-")) {
|
|
750
|
+
const info = await lstat(entry).catch(() => void 0);
|
|
751
|
+
if (info?.isDirectory() && !temp.includes(realpathOr(entry))) temp.push(realpathOr(entry));
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
async function size(paths) {
|
|
755
|
+
if (!paths.length) return 0;
|
|
756
|
+
if (process.platform === "win32") return void 0;
|
|
757
|
+
const result = await run("du", ["-sk", ...paths], { env, timeoutMs: 2e4 });
|
|
758
|
+
if (result.code !== 0 && !result.stdout) return void 0;
|
|
759
|
+
const total = result.stdout.split("\n").reduce((sum, line) => sum + (Number(line.split(/\s+/)[0]) || 0), 0);
|
|
760
|
+
return total * 1024;
|
|
761
|
+
}
|
|
762
|
+
const gitEnv = { ...Object.fromEntries(Object.entries(env).filter(([name]) => !/^GIT_(DIR|WORK_TREE|INDEX_FILE|COMMON_DIR|OBJECT_DIRECTORY|NAMESPACE|CEILING_DIRECTORIES)$/.test(name))), GIT_OPTIONAL_LOCKS: "0" };
|
|
763
|
+
const groups = [[`${path.join(home, "worktrees")}`, worktrees], [`${tempDirs.map((directory) => path.join(directory, "alp-*")).join(", ")}`, temp]].filter(([, paths]) => paths.length);
|
|
764
|
+
const [sizes, leftovers] = await Promise.all([
|
|
765
|
+
Promise.all(groups.map(([, paths]) => size(paths))),
|
|
766
|
+
ownedPaths(home).then((owned) => classifyLeftovers([.../* @__PURE__ */ new Set([...worktrees, ...temp])], { run, env: gitEnv, owned, here: realpathOr(cwd), budgetMs: classifyMs, recentMs, platform }))
|
|
767
|
+
]);
|
|
768
|
+
const details = groups.map(([label, paths], index) => `${paths.length} left in ${label}${sizes[index] === void 0 ? "" : `, ${formatSize(sizes[index])}`}`);
|
|
769
|
+
for (const [state, meaning] of Object.entries(LEFTOVER_STATES)) {
|
|
770
|
+
const count = leftovers.filter((entry) => entry.state === state).length;
|
|
771
|
+
if (count) details.push(`${count} ${meaning}`);
|
|
772
|
+
}
|
|
773
|
+
const unchecked = leftovers.filter((entry) => entry.reason === NOT_CHECKED).length;
|
|
774
|
+
if (unchecked) details.push(` ${unchecked} of the unknown were not checked within ${classifyMs < 1e3 ? `${classifyMs} ms` : `${Math.round(classifyMs / 1e3)} s`}`);
|
|
775
|
+
const commands = leftovers.filter((entry) => entry.state === "clean-pushed").map((entry) => entry.command ?? `# remove by hand after checking (no safe command): ${printable(entry.path)}`);
|
|
776
|
+
for (const command of commands.slice(0, SHOWN_COMMANDS)) details.push(` ${command}`);
|
|
777
|
+
if (commands.length > SHOWN_COMMANDS) details.push(` \u2026 ${commands.length - SHOWN_COMMANDS} more; alp doctor --json lists every one`);
|
|
778
|
+
const hint = details.length ? "ALP deletes none of these, and --fix does not either. Only a clean and pushed leftover gets a command, for you to run by hand, and only when its path is plain ASCII; inspect the others before removing anything." : void 0;
|
|
779
|
+
const where = bytes === void 0 ? "free space unknown" : `${formatSize(bytes)} free`;
|
|
780
|
+
const status = bytes !== void 0 && bytes < 2 * GIB ? "warn" : "ok";
|
|
781
|
+
const summary = bytes !== void 0 && bytes < 2 * GIB ? `${where} where ALP_HOME lives; when the disk is full, alpd pauses all work until space returns` : `${where} where ALP_HOME lives`;
|
|
782
|
+
return { id: "disk", status, summary, ...details.length ? { details } : {}, ...hint ? { hint } : {}, ...leftovers.length ? { leftovers } : {} };
|
|
783
|
+
}
|
|
784
|
+
function realpathOr(file) {
|
|
785
|
+
try {
|
|
786
|
+
return realpathSync(file);
|
|
787
|
+
} catch {
|
|
788
|
+
return file;
|
|
789
|
+
}
|
|
790
|
+
}
|
|
536
791
|
async function diagnose({ home, project, env = process.env, run = runCommand, sandbox, daemonEntry, timeoutMs = 3e3 } = {}) {
|
|
537
792
|
const checks = [];
|
|
538
793
|
if (daemonEntry) {
|
|
539
794
|
checks.push(await lstat(daemonEntry).then(() => ({ id: "build", status: "ok", summary: daemonEntry }), () => ({ id: "build", status: "fail", summary: `alpd is not built (${daemonEntry}); run npm run build` })));
|
|
540
795
|
}
|
|
541
796
|
checks.push(...await runtimeChecks({ env, run }));
|
|
797
|
+
checks.push(await homeLocationCheck(home, project));
|
|
798
|
+
if (home) checks.push(await diskCheck(home, { run, env }));
|
|
542
799
|
const daemon = await daemonCheck(home);
|
|
543
800
|
checks.push(daemon);
|
|
544
801
|
const service = await serviceCheck(home, env);
|
|
@@ -557,6 +814,8 @@ async function diagnose({ home, project, env = process.env, run = runCommand, sa
|
|
|
557
814
|
checks.push(await userSettingsCheck(home));
|
|
558
815
|
const skills = await librarySkillsCheck(home);
|
|
559
816
|
if (skills) checks.push(skills);
|
|
817
|
+
const skillFormat = await skillFormatCheck(home);
|
|
818
|
+
if (skillFormat) checks.push(skillFormat);
|
|
560
819
|
const providers = await providersCheck(home, env);
|
|
561
820
|
if (providers) checks.push(providers);
|
|
562
821
|
const live = await liveCheck(home, running);
|
|
@@ -581,7 +840,11 @@ async function repair(checks) {
|
|
|
581
840
|
return done;
|
|
582
841
|
}
|
|
583
842
|
export {
|
|
843
|
+
LEFTOVER_STATES,
|
|
584
844
|
diagnose,
|
|
845
|
+
diskCheck,
|
|
846
|
+
printable,
|
|
585
847
|
repair,
|
|
586
|
-
runCommand
|
|
848
|
+
runCommand,
|
|
849
|
+
shellQuote
|
|
587
850
|
};
|