@anhlp/alp-client 0.0.0-beta.2 → 0.0.1-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +23 -1
  2. package/dist/acp-probe.d.ts +3 -2
  3. package/dist/acp-probe.js +11 -2
  4. package/dist/antigravity-probe.d.ts +1 -2
  5. package/dist/antigravity-probe.js +11 -5
  6. package/dist/command.js +3 -1
  7. package/dist/doctor.d.ts +8 -0
  8. package/dist/doctor.js +276 -13
  9. package/dist/index.d.ts +123 -8
  10. package/dist/index.js +332 -52
  11. package/dist/integration-lock.d.ts +37 -0
  12. package/dist/integration-lock.js +199 -0
  13. package/dist/mcp-probe.js +1 -1
  14. package/dist/portable.d.ts +3 -1
  15. package/dist/portable.js +11 -2
  16. package/dist/render.js +3 -0
  17. package/dist/rpc/handshake.d.ts +6 -1
  18. package/dist/rpc/handshake.js +4 -2
  19. package/dist/rpc/registry.d.ts +227 -0
  20. package/dist/rpc/registry.js +223 -0
  21. package/dist/rpc/terminal-directory.d.ts +24 -0
  22. package/dist/rpc/terminal-directory.js +70 -0
  23. package/dist/service.d.ts +2 -2
  24. package/dist/service.js +3 -1
  25. package/dist/setup.d.ts +7 -1
  26. package/dist/setup.js +159 -32
  27. package/dist/supervise.d.ts +3 -1
  28. package/dist/supervise.js +26 -16
  29. package/package.json +11 -3
  30. package/src/acp-probe.js +10 -3
  31. package/src/antigravity-probe.js +12 -5
  32. package/src/command.js +3 -1
  33. package/src/doctor.d.ts +8 -0
  34. package/src/doctor.js +345 -3
  35. package/src/index.js +411 -55
  36. package/src/integration-lock.js +203 -0
  37. package/src/mcp-probe.js +1 -1
  38. package/src/portable.js +4 -1
  39. package/src/render.js +3 -0
  40. package/src/rpc/handshake.js +7 -2
  41. package/src/rpc/registry.js +229 -0
  42. package/src/rpc/terminal-directory.js +61 -0
  43. package/src/service.js +7 -3
  44. package/src/setup.js +201 -35
  45. package/src/supervise.d.ts +3 -1
  46. package/src/supervise.js +31 -19
