@tagma/sdk 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/sdk.ts CHANGED
@@ -5,10 +5,32 @@
5
5
 
6
6
  // ── Core engine ──
7
7
  export { runPipeline } from './engine';
8
- export type { EngineResult, RunPipelineOptions } from './engine';
8
+ export type { EngineResult, RunPipelineOptions, PipelineEvent } from './engine';
9
9
 
10
- // ── Schema: parse / resolve / load ──
11
- export { parseYaml, resolveConfig, expandTemplates, loadPipeline } from './schema';
10
+ // ── Pipeline runner (multi-pipeline lifecycle management) ──
11
+ export { PipelineRunner } from './pipeline-runner';
12
+ export type { PipelineRunnerStatus } from './pipeline-runner';
13
+
14
+ // ── Raw config CRUD (visual editor / YAML sync) ──
15
+ export {
16
+ createEmptyPipeline,
17
+ setPipelineField,
18
+ upsertTrack,
19
+ removeTrack,
20
+ moveTrack,
21
+ updateTrack,
22
+ upsertTask,
23
+ removeTask,
24
+ moveTask,
25
+ transferTask,
26
+ } from './config-ops';
27
+
28
+ // ── Raw config validation (real-time feedback) ──
29
+ export { validateRaw } from './validate-raw';
30
+ export type { ValidationError } from './validate-raw';
31
+
32
+ // ── Schema: parse / resolve / load / serialize / validate ──
33
+ export { parseYaml, resolveConfig, expandTemplates, loadPipeline, serializePipeline, deresolvePipeline, validateConfig } from './schema';
12
34
 
13
35
  // ── DAG ──
14
36
  export { buildDag } from './dag';
