coding-agents-sdk 0.2.0 → 0.3.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 (59) hide show
  1. package/README.md +32 -0
  2. package/dist/SdkAgent-a97nkDuR.mjs +1 -0
  3. package/dist/adapters/claude-code-cli/index.d.mts +1 -1
  4. package/dist/adapters/claude-code-cli/index.mjs +2 -490
  5. package/dist/adapters/claude-code-sdk/index.d.mts +1 -1
  6. package/dist/adapters/claude-code-sdk/index.mjs +4 -483
  7. package/dist/adapters/codex-cli/index.d.mts +1 -1
  8. package/dist/adapters/codex-cli/index.mjs +2 -626
  9. package/dist/adapters/codex-sdk/index.d.mts +1 -1
  10. package/dist/adapters/codex-sdk/index.mjs +1 -286
  11. package/dist/adapters/gemini-cli/index.d.mts +1 -1
  12. package/dist/adapters/gemini-cli/index.mjs +1 -292
  13. package/dist/classify-error-V6x6jP_R.mjs +8 -0
  14. package/dist/container/index.d.mts +1 -1
  15. package/dist/container/index.mjs +1 -24
  16. package/dist/container-BY7JDOGo.mjs +1 -0
  17. package/dist/container-DWTITDhL.mjs +1 -0
  18. package/dist/container-vkn5-3Xl.mjs +1 -0
  19. package/dist/diff-BCfLDXNN.mjs +1 -0
  20. package/dist/env-Dkd8Sgjf.mjs +1 -0
  21. package/dist/errors-XV0frS3r.mjs +1 -0
  22. package/dist/execution-target-BJ5mWjDM.mjs +4 -0
  23. package/dist/{index-C3ZxLAd0.d.mts → index-COHwWTg_.d.mts} +6 -6
  24. package/dist/{index-B3YqrgIp.d.mts → index-CzvanLE_.d.mts} +3 -2
  25. package/dist/index-DCaZeLrI.d.mts +51 -0
  26. package/dist/{index-dRVpEAr8.d.mts → index-DNyKelMh.d.mts} +5 -5
  27. package/dist/{index-nzo1sBiK.d.mts → index-DP4Jxoax.d.mts} +7 -7
  28. package/dist/{index-ByAOGMUM.d.mts → index-R77YR8ak.d.mts} +1 -1
  29. package/dist/{index-CFpNOmdA.d.mts → index-jUwKDQ34.d.mts} +2 -1
  30. package/dist/index.d.mts +10 -9
  31. package/dist/index.mjs +1 -61
  32. package/dist/oci-C_S_FKHj.mjs +1 -0
  33. package/dist/sandbox/index.d.mts +2 -0
  34. package/dist/sandbox/index.mjs +1 -0
  35. package/dist/sandbox-DeKpyenZ.mjs +1 -0
  36. package/dist/schemas/index.d.mts +1 -1
  37. package/dist/schemas/index.mjs +1 -2
  38. package/dist/schemas-BM6qORw3.mjs +1 -0
  39. package/dist/spawner-BJesLc8I.mjs +1 -0
  40. package/dist/structured-output-DEkBQ-1Z.mjs +1 -0
  41. package/dist/{types-Cb_EXIEe.d.mts → types-COlDAzs5.d.mts} +9 -24
  42. package/dist/types-CwvWHEpy.mjs +1 -0
  43. package/dist/util-CGg8cK92.mjs +1 -0
  44. package/package.json +5 -1
  45. package/dist/Agent-D8WkUilj.mjs +0 -262
  46. package/dist/SdkAgent-B47mJiIE.mjs +0 -38
  47. package/dist/classify-error-pL6jeu4T.mjs +0 -456
  48. package/dist/container-2UmPZ0CI.mjs +0 -22
  49. package/dist/container-CHxKIonn.mjs +0 -440
  50. package/dist/container-D2Z0ITDJ.mjs +0 -22
  51. package/dist/diff-De8d3MVb.mjs +0 -333
  52. package/dist/errors-BAmHDQu8.mjs +0 -45
  53. package/dist/oci-DMZZQZ47.mjs +0 -438
  54. package/dist/schemas-DwD4pwJB.mjs +0 -96
  55. package/dist/spawner-Bw9UBEGX.mjs +0 -54
  56. package/dist/structured-output-BHtr_zpz.mjs +0 -19
  57. package/dist/types-aNMD8h3x.mjs +0 -19
  58. package/dist/util-B4RQZkKr.mjs +0 -77
  59. /package/dist/{events-nxuRbYIu.d.mts → events-D31_b0sA.d.mts} +0 -0
