@anhlp/alp-client 0.0.1-beta.7 → 0.0.1-beta.9

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/index.js CHANGED
@@ -2,13 +2,14 @@
2
2
  import { setTimeout as delay } from "node:timers/promises";
3
3
  import { execFileSync, spawn } from "node:child_process";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
- import { readFileSync } from "node:fs";
6
- import { open, readFile, writeFile, realpath, stat, lstat, mkdir, readlink, unlink, readdir, rename, rmdir, link } from "node:fs/promises";
5
+ import { fstatSync, readFileSync } from "node:fs";
6
+ import { open, readFile, writeFile, realpath, stat, lstat, mkdir, readlink, unlink, readdir, chmod, rename, rmdir, link } from "node:fs/promises";
7
7
  import net from "node:net";
8
8
  import os from "node:os";
9
9
  import path from "node:path";
10
10
  import { scrubText } from "@anhlp/alp-core/log";
11
- import { entryCommand } from "@anhlp/alp-core/packaged";
11
+ import { entryCommand, isNativeDaemonName, NATIVE_DAEMON } from "@anhlp/alp-core/packaged";
12
+ import { dashboardSettings } from "@anhlp/alp-core/user-settings";
12
13
  import { createSocketTransport } from "./ipc.js";
13
14
  import { AlpRpcClient } from "./rpc/client.js";
14
15
  import { hello } from "./rpc/handshake.js";