@@ -1,94 +1,94 @@
1
- import { watch } from 'chokidar';
2
- import { resolve, dirname } from 'path';
3
- import type { TriggerPlugin, TriggerContext } from '../types';
4
- import { parseDuration, validatePath } from '../utils';
5
-
6
- const IS_WINDOWS = process.platform === 'win32';
7
-
8
- function pathsEqual(a: string, b: string): boolean {
9
- return IS_WINDOWS ? a.toLowerCase() === b.toLowerCase() : a === b;
10
- }
11
-
12
- export const FileTrigger: TriggerPlugin = {
13
- name: 'file',
14
-
15
- watch(config: Record<string, unknown>, ctx: TriggerContext): Promise<unknown> {
16
- const filePath = config.path as string;
17
- if (!filePath) throw new Error(`file trigger: "path" is required`);
18
-
19
- const safePath = validatePath(filePath, ctx.workDir);
20
- const timeoutMs = config.timeout != null ? parseDuration(String(config.timeout)) : 0;
21
-
22
- return new Promise((resolve_p, reject) => {
23
- if (ctx.signal.aborted) {
24
- reject(new Error('Pipeline aborted'));
25
- return;
26
- }
27
-
28
- let settled = false;
29
- let timer: ReturnType<typeof setTimeout> | null = null;
30
-
31
- const dir = dirname(safePath);
32
- const watcher = watch(dir, {
33
- ignoreInitial: true,
34
- depth: 0,
35
- awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 50 },
36
- });
37
-
38
- const cleanup = () => {
39
- if (settled) return;
40
- settled = true;
41
- watcher.close().catch(() => { /* ignore */ });
42
- if (timer) clearTimeout(timer);
43
- ctx.signal.removeEventListener('abort', onAbort);
44
- };
45
-
46
- const onAbort = () => {
47
- cleanup();
48
- reject(new Error('Pipeline aborted'));
49
- };
50
-
51
- watcher.on('add', (addedPath: string) => {
52
- if (settled) return;
53
- if (pathsEqual(resolve(addedPath), safePath)) {
54
- cleanup();
55
- resolve_p({ path: safePath });
56
- }
57
- });
58
-
59
- watcher.on('error', (err: unknown) => {
60
- if (settled) return;
61
- cleanup();
62
- reject(new Error(`file trigger watch error: ${err instanceof Error ? err.message : String(err)}`));
63
- });
64
-
65
- // After the watcher finishes its initial scan, check if the file already exists.
66
- // Doing this inside 'ready' eliminates the race window between existence check
67
- // and watcher startup, so we neither miss events nor double-resolve.
68
- watcher.on('ready', () => {
69
- if (settled) return;
70
- Bun.file(safePath).exists().then((exists) => {
71
- if (settled) return;
72
- if (exists) {
73
- cleanup();
74
- resolve_p({ path: safePath });
75
- }
76
- }).catch((err: unknown) => {
77
- if (settled) return;
78
- cleanup();
79
- reject(new Error(`file trigger existence check failed: ${err instanceof Error ? err.message : String(err)}`));
80
- });
81
- });
82
-
83
- if (timeoutMs > 0) {
84
- timer = setTimeout(() => {
85
- if (settled) return;
86
- cleanup();
87
- reject(new Error(`file trigger timeout: ${filePath} did not appear within ${config.timeout}`));
88
- }, timeoutMs);
89
- }
90
-
91
- ctx.signal.addEventListener('abort', onAbort);
92
- });
93
- },
94
- };
1
+ import { watch } from 'chokidar';
2
+ import { resolve, dirname } from 'path';
3
+ import type { TriggerPlugin, TriggerContext } from '../types';
4
+ import { parseDuration, validatePath } from '../utils';
5
+
6
+ const IS_WINDOWS = process.platform === 'win32';
7
+
8
+ function pathsEqual(a: string, b: string): boolean {
9
+ return IS_WINDOWS ? a.toLowerCase() === b.toLowerCase() : a === b;
10
+ }
11
+
12
+ export const FileTrigger: TriggerPlugin = {
13
+ name: 'file',
14
+
15
+ watch(config: Record<string, unknown>, ctx: TriggerContext): Promise<unknown> {
16
+ const filePath = config.path as string;
17
+ if (!filePath) throw new Error(`file trigger: "path" is required`);
18
+
19
+ const safePath = validatePath(filePath, ctx.workDir);
20
+ const timeoutMs = config.timeout != null ? parseDuration(String(config.timeout)) : 0;
21
+
22
+ return new Promise((resolve_p, reject) => {
23
+ if (ctx.signal.aborted) {
24
+ reject(new Error('Pipeline aborted'));
25
+ return;
26
+ }
27
+
28
+ let settled = false;
29
+ let timer: ReturnType<typeof setTimeout> | null = null;
30
+
31
+ const dir = dirname(safePath);
32
+ const watcher = watch(dir, {
33
+ ignoreInitial: true,
34
+ depth: 0,
35
+ awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 50 },
36
+ });
37
+
38
+ const cleanup = () => {
39
+ if (settled) return;
40
+ settled = true;
41
+ watcher.close().catch(() => { /* ignore */ });
42
+ if (timer) clearTimeout(timer);
43
+ ctx.signal.removeEventListener('abort', onAbort);
44
+ };
45
+
46
+ const onAbort = () => {
47
+ cleanup();
48
+ reject(new Error('Pipeline aborted'));
49
+ };
50
+
51
+ watcher.on('add', (addedPath: string) => {
52
+ if (settled) return;
53
+ if (pathsEqual(resolve(addedPath), safePath)) {
54
+ cleanup();
55
+ resolve_p({ path: safePath });
56
+ }
57
+ });
58
+
59
+ watcher.on('error', (err: unknown) => {
60
+ if (settled) return;
61
+ cleanup();
62
+ reject(new Error(`file trigger watch error: ${err instanceof Error ? err.message : String(err)}`));
63
+ });
64
+
65
+ // After the watcher finishes its initial scan, check if the file already exists.
66
+ // Doing this inside 'ready' eliminates the race window between existence check
67
+ // and watcher startup, so we neither miss events nor double-resolve.
68
+ watcher.on('ready', () => {
69
+ if (settled) return;
70
+ Bun.file(safePath).exists().then((exists) => {
71
+ if (settled) return;
72
+ if (exists) {
73
+ cleanup();
74
+ resolve_p({ path: safePath });
75
+ }
76
+ }).catch((err: unknown) => {
77
+ if (settled) return;
78
+ cleanup();
79
+ reject(new Error(`file trigger existence check failed: ${err instanceof Error ? err.message : String(err)}`));
80
+ });
81
+ });
82
+
83
+ if (timeoutMs > 0) {
84
+ timer = setTimeout(() => {
85
+ if (settled) return;
86
+ cleanup();
87
+ reject(new Error(`file trigger timeout: ${filePath} did not appear within ${config.timeout}`));
88
+ }, timeoutMs);
89
+ }
90
+
91
+ ctx.signal.addEventListener('abort', onAbort);
92
+ });
93
+ },
94
+ };
@@ -1,61 +1,61 @@
1
- import type { TriggerPlugin, TriggerContext } from '../types';
2
- import { parseDuration } from '../utils';
3
-
4
- export const ManualTrigger: TriggerPlugin = {
5
- name: 'manual',
6
-
7
- async watch(config: Record<string, unknown>, ctx: TriggerContext): Promise<unknown> {
8
- const message =
9
- (config.message as string | undefined) ?? `Manual confirmation required for task "${ctx.taskId}"`;
10
- const timeoutMs = config.timeout ? parseDuration(config.timeout as string) : 0;
11
- const options = Array.isArray(config.options)
12
- ? (config.options as unknown[]).map(String)
13
- : undefined;
14
- const metadata =
15
- config.metadata && typeof config.metadata === 'object'
16
- ? (config.metadata as Record<string, unknown>)
17
- : undefined;
18
-
19
- const decisionPromise = ctx.approvalGateway.request({
20
- taskId: ctx.taskId,
21
- trackId: ctx.trackId,
22
- message,
23
- options,
24
- timeoutMs,
25
- metadata,
26
- });
27
-
28
- // Wire AbortSignal → try to resolve this specific request as aborted.
29
- // We can't directly cancel via the gateway (no id yet at .request() call site),
30
- // so instead we race against an abort promise and let engine status logic
31
- // fall back to pipelineAborted → skipped. abortAll() on gateway still runs
32
- // from engine shutdown path to clean up any truly-pending entries.
33
- const abortPromise = new Promise<never>((_, reject) => {
34
- if (ctx.signal.aborted) {
35
- reject(new Error('Pipeline aborted'));
36
- return;
37
- }
38
- ctx.signal.addEventListener(
39
- 'abort',
40
- () => reject(new Error('Pipeline aborted')),
41
- { once: true },
42
- );
43
- });
44
-
45
- const decision = await Promise.race([decisionPromise, abortPromise]);
46
-
47
- switch (decision.outcome) {
48
- case 'approved':
49
- return { confirmed: true, approvalId: decision.approvalId, choice: decision.choice, actor: decision.actor };
50
- case 'rejected':
51
- throw new Error(
52
- `Manual trigger rejected by ${decision.actor ?? 'user'}` +
53
- (decision.reason ? `: ${decision.reason}` : ''),
54
- );
55
- case 'timeout':
56
- throw new Error(`Manual trigger timeout: ${decision.reason ?? 'no decision made'}`);
57
- case 'aborted':
58
- throw new Error(`Manual trigger aborted: ${decision.reason ?? 'pipeline aborted'}`);
59
- }
60
- },
61
- };
1
+ import type { TriggerPlugin, TriggerContext } from '../types';
2
+ import { parseDuration } from '../utils';
3
+
4
+ export const ManualTrigger: TriggerPlugin = {
5
+ name: 'manual',
6
+
7
+ async watch(config: Record<string, unknown>, ctx: TriggerContext): Promise<unknown> {
8
+ const message =
9
+ (config.message as string | undefined) ?? `Manual confirmation required for task "${ctx.taskId}"`;
10
+ const timeoutMs = config.timeout ? parseDuration(config.timeout as string) : 0;
11
+ const options = Array.isArray(config.options)
12
+ ? (config.options as unknown[]).map(String)
13
+ : undefined;
14
+ const metadata =
15
+ config.metadata && typeof config.metadata === 'object'
16
+ ? (config.metadata as Record<string, unknown>)
17
+ : undefined;
18
+
19
+ const decisionPromise = ctx.approvalGateway.request({
20
+ taskId: ctx.taskId,
21
+ trackId: ctx.trackId,
22
+ message,
23
+ options,
24
+ timeoutMs,
25
+ metadata,
26
+ });
27
+
28
+ // Wire AbortSignal → try to resolve this specific request as aborted.
29
+ // We can't directly cancel via the gateway (no id yet at .request() call site),
30
+ // so instead we race against an abort promise and let engine status logic
31
+ // fall back to pipelineAborted → skipped. abortAll() on gateway still runs
32
+ // from engine shutdown path to clean up any truly-pending entries.
33
+ const abortPromise = new Promise<never>((_, reject) => {
34
+ if (ctx.signal.aborted) {
35
+ reject(new Error('Pipeline aborted'));
36
+ return;
37
+ }
38
+ ctx.signal.addEventListener(
39
+ 'abort',
40
+ () => reject(new Error('Pipeline aborted')),
41
+ { once: true },
42
+ );
43
+ });
44
+
45
+ const decision = await Promise.race([decisionPromise, abortPromise]);
46
+
47
+ switch (decision.outcome) {
48
+ case 'approved':
49
+ return { confirmed: true, approvalId: decision.approvalId, choice: decision.choice, actor: decision.actor };
50
+ case 'rejected':
51
+ throw new Error(
52
+ `Manual trigger rejected by ${decision.actor ?? 'user'}` +
53
+ (decision.reason ? `: ${decision.reason}` : ''),
54
+ );
55
+ case 'timeout':
56
+ throw new Error(`Manual trigger timeout: ${decision.reason ?? 'no decision made'}`);
57
+ case 'aborted':
58
+ throw new Error(`Manual trigger aborted: ${decision.reason ?? 'pipeline aborted'}`);
59
+ }
60
+ },
61
+ };
package/src/utils.ts CHANGED
@@ -1,147 +1,147 @@
1
- import { resolve, relative } from 'path';
2
-
3
- const DURATION_RE = /^(\d+(?:\.\d+)?)\s*(s|m|h)$/;
4
-
5
- export function parseDuration(input: string): number {
6
- const match = DURATION_RE.exec(input.trim());
7
- if (!match) {
8
- throw new Error(`Invalid duration format: "${input}". Expected format: <number>(s|m|h)`);
9
- }
10
- const value = parseFloat(match[1]);
11
- const unit = match[2];
12
- switch (unit) {
13
- case 's': return value * 1000;
14
- case 'm': return value * 60_000;
15
- case 'h': return value * 3_600_000;
16
- default: throw new Error(`Unknown duration unit: "${unit}"`);
17
- }
18
- }
19
-
20
- export function validatePath(filePath: string, projectRoot: string): string {
21
- const resolved = resolve(projectRoot, filePath);
22
- const rel = relative(projectRoot, resolved);
23
-
24
- if (rel.startsWith('..') || rel.startsWith('/') || /^[a-zA-Z]:/.test(rel)) {
25
- throw new Error(
26
- `Security: path "${filePath}" escapes project root. ` +
27
- `All file references must be within "${projectRoot}".`
28
- );
29
- }
30
-
31
- return resolved;
32
- }
33
-
34
- const SHELL_META_CHARS = /[;&|$`\\!><()\[\]{}*?#~]/;
35
-
36
- export function validatePathParam(filePath: string): void {
37
- if (filePath.includes('..')) {
38
- throw new Error(`Template param type=path: ".." traversal not allowed in "${filePath}"`);
39
- }
40
- if (resolve(filePath) === filePath) {
41
- throw new Error(`Template param type=path: absolute path not allowed: "${filePath}"`);
42
- }
43
- if (SHELL_META_CHARS.test(filePath)) {
44
- throw new Error(`Template param type=path: shell metacharacters not allowed in "${filePath}"`);
45
- }
46
- }
47
-
48
- let runCounter = 0;
49
-
50
- export function generateRunId(): string {
51
- const ts = Date.now().toString(36);
52
- const seq = (runCounter++).toString(36);
53
- return `run_${ts}_${seq}`;
54
- }
55
-
56
- export function truncateForName(text: string, maxLen = 40): string {
57
- const first = text.split('\n')[0].trim();
58
- return first.length > maxLen ? first.slice(0, maxLen) + '...' : first;
59
- }
60
-
61
- export function nowISO(): string {
62
- return new Date().toISOString();
63
- }
64
-
65
- // ═══ Platform-aware shell ═══
66
- //
67
- // Resolution order:
68
- // 1. Env override: PIPELINE_SHELL="bash" or PIPELINE_SHELL="cmd" etc.
69
- // 2. Windows: prefer sh (Git Bash / MSYS2) if on PATH, fall back to cmd.exe
70
- // 3. Unix: sh
71
- //
72
- // Resolution is cached once on first call to avoid repeated PATH lookups.
73
-
74
- const IS_WINDOWS = process.platform === 'win32';
75
-
76
- type ShellKind = 'sh' | 'bash' | 'cmd' | 'powershell';
77
- let resolvedShell: { kind: ShellKind; path: string } | null = null;
78
-
79
- function detectShell(): { kind: ShellKind; path: string } {
80
- // Env override takes precedence
81
- const override = process.env.PIPELINE_SHELL;
82
- if (override) {
83
- const kind = override as ShellKind;
84
- return { kind, path: override };
85
- }
86
-
87
- if (!IS_WINDOWS) {
88
- return { kind: 'sh', path: 'sh' };
89
- }
90
-
91
- // Windows: probe PATH for sh (bundled with Git for Windows / MSYS2)
92
- const pathEnv = process.env.PATH ?? '';
93
- const pathExt = (process.env.PATHEXT ?? '.EXE;.CMD;.BAT').split(';');
94
- const dirs = pathEnv.split(';').filter(Boolean);
95
-
96
- for (const dir of dirs) {
97
- for (const ext of ['', ...pathExt]) {
98
- const candidate = `${dir}\\sh${ext}`;
99
- try {
100
- if (Bun.file(candidate).size > 0) {
101
- return { kind: 'sh', path: candidate };
102
- }
103
- } catch { /* ignore */ }
104
- }
105
- }
106
-
107
- // Fallback: cmd.exe (always present on Windows)
108
- const systemRoot = process.env.SystemRoot ?? 'C:\\Windows';
109
- return { kind: 'cmd', path: `${systemRoot}\\System32\\cmd.exe` };
110
- }
111
-
112
- function getShell(): { kind: ShellKind; path: string } {
113
- if (!resolvedShell) resolvedShell = detectShell();
114
- return resolvedShell;
115
- }
116
-
117
- export function shellArgs(command: string): readonly string[] {
118
- const sh = getShell();
119
- if (sh.kind === 'cmd') {
120
- return [sh.path, '/c', command];
121
- }
122
- if (sh.kind === 'powershell') {
123
- return [sh.path, '-Command', command];
124
- }
125
- // sh or bash
126
- return [sh.path, '-c', command];
127
- }
128
-
129
- /** Quote a single argument for inclusion in a shell command string. */
130
- function quoteArg(arg: string): string {
131
- if (!/[\s"'\\<>|&;`$!^%]/.test(arg)) return arg;
132
- // Double-quote and escape embedded double quotes + backslashes
133
- return '"' + arg.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
134
- }
135
-
136
- /**
137
- * Convert an args array to shell-wrapped args suitable for Bun.spawn.
138
- * Each arg is quoted as needed, then joined and passed through shellArgs.
139
- */
140
- export function shellArgsFromArray(args: readonly string[]): readonly string[] {
141
- return shellArgs(args.map(quoteArg).join(' '));
142
- }
143
-
144
- // For tests: allow resetting the cached shell detection
145
- export function _resetShellCache(): void {
146
- resolvedShell = null;
147
- }
1
+ import { resolve, relative } from 'path';
2
+
3
+ const DURATION_RE = /^(\d+(?:\.\d+)?)\s*(s|m|h)$/;
4
+
5
+ export function parseDuration(input: string): number {
6
+ const match = DURATION_RE.exec(input.trim());
7
+ if (!match) {
8
+ throw new Error(`Invalid duration format: "${input}". Expected format: <number>(s|m|h)`);
9
+ }
10
+ const value = parseFloat(match[1]);
11
+ const unit = match[2];
12
+ switch (unit) {
13
+ case 's': return value * 1000;
14
+ case 'm': return value * 60_000;
15
+ case 'h': return value * 3_600_000;
16
+ default: throw new Error(`Unknown duration unit: "${unit}"`);
17
+ }
18
+ }
19
+
20
+ export function validatePath(filePath: string, projectRoot: string): string {
21
+ const resolved = resolve(projectRoot, filePath);
22
+ const rel = relative(projectRoot, resolved);
23
+
24
+ if (rel.startsWith('..') || rel.startsWith('/') || /^[a-zA-Z]:/.test(rel)) {
25
+ throw new Error(
26
+ `Security: path "${filePath}" escapes project root. ` +
27
+ `All file references must be within "${projectRoot}".`
28
+ );
29
+ }
30
+
31
+ return resolved;
32
+ }
33
+
34
+ const SHELL_META_CHARS = /[;&|$`\\!><()\[\]{}*?#~]/;
35
+
36
+ export function validatePathParam(filePath: string): void {
37
+ if (filePath.includes('..')) {
38
+ throw new Error(`Template param type=path: ".." traversal not allowed in "${filePath}"`);
39
+ }
40
+ if (resolve(filePath) === filePath) {
41
+ throw new Error(`Template param type=path: absolute path not allowed: "${filePath}"`);
42
+ }
43
+ if (SHELL_META_CHARS.test(filePath)) {
44
+ throw new Error(`Template param type=path: shell metacharacters not allowed in "${filePath}"`);
45
+ }
46
+ }
47
+
48
+ let runCounter = 0;
49
+
50
+ export function generateRunId(): string {
51
+ const ts = Date.now().toString(36);
52
+ const seq = (runCounter++).toString(36);
53
+ return `run_${ts}_${seq}`;
54
+ }
55
+
56
+ export function truncateForName(text: string, maxLen = 40): string {
57
+ const first = text.split('\n')[0].trim();
58
+ return first.length > maxLen ? first.slice(0, maxLen) + '...' : first;
59
+ }
60
+
61
+ export function nowISO(): string {
62
+ return new Date().toISOString();
63
+ }
64
+
65
+ // ═══ Platform-aware shell ═══
66
+ //
67
+ // Resolution order:
68
+ // 1. Env override: PIPELINE_SHELL="bash" or PIPELINE_SHELL="cmd" etc.
69
+ // 2. Windows: prefer sh (Git Bash / MSYS2) if on PATH, fall back to cmd.exe
70
+ // 3. Unix: sh
71
+ //
72
+ // Resolution is cached once on first call to avoid repeated PATH lookups.
73
+
74
+ const IS_WINDOWS = process.platform === 'win32';
75
+
76
+ type ShellKind = 'sh' | 'bash' | 'cmd' | 'powershell';
77
+ let resolvedShell: { kind: ShellKind; path: string } | null = null;
78
+
79
+ function detectShell(): { kind: ShellKind; path: string } {
80
+ // Env override takes precedence
81
+ const override = process.env.PIPELINE_SHELL;
82
+ if (override) {
83
+ const kind = override as ShellKind;
84
+ return { kind, path: override };
85
+ }
86
+
87
+ if (!IS_WINDOWS) {
88
+ return { kind: 'sh', path: 'sh' };
89
+ }
90
+
91
+ // Windows: probe PATH for sh (bundled with Git for Windows / MSYS2)
92
+ const pathEnv = process.env.PATH ?? '';
93
+ const pathExt = (process.env.PATHEXT ?? '.EXE;.CMD;.BAT').split(';');
94
+ const dirs = pathEnv.split(';').filter(Boolean);
95
+
96
+ for (const dir of dirs) {
97
+ for (const ext of ['', ...pathExt]) {
98
+ const candidate = `${dir}\\sh${ext}`;
99
+ try {
100
+ if (Bun.file(candidate).size > 0) {
101
+ return { kind: 'sh', path: candidate };
102
+ }
103
+ } catch { /* ignore */ }
104
+ }
105
+ }
106
+
107
+ // Fallback: cmd.exe (always present on Windows)
108
+ const systemRoot = process.env.SystemRoot ?? 'C:\\Windows';
109
+ return { kind: 'cmd', path: `${systemRoot}\\System32\\cmd.exe` };
110
+ }
111
+
112
+ function getShell(): { kind: ShellKind; path: string } {
113
+ if (!resolvedShell) resolvedShell = detectShell();
114
+ return resolvedShell;
115
+ }
116
+
117
+ export function shellArgs(command: string): readonly string[] {
118
+ const sh = getShell();
119
+ if (sh.kind === 'cmd') {
120
+ return [sh.path, '/c', command];
121
+ }
122
+ if (sh.kind === 'powershell') {
123
+ return [sh.path, '-Command', command];
124
+ }
125
+ // sh or bash
126
+ return [sh.path, '-c', command];
127
+ }
128
+
129
+ /** Quote a single argument for inclusion in a shell command string. */
130
+ function quoteArg(arg: string): string {
131
+ if (!/[\s"'\\<>|&;`$!^%]/.test(arg)) return arg;
132
+ // Double-quote and escape embedded double quotes + backslashes
133
+ return '"' + arg.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
134
+ }
135
+
136
+ /**
137
+ * Convert an args array to shell-wrapped args suitable for Bun.spawn.
138
+ * Each arg is quoted as needed, then joined and passed through shellArgs.
139
+ */
140
+ export function shellArgsFromArray(args: readonly string[]): readonly string[] {
141
+ return shellArgs(args.map(quoteArg).join(' '));
142
+ }
143
+
144
+ // For tests: allow resetting the cached shell detection
145
+ export function _resetShellCache(): void {
146
+ resolvedShell = null;
147
+ }