@scottwalker/claude-connector 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 (91) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +444 -0
  3. package/dist/builder/args-builder.d.ts +64 -0
  4. package/dist/builder/args-builder.d.ts.map +1 -0
  5. package/dist/builder/args-builder.js +134 -0
  6. package/dist/builder/args-builder.js.map +1 -0
  7. package/dist/builder/index.d.ts +2 -0
  8. package/dist/builder/index.d.ts.map +1 -0
  9. package/dist/builder/index.js +2 -0
  10. package/dist/builder/index.js.map +1 -0
  11. package/dist/client/claude.d.ts +120 -0
  12. package/dist/client/claude.d.ts.map +1 -0
  13. package/dist/client/claude.js +182 -0
  14. package/dist/client/claude.js.map +1 -0
  15. package/dist/client/session.d.ts +64 -0
  16. package/dist/client/session.d.ts.map +1 -0
  17. package/dist/client/session.js +128 -0
  18. package/dist/client/session.js.map +1 -0
  19. package/dist/errors/errors.d.ts +52 -0
  20. package/dist/errors/errors.d.ts.map +1 -0
  21. package/dist/errors/errors.js +78 -0
  22. package/dist/errors/errors.js.map +1 -0
  23. package/dist/errors/index.d.ts +2 -0
  24. package/dist/errors/index.d.ts.map +1 -0
  25. package/dist/errors/index.js +2 -0
  26. package/dist/errors/index.js.map +1 -0
  27. package/dist/executor/cli-executor.d.ts +35 -0
  28. package/dist/executor/cli-executor.d.ts.map +1 -0
  29. package/dist/executor/cli-executor.js +223 -0
  30. package/dist/executor/cli-executor.js.map +1 -0
  31. package/dist/executor/index.d.ts +4 -0
  32. package/dist/executor/index.d.ts.map +1 -0
  33. package/dist/executor/index.js +3 -0
  34. package/dist/executor/index.js.map +1 -0
  35. package/dist/executor/interface.d.ts +65 -0
  36. package/dist/executor/interface.d.ts.map +1 -0
  37. package/dist/executor/interface.js +2 -0
  38. package/dist/executor/interface.js.map +1 -0
  39. package/dist/executor/sdk-executor.d.ts +102 -0
  40. package/dist/executor/sdk-executor.d.ts.map +1 -0
  41. package/dist/executor/sdk-executor.js +256 -0
  42. package/dist/executor/sdk-executor.js.map +1 -0
  43. package/dist/index.d.ts +49 -0
  44. package/dist/index.d.ts.map +1 -0
  45. package/dist/index.js +49 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/parser/index.d.ts +3 -0
  48. package/dist/parser/index.d.ts.map +1 -0
  49. package/dist/parser/index.js +3 -0
  50. package/dist/parser/index.js.map +1 -0
  51. package/dist/parser/json-parser.d.ts +22 -0
  52. package/dist/parser/json-parser.d.ts.map +1 -0
  53. package/dist/parser/json-parser.js +87 -0
  54. package/dist/parser/json-parser.js.map +1 -0
  55. package/dist/parser/stream-parser.d.ts +21 -0
  56. package/dist/parser/stream-parser.d.ts.map +1 -0
  57. package/dist/parser/stream-parser.js +84 -0
  58. package/dist/parser/stream-parser.js.map +1 -0
  59. package/dist/scheduler/index.d.ts +2 -0
  60. package/dist/scheduler/index.d.ts.map +1 -0
  61. package/dist/scheduler/index.js +2 -0
  62. package/dist/scheduler/index.js.map +1 -0
  63. package/dist/scheduler/scheduler.d.ts +65 -0
  64. package/dist/scheduler/scheduler.d.ts.map +1 -0
  65. package/dist/scheduler/scheduler.js +134 -0
  66. package/dist/scheduler/scheduler.js.map +1 -0
  67. package/dist/types/client.d.ts +184 -0
  68. package/dist/types/client.d.ts.map +1 -0
  69. package/dist/types/client.js +2 -0
  70. package/dist/types/client.js.map +1 -0
  71. package/dist/types/index.d.ts +4 -0
  72. package/dist/types/index.d.ts.map +1 -0
  73. package/dist/types/index.js +2 -0
  74. package/dist/types/index.js.map +1 -0
  75. package/dist/types/result.d.ts +94 -0
  76. package/dist/types/result.d.ts.map +1 -0
  77. package/dist/types/result.js +2 -0
  78. package/dist/types/result.js.map +1 -0
  79. package/dist/types/session.d.ts +37 -0
  80. package/dist/types/session.d.ts.map +1 -0
  81. package/dist/types/session.js +2 -0
  82. package/dist/types/session.js.map +1 -0
  83. package/dist/utils/index.d.ts +2 -0
  84. package/dist/utils/index.d.ts.map +1 -0
  85. package/dist/utils/index.js +2 -0
  86. package/dist/utils/index.js.map +1 -0
  87. package/dist/utils/validation.d.ts +15 -0
  88. package/dist/utils/validation.d.ts.map +1 -0
  89. package/dist/utils/validation.js +45 -0
  90. package/dist/utils/validation.js.map +1 -0
  91. package/package.json +62 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/errors/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,iBAAiB,EACjB,eAAe,EACf,UAAU,EACV,eAAe,GAChB,MAAM,aAAa,CAAC"}
