@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,227 @@
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
+ request<T = any>(method: string, params?: unknown): Promise<T>;
5
+ }): {
6
+ /** @param {string} workspaceId @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['workspace.worktree.options']['result']>} */
7
+ worktreeOptions: (workspaceId: string) => Promise<import("@anhlp/alp-protocol").RpcMethodMap["workspace.worktree.options"]["result"]>;
8
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['workspace.worktree.create']['params']} params @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['workspace.worktree.create']['result']>} */
9
+ createWorktree: (params: import("@anhlp/alp-protocol").RpcMethodMap["workspace.worktree.create"]["params"]) => Promise<import("@anhlp/alp-protocol").RpcMethodMap["workspace.worktree.create"]["result"]>;
10
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['workspace.worktree.remove']['params']} params @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['workspace.worktree.remove']['result']>} */
11
+ removeWorktree: (params: import("@anhlp/alp-protocol").RpcMethodMap["workspace.worktree.remove"]["params"]) => Promise<import("@anhlp/alp-protocol").RpcMethodMap["workspace.worktree.remove"]["result"]>;
12
+ /** 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']>} */
13
+ gitStatus: (workspaceId: string) => Promise<import("@anhlp/alp-protocol").RpcMethodMap["workspace.git.status"]["result"]>;
14
+ /** 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']>} */
15
+ gitDiff: (params: import("@anhlp/alp-protocol").RpcMethodMap["workspace.git.diff"]["params"]) => Promise<import("@anhlp/alp-protocol").RpcMethodMap["workspace.git.diff"]["result"]>;
16
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['project.list']['params']} [params] @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['project.list']['result']>} */
17
+ projects: (params?: import("@anhlp/alp-protocol").RpcMethodMap["project.list"]["params"]) => Promise<import("@anhlp/alp-protocol").RpcMethodMap["project.list"]["result"]>;
18
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['workspace.list']['params']} [params] @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['workspace.list']['result']>} */
19
+ workspaces: (params?: import("@anhlp/alp-protocol").RpcMethodMap["workspace.list"]["params"]) => Promise<import("@anhlp/alp-protocol").RpcMethodMap["workspace.list"]["result"]>;
20
+ /** @param {string} workspaceId @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['workspace.get']['result']>} */
21
+ get: (workspaceId: string) => Promise<import("@anhlp/alp-protocol").RpcMethodMap["workspace.get"]["result"]>;
22
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['project.register']['params']} params @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['project.register']['result']>} */
23
+ register: (params: import("@anhlp/alp-protocol").RpcMethodMap["project.register"]["params"]) => Promise<import("@anhlp/alp-protocol").RpcMethodMap["project.register"]["result"]>;
24
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['project.remove']['params']} params @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['project.remove']['result']>} */
25
+ remove: (params: import("@anhlp/alp-protocol").RpcMethodMap["project.remove"]["params"]) => Promise<import("@anhlp/alp-protocol").RpcMethodMap["project.remove"]["result"]>;
26
+ /** @param {import('@anhlp/alp-protocol').RpcMethodMap['workspace.update']['params']} params @returns {Promise<import('@anhlp/alp-protocol').RpcMethodMap['workspace.update']['result']>} */
27
+ update: (params: import("@anhlp/alp-protocol").RpcMethodMap["workspace.update"]["params"]) => Promise<import("@anhlp/alp-protocol").RpcMethodMap["workspace.update"]["result"]>;
28
+ };
29
+ /** Canonical base64 of `bytes`, without Buffer or btoa, so it runs in browsers and Node alike. @param {Uint8Array} bytes */
30
+ export function base64Encode(bytes: Uint8Array): string;
31
+ /** Lowercase hex SHA-256 of `bytes` through WebCrypto (browsers' secure contexts, Node 19+). @param {Uint8Array} bytes */
32
+ export function sha256Hex(bytes: Uint8Array): Promise<string>;
33
+ /**
34
+ * Typed attachment methods (capability `attachments`, docs/protocol/alp-json-rpc-v1.md §12.6) and a
35
+ * chunked upload that keeps to the limits the daemon (or gateway) advertised. Mutations are sent
36
+ * once: `upload` resumes an interrupted upload by repeating its begin with the same requestId and
37
+ * continues from what the daemon holds.
38
+ * @param {{request<T = any>(method: string, params?: unknown): Promise<T>}} client
39
+ */
40
+ export function attachments(client: {
41
+ request<T = any>(method: string, params?: unknown): Promise<T>;
42
+ }): {
43
+ /** @param {Map['attachment.begin']['params']} params @returns {Promise<Map['attachment.begin']['result']>} */
44
+ begin: (params: import("@anhlp/alp-protocol").PrincipalContext & {
45
+ sessionId: string;
46
+ name: string;
47
+ size: number;
48
+ mimeType: string;
49
+ sha256?: string;
50
+ requestId: string;
51
+ }) => Promise<{
52
+ uploadId: string;
53
+ state: "uploading" | "committed";
54
+ received: number;
55
+ size: number;
56
+ maxChunkBytes: number;
57
+ expiresAt?: string;
58
+ attachmentId?: string;
59
+ }>;
60
+ /** @param {Map['attachment.chunk']['params']} params @returns {Promise<Map['attachment.chunk']['result']>} */
61
+ chunk: (params: import("@anhlp/alp-protocol").PrincipalContext & {
62
+ uploadId: string;
63
+ offset: number;
64
+ data: string;
65
+ }) => Promise<{
66
+ received: number;
67
+ size: number;
68
+ }>;
69
+ /** @param {Map['attachment.commit']['params']} params @returns {Promise<Map['attachment.commit']['result']>} */
70
+ commit: (params: import("@anhlp/alp-protocol").PrincipalContext & {
71
+ uploadId: string;
72
+ sha256: string;
73
+ }) => Promise<{
74
+ attachment: import("@anhlp/alp-protocol").AttachmentInfo;
75
+ }>;
76
+ /** @param {string} uploadId @returns {Promise<Map['attachment.abort']['result']>} */
77
+ abort: (uploadId: string) => Promise<{
78
+ aborted: true;
79
+ }>;
80
+ /** Metadata only (no bytes, no path). @param {string} attachmentId @returns {Promise<Map['attachment.get']['result']>} */
81
+ get: (attachmentId: string) => Promise<{
82
+ attachment: import("@anhlp/alp-protocol").AttachmentInfo;
83
+ }>;
84
+ /** Refused (1004 attachment_referenced) while a prompt references it. @param {string} attachmentId @returns {Promise<Map['attachment.delete']['result']>} */
85
+ delete: (attachmentId: string) => Promise<{
86
+ deleted: true;
87
+ }>;
88
+ /**
89
+ * Uploads `data` and commits it: begin (or resume, with the same requestId), chunks of at most
90
+ * the smaller of `maxChunkBytes` and what begin answered, commit with its SHA-256. A chunk
91
+ * refused `offset_mismatch` continues from the daemon's `received`. Returns the attachment.
92
+ * The returned promise exposes `.uploadId` once begun and `.abort(reason?: any)` to abort on alpd.
93
+ * @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
94
+ * @returns {Promise<Map['attachment.commit']['result']['attachment']> & { readonly uploadId?: string, abort(reason?: any): Promise<void> }}
95
+ */
96
+ upload({ sessionId, name, mimeType, data, requestId, sha256, maxChunkBytes, signal, onBegun, onProgress }: {
97
+ sessionId: string;
98
+ name: string;
99
+ mimeType: string;
100
+ data: Uint8Array;
101
+ requestId: string;
102
+ sha256?: string;
103
+ maxChunkBytes?: number;
104
+ signal?: AbortSignal;
105
+ onBegun?: (uploadId: string) => void;
106
+ onProgress?: (received: number, size: number) => void;
107
+ }): Promise<import("@anhlp/alp-protocol").AttachmentInfo> & {
108
+ readonly uploadId?: string;
109
+ abort(reason?: any): Promise<void>;
110
+ };
111
+ };
112
+ /**
113
+ * Typed conversation methods (capabilities `session.fork` and `session.rewind`, docs/protocol/
114
+ * 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
115
+ * once: keep `requestId` (and `ifGeneration`) to repeat the identical request after a timeout, which
116
+ * answers the first result with `duplicate: true`. After a rewind, attached clients get a
117
+ * `history.reset` event: drop cached history, fetch a new tail and attach with its generation.
118
+ * @param {{request<T = any>(method: string, params?: unknown): Promise<T>}} client
119
+ */
120
+ export function conversation(client: {
121
+ request<T = any>(method: string, params?: unknown): Promise<T>;
122
+ }): {
123
+ /**
124
+ * A new closed root whose conversation is the source root's through or before a turn (`boundary`),
125
+ * or a branch a rewind set aside (`branchId`); resume it with session.create { sessionId, resume: true }.
126
+ * Principal fields are set by a trusted gateway on its own connection, never by a remote client.
127
+ * @param {Map['session.fork']['params']} params @returns {Promise<Map['session.fork']['result']>}
128
+ */
129
+ fork: (params: import("@anhlp/alp-protocol").PrincipalContext & {
130
+ sessionId: string;
131
+ requestId: string;
132
+ ifGeneration: string;
133
+ boundary?: import("@anhlp/alp-protocol").ForkBoundary;
134
+ branchId?: string;
135
+ workspaceId?: string;
136
+ newSessionId?: string;
137
+ title?: string;
138
+ }) => Promise<{
139
+ session: import("@anhlp/alp-protocol").SessionSummary;
140
+ forkedFrom: import("@anhlp/alp-protocol").ForkProvenance;
141
+ duplicate?: true;
142
+ }>;
143
+ /**
144
+ * Continues the root's conversation from before `beforeTurnId` under the same session id; the
145
+ * later turns stay a branch (`branch.branchId`) that `fork({ branchId })` recovers.
146
+ * @param {Map['session.rewind']['params']} params @returns {Promise<Map['session.rewind']['result']>}
147
+ */
148
+ rewind: (params: {
149
+ sessionId: string;
150
+ requestId: string;
151
+ ifGeneration: string;
152
+ beforeTurnId: string;
153
+ }) => Promise<{
154
+ session: import("@anhlp/alp-protocol").SessionSummary;
155
+ generation: string;
156
+ branch: import("@anhlp/alp-protocol").ConversationBranch;
157
+ duplicate?: true;
158
+ }>;
159
+ /**
160
+ * Restarts a live root's native process on its own conversation and configuration at the idle
161
+ * barrier (capability `session.reload`, §12.8); id, history and receipts stay. Sent once: repeat
162
+ * the same `requestId` after a lost answer.
163
+ * @param {Map['session.reload']['params']} params @returns {Promise<Map['session.reload']['result']>}
164
+ */
165
+ reload: (params: {
166
+ sessionId: string;
167
+ requestId: string;
168
+ ifGeneration: string;
169
+ }) => Promise<{
170
+ session: import("@anhlp/alp-protocol").SessionSummary;
171
+ duplicate?: true;
172
+ }>;
173
+ /**
174
+ * The ALP CLI command that follows the session in a terminal (capability `session.resumeCommand`,
175
+ * §12.8), built by alpd: for the clipboard only, never to run.
176
+ * @param {Map['session.resumeCommand']['params']} params @returns {Promise<Map['session.resumeCommand']['result']>}
177
+ */
178
+ resumeCommand: (params: {
179
+ sessionId: string;
180
+ }) => Promise<import("@anhlp/alp-protocol").ResumeCommand>;
181
+ /**
182
+ * The slash commands and skills the session's composer offers after "/" (capability `session.commands`, §12.12).
183
+ * @param {Map['session.commands']['params']} params @returns {Promise<Map['session.commands']['result']>}
184
+ */
185
+ commands: (params: {
186
+ sessionId: string;
187
+ }) => Promise<{
188
+ commands: import("@anhlp/alp-protocol").SessionCommand[];
189
+ }>;
190
+ /**
191
+ * Changes a live root's model, effort or team (capability `session.configure.live`, §12.9) at the
192
+ * idle barrier, through a restart of its native process on the same conversation; `configured` says
193
+ * what it runs with now. Sent once: repeat the same `requestId` after a lost answer. A change to
194
+ * another runtime is refused (1005 runtime_mismatch, `data.action: 'session.create'`).
195
+ * @param {Map['session.configure']['params'] & { requestId: string; ifGeneration: string }} params @returns {Promise<Map['session.configure']['result']>}
196
+ */
197
+ configure: (params: {
198
+ sessionId: string;
199
+ mode?: string;
200
+ model?: string;
201
+ thinking?: string;
202
+ team?: string;
203
+ requestId?: string;
204
+ ifGeneration?: string;
205
+ } & {
206
+ requestId: string;
207
+ ifGeneration: string;
208
+ }) => Promise<{
209
+ session: import("@anhlp/alp-protocol").SessionSnapshot | import("@anhlp/alp-protocol").SessionSummary;
210
+ configured?: import("@anhlp/alp-protocol").ConfigureOutcome;
211
+ duplicate?: true;
212
+ }>;
213
+ /**
214
+ * What a change of model, effort, team or mode would run a live root with, and whether it would be
215
+ * taken now (capability `session.configure.live`, §12.9). Reads only.
216
+ * @param {Map['session.configure.preview']['params']} params @returns {Promise<Map['session.configure.preview']['result']>}
217
+ */
218
+ configurePreview: (params: {
219
+ sessionId: string;
220
+ mode?: string;
221
+ model?: string;
222
+ thinking?: string;
223
+ team?: string;
224
+ }) => Promise<{
225
+ preview: import("@anhlp/alp-protocol").ConfigurePreview;
226
+ }>;
227
+ };
@@ -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
+ };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * A timeout option as a setTimeout delay. `undefined` means no timer: no timeout given, Infinity,
3
+ * or a wait longer than any timer can (about 24.8 days). Anything that is not a non-negative
4
+ * number is a TypeError, so a typo cannot turn into an instant timeout.
5
+ * @param {unknown} value
6
+ * @param {string} [name]
7
+ * @returns {number | undefined}
8
+ */
9
+ export function timerDelay(value: unknown, name?: string): number | undefined;
10
+ /** The longest delay setTimeout honours; a longer one fires at once, in browsers, Node and Hermes. */
11
+ export const MAX_TIMER_MS: 2147483647;
@@ -0,0 +1,11 @@
1
+ // packages/client/src/rpc/timers.js
2
+ var MAX_TIMER_MS = 2147483647;
3
+ function timerDelay(value, name = "timeoutMs") {
4
+ if (value === void 0 || value === Infinity) return void 0;
5
+ if (typeof value !== "number" || Number.isNaN(value) || value < 0) throw new TypeError(`${name} must be a non-negative number of milliseconds`);
6
+ return value > MAX_TIMER_MS ? void 0 : value;
7
+ }
8
+ export {
9
+ MAX_TIMER_MS,
10
+ timerDelay
11
+ };
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Where and how alpd for `home` is defined as a service on `platform`, or undefined
3
+ * where ALP has no service support. Each ALP_HOME gets its own service.
4
+ */
5
+ export function serviceFor({ home, env, platform, uid }: {
6
+ home: any;
7
+ env?: NodeJS.ProcessEnv | undefined;
8
+ platform?: NodeJS.Platform | undefined;
9
+ uid?: number | undefined;
10
+ }): {
11
+ kind: string;
12
+ name: string;
13
+ file: string;
14
+ install: (string | string[] | {
15
+ ignore: boolean;
16
+ })[][];
17
+ start: (string | string[])[][];
18
+ uninstall: (string | string[] | {
19
+ ignore: boolean;
20
+ })[][];
21
+ afterUninstall?: undefined;
22
+ } | {
23
+ kind: string;
24
+ name: string;
25
+ file: string;
26
+ install: (string | string[])[][];
27
+ start: (string | string[])[][];
28
+ uninstall: (string | string[] | {
29
+ ignore: boolean;
30
+ })[][];
31
+ afterUninstall: (string | string[] | {
32
+ ignore: boolean;
33
+ })[][];
34
+ } | undefined;
35
+ /** The service definition that runs `entry` (alpd.js with `execPath`, the native alpd, or an `alp` command) for `home`. */
36
+ export function serviceDefinition(service: any, { home, entry, execPath, env }: {
37
+ home: any;
38
+ entry: any;
39
+ execPath?: string | undefined;
40
+ env?: NodeJS.ProcessEnv | undefined;
41
+ }): string;
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
+ export function installedProgram(service: any): Promise<any[] | undefined>;
44
+ /** Writes the definition and loads it, which starts alpd. */
45
+ export function installService(service: any, options: any, run?: typeof runCommand): Promise<void>;
46
+ /** Starts an installed service's alpd. */
47
+ export function startService(service: any, run?: typeof runCommand): Promise<void>;
48
+ /** Unloads the service, which stops its alpd, and removes the definition; false when none was installed. */
49
+ export function uninstallService(service: any, run?: typeof runCommand): Promise<boolean>;
50
+ import { runCommand } from './command.js';