@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,203 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdir, open, rmdir, unlink } from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { moveFile } from '@anhlp/alp-core/atomic';
6
+ import { assertIntegrationName, bootId, bootTime, isSameBoot } from './index.js';
7
+
8
+ /**
9
+ * @typedef {{ pid: number, bootTime: number, bootId?: string, startedUptime?: number, startedAt: string, ready: boolean, lockVersion?: number, owner?: string }} IntegrationLockRecord
10
+ * @typedef {{
11
+ * acquire(): Promise<{ acquired: boolean, lock: IntegrationLockRecord }>,
12
+ * setReady(ready: boolean): Promise<boolean>,
13
+ * release(): Promise<boolean>,
14
+ * }} IntegrationLock
15
+ */
16
+
17
+ /**
18
+ * The single-owner lock of one integration service, at `<home>/integrations/<name>.lock`, with its
19
+ * mutation guard `<name>.lock.reclaim`. Each instance is single-use: acquire once, then setReady and
20
+ * release while it owns the lock.
21
+ *
22
+ * Single-host, same PID namespace, private local filesystem only. Never reap the mutation guard.
23
+ * @param {string} home the ALP_HOME the integration runs under
24
+ * @param {string} name the integration name, for example `web`
25
+ * @returns {IntegrationLock}
26
+ */
27
+ export function createIntegrationLock(home, name) {
28
+ const file = path.join(home, 'integrations', `${assertIntegrationName(name)}.lock`);
29
+ const guard = `${file}.reclaim`;
30
+ /** @type {'new' | 'acquiring' | 'owned' | 'retired'} */
31
+ let phase = 'new';
32
+ /** This instance's lock while it owns it: the lifetime nonce and the file's identity. @type {{ owner: string, dev: number, ino: number } | undefined} */
33
+ let owned;
34
+ /** Serializes concurrent in-process setReady calls to preserve FIFO order. @type {Promise<any>} */
35
+ let readyQueue = Promise.resolve();
36
+ // The lock file as read: its record and the stats of the handle it was read through. Kept inside
37
+ // the factory so the published declarations name only IntegrationLock and its record.
38
+ /** @typedef {{ value: any, info: import('node:fs').Stats }} Snapshot */
39
+ /** @param {string} reason */
40
+ const recovery = reason => new Error(`${reason}. Stop ALL integration processes using this ALP_HOME before manual lock-only recovery of ${file} and ${guard}; see docs/modular-monorepo.md`);
41
+
42
+ /**
43
+ * @template T
44
+ * @param {() => Promise<T>} run
45
+ * @returns {Promise<T>}
46
+ */
47
+ async function guarded(run) {
48
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
49
+ const deadline = Date.now() + 20_000;
50
+ for (;;) {
51
+ try { await mkdir(guard, { mode: 0o700 }); break; }
52
+ catch (error) {
53
+ if (/** @type {any} */ (error)?.code !== 'EEXIST') throw error;
54
+ if (Date.now() >= deadline) throw recovery('Integration mutation guard remains busy or abandoned');
55
+ await new Promise(resolve => setTimeout(resolve, 25));
56
+ }
57
+ }
58
+ const token = path.join(guard, `owner-${process.pid}-${randomUUID()}`);
59
+ // If token initialization/close fails, leave the guard: no speculative cleanup of shared paths.
60
+ try {
61
+ const handle = await open(token, 'wx', 0o600);
62
+ await handle.close();
63
+ } catch (error) { throw recovery(`Integration guard initialization failed: ${String(error)}`); }
64
+ try { return await run(); }
65
+ finally {
66
+ // Only this successful mkdir owner finalizes, once. Missing token may mean a replacement
67
+ // generation: never rmdir in that case. No contender removes any other owner's token.
68
+ try { await unlink(token); }
69
+ catch (error) { throw recovery(/** @type {any} */ (error)?.code === 'ENOENT' ? 'Integration guard ownership was lost' : `Integration guard token cleanup failed: ${String(error)}`); }
70
+ try { await rmdir(guard); }
71
+ catch (error) { throw recovery(`Integration guard cleanup failed: ${String(error)}`); }
72
+ }
73
+ }
74
+
75
+ /** @returns {Promise<Snapshot | undefined>} */
76
+ async function snapshot() {
77
+ let handle;
78
+ try { handle = await open(file, 'r'); }
79
+ catch (error) { if (/** @type {any} */ (error)?.code === 'ENOENT') return undefined; throw error; }
80
+ try {
81
+ const info = await handle.stat();
82
+ const raw = await handle.readFile('utf8');
83
+ let value;
84
+ try { value = JSON.parse(raw); } catch { value = undefined; }
85
+ return { value, info };
86
+ } finally { await handle.close(); }
87
+ }
88
+
89
+ /**
90
+ * @param {any} value
91
+ * @returns {value is IntegrationLockRecord}
92
+ */
93
+ function complete(value) {
94
+ return value && Number.isSafeInteger(value.pid) && value.pid > 0
95
+ && typeof value.bootTime === 'number' && Number.isFinite(value.bootTime) && value.bootTime > 0
96
+ && (value.bootId === undefined || typeof value.bootId === 'string' && value.bootId.length > 0)
97
+ && (value.startedUptime === undefined || typeof value.startedUptime === 'number' && Number.isFinite(value.startedUptime))
98
+ && typeof value.startedAt === 'string' && Number.isFinite(Date.parse(value.startedAt))
99
+ && typeof value.ready === 'boolean'
100
+ && (value.lockVersion === undefined && value.owner === undefined
101
+ || value.lockVersion === 1 && typeof value.owner === 'string' && /^[a-f0-9-]{36}$/.test(value.owner));
102
+ }
103
+
104
+ /**
105
+ * @param {IntegrationLockRecord} value
106
+ * @returns {boolean}
107
+ */
108
+ function dead(value) {
109
+ try { process.kill(value.pid, 0); return false; }
110
+ catch (error) {
111
+ if (/** @type {any} */ (error)?.code !== 'ESRCH') return false; // EPERM and unknown errors never grant takeover.
112
+ // Approximate wall-clock boot metadata is context, never affirmative death evidence.
113
+ if (!isSameBoot(value)) throw recovery('Integration owner boot context is uncertain');
114
+ return true;
115
+ }
116
+ }
117
+
118
+ /**
119
+ * @param {Snapshot | undefined} current
120
+ * @returns {boolean}
121
+ */
122
+ function matches(current) {
123
+ return !!owned && current?.value?.owner === owned.owner
124
+ && current.info.dev === owned.dev && current.info.ino === owned.ino;
125
+ }
126
+
127
+ return {
128
+ async acquire() {
129
+ if (phase !== 'new') throw new Error('Integration lock instance has already been used');
130
+ phase = 'acquiring';
131
+ try {
132
+ return await guarded(async () => {
133
+ const current = await snapshot();
134
+ if (current) {
135
+ if (!complete(current.value)) throw recovery('Integration lock is malformed, incomplete or unsupported');
136
+ if (!dead(current.value)) { phase = 'retired'; return { acquired: false, lock: current.value }; }
137
+ await unlink(file);
138
+ }
139
+ const currentBootId = bootId();
140
+ /** @type {IntegrationLockRecord & { owner: string }} */
141
+ const value = {
142
+ pid: process.pid,
143
+ bootTime: bootTime(),
144
+ ...(currentBootId ? { bootId: currentBootId } : {}),
145
+ startedAt: new Date().toISOString(),
146
+ startedUptime: Math.floor(os.uptime()),
147
+ ready: false,
148
+ lockVersion: 1,
149
+ owner: randomUUID(),
150
+ };
151
+ const handle = await open(file, 'wx', 0o600);
152
+ let info;
153
+ try { await handle.writeFile(JSON.stringify(value)); info = await handle.stat(); }
154
+ finally { await handle.close(); }
155
+ owned = { owner: value.owner, dev: info.dev, ino: info.ino };
156
+ phase = 'owned';
157
+ return { acquired: true, lock: value };
158
+ });
159
+ } catch (error) { phase = 'retired'; owned = undefined; throw error; }
160
+ },
161
+
162
+ async setReady(ready) {
163
+ if (phase !== 'owned') return false;
164
+ const execute = async () => {
165
+ if (phase !== 'owned') return false;
166
+ return guarded(async () => {
167
+ if (phase !== 'owned') return false;
168
+ const current = await snapshot();
169
+ if (!current || !matches(current)) { phase = 'retired'; owned = undefined; return false; }
170
+ const value = { ...current.value, ready };
171
+ const tmp = `${file}.${randomUUID()}.tmp`;
172
+ const handle = await open(tmp, 'wx', 0o600);
173
+ let info;
174
+ try {
175
+ try { await handle.writeFile(JSON.stringify(value)); info = await handle.stat(); }
176
+ finally { await handle.close(); }
177
+ // Readers (alp dashboard --status, a polling client) may hold the lock open; Windows then refuses the
178
+ // replace with EPERM/EACCES/EBUSY for a moment, so moveFile retries it there.
179
+ await moveFile(tmp, file);
180
+ owned = { owner: value.owner, dev: info.dev, ino: info.ino };
181
+ return true;
182
+ } finally { await unlink(tmp).catch(error => { if (error?.code !== 'ENOENT') throw error; }); }
183
+ });
184
+ };
185
+ const chained = readyQueue.then(execute, execute);
186
+ readyQueue = chained.catch(() => {});
187
+ return chained;
188
+ },
189
+
190
+ async release() {
191
+ if (phase !== 'owned') return false;
192
+ return guarded(async () => {
193
+ if (phase !== 'owned') return false;
194
+ const current = await snapshot();
195
+ const ours = matches(current);
196
+ phase = 'retired'; owned = undefined;
197
+ if (!ours) return false;
198
+ await unlink(file);
199
+ return true;
200
+ });
201
+ },
202
+ };
203
+ }
package/src/mcp-probe.js CHANGED
@@ -35,7 +35,7 @@ export function stdioSession(server, cwd, timeoutMs) {
35
35
  // Its own process group, so a launcher such as npx is stopped with what it started.
36
36
  const env = { ...process.env, ...(server.env ?? {}) };
37
37
  const launch = launchCommand(server.command, server.args ?? [], env);
38
- const child = spawn(launch.command, launch.args, { cwd: server.cwd ?? cwd, env, stdio: ['pipe', 'pipe', 'pipe'], detached: true });
38
+ const child = spawn(launch.command, launch.args, { cwd: server.cwd ?? cwd, env: launch.env ? { ...env, ...launch.env } : env, stdio: ['pipe', 'pipe', 'pipe'], detached: true });
39
39
  const signal = name => { try { process.kill(-child.pid, name); } catch { child.kill(name); } };
40
40
  let stderr = '';
41
41
  child.stderr.setEncoding('utf8');
package/src/portable.js CHANGED
@@ -23,5 +23,8 @@ export { AlpRpcClient, DEFAULT_MAX_PENDING } from './rpc/client.js';
23
23
  export { AlpClientError, CLIENT_ERROR, isAlpClientError } from './rpc/errors.js';
24
24
  export { createLineDecoder, utf8Length } from './rpc/framing.js';
25
25
  export { MAX_TIMER_MS, timerDelay } from './rpc/timers.js';
26
- export { hello } from './rpc/handshake.js';
26
+ export { AGENT_CAPABILITY, hello } from './rpc/handshake.js';
27
27
  export { backoffDelay, createReconnectingClient, retryable } from './rpc/reconnect.js';
28
+ export { attachments, base64Encode, conversation, sha256Hex, workspaceRegistry } from './rpc/registry.js';
29
+
30
+ export { watchTerminals } from "./rpc/terminal-directory.js";
package/src/render.js CHANGED
@@ -94,6 +94,9 @@ export function renderLog(rootId, entries) {
94
94
  ? `✦ ${entry.agent} saved skill ${entry.name} for ${entry.roles.join(', ')}`
95
95
  : `✦ ${entry.agent} uses skill ${entry.skill}${entry.via === 'skill' ? ' (Skill tool)' : ''}`;
96
96
  break;
97
+ case 'skill-resource':
98
+ text = `✦ ${entry.agent} ${entry.action === 'run' ? 'runs' : 'reads'} ${entry.skill}/${entry.resource}`;
99
+ break;
97
100
  case 'compacted':
98
101
  text = entry.failed
99
102
  ? `✗ ${entry.agent}'s context could not be compacted${entry.error ? `: ${entry.error}` : ''}`
@@ -1,5 +1,8 @@
1
1
  import { PROTOCOL_VERSION } from '@anhlp/alp-protocol';
2
2
 
3
+ /** The daemon.hello capability a process an ALP agent started announces. */
4
+ export const AGENT_CAPABILITY = 'principal.agent';
5
+
3
6
  /** @typedef {{ name: string, version: string }} ClientInfo */
4
7
 
5
8
  /**
@@ -9,8 +12,10 @@ import { PROTOCOL_VERSION } from '@anhlp/alp-protocol';
9
12
  * @param {{ request(method: string, params?: unknown, options?: import('./client.js').RequestOptions): Promise<any> }} client
10
13
  * @param {ClientInfo} [info]
11
14
  * @param {import('./client.js').RequestOptions} [options]
15
+ * @param {{ agent?: boolean }} [principal] `agent`: an ALP agent started this process (the Node entry reads ALP_AGENT_SESSION).
12
16
  * @returns {Promise<{ protocolVersion: number } & Record<string, unknown>>}
13
17
  */
14
- export function hello(client, info = { name: 'alp', version: '0' }, options) {
15
- return client.request('daemon.hello', { protocolVersion: PROTOCOL_VERSION, client: info }, options);
18
+ export function hello(client, info = { name: 'alp', version: '0' }, options, { agent = false } = {}) {
19
+ // A process an ALP agent started says so (t-ca1f): alpd then refuses it what only the user may do.
20
+ return client.request('daemon.hello', { protocolVersion: PROTOCOL_VERSION, client: info, ...(agent ? { capabilities: [AGENT_CAPABILITY] } : {}) }, options);
16
21
  }
@@ -0,0 +1,229 @@
1
+ /** Typed registry methods for portable clients. Mutations are sent once: callers retain requestId
2
+ * and ifRevision to reconcile a timeout by repeating the identical request. @param {{request<T = any>(method: string, params?: unknown): Promise<T>}} client */
3
+ export function workspaceRegistry(client) {
4
+ return {
5
+ /** @param {string} workspaceId @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['workspace.worktree.options']['result']>} */
6
+ worktreeOptions: workspaceId => client.request('workspace.worktree.options', { workspaceId }),
7
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['workspace.worktree.create']['params']} params @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['workspace.worktree.create']['result']>} */
8
+ createWorktree: params => client.request('workspace.worktree.create', params),
9
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['workspace.worktree.remove']['params']} params @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['workspace.worktree.remove']['result']>} */
10
+ removeWorktree: params => client.request('workspace.worktree.remove', params),
11
+ /** 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']>} */
12
+ gitStatus: workspaceId => client.request('workspace.git.status', { workspaceId }),
13
+ /** 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']>} */
14
+ gitDiff: params => client.request('workspace.git.diff', params),
15
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['project.list']['params']} [params] @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['project.list']['result']>} */
16
+ projects: (params = {}) => client.request('project.list', params),
17
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['workspace.list']['params']} [params] @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['workspace.list']['result']>} */
18
+ workspaces: (params = {}) => client.request('workspace.list', params),
19
+ /** @param {string} workspaceId @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['workspace.get']['result']>} */
20
+ get: workspaceId => client.request('workspace.get', { workspaceId }),
21
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['project.register']['params']} params @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['project.register']['result']>} */
22
+ register: params => client.request('project.register', params),
23
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['project.remove']['params']} params @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['project.remove']['result']>} */
24
+ remove: params => client.request('project.remove', params),
25
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['workspace.update']['params']} params @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['workspace.update']['result']>} */
26
+ update: params => client.request('workspace.update', params),
27
+ };
28
+ }
29
+
30
+ const BASE64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
31
+
32
+ /** Canonical base64 of `bytes`, without Buffer or btoa, so it runs in browsers and Node alike. @param {Uint8Array} bytes */
33
+ export function base64Encode(bytes) {
34
+ let out = '';
35
+ let index = 0;
36
+ for (; index + 2 < bytes.length; index += 3) {
37
+ const n = (bytes[index] << 16) | (bytes[index + 1] << 8) | bytes[index + 2];
38
+ out += BASE64[n >> 18] + BASE64[(n >> 12) & 63] + BASE64[(n >> 6) & 63] + BASE64[n & 63];
39
+ }
40
+ if (index < bytes.length) {
41
+ const n = (bytes[index] << 16) | ((index + 1 < bytes.length ? bytes[index + 1] : 0) << 8);
42
+ out += BASE64[n >> 18] + BASE64[(n >> 12) & 63] + (index + 1 < bytes.length ? BASE64[(n >> 6) & 63] : '=') + '=';
43
+ }
44
+ return out;
45
+ }
46
+
47
+ /** Lowercase hex SHA-256 of `bytes` through WebCrypto (browsers' secure contexts, Node 19+). @param {Uint8Array} bytes */
48
+ export async function sha256Hex(bytes) {
49
+ const subtle = globalThis.crypto?.subtle;
50
+ if (!subtle) throw new Error('SHA-256 needs WebCrypto here; pass sha256 yourself');
51
+ const digest = new Uint8Array(await subtle.digest('SHA-256', bytes));
52
+ return Array.from(digest, byte => byte.toString(16).padStart(2, '0')).join('');
53
+ }
54
+
55
+ /**
56
+ * Typed attachment methods (capability `attachments`, docs/protocol/alp-json-rpc-v1.md §12.6) and a
57
+ * chunked upload that keeps to the limits the daemon (or gateway) advertised. Mutations are sent
58
+ * once: `upload` resumes an interrupted upload by repeating its begin with the same requestId and
59
+ * continues from what the daemon holds.
60
+ * @param {{request<T = any>(method: string, params?: unknown): Promise<T>}} client
61
+ */
62
+ export function attachments(client) {
63
+ /** @typedef {import('@anhlp/alp-protocol').RpcMethodMap} Map */
64
+ const api = {
65
+ /** @param {Map['attachment.begin']['params']} params @returns {Promise<Map['attachment.begin']['result']>} */
66
+ begin: params => client.request('attachment.begin', params),
67
+ /** @param {Map['attachment.chunk']['params']} params @returns {Promise<Map['attachment.chunk']['result']>} */
68
+ chunk: params => client.request('attachment.chunk', params),
69
+ /** @param {Map['attachment.commit']['params']} params @returns {Promise<Map['attachment.commit']['result']>} */
70
+ commit: params => client.request('attachment.commit', params),
71
+ /** @param {string} uploadId @returns {Promise<Map['attachment.abort']['result']>} */
72
+ abort: uploadId => client.request('attachment.abort', { uploadId }),
73
+ /** Metadata only (no bytes, no path). @param {string} attachmentId @returns {Promise<Map['attachment.get']['result']>} */
74
+ get: attachmentId => client.request('attachment.get', { attachmentId }),
75
+ /** Refused (1004 attachment_referenced) while a prompt references it. @param {string} attachmentId @returns {Promise<Map['attachment.delete']['result']>} */
76
+ delete: attachmentId => client.request('attachment.delete', { attachmentId }),
77
+ /**
78
+ * Uploads `data` and commits it: begin (or resume, with the same requestId), chunks of at most
79
+ * the smaller of `maxChunkBytes` and what begin answered, commit with its SHA-256. A chunk
80
+ * refused `offset_mismatch` continues from the daemon's `received`. Returns the attachment.
81
+ * The returned promise exposes `.uploadId` once begun and `.abort(reason?: any)` to abort on alpd.
82
+ * @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
83
+ * @returns {Promise<Map['attachment.commit']['result']['attachment']> & { readonly uploadId?: string, abort(reason?: any): Promise<void> }}
84
+ */
85
+ upload({ sessionId, name, mimeType, data, requestId, sha256, maxChunkBytes, signal, onBegun, onProgress }) {
86
+ /** @type {string | undefined} */
87
+ let uploadId;
88
+ let userAborted = false;
89
+ let userAbortReason;
90
+ const isAborted = () => userAborted || (signal?.aborted ?? false);
91
+ const getAbortReason = () => userAbortReason ?? signal?.reason ?? new Error('Upload aborted');
92
+
93
+ const onSignalAbort = () => {
94
+ if (uploadId) api.abort(uploadId).catch(() => {});
95
+ };
96
+ signal?.addEventListener?.('abort', onSignalAbort, { once: true });
97
+
98
+ const run = /** @type {Promise<Map['attachment.commit']['result']['attachment']> & { uploadId?: string, abort(reason?: any): Promise<void> }} */ ((async () => {
99
+ try {
100
+ if (isAborted()) throw getAbortReason();
101
+ const digest = sha256 ?? await sha256Hex(data);
102
+ if (isAborted()) throw getAbortReason();
103
+ const begun = await api.begin({ sessionId, name, size: data.length, mimeType, sha256: digest, requestId });
104
+ uploadId = begun.uploadId;
105
+ try { onBegun?.(begun.uploadId); }
106
+ catch (error) {
107
+ if (begun.state !== 'committed') await api.abort(begun.uploadId).catch(() => {});
108
+ throw error;
109
+ }
110
+ if (isAborted()) {
111
+ if (begun.state !== 'committed') await api.abort(begun.uploadId).catch(() => {});
112
+ throw getAbortReason();
113
+ }
114
+ if (begun.state === 'committed' && begun.attachmentId) return (await api.get(begun.attachmentId)).attachment;
115
+ const size = Math.max(1, Math.min(begun.maxChunkBytes, maxChunkBytes ?? Infinity));
116
+ let offset = begun.received;
117
+ for (let realigned = 0; offset < data.length;) {
118
+ if (isAborted()) {
119
+ await api.abort(begun.uploadId).catch(() => {});
120
+ throw getAbortReason();
121
+ }
122
+ const end = Math.min(data.length, offset + size);
123
+ try {
124
+ const { received } = await api.chunk({ uploadId: begun.uploadId, offset, data: base64Encode(data.subarray(offset, end)) });
125
+ offset = received;
126
+ } catch (error) {
127
+ if (isAborted()) {
128
+ await api.abort(begun.uploadId).catch(() => {});
129
+ throw getAbortReason();
130
+ }
131
+ const held = /** @type {any} */ (error)?.data;
132
+ // Another attempt got further (or less far) than this one knew: continue where the daemon is.
133
+ if (held?.reason !== 'offset_mismatch' || !Number.isSafeInteger(held.received) || ++realigned > 3) throw error;
134
+ offset = held.received;
135
+ continue;
136
+ }
137
+ if (isAborted()) {
138
+ await api.abort(begun.uploadId).catch(() => {});
139
+ throw getAbortReason();
140
+ }
141
+ try { onProgress?.(offset, data.length); }
142
+ catch (error) {
143
+ await api.abort(begun.uploadId).catch(() => {});
144
+ throw error;
145
+ }
146
+ }
147
+ if (isAborted()) {
148
+ await api.abort(begun.uploadId).catch(() => {});
149
+ throw getAbortReason();
150
+ }
151
+ return (await api.commit({ uploadId: begun.uploadId, sha256: digest })).attachment;
152
+ } finally {
153
+ signal?.removeEventListener?.('abort', onSignalAbort);
154
+ }
155
+ })());
156
+
157
+ Object.defineProperty(run, 'uploadId', {
158
+ get: () => uploadId,
159
+ enumerable: true,
160
+ });
161
+ run.abort = async (reason) => {
162
+ userAborted = true;
163
+ userAbortReason = reason ?? new Error('Upload aborted');
164
+ if (uploadId) await api.abort(uploadId).catch(() => {});
165
+ };
166
+ return run;
167
+ },
168
+ };
169
+ return api;
170
+ }
171
+
172
+ /**
173
+ * Typed conversation methods (capabilities `session.fork` and `session.rewind`, docs/protocol/
174
+ * alp-json-rpc-v1.md §12.7; `session.reload` and `session.resumeCommand`, §12.8). Both change the conversation only, never a file. Mutations are sent
175
+ * once: keep `requestId` (and `ifGeneration`) to repeat the identical request after a timeout, which
176
+ * answers the first result with `duplicate: true`. After a rewind, attached clients get a
177
+ * `history.reset` event: drop cached history, fetch a new tail and attach with its generation.
178
+ * @param {{request<T = any>(method: string, params?: unknown): Promise<T>}} client
179
+ */
180
+ export function conversation(client) {
181
+ /** @typedef {import('@anhlp/alp-protocol').RpcMethodMap} Map */
182
+ return {
183
+ /**
184
+ * A new closed root whose conversation is the source root's through or before a turn (`boundary`),
185
+ * or a branch a rewind set aside (`branchId`); resume it with session.create { sessionId, resume: true }.
186
+ * Principal fields are set by a trusted gateway on its own connection, never by a remote client.
187
+ * @param {Map['session.fork']['params']} params @returns {Promise<Map['session.fork']['result']>}
188
+ */
189
+ fork: params => client.request('session.fork', params),
190
+ /**
191
+ * Continues the root's conversation from before `beforeTurnId` under the same session id; the
192
+ * later turns stay a branch (`branch.branchId`) that `fork({ branchId })` recovers.
193
+ * @param {Map['session.rewind']['params']} params @returns {Promise<Map['session.rewind']['result']>}
194
+ */
195
+ rewind: params => client.request('session.rewind', params),
196
+ /**
197
+ * Restarts a live root's native process on its own conversation and configuration at the idle
198
+ * barrier (capability `session.reload`, §12.8); id, history and receipts stay. Sent once: repeat
199
+ * the same `requestId` after a lost answer.
200
+ * @param {Map['session.reload']['params']} params @returns {Promise<Map['session.reload']['result']>}
201
+ */
202
+ reload: params => client.request('session.reload', params),
203
+ /**
204
+ * The ALP CLI command that follows the session in a terminal (capability `session.resumeCommand`,
205
+ * §12.8), built by alpd: for the clipboard only, never to run.
206
+ * @param {Map['session.resumeCommand']['params']} params @returns {Promise<Map['session.resumeCommand']['result']>}
207
+ */
208
+ resumeCommand: params => client.request('session.resumeCommand', params),
209
+ /**
210
+ * The slash commands and skills the session's composer offers after "/" (capability `session.commands`, §12.12).
211
+ * @param {Map['session.commands']['params']} params @returns {Promise<Map['session.commands']['result']>}
212
+ */
213
+ commands: params => client.request('session.commands', params),
214
+ /**
215
+ * Changes a live root's model, effort or team (capability `session.configure.live`, §12.9) at the
216
+ * idle barrier, through a restart of its native process on the same conversation; `configured` says
217
+ * what it runs with now. Sent once: repeat the same `requestId` after a lost answer. A change to
218
+ * another runtime is refused (1005 runtime_mismatch, `data.action: 'session.create'`).
219
+ * @param {Map['session.configure']['params'] & { requestId: string; ifGeneration: string }} params @returns {Promise<Map['session.configure']['result']>}
220
+ */
221
+ configure: params => client.request('session.configure', params),
222
+ /**
223
+ * What a change of model, effort, team or mode would run a live root with, and whether it would be
224
+ * taken now (capability `session.configure.live`, §12.9). Reads only.
225
+ * @param {Map['session.configure.preview']['params']} params @returns {Promise<Map['session.configure.preview']['result']>}
226
+ */
227
+ configurePreview: params => client.request('session.configure.preview', params),
228
+ };
229
+ }
@@ -0,0 +1,61 @@
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, options) {
9
+ const events = options.capabilities.includes('terminal.watch') && !!connection.onNotification;
10
+ let closed = false;
11
+ let watchId = '';
12
+ let cursor = '';
13
+ let again = false;
14
+ /** @type {Promise<void> | undefined} */ let refreshing;
15
+ // One newest token per watchId; bounded even when the host sends malformed/stale traffic.
16
+ /** @type {Map<string,string>} */ const pending = new Map();
17
+ const off = connection.onNotification?.((method, params) => {
18
+ if (closed || !events || method !== 'terminal.changed' || !/^[0-9a-f]{32}$/.test(params?.watchId) || !/^[0-9a-f]{32}$/.test(params?.cursor)) return;
19
+ if (pending.size >= 4 && !pending.has(params.watchId)) pending.delete(pending.keys().next().value ?? '');
20
+ pending.set(params.watchId, params.cursor);
21
+ if (params.watchId === watchId && params.cursor !== cursor) { again = true; void refresh(); }
22
+ });
23
+ function refresh() {
24
+ if (closed) return Promise.resolve();
25
+ if (refreshing) return refreshing;
26
+ refreshing = (async () => {
27
+ do {
28
+ again = false;
29
+ try {
30
+ const result = await connection.request(events ? 'terminal.watch' : 'terminal.list', { ...(options.workspaceId ? { workspaceId: options.workspaceId } : {}), ...(events && cursor ? { after: cursor } : {}) });
31
+ if (closed) return;
32
+ if (!Array.isArray(result?.terminals)) throw new Error('Invalid terminal directory snapshot');
33
+ if (events) {
34
+ 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');
35
+ watchId = result.watchId;
36
+ cursor = result.cursor;
37
+ again = pending.has(watchId) && pending.get(watchId) !== cursor;
38
+ pending.clear();
39
+ }
40
+ options.onSnapshot(result.terminals);
41
+ } catch (error) { options.onError?.(error); return; }
42
+ } while (again && !closed);
43
+ })().finally(() => { refreshing = undefined; });
44
+ return refreshing;
45
+ }
46
+ const timer = events ? undefined : setInterval(() => { void refresh(); }, options.pollMs ?? 5000);
47
+ let offClose = () => {};
48
+ /** @param {boolean} [unwatch] */
49
+ function close(unwatch = true) {
50
+ if (closed) return;
51
+ closed = true;
52
+ if (timer !== undefined) clearInterval(timer);
53
+ off?.(); offClose(); pending.clear();
54
+ if (events && unwatch) void connection.request('terminal.unwatch', {}).catch(() => {});
55
+ }
56
+ offClose = connection.onClose(() => close(false));
57
+ if (closed) offClose();
58
+ options.onMode?.(events ? 'events' : 'polling');
59
+ const ready = refresh();
60
+ return { ready, refresh, close, mode: events ? 'events' : 'polling' };
61
+ }
package/src/service.js CHANGED
@@ -3,6 +3,7 @@ import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { runCommand } from './command.js';
6
+ import { entryCommand, stablePath } from '@anhlp/alp-core/packaged';
6
7
 
