@dsh-ray/coding-subscription-provider 0.0.1-seed.0 → 0.2.1

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 (56) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +98 -1
  3. package/cordis.patch.yml +8 -0
  4. package/lib/adapter.d.ts +120 -0
  5. package/lib/adapter.d.ts.map +1 -0
  6. package/lib/adapter.js +742 -0
  7. package/lib/adapter.js.map +1 -0
  8. package/lib/auth.d.ts +33 -0
  9. package/lib/auth.d.ts.map +1 -0
  10. package/lib/auth.js +101 -0
  11. package/lib/auth.js.map +1 -0
  12. package/lib/codex-catalog.d.ts +57 -0
  13. package/lib/codex-catalog.d.ts.map +1 -0
  14. package/lib/codex-catalog.js +369 -0
  15. package/lib/codex-catalog.js.map +1 -0
  16. package/lib/codex-direct-auth.d.ts +35 -0
  17. package/lib/codex-direct-auth.d.ts.map +1 -0
  18. package/lib/codex-direct-auth.js +626 -0
  19. package/lib/codex-direct-auth.js.map +1 -0
  20. package/lib/codex-direct-responses.d.ts +57 -0
  21. package/lib/codex-direct-responses.d.ts.map +1 -0
  22. package/lib/codex-direct-responses.js +1759 -0
  23. package/lib/codex-direct-responses.js.map +1 -0
  24. package/lib/config.d.ts +65 -0
  25. package/lib/config.d.ts.map +1 -0
  26. package/lib/config.js +105 -0
  27. package/lib/config.js.map +1 -0
  28. package/lib/index.d.ts +10 -0
  29. package/lib/index.d.ts.map +1 -0
  30. package/lib/index.js +70 -0
  31. package/lib/index.js.map +1 -0
  32. package/lib/process.d.ts +131 -0
  33. package/lib/process.d.ts.map +1 -0
  34. package/lib/process.js +1131 -0
  35. package/lib/process.js.map +1 -0
  36. package/lib/prompt.d.ts +15 -0
  37. package/lib/prompt.d.ts.map +1 -0
  38. package/lib/prompt.js +299 -0
  39. package/lib/prompt.js.map +1 -0
  40. package/lib/providers.d.ts +43 -0
  41. package/lib/providers.d.ts.map +1 -0
  42. package/lib/providers.js +179 -0
  43. package/lib/providers.js.map +1 -0
  44. package/lib/session-cwd.d.ts +26 -0
  45. package/lib/session-cwd.d.ts.map +1 -0
  46. package/lib/session-cwd.js +57 -0
  47. package/lib/session-cwd.js.map +1 -0
  48. package/lib/subscription-catalog.d.ts +51 -0
  49. package/lib/subscription-catalog.d.ts.map +1 -0
  50. package/lib/subscription-catalog.js +290 -0
  51. package/lib/subscription-catalog.js.map +1 -0
  52. package/lib/version.d.ts +2 -0
  53. package/lib/version.d.ts.map +1 -0
  54. package/lib/version.js +2 -0
  55. package/lib/version.js.map +1 -0
  56. package/package.json +82 -4
