@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.
package/README.md CHANGED
@@ -27,3 +27,19 @@ the gateway (Task 08).
27
27
  Build: `npm run build --workspace=@anhlp/alp-client`. Test: `npm run test --workspace=@anhlp/alp-client`.
28
28
 
29
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
+ Each mutation is sent once: keep its `requestId` and `ifGeneration` (the generation `session.history`
36
+ answered) and send the identical request again only after a lost answer, which alpd answers with the
37
+ first result and `duplicate: true`. After a rewind, attached clients get `history.reset`: drop the
38
+ cached history and attach again with its generation. See
39
+ [docs/alp/client-sdk.md](../../docs/alp/client-sdk.md).
40
+
41
+ Terminal directory clients can use `watchTerminals(connection, {capabilities, onSnapshot,
42
+ onMode, onError})` from the portable entry. Install one per connection, await `ready`, and call
43
+ `close()` when leaving. It uses atomic scoped snapshots and cursor invalidations on hosts with
44
+ `terminal.watch`; `onMode('polling')` explicitly identifies the five-second older-host fallback.
45
+ Reconnect with a new helper and replace the directory from the reset snapshot.
@@ -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, readOnlyMode?: 'instructions' | 'reject' }} [provider]
3
+ * @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.
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: provider.readOnlyMode === "instructions" ? [...ANTIGRAVITY_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(script ? process.execPath : command, script ? [command, ...args] : args, { cwd, env, stdio: ["ignore", "pipe", "pipe"] });
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,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/dist/doctor.js CHANGED
@@ -1,5 +1,7 @@
1
1
  // packages/client/src/doctor.js
2
- import { access, chmod, constants, lstat, readdir, readFile, unlink, writeFile } from "node:fs/promises";
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";
@@ -272,15 +274,15 @@ async function daemonCheck(home) {
272
274
  };
273
275
  }
274
276
  async function privateEntries(home) {
275
- const entries = [home];
276
- for (const name of ["settings.json", "alpd.lock", "alpd.json", "role-skills.json"]) entries.push(path.join(home, name));
277
+ const entries2 = [home];
278
+ for (const name of ["settings.json", "alpd.lock", "alpd.json", "role-skills.json"]) entries2.push(path.join(home, name));
277
279
  for (const directory of ["state", "runs", "logs", "boards", "worktrees", "copies"]) {
278
280
  const full = path.join(home, directory);
279
- entries.push(full);
281
+ entries2.push(full);
280
282
  if (directory === "worktrees" || directory === "copies") continue;
281
- for (const name of await readdir(full).catch(() => [])) entries.push(path.join(full, name));
283
+ for (const name of await readdir(full).catch(() => [])) entries2.push(path.join(full, name));
282
284
  }
283
- return entries;
285
+ return entries2;
284
286
  }