@@ -0,0 +1,35 @@
1
+ import type { QueryResult, StreamEvent } from '../types/index.js';
2
+ import type { IExecutor, ExecuteOptions } from './interface.js';
3
+ /**
4
+ * Executor implementation that spawns the Claude Code CLI as a child process.
5
+ *
6
+ * ## How it works
7
+ *
8
+ * - `execute()` spawns `claude -p <prompt> --output-format json` and collects stdout.
9
+ * - `stream()` spawns `claude -p <prompt> --output-format stream-json` and parses
10
+ * newline-delimited JSON (NDJSON) from stdout in real time.
11
+ *
12
+ * ## Error handling
13
+ *
14
+ * - Non-zero exit code → {@link CliExecutionError}
15
+ * - `ENOENT` (binary not found) → {@link CliNotFoundError}
16
+ * - Timeout → {@link CliTimeoutError}
17
+ *
18
+ * ## Lifecycle
19
+ *
20
+ * Each call to `execute()` or `stream()` spawns a fresh process.
21
+ * The executor is stateless — safe to use concurrently from multiple queries.
22
+ */
23
+ export declare class CliExecutor implements IExecutor {
24
+ private readonly executable;
25
+ private readonly timeoutMs;
26
+ private activeProcess;
27
+ constructor(executable?: string, timeoutMs?: number);
28
+ execute(args: readonly string[], options: ExecuteOptions): Promise<QueryResult>;
29
+ stream(args: readonly string[], options: ExecuteOptions): AsyncIterable<StreamEvent>;
30
+ abort(): void;
31
+ private spawnProcess;
32
+ private spawn;
33
+ private readStream;
34
+ }
35
+ //# sourceMappingURL=cli-executor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli-executor.d.ts","sourceRoot":"","sources":["../../src/executor/cli-executor.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAClE,OAAO,KAAK,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAQhE;;;;;;;;;;;;;;;;;;;GAmBG;AACH,qBAAa,WAAY,YAAW,SAAS;IAC3C,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,aAAa,CAA6B;gBAEtC,UAAU,GAAE,MAAiB,EAAE,SAAS,GAAE,MAA2B;IAK3E,OAAO,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,EAAE,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,WAAW,CAAC;IAc9E,MAAM,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,EAAE,OAAO,EAAE,cAAc,GAAG,aAAa,CAAC,WAAW,CAAC;IAW3F,KAAK,IAAI,IAAI;IASb,OAAO,CAAC,YAAY;IAwBpB,OAAO,CAAC,KAAK;YA2CE,UAAU;CAsC1B"}
@@ -0,0 +1,223 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { parseJsonResult } from '../parser/json-parser.js';
3
+ import { parseStreamLine } from '../parser/stream-parser.js';
4
+ import { CliExecutionError, CliNotFoundError, CliTimeoutError } from '../errors/errors.js';
5
+ /**
6
+ * Default timeout for CLI execution (10 minutes).
7
+ * Long-running agentic tasks can exceed typical HTTP timeouts.
8
+ */
9
+ const DEFAULT_TIMEOUT_MS = 600_000;
10
+ /**
11
+ * Executor implementation that spawns the Claude Code CLI as a child process.
12
+ *
13
+ * ## How it works
14
+ *
15
+ * - `execute()` spawns `claude -p <prompt> --output-format json` and collects stdout.
16
+ * - `stream()` spawns `claude -p <prompt> --output-format stream-json` and parses
17
+ * newline-delimited JSON (NDJSON) from stdout in real time.
18
+ *
19
+ * ## Error handling
20
+ *
21
+ * - Non-zero exit code → {@link CliExecutionError}
22
+ * - `ENOENT` (binary not found) → {@link CliNotFoundError}
23
+ * - Timeout → {@link CliTimeoutError}
24
+ *
25
+ * ## Lifecycle
26
+ *
27
+ * Each call to `execute()` or `stream()` spawns a fresh process.
28
+ * The executor is stateless — safe to use concurrently from multiple queries.
29
+ */
30
+ export class CliExecutor {
31
+ executable;
32
+ timeoutMs;
33
+ activeProcess = null;
34
+ constructor(executable = 'claude', timeoutMs = DEFAULT_TIMEOUT_MS) {
35
+ this.executable = executable;
36
+ this.timeoutMs = timeoutMs;
37
+ }
38
+ async execute(args, options) {
39
+ const { stdout, stderr, exitCode } = await this.spawn(args, options);
40
+ if (exitCode !== 0) {
41
+ throw new CliExecutionError(`CLI exited with code ${exitCode}: ${stderr}`, exitCode, stderr);
42
+ }
43
+ return parseJsonResult(stdout);
44
+ }
45
+ async *stream(args, options) {
46
+ const child = this.spawnProcess(args, options);
47
+ this.activeProcess = child;
48
+ try {
49
+ yield* this.readStream(child);
50
+ }
51
+ finally {
52
+ this.activeProcess = null;
53
+ }
54
+ }
55
+ abort() {
56
+ if (this.activeProcess && !this.activeProcess.killed) {
57
+ this.activeProcess.kill('SIGTERM');
58
+ this.activeProcess = null;
59
+ }
60
+ }
61
+ // ── Private helpers ───────────────────────────────────────────────
62
+ spawnProcess(args, options) {
63
+ try {
64
+ const child = spawn(this.executable, args, {
65
+ cwd: options.cwd,
66
+ env: { ...process.env, ...options.env },
67
+ stdio: ['pipe', 'pipe', 'pipe'],
68
+ });
69
+ if (options.input && child.stdin) {
70
+ child.stdin.write(options.input);
71
+ child.stdin.end();
72
+ }
73
+ else if (child.stdin) {
74
+ child.stdin.end();
75
+ }
76
+ return child;
77
+ }
78
+ catch (error) {
79
+ if (isNodeError(error) && error.code === 'ENOENT') {
80
+ throw new CliNotFoundError(this.executable);
81
+ }
82
+ throw error;
83
+ }
84
+ }
85
+ spawn(args, options) {
86
+ return new Promise((resolve, reject) => {
87
+ const child = this.spawnProcess(args, options);
88
+ this.activeProcess = child;
89
+ const chunks = [];
90
+ const errChunks = [];
91
+ child.stdout.on('data', (chunk) => chunks.push(chunk));
92
+ child.stderr.on('data', (chunk) => errChunks.push(chunk));
93
+ const timer = setTimeout(() => {
94
+ child.kill('SIGTERM');
95
+ reject(new CliTimeoutError(this.timeoutMs));
96
+ }, this.timeoutMs);
97
+ child.on('error', (err) => {
98
+ clearTimeout(timer);
99
+ this.activeProcess = null;
100
+ if (err.code === 'ENOENT') {
101
+ reject(new CliNotFoundError(this.executable));
102
+ }
103
+ else {
104
+ reject(err);
105
+ }
106
+ });
107
+ child.on('close', (exitCode) => {
108
+ clearTimeout(timer);
109
+ this.activeProcess = null;
110
+ resolve({
111
+ stdout: Buffer.concat(chunks).toString('utf-8'),
112
+ stderr: Buffer.concat(errChunks).toString('utf-8'),
113
+ exitCode: exitCode ?? 1,
114
+ });
115
+ });
116
+ });
117
+ }
118
+ async *readStream(child) {
119
+ // Buffer for incomplete lines (NDJSON may arrive in partial chunks)
120
+ let buffer = '';
121
+ const iterator = createAsyncIterator(child, (chunk, push) => {
122
+ buffer += chunk.toString('utf-8');
123
+ const lines = buffer.split('\n');
124
+ // Keep the last (possibly incomplete) line in the buffer
125
+ buffer = lines.pop() ?? '';
126
+ for (const line of lines) {
127
+ const trimmed = line.trim();
128
+ if (!trimmed)
129
+ continue;
130
+ const event = parseStreamLine(trimmed);
131
+ if (event)
132
+ push(event);
133
+ }
134
+ }, () => {
135
+ // Flush remaining buffer on stream end
136
+ const trimmed = buffer.trim();
137
+ if (trimmed) {
138
+ const event = parseStreamLine(trimmed);
139
+ if (event)
140
+ return event;
141
+ }
142
+ return null;
143
+ });
144
+ for await (const event of iterator) {
145
+ if (event !== null) {
146
+ yield event;
147
+ }
148
+ }
149
+ }
150
+ }
151
+ // ── Utility ───────────────────────────────────────────────────────
152
+ function isNodeError(err) {
153
+ return err instanceof Error && 'code' in err;
154
+ }
155
+ /**
156
+ * Creates an async iterator from a child process stdout.
157
+ * Handles backpressure, errors, and process exit.
158
+ */
159
+ function createAsyncIterator(child, onData, onEnd) {
160
+ return {
161
+ [Symbol.asyncIterator]() {
162
+ const queue = [];
163
+ let resolve = null;
164
+ let done = false;
165
+ let error = null;
166
+ const push = (item) => {
167
+ if (resolve) {
168
+ const r = resolve;
169
+ resolve = null;
170
+ r({ value: item, done: false });
171
+ }
172
+ else {
173
+ queue.push(item);
174
+ }
175
+ };
176
+ child.stdout.on('data', (chunk) => {
177
+ onData(chunk, push);
178
+ });
179
+ child.stderr.on('data', (chunk) => {
180
+ // Capture stderr but don't fail — CLI may log warnings there
181
+ const text = chunk.toString('utf-8').trim();
182
+ if (text) {
183
+ push({ type: 'system', subtype: 'stderr', data: { text } });
184
+ }
185
+ });
186
+ const finish = () => {
187
+ if (done)
188
+ return;
189
+ done = true;
190
+ const final = onEnd();
191
+ if (final !== null)
192
+ push(final);
193
+ if (resolve) {
194
+ const r = resolve;
195
+ resolve = null;
196
+ r({ value: undefined, done: true });
197
+ }
198
+ };
199
+ child.on('close', finish);
200
+ child.on('error', (err) => {
201
+ error = err;
202
+ finish();
203
+ });
204
+ return {
205
+ next() {
206
+ if (queue.length > 0) {
207
+ return Promise.resolve({ value: queue.shift(), done: false });
208
+ }
209
+ if (done) {
210
+ return Promise.resolve({ value: undefined, done: true });
211
+ }
212
+ if (error) {
213
+ return Promise.reject(error);
214
+ }
215
+ return new Promise((r) => {
216
+ resolve = r;
217
+ });
218
+ },
219
+ };
220
+ },
221
+ };
222
+ }
223
+ //# sourceMappingURL=cli-executor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli-executor.js","sourceRoot":"","sources":["../../src/executor/cli-executor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAqB,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAC3D,OAAO,EAAE,eAAe,EAA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AAO,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE;wBACvB,OAAO,GAAG,CAAC,CAAC;oBACd,CAAC,CAAC,CAAC;gBACL,CAAC;aACF,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,4 @@
1
+ export type { IExecutor, ExecuteOptions } from './interface.js';
2
+ export { CliExecutor } from './cli-executor.js';
3
+ export { SdkExecutor, type SdkExecutorOptions, type SdkExecutorEvents, type InitStage } from './sdk-executor.js';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/executor/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,KAAK,kBAAkB,EAAE,KAAK,iBAAiB,EAAE,KAAK,SAAS,EAAE,MAAM,mBAAmB,CAAC"}
@@ -0,0 +1,3 @@
1
+ export { CliExecutor } from './cli-executor.js';
2
+ export { SdkExecutor } from './sdk-executor.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/executor/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAmE,MAAM,mBAAmB,CAAC"}
@@ -0,0 +1,65 @@
1
+ import type { QueryResult, StreamEvent } from '../types/index.js';
2
+ /**
3
+ * Abstract execution interface — the core abstraction of claude-connector.
4
+ *
5
+ * All interaction with Claude Code goes through an executor. This decouples
6
+ * the public API ({@link Claude}, {@link Session}) from the underlying
7
+ * transport mechanism.
8
+ *
9
+ * ## Why this abstraction exists
10
+ *
11
+ * Today the only executor is {@link CliExecutor} (spawns `claude -p`).
12
+ * Tomorrow Anthropic may ship a native Node.js SDK, an HTTP API,
13
+ * or a Unix socket interface. By coding against `IExecutor`, the entire
14
+ * public surface remains stable — only a new executor implementation is needed.
15
+ *
16
+ * ## Contract
17
+ *
18
+ * - `execute()` runs a query to completion and returns a structured result.
19
+ * - `stream()` runs a query and yields incremental events as an async iterator.
20
+ * - Both methods receive a fully resolved argument list (no option merging here).
21
+ * - Executors must NOT hold mutable state between calls (stateless per invocation).
22
+ * - Error conditions must throw {@link ClaudeConnectorError} subclasses.
23
+ */
24
+ export interface IExecutor {
25
+ /**
26
+ * Execute a query and return the complete result.
27
+ *
28
+ * @param args - Resolved CLI arguments (produced by ArgsBuilder).
29
+ * @param options - Execution-level options (cwd, env, input).
30
+ * @returns Parsed query result.
31
+ */
32
+ execute(args: readonly string[], options: ExecuteOptions): Promise<QueryResult>;
33
+ /**
34
+ * Execute a query and stream incremental events.
35
+ *
36
+ * The returned async iterable yields events as they arrive.
37
+ * The final event is always of type `'result'` or `'error'`.
38
+ *
39
+ * @param args - Resolved CLI arguments (produced by ArgsBuilder).
40
+ * @param options - Execution-level options (cwd, env, input).
41
+ * @returns Async iterable of stream events.
42
+ */
43
+ stream(args: readonly string[], options: ExecuteOptions): AsyncIterable<StreamEvent>;
44
+ /**
45
+ * Abort a running execution.
46
+ * Implementations should kill the underlying process gracefully.
47
+ */
48
+ abort?(): void;
49
+ }
50
+ /**
51
+ * Low-level options passed directly to the executor.
52
+ * These are resolved from ClientOptions + QueryOptions by the client layer.
53
+ */
54
+ export interface ExecuteOptions {
55
+ /** Working directory for the CLI process. */
56
+ readonly cwd: string;
57
+ /** Environment variables merged with process.env. */
58
+ readonly env: Readonly<Record<string, string>>;
59
+ /**
60
+ * Data piped to the CLI's stdin.
61
+ * Equivalent to `echo "data" | claude -p "prompt"`.
62
+ */
63
+ readonly input?: string;
64
+ }
65
+ //# sourceMappingURL=interface.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interface.d.ts","sourceRoot":"","sources":["../../src/executor/interface.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAElE;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,WAAW,SAAS;IACxB;;;;;;OAMG;IACH,OAAO,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,EAAE,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;IAEhF;;;;;;;;;OASG;IACH,MAAM,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,EAAE,OAAO,EAAE,cAAc,GAAG,aAAa,CAAC,WAAW,CAAC,CAAC;IAErF;;;OAGG;IACH,KAAK,CAAC,IAAI,IAAI,CAAC;CAChB;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC7B,6CAA6C;IAC7C,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IAErB,qDAAqD;IACrD,QAAQ,CAAC,GAAG,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAE/C;;;OAGG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;CACzB"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=interface.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interface.js","sourceRoot":"","sources":["../../src/executor/interface.ts"],"names":[],"mappings":""}
@@ -0,0 +1,102 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import type { QueryResult, StreamEvent } from '../types/index.js';
3
+ import type { IExecutor, ExecuteOptions } from './interface.js';
4
+ /**
5
+ * Initialization stages emitted during SDK warm-up.
6
+ */
7
+ export type InitStage = 'importing' | 'creating' | 'connecting' | 'ready';
8
+ /**
9
+ * Events emitted by SdkExecutor.
10
+ */
11
+ export interface SdkExecutorEvents {
12
+ /** Emitted as initialization progresses through stages. */
13
+ 'init:stage': [InitStage, string];
14
+ /** Emitted once the session is fully warmed up. */
15
+ 'init:ready': [];
16
+ /** Emitted if initialization fails. */
17
+ 'init:error': [Error];
18
+ }
19
+ /**
20
+ * Executor implementation using the Claude Agent SDK (V2 API).
21
+ *
22
+ * ## Why this exists
23
+ *
24
+ * The CLI executor (`CliExecutor`) spawns a new `claude` process for every query.
25
+ * Each spawn has a cold-start cost: loading the CLI, authenticating, initializing
26
+ * tools and MCP servers. For interactive use this delay is noticeable (5-15s).
27
+ *
28
+ * `SdkExecutor` solves this by creating a **persistent SDK session** via
29
+ * `unstable_v2_createSession()`. The session stays warm — subsequent queries
30
+ * use `session.send()` + `session.stream()` with near-zero overhead.
31
+ *
32
+ * ## Lifecycle
33
+ *
34
+ * ```
35
+ * const executor = new SdkExecutor({ model: 'sonnet' })
36
+ * await executor.init() // warm up (emits stage events)
37
+ * executor.execute(args, opts) // fast — session already running
38
+ * executor.execute(args, opts) // fast
39
+ * executor.close() // cleanup
40
+ * ```
41
+ *
42
+ * ## Initialization events
43
+ *
44
+ * Subscribe to stage events for UI feedback:
45
+ * ```
46
+ * executor.on('init:stage', (stage, message) => {
47
+ * console.log(`[${stage}] ${message}`)
48
+ * })
49
+ * executor.on('init:ready', () => console.log('Ready!'))
50
+ * ```
51
+ */
52
+ export declare class SdkExecutor extends EventEmitter<SdkExecutorEvents> implements IExecutor {
53
+ private sdkModule;
54
+ private session;
55
+ private _ready;
56
+ private initPromise;
57
+ private readonly sdkOptions;
58
+ constructor(options: SdkExecutorOptions);
59
+ /** Whether the session is initialized and ready for queries. */
60
+ get ready(): boolean;
61
+ /**
62
+ * Initialize the SDK session (warm up).
63
+ *
64
+ * This imports the SDK, creates a persistent session, and waits for
65
+ * the `system/init` message confirming Claude Code is ready.
66
+ *
67
+ * Call this once at startup. Subsequent queries will be fast.
68
+ * Safe to call multiple times — only initializes once.
69
+ */
70
+ init(): Promise<void>;
71
+ execute(args: readonly string[], options: ExecuteOptions): Promise<QueryResult>;
72
+ stream(args: readonly string[], options: ExecuteOptions): AsyncIterable<StreamEvent>;
73
+ abort(): void;
74
+ /**
75
+ * Close the SDK session and free resources.
76
+ */
77
+ close(): void;
78
+ private doInit;
79
+ private ensureReady;
80
+ /**
81
+ * Map an SDK message to our StreamEvent type.
82
+ */
83
+ private mapMessage;
84
+ }
85
+ /**
86
+ * Options for SdkExecutor.
87
+ */
88
+ export interface SdkExecutorOptions {
89
+ /** Model to use. Default: 'sonnet'. */
90
+ readonly model?: string;
91
+ /** Path to Claude Code executable (for SDK internal use). */
92
+ readonly pathToClaudeCodeExecutable?: string;
93
+ /** Permission mode. */
94
+ readonly permissionMode?: string;
95
+ /** Auto-approved tools. */
96
+ readonly allowedTools?: readonly string[];
97
+ /** Denied tools. */
98
+ readonly disallowedTools?: readonly string[];
99
+ /** Extra environment variables. */
100
+ readonly env?: Readonly<Record<string, string>>;
101
+ }
102
+ //# sourceMappingURL=sdk-executor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sdk-executor.d.ts","sourceRoot":"","sources":["../../src/executor/sdk-executor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAc,MAAM,mBAAmB,CAAC;AAC9E,OAAO,KAAK,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAShE;;GAEG;AACH,MAAM,MAAM,SAAS,GACjB,WAAW,GACX,UAAU,GACV,YAAY,GACZ,OAAO,CAAC;AAEZ;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,2DAA2D;IAC3D,YAAY,EAAE,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;IAClC,mDAAmD;IACnD,YAAY,EAAE,EAAE,CAAC;IACjB,uCAAuC;IACvC,YAAY,EAAE,CAAC,KAAK,CAAC,CAAC;CACvB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,qBAAa,WAAY,SAAQ,YAAY,CAAC,iBAAiB,CAAE,YAAW,SA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