package/lib/process.js ADDED
@@ -0,0 +1,1131 @@
1
+ import { spawn as nodeSpawn } from 'node:child_process';
2
+ import { chmod, mkdtemp, open, rmdir, unlink } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ /** A stable, credential-free protocol failure that the adapter can map. */
6
+ export class CliProtocolError extends Error {
7
+ provider;
8
+ reason;
9
+ code = 'CLI_PROTOCOL_ERROR';
10
+ constructor(provider, reason) {
11
+ super(protocolErrorMessage(provider, reason), { cause: 'protocol' });
12
+ this.provider = provider;
13
+ this.reason = reason;
14
+ this.name = 'CliProtocolError';
15
+ }
16
+ }
17
+ /** Cursor reported, or failed to report, the subscription login required by this route. */
18
+ export class CliSubscriptionAuthError extends Error {
19
+ provider;
20
+ reason;
21
+ code = 'CLI_SUBSCRIPTION_AUTH_ERROR';
22
+ constructor(provider, reason) {
23
+ super(reason === 'MISSING_AUTH_EVENT'
24
+ ? 'cursor CLI did not report its authentication source'
25
+ : 'cursor CLI is not authenticated with the subscription login', { cause: 'subscription-auth' });
26
+ this.provider = provider;
27
+ this.reason = reason;
28
+ this.name = 'CliSubscriptionAuthError';
29
+ }
30
+ }
31
+ /** The child really closed, but not with an unambiguous zero-code, no-signal exit. */
32
+ export class CliProcessExitError extends Error {
33
+ provider;
34
+ exitCode;
35
+ signal;
36
+ code = 'CLI_PROCESS_EXIT_ERROR';
37
+ constructor(provider, exitCode, signal) {
38
+ super(`${provider} CLI exited unsuccessfully (${exitDescription(exitCode, signal)})`, { cause: 'process-exit' });
39
+ this.provider = provider;
40
+ this.exitCode = exitCode;
41
+ this.signal = signal;
42
+ this.name = 'CliProcessExitError';
43
+ }
44
+ }
45
+ /** Codex refused to run because its configured cwd is not an accepted repository. */
46
+ export class CliWorkingDirectoryError extends Error {
47
+ code = 'CLI_WORKING_DIRECTORY_ERROR';
48
+ provider = 'codex';
49
+ constructor() {
50
+ super('codex CLI refused its configured working directory', { cause: 'working-directory' });
51
+ this.name = 'CliWorkingDirectoryError';
52
+ }
53
+ }
54
+ /** SIGKILL was requested, but ChildProcess never proved process/stdio closure. */
55
+ export class CliTeardownTimeoutError extends Error {
56
+ provider;
57
+ timeoutMs;
58
+ code = 'CLI_TEARDOWN_TIMEOUT';
59
+ constructor(provider, timeoutMs) {
60
+ super(`${provider} CLI did not close within ${timeoutMs}ms after SIGKILL`, { cause: 'process-exit' });
61
+ this.provider = provider;
62
+ this.timeoutMs = timeoutMs;
63
+ this.name = 'CliTeardownTimeoutError';
64
+ }
65
+ }
66
+ /** Prompt transport failed without embedding any request content in the error. */
67
+ export class CliPromptInputError extends Error {
68
+ provider;
69
+ reason;
70
+ code = 'CLI_PROMPT_INPUT_ERROR';
71
+ constructor(provider, reason) {
72
+ super(promptInputErrorMessage(provider, reason), { cause: 'prompt-input' });
73
+ this.provider = provider;
74
+ this.reason = reason;
75
+ this.name = 'CliPromptInputError';
76
+ }
77
+ }
78
+ const defaults = {
79
+ timeoutMs: 10 * 60_000,
80
+ killGraceMs: 3_000,
81
+ maxLineBytes: 64 * 1024,
82
+ maxOutputBytes: 512 * 1024,
83
+ maxStderrBytes: 32 * 1024,
84
+ };
85
+ const defaultSpawn = (command, args, options) => nodeSpawn(command, [...args], { ...options, stdio: [...options.stdio] });
86
+ const inheritedEnvNames = new Set([
87
+ 'PATH', 'HOME', 'USER', 'LOGNAME', 'SHELL', 'USERPROFILE',
88
+ 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_CACHE_HOME', 'XDG_RUNTIME_DIR',
89
+ 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'LC_ALL', 'DBUS_SESSION_BUS_ADDRESS',
90
+ 'SystemRoot', 'WINDIR', 'ComSpec', 'PATHEXT', 'APPDATA', 'LOCALAPPDATA',
91
+ 'HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'http_proxy', 'https_proxy', 'no_proxy',
92
+ 'NODE_EXTRA_CA_CERTS', 'SSL_CERT_FILE', 'SSL_CERT_DIR', 'REQUESTS_CA_BUNDLE',
93
+ 'CODEX_HOME', 'CLAUDE_CONFIG_DIR', 'CURSOR_CONFIG_DIR',
94
+ 'GROK_HOME', 'GROK_CONFIG_DIR', 'XAI_CONFIG_DIR',
95
+ ]);
96
+ const excludedEnvNames = new Set([
97
+ 'CODEX_API_KEY', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN',
98
+ 'CLAUDE_CODE_OAUTH_TOKEN',
99
+ 'CURSOR_API_KEY', 'XAI_API_KEY',
100
+ 'OPENAI_BASE_URL', 'ANTHROPIC_BASE_URL', 'XAI_BASE_URL',
101
+ 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY', 'ANTHROPIC_PROFILE',
102
+ ]);
103
+ /** Build an inherited environment that favours the local CLI's subscription login over API-key billing. */
104
+ export function buildSubscriptionEnv(extraEnvNames = []) {
105
+ const env = {};
106
+ for (const name of new Set([...inheritedEnvNames, ...extraEnvNames])) {
107
+ if (excludedEnvNames.has(name.toUpperCase()))
108
+ continue;
109
+ const value = process.env[name];
110
+ if (value !== undefined)
111
+ env[name] = value;
112
+ }
113
+ return env;
114
+ }
115
+ async function preparePromptTransport(invocation) {
116
+ if (invocation.promptTransport === 'stdin') {
117
+ return { args: invocation.args, cleanup: async () => { } };
118
+ }
119
+ let directory;
120
+ let promptPath;
121
+ try {
122
+ directory = await mkdtemp(join(tmpdir(), 'dsh-coding-prompt-'));
123
+ // mkdtemp is private on supported platforms; chmod makes the contract explicit
124
+ // for unusual umasks and for cross-platform transport tests running on POSIX.
125
+ await chmod(directory, 0o700);
126
+ promptPath = join(directory, 'prompt.txt');
127
+ const handle = await open(promptPath, 'wx', 0o600);
128
+ try {
129
+ await handle.writeFile(invocation.prompt, { encoding: 'utf8' });
130
+ }
131
+ finally {
132
+ await handle.close();
133
+ }
134
+ }
135
+ catch {
136
+ if (promptPath !== undefined)
137
+ await unlink(promptPath).catch(() => { });
138
+ if (directory !== undefined)
139
+ await rmdir(directory).catch(() => { });
140
+ throw new CliPromptInputError(invocation.provider, 'FILE_PREPARE_FAILED');
141
+ }
142
+ let fileCleaned = false;
143
+ let directoryCleaned = false;
144
+ const cleanup = async () => {
145
+ if (!fileCleaned) {
146
+ try {
147
+ await unlink(promptPath);
148
+ fileCleaned = true;
149
+ }
150
+ catch (error) {
151
+ if (isNotFoundError(error))
152
+ fileCleaned = true;
153
+ else
154
+ throw new CliPromptInputError(invocation.provider, 'FILE_CLEANUP_FAILED');
155
+ }
156
+ }
157
+ if (!directoryCleaned) {
158
+ try {
159
+ await rmdir(directory);
160
+ directoryCleaned = true;
161
+ }
162
+ catch (error) {
163
+ if (isNotFoundError(error))
164
+ directoryCleaned = true;
165
+ else
166
+ throw new CliPromptInputError(invocation.provider, 'FILE_CLEANUP_FAILED');
167
+ }
168
+ }
169
+ };
170
+ return {
171
+ args: ['--prompt-file', promptPath, ...invocation.args],
172
+ cleanup,
173
+ };
174
+ }
175
+ /**
176
+ * Starts one local, already-authenticated coding CLI and yields only assistant text.
177
+ * It never reads credential files or accepts credential values in config. An explicitly
178
+ * allowlisted environment name may still be forwarded unchanged to the official CLI.
179
+ * No shell is invoked.
180
+ */
181
+ export async function* runCliText(invocation, options = {}) {
182
+ const limits = { ...defaults, ...options };
183
+ // Pre-spawn failures never handed prompt input to the child: report not-submitted and stop.
184
+ const reportPreSpawn = () => {
185
+ if (options.onSettled === undefined)
186
+ return;
187
+ try {
188
+ options.onSettled({ phase: 'spawn', promptSubmissionState: 'not-submitted', assistantTextObserved: false, teardownState: 'not-started' });
189
+ }
190
+ catch {
191
+ // A diagnostic sink must never change model-call settlement.
192
+ }
193
+ };
194
+ if (options.signal?.aborted) {
195
+ reportPreSpawn();
196
+ throw abortError('aborted before CLI spawn');
197
+ }
198
+ let prepared;
199
+ try {
200
+ prepared = await preparePromptTransport(invocation);
201
+ }
202
+ catch (error) {
203
+ reportPreSpawn();
204
+ throw error;
205
+ }
206
+ // Creating a private Grok prompt file is asynchronous. Close the abort race
207
+ // before spawning and remove the file before returning control to the caller.
208
+ if (options.signal?.aborted) {
209
+ let cleanupError;
210
+ try {
211
+ await prepared.cleanup();
212
+ }
213
+ catch (error) {
214
+ cleanupError = error;
215
+ }
216
+ reportPreSpawn();
217
+ throw cleanupError ?? abortError('aborted before CLI spawn');
218
+ }
219
+ let child;
220
+ try {
221
+ child = (options.spawn ?? defaultSpawn)(invocation.command, prepared.args, {
222
+ cwd: invocation.cwd,
223
+ shell: false,
224
+ detached: process.platform !== 'win32',
225
+ stdio: ['pipe', 'pipe', 'pipe'],
226
+ env: buildSubscriptionEnv(options.extraEnvNames),
227
+ });
228
+ }
229
+ catch (error) {
230
+ let cleanupError;
231
+ try {
232
+ await prepared.cleanup();
233
+ }
234
+ catch (cleanupFailure) {
235
+ cleanupError = cleanupFailure;
236
+ }
237
+ reportPreSpawn();
238
+ throw cleanupError ?? error;
239
+ }
240
+ const queue = new TextQueue();
241
+ let totalOutputBytes = 0;
242
+ let stderr = '';
243
+ let finished = false;
244
+ let stopping = false;
245
+ let terminationError;
246
+ let sawIncrementalText = false;
247
+ let sawAggregateText = false;
248
+ let sawValidJson = false;
249
+ let sawAssistantText = false;
250
+ let sawSuccessTerminal = false;
251
+ let terminalReason;
252
+ let sawCursorAuthInit = false;
253
+ let sawChildOutput = false;
254
+ let sawStdoutOutput = false;
255
+ let killTimer;
256
+ let postKillTimer;
257
+ let resolveClosed;
258
+ const closed = new Promise(resolve => { resolveClosed = resolve; });
259
+ let disposeStdin = () => { };
260
+ let disposeStdout = () => { };
261
+ let disposeStderr = () => { };
262
+ // Prompt input is not submitted until either the whole stdin stream flushes or
263
+ // the OS accepts Grok's private prompt-file path. Partial stdin writes are unknown.
264
+ // A temporary-file path already entered spawn argv when spawn() returned, so
265
+ // its state is unknown until a spawn/error event. stdin carries no prompt argv
266
+ // and remains provably not-submitted until the first write attempt.
267
+ let promptSubmissionState = invocation.promptTransport === 'secure-temporary-file'
268
+ ? 'unknown'
269
+ : 'not-submitted';
270
+ let promptInputStarted = false;
271
+ let sawSpawn = false;
272
+ let phase = 'spawn';
273
+ // Teardown begins the moment `stop` fires and completes when ChildProcess `close` is settled.
274
+ let teardownState = 'not-started';
275
+ // Monotonic clock anchors (ms); each metric is reported only when both its ends are known.
276
+ // `spawn()` returning a ChildProcess does not prove the OS accepted it, so the spawn
277
+ // anchor is captured only from the corresponding child event below.
278
+ let spawnedAt;
279
+ let firstEventAt;
280
+ let firstTextAt;
281
+ let terminalAt;
282
+ let stopAt;
283
+ let closeAt;
284
+ let observedExitCode;
285
+ let observedSignal;
286
+ const buildMetrics = () => {
287
+ const metrics = {};
288
+ if (spawnedAt !== undefined && firstEventAt !== undefined && firstEventAt >= spawnedAt) {
289
+ metrics.spawnToFirstEventMs = firstEventAt - spawnedAt;
290
+ }
291
+ if (firstEventAt !== undefined && firstTextAt !== undefined)
292
+ metrics.eventToFirstTextMs = firstTextAt - firstEventAt;
293
+ if (spawnedAt !== undefined && terminalAt !== undefined && terminalAt >= spawnedAt) {
294
+ metrics.spawnToTerminalMs = terminalAt - spawnedAt;
295
+ }
296
+ if (stopAt !== undefined && closeAt !== undefined)
297
+ metrics.teardownDurationMs = closeAt - stopAt;
298
+ return Object.keys(metrics).length > 0 ? metrics : undefined;
299
+ };
300
+ const reportSettled = (error) => {
301
+ if (options.onSettled === undefined)
302
+ return;
303
+ const metrics = buildMetrics();
304
+ const context = {
305
+ phase: error === undefined ? 'terminal' : phase,
306
+ promptSubmissionState,
307
+ assistantTextObserved: sawAssistantText,
308
+ teardownState,
309
+ ...(terminalReason !== undefined ? { terminalReason } : {}),
310
+ ...(observedExitCode !== undefined ? { exitCode: observedExitCode } : {}),
311
+ ...(observedSignal !== undefined ? { signal: observedSignal } : {}),
312
+ ...(metrics !== undefined ? { metrics } : {}),
313
+ };
314
+ try {
315
+ options.onSettled(context);
316
+ }
317
+ catch {
318
+ // A diagnostic sink must never change model-call settlement.
319
+ }
320
+ };
321
+ const stop = (error) => {
322
+ if (stopping || finished)
323
+ return;
324
+ stopping = true;
325
+ terminationError = error;
326
+ if (teardownState === 'not-started')
327
+ teardownState = 'in-progress';
328
+ stopAt ??= performance.now();
329
+ destroyWritable(child.stdin);
330
+ terminateProcessTree(child, 'SIGINT');
331
+ // An injected/embedded ChildProcess may emit close synchronously from kill().
332
+ // Do not arm escalation after that close already settled the request.
333
+ if (finished)
334
+ return;
335
+ killTimer = setTimeout(() => {
336
+ terminateProcessTree(child, 'SIGKILL');
337
+ // Apply the same guard when SIGKILL synchronously proves closure.
338
+ if (finished)
339
+ return;
340
+ // SIGKILL being sent does not prove that the process (or its stdio) has
341
+ // closed. Give `close` one more bounded grace interval, then settle with
342
+ // an explicit live-process-risk state instead of hanging forever.
343
+ postKillTimer = setTimeout(() => {
344
+ phase = 'child-close';
345
+ teardownState = 'timed-out';
346
+ // Preserve the initiating model-call error (abort/timeout/protocol/limit)
347
+ // for routing and health classification. The distinct teardown risk lives
348
+ // in context; the fallback is only for defensive completeness.
349
+ close(terminationError ?? new CliTeardownTimeoutError(invocation.provider, limits.killGraceMs), false);
350
+ }, limits.killGraceMs);
351
+ }, limits.killGraceMs);
352
+ };
353
+ const onAbort = () => stop(abortError('CLI execution aborted'));
354
+ const timeout = setTimeout(() => stop(timeoutError(limits.timeoutMs)), limits.timeoutMs);
355
+ const cleanupChildTracking = () => {
356
+ child.removeListener?.('spawn', onSpawn);
357
+ child.removeListener?.('error', onError);
358
+ child.removeListener?.('close', onClose);
359
+ disposeStdin();
360
+ disposeStdout();
361
+ disposeStderr();
362
+ };
363
+ const close = (error, observedClose = true) => {
364
+ if (finished) {
365
+ // A post-deadline close only releases background tracking. The request and
366
+ // its diagnostic callback were already settled exactly once as timed-out.
367
+ if (observedClose && teardownState === 'timed-out') {
368
+ cleanupChildTracking();
369
+ // A child may have kept the prompt file open past the teardown
370
+ // deadline. Retry deletion once actual process/stdio closure is observed.
371
+ void prepared.cleanup().catch(() => { });
372
+ }
373
+ return;
374
+ }
375
+ finished = true;
376
+ clearTimeout(timeout);
377
+ if (killTimer)
378
+ clearTimeout(killTimer);
379
+ if (postKillTimer)
380
+ clearTimeout(postKillTimer);
381
+ options.signal?.removeEventListener('abort', onAbort);
382
+ if (observedClose) {
383
+ // The child's stdio has now closed; any teardown started by `stop` has completed.
384
+ closeAt ??= performance.now();
385
+ if (teardownState === 'in-progress')
386
+ teardownState = 'completed';
387
+ cleanupChildTracking();
388
+ }
389
+ else {
390
+ // The request is bounded, while minimal background listeners keep draining
391
+ // pipes and observe a late close without ever reporting a second settlement.
392
+ child.unref?.();
393
+ }
394
+ if (stderr) {
395
+ try {
396
+ options.onDiagnostic?.(stderr);
397
+ }
398
+ catch {
399
+ // Diagnostics must never change model-call settlement.
400
+ }
401
+ }
402
+ const settleAfterPromptCleanup = async () => {
403
+ let settledError = error;
404
+ try {
405
+ await prepared.cleanup();
406
+ }
407
+ catch (cleanupError) {
408
+ if (settledError === undefined) {
409
+ phase = 'child-close';
410
+ settledError = cleanupError;
411
+ }
412
+ }
413
+ reportSettled(settledError);
414
+ queue.close(settledError);
415
+ resolveClosed?.();
416
+ };
417
+ void settleAfterPromptCleanup();
418
+ };
419
+ const onError = (error) => {
420
+ // Node guarantees `close` after a spawn `error`. Waiting for it also avoids
421
+ // treating a kill-related error as proof that a live process has exited.
422
+ // Any spawn error before both a `spawn` event and any child output (ENOENT,
423
+ // EACCES, and every other pre-run failure alike) proves prompt input was never
424
+ // attempted, so replay stays safe. Once the child has spawned or produced
425
+ // output, submission is no longer disprovable.
426
+ if (!stopping && !sawSpawn && !sawChildOutput)
427
+ promptSubmissionState = 'not-submitted';
428
+ if (!terminationError)
429
+ terminationError = error;
430
+ stopping = true;
431
+ };
432
+ const settleChildClose = (code, signal) => {
433
+ if (terminationError)
434
+ close(terminationError);
435
+ else if (code !== 0 || signal !== null) {
436
+ phase = 'child-close';
437
+ close(invocation.provider === 'codex' && code === 1 && signal === null && !sawStdoutOutput
438
+ && isCodexWorkingDirectoryRejection(stderr)
439
+ ? new CliWorkingDirectoryError()
440
+ : new CliProcessExitError(invocation.provider, code, signal));
441
+ }
442
+ else
443
+ close(validateProtocolSettlement(invocation.provider, {
444
+ sawValidJson,
445
+ sawAssistantText,
446
+ sawSuccessTerminal,
447
+ sawCursorAuthInit,
448
+ }));
449
+ };
450
+ const onClose = (code, signal) => {
451
+ observedExitCode = code;
452
+ observedSignal = signal;
453
+ if (finished) {
454
+ settleChildClose(code, signal);
455
+ return;
456
+ }
457
+ // Writable `finish` is queued on nextTick for Node streams. Give it that one
458
+ // bounded turn, then fail closed if a reduced process shim closed without ever
459
+ // completing or explicitly failing its stdin lifecycle.
460
+ process.nextTick(() => {
461
+ if (!terminationError && invocation.promptTransport === 'stdin'
462
+ && promptInputStarted && promptSubmissionState !== 'submitted') {
463
+ phase = 'prompt';
464
+ close(new CliPromptInputError(invocation.provider, 'CLOSED_EARLY'));
465
+ return;
466
+ }
467
+ settleChildClose(code, signal);
468
+ });
469
+ };
470
+ const startPromptSubmission = () => {
471
+ if (promptInputStarted || stopping || finished)
472
+ return;
473
+ promptInputStarted = true;
474
+ phase = 'prompt';
475
+ if (invocation.promptTransport === 'secure-temporary-file') {
476
+ // The spawn event proves the private path was handed to the child. Keep the
477
+ // file until child-close so the child cannot race path opening against cleanup.
478
+ promptSubmissionState = 'submitted';
479
+ disposeStdin = closeUnusedWritable(child.stdin);
480
+ return;
481
+ }
482
+ const input = child.stdin;
483
+ if (!input) {
484
+ stop(new CliPromptInputError(invocation.provider, 'MISSING_STDIN'));
485
+ return;
486
+ }
487
+ promptSubmissionState = 'unknown';
488
+ let inputSettled = false;
489
+ const onInputFinish = () => {
490
+ if (inputSettled)
491
+ return;
492
+ inputSettled = true;
493
+ promptSubmissionState = 'submitted';
494
+ };
495
+ const onInputError = () => {
496
+ if (inputSettled)
497
+ return;
498
+ inputSettled = true;
499
+ if (stopping || finished)
500
+ return;
501
+ stop(new CliPromptInputError(invocation.provider, 'WRITE_FAILED'));
502
+ };
503
+ const onInputClose = () => {
504
+ if (inputSettled)
505
+ return;
506
+ inputSettled = true;
507
+ if (stopping || finished)
508
+ return;
509
+ stop(new CliPromptInputError(invocation.provider, 'CLOSED_EARLY'));
510
+ };
511
+ input.once('finish', onInputFinish);
512
+ // Keep absorbing any follow-up stream errors until child-close cleanup.
513
+ input.on('error', onInputError);
514
+ input.once('close', onInputClose);
515
+ disposeStdin = () => {
516
+ input.removeListener('finish', onInputFinish);
517
+ input.removeListener('error', onInputError);
518
+ input.removeListener('close', onInputClose);
519
+ };
520
+ try {
521
+ input.end(invocation.prompt);
522
+ }
523
+ catch {
524
+ onInputError();
525
+ }
526
+ };
527
+ // A delivered `spawn` is the first point at which prompt transport may begin.
528
+ const onSpawn = () => {
529
+ sawSpawn = true;
530
+ spawnedAt ??= performance.now();
531
+ if (phase === 'spawn')
532
+ phase = 'initialize';
533
+ startPromptSubmission();
534
+ };
535
+ child.once('spawn', onSpawn);
536
+ child.once('error', onError);
537
+ // Unlike `exit`, `close` fires after stdio is closed, so the final JSONL event
538
+ // cannot be dropped while buffered stdout is still draining.
539
+ child.once('close', onClose);
540
+ disposeStdout = consumeLines(child.stdout, limits.maxLineBytes, line => {
541
+ if (stopping || finished)
542
+ return;
543
+ // Real ChildProcess always emits `spawn` before output. Starting here as a
544
+ // defensive fallback also supports embedders that provide a reduced process shim.
545
+ startPromptSubmission();
546
+ // Child output proves the process ran. Without a full stdin finish or accepted
547
+ // prompt-file path, replay safety is unknown.
548
+ sawChildOutput = true;
549
+ if (promptSubmissionState === 'not-submitted')
550
+ promptSubmissionState = 'unknown';
551
+ const decoded = decodeJsonLine(line);
552
+ if (decoded.kind === 'empty')
553
+ return;
554
+ if (sawSuccessTerminal) {
555
+ stop(new CliProtocolError(invocation.provider, 'EVENT_AFTER_TERMINAL'));
556
+ return;
557
+ }
558
+ sawStdoutOutput = true;
559
+ if (decoded.kind === 'malformed') {
560
+ stop(new CliProtocolError(invocation.provider, 'MALFORMED_JSON'));
561
+ return;
562
+ }
563
+ sawValidJson = true;
564
+ if (!decoded.event) {
565
+ stop(new CliProtocolError(invocation.provider, 'UNKNOWN_EVENT'));
566
+ return;
567
+ }
568
+ const parsed = parseProviderEvent(invocation.provider, decoded.event);
569
+ if (!parsed) {
570
+ stop(new CliProtocolError(invocation.provider, 'UNKNOWN_EVENT'));
571
+ return;
572
+ }
573
+ firstEventAt ??= performance.now();
574
+ if (phase === 'spawn' || phase === 'initialize')
575
+ phase = 'prompt';
576
+ if (parsed.auth === 'subscription')
577
+ sawCursorAuthInit = true;
578
+ else if (parsed.auth === 'other') {
579
+ stop(new CliSubscriptionAuthError('cursor', 'UNEXPECTED_AUTH_SOURCE'));
580
+ return;
581
+ }
582
+ if (parsed.nativeTool) {
583
+ terminalReason = 'native-tool-event';
584
+ phase = 'terminal';
585
+ stop(new CliProtocolError(invocation.provider, 'NATIVE_TOOL_EVENT'));
586
+ return;
587
+ }
588
+ if (parsed.outcome === 'failure') {
589
+ terminalReason = 'reported-failure';
590
+ phase = 'terminal';
591
+ stop(new CliProtocolError(invocation.provider, 'REPORTED_FAILURE'));
592
+ return;
593
+ }
594
+ if (parsed.outcome === 'invalid') {
595
+ terminalReason = 'invalid-terminal';
596
+ phase = 'terminal';
597
+ stop(new CliProtocolError(invocation.provider, 'INVALID_TERMINAL'));
598
+ return;
599
+ }
600
+ if (parsed.outcome === 'success') {
601
+ sawSuccessTerminal = true;
602
+ terminalReason = 'success';
603
+ terminalAt ??= performance.now();
604
+ phase = 'terminal';
605
+ }
606
+ if (!parsed.text)
607
+ return;
608
+ sawAssistantText = true;
609
+ firstTextAt ??= performance.now();
610
+ if (phase === 'prompt')
611
+ phase = 'stream';
612
+ if (parsed.terminal && (sawIncrementalText || sawAggregateText))
613
+ return;
614
+ if (parsed.terminal)
615
+ sawAggregateText = true;
616
+ else
617
+ sawIncrementalText = true;
618
+ totalOutputBytes += byteLength(parsed.text);
619
+ if (totalOutputBytes > limits.maxOutputBytes) {
620
+ stop(outputLimitError(limits.maxOutputBytes));
621
+ return;
622
+ }
623
+ queue.push(parsed.text);
624
+ }, error => stop(error));
625
+ disposeStderr = consumeLines(child.stderr, limits.maxLineBytes, line => {
626
+ if (stopping || finished)
627
+ return;
628
+ startPromptSubmission();
629
+ sawChildOutput = true;
630
+ if (promptSubmissionState === 'not-submitted')
631
+ promptSubmissionState = 'unknown';
632
+ // Stderr is diagnostic only; never expose it as model output or retain it unbounded.
633
+ stderr = appendBounded(stderr, line, limits.maxStderrBytes);
634
+ }, error => stop(error));
635
+ options.signal?.addEventListener('abort', onAbort, { once: true });
636
+ // Close the race where the signal aborted after the pre-spawn check but before
637
+ // listener registration. Child and pipe lifecycle handlers are installed first,
638
+ // including for injected process implementations whose kill() settles synchronously.
639
+ if (options.signal?.aborted)
640
+ onAbort();
641
+ try {
642
+ for await (const text of queue)
643
+ yield text;
644
+ }
645
+ finally {
646
+ // A consumer that breaks early must still give SIGINT the grace interval.
647
+ if (!finished)
648
+ stop(abortError('CLI output consumer closed early'));
649
+ await closed;
650
+ }
651
+ }
652
+ export function parseAssistantEvent(provider, line) {
653
+ const decoded = decodeJsonLine(line);
654
+ return decoded.kind === 'json' && decoded.event ? parseProviderEvent(provider, decoded.event) : undefined;
655
+ }
656
+ /**
657
+ * Recognizes one already-decoded JSON event into the normalized {@link ParsedEvent}.
658
+ * The layering is: `decodeJsonLine` (syntax) -> a per-provider decoder (shape) ->
659
+ * this dispatcher (routing) -> the stdout reducer in `runCliText` (text/terminal/auth).
660
+ * An unrecognized event returns `undefined` so the caller can fail closed on it.
661
+ */
662
+ function parseProviderEvent(provider, event) {
663
+ return providerDecoders[provider](event);
664
+ }
665
+ const providerDecoders = {
666
+ codex: decodeCodexEvent,
667
+ claude: decodeClaudeEvent,
668
+ cursor: decodeCursorEvent,
669
+ grok: decodeGrokEvent,
670
+ };
671
+ function decodeCodexEvent(event) {
672
+ const item = object(event.item);
673
+ if (isCodexItemEvent(event.type) && isCodexNativeToolItem(item))
674
+ return nativeTool();
675
+ if (event.type === 'item.completed' && item?.type === 'agent_message')
676
+ return parsed(textOf(item.content) ?? textOf(item.text), false);
677
+ if (event.type === 'agent_message')
678
+ return parsed(textOf(event.content) ?? textOf(event.text), false);
679
+ if (event.type === 'turn.completed')
680
+ return known({ outcome: 'success' });
681
+ if (event.type === 'turn.failed' || event.type === 'error')
682
+ return known({ outcome: 'failure' });
683
+ if (event.type === 'thread.started' || event.type === 'turn.started' || event.type === 'item.started'
684
+ || event.type === 'item.updated' || event.type === 'item.completed')
685
+ return known();
686
+ return undefined;
687
+ }
688
+ function decodeClaudeEvent(event) {
689
+ const inner = object(event.event);
690
+ if (isClaudeNativeToolEvent(event, inner))
691
+ return nativeTool();
692
+ if (event.type === 'stream_event')
693
+ return decodeAnthropicStreamEvent(inner);
694
+ if (event.type === 'assistant')
695
+ return parsed(textOf(event.message) ?? textOf(event.content), true);
696
+ if (event.type === 'result')
697
+ return parsed(textOf(event.result), true, resultOutcome(event));
698
+ if (knownType(event, ['system', 'user', 'auth_status', 'rate_limit_event']))
699
+ return known();
700
+ return undefined;
701
+ }
702
+ function decodeCursorEvent(event) {
703
+ if (isToolLifecycle(event.type) || containsNativeToolBlock(event.message) || containsNativeToolBlock(event.content)) {
704
+ return nativeTool();
705
+ }
706
+ if (event.type === 'system' && event.subtype === 'init') {
707
+ return known({ auth: event.apiKeySource === 'login' ? 'subscription' : 'other' });
708
+ }
709
+ if (event.type === 'system')
710
+ return known();
711
+ if (event.type === 'assistant')
712
+ return parsed(textOf(event.message) ?? textOf(event.content) ?? textOf(event.text), false);
713
+ if (event.type === 'result')
714
+ return parsed(textOf(event.result) ?? textOf(event.message), true, resultOutcome(event));
715
+ if (event.type === 'user')
716
+ return known();
717
+ return undefined;
718
+ }
719
+ function decodeGrokEvent(event) {
720
+ const update = object(event.update);
721
+ const paramsUpdate = object(object(event.params)?.update);
722
+ const anthropic = object(event.event);
723
+ if (isGrokNativeToolEvent(event, update, paramsUpdate, anthropic))
724
+ return nativeTool();
725
+ if (event.type === 'text') {
726
+ return typeof event.data === 'string' ? parsed(event.data, false) : undefined;
727
+ }
728
+ if (event.type === 'error')
729
+ return known({ outcome: 'failure' });
730
+ if (event.type === 'end') {
731
+ if (event.stopReason === 'end_turn')
732
+ return known({ outcome: 'success' });
733
+ if (event.stopReason === 'tool_use')
734
+ return nativeTool();
735
+ if (isKnownGrokFailureStopReason(event.stopReason))
736
+ return known({ outcome: 'failure' });
737
+ return known({ outcome: 'invalid' });
738
+ }
739
+ if (event.type === 'available_commands') {
740
+ if (!Array.isArray(event.tools) || (event.commands !== undefined && !Array.isArray(event.commands)))
741
+ return undefined;
742
+ return event.tools.length === 0 ? known() : nativeTool();
743
+ }
744
+ if (event.type === 'usage') {
745
+ if (event.stopReason === undefined || event.stopReason === 'end_turn')
746
+ return known();
747
+ if (event.stopReason === 'tool_use')
748
+ return nativeTool();
749
+ if (isKnownGrokFailureStopReason(event.stopReason))
750
+ return known({ outcome: 'failure' });
751
+ return known({ outcome: 'invalid' });
752
+ }
753
+ if (event.type === 'streaming-messages-json' || event.type === 'message' || event.type === 'update') {
754
+ const text = textOf(event.text) ?? textOf(event.content) ?? textOf(object(event.delta)?.text) ?? textOf(event.message);
755
+ return text === undefined ? undefined : parsed(text, false);
756
+ }
757
+ if (event.type === 'stream_event')
758
+ return decodeAnthropicStreamEvent(anthropic);
759
+ if (event.type === 'content_block_delta')
760
+ return decodeAnthropicContentBlockDelta(object(event.delta));
761
+ if (typeof event.sessionUpdate === 'string') {
762
+ return decodeGrokSessionUpdate(event.sessionUpdate, event.content ?? update?.content);
763
+ }
764
+ if (typeof update?.sessionUpdate === 'string')
765
+ return decodeGrokSessionUpdate(update.sessionUpdate, update.content);
766
+ if (event.method === 'session/update' && typeof paramsUpdate?.sessionUpdate === 'string') {
767
+ return decodeGrokSessionUpdate(paramsUpdate.sessionUpdate, paramsUpdate.content);
768
+ }
769
+ if (event.type === 'result') {
770
+ const outcome = resultOutcome(event);
771
+ return parsed(textOf(event.result) ?? textOf(event.text), true, outcome === 'success' ? undefined : outcome);
772
+ }
773
+ if (event.type === 'assistant')
774
+ return parsed(textOf(event.message) ?? textOf(event.content) ?? textOf(event.text), false);
775
+ if (knownType(event, ['system', 'user']))
776
+ return known();
777
+ return undefined;
778
+ }
779
+ function isCodexItemEvent(type) {
780
+ return type === 'item.started' || type === 'item.updated' || type === 'item.completed';
781
+ }
782
+ function decodeAnthropicStreamEvent(inner) {
783
+ if (inner?.type === 'content_block_delta')
784
+ return decodeAnthropicContentBlockDelta(object(inner.delta));
785
+ if (inner?.type === 'content_block_start') {
786
+ const block = object(inner.content_block);
787
+ if (!knownValue(block?.type, ['text', 'thinking', 'redacted_thinking']))
788
+ return undefined;
789
+ return parsed(textOf(block?.text), false);
790
+ }
791
+ if (inner?.type === 'error')
792
+ return known({ outcome: 'failure' });
793
+ if (knownValue(inner?.type, ['message_start', 'content_block_stop', 'message_delta', 'message_stop', 'ping']))
794
+ return known();
795
+ return undefined;
796
+ }
797
+ function decodeAnthropicContentBlockDelta(delta) {
798
+ if (delta?.type === undefined && typeof delta?.text === 'string')
799
+ return parsed(delta.text, false);
800
+ if (delta?.type === 'text_delta' && typeof delta.text === 'string')
801
+ return parsed(delta.text, false);
802
+ if (knownValue(delta?.type, ['thinking_delta', 'signature_delta', 'citations_delta']))
803
+ return known();
804
+ return undefined;
805
+ }
806
+ const passiveGrokSessionUpdates = [
807
+ 'user_message_chunk',
808
+ 'agent_thought_chunk',
809
+ 'plan',
810
+ 'plan_update',
811
+ 'plan_removed',
812
+ 'available_commands_update',
813
+ 'current_mode_update',
814
+ 'config_option_update',
815
+ 'session_info_update',
816
+ 'usage_update',
817
+ ];
818
+ function decodeGrokSessionUpdate(type, content) {
819
+ if (type === 'agent_message_chunk') {
820
+ const text = textOf(content);
821
+ return text === undefined ? undefined : parsed(text, false);
822
+ }
823
+ return knownValue(type, passiveGrokSessionUpdates) ? known() : undefined;
824
+ }
825
+ /** Codex exec JSONL currently has only three passive item kinds; every other
826
+ * item kind represents a built-in/dynamic tool or another active capability.
827
+ * Keeping this as a passive allowlist makes new native executors fail closed. */
828
+ function isCodexNativeToolItem(item) {
829
+ if (typeof item?.type !== 'string')
830
+ return true;
831
+ return item.type !== 'agent_message' && item.type !== 'reasoning' && item.type !== 'error';
832
+ }
833
+ function isClaudeNativeToolEvent(event, inner) {
834
+ if (isToolLifecycle(event.type) || event.type === 'tool_progress')
835
+ return true;
836
+ if (event.stop_reason === 'tool_use' || object(event.message)?.stop_reason === 'tool_use')
837
+ return true;
838
+ if (object(inner?.delta)?.stop_reason === 'tool_use')
839
+ return true;
840
+ if (event.type === 'system' && Array.isArray(event.tools) && event.tools.length > 0)
841
+ return true;
842
+ if (containsNativeToolBlock(event.message) || containsNativeToolBlock(event.content)
843
+ || containsNativeToolBlock(event.delta))
844
+ return true;
845
+ return event.type === 'stream_event'
846
+ && (containsNativeToolBlock(inner?.message) || containsNativeToolBlock(inner?.content_block)
847
+ || containsNativeToolBlock(inner?.delta));
848
+ }
849
+ function isGrokNativeToolEvent(event, update, paramsUpdate, anthropic) {
850
+ if (isToolLifecycle(event.type) || isToolLifecycle(event.sessionUpdate)
851
+ || isToolLifecycle(update?.sessionUpdate) || isToolLifecycle(paramsUpdate?.sessionUpdate))
852
+ return true;
853
+ if (event.type === 'available_commands' && Array.isArray(event.tools) && event.tools.length > 0)
854
+ return true;
855
+ if (event.method === 'session/request_permission' || event.method === 'session/requestPermission')
856
+ return true;
857
+ if (containsNativeToolBlock(event.message) || containsNativeToolBlock(event.content)
858
+ || containsNativeToolBlock(event.delta))
859
+ return true;
860
+ return event.type === 'stream_event'
861
+ && (containsNativeToolBlock(anthropic?.message) || containsNativeToolBlock(anthropic?.content_block)
862
+ || containsNativeToolBlock(anthropic?.delta));
863
+ }
864
+ function isToolLifecycle(value) {
865
+ if (typeof value !== 'string')
866
+ return false;
867
+ return value === 'tool_call' || value === 'tool_result' || value === 'tool_use'
868
+ || value.startsWith('tool_call_') || value.startsWith('tool_use_')
869
+ || value === 'hook_execution' || value === 'pending_interaction' || value === 'interaction_resolved';
870
+ }
871
+ function containsNativeToolBlock(value, depth = 0) {
872
+ if (depth > 8)
873
+ return false;
874
+ if (Array.isArray(value))
875
+ return value.some(item => containsNativeToolBlock(item, depth + 1));
876
+ const record = object(value);
877
+ if (record === undefined)
878
+ return false;
879
+ const type = record.type;
880
+ if (isToolLifecycle(type) || type === 'server_tool_use' || type === 'input_json_delta'
881
+ || (typeof type === 'string' && type.endsWith('_tool_result')))
882
+ return true;
883
+ return containsNativeToolBlock(record.content, depth + 1)
884
+ || containsNativeToolBlock(record.message, depth + 1)
885
+ || containsNativeToolBlock(record.content_block, depth + 1)
886
+ || containsNativeToolBlock(record.delta, depth + 1);
887
+ }
888
+ function nativeTool() {
889
+ return { terminal: false, nativeTool: true };
890
+ }
891
+ export function parseAssistantText(provider, line) {
892
+ return parseAssistantEvent(provider, line)?.text;
893
+ }
894
+ function parsed(text, terminal, outcome) {
895
+ return { ...(text ? { text } : {}), terminal, ...(outcome ? { outcome } : {}) };
896
+ }
897
+ function known(fields = {}) {
898
+ return { terminal: false, ...fields };
899
+ }
900
+ function knownType(event, types) {
901
+ return typeof event.type === 'string' && types.includes(event.type);
902
+ }
903
+ function knownValue(value, values) {
904
+ return typeof value === 'string' && values.includes(value);
905
+ }
906
+ function isKnownGrokFailureStopReason(value) {
907
+ return knownValue(value, ['cancelled', 'canceled', 'max_tokens', 'max_turn_requests']);
908
+ }
909
+ function resultOutcome(event) {
910
+ const subtype = typeof event.subtype === 'string' ? event.subtype.toLowerCase() : '';
911
+ if (subtype === 'success' && event.is_error === false)
912
+ return 'success';
913
+ if (event.is_error === true || event.success === false
914
+ || (event.error !== undefined && event.error !== null && event.error !== false)
915
+ || subtype.includes('error') || subtype.includes('fail')
916
+ || subtype.includes('cancel') || subtype.includes('interrupt'))
917
+ return 'failure';
918
+ return 'invalid';
919
+ }
920
+ function decodeJsonLine(line) {
921
+ const trimmed = line.trim();
922
+ if (!trimmed)
923
+ return { kind: 'empty' };
924
+ try {
925
+ const value = JSON.parse(trimmed);
926
+ const event = object(value);
927
+ return event ? { kind: 'json', event } : { kind: 'json' };
928
+ }
929
+ catch {
930
+ return { kind: 'malformed' };
931
+ }
932
+ }
933
+ function validateProtocolSettlement(provider, state) {
934
+ if (provider === 'cursor' && !state.sawCursorAuthInit) {
935
+ return new CliSubscriptionAuthError('cursor', 'MISSING_AUTH_EVENT');
936
+ }
937
+ if (!state.sawValidJson)
938
+ return new CliProtocolError(provider, 'NO_JSON_EVENTS');
939
+ if (!state.sawAssistantText)
940
+ return new CliProtocolError(provider, 'NO_ASSISTANT_TEXT');
941
+ if ((provider === 'codex' || provider === 'claude' || provider === 'cursor' || provider === 'grok') && !state.sawSuccessTerminal) {
942
+ return new CliProtocolError(provider, 'MISSING_SUCCESS_TERMINAL');
943
+ }
944
+ return undefined;
945
+ }
946
+ function protocolErrorMessage(provider, reason) {
947
+ const descriptions = {
948
+ MALFORMED_JSON: 'emitted malformed NDJSON',
949
+ NO_JSON_EVENTS: 'closed without any JSON events',
950
+ UNKNOWN_EVENT: 'emitted an event outside the supported protocol allowlist',
951
+ EVENT_AFTER_TERMINAL: 'emitted an event after its successful terminal event',
952
+ NO_ASSISTANT_TEXT: 'closed without assistant text',
953
+ MISSING_SUCCESS_TERMINAL: 'closed without a successful terminal event',
954
+ INVALID_TERMINAL: 'emitted an unrecognized terminal result',
955
+ NATIVE_TOOL_EVENT: 'emitted a forbidden native tool event',
956
+ REPORTED_FAILURE: 'reported a failed model turn',
957
+ };
958
+ return `${provider} CLI ${descriptions[reason]}`;
959
+ }
960
+ function promptInputErrorMessage(provider, reason) {
961
+ const descriptions = {
962
+ MISSING_STDIN: 'did not expose a writable stdin pipe',
963
+ WRITE_FAILED: 'failed while receiving prompt input',
964
+ CLOSED_EARLY: 'closed before prompt input completed',
965
+ FILE_PREPARE_FAILED: 'could not prepare its private prompt file',
966
+ FILE_CLEANUP_FAILED: 'could not remove its private prompt file',
967
+ };
968
+ return `${provider} CLI ${descriptions[reason]}`;
969
+ }
970
+ function exitDescription(code, signal) {
971
+ const parts = [`code=${code === null ? 'null' : String(code)}`];
972
+ if (signal !== null)
973
+ parts.push(`signal=${signal}`);
974
+ return parts.join(', ');
975
+ }
976
+ function isCodexWorkingDirectoryRejection(diagnostic) {
977
+ const expected = 'Not inside a trusted directory and --skip-git-repo-check was not specified.';
978
+ const allowed = new Set([
979
+ expected,
980
+ 'Reading additional input from stdin...',
981
+ 'Reading prompt from stdin...',
982
+ ]);
983
+ const lines = diagnostic.split(/\r?\n/).map(line => line.trim()).filter(Boolean);
984
+ return lines.includes(expected) && lines.every(line => allowed.has(line));
985
+ }
986
+ function object(value) {
987
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
988
+ }
989
+ function textOf(value) {
990
+ if (typeof value === 'string')
991
+ return value;
992
+ if (value !== null && typeof value === 'object' && !Array.isArray(value))
993
+ return textOf(object(value)?.text) ?? textOf(object(value)?.content);
994
+ if (Array.isArray(value))
995
+ return value.map(part => textOf(part) ?? '').join('') || undefined;
996
+ return undefined;
997
+ }
998
+ function appendBounded(value, addition, limit) {
999
+ const next = `${value}${value ? '\n' : ''}${addition}`;
1000
+ const bytes = Buffer.from(next);
1001
+ return bytes.byteLength <= limit ? next : bytes.subarray(bytes.byteLength - limit).toString('utf8');
1002
+ }
1003
+ function byteLength(value) { return Buffer.byteLength(value, 'utf8'); }
1004
+ function isNotFoundError(error) {
1005
+ return error !== null && typeof error === 'object' && 'code' in error && error.code === 'ENOENT';
1006
+ }
1007
+ function closeUnusedWritable(stream) {
1008
+ if (!stream)
1009
+ return () => { };
1010
+ const onError = () => { };
1011
+ stream.on('error', onError);
1012
+ try {
1013
+ stream.end();
1014
+ }
1015
+ catch {
1016
+ // The prompt lives in the private file; failure to close an unused stdin pipe
1017
+ // neither loses nor exposes it. Keep absorbing a later stream error.
1018
+ }
1019
+ return () => { stream.removeListener('error', onError); };
1020
+ }
1021
+ function destroyWritable(stream) {
1022
+ try {
1023
+ const destroyable = stream;
1024
+ destroyable?.destroy?.();
1025
+ }
1026
+ catch {
1027
+ // Process-tree termination remains the authoritative teardown path.
1028
+ }
1029
+ }
1030
+ function consumeLines(stream, maxLineBytes, onLine, onError) {
1031
+ if (!stream)
1032
+ return () => { };
1033
+ let pending = '';
1034
+ stream.setEncoding('utf8');
1035
+ const onData = (chunk) => {
1036
+ pending += chunk;
1037
+ while (true) {
1038
+ const newline = pending.indexOf('\n');
1039
+ if (newline === -1) {
1040
+ if (byteLength(pending) > maxLineBytes) {
1041
+ onError(lineLimitError(maxLineBytes));
1042
+ pending = '';
1043
+ }
1044
+ return;
1045
+ }
1046
+ let line = pending.slice(0, newline);
1047
+ pending = pending.slice(newline + 1);
1048
+ if (line.endsWith('\r'))
1049
+ line = line.slice(0, -1);
1050
+ if (byteLength(line) > maxLineBytes)
1051
+ onError(lineLimitError(maxLineBytes));
1052
+ else
1053
+ onLine(line);
1054
+ }
1055
+ };
1056
+ const onEnd = () => {
1057
+ if (!pending)
1058
+ return;
1059
+ if (byteLength(pending) > maxLineBytes)
1060
+ onError(lineLimitError(maxLineBytes));
1061
+ else
1062
+ onLine(pending);
1063
+ };
1064
+ stream.on('data', onData);
1065
+ stream.on('error', onError);
1066
+ stream.on('end', onEnd);
1067
+ return () => {
1068
+ stream.removeListener('data', onData);
1069
+ stream.removeListener('error', onError);
1070
+ stream.removeListener('end', onEnd);
1071
+ };
1072
+ }
1073
+ function abortError(message) { return new Error(message, { cause: 'abort' }); }
1074
+ function timeoutError(timeoutMs) { return new Error(`CLI execution timed out after ${timeoutMs}ms`, { cause: 'timeout' }); }
1075
+ function outputLimitError(maxOutputBytes) { return new Error(`CLI output exceeded ${maxOutputBytes} bytes`, { cause: 'output-limit' }); }
1076
+ function lineLimitError(maxLineBytes) { return new Error(`CLI line exceeded ${maxLineBytes} bytes`, { cause: 'line-limit' }); }
1077
+ function terminateProcessTree(child, signal) {
1078
+ if (process.platform !== 'win32' && child.pid !== undefined && child.pid > 0) {
1079
+ try {
1080
+ process.kill(-child.pid, signal);
1081
+ return;
1082
+ }
1083
+ catch {
1084
+ // The group may already have exited; fall back to the direct child handle.
1085
+ }
1086
+ }
1087
+ try {
1088
+ child.kill(signal);
1089
+ }
1090
+ catch {
1091
+ // Teardown is best-effort after the process has already disappeared.
1092
+ }
1093
+ }
1094
+ class TextQueue {
1095
+ values = [];
1096
+ waiter;
1097
+ error;
1098
+ done = false;
1099
+ push(value) {
1100
+ if (this.done)
1101
+ return;
1102
+ this.values.push(value);
1103
+ const waiter = this.waiter;
1104
+ this.waiter = undefined;
1105
+ waiter?.();
1106
+ }
1107
+ close(error) {
1108
+ if (this.done)
1109
+ return;
1110
+ this.done = true;
1111
+ this.error = error;
1112
+ const waiter = this.waiter;
1113
+ this.waiter = undefined;
1114
+ waiter?.();
1115
+ }
1116
+ async *[Symbol.asyncIterator]() {
1117
+ while (true) {
1118
+ if (this.values.length)
1119
+ yield this.values.shift();
1120
+ else if (this.done) {
1121
+ if (this.error)
1122
+ throw this.error;
1123
+ return;
1124
+ }
1125
+ else {
1126
+ await new Promise(resolve => { this.waiter = resolve; });
1127
+ }
1128
+ }
1129
+ }
1130
+ }
1131
+ //# sourceMappingURL=process.js.map