@anhlp/alp-protocol 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.
package/src/session.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { RuntimeKind } from './dto.js';
2
- import type { SessionSnapshot } from './events.js';
2
+ import type { SessionSnapshot, TurnAttention } from './events.js';
3
3
  /** MCP servers a client adds to the agent's own; the agent's names win no collisions. */
4
4
  export type HostMcpServer =
5
5
  | { type: 'stdio'; command: string; args?: string[]; env?: Record<string, string> }
@@ -22,7 +22,11 @@ export type SessionSpec = {
22
22
  persist?: boolean;
23
23
  /** Keep the native thread on disk though the session cannot be resumed: an assignment, which alp_recall may question later. */
24
24
  keepThread?: boolean;
25
- restore?: { agent: string; threadId: string; runtime?: string; model?: string; workflow?: { mode: string; maxPeers: number; supervisor?: boolean } };
25
+ restore?: {
26
+ agent: string; threadId: string; runtime?: string; model?: string; workflow?: { mode: string; maxPeers: number; supervisor?: boolean };
27
+ /** Claude: `threadId` does not exist yet and is made from this conversation on its first prompt (a fork or rewind, §12.7). */
28
+ base?: NativeBase;
29
+ };
26
30
  /** Where the native harness works, when not the project root: an assignment's git worktree. ALP files are still read from cwd. */
27
31
  workdir?: string;
28
32
  /** Explicit shared-assignment write scope; workdir points here while ALP uses cwd for its project. */
@@ -41,8 +45,17 @@ export type OpenOptions = {
41
45
 
42
46
  /** An image inline in a prompt (capability `prompt.images`): base64 data, never a path or URL; limits in PROMPT_IMAGES. */
43
47
  export type PromptImage = { type: 'image'; mimeType: 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp'; data: string; name?: string };
44
- /** Text parts carry `text`; image parts (`type: 'image'`) carry PromptImage's fields. */
45
- export type PromptContent = Array<{ type: string; text?: string; mimeType?: string; data?: string; name?: string }>;
48
+ /** A stored attachment in a prompt (capability `attachments`, §12.6): its opaque id only, never a path or URL. */
49
+ export type PromptAttachment = { type: 'attachment'; attachmentId: string };
50
+ /**
51
+ * What alpd hands a runtime for an attachment part once it validated and pinned it (§12.6, the
52
+ * runtime seam of issue #121 branch J): ids, display metadata and digest, never a host path. The
53
+ * runtime reads the bytes through the AttachmentReader alpd binds, and only for a session whose
54
+ * runtime declared it takes attachments.
55
+ */
56
+ export type RuntimeAttachment = { type: 'attachment'; attachmentId: string; name: string; mimeType: string; detectedMimeType: string; size: number; sha256: string };
57
+ /** Text parts carry `text`; image parts (`type: 'image'`) carry PromptImage's fields; attachment parts (`type: 'attachment'`) `attachmentId`. */
58
+ export type PromptContent = Array<{ type: string; text?: string; mimeType?: string; data?: string; name?: string; attachmentId?: string }>;
46
59
 
47
60
  export type PromptInput = {
48
61
  clientMessageId: string;
@@ -67,7 +80,7 @@ export type SessionPreview = {
67
80
  /** What became of one assignment an earlier alpd left running. */
68
81
  export type RecoveryOutcome = { assignmentId: string; agent: string; outcome: 'resumed' | 'parked' | 'failed'; error?: string };
69
82
 
70
- export type Pause = { since: string; by: string; reason: string; resetsAt?: string; /** When alpd last asked the runtime about the limit (ALPD §58). */ checkedAt?: string };
83
+ export type Pause = { since: string; by: string; reason: string; resetsAt?: string; /** Why alpd paused by itself other than a usage limit: its disk takes no writes (t-2831). */ cause?: 'disk'; /** When alpd last asked the runtime about the limit (ALPD §58). */ checkedAt?: string };
71
84
  export type PauseState = {
72
85
  all?: Pause;
73
86
  runtimes: Partial<Record<RuntimeKind, Pause>>;
@@ -91,7 +104,110 @@ export type SessionSummary = SessionSnapshot & {
91
104
  status: SessionStatus;
92
105
  title?: string;
93
106
  archived?: boolean;
107
+ /** A root's turn that ended unseen, until a client acknowledges it (capability `session.attention`). */
108
+ attention?: TurnAttention;
94
109
  lastError?: SessionError;
95
110
  createdAt?: string;
96
111
  updatedAt?: string;
112
+ /**
113
+ * Whether alpd can fork or rewind this session's conversation now, and why not (capabilities
114
+ * `session.fork` and `session.rewind`, §12.7). A single turn may still be refused: one in
115
+ * progress, the first one, or one alpd cannot map to the runtime's own history.
116
+ */
117
+ conversation?: {
118
+ fork: boolean; rewind: boolean;
119
+ /** Whether session.reload can restart this root's native process (capability `session.reload`, §12.8); the root must also be open and idle. */
120
+ reload?: boolean;
121
+ /** Whether session.configure can change this root's model, effort or team (capability `session.configure.live`, §12.9); the root must also be open and idle. */
122
+ configure?: boolean;
123
+ reason?: 'runtime_unsupported' | 'not_persistent' | 'not_root';
124
+ };
125
+ /** The session this root was forked from (§12.7). */
126
+ forkedFrom?: ForkProvenance;
127
+ /** Conversation branches rewinds set aside, oldest first; each stays recoverable with session.fork { branchId } (§12.7). */
128
+ branches?: ConversationBranch[];
129
+ };
130
+
131
+ /**
132
+ * A Claude conversation ALP has bound a session to but the runtime has not written yet (§12.7): the
133
+ * first prompt resumes `threadId` as a new session, keeping its history through the entry `at` (all of
134
+ * it when absent). Internal to alpd and its runtime; never accepted from a remote client.
135
+ */
136
+ export type NativeBase = { threadId: string; at?: string };
137
+
138
+ /** Where a fork came from (§12.7): the source root, and the turn its conversation was cut at. */
139
+ export type ForkProvenance = {
140
+ sessionId: string;
141
+ /** The cut: through this turn, or before it; absent when the whole conversation was taken. */
142
+ turnId?: string;
143
+ boundary: 'through' | 'before' | 'whole';
144
+ /** Set when the fork restored a branch a rewind set aside. */
145
+ branchId?: string;
146
+ at: string;
147
+ };
148
+
149
+ /** The later turns of a conversation a rewind set aside (§12.7): kept, never deleted, recoverable as a new session. */
150
+ export type ConversationBranch = {
151
+ branchId: string;
152
+ /** The turn the rewind went back to before; it and every later turn are in the branch. */
153
+ beforeTurnId: string;
154
+ /** How many turns the branch holds past the kept conversation. */
155
+ turns: number;
156
+ at: string;
157
+ };
158
+
159
+ /**
160
+ * The ALP CLI command that continues a session in a terminal (session.resumeCommand, §12.8): `argv`
161
+ * and the same command quoted for a POSIX shell and for Windows (cmd.exe). `display` is the one for
162
+ * the daemon host's own platform. Never a native runtime's command, credential, env or path.
163
+ */
164
+ export type ResumeCommand = { argv: string[]; posix: string; windows: string; display: string; platform: 'posix' | 'windows' };
165
+
166
+ /**
167
+ * The configuration a root runs with, or would after a change, as alpd resolved it (§12.9): its team,
168
+ * agent, runtime, model, effort and mode, and what they bring (delegation targets, ALP tools, MCP
169
+ * servers by name and kind, hook count, an instructions digest). Never a path, command or credential.
170
+ */
171
+ export type EffectiveConfig = {
172
+ team: string;
173
+ teamLabel?: string;
174
+ agent: string;
175
+ runtime: RuntimeKind;
176
+ model: string;
177
+ thinking: string;
178
+ mode: string;
179
+ /** The permission profile capping the agent's mode, when one does. */
180
+ permissionProfile?: string;
181
+ supervisor: boolean;
182
+ maxPeers?: number;
183
+ delegates: string[];
184
+ tools: string[];
185
+ mcpServers: Array<{ name: string; kind: 'stdio' | 'http' }>;
186
+ hooks: number;
187
+ instructionsSha?: string;
188
+ };
189
+
190
+ export type ConfigureChange = 'model' | 'thinking' | 'team' | 'mode';
191
+ export type ConfigureRefusal = 'session_busy' | 'session_closed' | 'not_root' | 'runtime_unsupported' | 'runtime_mismatch' | 'agent_mismatch' | 'permission_escalation' | 'team_not_found' | 'invalid_params' | 'not_persistent';
192
+
193
+ /** session.configure.preview (§12.9): the current and proposed configuration, and whether alpd would apply it now. */
194
+ export type ConfigurePreview = {
195
+ current: EffectiveConfig;
196
+ proposed: EffectiveConfig;
197
+ changes: ConfigureChange[];
198
+ /** Applying it restarts the root's native process on its own conversation. */
199
+ restart: boolean;
200
+ /** session.configure would take it now; a tree that gets busy meanwhile still refuses it. */
201
+ allowed: boolean;
202
+ reason?: ConfigureRefusal;
203
+ message?: string;
204
+ teams: Array<{ id: string; label: string; description?: string }>;
205
+ };
206
+
207
+ /** What a session.configure with model, thinking or team did (§12.9): what was asked, and what the root runs with now. */
208
+ export type ConfigureOutcome = {
209
+ status: 'applied' | 'unchanged';
210
+ requested: { model?: string; thinking?: string; team?: string; mode?: string };
211
+ effective: EffectiveConfig;
212
+ restarted: boolean;
97
213
  };
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', 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', sessionCommands: 'session.commands', 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,95 @@ 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.commands", "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
+ /**
102
+ * An agent's name: lower-case letters, digits and single hyphens, starting with a letter, 1 to 64
103
+ * characters. One pattern for `principal.agent` in daemon.hello and a gateway credential's agent.
104
+ */
105
+ export const AGENT_NAME = /^[a-z](?:[a-z0-9]|-(?=[a-z0-9])){0,63}$/;
106
+ /** An opaque terminal id (§12.10). @param {unknown} id */
107
+ export const isTerminalId = id => typeof id === 'string' && /^term_[0-9a-f]{32}$/.test(id);
108
+ /** Room an attachment.chunk request needs besides its base64 data. */
109
+ export const ATTACHMENT_CHUNK_OVERHEAD = 64 * 1024;
110
+ /**
111
+ * The decoded bytes one attachment.chunk may carry over frames of at most `maxFrame` bytes:
112
+ * `maxChunkBytes`, lowered so its base64 and ATTACHMENT_CHUNK_OVERHEAD fit. At least 1 byte.
113
+ * @param {number} [maxFrame] @param {number} [maxChunkBytes]
114
+ */
115
+ export function attachmentChunkBytes(maxFrame = MAX_FRAME, maxChunkBytes = ATTACHMENTS.maxChunkBytes) {
116
+ const fits = Math.floor((maxFrame - ATTACHMENT_CHUNK_OVERHEAD) * 3 / 4);
117
+ return Math.max(1, Math.min(maxChunkBytes, fits));
118
+ }
38
119
 
39
120
  /** 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
121
  const BLOCKED_DIRECTORIES = new Set(['.git', '.alp', '.ssh', '.gnupg', '.aws', '.azure', '.kube', '.docker', 'gcloud']);
@@ -85,3 +166,56 @@ export function blockedFilePath(relative) {
85
166
  export function encodeFrame(value) { return `${JSON.stringify(value)}\n`; }
86
167
  /** Parse one complete frame. Buffering and failure handling belong to the socket owner. @param {string} line @returns {unknown} */
87
168
  export function decodeFrame(line) { return JSON.parse(line); }
169
+
170
+ /**
171
+ * The command lines of session.resumeCommand (docs/protocol/alp-json-rpc-v1.md §12.8), built from argv
172
+ * so that every argument reaches the program as it is: for a POSIX shell (sh, bash, zsh) and for
173
+ * Windows cmd.exe, typed at its prompt and then read again by npm's `alp.cmd` shim (`%*`). An argument
174
+ * with a control character (a line break would run a pasted command early) is refused, and for cmd.exe
175
+ * one with `"`, `%` or `!` too: a quote inside an argument ends the shim's quoting and lets the rest
176
+ * run, and `%`/`!` expand variables in either parse, so no escaping keeps them (session ids have none).
177
+ */
178
+ const POSIX_SAFE = /^[A-Za-z0-9_@+:,./-]+$/;
179
+ const WINDOWS_SAFE = /^[A-Za-z0-9_@+:./\\-]+$/;
180
+ const assertArgument = (/** @type {unknown} */ arg) => {
181
+ if (typeof arg !== 'string') throw new TypeError('A command argument is a string');
182
+ if (/[\u0000-\u001f\u007f]/.test(arg)) throw new TypeError('A command argument has no control characters');
183
+ return arg;
184
+ };
185
+ /** One argument for a POSIX shell: as it is when nothing in it is special, else in single quotes. @param {string} arg */
186
+ export function quotePosix(arg) {
187
+ const text = assertArgument(arg);
188
+ return text && POSIX_SAFE.test(text) ? text : `'${text.replace(/'/g, `'\\''`)}'`;
189
+ }
190
+ /**
191
+ * One argument for cmd.exe: as it is when nothing in it is special; else in double quotes for the C
192
+ * runtime's split (backslashes before the closing quote doubled), with every cmd.exe metacharacter,
193
+ * the quotes too, escaped with ^ for the interactive parse; the shim's second parse then sees one
194
+ * quoted argument, inside which `&|<>()^` are literal. `"`, `%` and `!` are refused (see above).
195
+ * @param {string} arg
196
+ */
197
+ export function quoteWindows(arg) {
198
+ const text = assertArgument(arg);
199
+ if (text && WINDOWS_SAFE.test(text)) return text;
200
+ if (/["%!]/.test(text)) throw new TypeError('A cmd.exe command argument has no ", % or !');
201
+ const quoted = `"${text.replace(/(\\*)$/, '$1$1')}"`;
202
+ return quoted.replace(/([()\][^"`<>&|;, *?])/g, '^$1');
203
+ }
204
+ const SESSION_ID = /^[\w.:-]{1,128}$/;
205
+ /** argv as one command line. @param {string[]} argv @param {'posix' | 'windows'} platform */
206
+ export function commandLine(argv, platform) {
207
+ return argv.map(platform === 'windows' ? quoteWindows : quotePosix).join(' ');
208
+ }
209
+ /**
210
+ * session.resumeCommand's answer for a session: `alp attach <sessionId>`, which follows the session in
211
+ * a terminal (a closed one says how to send it a message). ALP keeps the orchestration, so it is never
212
+ * a native runtime's own resume command.
213
+ * @param {string} sessionId @param {'posix' | 'windows'} platform the daemon host's
214
+ */
215
+ export function resumeCommandOf(sessionId, platform) {
216
+ if (typeof sessionId !== 'string' || !SESSION_ID.test(sessionId)) throw new TypeError('A session id is [A-Za-z0-9_.:-], at most 128 characters');
217
+ const argv = ['alp', 'attach', sessionId];
218
+ const posix = commandLine(argv, 'posix');
219
+ const windows = commandLine(argv, 'windows');
220
+ return { argv, posix, windows, display: platform === 'windows' ? windows : posix, platform };
221
+ }