@@ -0,0 +1,223 @@
1
+ // packages/client/src/rpc/registry.js
2
+ function workspaceRegistry(client) {
3
+ return {
4
+ /** @param {string} workspaceId @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['workspace.worktree.options']['result']>} */
5
+ worktreeOptions: (workspaceId) => client.request("workspace.worktree.options", { workspaceId }),
6
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['workspace.worktree.create']['params']} params @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['workspace.worktree.create']['result']>} */
7
+ createWorktree: (params) => client.request("workspace.worktree.create", params),
8
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['workspace.worktree.remove']['params']} params @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['workspace.worktree.remove']['result']>} */
9
+ removeWorktree: (params) => client.request("workspace.worktree.remove", params),
10
+ /** Read-only Git status of a registry workspace (capability `workspace.git`, §12.5). @param {string} workspaceId @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['workspace.git.status']['result']>} */
11
+ gitStatus: (workspaceId) => client.request("workspace.git.status", { workspaceId }),
12
+ /** One page of a read-only Git diff; pass `nextCursor` back as `cursor` with the same comparison and path. @param {import('@anhlp/alp-protocol').RpcMethodMap['workspace.git.diff']['params']} params @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['workspace.git.diff']['result']>} */
13
+ gitDiff: (params) => client.request("workspace.git.diff", params),
14
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['project.list']['params']} [params] @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['project.list']['result']>} */
15
+ projects: (params = {}) => client.request("project.list", params),
16
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['workspace.list']['params']} [params] @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['workspace.list']['result']>} */
17
+ workspaces: (params = {}) => client.request("workspace.list", params),
18
+ /** @param {string} workspaceId @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['workspace.get']['result']>} */
19
+ get: (workspaceId) => client.request("workspace.get", { workspaceId }),
20
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['project.register']['params']} params @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['project.register']['result']>} */
21
+ register: (params) => client.request("project.register", params),
22
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['project.remove']['params']} params @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['project.remove']['result']>} */
23
+ remove: (params) => client.request("project.remove", params),
24
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['workspace.update']['params']} params @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['workspace.update']['result']>} */
25
+ update: (params) => client.request("workspace.update", params)
26
+ };
27
+ }
28
+ var BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
29
+ function base64Encode(bytes) {
30
+ let out = "";
31
+ let index = 0;
32
+ for (; index + 2 < bytes.length; index += 3) {
33
+ const n = bytes[index] << 16 | bytes[index + 1] << 8 | bytes[index + 2];
34
+ out += BASE64[n >> 18] + BASE64[n >> 12 & 63] + BASE64[n >> 6 & 63] + BASE64[n & 63];
35
+ }
36
+ if (index < bytes.length) {
37
+ const n = bytes[index] << 16 | (index + 1 < bytes.length ? bytes[index + 1] : 0) << 8;
38
+ out += BASE64[n >> 18] + BASE64[n >> 12 & 63] + (index + 1 < bytes.length ? BASE64[n >> 6 & 63] : "=") + "=";
39
+ }
40
+ return out;
41
+ }
42
+ async function sha256Hex(bytes) {
43
+ const subtle = globalThis.crypto?.subtle;
44
+ if (!subtle) throw new Error("SHA-256 needs WebCrypto here; pass sha256 yourself");
45
+ const digest = new Uint8Array(await subtle.digest("SHA-256", bytes));
46
+ return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
47
+ }
48
+ function attachments(client) {
49
+ const api = {
50
+ /** @param {Map['attachment.begin']['params']} params @returns {Promise<Map['attachment.begin']['result']>} */
51
+ begin: (params) => client.request("attachment.begin", params),
52
+ /** @param {Map['attachment.chunk']['params']} params @returns {Promise<Map['attachment.chunk']['result']>} */
53
+ chunk: (params) => client.request("attachment.chunk", params),
54
+ /** @param {Map['attachment.commit']['params']} params @returns {Promise<Map['attachment.commit']['result']>} */
55
+ commit: (params) => client.request("attachment.commit", params),
56
+ /** @param {string} uploadId @returns {Promise<Map['attachment.abort']['result']>} */
57
+ abort: (uploadId) => client.request("attachment.abort", { uploadId }),
58
+ /** Metadata only (no bytes, no path). @param {string} attachmentId @returns {Promise<Map['attachment.get']['result']>} */
59
+ get: (attachmentId) => client.request("attachment.get", { attachmentId }),
60
+ /** Refused (1004 attachment_referenced) while a prompt references it. @param {string} attachmentId @returns {Promise<Map['attachment.delete']['result']>} */
61
+ delete: (attachmentId) => client.request("attachment.delete", { attachmentId }),
62
+ /**
63
+ * Uploads `data` and commits it: begin (or resume, with the same requestId), chunks of at most
64
+ * the smaller of `maxChunkBytes` and what begin answered, commit with its SHA-256. A chunk
65
+ * refused `offset_mismatch` continues from the daemon's `received`. Returns the attachment.
66
+ * The returned promise exposes `.uploadId` once begun and `.abort(reason?: any)` to abort on alpd.
67
+ * @param {{ sessionId: string, name: string, mimeType: string, data: Uint8Array, requestId: string, sha256?: string, maxChunkBytes?: number, signal?: AbortSignal, onBegun?: (uploadId: string) => void, onProgress?: (received: number, size: number) => void }} options
68
+ * @returns {Promise<Map['attachment.commit']['result']['attachment']> & { readonly uploadId?: string, abort(reason?: any): Promise<void> }}
69
+ */
70
+ upload({ sessionId, name, mimeType, data, requestId, sha256, maxChunkBytes, signal, onBegun, onProgress }) {
71
+ let uploadId;
72
+ let userAborted = false;
73
+ let userAbortReason;
74
+ const isAborted = () => userAborted || (signal?.aborted ?? false);
75
+ const getAbortReason = () => userAbortReason ?? signal?.reason ?? new Error("Upload aborted");
76
+ const onSignalAbort = () => {
77
+ if (uploadId) api.abort(uploadId).catch(() => {
78
+ });
79
+ };
80
+ signal?.addEventListener?.("abort", onSignalAbort, { once: true });
81
+ const run = (
82
+ /** @type {Promise<Map['attachment.commit']['result']['attachment']> & { uploadId?: string, abort(reason?: any): Promise<void> }} */
83
+ (async () => {
84
+ try {
85
+ if (isAborted()) throw getAbortReason();
86
+ const digest = sha256 ?? await sha256Hex(data);
87
+ if (isAborted()) throw getAbortReason();
88
+ const begun = await api.begin({ sessionId, name, size: data.length, mimeType, sha256: digest, requestId });
89
+ uploadId = begun.uploadId;
90
+ try {
91
+ onBegun?.(begun.uploadId);
92
+ } catch (error) {
93
+ if (begun.state !== "committed") await api.abort(begun.uploadId).catch(() => {
94
+ });
95
+ throw error;
96
+ }
97
+ if (isAborted()) {
98
+ if (begun.state !== "committed") await api.abort(begun.uploadId).catch(() => {
99
+ });
100
+ throw getAbortReason();
101
+ }
102
+ if (begun.state === "committed" && begun.attachmentId) return (await api.get(begun.attachmentId)).attachment;
103
+ const size = Math.max(1, Math.min(begun.maxChunkBytes, maxChunkBytes ?? Infinity));
104
+ let offset = begun.received;
105
+ for (let realigned = 0; offset < data.length; ) {
106
+ if (isAborted()) {
107
+ await api.abort(begun.uploadId).catch(() => {
108
+ });
109
+ throw getAbortReason();
110
+ }
111
+ const end = Math.min(data.length, offset + size);
112
+ try {
113
+ const { received } = await api.chunk({ uploadId: begun.uploadId, offset, data: base64Encode(data.subarray(offset, end)) });
114
+ offset = received;
115
+ } catch (error) {
116
+ if (isAborted()) {
117
+ await api.abort(begun.uploadId).catch(() => {
118
+ });
119
+ throw getAbortReason();
120
+ }
121
+ const held = (
122
+ /** @type {any} */
123
+ error?.data
124
+ );
125
+ if (held?.reason !== "offset_mismatch" || !Number.isSafeInteger(held.received) || ++realigned > 3) throw error;
126
+ offset = held.received;
127
+ continue;
128
+ }
129
+ if (isAborted()) {
130
+ await api.abort(begun.uploadId).catch(() => {
131
+ });
132
+ throw getAbortReason();
133
+ }
134
+ try {
135
+ onProgress?.(offset, data.length);
136
+ } catch (error) {
137
+ await api.abort(begun.uploadId).catch(() => {
138
+ });
139
+ throw error;
140
+ }
141
+ }
142
+ if (isAborted()) {
143
+ await api.abort(begun.uploadId).catch(() => {
144
+ });
145
+ throw getAbortReason();
146
+ }
147
+ return (await api.commit({ uploadId: begun.uploadId, sha256: digest })).attachment;
148
+ } finally {
149
+ signal?.removeEventListener?.("abort", onSignalAbort);
150
+ }
151
+ })()
152
+ );
153
+ Object.defineProperty(run, "uploadId", {
154
+ get: () => uploadId,
155
+ enumerable: true
156
+ });
157
+ run.abort = async (reason) => {
158
+ userAborted = true;
159
+ userAbortReason = reason ?? new Error("Upload aborted");
160
+ if (uploadId) await api.abort(uploadId).catch(() => {
161
+ });
162
+ };
163
+ return run;
164
+ }
165
+ };
166
+ return api;
167
+ }
168
+ function conversation(client) {
169
+ return {
170
+ /**
171
+ * A new closed root whose conversation is the source root's through or before a turn (`boundary`),
172
+ * or a branch a rewind set aside (`branchId`); resume it with session.create { sessionId, resume: true }.
173
+ * Principal fields are set by a trusted gateway on its own connection, never by a remote client.
174
+ * @param {Map['session.fork']['params']} params @returns {Promise<Map['session.fork']['result']>}
175
+ */
176
+ fork: (params) => client.request("session.fork", params),
177
+ /**
178
+ * Continues the root's conversation from before `beforeTurnId` under the same session id; the
179
+ * later turns stay a branch (`branch.branchId`) that `fork({ branchId })` recovers.
180
+ * @param {Map['session.rewind']['params']} params @returns {Promise<Map['session.rewind']['result']>}
181
+ */
182
+ rewind: (params) => client.request("session.rewind", params),
183
+ /**
184
+ * Restarts a live root's native process on its own conversation and configuration at the idle
185
+ * barrier (capability `session.reload`, §12.8); id, history and receipts stay. Sent once: repeat
186
+ * the same `requestId` after a lost answer.
187
+ * @param {Map['session.reload']['params']} params @returns {Promise<Map['session.reload']['result']>}
188
+ */
189
+ reload: (params) => client.request("session.reload", params),
190
+ /**
191
+ * The ALP CLI command that follows the session in a terminal (capability `session.resumeCommand`,
192
+ * §12.8), built by alpd: for the clipboard only, never to run.
193
+ * @param {Map['session.resumeCommand']['params']} params @returns {Promise<Map['session.resumeCommand']['result']>}
194
+ */
195
+ resumeCommand: (params) => client.request("session.resumeCommand", params),
196
+ /**
197
+ * The slash commands and skills the session's composer offers after "/" (capability `session.commands`, §12.12).
198
+ * @param {Map['session.commands']['params']} params @returns {Promise<Map['session.commands']['result']>}
199
+ */
200
+ commands: (params) => client.request("session.commands", params),
201
+ /**
202
+ * Changes a live root's model, effort or team (capability `session.configure.live`, §12.9) at the
203
+ * idle barrier, through a restart of its native process on the same conversation; `configured` says
204
+ * what it runs with now. Sent once: repeat the same `requestId` after a lost answer. A change to
205
+ * another runtime is refused (1005 runtime_mismatch, `data.action: 'session.create'`).
206
+ * @param {Map['session.configure']['params'] & { requestId: string; ifGeneration: string }} params @returns {Promise<Map['session.configure']['result']>}
207
+ */
208
+ configure: (params) => client.request("session.configure", params),
209
+ /**
210
+ * What a change of model, effort, team or mode would run a live root with, and whether it would be
211
+ * taken now (capability `session.configure.live`, §12.9). Reads only.
212
+ * @param {Map['session.configure.preview']['params']} params @returns {Promise<Map['session.configure.preview']['result']>}
213
+ */
214
+ configurePreview: (params) => client.request("session.configure.preview", params)
215
+ };
216
+ }
217
+ export {
218
+ attachments,
219
+ base64Encode,
220
+ conversation,
221
+ sha256Hex,
222
+ workspaceRegistry
223
+ };
@@ -0,0 +1,24 @@
1
+ /**
2
+ * A terminal directory for one connection. Subscribe before requesting the atomic snapshot.
3
+ * Invalidations are coalesced; a reconnect installs a new watcher and replaces state with its
4
+ * full snapshot (reset), rather than replaying obsolete list mutations. No output is replayed.
5
+ * @param {{request<T = any>(method:string, params?:any):Promise<T>, onNotification?(listener:(method:string,params:any)=>void):()=>void, onClose(listener:(error:Error)=>void):()=>void}} connection
6
+ * @param {{capabilities:readonly string[], workspaceId?:string, pollMs?:number, onSnapshot:(terminals:import('@anhlp/alp-protocol').TerminalInfo[])=>void, onError?:(error:unknown)=>void, onMode?:(mode:'events'|'polling')=>void}} options
7
+ */
8
+ export function watchTerminals(connection: {
9
+ request<T = any>(method: string, params?: any): Promise<T>;
10
+ onNotification?(listener: (method: string, params: any) => void): () => void;
11
+ onClose(listener: (error: Error) => void): () => void;
12
+ }, options: {
13
+ capabilities: readonly string[];
14
+ workspaceId?: string;
15
+ pollMs?: number;
16
+ onSnapshot: (terminals: import("@anhlp/alp-protocol").TerminalInfo[]) => void;
17
+ onError?: (error: unknown) => void;
18
+ onMode?: (mode: "events" | "polling") => void;
19
+ }): {
20
+ ready: Promise<void>;
21
+ refresh: () => Promise<void>;
22
+ close: (unwatch?: boolean) => void;
23
+ mode: string;
24
+ };
@@ -0,0 +1,70 @@
1
+ // packages/client/src/rpc/terminal-directory.js
2
+ function watchTerminals(connection, options) {
3
+ const events = options.capabilities.includes("terminal.watch") && !!connection.onNotification;
4
+ let closed = false;
5
+ let watchId = "";
6
+ let cursor = "";
7
+ let again = false;
8
+ let refreshing;
9
+ const pending = /* @__PURE__ */ new Map();
10
+ const off = connection.onNotification?.((method, params) => {
11
+ if (closed || !events || method !== "terminal.changed" || !/^[0-9a-f]{32}$/.test(params?.watchId) || !/^[0-9a-f]{32}$/.test(params?.cursor)) return;
12
+ if (pending.size >= 4 && !pending.has(params.watchId)) pending.delete(pending.keys().next().value ?? "");
13
+ pending.set(params.watchId, params.cursor);
14
+ if (params.watchId === watchId && params.cursor !== cursor) {
15
+ again = true;
16
+ void refresh();
17
+ }
18
+ });
19
+ function refresh() {
20
+ if (closed) return Promise.resolve();
21
+ if (refreshing) return refreshing;
22
+ refreshing = (async () => {
23
+ do {
24
+ again = false;
25
+ try {
26
+ const result = await connection.request(events ? "terminal.watch" : "terminal.list", { ...options.workspaceId ? { workspaceId: options.workspaceId } : {}, ...events && cursor ? { after: cursor } : {} });
27
+ if (closed) return;
28
+ if (!Array.isArray(result?.terminals)) throw new Error("Invalid terminal directory snapshot");
29
+ if (events) {
30
+ if (!/^[0-9a-f]{32}$/.test(result.watchId) || !/^[0-9a-f]{32}$/.test(result.cursor) || typeof result.reset !== "boolean") throw new Error("Invalid terminal directory cursor");
31
+ watchId = result.watchId;
32
+ cursor = result.cursor;
33
+ again = pending.has(watchId) && pending.get(watchId) !== cursor;
34
+ pending.clear();
35
+ }
36
+ options.onSnapshot(result.terminals);
37
+ } catch (error) {
38
+ options.onError?.(error);
39
+ return;
40
+ }
41
+ } while (again && !closed);
42
+ })().finally(() => {
43
+ refreshing = void 0;
44
+ });
45
+ return refreshing;
46
+ }
47
+ const timer = events ? void 0 : setInterval(() => {
48
+ void refresh();
49
+ }, options.pollMs ?? 5e3);
50
+ let offClose = () => {
51
+ };
52
+ function close(unwatch = true) {
53
+ if (closed) return;
54
+ closed = true;
55
+ if (timer !== void 0) clearInterval(timer);
56
+ off?.();
57
+ offClose();
58
+ pending.clear();
59
+ if (events && unwatch) void connection.request("terminal.unwatch", {}).catch(() => {
60
+ });
61
+ }
62
+ offClose = connection.onClose(() => close(false));
63
+ if (closed) offClose();
64
+ options.onMode?.(events ? "events" : "polling");
65
+ const ready = refresh();
66
+ return { ready, refresh, close, mode: events ? "events" : "polling" };
67
+ }
68
+ export {
69
+ watchTerminals
70
+ };
package/dist/service.d.ts CHANGED
@@ -32,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` with `execPath` 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/service.js CHANGED
@@ -4,6 +4,7 @@ import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { runCommand } from "./command.js";
7
+ import { entryCommand, stablePath } from "@anhlp/alp-core/packaged";
7
8
  var CARRIED = ["ALP_RUN_LOG_DIR", "ALP_CODEX_BIN", "ALP_CLAUDE_BIN", "ALP_ANTIGRAVITY_BIN", "ALP_GH_BIN"];
8
9
  var escapeXml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
9
10
  var quoteUnit = (value) => `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