285
287
  async function permissionsCheck(home) {
286
288
  if (process.platform === "win32") return { id: "permissions", status: "ok", summary: `${home} follows your Windows profile access rules` };
@@ -434,18 +436,18 @@ async function librarySkillsCheck(home) {
434
436
  }
435
437
  async function liveCheck(home, running) {
436
438
  const file = path.join(home, "state", "live.json");
437
- let entries;
439
+ let entries2;
438
440
  try {
439
- entries = JSON.parse(await readFile(file, "utf8"));
441
+ entries2 = JSON.parse(await readFile(file, "utf8"));
440
442
  } catch {
441
443
  return void 0;
442
444
  }
443
- if (!Array.isArray(entries)) return { id: "live work", status: "warn", summary: `${file} is not a list; alpd ignores it` };
445
+ if (!Array.isArray(entries2)) return { id: "live work", status: "warn", summary: `${file} is not a list; alpd ignores it` };
444
446
  const gone = [];
445
- for (const entry of entries) {
447
+ for (const entry of entries2) {
446
448
  if (typeof entry?.project !== "string" || !await lstat(entry.project).then(() => true, () => false)) gone.push(entry);
447
449
  }
448
- if (!gone.length) return { id: "live work", status: entries.length && !running ? "info" : "ok", summary: entries.length ? `${entries.length} assignment${entries.length > 1 ? "s" : ""} ${running ? "running" : "waiting for alpd to continue"}` : "no running assignments" };
450
+ 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
451
  return {
450
452
  id: "live work",
451
453
  status: "warn",
@@ -533,12 +535,103 @@ async function schemaChecks(home) {
533
535
  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
536
  return checks;
535
537
  }
538
+ function isInside(target, container) {
539
+ const resolve = (directory) => {
540
+ let current = path.resolve(directory);
541
+ let suffix = "";
542
+ for (; ; ) {
543
+ try {
544
+ return path.join(realpathSync(current), suffix);
545
+ } catch {
546
+ const parent = path.dirname(current);
547
+ if (parent === current) return path.join(current, suffix);
548
+ suffix = path.join(path.basename(current), suffix);
549
+ current = parent;
550
+ }
551
+ }
552
+ };
553
+ const resolvedTarget = resolve(target);
554
+ const resolvedContainer = resolve(container);
555
+ const relative = path.relative(resolvedContainer, resolvedTarget);
556
+ return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
557
+ }
558
+ async function homeLocationCheck(home, project) {
559
+ if (process.platform === "win32" || !home) return { id: "home", status: "ok", summary: home ?? "" };
560
+ if (project && isInside(home, project)) {
561
+ return {
562
+ id: "home",
563
+ status: "warn",
564
+ 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)`
565
+ };
566
+ }
567
+ const inTmp = isInside(home, os.tmpdir()) || isInside(home, "/tmp");
568
+ if (inTmp) {
569
+ return {
570
+ id: "home",
571
+ status: "warn",
572
+ 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)`
573
+ };
574
+ }
575
+ return { id: "home", status: "ok", summary: home };
576
+ }
577
+ var GIB = 1024 ** 3;
578
+ var formatSize = (bytes) => bytes >= GIB ? `${(bytes / GIB).toFixed(1)} GB` : `${Math.round(bytes / 1024 ** 2)} MB`;
579
+ async function entries(directory, prefix = "") {
580
+ const names = await readdir(directory).catch(() => []);
581
+ return names.filter((name) => name.startsWith(prefix)).map((name) => path.join(directory, name));
582
+ }
583
+ async function diskCheck(home, { run = runCommand, env = process.env, free, tempDirs = [.../* @__PURE__ */ new Set([os.tmpdir(), ...process.platform === "win32" ? [] : ["/tmp"]])] } = {}) {
584
+ let bytes = free;
585
+ if (bytes === void 0) {
586
+ try {
587
+ const info = await statfs(home);
588
+ bytes = Number(info.bavail) * Number(info.bsize);
589
+ } catch {
590
+ }
591
+ }
592
+ const worktrees = await entries(path.join(home, "worktrees"));
593
+ const temp = [];
594
+ for (const directory of tempDirs) {
595
+ for (const entry of await entries(directory, "alp-")) {
596
+ const info = await lstat(entry).catch(() => void 0);
597
+ if (info?.isDirectory() && !temp.includes(realpathOr(entry))) temp.push(realpathOr(entry));
598
+ }
599
+ }
600
+ async function size(paths) {
601
+ if (!paths.length) return 0;
602
+ if (process.platform === "win32") return void 0;
603
+ const result = await run("du", ["-sk", ...paths], { env, timeoutMs: 2e4 });
604
+ if (result.code !== 0 && !result.stdout) return void 0;
605
+ const total = result.stdout.split("\n").reduce((sum, line) => sum + (Number(line.split(/\s+/)[0]) || 0), 0);
606
+ return total * 1024;
607
+ }
608
+ const details = [];
609
+ for (const [label, paths] of [[`${path.join(home, "worktrees")}`, worktrees], [`${tempDirs.map((directory) => path.join(directory, "alp-*")).join(", ")}`, temp]]) {
610
+ if (!paths.length) continue;
611
+ const used = await size(paths);
612
+ details.push(`${paths.length} left in ${label}${used === void 0 ? "" : `, ${formatSize(used)}`}`);
613
+ }
614
+ 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)." : void 0;
615
+ const where = bytes === void 0 ? "free space unknown" : `${formatSize(bytes)} free`;
616
+ const status = bytes !== void 0 && bytes < 2 * GIB ? "warn" : "ok";
617
+ 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`;
618
+ return { id: "disk", status, summary, ...details.length ? { details } : {}, ...hint ? { hint } : {} };
619
+ }
620
+ function realpathOr(file) {
621
+ try {
622
+ return realpathSync(file);
623
+ } catch {
624
+ return file;
625
+ }
626
+ }
536
627
  async function diagnose({ home, project, env = process.env, run = runCommand, sandbox, daemonEntry, timeoutMs = 3e3 } = {}) {
537
628
  const checks = [];
538
629
  if (daemonEntry) {
539
630
  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
631
  }
541
632
  checks.push(...await runtimeChecks({ env, run }));
633
+ checks.push(await homeLocationCheck(home, project));
634
+ if (home) checks.push(await diskCheck(home, { run, env }));
542
635
  const daemon = await daemonCheck(home);
543
636
  checks.push(daemon);
544
637
  const service = await serviceCheck(home, env);
@@ -582,6 +675,7 @@ async function repair(checks) {
582
675
  }
583
676
  export {
584
677
  diagnose,
678
+ diskCheck,
585
679
  repair,
586
680
  runCommand
587
681
  };
package/dist/index.d.ts CHANGED
@@ -28,8 +28,44 @@ export function findDaemonEntry({ home, env, candidates }?: {
28
28
  * @returns {string}
29
29
  */
30
30
  export function assertIntegrationName(name: unknown): string;
31
+ /**
32
+ * Returns a stable identifier for the current OS boot session,
33
+ * or undefined if unavailable on the platform or inaccessible.
34
+ *
35
+ * On Linux, reads /proc/sys/kernel/random/boot_id.
36
+ * On Darwin (macOS), queries sysctl kern.bootsessionuuid.
37
+ *
38
+ * @returns {string | undefined}
39
+ */
40
+ export function bootId(): string | undefined;
41
+ /**
42
+ * Internal/testing seam: resets or sets the cached boot identifier.
43
+ * @param {string | undefined | null} [id]
44
+ */
45
+ export function _setBootIdForTest(id?: string | undefined | null): void;
31
46
  /** Wall-clock boot time; a lock from an earlier boot is stale even if its pid is reused. */
32
47
  export function bootTime(): number;
48
+ /**
49
+ * Evaluates whether a lock record belongs to the current boot session.
50
+ *
51
+ * When both the lock and the current environment supply a bootId (Linux
52
+ * /proc/sys/kernel/random/boot_id or macOS kern.bootsessionuuid), identity is
53
+ * determined by exact bootId match, which is immune to wall-clock jumps.
54
+ *
55
+ * For legacy locks or environments without a bootId, falls back to checking
56
+ * whether wall-clock bootTime is within a 30-second window.
57
+ *
58
+ * @param {{ bootId?: string, bootTime?: number }} [lock]
59
+ * @param {{ bootId?: string, bootTime?: number }} [current]
60
+ * @returns {boolean}
61
+ */
62
+ export function isSameBoot(lock?: {
63
+ bootId?: string;
64
+ bootTime?: number;
65
+ }, { bootId: curBootId, bootTime: curBootTime }?: {
66
+ bootId?: string;
67
+ bootTime?: number;
68
+ }): boolean;
33
69
  export function readLock(home: any): Promise<any>;
34
70
  export function lockAlive(lock: any): boolean;
35
71
  /**
@@ -49,11 +85,13 @@ export function acquireDaemonLock(home: string, contents: {
49
85
  protocolVersion: number;
50
86
  socket: string;
51
87
  maintenance?: string;
88
+ uid: number;
89
+ ready: boolean;
90
+ bootId?: string | undefined;
52
91
  pid: number;
53
92
  startedAt: string;
93
+ startedUptime: number;
54
94
  bootTime: number;
55
- uid: number;
56
- ready: boolean;
57
95
  }>;
58
96
  /** Lets go of alpd's lock if this process holds it. */
59
97
  export function releaseDaemonLock(home: any): Promise<void>;
@@ -86,21 +124,23 @@ export function readDaemonLifecycle(home: any): Promise<{
86
124
  * be replaced. Reaping/release unlinks only its unique owner token, then rmdir; even
87
125
  * racing stale reapers cannot remove a successor's nonempty directory.
88
126
  */
89
- export function withDaemonLifecycle(home: any, action: any, run: any, { joinStart }?: {
127
+ export function withDaemonLifecycle(home: any, action: any, run: any, { joinStart, signal }?: {
90
128
  joinStart?: boolean | undefined;
129
+ signal?: AbortSignal | undefined;
91
130
  }): Promise<any>;
92
131
  /**
93
132
  * Returns the socket of a ready daemon, starting one when none runs.
94
133
  * `entry` is the daemon script; it is started through its own detaching launcher so the
95
134
  * daemon outlives the client that started it.
96
135
  */
97
- export function ensureDaemon({ home, entry, env, execPath, timeoutMs, lifecycleLocked }?: {
136
+ export function ensureDaemon({ home, entry, env, execPath, timeoutMs, lifecycleLocked, signal }?: {
98
137
  home?: string | undefined;
99
138
  entry?: string | undefined;
100
139
  env?: NodeJS.ProcessEnv | undefined;
101
140
  execPath?: string | undefined;
102
141
  timeoutMs?: number | undefined;
103
142
  lifecycleLocked?: boolean | undefined;
143
+ signal?: AbortSignal | undefined;
104
144
  }): Promise<any>;
105
145
  /**
106
146
  * The entry of integration `name`: an environment override, a descriptor under the home or a
@@ -116,6 +156,7 @@ export function ensureDaemon({ home, entry, env, execPath, timeoutMs, lifecycleL
116
156
  export function discoverIntegration(name?: string, options?: {
117
157
  home?: string;
118
158
  }): Promise<string | undefined>;
159
+ export function integrationAlive(lock: any): boolean;
119
160
  /**
120
161
  * Starts integration `name` (default `web`) detached with `--service` (then `args`) unless its lock
121
162
  * already names a live owner, then waits until its ready lock and `<home>/<name>.json` name the same
@@ -145,6 +186,16 @@ export class AlpClient extends AlpRpcClient {
145
186
  constructor(socket: import("node:net").Socket, { maxFrame, maxBufferedBytes, ...options }?: import("./rpc/client.js").AlpRpcClientOptions & import("./ipc.js").SocketTransportOptions);
146
187
  /** Host features captured by connect's handshake. @type {readonly string[]} */
147
188
  capabilities: readonly string[];
189
+ /** Limits captured by connect's handshake. @type {import('@anhlp/alp-protocol').AttachmentLimits | undefined} */
190
+ attachmentLimits: import("@anhlp/alp-protocol").AttachmentLimits | undefined;
191
+ /** @type {{ readonly maxCount: number; readonly maxBytes: number; readonly maxTotalBytes: number } | undefined} */
192
+ promptImageLimits: {
193
+ readonly maxCount: number;
194
+ readonly maxBytes: number;
195
+ readonly maxTotalBytes: number;
196
+ } | undefined;
197
+ /** @type {import('@anhlp/alp-protocol').TerminalLimits | undefined} */
198
+ terminalLimits: import("@anhlp/alp-protocol").TerminalLimits | undefined;
148
199
  }
149
200
  import { AlpRpcClient } from './rpc/client.js';
150
201
  export { PROTOCOL_VERSION, MAX_FRAME, AlpRpcError, encodeFrame } from "@anhlp/alp-protocol";