@anhlp/alp-client 0.0.0-stage → 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.
Files changed (78) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +7 -0
  3. package/README.md +45 -2
  4. package/dist/acp-probe.d.ts +45 -0
  5. package/dist/acp-probe.js +46 -0
  6. package/dist/antigravity-probe.d.ts +33 -0
  7. package/dist/antigravity-probe.js +101 -0
  8. package/dist/command.d.ts +5 -0
  9. package/dist/command.js +35 -0
  10. package/dist/doctor.d.ts +21 -0
  11. package/dist/doctor.js +850 -0
  12. package/dist/index.d.ts +216 -0
  13. package/dist/index.js +702 -0
  14. package/dist/integration-lock.d.ts +37 -0
  15. package/dist/integration-lock.js +199 -0
  16. package/dist/ipc.d.ts +42 -0
  17. package/dist/ipc.js +69 -0
  18. package/dist/library-test.d.ts +94 -0
  19. package/dist/library-test.js +37 -0
  20. package/dist/mcp-probe.d.ts +24 -0
  21. package/dist/mcp-probe.js +147 -0
  22. package/dist/portable.d.ts +20 -0
  23. package/dist/portable.js +36 -0
  24. package/dist/prompt.d.ts +32 -0
  25. package/dist/prompt.js +59 -0
  26. package/dist/render.d.ts +6 -0
  27. package/dist/render.js +123 -0
  28. package/dist/rpc/client.d.ts +82 -0
  29. package/dist/rpc/client.js +292 -0
  30. package/dist/rpc/errors.d.ts +42 -0
  31. package/dist/rpc/errors.js +34 -0
  32. package/dist/rpc/framing.d.ts +21 -0
  33. package/dist/rpc/framing.js +57 -0
  34. package/dist/rpc/handshake.d.ts +24 -0
  35. package/dist/rpc/handshake.js +10 -0
  36. package/dist/rpc/reconnect.d.ts +97 -0
  37. package/dist/rpc/reconnect.js +227 -0
  38. package/dist/rpc/registry.d.ts +227 -0
  39. package/dist/rpc/registry.js +223 -0
  40. package/dist/rpc/terminal-directory.d.ts +24 -0
  41. package/dist/rpc/terminal-directory.js +70 -0
  42. package/dist/rpc/timers.d.ts +11 -0
  43. package/dist/rpc/timers.js +11 -0
  44. package/dist/service.d.ts +50 -0
  45. package/dist/service.js +145 -0
  46. package/dist/setup.d.ts +8 -0
  47. package/dist/setup.js +273 -0
  48. package/dist/supervise.d.ts +14 -0
  49. package/dist/supervise.js +91 -0
  50. package/dist/websocket.d.ts +51 -0
  51. package/dist/websocket.js +190 -0
  52. package/package.json +174 -4
  53. package/src/acp-probe.js +53 -0
  54. package/src/antigravity-probe.js +113 -0
  55. package/src/command.js +20 -0
  56. package/src/doctor.d.ts +21 -0
  57. package/src/doctor.js +912 -0
  58. package/src/index.js +813 -0
  59. package/src/integration-lock.js +203 -0
  60. package/src/ipc.js +92 -0
  61. package/src/library-test.js +41 -0
  62. package/src/mcp-probe.js +118 -0
  63. package/src/portable.js +30 -0
  64. package/src/prompt.js +64 -0
  65. package/src/render.js +139 -0
  66. package/src/rpc/client.js +296 -0
  67. package/src/rpc/errors.js +54 -0
  68. package/src/rpc/framing.js +61 -0
  69. package/src/rpc/handshake.js +21 -0
  70. package/src/rpc/reconnect.js +226 -0
  71. package/src/rpc/registry.js +229 -0
  72. package/src/rpc/terminal-directory.js +61 -0
  73. package/src/rpc/timers.js +16 -0
  74. package/src/service.js +158 -0
  75. package/src/setup.js +316 -0
  76. package/src/supervise.d.ts +14 -0
  77. package/src/supervise.js +97 -0
  78. package/src/websocket.js +259 -0