@@ -44,7 +45,8 @@ function serviceFor({ home, env = process.env, platform = process.platform, uid
44
45
  function serviceDefinition(service, { home, entry, execPath = process.execPath, env = process.env }) {
45
46
  const variables = { ALP_HOME: path.resolve(home), PATH: env.PATH ?? "" };
46
47
  for (const name of CARRIED) if (env[name]) variables[name] = env[name];
47
- const program = [execPath, entry, "--service"];
48
+ const launch = entryCommand(stablePath(entry), "daemon", ["--service"], stablePath(execPath));
49
+ const program = [launch.command, ...launch.args];
48
50
  const fatal = path.join(path.resolve(home), "logs", "alpd.service.log");
49
51
  if (service.kind === "launchd") {
50
52
  return `<?xml version="1.0" encoding="UTF-8"?>
package/dist/setup.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 { MODELS } 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: [
@@ -83,18 +80,18 @@ async function setup(args, home) {
83
80
  ] });
84
81
  if (next2 === "cancel") throw new Cancelled();
85
82
  if (next2 === "save") break;
86
- await change(seats);
83
+ await change(seats, 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;
@@ -102,16 +99,17 @@ async function setup(args, home) {
102
99
  }
103
100
  }
104
101
  var describe = (choice) => `${choice.provider}:${choice.model}${choice.effort ? `:${choice.effort}` : ""}`;
105
- async function change(seats) {
102
+ async function change(seats, home) {
103
+ const catalog = catalogModels(home);
106
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) }))) });
107
105
  const current = seats[seat][at];
108
- const offered = MODELS.filter((model2) => model2.runtime === current.provider);
106
+ const offered = catalog.filter((model2) => model2.runtime === current.provider);
109
107
  const picked = await select({ message: `${SEAT_LABEL[seat]} on ${PROVIDER_LABEL[current.provider]}`, initial: current.model, choices: [
110
108
  ...offered.map((model2) => ({ label: model2.label, value: model2.id, hint: `${model2.id} \xB7 ${model2.description}` })),
111
109
  { label: "Other\u2026", value: void 0, hint: "type a model ID" }
112
110
  ] });
113
111
  const model = picked ?? nativeModel(await text(`${PROVIDER_LABEL[current.provider]} model ID:`), current.provider, "The model ID");
114
- const efforts = modelEfforts(`${current.provider}:${model}`) ?? ANY_EFFORT;
112
+ const efforts = catalog.find((entry) => entry.runtime === current.provider && entry.id === model)?.efforts ?? modelEfforts(`${current.provider}:${model}`) ?? ANY_EFFORT;
115
113
  const effort = efforts.length > 1 ? await select({
116
114
  message: "Effort",
117
115
  initial: efforts.includes(current.effort) ? current.effort : DEFAULTS[seat][current.provider][1],
@@ -119,23 +117,152 @@ async function change(seats) {
119
117
  }) : efforts[0];
120
118
  seats[seat][at] = { provider: current.provider, model, ...effort ? { effort } : {} };
121
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
+ }
122
145
  async function profiles(root, home, seats, peers, settings) {
123
146
  const profile = {};
124
- for (const id of ["pho", "cafe"]) {
147
+ for (const id of BUILTIN_TEAMS) {
125
148
  const team = await resolveTeam(root, id, { library: home });
126
149
  const agents = {};
127
- const seat = (name, choices) => {
128
- agents[name] = { profiles: choices.map((choice) => typeof choice === "string" ? choice : describe(choice)), autocompact: (settings?.team ?? settings?.profile)?.[id]?.[name]?.autocompact ?? "auto" };
129
- };
130
- for (const [name, member] of Object.entries(team.members)) {
131
- 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 } : {} };
132
153
  }
133
- if (team.supervisor) seat(team.supervisor.agent, seats.supervisor);
134
- if (team.members.oracle) seat("oracle", seats.oracle);
135
154
  profile[id] = agents;
136
155
  }
137
156
  return profile;
138
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
+ }
139
266
  function nativeModel(id, provider, where) {
140
267
  const model = id.startsWith(`${provider}:`) ? id.slice(provider.length + 1) : id;
141
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}'`);