@tagma/driver-claude-code 0.3.6 → 0.3.7

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