@tagma/sdk 0.4.11 → 0.4.13

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 (88) hide show
  1. package/README.md +572 -566
  2. package/dist/adapters/websocket-approval.d.ts.map +1 -1
  3. package/dist/adapters/websocket-approval.js +3 -1
  4. package/dist/adapters/websocket-approval.js.map +1 -1
  5. package/dist/approval.d.ts.map +1 -1
  6. package/dist/approval.js.map +1 -1
  7. package/dist/completions/exit-code.d.ts.map +1 -1
  8. package/dist/completions/exit-code.js.map +1 -1
  9. package/dist/completions/file-exists.d.ts.map +1 -1
  10. package/dist/completions/file-exists.js.map +1 -1
  11. package/dist/completions/output-check.js +2 -7
  12. package/dist/completions/output-check.js.map +1 -1
  13. package/dist/config-ops.d.ts.map +1 -1
  14. package/dist/config-ops.js +24 -26
  15. package/dist/config-ops.js.map +1 -1
  16. package/dist/dag.d.ts.map +1 -1
  17. package/dist/dag.js +1 -1
  18. package/dist/dag.js.map +1 -1
  19. package/dist/drivers/claude-code.d.ts.map +1 -1
  20. package/dist/drivers/claude-code.js +10 -5
  21. package/dist/drivers/claude-code.js.map +1 -1
  22. package/dist/engine.d.ts.map +1 -1
  23. package/dist/engine.js +63 -29
  24. package/dist/engine.js.map +1 -1
  25. package/dist/hooks.d.ts.map +1 -1
  26. package/dist/hooks.js +1 -3
  27. package/dist/hooks.js.map +1 -1
  28. package/dist/logger.d.ts.map +1 -1
  29. package/dist/logger.js +4 -2
  30. package/dist/logger.js.map +1 -1
  31. package/dist/pipeline-runner.d.ts.map +1 -1
  32. package/dist/pipeline-runner.js +10 -4
  33. package/dist/pipeline-runner.js.map +1 -1
  34. package/dist/registry.d.ts +11 -1
  35. package/dist/registry.d.ts.map +1 -1
  36. package/dist/registry.js +28 -3
  37. package/dist/registry.js.map +1 -1
  38. package/dist/runner.d.ts.map +1 -1
  39. package/dist/runner.js +18 -13
  40. package/dist/runner.js.map +1 -1
  41. package/dist/schema.d.ts.map +1 -1
  42. package/dist/schema.js +39 -14
  43. package/dist/schema.js.map +1 -1
  44. package/dist/schema.test.js +5 -1
  45. package/dist/schema.test.js.map +1 -1
  46. package/dist/sdk.d.ts +2 -2
  47. package/dist/sdk.d.ts.map +1 -1
  48. package/dist/sdk.js +1 -1
  49. package/dist/sdk.js.map +1 -1
  50. package/dist/triggers/file.d.ts.map +1 -1
  51. package/dist/triggers/file.js +11 -4
  52. package/dist/triggers/file.js.map +1 -1
  53. package/dist/triggers/manual.d.ts.map +1 -1
  54. package/dist/triggers/manual.js +2 -1
  55. package/dist/triggers/manual.js.map +1 -1
  56. package/dist/utils.d.ts.map +1 -1
  57. package/dist/utils.js +63 -8
  58. package/dist/utils.js.map +1 -1
  59. package/dist/validate-raw.d.ts.map +1 -1
  60. package/dist/validate-raw.js +60 -11
  61. package/dist/validate-raw.js.map +1 -1
  62. package/package.json +2 -2
  63. package/scripts/preinstall.js +1 -1
  64. package/src/adapters/stdin-approval.ts +106 -106
  65. package/src/adapters/websocket-approval.ts +224 -220
  66. package/src/approval.ts +131 -125
  67. package/src/bootstrap.ts +37 -37
  68. package/src/completions/exit-code.ts +34 -30
  69. package/src/completions/file-exists.ts +66 -60
  70. package/src/completions/output-check.ts +86 -86
  71. package/src/config-ops.ts +307 -322
  72. package/src/dag.ts +234 -228
  73. package/src/drivers/claude-code.ts +250 -240
  74. package/src/engine.ts +1098 -928
  75. package/src/hooks.ts +187 -179
  76. package/src/logger.ts +182 -178
  77. package/src/middlewares/static-context.ts +45 -45
  78. package/src/pipeline-runner.ts +156 -150
  79. package/src/registry.ts +51 -23
  80. package/src/runner.ts +395 -397
  81. package/src/schema.test.ts +5 -1
  82. package/src/schema.ts +338 -298
  83. package/src/sdk.ts +91 -81
  84. package/src/triggers/file.ts +33 -14
  85. package/src/triggers/manual.ts +86 -81
  86. package/src/types.ts +18 -18
  87. package/src/utils.ts +202 -140
  88. package/src/validate-raw.ts +442 -389
