@anhlp/alp-client 0.0.1-beta.4 → 0.0.1-beta.5

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.
@@ -63,31 +63,104 @@ function attachments(client) {
63
63
  * Uploads `data` and commits it: begin (or resume, with the same requestId), chunks of at most
64
64
  * the smaller of `maxChunkBytes` and what begin answered, commit with its SHA-256. A chunk
65
65
  * refused `offset_mismatch` continues from the daemon's `received`. Returns the attachment.
66
- * @param {{ sessionId: string, name: string, mimeType: string, data: Uint8Array, requestId: string, sha256?: string, maxChunkBytes?: number, onProgress?: (received: number, size: number) => void }} options
66
+ * The returned promise exposes `.uploadId` once begun and `.abort(reason?: any)` to abort on alpd.
67
+ * @param {{ sessionId: string, name: string, mimeType: string, data: Uint8Array, requestId: string, sha256?: string, maxChunkBytes?: number, signal?: AbortSignal, onBegun?: (uploadId: string) => void, onProgress?: (received: number, size: number) => void }} options
68
+ * @returns {Promise<Map['attachment.commit']['result']['attachment']> & { readonly uploadId?: string, abort(reason?: any): Promise<void> }}
67
69
  */
68
- async upload({ sessionId, name, mimeType, data, requestId, sha256, maxChunkBytes, onProgress }) {
69
- const digest = sha256 ?? await sha256Hex(data);
70
- const begun = await api.begin({ sessionId, name, size: data.length, mimeType, sha256: digest, requestId });
71
- if (begun.state === "committed" && begun.attachmentId) return (await api.get(begun.attachmentId)).attachment;
72
- const size = Math.max(1, Math.min(begun.maxChunkBytes, maxChunkBytes ?? Infinity));
73
- let offset = begun.received;
74
- for (let realigned = 0; offset < data.length; ) {
75
- const end = Math.min(data.length, offset + size);
76
- try {
77
- const { received } = await api.chunk({ uploadId: begun.uploadId, offset, data: base64Encode(data.subarray(offset, end)) });
78
- offset = received;
79
- } catch (error) {
80
- const held = (
81
- /** @type {any} */
82
- error?.data
83
- );
84
- if (held?.reason !== "offset_mismatch" || !Number.isSafeInteger(held.received) || ++realigned > 3) throw error;
85
- offset = held.received;
86
- continue;
87
- }
88
- onProgress?.(offset, data.length);
89
- }
90
- return (await api.commit({ uploadId: begun.uploadId, sha256: digest })).attachment;
70
+ upload({ sessionId, name, mimeType, data, requestId, sha256, maxChunkBytes, signal, onBegun, onProgress }) {
71
+ let uploadId;
72
+ let userAborted = false;
73
+ let userAbortReason;
74
+ const isAborted = () => userAborted || (signal?.aborted ?? false);
75
+ const getAbortReason = () => userAbortReason ?? signal?.reason ?? new Error("Upload aborted");
76
+ const onSignalAbort = () => {
77
+ if (uploadId) api.abort(uploadId).catch(() => {
78
+ });
79
+ };
80
+ signal?.addEventListener?.("abort", onSignalAbort, { once: true });
81
+ const run = (
82
+ /** @type {Promise<Map['attachment.commit']['result']['attachment']> & { uploadId?: string, abort(reason?: any): Promise<void> }} */
83
+ (async () => {
84
+ try {
85
+ if (isAborted()) throw getAbortReason();
86
+ const digest = sha256 ?? await sha256Hex(data);
87
+ if (isAborted()) throw getAbortReason();
88
+ const begun = await api.begin({ sessionId, name, size: data.length, mimeType, sha256: digest, requestId });
89
+ uploadId = begun.uploadId;
90
+ try {
91
+ onBegun?.(begun.uploadId);
92
+ } catch (error) {
93
+ if (begun.state !== "committed") await api.abort(begun.uploadId).catch(() => {
94
+ });
95
+ throw error;
96
+ }
97
+ if (isAborted()) {
98
+ if (begun.state !== "committed") await api.abort(begun.uploadId).catch(() => {
99
+ });
100
+ throw getAbortReason();
101
+ }
102
+ if (begun.state === "committed" && begun.attachmentId) return (await api.get(begun.attachmentId)).attachment;
103
+ const size = Math.max(1, Math.min(begun.maxChunkBytes, maxChunkBytes ?? Infinity));
104
+ let offset = begun.received;
105
+ for (let realigned = 0; offset < data.length; ) {
106
+ if (isAborted()) {
107
+ await api.abort(begun.uploadId).catch(() => {
108
+ });
109
+ throw getAbortReason();
110
+ }
111
+ const end = Math.min(data.length, offset + size);
112
+ try {
113
+ const { received } = await api.chunk({ uploadId: begun.uploadId, offset, data: base64Encode(data.subarray(offset, end)) });
114
+ offset = received;
115
+ } catch (error) {
116
+ if (isAborted()) {
117
+ await api.abort(begun.uploadId).catch(() => {
118
+ });
119
+ throw getAbortReason();
120
+ }
121
+ const held = (
122
+ /** @type {any} */
123
+ error?.data
124
+ );
125
+ if (held?.reason !== "offset_mismatch" || !Number.isSafeInteger(held.received) || ++realigned > 3) throw error;
126
+ offset = held.received;
127
+ continue;
128
+ }
129
+ if (isAborted()) {
130
+ await api.abort(begun.uploadId).catch(() => {
131
+ });
132
+ throw getAbortReason();
133
+ }
134
+ try {
135
+ onProgress?.(offset, data.length);
136
+ } catch (error) {
137
+ await api.abort(begun.uploadId).catch(() => {
138
+ });
139
+ throw error;
140
+ }
141
+ }
142
+ if (isAborted()) {
143
+ await api.abort(begun.uploadId).catch(() => {
144
+ });
145
+ throw getAbortReason();
146
+ }
147
+ return (await api.commit({ uploadId: begun.uploadId, sha256: digest })).attachment;
148
+ } finally {
149
+ signal?.removeEventListener?.("abort", onSignalAbort);
150
+ }
151
+ })()
152
+ );
153
+ Object.defineProperty(run, "uploadId", {
154
+ get: () => uploadId,
155
+ enumerable: true
156
+ });
157
+ run.abort = async (reason) => {
158
+ userAborted = true;
159
+ userAbortReason = reason ?? new Error("Upload aborted");
160
+ if (uploadId) await api.abort(uploadId).catch(() => {
161
+ });
162
+ };
163
+ return run;
91
164
  }
92
165
  };
93
166
  return api;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * A terminal directory for one connection. Subscribe before requesting the atomic snapshot.
3
+ * Invalidations are coalesced; a reconnect installs a new watcher and replaces state with its
4
+ * full snapshot (reset), rather than replaying obsolete list mutations. No output is replayed.
5
+ * @param {{request<T = any>(method:string, params?:any):Promise<T>, onNotification?(listener:(method:string,params:any)=>void):()=>void, onClose(listener:(error:Error)=>void):()=>void}} connection
6
+ * @param {{capabilities:readonly string[], workspaceId?:string, pollMs?:number, onSnapshot:(terminals:import('@anhlp/alp-protocol').TerminalInfo[])=>void, onError?:(error:unknown)=>void, onMode?:(mode:'events'|'polling')=>void}} options
7
+ */
8
+ export function watchTerminals(connection: {
9
+ request<T = any>(method: string, params?: any): Promise<T>;
10
+ onNotification?(listener: (method: string, params: any) => void): () => void;
11
+ onClose(listener: (error: Error) => void): () => void;
12
+ }, options: {
13
+ capabilities: readonly string[];
14
+ workspaceId?: string;
15
+ pollMs?: number;
16
+ onSnapshot: (terminals: import("@anhlp/alp-protocol").TerminalInfo[]) => void;
17
+ onError?: (error: unknown) => void;
18
+ onMode?: (mode: "events" | "polling") => void;
19
+ }): {
20
+ ready: Promise<void>;
21
+ refresh: () => Promise<void>;
22
+ close: (unwatch?: boolean) => void;
23
+ mode: string;
24
+ };
@@ -0,0 +1,70 @@
1
+ // packages/client/src/rpc/terminal-directory.js
2
+ function watchTerminals(connection, options) {
3
+ const events = options.capabilities.includes("terminal.watch") && !!connection.onNotification;
4
+ let closed = false;
5
+ let watchId = "";
6
+ let cursor = "";
7
+ let again = false;
8
+ let refreshing;
9
+ const pending = /* @__PURE__ */ new Map();
10
+ const off = connection.onNotification?.((method, params) => {
11
+ if (closed || !events || method !== "terminal.changed" || !/^[0-9a-f]{32}$/.test(params?.watchId) || !/^[0-9a-f]{32}$/.test(params?.cursor)) return;
12
+ if (pending.size >= 4 && !pending.has(params.watchId)) pending.delete(pending.keys().next().value ?? "");
13
+ pending.set(params.watchId, params.cursor);
14
+ if (params.watchId === watchId && params.cursor !== cursor) {
15
+ again = true;
16
+ void refresh();
17
+ }
18
+ });
19
+ function refresh() {
20
+ if (closed) return Promise.resolve();
21
+ if (refreshing) return refreshing;
22
+ refreshing = (async () => {
23
+ do {
24
+ again = false;
25
+ try {
26
+ const result = await connection.request(events ? "terminal.watch" : "terminal.list", { ...options.workspaceId ? { workspaceId: options.workspaceId } : {}, ...events && cursor ? { after: cursor } : {} });
27
+ if (closed) return;
28
+ if (!Array.isArray(result?.terminals)) throw new Error("Invalid terminal directory snapshot");
29
+ if (events) {
30
+ if (!/^[0-9a-f]{32}$/.test(result.watchId) || !/^[0-9a-f]{32}$/.test(result.cursor) || typeof result.reset !== "boolean") throw new Error("Invalid terminal directory cursor");
31
+ watchId = result.watchId;
32
+ cursor = result.cursor;
33
+ again = pending.has(watchId) && pending.get(watchId) !== cursor;
34
+ pending.clear();
35
+ }
36
+ options.onSnapshot(result.terminals);
37
+ } catch (error) {
38
+ options.onError?.(error);
39
+ return;
40
+ }
41
+ } while (again && !closed);
42
+ })().finally(() => {
43
+ refreshing = void 0;
44
+ });
45
+ return refreshing;
46
+ }
47
+ const timer = events ? void 0 : setInterval(() => {
48
+ void refresh();
49
+ }, options.pollMs ?? 5e3);
50
+ let offClose = () => {
51
+ };
52
+ function close(unwatch = true) {
53
+ if (closed) return;
54
+ closed = true;
55
+ if (timer !== void 0) clearInterval(timer);
56
+ off?.();
57
+ offClose();
58
+ pending.clear();
59
+ if (events && unwatch) void connection.request("terminal.unwatch", {}).catch(() => {
60
+ });
61
+ }
62
+ offClose = connection.onClose(() => close(false));
63
+ if (closed) offClose();
64
+ options.onMode?.(events ? "events" : "polling");
65
+ const ready = refresh();
66
+ return { ready, refresh, close, mode: events ? "events" : "polling" };
67
+ }
68
+ export {
69
+ watchTerminals
70
+ };
package/dist/service.d.ts CHANGED
@@ -32,7 +32,7 @@ export function serviceFor({ home, env, platform, uid }: {
32
32
  ignore: boolean;
33
33
  })[][];
34
34
  } | undefined;