7
8
  /**
8
9
  * alpd as a user service (ALPD §37): a LaunchAgent on macOS, a systemd user unit on
@@ -53,11 +54,14 @@ export function serviceFor({ home, env = process.env, platform = process.platfor
53
54
  return undefined;
54
55
  }
55
56
 
56
- /** The service definition that runs `entry` with `execPath` for `home`. */
57
+ /** The service definition that runs `entry` (alpd.js with `execPath`, the native alpd, or an `alp` command) for `home`. */
57
58
  export function serviceDefinition(service, { home, entry, execPath = process.execPath, env = process.env }) {
58
59
  const variables = { ALP_HOME: path.resolve(home), PATH: env.PATH ?? '' };
59
60
  for (const name of CARRIED) if (env[name]) variables[name] = env[name];
60
- const program = [execPath, entry, '--service'];
61
+ // A script entry runs under execPath; an `alp` command runs `alp daemon run --service`. Inside the
62
+ // ALP bundle both name it through app/current, so `alp update` never leaves the service on a removed version.
63
+ const launch = entryCommand(stablePath(entry), 'daemon', ['--service'], stablePath(execPath));
64
+ const program = [launch.command, ...launch.args];
61
65
  const fatal = path.join(path.resolve(home), 'logs', 'alpd.service.log');
62
66
  if (service.kind === 'launchd') {
63
67
  return `<?xml version="1.0" encoding="UTF-8"?>
@@ -111,7 +115,7 @@ WantedBy=default.target
111
115
  `;
112
116
  }
113
117
 
114
- /** The program an installed definition runs: [node, alpd.js], or undefined when it is not installed. */
118
+ /** The program an installed definition runs: [node, alpd.js] or [alpd, --service] (native, t-81b0.9), or undefined when it is not installed. */
115
119
  export async function installedProgram(service) {
116
120
  const text = await readFile(service.file, 'utf8').catch(() => undefined);
117
121
  if (text === undefined) return undefined;