@@ -63,11 +64,21 @@ async function assertSafeAncestors(directory) {
63
64
  async function assertPrivateDirectory(directory, { create = false } = {}) {
64
65
  await assertSafeAncestors(directory);
65
66
  if (create) await mkdir(directory, { recursive: true, mode: 448 });
66
- const info = await lstat(directory);
67
+ let info = await lstat(directory);
67
68
  if (!info.isDirectory() || info.isSymbolicLink()) throw new Error("IPC requires a private directory, not a symlink");
68
- if (process.platform !== "win32" && (info.uid !== process.getuid?.() || (info.mode & 63) !== 0)) {
69
- throw new Error("IPC directory must be owned by the current user with private permissions (0700)");
69
+ if (process.platform === "win32") return;
70
+ const shown = JSON.stringify(directory);
71
+ const mine = (entry) => entry.isDirectory() && !entry.isSymbolicLink() && entry.uid === process.getuid?.();
72
+ if (info.uid !== process.getuid?.()) throw new Error(`IPC directory ${shown} must be owned by the current user (it belongs to uid ${info.uid}); use a directory of your own`);
73
+ if ((info.mode & 63) === 0) return;
74
+ if (create && (await readdir(directory)).length === 0) {
75
+ await chmod(directory, 448).catch(() => {
76
+ });
70
77
  }
78
+ info = await lstat(directory);
79
+ if (mine(info) && (info.mode & 63) === 0) return;
80
+ const quoted = `'${directory.replaceAll("'", "'\\''")}'`;
81
+ throw new Error(`IPC directory ${shown} must have private permissions (0700), not ${(info.mode & 511).toString(8).padStart(4, "0")}; fix it with: chmod 700 ${quoted}`);
71
82
  }
72
83
  async function assertPrivateSocket(socketPath) {
73
84
  if (process.platform === "win32") return;
@@ -81,17 +92,27 @@ async function assertPrivateSocket(socketPath) {
81
92
  var isFile = (file) => stat(file).then((info) => info.isFile(), () => false);
82
93
  var BIN_DIRECTORIES = [path.join(os.homedir(), ".alp", "bin"), path.join(os.homedir(), ".npm-global", "bin"), path.join(os.homedir(), ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin"];
83
94
  var CLI_PACKAGES = ["@anhlp/alp", "@anhlp/alp-cli"];
84
- async function cliDaemonEntry(cli) {
95
+ async function cliDaemonEntry(cli, depth = 0, env = process.env) {
85
96
  const base = path.basename(cli).toLowerCase();
86
97
  const root = path.resolve(path.dirname(cli), "..");
87
98
  const alpd = (directory) => path.join(directory, "dist", "alpd.js");
88
99
  const named = async (directory) => readFile(path.join(directory, "package.json"), "utf8").then((text) => JSON.parse(text)?.name).catch(() => void 0);
89
100
  let candidates = [];
101
+ if (base === "alp.cmd" && depth < 1 && !await isFile(path.join(root, "alp-bundle.json"))) {
102
+ const text = await stat(cli).then((info) => info.size <= 64 * 1024 ? readFile(cli, "utf8") : "", () => "");
103
+ for (const [, quoted] of text.matchAll(/"([^"\r\n]+\.js)"/gi)) {
104
+ const script = quoted.replace(/^%~?dp0%?[\\/]?/i, `${path.dirname(cli)}${path.sep}`);
105
+ const entry = path.isAbsolute(script) && await isFile(script) ? await cliDaemonEntry(script, depth + 1, env) : void 0;
106
+ if (entry) return entry;
107
+ }
108
+ return void 0;
109
+ }
90
110
  if (base === "alp" || base === "alp.cmd") {
91
111
  if (!await isFile(path.join(root, "alp-bundle.json"))) return void 0;
92
112
  const current = path.join(path.dirname(root), "current");
93
113
  const viaCurrent = await realpath(current).then((real) => real === root, () => false);
94
- candidates = [alpd(path.join(viaCurrent ? current : root, "lib", "node_modules", "@anhlp", "alp-cli"))];
114
+ const bundle = viaCurrent ? current : root;
115
+ candidates = [...env.ALP_NATIVE_DAEMON === "0" ? [] : [path.join(bundle, "bin", NATIVE_DAEMON)], alpd(path.join(bundle, "lib", "node_modules", "@anhlp", "alp-cli"))];
95
116
  } else if (base === "cli.js" && CLI_PACKAGES.includes(await named(root))) {
96
117
  candidates = [alpd(root)];
97
118
  } else if (base === "alp.js" && await named(root) === "@anhlp/alp") {
@@ -103,17 +124,17 @@ async function cliDaemonEntry(cli) {
103
124
  async function findDaemonEntry({ home = alpHome(), env = process.env, candidates = (
104
125
  /** @type {Array<string | undefined>} */
105
126
  []
106
- ) } = {}) {
127
+ ), binDirectories = BIN_DIRECTORIES } = {}) {
107
128
  for (const candidate of candidates) if (candidate && await isFile(candidate)) return candidate;
108
129
  try {
109
130
  const { entry } = JSON.parse(await readFile(daemonPaths(home).install, "utf8"));
110
131
  if (typeof entry === "string" && await isFile(entry)) return entry;
111
132
  } catch {
112
133
  }
113
- for (const directory of [...(env.PATH ?? "").split(path.delimiter).filter(Boolean), ...BIN_DIRECTORIES]) {
134
+ for (const directory of [...(env.PATH ?? "").split(path.delimiter).filter(Boolean), ...binDirectories]) {
114
135
  for (const name of process.platform === "win32" ? ["alp.cmd", "alp"] : ["alp"]) {
115
136
  const cli = await realpath(path.join(directory, name)).catch(() => void 0);
116
- const entry = cli && await cliDaemonEntry(cli);
137
+ const entry = cli && await cliDaemonEntry(cli, 0, env);
117
138
  if (entry) return entry;
118
139
  }
119
140
  }
@@ -198,7 +219,24 @@ async function acquireDaemonLock(home, contents) {
198
219
  for (let attempt = 0; attempt < 2; attempt++) {
199
220
  try {
200
221
  const handle = await open(file, "wx", 384);
201
- await handle.writeFile(JSON.stringify(lock));
222
+ let ours;
223
+ try {
224
+ ours = await handle.stat();
225
+ await handle.writeFile(JSON.stringify(lock));
226
+ } catch (error) {
227
+ if (!ours) {
228
+ try {
229
+ ours = fstatSync(handle.fd);
230
+ } catch {
231
+ }
232
+ }
233
+ await handle.close().catch(() => {
234
+ });
235
+ const there = await lstat(file).catch(() => void 0);
236
+ if (ours && there && ours.ino === there.ino && ours.dev === there.dev) await unlink(file).catch(() => {
237
+ });
238
+ throw error;
239
+ }
202
240
  await handle.close();
203
241
  return lock;
204
242
  } catch (error) {
@@ -206,7 +244,13 @@ async function acquireDaemonLock(home, contents) {
206
244
  const current = await readLock(home);
207
245
  if (lockAlive(current)) throw new Error(current.maintenance ? `ALP is busy: alp ${current.maintenance} runs (pid ${current.pid}); try again when it finishes` : `ALP daemon already running (pid ${current.pid})`);
208
246
  const again = await readFile(file, "utf8").catch(() => void 0);
209
- if (again === void 0 || JSON.stringify(current) === again || !lockAlive(JSON.parse(again))) await unlink(file).catch(() => {
247
+ let parsed;
248
+ try {
249
+ parsed = again === void 0 ? void 0 : JSON.parse(again);
250
+ } catch {
251
+ throw new Error(`ALP daemon lock ${file} cannot be read: another start may be writing it. If no alpd or alp command is starting, remove it and try again`);
252
+ }
253
+ if (again === void 0 || JSON.stringify(current) === again || !lockAlive(parsed)) await unlink(file).catch(() => {
210
254
  });
211
255
  }
212
256
  }
@@ -377,10 +421,18 @@ async function withDaemonLifecycle(home, action, run, { joinStart = false, signa
377
421
  });
378
422
  }
379
423
  }
424
+ var DAEMON_START_TIMEOUT_MS = 6e4;
425
+ var DAEMON_START_TIMEOUT_MAX_MS = 36e5;
426
+ function daemonStartTimeoutMs(env = process.env) {
427
+ const raw = env.ALP_DAEMON_START_TIMEOUT_MS?.trim();
428
+ if (!raw || !/^[0-9]+$/.test(raw)) return DAEMON_START_TIMEOUT_MS;
429
+ const value = Number(raw);
430
+ return value > 0 && value <= DAEMON_START_TIMEOUT_MAX_MS ? value : DAEMON_START_TIMEOUT_MS;
431
+ }
380
432
  async function ensureDaemon({ home = alpHome(), entry = (
381
433
  /** @type {string | undefined} */
382
434
  void 0
383
- ), env = process.env, execPath = process.execPath, timeoutMs = 15e3, lifecycleLocked = false, signal = (
435
+ ), env = process.env, execPath = process.execPath, timeoutMs = daemonStartTimeoutMs(env), lifecycleLocked = false, signal = (
384
436
  /** @type {AbortSignal | undefined} */
385
437
  void 0
386
438
  ) } = {}) {
@@ -400,8 +452,10 @@ async function ensureDaemon({ home = alpHome(), entry = (
400
452
  signal?.throwIfAborted();
401
453
  await new Promise((resolve, reject) => {
402
454
  const launch = entryCommand(entry, "daemon", ["--detach", `--startup-timeout=${timeoutMs}`], execPath);
455
+ const launchEnv = { ...env, ALP_HOME: home, ELECTRON_RUN_AS_NODE: "1" };
456
+ if (isNativeDaemonName(launch.command)) delete launchEnv.BUN_BE_BUN;
403
457
  const launcher = spawn(launch.command, launch.args, {
404
- env: { ...env, ALP_HOME: home, ELECTRON_RUN_AS_NODE: "1" },
458
+ env: launchEnv,
405
459
  stdio: ["ignore", "ignore", "pipe"],
406
460
  windowsHide: true
407
461
  });
@@ -477,26 +531,27 @@ async function distributionRoots() {
477
531
  roots.push(process.cwd());
478
532
  return [...new Set(roots)];
479
533
  }
480
- async function discoverIntegration(name = "web", options = {}) {
534
+ async function discoverIntegration(name = "dashboard", options = {}) {
481
535
  assertIntegrationName(name);
482
- if (name === "web") return void 0;
536
+ if (name === "dashboard" || name === "web") return void 0;
537
+ const { env = process.env, binDirectories = BIN_DIRECTORIES, roots } = options;
483
538
  const envCandidates = [
484
- process.env[`ALP_${name.toUpperCase()}_INTEGRATION`],
485
- name === "paseo" ? process.env.ALP_WEB_INTEGRATION : void 0,
486
- process.env.ALP_INTEGRATION_ENTRY
539
+ env[`ALP_${name.toUpperCase()}_INTEGRATION`],
540
+ name === "paseo" ? env.ALP_WEB_INTEGRATION : void 0,
541
+ env.ALP_INTEGRATION_ENTRY
487
542
  ].filter(Boolean);
488
543
  for (const candidate of envCandidates) if (await isFile(candidate)) return candidate;
489
544
  const home = options?.home ? path.resolve(options.home) : alpHome();
490
545
  const fromHome = await integrationCandidateFromHome(home, name);
491
546
  if (fromHome) return fromHome;
492
- for (const root of await distributionRoots()) {
547
+ for (const root of roots ?? await distributionRoots()) {
493
548
  for (const descriptorPath of [path.join(root, "integrations", `${name}.json`), path.join(root, "integrations", name, "integration.json")]) {
494
549
  const entry = await readIntegrationDescriptor(descriptorPath, [root]);
495
550
  if (entry) return entry;
496
551
  }
497
552
  }
498
553
  const binary = integrationBinaryName(name);
499
- for (const directory of [...(process.env.PATH ?? "").split(path.delimiter).filter(Boolean), ...BIN_DIRECTORIES]) {
554
+ for (const directory of [...(env.PATH ?? "").split(path.delimiter).filter(Boolean), ...binDirectories]) {
500
555
  const candidate = await realpath(path.join(directory, binary)).catch(() => void 0);
501
556
  if (candidate && await isFile(candidate)) return candidate;
502
557
  }
@@ -513,10 +568,10 @@ function integrationAlive(lock) {
513
568
  }
514
569
  function integrationText(name, home) {
515
570
  const logs = path.join(home, "logs", "integrations");
516
- if (name === "web") return {
517
- what: "alp web",
518
- log: path.join(logs, "alp-web.log"),
519
- missing: "alp web runs the alp-web service of the ALP CLI, which is started with its entry (packages/cli/dist/alp-web.js); run `alp web`"
571
+ if (name === "dashboard") return {
572
+ what: "alp dashboard",
573
+ log: path.join(logs, "alp-dashboard.log"),
574
+ missing: "alp dashboard runs the alp-dashboard service of the ALP CLI, which is started with its entry (packages/cli/dist/alp-dashboard.js); run `alp dashboard`"
520
575
  };
521
576
  if (name === "paseo") return {
522
577
  what: "The Paseo integration",
@@ -529,9 +584,9 @@ function integrationText(name, home) {
529
584
  missing: `ALP integration ${name} is not installed: no ALP_${name.toUpperCase()}_INTEGRATION, descriptor <home>/integrations/${name}.json or alp-${name}-integration binary was found.`
530
585
  };
531
586
  }
532
- async function startIntegration(nameOrOptions = "web") {
587
+ async function startIntegration(nameOrOptions = "dashboard") {
533
588
  const options = typeof nameOrOptions === "string" ? { name: nameOrOptions } : nameOrOptions ?? {};
534
- const name = assertIntegrationName(options.name ?? "web");
589
+ const name = assertIntegrationName(options.name ?? "dashboard");
535
590
  if (options.entry !== void 0 && (typeof options.entry !== "string" || !options.entry)) throw new TypeError("startIntegration entry must be a non-empty path");
536
591
  const args = options.args ?? [];
537
592
  if (!Array.isArray(args) || !args.every((arg) => typeof arg === "string")) throw new TypeError("startIntegration args must be a list of strings");
@@ -544,13 +599,13 @@ async function startIntegration(nameOrOptions = "web") {
544
599
  const lockPath = pathMod.join(home, "integrations", `${name}.lock`);
545
600
  const webPath = pathMod.join(home, `${name}.json`);
546
601
  const started = explicit ? ` (entry ${explicit})` : "";
547
- if (name === "web") {
602
+ if (name === "dashboard") {
548
603
  let settings = {};
549
604
  try {
550
605
  settings = JSON.parse(await fs.readFile(pathMod.join(home, "settings.json"), "utf8"));
551
606
  } catch {
552
607
  }
553
- if (settings?.web?.enabled === false) throw new Error('alp web is disabled by settings ("web.enabled": false).');
608
+ if (dashboardSettings(settings).enabled === false) throw new Error('alp dashboard is disabled by settings ("dashboard.enabled": false).');
554
609
  }
555
610
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
556
611
  const readLock2 = async () => {
@@ -575,7 +630,7 @@ async function startIntegration(nameOrOptions = "web") {
575
630
  const info = await readWeb();
576
631
  if (info && info.pid === lock2.pid) return lock2;
577
632
  }
578
- if (name === "web" && webStartupFailed()) throw new Error(`${text.what}${started} failed to start; see ${text.log}`);
633
+ if (name === "dashboard" && webStartupFailed()) throw new Error(`${text.what}${started} failed to start; see ${text.log}`);
579
634
  await sleep(100);
580
635
  }
581
636
  const lock = await readLock2();
@@ -591,7 +646,7 @@ async function startIntegration(nameOrOptions = "web") {
591
646
  const entry = explicit ?? await discoverIntegration(name, { home });
592
647
  if (!entry) throw new Error(text.missing);
593
648
  const { spawn: spawn2 } = await import("node:child_process");
594
- const launch = name === "web" ? entryCommand(entry, "web", ["--service", ...args]) : entryCommand(entry, "web", ["--service", ...args], void 0, { scriptOnly: true });
649
+ const launch = name === "dashboard" ? entryCommand(entry, "dashboard", ["--service", ...args]) : entryCommand(entry, "dashboard", ["--service", ...args], void 0, { scriptOnly: true });
595
650
  const child = spawn2(launch.command, launch.args, { stdio: "ignore", detached: true, env: { ...process.env, ALP_HOME: home } });
596
651
  let spawnError = null;
597
652
  child.on("error", (error) => {
@@ -613,6 +668,7 @@ export {
613
668
  AlpClient,
614
669
  AlpRpcError,
615
670
  CLOSE_CODE,
671
+ DAEMON_START_TIMEOUT_MS,
616
672
  MAX_FRAME,
617
673
  PROTOCOL_VERSION,
618
674
  _setBootIdForTest,
@@ -629,6 +685,7 @@ export {
629
685
  createSocketTransport2 as createSocketTransport,
630
686
  createWebSocketTransport,
631
687
  daemonPaths,
688
+ daemonStartTimeoutMs,
632
689
  discoverIntegration,
633
690
  encodeFrame,
634
691
  ensureDaemon,
package/dist/render.js CHANGED
@@ -75,6 +75,9 @@ function renderLog(rootId, entries) {
75
75
  case "skill":
76
76
  text = Array.isArray(entry.roles) ? `\u2726 ${entry.agent} saved skill ${entry.name} for ${entry.roles.join(", ")}` : `\u2726 ${entry.agent} uses skill ${entry.skill}${entry.via === "skill" ? " (Skill tool)" : ""}`;
77
77
  break;
78
+ case "skill-resource":
79
+ text = `\u2726 ${entry.agent} ${entry.action === "run" ? "runs" : "reads"} ${entry.skill}/${entry.resource}`;
80
+ break;
78
81
  case "compacted":
79
82
  text = entry.failed ? `\u2717 ${entry.agent}'s context could not be compacted${entry.error ? `: ${entry.error}` : ""}` : `\u25D1 ${entry.agent}'s context compacted${entry.preTokens !== void 0 ? ` from ${tokens(entry.preTokens)}` : ""}${entry.postTokens !== void 0 ? ` to ${tokens(entry.postTokens)}` : ""}${entry.trigger === "manual" ? " on request" : ""}`;
80
83
  break;
package/dist/service.d.ts CHANGED
@@ -32,14 +32,14 @@ export function serviceFor({ home, env, platform, uid }: {
32
32
  ignore: boolean;
33
33
  })[][];
34
34
  } | undefined;
35
- /** The service definition that runs `entry` (alpd.js with `execPath`, or an `alp` command) for `home`. */
35
+ /** The service definition that runs `entry` (alpd.js with `execPath`, the native alpd, or an `alp` command) for `home`. */
36
36
  export function serviceDefinition(service: any, { home, entry, execPath, env }: {
37
37
  home: any;
38
38
  entry: any;
39
39
  execPath?: string | undefined;
40
40
  env?: NodeJS.ProcessEnv | undefined;
41
41
  }): string;
42
- /** The program an installed definition runs: [node, alpd.js], or undefined when it is not installed. */
42
+ /** The program an installed definition runs: [node, alpd.js] or [alpd, --service] (native, t-81b0.9), or undefined when it is not installed. */
43
43
  export function installedProgram(service: any): Promise<any[] | undefined>;
44
44
  /** Writes the definition and loads it, which starts alpd. */
45
45
  export function installService(service: any, options: any, run?: typeof runCommand): Promise<void>;
package/dist/setup.d.ts CHANGED
@@ -1,2 +1,8 @@
1
- /** Write Phở and Cafe's agent profiles into a project's .alp/settings.json, without installing software or calling models. */
1
+ /**
2
+ * Write Phở and Cafe's agent profiles into a project's .alp/settings.json, without installing software or calling models.
3
+ * Only entries ALP wrote are rewritten: the template's defaults (templateDefaults) and setup's own earlier output
4
+ * (its record in .alp/state/setup-profiles.json, or for a project without one, what setup writes with its default models). A profile
5
+ * list the user wrote, or one a team override of Phở or Cafe pins in its team.json, is kept and named. Other teams are
6
+ * left alone and named with the settings keys to edit: their team.json carries their author's model choices.
7
+ */
2
8
  export function setup(args: any, home: any): Promise<void>;
package/dist/setup.js CHANGED
@@ -1,11 +1,11 @@
1
1
  // packages/client/src/setup.js
2
- import { copyFile, readFile, writeFile } from "node:fs/promises";
2
+ import { copyFile, mkdir, 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 { catalogModels } from "@anhlp/alp-core/models";
7
- import { fitEffort, modelEfforts } from "@anhlp/alp-core/profiles";
8
- import { resolveTeam } from "@anhlp/alp-core/teams";
6
+ import { catalogModels, useLiveModels } from "@anhlp/alp-core/models";
7
+ import { fitEffort, modelEfforts, profileDefaults, profileFingerprint, projectProfiles } from "@anhlp/alp-core/profiles";
8
+ import { BUILTIN_TEAMS, resolveTeam, teamSources } from "@anhlp/alp-core/teams";
9
9
  import { validateSettings } from "@anhlp/alp-core/validation";
10
10
  import { Cancelled, select, text } from "./prompt.js";
11
11
  var PROVIDERS = ["claude", "codex"];
@@ -20,6 +20,7 @@ var FLAGS = { main: "model", worker: "model", supervisor: "supervisor", oracle:
20
20
  var SEAT_LABEL = { main: "main", worker: "lead, reviewer", supervisor: "supervisor", oracle: "oracle" };
21
21
  var ANY_EFFORT = ["low", "medium", "high", "xhigh", "max"];
22
22
  async function setup(args, home) {
23
+ useLiveModels(catalogModels(home));
23
24
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: Object.fromEntries(
24
25
  ["runtime", "prefer", ...PROVIDERS.flatMap((provider) => Object.values(FLAGS).map((flag) => `${provider}-${flag}`))].map((name) => [name, { type: "string" }])
25
26
  ) });
@@ -45,16 +46,8 @@ async function setup(args, home) {
45
46
  if (!enabled.includes(provider) && values[`${provider}-${flag}`]) throw new Error(`--${provider}-${flag} is unavailable in ${runtime}-only mode`);
46
47
  }
47
48
  }
48
- const seats = {};
49
- for (const [seat, flag] of Object.entries(FLAGS)) {
50
- seats[seat] = (seat === "main" ? [prefer] : enabled).map((provider) => {
51
- const option = `${provider}-${flag}`;
52
- const [fallback, effort] = DEFAULTS[seat][provider];
53
- const model = nativeModel(values[option] ?? fallback, provider, `--${option}`);
54
- return { provider, model, effort: fitEffort(`${provider}:${model}`, effort) };
55
- });
56
- }
57
- const peers = enabled.map((provider) => `${provider}:*`);
49
+ const seats = seatsFor(enabled, prefer, values);
50
+ const peers = peersFor(enabled);
58
51
  const file = path.join(root, ".alp/settings.json");
59
52
  const settings = await readFile(file, "utf8").then((content) => {
60
53
  try {
@@ -70,10 +63,14 @@ async function setup(args, home) {
70
63
  for (const [seat, choices] of Object.entries(seats)) console.log(` ${SEAT_LABEL[seat]}: ${choices.map(describe).join(", ")}`);
71
64
  console.log(` peer: ${peers.join(", ")} (any model: whoever assigns a peer picks its model and effort for the task)`);
72
65
  };
66
+ if (settings) validateSettings(settings, file);
73
67
  console.log(`Profiles for Ph\u1EDF and Cafe in ${file}:`);
74
68
  show();
75
- const replaced = ["pho", "cafe"].filter((id) => (settings?.team ?? settings?.profile)?.[id]);
76
- if (replaced.length) console.log(`These replace the ${replaced.join(" and ")} profiles already in the file; a backup is kept in ${file}.bak.`);
69
+ const owners = await ownership(root, home, settings);
70
+ const replaced = BUILTIN_TEAMS.filter((id) => Object.keys(currentTeams(settings)?.[id] ?? {}).some((name) => owners.rewrites(id, name)));
71
+ if (replaced.length) console.log(`These replace the ${replaced.join(" and ")} profiles ALP or an earlier alp setup wrote; saving backs the file up to ${file}.bak first.`);
72
+ for (const line of owners.kept) console.log(line);
73
+ for (const line of owners.others) console.log(line);
77
74
  if (interactive) {
78
75
  for (; ; ) {
79
76
  const next2 = await select({ message: "Save these profiles?", initial: "save", choices: [
@@ -87,14 +84,14 @@ async function setup(args, home) {
87
84
  show();
88
85
  }
89
86
  }
90
- const profile = await profiles(root, home, seats, peers, settings);
91
- validateSettings({ ...settings ?? {}, team: { ...settings?.profile ?? {}, ...settings?.team ?? {}, ...profile } }, file);
87
+ validateSettings(merge(settings ?? {}, await profiles(root, home, seats, peers, settings), owners).next, file);
92
88
  if (!settings) await initProject(root, { library: home });
93
89
  else if (replaced.length) await copyFile(file, `${file}.bak`);
94
90
  const written = settings ?? JSON.parse(await readFile(file, "utf8"));
95
- const next = { ...written, team: { ...written.profile ?? {}, ...written.team ?? {}, ...profile } };
96
- delete next.profile;
91
+ const { next, record } = merge(written, await profiles(root, home, seats, peers, written), owners);
92
+ validateSettings(next, file);
97
93
  await writeFile(file, JSON.stringify(next, null, 2) + "\n");
94
+ await writeRecord(root, record, owners.newer);
98
95
  console.log("Setup saved. New sessions in this project use these profiles; edit the file to change one agent. Run alp doctor to check that each CLI is installed and logged in.");
99
96
  } catch (error) {
100
97
  if (!(error instanceof Cancelled)) throw error;
@@ -120,24 +117,152 @@ async function change(seats, home) {
120
117
  }) : efforts[0];
121
118
  seats[seat][at] = { provider: current.provider, model, ...effort ? { effort } : {} };
122
119
  }
120
+ function seatsFor(enabled, prefer, values = {}) {
121
+ const seats = {};
122
+ for (const [seat, flag] of Object.entries(FLAGS)) {
123
+ seats[seat] = (seat === "main" ? [prefer] : enabled).map((provider) => {
124
+ const option = `${provider}-${flag}`;
125
+ const [fallback, effort] = DEFAULTS[seat][provider];
126
+ const model = nativeModel(values[option] ?? fallback, provider, `--${option}`);
127
+ return { provider, model, effort: fitEffort(`${provider}:${model}`, effort) };
128
+ });
129
+ }
130
+ return seats;
131
+ }
132
+ var sameEntries = (a, b) => JSON.stringify(Object.entries(a ?? {}).sort()) === JSON.stringify(Object.entries(b ?? {}).sort());
133
+ var peersFor = (enabled) => enabled.map((provider) => `${provider}:*`);
134
+ var currentTeams = (settings) => settings && { ...settings.profile ?? {}, ...settings.team ?? {} };
135
+ function teamProfiles(team, seats, peers) {
136
+ const strings = (choices) => choices.map((choice) => typeof choice === "string" ? choice : describe(choice));
137
+ const agents = {};
138
+ for (const [name, member] of Object.entries(team.members)) {
139
+ if (name !== "oracle") agents[name] = strings(name === team.main ? seats.main : member.role === "peer" ? peers : seats.worker);
140
+ }
141
+ if (team.supervisor) agents[team.supervisor.agent] = strings(seats.supervisor);
142
+ if (team.members.oracle) agents.oracle = strings(seats.oracle);
143
+ return agents;
144
+ }
123
145
  async function profiles(root, home, seats, peers, settings) {
124
146
  const profile = {};
125
- for (const id of ["pho", "cafe"]) {
147
+ for (const id of BUILTIN_TEAMS) {
126
148
  const team = await resolveTeam(root, id, { library: home });
127
149
  const agents = {};
128
- const seat = (name, choices) => {
129
- const old = (settings?.team ?? settings?.profile)?.[id]?.[name];
130
- agents[name] = { profiles: choices.map((choice) => typeof choice === "string" ? choice : describe(choice)), autocompact: old?.autocompact ?? "auto", ...old?.commands ? { commands: old.commands } : {} };
131
- };
132
- for (const [name, member] of Object.entries(team.members)) {
133
- if (name !== "oracle") seat(name, name === team.main ? seats.main : member.role === "peer" ? peers : seats.worker);
150
+ for (const [name, list] of Object.entries(teamProfiles(team, seats, peers))) {
151
+ const old = currentTeams(settings)?.[id]?.[name];
152
+ agents[name] = { profiles: list, autocompact: old?.autocompact ?? "auto", ...old?.commands ? { commands: old.commands } : {} };
134
153
  }
135
- if (team.supervisor) seat(team.supervisor.agent, seats.supervisor);
136
- if (team.members.oracle) seat("oracle", seats.oracle);
137
154
  profile[id] = agents;
138
155
  }
139
156
  return profile;
140
157
  }
158
+ var RECORD_VERSION = 1;
159
+ var recordFile = (root) => path.join(root, ".alp", "state", "setup-profiles.json");
160
+ async function readRecord(root) {
161
+ let value;
162
+ try {
163
+ value = JSON.parse(await readFile(recordFile(root), "utf8"));
164
+ } catch {
165
+ return { teams: {}, newer: false };
166
+ }
167
+ if (Number.isSafeInteger(value?.version) && value.version > RECORD_VERSION) return { teams: {}, newer: true };
168
+ const teams = value?.version === RECORD_VERSION && value.teams && typeof value.teams === "object" && !Array.isArray(value.teams) ? value.teams : {};
169
+ return { newer: false, teams: Object.fromEntries(Object.entries(teams).filter(([, agents]) => agents && typeof agents === "object" && !Array.isArray(agents)).map(([id, agents]) => [id, Object.fromEntries(Object.entries(agents).filter(([, hash]) => typeof hash === "string" && /^[a-f0-9]{64}$/.test(hash)))])) };
170
+ }
171
+ async function writeRecord(root, teams, newer) {
172
+ if (newer) return;
173
+ const directory = path.dirname(recordFile(root));
174
+ try {
175
+ await mkdir(directory, { recursive: true });
176
+ await writeFile(path.join(directory, ".gitignore"), "*\n", { flag: "wx" }).catch((error) => {
177
+ if (error.code !== "EEXIST") throw error;
178
+ });
179
+ await writeFile(recordFile(root), JSON.stringify({ version: RECORD_VERSION, teams }, null, 2) + "\n");
180
+ } catch (error) {
181
+ console.log(`Could not save ${recordFile(root)} (${error.message}); the next alp setup recognizes these profiles by setup's defaults instead.`);
182
+ }
183
+ }
184
+ async function ownership(root, home, existing) {
185
+ const { teams: record, newer } = await readRecord(root);
186
+ const initial = existing ? void 0 : await projectProfiles({ root, library: home });
187
+ const settings = existing ?? { team: initial, templateDefaults: profileDefaults(initial) };
188
+ const teams = currentTeams(settings) ?? {};
189
+ const file = path.join(root, ".alp/settings.json");
190
+ const legacy = {};
191
+ const pinned = {};
192
+ for (const id of BUILTIN_TEAMS) {
193
+ const team = await resolveTeam(root, id, { library: home });
194
+ const builtin = await resolveTeam(void 0, id, { library: "" });
195
+ legacy[id] = {};
196
+ for (const runtime of [...PROVIDERS, "mix"]) {
197
+ for (const prefer of runtime === "mix" ? PROVIDERS : [runtime]) {
198
+ const enabled = runtime === "mix" ? [prefer, ...PROVIDERS.filter((provider) => provider !== prefer)] : [runtime];
199
+ for (const [name, list] of Object.entries(teamProfiles(team, seatsFor(enabled, prefer), peersFor(enabled)))) {
200
+ (legacy[id][name] ??= []).push(profileFingerprint({ profiles: list }, name));
201
+ }
202
+ }
203
+ }
204
+ pinned[id] = {};
205
+ if (team.source !== "builtin") {
206
+ const choice = (own, base) => {
207
+ const parts = [own?.model && own.model !== base?.model ? own.model : void 0, own?.thinking && own.thinking !== base?.thinking ? `effort ${own.thinking}` : void 0].filter(Boolean);
208
+ return parts.length ? parts.join(", ") : void 0;
209
+ };
210
+ for (const [name, member] of Object.entries(team.members)) {
211
+ const set = name === "oracle" ? void 0 : choice(member, builtin.members[name]);
212
+ if (set) pinned[id][name] = set;
213
+ }
214
+ if (team.supervisor) {
215
+ const set = choice(team.supervisor, builtin.supervisor && builtin.supervisor.agent === team.supervisor.agent ? builtin.supervisor : void 0);
216
+ if (set) pinned[id][team.supervisor.agent] = set;
217
+ }
218
+ if (team.members.oracle && (team.oracleModels && JSON.stringify(team.oracleModels) !== JSON.stringify(builtin.oracleModels) || team.oracleThinking && sameEntries(team.oracleThinking, builtin.oracleThinking) === false)) {
219
+ pinned[id].oracle = [team.oracleModels?.join(", "), team.oracleThinking ? `efforts ${Object.entries(team.oracleThinking).map(([lens, effort]) => `${lens} ${effort}`).join(", ")}` : void 0].filter(Boolean).join("; ");
220
+ }
221
+ }
222
+ }
223
+ const rewrites = (id, name) => {
224
+ const config = teams[id]?.[name];
225
+ if (!config) return true;
226
+ const fingerprint = profileFingerprint(config, name);
227
+ if (record[id]?.[name] === fingerprint || legacy[id]?.[name]?.includes(fingerprint)) return true;
228
+ return settings?.templateDefaults?.[id]?.[name] === fingerprint && !pinned[id]?.[name];
229
+ };
230
+ const kept = [];
231
+ for (const id of BUILTIN_TEAMS) {
232
+ for (const [name, config] of Object.entries(teams[id] ?? {})) {
233
+ if (rewrites(id, name)) continue;
234
+ const list = (config.profiles ?? []).map((profile) => typeof profile === "string" ? profile : describe(profile)).join(", ");
235
+ kept.push(pinned[id]?.[name] && settings?.templateDefaults?.[id]?.[name] === profileFingerprint(config, name) ? `Kept team.${id}.${name}.profiles (${list}): the ${id} team's team.json sets it (${pinned[id][name]}). Delete the entry from the file and run alp setup again to replace it.` : record[id]?.[name] ? `Kept team.${id}.${name}.profiles (${list}): changed since alp setup wrote it, so it is kept as yours. Delete the entry from the file and run alp setup again to replace it.` : `Kept team.${id}.${name}.profiles (${list}): ALP cannot tell whether an earlier alp setup or you wrote it (it is none of setup's defaults, and no setup record names it), so it is kept as yours. Delete the entry from the file and run alp setup again to replace it.`);
236
+ }
237
+ }
238
+ const others = [];
239
+ for (const [id, found] of await teamSources(root, { library: home })) {
240
+ if (BUILTIN_TEAMS.includes(id)) continue;
241
+ const team = await resolveTeam(root, id, { library: home }).catch(() => void 0);
242
+ const agents = team ? [...Object.keys(team.members).filter((name) => name !== "oracle"), ...team.supervisor ? [team.supervisor.agent] : [], ...team.members.oracle ? ["oracle"] : []] : [];
243
+ others.push(`Team ${id} (${found.source}) is not Ph\u1EDF or Cafe, so alp setup leaves its profiles as they are: its team.json chooses its models. To change them, edit team.${id}.<agent>.profiles in ${file}${agents.length ? ` (agents: ${agents.join(", ")})` : ""}.`);
244
+ }
245
+ return { rewrites, kept, others, record, newer };
246
+ }
247
+ function merge(written, profile, owners) {
248
+ const next = { ...written, team: currentTeams(written) };
249
+ delete next.profile;
250
+ const record = structuredClone(owners.record);
251
+ for (const [id, agents] of Object.entries(profile)) {
252
+ const team = { ...next.team[id] ?? {} };
253
+ for (const [name, config] of Object.entries(agents)) {
254
+ if (!owners.rewrites(id, name)) {
255
+ if (record[id]) delete record[id][name];
256
+ continue;
257
+ }
258
+ team[name] = config;
259
+ (record[id] ??= {})[name] = profileFingerprint(config, name);
260
+ }
261
+ next.team[id] = team;
262
+ if (record[id] && !Object.keys(record[id]).length) delete record[id];
263
+ }
264
+ return { next, record };
265
+ }
141
266
  function nativeModel(id, provider, where) {
142
267
  const model = id.startsWith(`${provider}:`) ? id.slice(provider.length + 1) : id;
143
268
  if (!model || /\s/.test(model) || /^(codex|claude):/.test(model) || model.includes(":") && !id.startsWith(`${provider}:`)) throw new Error(`${where} expects a ${provider} model, got '${id}'`);
package/dist/supervise.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // packages/client/src/supervise.js
2
2
  import { mkdir, unlink, writeFile, stat } from "node:fs/promises";
3
3
  import path from "node:path";
4
- import { ensureDaemon, lockAlive, readLock, withDaemonLifecycle } from "./index.js";
4
+ import { daemonStartTimeoutMs, ensureDaemon, lockAlive, readLock, withDaemonLifecycle } from "./index.js";
5
5
  import { installedProgram, serviceFor, startService } from "./service.js";
6
6
  var holdFile = (home) => path.join(home, "state", "alpd.held");
7
7
  async function holdDaemon(home, by = "alp daemon stop") {
@@ -25,7 +25,7 @@ async function whenReady(home, timeoutMs, signal) {
25
25
  }
26
26
  throw new Error(`alpd did not become ready within ${timeoutMs / 1e3} s; see ${path.join(home, "logs")}`);
27
27
  }
28
- async function startDaemon({ home, entry, env = process.env, timeoutMs = 15e3, automatic = false, signal }) {
28
+ async function startDaemon({ home, entry, env = process.env, timeoutMs = daemonStartTimeoutMs(env), automatic = false, signal }) {
29
29
  return withDaemonLifecycle(home, "start", async () => {
30
30
  signal?.throwIfAborted();
31
31
  if (automatic) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anhlp/alp-client",
3
- "version": "0.0.1-beta.7",
3
+ "version": "0.0.1-beta.9",
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.7",
154
- "@anhlp/alp-protocol": "0.0.1-beta.7"
153
+ "@anhlp/alp-core": "0.0.1-beta.9",
154
+ "@anhlp/alp-protocol": "0.0.1-beta.9"
155
155
  },
156
156
  "scripts": {
157
157
  "build": "node ../../scripts/build-workspace.mjs client",
package/src/acp-probe.js CHANGED
@@ -7,12 +7,17 @@ import { stdioSession } from './mcp-probe.js';
7
7
  * it also opens a session in `cwd`, as Paseo does, to read the models and modes the agent
8
8
  * offers (ALPD §65); an agent that offers none leaves them out.
9
9
  * @param {{ command: string, args?: string[], env?: Record<string, string>, label?: string, id?: string }} provider
10
- * @param {{ cwd?: string, timeoutMs?: number, discover?: boolean }} [options]
10
+ * @param {{ cwd?: string, timeoutMs?: number, discover?: boolean, signal?: AbortSignal }} [options]
11
11
  * @returns {Promise<{ protocolVersion: number, agent?: { name?: string, title?: string, version?: string }, loadSession: boolean, mcpHttp: boolean, authMethods: string[],
12
12
  * models?: Array<{ id: string, label: string, description?: string }>, currentModel?: string, modes?: Array<{ id: string, label: string, description?: string }>, currentMode?: string }>}
13
13
  */
14
- export async function probeAcp(provider, { cwd, timeoutMs = 20_000, discover = false } = {}) {
14
+ export async function probeAcp(provider, { cwd, timeoutMs = 20_000, discover = false, signal } = {}) {
15
+ signal?.throwIfAborted();
15
16
  const session = stdioSession({ command: provider.command, args: provider.args ?? [], env: provider.env ?? {} }, cwd, timeoutMs);
17
+ let closing;
18
+ const abort = () => { closing ??= session.close(); };
19
+ signal?.addEventListener('abort', abort, { once: true });
20
+ if (signal?.aborted) abort();
16
21
  try {
17
22
  const result = await session.request('initialize', {
18
23
  protocolVersion: 1,
@@ -41,6 +46,8 @@ export async function probeAcp(provider, { cwd, timeoutMs = 20_000, discover = f
41
46
  authMethods: (result.authMethods ?? []).map(method => method?.name ?? method?.id).filter(Boolean),
42
47
  };
43
48
  } finally {
44
- await session.close();
49
+ signal?.removeEventListener('abort', abort);
50
+ await (closing ?? session.close());
51
+ signal?.throwIfAborted();
45
52
  }
46
53
  }
@@ -64,7 +64,7 @@ function runCommand(command, args, { env = process.env, cwd, timeoutMs = 20_000
64
64
 
65
65
  /**
66
66
  * Probes Antigravity CLI for version, status and available models.
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.
67
+ * @param {{ command?: string, args?: string[], env?: Record<string, string>, label?: string, id?: string}} [provider]
68
68
  * @param {{ cwd?: string, timeoutMs?: number }} [options]
69
69
  */
70
70
  export async function probeAntigravity(provider = {}, { cwd, timeoutMs = 20_000 } = {}) {