35
- /** The service definition that runs `entry` with `execPath` for `home`. */
35
+ /** The service definition that runs `entry` (alpd.js with `execPath`, or the ALP executable) for `home`. */
36
36
  export function serviceDefinition(service: any, { home, entry, execPath, env }: {
37
37
  home: any;
38
38
  entry: any;
package/dist/service.js CHANGED
@@ -4,6 +4,7 @@ import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { runCommand } from "./command.js";
7
+ import { entryCommand } from "@anhlp/alp-core/packaged";
7
8
  var CARRIED = ["ALP_RUN_LOG_DIR", "ALP_CODEX_BIN", "ALP_CLAUDE_BIN", "ALP_ANTIGRAVITY_BIN", "ALP_GH_BIN"];
8
9
  var escapeXml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
9
10
  var quoteUnit = (value) => `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
@@ -44,7 +45,8 @@ function serviceFor({ home, env = process.env, platform = process.platform, uid
44
45
  function serviceDefinition(service, { home, entry, execPath = process.execPath, env = process.env }) {
45
46
  const variables = { ALP_HOME: path.resolve(home), PATH: env.PATH ?? "" };
46
47
  for (const name of CARRIED) if (env[name]) variables[name] = env[name];
47
- const program = [execPath, entry, "--service"];
48
+ const launch = entryCommand(entry, "daemon", ["--service"], execPath);
49
+ const program = [launch.command, ...launch.args];
48
50
  const fatal = path.join(path.resolve(home), "logs", "alpd.service.log");
49
51
  if (service.kind === "launchd") {
50
52
  return `<?xml version="1.0" encoding="UTF-8"?>
package/dist/setup.js CHANGED
@@ -3,7 +3,7 @@ import { copyFile, readFile, writeFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { parseArgs } from "node:util";
5
5
  import { initProject } from "@anhlp/alp-core/init";
6
- import { MODELS } from "@anhlp/alp-core/models";
6
+ import { catalogModels } from "@anhlp/alp-core/models";
7
7
  import { fitEffort, modelEfforts } from "@anhlp/alp-core/profiles";
8
8
  import { resolveTeam } from "@anhlp/alp-core/teams";
9
9
  import { validateSettings } from "@anhlp/alp-core/validation";
@@ -83,7 +83,7 @@ async function setup(args, home) {
83
83
  ] });
84
84
  if (next2 === "cancel") throw new Cancelled();
85
85
  if (next2 === "save") break;
86
- await change(seats);
86
+ await change(seats, home);
87
87
  show();
88
88
  }