@@ -1,438 +0,0 @@
1
- import { t as formatError } from "./util-B4RQZkKr.mjs";
2
- import { a as ContainerExecError, n as ContainerDiffError, o as ContainerNotRunningError, r as ContainerDisposedError, s as ContainerStartError, t as ContainerCreateError } from "./errors-BAmHDQu8.mjs";
3
- import { t as DEFAULT_SPAWNER } from "./spawner-Bw9UBEGX.mjs";
4
- import { i as isExecFileError, n as createWorkdirDiffApi, r as shellEscape, t as copyLocalDirectoryContents } from "./diff-De8d3MVb.mjs";
5
- import { mkdtemp, rm, writeFile } from "node:fs/promises";
6
- import { tmpdir } from "node:os";
7
- import { isAbsolute, join, posix } from "node:path";
8
- import { execFile } from "node:child_process";
9
- import { randomBytes } from "node:crypto";
10
- import { promisify } from "node:util";
11
- //#region src/container/oci.ts
12
- const execFileAsync = promisify(execFile);
13
- const generateContainerName = () => `cw-${randomBytes(6).toString("hex")}`;
14
- const runOci = async (binary, args, options) => {
15
- const result = await execFileAsync(binary, args, {
16
- encoding: "utf8",
17
- timeout: options?.timeoutMs,
18
- signal: options?.signal,
19
- maxBuffer: 50 * 1024 * 1024
20
- });
21
- return {
22
- stdout: result.stdout,
23
- stderr: result.stderr
24
- };
25
- };
26
- const buildOciImage = async (binary, build) => {
27
- const tag = build.tag ?? `cw-build-${randomBytes(4).toString("hex")}`;
28
- const args = [
29
- "build",
30
- "-t",
31
- tag
32
- ];
33
- if (build.args) for (const [key, value] of Object.entries(build.args)) args.push("--build-arg", `${key}=${value}`);
34
- if ("dockerfile" in build && build.dockerfile) {
35
- args.push("-f", build.dockerfile);
36
- args.push(build.context ?? ".");
37
- }
38
- let tempDir;
39
- if ("content" in build && build.content) {
40
- tempDir = await mkdtemp(join(tmpdir(), "cw-oci-build-"));
41
- const dockerfilePath = join(tempDir, "Dockerfile");
42
- await writeFile(dockerfilePath, build.content, {
43
- encoding: "utf8",
44
- mode: 384
45
- });
46
- args.push("-f", dockerfilePath);
47
- args.push(build.context ?? tempDir);
48
- }
49
- try {
50
- await runOci(binary, args);
51
- } catch (error) {
52
- throw new ContainerCreateError(`Image build failed: ${formatError(error)}`);
53
- } finally {
54
- if (tempDir) await rm(tempDir, {
55
- recursive: true,
56
- force: true
57
- }).catch(() => {});
58
- }
59
- return tag;
60
- };
61
- const resolvePortMappings = async (binary, containerId, ports) => {
62
- const results = await Promise.all(ports.map(async (port) => {
63
- try {
64
- const { container: containerPort, protocol = "tcp" } = port;
65
- const { stdout } = await runOci(binary, [
66
- "port",
67
- containerId,
68
- `${containerPort}/${protocol}`
69
- ]);
70
- const match = /:(\d+)$/m.exec(stdout.trim());
71
- if (match?.[1]) return [containerPort, Number(match[1])];
72
- } catch {}
73
- }));
74
- const mapped = /* @__PURE__ */ new Map();
75
- for (const entry of results) if (entry) mapped.set(entry[0], entry[1]);
76
- return mapped;
77
- };
78
- const createOciSpawner = (containerId, binary) => ({ spawn: (command, args, options = {}) => {
79
- const execArgs = ["exec", "-i"];
80
- if (options.cwd) execArgs.push("-w", options.cwd);
81
- if (options.env) for (const [key, value] of Object.entries(options.env)) execArgs.push("-e", `${key}=${value}`);
82
- execArgs.push(containerId, command, ...args);
83
- return DEFAULT_SPAWNER.spawn(binary, execArgs, { stdio: options.stdio });
84
- } });
85
- const isWithinContainerMount = (mountTarget, cwd) => {
86
- const relativePath = posix.relative(mountTarget, cwd);
87
- return relativePath === "" || !relativePath.startsWith("..") && !posix.isAbsolute(relativePath);
88
- };
89
- const resolveHostMountPath = (mounts, cwd) => {
90
- if (!mounts || mounts.length === 0) return;
91
- const normalizedCwd = posix.normalize(cwd);
92
- let bestMatch;
93
- for (const mount of mounts) {
94
- if (!isAbsolute(mount.source)) continue;
95
- const normalizedTarget = posix.normalize(mount.target);
96
- if (!isWithinContainerMount(normalizedTarget, normalizedCwd)) continue;
97
- if (!bestMatch || normalizedTarget.length > posix.normalize(bestMatch.target).length) bestMatch = mount;
98
- }
99
- if (!bestMatch) return;
100
- const relativePath = posix.relative(posix.normalize(bestMatch.target), normalizedCwd);
101
- return relativePath === "" ? bestMatch.source : join(bestMatch.source, ...relativePath.split("/"));
102
- };
103
- const createOciContainer = async (type, params, config) => {
104
- const { binary, builtImage, containerName: requestedContainerName, workdir, user, network, platform, env, ports, mounts, extraArgs, image } = params;
105
- const containerName = requestedContainerName ?? generateContainerName();
106
- const createArgs = [
107
- "create",
108
- "--name",
109
- containerName
110
- ];
111
- if (user) createArgs.push("--user", user);
112
- if (network) createArgs.push("--network", network);
113
- if (platform) createArgs.push("--platform", platform);
114
- if (env) for (const [key, value] of Object.entries(env)) createArgs.push("-e", `${key}=${value}`);
115
- if (ports) for (const port of ports) {
116
- const { host, container, protocol = "tcp" } = port;
117
- createArgs.push("-p", `${host ?? ""}:${container}/${protocol}`);
118
- }
119
- if (mounts) for (const mount of mounts) {
120
- const { readonly: isReadonly, source, target } = mount;
121
- const mode = isReadonly ? "ro" : "rw";
122
- createArgs.push("-v", `${source}:${target}:${mode}`);
123
- }
124
- if (extraArgs) createArgs.push(...extraArgs);
125
- createArgs.push(image, "sleep", "infinity");
126
- let containerId;
127
- try {
128
- const { stdout } = await runOci(binary, createArgs);
129
- containerId = stdout.trim();
130
- } catch (error) {
131
- throw new ContainerCreateError(`Container create failed: ${formatError(error)}`);
132
- }
133
- let status = "created";
134
- let portMappings = /* @__PURE__ */ new Map();
135
- const assertNotDisposed = () => {
136
- if (status === "disposed") throw new ContainerDisposedError();
137
- };
138
- const assertRunning = () => {
139
- assertNotDisposed();
140
- if (status !== "running") throw new ContainerNotRunningError();
141
- };
142
- const spawner = createOciSpawner(containerId, binary);
143
- const diffApi = createWorkdirDiffApi({
144
- owner: {},
145
- workdir,
146
- materialize: async (cwd, targetDir) => {
147
- assertNotDisposed();
148
- const hostPath = resolveHostMountPath(mounts, cwd);
149
- if (hostPath) {
150
- await copyLocalDirectoryContents(hostPath, targetDir);
151
- return;
152
- }
153
- assertRunning();
154
- try {
155
- await runOci(binary, [
156
- "exec",
157
- containerId,
158
- "sh",
159
- "-c",
160
- `test -d ${shellEscape(cwd)}`
161
- ]);
162
- } catch {
163
- throw new ContainerDiffError(`Target path is not a directory: ${cwd}`);
164
- }
165
- try {
166
- await runOci(binary, [
167
- "cp",
168
- `${containerId}:${cwd}/.`,
169
- targetDir
170
- ]);
171
- } catch (error) {
172
- throw new ContainerDiffError(`Failed to materialize container path ${cwd}: ${formatError(error)}`);
173
- }
174
- }
175
- });
176
- const instance = {
177
- get type() {
178
- return type;
179
- },
180
- get id() {
181
- return containerId;
182
- },
183
- get name() {
184
- return containerName;
185
- },
186
- get config() {
187
- return config;
188
- },
189
- get status() {
190
- return status;
191
- },
192
- get workdir() {
193
- return workdir;
194
- },
195
- get spawner() {
196
- return spawner;
197
- },
198
- async start() {
199
- assertNotDisposed();
200
- if (status === "running") return;
201
- try {
202
- await runOci(binary, ["start", containerId]);
203
- } catch (error) {
204
- throw new ContainerStartError(`Container start failed: ${formatError(error)}`);
205
- }
206
- try {
207
- await runOci(binary, [
208
- "exec",
209
- containerId,
210
- "mkdir",
211
- "-p",
212
- workdir
213
- ]);
214
- } catch (error) {
215
- try {
216
- await runOci(binary, [
217
- "stop",
218
- "-t",
219
- "0",
220
- containerId
221
- ]);
222
- status = "stopped";
223
- } catch {
224
- try {
225
- const { stdout } = await runOci(binary, [
226
- "inspect",
227
- "--format",
228
- "{{.State.Status}}",
229
- containerId
230
- ]);
231
- status = stdout.trim() === "running" ? "running" : "stopped";
232
- } catch {
233
- status = "disposed";
234
- }
235
- }
236
- throw new ContainerStartError(`Container start failed: ${formatError(error)}`);
237
- }
238
- status = "running";
239
- if (ports?.length) portMappings = await resolvePortMappings(binary, containerId, ports);
240
- },
241
- async stop() {
242
- assertNotDisposed();
243
- if (status !== "running") return;
244
- try {
245
- await runOci(binary, [
246
- "stop",
247
- "-t",
248
- "2",
249
- containerId
250
- ]);
251
- } catch {
252
- try {
253
- const { stdout } = await runOci(binary, [
254
- "inspect",
255
- "--format",
256
- "{{.State.Status}}",
257
- containerId
258
- ]);
259
- if (stdout.trim() === "running") return;
260
- } catch {
261
- status = "disposed";
262
- return;
263
- }
264
- }
265
- status = "stopped";
266
- },
267
- async dispose() {
268
- if (status === "disposed") return;
269
- try {
270
- await runOci(binary, [
271
- "stop",
272
- "-t",
273
- "0",
274
- containerId
275
- ]);
276
- } catch {}
277
- try {
278
- await runOci(binary, [
279
- "rm",
280
- "-f",
281
- containerId
282
- ]);
283
- } catch {}
284
- if (builtImage) await runOci(binary, ["rmi", image]).catch(() => {});
285
- await diffApi.disposeSnapshots().catch(() => {});
286
- status = "disposed";
287
- },
288
- async exec(command, args, options = {}) {
289
- assertRunning();
290
- const execArgs = ["exec"];
291
- if (options.cwd) execArgs.push("-w", options.cwd);
292
- if (options.env) for (const [key, value] of Object.entries(options.env)) execArgs.push("-e", `${key}=${value}`);
293
- execArgs.push(containerId, command, ...args);
294
- try {
295
- const { stdout, stderr } = await runOci(binary, execArgs, {
296
- timeoutMs: options.timeoutMs,
297
- signal: options.signal
298
- });
299
- return {
300
- exitCode: 0,
301
- stdout,
302
- stderr
303
- };
304
- } catch (error) {
305
- if (isExecFileError(error)) return {
306
- exitCode: typeof error.code === "number" ? error.code : -1,
307
- stdout: String(error.stdout ?? ""),
308
- stderr: String(error.stderr ?? "")
309
- };
310
- throw error;
311
- }
312
- },
313
- async copyTo(hostPath, containerPath) {
314
- assertRunning();
315
- await runOci(binary, [
316
- "cp",
317
- hostPath,
318
- `${containerId}:${containerPath}`
319
- ]);
320
- },
321
- async copyFrom(containerPath, hostPath) {
322
- assertRunning();
323
- await runOci(binary, [
324
- "cp",
325
- `${containerId}:${containerPath}`,
326
- hostPath
327
- ]);
328
- },
329
- async writeFile(path, content) {
330
- assertRunning();
331
- const resolved = posix.isAbsolute(path) ? path : posix.resolve(workdir, path);
332
- const dir = posix.dirname(resolved);
333
- const encoded = typeof content === "string" ? Buffer.from(content, "utf8") : content;
334
- const execArgs = ["exec", "-i"];
335
- if (user) execArgs.push("--user", user);
336
- execArgs.push(containerId, "sh", "-c", `mkdir -p ${shellEscape(dir)} && cat > ${shellEscape(resolved)}`);
337
- const proc = DEFAULT_SPAWNER.spawn(binary, execArgs, { stdio: [
338
- "pipe",
339
- "ignore",
340
- "ignore"
341
- ] });
342
- proc.stdin?.write?.(encoded);
343
- proc.stdin?.end();
344
- const result = await proc.wait();
345
- if (result.exitCode !== 0) throw new ContainerExecError(`writeFile failed for ${resolved} (exit ${result.exitCode})`);
346
- },
347
- async readFile(path) {
348
- assertRunning();
349
- const resolved = posix.isAbsolute(path) ? path : posix.resolve(workdir, path);
350
- const { stdout } = await runOci(binary, [
351
- "exec",
352
- containerId,
353
- "cat",
354
- resolved
355
- ]);
356
- return stdout;
357
- },
358
- async fileExists(path) {
359
- assertRunning();
360
- const resolved = posix.isAbsolute(path) ? path : posix.resolve(workdir, path);
361
- try {
362
- await runOci(binary, [
363
- "exec",
364
- containerId,
365
- "test",
366
- "-e",
367
- resolved
368
- ]);
369
- return true;
370
- } catch {
371
- return false;
372
- }
373
- },
374
- async mkdir(path) {
375
- assertRunning();
376
- const resolved = posix.isAbsolute(path) ? path : posix.resolve(workdir, path);
377
- await runOci(binary, [
378
- "exec",
379
- containerId,
380
- "mkdir",
381
- "-p",
382
- resolved
383
- ]);
384
- },
385
- async execShell(script, options = {}) {
386
- return instance.exec("sh", ["-c", script], options);
387
- },
388
- async logs(options = {}) {
389
- assertNotDisposed();
390
- const args = ["logs"];
391
- if (options.tail !== void 0) args.push("--tail", String(options.tail));
392
- args.push(containerId);
393
- const { stdout } = await runOci(binary, args);
394
- return stdout;
395
- },
396
- async syncStatus() {
397
- assertNotDisposed();
398
- try {
399
- const { stdout } = await runOci(binary, [
400
- "inspect",
401
- "--format",
402
- "{{.State.Status}}",
403
- containerId
404
- ]);
405
- const raw = stdout.trim();
406
- if (raw === "running") status = "running";
407
- else if (raw === "created") status = "created";
408
- else status = "stopped";
409
- } catch {
410
- status = "disposed";
411
- }
412
- return status;
413
- },
414
- async snapshotWorkdir(options = {}) {
415
- return diffApi.snapshotWorkdir(options);
416
- },
417
- async diffWorkdir(snapshot) {
418
- return diffApi.diffWorkdir(snapshot);
419
- },
420
- async releaseWorkdirSnapshot(snapshot) {
421
- return diffApi.releaseWorkdirSnapshot(snapshot);
422
- },
423
- getMappedPort(containerPort) {
424
- return portMappings.get(containerPort);
425
- },
426
- [Symbol.asyncDispose]() {
427
- return instance.dispose();
428
- }
429
- };
430
- return instance;
431
- };
432
- const resolveOciImage = async (binary, provider) => {
433
- if (provider.image) return provider.image;
434
- if (provider.build) return buildOciImage(binary, provider.build);
435
- throw new ContainerCreateError("Either image or build must be provided.");
436
- };
437
- //#endregion
438
- export { resolveOciImage as n, createOciContainer as t };
@@ -1,96 +0,0 @@
1
- import { z } from "zod/v4";
2
- //#region src/schemas/agent.ts
3
- const textContentPartSchema = z.object({
4
- type: z.literal("text"),
5
- text: z.string()
6
- });
7
- const imageContentPartSchema = z.object({
8
- type: z.literal("image"),
9
- path: z.string(),
10
- mediaType: z.string().optional()
11
- });
12
- const contentPartSchema = z.discriminatedUnion("type", [textContentPartSchema, imageContentPartSchema]);
13
- const agentCapabilitiesSchema = z.object({
14
- structuredOutput: z.boolean(),
15
- sessionResume: z.boolean(),
16
- imageInput: z.boolean(),
17
- mcp: z.boolean(),
18
- eventStreaming: z.boolean(),
19
- sessionFork: z.boolean().optional()
20
- });
21
- //#endregion
22
- //#region src/schemas/events.ts
23
- const baseEventSchema = z.object({
24
- id: z.string(),
25
- runId: z.string(),
26
- timestamp: z.date()
27
- });
28
- const sessionStartEventSchema = baseEventSchema.extend({
29
- type: z.literal("session-start"),
30
- requestedSessionId: z.string().optional(),
31
- sessionId: z.string().optional(),
32
- resumed: z.boolean()
33
- });
34
- const messageEventSchema = baseEventSchema.extend({
35
- type: z.literal("message"),
36
- sessionId: z.string().optional(),
37
- model: z.string().nullable(),
38
- role: z.enum([
39
- "system",
40
- "user",
41
- "assistant"
42
- ]),
43
- content: z.array(contentPartSchema),
44
- text: z.string().optional()
45
- });
46
- const reasoningEventSchema = baseEventSchema.extend({
47
- type: z.literal("reasoning"),
48
- sessionId: z.string().optional(),
49
- model: z.string().nullable(),
50
- content: z.array(contentPartSchema),
51
- text: z.string().optional()
52
- });
53
- const toolCallEventSchema = baseEventSchema.extend({
54
- type: z.literal("tool-call"),
55
- sessionId: z.string().optional(),
56
- model: z.string().nullable(),
57
- toolCallId: z.string(),
58
- toolName: z.string(),
59
- input: z.unknown().optional()
60
- });
61
- const toolResultEventSchema = baseEventSchema.extend({
62
- type: z.literal("tool-result"),
63
- sessionId: z.string().optional(),
64
- toolCallId: z.string(),
65
- toolName: z.string().optional(),
66
- input: z.unknown().optional(),
67
- output: z.unknown(),
68
- isError: z.boolean().optional(),
69
- error: z.string().optional()
70
- });
71
- const stderrEventSchema = baseEventSchema.extend({
72
- type: z.literal("stderr"),
73
- sessionId: z.string().optional(),
74
- text: z.string()
75
- });
76
- const sessionEndEventSchema = baseEventSchema.extend({
77
- type: z.literal("session-end"),
78
- sessionId: z.string().optional(),
79
- status: z.enum([
80
- "completed",
81
- "failed",
82
- "cancelled"
83
- ]),
84
- error: z.string().optional()
85
- });
86
- const eventSchema = z.discriminatedUnion("type", [
87
- sessionStartEventSchema,
88
- messageEventSchema,
89
- reasoningEventSchema,
90
- toolCallEventSchema,
91
- toolResultEventSchema,
92
- stderrEventSchema,
93
- sessionEndEventSchema
94
- ]);
95
- //#endregion
96
- export { sessionEndEventSchema as a, toolCallEventSchema as c, contentPartSchema as d, imageContentPartSchema as f, reasoningEventSchema as i, toolResultEventSchema as l, eventSchema as n, sessionStartEventSchema as o, textContentPartSchema as p, messageEventSchema as r, stderrEventSchema as s, baseEventSchema as t, agentCapabilitiesSchema as u };
@@ -1,54 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- //#region src/core/process/spawner.ts
3
- const streamToAsyncIterable = (stream) => ({ async *[Symbol.asyncIterator]() {
4
- for await (const chunk of stream) {
5
- if (chunk instanceof Buffer) {
6
- yield new Uint8Array(chunk);
7
- continue;
8
- }
9
- if (typeof chunk === "string") {
10
- yield new TextEncoder().encode(chunk);
11
- continue;
12
- }
13
- if (chunk instanceof Uint8Array) {
14
- yield chunk;
15
- continue;
16
- }
17
- throw new Error(`Unsupported stdout/stderr chunk type: ${typeof chunk}`);
18
- }
19
- } });
20
- const spawnProcess = (command, args, options = {}) => {
21
- const child = spawn(command, args, {
22
- cwd: options.cwd,
23
- env: options.env,
24
- stdio: options.stdio
25
- });
26
- const waitPromise = new Promise((resolve, reject) => {
27
- const onClose = (exitCode, signal) => {
28
- child.removeListener("error", onError);
29
- resolve({
30
- exitCode,
31
- signal
32
- });
33
- };
34
- const onError = (err) => {
35
- child.removeListener("close", onClose);
36
- reject(err);
37
- };
38
- child.once("error", onError);
39
- child.once("close", onClose);
40
- });
41
- return {
42
- stdout: child.stdout ? streamToAsyncIterable(child.stdout) : null,
43
- stderr: child.stderr ? streamToAsyncIterable(child.stderr) : null,
44
- stdin: child.stdin ? {
45
- write: (chunk) => child.stdin?.write(chunk),
46
- end: () => child.stdin?.end()
47
- } : null,
48
- kill: (signal) => child.kill(signal),
49
- wait: () => waitPromise
50
- };
51
- };
52
- const DEFAULT_SPAWNER = { spawn: spawnProcess };
53
- //#endregion
54
- export { DEFAULT_SPAWNER as t };
@@ -1,19 +0,0 @@
1
- //#region src/core/structured-output.ts
2
- const findStructuredOutputToolCallInput = (toolCalls) => {
3
- let latestInput;
4
- for (const [, record] of toolCalls) if (record.toolName === "StructuredOutput" && record.input !== void 0) latestInput = record.input;
5
- return latestInput;
6
- };
7
- const extractClaudeStructuredOutput = (structuredOutput, context, eventMeta, errorMessage) => {
8
- if (structuredOutput !== void 0) return { value: structuredOutput };
9
- if (!context.schemaRequested) return {};
10
- const toolCallOutput = findStructuredOutputToolCallInput(context.toolCalls);
11
- if (toolCallOutput !== void 0) return { value: toolCallOutput };
12
- if (eventMeta.isSuccess) return { error: {
13
- kind: "parse",
14
- message: errorMessage
15
- } };
16
- return {};
17
- };
18
- //#endregion
19
- export { extractClaudeStructuredOutput as t };
@@ -1,19 +0,0 @@
1
- //#region src/core/agent/types.ts
2
- /** Thrown by `runOrThrow()` when the run does not complete successfully. carries the full `RunResult` on `.result`. */
3
- var AgentRunError = class extends Error {
4
- result;
5
- constructor(result) {
6
- super(result.error.message);
7
- this.name = "AgentRunError";
8
- this.result = result;
9
- }
10
- };
11
- /** Thrown when agent configuration or request parameters are invalid (e.g. unsupported capability, empty input) */
12
- var AgentValidationError = class extends Error {
13
- constructor(message) {
14
- super(message);
15
- this.name = "AgentValidationError";
16
- }
17
- };
18
- //#endregion
19
- export { AgentValidationError as n, AgentRunError as t };
@@ -1,77 +0,0 @@
1
- //#region src/core/util.ts
2
- const toArray = (value) => {
3
- return Array.isArray(value) ? value : [value];
4
- };
5
- const formatError = (error) => error instanceof Error ? error.message : String(error);
6
- const isRecord = (value) => typeof value === "object" && value !== null;
7
- const sumTokens = (...values) => values.reduce((sum, v) => sum + (v ?? 0), 0);
8
- const stripMarkdownCodeFence = (value) => {
9
- const trimmed = value.trim();
10
- if (!trimmed.startsWith("```")) return trimmed;
11
- return trimmed.replace(/^```[\w-]*\s*/i, "").replace(/\s*```$/i, "").trim();
12
- };
13
- const extractMarkdownCodeBlock = (value) => {
14
- return /```[\w-]*\s*([\S\s]*?)\s*```/i.exec(value)?.[1]?.trim();
15
- };
16
- const extractBalancedJson = (value) => {
17
- let start = -1;
18
- const stack = [];
19
- let inString = false;
20
- let escaped = false;
21
- for (let index = 0; index < value.length; index++) {
22
- const char = value[index];
23
- if (!char) continue;
24
- if (start === -1) {
25
- if (char === "{" || char === "[") {
26
- start = index;
27
- stack.push(char);
28
- }
29
- continue;
30
- }
31
- if (inString) {
32
- if (escaped) {
33
- escaped = false;
34
- continue;
35
- }
36
- if (char === "\\") {
37
- escaped = true;
38
- continue;
39
- }
40
- if (char === "\"") inString = false;
41
- continue;
42
- }
43
- if (char === "\"") {
44
- inString = true;
45
- continue;
46
- }
47
- if (char === "{" || char === "[") {
48
- stack.push(char);
49
- continue;
50
- }
51
- if (char === "}" || char === "]") {
52
- const open = stack.pop();
53
- if (open === "{" && char !== "}" || open === "[" && char !== "]") return;
54
- if (stack.length === 0) return value.slice(start, index + 1).trim();
55
- }
56
- }
57
- };
58
- const parseJsonResponseText = (value) => {
59
- const trimmed = value.trim();
60
- const candidates = [
61
- stripMarkdownCodeFence(trimmed),
62
- extractMarkdownCodeBlock(trimmed),
63
- extractBalancedJson(trimmed)
64
- ];
65
- let lastError;
66
- for (const candidate of new Set(candidates)) {
67
- if (!candidate) continue;
68
- try {
69
- return JSON.parse(candidate);
70
- } catch (error) {
71
- lastError = error;
72
- }
73
- }
74
- throw lastError instanceof Error ? lastError : /* @__PURE__ */ new SyntaxError("Failed to parse JSON response text.");
75
- };
76
- //#endregion
77
- export { toArray as a, sumTokens as i, isRecord as n, parseJsonResponseText as r, formatError as t };