@tagma/sdk 0.4.12 → 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 +54 -27
  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 +14 -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 +13 -6
  58. package/dist/utils.js.map +1 -1
  59. package/dist/validate-raw.d.ts.map +1 -1
  60. package/dist/validate-raw.js +40 -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 -935
  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 -328
  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 -191
  88. package/src/validate-raw.ts +442 -409
@@ -1,240 +1,250 @@
1
- import { existsSync } from 'node:fs';
2
- import { isAbsolute, relative, dirname, join } from 'node:path';
3
- import type {
4
- DriverPlugin, DriverCapabilities, DriverResultMeta,
5
- TaskConfig, TrackConfig, DriverContext, SpawnSpec, Permissions,
6
- } from '../types';
7
-
8
- // Claude Code CLI reference: https://code.claude.com/docs/en/cli-reference
9
-
10
- const DEFAULT_MODEL = 'sonnet';
11
-
12
- // Claude Code CLI accepts --effort low|medium|high|max. tagma's vocabulary
13
- // is low|medium|high, so low/medium/high pass through unchanged; users who
14
- // want the claude-specific "max" tier can also set it explicitly.
15
- const VALID_EFFORT = new Set(['low', 'medium', 'high', 'max']);
16
-
17
- function resolveModel(): string {
18
- return DEFAULT_MODEL;
19
- }
20
-
21
- function resolveTools(permissions: Permissions): string {
22
- const tools = ['Grep', 'Glob'];
23
- if (permissions.read) tools.push('Read');
24
- if (permissions.write) tools.push('Edit', 'Write');
25
- if (permissions.execute) tools.push('Bash');
26
- return tools.join(',');
27
- }
28
-
29
- // Maps our Permissions to Claude Code's --permission-mode. In print (-p) mode
30
- // Claude needs non-interactive permission handling:
31
- // - `bypassPermissions` skips all checks (required for reliable Bash automation
32
- // under `execute: true`, matches the "full trust" semantics of that tier).
33
- // - `dontAsk` auto-denies anything outside `--allowedTools`, which is exactly
34
- // what we want for read/write tiers: the allowedTools whitelist already
35
- // enumerates what Claude may do, and dontAsk makes violations fail fast
36
- // instead of hanging on a prompt no one can answer in headless mode.
37
- // See: https://code.claude.com/docs/en/permission-modes
38
- function resolvePermissionMode(permissions: Permissions): string {
39
- if (permissions.execute) return 'bypassPermissions';
40
- return 'dontAsk';
41
- }
42
-
43
- // Returns true if `sub` is inside `root` (or equal to it).
44
- function isInside(root: string, sub: string): boolean {
45
- const rel = relative(root, sub);
46
- return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
47
- }
48
-
49
- // Claude Code requires CLAUDE_CODE_GIT_BASH_PATH on Windows pointing to
50
- // Git Bash (bin\bash.exe under a Git for Windows install). See:
51
- // https://code.claude.com/docs/en/troubleshooting#windows-claude-code-on-windows-requires-git-bash
52
- // The path must use native Windows backslashes — forward slashes are rejected
53
- // by Claude Code's path validation.
54
- function resolveGitBashEnv(): Record<string, string> {
55
- if (process.platform !== 'win32') return {};
56
-
57
- // Respect user-provided value if it points to an actual file. If the user
58
- // set it to a non-existent path, fall through to discovery rather than
59
- // propagating the broken config.
60
- const existing = process.env.CLAUDE_CODE_GIT_BASH_PATH;
61
- if (existing && existsSync(existing)) return {};
62
-
63
- const discovered = discoverGitBash();
64
- return discovered ? { CLAUDE_CODE_GIT_BASH_PATH: discovered } : {};
65
- }
66
-
67
- function discoverGitBash(): string | null {
68
- // Strategy 1: find git.exe in PATH (equivalent to `where.exe git`) and
69
- // walk up looking for bin\bash.exe under a Git install root. Git for
70
- // Windows may expose multiple git.exe locations (cmd\git.exe,
71
- // mingw64\bin\git.exe, mingw64\libexec\git-core\git.exe), so we walk up
72
- // several levels rather than assuming a fixed depth.
73
- const gitExe = findExeInPath('git.exe');
74
- if (gitExe) {
75
- let dir = dirname(gitExe);
76
- for (let depth = 0; depth < 5; depth++) {
77
- const candidate = join(dir, 'bin', 'bash.exe');
78
- if (existsSync(candidate)) return candidate;
79
- const parent = dirname(dir);
80
- if (parent === dir) break;
81
- dir = parent;
82
- }
83
- }
84
-
85
- // Strategy 2: check common Git for Windows install locations.
86
- // Uses %ProgramFiles%/%LOCALAPPDATA%/%USERPROFILE% env vars so it works on
87
- // systems where those aren't mapped to C:\ (e.g. localized Windows).
88
- const programFiles = process.env['ProgramFiles'] ?? 'C:\\Program Files';
89
- const programFilesX86 = process.env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)';
90
- const localAppData = process.env['LOCALAPPDATA'];
91
- const userProfile = process.env['USERPROFILE'];
92
-
93
- const candidates = [
94
- join(programFiles, 'Git', 'bin', 'bash.exe'),
95
- join(programFilesX86, 'Git', 'bin', 'bash.exe'),
96
- // Git for Windows user-level install
97
- localAppData && join(localAppData, 'Programs', 'Git', 'bin', 'bash.exe'),
98
- // Scoop
99
- userProfile && join(userProfile, 'scoop', 'apps', 'git', 'current', 'bin', 'bash.exe'),
100
- // Chocolatey default
101
- 'C:\\tools\\git\\bin\\bash.exe',
102
- ].filter((p): p is string => Boolean(p));
103
-
104
- for (const c of candidates) {
105
- if (existsSync(c)) return c;
106
- }
107
-
108
- // Strategy 3: scan PATH for any entry containing "git" (e.g. Git's
109
- // mingw64/bin or usr/bin already in PATH), walk up to find bash.exe.
110
- // Catches custom install locations.
111
- const pathEntries = (process.env.PATH ?? '').split(';');
112
- for (const entry of pathEntries) {
113
- if (!/git/i.test(entry)) continue;
114
- const normalized = entry.replace(/\//g, '\\').replace(/\\+$/, '');
115
- const parts = normalized.split('\\');
116
- for (let depth = 1; depth <= 4; depth++) {
117
- const root = parts.slice(0, parts.length - depth).join('\\');
118
- if (!root) continue;
119
- const candidate = root + '\\bin\\bash.exe';
120
- if (existsSync(candidate)) return candidate;
121
- }
122
- }
123
-
124
- return null;
125
- }
126
-
127
- function findExeInPath(exe: string): string | null {
128
- const pathDirs = (process.env.PATH ?? '').split(';');
129
- for (const dir of pathDirs) {
130
- if (!dir) continue;
131
- const full = join(dir, exe);
132
- if (existsSync(full)) return full;
133
- }
134
- return null;
135
- }
136
-
137
- export const ClaudeCodeDriver: DriverPlugin = {
138
- name: 'claude-code',
139
-
140
- capabilities: {
141
- sessionResume: true,
142
- systemPrompt: true,
143
- outputFormat: true,
144
- } satisfies DriverCapabilities,
145
-
146
- resolveModel,
147
- resolveTools,
148
-
149
- async buildCommand(
150
- task: TaskConfig, track: TrackConfig, ctx: DriverContext,
151
- ): Promise<SpawnSpec> {
152
- const permissions = task.permissions ?? track.permissions!;
153
- const model = task.model ?? track.model ?? DEFAULT_MODEL;
154
- // SDK schema layer already resolved task → track → pipeline inheritance.
155
- // Drop unknown effort values so a typo can't break `claude -p` startup;
156
- // validateRaw / the UI should prevent this from reaching us in practice.
157
- const rawEffort = task.reasoning_effort ?? track.reasoning_effort;
158
- const effort = rawEffort && VALID_EFFORT.has(rawEffort) ? rawEffort : null;
159
- const tools = resolveTools(permissions);
160
- const permissionMode = resolvePermissionMode(permissions);
161
-
162
- // Pass the prompt via stdin instead of as a -p argument value. On Windows,
163
- // multi-line strings in CLI arguments break cmd.exe argument parsing when
164
- // the executable is a .cmd wrapper — newlines cause all subsequent flags
165
- // (--output-format, --model, etc.) to be silently dropped.
166
- const stdin = task.prompt!;
167
-
168
- const args: string[] = [
169
- 'claude',
170
- '-p', // no value prompt is piped via stdin
171
- '--model', model,
172
- '--allowedTools', tools,
173
- '--permission-mode', permissionMode,
174
- '--output-format', 'json',
175
- // NOTE: do NOT use --verbose here. It changes stdout from a single JSON
176
- // result object to a JSON event-stream array, breaking parseResult's
177
- // session_id extraction (needed for continue_from) and normalizedOutput.
178
- // The engine already captures stdout/stderr for pipeline logs.
179
- // Pin to project+local settings only; don't inherit arbitrary user-level
180
- // config (hooks, MCP servers, etc.) into pipeline automation.
181
- '--setting-sources', 'project,local',
182
- ];
183
-
184
- if (effort) {
185
- args.push('--effort', effort);
186
- }
187
-
188
- // If the task runs in a subdirectory of the project, grant read/edit
189
- // access to the project root via --add-dir so Claude can still see
190
- // shared files (configs, types, etc.) outside task.cwd.
191
- const effectiveCwd = task.cwd ?? ctx.workDir;
192
- if (effectiveCwd !== ctx.workDir && isInside(ctx.workDir, effectiveCwd)) {
193
- args.push('--add-dir', ctx.workDir);
194
- }
195
-
196
- // Native session resume
197
- if (task.continue_from) {
198
- const sessionId = ctx.sessionMap.get(task.continue_from);
199
- if (sessionId) {
200
- args.push('--resume', sessionId);
201
- }
202
- }
203
-
204
- // --append-system-prompt MUST be last: its value may contain newlines,
205
- // and on Windows cmd.exe can silently drop any flags that follow a
206
- // newline-containing argument.
207
- const profile = task.agent_profile ?? track.agent_profile;
208
- if (profile) {
209
- args.push('--append-system-prompt', profile);
210
- }
211
-
212
- return { args, cwd: effectiveCwd, env: resolveGitBashEnv(), stdin };
213
- },
214
-
215
- parseResult(stdout: string): DriverResultMeta {
216
- try {
217
- let json = JSON.parse(stdout);
218
-
219
- // --verbose produces a JSON array of events; extract the final "result"
220
- // event so session_id and normalizedOutput are correctly populated.
221
- if (Array.isArray(json)) {
222
- const resultEvent = json.findLast((e: Record<string, unknown>) => e.type === 'result');
223
- if (!resultEvent) return { normalizedOutput: stdout };
224
- json = resultEvent;
225
- }
226
-
227
- // Extract canonical text: strip JSON envelope so downstream drivers
228
- // get the actual AI response, not metadata
229
- const normalizedOutput = json.result ?? json.text ?? json.content ?? stdout;
230
- return {
231
- sessionId: json.session_id,
232
- normalizedOutput: typeof normalizedOutput === 'string'
233
- ? normalizedOutput
234
- : JSON.stringify(normalizedOutput),
235
- };
236
- } catch {
237
- return { normalizedOutput: stdout };
238
- }
239
- },
240
- };
1
+ import { existsSync } from 'node:fs';
2
+ import { isAbsolute, relative, dirname, join } from 'node:path';
3
+ import type {
4
+ DriverPlugin,
5
+ DriverCapabilities,
6
+ DriverResultMeta,
7
+ TaskConfig,
8
+ TrackConfig,
9
+ DriverContext,
10
+ SpawnSpec,
11
+ Permissions,
12
+ } from '../types';
13
+
14
+ // Claude Code CLI reference: https://code.claude.com/docs/en/cli-reference
15
+
16
+ const DEFAULT_MODEL = 'sonnet';
17
+
18
+ // Claude Code CLI accepts --effort low|medium|high|max. tagma's vocabulary
19
+ // is low|medium|high, so low/medium/high pass through unchanged; users who
20
+ // want the claude-specific "max" tier can also set it explicitly.
21
+ const VALID_EFFORT = new Set(['low', 'medium', 'high', 'max']);
22
+
23
+ function resolveModel(): string {
24
+ return DEFAULT_MODEL;
25
+ }
26
+
27
+ function resolveTools(permissions: Permissions): string {
28
+ const tools = ['Grep', 'Glob'];
29
+ if (permissions.read) tools.push('Read');
30
+ if (permissions.write) tools.push('Edit', 'Write');
31
+ if (permissions.execute) tools.push('Bash');
32
+ return tools.join(',');
33
+ }
34
+
35
+ // Maps our Permissions to Claude Code's --permission-mode. In print (-p) mode
36
+ // Claude needs non-interactive permission handling:
37
+ // - `bypassPermissions` skips all checks (required for reliable Bash automation
38
+ // under `execute: true`, matches the "full trust" semantics of that tier).
39
+ // - `dontAsk` auto-denies anything outside `--allowedTools`, which is exactly
40
+ // what we want for read/write tiers: the allowedTools whitelist already
41
+ // enumerates what Claude may do, and dontAsk makes violations fail fast
42
+ // instead of hanging on a prompt no one can answer in headless mode.
43
+ // See: https://code.claude.com/docs/en/permission-modes
44
+ function resolvePermissionMode(permissions: Permissions): string {
45
+ if (permissions.execute) return 'bypassPermissions';
46
+ return 'dontAsk';
47
+ }
48
+
49
+ // Returns true if `sub` is inside `root` (or equal to it).
50
+ function isInside(root: string, sub: string): boolean {
51
+ const rel = relative(root, sub);
52
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
53
+ }
54
+
55
+ // Claude Code requires CLAUDE_CODE_GIT_BASH_PATH on Windows pointing to
56
+ // Git Bash (bin\bash.exe under a Git for Windows install). See:
57
+ // https://code.claude.com/docs/en/troubleshooting#windows-claude-code-on-windows-requires-git-bash
58
+ // The path must use native Windows backslashes forward slashes are rejected
59
+ // by Claude Code's path validation.
60
+ function resolveGitBashEnv(): Record<string, string> {
61
+ if (process.platform !== 'win32') return {};
62
+
63
+ // Respect user-provided value if it points to an actual file. If the user
64
+ // set it to a non-existent path, fall through to discovery rather than
65
+ // propagating the broken config.
66
+ const existing = process.env.CLAUDE_CODE_GIT_BASH_PATH;
67
+ if (existing && existsSync(existing)) return {};
68
+
69
+ const discovered = discoverGitBash();
70
+ return discovered ? { CLAUDE_CODE_GIT_BASH_PATH: discovered } : {};
71
+ }
72
+
73
+ function discoverGitBash(): string | null {
74
+ // Strategy 1: find git.exe in PATH (equivalent to `where.exe git`) and
75
+ // walk up looking for bin\bash.exe under a Git install root. Git for
76
+ // Windows may expose multiple git.exe locations (cmd\git.exe,
77
+ // mingw64\bin\git.exe, mingw64\libexec\git-core\git.exe), so we walk up
78
+ // several levels rather than assuming a fixed depth.
79
+ const gitExe = findExeInPath('git.exe');
80
+ if (gitExe) {
81
+ let dir = dirname(gitExe);
82
+ for (let depth = 0; depth < 5; depth++) {
83
+ const candidate = join(dir, 'bin', 'bash.exe');
84
+ if (existsSync(candidate)) return candidate;
85
+ const parent = dirname(dir);
86
+ if (parent === dir) break;
87
+ dir = parent;
88
+ }
89
+ }
90
+
91
+ // Strategy 2: check common Git for Windows install locations.
92
+ // Uses %ProgramFiles%/%LOCALAPPDATA%/%USERPROFILE% env vars so it works on
93
+ // systems where those aren't mapped to C:\ (e.g. localized Windows).
94
+ const programFiles = process.env['ProgramFiles'] ?? 'C:\\Program Files';
95
+ const programFilesX86 = process.env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)';
96
+ const localAppData = process.env['LOCALAPPDATA'];
97
+ const userProfile = process.env['USERPROFILE'];
98
+
99
+ const candidates = [
100
+ join(programFiles, 'Git', 'bin', 'bash.exe'),
101
+ join(programFilesX86, 'Git', 'bin', 'bash.exe'),
102
+ // Git for Windows user-level install
103
+ localAppData && join(localAppData, 'Programs', 'Git', 'bin', 'bash.exe'),
104
+ // Scoop
105
+ userProfile && join(userProfile, 'scoop', 'apps', 'git', 'current', 'bin', 'bash.exe'),
106
+ // Chocolatey default
107
+ 'C:\\tools\\git\\bin\\bash.exe',
108
+ ].filter((p): p is string => Boolean(p));
109
+
110
+ for (const c of candidates) {
111
+ if (existsSync(c)) return c;
112
+ }
113
+
114
+ // Strategy 3: scan PATH for any entry containing "git" (e.g. Git's
115
+ // mingw64/bin or usr/bin already in PATH), walk up to find bash.exe.
116
+ // Catches custom install locations.
117
+ const pathEntries = (process.env.PATH ?? '').split(';');
118
+ for (const entry of pathEntries) {
119
+ if (!/git/i.test(entry)) continue;
120
+ const normalized = entry.replace(/\//g, '\\').replace(/\\+$/, '');
121
+ const parts = normalized.split('\\');
122
+ for (let depth = 1; depth <= 4; depth++) {
123
+ const root = parts.slice(0, parts.length - depth).join('\\');
124
+ if (!root) continue;
125
+ const candidate = root + '\\bin\\bash.exe';
126
+ if (existsSync(candidate)) return candidate;
127
+ }
128
+ }
129
+
130
+ return null;
131
+ }
132
+
133
+ function findExeInPath(exe: string): string | null {
134
+ const pathDirs = (process.env.PATH ?? '').split(';');
135
+ for (const dir of pathDirs) {
136
+ if (!dir) continue;
137
+ const full = join(dir, exe);
138
+ if (existsSync(full)) return full;
139
+ }
140
+ return null;
141
+ }
142
+
143
+ export const ClaudeCodeDriver: DriverPlugin = {
144
+ name: 'claude-code',
145
+
146
+ capabilities: {
147
+ sessionResume: true,
148
+ systemPrompt: true,
149
+ outputFormat: true,
150
+ } satisfies DriverCapabilities,
151
+
152
+ resolveModel,
153
+ resolveTools,
154
+
155
+ async buildCommand(task: TaskConfig, track: TrackConfig, ctx: DriverContext): Promise<SpawnSpec> {
156
+ const permissions = task.permissions ?? track.permissions!;
157
+ const model = task.model ?? track.model ?? DEFAULT_MODEL;
158
+ // SDK schema layer already resolved task track → pipeline inheritance.
159
+ // Drop unknown effort values so a typo can't break `claude -p` startup;
160
+ // validateRaw / the UI should prevent this from reaching us in practice.
161
+ const rawEffort = task.reasoning_effort ?? track.reasoning_effort;
162
+ const effort = rawEffort && VALID_EFFORT.has(rawEffort) ? rawEffort : null;
163
+ const tools = resolveTools(permissions);
164
+ const permissionMode = resolvePermissionMode(permissions);
165
+
166
+ // Pass the prompt via stdin instead of as a -p argument value. On Windows,
167
+ // multi-line strings in CLI arguments break cmd.exe argument parsing when
168
+ // the executable is a .cmd wrapper — newlines cause all subsequent flags
169
+ // (--output-format, --model, etc.) to be silently dropped.
170
+ const stdin = task.prompt!;
171
+
172
+ const args: string[] = [
173
+ 'claude',
174
+ '-p', // no value — prompt is piped via stdin
175
+ '--model',
176
+ model,
177
+ '--allowedTools',
178
+ tools,
179
+ '--permission-mode',
180
+ permissionMode,
181
+ '--output-format',
182
+ 'json',
183
+ // NOTE: do NOT use --verbose here. It changes stdout from a single JSON
184
+ // result object to a JSON event-stream array, breaking parseResult's
185
+ // session_id extraction (needed for continue_from) and normalizedOutput.
186
+ // The engine already captures stdout/stderr for pipeline logs.
187
+ // Pin to project+local settings only; don't inherit arbitrary user-level
188
+ // config (hooks, MCP servers, etc.) into pipeline automation.
189
+ '--setting-sources',
190
+ 'project,local',
191
+ ];
192
+
193
+ if (effort) {
194
+ args.push('--effort', effort);
195
+ }
196
+
197
+ // If the task runs in a subdirectory of the project, grant read/edit
198
+ // access to the project root via --add-dir so Claude can still see
199
+ // shared files (configs, types, etc.) outside task.cwd.
200
+ const effectiveCwd = task.cwd ?? ctx.workDir;
201
+ if (effectiveCwd !== ctx.workDir && isInside(ctx.workDir, effectiveCwd)) {
202
+ args.push('--add-dir', ctx.workDir);
203
+ }
204
+
205
+ // Native session resume
206
+ if (task.continue_from) {
207
+ const sessionId = ctx.sessionMap.get(task.continue_from);
208
+ if (sessionId) {
209
+ args.push('--resume', sessionId);
210
+ }
211
+ }
212
+
213
+ // --append-system-prompt MUST be last: its value may contain newlines,
214
+ // and on Windows cmd.exe can silently drop any flags that follow a
215
+ // newline-containing argument.
216
+ const profile = task.agent_profile ?? track.agent_profile;
217
+ if (profile) {
218
+ args.push('--append-system-prompt', profile);
219
+ }
220
+
221
+ return { args, cwd: effectiveCwd, env: resolveGitBashEnv(), stdin };
222
+ },
223
+
224
+ parseResult(stdout: string): DriverResultMeta {
225
+ try {
226
+ let json = JSON.parse(stdout);
227
+
228
+ // --verbose produces a JSON array of events; extract the final "result"
229
+ // event so session_id and normalizedOutput are correctly populated.
230
+ if (Array.isArray(json)) {
231
+ const resultEvent = json.findLast((e: Record<string, unknown>) => e.type === 'result');
232
+ if (!resultEvent) return { normalizedOutput: stdout };
233
+ json = resultEvent;
234
+ }
235
+
236
+ // Extract canonical text: strip JSON envelope so downstream drivers
237
+ // get the actual AI response, not metadata
238
+ const normalizedOutput = json.result ?? json.text ?? json.content ?? stdout;
239
+ return {
240
+ sessionId: json.session_id,
241
+ normalizedOutput:
242
+ typeof normalizedOutput === 'string'
243
+ ? normalizedOutput
244
+ : JSON.stringify(normalizedOutput),
245
+ };
246
+ } catch {
247
+ return { normalizedOutput: stdout };
248
+ }
249
+ },
250
+ };