@operad-io/shell 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/package.json +21 -4
  4. package/src/index.ts +461 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yinghai Zhao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ # @operad-io/shell
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **The base stage plugin.** Provides `shell/command`, `shell/check` and `shell/probe`: run one shell line, run a list of lines that stops at the first failure, and a probe a wait can call.
4
+
5
+ This package is part of [operad](https://github.com/operad-io/operad). Most people install only [`@operad-io/cli`](https://www.npmjs.com/package/@operad-io/cli).
6
+
7
+ ## Documentation
8
+
9
+ - User guide: [docs/user/index.md](https://github.com/operad-io/operad/blob/main/docs/user/index.md)
10
+ - Website: <https://operad.io>
11
+ - Developer reference: `REFERENCE.md` in this directory
12
+
13
+ MIT licensed.
package/package.json CHANGED
@@ -1,6 +1,23 @@
1
1
  {
2
2
  "name": "@operad-io/shell",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": "./src/index.ts"
7
+ },
8
+ "dependencies": {
9
+ "@operad-io/engine": "0.1.0"
10
+ },
11
+ "description": "operad: the shell plugin's command and check steps",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/operad-io/operad.git",
15
+ "directory": "packages/shell"
16
+ },
17
+ "license": "MIT",
18
+ "files": [
19
+ "src",
20
+ "README.md",
21
+ "LICENSE"
22
+ ]
23
+ }
package/src/index.ts ADDED
@@ -0,0 +1,461 @@
1
+ /**
2
+ * The base plugin installed with operad: it runs a shell line, a list of
3
+ * checks, and a probe the kernel's `wait` step can poll. The kernel never runs
4
+ * a command itself.
5
+ */
6
+
7
+ import pkg from "../package.json" with { type: "json" };
8
+ import { createHash } from "node:crypto";
9
+ import { stat } from "node:fs/promises";
10
+ import { definePlugin, paramsObject, type PluginLogger, type PluginStepResult, type StepContext } from "@operad-io/engine";
11
+ import {
12
+ runLine,
13
+ type Clock,
14
+ type LineOutcome,
15
+ } from "@operad-io/engine/platform";
16
+
17
+ function lineParam(params: Record<string, unknown>, at: string): string {
18
+ const line = params.line;
19
+ if (typeof line !== "string" || line.trim().length === 0) {
20
+ throw new Error(`${at}: params.line: must be a non-empty string`);
21
+ }
22
+ return line;
23
+ }
24
+
25
+ function cwdParam(ctx: StepContext, params: Record<string, unknown>, at: string): string {
26
+ const cwd = params.cwd;
27
+ if (cwd === undefined) return ctx.cwd;
28
+ if (typeof cwd !== "string" || cwd.length === 0) {
29
+ throw new Error(`${at}: params.cwd: must be a non-empty string`);
30
+ }
31
+ return cwd;
32
+ }
33
+
34
+ function timeoutParam(
35
+ params: Record<string, unknown>,
36
+ at: string,
37
+ ): { readonly ms: number | undefined; readonly secs: number | undefined } {
38
+ const secs = params.timeoutSecs;
39
+ if (secs === undefined) return { ms: undefined, secs: undefined };
40
+ if (typeof secs !== "number" || !Number.isFinite(secs) || secs < 0) {
41
+ throw new Error(`${at}: params.timeoutSecs: must be zero or more seconds`);
42
+ }
43
+ return { ms: secs * 1000, secs };
44
+ }
45
+
46
+ function stallParam(
47
+ params: Record<string, unknown>,
48
+ at: string,
49
+ ): { readonly ms: number | undefined; readonly secs: number | undefined } {
50
+ const secs = params.stallSecs;
51
+ if (secs === undefined) return { ms: undefined, secs: undefined };
52
+ if (typeof secs !== "number" || !Number.isFinite(secs) || secs <= 0) {
53
+ throw new Error(`${at}: params.stallSecs: must be a positive number of seconds`);
54
+ }
55
+ return { ms: secs * 1000, secs };
56
+ }
57
+
58
+ function envParam(
59
+ params: Record<string, unknown>,
60
+ at: string,
61
+ ): Readonly<Record<string, string>> | undefined {
62
+ const env = params.env;
63
+ if (env === undefined) return undefined;
64
+ if (typeof env !== "object" || env === null || Array.isArray(env)) {
65
+ throw new Error(`${at}: params.env: must be an object of strings`);
66
+ }
67
+ const entries: [string, string][] = [];
68
+ for (const [key, value] of Object.entries(env)) {
69
+ if (typeof value !== "string") {
70
+ throw new Error(`${at}: params.env.${key}: must be a string`);
71
+ }
72
+ entries.push([key, value]);
73
+ }
74
+ return Object.fromEntries(entries);
75
+ }
76
+
77
+ /** The reason a directory cannot be a working directory, if it cannot. */
78
+ async function directoryError(cwd: string): Promise<string | undefined> {
79
+ try {
80
+ const info = await stat(cwd);
81
+ return info.isDirectory() ? undefined : `cwd is not a directory: ${cwd}`;
82
+ } catch {
83
+ return `cwd does not exist: ${cwd}`;
84
+ }
85
+ }
86
+
87
+ async function writeNote(logger: PluginLogger, note: string): Promise<string> {
88
+ return logger.write(note);
89
+ }
90
+
91
+ /**
92
+ * The log's size before this call writes, the byte where its output starts.
93
+ * A log that is not there yet starts at zero.
94
+ */
95
+ async function logStart(logger: PluginLogger): Promise<number> {
96
+ try {
97
+ return (await stat(logger.path)).size;
98
+ } catch {
99
+ return 0;
100
+ }
101
+ }
102
+
103
+ function failureData(
104
+ outcome: LineOutcome,
105
+ extra: Readonly<Record<string, unknown>>,
106
+ ): Record<string, unknown> {
107
+ return {
108
+ exitCode: outcome.exitCode,
109
+ signal: outcome.signal,
110
+ log: outcome.log,
111
+ tail: outcome.tail,
112
+ ...extra,
113
+ };
114
+ }
115
+
116
+ function stallDuration(secs: number): string {
117
+ const minutes = secs / 60;
118
+ return Number.isInteger(minutes) && minutes >= 1 ? `${minutes} min` : `${secs}s`;
119
+ }
120
+
121
+ /** The last test file header, then the last lines, for a stall's reason. */
122
+ function stallLines(outcome: LineOutcome): readonly string[] {
123
+ const all = outcome.stallTail;
124
+ const header = [...all]
125
+ .reverse()
126
+ .find((line) => /\.(?:test|spec)\.[cm]?[jt]sx?:\s*$/.test(line));
127
+ const tail = outcome.tail.slice(-8);
128
+ return header === undefined || tail.includes(header) ? tail : [header, ...tail];
129
+ }
130
+
131
+ function stallData(
132
+ outcome: LineOutcome,
133
+ secs: number | undefined,
134
+ extra: Readonly<Record<string, unknown>> = {},
135
+ ): Record<string, unknown> {
136
+ const duration = secs === undefined ? "too long" : stallDuration(secs);
137
+ const lines = stallLines(outcome).join("\n");
138
+ return failureData(outcome, {
139
+ reason: "stall",
140
+ message: `check wrote nothing for ${duration}; last lines: ${lines}`,
141
+ ...(secs === undefined ? {} : { stallSecs: secs }),
142
+ ...extra,
143
+ });
144
+ }
145
+
146
+ function commandResult(
147
+ outcome: LineOutcome,
148
+ timeoutSecs: number | undefined,
149
+ stallSecs?: number | undefined,
150
+ ): PluginStepResult {
151
+ if (outcome.spawnError !== undefined) {
152
+ return {
153
+ result: "fail",
154
+ data: failureData(outcome, {
155
+ reason: "spawn",
156
+ message: outcome.spawnError,
157
+ }),
158
+ };
159
+ }
160
+ if (outcome.cancelled) {
161
+ return {
162
+ result: "interrupted",
163
+ data: failureData(outcome, { reason: "cancelled" }),
164
+ };
165
+ }
166
+ if (outcome.stalled) {
167
+ return { result: "fail", data: stallData(outcome, stallSecs) };
168
+ }
169
+ if (outcome.timedOut) {
170
+ const limit = timeoutSecs === undefined ? "" : ` after ${timeoutSecs}s`;
171
+ return {
172
+ result: "fail",
173
+ data: failureData(outcome, {
174
+ reason: "timeout",
175
+ message: `the command was stopped${limit}`,
176
+ }),
177
+ };
178
+ }
179
+ if (outcome.exitCode === 0) {
180
+ return { result: "pass", data: failureData(outcome, {}) };
181
+ }
182
+ const killed =
183
+ outcome.exitCode === null && outcome.signal !== null
184
+ ? `the command was killed by ${outcome.signal}`
185
+ : `the command exited ${String(outcome.exitCode)}`;
186
+ return {
187
+ result: "fail",
188
+ data: failureData(outcome, {
189
+ reason: outcome.exitCode === null ? "signal" : "exit",
190
+ message: killed,
191
+ }),
192
+ };
193
+ }
194
+
195
+ function probeId(runId: string, cwd: string, line: string): string {
196
+ return createHash("sha256")
197
+ .update(JSON.stringify([runId, cwd, line]))
198
+ .digest("hex");
199
+ }
200
+
201
+ /** Options for the shell plugin. A test injects a clock to control timeouts. */
202
+ export interface ShellPluginOptions {
203
+ readonly clock?: Clock | undefined;
204
+ }
205
+
206
+ export function createShellPlugin(options: ShellPluginOptions = {}) {
207
+ const clock = options.clock;
208
+ return definePlugin({
209
+ name: "shell",
210
+ kind: "stage",
211
+ version: pkg.version,
212
+ steps: [
213
+ {
214
+ name: "command",
215
+ results: ["pass", "fail", "interrupted"],
216
+ async run(ctx, params) {
217
+ const at = "shell/command";
218
+ const input = paramsObject(params, at);
219
+ const line = lineParam(input, at);
220
+ const cwd = cwdParam(ctx, input, at);
221
+ const env = envParam(input, at);
222
+ const timeout = timeoutParam(input, at);
223
+ const stall = stallParam(input, at);
224
+
225
+ const cwdProblem = await directoryError(cwd);
226
+ if (cwdProblem !== undefined) {
227
+ const log = await writeNote(ctx.logger, cwdProblem);
228
+ return {
229
+ result: "fail",
230
+ data: {
231
+ reason: "cwd",
232
+ message: cwdProblem,
233
+ exitCode: null,
234
+ log,
235
+ tail: [cwdProblem],
236
+ },
237
+ };
238
+ }
239
+
240
+ const outcome = await runLine({
241
+ line,
242
+ cwd,
243
+ env,
244
+ timeoutMs: timeout.ms,
245
+ stallMs: stall.ms,
246
+ signal: ctx.signal,
247
+ logger: ctx.logger,
248
+ clock,
249
+ });
250
+ return commandResult(outcome, timeout.secs, stall.secs);
251
+ },
252
+ },
253
+ {
254
+ name: "check",
255
+ results: ["pass", "fail", "interrupted"],
256
+ async run(ctx, params) {
257
+ const at = "shell/check";
258
+ const input = paramsObject(params, at);
259
+ const lines = input.lines;
260
+ if (
261
+ !Array.isArray(lines) ||
262
+ !lines.every(
263
+ (line): line is string =>
264
+ typeof line === "string" && line.trim().length > 0,
265
+ )
266
+ ) {
267
+ throw new Error(
268
+ `${at}: params.lines: must be an array of non-empty strings`,
269
+ );
270
+ }
271
+ const cwd = cwdParam(ctx, input, at);
272
+ const timeout = timeoutParam(input, at);
273
+ const stall = stallParam(input, at);
274
+ const start = await logStart(ctx.logger);
275
+
276
+ const cwdProblem = await directoryError(cwd);
277
+ if (cwdProblem !== undefined) {
278
+ const log = await writeNote(ctx.logger, cwdProblem);
279
+ return {
280
+ result: "fail",
281
+ data: {
282
+ reason: "cwd",
283
+ message: cwdProblem,
284
+ exitCode: null,
285
+ log,
286
+ logStart: start,
287
+ tail: [cwdProblem],
288
+ },
289
+ };
290
+ }
291
+
292
+ if (lines.length === 0) {
293
+ const log = await ctx.logger.write("");
294
+ return { result: "pass", data: { lines: 0, log, logStart: start, tail: [] } };
295
+ }
296
+
297
+ for (const [index, line] of lines.entries()) {
298
+ if (ctx.signal.aborted) {
299
+ // No line has written output yet: create the log the fact names,
300
+ // so the path is a file a reader can open.
301
+ const log = await writeNote(ctx.logger, "");
302
+ return {
303
+ result: "interrupted",
304
+ data: {
305
+ reason: "cancelled",
306
+ line,
307
+ lineNumber: index + 1,
308
+ log,
309
+ logStart: start,
310
+ tail: [],
311
+ },
312
+ };
313
+ }
314
+
315
+ const outcome = await runLine({
316
+ line,
317
+ cwd,
318
+ timeoutMs: timeout.ms,
319
+ stallMs: stall.ms,
320
+ signal: ctx.signal,
321
+ logger: ctx.logger,
322
+ clock,
323
+ });
324
+
325
+ if (outcome.cancelled) {
326
+ return {
327
+ result: "interrupted",
328
+ data: failureData(outcome, {
329
+ reason: "cancelled",
330
+ line,
331
+ lineNumber: index + 1,
332
+ logStart: start,
333
+ }),
334
+ };
335
+ }
336
+
337
+ if (outcome.stalled) {
338
+ return {
339
+ result: "fail",
340
+ data: stallData(outcome, stall.secs, {
341
+ line,
342
+ lineNumber: index + 1,
343
+ logStart: start,
344
+ }),
345
+ };
346
+ }
347
+
348
+ if (
349
+ outcome.spawnError !== undefined ||
350
+ outcome.timedOut ||
351
+ outcome.exitCode !== 0
352
+ ) {
353
+ const reason =
354
+ outcome.spawnError !== undefined
355
+ ? "spawn"
356
+ : outcome.timedOut
357
+ ? "timeout"
358
+ : outcome.exitCode === null
359
+ ? "signal"
360
+ : "exit";
361
+ const message =
362
+ outcome.spawnError ??
363
+ (outcome.timedOut
364
+ ? `check line ${index + 1} was stopped after ${String(timeout.secs)}s`
365
+ : outcome.exitCode === null
366
+ ? `check line ${index + 1} was killed by ${String(outcome.signal)}`
367
+ : `check line ${index + 1} exited ${String(outcome.exitCode)}`);
368
+ return {
369
+ result: "fail",
370
+ data: failureData(outcome, {
371
+ reason,
372
+ message,
373
+ line,
374
+ lineNumber: index + 1,
375
+ logStart: start,
376
+ }),
377
+ };
378
+ }
379
+ }
380
+
381
+ return {
382
+ result: "pass",
383
+ data: {
384
+ lines: lines.length,
385
+ log: ctx.logger.path,
386
+ logStart: start,
387
+ tail: [],
388
+ },
389
+ };
390
+ },
391
+ },
392
+ {
393
+ name: "probe",
394
+ results: ["ready", "waiting", "interrupted"],
395
+ async run(ctx, params) {
396
+ const at = "shell/probe";
397
+ const input = paramsObject(params, at);
398
+ const line = lineParam(input, at);
399
+ const cwd = cwdParam(ctx, input, at);
400
+ const timeout = timeoutParam(input, at);
401
+
402
+ const cwdProblem = await directoryError(cwd);
403
+ if (cwdProblem !== undefined) {
404
+ return {
405
+ result: "interrupted",
406
+ data: { reason: "cwd", message: cwdProblem },
407
+ };
408
+ }
409
+
410
+ const outcome = await runLine({
411
+ line,
412
+ cwd,
413
+ timeoutMs: timeout.ms,
414
+ signal: ctx.signal,
415
+ clock,
416
+ });
417
+ if (outcome.cancelled) {
418
+ return { result: "interrupted", data: { reason: "cancelled" } };
419
+ }
420
+ if (outcome.spawnError !== undefined) {
421
+ return {
422
+ result: "interrupted",
423
+ data: { reason: "spawn", message: outcome.spawnError },
424
+ };
425
+ }
426
+ if (outcome.timedOut) {
427
+ return {
428
+ result: "interrupted",
429
+ data: {
430
+ reason: "timeout",
431
+ message: `the probe was stopped after ${String(timeout.secs)}s`,
432
+ },
433
+ };
434
+ }
435
+
436
+ const exitCode = outcome.exitCode;
437
+ const id = probeId(ctx.runId, cwd, line);
438
+ const previous = await ctx.store.get("probe", id);
439
+ const data = { line, cwd, exitCode };
440
+ if (previous === undefined) {
441
+ await ctx.store.put("probe", id, data, "probe");
442
+ return { result: "waiting", data };
443
+ }
444
+
445
+ const before = previous.data.exitCode;
446
+ const previousCode = typeof before === "number" ? before : null;
447
+ if (previousCode !== exitCode) {
448
+ await ctx.store.put("probe", id, data, "probe");
449
+ return { result: "ready", data };
450
+ }
451
+ return { result: "waiting", data };
452
+ },
453
+ },
454
+ ],
455
+ check() {
456
+ return "ready";
457
+ },
458
+ });
459
+ }
460
+
461
+ export default createShellPlugin();