@melra/terminal-runtime 0.3.0-alpha.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,46 @@
1
+ # @melra/terminal-runtime
2
+
3
+ Bounded process execution for [MELRA](https://github.com/XAGI-Lab/melra):
4
+ one-shot `run`, plus `start`/`status`/`output`/`stop` for longer-lived processes.
5
+
6
+ ```bash
7
+ npm install @melra/terminal-runtime
8
+ ```
9
+
10
+ ```ts
11
+ import { TerminalOperationSchema } from "@melra/protocol";
12
+ import { TerminalRuntime } from "@melra/terminal-runtime";
13
+
14
+ const terminal = await TerminalRuntime.create({ root: workspaceRoot });
15
+ const result = await terminal.execute(
16
+ TerminalOperationSchema.parse({
17
+ kind: "terminal",
18
+ action: "run",
19
+ command: "git",
20
+ args: ["status", "--porcelain"],
21
+ }),
22
+ );
23
+ ```
24
+
25
+ Commands are spawned without a shell. Arguments are passed as an array, never
26
+ interpolated into a command line, so a value containing `;` or `$(...)` is an
27
+ argument rather than a second command. The working directory stays inside
28
+ `root`, and only environment variables you name in `allowedEnvironment` are
29
+ passed through.
30
+
31
+ Output is captured up to the operation's `maxOutputChars` and flagged
32
+ `truncated` past it, and every process runs under an `AbortSignal` so a duration
33
+ budget actually stops work rather than just reporting a timeout.
34
+
35
+ `redactTerminalOutput` strips credential-shaped values from captured output
36
+ before it is persisted — tokens, `Authorization` headers, and connection strings
37
+ show up in stdout more often than anyone expects.
38
+
39
+ Allowlisting decides which commands may run at all, and that lives in
40
+ [`@melra/policy-core`](https://www.npmjs.com/package/@melra/policy-core), not
41
+ here.
42
+
43
+ Requires Node.js 22 or newer. Full documentation:
44
+ [github.com/XAGI-Lab/melra](https://github.com/XAGI-Lab/melra)
45
+
46
+ Apache-2.0
@@ -0,0 +1,38 @@
1
+ import type { TerminalOperation } from "@melra/protocol";
2
+ export { quoteForCmd, resolveCommand } from "./resolve-command.js";
3
+ export type { ResolvedCommand } from "./resolve-command.js";
4
+ export interface TerminalRuntimeOptions {
5
+ root: string;
6
+ allowedEnvironment?: string[];
7
+ baseEnvironment?: NodeJS.ProcessEnv;
8
+ }
9
+ export declare function redactTerminalOutput(value: string): string;
10
+ export declare class TerminalRuntime {
11
+ readonly root: string;
12
+ readonly allowedEnvironment: Set<string>;
13
+ readonly baseEnvironment: NodeJS.ProcessEnv;
14
+ private readonly jobs;
15
+ private constructor();
16
+ static create(options: TerminalRuntimeOptions): Promise<TerminalRuntime>;
17
+ private resolveCwd;
18
+ private prepare;
19
+ private runForeground;
20
+ private startBackground;
21
+ /**
22
+ * Answers a prompt on a running job's stdin.
23
+ *
24
+ * This is a pipe, not a terminal. A program that asks `isatty` still sees a
25
+ * non-interactive session and may keep its non-interactive behaviour — reading
26
+ * a password without echo is the usual one, and it will not work here. A real
27
+ * PTY needs a native addon; this covers the case that does not.
28
+ *
29
+ * ponytail: pipe-only. Add `node-pty` behind an optional dependency if a task
30
+ * genuinely needs a program that refuses to run without a tty.
31
+ */
32
+ private sendInput;
33
+ private job;
34
+ private jobResult;
35
+ execute(operation: TerminalOperation, signal?: AbortSignal): Promise<Record<string, unknown>>;
36
+ close(): void;
37
+ }
38
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAGzD,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACnE,YAAY,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAE5D,MAAM,WAAW,sBAAsB;IACrC,IAAI,EAAE,MAAM,CAAC;IACb,kBAAkB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC9B,eAAe,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;CACrC;AAcD,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAK1D;AA+CD,qBAAa,eAAe;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,kBAAkB,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACzC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC,UAAU,CAAC;IAC5C,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAoC;IAEzD,OAAO;WAWM,MAAM,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAAC,eAAe,CAAC;YAIhE,UAAU;YAQV,OAAO;YA8CP,aAAa;YA+Db,eAAe;IAgF7B;;;;;;;;;;OAUG;IACH,OAAO,CAAC,SAAS;IA0BjB,OAAO,CAAC,GAAG;IASX,OAAO,CAAC,SAAS;IAuBX,OAAO,CACX,SAAS,EAAE,iBAAiB,EAC5B,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAoBnC,KAAK,IAAI,IAAI;CAOd"}
package/dist/index.js ADDED
@@ -0,0 +1,331 @@
1
+ // Copyright 2026 XAGI Labs Private Limited
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { spawn } from "node:child_process";
4
+ import { randomUUID } from "node:crypto";
5
+ import { realpath } from "node:fs/promises";
6
+ import { isAbsolute, relative, resolve, sep } from "node:path";
7
+ import { resolveCommand } from "./resolve-command.js";
8
+ export { quoteForCmd, resolveCommand } from "./resolve-command.js";
9
+ const SECRET_PATTERNS = [
10
+ /\bgh[opurs]_[A-Za-z0-9]{20,}\b/g,
11
+ /\b(?:sk|pk|api)[-_][a-z0-9_-]{16,}\b/gi,
12
+ /\bBearer\s+[A-Za-z0-9._~+/-]+=*\b/gi,
13
+ /\b(password|passwd|secret)\s*[:=]\s*\S+/gi,
14
+ ];
15
+ function inside(root, candidate) {
16
+ const rel = relative(root, candidate);
17
+ return rel === "" || (!rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel));
18
+ }
19
+ export function redactTerminalOutput(value) {
20
+ return SECRET_PATTERNS.reduce((current, pattern) => current.replace(pattern, "[REDACTED]"), value);
21
+ }
22
+ /**
23
+ * `spawn` reports a missing program as a bare `ENOENT` naming only the syscall,
24
+ * which reads as an internal fault rather than "that program is not installed".
25
+ */
26
+ function describeSpawnError(error, command) {
27
+ const code = error?.code;
28
+ if (code === "ENOENT")
29
+ return new Error(`terminal_command_not_found:${command}`);
30
+ if (code === "EACCES")
31
+ return new Error(`terminal_command_not_executable:${command}`);
32
+ return error instanceof Error ? error : new Error(String(error));
33
+ }
34
+ export class TerminalRuntime {
35
+ root;
36
+ allowedEnvironment;
37
+ baseEnvironment;
38
+ jobs = new Map();
39
+ constructor(options, root) {
40
+ this.root = root;
41
+ this.allowedEnvironment = new Set(options.allowedEnvironment ?? ["CI", "LANG", "LC_ALL", "NO_COLOR", "TERM"]);
42
+ this.baseEnvironment = options.baseEnvironment ?? process.env;
43
+ }
44
+ static async create(options) {
45
+ return new TerminalRuntime(options, await realpath(options.root));
46
+ }
47
+ async resolveCwd(cwd) {
48
+ const candidate = resolve(this.root, cwd ?? ".");
49
+ if (!inside(this.root, candidate))
50
+ throw new Error("cwd_outside_workspace");
51
+ const actual = await realpath(candidate);
52
+ if (!inside(this.root, actual))
53
+ throw new Error("cwd_outside_workspace");
54
+ return actual;
55
+ }
56
+ async prepare(operation) {
57
+ if (operation.command === undefined) {
58
+ throw new Error(`terminal_${operation.action}_requires_command`);
59
+ }
60
+ if (operation.command.includes("\0") || operation.args.some((arg) => arg.includes("\0"))) {
61
+ throw new Error("terminal_input_contains_null");
62
+ }
63
+ const cwd = await this.resolveCwd(operation.cwd);
64
+ const environment = {};
65
+ for (const name of ["PATH", "PATHEXT", "SYSTEMROOT", "WINDIR", "COMSPEC"]) {
66
+ if (this.baseEnvironment[name] !== undefined) {
67
+ environment[name] = this.baseEnvironment[name];
68
+ }
69
+ }
70
+ for (const name of this.allowedEnvironment) {
71
+ if (this.baseEnvironment[name] !== undefined) {
72
+ environment[name] = this.baseEnvironment[name];
73
+ }
74
+ }
75
+ for (const [name, value] of Object.entries(operation.env ?? {})) {
76
+ if (!this.allowedEnvironment.has(name)) {
77
+ throw new Error(`environment_variable_not_allowed:${name}`);
78
+ }
79
+ environment[name] = value;
80
+ }
81
+ const resolved = await resolveCommand(operation.command, operation.args, {
82
+ cwd,
83
+ path: environment["PATH"] ?? environment["Path"],
84
+ pathExt: environment["PATHEXT"],
85
+ comspec: this.baseEnvironment["COMSPEC"],
86
+ });
87
+ return {
88
+ command: operation.command,
89
+ args: operation.args,
90
+ file: resolved.file,
91
+ spawnArgs: resolved.args,
92
+ windowsVerbatimArguments: resolved.windowsVerbatimArguments,
93
+ executable: resolved.executable,
94
+ cwd,
95
+ environment,
96
+ timeoutMs: operation.timeoutMs,
97
+ maxOutputChars: operation.maxOutputChars,
98
+ interactive: operation.interactive,
99
+ };
100
+ }
101
+ async runForeground(prepared, signal) {
102
+ return await new Promise((resolvePromise, reject) => {
103
+ const child = spawn(prepared.file, prepared.spawnArgs, {
104
+ cwd: prepared.cwd,
105
+ env: prepared.environment,
106
+ shell: false,
107
+ windowsHide: true,
108
+ windowsVerbatimArguments: prepared.windowsVerbatimArguments,
109
+ stdio: ["ignore", "pipe", "pipe"],
110
+ signal,
111
+ });
112
+ let stdout = "";
113
+ let stderr = "";
114
+ let truncated = false;
115
+ let timedOut = false;
116
+ const append = (current, chunk) => {
117
+ const next = current + chunk.toString("utf8");
118
+ if (next.length > prepared.maxOutputChars) {
119
+ truncated = true;
120
+ return next.slice(0, prepared.maxOutputChars);
121
+ }
122
+ return next;
123
+ };
124
+ child.stdout.on("data", (chunk) => {
125
+ stdout = append(stdout, chunk);
126
+ });
127
+ child.stderr.on("data", (chunk) => {
128
+ stderr = append(stderr, chunk);
129
+ });
130
+ const timer = setTimeout(() => {
131
+ timedOut = true;
132
+ child.kill("SIGTERM");
133
+ setTimeout(() => child.kill("SIGKILL"), 1_000).unref();
134
+ }, prepared.timeoutMs);
135
+ timer.unref();
136
+ child.once("error", (error) => {
137
+ clearTimeout(timer);
138
+ reject(describeSpawnError(error, prepared.command));
139
+ });
140
+ child.once("close", (code, terminationSignal) => {
141
+ clearTimeout(timer);
142
+ resolvePromise({
143
+ command: prepared.command,
144
+ args: prepared.args,
145
+ cwd: relative(this.root, prepared.cwd) || ".",
146
+ exitCode: code,
147
+ signal: terminationSignal,
148
+ timedOut,
149
+ stdout: redactTerminalOutput(stdout),
150
+ stderr: redactTerminalOutput(stderr),
151
+ truncated,
152
+ success: code === 0 && !timedOut,
153
+ });
154
+ });
155
+ });
156
+ }
157
+ async startBackground(prepared) {
158
+ const id = randomUUID();
159
+ const child = spawn(prepared.file, prepared.spawnArgs, {
160
+ cwd: prepared.cwd,
161
+ env: prepared.environment,
162
+ shell: false,
163
+ windowsHide: true,
164
+ windowsVerbatimArguments: prepared.windowsVerbatimArguments,
165
+ stdio: [prepared.interactive ? "pipe" : "ignore", "pipe", "pipe"],
166
+ });
167
+ const timer = setTimeout(() => {
168
+ child.kill("SIGTERM");
169
+ setTimeout(() => child.kill("SIGKILL"), 1_000).unref();
170
+ }, prepared.timeoutMs);
171
+ timer.unref();
172
+ const job = {
173
+ id,
174
+ child,
175
+ command: prepared.command,
176
+ args: prepared.args,
177
+ cwd: prepared.cwd,
178
+ stdout: "",
179
+ stderr: "",
180
+ truncated: false,
181
+ startedAt: new Date().toISOString(),
182
+ timer,
183
+ };
184
+ const append = (current, chunk) => {
185
+ const next = current + chunk.toString("utf8");
186
+ if (next.length > prepared.maxOutputChars) {
187
+ job.truncated = true;
188
+ return next.slice(0, prepared.maxOutputChars);
189
+ }
190
+ return next;
191
+ };
192
+ child.stdout?.on("data", (chunk) => {
193
+ job.stdout = append(job.stdout, chunk);
194
+ });
195
+ child.stderr?.on("data", (chunk) => {
196
+ job.stderr = append(job.stderr, chunk);
197
+ });
198
+ child.once("error", (error) => {
199
+ job.error = error.message;
200
+ job.endedAt = new Date().toISOString();
201
+ clearTimeout(timer);
202
+ });
203
+ child.once("close", (exitCode, terminationSignal) => {
204
+ job.exitCode = exitCode;
205
+ job.signal = terminationSignal;
206
+ job.endedAt = new Date().toISOString();
207
+ clearTimeout(timer);
208
+ });
209
+ // `spawn` only reports a failed start asynchronously, so returning as soon
210
+ // as the call came back reported `started: true` for a command that never
211
+ // ran — the caller got a job id for a process that did not exist. Waiting
212
+ // for whichever of `spawn`/`error` fires first makes the reported start real.
213
+ try {
214
+ await new Promise((settled, failed) => {
215
+ child.once("spawn", settled);
216
+ child.once("error", failed);
217
+ });
218
+ }
219
+ catch (error) {
220
+ clearTimeout(timer);
221
+ throw describeSpawnError(error, prepared.command);
222
+ }
223
+ this.jobs.set(id, job);
224
+ return {
225
+ success: true,
226
+ started: true,
227
+ jobId: id,
228
+ pid: child.pid ?? null,
229
+ command: prepared.command,
230
+ executable: prepared.executable,
231
+ cwd: relative(this.root, prepared.cwd) || ".",
232
+ interactive: prepared.interactive,
233
+ };
234
+ }
235
+ /**
236
+ * Answers a prompt on a running job's stdin.
237
+ *
238
+ * This is a pipe, not a terminal. A program that asks `isatty` still sees a
239
+ * non-interactive session and may keep its non-interactive behaviour — reading
240
+ * a password without echo is the usual one, and it will not work here. A real
241
+ * PTY needs a native addon; this covers the case that does not.
242
+ *
243
+ * ponytail: pipe-only. Add `node-pty` behind an optional dependency if a task
244
+ * genuinely needs a program that refuses to run without a tty.
245
+ */
246
+ sendInput(operation) {
247
+ const job = this.job(operation);
248
+ if (operation.input === undefined) {
249
+ throw new Error("terminal_send_requires_input");
250
+ }
251
+ if (job.endedAt !== undefined)
252
+ throw new Error("terminal_job_not_running");
253
+ const stdin = job.child.stdin;
254
+ // `start` without `interactive: true` gets an ignored stdin, and writing to
255
+ // a closed one throws EPIPE asynchronously — which would surface as an
256
+ // unhandled error rather than a failed task.
257
+ if (stdin === null || stdin.destroyed || !stdin.writable) {
258
+ throw new Error("terminal_job_not_interactive");
259
+ }
260
+ const payload = operation.appendNewline && !operation.input.endsWith("\n")
261
+ ? `${operation.input}\n`
262
+ : operation.input;
263
+ stdin.write(payload);
264
+ return {
265
+ success: true,
266
+ sent: true,
267
+ bytes: Buffer.byteLength(payload),
268
+ ...this.jobResult(job, false),
269
+ };
270
+ }
271
+ job(operation) {
272
+ if (operation.jobId === undefined) {
273
+ throw new Error(`terminal_${operation.action}_requires_job_id`);
274
+ }
275
+ const job = this.jobs.get(operation.jobId);
276
+ if (job === undefined)
277
+ throw new Error("terminal_job_not_found");
278
+ return job;
279
+ }
280
+ jobResult(job, includeOutput) {
281
+ return {
282
+ jobId: job.id,
283
+ running: job.endedAt === undefined,
284
+ pid: job.child.pid ?? null,
285
+ command: job.command,
286
+ args: job.args,
287
+ cwd: relative(this.root, job.cwd) || ".",
288
+ startedAt: job.startedAt,
289
+ ...(job.endedAt === undefined ? {} : { endedAt: job.endedAt }),
290
+ ...(job.exitCode === undefined ? {} : { exitCode: job.exitCode }),
291
+ ...(job.signal === undefined ? {} : { signal: job.signal }),
292
+ ...(job.error === undefined ? {} : { error: job.error }),
293
+ truncated: job.truncated,
294
+ ...(includeOutput
295
+ ? {
296
+ stdout: redactTerminalOutput(job.stdout),
297
+ stderr: redactTerminalOutput(job.stderr),
298
+ }
299
+ : {}),
300
+ };
301
+ }
302
+ async execute(operation, signal) {
303
+ switch (operation.action) {
304
+ case "run":
305
+ return await this.runForeground(await this.prepare(operation), signal);
306
+ case "start":
307
+ return await this.startBackground(await this.prepare(operation));
308
+ case "status":
309
+ return this.jobResult(this.job(operation), false);
310
+ case "output":
311
+ return this.jobResult(this.job(operation), true);
312
+ case "send":
313
+ return this.sendInput(operation);
314
+ case "stop": {
315
+ const job = this.job(operation);
316
+ if (job.endedAt === undefined)
317
+ job.child.kill("SIGTERM");
318
+ return { stopped: true, ...this.jobResult(job, true) };
319
+ }
320
+ }
321
+ }
322
+ close() {
323
+ for (const job of this.jobs.values()) {
324
+ clearTimeout(job.timer);
325
+ if (job.endedAt === undefined)
326
+ job.child.kill("SIGTERM");
327
+ }
328
+ this.jobs.clear();
329
+ }
330
+ }
331
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,2CAA2C;AAC3C,sCAAsC;AAEtC,OAAO,EAAE,KAAK,EAAqB,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAE/D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEtD,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AASnE,MAAM,eAAe,GAAa;IAChC,iCAAiC;IACjC,wCAAwC;IACxC,qCAAqC;IACrC,2CAA2C;CAC5C,CAAC;AAEF,SAAS,MAAM,CAAC,IAAY,EAAE,SAAiB;IAC7C,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;IACtC,OAAO,GAAG,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,GAAG,EAAE,CAAC,IAAI,GAAG,KAAK,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC;AACzF,CAAC;AAED,MAAM,UAAU,oBAAoB,CAAC,KAAa;IAChD,OAAO,eAAe,CAAC,MAAM,CAC3B,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,EAAE,YAAY,CAAC,EAC5D,KAAK,CACN,CAAC;AACJ,CAAC;AAmBD;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AC,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,KAAK,CAAC,CAAC;YACpD,KAAK,QAAQ;gBACX,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,CAAC;YACnD,KAAK,MAAM;gBACT,OAAO,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;YACnC,KAAK,MAAM,CAAC,CAAC,CAAC;gBACZ,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;gBAChC,IAAI,GAAG,CAAC,OAAO,KAAK,SAAS;oBAAE,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;gBACzD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,IAAI,CAAC,EAAE,CAAC;YACzD,CAAC;QACH,CAAC;IACH,CAAC;IAED,KAAK;QACH,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,CAAC;YACrC,YAAY,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;YACxB,IAAI,GAAG,CAAC,OAAO,KAAK,SAAS;gBAAE,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAC3D,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;IACpB,CAAC;CACF"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=index.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.test.d.ts","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,148 @@
1
+ // Copyright 2026 XAGI Labs Private Limited
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { mkdtemp, rm } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { afterEach, describe, expect, it } from "vitest";
7
+ import { TerminalOperationSchema } from "@melra/protocol";
8
+ import { TerminalRuntime, redactTerminalOutput } from "./index.js";
9
+ const roots = [];
10
+ afterEach(async () => {
11
+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
12
+ });
13
+ describe("TerminalRuntime", () => {
14
+ it("runs executable and argument arrays without a shell", async () => {
15
+ const root = await mkdtemp(join(tmpdir(), "melra-terminal-"));
16
+ roots.push(root);
17
+ const runtime = await TerminalRuntime.create({ root });
18
+ const result = await runtime.execute(TerminalOperationSchema.parse({
19
+ kind: "terminal",
20
+ action: "run",
21
+ command: process.execPath,
22
+ args: ["-e", "process.stdout.write(process.argv[1])", "hello; touch nope"],
23
+ }));
24
+ expect(result.success).toBe(true);
25
+ expect(result.stdout).toBe("hello; touch nope");
26
+ });
27
+ it("redacts secret-shaped output", () => {
28
+ expect(redactTerminalOutput("password=hunter2 ghp_123456789012345678901234")).not.toContain("hunter2");
29
+ });
30
+ it("stops commands at the configured timeout", async () => {
31
+ const root = await mkdtemp(join(tmpdir(), "melra-terminal-"));
32
+ roots.push(root);
33
+ const runtime = await TerminalRuntime.create({ root });
34
+ const result = await runtime.execute(TerminalOperationSchema.parse({
35
+ kind: "terminal",
36
+ action: "run",
37
+ command: process.execPath,
38
+ args: ["-e", "setTimeout(() => {}, 10_000)"],
39
+ timeoutMs: 150,
40
+ }));
41
+ expect(result.timedOut).toBe(true);
42
+ expect(result.success).toBe(false);
43
+ });
44
+ it("supervises bounded background jobs and output", async () => {
45
+ const root = await mkdtemp(join(tmpdir(), "melra-terminal-"));
46
+ roots.push(root);
47
+ const runtime = await TerminalRuntime.create({ root });
48
+ const started = await runtime.execute(TerminalOperationSchema.parse({
49
+ kind: "terminal",
50
+ action: "start",
51
+ command: process.execPath,
52
+ args: [
53
+ "-e",
54
+ "process.stdout.write('background-ready'); setTimeout(() => {}, 150)",
55
+ ],
56
+ timeoutMs: 2_000,
57
+ }));
58
+ expect(started.started).toBe(true);
59
+ // The child writes its output and then exits on its own. How long that
60
+ // takes depends on process startup under CI load, so poll for completion
61
+ // rather than assuming it finishes within a fixed wall-clock delay.
62
+ const deadline = Date.now() + 10_000;
63
+ const readOutput = async () => runtime.execute(TerminalOperationSchema.parse({
64
+ kind: "terminal",
65
+ action: "output",
66
+ jobId: started.jobId,
67
+ }));
68
+ let output = await readOutput();
69
+ while (output.running === true && Date.now() < deadline) {
70
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, 25));
71
+ output = await readOutput();
72
+ }
73
+ expect(output.stdout).toContain("background-ready");
74
+ expect(output.running).toBe(false);
75
+ runtime.close();
76
+ }, 30_000);
77
+ it("answers a running job's prompt and refuses one that cannot be answered", async () => {
78
+ const root = await mkdtemp(join(tmpdir(), "melra-terminal-"));
79
+ roots.push(root);
80
+ const runtime = await TerminalRuntime.create({ root });
81
+ const script = "process.stdout.write('name? ');" +
82
+ "process.stdin.once('data', (d) => { process.stdout.write('hello ' + String(d).trim()); process.exit(0); })";
83
+ const start = (interactive) => runtime.execute(TerminalOperationSchema.parse({
84
+ kind: "terminal",
85
+ action: "start",
86
+ command: process.execPath,
87
+ args: ["-e", script],
88
+ interactive,
89
+ timeoutMs: 5_000,
90
+ }));
91
+ const interactive = await start(true);
92
+ const sent = await runtime.execute(TerminalOperationSchema.parse({
93
+ kind: "terminal",
94
+ action: "send",
95
+ jobId: interactive.jobId,
96
+ input: "melra",
97
+ }));
98
+ expect(sent.sent).toBe(true);
99
+ const deadline = Date.now() + 10_000;
100
+ const readOutput = async (jobId) => runtime.execute(TerminalOperationSchema.parse({
101
+ kind: "terminal",
102
+ action: "output",
103
+ jobId,
104
+ }));
105
+ let output = await readOutput(interactive.jobId);
106
+ while (output.running === true && Date.now() < deadline) {
107
+ await new Promise((done) => setTimeout(done, 25));
108
+ output = await readOutput(interactive.jobId);
109
+ }
110
+ expect(output.stdout).toContain("hello melra");
111
+ // Without `interactive`, stdin is ignored rather than piped. Writing to it
112
+ // would throw EPIPE asynchronously and surface as an unhandled error, so
113
+ // the refusal has to come first and name the reason.
114
+ const plain = await start(false);
115
+ await expect(runtime.execute(TerminalOperationSchema.parse({
116
+ kind: "terminal",
117
+ action: "send",
118
+ jobId: plain.jobId,
119
+ input: "melra",
120
+ }))).rejects.toThrow("terminal_job_not_interactive");
121
+ runtime.close();
122
+ }, 30_000);
123
+ it("names a missing program instead of surfacing a bare ENOENT", async () => {
124
+ const root = await mkdtemp(join(tmpdir(), "melra-terminal-"));
125
+ roots.push(root);
126
+ const runtime = await TerminalRuntime.create({ root });
127
+ await expect(runtime.execute(TerminalOperationSchema.parse({
128
+ kind: "terminal",
129
+ action: "run",
130
+ command: "melra-program-that-does-not-exist",
131
+ }))).rejects.toThrow("terminal_command_not_found");
132
+ runtime.close();
133
+ });
134
+ it("does not report a background job that never started", async () => {
135
+ // `spawn` reports a failed start asynchronously, so this used to resolve
136
+ // with `started: true` and a job id for a process that never existed.
137
+ const root = await mkdtemp(join(tmpdir(), "melra-terminal-"));
138
+ roots.push(root);
139
+ const runtime = await TerminalRuntime.create({ root });
140
+ await expect(runtime.execute(TerminalOperationSchema.parse({
141
+ kind: "terminal",
142
+ action: "start",
143
+ command: "melra-program-that-does-not-exist",
144
+ }))).rejects.toThrow("terminal_command_not_found");
145
+ runtime.close();
146
+ });
147
+ });
148
+ //# sourceMappingURL=index.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.test.js","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":"AAAA,2CAA2C;AAC3C,sCAAsC;AAEtC,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AACzD,OA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AO,CAAC,4BAA4B,CAAC,CAAC;QAChD,OAAO,CAAC,KAAK,EAAE,CAAC;IAClB,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,qDAAqD,EAAE,KAAK,IAAI,EAAE;QACnE,yEAAyE;QACzE,sEAAsE;QACtE,MAAM,IAAI,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,iBAAiB,CAAC,CAAC,CAAC;QAC9D,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACjB,MAAM,OAAO,GAAG,MAAM,eAAe,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;QACvD,MAAM,MAAM,CACV,OAAO,CAAC,OAAO,CACb,uBAAuB,CAAC,KAAK,CAAC;YAC5B,IAAI,EAAE,UAAU;YAChB,MAAM,EAAE,OAAO;YACf,OAAO,EAAE,mCAAmC;SAC7C,CAAC,CACH,CACF,CAAC,OAAO,CAAC,OAAO,CAAC,4BAA4B,CAAC,CAAC;QAChD,OAAO,CAAC,KAAK,EAAE,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -0,0 +1,45 @@
1
+ export interface ResolvedCommand {
2
+ /** Executable actually handed to `spawn`. */
3
+ file: string;
4
+ args: string[];
5
+ /** True when `args` is an already-quoted Windows command line. */
6
+ windowsVerbatimArguments: boolean;
7
+ /** Absolute path of the program the caller named, for the receipt. */
8
+ executable: string;
9
+ }
10
+ export interface ResolveCommandOptions {
11
+ cwd: string;
12
+ platform?: NodeJS.Platform;
13
+ path?: string | undefined;
14
+ pathExt?: string | undefined;
15
+ comspec?: string | undefined;
16
+ /** Seam for tests: decides whether a candidate path is a runnable file. */
17
+ exists?: (candidate: string) => Promise<boolean>;
18
+ }
19
+ /**
20
+ * Quote one argument so `cmd.exe /s /c` passes it through unchanged.
21
+ *
22
+ * Two layers have to agree. `cmd.exe` treats `& | < > ^ ( )` as syntax, but not
23
+ * inside double quotes, so quoting neutralises them. The program's own
24
+ * `CommandLineToArgvW` then unquotes, which is why backslashes before a quote
25
+ * are doubled and a trailing backslash run is doubled before the closing quote.
26
+ *
27
+ * `%` and `!` are the exception: `cmd.exe` expands those *inside* quotes, and no
28
+ * escape survives the round trip reliably. Rather than ship a
29
+ * quoting scheme with a hole in it, an argument containing them is refused —
30
+ * the allowlist would otherwise be bypassable by `npm install "%FOO%"`.
31
+ * Newlines are refused for the same reason: a command line cannot carry one.
32
+ */
33
+ export declare function quoteForCmd(value: string): string;
34
+ /**
35
+ * Turn an allowlisted command name into something `spawn` can actually start.
36
+ *
37
+ * On POSIX the name is already runnable and is returned untouched. On Windows it
38
+ * usually is not: `spawn` runs without a shell, so `npm` never resolves to
39
+ * `npm.cmd`, and a `.cmd` cannot be executed directly at all. That is the whole
40
+ * Windows deadlock — the bare name passed policy but could not run, and the
41
+ * `.cmd` spelling could run but was denied by policy. Resolving here (and
42
+ * normalising the extension in the policy allowlist) fixes both ends.
43
+ */
44
+ export declare function resolveCommand(command: string, args: string[], options: ResolveCommandOptions): Promise<ResolvedCommand>;
45
+ //# sourceMappingURL=resolve-command.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve-command.d.ts","sourceRoot":"","sources":["../src/resolve-command.ts"],"names":[],"mappings":"AAOA,MAAM,WAAW,eAAe;IAC9B,6CAA6C;IAC7C,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,kEAAkE;IAClE,wBAAwB,EAAE,OAAO,CAAC;IAClC,sEAAsE;IACtE,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,qBAAqB;IACpC,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC;IAC3B,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,2EAA2E;IAC3E,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;CAClD;AAoBD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAMjD;AAgDD;;;;;;;;;GASG;AACH,wBAAsB,cAAc,CAClC,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EAAE,EACd,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,eAAe,CAAC,CAiC1B"}
@@ -0,0 +1,126 @@
1
+ // Copyright 2026 XAGI Labs Private Limited
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { constants } from "node:fs";
4
+ import { access } from "node:fs/promises";
5
+ import { win32 } from "node:path";
6
+ /** What `cmd.exe` itself assumes when PATHEXT is unset. */
7
+ const DEFAULT_PATHEXT = ".COM;.EXE;.BAT;.CMD";
8
+ /**
9
+ * Batch shims cannot be executed by `CreateProcess`, so Node refuses to spawn
10
+ * them without a shell (CVE-2024-27980). They have to go through `cmd.exe`.
11
+ */
12
+ const BATCH_SUFFIXES = [".bat", ".cmd"];
13
+ async function isFile(candidate) {
14
+ try {
15
+ await access(candidate, constants.F_OK);
16
+ return true;
17
+ }
18
+ catch {
19
+ return false;
20
+ }
21
+ }
22
+ /**
23
+ * Quote one argument so `cmd.exe /s /c` passes it through unchanged.
24
+ *
25
+ * Two layers have to agree. `cmd.exe` treats `& | < > ^ ( )` as syntax, but not
26
+ * inside double quotes, so quoting neutralises them. The program's own
27
+ * `CommandLineToArgvW` then unquotes, which is why backslashes before a quote
28
+ * are doubled and a trailing backslash run is doubled before the closing quote.
29
+ *
30
+ * `%` and `!` are the exception: `cmd.exe` expands those *inside* quotes, and no
31
+ * escape survives the round trip reliably. Rather than ship a
32
+ * quoting scheme with a hole in it, an argument containing them is refused —
33
+ * the allowlist would otherwise be bypassable by `npm install "%FOO%"`.
34
+ * Newlines are refused for the same reason: a command line cannot carry one.
35
+ */
36
+ export function quoteForCmd(value) {
37
+ if (/[%!\r\n]/.test(value)) {
38
+ throw new Error("terminal_windows_argument_not_quotable");
39
+ }
40
+ const escaped = value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1");
41
+ return `"${escaped}"`;
42
+ }
43
+ function spellings(command, pathExt) {
44
+ const extensions = pathExt
45
+ .split(";")
46
+ .map((item) => item.trim())
47
+ .filter((item) => item.length > 0);
48
+ const lowered = command.toLowerCase();
49
+ // An explicit extension is honoured as written. Otherwise only the PATHEXT
50
+ // spellings are tried and never the bare name — npm ships a *POSIX* `npm`
51
+ // shell script next to `npm.cmd`, and preferring the bare name would find the
52
+ // one Windows cannot run.
53
+ return extensions.some((extension) => lowered.endsWith(extension.toLowerCase()))
54
+ ? [command]
55
+ // PATHEXT is conventionally uppercase, and Windows filenames are matched
56
+ // case-insensitively, so the appended suffix is lowercased purely so the
57
+ // path recorded in the receipt looks like the file on disk.
58
+ : extensions.map((extension) => `${command}${extension.toLowerCase()}`);
59
+ }
60
+ async function findExecutable(command, options, exists) {
61
+ const directoryQualified = /[\\/]/.test(command);
62
+ // The current directory is deliberately not searched for a bare command.
63
+ // Windows `CreateProcess` does search it, which would let a `git.cmd` dropped
64
+ // in the workspace shadow the real `git` that policy actually allowlisted.
65
+ //
66
+ // `win32` rather than the ambient path module: these are Windows paths whether
67
+ // or not the host is Windows, and pinning it is what lets the win32 branch be
68
+ // tested from any machine.
69
+ const directories = directoryQualified
70
+ ? [win32.resolve(options.cwd, win32.dirname(command))]
71
+ : (options.path ?? "")
72
+ .split(win32.delimiter)
73
+ .filter((item) => item.length > 0);
74
+ const name = directoryQualified ? win32.basename(command) : command;
75
+ for (const directory of directories) {
76
+ for (const spelling of spellings(name, options.pathExt ?? DEFAULT_PATHEXT)) {
77
+ const candidate = win32.resolve(options.cwd, win32.join(directory, spelling));
78
+ if (await exists(candidate))
79
+ return candidate;
80
+ }
81
+ }
82
+ return undefined;
83
+ }
84
+ /**
85
+ * Turn an allowlisted command name into something `spawn` can actually start.
86
+ *
87
+ * On POSIX the name is already runnable and is returned untouched. On Windows it
88
+ * usually is not: `spawn` runs without a shell, so `npm` never resolves to
89
+ * `npm.cmd`, and a `.cmd` cannot be executed directly at all. That is the whole
90
+ * Windows deadlock — the bare name passed policy but could not run, and the
91
+ * `.cmd` spelling could run but was denied by policy. Resolving here (and
92
+ * normalising the extension in the policy allowlist) fixes both ends.
93
+ */
94
+ export async function resolveCommand(command, args, options) {
95
+ const platform = options.platform ?? process.platform;
96
+ if (platform !== "win32") {
97
+ return {
98
+ file: command,
99
+ args,
100
+ windowsVerbatimArguments: false,
101
+ executable: command,
102
+ };
103
+ }
104
+ const found = await findExecutable(command, options, options.exists ?? isFile);
105
+ if (found === undefined) {
106
+ throw new Error(`terminal_command_not_found:${command}`);
107
+ }
108
+ const isBatch = BATCH_SUFFIXES.some((suffix) => found.toLowerCase().endsWith(suffix));
109
+ if (!isBatch) {
110
+ return {
111
+ file: found,
112
+ args,
113
+ windowsVerbatimArguments: false,
114
+ executable: found,
115
+ };
116
+ }
117
+ return {
118
+ file: options.comspec ?? "cmd.exe",
119
+ // `/d` skips AutoRun registry commands, `/s` makes cmd strip exactly the
120
+ // outer quote pair and leave everything between them alone.
121
+ args: ["/d", "/s", "/c", `"${[found, ...args].map(quoteForCmd).join(" ")}"`],
122
+ windowsVerbatimArguments: true,
123
+ executable: found,
124
+ };
125
+ }
126
+ //# sourceMappingURL=resolve-command.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve-command.js","sourceRoot":"","sources":["../src/resolve-command.ts"],"names":[],"mappings":"AAAA,2CAA2C;AAC3C,sCAAsC;AAEtC,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAsBlC,2DA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B,UAAU,EAAE,KAAK;KAClB,CAAC;AACJ,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=resolve-command.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve-command.test.d.ts","sourceRoot":"","sources":["../src/resolve-command.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,96 @@
1
+ // Copyright 2026 XAGI Labs Private Limited
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { describe, expect, it } from "vitest";
4
+ import { quoteForCmd, resolveCommand } from "./resolve-command.js";
5
+ /**
6
+ * These run the Windows branch on every host. The Windows breakage shipped green
7
+ * through a CI matrix that *includes* `windows-latest` precisely because nothing
8
+ * exercised the win32 path, so platform and filesystem are injected rather than
9
+ * detected.
10
+ */
11
+ const WINDOWS_FILES = new Set([
12
+ "C:\\Program Files\\nodejs\\npm.cmd",
13
+ "C:\\Program Files\\nodejs\\node.exe",
14
+ "C:\\Windows\\System32\\where.exe",
15
+ // npm also ships a POSIX shell script with no extension, right next to the
16
+ // shim. It is not runnable on Windows.
17
+ "C:\\Program Files\\nodejs\\npm",
18
+ ].map((item) => item.toLowerCase()));
19
+ const windows = {
20
+ cwd: "C:\\workspace",
21
+ platform: "win32",
22
+ path: "C:\\Program Files\\nodejs;C:\\Windows\\System32",
23
+ pathExt: ".COM;.EXE;.BAT;.CMD",
24
+ comspec: "C:\\Windows\\System32\\cmd.exe",
25
+ exists: async (candidate) => WINDOWS_FILES.has(candidate.toLowerCase()),
26
+ };
27
+ describe("resolveCommand", () => {
28
+ it("leaves POSIX commands untouched", async () => {
29
+ await expect(resolveCommand("git", ["status"], {
30
+ cwd: "/workspace",
31
+ platform: "linux",
32
+ })).resolves.toEqual({
33
+ file: "git",
34
+ args: ["status"],
35
+ windowsVerbatimArguments: false,
36
+ executable: "git",
37
+ });
38
+ });
39
+ it("resolves a bare Windows name to its .exe", async () => {
40
+ const resolved = await resolveCommand("node", ["-v"], windows);
41
+ expect(resolved.file.toLowerCase()).toBe("c:\\program files\\nodejs\\node.exe");
42
+ expect(resolved.args).toEqual(["-v"]);
43
+ expect(resolved.windowsVerbatimArguments).toBe(false);
44
+ });
45
+ it("prefers the .cmd shim over the extension-less POSIX script", async () => {
46
+ // The deadlock in miniature: `npm` is what policy allowlists, `npm.cmd` is
47
+ // what Windows can actually start, and `npm` (the sh script) is a trap.
48
+ const resolved = await resolveCommand("npm", ["install"], windows);
49
+ expect(resolved.executable.toLowerCase()).toBe("c:\\program files\\nodejs\\npm.cmd");
50
+ });
51
+ it("runs a batch shim through cmd.exe with the payload quoted", async () => {
52
+ const resolved = await resolveCommand("npm", ["run", "build"], windows);
53
+ expect(resolved.file).toBe("C:\\Windows\\System32\\cmd.exe");
54
+ expect(resolved.windowsVerbatimArguments).toBe(true);
55
+ expect(resolved.args.slice(0, 3)).toEqual(["/d", "/s", "/c"]);
56
+ expect(resolved.args[3]).toBe('""C:\\Program Files\\nodejs\\npm.cmd" "run" "build""');
57
+ });
58
+ it("keeps shell metacharacters inside the quoted argument", async () => {
59
+ // Without quoting, cmd.exe would treat `&&` as a separator and run a second
60
+ // program that policy never allowlisted.
61
+ const resolved = await resolveCommand("npm", ["install", "x && calc.exe"], windows);
62
+ expect(resolved.args[3]).toContain('"install" "x && calc.exe"');
63
+ });
64
+ it("refuses arguments cmd.exe would expand rather than quoting them wrongly", async () => {
65
+ await expect(resolveCommand("npm", ["install", "%USERPROFILE%"], windows)).rejects.toThrow("terminal_windows_argument_not_quotable");
66
+ });
67
+ it("reports a missing program by name instead of a bare ENOENT", async () => {
68
+ await expect(resolveCommand("rg", [], windows)).rejects.toThrow("terminal_command_not_found:rg");
69
+ });
70
+ it("does not search the working directory for a bare command", async () => {
71
+ // A `git.cmd` dropped in the workspace must not shadow the allowlisted git.
72
+ await expect(resolveCommand("git", [], {
73
+ ...windows,
74
+ exists: async (candidate) => candidate.toLowerCase() === "c:\\workspace\\git.cmd",
75
+ })).rejects.toThrow("terminal_command_not_found:git");
76
+ });
77
+ it("still honours an explicitly directory-qualified command", async () => {
78
+ const resolved = await resolveCommand(".\\tool", [], {
79
+ ...windows,
80
+ exists: async (candidate) => candidate.toLowerCase() === "c:\\workspace\\tool.exe",
81
+ });
82
+ expect(resolved.file.toLowerCase()).toBe("c:\\workspace\\tool.exe");
83
+ });
84
+ });
85
+ describe("quoteForCmd", () => {
86
+ it("escapes embedded quotes so the program sees them literally", () => {
87
+ expect(quoteForCmd('say "hi"')).toBe('"say \\"hi\\""');
88
+ });
89
+ it("doubles a trailing backslash run before the closing quote", () => {
90
+ expect(quoteForCmd("C:\\path\\")).toBe('"C:\\path\\\\"');
91
+ });
92
+ it("refuses a newline, which a command line cannot carry", () => {
93
+ expect(() => quoteForCmd("a\nb")).toThrow("terminal_windows_argument_not_quotable");
94
+ });
95
+ });
96
+ //# sourceMappingURL=resolve-command.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve-command.test.js","sourceRoot":"","sources":["../src/resolve-command.test.ts"],"names":[],"mappings":"AAAA,2CAA2C;AAC3C,sCAAsC;AAEtC,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEnE;;;;;GAKG;AACH,MAAM,aAAa,GAAG,IAAI,GAAG,CAC3B;IACE,oCAAoC;IACpC,qCAAqC;IACrC,kCAAkC;IAClC,2EAA2E;IAC3E,uCAAuC;IACvC,gCAAgC;CACjC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CACpC,CAAC;AAEF,MAAM,OAAO,GAAG;IACd,GAAG,EAAE,eAAe;IACpB,QAAQ,EAAE,OAAgB;IAC1B,IAAI,EAAE,iDAAiD;IACvD,OAAO,EAAE,qBAAqB;IAC9B,OAAO,EAAE,gCAAgC;IACzC,MAAM,EAAE,KAAK,EAAE,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EH,EAAE,CAAC,sDAAsD,EAAE,GAAG,EAAE;QAC9D,MAAM,CAAC,GAAG,EAAE,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CACvC,wCAAwC,CACzC,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@melra/terminal-runtime",
3
+ "version": "0.3.0-alpha.10",
4
+ "description": "Shell-free supervised terminal reference effect adapter for the MELRA kernel.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/XAGI-Lab/melra.git",
9
+ "directory": "packages/terminal-runtime"
10
+ },
11
+ "homepage": "https://github.com/XAGI-Lab/melra#readme",
12
+ "bugs": "https://github.com/XAGI-Lab/melra/issues",
13
+ "type": "module",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "dependencies": {
24
+ "@melra/protocol": "0.3.0-alpha.10"
25
+ },
26
+ "scripts": {
27
+ "build": "tsc -p tsconfig.json",
28
+ "clean": "rm -rf dist",
29
+ "test": "vitest run",
30
+ "typecheck": "tsc -p tsconfig.json --noEmit"
31
+ }
32
+ }