package/src/utils.ts CHANGED
@@ -1,141 +1,203 @@
1
- import { resolve, relative } from 'path';
2
- import { randomBytes } from 'crypto';
3
-
4
- const DURATION_RE = /^(\d*\.?\d+)\s*(s|m|h|d)$/;
5
-
6
- export function parseDuration(input: string): number {
7
- const match = DURATION_RE.exec(input.trim());
8
- if (!match) {
9
- throw new Error(`Invalid duration format: "${input}". Expected format: <number>(s|m|h|d)`);
10
- }
11
- const value = parseFloat(match[1]);
12
- const unit = match[2];
13
- switch (unit) {
14
- case 's': return value * 1000;
15
- case 'm': return value * 60_000;
16
- case 'h': return value * 3_600_000;
17
- case 'd': return value * 86_400_000;
18
- default: throw new Error(`Unknown duration unit: "${unit}"`);
19
- }
20
- }
21
-
22
- export function validatePath(filePath: string, projectRoot: string): string {
23
- const resolved = resolve(projectRoot, filePath);
24
- const rel = relative(projectRoot, resolved);
25
-
26
- if (rel.startsWith('..') || rel.startsWith('/') || /^[a-zA-Z]:/.test(rel)) {
27
- throw new Error(
28
- `Security: path "${filePath}" escapes project root. ` +
29
- `All file references must be within "${projectRoot}".`
30
- );
31
- }
32
-
33
- return resolved;
34
- }
35
-
36
- export function generateRunId(): string {
37
- const ts = Date.now().toString(36);
38
- const rand = randomBytes(6).toString('hex');
39
- return `run_${ts}_${rand}`;
1
+ import { resolve, relative, parse as parsePath } from 'path';
2
+ import { realpathSync, lstatSync, existsSync } from 'fs';
3
+ import { randomBytes } from 'crypto';
4
+
5
+ const DURATION_RE = /^(\d*\.?\d+)\s*(s|m|h|d)$/;
6
+
7
+ export function parseDuration(input: string): number {
8
+ const match = DURATION_RE.exec(input.trim());
9
+ if (!match) {
10
+ throw new Error(`Invalid duration format: "${input}". Expected format: <number>(s|m|h|d)`);
11
+ }
12
+ const value = parseFloat(match[1]);
13
+ const unit = match[2];
14
+ switch (unit) {
15
+ case 's':
16
+ return value * 1000;
17
+ case 'm':
18
+ return value * 60_000;
19
+ case 'h':
20
+ return value * 3_600_000;
21
+ case 'd':
22
+ return value * 86_400_000;
23
+ default:
24
+ throw new Error(`Unknown duration unit: "${unit}"`);
25
+ }
26
+ }
27
+
28
+ export function validatePath(filePath: string, projectRoot: string): string {
29
+ const resolved = resolve(projectRoot, filePath);
30
+
31
+ // D2: Cross-drive check (Windows) — path.relative('C:\\root', 'D:\\x') returns
32
+ // 'D:\\x' which does NOT start with '..', so a pure relative check would wrongly
33
+ // allow cross-drive paths. Reject them explicitly before any further comparison.
34
+ if (parsePath(projectRoot).root !== parsePath(resolved).root) {
35
+ throw new Error(
36
+ `Security: path "${filePath}" is on a different drive than the project root "${projectRoot}".`,
37
+ );
38
+ }
39
+
40
+ const rel = relative(projectRoot, resolved);
41
+ if (rel.startsWith('..') || rel.startsWith('/')) {
42
+ throw new Error(
43
+ `Security: path "${filePath}" escapes project root. ` +
44
+ `All file references must be within "${projectRoot}".`,
45
+ );
46
+ }
47
+
48
+ // D1: Resolve symlinks and re-validate so a symlink whose string path is
49
+ // inside the project root but whose target lies outside is rejected.
50
+ // Only resolve if the path exists on disk; at parse time the file may not
51
+ // yet exist (e.g. a future output path), so we skip realpath for absent paths.
52
+ if (existsSync(resolved)) {
53
+ // Reject the entry outright if it is itself a symlink — callers that want
54
+ // to allow symlinks within the tree can pass pre-resolved paths.
55
+ try {
56
+ const stat = lstatSync(resolved);
57
+ if (stat.isSymbolicLink()) {
58
+ throw new Error(
59
+ `Security: path "${filePath}" is a symbolic link. Symbolic links are not allowed within the project root.`,
60
+ );
61
+ }
62
+ } catch (err) {
63
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
64
+ }
65
+
66
+ // Also verify the real (fully resolved) path stays within the project root.
67
+ let real: string;
68
+ try {
69
+ real = realpathSync.native(resolved);
70
+ } catch {
71
+ real = resolved; // path vanished between existsSync and realpathSync — skip
72
+ }
73
+ const realRoot = (() => {
74
+ try {
75
+ return realpathSync.native(projectRoot);
76
+ } catch {
77
+ return projectRoot;
78
+ }
79
+ })();
80
+ if (parsePath(realRoot).root !== parsePath(real).root) {
81
+ throw new Error(
82
+ `Security: resolved path "${real}" is on a different drive than the project root "${realRoot}".`,
83
+ );
84
+ }
85
+ const realRel = relative(realRoot, real);
86
+ if (realRel.startsWith('..') || realRel.startsWith('/')) {
87
+ throw new Error(
88
+ `Security: path "${filePath}" resolves via symlink to "${real}" which escapes project root "${realRoot}".`,
89
+ );
90
+ }
91
+ }
92
+
93
+ return resolved;
94
+ }
95
+
96
+ export function generateRunId(): string {
97
+ const ts = Date.now().toString(36);
98
+ const rand = randomBytes(6).toString('hex');
99
+ return `run_${ts}_${rand}`;
100
+ }
101
+
102
+ export function truncateForName(text: string, maxLen = 40): string {
103
+ const first = text.split('\n')[0]!.trim();
104
+ // Guard: if the first line is empty (e.g. prompt is all whitespace/newlines),
105
+ // fall back to the raw text trimmed rather than silently producing an empty name.
106
+ if (!first) return text.trim().slice(0, maxLen) || '...';
107
+ return first.length > maxLen ? first.slice(0, maxLen) + '...' : first;
108
+ }
109
+
110
+ export function nowISO(): string {
111
+ return new Date().toISOString();
112
+ }
113
+
114
+ // ═══ Platform-aware shell ═══
115
+ //
116
+ // Resolution order:
117
+ // 1. Env override: PIPELINE_SHELL="bash" or PIPELINE_SHELL="cmd" etc.
118
+ // 2. Windows: prefer sh (Git Bash / MSYS2) if on PATH, fall back to cmd.exe
119
+ // 3. Unix: sh
120
+ //
121
+ // Resolution is cached once on first call to avoid repeated PATH lookups.
122
+
123
+ const IS_WINDOWS = process.platform === 'win32';
124
+
125
+ type ShellKind = 'sh' | 'bash' | 'cmd' | 'powershell';
126
+ let resolvedShell: { kind: ShellKind; path: string } | null = null;
127
+
128
+ function detectShell(): { kind: ShellKind; path: string } {
129
+ // Env override takes precedence
130
+ const override = process.env.PIPELINE_SHELL;
131
+ if (override) {
132
+ const kind = override as ShellKind;
133
+ return { kind, path: override };
134
+ }
135
+
136
+ if (!IS_WINDOWS) {
137
+ return { kind: 'sh', path: 'sh' };
138
+ }
139
+
140
+ // Windows: probe PATH for sh (bundled with Git for Windows / MSYS2)
141
+ const pathEnv = process.env.PATH ?? '';
142
+ const pathExt = (process.env.PATHEXT ?? '.EXE;.CMD;.BAT').split(';');
143
+ const dirs = pathEnv.split(';').filter(Boolean);
144
+
145
+ for (const dir of dirs) {
146
+ for (const ext of ['', ...pathExt]) {
147
+ const candidate = `${dir}\\sh${ext}`;
148
+ try {
149
+ if (Bun.file(candidate).size > 0) {
150
+ return { kind: 'sh', path: candidate };
151
+ }
152
+ } catch {
153
+ /* ignore */
154
+ }
155
+ }
156
+ }
157
+
158
+ // Fallback: cmd.exe (always present on Windows)
159
+ const systemRoot = process.env.SystemRoot ?? 'C:\\Windows';
160
+ return { kind: 'cmd', path: `${systemRoot}\\System32\\cmd.exe` };
161
+ }
162
+
163
+ function getShell(): { kind: ShellKind; path: string } {
164
+ if (!resolvedShell) resolvedShell = detectShell();
165
+ return resolvedShell;
166
+ }
167
+
168
+ export function shellArgs(command: string): readonly string[] {
169
+ const sh = getShell();
170
+ if (sh.kind === 'cmd') {
171
+ return [sh.path, '/c', command];
172
+ }
173
+ if (sh.kind === 'powershell') {
174
+ return [sh.path, '-Command', command];
175
+ }
176
+ // sh or bash
177
+ return [sh.path, '-c', command];
178
+ }
179
+
180
+ /** Quote a single argument for inclusion in a shell command string. */
181
+ function quoteArg(arg: string): string {
182
+ if (!/[\s"'\\<>|&;`$!^%]/.test(arg)) return arg;
183
+ if (IS_WINDOWS) {
184
+ // On Windows (cmd.exe), double-quote and escape embedded quotes + backslashes
185
+ return '"' + arg.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
186
+ }
187
+ // On Unix, use single quotes to prevent $variable expansion.
188
+ // Escape embedded single quotes via the '\'' idiom.
189
+ return "'" + arg.replace(/'/g, "'\\''") + "'";
190
+ }
191
+
192
+ /**
193
+ * Convert an args array to shell-wrapped args suitable for Bun.spawn.
194
+ * Each arg is quoted as needed, then joined and passed through shellArgs.
195
+ */
196
+ export function shellArgsFromArray(args: readonly string[]): readonly string[] {
197
+ return shellArgs(args.map(quoteArg).join(' '));
198
+ }
199
+
200
+ // For tests: allow resetting the cached shell detection
201
+ export function _resetShellCache(): void {
202
+ resolvedShell = null;
40
203
  }
41
-
42
- export function truncateForName(text: string, maxLen = 40): string {
43
- const first = text.split('\n')[0]!.trim();
44
- // Guard: if the first line is empty (e.g. prompt is all whitespace/newlines),
45
- // fall back to the raw text trimmed rather than silently producing an empty name.
46
- if (!first) return text.trim().slice(0, maxLen) || '...';
47
- return first.length > maxLen ? first.slice(0, maxLen) + '...' : first;
48
- }
49
-
50
- export function nowISO(): string {
51
- return new Date().toISOString();
52
- }
53
-
54
- // ═══ Platform-aware shell ═══
55
- //
56
- // Resolution order:
57
- // 1. Env override: PIPELINE_SHELL="bash" or PIPELINE_SHELL="cmd" etc.
58
- // 2. Windows: prefer sh (Git Bash / MSYS2) if on PATH, fall back to cmd.exe
59
- // 3. Unix: sh
60
- //
61
- // Resolution is cached once on first call to avoid repeated PATH lookups.
62
-
63
- const IS_WINDOWS = process.platform === 'win32';
64
-
65
- type ShellKind = 'sh' | 'bash' | 'cmd' | 'powershell';
66
- let resolvedShell: { kind: ShellKind; path: string } | null = null;
67
-
68
- function detectShell(): { kind: ShellKind; path: string } {
69
- // Env override takes precedence
70
- const override = process.env.PIPELINE_SHELL;
71
- if (override) {
72
- const kind = override as ShellKind;
73
- return { kind, path: override };
74
- }
75
-
76
- if (!IS_WINDOWS) {
77
- return { kind: 'sh', path: 'sh' };
78
- }
79
-
80
- // Windows: probe PATH for sh (bundled with Git for Windows / MSYS2)
81
- const pathEnv = process.env.PATH ?? '';
82
- const pathExt = (process.env.PATHEXT ?? '.EXE;.CMD;.BAT').split(';');
83
- const dirs = pathEnv.split(';').filter(Boolean);
84
-
85
- for (const dir of dirs) {
86
- for (const ext of ['', ...pathExt]) {
87
- const candidate = `${dir}\\sh${ext}`;
88
- try {
89
- if (Bun.file(candidate).size > 0) {
90
- return { kind: 'sh', path: candidate };
91
- }
92
- } catch { /* ignore */ }
93
- }
94
- }
95
-
96
- // Fallback: cmd.exe (always present on Windows)
97
- const systemRoot = process.env.SystemRoot ?? 'C:\\Windows';
98
- return { kind: 'cmd', path: `${systemRoot}\\System32\\cmd.exe` };
99
- }
100
-
101
- function getShell(): { kind: ShellKind; path: string } {
102
- if (!resolvedShell) resolvedShell = detectShell();
103
- return resolvedShell;
104
- }
105
-
106
- export function shellArgs(command: string): readonly string[] {
107
- const sh = getShell();
108
- if (sh.kind === 'cmd') {
109
- return [sh.path, '/c', command];
110
- }
111
- if (sh.kind === 'powershell') {
112
- return [sh.path, '-Command', command];
113
- }
114
- // sh or bash
115
- return [sh.path, '-c', command];
116
- }
117
-
118
- /** Quote a single argument for inclusion in a shell command string. */
119
- function quoteArg(arg: string): string {
120
- if (!/[\s"'\\<>|&;`$!^%]/.test(arg)) return arg;
121
- if (IS_WINDOWS) {
122
- // On Windows (cmd.exe), double-quote and escape embedded quotes + backslashes
123
- return '"' + arg.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
124
- }
125
- // On Unix, use single quotes to prevent $variable expansion.
126
- // Escape embedded single quotes via the '\'' idiom.
127
- return "'" + arg.replace(/'/g, "'\\''") + "'";
128
- }
129
-
130
- /**
131
- * Convert an args array to shell-wrapped args suitable for Bun.spawn.
132
- * Each arg is quoted as needed, then joined and passed through shellArgs.
133
- */
134
- export function shellArgsFromArray(args: readonly string[]): readonly string[] {
135
- return shellArgs(args.map(quoteArg).join(' '));
136
- }
137
-
138
- // For tests: allow resetting the cached shell detection
139
- export function _resetShellCache(): void {
140
- resolvedShell = null;
141
- }