@sourcegraph/amp-sdk 0.1.0-20251020161918-gf8ab86d → 0.1.0-20251021152627-g8658f12

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 (3) hide show
  1. package/dist/index.js +4288 -338
  2. package/package.json +2 -2
  3. package/dist/types.js +0 -127
package/dist/index.js CHANGED
@@ -1,407 +1,4357 @@
1
- /**
2
- * Amp TypeScript SDK
3
- *
4
- * This SDK provides a TypeScript interface to the Amp CLI, allowing you to
5
- * run Amp programmatically in Node.js applications. It wraps the Amp CLI
6
- * with the --stream-json flag to provide structured output.
7
- */
8
- import { spawn } from 'node:child_process';
9
- import fs from 'node:fs';
10
- import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
11
- import { createRequire } from 'node:module';
12
- import path from 'node:path';
13
- import { createInterface } from 'node:readline';
14
- import { AmpOptionsSchema, UserInputMessageSchema, } from './types.js';
15
- // Platform detection
16
- const isWindows = process.platform === 'win32';
17
- // ============================================================================
18
- // Main Execute Function
19
- // ============================================================================
20
- /** Execute a command with Amp CLI and return an async iterator of messages */
21
- export async function* execute(options) {
22
- const { prompt, options: ampOptions = {}, signal } = options;
23
- // Validate options
24
- let validatedOptions = AmpOptionsSchema.parse(ampOptions);
25
- // Build settings file (create temp file if needed)
26
- const { settingsFilePath, cleanupTempFile } = await buildSettingsFile(validatedOptions, generateSessionId());
27
- // Update options with temp settings file path if created
28
- validatedOptions = {
29
- ...validatedOptions,
30
- ...(settingsFilePath && { settingsFile: settingsFilePath }),
31
- };
32
- // Build CLI arguments
33
- const args = buildCliArgs(validatedOptions);
34
- // Handle different prompt types
35
- const isStreamingInput = typeof prompt !== 'string' && Symbol.asyncIterator in prompt;
36
- // Add flag for streaming input if needed
37
- if (isStreamingInput) {
38
- args.push('--stream-json-input');
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, {
5
+ get: all[name],
6
+ enumerable: true,
7
+ configurable: true,
8
+ set: (newValue) => all[name] = () => newValue
9
+ });
10
+ };
11
+
12
+ // src/index.ts
13
+ import { spawn } from "node:child_process";
14
+ import fs from "node:fs";
15
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
16
+ import { createRequire } from "node:module";
17
+ import path from "node:path";
18
+ import { createInterface } from "node:readline";
19
+
20
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js
21
+ var exports_external = {};
22
+ __export(exports_external, {
23
+ void: () => voidType,
24
+ util: () => util,
25
+ unknown: () => unknownType,
26
+ union: () => unionType,
27
+ undefined: () => undefinedType,
28
+ tuple: () => tupleType,
29
+ transformer: () => effectsType,
30
+ symbol: () => symbolType,
31
+ string: () => stringType,
32
+ strictObject: () => strictObjectType,
33
+ setErrorMap: () => setErrorMap,
34
+ set: () => setType,
35
+ record: () => recordType,
36
+ quotelessJson: () => quotelessJson,
37
+ promise: () => promiseType,
38
+ preprocess: () => preprocessType,
39
+ pipeline: () => pipelineType,
40
+ ostring: () => ostring,
41
+ optional: () => optionalType,
42
+ onumber: () => onumber,
43
+ oboolean: () => oboolean,
44
+ objectUtil: () => objectUtil,
45
+ object: () => objectType,
46
+ number: () => numberType,
47
+ nullable: () => nullableType,
48
+ null: () => nullType,
49
+ never: () => neverType,
50
+ nativeEnum: () => nativeEnumType,
51
+ nan: () => nanType,
52
+ map: () => mapType,
53
+ makeIssue: () => makeIssue,
54
+ literal: () => literalType,
55
+ lazy: () => lazyType,
56
+ late: () => late,
57
+ isValid: () => isValid,
58
+ isDirty: () => isDirty,
59
+ isAsync: () => isAsync,
60
+ isAborted: () => isAborted,
61
+ intersection: () => intersectionType,
62
+ instanceof: () => instanceOfType,
63
+ getParsedType: () => getParsedType,
64
+ getErrorMap: () => getErrorMap,
65
+ function: () => functionType,
66
+ enum: () => enumType,
67
+ effect: () => effectsType,
68
+ discriminatedUnion: () => discriminatedUnionType,
69
+ defaultErrorMap: () => en_default,
70
+ datetimeRegex: () => datetimeRegex,
71
+ date: () => dateType,
72
+ custom: () => custom,
73
+ coerce: () => coerce,
74
+ boolean: () => booleanType,
75
+ bigint: () => bigIntType,
76
+ array: () => arrayType,
77
+ any: () => anyType,
78
+ addIssueToContext: () => addIssueToContext,
79
+ ZodVoid: () => ZodVoid,
80
+ ZodUnknown: () => ZodUnknown,
81
+ ZodUnion: () => ZodUnion,
82
+ ZodUndefined: () => ZodUndefined,
83
+ ZodType: () => ZodType,
84
+ ZodTuple: () => ZodTuple,
85
+ ZodTransformer: () => ZodEffects,
86
+ ZodSymbol: () => ZodSymbol,
87
+ ZodString: () => ZodString,
88
+ ZodSet: () => ZodSet,
89
+ ZodSchema: () => ZodType,
90
+ ZodRecord: () => ZodRecord,
91
+ ZodReadonly: () => ZodReadonly,
92
+ ZodPromise: () => ZodPromise,
93
+ ZodPipeline: () => ZodPipeline,
94
+ ZodParsedType: () => ZodParsedType,
95
+ ZodOptional: () => ZodOptional,
96
+ ZodObject: () => ZodObject,
97
+ ZodNumber: () => ZodNumber,
98
+ ZodNullable: () => ZodNullable,
99
+ ZodNull: () => ZodNull,
100
+ ZodNever: () => ZodNever,
101
+ ZodNativeEnum: () => ZodNativeEnum,
102
+ ZodNaN: () => ZodNaN,
103
+ ZodMap: () => ZodMap,
104
+ ZodLiteral: () => ZodLiteral,
105
+ ZodLazy: () => ZodLazy,
106
+ ZodIssueCode: () => ZodIssueCode,
107
+ ZodIntersection: () => ZodIntersection,
108
+ ZodFunction: () => ZodFunction,
109
+ ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
110
+ ZodError: () => ZodError,
111
+ ZodEnum: () => ZodEnum,
112
+ ZodEffects: () => ZodEffects,
113
+ ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
114
+ ZodDefault: () => ZodDefault,
115
+ ZodDate: () => ZodDate,
116
+ ZodCatch: () => ZodCatch,
117
+ ZodBranded: () => ZodBranded,
118
+ ZodBoolean: () => ZodBoolean,
119
+ ZodBigInt: () => ZodBigInt,
120
+ ZodArray: () => ZodArray,
121
+ ZodAny: () => ZodAny,
122
+ Schema: () => ZodType,
123
+ ParseStatus: () => ParseStatus,
124
+ OK: () => OK,
125
+ NEVER: () => NEVER,
126
+ INVALID: () => INVALID,
127
+ EMPTY_PATH: () => EMPTY_PATH,
128
+ DIRTY: () => DIRTY,
129
+ BRAND: () => BRAND
130
+ });
131
+
132
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js
133
+ var util;
134
+ (function(util2) {
135
+ util2.assertEqual = (_) => {};
136
+ function assertIs(_arg) {}
137
+ util2.assertIs = assertIs;
138
+ function assertNever(_x) {
139
+ throw new Error;
140
+ }
141
+ util2.assertNever = assertNever;
142
+ util2.arrayToEnum = (items) => {
143
+ const obj = {};
144
+ for (const item of items) {
145
+ obj[item] = item;
39
146
  }
40
- // Build environment variables
41
- const env = buildEnvironmentVariables(validatedOptions);
42
- // Log the full CLI command for debugging (only in debug mode)
43
- if (process.env.AMP_DEBUG || validatedOptions.logLevel === 'debug') {
44
- const ampCommand = findAmpCommand();
45
- console.debug(`Executing Amp CLI: ${ampCommand.command} ${[...ampCommand.args, ...args].join(' ')}`);
147
+ return obj;
148
+ };
149
+ util2.getValidEnumValues = (obj) => {
150
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
151
+ const filtered = {};
152
+ for (const k of validKeys) {
153
+ filtered[k] = obj[k];
46
154
  }
47
- // Spawn Amp CLI process
48
- const ampProcess = spawnAmpCli(args, {
49
- env,
50
- cwd: validatedOptions.cwd,
51
- signal,
155
+ return util2.objectValues(filtered);
156
+ };
157
+ util2.objectValues = (obj) => {
158
+ return util2.objectKeys(obj).map(function(e) {
159
+ return obj[e];
52
160
  });
53
- try {
54
- // Handle input via stdin
55
- if (isStreamingInput) {
56
- handleStreamingInput(ampProcess, prompt);
57
- }
58
- else if (typeof prompt === 'string' && prompt) {
59
- handleStringInput(ampProcess, prompt);
60
- }
61
- // Process output stream
62
- yield* processOutputStream(ampProcess.stdout);
63
- // Wait for process to complete and check exit code
64
- const { exitCode, stderr, signal: processSignal } = await waitForProcess(ampProcess, signal);
65
- // Handle exit code properly - null indicates signal termination
66
- if (exitCode === null) {
67
- // Process was killed by signal
68
- if (signal?.aborted) {
69
- // Expected termination due to AbortController
70
- throw new Error('Amp CLI process was aborted');
71
- }
72
- else if (processSignal) {
73
- // Killed by system signal
74
- throw new Error(`Amp CLI process was killed by signal ${processSignal}`);
75
- }
76
- else {
77
- // Unexpected null exit code
78
- throw new Error('Amp CLI process terminated unexpectedly');
161
+ };
162
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
163
+ const keys = [];
164
+ for (const key in object) {
165
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
166
+ keys.push(key);
167
+ }
168
+ }
169
+ return keys;
170
+ };
171
+ util2.find = (arr, checker) => {
172
+ for (const item of arr) {
173
+ if (checker(item))
174
+ return item;
175
+ }
176
+ return;
177
+ };
178
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
179
+ function joinValues(array, separator = " | ") {
180
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
181
+ }
182
+ util2.joinValues = joinValues;
183
+ util2.jsonStringifyReplacer = (_, value) => {
184
+ if (typeof value === "bigint") {
185
+ return value.toString();
186
+ }
187
+ return value;
188
+ };
189
+ })(util || (util = {}));
190
+ var objectUtil;
191
+ (function(objectUtil2) {
192
+ objectUtil2.mergeShapes = (first, second) => {
193
+ return {
194
+ ...first,
195
+ ...second
196
+ };
197
+ };
198
+ })(objectUtil || (objectUtil = {}));
199
+ var ZodParsedType = util.arrayToEnum([
200
+ "string",
201
+ "nan",
202
+ "number",
203
+ "integer",
204
+ "float",
205
+ "boolean",
206
+ "date",
207
+ "bigint",
208
+ "symbol",
209
+ "function",
210
+ "undefined",
211
+ "null",
212
+ "array",
213
+ "object",
214
+ "unknown",
215
+ "promise",
216
+ "void",
217
+ "never",
218
+ "map",
219
+ "set"
220
+ ]);
221
+ var getParsedType = (data) => {
222
+ const t = typeof data;
223
+ switch (t) {
224
+ case "undefined":
225
+ return ZodParsedType.undefined;
226
+ case "string":
227
+ return ZodParsedType.string;
228
+ case "number":
229
+ return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
230
+ case "boolean":
231
+ return ZodParsedType.boolean;
232
+ case "function":
233
+ return ZodParsedType.function;
234
+ case "bigint":
235
+ return ZodParsedType.bigint;
236
+ case "symbol":
237
+ return ZodParsedType.symbol;
238
+ case "object":
239
+ if (Array.isArray(data)) {
240
+ return ZodParsedType.array;
241
+ }
242
+ if (data === null) {
243
+ return ZodParsedType.null;
244
+ }
245
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
246
+ return ZodParsedType.promise;
247
+ }
248
+ if (typeof Map !== "undefined" && data instanceof Map) {
249
+ return ZodParsedType.map;
250
+ }
251
+ if (typeof Set !== "undefined" && data instanceof Set) {
252
+ return ZodParsedType.set;
253
+ }
254
+ if (typeof Date !== "undefined" && data instanceof Date) {
255
+ return ZodParsedType.date;
256
+ }
257
+ return ZodParsedType.object;
258
+ default:
259
+ return ZodParsedType.unknown;
260
+ }
261
+ };
262
+
263
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js
264
+ var ZodIssueCode = util.arrayToEnum([
265
+ "invalid_type",
266
+ "invalid_literal",
267
+ "custom",
268
+ "invalid_union",
269
+ "invalid_union_discriminator",
270
+ "invalid_enum_value",
271
+ "unrecognized_keys",
272
+ "invalid_arguments",
273
+ "invalid_return_type",
274
+ "invalid_date",
275
+ "invalid_string",
276
+ "too_small",
277
+ "too_big",
278
+ "invalid_intersection_types",
279
+ "not_multiple_of",
280
+ "not_finite"
281
+ ]);
282
+ var quotelessJson = (obj) => {
283
+ const json = JSON.stringify(obj, null, 2);
284
+ return json.replace(/"([^"]+)":/g, "$1:");
285
+ };
286
+
287
+ class ZodError extends Error {
288
+ get errors() {
289
+ return this.issues;
290
+ }
291
+ constructor(issues) {
292
+ super();
293
+ this.issues = [];
294
+ this.addIssue = (sub) => {
295
+ this.issues = [...this.issues, sub];
296
+ };
297
+ this.addIssues = (subs = []) => {
298
+ this.issues = [...this.issues, ...subs];
299
+ };
300
+ const actualProto = new.target.prototype;
301
+ if (Object.setPrototypeOf) {
302
+ Object.setPrototypeOf(this, actualProto);
303
+ } else {
304
+ this.__proto__ = actualProto;
305
+ }
306
+ this.name = "ZodError";
307
+ this.issues = issues;
308
+ }
309
+ format(_mapper) {
310
+ const mapper = _mapper || function(issue) {
311
+ return issue.message;
312
+ };
313
+ const fieldErrors = { _errors: [] };
314
+ const processError = (error) => {
315
+ for (const issue of error.issues) {
316
+ if (issue.code === "invalid_union") {
317
+ issue.unionErrors.map(processError);
318
+ } else if (issue.code === "invalid_return_type") {
319
+ processError(issue.returnTypeError);
320
+ } else if (issue.code === "invalid_arguments") {
321
+ processError(issue.argumentsError);
322
+ } else if (issue.path.length === 0) {
323
+ fieldErrors._errors.push(mapper(issue));
324
+ } else {
325
+ let curr = fieldErrors;
326
+ let i = 0;
327
+ while (i < issue.path.length) {
328
+ const el = issue.path[i];
329
+ const terminal = i === issue.path.length - 1;
330
+ if (!terminal) {
331
+ curr[el] = curr[el] || { _errors: [] };
332
+ } else {
333
+ curr[el] = curr[el] || { _errors: [] };
334
+ curr[el]._errors.push(mapper(issue));
79
335
  }
336
+ curr = curr[el];
337
+ i++;
338
+ }
80
339
  }
81
- else if (exitCode !== 0) {
82
- // Normal exit with error code
83
- const errorDetails = stderr ? `: ${stderr}` : '';
84
- throw new Error(`Amp CLI process exited with code ${exitCode}${errorDetails}`);
85
- }
340
+ }
341
+ };
342
+ processError(this);
343
+ return fieldErrors;
344
+ }
345
+ static assert(value) {
346
+ if (!(value instanceof ZodError)) {
347
+ throw new Error(`Not a ZodError: ${value}`);
348
+ }
349
+ }
350
+ toString() {
351
+ return this.message;
352
+ }
353
+ get message() {
354
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
355
+ }
356
+ get isEmpty() {
357
+ return this.issues.length === 0;
358
+ }
359
+ flatten(mapper = (issue) => issue.message) {
360
+ const fieldErrors = {};
361
+ const formErrors = [];
362
+ for (const sub of this.issues) {
363
+ if (sub.path.length > 0) {
364
+ const firstEl = sub.path[0];
365
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
366
+ fieldErrors[firstEl].push(mapper(sub));
367
+ } else {
368
+ formErrors.push(mapper(sub));
369
+ }
86
370
  }
87
- catch (error) {
88
- // Clean up process on error
89
- if (!ampProcess.killed) {
90
- ampProcess.kill(isWindows ? 'SIGKILL' : 'SIGTERM');
371
+ return { formErrors, fieldErrors };
372
+ }
373
+ get formErrors() {
374
+ return this.flatten();
375
+ }
376
+ }
377
+ ZodError.create = (issues) => {
378
+ const error = new ZodError(issues);
379
+ return error;
380
+ };
381
+
382
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js
383
+ var errorMap = (issue, _ctx) => {
384
+ let message;
385
+ switch (issue.code) {
386
+ case ZodIssueCode.invalid_type:
387
+ if (issue.received === ZodParsedType.undefined) {
388
+ message = "Required";
389
+ } else {
390
+ message = `Expected ${issue.expected}, received ${issue.received}`;
391
+ }
392
+ break;
393
+ case ZodIssueCode.invalid_literal:
394
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
395
+ break;
396
+ case ZodIssueCode.unrecognized_keys:
397
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
398
+ break;
399
+ case ZodIssueCode.invalid_union:
400
+ message = `Invalid input`;
401
+ break;
402
+ case ZodIssueCode.invalid_union_discriminator:
403
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
404
+ break;
405
+ case ZodIssueCode.invalid_enum_value:
406
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
407
+ break;
408
+ case ZodIssueCode.invalid_arguments:
409
+ message = `Invalid function arguments`;
410
+ break;
411
+ case ZodIssueCode.invalid_return_type:
412
+ message = `Invalid function return type`;
413
+ break;
414
+ case ZodIssueCode.invalid_date:
415
+ message = `Invalid date`;
416
+ break;
417
+ case ZodIssueCode.invalid_string:
418
+ if (typeof issue.validation === "object") {
419
+ if ("includes" in issue.validation) {
420
+ message = `Invalid input: must include "${issue.validation.includes}"`;
421
+ if (typeof issue.validation.position === "number") {
422
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
423
+ }
424
+ } else if ("startsWith" in issue.validation) {
425
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
426
+ } else if ("endsWith" in issue.validation) {
427
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
428
+ } else {
429
+ util.assertNever(issue.validation);
91
430
  }
92
- throw error;
431
+ } else if (issue.validation !== "regex") {
432
+ message = `Invalid ${issue.validation}`;
433
+ } else {
434
+ message = "Invalid";
435
+ }
436
+ break;
437
+ case ZodIssueCode.too_small:
438
+ if (issue.type === "array")
439
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
440
+ else if (issue.type === "string")
441
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
442
+ else if (issue.type === "number")
443
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
444
+ else if (issue.type === "bigint")
445
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
446
+ else if (issue.type === "date")
447
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
448
+ else
449
+ message = "Invalid input";
450
+ break;
451
+ case ZodIssueCode.too_big:
452
+ if (issue.type === "array")
453
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
454
+ else if (issue.type === "string")
455
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
456
+ else if (issue.type === "number")
457
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
458
+ else if (issue.type === "bigint")
459
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
460
+ else if (issue.type === "date")
461
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
462
+ else
463
+ message = "Invalid input";
464
+ break;
465
+ case ZodIssueCode.custom:
466
+ message = `Invalid input`;
467
+ break;
468
+ case ZodIssueCode.invalid_intersection_types:
469
+ message = `Intersection results could not be merged`;
470
+ break;
471
+ case ZodIssueCode.not_multiple_of:
472
+ message = `Number must be a multiple of ${issue.multipleOf}`;
473
+ break;
474
+ case ZodIssueCode.not_finite:
475
+ message = "Number must be finite";
476
+ break;
477
+ default:
478
+ message = _ctx.defaultError;
479
+ util.assertNever(issue);
480
+ }
481
+ return { message };
482
+ };
483
+ var en_default = errorMap;
484
+
485
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js
486
+ var overrideErrorMap = en_default;
487
+ function setErrorMap(map) {
488
+ overrideErrorMap = map;
489
+ }
490
+ function getErrorMap() {
491
+ return overrideErrorMap;
492
+ }
493
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
494
+ var makeIssue = (params) => {
495
+ const { data, path, errorMaps, issueData } = params;
496
+ const fullPath = [...path, ...issueData.path || []];
497
+ const fullIssue = {
498
+ ...issueData,
499
+ path: fullPath
500
+ };
501
+ if (issueData.message !== undefined) {
502
+ return {
503
+ ...issueData,
504
+ path: fullPath,
505
+ message: issueData.message
506
+ };
507
+ }
508
+ let errorMessage = "";
509
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
510
+ for (const map of maps) {
511
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
512
+ }
513
+ return {
514
+ ...issueData,
515
+ path: fullPath,
516
+ message: errorMessage
517
+ };
518
+ };
519
+ var EMPTY_PATH = [];
520
+ function addIssueToContext(ctx, issueData) {
521
+ const overrideMap = getErrorMap();
522
+ const issue = makeIssue({
523
+ issueData,
524
+ data: ctx.data,
525
+ path: ctx.path,
526
+ errorMaps: [
527
+ ctx.common.contextualErrorMap,
528
+ ctx.schemaErrorMap,
529
+ overrideMap,
530
+ overrideMap === en_default ? undefined : en_default
531
+ ].filter((x) => !!x)
532
+ });
533
+ ctx.common.issues.push(issue);
534
+ }
535
+
536
+ class ParseStatus {
537
+ constructor() {
538
+ this.value = "valid";
539
+ }
540
+ dirty() {
541
+ if (this.value === "valid")
542
+ this.value = "dirty";
543
+ }
544
+ abort() {
545
+ if (this.value !== "aborted")
546
+ this.value = "aborted";
547
+ }
548
+ static mergeArray(status, results) {
549
+ const arrayValue = [];
550
+ for (const s of results) {
551
+ if (s.status === "aborted")
552
+ return INVALID;
553
+ if (s.status === "dirty")
554
+ status.dirty();
555
+ arrayValue.push(s.value);
93
556
  }
94
- finally {
95
- // Clean up temp settings file
96
- await cleanupTempFile();
557
+ return { status: status.value, value: arrayValue };
558
+ }
559
+ static async mergeObjectAsync(status, pairs) {
560
+ const syncPairs = [];
561
+ for (const pair of pairs) {
562
+ const key = await pair.key;
563
+ const value = await pair.value;
564
+ syncPairs.push({
565
+ key,
566
+ value
567
+ });
97
568
  }
569
+ return ParseStatus.mergeObjectSync(status, syncPairs);
570
+ }
571
+ static mergeObjectSync(status, pairs) {
572
+ const finalObject = {};
573
+ for (const pair of pairs) {
574
+ const { key, value } = pair;
575
+ if (key.status === "aborted")
576
+ return INVALID;
577
+ if (value.status === "aborted")
578
+ return INVALID;
579
+ if (key.status === "dirty")
580
+ status.dirty();
581
+ if (value.status === "dirty")
582
+ status.dirty();
583
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
584
+ finalObject[key.value] = value.value;
585
+ }
586
+ }
587
+ return { status: status.value, value: finalObject };
588
+ }
98
589
  }
99
- // ============================================================================
100
- // Settings File Management
101
- // ============================================================================
102
- /** Generate a unique session ID for organizing temp files */
103
- function generateSessionId() {
104
- const randomHex = Math.random().toString(36).substring(2, 10);
105
- return `sdk-${Date.now()}-${randomHex}`;
590
+ var INVALID = Object.freeze({
591
+ status: "aborted"
592
+ });
593
+ var DIRTY = (value) => ({ status: "dirty", value });
594
+ var OK = (value) => ({ status: "valid", value });
595
+ var isAborted = (x) => x.status === "aborted";
596
+ var isDirty = (x) => x.status === "dirty";
597
+ var isValid = (x) => x.status === "valid";
598
+ var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
599
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
600
+ var errorUtil;
601
+ (function(errorUtil2) {
602
+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
603
+ errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
604
+ })(errorUtil || (errorUtil = {}));
605
+
606
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js
607
+ class ParseInputLazyPath {
608
+ constructor(parent, value, path, key) {
609
+ this._cachedPath = [];
610
+ this.parent = parent;
611
+ this.data = value;
612
+ this._path = path;
613
+ this._key = key;
614
+ }
615
+ get path() {
616
+ if (!this._cachedPath.length) {
617
+ if (Array.isArray(this._key)) {
618
+ this._cachedPath.push(...this._path, ...this._key);
619
+ } else {
620
+ this._cachedPath.push(...this._path, this._key);
621
+ }
622
+ }
623
+ return this._cachedPath;
624
+ }
106
625
  }
107
- /** Build settings file for CLI execution, creating a temp file if permissions need to be passed */
108
- async function buildSettingsFile(options, sessionId) {
109
- // Check if we need to create a temp settings file
110
- if (!options.permissions) {
111
- // No temp file needed
112
- return {
113
- settingsFilePath: null,
114
- cleanupTempFile: async () => { },
626
+ var handleResult = (ctx, result) => {
627
+ if (isValid(result)) {
628
+ return { success: true, data: result.value };
629
+ } else {
630
+ if (!ctx.common.issues.length) {
631
+ throw new Error("Validation failed but no issues detected.");
632
+ }
633
+ return {
634
+ success: false,
635
+ get error() {
636
+ if (this._error)
637
+ return this._error;
638
+ const error = new ZodError(ctx.common.issues);
639
+ this._error = error;
640
+ return this._error;
641
+ }
642
+ };
643
+ }
644
+ };
645
+ function processCreateParams(params) {
646
+ if (!params)
647
+ return {};
648
+ const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
649
+ if (errorMap2 && (invalid_type_error || required_error)) {
650
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
651
+ }
652
+ if (errorMap2)
653
+ return { errorMap: errorMap2, description };
654
+ const customMap = (iss, ctx) => {
655
+ const { message } = params;
656
+ if (iss.code === "invalid_enum_value") {
657
+ return { message: message ?? ctx.defaultError };
658
+ }
659
+ if (typeof ctx.data === "undefined") {
660
+ return { message: message ?? required_error ?? ctx.defaultError };
661
+ }
662
+ if (iss.code !== "invalid_type")
663
+ return { message: ctx.defaultError };
664
+ return { message: message ?? invalid_type_error ?? ctx.defaultError };
665
+ };
666
+ return { errorMap: customMap, description };
667
+ }
668
+
669
+ class ZodType {
670
+ get description() {
671
+ return this._def.description;
672
+ }
673
+ _getType(input) {
674
+ return getParsedType(input.data);
675
+ }
676
+ _getOrReturnCtx(input, ctx) {
677
+ return ctx || {
678
+ common: input.parent.common,
679
+ data: input.data,
680
+ parsedType: getParsedType(input.data),
681
+ schemaErrorMap: this._def.errorMap,
682
+ path: input.path,
683
+ parent: input.parent
684
+ };
685
+ }
686
+ _processInputParams(input) {
687
+ return {
688
+ status: new ParseStatus,
689
+ ctx: {
690
+ common: input.parent.common,
691
+ data: input.data,
692
+ parsedType: getParsedType(input.data),
693
+ schemaErrorMap: this._def.errorMap,
694
+ path: input.path,
695
+ parent: input.parent
696
+ }
697
+ };
698
+ }
699
+ _parseSync(input) {
700
+ const result = this._parse(input);
701
+ if (isAsync(result)) {
702
+ throw new Error("Synchronous parse encountered promise.");
703
+ }
704
+ return result;
705
+ }
706
+ _parseAsync(input) {
707
+ const result = this._parse(input);
708
+ return Promise.resolve(result);
709
+ }
710
+ parse(data, params) {
711
+ const result = this.safeParse(data, params);
712
+ if (result.success)
713
+ return result.data;
714
+ throw result.error;
715
+ }
716
+ safeParse(data, params) {
717
+ const ctx = {
718
+ common: {
719
+ issues: [],
720
+ async: params?.async ?? false,
721
+ contextualErrorMap: params?.errorMap
722
+ },
723
+ path: params?.path || [],
724
+ schemaErrorMap: this._def.errorMap,
725
+ parent: null,
726
+ data,
727
+ parsedType: getParsedType(data)
728
+ };
729
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
730
+ return handleResult(ctx, result);
731
+ }
732
+ "~validate"(data) {
733
+ const ctx = {
734
+ common: {
735
+ issues: [],
736
+ async: !!this["~standard"].async
737
+ },
738
+ path: [],
739
+ schemaErrorMap: this._def.errorMap,
740
+ parent: null,
741
+ data,
742
+ parsedType: getParsedType(data)
743
+ };
744
+ if (!this["~standard"].async) {
745
+ try {
746
+ const result = this._parseSync({ data, path: [], parent: ctx });
747
+ return isValid(result) ? {
748
+ value: result.value
749
+ } : {
750
+ issues: ctx.common.issues
751
+ };
752
+ } catch (err) {
753
+ if (err?.message?.toLowerCase()?.includes("encountered")) {
754
+ this["~standard"].async = true;
755
+ }
756
+ ctx.common = {
757
+ issues: [],
758
+ async: true
115
759
  };
760
+ }
116
761
  }
117
- // Determine working directory
118
- const cwd = options.cwd || process.cwd();
119
- // Create temp directory path: {cwd}/.tmp/{sessionId}/
120
- const tempDir = path.join(cwd, '.tmp', sessionId);
121
- const tempSettingsPath = path.join(tempDir, 'settings.json');
122
- // Read existing settings file if provided
123
- let mergedSettings = {};
124
- if (options.settingsFile) {
762
+ return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
763
+ value: result.value
764
+ } : {
765
+ issues: ctx.common.issues
766
+ });
767
+ }
768
+ async parseAsync(data, params) {
769
+ const result = await this.safeParseAsync(data, params);
770
+ if (result.success)
771
+ return result.data;
772
+ throw result.error;
773
+ }
774
+ async safeParseAsync(data, params) {
775
+ const ctx = {
776
+ common: {
777
+ issues: [],
778
+ contextualErrorMap: params?.errorMap,
779
+ async: true
780
+ },
781
+ path: params?.path || [],
782
+ schemaErrorMap: this._def.errorMap,
783
+ parent: null,
784
+ data,
785
+ parsedType: getParsedType(data)
786
+ };
787
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
788
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
789
+ return handleResult(ctx, result);
790
+ }
791
+ refine(check, message) {
792
+ const getIssueProperties = (val) => {
793
+ if (typeof message === "string" || typeof message === "undefined") {
794
+ return { message };
795
+ } else if (typeof message === "function") {
796
+ return message(val);
797
+ } else {
798
+ return message;
799
+ }
800
+ };
801
+ return this._refinement((val, ctx) => {
802
+ const result = check(val);
803
+ const setError = () => ctx.addIssue({
804
+ code: ZodIssueCode.custom,
805
+ ...getIssueProperties(val)
806
+ });
807
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
808
+ return result.then((data) => {
809
+ if (!data) {
810
+ setError();
811
+ return false;
812
+ } else {
813
+ return true;
814
+ }
815
+ });
816
+ }
817
+ if (!result) {
818
+ setError();
819
+ return false;
820
+ } else {
821
+ return true;
822
+ }
823
+ });
824
+ }
825
+ refinement(check, refinementData) {
826
+ return this._refinement((val, ctx) => {
827
+ if (!check(val)) {
828
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
829
+ return false;
830
+ } else {
831
+ return true;
832
+ }
833
+ });
834
+ }
835
+ _refinement(refinement) {
836
+ return new ZodEffects({
837
+ schema: this,
838
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
839
+ effect: { type: "refinement", refinement }
840
+ });
841
+ }
842
+ superRefine(refinement) {
843
+ return this._refinement(refinement);
844
+ }
845
+ constructor(def) {
846
+ this.spa = this.safeParseAsync;
847
+ this._def = def;
848
+ this.parse = this.parse.bind(this);
849
+ this.safeParse = this.safeParse.bind(this);
850
+ this.parseAsync = this.parseAsync.bind(this);
851
+ this.safeParseAsync = this.safeParseAsync.bind(this);
852
+ this.spa = this.spa.bind(this);
853
+ this.refine = this.refine.bind(this);
854
+ this.refinement = this.refinement.bind(this);
855
+ this.superRefine = this.superRefine.bind(this);
856
+ this.optional = this.optional.bind(this);
857
+ this.nullable = this.nullable.bind(this);
858
+ this.nullish = this.nullish.bind(this);
859
+ this.array = this.array.bind(this);
860
+ this.promise = this.promise.bind(this);
861
+ this.or = this.or.bind(this);
862
+ this.and = this.and.bind(this);
863
+ this.transform = this.transform.bind(this);
864
+ this.brand = this.brand.bind(this);
865
+ this.default = this.default.bind(this);
866
+ this.catch = this.catch.bind(this);
867
+ this.describe = this.describe.bind(this);
868
+ this.pipe = this.pipe.bind(this);
869
+ this.readonly = this.readonly.bind(this);
870
+ this.isNullable = this.isNullable.bind(this);
871
+ this.isOptional = this.isOptional.bind(this);
872
+ this["~standard"] = {
873
+ version: 1,
874
+ vendor: "zod",
875
+ validate: (data) => this["~validate"](data)
876
+ };
877
+ }
878
+ optional() {
879
+ return ZodOptional.create(this, this._def);
880
+ }
881
+ nullable() {
882
+ return ZodNullable.create(this, this._def);
883
+ }
884
+ nullish() {
885
+ return this.nullable().optional();
886
+ }
887
+ array() {
888
+ return ZodArray.create(this);
889
+ }
890
+ promise() {
891
+ return ZodPromise.create(this, this._def);
892
+ }
893
+ or(option) {
894
+ return ZodUnion.create([this, option], this._def);
895
+ }
896
+ and(incoming) {
897
+ return ZodIntersection.create(this, incoming, this._def);
898
+ }
899
+ transform(transform) {
900
+ return new ZodEffects({
901
+ ...processCreateParams(this._def),
902
+ schema: this,
903
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
904
+ effect: { type: "transform", transform }
905
+ });
906
+ }
907
+ default(def) {
908
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
909
+ return new ZodDefault({
910
+ ...processCreateParams(this._def),
911
+ innerType: this,
912
+ defaultValue: defaultValueFunc,
913
+ typeName: ZodFirstPartyTypeKind.ZodDefault
914
+ });
915
+ }
916
+ brand() {
917
+ return new ZodBranded({
918
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
919
+ type: this,
920
+ ...processCreateParams(this._def)
921
+ });
922
+ }
923
+ catch(def) {
924
+ const catchValueFunc = typeof def === "function" ? def : () => def;
925
+ return new ZodCatch({
926
+ ...processCreateParams(this._def),
927
+ innerType: this,
928
+ catchValue: catchValueFunc,
929
+ typeName: ZodFirstPartyTypeKind.ZodCatch
930
+ });
931
+ }
932
+ describe(description) {
933
+ const This = this.constructor;
934
+ return new This({
935
+ ...this._def,
936
+ description
937
+ });
938
+ }
939
+ pipe(target) {
940
+ return ZodPipeline.create(this, target);
941
+ }
942
+ readonly() {
943
+ return ZodReadonly.create(this);
944
+ }
945
+ isOptional() {
946
+ return this.safeParse(undefined).success;
947
+ }
948
+ isNullable() {
949
+ return this.safeParse(null).success;
950
+ }
951
+ }
952
+ var cuidRegex = /^c[^\s-]{8,}$/i;
953
+ var cuid2Regex = /^[0-9a-z]+$/;
954
+ var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
955
+ var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
956
+ var nanoidRegex = /^[a-z0-9_-]{21}$/i;
957
+ var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
958
+ var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
959
+ var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
960
+ var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
961
+ var emojiRegex;
962
+ var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
963
+ var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
964
+ var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
965
+ var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
966
+ var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
967
+ var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
968
+ var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
969
+ var dateRegex = new RegExp(`^${dateRegexSource}$`);
970
+ function timeRegexSource(args) {
971
+ let secondsRegexSource = `[0-5]\\d`;
972
+ if (args.precision) {
973
+ secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
974
+ } else if (args.precision == null) {
975
+ secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
976
+ }
977
+ const secondsQuantifier = args.precision ? "+" : "?";
978
+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
979
+ }
980
+ function timeRegex(args) {
981
+ return new RegExp(`^${timeRegexSource(args)}$`);
982
+ }
983
+ function datetimeRegex(args) {
984
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
985
+ const opts = [];
986
+ opts.push(args.local ? `Z?` : `Z`);
987
+ if (args.offset)
988
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
989
+ regex = `${regex}(${opts.join("|")})`;
990
+ return new RegExp(`^${regex}$`);
991
+ }
992
+ function isValidIP(ip, version) {
993
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
994
+ return true;
995
+ }
996
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
997
+ return true;
998
+ }
999
+ return false;
1000
+ }
1001
+ function isValidJWT(jwt, alg) {
1002
+ if (!jwtRegex.test(jwt))
1003
+ return false;
1004
+ try {
1005
+ const [header] = jwt.split(".");
1006
+ if (!header)
1007
+ return false;
1008
+ const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
1009
+ const decoded = JSON.parse(atob(base64));
1010
+ if (typeof decoded !== "object" || decoded === null)
1011
+ return false;
1012
+ if ("typ" in decoded && decoded?.typ !== "JWT")
1013
+ return false;
1014
+ if (!decoded.alg)
1015
+ return false;
1016
+ if (alg && decoded.alg !== alg)
1017
+ return false;
1018
+ return true;
1019
+ } catch {
1020
+ return false;
1021
+ }
1022
+ }
1023
+ function isValidCidr(ip, version) {
1024
+ if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
1025
+ return true;
1026
+ }
1027
+ if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
1028
+ return true;
1029
+ }
1030
+ return false;
1031
+ }
1032
+
1033
+ class ZodString extends ZodType {
1034
+ _parse(input) {
1035
+ if (this._def.coerce) {
1036
+ input.data = String(input.data);
1037
+ }
1038
+ const parsedType = this._getType(input);
1039
+ if (parsedType !== ZodParsedType.string) {
1040
+ const ctx2 = this._getOrReturnCtx(input);
1041
+ addIssueToContext(ctx2, {
1042
+ code: ZodIssueCode.invalid_type,
1043
+ expected: ZodParsedType.string,
1044
+ received: ctx2.parsedType
1045
+ });
1046
+ return INVALID;
1047
+ }
1048
+ const status = new ParseStatus;
1049
+ let ctx = undefined;
1050
+ for (const check of this._def.checks) {
1051
+ if (check.kind === "min") {
1052
+ if (input.data.length < check.value) {
1053
+ ctx = this._getOrReturnCtx(input, ctx);
1054
+ addIssueToContext(ctx, {
1055
+ code: ZodIssueCode.too_small,
1056
+ minimum: check.value,
1057
+ type: "string",
1058
+ inclusive: true,
1059
+ exact: false,
1060
+ message: check.message
1061
+ });
1062
+ status.dirty();
1063
+ }
1064
+ } else if (check.kind === "max") {
1065
+ if (input.data.length > check.value) {
1066
+ ctx = this._getOrReturnCtx(input, ctx);
1067
+ addIssueToContext(ctx, {
1068
+ code: ZodIssueCode.too_big,
1069
+ maximum: check.value,
1070
+ type: "string",
1071
+ inclusive: true,
1072
+ exact: false,
1073
+ message: check.message
1074
+ });
1075
+ status.dirty();
1076
+ }
1077
+ } else if (check.kind === "length") {
1078
+ const tooBig = input.data.length > check.value;
1079
+ const tooSmall = input.data.length < check.value;
1080
+ if (tooBig || tooSmall) {
1081
+ ctx = this._getOrReturnCtx(input, ctx);
1082
+ if (tooBig) {
1083
+ addIssueToContext(ctx, {
1084
+ code: ZodIssueCode.too_big,
1085
+ maximum: check.value,
1086
+ type: "string",
1087
+ inclusive: true,
1088
+ exact: true,
1089
+ message: check.message
1090
+ });
1091
+ } else if (tooSmall) {
1092
+ addIssueToContext(ctx, {
1093
+ code: ZodIssueCode.too_small,
1094
+ minimum: check.value,
1095
+ type: "string",
1096
+ inclusive: true,
1097
+ exact: true,
1098
+ message: check.message
1099
+ });
1100
+ }
1101
+ status.dirty();
1102
+ }
1103
+ } else if (check.kind === "email") {
1104
+ if (!emailRegex.test(input.data)) {
1105
+ ctx = this._getOrReturnCtx(input, ctx);
1106
+ addIssueToContext(ctx, {
1107
+ validation: "email",
1108
+ code: ZodIssueCode.invalid_string,
1109
+ message: check.message
1110
+ });
1111
+ status.dirty();
1112
+ }
1113
+ } else if (check.kind === "emoji") {
1114
+ if (!emojiRegex) {
1115
+ emojiRegex = new RegExp(_emojiRegex, "u");
1116
+ }
1117
+ if (!emojiRegex.test(input.data)) {
1118
+ ctx = this._getOrReturnCtx(input, ctx);
1119
+ addIssueToContext(ctx, {
1120
+ validation: "emoji",
1121
+ code: ZodIssueCode.invalid_string,
1122
+ message: check.message
1123
+ });
1124
+ status.dirty();
1125
+ }
1126
+ } else if (check.kind === "uuid") {
1127
+ if (!uuidRegex.test(input.data)) {
1128
+ ctx = this._getOrReturnCtx(input, ctx);
1129
+ addIssueToContext(ctx, {
1130
+ validation: "uuid",
1131
+ code: ZodIssueCode.invalid_string,
1132
+ message: check.message
1133
+ });
1134
+ status.dirty();
1135
+ }
1136
+ } else if (check.kind === "nanoid") {
1137
+ if (!nanoidRegex.test(input.data)) {
1138
+ ctx = this._getOrReturnCtx(input, ctx);
1139
+ addIssueToContext(ctx, {
1140
+ validation: "nanoid",
1141
+ code: ZodIssueCode.invalid_string,
1142
+ message: check.message
1143
+ });
1144
+ status.dirty();
1145
+ }
1146
+ } else if (check.kind === "cuid") {
1147
+ if (!cuidRegex.test(input.data)) {
1148
+ ctx = this._getOrReturnCtx(input, ctx);
1149
+ addIssueToContext(ctx, {
1150
+ validation: "cuid",
1151
+ code: ZodIssueCode.invalid_string,
1152
+ message: check.message
1153
+ });
1154
+ status.dirty();
1155
+ }
1156
+ } else if (check.kind === "cuid2") {
1157
+ if (!cuid2Regex.test(input.data)) {
1158
+ ctx = this._getOrReturnCtx(input, ctx);
1159
+ addIssueToContext(ctx, {
1160
+ validation: "cuid2",
1161
+ code: ZodIssueCode.invalid_string,
1162
+ message: check.message
1163
+ });
1164
+ status.dirty();
1165
+ }
1166
+ } else if (check.kind === "ulid") {
1167
+ if (!ulidRegex.test(input.data)) {
1168
+ ctx = this._getOrReturnCtx(input, ctx);
1169
+ addIssueToContext(ctx, {
1170
+ validation: "ulid",
1171
+ code: ZodIssueCode.invalid_string,
1172
+ message: check.message
1173
+ });
1174
+ status.dirty();
1175
+ }
1176
+ } else if (check.kind === "url") {
125
1177
  try {
126
- const settingsContent = await readFile(options.settingsFile, 'utf-8');
127
- mergedSettings = JSON.parse(settingsContent);
1178
+ new URL(input.data);
1179
+ } catch {
1180
+ ctx = this._getOrReturnCtx(input, ctx);
1181
+ addIssueToContext(ctx, {
1182
+ validation: "url",
1183
+ code: ZodIssueCode.invalid_string,
1184
+ message: check.message
1185
+ });
1186
+ status.dirty();
128
1187
  }
129
- catch (error) {
130
- // If file doesn't exist or can't be read, start with empty settings
131
- if (error.code !== 'ENOENT') {
132
- throw new Error(`Failed to read settings file ${options.settingsFile}: ${error instanceof Error ? error.message : String(error)}`);
133
- }
1188
+ } else if (check.kind === "regex") {
1189
+ check.regex.lastIndex = 0;
1190
+ const testResult = check.regex.test(input.data);
1191
+ if (!testResult) {
1192
+ ctx = this._getOrReturnCtx(input, ctx);
1193
+ addIssueToContext(ctx, {
1194
+ validation: "regex",
1195
+ code: ZodIssueCode.invalid_string,
1196
+ message: check.message
1197
+ });
1198
+ status.dirty();
1199
+ }
1200
+ } else if (check.kind === "trim") {
1201
+ input.data = input.data.trim();
1202
+ } else if (check.kind === "includes") {
1203
+ if (!input.data.includes(check.value, check.position)) {
1204
+ ctx = this._getOrReturnCtx(input, ctx);
1205
+ addIssueToContext(ctx, {
1206
+ code: ZodIssueCode.invalid_string,
1207
+ validation: { includes: check.value, position: check.position },
1208
+ message: check.message
1209
+ });
1210
+ status.dirty();
1211
+ }
1212
+ } else if (check.kind === "toLowerCase") {
1213
+ input.data = input.data.toLowerCase();
1214
+ } else if (check.kind === "toUpperCase") {
1215
+ input.data = input.data.toUpperCase();
1216
+ } else if (check.kind === "startsWith") {
1217
+ if (!input.data.startsWith(check.value)) {
1218
+ ctx = this._getOrReturnCtx(input, ctx);
1219
+ addIssueToContext(ctx, {
1220
+ code: ZodIssueCode.invalid_string,
1221
+ validation: { startsWith: check.value },
1222
+ message: check.message
1223
+ });
1224
+ status.dirty();
1225
+ }
1226
+ } else if (check.kind === "endsWith") {
1227
+ if (!input.data.endsWith(check.value)) {
1228
+ ctx = this._getOrReturnCtx(input, ctx);
1229
+ addIssueToContext(ctx, {
1230
+ code: ZodIssueCode.invalid_string,
1231
+ validation: { endsWith: check.value },
1232
+ message: check.message
1233
+ });
1234
+ status.dirty();
1235
+ }
1236
+ } else if (check.kind === "datetime") {
1237
+ const regex = datetimeRegex(check);
1238
+ if (!regex.test(input.data)) {
1239
+ ctx = this._getOrReturnCtx(input, ctx);
1240
+ addIssueToContext(ctx, {
1241
+ code: ZodIssueCode.invalid_string,
1242
+ validation: "datetime",
1243
+ message: check.message
1244
+ });
1245
+ status.dirty();
1246
+ }
1247
+ } else if (check.kind === "date") {
1248
+ const regex = dateRegex;
1249
+ if (!regex.test(input.data)) {
1250
+ ctx = this._getOrReturnCtx(input, ctx);
1251
+ addIssueToContext(ctx, {
1252
+ code: ZodIssueCode.invalid_string,
1253
+ validation: "date",
1254
+ message: check.message
1255
+ });
1256
+ status.dirty();
134
1257
  }
1258
+ } else if (check.kind === "time") {
1259
+ const regex = timeRegex(check);
1260
+ if (!regex.test(input.data)) {
1261
+ ctx = this._getOrReturnCtx(input, ctx);
1262
+ addIssueToContext(ctx, {
1263
+ code: ZodIssueCode.invalid_string,
1264
+ validation: "time",
1265
+ message: check.message
1266
+ });
1267
+ status.dirty();
1268
+ }
1269
+ } else if (check.kind === "duration") {
1270
+ if (!durationRegex.test(input.data)) {
1271
+ ctx = this._getOrReturnCtx(input, ctx);
1272
+ addIssueToContext(ctx, {
1273
+ validation: "duration",
1274
+ code: ZodIssueCode.invalid_string,
1275
+ message: check.message
1276
+ });
1277
+ status.dirty();
1278
+ }
1279
+ } else if (check.kind === "ip") {
1280
+ if (!isValidIP(input.data, check.version)) {
1281
+ ctx = this._getOrReturnCtx(input, ctx);
1282
+ addIssueToContext(ctx, {
1283
+ validation: "ip",
1284
+ code: ZodIssueCode.invalid_string,
1285
+ message: check.message
1286
+ });
1287
+ status.dirty();
1288
+ }
1289
+ } else if (check.kind === "jwt") {
1290
+ if (!isValidJWT(input.data, check.alg)) {
1291
+ ctx = this._getOrReturnCtx(input, ctx);
1292
+ addIssueToContext(ctx, {
1293
+ validation: "jwt",
1294
+ code: ZodIssueCode.invalid_string,
1295
+ message: check.message
1296
+ });
1297
+ status.dirty();
1298
+ }
1299
+ } else if (check.kind === "cidr") {
1300
+ if (!isValidCidr(input.data, check.version)) {
1301
+ ctx = this._getOrReturnCtx(input, ctx);
1302
+ addIssueToContext(ctx, {
1303
+ validation: "cidr",
1304
+ code: ZodIssueCode.invalid_string,
1305
+ message: check.message
1306
+ });
1307
+ status.dirty();
1308
+ }
1309
+ } else if (check.kind === "base64") {
1310
+ if (!base64Regex.test(input.data)) {
1311
+ ctx = this._getOrReturnCtx(input, ctx);
1312
+ addIssueToContext(ctx, {
1313
+ validation: "base64",
1314
+ code: ZodIssueCode.invalid_string,
1315
+ message: check.message
1316
+ });
1317
+ status.dirty();
1318
+ }
1319
+ } else if (check.kind === "base64url") {
1320
+ if (!base64urlRegex.test(input.data)) {
1321
+ ctx = this._getOrReturnCtx(input, ctx);
1322
+ addIssueToContext(ctx, {
1323
+ validation: "base64url",
1324
+ code: ZodIssueCode.invalid_string,
1325
+ message: check.message
1326
+ });
1327
+ status.dirty();
1328
+ }
1329
+ } else {
1330
+ util.assertNever(check);
1331
+ }
1332
+ }
1333
+ return { status: status.value, value: input.data };
1334
+ }
1335
+ _regex(regex, validation, message) {
1336
+ return this.refinement((data) => regex.test(data), {
1337
+ validation,
1338
+ code: ZodIssueCode.invalid_string,
1339
+ ...errorUtil.errToObj(message)
1340
+ });
1341
+ }
1342
+ _addCheck(check) {
1343
+ return new ZodString({
1344
+ ...this._def,
1345
+ checks: [...this._def.checks, check]
1346
+ });
1347
+ }
1348
+ email(message) {
1349
+ return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
1350
+ }
1351
+ url(message) {
1352
+ return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
1353
+ }
1354
+ emoji(message) {
1355
+ return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
1356
+ }
1357
+ uuid(message) {
1358
+ return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1359
+ }
1360
+ nanoid(message) {
1361
+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1362
+ }
1363
+ cuid(message) {
1364
+ return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1365
+ }
1366
+ cuid2(message) {
1367
+ return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
1368
+ }
1369
+ ulid(message) {
1370
+ return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1371
+ }
1372
+ base64(message) {
1373
+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
1374
+ }
1375
+ base64url(message) {
1376
+ return this._addCheck({
1377
+ kind: "base64url",
1378
+ ...errorUtil.errToObj(message)
1379
+ });
1380
+ }
1381
+ jwt(options) {
1382
+ return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
1383
+ }
1384
+ ip(options) {
1385
+ return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1386
+ }
1387
+ cidr(options) {
1388
+ return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
1389
+ }
1390
+ datetime(options) {
1391
+ if (typeof options === "string") {
1392
+ return this._addCheck({
1393
+ kind: "datetime",
1394
+ precision: null,
1395
+ offset: false,
1396
+ local: false,
1397
+ message: options
1398
+ });
1399
+ }
1400
+ return this._addCheck({
1401
+ kind: "datetime",
1402
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
1403
+ offset: options?.offset ?? false,
1404
+ local: options?.local ?? false,
1405
+ ...errorUtil.errToObj(options?.message)
1406
+ });
1407
+ }
1408
+ date(message) {
1409
+ return this._addCheck({ kind: "date", message });
1410
+ }
1411
+ time(options) {
1412
+ if (typeof options === "string") {
1413
+ return this._addCheck({
1414
+ kind: "time",
1415
+ precision: null,
1416
+ message: options
1417
+ });
1418
+ }
1419
+ return this._addCheck({
1420
+ kind: "time",
1421
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
1422
+ ...errorUtil.errToObj(options?.message)
1423
+ });
1424
+ }
1425
+ duration(message) {
1426
+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
1427
+ }
1428
+ regex(regex, message) {
1429
+ return this._addCheck({
1430
+ kind: "regex",
1431
+ regex,
1432
+ ...errorUtil.errToObj(message)
1433
+ });
1434
+ }
1435
+ includes(value, options) {
1436
+ return this._addCheck({
1437
+ kind: "includes",
1438
+ value,
1439
+ position: options?.position,
1440
+ ...errorUtil.errToObj(options?.message)
1441
+ });
1442
+ }
1443
+ startsWith(value, message) {
1444
+ return this._addCheck({
1445
+ kind: "startsWith",
1446
+ value,
1447
+ ...errorUtil.errToObj(message)
1448
+ });
1449
+ }
1450
+ endsWith(value, message) {
1451
+ return this._addCheck({
1452
+ kind: "endsWith",
1453
+ value,
1454
+ ...errorUtil.errToObj(message)
1455
+ });
1456
+ }
1457
+ min(minLength, message) {
1458
+ return this._addCheck({
1459
+ kind: "min",
1460
+ value: minLength,
1461
+ ...errorUtil.errToObj(message)
1462
+ });
1463
+ }
1464
+ max(maxLength, message) {
1465
+ return this._addCheck({
1466
+ kind: "max",
1467
+ value: maxLength,
1468
+ ...errorUtil.errToObj(message)
1469
+ });
1470
+ }
1471
+ length(len, message) {
1472
+ return this._addCheck({
1473
+ kind: "length",
1474
+ value: len,
1475
+ ...errorUtil.errToObj(message)
1476
+ });
1477
+ }
1478
+ nonempty(message) {
1479
+ return this.min(1, errorUtil.errToObj(message));
1480
+ }
1481
+ trim() {
1482
+ return new ZodString({
1483
+ ...this._def,
1484
+ checks: [...this._def.checks, { kind: "trim" }]
1485
+ });
1486
+ }
1487
+ toLowerCase() {
1488
+ return new ZodString({
1489
+ ...this._def,
1490
+ checks: [...this._def.checks, { kind: "toLowerCase" }]
1491
+ });
1492
+ }
1493
+ toUpperCase() {
1494
+ return new ZodString({
1495
+ ...this._def,
1496
+ checks: [...this._def.checks, { kind: "toUpperCase" }]
1497
+ });
1498
+ }
1499
+ get isDatetime() {
1500
+ return !!this._def.checks.find((ch) => ch.kind === "datetime");
1501
+ }
1502
+ get isDate() {
1503
+ return !!this._def.checks.find((ch) => ch.kind === "date");
1504
+ }
1505
+ get isTime() {
1506
+ return !!this._def.checks.find((ch) => ch.kind === "time");
1507
+ }
1508
+ get isDuration() {
1509
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
1510
+ }
1511
+ get isEmail() {
1512
+ return !!this._def.checks.find((ch) => ch.kind === "email");
1513
+ }
1514
+ get isURL() {
1515
+ return !!this._def.checks.find((ch) => ch.kind === "url");
1516
+ }
1517
+ get isEmoji() {
1518
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
1519
+ }
1520
+ get isUUID() {
1521
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
1522
+ }
1523
+ get isNANOID() {
1524
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1525
+ }
1526
+ get isCUID() {
1527
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
1528
+ }
1529
+ get isCUID2() {
1530
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1531
+ }
1532
+ get isULID() {
1533
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
1534
+ }
1535
+ get isIP() {
1536
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
1537
+ }
1538
+ get isCIDR() {
1539
+ return !!this._def.checks.find((ch) => ch.kind === "cidr");
1540
+ }
1541
+ get isBase64() {
1542
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
1543
+ }
1544
+ get isBase64url() {
1545
+ return !!this._def.checks.find((ch) => ch.kind === "base64url");
1546
+ }
1547
+ get minLength() {
1548
+ let min = null;
1549
+ for (const ch of this._def.checks) {
1550
+ if (ch.kind === "min") {
1551
+ if (min === null || ch.value > min)
1552
+ min = ch.value;
1553
+ }
1554
+ }
1555
+ return min;
1556
+ }
1557
+ get maxLength() {
1558
+ let max = null;
1559
+ for (const ch of this._def.checks) {
1560
+ if (ch.kind === "max") {
1561
+ if (max === null || ch.value < max)
1562
+ max = ch.value;
1563
+ }
1564
+ }
1565
+ return max;
1566
+ }
1567
+ }
1568
+ ZodString.create = (params) => {
1569
+ return new ZodString({
1570
+ checks: [],
1571
+ typeName: ZodFirstPartyTypeKind.ZodString,
1572
+ coerce: params?.coerce ?? false,
1573
+ ...processCreateParams(params)
1574
+ });
1575
+ };
1576
+ function floatSafeRemainder(val, step) {
1577
+ const valDecCount = (val.toString().split(".")[1] || "").length;
1578
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
1579
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
1580
+ const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
1581
+ const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
1582
+ return valInt % stepInt / 10 ** decCount;
1583
+ }
1584
+
1585
+ class ZodNumber extends ZodType {
1586
+ constructor() {
1587
+ super(...arguments);
1588
+ this.min = this.gte;
1589
+ this.max = this.lte;
1590
+ this.step = this.multipleOf;
1591
+ }
1592
+ _parse(input) {
1593
+ if (this._def.coerce) {
1594
+ input.data = Number(input.data);
1595
+ }
1596
+ const parsedType = this._getType(input);
1597
+ if (parsedType !== ZodParsedType.number) {
1598
+ const ctx2 = this._getOrReturnCtx(input);
1599
+ addIssueToContext(ctx2, {
1600
+ code: ZodIssueCode.invalid_type,
1601
+ expected: ZodParsedType.number,
1602
+ received: ctx2.parsedType
1603
+ });
1604
+ return INVALID;
1605
+ }
1606
+ let ctx = undefined;
1607
+ const status = new ParseStatus;
1608
+ for (const check of this._def.checks) {
1609
+ if (check.kind === "int") {
1610
+ if (!util.isInteger(input.data)) {
1611
+ ctx = this._getOrReturnCtx(input, ctx);
1612
+ addIssueToContext(ctx, {
1613
+ code: ZodIssueCode.invalid_type,
1614
+ expected: "integer",
1615
+ received: "float",
1616
+ message: check.message
1617
+ });
1618
+ status.dirty();
1619
+ }
1620
+ } else if (check.kind === "min") {
1621
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1622
+ if (tooSmall) {
1623
+ ctx = this._getOrReturnCtx(input, ctx);
1624
+ addIssueToContext(ctx, {
1625
+ code: ZodIssueCode.too_small,
1626
+ minimum: check.value,
1627
+ type: "number",
1628
+ inclusive: check.inclusive,
1629
+ exact: false,
1630
+ message: check.message
1631
+ });
1632
+ status.dirty();
1633
+ }
1634
+ } else if (check.kind === "max") {
1635
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1636
+ if (tooBig) {
1637
+ ctx = this._getOrReturnCtx(input, ctx);
1638
+ addIssueToContext(ctx, {
1639
+ code: ZodIssueCode.too_big,
1640
+ maximum: check.value,
1641
+ type: "number",
1642
+ inclusive: check.inclusive,
1643
+ exact: false,
1644
+ message: check.message
1645
+ });
1646
+ status.dirty();
1647
+ }
1648
+ } else if (check.kind === "multipleOf") {
1649
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
1650
+ ctx = this._getOrReturnCtx(input, ctx);
1651
+ addIssueToContext(ctx, {
1652
+ code: ZodIssueCode.not_multiple_of,
1653
+ multipleOf: check.value,
1654
+ message: check.message
1655
+ });
1656
+ status.dirty();
1657
+ }
1658
+ } else if (check.kind === "finite") {
1659
+ if (!Number.isFinite(input.data)) {
1660
+ ctx = this._getOrReturnCtx(input, ctx);
1661
+ addIssueToContext(ctx, {
1662
+ code: ZodIssueCode.not_finite,
1663
+ message: check.message
1664
+ });
1665
+ status.dirty();
1666
+ }
1667
+ } else {
1668
+ util.assertNever(check);
1669
+ }
1670
+ }
1671
+ return { status: status.value, value: input.data };
1672
+ }
1673
+ gte(value, message) {
1674
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1675
+ }
1676
+ gt(value, message) {
1677
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1678
+ }
1679
+ lte(value, message) {
1680
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1681
+ }
1682
+ lt(value, message) {
1683
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1684
+ }
1685
+ setLimit(kind, value, inclusive, message) {
1686
+ return new ZodNumber({
1687
+ ...this._def,
1688
+ checks: [
1689
+ ...this._def.checks,
1690
+ {
1691
+ kind,
1692
+ value,
1693
+ inclusive,
1694
+ message: errorUtil.toString(message)
1695
+ }
1696
+ ]
1697
+ });
1698
+ }
1699
+ _addCheck(check) {
1700
+ return new ZodNumber({
1701
+ ...this._def,
1702
+ checks: [...this._def.checks, check]
1703
+ });
1704
+ }
1705
+ int(message) {
1706
+ return this._addCheck({
1707
+ kind: "int",
1708
+ message: errorUtil.toString(message)
1709
+ });
1710
+ }
1711
+ positive(message) {
1712
+ return this._addCheck({
1713
+ kind: "min",
1714
+ value: 0,
1715
+ inclusive: false,
1716
+ message: errorUtil.toString(message)
1717
+ });
1718
+ }
1719
+ negative(message) {
1720
+ return this._addCheck({
1721
+ kind: "max",
1722
+ value: 0,
1723
+ inclusive: false,
1724
+ message: errorUtil.toString(message)
1725
+ });
1726
+ }
1727
+ nonpositive(message) {
1728
+ return this._addCheck({
1729
+ kind: "max",
1730
+ value: 0,
1731
+ inclusive: true,
1732
+ message: errorUtil.toString(message)
1733
+ });
1734
+ }
1735
+ nonnegative(message) {
1736
+ return this._addCheck({
1737
+ kind: "min",
1738
+ value: 0,
1739
+ inclusive: true,
1740
+ message: errorUtil.toString(message)
1741
+ });
1742
+ }
1743
+ multipleOf(value, message) {
1744
+ return this._addCheck({
1745
+ kind: "multipleOf",
1746
+ value,
1747
+ message: errorUtil.toString(message)
1748
+ });
1749
+ }
1750
+ finite(message) {
1751
+ return this._addCheck({
1752
+ kind: "finite",
1753
+ message: errorUtil.toString(message)
1754
+ });
1755
+ }
1756
+ safe(message) {
1757
+ return this._addCheck({
1758
+ kind: "min",
1759
+ inclusive: true,
1760
+ value: Number.MIN_SAFE_INTEGER,
1761
+ message: errorUtil.toString(message)
1762
+ })._addCheck({
1763
+ kind: "max",
1764
+ inclusive: true,
1765
+ value: Number.MAX_SAFE_INTEGER,
1766
+ message: errorUtil.toString(message)
1767
+ });
1768
+ }
1769
+ get minValue() {
1770
+ let min = null;
1771
+ for (const ch of this._def.checks) {
1772
+ if (ch.kind === "min") {
1773
+ if (min === null || ch.value > min)
1774
+ min = ch.value;
1775
+ }
1776
+ }
1777
+ return min;
1778
+ }
1779
+ get maxValue() {
1780
+ let max = null;
1781
+ for (const ch of this._def.checks) {
1782
+ if (ch.kind === "max") {
1783
+ if (max === null || ch.value < max)
1784
+ max = ch.value;
1785
+ }
1786
+ }
1787
+ return max;
1788
+ }
1789
+ get isInt() {
1790
+ return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
1791
+ }
1792
+ get isFinite() {
1793
+ let max = null;
1794
+ let min = null;
1795
+ for (const ch of this._def.checks) {
1796
+ if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
1797
+ return true;
1798
+ } else if (ch.kind === "min") {
1799
+ if (min === null || ch.value > min)
1800
+ min = ch.value;
1801
+ } else if (ch.kind === "max") {
1802
+ if (max === null || ch.value < max)
1803
+ max = ch.value;
1804
+ }
1805
+ }
1806
+ return Number.isFinite(min) && Number.isFinite(max);
1807
+ }
1808
+ }
1809
+ ZodNumber.create = (params) => {
1810
+ return new ZodNumber({
1811
+ checks: [],
1812
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
1813
+ coerce: params?.coerce || false,
1814
+ ...processCreateParams(params)
1815
+ });
1816
+ };
1817
+
1818
+ class ZodBigInt extends ZodType {
1819
+ constructor() {
1820
+ super(...arguments);
1821
+ this.min = this.gte;
1822
+ this.max = this.lte;
1823
+ }
1824
+ _parse(input) {
1825
+ if (this._def.coerce) {
1826
+ try {
1827
+ input.data = BigInt(input.data);
1828
+ } catch {
1829
+ return this._getInvalidInput(input);
1830
+ }
1831
+ }
1832
+ const parsedType = this._getType(input);
1833
+ if (parsedType !== ZodParsedType.bigint) {
1834
+ return this._getInvalidInput(input);
1835
+ }
1836
+ let ctx = undefined;
1837
+ const status = new ParseStatus;
1838
+ for (const check of this._def.checks) {
1839
+ if (check.kind === "min") {
1840
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1841
+ if (tooSmall) {
1842
+ ctx = this._getOrReturnCtx(input, ctx);
1843
+ addIssueToContext(ctx, {
1844
+ code: ZodIssueCode.too_small,
1845
+ type: "bigint",
1846
+ minimum: check.value,
1847
+ inclusive: check.inclusive,
1848
+ message: check.message
1849
+ });
1850
+ status.dirty();
1851
+ }
1852
+ } else if (check.kind === "max") {
1853
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1854
+ if (tooBig) {
1855
+ ctx = this._getOrReturnCtx(input, ctx);
1856
+ addIssueToContext(ctx, {
1857
+ code: ZodIssueCode.too_big,
1858
+ type: "bigint",
1859
+ maximum: check.value,
1860
+ inclusive: check.inclusive,
1861
+ message: check.message
1862
+ });
1863
+ status.dirty();
1864
+ }
1865
+ } else if (check.kind === "multipleOf") {
1866
+ if (input.data % check.value !== BigInt(0)) {
1867
+ ctx = this._getOrReturnCtx(input, ctx);
1868
+ addIssueToContext(ctx, {
1869
+ code: ZodIssueCode.not_multiple_of,
1870
+ multipleOf: check.value,
1871
+ message: check.message
1872
+ });
1873
+ status.dirty();
1874
+ }
1875
+ } else {
1876
+ util.assertNever(check);
1877
+ }
1878
+ }
1879
+ return { status: status.value, value: input.data };
1880
+ }
1881
+ _getInvalidInput(input) {
1882
+ const ctx = this._getOrReturnCtx(input);
1883
+ addIssueToContext(ctx, {
1884
+ code: ZodIssueCode.invalid_type,
1885
+ expected: ZodParsedType.bigint,
1886
+ received: ctx.parsedType
1887
+ });
1888
+ return INVALID;
1889
+ }
1890
+ gte(value, message) {
1891
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1892
+ }
1893
+ gt(value, message) {
1894
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1895
+ }
1896
+ lte(value, message) {
1897
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1898
+ }
1899
+ lt(value, message) {
1900
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1901
+ }
1902
+ setLimit(kind, value, inclusive, message) {
1903
+ return new ZodBigInt({
1904
+ ...this._def,
1905
+ checks: [
1906
+ ...this._def.checks,
1907
+ {
1908
+ kind,
1909
+ value,
1910
+ inclusive,
1911
+ message: errorUtil.toString(message)
1912
+ }
1913
+ ]
1914
+ });
1915
+ }
1916
+ _addCheck(check) {
1917
+ return new ZodBigInt({
1918
+ ...this._def,
1919
+ checks: [...this._def.checks, check]
1920
+ });
1921
+ }
1922
+ positive(message) {
1923
+ return this._addCheck({
1924
+ kind: "min",
1925
+ value: BigInt(0),
1926
+ inclusive: false,
1927
+ message: errorUtil.toString(message)
1928
+ });
1929
+ }
1930
+ negative(message) {
1931
+ return this._addCheck({
1932
+ kind: "max",
1933
+ value: BigInt(0),
1934
+ inclusive: false,
1935
+ message: errorUtil.toString(message)
1936
+ });
1937
+ }
1938
+ nonpositive(message) {
1939
+ return this._addCheck({
1940
+ kind: "max",
1941
+ value: BigInt(0),
1942
+ inclusive: true,
1943
+ message: errorUtil.toString(message)
1944
+ });
1945
+ }
1946
+ nonnegative(message) {
1947
+ return this._addCheck({
1948
+ kind: "min",
1949
+ value: BigInt(0),
1950
+ inclusive: true,
1951
+ message: errorUtil.toString(message)
1952
+ });
1953
+ }
1954
+ multipleOf(value, message) {
1955
+ return this._addCheck({
1956
+ kind: "multipleOf",
1957
+ value,
1958
+ message: errorUtil.toString(message)
1959
+ });
1960
+ }
1961
+ get minValue() {
1962
+ let min = null;
1963
+ for (const ch of this._def.checks) {
1964
+ if (ch.kind === "min") {
1965
+ if (min === null || ch.value > min)
1966
+ min = ch.value;
1967
+ }
1968
+ }
1969
+ return min;
1970
+ }
1971
+ get maxValue() {
1972
+ let max = null;
1973
+ for (const ch of this._def.checks) {
1974
+ if (ch.kind === "max") {
1975
+ if (max === null || ch.value < max)
1976
+ max = ch.value;
1977
+ }
1978
+ }
1979
+ return max;
1980
+ }
1981
+ }
1982
+ ZodBigInt.create = (params) => {
1983
+ return new ZodBigInt({
1984
+ checks: [],
1985
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
1986
+ coerce: params?.coerce ?? false,
1987
+ ...processCreateParams(params)
1988
+ });
1989
+ };
1990
+
1991
+ class ZodBoolean extends ZodType {
1992
+ _parse(input) {
1993
+ if (this._def.coerce) {
1994
+ input.data = Boolean(input.data);
1995
+ }
1996
+ const parsedType = this._getType(input);
1997
+ if (parsedType !== ZodParsedType.boolean) {
1998
+ const ctx = this._getOrReturnCtx(input);
1999
+ addIssueToContext(ctx, {
2000
+ code: ZodIssueCode.invalid_type,
2001
+ expected: ZodParsedType.boolean,
2002
+ received: ctx.parsedType
2003
+ });
2004
+ return INVALID;
2005
+ }
2006
+ return OK(input.data);
2007
+ }
2008
+ }
2009
+ ZodBoolean.create = (params) => {
2010
+ return new ZodBoolean({
2011
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
2012
+ coerce: params?.coerce || false,
2013
+ ...processCreateParams(params)
2014
+ });
2015
+ };
2016
+
2017
+ class ZodDate extends ZodType {
2018
+ _parse(input) {
2019
+ if (this._def.coerce) {
2020
+ input.data = new Date(input.data);
2021
+ }
2022
+ const parsedType = this._getType(input);
2023
+ if (parsedType !== ZodParsedType.date) {
2024
+ const ctx2 = this._getOrReturnCtx(input);
2025
+ addIssueToContext(ctx2, {
2026
+ code: ZodIssueCode.invalid_type,
2027
+ expected: ZodParsedType.date,
2028
+ received: ctx2.parsedType
2029
+ });
2030
+ return INVALID;
2031
+ }
2032
+ if (Number.isNaN(input.data.getTime())) {
2033
+ const ctx2 = this._getOrReturnCtx(input);
2034
+ addIssueToContext(ctx2, {
2035
+ code: ZodIssueCode.invalid_date
2036
+ });
2037
+ return INVALID;
2038
+ }
2039
+ const status = new ParseStatus;
2040
+ let ctx = undefined;
2041
+ for (const check of this._def.checks) {
2042
+ if (check.kind === "min") {
2043
+ if (input.data.getTime() < check.value) {
2044
+ ctx = this._getOrReturnCtx(input, ctx);
2045
+ addIssueToContext(ctx, {
2046
+ code: ZodIssueCode.too_small,
2047
+ message: check.message,
2048
+ inclusive: true,
2049
+ exact: false,
2050
+ minimum: check.value,
2051
+ type: "date"
2052
+ });
2053
+ status.dirty();
2054
+ }
2055
+ } else if (check.kind === "max") {
2056
+ if (input.data.getTime() > check.value) {
2057
+ ctx = this._getOrReturnCtx(input, ctx);
2058
+ addIssueToContext(ctx, {
2059
+ code: ZodIssueCode.too_big,
2060
+ message: check.message,
2061
+ inclusive: true,
2062
+ exact: false,
2063
+ maximum: check.value,
2064
+ type: "date"
2065
+ });
2066
+ status.dirty();
2067
+ }
2068
+ } else {
2069
+ util.assertNever(check);
2070
+ }
135
2071
  }
136
- // Add permissions to settings with amp. prefix
137
- mergedSettings['amp.permissions'] = options.permissions;
138
- // Create temp directory
139
- await mkdir(tempDir, { recursive: true });
140
- // Write merged settings to temp file
141
- await writeFile(tempSettingsPath, JSON.stringify(mergedSettings, null, 2), 'utf-8');
142
- // Return temp file path and cleanup function
143
2072
  return {
144
- settingsFilePath: tempSettingsPath,
145
- cleanupTempFile: async () => {
146
- try {
147
- await rm(tempDir, { recursive: true, force: true });
148
- }
149
- catch (error) {
150
- // Ignore cleanup errors
151
- }
152
- },
2073
+ status: status.value,
2074
+ value: new Date(input.data.getTime())
153
2075
  };
2076
+ }
2077
+ _addCheck(check) {
2078
+ return new ZodDate({
2079
+ ...this._def,
2080
+ checks: [...this._def.checks, check]
2081
+ });
2082
+ }
2083
+ min(minDate, message) {
2084
+ return this._addCheck({
2085
+ kind: "min",
2086
+ value: minDate.getTime(),
2087
+ message: errorUtil.toString(message)
2088
+ });
2089
+ }
2090
+ max(maxDate, message) {
2091
+ return this._addCheck({
2092
+ kind: "max",
2093
+ value: maxDate.getTime(),
2094
+ message: errorUtil.toString(message)
2095
+ });
2096
+ }
2097
+ get minDate() {
2098
+ let min = null;
2099
+ for (const ch of this._def.checks) {
2100
+ if (ch.kind === "min") {
2101
+ if (min === null || ch.value > min)
2102
+ min = ch.value;
2103
+ }
2104
+ }
2105
+ return min != null ? new Date(min) : null;
2106
+ }
2107
+ get maxDate() {
2108
+ let max = null;
2109
+ for (const ch of this._def.checks) {
2110
+ if (ch.kind === "max") {
2111
+ if (max === null || ch.value < max)
2112
+ max = ch.value;
2113
+ }
2114
+ }
2115
+ return max != null ? new Date(max) : null;
2116
+ }
154
2117
  }
155
- // ============================================================================
156
- // Environment Variable Management
157
- // ============================================================================
158
- /** Build environment variables for the Amp CLI process */
159
- function buildEnvironmentVariables(options) {
160
- const env = {
161
- ...process.env,
162
- };
163
- // Set AMP_TOOLBOX if toolbox option is provided
164
- if (options.toolbox) {
165
- env.AMP_TOOLBOX = options.toolbox;
2118
+ ZodDate.create = (params) => {
2119
+ return new ZodDate({
2120
+ checks: [],
2121
+ coerce: params?.coerce || false,
2122
+ typeName: ZodFirstPartyTypeKind.ZodDate,
2123
+ ...processCreateParams(params)
2124
+ });
2125
+ };
2126
+
2127
+ class ZodSymbol extends ZodType {
2128
+ _parse(input) {
2129
+ const parsedType = this._getType(input);
2130
+ if (parsedType !== ZodParsedType.symbol) {
2131
+ const ctx = this._getOrReturnCtx(input);
2132
+ addIssueToContext(ctx, {
2133
+ code: ZodIssueCode.invalid_type,
2134
+ expected: ZodParsedType.symbol,
2135
+ received: ctx.parsedType
2136
+ });
2137
+ return INVALID;
2138
+ }
2139
+ return OK(input.data);
2140
+ }
2141
+ }
2142
+ ZodSymbol.create = (params) => {
2143
+ return new ZodSymbol({
2144
+ typeName: ZodFirstPartyTypeKind.ZodSymbol,
2145
+ ...processCreateParams(params)
2146
+ });
2147
+ };
2148
+
2149
+ class ZodUndefined extends ZodType {
2150
+ _parse(input) {
2151
+ const parsedType = this._getType(input);
2152
+ if (parsedType !== ZodParsedType.undefined) {
2153
+ const ctx = this._getOrReturnCtx(input);
2154
+ addIssueToContext(ctx, {
2155
+ code: ZodIssueCode.invalid_type,
2156
+ expected: ZodParsedType.undefined,
2157
+ received: ctx.parsedType
2158
+ });
2159
+ return INVALID;
166
2160
  }
167
- // User-provided env variables override system ones
168
- if (options.env) {
169
- Object.assign(env, options.env);
2161
+ return OK(input.data);
2162
+ }
2163
+ }
2164
+ ZodUndefined.create = (params) => {
2165
+ return new ZodUndefined({
2166
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
2167
+ ...processCreateParams(params)
2168
+ });
2169
+ };
2170
+
2171
+ class ZodNull extends ZodType {
2172
+ _parse(input) {
2173
+ const parsedType = this._getType(input);
2174
+ if (parsedType !== ZodParsedType.null) {
2175
+ const ctx = this._getOrReturnCtx(input);
2176
+ addIssueToContext(ctx, {
2177
+ code: ZodIssueCode.invalid_type,
2178
+ expected: ZodParsedType.null,
2179
+ received: ctx.parsedType
2180
+ });
2181
+ return INVALID;
170
2182
  }
171
- return env;
2183
+ return OK(input.data);
2184
+ }
172
2185
  }
173
- // ============================================================================
174
- // CLI Process Management
175
- // ============================================================================
176
- /** Spawn the Amp CLI process with the given arguments */
177
- function spawnAmpCli(args, options) {
178
- const { env, cwd, signal } = options;
179
- // Find amp executable
180
- const ampCommand = findAmpCommand();
181
- const childProcess = spawn(ampCommand.command, [...ampCommand.args, ...args], {
182
- cwd: cwd || process.cwd(),
183
- env: env || process.env,
184
- stdio: ['pipe', 'pipe', 'pipe'],
185
- signal,
2186
+ ZodNull.create = (params) => {
2187
+ return new ZodNull({
2188
+ typeName: ZodFirstPartyTypeKind.ZodNull,
2189
+ ...processCreateParams(params)
2190
+ });
2191
+ };
2192
+
2193
+ class ZodAny extends ZodType {
2194
+ constructor() {
2195
+ super(...arguments);
2196
+ this._any = true;
2197
+ }
2198
+ _parse(input) {
2199
+ return OK(input.data);
2200
+ }
2201
+ }
2202
+ ZodAny.create = (params) => {
2203
+ return new ZodAny({
2204
+ typeName: ZodFirstPartyTypeKind.ZodAny,
2205
+ ...processCreateParams(params)
2206
+ });
2207
+ };
2208
+
2209
+ class ZodUnknown extends ZodType {
2210
+ constructor() {
2211
+ super(...arguments);
2212
+ this._unknown = true;
2213
+ }
2214
+ _parse(input) {
2215
+ return OK(input.data);
2216
+ }
2217
+ }
2218
+ ZodUnknown.create = (params) => {
2219
+ return new ZodUnknown({
2220
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
2221
+ ...processCreateParams(params)
2222
+ });
2223
+ };
2224
+
2225
+ class ZodNever extends ZodType {
2226
+ _parse(input) {
2227
+ const ctx = this._getOrReturnCtx(input);
2228
+ addIssueToContext(ctx, {
2229
+ code: ZodIssueCode.invalid_type,
2230
+ expected: ZodParsedType.never,
2231
+ received: ctx.parsedType
2232
+ });
2233
+ return INVALID;
2234
+ }
2235
+ }
2236
+ ZodNever.create = (params) => {
2237
+ return new ZodNever({
2238
+ typeName: ZodFirstPartyTypeKind.ZodNever,
2239
+ ...processCreateParams(params)
2240
+ });
2241
+ };
2242
+
2243
+ class ZodVoid extends ZodType {
2244
+ _parse(input) {
2245
+ const parsedType = this._getType(input);
2246
+ if (parsedType !== ZodParsedType.undefined) {
2247
+ const ctx = this._getOrReturnCtx(input);
2248
+ addIssueToContext(ctx, {
2249
+ code: ZodIssueCode.invalid_type,
2250
+ expected: ZodParsedType.void,
2251
+ received: ctx.parsedType
2252
+ });
2253
+ return INVALID;
2254
+ }
2255
+ return OK(input.data);
2256
+ }
2257
+ }
2258
+ ZodVoid.create = (params) => {
2259
+ return new ZodVoid({
2260
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
2261
+ ...processCreateParams(params)
2262
+ });
2263
+ };
2264
+
2265
+ class ZodArray extends ZodType {
2266
+ _parse(input) {
2267
+ const { ctx, status } = this._processInputParams(input);
2268
+ const def = this._def;
2269
+ if (ctx.parsedType !== ZodParsedType.array) {
2270
+ addIssueToContext(ctx, {
2271
+ code: ZodIssueCode.invalid_type,
2272
+ expected: ZodParsedType.array,
2273
+ received: ctx.parsedType
2274
+ });
2275
+ return INVALID;
2276
+ }
2277
+ if (def.exactLength !== null) {
2278
+ const tooBig = ctx.data.length > def.exactLength.value;
2279
+ const tooSmall = ctx.data.length < def.exactLength.value;
2280
+ if (tooBig || tooSmall) {
2281
+ addIssueToContext(ctx, {
2282
+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2283
+ minimum: tooSmall ? def.exactLength.value : undefined,
2284
+ maximum: tooBig ? def.exactLength.value : undefined,
2285
+ type: "array",
2286
+ inclusive: true,
2287
+ exact: true,
2288
+ message: def.exactLength.message
2289
+ });
2290
+ status.dirty();
2291
+ }
2292
+ }
2293
+ if (def.minLength !== null) {
2294
+ if (ctx.data.length < def.minLength.value) {
2295
+ addIssueToContext(ctx, {
2296
+ code: ZodIssueCode.too_small,
2297
+ minimum: def.minLength.value,
2298
+ type: "array",
2299
+ inclusive: true,
2300
+ exact: false,
2301
+ message: def.minLength.message
2302
+ });
2303
+ status.dirty();
2304
+ }
2305
+ }
2306
+ if (def.maxLength !== null) {
2307
+ if (ctx.data.length > def.maxLength.value) {
2308
+ addIssueToContext(ctx, {
2309
+ code: ZodIssueCode.too_big,
2310
+ maximum: def.maxLength.value,
2311
+ type: "array",
2312
+ inclusive: true,
2313
+ exact: false,
2314
+ message: def.maxLength.message
2315
+ });
2316
+ status.dirty();
2317
+ }
2318
+ }
2319
+ if (ctx.common.async) {
2320
+ return Promise.all([...ctx.data].map((item, i) => {
2321
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2322
+ })).then((result2) => {
2323
+ return ParseStatus.mergeArray(status, result2);
2324
+ });
2325
+ }
2326
+ const result = [...ctx.data].map((item, i) => {
2327
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2328
+ });
2329
+ return ParseStatus.mergeArray(status, result);
2330
+ }
2331
+ get element() {
2332
+ return this._def.type;
2333
+ }
2334
+ min(minLength, message) {
2335
+ return new ZodArray({
2336
+ ...this._def,
2337
+ minLength: { value: minLength, message: errorUtil.toString(message) }
2338
+ });
2339
+ }
2340
+ max(maxLength, message) {
2341
+ return new ZodArray({
2342
+ ...this._def,
2343
+ maxLength: { value: maxLength, message: errorUtil.toString(message) }
186
2344
  });
187
- // Add error handler immediately to prevent unhandled error events
188
- childProcess.on('error', () => {
189
- // Error will be handled by waitForProcess
2345
+ }
2346
+ length(len, message) {
2347
+ return new ZodArray({
2348
+ ...this._def,
2349
+ exactLength: { value: len, message: errorUtil.toString(message) }
190
2350
  });
191
- return childProcess;
2351
+ }
2352
+ nonempty(message) {
2353
+ return this.min(1, message);
2354
+ }
192
2355
  }
193
- /** Find the Amp CLI executable in the local node_modules */
194
- function findAmpCommand() {
195
- // Try to find the local CLI (npm already resolved the correct version)
196
- try {
197
- const require = createRequire(import.meta.url);
198
- const pkgJsonPath = require.resolve('@sourcegraph/amp/package.json');
199
- const pkgJsonRaw = fs.readFileSync(pkgJsonPath, 'utf8');
200
- const pkgJson = JSON.parse(pkgJsonRaw);
201
- if (pkgJson.bin?.amp) {
202
- const binPath = path.join(path.dirname(pkgJsonPath), pkgJson.bin.amp);
2356
+ ZodArray.create = (schema, params) => {
2357
+ return new ZodArray({
2358
+ type: schema,
2359
+ minLength: null,
2360
+ maxLength: null,
2361
+ exactLength: null,
2362
+ typeName: ZodFirstPartyTypeKind.ZodArray,
2363
+ ...processCreateParams(params)
2364
+ });
2365
+ };
2366
+ function deepPartialify(schema) {
2367
+ if (schema instanceof ZodObject) {
2368
+ const newShape = {};
2369
+ for (const key in schema.shape) {
2370
+ const fieldSchema = schema.shape[key];
2371
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
2372
+ }
2373
+ return new ZodObject({
2374
+ ...schema._def,
2375
+ shape: () => newShape
2376
+ });
2377
+ } else if (schema instanceof ZodArray) {
2378
+ return new ZodArray({
2379
+ ...schema._def,
2380
+ type: deepPartialify(schema.element)
2381
+ });
2382
+ } else if (schema instanceof ZodOptional) {
2383
+ return ZodOptional.create(deepPartialify(schema.unwrap()));
2384
+ } else if (schema instanceof ZodNullable) {
2385
+ return ZodNullable.create(deepPartialify(schema.unwrap()));
2386
+ } else if (schema instanceof ZodTuple) {
2387
+ return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
2388
+ } else {
2389
+ return schema;
2390
+ }
2391
+ }
2392
+
2393
+ class ZodObject extends ZodType {
2394
+ constructor() {
2395
+ super(...arguments);
2396
+ this._cached = null;
2397
+ this.nonstrict = this.passthrough;
2398
+ this.augment = this.extend;
2399
+ }
2400
+ _getCached() {
2401
+ if (this._cached !== null)
2402
+ return this._cached;
2403
+ const shape = this._def.shape();
2404
+ const keys = util.objectKeys(shape);
2405
+ this._cached = { shape, keys };
2406
+ return this._cached;
2407
+ }
2408
+ _parse(input) {
2409
+ const parsedType = this._getType(input);
2410
+ if (parsedType !== ZodParsedType.object) {
2411
+ const ctx2 = this._getOrReturnCtx(input);
2412
+ addIssueToContext(ctx2, {
2413
+ code: ZodIssueCode.invalid_type,
2414
+ expected: ZodParsedType.object,
2415
+ received: ctx2.parsedType
2416
+ });
2417
+ return INVALID;
2418
+ }
2419
+ const { status, ctx } = this._processInputParams(input);
2420
+ const { shape, keys: shapeKeys } = this._getCached();
2421
+ const extraKeys = [];
2422
+ if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
2423
+ for (const key in ctx.data) {
2424
+ if (!shapeKeys.includes(key)) {
2425
+ extraKeys.push(key);
2426
+ }
2427
+ }
2428
+ }
2429
+ const pairs = [];
2430
+ for (const key of shapeKeys) {
2431
+ const keyValidator = shape[key];
2432
+ const value = ctx.data[key];
2433
+ pairs.push({
2434
+ key: { status: "valid", value: key },
2435
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2436
+ alwaysSet: key in ctx.data
2437
+ });
2438
+ }
2439
+ if (this._def.catchall instanceof ZodNever) {
2440
+ const unknownKeys = this._def.unknownKeys;
2441
+ if (unknownKeys === "passthrough") {
2442
+ for (const key of extraKeys) {
2443
+ pairs.push({
2444
+ key: { status: "valid", value: key },
2445
+ value: { status: "valid", value: ctx.data[key] }
2446
+ });
2447
+ }
2448
+ } else if (unknownKeys === "strict") {
2449
+ if (extraKeys.length > 0) {
2450
+ addIssueToContext(ctx, {
2451
+ code: ZodIssueCode.unrecognized_keys,
2452
+ keys: extraKeys
2453
+ });
2454
+ status.dirty();
2455
+ }
2456
+ } else if (unknownKeys === "strip") {} else {
2457
+ throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2458
+ }
2459
+ } else {
2460
+ const catchall = this._def.catchall;
2461
+ for (const key of extraKeys) {
2462
+ const value = ctx.data[key];
2463
+ pairs.push({
2464
+ key: { status: "valid", value: key },
2465
+ value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2466
+ alwaysSet: key in ctx.data
2467
+ });
2468
+ }
2469
+ }
2470
+ if (ctx.common.async) {
2471
+ return Promise.resolve().then(async () => {
2472
+ const syncPairs = [];
2473
+ for (const pair of pairs) {
2474
+ const key = await pair.key;
2475
+ const value = await pair.value;
2476
+ syncPairs.push({
2477
+ key,
2478
+ value,
2479
+ alwaysSet: pair.alwaysSet
2480
+ });
2481
+ }
2482
+ return syncPairs;
2483
+ }).then((syncPairs) => {
2484
+ return ParseStatus.mergeObjectSync(status, syncPairs);
2485
+ });
2486
+ } else {
2487
+ return ParseStatus.mergeObjectSync(status, pairs);
2488
+ }
2489
+ }
2490
+ get shape() {
2491
+ return this._def.shape();
2492
+ }
2493
+ strict(message) {
2494
+ errorUtil.errToObj;
2495
+ return new ZodObject({
2496
+ ...this._def,
2497
+ unknownKeys: "strict",
2498
+ ...message !== undefined ? {
2499
+ errorMap: (issue, ctx) => {
2500
+ const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
2501
+ if (issue.code === "unrecognized_keys")
203
2502
  return {
204
- command: 'node',
205
- args: [binPath],
2503
+ message: errorUtil.errToObj(message).message ?? defaultError
206
2504
  };
2505
+ return {
2506
+ message: defaultError
2507
+ };
207
2508
  }
208
- throw new Error('Local @sourcegraph/amp package found but no bin entry for Amp CLI');
2509
+ } : {}
2510
+ });
2511
+ }
2512
+ strip() {
2513
+ return new ZodObject({
2514
+ ...this._def,
2515
+ unknownKeys: "strip"
2516
+ });
2517
+ }
2518
+ passthrough() {
2519
+ return new ZodObject({
2520
+ ...this._def,
2521
+ unknownKeys: "passthrough"
2522
+ });
2523
+ }
2524
+ extend(augmentation) {
2525
+ return new ZodObject({
2526
+ ...this._def,
2527
+ shape: () => ({
2528
+ ...this._def.shape(),
2529
+ ...augmentation
2530
+ })
2531
+ });
2532
+ }
2533
+ merge(merging) {
2534
+ const merged = new ZodObject({
2535
+ unknownKeys: merging._def.unknownKeys,
2536
+ catchall: merging._def.catchall,
2537
+ shape: () => ({
2538
+ ...this._def.shape(),
2539
+ ...merging._def.shape()
2540
+ }),
2541
+ typeName: ZodFirstPartyTypeKind.ZodObject
2542
+ });
2543
+ return merged;
2544
+ }
2545
+ setKey(key, schema) {
2546
+ return this.augment({ [key]: schema });
2547
+ }
2548
+ catchall(index) {
2549
+ return new ZodObject({
2550
+ ...this._def,
2551
+ catchall: index
2552
+ });
2553
+ }
2554
+ pick(mask) {
2555
+ const shape = {};
2556
+ for (const key of util.objectKeys(mask)) {
2557
+ if (mask[key] && this.shape[key]) {
2558
+ shape[key] = this.shape[key];
2559
+ }
2560
+ }
2561
+ return new ZodObject({
2562
+ ...this._def,
2563
+ shape: () => shape
2564
+ });
2565
+ }
2566
+ omit(mask) {
2567
+ const shape = {};
2568
+ for (const key of util.objectKeys(this.shape)) {
2569
+ if (!mask[key]) {
2570
+ shape[key] = this.shape[key];
2571
+ }
209
2572
  }
210
- catch (error) {
211
- if (error instanceof Error && error.message.includes('Local @sourcegraph/amp')) {
212
- throw error;
2573
+ return new ZodObject({
2574
+ ...this._def,
2575
+ shape: () => shape
2576
+ });
2577
+ }
2578
+ deepPartial() {
2579
+ return deepPartialify(this);
2580
+ }
2581
+ partial(mask) {
2582
+ const newShape = {};
2583
+ for (const key of util.objectKeys(this.shape)) {
2584
+ const fieldSchema = this.shape[key];
2585
+ if (mask && !mask[key]) {
2586
+ newShape[key] = fieldSchema;
2587
+ } else {
2588
+ newShape[key] = fieldSchema.optional();
2589
+ }
2590
+ }
2591
+ return new ZodObject({
2592
+ ...this._def,
2593
+ shape: () => newShape
2594
+ });
2595
+ }
2596
+ required(mask) {
2597
+ const newShape = {};
2598
+ for (const key of util.objectKeys(this.shape)) {
2599
+ if (mask && !mask[key]) {
2600
+ newShape[key] = this.shape[key];
2601
+ } else {
2602
+ const fieldSchema = this.shape[key];
2603
+ let newField = fieldSchema;
2604
+ while (newField instanceof ZodOptional) {
2605
+ newField = newField._def.innerType;
213
2606
  }
214
- throw new Error('Could not find local @sourcegraph/amp package. Make sure it is installed.');
2607
+ newShape[key] = newField;
2608
+ }
215
2609
  }
2610
+ return new ZodObject({
2611
+ ...this._def,
2612
+ shape: () => newShape
2613
+ });
2614
+ }
2615
+ keyof() {
2616
+ return createZodEnum(util.objectKeys(this.shape));
2617
+ }
216
2618
  }
217
- /** Build CLI arguments from options */
218
- function buildCliArgs(options) {
219
- const args = [];
220
- // Handle continue option first as it changes the base command structure
221
- if (typeof options.continue === 'string') {
222
- args.push('threads', 'continue', options.continue);
2619
+ ZodObject.create = (shape, params) => {
2620
+ return new ZodObject({
2621
+ shape: () => shape,
2622
+ unknownKeys: "strip",
2623
+ catchall: ZodNever.create(),
2624
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2625
+ ...processCreateParams(params)
2626
+ });
2627
+ };
2628
+ ZodObject.strictCreate = (shape, params) => {
2629
+ return new ZodObject({
2630
+ shape: () => shape,
2631
+ unknownKeys: "strict",
2632
+ catchall: ZodNever.create(),
2633
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2634
+ ...processCreateParams(params)
2635
+ });
2636
+ };
2637
+ ZodObject.lazycreate = (shape, params) => {
2638
+ return new ZodObject({
2639
+ shape,
2640
+ unknownKeys: "strip",
2641
+ catchall: ZodNever.create(),
2642
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2643
+ ...processCreateParams(params)
2644
+ });
2645
+ };
2646
+
2647
+ class ZodUnion extends ZodType {
2648
+ _parse(input) {
2649
+ const { ctx } = this._processInputParams(input);
2650
+ const options = this._def.options;
2651
+ function handleResults(results) {
2652
+ for (const result of results) {
2653
+ if (result.result.status === "valid") {
2654
+ return result.result;
2655
+ }
2656
+ }
2657
+ for (const result of results) {
2658
+ if (result.result.status === "dirty") {
2659
+ ctx.common.issues.push(...result.ctx.common.issues);
2660
+ return result.result;
2661
+ }
2662
+ }
2663
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
2664
+ addIssueToContext(ctx, {
2665
+ code: ZodIssueCode.invalid_union,
2666
+ unionErrors
2667
+ });
2668
+ return INVALID;
2669
+ }
2670
+ if (ctx.common.async) {
2671
+ return Promise.all(options.map(async (option) => {
2672
+ const childCtx = {
2673
+ ...ctx,
2674
+ common: {
2675
+ ...ctx.common,
2676
+ issues: []
2677
+ },
2678
+ parent: null
2679
+ };
2680
+ return {
2681
+ result: await option._parseAsync({
2682
+ data: ctx.data,
2683
+ path: ctx.path,
2684
+ parent: childCtx
2685
+ }),
2686
+ ctx: childCtx
2687
+ };
2688
+ })).then(handleResults);
2689
+ } else {
2690
+ let dirty = undefined;
2691
+ const issues = [];
2692
+ for (const option of options) {
2693
+ const childCtx = {
2694
+ ...ctx,
2695
+ common: {
2696
+ ...ctx.common,
2697
+ issues: []
2698
+ },
2699
+ parent: null
2700
+ };
2701
+ const result = option._parseSync({
2702
+ data: ctx.data,
2703
+ path: ctx.path,
2704
+ parent: childCtx
2705
+ });
2706
+ if (result.status === "valid") {
2707
+ return result;
2708
+ } else if (result.status === "dirty" && !dirty) {
2709
+ dirty = { result, ctx: childCtx };
2710
+ }
2711
+ if (childCtx.common.issues.length) {
2712
+ issues.push(childCtx.common.issues);
2713
+ }
2714
+ }
2715
+ if (dirty) {
2716
+ ctx.common.issues.push(...dirty.ctx.common.issues);
2717
+ return dirty.result;
2718
+ }
2719
+ const unionErrors = issues.map((issues2) => new ZodError(issues2));
2720
+ addIssueToContext(ctx, {
2721
+ code: ZodIssueCode.invalid_union,
2722
+ unionErrors
2723
+ });
2724
+ return INVALID;
223
2725
  }
224
- else if (options.continue === true) {
225
- args.push('threads', 'continue');
2726
+ }
2727
+ get options() {
2728
+ return this._def.options;
2729
+ }
2730
+ }
2731
+ ZodUnion.create = (types, params) => {
2732
+ return new ZodUnion({
2733
+ options: types,
2734
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
2735
+ ...processCreateParams(params)
2736
+ });
2737
+ };
2738
+ var getDiscriminator = (type) => {
2739
+ if (type instanceof ZodLazy) {
2740
+ return getDiscriminator(type.schema);
2741
+ } else if (type instanceof ZodEffects) {
2742
+ return getDiscriminator(type.innerType());
2743
+ } else if (type instanceof ZodLiteral) {
2744
+ return [type.value];
2745
+ } else if (type instanceof ZodEnum) {
2746
+ return type.options;
2747
+ } else if (type instanceof ZodNativeEnum) {
2748
+ return util.objectValues(type.enum);
2749
+ } else if (type instanceof ZodDefault) {
2750
+ return getDiscriminator(type._def.innerType);
2751
+ } else if (type instanceof ZodUndefined) {
2752
+ return [undefined];
2753
+ } else if (type instanceof ZodNull) {
2754
+ return [null];
2755
+ } else if (type instanceof ZodOptional) {
2756
+ return [undefined, ...getDiscriminator(type.unwrap())];
2757
+ } else if (type instanceof ZodNullable) {
2758
+ return [null, ...getDiscriminator(type.unwrap())];
2759
+ } else if (type instanceof ZodBranded) {
2760
+ return getDiscriminator(type.unwrap());
2761
+ } else if (type instanceof ZodReadonly) {
2762
+ return getDiscriminator(type.unwrap());
2763
+ } else if (type instanceof ZodCatch) {
2764
+ return getDiscriminator(type._def.innerType);
2765
+ } else {
2766
+ return [];
2767
+ }
2768
+ };
2769
+
2770
+ class ZodDiscriminatedUnion extends ZodType {
2771
+ _parse(input) {
2772
+ const { ctx } = this._processInputParams(input);
2773
+ if (ctx.parsedType !== ZodParsedType.object) {
2774
+ addIssueToContext(ctx, {
2775
+ code: ZodIssueCode.invalid_type,
2776
+ expected: ZodParsedType.object,
2777
+ received: ctx.parsedType
2778
+ });
2779
+ return INVALID;
226
2780
  }
227
- // Add execute and stream-json flags
228
- args.push('--execute', '--stream-json');
229
- // Optional flags
230
- if (options.dangerouslyAllowAll) {
231
- args.push('--dangerously-allow-all');
2781
+ const discriminator = this.discriminator;
2782
+ const discriminatorValue = ctx.data[discriminator];
2783
+ const option = this.optionsMap.get(discriminatorValue);
2784
+ if (!option) {
2785
+ addIssueToContext(ctx, {
2786
+ code: ZodIssueCode.invalid_union_discriminator,
2787
+ options: Array.from(this.optionsMap.keys()),
2788
+ path: [discriminator]
2789
+ });
2790
+ return INVALID;
232
2791
  }
233
- if (options.visibility) {
234
- args.push('--visibility', options.visibility);
2792
+ if (ctx.common.async) {
2793
+ return option._parseAsync({
2794
+ data: ctx.data,
2795
+ path: ctx.path,
2796
+ parent: ctx
2797
+ });
2798
+ } else {
2799
+ return option._parseSync({
2800
+ data: ctx.data,
2801
+ path: ctx.path,
2802
+ parent: ctx
2803
+ });
235
2804
  }
236
- if (options.settingsFile) {
237
- args.push('--settings-file', options.settingsFile);
2805
+ }
2806
+ get discriminator() {
2807
+ return this._def.discriminator;
2808
+ }
2809
+ get options() {
2810
+ return this._def.options;
2811
+ }
2812
+ get optionsMap() {
2813
+ return this._def.optionsMap;
2814
+ }
2815
+ static create(discriminator, options, params) {
2816
+ const optionsMap = new Map;
2817
+ for (const type of options) {
2818
+ const discriminatorValues = getDiscriminator(type.shape[discriminator]);
2819
+ if (!discriminatorValues.length) {
2820
+ throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
2821
+ }
2822
+ for (const value of discriminatorValues) {
2823
+ if (optionsMap.has(value)) {
2824
+ throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
2825
+ }
2826
+ optionsMap.set(value, type);
2827
+ }
238
2828
  }
239
- if (options.logLevel) {
240
- args.push('--log-level', options.logLevel);
2829
+ return new ZodDiscriminatedUnion({
2830
+ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
2831
+ discriminator,
2832
+ options,
2833
+ optionsMap,
2834
+ ...processCreateParams(params)
2835
+ });
2836
+ }
2837
+ }
2838
+ function mergeValues(a, b) {
2839
+ const aType = getParsedType(a);
2840
+ const bType = getParsedType(b);
2841
+ if (a === b) {
2842
+ return { valid: true, data: a };
2843
+ } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
2844
+ const bKeys = util.objectKeys(b);
2845
+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
2846
+ const newObj = { ...a, ...b };
2847
+ for (const key of sharedKeys) {
2848
+ const sharedValue = mergeValues(a[key], b[key]);
2849
+ if (!sharedValue.valid) {
2850
+ return { valid: false };
2851
+ }
2852
+ newObj[key] = sharedValue.data;
241
2853
  }
242
- if (options.logFile) {
243
- args.push('--log-file', options.logFile);
2854
+ return { valid: true, data: newObj };
2855
+ } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
2856
+ if (a.length !== b.length) {
2857
+ return { valid: false };
244
2858
  }
245
- if (options.mcpConfig) {
246
- const mcpConfigValue = typeof options.mcpConfig === 'string'
247
- ? options.mcpConfig
248
- : JSON.stringify(options.mcpConfig);
249
- args.push('--mcp-config', mcpConfigValue);
2859
+ const newArray = [];
2860
+ for (let index = 0;index < a.length; index++) {
2861
+ const itemA = a[index];
2862
+ const itemB = b[index];
2863
+ const sharedValue = mergeValues(itemA, itemB);
2864
+ if (!sharedValue.valid) {
2865
+ return { valid: false };
2866
+ }
2867
+ newArray.push(sharedValue.data);
250
2868
  }
251
- return args;
2869
+ return { valid: true, data: newArray };
2870
+ } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
2871
+ return { valid: true, data: a };
2872
+ } else {
2873
+ return { valid: false };
2874
+ }
252
2875
  }
253
- // ============================================================================
254
- // Stream Processing
255
- // ============================================================================
256
- /** Process the stdout stream from Amp CLI and yield parsed messages */
257
- async function* processOutputStream(stdout) {
258
- if (!stdout) {
259
- throw new Error('No stdout stream available from Amp CLI process');
2876
+
2877
+ class ZodIntersection extends ZodType {
2878
+ _parse(input) {
2879
+ const { status, ctx } = this._processInputParams(input);
2880
+ const handleParsed = (parsedLeft, parsedRight) => {
2881
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) {
2882
+ return INVALID;
2883
+ }
2884
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
2885
+ if (!merged.valid) {
2886
+ addIssueToContext(ctx, {
2887
+ code: ZodIssueCode.invalid_intersection_types
2888
+ });
2889
+ return INVALID;
2890
+ }
2891
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) {
2892
+ status.dirty();
2893
+ }
2894
+ return { status: status.value, value: merged.data };
2895
+ };
2896
+ if (ctx.common.async) {
2897
+ return Promise.all([
2898
+ this._def.left._parseAsync({
2899
+ data: ctx.data,
2900
+ path: ctx.path,
2901
+ parent: ctx
2902
+ }),
2903
+ this._def.right._parseAsync({
2904
+ data: ctx.data,
2905
+ path: ctx.path,
2906
+ parent: ctx
2907
+ })
2908
+ ]).then(([left, right]) => handleParsed(left, right));
2909
+ } else {
2910
+ return handleParsed(this._def.left._parseSync({
2911
+ data: ctx.data,
2912
+ path: ctx.path,
2913
+ parent: ctx
2914
+ }), this._def.right._parseSync({
2915
+ data: ctx.data,
2916
+ path: ctx.path,
2917
+ parent: ctx
2918
+ }));
2919
+ }
2920
+ }
2921
+ }
2922
+ ZodIntersection.create = (left, right, params) => {
2923
+ return new ZodIntersection({
2924
+ left,
2925
+ right,
2926
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
2927
+ ...processCreateParams(params)
2928
+ });
2929
+ };
2930
+
2931
+ class ZodTuple extends ZodType {
2932
+ _parse(input) {
2933
+ const { status, ctx } = this._processInputParams(input);
2934
+ if (ctx.parsedType !== ZodParsedType.array) {
2935
+ addIssueToContext(ctx, {
2936
+ code: ZodIssueCode.invalid_type,
2937
+ expected: ZodParsedType.array,
2938
+ received: ctx.parsedType
2939
+ });
2940
+ return INVALID;
2941
+ }
2942
+ if (ctx.data.length < this._def.items.length) {
2943
+ addIssueToContext(ctx, {
2944
+ code: ZodIssueCode.too_small,
2945
+ minimum: this._def.items.length,
2946
+ inclusive: true,
2947
+ exact: false,
2948
+ type: "array"
2949
+ });
2950
+ return INVALID;
2951
+ }
2952
+ const rest = this._def.rest;
2953
+ if (!rest && ctx.data.length > this._def.items.length) {
2954
+ addIssueToContext(ctx, {
2955
+ code: ZodIssueCode.too_big,
2956
+ maximum: this._def.items.length,
2957
+ inclusive: true,
2958
+ exact: false,
2959
+ type: "array"
2960
+ });
2961
+ status.dirty();
2962
+ }
2963
+ const items = [...ctx.data].map((item, itemIndex) => {
2964
+ const schema = this._def.items[itemIndex] || this._def.rest;
2965
+ if (!schema)
2966
+ return null;
2967
+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
2968
+ }).filter((x) => !!x);
2969
+ if (ctx.common.async) {
2970
+ return Promise.all(items).then((results) => {
2971
+ return ParseStatus.mergeArray(status, results);
2972
+ });
2973
+ } else {
2974
+ return ParseStatus.mergeArray(status, items);
260
2975
  }
261
- const readline = createInterface({
262
- input: stdout,
263
- crlfDelay: Number.POSITIVE_INFINITY,
2976
+ }
2977
+ get items() {
2978
+ return this._def.items;
2979
+ }
2980
+ rest(rest) {
2981
+ return new ZodTuple({
2982
+ ...this._def,
2983
+ rest
264
2984
  });
265
- try {
266
- for await (const line of readline) {
267
- if (!line.trim())
268
- continue;
269
- try {
270
- const message = JSON.parse(line);
271
- yield message;
272
- }
273
- catch (parseError) {
274
- throw new Error(`Failed to parse JSON response, raw line: ${line}`);
275
- }
2985
+ }
2986
+ }
2987
+ ZodTuple.create = (schemas, params) => {
2988
+ if (!Array.isArray(schemas)) {
2989
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
2990
+ }
2991
+ return new ZodTuple({
2992
+ items: schemas,
2993
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
2994
+ rest: null,
2995
+ ...processCreateParams(params)
2996
+ });
2997
+ };
2998
+
2999
+ class ZodRecord extends ZodType {
3000
+ get keySchema() {
3001
+ return this._def.keyType;
3002
+ }
3003
+ get valueSchema() {
3004
+ return this._def.valueType;
3005
+ }
3006
+ _parse(input) {
3007
+ const { status, ctx } = this._processInputParams(input);
3008
+ if (ctx.parsedType !== ZodParsedType.object) {
3009
+ addIssueToContext(ctx, {
3010
+ code: ZodIssueCode.invalid_type,
3011
+ expected: ZodParsedType.object,
3012
+ received: ctx.parsedType
3013
+ });
3014
+ return INVALID;
3015
+ }
3016
+ const pairs = [];
3017
+ const keyType = this._def.keyType;
3018
+ const valueType = this._def.valueType;
3019
+ for (const key in ctx.data) {
3020
+ pairs.push({
3021
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3022
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3023
+ alwaysSet: key in ctx.data
3024
+ });
3025
+ }
3026
+ if (ctx.common.async) {
3027
+ return ParseStatus.mergeObjectAsync(status, pairs);
3028
+ } else {
3029
+ return ParseStatus.mergeObjectSync(status, pairs);
3030
+ }
3031
+ }
3032
+ get element() {
3033
+ return this._def.valueType;
3034
+ }
3035
+ static create(first, second, third) {
3036
+ if (second instanceof ZodType) {
3037
+ return new ZodRecord({
3038
+ keyType: first,
3039
+ valueType: second,
3040
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3041
+ ...processCreateParams(third)
3042
+ });
3043
+ }
3044
+ return new ZodRecord({
3045
+ keyType: ZodString.create(),
3046
+ valueType: first,
3047
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3048
+ ...processCreateParams(second)
3049
+ });
3050
+ }
3051
+ }
3052
+
3053
+ class ZodMap extends ZodType {
3054
+ get keySchema() {
3055
+ return this._def.keyType;
3056
+ }
3057
+ get valueSchema() {
3058
+ return this._def.valueType;
3059
+ }
3060
+ _parse(input) {
3061
+ const { status, ctx } = this._processInputParams(input);
3062
+ if (ctx.parsedType !== ZodParsedType.map) {
3063
+ addIssueToContext(ctx, {
3064
+ code: ZodIssueCode.invalid_type,
3065
+ expected: ZodParsedType.map,
3066
+ received: ctx.parsedType
3067
+ });
3068
+ return INVALID;
3069
+ }
3070
+ const keyType = this._def.keyType;
3071
+ const valueType = this._def.valueType;
3072
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
3073
+ return {
3074
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
3075
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
3076
+ };
3077
+ });
3078
+ if (ctx.common.async) {
3079
+ const finalMap = new Map;
3080
+ return Promise.resolve().then(async () => {
3081
+ for (const pair of pairs) {
3082
+ const key = await pair.key;
3083
+ const value = await pair.value;
3084
+ if (key.status === "aborted" || value.status === "aborted") {
3085
+ return INVALID;
3086
+ }
3087
+ if (key.status === "dirty" || value.status === "dirty") {
3088
+ status.dirty();
3089
+ }
3090
+ finalMap.set(key.value, value.value);
276
3091
  }
3092
+ return { status: status.value, value: finalMap };
3093
+ });
3094
+ } else {
3095
+ const finalMap = new Map;
3096
+ for (const pair of pairs) {
3097
+ const key = pair.key;
3098
+ const value = pair.value;
3099
+ if (key.status === "aborted" || value.status === "aborted") {
3100
+ return INVALID;
3101
+ }
3102
+ if (key.status === "dirty" || value.status === "dirty") {
3103
+ status.dirty();
3104
+ }
3105
+ finalMap.set(key.value, value.value);
3106
+ }
3107
+ return { status: status.value, value: finalMap };
3108
+ }
3109
+ }
3110
+ }
3111
+ ZodMap.create = (keyType, valueType, params) => {
3112
+ return new ZodMap({
3113
+ valueType,
3114
+ keyType,
3115
+ typeName: ZodFirstPartyTypeKind.ZodMap,
3116
+ ...processCreateParams(params)
3117
+ });
3118
+ };
3119
+
3120
+ class ZodSet extends ZodType {
3121
+ _parse(input) {
3122
+ const { status, ctx } = this._processInputParams(input);
3123
+ if (ctx.parsedType !== ZodParsedType.set) {
3124
+ addIssueToContext(ctx, {
3125
+ code: ZodIssueCode.invalid_type,
3126
+ expected: ZodParsedType.set,
3127
+ received: ctx.parsedType
3128
+ });
3129
+ return INVALID;
277
3130
  }
278
- finally {
279
- readline.close();
3131
+ const def = this._def;
3132
+ if (def.minSize !== null) {
3133
+ if (ctx.data.size < def.minSize.value) {
3134
+ addIssueToContext(ctx, {
3135
+ code: ZodIssueCode.too_small,
3136
+ minimum: def.minSize.value,
3137
+ type: "set",
3138
+ inclusive: true,
3139
+ exact: false,
3140
+ message: def.minSize.message
3141
+ });
3142
+ status.dirty();
3143
+ }
280
3144
  }
3145
+ if (def.maxSize !== null) {
3146
+ if (ctx.data.size > def.maxSize.value) {
3147
+ addIssueToContext(ctx, {
3148
+ code: ZodIssueCode.too_big,
3149
+ maximum: def.maxSize.value,
3150
+ type: "set",
3151
+ inclusive: true,
3152
+ exact: false,
3153
+ message: def.maxSize.message
3154
+ });
3155
+ status.dirty();
3156
+ }
3157
+ }
3158
+ const valueType = this._def.valueType;
3159
+ function finalizeSet(elements2) {
3160
+ const parsedSet = new Set;
3161
+ for (const element of elements2) {
3162
+ if (element.status === "aborted")
3163
+ return INVALID;
3164
+ if (element.status === "dirty")
3165
+ status.dirty();
3166
+ parsedSet.add(element.value);
3167
+ }
3168
+ return { status: status.value, value: parsedSet };
3169
+ }
3170
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3171
+ if (ctx.common.async) {
3172
+ return Promise.all(elements).then((elements2) => finalizeSet(elements2));
3173
+ } else {
3174
+ return finalizeSet(elements);
3175
+ }
3176
+ }
3177
+ min(minSize, message) {
3178
+ return new ZodSet({
3179
+ ...this._def,
3180
+ minSize: { value: minSize, message: errorUtil.toString(message) }
3181
+ });
3182
+ }
3183
+ max(maxSize, message) {
3184
+ return new ZodSet({
3185
+ ...this._def,
3186
+ maxSize: { value: maxSize, message: errorUtil.toString(message) }
3187
+ });
3188
+ }
3189
+ size(size, message) {
3190
+ return this.min(size, message).max(size, message);
3191
+ }
3192
+ nonempty(message) {
3193
+ return this.min(1, message);
3194
+ }
281
3195
  }
282
- /** Handle streaming input by writing user messages to the process stdin */
283
- async function handleStreamingInput(process, prompt, signal) {
284
- if (!process.stdin) {
285
- throw new Error('No stdin stream available for Amp CLI process');
3196
+ ZodSet.create = (valueType, params) => {
3197
+ return new ZodSet({
3198
+ valueType,
3199
+ minSize: null,
3200
+ maxSize: null,
3201
+ typeName: ZodFirstPartyTypeKind.ZodSet,
3202
+ ...processCreateParams(params)
3203
+ });
3204
+ };
3205
+
3206
+ class ZodFunction extends ZodType {
3207
+ constructor() {
3208
+ super(...arguments);
3209
+ this.validate = this.implement;
3210
+ }
3211
+ _parse(input) {
3212
+ const { ctx } = this._processInputParams(input);
3213
+ if (ctx.parsedType !== ZodParsedType.function) {
3214
+ addIssueToContext(ctx, {
3215
+ code: ZodIssueCode.invalid_type,
3216
+ expected: ZodParsedType.function,
3217
+ received: ctx.parsedType
3218
+ });
3219
+ return INVALID;
286
3220
  }
287
- // Check if already aborted before starting
288
- signal?.throwIfAborted();
289
- try {
290
- for await (const message of prompt) {
291
- // Check for abort before processing each message
292
- signal?.throwIfAborted();
293
- // Validate message format
294
- const validatedMessage = UserInputMessageSchema.parse(message);
295
- // Send the complete JSON message
296
- const jsonMessage = JSON.stringify(validatedMessage) + '\n';
297
- if (!process.stdin.write(jsonMessage)) {
298
- // Wait for drain if buffer is full, but allow cancellation during wait
299
- await new Promise((resolve, reject) => {
300
- const onAbort = () => reject(signal?.reason || new Error('Aborted'));
301
- signal?.addEventListener('abort', onAbort, { once: true });
302
- process.stdin.once('drain', () => {
303
- // Clean up abort listener when drain completes
304
- signal?.removeEventListener('abort', onAbort);
305
- resolve();
306
- });
307
- });
308
- }
3221
+ function makeArgsIssue(args, error) {
3222
+ return makeIssue({
3223
+ data: args,
3224
+ path: ctx.path,
3225
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3226
+ issueData: {
3227
+ code: ZodIssueCode.invalid_arguments,
3228
+ argumentsError: error
309
3229
  }
3230
+ });
310
3231
  }
311
- finally {
312
- // Close stdin to signal end of input
313
- process.stdin.end();
3232
+ function makeReturnsIssue(returns, error) {
3233
+ return makeIssue({
3234
+ data: returns,
3235
+ path: ctx.path,
3236
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3237
+ issueData: {
3238
+ code: ZodIssueCode.invalid_return_type,
3239
+ returnTypeError: error
3240
+ }
3241
+ });
314
3242
  }
3243
+ const params = { errorMap: ctx.common.contextualErrorMap };
3244
+ const fn = ctx.data;
3245
+ if (this._def.returns instanceof ZodPromise) {
3246
+ const me = this;
3247
+ return OK(async function(...args) {
3248
+ const error = new ZodError([]);
3249
+ const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
3250
+ error.addIssue(makeArgsIssue(args, e));
3251
+ throw error;
3252
+ });
3253
+ const result = await Reflect.apply(fn, this, parsedArgs);
3254
+ const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
3255
+ error.addIssue(makeReturnsIssue(result, e));
3256
+ throw error;
3257
+ });
3258
+ return parsedReturns;
3259
+ });
3260
+ } else {
3261
+ const me = this;
3262
+ return OK(function(...args) {
3263
+ const parsedArgs = me._def.args.safeParse(args, params);
3264
+ if (!parsedArgs.success) {
3265
+ throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3266
+ }
3267
+ const result = Reflect.apply(fn, this, parsedArgs.data);
3268
+ const parsedReturns = me._def.returns.safeParse(result, params);
3269
+ if (!parsedReturns.success) {
3270
+ throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3271
+ }
3272
+ return parsedReturns.data;
3273
+ });
3274
+ }
3275
+ }
3276
+ parameters() {
3277
+ return this._def.args;
3278
+ }
3279
+ returnType() {
3280
+ return this._def.returns;
3281
+ }
3282
+ args(...items) {
3283
+ return new ZodFunction({
3284
+ ...this._def,
3285
+ args: ZodTuple.create(items).rest(ZodUnknown.create())
3286
+ });
3287
+ }
3288
+ returns(returnType) {
3289
+ return new ZodFunction({
3290
+ ...this._def,
3291
+ returns: returnType
3292
+ });
3293
+ }
3294
+ implement(func) {
3295
+ const validatedFunc = this.parse(func);
3296
+ return validatedFunc;
3297
+ }
3298
+ strictImplement(func) {
3299
+ const validatedFunc = this.parse(func);
3300
+ return validatedFunc;
3301
+ }
3302
+ static create(args, returns, params) {
3303
+ return new ZodFunction({
3304
+ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
3305
+ returns: returns || ZodUnknown.create(),
3306
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
3307
+ ...processCreateParams(params)
3308
+ });
3309
+ }
3310
+ }
3311
+
3312
+ class ZodLazy extends ZodType {
3313
+ get schema() {
3314
+ return this._def.getter();
3315
+ }
3316
+ _parse(input) {
3317
+ const { ctx } = this._processInputParams(input);
3318
+ const lazySchema = this._def.getter();
3319
+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
3320
+ }
315
3321
  }
316
- /** Handle string input by writing the prompt to process stdin */
317
- function handleStringInput(process, prompt) {
318
- if (!process.stdin) {
319
- throw new Error('No stdin stream available for Amp CLI process');
3322
+ ZodLazy.create = (getter, params) => {
3323
+ return new ZodLazy({
3324
+ getter,
3325
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
3326
+ ...processCreateParams(params)
3327
+ });
3328
+ };
3329
+
3330
+ class ZodLiteral extends ZodType {
3331
+ _parse(input) {
3332
+ if (input.data !== this._def.value) {
3333
+ const ctx = this._getOrReturnCtx(input);
3334
+ addIssueToContext(ctx, {
3335
+ received: ctx.data,
3336
+ code: ZodIssueCode.invalid_literal,
3337
+ expected: this._def.value
3338
+ });
3339
+ return INVALID;
320
3340
  }
321
- // Write the prompt to stdin and close it
322
- process.stdin.write(prompt + '\n');
323
- process.stdin.end();
3341
+ return { status: "valid", value: input.data };
3342
+ }
3343
+ get value() {
3344
+ return this._def.value;
3345
+ }
324
3346
  }
325
- /** Wait for the process to exit and capture exit code, stderr, and signal */
326
- function waitForProcess(process, signal) {
327
- return new Promise((resolve, reject) => {
328
- let resolved = false;
329
- let stderrData = '';
330
- const cleanup = () => {
331
- resolved = true;
332
- };
333
- // Capture stderr output
334
- if (process.stderr) {
335
- process.stderr.on('data', (data) => {
336
- stderrData += data.toString();
337
- });
3347
+ ZodLiteral.create = (value, params) => {
3348
+ return new ZodLiteral({
3349
+ value,
3350
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
3351
+ ...processCreateParams(params)
3352
+ });
3353
+ };
3354
+ function createZodEnum(values, params) {
3355
+ return new ZodEnum({
3356
+ values,
3357
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
3358
+ ...processCreateParams(params)
3359
+ });
3360
+ }
3361
+
3362
+ class ZodEnum extends ZodType {
3363
+ _parse(input) {
3364
+ if (typeof input.data !== "string") {
3365
+ const ctx = this._getOrReturnCtx(input);
3366
+ const expectedValues = this._def.values;
3367
+ addIssueToContext(ctx, {
3368
+ expected: util.joinValues(expectedValues),
3369
+ received: ctx.parsedType,
3370
+ code: ZodIssueCode.invalid_type
3371
+ });
3372
+ return INVALID;
3373
+ }
3374
+ if (!this._cache) {
3375
+ this._cache = new Set(this._def.values);
3376
+ }
3377
+ if (!this._cache.has(input.data)) {
3378
+ const ctx = this._getOrReturnCtx(input);
3379
+ const expectedValues = this._def.values;
3380
+ addIssueToContext(ctx, {
3381
+ received: ctx.data,
3382
+ code: ZodIssueCode.invalid_enum_value,
3383
+ options: expectedValues
3384
+ });
3385
+ return INVALID;
3386
+ }
3387
+ return OK(input.data);
3388
+ }
3389
+ get options() {
3390
+ return this._def.values;
3391
+ }
3392
+ get enum() {
3393
+ const enumValues = {};
3394
+ for (const val of this._def.values) {
3395
+ enumValues[val] = val;
3396
+ }
3397
+ return enumValues;
3398
+ }
3399
+ get Values() {
3400
+ const enumValues = {};
3401
+ for (const val of this._def.values) {
3402
+ enumValues[val] = val;
3403
+ }
3404
+ return enumValues;
3405
+ }
3406
+ get Enum() {
3407
+ const enumValues = {};
3408
+ for (const val of this._def.values) {
3409
+ enumValues[val] = val;
3410
+ }
3411
+ return enumValues;
3412
+ }
3413
+ extract(values, newDef = this._def) {
3414
+ return ZodEnum.create(values, {
3415
+ ...this._def,
3416
+ ...newDef
3417
+ });
3418
+ }
3419
+ exclude(values, newDef = this._def) {
3420
+ return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
3421
+ ...this._def,
3422
+ ...newDef
3423
+ });
3424
+ }
3425
+ }
3426
+ ZodEnum.create = createZodEnum;
3427
+
3428
+ class ZodNativeEnum extends ZodType {
3429
+ _parse(input) {
3430
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
3431
+ const ctx = this._getOrReturnCtx(input);
3432
+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
3433
+ const expectedValues = util.objectValues(nativeEnumValues);
3434
+ addIssueToContext(ctx, {
3435
+ expected: util.joinValues(expectedValues),
3436
+ received: ctx.parsedType,
3437
+ code: ZodIssueCode.invalid_type
3438
+ });
3439
+ return INVALID;
3440
+ }
3441
+ if (!this._cache) {
3442
+ this._cache = new Set(util.getValidEnumValues(this._def.values));
3443
+ }
3444
+ if (!this._cache.has(input.data)) {
3445
+ const expectedValues = util.objectValues(nativeEnumValues);
3446
+ addIssueToContext(ctx, {
3447
+ received: ctx.data,
3448
+ code: ZodIssueCode.invalid_enum_value,
3449
+ options: expectedValues
3450
+ });
3451
+ return INVALID;
3452
+ }
3453
+ return OK(input.data);
3454
+ }
3455
+ get enum() {
3456
+ return this._def.values;
3457
+ }
3458
+ }
3459
+ ZodNativeEnum.create = (values, params) => {
3460
+ return new ZodNativeEnum({
3461
+ values,
3462
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3463
+ ...processCreateParams(params)
3464
+ });
3465
+ };
3466
+
3467
+ class ZodPromise extends ZodType {
3468
+ unwrap() {
3469
+ return this._def.type;
3470
+ }
3471
+ _parse(input) {
3472
+ const { ctx } = this._processInputParams(input);
3473
+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
3474
+ addIssueToContext(ctx, {
3475
+ code: ZodIssueCode.invalid_type,
3476
+ expected: ZodParsedType.promise,
3477
+ received: ctx.parsedType
3478
+ });
3479
+ return INVALID;
3480
+ }
3481
+ const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
3482
+ return OK(promisified.then((data) => {
3483
+ return this._def.type.parseAsync(data, {
3484
+ path: ctx.path,
3485
+ errorMap: ctx.common.contextualErrorMap
3486
+ });
3487
+ }));
3488
+ }
3489
+ }
3490
+ ZodPromise.create = (schema, params) => {
3491
+ return new ZodPromise({
3492
+ type: schema,
3493
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
3494
+ ...processCreateParams(params)
3495
+ });
3496
+ };
3497
+
3498
+ class ZodEffects extends ZodType {
3499
+ innerType() {
3500
+ return this._def.schema;
3501
+ }
3502
+ sourceType() {
3503
+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
3504
+ }
3505
+ _parse(input) {
3506
+ const { status, ctx } = this._processInputParams(input);
3507
+ const effect = this._def.effect || null;
3508
+ const checkCtx = {
3509
+ addIssue: (arg) => {
3510
+ addIssueToContext(ctx, arg);
3511
+ if (arg.fatal) {
3512
+ status.abort();
3513
+ } else {
3514
+ status.dirty();
338
3515
  }
339
- process.on('exit', (code, processSignal) => {
340
- if (!resolved) {
341
- cleanup();
342
- resolve({ exitCode: code, stderr: stderrData, signal: processSignal });
343
- }
3516
+ },
3517
+ get path() {
3518
+ return ctx.path;
3519
+ }
3520
+ };
3521
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3522
+ if (effect.type === "preprocess") {
3523
+ const processed = effect.transform(ctx.data, checkCtx);
3524
+ if (ctx.common.async) {
3525
+ return Promise.resolve(processed).then(async (processed2) => {
3526
+ if (status.value === "aborted")
3527
+ return INVALID;
3528
+ const result = await this._def.schema._parseAsync({
3529
+ data: processed2,
3530
+ path: ctx.path,
3531
+ parent: ctx
3532
+ });
3533
+ if (result.status === "aborted")
3534
+ return INVALID;
3535
+ if (result.status === "dirty")
3536
+ return DIRTY(result.value);
3537
+ if (status.value === "dirty")
3538
+ return DIRTY(result.value);
3539
+ return result;
344
3540
  });
345
- process.on('error', (error) => {
346
- if (!resolved) {
347
- cleanup();
348
- reject(error);
349
- }
3541
+ } else {
3542
+ if (status.value === "aborted")
3543
+ return INVALID;
3544
+ const result = this._def.schema._parseSync({
3545
+ data: processed,
3546
+ path: ctx.path,
3547
+ parent: ctx
350
3548
  });
351
- // Handle abort signal
352
- if (signal?.aborted) {
353
- if (!resolved) {
354
- cleanup();
355
- reject(new Error('Operation was aborted'));
356
- }
3549
+ if (result.status === "aborted")
3550
+ return INVALID;
3551
+ if (result.status === "dirty")
3552
+ return DIRTY(result.value);
3553
+ if (status.value === "dirty")
3554
+ return DIRTY(result.value);
3555
+ return result;
3556
+ }
3557
+ }
3558
+ if (effect.type === "refinement") {
3559
+ const executeRefinement = (acc) => {
3560
+ const result = effect.refinement(acc, checkCtx);
3561
+ if (ctx.common.async) {
3562
+ return Promise.resolve(result);
357
3563
  }
358
- else if (signal) {
359
- const abortHandler = () => {
360
- if (!resolved) {
361
- cleanup();
362
- reject(new Error('Operation was aborted'));
363
- }
364
- };
365
- signal.addEventListener('abort', abortHandler);
366
- // Clean up listener
367
- process.on('exit', () => {
368
- signal.removeEventListener('abort', abortHandler);
369
- });
3564
+ if (result instanceof Promise) {
3565
+ throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3566
+ }
3567
+ return acc;
3568
+ };
3569
+ if (ctx.common.async === false) {
3570
+ const inner = this._def.schema._parseSync({
3571
+ data: ctx.data,
3572
+ path: ctx.path,
3573
+ parent: ctx
3574
+ });
3575
+ if (inner.status === "aborted")
3576
+ return INVALID;
3577
+ if (inner.status === "dirty")
3578
+ status.dirty();
3579
+ executeRefinement(inner.value);
3580
+ return { status: status.value, value: inner.value };
3581
+ } else {
3582
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
3583
+ if (inner.status === "aborted")
3584
+ return INVALID;
3585
+ if (inner.status === "dirty")
3586
+ status.dirty();
3587
+ return executeRefinement(inner.value).then(() => {
3588
+ return { status: status.value, value: inner.value };
3589
+ });
3590
+ });
3591
+ }
3592
+ }
3593
+ if (effect.type === "transform") {
3594
+ if (ctx.common.async === false) {
3595
+ const base = this._def.schema._parseSync({
3596
+ data: ctx.data,
3597
+ path: ctx.path,
3598
+ parent: ctx
3599
+ });
3600
+ if (!isValid(base))
3601
+ return INVALID;
3602
+ const result = effect.transform(base.value, checkCtx);
3603
+ if (result instanceof Promise) {
3604
+ throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
370
3605
  }
3606
+ return { status: status.value, value: result };
3607
+ } else {
3608
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
3609
+ if (!isValid(base))
3610
+ return INVALID;
3611
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
3612
+ status: status.value,
3613
+ value: result
3614
+ }));
3615
+ });
3616
+ }
3617
+ }
3618
+ util.assertNever(effect);
3619
+ }
3620
+ }
3621
+ ZodEffects.create = (schema, effect, params) => {
3622
+ return new ZodEffects({
3623
+ schema,
3624
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3625
+ effect,
3626
+ ...processCreateParams(params)
3627
+ });
3628
+ };
3629
+ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3630
+ return new ZodEffects({
3631
+ schema,
3632
+ effect: { type: "preprocess", transform: preprocess },
3633
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3634
+ ...processCreateParams(params)
3635
+ });
3636
+ };
3637
+ class ZodOptional extends ZodType {
3638
+ _parse(input) {
3639
+ const parsedType = this._getType(input);
3640
+ if (parsedType === ZodParsedType.undefined) {
3641
+ return OK(undefined);
3642
+ }
3643
+ return this._def.innerType._parse(input);
3644
+ }
3645
+ unwrap() {
3646
+ return this._def.innerType;
3647
+ }
3648
+ }
3649
+ ZodOptional.create = (type, params) => {
3650
+ return new ZodOptional({
3651
+ innerType: type,
3652
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
3653
+ ...processCreateParams(params)
3654
+ });
3655
+ };
3656
+
3657
+ class ZodNullable extends ZodType {
3658
+ _parse(input) {
3659
+ const parsedType = this._getType(input);
3660
+ if (parsedType === ZodParsedType.null) {
3661
+ return OK(null);
3662
+ }
3663
+ return this._def.innerType._parse(input);
3664
+ }
3665
+ unwrap() {
3666
+ return this._def.innerType;
3667
+ }
3668
+ }
3669
+ ZodNullable.create = (type, params) => {
3670
+ return new ZodNullable({
3671
+ innerType: type,
3672
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
3673
+ ...processCreateParams(params)
3674
+ });
3675
+ };
3676
+
3677
+ class ZodDefault extends ZodType {
3678
+ _parse(input) {
3679
+ const { ctx } = this._processInputParams(input);
3680
+ let data = ctx.data;
3681
+ if (ctx.parsedType === ZodParsedType.undefined) {
3682
+ data = this._def.defaultValue();
3683
+ }
3684
+ return this._def.innerType._parse({
3685
+ data,
3686
+ path: ctx.path,
3687
+ parent: ctx
3688
+ });
3689
+ }
3690
+ removeDefault() {
3691
+ return this._def.innerType;
3692
+ }
3693
+ }
3694
+ ZodDefault.create = (type, params) => {
3695
+ return new ZodDefault({
3696
+ innerType: type,
3697
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
3698
+ defaultValue: typeof params.default === "function" ? params.default : () => params.default,
3699
+ ...processCreateParams(params)
3700
+ });
3701
+ };
3702
+
3703
+ class ZodCatch extends ZodType {
3704
+ _parse(input) {
3705
+ const { ctx } = this._processInputParams(input);
3706
+ const newCtx = {
3707
+ ...ctx,
3708
+ common: {
3709
+ ...ctx.common,
3710
+ issues: []
3711
+ }
3712
+ };
3713
+ const result = this._def.innerType._parse({
3714
+ data: newCtx.data,
3715
+ path: newCtx.path,
3716
+ parent: {
3717
+ ...newCtx
3718
+ }
3719
+ });
3720
+ if (isAsync(result)) {
3721
+ return result.then((result2) => {
3722
+ return {
3723
+ status: "valid",
3724
+ value: result2.status === "valid" ? result2.value : this._def.catchValue({
3725
+ get error() {
3726
+ return new ZodError(newCtx.common.issues);
3727
+ },
3728
+ input: newCtx.data
3729
+ })
3730
+ };
3731
+ });
3732
+ } else {
3733
+ return {
3734
+ status: "valid",
3735
+ value: result.status === "valid" ? result.value : this._def.catchValue({
3736
+ get error() {
3737
+ return new ZodError(newCtx.common.issues);
3738
+ },
3739
+ input: newCtx.data
3740
+ })
3741
+ };
3742
+ }
3743
+ }
3744
+ removeCatch() {
3745
+ return this._def.innerType;
3746
+ }
3747
+ }
3748
+ ZodCatch.create = (type, params) => {
3749
+ return new ZodCatch({
3750
+ innerType: type,
3751
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
3752
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
3753
+ ...processCreateParams(params)
3754
+ });
3755
+ };
3756
+
3757
+ class ZodNaN extends ZodType {
3758
+ _parse(input) {
3759
+ const parsedType = this._getType(input);
3760
+ if (parsedType !== ZodParsedType.nan) {
3761
+ const ctx = this._getOrReturnCtx(input);
3762
+ addIssueToContext(ctx, {
3763
+ code: ZodIssueCode.invalid_type,
3764
+ expected: ZodParsedType.nan,
3765
+ received: ctx.parsedType
3766
+ });
3767
+ return INVALID;
3768
+ }
3769
+ return { status: "valid", value: input.data };
3770
+ }
3771
+ }
3772
+ ZodNaN.create = (params) => {
3773
+ return new ZodNaN({
3774
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
3775
+ ...processCreateParams(params)
3776
+ });
3777
+ };
3778
+ var BRAND = Symbol("zod_brand");
3779
+
3780
+ class ZodBranded extends ZodType {
3781
+ _parse(input) {
3782
+ const { ctx } = this._processInputParams(input);
3783
+ const data = ctx.data;
3784
+ return this._def.type._parse({
3785
+ data,
3786
+ path: ctx.path,
3787
+ parent: ctx
3788
+ });
3789
+ }
3790
+ unwrap() {
3791
+ return this._def.type;
3792
+ }
3793
+ }
3794
+
3795
+ class ZodPipeline extends ZodType {
3796
+ _parse(input) {
3797
+ const { status, ctx } = this._processInputParams(input);
3798
+ if (ctx.common.async) {
3799
+ const handleAsync = async () => {
3800
+ const inResult = await this._def.in._parseAsync({
3801
+ data: ctx.data,
3802
+ path: ctx.path,
3803
+ parent: ctx
3804
+ });
3805
+ if (inResult.status === "aborted")
3806
+ return INVALID;
3807
+ if (inResult.status === "dirty") {
3808
+ status.dirty();
3809
+ return DIRTY(inResult.value);
3810
+ } else {
3811
+ return this._def.out._parseAsync({
3812
+ data: inResult.value,
3813
+ path: ctx.path,
3814
+ parent: ctx
3815
+ });
3816
+ }
3817
+ };
3818
+ return handleAsync();
3819
+ } else {
3820
+ const inResult = this._def.in._parseSync({
3821
+ data: ctx.data,
3822
+ path: ctx.path,
3823
+ parent: ctx
3824
+ });
3825
+ if (inResult.status === "aborted")
3826
+ return INVALID;
3827
+ if (inResult.status === "dirty") {
3828
+ status.dirty();
3829
+ return {
3830
+ status: "dirty",
3831
+ value: inResult.value
3832
+ };
3833
+ } else {
3834
+ return this._def.out._parseSync({
3835
+ data: inResult.value,
3836
+ path: ctx.path,
3837
+ parent: ctx
3838
+ });
3839
+ }
3840
+ }
3841
+ }
3842
+ static create(a, b) {
3843
+ return new ZodPipeline({
3844
+ in: a,
3845
+ out: b,
3846
+ typeName: ZodFirstPartyTypeKind.ZodPipeline
3847
+ });
3848
+ }
3849
+ }
3850
+
3851
+ class ZodReadonly extends ZodType {
3852
+ _parse(input) {
3853
+ const result = this._def.innerType._parse(input);
3854
+ const freeze = (data) => {
3855
+ if (isValid(data)) {
3856
+ data.value = Object.freeze(data.value);
3857
+ }
3858
+ return data;
3859
+ };
3860
+ return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
3861
+ }
3862
+ unwrap() {
3863
+ return this._def.innerType;
3864
+ }
3865
+ }
3866
+ ZodReadonly.create = (type, params) => {
3867
+ return new ZodReadonly({
3868
+ innerType: type,
3869
+ typeName: ZodFirstPartyTypeKind.ZodReadonly,
3870
+ ...processCreateParams(params)
3871
+ });
3872
+ };
3873
+ function cleanParams(params, data) {
3874
+ const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
3875
+ const p2 = typeof p === "string" ? { message: p } : p;
3876
+ return p2;
3877
+ }
3878
+ function custom(check, _params = {}, fatal) {
3879
+ if (check)
3880
+ return ZodAny.create().superRefine((data, ctx) => {
3881
+ const r = check(data);
3882
+ if (r instanceof Promise) {
3883
+ return r.then((r2) => {
3884
+ if (!r2) {
3885
+ const params = cleanParams(_params, data);
3886
+ const _fatal = params.fatal ?? fatal ?? true;
3887
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
3888
+ }
3889
+ });
3890
+ }
3891
+ if (!r) {
3892
+ const params = cleanParams(_params, data);
3893
+ const _fatal = params.fatal ?? fatal ?? true;
3894
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
3895
+ }
3896
+ return;
3897
+ });
3898
+ return ZodAny.create();
3899
+ }
3900
+ var late = {
3901
+ object: ZodObject.lazycreate
3902
+ };
3903
+ var ZodFirstPartyTypeKind;
3904
+ (function(ZodFirstPartyTypeKind2) {
3905
+ ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
3906
+ ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
3907
+ ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
3908
+ ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
3909
+ ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
3910
+ ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
3911
+ ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
3912
+ ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
3913
+ ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
3914
+ ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
3915
+ ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
3916
+ ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
3917
+ ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
3918
+ ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
3919
+ ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
3920
+ ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
3921
+ ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
3922
+ ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
3923
+ ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
3924
+ ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
3925
+ ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
3926
+ ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
3927
+ ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
3928
+ ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
3929
+ ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
3930
+ ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
3931
+ ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
3932
+ ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
3933
+ ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
3934
+ ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
3935
+ ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
3936
+ ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
3937
+ ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
3938
+ ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
3939
+ ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
3940
+ ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
3941
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
3942
+ var instanceOfType = (cls, params = {
3943
+ message: `Input not instance of ${cls.name}`
3944
+ }) => custom((data) => data instanceof cls, params);
3945
+ var stringType = ZodString.create;
3946
+ var numberType = ZodNumber.create;
3947
+ var nanType = ZodNaN.create;
3948
+ var bigIntType = ZodBigInt.create;
3949
+ var booleanType = ZodBoolean.create;
3950
+ var dateType = ZodDate.create;
3951
+ var symbolType = ZodSymbol.create;
3952
+ var undefinedType = ZodUndefined.create;
3953
+ var nullType = ZodNull.create;
3954
+ var anyType = ZodAny.create;
3955
+ var unknownType = ZodUnknown.create;
3956
+ var neverType = ZodNever.create;
3957
+ var voidType = ZodVoid.create;
3958
+ var arrayType = ZodArray.create;
3959
+ var objectType = ZodObject.create;
3960
+ var strictObjectType = ZodObject.strictCreate;
3961
+ var unionType = ZodUnion.create;
3962
+ var discriminatedUnionType = ZodDiscriminatedUnion.create;
3963
+ var intersectionType = ZodIntersection.create;
3964
+ var tupleType = ZodTuple.create;
3965
+ var recordType = ZodRecord.create;
3966
+ var mapType = ZodMap.create;
3967
+ var setType = ZodSet.create;
3968
+ var functionType = ZodFunction.create;
3969
+ var lazyType = ZodLazy.create;
3970
+ var literalType = ZodLiteral.create;
3971
+ var enumType = ZodEnum.create;
3972
+ var nativeEnumType = ZodNativeEnum.create;
3973
+ var promiseType = ZodPromise.create;
3974
+ var effectsType = ZodEffects.create;
3975
+ var optionalType = ZodOptional.create;
3976
+ var nullableType = ZodNullable.create;
3977
+ var preprocessType = ZodEffects.createWithPreprocess;
3978
+ var pipelineType = ZodPipeline.create;
3979
+ var ostring = () => stringType().optional();
3980
+ var onumber = () => numberType().optional();
3981
+ var oboolean = () => booleanType().optional();
3982
+ var coerce = {
3983
+ string: (arg) => ZodString.create({ ...arg, coerce: true }),
3984
+ number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
3985
+ boolean: (arg) => ZodBoolean.create({
3986
+ ...arg,
3987
+ coerce: true
3988
+ }),
3989
+ bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
3990
+ date: (arg) => ZodDate.create({ ...arg, coerce: true })
3991
+ };
3992
+ var NEVER = INVALID;
3993
+ // src/types.ts
3994
+ var UserInputMessageSchema = exports_external.object({
3995
+ type: exports_external.literal("user"),
3996
+ message: exports_external.object({
3997
+ role: exports_external.literal("user"),
3998
+ content: exports_external.array(exports_external.object({
3999
+ type: exports_external.literal("text"),
4000
+ text: exports_external.string()
4001
+ }))
4002
+ })
4003
+ });
4004
+ var PermissionMatchConditionSchema = exports_external.lazy(() => exports_external.union([
4005
+ exports_external.string().describe('Pattern match where "*" matches any number of any characters'),
4006
+ exports_external.array(PermissionMatchConditionSchema).min(1).describe("OR match of each entry"),
4007
+ exports_external.boolean().describe("A literal boolean match"),
4008
+ exports_external.number().describe("A literal number match"),
4009
+ exports_external.null().describe("A literal null match"),
4010
+ exports_external.undefined().describe("A literal undefined match"),
4011
+ exports_external.record(exports_external.string(), PermissionMatchConditionSchema).describe("Matching individual keys of an object")
4012
+ ]));
4013
+ var PermissionSchema = exports_external.object({
4014
+ tool: exports_external.string().min(1).describe("The name of the tool to which this entry applies"),
4015
+ matches: exports_external.record(exports_external.string(), PermissionMatchConditionSchema).optional().describe("Maps tool inputs to conditions"),
4016
+ action: exports_external.enum(["allow", "reject", "ask", "delegate"]).describe("How Amp should proceed in case of a match"),
4017
+ context: exports_external.enum(["thread", "subagent"]).optional().describe("Only apply this entry in this context"),
4018
+ to: exports_external.string().min(1).optional().describe('Command to delegate to when action is "delegate"')
4019
+ }).superRefine((data, ctx) => {
4020
+ if (data.action === "delegate" && !data.to) {
4021
+ ctx.addIssue({
4022
+ code: exports_external.ZodIssueCode.custom,
4023
+ message: 'delegate action requires "to" field',
4024
+ path: ["to"]
4025
+ });
4026
+ }
4027
+ if (data.action !== "delegate" && data.to) {
4028
+ ctx.addIssue({
4029
+ code: exports_external.ZodIssueCode.custom,
4030
+ message: '"to" field only allowed with delegate action',
4031
+ path: ["to"]
371
4032
  });
4033
+ }
4034
+ });
4035
+ var MCPServerSchema = exports_external.object({
4036
+ command: exports_external.string().describe("Command to run the MCP server"),
4037
+ args: exports_external.array(exports_external.string()).describe("Arguments for the MCP server command").optional(),
4038
+ env: exports_external.record(exports_external.string(), exports_external.string()).describe("Environment variables for the server").optional()
4039
+ });
4040
+ var MCPConfigSchema = exports_external.record(exports_external.string(), MCPServerSchema).describe("MCP server configurations keyed by server name");
4041
+ var AmpOptionsSchema = exports_external.object({
4042
+ cwd: exports_external.string().describe("Current working directory").optional(),
4043
+ dangerouslyAllowAll: exports_external.boolean().describe("Allow all tool usage without asking for permission").optional(),
4044
+ visibility: exports_external.enum(["private", "public", "workspace", "group"]).describe("Visibility level for new threads").default("workspace").optional(),
4045
+ settingsFile: exports_external.string().describe("Settings file path").optional(),
4046
+ logLevel: exports_external.enum(["debug", "info", "warn", "error", "audit"]).describe("Log level").optional(),
4047
+ logFile: exports_external.string().describe("Log file path").optional(),
4048
+ mcpConfig: exports_external.union([exports_external.string(), MCPConfigSchema]).describe("MCP server configuration as JSON string, path to JSON file, or config object").optional(),
4049
+ env: exports_external.record(exports_external.string(), exports_external.string()).describe("Additional environment variables").optional(),
4050
+ continue: exports_external.union([exports_external.boolean(), exports_external.string()]).describe("Continue the most recent thread (true) or a specific thread by ID (string)").optional(),
4051
+ toolbox: exports_external.string().describe("Folder path with toolbox scripts").optional(),
4052
+ permissions: exports_external.array(PermissionSchema).describe("Permission rules for tool usage").optional()
4053
+ }).strict();
4054
+
4055
+ // src/index.ts
4056
+ var isWindows = process.platform === "win32";
4057
+ async function* execute(options) {
4058
+ const { prompt, options: ampOptions = {}, signal } = options;
4059
+ let validatedOptions = AmpOptionsSchema.parse(ampOptions);
4060
+ const { settingsFilePath, cleanupTempFile } = await buildSettingsFile(validatedOptions, generateSessionId());
4061
+ validatedOptions = {
4062
+ ...validatedOptions,
4063
+ ...settingsFilePath && { settingsFile: settingsFilePath }
4064
+ };
4065
+ const args = buildCliArgs(validatedOptions);
4066
+ const isStreamingInput = typeof prompt !== "string" && Symbol.asyncIterator in prompt;
4067
+ if (isStreamingInput) {
4068
+ args.push("--stream-json-input");
4069
+ }
4070
+ const env = buildEnvironmentVariables(validatedOptions);
4071
+ if (process.env.AMP_DEBUG || validatedOptions.logLevel === "debug") {
4072
+ const ampCommand = findAmpCommand();
4073
+ console.debug(`Executing Amp CLI: ${ampCommand.command} ${[...ampCommand.args, ...args].join(" ")}`);
4074
+ }
4075
+ const ampProcess = spawnAmpCli(args, {
4076
+ env,
4077
+ cwd: validatedOptions.cwd,
4078
+ signal
4079
+ });
4080
+ try {
4081
+ if (isStreamingInput) {
4082
+ handleStreamingInput(ampProcess, prompt);
4083
+ } else if (typeof prompt === "string" && prompt) {
4084
+ handleStringInput(ampProcess, prompt);
4085
+ }
4086
+ yield* processOutputStream(ampProcess.stdout);
4087
+ const { exitCode, stderr, signal: processSignal } = await waitForProcess(ampProcess, signal);
4088
+ if (exitCode === null) {
4089
+ if (signal?.aborted) {
4090
+ throw new Error("Amp CLI process was aborted");
4091
+ } else if (processSignal) {
4092
+ throw new Error(`Amp CLI process was killed by signal ${processSignal}`);
4093
+ } else {
4094
+ throw new Error("Amp CLI process terminated unexpectedly");
4095
+ }
4096
+ } else if (exitCode !== 0) {
4097
+ const errorDetails = stderr ? `: ${stderr}` : "";
4098
+ throw new Error(`Amp CLI process exited with code ${exitCode}${errorDetails}`);
4099
+ }
4100
+ } catch (error) {
4101
+ if (!ampProcess.killed) {
4102
+ ampProcess.kill(isWindows ? "SIGKILL" : "SIGTERM");
4103
+ }
4104
+ throw error;
4105
+ } finally {
4106
+ await cleanupTempFile();
4107
+ }
4108
+ }
4109
+ function generateSessionId() {
4110
+ const randomHex = Math.random().toString(36).substring(2, 10);
4111
+ return `sdk-${Date.now()}-${randomHex}`;
372
4112
  }
373
- // ============================================================================
374
- // Utility Functions
375
- // ============================================================================
376
- /** Create a user input message for streaming conversations */
377
- export function createUserMessage(text) {
4113
+ async function buildSettingsFile(options, sessionId) {
4114
+ if (!options.permissions) {
378
4115
  return {
379
- type: 'user',
380
- message: {
381
- role: 'user',
382
- content: [{ type: 'text', text }],
383
- },
4116
+ settingsFilePath: null,
4117
+ cleanupTempFile: async () => {}
384
4118
  };
4119
+ }
4120
+ const cwd = options.cwd || process.cwd();
4121
+ const tempDir = path.join(cwd, ".tmp", sessionId);
4122
+ const tempSettingsPath = path.join(tempDir, "settings.json");
4123
+ let mergedSettings = {};
4124
+ if (options.settingsFile) {
4125
+ try {
4126
+ const settingsContent = await readFile(options.settingsFile, "utf-8");
4127
+ mergedSettings = JSON.parse(settingsContent);
4128
+ } catch (error) {
4129
+ if (error.code !== "ENOENT") {
4130
+ throw new Error(`Failed to read settings file ${options.settingsFile}: ${error instanceof Error ? error.message : String(error)}`);
4131
+ }
4132
+ }
4133
+ }
4134
+ mergedSettings["amp.permissions"] = options.permissions;
4135
+ await mkdir(tempDir, { recursive: true });
4136
+ await writeFile(tempSettingsPath, JSON.stringify(mergedSettings, null, 2), "utf-8");
4137
+ return {
4138
+ settingsFilePath: tempSettingsPath,
4139
+ cleanupTempFile: async () => {
4140
+ try {
4141
+ await rm(tempDir, { recursive: true, force: true });
4142
+ } catch (error) {}
4143
+ }
4144
+ };
385
4145
  }
386
- /** Create a permission object for controlling tool usage */
387
- export function createPermission(tool, action, options) {
388
- const permission = {
389
- tool,
390
- action,
391
- ...(options?.matches && { matches: options.matches }),
392
- ...(options?.context && { context: options.context }),
4146
+ function buildEnvironmentVariables(options) {
4147
+ const env = {
4148
+ ...process.env
4149
+ };
4150
+ if (options.toolbox) {
4151
+ env.AMP_TOOLBOX = options.toolbox;
4152
+ }
4153
+ if (options.env) {
4154
+ Object.assign(env, options.env);
4155
+ }
4156
+ env.AMP_SDK_VERSION = "0.1.0-20251021152627-g8658f12";
4157
+ return env;
4158
+ }
4159
+ function spawnAmpCli(args, options) {
4160
+ const { env, cwd, signal } = options;
4161
+ const ampCommand = findAmpCommand();
4162
+ const childProcess = spawn(ampCommand.command, [...ampCommand.args, ...args], {
4163
+ cwd: cwd || process.cwd(),
4164
+ env: env || process.env,
4165
+ stdio: ["pipe", "pipe", "pipe"],
4166
+ signal
4167
+ });
4168
+ childProcess.on("error", () => {});
4169
+ return childProcess;
4170
+ }
4171
+ function findAmpCommand() {
4172
+ try {
4173
+ const require2 = createRequire(import.meta.url);
4174
+ const pkgJsonPath = require2.resolve("@sourcegraph/amp/package.json");
4175
+ const pkgJsonRaw = fs.readFileSync(pkgJsonPath, "utf8");
4176
+ const pkgJson = JSON.parse(pkgJsonRaw);
4177
+ if (pkgJson.bin?.amp) {
4178
+ const binPath = path.join(path.dirname(pkgJsonPath), pkgJson.bin.amp);
4179
+ return {
4180
+ command: "node",
4181
+ args: [binPath]
4182
+ };
4183
+ }
4184
+ throw new Error("Local @sourcegraph/amp package found but no bin entry for Amp CLI");
4185
+ } catch (error) {
4186
+ if (error instanceof Error && error.message.includes("Local @sourcegraph/amp")) {
4187
+ throw error;
4188
+ }
4189
+ throw new Error("Could not find local @sourcegraph/amp package. Make sure it is installed.");
4190
+ }
4191
+ }
4192
+ function buildCliArgs(options) {
4193
+ const args = [];
4194
+ if (typeof options.continue === "string") {
4195
+ args.push("threads", "continue", options.continue);
4196
+ } else if (options.continue === true) {
4197
+ args.push("threads", "continue");
4198
+ }
4199
+ args.push("--execute", "--stream-json");
4200
+ if (options.dangerouslyAllowAll) {
4201
+ args.push("--dangerously-allow-all");
4202
+ }
4203
+ if (options.visibility) {
4204
+ args.push("--visibility", options.visibility);
4205
+ }
4206
+ if (options.settingsFile) {
4207
+ args.push("--settings-file", options.settingsFile);
4208
+ }
4209
+ if (options.logLevel) {
4210
+ args.push("--log-level", options.logLevel);
4211
+ }
4212
+ if (options.logFile) {
4213
+ args.push("--log-file", options.logFile);
4214
+ }
4215
+ if (options.mcpConfig) {
4216
+ const mcpConfigValue = typeof options.mcpConfig === "string" ? options.mcpConfig : JSON.stringify(options.mcpConfig);
4217
+ args.push("--mcp-config", mcpConfigValue);
4218
+ }
4219
+ return args;
4220
+ }
4221
+ async function* processOutputStream(stdout) {
4222
+ if (!stdout) {
4223
+ throw new Error("No stdout stream available from Amp CLI process");
4224
+ }
4225
+ const readline = createInterface({
4226
+ input: stdout,
4227
+ crlfDelay: Number.POSITIVE_INFINITY
4228
+ });
4229
+ try {
4230
+ for await (const line of readline) {
4231
+ if (!line.trim())
4232
+ continue;
4233
+ try {
4234
+ const message = JSON.parse(line);
4235
+ yield message;
4236
+ } catch (parseError) {
4237
+ throw new Error(`Failed to parse JSON response, raw line: ${line}`);
4238
+ }
4239
+ }
4240
+ } finally {
4241
+ readline.close();
4242
+ }
4243
+ }
4244
+ async function handleStreamingInput(process2, prompt, signal) {
4245
+ if (!process2.stdin) {
4246
+ throw new Error("No stdin stream available for Amp CLI process");
4247
+ }
4248
+ signal?.throwIfAborted();
4249
+ try {
4250
+ for await (const message of prompt) {
4251
+ signal?.throwIfAborted();
4252
+ const validatedMessage = UserInputMessageSchema.parse(message);
4253
+ const jsonMessage = JSON.stringify(validatedMessage) + `
4254
+ `;
4255
+ if (!process2.stdin.write(jsonMessage)) {
4256
+ await new Promise((resolve, reject) => {
4257
+ const onAbort = () => reject(signal?.reason || new Error("Aborted"));
4258
+ signal?.addEventListener("abort", onAbort, { once: true });
4259
+ process2.stdin.once("drain", () => {
4260
+ signal?.removeEventListener("abort", onAbort);
4261
+ resolve();
4262
+ });
4263
+ });
4264
+ }
4265
+ }
4266
+ } finally {
4267
+ process2.stdin.end();
4268
+ }
4269
+ }
4270
+ function handleStringInput(process2, prompt) {
4271
+ if (!process2.stdin) {
4272
+ throw new Error("No stdin stream available for Amp CLI process");
4273
+ }
4274
+ process2.stdin.write(prompt + `
4275
+ `);
4276
+ process2.stdin.end();
4277
+ }
4278
+ function waitForProcess(process2, signal) {
4279
+ return new Promise((resolve, reject) => {
4280
+ let resolved = false;
4281
+ let stderrData = "";
4282
+ const cleanup = () => {
4283
+ resolved = true;
393
4284
  };
394
- // delegate requires "to"
395
- if (action === 'delegate') {
396
- if (!options?.to) {
397
- throw new Error('delegate action requires "to" option');
4285
+ if (process2.stderr) {
4286
+ process2.stderr.on("data", (data) => {
4287
+ stderrData += data.toString();
4288
+ });
4289
+ }
4290
+ process2.on("exit", (code, processSignal) => {
4291
+ if (!resolved) {
4292
+ cleanup();
4293
+ resolve({ exitCode: code, stderr: stderrData, signal: processSignal });
4294
+ }
4295
+ });
4296
+ process2.on("error", (error) => {
4297
+ if (!resolved) {
4298
+ cleanup();
4299
+ reject(error);
4300
+ }
4301
+ });
4302
+ if (signal?.aborted) {
4303
+ if (!resolved) {
4304
+ cleanup();
4305
+ reject(new Error("Operation was aborted"));
4306
+ }
4307
+ } else if (signal) {
4308
+ const abortHandler = () => {
4309
+ if (!resolved) {
4310
+ cleanup();
4311
+ reject(new Error("Operation was aborted"));
398
4312
  }
399
- permission.to = options.to;
4313
+ };
4314
+ signal.addEventListener("abort", abortHandler);
4315
+ process2.on("exit", () => {
4316
+ signal.removeEventListener("abort", abortHandler);
4317
+ });
4318
+ }
4319
+ });
4320
+ }
4321
+ function createUserMessage(text) {
4322
+ return {
4323
+ type: "user",
4324
+ message: {
4325
+ role: "user",
4326
+ content: [{ type: "text", text }]
4327
+ }
4328
+ };
4329
+ }
4330
+ function createPermission(tool, action, options) {
4331
+ const permission = {
4332
+ tool,
4333
+ action,
4334
+ ...options?.matches && { matches: options.matches },
4335
+ ...options?.context && { context: options.context }
4336
+ };
4337
+ if (action === "delegate") {
4338
+ if (!options?.to) {
4339
+ throw new Error('delegate action requires "to" option');
400
4340
  }
401
- return permission;
4341
+ permission.to = options.to;
4342
+ }
4343
+ return permission;
402
4344
  }
403
- // ============================================================================
404
- // Re-export types for convenience
405
- // ============================================================================
406
- export * from './types.js';
407
- //# sourceMappingURL=index.js.map
4345
+ export {
4346
+ execute,
4347
+ createUserMessage,
4348
+ createPermission,
4349
+ UserInputMessageSchema,
4350
+ PermissionSchema,
4351
+ PermissionMatchConditionSchema,
4352
+ MCPServerSchema,
4353
+ MCPConfigSchema,
4354
+ AmpOptionsSchema
4355
+ };
4356
+
4357
+ //# debugId=0322F896615530DD64756E2164756E21