@anhlp/alp-protocol 0.0.1-beta.3 → 0.0.1-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/wire.js CHANGED
@@ -17,7 +17,7 @@ export const RPC_ERROR = Object.freeze({ parseError: -32700, invalidRequest: -32
17
17
  * Features a daemon lists in its daemon.hello result. A client uses a feature only when listed;
18
18
  * a daemon that lists none (one older than this list) has none of them. Unknown names are ignored.
19
19
  */
20
- export const CAPABILITY = Object.freeze({ attachAfter: 'attach.after', promptReceipts: 'prompt.receipts', extensionMethods: 'extension.methods', team: 'team', task: 'task', library: 'library', libraryProjectWrite: 'library.project.write', settingsLanguage: 'settings.language', sessionListPage: 'session.list.page', questionWatch: 'question.watch', questionWatchTurns: 'question.watch.turns', workspaceFiles: 'workspace.files', workspaceFilesRead: 'workspace.files.read', promptImages: 'prompt.images' });
20
+ export const CAPABILITY = Object.freeze({ sessionInterruptTurn: 'session.interrupt.turn', catalogLive: 'catalog.live', attachAfter: 'attach.after', sessionHistory: 'session.history', workspaceRegistry: 'workspace.registry', workspaceWorktree: 'workspace.worktree', workspaceGit: 'workspace.git', workspaceGitFacts: 'workspace.git.facts', promptReceipts: 'prompt.receipts', extensionMethods: 'extension.methods', team: 'team', task: 'task', library: 'library', libraryProjectWrite: 'library.project.write', settingsLanguage: 'settings.language', sessionListPage: 'session.list.page', questionWatch: 'question.watch', questionWatchTurns: 'question.watch.turns', sessionAttention: 'session.attention', workspaceFiles: 'workspace.files', workspaceFilesRead: 'workspace.files.read', workspaceFilesBrowse: 'workspace.files.browse', hostDirectories: 'host.directories', promptImages: 'prompt.images', schedule: 'schedule', attachments: 'attachments', sessionFork: 'session.fork', sessionRewind: 'session.rewind' , sessionReload: 'session.reload', sessionResumeCommand: 'session.resumeCommand', sessionConfigureLive: 'session.configure.live', terminal: 'terminal', terminalCapture: 'terminal.capture', terminalWatch: 'terminal.watch' });
21
21
  /**
22
22
  * What alpd takes as images in one session.prompt (capability `prompt.images`): inline base64 of
23
23
  * these types only, never a path or URL; at most `maxCount` of them, each at most `maxBytes`
@@ -27,14 +27,90 @@ export const CAPABILITY = Object.freeze({ attachAfter: 'attach.after', promptRec
27
27
  export const PROMPT_IMAGES = Object.freeze({ mimeTypes: Object.freeze(['image/png', 'image/jpeg', 'image/gif', 'image/webp']), maxCount: 8, maxBytes: 5 * 1024 * 1024, maxTotalBytes: 11 * 1024 * 1024 });
28
28
  /** Decoded bytes of base64 `data` (padding aware), without decoding it. @param {string} data */
29
29
  export const base64Bytes = data => Math.floor(data.length * 3 / 4) - (data.endsWith('==') ? 2 : data.endsWith('=') ? 1 : 0);
30
- export const RPC_METHODS = Object.freeze(["assignment.recall", "board.list", "catalog.get", "daemon.hello", "daemon.pause", "daemon.pauses", "daemon.resume", "daemon.shutdown", "daemon.status", "daemon.usage", "extension.register", "extension.unregister", "library.delete", "library.duplicate", "library.get", "library.list", "library.models", "library.rename", "library.save", "library.skills.set", "question.answer", "question.list", "question.watch", "session.archive", "session.attach", "session.close", "session.configure", "session.create", "session.get", "session.interrupt", "session.list", "session.log", "session.message", "session.preview", "session.prompt", "session.release", "session.rename", "session.status", "settings.language.get", "settings.language.set", "task.create", "task.gate.resolve", "task.list", "task.update", "team.list", "workspace.files.list", "workspace.files.read", "workspace.files.search"]);
30
+ export const RPC_METHODS = Object.freeze(["assignment.recall", "attachment.abort", "attachment.begin", "attachment.chunk", "attachment.commit", "attachment.delete", "attachment.get", "board.list", "catalog.get", "catalog.refresh", "daemon.hello", "daemon.pause", "daemon.pauses", "daemon.resume", "daemon.shutdown", "daemon.status", "daemon.usage", "extension.register", "extension.unregister", "host.directories.search", "library.delete", "library.duplicate", "library.get", "library.list", "library.models", "library.rename", "library.save", "library.skills.set", "project.list", "project.register", "project.remove", "question.answer", "question.list", "question.watch", "registry.owner", "registry.worktree", "schedule.cancel", "schedule.create", "schedule.get", "schedule.list", "session.archive", "session.attach", "session.attention.clear", "session.close", "session.compact", "session.configure", "session.configure.preview", "session.create", "session.fork", "session.get", "session.history", "session.interrupt", "session.list", "session.log", "session.message", "session.preview", "session.prompt", "session.release", "session.reload", "session.rename", "session.resumeCommand", "session.rewind", "session.status", "settings.language.get", "settings.language.set", "task.create", "task.gate.resolve", "task.list", "task.update", "team.list", "terminal.attach", "terminal.close", "terminal.capture", "terminal.create", "terminal.input", "terminal.list", "terminal.watch", "terminal.unwatch", "terminal.resize", "terminal.revoke", "workspace.files.find", "workspace.files.list", "workspace.files.preview", "workspace.files.read", "workspace.files.search", "workspace.get", "workspace.git.diff", "workspace.git.facts", "workspace.git.status", "workspace.list", "workspace.update", "workspace.worktree.create", "workspace.worktree.options", "workspace.worktree.remove"]);
31
31
 
32
32
  /**
33
33
  * Limits of workspace.files.list and workspace.files.read (capability `workspace.files.read`,
34
34
  * docs/protocol/alp-json-rpc-v1.md §12.4): a file of at most `maxReadBytes`, a listing of at most
35
- * `maxListEntries` entries, a relative path of at most `maxPathLength` characters.
35
+ * `maxListEntries` entries, a relative path of at most `maxPathLength` characters. With
36
+ * `workspace.files.browse` (§12.11): a preview of a file of at most `maxPreviewBytes`, sent in chunks
37
+ * of at most `maxPreviewChunkBytes` decoded (their base64 fits one MAX_FRAME), and pages of at most
38
+ * `maxFindEntries` names from workspace.files.find.
36
39
  */
37
- export const WORKSPACE_FILES = Object.freeze({ maxReadBytes: 1024 * 1024, maxListEntries: 1000, maxPathLength: 4096 });
40
+ export const WORKSPACE_FILES = Object.freeze({ maxReadBytes: 1024 * 1024, maxListEntries: 1000, maxPathLength: 4096, maxPreviewBytes: 50 * 1024 * 1024, maxPreviewChunkBytes: 8 * 1024 * 1024, maxFindEntries: 1000 });
41
+
42
+ /**
43
+ * Limits of workspace.git.status and workspace.git.diff (capability `workspace.git`,
44
+ * docs/protocol/alp-json-rpc-v1.md §12.5): one file's patch at most `maxFileBytes`, one page's
45
+ * patches at most `maxTotalBytes` (then `nextCursor`), at most `maxUntracked` untracked files with
46
+ * content, `maxStatusFiles` status rows, a base branch name of at most `maxRefLength` characters.
47
+ * A gateway may lower them; never raise them.
48
+ */
49
+ export const WORKSPACE_GIT = Object.freeze({ maxFileBytes: 1024 * 1024, maxTotalBytes: 2 * 1024 * 1024, maxUntracked: 200, maxStatusFiles: 1000, maxRefLength: 255 });
50
+
51
+ /**
52
+ * Limits of non-image attachments (capability `attachments`, docs/protocol/alp-json-rpc-v1.md
53
+ * §12.6): an object of at most `maxObjectBytes`; a prompt of at most `maxPerPrompt` attachments and
54
+ * `maxPromptBytes` together; chunks of at most `maxChunkBytes` decoded (lowered further by
55
+ * attachmentChunkBytes to fit a frame); `maxActiveUploads` incomplete uploads and
56
+ * `maxPrincipalBytes` stored per principal, `maxDaemonBytes` per daemon, retained references
57
+ * included. An incomplete upload expires after `uploadTimeoutMs`; an unreferenced committed object
58
+ * is purged after `unreferencedRetentionMs`, one whose references were all released after
59
+ * `releasedGraceMs`. A display name is at most `maxNameBytes` UTF-8 bytes. An operator or a gateway
60
+ * may lower them, never raise them; daemon.hello advertises the effective ones (`attachmentLimits`).
61
+ */
62
+ export const ATTACHMENTS = Object.freeze({
63
+ maxObjectBytes: 20 * 1024 * 1024,
64
+ maxPerPrompt: 8,
65
+ maxPromptBytes: 40 * 1024 * 1024,
66
+ maxChunkBytes: 256 * 1024,
67
+ maxActiveUploads: 2,
68
+ maxPrincipalBytes: 200 * 1024 * 1024,
69
+ maxDaemonBytes: 1024 * 1024 * 1024,
70
+ uploadTimeoutMs: 60 * 60 * 1000,
71
+ unreferencedRetentionMs: 24 * 60 * 60 * 1000,
72
+ releasedGraceMs: 7 * 24 * 60 * 60 * 1000,
73
+ maxNameBytes: 255,
74
+ });
75
+ /**
76
+ * Limits of terminals (capability `terminal`, docs/protocol/alp-json-rpc-v1.md §12.10): at most
77
+ * `maxPerPrincipal` running terminals per principal and `maxPerDaemon` per daemon; a
78
+ * terminal.input of at most `maxInputBytes` UTF-8 bytes; output events of at most
79
+ * `maxOutputFrameBytes` bytes of data; `replayBytes` of output kept per terminal for attach; a
80
+ * terminal ends after `idleMs` without input or output, after `maxLifetimeMs` in any case, and
81
+ * `reconnectMs` after its stream detached unless attached again. Sizes are `minCols`..`maxCols`
82
+ * columns and `minRows`..`maxRows` rows. An operator or a gateway may lower the first eight, never
83
+ * raise them; daemon.hello advertises the effective ones (`terminalLimits`).
84
+ */
85
+ export const TERMINAL = Object.freeze({
86
+ maxPerPrincipal: 4,
87
+ maxPerDaemon: 16,
88
+ maxInputBytes: 64 * 1024,
89
+ maxOutputFrameBytes: 64 * 1024,
90
+ replayBytes: 1024 * 1024,
91
+ idleMs: 30 * 60 * 1000,
92
+ maxLifetimeMs: 8 * 60 * 60 * 1000,
93
+ reconnectMs: 60 * 1000,
94
+ minCols: 2,
95
+ maxCols: 500,
96
+ minRows: 1,
97
+ maxRows: 200,
98
+ });
99
+ /** The TERMINAL limits a daemon.hello `terminalLimits` carries (the size bounds are fixed). */
100
+ export const TERMINAL_LIMIT_KEYS = Object.freeze(['maxPerPrincipal', 'maxPerDaemon', 'maxInputBytes', 'maxOutputFrameBytes', 'replayBytes', 'idleMs', 'maxLifetimeMs', 'reconnectMs']);
101
+ /** An opaque terminal id (§12.10). @param {unknown} id */
102
+ export const isTerminalId = id => typeof id === 'string' && /^term_[0-9a-f]{32}$/.test(id);
103
+ /** Room an attachment.chunk request needs besides its base64 data. */
104
+ export const ATTACHMENT_CHUNK_OVERHEAD = 64 * 1024;
105
+ /**
106
+ * The decoded bytes one attachment.chunk may carry over frames of at most `maxFrame` bytes:
107
+ * `maxChunkBytes`, lowered so its base64 and ATTACHMENT_CHUNK_OVERHEAD fit. At least 1 byte.
108
+ * @param {number} [maxFrame] @param {number} [maxChunkBytes]
109
+ */
110
+ export function attachmentChunkBytes(maxFrame = MAX_FRAME, maxChunkBytes = ATTACHMENTS.maxChunkBytes) {
111
+ const fits = Math.floor((maxFrame - ATTACHMENT_CHUNK_OVERHEAD) * 3 / 4);
112
+ return Math.max(1, Math.min(maxChunkBytes, fits));
113
+ }
38
114
 
39
115
  /** Directories whose whole content is refused: Git's, ALP's own configuration (its library overrides hold env values), and key and cloud-credential stores. */
40
116
  const BLOCKED_DIRECTORIES = new Set(['.git', '.alp', '.ssh', '.gnupg', '.aws', '.azure', '.kube', '.docker', 'gcloud']);
@@ -85,3 +161,56 @@ export function blockedFilePath(relative) {
85
161
  export function encodeFrame(value) { return `${JSON.stringify(value)}\n`; }
86
162
  /** Parse one complete frame. Buffering and failure handling belong to the socket owner. @param {string} line @returns {unknown} */
87
163
  export function decodeFrame(line) { return JSON.parse(line); }
164
+
165
+ /**
166
+ * The command lines of session.resumeCommand (docs/protocol/alp-json-rpc-v1.md §12.8), built from argv
167
+ * so that every argument reaches the program as it is: for a POSIX shell (sh, bash, zsh) and for
168
+ * Windows cmd.exe, typed at its prompt and then read again by npm's `alp.cmd` shim (`%*`). An argument
169
+ * with a control character (a line break would run a pasted command early) is refused, and for cmd.exe
170
+ * one with `"`, `%` or `!` too: a quote inside an argument ends the shim's quoting and lets the rest
171
+ * run, and `%`/`!` expand variables in either parse, so no escaping keeps them (session ids have none).
172
+ */
173
+ const POSIX_SAFE = /^[A-Za-z0-9_@+:,./-]+$/;
174
+ const WINDOWS_SAFE = /^[A-Za-z0-9_@+:./\\-]+$/;
175
+ const assertArgument = (/** @type {unknown} */ arg) => {
176
+ if (typeof arg !== 'string') throw new TypeError('A command argument is a string');
177
+ if (/[\u0000-\u001f\u007f]/.test(arg)) throw new TypeError('A command argument has no control characters');
178
+ return arg;
179
+ };
180
+ /** One argument for a POSIX shell: as it is when nothing in it is special, else in single quotes. @param {string} arg */
181
+ export function quotePosix(arg) {
182
+ const text = assertArgument(arg);
183
+ return text && POSIX_SAFE.test(text) ? text : `'${text.replace(/'/g, `'\\''`)}'`;
184
+ }
185
+ /**
186
+ * One argument for cmd.exe: as it is when nothing in it is special; else in double quotes for the C
187
+ * runtime's split (backslashes before the closing quote doubled), with every cmd.exe metacharacter,
188
+ * the quotes too, escaped with ^ for the interactive parse; the shim's second parse then sees one
189
+ * quoted argument, inside which `&|<>()^` are literal. `"`, `%` and `!` are refused (see above).
190
+ * @param {string} arg
191
+ */
192
+ export function quoteWindows(arg) {
193
+ const text = assertArgument(arg);
194
+ if (text && WINDOWS_SAFE.test(text)) return text;
195
+ if (/["%!]/.test(text)) throw new TypeError('A cmd.exe command argument has no ", % or !');
196
+ const quoted = `"${text.replace(/(\\*)$/, '$1$1')}"`;
197
+ return quoted.replace(/([()\][^"`<>&|;, *?])/g, '^$1');
198
+ }
199
+ const SESSION_ID = /^[\w.:-]{1,128}$/;
200
+ /** argv as one command line. @param {string[]} argv @param {'posix' | 'windows'} platform */
201
+ export function commandLine(argv, platform) {
202
+ return argv.map(platform === 'windows' ? quoteWindows : quotePosix).join(' ');
203
+ }
204
+ /**
205
+ * session.resumeCommand's answer for a session: `alp attach <sessionId>`, which follows the session in
206
+ * a terminal (a closed one says how to send it a message). ALP keeps the orchestration, so it is never
207
+ * a native runtime's own resume command.
208
+ * @param {string} sessionId @param {'posix' | 'windows'} platform the daemon host's
209
+ */
210
+ export function resumeCommandOf(sessionId, platform) {
211
+ if (typeof sessionId !== 'string' || !SESSION_ID.test(sessionId)) throw new TypeError('A session id is [A-Za-z0-9_.:-], at most 128 characters');
212
+ const argv = ['alp', 'attach', sessionId];
213
+ const posix = commandLine(argv, 'posix');
214
+ const windows = commandLine(argv, 'windows');
215
+ return { argv, posix, windows, display: platform === 'windows' ? windows : posix, platform };
216
+ }