89
89
  }
@@ -102,16 +102,17 @@ async function setup(args, home) {
102
102
  }
103
103
  }
104
104
  var describe = (choice) => `${choice.provider}:${choice.model}${choice.effort ? `:${choice.effort}` : ""}`;
105
- async function change(seats) {
105
+ async function change(seats, home) {
106
+ const catalog = catalogModels(home);
106
107
  const [seat, at] = await select({ message: "Which model?", choices: Object.entries(seats).flatMap(([seat2, choices]) => choices.map((choice, at2) => ({ label: `${SEAT_LABEL[seat2]} \xB7 ${PROVIDER_LABEL[choice.provider]}`, value: [seat2, at2], hint: describe(choice) }))) });
107
108
  const current = seats[seat][at];
108
- const offered = MODELS.filter((model2) => model2.runtime === current.provider);
109
+ const offered = catalog.filter((model2) => model2.runtime === current.provider);
109
110
  const picked = await select({ message: `${SEAT_LABEL[seat]} on ${PROVIDER_LABEL[current.provider]}`, initial: current.model, choices: [
110
111
  ...offered.map((model2) => ({ label: model2.label, value: model2.id, hint: `${model2.id} \xB7 ${model2.description}` })),
111
112
  { label: "Other\u2026", value: void 0, hint: "type a model ID" }
112
113
  ] });
113
114
  const model = picked ?? nativeModel(await text(`${PROVIDER_LABEL[current.provider]} model ID:`), current.provider, "The model ID");
114
- const efforts = modelEfforts(`${current.provider}:${model}`) ?? ANY_EFFORT;
115
+ const efforts = catalog.find((entry) => entry.runtime === current.provider && entry.id === model)?.efforts ?? modelEfforts(`${current.provider}:${model}`) ?? ANY_EFFORT;
115
116
  const effort = efforts.length > 1 ? await select({
116
117
  message: "Effort",
117
118
  initial: efforts.includes(current.effort) ? current.effort : DEFAULTS[seat][current.provider][1],
@@ -1,7 +1,7 @@
1
1
  export function holdDaemon(home: string, by?: string): Promise<void>;
2
2
  export function releaseHold(home: string): Promise<void>;
3
3
  export function daemonHeld(home: string): Promise<boolean>;
4
- export function startDaemon(options: { home: string; entry?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number }): Promise<string>;
4
+ export function startDaemon(options: { home: string; entry?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number; signal?: AbortSignal }): Promise<string>;
5
5
  export function superviseDaemon(options: {
6
6
  home: string;
7
7
  entry?: string | (() => string | undefined);
package/dist/supervise.js CHANGED
@@ -15,29 +15,33 @@ async function releaseHold(home) {
15
15
  async function daemonHeld(home) {
16
16
  return stat(holdFile(home)).then(() => true, () => false);
17
17
  }
18
- async function whenReady(home, timeoutMs) {
18
+ async function whenReady(home, timeoutMs, signal) {
19
19
  const deadline = Date.now() + timeoutMs;
20
20
  while (Date.now() < deadline) {
21
+ signal?.throwIfAborted();
21
22
  const lock = await readLock(home);
22
23
  if (lockAlive(lock) && lock.ready) return lock.socket;
23
24
  await new Promise((resolve) => setTimeout(resolve, 100));
24
25
  }
25
26
  throw new Error(`alpd did not become ready within ${timeoutMs / 1e3} s; see ${path.join(home, "logs")}`);
26
27
  }
27
- async function startDaemon({ home, entry, env = process.env, timeoutMs = 15e3, automatic = false }) {
28
+ async function startDaemon({ home, entry, env = process.env, timeoutMs = 15e3, automatic = false, signal }) {
28
29
  return withDaemonLifecycle(home, "start", async () => {
30
+ signal?.throwIfAborted();
29
31
  if (automatic) {
30
32
  if (await daemonHeld(home)) return;
31
33
  } else await releaseHold(home);
32
34
  const lock = await readLock(home);
33
- if (lockAlive(lock)) return lock.ready ? lock.socket : whenReady(home, timeoutMs);
35
+ signal?.throwIfAborted();
36
+ if (lockAlive(lock)) return lock.ready ? lock.socket : whenReady(home, timeoutMs, signal);
34
37
  const service = serviceFor({ home, env });
35
38
  if (service && await installedProgram(service)) {
39
+ signal?.throwIfAborted();
36
40
  await startService(service);
37
- return whenReady(home, timeoutMs);
41
+ return whenReady(home, timeoutMs, signal);
38
42
  }
39
- return ensureDaemon({ home, entry, env, timeoutMs, lifecycleLocked: true });
40
- });
43
+ return ensureDaemon({ home, entry, env, timeoutMs, lifecycleLocked: true, signal });
44
+ }, { signal });
41
45
  }
42
46
  function superviseDaemon({ home, entry, env = process.env, intervalMs = 5e3, misses = 2, log = () => {
43
47
  }, by }) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anhlp/alp-client",
3
- "version": "0.0.1-beta.4",
3
+ "version": "0.0.1-beta.5",
4
4
  "type": "module",
5
5
  "description": "ALP client: portable JSON-RPC SDK, WebSocket and Node IPC transports, daemon discovery and setup",
6
6
  "files": [
@@ -150,8 +150,8 @@
150
150
  "node": ">=22.12"
151
151
  },
152
152
  "dependencies": {
153
- "@anhlp/alp-core": "0.0.1-beta.4",
154
- "@anhlp/alp-protocol": "0.0.1-beta.4"
153
+ "@anhlp/alp-core": "0.0.1-beta.5",
154
+ "@anhlp/alp-protocol": "0.0.1-beta.5"
155
155
  },
156
156
  "scripts": {
157
157
  "build": "node ../../scripts/build-workspace.mjs client",
@@ -12,6 +12,16 @@ const DEFAULT_ANTIGRAVITY_MODELS = [
12
12
  ];
13
13
 
14
14
  const ANTIGRAVITY_MODES = [
15
+ {
16
+ id: 'read-only',
17
+ label: 'Read only',
18
+ description: 'agy reads and searches; it denies file edits and terminal commands (--sandbox, request-review).',
19
+ },
20
+ {
21
+ id: 'workspace-write',
22
+ label: 'Workspace write',
23
+ description: 'agy edits files and runs commands in its terminal sandbox inside the workspace (--mode accept-edits --sandbox, proceed-in-sandbox).',
24
+ },
15
25
  {
16
26
  id: 'full-access',
17
27
  label: 'Full access',
@@ -54,7 +64,7 @@ function runCommand(command, args, { env = process.env, cwd, timeoutMs = 20_000
54
64
 
55
65
  /**
56
66
  * Probes Antigravity CLI for version, status and available models.
57
- * @param {{ command?: string, args?: string[], env?: Record<string, string>, label?: string, id?: string, readOnlyMode?: 'instructions' | 'reject' }} [provider]
67
+ * @param {{ command?: string, args?: string[], env?: Record<string, string>, label?: string, id?: string}} [provider] readOnlyMode, if set, is a legacy setting with no effect: agy enforces read-only itself.
58
68
  * @param {{ cwd?: string, timeoutMs?: number }} [options]
59
69
  */
60
70
  export async function probeAntigravity(provider = {}, { cwd, timeoutMs = 20_000 } = {}) {
@@ -97,10 +107,7 @@ export async function probeAntigravity(provider = {}, { cwd, timeoutMs = 20_000
97
107
  agent: { name: 'antigravity', title: 'Antigravity', version },
98
108
  models,
99
109
  currentModel: models[0]?.id,
100
- modes: provider.readOnlyMode === 'instructions' ? [...ANTIGRAVITY_MODES, {
101
- id: 'read-only', label: 'Read only (instructions)',
102
- description: 'For new sessions: prompt-only read-only behavior. agy still runs with full access; no OS sandbox enforces this mode.',
103
- }] : ANTIGRAVITY_MODES,
110
+ modes: ANTIGRAVITY_MODES,
104
111
  currentMode: 'full-access',
105
112
  };
106
113
  }
package/src/command.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { spawn } from 'node:child_process';
2
+ import { scriptCommand } from '@anhlp/alp-core/packaged';
2
3
 
3
4
  /** Runs a command; resolves with its exit code and output, never rejects. */
4
5
  export function runCommand(command, args, { cwd, env = process.env, timeoutMs = 15_000 } = {}) {
@@ -6,7 +7,8 @@ export function runCommand(command, args, { cwd, env = process.env, timeoutMs =
6
7
  let child;
7
8
  // Windows cannot exec a script by its shebang; a JavaScript command runs under this Node, as the Codex transport does.
8
9
  const script = process.platform === 'win32' && /\.[cm]?js$/i.test(command);
9
- try { child = spawn(script ? process.execPath : command, script ? [command, ...args] : args, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'] }); }
10
+ const run = script ? scriptCommand(command, args) : { command, args };
11
+ try { child = spawn(run.command, run.args, { cwd, env: run.env ? { ...env, ...run.env } : env, stdio: ['ignore', 'pipe', 'pipe'] }); }
10
12
  catch (error) { resolve({ code: -1, stdout: '', stderr: error.message }); return; }
11
13
  let stdout = '', stderr = '';
12
14
  child.stdout.on('data', chunk => { stdout += chunk; });
package/src/doctor.d.ts CHANGED
@@ -10,4 +10,5 @@ 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 function diskCheck(home: string, options?: { run?: CommandRunner; env?: NodeJS.ProcessEnv; free?: number; tempDirs?: string[] }): Promise<DoctorCheck>;
13
14
  export function repair(checks: DoctorCheck[]): Promise<Array<{ id: string; result: string }>>;
package/src/doctor.js CHANGED
@@ -1,4 +1,6 @@
1
- import { access, chmod, constants, lstat, readdir, readFile, unlink, writeFile } from 'node:fs/promises';
1
+ import { realpathSync } from 'node:fs';
2
+ import { access, chmod, constants, lstat, readdir, readFile, statfs, unlink, writeFile } from 'node:fs/promises';
3
+ import os from 'node:os';
2
4
  import path from 'node:path';
3
5
  import { runCommand } from './command.js';
4
6
  import { assertPrivateSocket, connect, daemonPaths, lockAlive, readLock } from './index.js';
@@ -519,12 +521,115 @@ async function schemaChecks(home) {
519
521
  return checks;
520
522
  }
521
523
 
524
+ /** Checks whether directory `target` is inside directory `container`. */
525
+ function isInside(target, container) {
526
+ const resolve = directory => {
527
+ let current = path.resolve(directory);
528
+ let suffix = '';
529
+ for (;;) {
530
+ try { return path.join(realpathSync(current), suffix); }
531
+ catch {
532
+ const parent = path.dirname(current);
533
+ if (parent === current) return path.join(current, suffix);
534
+ suffix = path.join(path.basename(current), suffix);
535
+ current = parent;
536
+ }
537
+ }
538
+ };
539
+ const resolvedTarget = resolve(target);
540
+ const resolvedContainer = resolve(container);
541
+ const relative = path.relative(resolvedContainer, resolvedTarget);
542
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
543
+ }
544
+
545
+ /**
546
+ * Checks where ALP_HOME sits: staging and state live there (§12.6). Sandboxed sessions
547
+ * can write the temp directory and their workspace, so staged copies inside either could
548
+ * be modified by a sandboxed tool before alpd reads them (ALP_ATTACHMENT_STAGE_EXPOSED).
549
+ */
550
+ async function homeLocationCheck(home, project) {
551
+ if (process.platform === 'win32' || !home) return { id: 'home', status: 'ok', summary: home ?? '' };
552
+ if (project && isInside(home, project)) {
553
+ return {
554
+ id: 'home', status: 'warn',
555
+ 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)`,
556
+ };
557
+ }
558
+ const inTmp = isInside(home, os.tmpdir()) || isInside(home, '/tmp');
559
+ if (inTmp) {
560
+ return {
561
+ id: 'home', status: 'warn',
562
+ 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)`,
563
+ };
564
+ }
565
+ return { id: 'home', status: 'ok', summary: home };
566
+ }
567
+
568
+ const GIB = 1024 ** 3;
569
+ const formatSize = bytes => bytes >= GIB ? `${(bytes / GIB).toFixed(1)} GB` : `${Math.round(bytes / 1024 ** 2)} MB`;
570
+
571
+ /** Entries of `directory` whose names start with `prefix`, as full paths; none when it cannot be read. */
572
+ async function entries(directory, prefix = '') {
573
+ const names = await readdir(directory).catch(() => []);
574
+ return names.filter(name => name.startsWith(prefix)).map(name => path.join(directory, name));
575
+ }
576
+
577
+ /**
578
+ * Free space where ALP_HOME lives (t-2831), and what earlier runs left that takes room:
579
+ * worktrees under ALP_HOME/worktrees and alp-* directories in the temp directory. When
580
+ * the disk fills, alpd pauses work instead of stopping; this says so before it happens.
581
+ * Nothing is deleted, by --fix either: a leftover may hold someone's uncommitted work.
582
+ */
583
+ export async function diskCheck(home, { run = runCommand, env = process.env, free, tempDirs = [...new Set([os.tmpdir(), ...(process.platform === 'win32' ? [] : ['/tmp'])])] } = {}) {
584
+ let bytes = free;
585
+ if (bytes === undefined) {
586
+ try { const info = await statfs(home); bytes = Number(info.bavail) * Number(info.bsize); } catch {}
587
+ }
588
+ const worktrees = await entries(path.join(home, 'worktrees'));
589
+ const temp = [];
590
+ for (const directory of tempDirs) {
591
+ for (const entry of await entries(directory, 'alp-')) {
592
+ const info = await lstat(entry).catch(() => undefined);
593
+ if (info?.isDirectory() && !temp.includes(realpathOr(entry))) temp.push(realpathOr(entry));
594
+ }
595
+ }
596
+ /** Kilobytes du counts under the paths; undefined when du is missing, slow or fails. */
597
+ async function size(paths) {
598
+ if (!paths.length) return 0;
599
+ if (process.platform === 'win32') return undefined;
600
+ const result = await run('du', ['-sk', ...paths], { env, timeoutMs: 20_000 });
601
+ if (result.code !== 0 && !result.stdout) return undefined;
602
+ const total = result.stdout.split('\n').reduce((sum, line) => sum + (Number(line.split(/\s+/)[0]) || 0), 0);
603
+ return total * 1024;
604
+ }
605
+ const details = [];
606
+ for (const [label, paths] of [[`${path.join(home, 'worktrees')}`, worktrees], [`${tempDirs.map(directory => path.join(directory, 'alp-*')).join(', ')}`, temp]]) {
607
+ if (!paths.length) continue;
608
+ const used = await size(paths);
609
+ details.push(`${paths.length} left in ${label}${used === undefined ? '' : `, ${formatSize(used)}`}`);
610
+ }
611
+ const hint = details.length ? 'ALP deletes none of these: some may belong to running assignments or hold uncommitted work. Remove those you no longer need (git worktree remove, or rm -rf).' : undefined;
612
+ const where = bytes === undefined ? 'free space unknown' : `${formatSize(bytes)} free`;
613
+ // Leftovers are listed, not judged: some may be live.
614
+ const status = bytes !== undefined && bytes < 2 * GIB ? 'warn' : 'ok';
615
+ const summary = bytes !== undefined && bytes < 2 * GIB
616
+ ? `${where} where ALP_HOME lives; when the disk is full, alpd pauses all work until space returns`
617
+ : `${where} where ALP_HOME lives`;
618
+ return { id: 'disk', status, summary, ...(details.length ? { details } : {}), ...(hint ? { hint } : {}) };
619
+ }
620
+
621
+ function realpathOr(file) {
622
+ try { return realpathSync(file); } catch { return file; }
623
+ }
624
+
522
625
  export async function diagnose({ home, project, env = process.env, run = runCommand, sandbox, daemonEntry, timeoutMs = 3000 } = {}) {
523
626
  const checks = [];
524
627
  if (daemonEntry) {
525
628
  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` })));
526
629
  }
527
630
  checks.push(...await runtimeChecks({ env, run }));
631
+ checks.push(await homeLocationCheck(home, project));
632
+ if (home) checks.push(await diskCheck(home, { run, env }));
528
633
  const daemon = await daemonCheck(home);
529
634
  checks.push(daemon);
530
635
  const service = await serviceCheck(home, env);