@@ -0,0 +1,145 @@
1
+ // packages/client/src/service.js
2
+ import { createHash } from "node:crypto";
3
+ import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { runCommand } from "./command.js";
7
+ import { entryCommand, stablePath } from "@anhlp/alp-core/packaged";
8
+ var CARRIED = ["ALP_RUN_LOG_DIR", "ALP_CODEX_BIN", "ALP_CLAUDE_BIN", "ALP_ANTIGRAVITY_BIN", "ALP_GH_BIN"];
9
+ var escapeXml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
10
+ var quoteUnit = (value) => `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
11
+ function serviceFor({ home, env = process.env, platform = process.platform, uid = process.getuid?.() ?? 0 }) {
12
+ const custom = path.resolve(home) !== path.join(os.homedir(), ".alp");
13
+ const suffix = custom ? createHash("sha256").update(path.resolve(home)).digest("hex").slice(0, 8) : "";
14
+ if (platform === "darwin") {
15
+ const label = `com.alp.alpd${suffix ? `.${suffix}` : ""}`;
16
+ const directory = env.ALP_SERVICE_DIR || path.join(os.homedir(), "Library", "LaunchAgents");
17
+ const launchctl = env.ALP_LAUNCHCTL || "launchctl";
18
+ const target = `gui/${uid}/${label}`;
19
+ const file = path.join(directory, `${label}.plist`);
20
+ return {
21
+ kind: "launchd",
22
+ name: label,
23
+ file,
24
+ install: [[launchctl, ["bootout", target], { ignore: true }], [launchctl, ["bootstrap", `gui/${uid}`, file]]],
25
+ start: [[launchctl, ["kickstart", target]]],
26
+ uninstall: [[launchctl, ["bootout", target], { ignore: true }]]
27
+ };
28
+ }
29
+ if (platform === "linux") {
30
+ const name = `alpd${suffix ? `-${suffix}` : ""}`;
31
+ const directory = env.ALP_SERVICE_DIR || path.join(env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "systemd", "user");
32
+ const systemctl = env.ALP_SYSTEMCTL || "systemctl";
33
+ return {
34
+ kind: "systemd",
35
+ name,
36
+ file: path.join(directory, `${name}.service`),
37
+ install: [[systemctl, ["--user", "daemon-reload"]], [systemctl, ["--user", "enable", "--now", `${name}.service`]]],
38
+ start: [[systemctl, ["--user", "start", `${name}.service`]]],
39
+ uninstall: [[systemctl, ["--user", "disable", "--now", `${name}.service`], { ignore: true }]],
40
+ afterUninstall: [[systemctl, ["--user", "daemon-reload"], { ignore: true }]]
41
+ };
42
+ }
43
+ return void 0;
44
+ }
45
+ function serviceDefinition(service, { home, entry, execPath = process.execPath, env = process.env }) {
46
+ const variables = { ALP_HOME: path.resolve(home), PATH: env.PATH ?? "" };
47
+ for (const name of CARRIED) if (env[name]) variables[name] = env[name];
48
+ const launch = entryCommand(stablePath(entry), "daemon", ["--service"], stablePath(execPath));
49
+ const program = [launch.command, ...launch.args];
50
+ const fatal = path.join(path.resolve(home), "logs", "alpd.service.log");
51
+ if (service.kind === "launchd") {
52
+ return `<?xml version="1.0" encoding="UTF-8"?>
53
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
54
+ <plist version="1.0">
55
+ <dict>
56
+ <key>Label</key>
57
+ <string>${escapeXml(service.name)}</string>
58
+ <key>ProgramArguments</key>
59
+ <array>
60
+ ${program.map((arg) => ` <string>${escapeXml(arg)}</string>`).join("\n")}
61
+ </array>
62
+ <key>EnvironmentVariables</key>
63
+ <dict>
64
+ ${Object.entries(variables).map(([key, value]) => ` <key>${escapeXml(key)}</key>
65
+ <string>${escapeXml(value)}</string>`).join("\n")}
66
+ </dict>
67
+ <key>RunAtLoad</key>
68
+ <true/>
69
+ <key>KeepAlive</key>
70
+ <dict>
71
+ <key>Crashed</key>
72
+ <true/>
73
+ <key>SuccessfulExit</key>
74
+ <false/>
75
+ </dict>
76
+ <key>ThrottleInterval</key>
77
+ <integer>10</integer>
78
+ <key>ProcessType</key>
79
+ <string>Background</string>
80
+ <key>StandardOutPath</key>
81
+ <string>${escapeXml(fatal)}</string>
82
+ <key>StandardErrorPath</key>
83
+ <string>${escapeXml(fatal)}</string>
84
+ </dict>
85
+ </plist>
86
+ `;
87
+ }
88
+ return `[Unit]
89
+ Description=ALP daemon (alpd) for ${path.resolve(home)}
90
+
91
+ [Service]
92
+ ExecStart=${program.map(quoteUnit).join(" ")}
93
+ ${Object.entries(variables).map(([key, value]) => `Environment=${quoteUnit(`${key}=${value}`)}`).join("\n")}
94
+ Restart=on-failure
95
+ RestartSec=10
96
+ StandardOutput=append:${fatal}
97
+ StandardError=append:${fatal}
98
+
99
+ [Install]
100
+ WantedBy=default.target
101
+ `;
102
+ }
103
+ async function installedProgram(service) {
104
+ const text = await readFile(service.file, "utf8").catch(() => void 0);
105
+ if (text === void 0) return void 0;
106
+ if (service.kind === "launchd") {
107
+ const array = text.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/)?.[1] ?? "";
108
+ const unescape = (value) => value.replace(/&quot;/g, '"').replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&amp;/g, "&");
109
+ return [...array.matchAll(/<string>([\s\S]*?)<\/string>/g)].map((match) => unescape(match[1])).slice(0, 2);
110
+ }
111
+ const line = text.match(/^ExecStart=(.*)$/m)?.[1] ?? "";
112
+ return [...line.matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((match) => match[1].replace(/\\(.)/g, "$1")).slice(0, 2);
113
+ }
114
+ async function runAll(steps, run) {
115
+ for (const [command, args, { ignore = false } = {}] of steps) {
116
+ const result = await run(command, args);
117
+ if (result.code !== 0 && !ignore) throw new Error(`${command} ${args.join(" ")} failed: ${(result.stderr || result.stdout).trim() || `exit ${result.code}`}`);
118
+ }
119
+ }
120
+ async function installService(service, options, run = runCommand) {
121
+ await mkdir(path.dirname(service.file), { recursive: true });
122
+ await mkdir(path.join(path.resolve(options.home), "logs"), { recursive: true, mode: 448 });
123
+ await writeFile(service.file, serviceDefinition(service, options), { mode: 420 });
124
+ await runAll(service.install, run);
125
+ }
126
+ async function startService(service, run = runCommand) {
127
+ await runAll(service.start, run);
128
+ }
129
+ async function uninstallService(service, run = runCommand) {
130
+ if (await installedProgram(service) === void 0) return false;
131
+ await runAll(service.uninstall, run);
132
+ await unlink(service.file).catch((error) => {
133
+ if (error.code !== "ENOENT") throw error;
134
+ });
135
+ await runAll(service.afterUninstall ?? [], run);
136
+ return true;
137
+ }
138
+ export {
139
+ installService,
140
+ installedProgram,
141
+ serviceDefinition,
142
+ serviceFor,
143
+ startService,
144
+ uninstallService
145
+ };
@@ -0,0 +1,8 @@
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
+ */
8
+ export function setup(args: any, home: any): Promise<void>;
package/dist/setup.js ADDED
@@ -0,0 +1,273 @@
1
+ // packages/client/src/setup.js
2
+ import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { parseArgs } from "node:util";
5
+ import { initProject } from "@anhlp/alp-core/init";
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
+ import { validateSettings } from "@anhlp/alp-core/validation";
10
+ import { Cancelled, select, text } from "./prompt.js";
11
+ var PROVIDERS = ["claude", "codex"];
12
+ var PROVIDER_LABEL = { claude: "Claude", codex: "Codex" };
13
+ var DEFAULTS = {
14
+ main: { claude: ["claude-opus-5-5", "high"], codex: ["gpt-6.1-sol", "high"] },
15
+ worker: { claude: ["claude-opus-5-5", "high"], codex: ["gpt-6.1-sol", "high"] },
16
+ supervisor: { claude: ["claude-sonnet-5", "medium"], codex: ["gpt-6-luna", "medium"] },
17
+ oracle: { claude: ["claude-fable-5-1", "high"], codex: ["gpt-6-astra", "high"] }
18
+ };
19
+ var FLAGS = { main: "model", worker: "model", supervisor: "supervisor", oracle: "oracle" };
20
+ var SEAT_LABEL = { main: "main", worker: "lead, reviewer", supervisor: "supervisor", oracle: "oracle" };
21
+ var ANY_EFFORT = ["low", "medium", "high", "xhigh", "max"];
22
+ async function setup(args, home) {
23
+ useLiveModels(catalogModels(home));
24
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: Object.fromEntries(
25
+ ["runtime", "prefer", ...PROVIDERS.flatMap((provider) => Object.values(FLAGS).map((flag) => `${provider}-${flag}`))].map((name) => [name, { type: "string" }])
26
+ ) });
27
+ if (positionals.length > 1) throw new Error("setup takes at most one directory");
28
+ const root = path.resolve(positionals[0] ?? process.cwd());
29
+ const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
30
+ try {
31
+ const runtime = values.runtime ?? (interactive ? await select({ message: "Runtime", initial: "mix", choices: [
32
+ { label: "Mix", value: "mix", hint: "Claude and Codex: main runs on one, the others can run on either" },
33
+ { label: "Codex only", value: "codex" },
34
+ { label: "Claude only", value: "claude" }
35
+ ] }) : void 0);
36
+ if (runtime === void 0) throw new Error("Pass --runtime codex, claude or mix when setup is not running in a terminal");
37
+ if (!["codex", "claude", "mix"].includes(runtime)) throw new Error("--runtime must be codex, claude or mix");
38
+ const prefer = values.prefer ?? (runtime !== "mix" ? runtime : interactive ? await select({ message: "Main runs on", initial: "claude", choices: [
39
+ { label: "Claude", value: "claude", hint: "Claude first for the others too" },
40
+ { label: "Codex", value: "codex", hint: "Codex first for the others too" }
41
+ ] }) : "claude");
42
+ if (!PROVIDERS.includes(prefer) || runtime !== "mix" && prefer !== runtime) throw new Error("--prefer must be an enabled runtime");
43
+ const enabled = runtime === "mix" ? [prefer, ...PROVIDERS.filter((provider) => provider !== prefer)] : [runtime];
44
+ for (const provider of PROVIDERS) {
45
+ for (const flag of Object.values(FLAGS)) {
46
+ if (!enabled.includes(provider) && values[`${provider}-${flag}`]) throw new Error(`--${provider}-${flag} is unavailable in ${runtime}-only mode`);
47
+ }
48
+ }
49
+ const seats = seatsFor(enabled, prefer, values);
50
+ const peers = peersFor(enabled);
51
+ const file = path.join(root, ".alp/settings.json");
52
+ const settings = await readFile(file, "utf8").then((content) => {
53
+ try {
54
+ return JSON.parse(content);
55
+ } catch (error) {
56
+ throw new Error(`${file} is not valid JSON: ${error.message}`);
57
+ }
58
+ }, (error) => {
59
+ if (error.code === "ENOENT") return void 0;
60
+ throw new Error(`${file}: ${error.message}`);
61
+ });
62
+ const show = () => {
63
+ for (const [seat, choices] of Object.entries(seats)) console.log(` ${SEAT_LABEL[seat]}: ${choices.map(describe).join(", ")}`);
64
+ console.log(` peer: ${peers.join(", ")} (any model: whoever assigns a peer picks its model and effort for the task)`);
65
+ };
66
+ if (settings) validateSettings(settings, file);
67
+ console.log(`Profiles for Ph\u1EDF and Cafe in ${file}:`);
68
+ show();
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);
74
+ if (interactive) {
75
+ for (; ; ) {
76
+ const next2 = await select({ message: "Save these profiles?", initial: "save", choices: [
77
+ { label: "Save", value: "save" },
78
+ { label: "Change a model", value: "change" },
79
+ { label: "Cancel", value: "cancel" }
80
+ ] });
81
+ if (next2 === "cancel") throw new Cancelled();
82
+ if (next2 === "save") break;
83
+ await change(seats, home);
84
+ show();
85
+ }
86
+ }
87
+ validateSettings(merge(settings ?? {}, await profiles(root, home, seats, peers, settings), owners).next, file);
88
+ if (!settings) await initProject(root, { library: home });
89
+ else if (replaced.length) await copyFile(file, `${file}.bak`);
90
+ const written = settings ?? JSON.parse(await readFile(file, "utf8"));
91
+ const { next, record } = merge(written, await profiles(root, home, seats, peers, written), owners);
92
+ validateSettings(next, file);
93
+ await writeFile(file, JSON.stringify(next, null, 2) + "\n");
94
+ await writeRecord(root, record, owners.newer);
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.");
96
+ } catch (error) {
97
+ if (!(error instanceof Cancelled)) throw error;
98
+ console.log(error.message);
99
+ }
100
+ }
101
+ var describe = (choice) => `${choice.provider}:${choice.model}${choice.effort ? `:${choice.effort}` : ""}`;
102
+ async function change(seats, home) {
103
+ const catalog = catalogModels(home);
104
+ 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) }))) });
105
+ const current = seats[seat][at];
106
+ const offered = catalog.filter((model2) => model2.runtime === current.provider);
107
+ const picked = await select({ message: `${SEAT_LABEL[seat]} on ${PROVIDER_LABEL[current.provider]}`, initial: current.model, choices: [
108
+ ...offered.map((model2) => ({ label: model2.label, value: model2.id, hint: `${model2.id} \xB7 ${model2.description}` })),
109
+ { label: "Other\u2026", value: void 0, hint: "type a model ID" }
110
+ ] });
111
+ const model = picked ?? nativeModel(await text(`${PROVIDER_LABEL[current.provider]} model ID:`), current.provider, "The model ID");
112
+ const efforts = catalog.find((entry) => entry.runtime === current.provider && entry.id === model)?.efforts ?? modelEfforts(`${current.provider}:${model}`) ?? ANY_EFFORT;
113
+ const effort = efforts.length > 1 ? await select({
114
+ message: "Effort",
115
+ initial: efforts.includes(current.effort) ? current.effort : DEFAULTS[seat][current.provider][1],
116
+ choices: efforts.map((effort2) => ({ label: effort2, value: effort2 }))
117
+ }) : efforts[0];
118
+ seats[seat][at] = { provider: current.provider, model, ...effort ? { effort } : {} };
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
+ }
145
+ async function profiles(root, home, seats, peers, settings) {
146
+ const profile = {};
147
+ for (const id of BUILTIN_TEAMS) {
148
+ const team = await resolveTeam(root, id, { library: home });
149
+ const agents = {};
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 } : {} };
153
+ }
154
+ profile[id] = agents;
155
+ }
156
+ return profile;
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
+ }
266
+ function nativeModel(id, provider, where) {
267
+ const model = id.startsWith(`${provider}:`) ? id.slice(provider.length + 1) : id;
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}'`);
269
+ return model;
270
+ }
271
+ export {
272
+ setup
273
+ };
@@ -0,0 +1,14 @@
1
+ export function holdDaemon(home: string, by?: string): Promise<void>;
2
+ export function releaseHold(home: string): Promise<void>;
3
+ export function daemonHeld(home: string): Promise<boolean>;
4
+ export function startDaemon(options: { home: string; entry?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number; signal?: AbortSignal }): Promise<string>;
5
+ export function superviseDaemon(options: {
6
+ home: string;
7
+ entry?: string | (() => string | undefined);
8
+ env?: NodeJS.ProcessEnv;
9
+ intervalMs?: number;
10
+ misses?: number;
11
+ log?: (message: string) => void;
12
+ /** Who keeps alpd up, for the log: "alpd started with <by>". */
13
+ by?: string;
14
+ }): (() => Promise<void>) & { started: Promise<void> };
@@ -0,0 +1,91 @@
1
+ // packages/client/src/supervise.js
2
+ import { mkdir, unlink, writeFile, stat } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { daemonStartTimeoutMs, ensureDaemon, lockAlive, readLock, withDaemonLifecycle } from "./index.js";
5
+ import { installedProgram, serviceFor, startService } from "./service.js";
6
+ var holdFile = (home) => path.join(home, "state", "alpd.held");
7
+ async function holdDaemon(home, by = "alp daemon stop") {
8
+ await mkdir(path.dirname(holdFile(home)), { recursive: true, mode: 448 });
9
+ await writeFile(holdFile(home), JSON.stringify({ by, at: (/* @__PURE__ */ new Date()).toISOString() }) + "\n", { mode: 384 });
10
+ }
11
+ async function releaseHold(home) {
12
+ await unlink(holdFile(home)).catch(() => {
13
+ });
14
+ }
15
+ async function daemonHeld(home) {
16
+ return stat(holdFile(home)).then(() => true, () => false);
17
+ }
18
+ async function whenReady(home, timeoutMs, signal) {
19
+ const deadline = Date.now() + timeoutMs;
20
+ while (Date.now() < deadline) {
21
+ signal?.throwIfAborted();
22
+ const lock = await readLock(home);
23
+ if (lockAlive(lock) && lock.ready) return lock.socket;
24
+ await new Promise((resolve) => setTimeout(resolve, 100));
25
+ }
26
+ throw new Error(`alpd did not become ready within ${timeoutMs / 1e3} s; see ${path.join(home, "logs")}`);
27
+ }
28
+ async function startDaemon({ home, entry, env = process.env, timeoutMs = daemonStartTimeoutMs(env), automatic = false, signal }) {
29
+ return withDaemonLifecycle(home, "start", async () => {
30
+ signal?.throwIfAborted();
31
+ if (automatic) {
32
+ if (await daemonHeld(home)) return;
33
+ } else await releaseHold(home);
34
+ const lock = await readLock(home);
35
+ signal?.throwIfAborted();
36
+ if (lockAlive(lock)) return lock.ready ? lock.socket : whenReady(home, timeoutMs, signal);
37
+ const service = serviceFor({ home, env });
38
+ if (service && await installedProgram(service)) {
39
+ signal?.throwIfAborted();
40
+ await startService(service);
41
+ return whenReady(home, timeoutMs, signal);
42
+ }
43
+ return ensureDaemon({ home, entry, env, timeoutMs, lifecycleLocked: true, signal });
44
+ }, { signal });
45
+ }
46
+ function superviseDaemon({ home, entry, env = process.env, intervalMs = 5e3, misses = 2, log = () => {
47
+ }, by }) {
48
+ let stopped = false;
49
+ let missed = 0;
50
+ let starting;
51
+ const start = (reason, automatic = true) => {
52
+ starting ??= startDaemon({ home, entry: typeof entry === "function" ? entry() : entry, env, automatic }).then((socket) => {
53
+ if (socket) log(`alpd ${reason}`);
54
+ }, (error) => log(`could not start alpd: ${error?.message ?? error}`)).finally(() => {
55
+ starting = void 0;
56
+ missed = 0;
57
+ });
58
+ return starting;
59
+ };
60
+ const check = async () => {
61
+ if (stopped || starting) return;
62
+ if (lockAlive(await readLock(home))) {
63
+ missed = 0;
64
+ return;
65
+ }
66
+ if (await daemonHeld(home)) {
67
+ missed = 0;
68
+ return;
69
+ }
70
+ if (++missed >= misses && !stopped) await start("was down; started it again");
71
+ };
72
+ const initial = start(by ? `started with ${by}` : "started", false);
73
+ const timer = setInterval(() => {
74
+ void check();
75
+ }, intervalMs);
76
+ timer.unref?.();
77
+ const stop = () => {
78
+ stopped = true;
79
+ clearInterval(timer);
80
+ return starting ?? Promise.resolve();
81
+ };
82
+ stop.started = initial;
83
+ return stop;
84
+ }
85
+ export {
86
+ daemonHeld,
87
+ holdDaemon,
88
+ releaseHold,
89
+ startDaemon,
90
+ superviseDaemon
91
+ };
@@ -0,0 +1,51 @@
1
+ /** A URL fit for an error message: no credentials, query or fragment, which may carry a token. @param {string} url */
2
+ export function redactUrl(url: string): string;
3
+ /**
4
+ * Wraps an open WebSocket in an ALP transport. The transport owns the socket from then on.
5
+ * @param {WebSocketLike} socket
6
+ * @param {WebSocketTransportOptions} [options]
7
+ * @returns {AlpTransport}
8
+ */
9
+ export function createWebSocketTransport(socket: WebSocketLike, { maxFrame, maxBufferedBytes }?: WebSocketTransportOptions): AlpTransport;
10
+ /**
11
+ * Opens a WebSocket to `url` and resolves with its transport once it is open. The socket comes
12
+ * from `createSocket`, else `new WebSocket(url, protocols)` with the injected or global WebSocket.
13
+ * Errors name the URL without its credentials, query or fragment.
14
+ * @param {string} url
15
+ * @param {ConnectWebSocketOptions} [options]
16
+ * @returns {Promise<AlpTransport>}
17
+ */
18
+ export function connectWebSocket(url: string, { WebSocket: Implementation, protocols, createSocket, signal, timeoutMs, ...options }?: ConnectWebSocketOptions): Promise<AlpTransport>;
19
+ /** Close codes this transport sends when the peer breaks the protocol. */
20
+ export const CLOSE_CODE: Readonly<{
21
+ unsupportedData: 4003;
22
+ tooLarge: 4009;
23
+ }>;
24
+ export type AlpTransport = import("./rpc/client.js").AlpTransport;
25
+ export type TransportClose = import("./rpc/client.js").TransportClose;
26
+ export type AbortSignalLike = import("./rpc/client.js").AbortSignalLike;
27
+ export type WebSocketLike = {
28
+ readonly readyState: number;
29
+ readonly bufferedAmount?: number;
30
+ binaryType?: string;
31
+ send(data: string): void;
32
+ close(code?: number, reason?: string): void;
33
+ addEventListener?(type: string, listener: (event: any) => void): void;
34
+ removeEventListener?(type: string, listener: (event: any) => void): void;
35
+ onopen?: ((event: any) => void) | null;
36
+ onmessage?: ((event: any) => void) | null;
37
+ onerror?: ((event: any) => void) | null;
38
+ onclose?: ((event: any) => void) | null;
39
+ };
40
+ export type WebSocketConstructor = new (url: string, protocols?: string | string[]) => WebSocketLike;
41
+ export type WebSocketTransportOptions = {
42
+ maxFrame?: number;
43
+ maxBufferedBytes?: number;
44
+ };
45
+ export type ConnectWebSocketOptions = WebSocketTransportOptions & {
46
+ WebSocket?: WebSocketConstructor;
47
+ protocols?: string | string[];
48
+ createSocket?: (url: string, protocols?: string | string[]) => WebSocketLike;
49
+ signal?: AbortSignalLike;
50
+ timeoutMs?: number;
51
+ };