@anthropic-ai/claude-agent-sdk 0.1.62 → 0.1.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/sdk.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // (c) Anthropic PBC. All rights reserved. Use is subject to the Legal Agreements outlined here: https://code.claude.com/docs/en/legal-and-compliance.
3
3
 
4
- // Version: 0.1.62
4
+ // Version: 0.1.65
5
5
 
6
6
  // Want to see the unminified source? We're hiring!
7
7
  // https://job-boards.greenhouse.io/anthropic/jobs/4816199008
@@ -6256,1448 +6256,1513 @@ import { createInterface } from "readline";
6256
6256
  // ../src/utils/fsOperations.ts
6257
6257
  import * as fs from "fs";
6258
6258
  import { stat as statPromise, open } from "fs/promises";
6259
- var NodeFsOperations = {
6260
- cwd() {
6261
- return process.cwd();
6262
- },
6263
- existsSync(fsPath) {
6264
- return fs.existsSync(fsPath);
6265
- },
6266
- async stat(fsPath) {
6267
- return statPromise(fsPath);
6268
- },
6269
- statSync(fsPath) {
6270
- return fs.statSync(fsPath);
6271
- },
6272
- readFileSync(fsPath, options) {
6273
- return fs.readFileSync(fsPath, { encoding: options.encoding });
6274
- },
6275
- readFileBytesSync(fsPath) {
6276
- return fs.readFileSync(fsPath);
6277
- },
6278
- readSync(fsPath, options) {
6279
- let fd = undefined;
6280
- try {
6281
- fd = fs.openSync(fsPath, "r");
6282
- const buffer = Buffer.alloc(options.length);
6283
- const bytesRead = fs.readSync(fd, buffer, 0, options.length, 0);
6284
- return { buffer, bytesRead };
6285
- } finally {
6286
- if (fd)
6287
- fs.closeSync(fd);
6288
- }
6289
- },
6290
- writeFileSync(fsPath, data, options) {
6291
- const fileExists = fs.existsSync(fsPath);
6292
- if (!options.flush) {
6293
- const writeOptions = {
6294
- encoding: options.encoding
6295
- };
6296
- if (!fileExists) {
6297
- writeOptions.mode = options.mode ?? 384;
6298
- } else if (options.mode !== undefined) {
6299
- writeOptions.mode = options.mode;
6300
- }
6301
- fs.writeFileSync(fsPath, data, writeOptions);
6302
- return;
6303
- }
6304
- let fd;
6305
- try {
6306
- const mode = !fileExists ? options.mode ?? 384 : options.mode;
6307
- fd = fs.openSync(fsPath, "w", mode);
6308
- fs.writeFileSync(fd, data, { encoding: options.encoding });
6309
- fs.fsyncSync(fd);
6310
- } finally {
6311
- if (fd) {
6312
- fs.closeSync(fd);
6313
- }
6314
- }
6315
- },
6316
- appendFileSync(path, data, options) {
6317
- if (!fs.existsSync(path)) {
6318
- const mode = options?.mode ?? 384;
6319
- const fd = fs.openSync(path, "a", mode);
6320
- try {
6321
- fs.appendFileSync(fd, data);
6322
- } finally {
6323
- fs.closeSync(fd);
6324
- }
6259
+
6260
+ // ../node_modules/lodash-es/_freeGlobal.js
6261
+ var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
6262
+ var _freeGlobal_default = freeGlobal;
6263
+
6264
+ // ../node_modules/lodash-es/_root.js
6265
+ var freeSelf = typeof self == "object" && self && self.Object === Object && self;
6266
+ var root = _freeGlobal_default || freeSelf || Function("return this")();
6267
+ var _root_default = root;
6268
+
6269
+ // ../node_modules/lodash-es/_Symbol.js
6270
+ var Symbol2 = _root_default.Symbol;
6271
+ var _Symbol_default = Symbol2;
6272
+
6273
+ // ../node_modules/lodash-es/_getRawTag.js
6274
+ var objectProto = Object.prototype;
6275
+ var hasOwnProperty = objectProto.hasOwnProperty;
6276
+ var nativeObjectToString = objectProto.toString;
6277
+ var symToStringTag = _Symbol_default ? _Symbol_default.toStringTag : undefined;
6278
+ function getRawTag(value) {
6279
+ var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
6280
+ try {
6281
+ value[symToStringTag] = undefined;
6282
+ var unmasked = true;
6283
+ } catch (e) {}
6284
+ var result = nativeObjectToString.call(value);
6285
+ if (unmasked) {
6286
+ if (isOwn) {
6287
+ value[symToStringTag] = tag;
6325
6288
  } else {
6326
- fs.appendFileSync(path, data);
6327
- }
6328
- },
6329
- copyFileSync(src, dest) {
6330
- fs.copyFileSync(src, dest);
6331
- },
6332
- unlinkSync(path) {
6333
- fs.unlinkSync(path);
6334
- },
6335
- renameSync(oldPath, newPath) {
6336
- fs.renameSync(oldPath, newPath);
6337
- },
6338
- linkSync(target, path) {
6339
- fs.linkSync(target, path);
6340
- },
6341
- symlinkSync(target, path) {
6342
- fs.symlinkSync(target, path);
6343
- },
6344
- readlinkSync(path) {
6345
- return fs.readlinkSync(path);
6346
- },
6347
- realpathSync(path) {
6348
- return fs.realpathSync(path);
6349
- },
6350
- mkdirSync(dirPath) {
6351
- if (!fs.existsSync(dirPath)) {
6352
- fs.mkdirSync(dirPath, { recursive: true, mode: 448 });
6289
+ delete value[symToStringTag];
6353
6290
  }
6354
- },
6355
- readdirSync(dirPath) {
6356
- return fs.readdirSync(dirPath, { withFileTypes: true });
6357
- },
6358
- readdirStringSync(dirPath) {
6359
- return fs.readdirSync(dirPath);
6360
- },
6361
- isDirEmptySync(dirPath) {
6362
- const files = this.readdirSync(dirPath);
6363
- return files.length === 0;
6364
- },
6365
- rmdirSync(dirPath) {
6366
- fs.rmdirSync(dirPath);
6367
- },
6368
- rmSync(path, options) {
6369
- fs.rmSync(path, options);
6370
- },
6371
- createWriteStream(path) {
6372
- return fs.createWriteStream(path);
6373
6291
  }
6374
- };
6375
- var activeFs = NodeFsOperations;
6376
- function getFsImplementation() {
6377
- return activeFs;
6292
+ return result;
6378
6293
  }
6294
+ var _getRawTag_default = getRawTag;
6379
6295
 
6380
- // ../src/entrypoints/agentSdkTypes.ts
6381
- var HOOK_EVENTS = [
6382
- "PreToolUse",
6383
- "PostToolUse",
6384
- "PostToolUseFailure",
6385
- "Notification",
6386
- "UserPromptSubmit",
6387
- "SessionStart",
6388
- "SessionEnd",
6389
- "Stop",
6390
- "SubagentStart",
6391
- "SubagentStop",
6392
- "PreCompact",
6393
- "PermissionRequest"
6394
- ];
6395
- var EXIT_REASONS = [
6396
- "clear",
6397
- "logout",
6398
- "prompt_input_exit",
6399
- "other",
6400
- "bypass_permissions_disabled"
6401
- ];
6402
- class AbortError extends Error {
6296
+ // ../node_modules/lodash-es/_objectToString.js
6297
+ var objectProto2 = Object.prototype;
6298
+ var nativeObjectToString2 = objectProto2.toString;
6299
+ function objectToString(value) {
6300
+ return nativeObjectToString2.call(value);
6403
6301
  }
6302
+ var _objectToString_default = objectToString;
6404
6303
 
6405
- // ../src/utils/bundledMode.ts
6406
- function isRunningWithBun() {
6407
- return process.versions.bun !== undefined;
6304
+ // ../node_modules/lodash-es/_baseGetTag.js
6305
+ var nullTag = "[object Null]";
6306
+ var undefinedTag = "[object Undefined]";
6307
+ var symToStringTag2 = _Symbol_default ? _Symbol_default.toStringTag : undefined;
6308
+ function baseGetTag(value) {
6309
+ if (value == null) {
6310
+ return value === undefined ? undefinedTag : nullTag;
6311
+ }
6312
+ return symToStringTag2 && symToStringTag2 in Object(value) ? _getRawTag_default(value) : _objectToString_default(value);
6408
6313
  }
6314
+ var _baseGetTag_default = baseGetTag;
6409
6315
 
6410
- // ../src/utils/sdkDebug.ts
6411
- import { randomUUID } from "crypto";
6412
- import { appendFileSync as appendFileSync2, existsSync as existsSync2, mkdirSync as mkdirSync2 } from "fs";
6413
- import { join as join2 } from "path";
6414
-
6415
- // ../src/utils/envUtils.ts
6416
- import { join } from "path";
6417
- import { homedir } from "os";
6418
- function getClaudeConfigHomeDir() {
6419
- return process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude");
6316
+ // ../node_modules/lodash-es/isObject.js
6317
+ function isObject(value) {
6318
+ var type = typeof value;
6319
+ return value != null && (type == "object" || type == "function");
6420
6320
  }
6421
- function isEnvTruthy(envVar) {
6422
- if (!envVar)
6321
+ var isObject_default = isObject;
6322
+
6323
+ // ../node_modules/lodash-es/isFunction.js
6324
+ var asyncTag = "[object AsyncFunction]";
6325
+ var funcTag = "[object Function]";
6326
+ var genTag = "[object GeneratorFunction]";
6327
+ var proxyTag = "[object Proxy]";
6328
+ function isFunction(value) {
6329
+ if (!isObject_default(value)) {
6423
6330
  return false;
6424
- if (typeof envVar === "boolean")
6425
- return envVar;
6426
- const normalizedValue = envVar.toLowerCase().trim();
6427
- return ["1", "true", "yes", "on"].includes(normalizedValue);
6331
+ }
6332
+ var tag = _baseGetTag_default(value);
6333
+ return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
6428
6334
  }
6335
+ var isFunction_default = isFunction;
6429
6336
 
6430
- // ../src/utils/sdkDebug.ts
6431
- var debugFilePath = null;
6432
- var initialized = false;
6433
- function getOrCreateDebugFile() {
6434
- if (initialized) {
6435
- return debugFilePath;
6436
- }
6437
- initialized = true;
6438
- if (!process.env.DEBUG_CLAUDE_AGENT_SDK) {
6439
- return null;
6440
- }
6441
- const debugDir = join2(getClaudeConfigHomeDir(), "debug");
6442
- debugFilePath = join2(debugDir, `sdk-${randomUUID()}.txt`);
6443
- if (!existsSync2(debugDir)) {
6444
- mkdirSync2(debugDir, { recursive: true });
6445
- }
6446
- process.stderr.write(`SDK debug logs: ${debugFilePath}
6447
- `);
6448
- return debugFilePath;
6337
+ // ../node_modules/lodash-es/_coreJsData.js
6338
+ var coreJsData = _root_default["__core-js_shared__"];
6339
+ var _coreJsData_default = coreJsData;
6340
+
6341
+ // ../node_modules/lodash-es/_isMasked.js
6342
+ var maskSrcKey = function() {
6343
+ var uid = /[^.]+$/.exec(_coreJsData_default && _coreJsData_default.keys && _coreJsData_default.keys.IE_PROTO || "");
6344
+ return uid ? "Symbol(src)_1." + uid : "";
6345
+ }();
6346
+ function isMasked(func) {
6347
+ return !!maskSrcKey && maskSrcKey in func;
6449
6348
  }
6450
- function logForSdkDebugging(message) {
6451
- const path = getOrCreateDebugFile();
6452
- if (!path) {
6453
- return;
6349
+ var _isMasked_default = isMasked;
6350
+
6351
+ // ../node_modules/lodash-es/_toSource.js
6352
+ var funcProto = Function.prototype;
6353
+ var funcToString = funcProto.toString;
6354
+ function toSource(func) {
6355
+ if (func != null) {
6356
+ try {
6357
+ return funcToString.call(func);
6358
+ } catch (e) {}
6359
+ try {
6360
+ return func + "";
6361
+ } catch (e) {}
6454
6362
  }
6455
- const timestamp = new Date().toISOString();
6456
- const output = `${timestamp} ${message}
6457
- `;
6458
- appendFileSync2(path, output);
6363
+ return "";
6459
6364
  }
6365
+ var _toSource_default = toSource;
6460
6366
 
6461
- // ../src/transport/sandboxUtils.ts
6462
- function mergeSandboxIntoExtraArgs(extraArgs, sandbox) {
6463
- const effectiveExtraArgs = { ...extraArgs };
6464
- if (sandbox) {
6465
- let settingsObj = { sandbox };
6466
- if (effectiveExtraArgs.settings) {
6467
- try {
6468
- const existingSettings = JSON.parse(effectiveExtraArgs.settings);
6469
- settingsObj = { ...existingSettings, sandbox };
6470
- } catch {}
6471
- }
6472
- effectiveExtraArgs.settings = JSON.stringify(settingsObj);
6367
+ // ../node_modules/lodash-es/_baseIsNative.js
6368
+ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
6369
+ var reIsHostCtor = /^\[object .+?Constructor\]$/;
6370
+ var funcProto2 = Function.prototype;
6371
+ var objectProto3 = Object.prototype;
6372
+ var funcToString2 = funcProto2.toString;
6373
+ var hasOwnProperty2 = objectProto3.hasOwnProperty;
6374
+ var reIsNative = RegExp("^" + funcToString2.call(hasOwnProperty2).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$");
6375
+ function baseIsNative(value) {
6376
+ if (!isObject_default(value) || _isMasked_default(value)) {
6377
+ return false;
6473
6378
  }
6474
- return effectiveExtraArgs;
6379
+ var pattern = isFunction_default(value) ? reIsNative : reIsHostCtor;
6380
+ return pattern.test(_toSource_default(value));
6475
6381
  }
6382
+ var _baseIsNative_default = baseIsNative;
6476
6383
 
6477
- // ../src/transport/ProcessTransport.ts
6478
- class ProcessTransport {
6479
- options;
6480
- child;
6481
- childStdin;
6482
- childStdout;
6483
- ready = false;
6484
- abortController;
6485
- exitError;
6486
- exitListeners = [];
6487
- processExitHandler;
6488
- abortHandler;
6489
- constructor(options) {
6490
- this.options = options;
6491
- this.abortController = options.abortController || createAbortController();
6492
- this.initialize();
6493
- }
6494
- initialize() {
6495
- try {
6496
- const {
6497
- additionalDirectories = [],
6498
- betas,
6499
- cwd,
6500
- executable = isRunningWithBun() ? "bun" : "node",
6501
- executableArgs = [],
6502
- extraArgs = {},
6503
- pathToClaudeCodeExecutable,
6504
- env = { ...process.env },
6505
- stderr,
6506
- maxThinkingTokens,
6507
- maxTurns,
6508
- maxBudgetUsd,
6509
- model,
6510
- fallbackModel,
6511
- jsonSchema,
6512
- permissionMode,
6513
- allowDangerouslySkipPermissions,
6514
- permissionPromptToolName,
6515
- continueConversation,
6516
- resume,
6517
- settingSources,
6518
- allowedTools = [],
6519
- disallowedTools = [],
6520
- mcpServers,
6521
- strictMcpConfig,
6522
- canUseTool,
6523
- includePartialMessages,
6524
- plugins,
6525
- sandbox
6526
- } = this.options;
6527
- const args = [
6528
- "--output-format",
6529
- "stream-json",
6530
- "--verbose",
6531
- "--input-format",
6532
- "stream-json"
6533
- ];
6534
- if (maxThinkingTokens !== undefined) {
6535
- args.push("--max-thinking-tokens", maxThinkingTokens.toString());
6536
- }
6537
- if (maxTurns)
6538
- args.push("--max-turns", maxTurns.toString());
6539
- if (maxBudgetUsd !== undefined) {
6540
- args.push("--max-budget-usd", maxBudgetUsd.toString());
6541
- }
6542
- if (model)
6543
- args.push("--model", model);
6544
- if (betas && betas.length > 0) {
6545
- args.push("--betas", betas.join(","));
6546
- }
6547
- if (jsonSchema) {
6548
- args.push("--json-schema", JSON.stringify(jsonSchema));
6549
- }
6550
- if (env.DEBUG_CLAUDE_AGENT_SDK) {
6551
- args.push("--debug-to-stderr");
6552
- }
6553
- if (canUseTool) {
6554
- if (permissionPromptToolName) {
6555
- throw new Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");
6556
- }
6557
- args.push("--permission-prompt-tool", "stdio");
6558
- } else if (permissionPromptToolName) {
6559
- args.push("--permission-prompt-tool", permissionPromptToolName);
6560
- }
6561
- if (continueConversation)
6562
- args.push("--continue");
6563
- if (resume)
6564
- args.push("--resume", resume);
6565
- if (allowedTools.length > 0) {
6566
- args.push("--allowedTools", allowedTools.join(","));
6567
- }
6568
- if (disallowedTools.length > 0) {
6569
- args.push("--disallowedTools", disallowedTools.join(","));
6570
- }
6571
- const { tools } = this.options;
6572
- if (tools !== undefined) {
6573
- if (Array.isArray(tools)) {
6574
- if (tools.length === 0) {
6575
- args.push("--tools", "");
6576
- } else {
6577
- args.push("--tools", tools.join(","));
6578
- }
6579
- } else {
6580
- args.push("--tools", "default");
6581
- }
6582
- }
6583
- if (mcpServers && Object.keys(mcpServers).length > 0) {
6584
- args.push("--mcp-config", JSON.stringify({ mcpServers }));
6585
- }
6586
- if (settingSources) {
6587
- args.push("--setting-sources", settingSources.join(","));
6588
- }
6589
- if (strictMcpConfig) {
6590
- args.push("--strict-mcp-config");
6591
- }
6592
- if (permissionMode) {
6593
- args.push("--permission-mode", permissionMode);
6594
- }
6595
- if (allowDangerouslySkipPermissions) {
6596
- args.push("--allow-dangerously-skip-permissions");
6597
- }
6598
- if (fallbackModel) {
6599
- if (model && fallbackModel === model) {
6600
- throw new Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option.");
6601
- }
6602
- args.push("--fallback-model", fallbackModel);
6603
- }
6604
- if (includePartialMessages) {
6605
- args.push("--include-partial-messages");
6606
- }
6607
- for (const dir of additionalDirectories) {
6608
- args.push("--add-dir", dir);
6609
- }
6610
- if (plugins && plugins.length > 0) {
6611
- for (const plugin of plugins) {
6612
- if (plugin.type === "local") {
6613
- args.push("--plugin-dir", plugin.path);
6614
- } else {
6615
- throw new Error(`Unsupported plugin type: ${plugin.type}`);
6616
- }
6617
- }
6618
- }
6619
- if (this.options.forkSession) {
6620
- args.push("--fork-session");
6621
- }
6622
- if (this.options.resumeSessionAt) {
6623
- args.push("--resume-session-at", this.options.resumeSessionAt);
6624
- }
6625
- const effectiveExtraArgs = mergeSandboxIntoExtraArgs(extraArgs ?? {}, sandbox);
6626
- for (const [flag, value] of Object.entries(effectiveExtraArgs)) {
6627
- if (value === null) {
6628
- args.push(`--${flag}`);
6629
- } else {
6630
- args.push(`--${flag}`, value);
6631
- }
6632
- }
6633
- if (!env.CLAUDE_CODE_ENTRYPOINT) {
6634
- env.CLAUDE_CODE_ENTRYPOINT = "sdk-ts";
6635
- }
6636
- delete env.NODE_OPTIONS;
6637
- if (env.DEBUG_CLAUDE_AGENT_SDK) {
6638
- env.DEBUG = "1";
6639
- } else {
6640
- delete env.DEBUG;
6641
- }
6642
- const fs2 = getFsImplementation();
6643
- if (!fs2.existsSync(pathToClaudeCodeExecutable)) {
6644
- const errorMessage = isNativeBinary(pathToClaudeCodeExecutable) ? `Claude Code native binary not found at ${pathToClaudeCodeExecutable}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.` : `Claude Code executable not found at ${pathToClaudeCodeExecutable}. Is options.pathToClaudeCodeExecutable set?`;
6645
- throw new ReferenceError(errorMessage);
6646
- }
6647
- const isNative = isNativeBinary(pathToClaudeCodeExecutable);
6648
- const spawnCommand = isNative ? pathToClaudeCodeExecutable : executable;
6649
- const spawnArgs = isNative ? [...executableArgs, ...args] : [...executableArgs, pathToClaudeCodeExecutable, ...args];
6650
- const spawnMessage = isNative ? `Spawning Claude Code native binary: ${spawnCommand} ${spawnArgs.join(" ")}` : `Spawning Claude Code process: ${spawnCommand} ${spawnArgs.join(" ")}`;
6651
- logForSdkDebugging(spawnMessage);
6652
- if (stderr) {
6653
- stderr(spawnMessage);
6654
- }
6655
- const stderrMode = env.DEBUG_CLAUDE_AGENT_SDK || stderr ? "pipe" : "ignore";
6656
- this.child = spawn(spawnCommand, spawnArgs, {
6657
- cwd,
6658
- stdio: ["pipe", "pipe", stderrMode],
6659
- signal: this.abortController.signal,
6660
- env
6661
- });
6662
- this.childStdin = this.child.stdin;
6663
- this.childStdout = this.child.stdout;
6664
- if (env.DEBUG_CLAUDE_AGENT_SDK || stderr) {
6665
- this.child.stderr.on("data", (data) => {
6666
- const message = data.toString();
6667
- logForSdkDebugging(message);
6668
- if (stderr) {
6669
- stderr(message);
6670
- }
6671
- });
6672
- }
6673
- const cleanup = () => {
6674
- if (this.child && !this.child.killed) {
6675
- this.child.kill("SIGTERM");
6676
- }
6677
- };
6678
- this.processExitHandler = cleanup;
6679
- this.abortHandler = cleanup;
6680
- process.on("exit", this.processExitHandler);
6681
- this.abortController.signal.addEventListener("abort", this.abortHandler);
6682
- this.child.on("error", (error) => {
6683
- this.ready = false;
6684
- if (this.abortController.signal.aborted) {
6685
- this.exitError = new AbortError("Claude Code process aborted by user");
6686
- } else {
6687
- this.exitError = new Error(`Failed to spawn Claude Code process: ${error.message}`);
6688
- logForSdkDebugging(this.exitError.message);
6689
- }
6690
- });
6691
- this.child.on("close", (code, signal) => {
6692
- this.ready = false;
6693
- if (this.abortController.signal.aborted) {
6694
- this.exitError = new AbortError("Claude Code process aborted by user");
6695
- } else {
6696
- const error = this.getProcessExitError(code, signal);
6697
- if (error) {
6698
- this.exitError = error;
6699
- logForSdkDebugging(error.message);
6700
- }
6701
- }
6702
- });
6703
- this.ready = true;
6704
- } catch (error) {
6705
- this.ready = false;
6706
- throw error;
6707
- }
6708
- }
6709
- getProcessExitError(code, signal) {
6710
- if (code !== 0 && code !== null) {
6711
- return new Error(`Claude Code process exited with code ${code}`);
6712
- } else if (signal) {
6713
- return new Error(`Claude Code process terminated by signal ${signal}`);
6714
- }
6715
- return;
6716
- }
6717
- write(data) {
6718
- if (this.abortController.signal.aborted) {
6719
- throw new AbortError("Operation aborted");
6720
- }
6721
- if (!this.ready || !this.childStdin) {
6722
- throw new Error("ProcessTransport is not ready for writing");
6723
- }
6724
- if (this.child?.killed || this.child?.exitCode !== null) {
6725
- throw new Error("Cannot write to terminated process");
6726
- }
6727
- if (this.exitError) {
6728
- throw new Error(`Cannot write to process that exited with error: ${this.exitError.message}`);
6729
- }
6730
- logForSdkDebugging(`[ProcessTransport] Writing to stdin: ${data.substring(0, 100)}`);
6731
- try {
6732
- const written = this.childStdin.write(data);
6733
- if (!written) {
6734
- logForSdkDebugging("[ProcessTransport] Write buffer full, data queued");
6735
- }
6736
- } catch (error) {
6737
- this.ready = false;
6738
- throw new Error(`Failed to write to process stdin: ${error.message}`);
6739
- }
6740
- }
6741
- close() {
6742
- if (this.childStdin) {
6743
- this.childStdin.end();
6744
- this.childStdin = undefined;
6745
- }
6746
- if (this.processExitHandler) {
6747
- process.off("exit", this.processExitHandler);
6748
- this.processExitHandler = undefined;
6749
- }
6750
- if (this.abortHandler) {
6751
- this.abortController.signal.removeEventListener("abort", this.abortHandler);
6752
- this.abortHandler = undefined;
6753
- }
6754
- for (const { handler } of this.exitListeners) {
6755
- this.child?.off("exit", handler);
6756
- }
6757
- this.exitListeners = [];
6758
- if (this.child && !this.child.killed) {
6759
- this.child.kill("SIGTERM");
6760
- setTimeout(() => {
6761
- if (this.child && !this.child.killed) {
6762
- this.child.kill("SIGKILL");
6763
- }
6764
- }, 5000);
6765
- }
6766
- this.ready = false;
6767
- }
6768
- isReady() {
6769
- return this.ready;
6770
- }
6771
- async* readMessages() {
6772
- if (!this.childStdout) {
6773
- throw new Error("ProcessTransport output stream not available");
6774
- }
6775
- const rl = createInterface({ input: this.childStdout });
6776
- try {
6777
- for await (const line of rl) {
6778
- if (line.trim()) {
6779
- const message = JSON.parse(line);
6780
- yield message;
6781
- }
6782
- }
6783
- await this.waitForExit();
6784
- } catch (error) {
6785
- throw error;
6786
- } finally {
6787
- rl.close();
6788
- }
6789
- }
6790
- endInput() {
6791
- if (this.childStdin) {
6792
- this.childStdin.end();
6793
- }
6794
- }
6795
- getInputStream() {
6796
- return this.childStdin;
6797
- }
6798
- onExit(callback) {
6799
- if (!this.child)
6800
- return () => {};
6801
- const handler = (code, signal) => {
6802
- const error = this.getProcessExitError(code, signal);
6803
- callback(error);
6804
- };
6805
- this.child.on("exit", handler);
6806
- this.exitListeners.push({ callback, handler });
6807
- return () => {
6808
- if (this.child) {
6809
- this.child.off("exit", handler);
6810
- }
6811
- const index = this.exitListeners.findIndex((l) => l.handler === handler);
6812
- if (index !== -1) {
6813
- this.exitListeners.splice(index, 1);
6814
- }
6815
- };
6384
+ // ../node_modules/lodash-es/_getValue.js
6385
+ function getValue(object, key) {
6386
+ return object == null ? undefined : object[key];
6387
+ }
6388
+ var _getValue_default = getValue;
6389
+
6390
+ // ../node_modules/lodash-es/_getNative.js
6391
+ function getNative(object, key) {
6392
+ var value = _getValue_default(object, key);
6393
+ return _baseIsNative_default(value) ? value : undefined;
6394
+ }
6395
+ var _getNative_default = getNative;
6396
+
6397
+ // ../node_modules/lodash-es/_nativeCreate.js
6398
+ var nativeCreate = _getNative_default(Object, "create");
6399
+ var _nativeCreate_default = nativeCreate;
6400
+
6401
+ // ../node_modules/lodash-es/_hashClear.js
6402
+ function hashClear() {
6403
+ this.__data__ = _nativeCreate_default ? _nativeCreate_default(null) : {};
6404
+ this.size = 0;
6405
+ }
6406
+ var _hashClear_default = hashClear;
6407
+
6408
+ // ../node_modules/lodash-es/_hashDelete.js
6409
+ function hashDelete(key) {
6410
+ var result = this.has(key) && delete this.__data__[key];
6411
+ this.size -= result ? 1 : 0;
6412
+ return result;
6413
+ }
6414
+ var _hashDelete_default = hashDelete;
6415
+
6416
+ // ../node_modules/lodash-es/_hashGet.js
6417
+ var HASH_UNDEFINED = "__lodash_hash_undefined__";
6418
+ var objectProto4 = Object.prototype;
6419
+ var hasOwnProperty3 = objectProto4.hasOwnProperty;
6420
+ function hashGet(key) {
6421
+ var data = this.__data__;
6422
+ if (_nativeCreate_default) {
6423
+ var result = data[key];
6424
+ return result === HASH_UNDEFINED ? undefined : result;
6816
6425
  }
6817
- async waitForExit() {
6818
- if (!this.child) {
6819
- if (this.exitError) {
6820
- throw this.exitError;
6821
- }
6822
- return;
6823
- }
6824
- if (this.child.exitCode !== null || this.child.killed) {
6825
- if (this.exitError) {
6826
- throw this.exitError;
6827
- }
6828
- return;
6829
- }
6830
- return new Promise((resolve, reject) => {
6831
- const exitHandler = (code, signal) => {
6832
- if (this.abortController.signal.aborted) {
6833
- reject(new AbortError("Operation aborted"));
6834
- return;
6835
- }
6836
- const error = this.getProcessExitError(code, signal);
6837
- if (error) {
6838
- reject(error);
6839
- } else {
6840
- resolve();
6841
- }
6842
- };
6843
- this.child.once("exit", exitHandler);
6844
- const errorHandler = (error) => {
6845
- this.child.off("exit", exitHandler);
6846
- reject(error);
6847
- };
6848
- this.child.once("error", errorHandler);
6849
- this.child.once("exit", () => {
6850
- this.child.off("error", errorHandler);
6851
- });
6852
- });
6426
+ return hasOwnProperty3.call(data, key) ? data[key] : undefined;
6427
+ }
6428
+ var _hashGet_default = hashGet;
6429
+
6430
+ // ../node_modules/lodash-es/_hashHas.js
6431
+ var objectProto5 = Object.prototype;
6432
+ var hasOwnProperty4 = objectProto5.hasOwnProperty;
6433
+ function hashHas(key) {
6434
+ var data = this.__data__;
6435
+ return _nativeCreate_default ? data[key] !== undefined : hasOwnProperty4.call(data, key);
6436
+ }
6437
+ var _hashHas_default = hashHas;
6438
+
6439
+ // ../node_modules/lodash-es/_hashSet.js
6440
+ var HASH_UNDEFINED2 = "__lodash_hash_undefined__";
6441
+ function hashSet(key, value) {
6442
+ var data = this.__data__;
6443
+ this.size += this.has(key) ? 0 : 1;
6444
+ data[key] = _nativeCreate_default && value === undefined ? HASH_UNDEFINED2 : value;
6445
+ return this;
6446
+ }
6447
+ var _hashSet_default = hashSet;
6448
+
6449
+ // ../node_modules/lodash-es/_Hash.js
6450
+ function Hash(entries) {
6451
+ var index = -1, length = entries == null ? 0 : entries.length;
6452
+ this.clear();
6453
+ while (++index < length) {
6454
+ var entry = entries[index];
6455
+ this.set(entry[0], entry[1]);
6853
6456
  }
6854
6457
  }
6855
- function isNativeBinary(executablePath) {
6856
- const jsExtensions = [".js", ".mjs", ".tsx", ".ts", ".jsx"];
6857
- return !jsExtensions.some((ext) => executablePath.endsWith(ext));
6458
+ Hash.prototype.clear = _hashClear_default;
6459
+ Hash.prototype["delete"] = _hashDelete_default;
6460
+ Hash.prototype.get = _hashGet_default;
6461
+ Hash.prototype.has = _hashHas_default;
6462
+ Hash.prototype.set = _hashSet_default;
6463
+ var _Hash_default = Hash;
6464
+
6465
+ // ../node_modules/lodash-es/_listCacheClear.js
6466
+ function listCacheClear() {
6467
+ this.__data__ = [];
6468
+ this.size = 0;
6858
6469
  }
6470
+ var _listCacheClear_default = listCacheClear;
6859
6471
 
6860
- // ../src/utils/stream.ts
6861
- class Stream {
6862
- returned;
6863
- queue = [];
6864
- readResolve;
6865
- readReject;
6866
- isDone = false;
6867
- hasError;
6868
- started = false;
6869
- constructor(returned) {
6870
- this.returned = returned;
6871
- }
6872
- [Symbol.asyncIterator]() {
6873
- if (this.started) {
6874
- throw new Error("Stream can only be iterated once");
6875
- }
6876
- this.started = true;
6877
- return this;
6878
- }
6879
- next() {
6880
- if (this.queue.length > 0) {
6881
- return Promise.resolve({
6882
- done: false,
6883
- value: this.queue.shift()
6884
- });
6885
- }
6886
- if (this.isDone) {
6887
- return Promise.resolve({ done: true, value: undefined });
6888
- }
6889
- if (this.hasError) {
6890
- return Promise.reject(this.hasError);
6891
- }
6892
- return new Promise((resolve, reject) => {
6893
- this.readResolve = resolve;
6894
- this.readReject = reject;
6895
- });
6896
- }
6897
- enqueue(value) {
6898
- if (this.readResolve) {
6899
- const resolve = this.readResolve;
6900
- this.readResolve = undefined;
6901
- this.readReject = undefined;
6902
- resolve({ done: false, value });
6903
- } else {
6904
- this.queue.push(value);
6905
- }
6906
- }
6907
- done() {
6908
- this.isDone = true;
6909
- if (this.readResolve) {
6910
- const resolve = this.readResolve;
6911
- this.readResolve = undefined;
6912
- this.readReject = undefined;
6913
- resolve({ done: true, value: undefined });
6472
+ // ../node_modules/lodash-es/eq.js
6473
+ function eq(value, other) {
6474
+ return value === other || value !== value && other !== other;
6475
+ }
6476
+ var eq_default = eq;
6477
+
6478
+ // ../node_modules/lodash-es/_assocIndexOf.js
6479
+ function assocIndexOf(array, key) {
6480
+ var length = array.length;
6481
+ while (length--) {
6482
+ if (eq_default(array[length][0], key)) {
6483
+ return length;
6914
6484
  }
6915
6485
  }
6916
- error(error) {
6917
- this.hasError = error;
6918
- if (this.readReject) {
6919
- const reject = this.readReject;
6920
- this.readResolve = undefined;
6921
- this.readReject = undefined;
6922
- reject(error);
6923
- }
6486
+ return -1;
6487
+ }
6488
+ var _assocIndexOf_default = assocIndexOf;
6489
+
6490
+ // ../node_modules/lodash-es/_listCacheDelete.js
6491
+ var arrayProto = Array.prototype;
6492
+ var splice = arrayProto.splice;
6493
+ function listCacheDelete(key) {
6494
+ var data = this.__data__, index = _assocIndexOf_default(data, key);
6495
+ if (index < 0) {
6496
+ return false;
6924
6497
  }
6925
- return() {
6926
- this.isDone = true;
6927
- if (this.returned) {
6928
- this.returned();
6929
- }
6930
- return Promise.resolve({ done: true, value: undefined });
6498
+ var lastIndex = data.length - 1;
6499
+ if (index == lastIndex) {
6500
+ data.pop();
6501
+ } else {
6502
+ splice.call(data, index, 1);
6931
6503
  }
6504
+ --this.size;
6505
+ return true;
6932
6506
  }
6507
+ var _listCacheDelete_default = listCacheDelete;
6933
6508
 
6934
- // ../src/services/mcp/SdkControlTransport.ts
6935
- class SdkControlServerTransport {
6936
- sendMcpMessage;
6937
- isClosed = false;
6938
- constructor(sendMcpMessage) {
6939
- this.sendMcpMessage = sendMcpMessage;
6940
- }
6941
- onclose;
6942
- onerror;
6943
- onmessage;
6944
- async start() {}
6945
- async send(message) {
6946
- if (this.isClosed) {
6947
- throw new Error("Transport is closed");
6948
- }
6949
- this.sendMcpMessage(message);
6509
+ // ../node_modules/lodash-es/_listCacheGet.js
6510
+ function listCacheGet(key) {
6511
+ var data = this.__data__, index = _assocIndexOf_default(data, key);
6512
+ return index < 0 ? undefined : data[index][1];
6513
+ }
6514
+ var _listCacheGet_default = listCacheGet;
6515
+
6516
+ // ../node_modules/lodash-es/_listCacheHas.js
6517
+ function listCacheHas(key) {
6518
+ return _assocIndexOf_default(this.__data__, key) > -1;
6519
+ }
6520
+ var _listCacheHas_default = listCacheHas;
6521
+
6522
+ // ../node_modules/lodash-es/_listCacheSet.js
6523
+ function listCacheSet(key, value) {
6524
+ var data = this.__data__, index = _assocIndexOf_default(data, key);
6525
+ if (index < 0) {
6526
+ ++this.size;
6527
+ data.push([key, value]);
6528
+ } else {
6529
+ data[index][1] = value;
6950
6530
  }
6951
- async close() {
6952
- if (this.isClosed) {
6953
- return;
6954
- }
6955
- this.isClosed = true;
6956
- this.onclose?.();
6531
+ return this;
6532
+ }
6533
+ var _listCacheSet_default = listCacheSet;
6534
+
6535
+ // ../node_modules/lodash-es/_ListCache.js
6536
+ function ListCache(entries) {
6537
+ var index = -1, length = entries == null ? 0 : entries.length;
6538
+ this.clear();
6539
+ while (++index < length) {
6540
+ var entry = entries[index];
6541
+ this.set(entry[0], entry[1]);
6957
6542
  }
6958
6543
  }
6544
+ ListCache.prototype.clear = _listCacheClear_default;
6545
+ ListCache.prototype["delete"] = _listCacheDelete_default;
6546
+ ListCache.prototype.get = _listCacheGet_default;
6547
+ ListCache.prototype.has = _listCacheHas_default;
6548
+ ListCache.prototype.set = _listCacheSet_default;
6549
+ var _ListCache_default = ListCache;
6959
6550
 
6960
- // ../node_modules/lodash-es/_freeGlobal.js
6961
- var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
6962
- var _freeGlobal_default = freeGlobal;
6551
+ // ../node_modules/lodash-es/_Map.js
6552
+ var Map2 = _getNative_default(_root_default, "Map");
6553
+ var _Map_default = Map2;
6963
6554
 
6964
- // ../node_modules/lodash-es/_root.js
6965
- var freeSelf = typeof self == "object" && self && self.Object === Object && self;
6966
- var root = _freeGlobal_default || freeSelf || Function("return this")();
6967
- var _root_default = root;
6555
+ // ../node_modules/lodash-es/_mapCacheClear.js
6556
+ function mapCacheClear() {
6557
+ this.size = 0;
6558
+ this.__data__ = {
6559
+ hash: new _Hash_default,
6560
+ map: new (_Map_default || _ListCache_default),
6561
+ string: new _Hash_default
6562
+ };
6563
+ }
6564
+ var _mapCacheClear_default = mapCacheClear;
6968
6565
 
6969
- // ../node_modules/lodash-es/_Symbol.js
6970
- var Symbol2 = _root_default.Symbol;
6971
- var _Symbol_default = Symbol2;
6566
+ // ../node_modules/lodash-es/_isKeyable.js
6567
+ function isKeyable(value) {
6568
+ var type = typeof value;
6569
+ return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
6570
+ }
6571
+ var _isKeyable_default = isKeyable;
6972
6572
 
6973
- // ../node_modules/lodash-es/_getRawTag.js
6974
- var objectProto = Object.prototype;
6975
- var hasOwnProperty = objectProto.hasOwnProperty;
6976
- var nativeObjectToString = objectProto.toString;
6977
- var symToStringTag = _Symbol_default ? _Symbol_default.toStringTag : undefined;
6978
- function getRawTag(value) {
6979
- var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
6980
- try {
6981
- value[symToStringTag] = undefined;
6982
- var unmasked = true;
6983
- } catch (e) {}
6984
- var result = nativeObjectToString.call(value);
6985
- if (unmasked) {
6986
- if (isOwn) {
6987
- value[symToStringTag] = tag;
6988
- } else {
6989
- delete value[symToStringTag];
6990
- }
6991
- }
6992
- return result;
6573
+ // ../node_modules/lodash-es/_getMapData.js
6574
+ function getMapData(map, key) {
6575
+ var data = map.__data__;
6576
+ return _isKeyable_default(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
6993
6577
  }
6994
- var _getRawTag_default = getRawTag;
6578
+ var _getMapData_default = getMapData;
6995
6579
 
6996
- // ../node_modules/lodash-es/_objectToString.js
6997
- var objectProto2 = Object.prototype;
6998
- var nativeObjectToString2 = objectProto2.toString;
6999
- function objectToString(value) {
7000
- return nativeObjectToString2.call(value);
6580
+ // ../node_modules/lodash-es/_mapCacheDelete.js
6581
+ function mapCacheDelete(key) {
6582
+ var result = _getMapData_default(this, key)["delete"](key);
6583
+ this.size -= result ? 1 : 0;
6584
+ return result;
7001
6585
  }
7002
- var _objectToString_default = objectToString;
6586
+ var _mapCacheDelete_default = mapCacheDelete;
7003
6587
 
7004
- // ../node_modules/lodash-es/_baseGetTag.js
7005
- var nullTag = "[object Null]";
7006
- var undefinedTag = "[object Undefined]";
7007
- var symToStringTag2 = _Symbol_default ? _Symbol_default.toStringTag : undefined;
7008
- function baseGetTag(value) {
7009
- if (value == null) {
7010
- return value === undefined ? undefinedTag : nullTag;
7011
- }
7012
- return symToStringTag2 && symToStringTag2 in Object(value) ? _getRawTag_default(value) : _objectToString_default(value);
6588
+ // ../node_modules/lodash-es/_mapCacheGet.js
6589
+ function mapCacheGet(key) {
6590
+ return _getMapData_default(this, key).get(key);
7013
6591
  }
7014
- var _baseGetTag_default = baseGetTag;
6592
+ var _mapCacheGet_default = mapCacheGet;
7015
6593
 
7016
- // ../node_modules/lodash-es/isObject.js
7017
- function isObject(value) {
7018
- var type = typeof value;
7019
- return value != null && (type == "object" || type == "function");
6594
+ // ../node_modules/lodash-es/_mapCacheHas.js
6595
+ function mapCacheHas(key) {
6596
+ return _getMapData_default(this, key).has(key);
7020
6597
  }
7021
- var isObject_default = isObject;
6598
+ var _mapCacheHas_default = mapCacheHas;
7022
6599
 
7023
- // ../node_modules/lodash-es/isFunction.js
7024
- var asyncTag = "[object AsyncFunction]";
7025
- var funcTag = "[object Function]";
7026
- var genTag = "[object GeneratorFunction]";
7027
- var proxyTag = "[object Proxy]";
7028
- function isFunction(value) {
7029
- if (!isObject_default(value)) {
7030
- return false;
7031
- }
7032
- var tag = _baseGetTag_default(value);
7033
- return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
6600
+ // ../node_modules/lodash-es/_mapCacheSet.js
6601
+ function mapCacheSet(key, value) {
6602
+ var data = _getMapData_default(this, key), size = data.size;
6603
+ data.set(key, value);
6604
+ this.size += data.size == size ? 0 : 1;
6605
+ return this;
7034
6606
  }
7035
- var isFunction_default = isFunction;
6607
+ var _mapCacheSet_default = mapCacheSet;
7036
6608
 
7037
- // ../node_modules/lodash-es/_coreJsData.js
7038
- var coreJsData = _root_default["__core-js_shared__"];
7039
- var _coreJsData_default = coreJsData;
6609
+ // ../node_modules/lodash-es/_MapCache.js
6610
+ function MapCache(entries) {
6611
+ var index = -1, length = entries == null ? 0 : entries.length;
6612
+ this.clear();
6613
+ while (++index < length) {
6614
+ var entry = entries[index];
6615
+ this.set(entry[0], entry[1]);
6616
+ }
6617
+ }
6618
+ MapCache.prototype.clear = _mapCacheClear_default;
6619
+ MapCache.prototype["delete"] = _mapCacheDelete_default;
6620
+ MapCache.prototype.get = _mapCacheGet_default;
6621
+ MapCache.prototype.has = _mapCacheHas_default;
6622
+ MapCache.prototype.set = _mapCacheSet_default;
6623
+ var _MapCache_default = MapCache;
7040
6624
 
7041
- // ../node_modules/lodash-es/_isMasked.js
7042
- var maskSrcKey = function() {
7043
- var uid = /[^.]+$/.exec(_coreJsData_default && _coreJsData_default.keys && _coreJsData_default.keys.IE_PROTO || "");
7044
- return uid ? "Symbol(src)_1." + uid : "";
7045
- }();
7046
- function isMasked(func) {
7047
- return !!maskSrcKey && maskSrcKey in func;
6625
+ // ../node_modules/lodash-es/memoize.js
6626
+ var FUNC_ERROR_TEXT = "Expected a function";
6627
+ function memoize(func, resolver) {
6628
+ if (typeof func != "function" || resolver != null && typeof resolver != "function") {
6629
+ throw new TypeError(FUNC_ERROR_TEXT);
6630
+ }
6631
+ var memoized = function() {
6632
+ var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache;
6633
+ if (cache.has(key)) {
6634
+ return cache.get(key);
6635
+ }
6636
+ var result = func.apply(this, args);
6637
+ memoized.cache = cache.set(key, result) || cache;
6638
+ return result;
6639
+ };
6640
+ memoized.cache = new (memoize.Cache || _MapCache_default);
6641
+ return memoized;
7048
6642
  }
7049
- var _isMasked_default = isMasked;
6643
+ memoize.Cache = _MapCache_default;
6644
+ var memoize_default = memoize;
7050
6645
 
7051
- // ../node_modules/lodash-es/_toSource.js
7052
- var funcProto = Function.prototype;
7053
- var funcToString = funcProto.toString;
7054
- function toSource(func) {
7055
- if (func != null) {
7056
- try {
7057
- return funcToString.call(func);
7058
- } catch (e) {}
7059
- try {
7060
- return func + "";
7061
- } catch (e) {}
6646
+ // ../src/utils/process.ts
6647
+ var CHUNK_SIZE = 2000;
6648
+ function writeToStderr(data) {
6649
+ for (let i = 0;i < data.length; i += CHUNK_SIZE) {
6650
+ process.stderr.write(data.substring(i, i + CHUNK_SIZE));
7062
6651
  }
7063
- return "";
7064
6652
  }
7065
- var _toSource_default = toSource;
7066
6653
 
7067
- // ../node_modules/lodash-es/_baseIsNative.js
7068
- var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
7069
- var reIsHostCtor = /^\[object .+?Constructor\]$/;
7070
- var funcProto2 = Function.prototype;
7071
- var objectProto3 = Object.prototype;
7072
- var funcToString2 = funcProto2.toString;
7073
- var hasOwnProperty2 = objectProto3.hasOwnProperty;
7074
- var reIsNative = RegExp("^" + funcToString2.call(hasOwnProperty2).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$");
7075
- function baseIsNative(value) {
7076
- if (!isObject_default(value) || _isMasked_default(value)) {
6654
+ // ../src/utils/debugFilter.ts
6655
+ var parseDebugFilter = memoize_default((filterString) => {
6656
+ if (!filterString || filterString.trim() === "") {
6657
+ return null;
6658
+ }
6659
+ const filters = filterString.split(",").map((f) => f.trim()).filter(Boolean);
6660
+ if (filters.length === 0) {
6661
+ return null;
6662
+ }
6663
+ const hasExclusive = filters.some((f) => f.startsWith("!"));
6664
+ const hasInclusive = filters.some((f) => !f.startsWith("!"));
6665
+ if (hasExclusive && hasInclusive) {
6666
+ return null;
6667
+ }
6668
+ const cleanFilters = filters.map((f) => f.replace(/^!/, "").toLowerCase());
6669
+ return {
6670
+ include: hasExclusive ? [] : cleanFilters,
6671
+ exclude: hasExclusive ? cleanFilters : [],
6672
+ isExclusive: hasExclusive
6673
+ };
6674
+ });
6675
+ function extractDebugCategories(message) {
6676
+ const categories = [];
6677
+ const mcpMatch = message.match(/^MCP server ["']([^"']+)["']/);
6678
+ if (mcpMatch && mcpMatch[1]) {
6679
+ categories.push("mcp");
6680
+ categories.push(mcpMatch[1].toLowerCase());
6681
+ } else {
6682
+ const prefixMatch = message.match(/^([^:[]+):/);
6683
+ if (prefixMatch && prefixMatch[1]) {
6684
+ categories.push(prefixMatch[1].trim().toLowerCase());
6685
+ }
6686
+ }
6687
+ const bracketMatch = message.match(/^\[([^\]]+)]/);
6688
+ if (bracketMatch && bracketMatch[1]) {
6689
+ categories.push(bracketMatch[1].trim().toLowerCase());
6690
+ }
6691
+ if (message.toLowerCase().includes("statsig event:")) {
6692
+ categories.push("statsig");
6693
+ }
6694
+ const secondaryMatch = message.match(/:\s*([^:]+?)(?:\s+(?:type|mode|status|event))?:/);
6695
+ if (secondaryMatch && secondaryMatch[1]) {
6696
+ const secondary = secondaryMatch[1].trim().toLowerCase();
6697
+ if (secondary.length < 30 && !secondary.includes(" ")) {
6698
+ categories.push(secondary);
6699
+ }
6700
+ }
6701
+ return Array.from(new Set(categories));
6702
+ }
6703
+ function shouldShowDebugCategories(categories, filter) {
6704
+ if (!filter) {
6705
+ return true;
6706
+ }
6707
+ if (categories.length === 0) {
7077
6708
  return false;
7078
6709
  }
7079
- var pattern = isFunction_default(value) ? reIsNative : reIsHostCtor;
7080
- return pattern.test(_toSource_default(value));
6710
+ if (filter.isExclusive) {
6711
+ return !categories.some((cat) => filter.exclude.includes(cat));
6712
+ } else {
6713
+ return categories.some((cat) => filter.include.includes(cat));
6714
+ }
7081
6715
  }
7082
- var _baseIsNative_default = baseIsNative;
7083
-
7084
- // ../node_modules/lodash-es/_getValue.js
7085
- function getValue(object, key) {
7086
- return object == null ? undefined : object[key];
6716
+ function shouldShowDebugMessage(message, filter) {
6717
+ if (!filter) {
6718
+ return true;
6719
+ }
6720
+ const categories = extractDebugCategories(message);
6721
+ return shouldShowDebugCategories(categories, filter);
7087
6722
  }
7088
- var _getValue_default = getValue;
7089
6723
 
7090
- // ../node_modules/lodash-es/_getNative.js
7091
- function getNative(object, key) {
7092
- var value = _getValue_default(object, key);
7093
- return _baseIsNative_default(value) ? value : undefined;
6724
+ // ../src/utils/envUtils.ts
6725
+ import { join } from "path";
6726
+ import { homedir } from "os";
6727
+ function getClaudeConfigHomeDir() {
6728
+ return process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude");
7094
6729
  }
7095
- var _getNative_default = getNative;
7096
-
7097
- // ../node_modules/lodash-es/_nativeCreate.js
7098
- var nativeCreate = _getNative_default(Object, "create");
7099
- var _nativeCreate_default = nativeCreate;
7100
-
7101
- // ../node_modules/lodash-es/_hashClear.js
7102
- function hashClear() {
7103
- this.__data__ = _nativeCreate_default ? _nativeCreate_default(null) : {};
7104
- this.size = 0;
6730
+ function isEnvTruthy(envVar) {
6731
+ if (!envVar)
6732
+ return false;
6733
+ if (typeof envVar === "boolean")
6734
+ return envVar;
6735
+ const normalizedValue = envVar.toLowerCase().trim();
6736
+ return ["1", "true", "yes", "on"].includes(normalizedValue);
7105
6737
  }
7106
- var _hashClear_default = hashClear;
7107
6738
 
7108
- // ../node_modules/lodash-es/_hashDelete.js
7109
- function hashDelete(key) {
7110
- var result = this.has(key) && delete this.__data__[key];
7111
- this.size -= result ? 1 : 0;
7112
- return result;
7113
- }
7114
- var _hashDelete_default = hashDelete;
6739
+ // ../src/utils/debug.ts
6740
+ import { dirname, join as join2 } from "path";
7115
6741
 
7116
- // ../node_modules/lodash-es/_hashGet.js
7117
- var HASH_UNDEFINED = "__lodash_hash_undefined__";
7118
- var objectProto4 = Object.prototype;
7119
- var hasOwnProperty3 = objectProto4.hasOwnProperty;
7120
- function hashGet(key) {
7121
- var data = this.__data__;
7122
- if (_nativeCreate_default) {
7123
- var result = data[key];
7124
- return result === HASH_UNDEFINED ? undefined : result;
6742
+ // ../src/bootstrap/state.ts
6743
+ import { cwd } from "process";
6744
+ import { realpathSync } from "fs";
6745
+ import { randomUUID } from "crypto";
6746
+
6747
+ // ../src/bootstrap/envValidators.ts
6748
+ var bashMaxOutputLengthValidator = {
6749
+ name: "BASH_MAX_OUTPUT_LENGTH",
6750
+ default: 30000,
6751
+ validate: (value) => {
6752
+ const MAX_OUTPUT_LENGTH = 150000;
6753
+ const DEFAULT_MAX_OUTPUT_LENGTH = 30000;
6754
+ if (!value) {
6755
+ return {
6756
+ effective: DEFAULT_MAX_OUTPUT_LENGTH,
6757
+ status: "valid"
6758
+ };
6759
+ }
6760
+ const parsed = parseInt(value, 10);
6761
+ if (isNaN(parsed) || parsed <= 0) {
6762
+ return {
6763
+ effective: DEFAULT_MAX_OUTPUT_LENGTH,
6764
+ status: "invalid",
6765
+ message: `Invalid value "${value}" (using default: ${DEFAULT_MAX_OUTPUT_LENGTH})`
6766
+ };
6767
+ }
6768
+ if (parsed > MAX_OUTPUT_LENGTH) {
6769
+ return {
6770
+ effective: MAX_OUTPUT_LENGTH,
6771
+ status: "capped",
6772
+ message: `Capped from ${parsed} to ${MAX_OUTPUT_LENGTH}`
6773
+ };
6774
+ }
6775
+ return { effective: parsed, status: "valid" };
6776
+ }
6777
+ };
6778
+ var maxOutputTokensValidator = {
6779
+ name: "CLAUDE_CODE_MAX_OUTPUT_TOKENS",
6780
+ default: 32000,
6781
+ validate: (value) => {
6782
+ const MAX_OUTPUT_TOKENS = 64000;
6783
+ const DEFAULT_MAX_OUTPUT_TOKENS = 32000;
6784
+ if (!value) {
6785
+ return { effective: DEFAULT_MAX_OUTPUT_TOKENS, status: "valid" };
6786
+ }
6787
+ const parsed = parseInt(value, 10);
6788
+ if (isNaN(parsed) || parsed <= 0) {
6789
+ return {
6790
+ effective: DEFAULT_MAX_OUTPUT_TOKENS,
6791
+ status: "invalid",
6792
+ message: `Invalid value "${value}" (using default: ${DEFAULT_MAX_OUTPUT_TOKENS})`
6793
+ };
6794
+ }
6795
+ if (parsed > MAX_OUTPUT_TOKENS) {
6796
+ return {
6797
+ effective: MAX_OUTPUT_TOKENS,
6798
+ status: "capped",
6799
+ message: `Capped from ${parsed} to ${MAX_OUTPUT_TOKENS}`
6800
+ };
6801
+ }
6802
+ return { effective: parsed, status: "valid" };
7125
6803
  }
7126
- return hasOwnProperty3.call(data, key) ? data[key] : undefined;
7127
- }
7128
- var _hashGet_default = hashGet;
7129
-
7130
- // ../node_modules/lodash-es/_hashHas.js
7131
- var objectProto5 = Object.prototype;
7132
- var hasOwnProperty4 = objectProto5.hasOwnProperty;
7133
- function hashHas(key) {
7134
- var data = this.__data__;
7135
- return _nativeCreate_default ? data[key] !== undefined : hasOwnProperty4.call(data, key);
7136
- }
7137
- var _hashHas_default = hashHas;
7138
-
7139
- // ../node_modules/lodash-es/_hashSet.js
7140
- var HASH_UNDEFINED2 = "__lodash_hash_undefined__";
7141
- function hashSet(key, value) {
7142
- var data = this.__data__;
7143
- this.size += this.has(key) ? 0 : 1;
7144
- data[key] = _nativeCreate_default && value === undefined ? HASH_UNDEFINED2 : value;
7145
- return this;
7146
- }
7147
- var _hashSet_default = hashSet;
6804
+ };
7148
6805
 
7149
- // ../node_modules/lodash-es/_Hash.js
7150
- function Hash(entries) {
7151
- var index = -1, length = entries == null ? 0 : entries.length;
7152
- this.clear();
7153
- while (++index < length) {
7154
- var entry = entries[index];
7155
- this.set(entry[0], entry[1]);
6806
+ // ../src/bootstrap/state.ts
6807
+ function getInitialState() {
6808
+ let resolvedCwd = "";
6809
+ if (typeof process !== "undefined" && typeof process.cwd === "function") {
6810
+ resolvedCwd = realpathSync(cwd());
7156
6811
  }
6812
+ return {
6813
+ originalCwd: resolvedCwd,
6814
+ totalCostUSD: 0,
6815
+ totalAPIDuration: 0,
6816
+ totalAPIDurationWithoutRetries: 0,
6817
+ totalToolDuration: 0,
6818
+ startTime: Date.now(),
6819
+ lastInteractionTime: Date.now(),
6820
+ totalLinesAdded: 0,
6821
+ totalLinesRemoved: 0,
6822
+ hasUnknownModelCost: false,
6823
+ cwd: resolvedCwd,
6824
+ modelUsage: {},
6825
+ mainLoopModelOverride: undefined,
6826
+ initialMainLoopModel: null,
6827
+ modelStrings: null,
6828
+ isInteractive: false,
6829
+ clientType: "cli",
6830
+ sessionIngressToken: undefined,
6831
+ oauthTokenFromFd: undefined,
6832
+ apiKeyFromFd: undefined,
6833
+ flagSettingsPath: undefined,
6834
+ allowedSettingSources: [
6835
+ "userSettings",
6836
+ "projectSettings",
6837
+ "localSettings",
6838
+ "flagSettings",
6839
+ "policySettings"
6840
+ ],
6841
+ meter: null,
6842
+ sessionCounter: null,
6843
+ locCounter: null,
6844
+ prCounter: null,
6845
+ commitCounter: null,
6846
+ costCounter: null,
6847
+ tokenCounter: null,
6848
+ codeEditToolDecisionCounter: null,
6849
+ activeTimeCounter: null,
6850
+ sessionId: randomUUID(),
6851
+ loggerProvider: null,
6852
+ eventLogger: null,
6853
+ meterProvider: null,
6854
+ tracerProvider: null,
6855
+ agentColorMap: new Map,
6856
+ agentColorIndex: 0,
6857
+ envVarValidators: [bashMaxOutputLengthValidator, maxOutputTokensValidator],
6858
+ lastAPIRequest: null,
6859
+ inMemoryErrorLog: [],
6860
+ inlinePlugins: [],
6861
+ sessionBypassPermissionsMode: false,
6862
+ sessionPersistenceDisabled: false,
6863
+ hasExitedPlanMode: false,
6864
+ needsPlanModeExitAttachment: false,
6865
+ initJsonSchema: null,
6866
+ registeredHooks: null,
6867
+ planSlugCache: new Map
6868
+ };
7157
6869
  }
7158
- Hash.prototype.clear = _hashClear_default;
7159
- Hash.prototype["delete"] = _hashDelete_default;
7160
- Hash.prototype.get = _hashGet_default;
7161
- Hash.prototype.has = _hashHas_default;
7162
- Hash.prototype.set = _hashSet_default;
7163
- var _Hash_default = Hash;
7164
-
7165
- // ../node_modules/lodash-es/_listCacheClear.js
7166
- function listCacheClear() {
7167
- this.__data__ = [];
7168
- this.size = 0;
7169
- }
7170
- var _listCacheClear_default = listCacheClear;
7171
-
7172
- // ../node_modules/lodash-es/eq.js
7173
- function eq(value, other) {
7174
- return value === other || value !== value && other !== other;
6870
+ var STATE = getInitialState();
6871
+ function getSessionId() {
6872
+ return STATE.sessionId;
7175
6873
  }
7176
- var eq_default = eq;
7177
6874
 
7178
- // ../node_modules/lodash-es/_assocIndexOf.js
7179
- function assocIndexOf(array, key) {
7180
- var length = array.length;
7181
- while (length--) {
7182
- if (eq_default(array[length][0], key)) {
7183
- return length;
6875
+ // ../src/utils/bufferedWriter.ts
6876
+ function createBufferedWriter({
6877
+ writeFn,
6878
+ flushIntervalMs = 1000,
6879
+ maxBufferSize = 100,
6880
+ immediateMode = false
6881
+ }) {
6882
+ let buffer = [];
6883
+ let flushTimer = null;
6884
+ function clearTimer() {
6885
+ if (flushTimer) {
6886
+ clearTimeout(flushTimer);
6887
+ flushTimer = null;
7184
6888
  }
7185
6889
  }
7186
- return -1;
7187
- }
7188
- var _assocIndexOf_default = assocIndexOf;
7189
-
7190
- // ../node_modules/lodash-es/_listCacheDelete.js
7191
- var arrayProto = Array.prototype;
7192
- var splice = arrayProto.splice;
7193
- function listCacheDelete(key) {
7194
- var data = this.__data__, index = _assocIndexOf_default(data, key);
7195
- if (index < 0) {
7196
- return false;
6890
+ function flush() {
6891
+ if (buffer.length === 0)
6892
+ return;
6893
+ writeFn(buffer.join(""));
6894
+ buffer = [];
6895
+ clearTimer();
7197
6896
  }
7198
- var lastIndex = data.length - 1;
7199
- if (index == lastIndex) {
7200
- data.pop();
7201
- } else {
7202
- splice.call(data, index, 1);
6897
+ function scheduleFlush() {
6898
+ if (!flushTimer) {
6899
+ flushTimer = setTimeout(flush, flushIntervalMs);
6900
+ }
7203
6901
  }
7204
- --this.size;
7205
- return true;
6902
+ return {
6903
+ write(content) {
6904
+ if (immediateMode) {
6905
+ writeFn(content);
6906
+ return;
6907
+ }
6908
+ buffer.push(content);
6909
+ scheduleFlush();
6910
+ if (buffer.length >= maxBufferSize) {
6911
+ flush();
6912
+ }
6913
+ },
6914
+ flush,
6915
+ dispose() {
6916
+ flush();
6917
+ }
6918
+ };
7206
6919
  }
7207
- var _listCacheDelete_default = listCacheDelete;
7208
6920
 
7209
- // ../node_modules/lodash-es/_listCacheGet.js
7210
- function listCacheGet(key) {
7211
- var data = this.__data__, index = _assocIndexOf_default(data, key);
7212
- return index < 0 ? undefined : data[index][1];
6921
+ // ../src/utils/cleanupRegistry.ts
6922
+ var cleanupFunctions = new Set;
6923
+ function registerCleanup(cleanupFn) {
6924
+ cleanupFunctions.add(cleanupFn);
6925
+ return () => cleanupFunctions.delete(cleanupFn);
7213
6926
  }
7214
- var _listCacheGet_default = listCacheGet;
7215
6927
 
7216
- // ../node_modules/lodash-es/_listCacheHas.js
7217
- function listCacheHas(key) {
7218
- return _assocIndexOf_default(this.__data__, key) > -1;
6928
+ // ../src/utils/debug.ts
6929
+ var isDebugMode = memoize_default(() => {
6930
+ return isEnvTruthy(process.env.DEBUG) || isEnvTruthy(process.env.DEBUG_SDK) || process.argv.includes("--debug") || process.argv.includes("-d") || isDebugToStdErr() || process.argv.some((arg) => arg.startsWith("--debug="));
6931
+ });
6932
+ var getDebugFilter = memoize_default(() => {
6933
+ const debugArg = process.argv.find((arg) => arg.startsWith("--debug="));
6934
+ if (!debugArg) {
6935
+ return null;
6936
+ }
6937
+ const filterPattern = debugArg.substring("--debug=".length);
6938
+ return parseDebugFilter(filterPattern);
6939
+ });
6940
+ var isDebugToStdErr = memoize_default(() => {
6941
+ return process.argv.includes("--debug-to-stderr") || process.argv.includes("-d2e");
6942
+ });
6943
+ function shouldLogDebugMessage(message) {
6944
+ if (false) {}
6945
+ if (typeof process === "undefined" || typeof process.versions === "undefined" || typeof process.versions.node === "undefined") {
6946
+ return false;
6947
+ }
6948
+ const filter = getDebugFilter();
6949
+ return shouldShowDebugMessage(message, filter);
7219
6950
  }
7220
- var _listCacheHas_default = listCacheHas;
7221
-
7222
- // ../node_modules/lodash-es/_listCacheSet.js
7223
- function listCacheSet(key, value) {
7224
- var data = this.__data__, index = _assocIndexOf_default(data, key);
7225
- if (index < 0) {
7226
- ++this.size;
7227
- data.push([key, value]);
7228
- } else {
7229
- data[index][1] = value;
6951
+ var hasFormattedOutput = false;
6952
+ var debugWriter = null;
6953
+ function getDebugWriter() {
6954
+ if (!debugWriter) {
6955
+ debugWriter = createBufferedWriter({
6956
+ writeFn: (content) => {
6957
+ const path = getDebugLogPath();
6958
+ if (!getFsImplementation().existsSync(dirname(path))) {
6959
+ getFsImplementation().mkdirSync(dirname(path));
6960
+ }
6961
+ getFsImplementation().appendFileSync(path, content);
6962
+ updateLatestDebugLogSymlink();
6963
+ },
6964
+ flushIntervalMs: 1000,
6965
+ maxBufferSize: 100,
6966
+ immediateMode: isDebugMode()
6967
+ });
6968
+ registerCleanup(async () => debugWriter?.dispose());
7230
6969
  }
7231
- return this;
6970
+ return debugWriter;
7232
6971
  }
7233
- var _listCacheSet_default = listCacheSet;
7234
-
7235
- // ../node_modules/lodash-es/_ListCache.js
7236
- function ListCache(entries) {
7237
- var index = -1, length = entries == null ? 0 : entries.length;
7238
- this.clear();
7239
- while (++index < length) {
7240
- var entry = entries[index];
7241
- this.set(entry[0], entry[1]);
6972
+ function logForDebugging(message, { level } = {
6973
+ level: "debug"
6974
+ }) {
6975
+ if (!shouldLogDebugMessage(message)) {
6976
+ return;
7242
6977
  }
6978
+ if (hasFormattedOutput && message.includes(`
6979
+ `)) {
6980
+ message = JSON.stringify(message);
6981
+ }
6982
+ const timestamp = new Date().toISOString();
6983
+ const output = `${timestamp} [${level.toUpperCase()}] ${message.trim()}
6984
+ `;
6985
+ if (isDebugToStdErr()) {
6986
+ writeToStderr(output);
6987
+ return;
6988
+ }
6989
+ getDebugWriter().write(output);
7243
6990
  }
7244
- ListCache.prototype.clear = _listCacheClear_default;
7245
- ListCache.prototype["delete"] = _listCacheDelete_default;
7246
- ListCache.prototype.get = _listCacheGet_default;
7247
- ListCache.prototype.has = _listCacheHas_default;
7248
- ListCache.prototype.set = _listCacheSet_default;
7249
- var _ListCache_default = ListCache;
7250
-
7251
- // ../node_modules/lodash-es/_Map.js
7252
- var Map2 = _getNative_default(_root_default, "Map");
7253
- var _Map_default = Map2;
7254
-
7255
- // ../node_modules/lodash-es/_mapCacheClear.js
7256
- function mapCacheClear() {
7257
- this.size = 0;
7258
- this.__data__ = {
7259
- hash: new _Hash_default,
7260
- map: new (_Map_default || _ListCache_default),
7261
- string: new _Hash_default
7262
- };
7263
- }
7264
- var _mapCacheClear_default = mapCacheClear;
7265
-
7266
- // ../node_modules/lodash-es/_isKeyable.js
7267
- function isKeyable(value) {
7268
- var type = typeof value;
7269
- return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
7270
- }
7271
- var _isKeyable_default = isKeyable;
7272
-
7273
- // ../node_modules/lodash-es/_getMapData.js
7274
- function getMapData(map, key) {
7275
- var data = map.__data__;
7276
- return _isKeyable_default(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
6991
+ function getDebugLogPath() {
6992
+ return process.env.CLAUDE_CODE_DEBUG_LOGS_DIR ?? join2(getClaudeConfigHomeDir(), "debug", `${getSessionId()}.txt`);
7277
6993
  }
7278
- var _getMapData_default = getMapData;
6994
+ var updateLatestDebugLogSymlink = memoize_default(() => {
6995
+ if (process.argv[2] === "--ripgrep") {
6996
+ return;
6997
+ }
6998
+ try {
6999
+ const debugLogPath = getDebugLogPath();
7000
+ const debugLogsDir = dirname(debugLogPath);
7001
+ const latestSymlinkPath = join2(debugLogsDir, "latest");
7002
+ if (!getFsImplementation().existsSync(debugLogsDir)) {
7003
+ getFsImplementation().mkdirSync(debugLogsDir);
7004
+ }
7005
+ if (getFsImplementation().existsSync(latestSymlinkPath)) {
7006
+ try {
7007
+ getFsImplementation().unlinkSync(latestSymlinkPath);
7008
+ } catch {}
7009
+ }
7010
+ getFsImplementation().symlinkSync(debugLogPath, latestSymlinkPath);
7011
+ } catch {}
7012
+ });
7279
7013
 
7280
- // ../node_modules/lodash-es/_mapCacheDelete.js
7281
- function mapCacheDelete(key) {
7282
- var result = _getMapData_default(this, key)["delete"](key);
7283
- this.size -= result ? 1 : 0;
7284
- return result;
7014
+ // ../src/utils/fsOperations.ts
7015
+ var SLOW_SYNC_THRESHOLD_MS = 5;
7016
+ function withSlowLogging(operation, fn) {
7017
+ const startTime = performance.now();
7018
+ try {
7019
+ return fn();
7020
+ } finally {
7021
+ const duration = performance.now() - startTime;
7022
+ if (duration > SLOW_SYNC_THRESHOLD_MS) {
7023
+ logForDebugging(`[SLOW OPERATION DETECTED] fs.${operation} (${duration.toFixed(1)}ms)`);
7024
+ }
7025
+ }
7285
7026
  }
7286
- var _mapCacheDelete_default = mapCacheDelete;
7287
-
7288
- // ../node_modules/lodash-es/_mapCacheGet.js
7289
- function mapCacheGet(key) {
7290
- return _getMapData_default(this, key).get(key);
7027
+ var NodeFsOperations = {
7028
+ cwd() {
7029
+ return process.cwd();
7030
+ },
7031
+ existsSync(fsPath) {
7032
+ return withSlowLogging("existsSync", () => fs.existsSync(fsPath));
7033
+ },
7034
+ async stat(fsPath) {
7035
+ return statPromise(fsPath);
7036
+ },
7037
+ statSync(fsPath) {
7038
+ return withSlowLogging("statSync", () => fs.statSync(fsPath));
7039
+ },
7040
+ lstatSync(fsPath) {
7041
+ return withSlowLogging("lstatSync", () => fs.lstatSync(fsPath));
7042
+ },
7043
+ readFileSync(fsPath, options) {
7044
+ return withSlowLogging("readFileSync", () => fs.readFileSync(fsPath, { encoding: options.encoding }));
7045
+ },
7046
+ readFileBytesSync(fsPath) {
7047
+ return withSlowLogging("readFileBytesSync", () => fs.readFileSync(fsPath));
7048
+ },
7049
+ readSync(fsPath, options) {
7050
+ return withSlowLogging("readSync", () => {
7051
+ let fd = undefined;
7052
+ try {
7053
+ fd = fs.openSync(fsPath, "r");
7054
+ const buffer = Buffer.alloc(options.length);
7055
+ const bytesRead = fs.readSync(fd, buffer, 0, options.length, 0);
7056
+ return { buffer, bytesRead };
7057
+ } finally {
7058
+ if (fd)
7059
+ fs.closeSync(fd);
7060
+ }
7061
+ });
7062
+ },
7063
+ writeFileSync(fsPath, data, options) {
7064
+ return withSlowLogging("writeFileSync", () => {
7065
+ const fileExists = fs.existsSync(fsPath);
7066
+ if (!options.flush) {
7067
+ const writeOptions = {
7068
+ encoding: options.encoding
7069
+ };
7070
+ if (!fileExists) {
7071
+ writeOptions.mode = options.mode ?? 384;
7072
+ } else if (options.mode !== undefined) {
7073
+ writeOptions.mode = options.mode;
7074
+ }
7075
+ fs.writeFileSync(fsPath, data, writeOptions);
7076
+ return;
7077
+ }
7078
+ let fd;
7079
+ try {
7080
+ const mode = !fileExists ? options.mode ?? 384 : options.mode;
7081
+ fd = fs.openSync(fsPath, "w", mode);
7082
+ fs.writeFileSync(fd, data, { encoding: options.encoding });
7083
+ fs.fsyncSync(fd);
7084
+ } finally {
7085
+ if (fd) {
7086
+ fs.closeSync(fd);
7087
+ }
7088
+ }
7089
+ });
7090
+ },
7091
+ appendFileSync(path, data, options) {
7092
+ return withSlowLogging("appendFileSync", () => {
7093
+ if (!fs.existsSync(path)) {
7094
+ const mode = options?.mode ?? 384;
7095
+ const fd = fs.openSync(path, "a", mode);
7096
+ try {
7097
+ fs.appendFileSync(fd, data);
7098
+ } finally {
7099
+ fs.closeSync(fd);
7100
+ }
7101
+ } else {
7102
+ fs.appendFileSync(path, data);
7103
+ }
7104
+ });
7105
+ },
7106
+ copyFileSync(src, dest) {
7107
+ return withSlowLogging("copyFileSync", () => fs.copyFileSync(src, dest));
7108
+ },
7109
+ unlinkSync(path) {
7110
+ return withSlowLogging("unlinkSync", () => fs.unlinkSync(path));
7111
+ },
7112
+ renameSync(oldPath, newPath) {
7113
+ return withSlowLogging("renameSync", () => fs.renameSync(oldPath, newPath));
7114
+ },
7115
+ linkSync(target, path) {
7116
+ return withSlowLogging("linkSync", () => fs.linkSync(target, path));
7117
+ },
7118
+ symlinkSync(target, path) {
7119
+ return withSlowLogging("symlinkSync", () => fs.symlinkSync(target, path));
7120
+ },
7121
+ readlinkSync(path) {
7122
+ return withSlowLogging("readlinkSync", () => fs.readlinkSync(path));
7123
+ },
7124
+ realpathSync(path) {
7125
+ return withSlowLogging("realpathSync", () => fs.realpathSync(path));
7126
+ },
7127
+ mkdirSync(dirPath) {
7128
+ return withSlowLogging("mkdirSync", () => {
7129
+ if (!fs.existsSync(dirPath)) {
7130
+ fs.mkdirSync(dirPath, { recursive: true, mode: 448 });
7131
+ }
7132
+ });
7133
+ },
7134
+ readdirSync(dirPath) {
7135
+ return withSlowLogging("readdirSync", () => fs.readdirSync(dirPath, { withFileTypes: true }));
7136
+ },
7137
+ readdirStringSync(dirPath) {
7138
+ return withSlowLogging("readdirStringSync", () => fs.readdirSync(dirPath));
7139
+ },
7140
+ isDirEmptySync(dirPath) {
7141
+ return withSlowLogging("isDirEmptySync", () => {
7142
+ const files = this.readdirSync(dirPath);
7143
+ return files.length === 0;
7144
+ });
7145
+ },
7146
+ rmdirSync(dirPath) {
7147
+ return withSlowLogging("rmdirSync", () => fs.rmdirSync(dirPath));
7148
+ },
7149
+ rmSync(path, options) {
7150
+ return withSlowLogging("rmSync", () => fs.rmSync(path, options));
7151
+ },
7152
+ createWriteStream(path) {
7153
+ return fs.createWriteStream(path);
7154
+ }
7155
+ };
7156
+ var activeFs = NodeFsOperations;
7157
+ function getFsImplementation() {
7158
+ return activeFs;
7291
7159
  }
7292
- var _mapCacheGet_default = mapCacheGet;
7293
7160
 
7294
- // ../node_modules/lodash-es/_mapCacheHas.js
7295
- function mapCacheHas(key) {
7296
- return _getMapData_default(this, key).has(key);
7161
+ // ../src/entrypoints/agentSdkTypes.ts
7162
+ var HOOK_EVENTS = [
7163
+ "PreToolUse",
7164
+ "PostToolUse",
7165
+ "PostToolUseFailure",
7166
+ "Notification",
7167
+ "UserPromptSubmit",
7168
+ "SessionStart",
7169
+ "SessionEnd",
7170
+ "Stop",
7171
+ "SubagentStart",
7172
+ "SubagentStop",
7173
+ "PreCompact",
7174
+ "PermissionRequest"
7175
+ ];
7176
+ var EXIT_REASONS = [
7177
+ "clear",
7178
+ "logout",
7179
+ "prompt_input_exit",
7180
+ "other",
7181
+ "bypass_permissions_disabled"
7182
+ ];
7183
+ class AbortError extends Error {
7297
7184
  }
7298
- var _mapCacheHas_default = mapCacheHas;
7299
7185
 
7300
- // ../node_modules/lodash-es/_mapCacheSet.js
7301
- function mapCacheSet(key, value) {
7302
- var data = _getMapData_default(this, key), size = data.size;
7303
- data.set(key, value);
7304
- this.size += data.size == size ? 0 : 1;
7305
- return this;
7186
+ // ../src/utils/bundledMode.ts
7187
+ function isRunningWithBun() {
7188
+ return process.versions.bun !== undefined;
7306
7189
  }
7307
- var _mapCacheSet_default = mapCacheSet;
7308
7190
 
7309
- // ../node_modules/lodash-es/_MapCache.js
7310
- function MapCache(entries) {
7311
- var index = -1, length = entries == null ? 0 : entries.length;
7312
- this.clear();
7313
- while (++index < length) {
7314
- var entry = entries[index];
7315
- this.set(entry[0], entry[1]);
7191
+ // ../src/utils/sdkDebug.ts
7192
+ import { randomUUID as randomUUID2 } from "crypto";
7193
+ import { appendFileSync as appendFileSync2, existsSync as existsSync2, mkdirSync as mkdirSync2 } from "fs";
7194
+ import { join as join3 } from "path";
7195
+ var debugFilePath = null;
7196
+ var initialized = false;
7197
+ function getOrCreateDebugFile() {
7198
+ if (initialized) {
7199
+ return debugFilePath;
7316
7200
  }
7317
- }
7318
- MapCache.prototype.clear = _mapCacheClear_default;
7319
- MapCache.prototype["delete"] = _mapCacheDelete_default;
7320
- MapCache.prototype.get = _mapCacheGet_default;
7321
- MapCache.prototype.has = _mapCacheHas_default;
7322
- MapCache.prototype.set = _mapCacheSet_default;
7323
- var _MapCache_default = MapCache;
7324
-
7325
- // ../node_modules/lodash-es/memoize.js
7326
- var FUNC_ERROR_TEXT = "Expected a function";
7327
- function memoize(func, resolver) {
7328
- if (typeof func != "function" || resolver != null && typeof resolver != "function") {
7329
- throw new TypeError(FUNC_ERROR_TEXT);
7201
+ initialized = true;
7202
+ if (!process.env.DEBUG_CLAUDE_AGENT_SDK) {
7203
+ return null;
7204
+ }
7205
+ const debugDir = join3(getClaudeConfigHomeDir(), "debug");
7206
+ debugFilePath = join3(debugDir, `sdk-${randomUUID2()}.txt`);
7207
+ if (!existsSync2(debugDir)) {
7208
+ mkdirSync2(debugDir, { recursive: true });
7209
+ }
7210
+ process.stderr.write(`SDK debug logs: ${debugFilePath}
7211
+ `);
7212
+ return debugFilePath;
7213
+ }
7214
+ function logForSdkDebugging(message) {
7215
+ const path = getOrCreateDebugFile();
7216
+ if (!path) {
7217
+ return;
7330
7218
  }
7331
- var memoized = function() {
7332
- var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache;
7333
- if (cache.has(key)) {
7334
- return cache.get(key);
7335
- }
7336
- var result = func.apply(this, args);
7337
- memoized.cache = cache.set(key, result) || cache;
7338
- return result;
7339
- };
7340
- memoized.cache = new (memoize.Cache || _MapCache_default);
7341
- return memoized;
7219
+ const timestamp = new Date().toISOString();
7220
+ const output = `${timestamp} ${message}
7221
+ `;
7222
+ appendFileSync2(path, output);
7342
7223
  }
7343
- memoize.Cache = _MapCache_default;
7344
- var memoize_default = memoize;
7345
7224
 
7346
- // ../src/utils/process.ts
7347
- var CHUNK_SIZE = 2000;
7348
- function writeToStderr(data) {
7349
- for (let i = 0;i < data.length; i += CHUNK_SIZE) {
7350
- process.stderr.write(data.substring(i, i + CHUNK_SIZE));
7225
+ // ../src/transport/sandboxUtils.ts
7226
+ function mergeSandboxIntoExtraArgs(extraArgs, sandbox) {
7227
+ const effectiveExtraArgs = { ...extraArgs };
7228
+ if (sandbox) {
7229
+ let settingsObj = { sandbox };
7230
+ if (effectiveExtraArgs.settings) {
7231
+ try {
7232
+ const existingSettings = JSON.parse(effectiveExtraArgs.settings);
7233
+ settingsObj = { ...existingSettings, sandbox };
7234
+ } catch {}
7235
+ }
7236
+ effectiveExtraArgs.settings = JSON.stringify(settingsObj);
7351
7237
  }
7238
+ return effectiveExtraArgs;
7352
7239
  }
7353
7240
 
7354
- // ../src/utils/debugFilter.ts
7355
- var parseDebugFilter = memoize_default((filterString) => {
7356
- if (!filterString || filterString.trim() === "") {
7357
- return null;
7358
- }
7359
- const filters = filterString.split(",").map((f) => f.trim()).filter(Boolean);
7360
- if (filters.length === 0) {
7361
- return null;
7241
+ // ../src/transport/ProcessTransport.ts
7242
+ class ProcessTransport {
7243
+ options;
7244
+ process;
7245
+ processStdin;
7246
+ processStdout;
7247
+ ready = false;
7248
+ abortController;
7249
+ exitError;
7250
+ exitListeners = [];
7251
+ processExitHandler;
7252
+ abortHandler;
7253
+ constructor(options) {
7254
+ this.options = options;
7255
+ this.abortController = options.abortController || createAbortController();
7256
+ this.initialize();
7362
7257
  }
7363
- const hasExclusive = filters.some((f) => f.startsWith("!"));
7364
- const hasInclusive = filters.some((f) => !f.startsWith("!"));
7365
- if (hasExclusive && hasInclusive) {
7366
- return null;
7258
+ getDefaultExecutable() {
7259
+ return isRunningWithBun() ? "bun" : "node";
7260
+ }
7261
+ spawnLocalProcess(spawnOptions) {
7262
+ const { command, args, cwd: cwd2, env, signal } = spawnOptions;
7263
+ const stderrMode = env.DEBUG_CLAUDE_AGENT_SDK || this.options.stderr ? "pipe" : "ignore";
7264
+ const childProcess = spawn(command, args, {
7265
+ cwd: cwd2,
7266
+ stdio: ["pipe", "pipe", stderrMode],
7267
+ signal,
7268
+ env
7269
+ });
7270
+ if (env.DEBUG_CLAUDE_AGENT_SDK || this.options.stderr) {
7271
+ childProcess.stderr.on("data", (data) => {
7272
+ const message = data.toString();
7273
+ logForSdkDebugging(message);
7274
+ if (this.options.stderr) {
7275
+ this.options.stderr(message);
7276
+ }
7277
+ });
7278
+ }
7279
+ const mappedProcess = {
7280
+ stdin: childProcess.stdin,
7281
+ stdout: childProcess.stdout,
7282
+ get killed() {
7283
+ return childProcess.killed;
7284
+ },
7285
+ get exitCode() {
7286
+ return childProcess.exitCode;
7287
+ },
7288
+ kill: childProcess.kill.bind(childProcess),
7289
+ on: childProcess.on.bind(childProcess),
7290
+ once: childProcess.once.bind(childProcess),
7291
+ off: childProcess.off.bind(childProcess)
7292
+ };
7293
+ return mappedProcess;
7367
7294
  }
7368
- const cleanFilters = filters.map((f) => f.replace(/^!/, "").toLowerCase());
7369
- return {
7370
- include: hasExclusive ? [] : cleanFilters,
7371
- exclude: hasExclusive ? cleanFilters : [],
7372
- isExclusive: hasExclusive
7373
- };
7374
- });
7375
- function extractDebugCategories(message) {
7376
- const categories = [];
7377
- const mcpMatch = message.match(/^MCP server ["']([^"']+)["']/);
7378
- if (mcpMatch && mcpMatch[1]) {
7379
- categories.push("mcp");
7380
- categories.push(mcpMatch[1].toLowerCase());
7381
- } else {
7382
- const prefixMatch = message.match(/^([^:[]+):/);
7383
- if (prefixMatch && prefixMatch[1]) {
7384
- categories.push(prefixMatch[1].trim().toLowerCase());
7295
+ initialize() {
7296
+ try {
7297
+ const {
7298
+ additionalDirectories = [],
7299
+ betas,
7300
+ cwd: cwd2,
7301
+ executable = this.getDefaultExecutable(),
7302
+ executableArgs = [],
7303
+ extraArgs = {},
7304
+ pathToClaudeCodeExecutable,
7305
+ env = { ...process.env },
7306
+ stderr,
7307
+ maxThinkingTokens,
7308
+ maxTurns,
7309
+ maxBudgetUsd,
7310
+ model,
7311
+ fallbackModel,
7312
+ jsonSchema,
7313
+ permissionMode,
7314
+ allowDangerouslySkipPermissions,
7315
+ permissionPromptToolName,
7316
+ continueConversation,
7317
+ resume,
7318
+ settingSources,
7319
+ allowedTools = [],
7320
+ disallowedTools = [],
7321
+ tools,
7322
+ mcpServers,
7323
+ strictMcpConfig,
7324
+ canUseTool,
7325
+ includePartialMessages,
7326
+ plugins,
7327
+ sandbox
7328
+ } = this.options;
7329
+ const args = [
7330
+ "--output-format",
7331
+ "stream-json",
7332
+ "--verbose",
7333
+ "--input-format",
7334
+ "stream-json"
7335
+ ];
7336
+ if (maxThinkingTokens !== undefined) {
7337
+ args.push("--max-thinking-tokens", maxThinkingTokens.toString());
7338
+ }
7339
+ if (maxTurns)
7340
+ args.push("--max-turns", maxTurns.toString());
7341
+ if (maxBudgetUsd !== undefined) {
7342
+ args.push("--max-budget-usd", maxBudgetUsd.toString());
7343
+ }
7344
+ if (model)
7345
+ args.push("--model", model);
7346
+ if (betas && betas.length > 0) {
7347
+ args.push("--betas", betas.join(","));
7348
+ }
7349
+ if (jsonSchema) {
7350
+ args.push("--json-schema", JSON.stringify(jsonSchema));
7351
+ }
7352
+ if (env.DEBUG_CLAUDE_AGENT_SDK) {
7353
+ args.push("--debug-to-stderr");
7354
+ }
7355
+ if (canUseTool) {
7356
+ if (permissionPromptToolName) {
7357
+ throw new Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");
7358
+ }
7359
+ args.push("--permission-prompt-tool", "stdio");
7360
+ } else if (permissionPromptToolName) {
7361
+ args.push("--permission-prompt-tool", permissionPromptToolName);
7362
+ }
7363
+ if (continueConversation)
7364
+ args.push("--continue");
7365
+ if (resume)
7366
+ args.push("--resume", resume);
7367
+ if (allowedTools.length > 0) {
7368
+ args.push("--allowedTools", allowedTools.join(","));
7369
+ }
7370
+ if (disallowedTools.length > 0) {
7371
+ args.push("--disallowedTools", disallowedTools.join(","));
7372
+ }
7373
+ if (tools !== undefined) {
7374
+ if (Array.isArray(tools)) {
7375
+ if (tools.length === 0) {
7376
+ args.push("--tools", "");
7377
+ } else {
7378
+ args.push("--tools", tools.join(","));
7379
+ }
7380
+ } else {
7381
+ args.push("--tools", "default");
7382
+ }
7383
+ }
7384
+ if (mcpServers && Object.keys(mcpServers).length > 0) {
7385
+ args.push("--mcp-config", JSON.stringify({ mcpServers }));
7386
+ }
7387
+ if (settingSources) {
7388
+ args.push("--setting-sources", settingSources.join(","));
7389
+ }
7390
+ if (strictMcpConfig) {
7391
+ args.push("--strict-mcp-config");
7392
+ }
7393
+ if (permissionMode) {
7394
+ args.push("--permission-mode", permissionMode);
7395
+ }
7396
+ if (allowDangerouslySkipPermissions) {
7397
+ args.push("--allow-dangerously-skip-permissions");
7398
+ }
7399
+ if (fallbackModel) {
7400
+ if (model && fallbackModel === model) {
7401
+ throw new Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option.");
7402
+ }
7403
+ args.push("--fallback-model", fallbackModel);
7404
+ }
7405
+ if (includePartialMessages) {
7406
+ args.push("--include-partial-messages");
7407
+ }
7408
+ for (const dir of additionalDirectories) {
7409
+ args.push("--add-dir", dir);
7410
+ }
7411
+ if (plugins && plugins.length > 0) {
7412
+ for (const plugin of plugins) {
7413
+ if (plugin.type === "local") {
7414
+ args.push("--plugin-dir", plugin.path);
7415
+ } else {
7416
+ throw new Error(`Unsupported plugin type: ${plugin.type}`);
7417
+ }
7418
+ }
7419
+ }
7420
+ if (this.options.forkSession) {
7421
+ args.push("--fork-session");
7422
+ }
7423
+ if (this.options.resumeSessionAt) {
7424
+ args.push("--resume-session-at", this.options.resumeSessionAt);
7425
+ }
7426
+ if (this.options.persistSession === false) {
7427
+ args.push("--no-session-persistence");
7428
+ }
7429
+ const effectiveExtraArgs = mergeSandboxIntoExtraArgs(extraArgs ?? {}, sandbox);
7430
+ for (const [flag, value] of Object.entries(effectiveExtraArgs)) {
7431
+ if (value === null) {
7432
+ args.push(`--${flag}`);
7433
+ } else {
7434
+ args.push(`--${flag}`, value);
7435
+ }
7436
+ }
7437
+ if (!env.CLAUDE_CODE_ENTRYPOINT) {
7438
+ env.CLAUDE_CODE_ENTRYPOINT = "sdk-ts";
7439
+ }
7440
+ delete env.NODE_OPTIONS;
7441
+ if (env.DEBUG_CLAUDE_AGENT_SDK) {
7442
+ env.DEBUG = "1";
7443
+ } else {
7444
+ delete env.DEBUG;
7445
+ }
7446
+ const isNative = isNativeBinary(pathToClaudeCodeExecutable);
7447
+ const spawnCommand = isNative ? pathToClaudeCodeExecutable : executable;
7448
+ const spawnArgs = isNative ? [...executableArgs, ...args] : [...executableArgs, pathToClaudeCodeExecutable, ...args];
7449
+ const spawnOptions = {
7450
+ command: spawnCommand,
7451
+ args: spawnArgs,
7452
+ cwd: cwd2,
7453
+ env,
7454
+ signal: this.abortController.signal
7455
+ };
7456
+ if (this.options.spawnClaudeCodeProcess) {
7457
+ logForSdkDebugging(`Spawning Claude Code (custom): ${spawnCommand} ${spawnArgs.join(" ")}`);
7458
+ this.process = this.options.spawnClaudeCodeProcess(spawnOptions);
7459
+ } else {
7460
+ const fs2 = getFsImplementation();
7461
+ if (!fs2.existsSync(pathToClaudeCodeExecutable)) {
7462
+ const errorMessage = isNative ? `Claude Code native binary not found at ${pathToClaudeCodeExecutable}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.` : `Claude Code executable not found at ${pathToClaudeCodeExecutable}. Is options.pathToClaudeCodeExecutable set?`;
7463
+ throw new ReferenceError(errorMessage);
7464
+ }
7465
+ const spawnMessage = `Spawning Claude Code: ${spawnCommand} ${spawnArgs.join(" ")}`;
7466
+ logForSdkDebugging(spawnMessage);
7467
+ if (stderr) {
7468
+ stderr(spawnMessage);
7469
+ }
7470
+ this.process = this.spawnLocalProcess(spawnOptions);
7471
+ }
7472
+ this.processStdin = this.process.stdin;
7473
+ this.processStdout = this.process.stdout;
7474
+ const cleanup = () => {
7475
+ if (this.process && !this.process.killed) {
7476
+ this.process.kill("SIGTERM");
7477
+ }
7478
+ };
7479
+ this.processExitHandler = cleanup;
7480
+ this.abortHandler = cleanup;
7481
+ process.on("exit", this.processExitHandler);
7482
+ this.abortController.signal.addEventListener("abort", this.abortHandler);
7483
+ this.process.on("error", (error) => {
7484
+ this.ready = false;
7485
+ if (this.abortController.signal.aborted) {
7486
+ this.exitError = new AbortError("Claude Code process aborted by user");
7487
+ } else {
7488
+ this.exitError = new Error(`Failed to spawn Claude Code process: ${error.message}`);
7489
+ logForSdkDebugging(this.exitError.message);
7490
+ }
7491
+ });
7492
+ this.process.on("exit", (code, signal) => {
7493
+ this.ready = false;
7494
+ if (this.abortController.signal.aborted) {
7495
+ this.exitError = new AbortError("Claude Code process aborted by user");
7496
+ } else {
7497
+ const error = this.getProcessExitError(code, signal);
7498
+ if (error) {
7499
+ this.exitError = error;
7500
+ logForSdkDebugging(error.message);
7501
+ }
7502
+ }
7503
+ });
7504
+ this.ready = true;
7505
+ } catch (error) {
7506
+ this.ready = false;
7507
+ throw error;
7385
7508
  }
7386
7509
  }
7387
- const bracketMatch = message.match(/^\[([^\]]+)]/);
7388
- if (bracketMatch && bracketMatch[1]) {
7389
- categories.push(bracketMatch[1].trim().toLowerCase());
7390
- }
7391
- if (message.toLowerCase().includes("statsig event:")) {
7392
- categories.push("statsig");
7393
- }
7394
- const secondaryMatch = message.match(/:\s*([^:]+?)(?:\s+(?:type|mode|status|event))?:/);
7395
- if (secondaryMatch && secondaryMatch[1]) {
7396
- const secondary = secondaryMatch[1].trim().toLowerCase();
7397
- if (secondary.length < 30 && !secondary.includes(" ")) {
7398
- categories.push(secondary);
7510
+ getProcessExitError(code, signal) {
7511
+ if (code !== 0 && code !== null) {
7512
+ return new Error(`Claude Code process exited with code ${code}`);
7513
+ } else if (signal) {
7514
+ return new Error(`Claude Code process terminated by signal ${signal}`);
7399
7515
  }
7516
+ return;
7400
7517
  }
7401
- return Array.from(new Set(categories));
7402
- }
7403
- function shouldShowDebugCategories(categories, filter) {
7404
- if (!filter) {
7405
- return true;
7406
- }
7407
- if (categories.length === 0) {
7408
- return false;
7409
- }
7410
- if (filter.isExclusive) {
7411
- return !categories.some((cat) => filter.exclude.includes(cat));
7412
- } else {
7413
- return categories.some((cat) => filter.include.includes(cat));
7414
- }
7415
- }
7416
- function shouldShowDebugMessage(message, filter) {
7417
- if (!filter) {
7418
- return true;
7419
- }
7420
- const categories = extractDebugCategories(message);
7421
- return shouldShowDebugCategories(categories, filter);
7422
- }
7423
-
7424
- // ../src/utils/debug.ts
7425
- import { dirname, join as join3 } from "path";
7426
-
7427
- // ../src/bootstrap/state.ts
7428
- import { cwd } from "process";
7429
- import { realpathSync as realpathSync2 } from "fs";
7430
- import { randomUUID as randomUUID2 } from "crypto";
7431
-
7432
- // ../src/bootstrap/envValidators.ts
7433
- var bashMaxOutputLengthValidator = {
7434
- name: "BASH_MAX_OUTPUT_LENGTH",
7435
- default: 30000,
7436
- validate: (value) => {
7437
- const MAX_OUTPUT_LENGTH = 150000;
7438
- const DEFAULT_MAX_OUTPUT_LENGTH = 30000;
7439
- if (!value) {
7440
- return {
7441
- effective: DEFAULT_MAX_OUTPUT_LENGTH,
7442
- status: "valid"
7443
- };
7518
+ write(data) {
7519
+ if (this.abortController.signal.aborted) {
7520
+ throw new AbortError("Operation aborted");
7444
7521
  }
7445
- const parsed = parseInt(value, 10);
7446
- if (isNaN(parsed) || parsed <= 0) {
7447
- return {
7448
- effective: DEFAULT_MAX_OUTPUT_LENGTH,
7449
- status: "invalid",
7450
- message: `Invalid value "${value}" (using default: ${DEFAULT_MAX_OUTPUT_LENGTH})`
7451
- };
7522
+ if (!this.ready || !this.processStdin) {
7523
+ throw new Error("ProcessTransport is not ready for writing");
7452
7524
  }
7453
- if (parsed > MAX_OUTPUT_LENGTH) {
7454
- return {
7455
- effective: MAX_OUTPUT_LENGTH,
7456
- status: "capped",
7457
- message: `Capped from ${parsed} to ${MAX_OUTPUT_LENGTH}`
7458
- };
7525
+ if (this.process?.killed || this.process?.exitCode !== null) {
7526
+ throw new Error("Cannot write to terminated process");
7527
+ }
7528
+ if (this.exitError) {
7529
+ throw new Error(`Cannot write to process that exited with error: ${this.exitError.message}`);
7530
+ }
7531
+ logForSdkDebugging(`[ProcessTransport] Writing to stdin: ${data.substring(0, 100)}`);
7532
+ try {
7533
+ const written = this.processStdin.write(data);
7534
+ if (!written) {
7535
+ logForSdkDebugging("[ProcessTransport] Write buffer full, data queued");
7536
+ }
7537
+ } catch (error) {
7538
+ this.ready = false;
7539
+ throw new Error(`Failed to write to process stdin: ${error.message}`);
7459
7540
  }
7460
- return { effective: parsed, status: "valid" };
7461
7541
  }
7462
- };
7463
- var maxOutputTokensValidator = {
7464
- name: "CLAUDE_CODE_MAX_OUTPUT_TOKENS",
7465
- default: 32000,
7466
- validate: (value) => {
7467
- const MAX_OUTPUT_TOKENS = 64000;
7468
- const DEFAULT_MAX_OUTPUT_TOKENS = 32000;
7469
- if (!value) {
7470
- return { effective: DEFAULT_MAX_OUTPUT_TOKENS, status: "valid" };
7542
+ close() {
7543
+ if (this.processStdin) {
7544
+ this.processStdin.end();
7545
+ this.processStdin = undefined;
7471
7546
  }
7472
- const parsed = parseInt(value, 10);
7473
- if (isNaN(parsed) || parsed <= 0) {
7474
- return {
7475
- effective: DEFAULT_MAX_OUTPUT_TOKENS,
7476
- status: "invalid",
7477
- message: `Invalid value "${value}" (using default: ${DEFAULT_MAX_OUTPUT_TOKENS})`
7478
- };
7547
+ if (this.abortHandler) {
7548
+ this.abortController.signal.removeEventListener("abort", this.abortHandler);
7549
+ this.abortHandler = undefined;
7479
7550
  }
7480
- if (parsed > MAX_OUTPUT_TOKENS) {
7481
- return {
7482
- effective: MAX_OUTPUT_TOKENS,
7483
- status: "capped",
7484
- message: `Capped from ${parsed} to ${MAX_OUTPUT_TOKENS}`
7485
- };
7551
+ for (const { handler } of this.exitListeners) {
7552
+ this.process?.off("exit", handler);
7553
+ }
7554
+ this.exitListeners = [];
7555
+ if (this.process && !this.process.killed) {
7556
+ this.process.kill("SIGTERM");
7557
+ setTimeout(() => {
7558
+ if (this.process && !this.process.killed) {
7559
+ this.process.kill("SIGKILL");
7560
+ }
7561
+ }, 5000);
7562
+ }
7563
+ this.ready = false;
7564
+ if (this.processExitHandler) {
7565
+ process.off("exit", this.processExitHandler);
7566
+ this.processExitHandler = undefined;
7486
7567
  }
7487
- return { effective: parsed, status: "valid" };
7488
7568
  }
7489
- };
7490
-
7491
- // ../src/bootstrap/state.ts
7492
- function getInitialState() {
7493
- let resolvedCwd = "";
7494
- if (typeof process !== "undefined" && typeof process.cwd === "function") {
7495
- resolvedCwd = realpathSync2(cwd());
7569
+ isReady() {
7570
+ return this.ready;
7496
7571
  }
7497
- return {
7498
- originalCwd: resolvedCwd,
7499
- totalCostUSD: 0,
7500
- totalAPIDuration: 0,
7501
- totalAPIDurationWithoutRetries: 0,
7502
- totalToolDuration: 0,
7503
- startTime: Date.now(),
7504
- lastInteractionTime: Date.now(),
7505
- totalLinesAdded: 0,
7506
- totalLinesRemoved: 0,
7507
- hasUnknownModelCost: false,
7508
- cwd: resolvedCwd,
7509
- modelUsage: {},
7510
- mainLoopModelOverride: undefined,
7511
- initialMainLoopModel: null,
7512
- modelStrings: null,
7513
- isInteractive: false,
7514
- clientType: "cli",
7515
- sessionIngressToken: undefined,
7516
- oauthTokenFromFd: undefined,
7517
- apiKeyFromFd: undefined,
7518
- flagSettingsPath: undefined,
7519
- allowedSettingSources: [
7520
- "userSettings",
7521
- "projectSettings",
7522
- "localSettings",
7523
- "flagSettings",
7524
- "policySettings"
7525
- ],
7526
- meter: null,
7527
- sessionCounter: null,
7528
- locCounter: null,
7529
- prCounter: null,
7530
- commitCounter: null,
7531
- costCounter: null,
7532
- tokenCounter: null,
7533
- codeEditToolDecisionCounter: null,
7534
- activeTimeCounter: null,
7535
- sessionId: randomUUID2(),
7536
- loggerProvider: null,
7537
- eventLogger: null,
7538
- meterProvider: null,
7539
- tracerProvider: null,
7540
- agentColorMap: new Map,
7541
- agentColorIndex: 0,
7542
- envVarValidators: [bashMaxOutputLengthValidator, maxOutputTokensValidator],
7543
- lastAPIRequest: null,
7544
- inMemoryErrorLog: [],
7545
- inlinePlugins: [],
7546
- sessionBypassPermissionsMode: false,
7547
- hasExitedPlanMode: false,
7548
- needsPlanModeExitAttachment: false,
7549
- initJsonSchema: null,
7550
- registeredHooks: null,
7551
- planSlugCache: new Map
7552
- };
7553
- }
7554
- var STATE = getInitialState();
7555
- function getSessionId() {
7556
- return STATE.sessionId;
7557
- }
7558
-
7559
- // ../src/utils/bufferedWriter.ts
7560
- function createBufferedWriter({
7561
- writeFn,
7562
- flushIntervalMs = 1000,
7563
- maxBufferSize = 100,
7564
- immediateMode = false
7565
- }) {
7566
- let buffer = [];
7567
- let flushTimer = null;
7568
- function clearTimer() {
7569
- if (flushTimer) {
7570
- clearTimeout(flushTimer);
7571
- flushTimer = null;
7572
+ async* readMessages() {
7573
+ if (!this.processStdout) {
7574
+ throw new Error("ProcessTransport output stream not available");
7575
+ }
7576
+ const rl = createInterface({ input: this.processStdout });
7577
+ try {
7578
+ for await (const line of rl) {
7579
+ if (line.trim()) {
7580
+ const message = JSON.parse(line);
7581
+ yield message;
7582
+ }
7583
+ }
7584
+ await this.waitForExit();
7585
+ } catch (error) {
7586
+ throw error;
7587
+ } finally {
7588
+ rl.close();
7589
+ }
7590
+ }
7591
+ endInput() {
7592
+ if (this.processStdin) {
7593
+ this.processStdin.end();
7572
7594
  }
7573
7595
  }
7574
- function flush() {
7575
- if (buffer.length === 0)
7596
+ getInputStream() {
7597
+ return this.processStdin;
7598
+ }
7599
+ onExit(callback) {
7600
+ if (!this.process)
7601
+ return () => {};
7602
+ const handler = (code, signal) => {
7603
+ const error = this.getProcessExitError(code, signal);
7604
+ callback(error);
7605
+ };
7606
+ this.process.on("exit", handler);
7607
+ this.exitListeners.push({ callback, handler });
7608
+ return () => {
7609
+ if (this.process) {
7610
+ this.process.off("exit", handler);
7611
+ }
7612
+ const index = this.exitListeners.findIndex((l) => l.handler === handler);
7613
+ if (index !== -1) {
7614
+ this.exitListeners.splice(index, 1);
7615
+ }
7616
+ };
7617
+ }
7618
+ async waitForExit() {
7619
+ if (!this.process) {
7620
+ if (this.exitError) {
7621
+ throw this.exitError;
7622
+ }
7576
7623
  return;
7577
- writeFn(buffer.join(""));
7578
- buffer = [];
7579
- clearTimer();
7580
- }
7581
- function scheduleFlush() {
7582
- if (!flushTimer) {
7583
- flushTimer = setTimeout(flush, flushIntervalMs);
7584
7624
  }
7585
- }
7586
- return {
7587
- write(content) {
7588
- if (immediateMode) {
7589
- writeFn(content);
7590
- return;
7591
- }
7592
- buffer.push(content);
7593
- scheduleFlush();
7594
- if (buffer.length >= maxBufferSize) {
7595
- flush();
7625
+ if (this.process.exitCode !== null || this.process.killed) {
7626
+ if (this.exitError) {
7627
+ throw this.exitError;
7596
7628
  }
7597
- },
7598
- flush,
7599
- dispose() {
7600
- flush();
7629
+ return;
7601
7630
  }
7602
- };
7631
+ return new Promise((resolve, reject) => {
7632
+ const exitHandler = (code, signal) => {
7633
+ if (this.abortController.signal.aborted) {
7634
+ reject(new AbortError("Operation aborted"));
7635
+ return;
7636
+ }
7637
+ const error = this.getProcessExitError(code, signal);
7638
+ if (error) {
7639
+ reject(error);
7640
+ } else {
7641
+ resolve();
7642
+ }
7643
+ };
7644
+ this.process.once("exit", exitHandler);
7645
+ const errorHandler = (error) => {
7646
+ this.process.off("exit", exitHandler);
7647
+ reject(error);
7648
+ };
7649
+ this.process.once("error", errorHandler);
7650
+ this.process.once("exit", () => {
7651
+ this.process.off("error", errorHandler);
7652
+ });
7653
+ });
7654
+ }
7603
7655
  }
7604
-
7605
- // ../src/utils/cleanupRegistry.ts
7606
- var cleanupFunctions = new Set;
7607
- function registerCleanup(cleanupFn) {
7608
- cleanupFunctions.add(cleanupFn);
7609
- return () => cleanupFunctions.delete(cleanupFn);
7656
+ function isNativeBinary(executablePath) {
7657
+ const jsExtensions = [".js", ".mjs", ".tsx", ".ts", ".jsx"];
7658
+ return !jsExtensions.some((ext) => executablePath.endsWith(ext));
7610
7659
  }
7611
7660
 
7612
- // ../src/utils/debug.ts
7613
- var isDebugMode = memoize_default(() => {
7614
- return isEnvTruthy(process.env.DEBUG) || isEnvTruthy(process.env.DEBUG_SDK) || process.argv.includes("--debug") || process.argv.includes("-d") || isDebugToStdErr() || process.argv.some((arg) => arg.startsWith("--debug="));
7615
- });
7616
- var getDebugFilter = memoize_default(() => {
7617
- const debugArg = process.argv.find((arg) => arg.startsWith("--debug="));
7618
- if (!debugArg) {
7619
- return null;
7661
+ // ../src/utils/stream.ts
7662
+ class Stream {
7663
+ returned;
7664
+ queue = [];
7665
+ readResolve;
7666
+ readReject;
7667
+ isDone = false;
7668
+ hasError;
7669
+ started = false;
7670
+ constructor(returned) {
7671
+ this.returned = returned;
7620
7672
  }
7621
- const filterPattern = debugArg.substring("--debug=".length);
7622
- return parseDebugFilter(filterPattern);
7623
- });
7624
- var isDebugToStdErr = memoize_default(() => {
7625
- return process.argv.includes("--debug-to-stderr") || process.argv.includes("-d2e");
7626
- });
7627
- function shouldLogDebugMessage(message) {
7628
- if (false) {}
7629
- if (typeof process === "undefined" || typeof process.versions === "undefined" || typeof process.versions.node === "undefined") {
7630
- return false;
7673
+ [Symbol.asyncIterator]() {
7674
+ if (this.started) {
7675
+ throw new Error("Stream can only be iterated once");
7676
+ }
7677
+ this.started = true;
7678
+ return this;
7631
7679
  }
7632
- const filter = getDebugFilter();
7633
- return shouldShowDebugMessage(message, filter);
7634
- }
7635
- var hasFormattedOutput = false;
7636
- var debugWriter = null;
7637
- function getDebugWriter() {
7638
- if (!debugWriter) {
7639
- debugWriter = createBufferedWriter({
7640
- writeFn: (content) => {
7641
- const path = getDebugLogPath();
7642
- if (!getFsImplementation().existsSync(dirname(path))) {
7643
- getFsImplementation().mkdirSync(dirname(path));
7644
- }
7645
- getFsImplementation().appendFileSync(path, content);
7646
- updateLatestDebugLogSymlink();
7647
- },
7648
- flushIntervalMs: 1000,
7649
- maxBufferSize: 100,
7650
- immediateMode: isDebugMode()
7680
+ next() {
7681
+ if (this.queue.length > 0) {
7682
+ return Promise.resolve({
7683
+ done: false,
7684
+ value: this.queue.shift()
7685
+ });
7686
+ }
7687
+ if (this.isDone) {
7688
+ return Promise.resolve({ done: true, value: undefined });
7689
+ }
7690
+ if (this.hasError) {
7691
+ return Promise.reject(this.hasError);
7692
+ }
7693
+ return new Promise((resolve, reject) => {
7694
+ this.readResolve = resolve;
7695
+ this.readReject = reject;
7651
7696
  });
7652
- registerCleanup(async () => debugWriter?.dispose());
7653
7697
  }
7654
- return debugWriter;
7655
- }
7656
- function logForDebugging(message, { level } = {
7657
- level: "debug"
7658
- }) {
7659
- if (!shouldLogDebugMessage(message)) {
7660
- return;
7698
+ enqueue(value) {
7699
+ if (this.readResolve) {
7700
+ const resolve = this.readResolve;
7701
+ this.readResolve = undefined;
7702
+ this.readReject = undefined;
7703
+ resolve({ done: false, value });
7704
+ } else {
7705
+ this.queue.push(value);
7706
+ }
7661
7707
  }
7662
- if (hasFormattedOutput && message.includes(`
7663
- `)) {
7664
- message = JSON.stringify(message);
7708
+ done() {
7709
+ this.isDone = true;
7710
+ if (this.readResolve) {
7711
+ const resolve = this.readResolve;
7712
+ this.readResolve = undefined;
7713
+ this.readReject = undefined;
7714
+ resolve({ done: true, value: undefined });
7715
+ }
7665
7716
  }
7666
- const timestamp = new Date().toISOString();
7667
- const output = `${timestamp} [${level.toUpperCase()}] ${message.trim()}
7668
- `;
7669
- if (isDebugToStdErr()) {
7670
- writeToStderr(output);
7671
- return;
7717
+ error(error) {
7718
+ this.hasError = error;
7719
+ if (this.readReject) {
7720
+ const reject = this.readReject;
7721
+ this.readResolve = undefined;
7722
+ this.readReject = undefined;
7723
+ reject(error);
7724
+ }
7725
+ }
7726
+ return() {
7727
+ this.isDone = true;
7728
+ if (this.returned) {
7729
+ this.returned();
7730
+ }
7731
+ return Promise.resolve({ done: true, value: undefined });
7672
7732
  }
7673
- getDebugWriter().write(output);
7674
- }
7675
- function getDebugLogPath() {
7676
- return process.env.CLAUDE_CODE_DEBUG_LOGS_DIR ?? join3(getClaudeConfigHomeDir(), "debug", `${getSessionId()}.txt`);
7677
7733
  }
7678
- var updateLatestDebugLogSymlink = memoize_default(() => {
7679
- try {
7680
- const debugLogPath = getDebugLogPath();
7681
- const debugLogsDir = dirname(debugLogPath);
7682
- const latestSymlinkPath = join3(debugLogsDir, "latest");
7683
- if (!getFsImplementation().existsSync(debugLogsDir)) {
7684
- getFsImplementation().mkdirSync(debugLogsDir);
7734
+
7735
+ // ../src/services/mcp/SdkControlTransport.ts
7736
+ class SdkControlServerTransport {
7737
+ sendMcpMessage;
7738
+ isClosed = false;
7739
+ constructor(sendMcpMessage) {
7740
+ this.sendMcpMessage = sendMcpMessage;
7741
+ }
7742
+ onclose;
7743
+ onerror;
7744
+ onmessage;
7745
+ async start() {}
7746
+ async send(message) {
7747
+ if (this.isClosed) {
7748
+ throw new Error("Transport is closed");
7685
7749
  }
7686
- if (getFsImplementation().existsSync(latestSymlinkPath)) {
7687
- try {
7688
- getFsImplementation().unlinkSync(latestSymlinkPath);
7689
- } catch {}
7750
+ this.sendMcpMessage(message);
7751
+ }
7752
+ async close() {
7753
+ if (this.isClosed) {
7754
+ return;
7690
7755
  }
7691
- getFsImplementation().symlinkSync(debugLogPath, latestSymlinkPath);
7692
- } catch {}
7693
- });
7756
+ this.isClosed = true;
7757
+ this.onclose?.();
7758
+ }
7759
+ }
7694
7760
 
7695
7761
  // ../src/core/Query.ts
7696
7762
  import { randomUUID as randomUUID3 } from "crypto";
7697
7763
 
7698
7764
  class Query {
7699
7765
  transport;
7700
- isSingleUserTurn;
7701
7766
  canUseTool;
7702
7767
  hooks;
7703
7768
  abortController;
@@ -7713,18 +7778,23 @@ class Query {
7713
7778
  nextCallbackId = 0;
7714
7779
  sdkMcpTransports = new Map;
7715
7780
  pendingMcpResponses = new Map;
7716
- firstResultReceivedPromise;
7717
- firstResultReceivedResolve;
7781
+ lastActivityTime = Date.now();
7782
+ userInputEndedResolve;
7718
7783
  streamCloseTimeout;
7719
- constructor(transport, isSingleUserTurn, canUseTool, hooks, abortController, sdkMcpServers = new Map, jsonSchema, initConfig) {
7784
+ resetLastActivityTime() {
7785
+ this.lastActivityTime = Date.now();
7786
+ }
7787
+ hasBidirectionalNeeds() {
7788
+ return this.sdkMcpTransports.size > 0 || this.hooks !== undefined && Object.keys(this.hooks).length > 0 || this.canUseTool !== undefined;
7789
+ }
7790
+ constructor(transport, _isSingleUserTurn, canUseTool, hooks, abortController, sdkMcpServers = new Map, jsonSchema, initConfig) {
7720
7791
  this.transport = transport;
7721
- this.isSingleUserTurn = isSingleUserTurn;
7722
7792
  this.canUseTool = canUseTool;
7723
7793
  this.hooks = hooks;
7724
7794
  this.abortController = abortController;
7725
7795
  this.jsonSchema = jsonSchema;
7726
7796
  this.initConfig = initConfig;
7727
- this.streamCloseTimeout = 60000;
7797
+ this.streamCloseTimeout = 5000;
7728
7798
  if (typeof process !== "undefined" && process.env?.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT) {
7729
7799
  this.streamCloseTimeout = parseInt(process.env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT);
7730
7800
  }
@@ -7734,9 +7804,6 @@ class Query {
7734
7804
  server.connect(sdkTransport);
7735
7805
  }
7736
7806
  this.sdkMessages = this.readSdkMessages();
7737
- this.firstResultReceivedPromise = new Promise((resolve) => {
7738
- this.firstResultReceivedResolve = resolve;
7739
- });
7740
7807
  this.readMessages();
7741
7808
  this.initialization = this.initialize();
7742
7809
  this.initialization.catch(() => {});
@@ -7785,6 +7852,7 @@ class Query {
7785
7852
  async readMessages() {
7786
7853
  try {
7787
7854
  for await (const message of this.transport.readMessages()) {
7855
+ this.resetLastActivityTime();
7788
7856
  if (message.type === "control_response") {
7789
7857
  const handler = this.pendingControlResponses.get(message.response.request_id);
7790
7858
  if (handler) {
@@ -7800,19 +7868,17 @@ class Query {
7800
7868
  } else if (message.type === "keep_alive") {
7801
7869
  continue;
7802
7870
  }
7803
- if (message.type === "result") {
7804
- if (this.firstResultReceivedResolve) {
7805
- this.firstResultReceivedResolve();
7806
- }
7807
- if (this.isSingleUserTurn) {
7808
- this.transport.endInput();
7809
- }
7810
- }
7811
7871
  this.inputStream.enqueue(message);
7812
7872
  }
7873
+ if (this.userInputEndedResolve) {
7874
+ this.userInputEndedResolve();
7875
+ }
7813
7876
  this.inputStream.done();
7814
7877
  this.cleanup();
7815
7878
  } catch (error) {
7879
+ if (this.userInputEndedResolve) {
7880
+ this.userInputEndedResolve();
7881
+ }
7816
7882
  this.inputStream.error(error);
7817
7883
  this.cleanup(error);
7818
7884
  }
@@ -7955,9 +8021,9 @@ class Query {
7955
8021
  max_thinking_tokens: maxThinkingTokens
7956
8022
  });
7957
8023
  }
7958
- async rewindCode(userMessageId) {
8024
+ async rewindFiles(userMessageId) {
7959
8025
  await this.request({
7960
- subtype: "rewind_code",
8026
+ subtype: "rewind_files",
7961
8027
  user_message_id: userMessageId
7962
8028
  });
7963
8029
  }
@@ -8008,7 +8074,6 @@ class Query {
8008
8074
  }
8009
8075
  async streamInput(stream) {
8010
8076
  logForDebugging(`[Query.streamInput] Starting to process input stream`);
8011
- logForDebugging(`[Query.streamInput] this.sdkMcpTransports.size = ${this.sdkMcpTransports.size}`);
8012
8077
  try {
8013
8078
  let messageCount = 0;
8014
8079
  for await (const message of stream) {
@@ -8020,28 +8085,9 @@ class Query {
8020
8085
  `));
8021
8086
  }
8022
8087
  logForDebugging(`[Query.streamInput] Finished processing ${messageCount} messages from input stream`);
8023
- logForDebugging(`[Query.streamInput] About to check MCP servers. this.sdkMcpTransports.size = ${this.sdkMcpTransports.size}`);
8024
- const hasHooks = this.hooks && Object.keys(this.hooks).length > 0;
8025
- if ((this.sdkMcpTransports.size > 0 || hasHooks) && this.firstResultReceivedPromise) {
8026
- logForDebugging(`[Query.streamInput] Entering Promise.race to wait for result`);
8027
- let timeoutId;
8028
- await Promise.race([
8029
- this.firstResultReceivedPromise.then(() => {
8030
- logForDebugging(`[Query.streamInput] Received first result, closing input stream`);
8031
- if (timeoutId) {
8032
- clearTimeout(timeoutId);
8033
- }
8034
- }),
8035
- new Promise((resolve) => {
8036
- timeoutId = setTimeout(() => {
8037
- logForDebugging(`[Query.streamInput] Timed out waiting for first result, closing input stream`);
8038
- resolve();
8039
- }, this.streamCloseTimeout);
8040
- })
8041
- ]);
8042
- if (timeoutId) {
8043
- clearTimeout(timeoutId);
8044
- }
8088
+ if (this.hasBidirectionalNeeds()) {
8089
+ logForDebugging(`[Query.streamInput] Has bidirectional needs, waiting for inactivity`);
8090
+ await this.waitForInactivity();
8045
8091
  }
8046
8092
  logForDebugging(`[Query] Calling transport.endInput() to close stdin to CLI process`);
8047
8093
  this.transport.endInput();
@@ -8051,6 +8097,43 @@ class Query {
8051
8097
  }
8052
8098
  }
8053
8099
  }
8100
+ async handleSingleTurnInputComplete() {
8101
+ if (this.hasBidirectionalNeeds()) {
8102
+ logForDebugging(`[Query.handleSingleTurnInputComplete] Has bidirectional needs, waiting for inactivity`);
8103
+ await this.waitForInactivity();
8104
+ }
8105
+ logForDebugging(`[Query.handleSingleTurnInputComplete] Calling transport.endInput()`);
8106
+ this.transport.endInput();
8107
+ }
8108
+ async waitForInactivity() {
8109
+ logForDebugging(`[Query.waitForInactivity] Waiting for inactivity (timeout: ${this.streamCloseTimeout}ms)`);
8110
+ return new Promise((resolve) => {
8111
+ this.userInputEndedResolve = resolve;
8112
+ if (this.abortController?.signal.aborted) {
8113
+ resolve();
8114
+ return;
8115
+ }
8116
+ this.abortController?.signal.addEventListener("abort", () => resolve(), {
8117
+ once: true
8118
+ });
8119
+ const checkInactivity = () => {
8120
+ if (this.abortController?.signal.aborted) {
8121
+ resolve();
8122
+ return;
8123
+ }
8124
+ const elapsed = Date.now() - this.lastActivityTime;
8125
+ if (elapsed >= this.streamCloseTimeout) {
8126
+ logForDebugging(`[Query.waitForInactivity] Inactivity timeout reached (${elapsed}ms elapsed). ` + `Closing stdin. If your tools or hooks need more time, set CLAUDE_CODE_STREAM_CLOSE_TIMEOUT ` + `to a higher value (current: ${this.streamCloseTimeout}ms).`);
8127
+ resolve();
8128
+ } else {
8129
+ const remaining = this.streamCloseTimeout - elapsed;
8130
+ logForDebugging(`[Query.waitForInactivity] Still active, checking again in ${remaining}ms`);
8131
+ setTimeout(checkInactivity, remaining);
8132
+ }
8133
+ };
8134
+ checkInactivity();
8135
+ });
8136
+ }
8054
8137
  handleHookCallbacks(callbackId, input, toolUseID, abortSignal) {
8055
8138
  const callback = this.hookCallbacks.get(callbackId);
8056
8139
  if (!callback) {
@@ -8121,7 +8204,17 @@ class SessionImpl {
8121
8204
  query;
8122
8205
  queryIterator = null;
8123
8206
  abortController;
8207
+ _sessionId = null;
8208
+ get sessionId() {
8209
+ if (this._sessionId === null) {
8210
+ throw new Error("Session ID not available until after receiving messages");
8211
+ }
8212
+ return this._sessionId;
8213
+ }
8124
8214
  constructor(options) {
8215
+ if (options.resume) {
8216
+ this._sessionId = options.resume;
8217
+ }
8125
8218
  this.inputStream = new Stream;
8126
8219
  let pathToClaudeCodeExecutable = options.pathToClaudeCodeExecutable;
8127
8220
  if (!pathToClaudeCodeExecutable) {
@@ -8129,7 +8222,7 @@ class SessionImpl {
8129
8222
  const dirname2 = join4(filename, "..");
8130
8223
  pathToClaudeCodeExecutable = join4(dirname2, "cli.js");
8131
8224
  }
8132
- const processEnv = { ...process.env };
8225
+ const processEnv = { ...options.env ?? process.env };
8133
8226
  if (!processEnv.CLAUDE_CODE_ENTRYPOINT) {
8134
8227
  processEnv.CLAUDE_CODE_ENTRYPOINT = "sdk-ts";
8135
8228
  }
@@ -8188,6 +8281,9 @@ class SessionImpl {
8188
8281
  if (done) {
8189
8282
  return;
8190
8283
  }
8284
+ if (value.type === "system" && value.subtype === "init") {
8285
+ this._sessionId = value.session_id;
8286
+ }
8191
8287
  yield value;
8192
8288
  if (value.type === "result") {
8193
8289
  return;
@@ -15113,7 +15209,7 @@ function query({
15113
15209
  const dirname2 = join5(filename, "..");
15114
15210
  pathToClaudeCodeExecutable = join5(dirname2, "cli.js");
15115
15211
  }
15116
- process.env.CLAUDE_AGENT_SDK_VERSION = "0.1.62";
15212
+ process.env.CLAUDE_AGENT_SDK_VERSION = "0.1.65";
15117
15213
  const {
15118
15214
  abortController = createAbortController(),
15119
15215
  additionalDirectories = [],
@@ -15130,9 +15226,11 @@ function query({
15130
15226
  executableArgs = [],
15131
15227
  extraArgs = {},
15132
15228
  fallbackModel,
15229
+ enableFileCheckpointing,
15133
15230
  forkSession,
15134
15231
  hooks,
15135
15232
  includePartialMessages,
15233
+ persistSession,
15136
15234
  maxThinkingTokens,
15137
15235
  maxTurns,
15138
15236
  maxBudgetUsd,
@@ -15156,6 +15254,9 @@ function query({
15156
15254
  if (!processEnv.CLAUDE_CODE_ENTRYPOINT) {
15157
15255
  processEnv.CLAUDE_CODE_ENTRYPOINT = "sdk-ts";
15158
15256
  }
15257
+ if (enableFileCheckpointing) {
15258
+ processEnv.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING = "true";
15259
+ }
15159
15260
  if (!pathToClaudeCodeExecutable) {
15160
15261
  throw new Error("pathToClaudeCodeExecutable is required");
15161
15262
  }
@@ -15208,8 +15309,10 @@ function query({
15208
15309
  canUseTool: !!canUseTool,
15209
15310
  hooks: !!hooks,
15210
15311
  includePartialMessages,
15312
+ persistSession,
15211
15313
  plugins,
15212
- sandbox
15314
+ sandbox,
15315
+ spawnClaudeCodeProcess: rest.spawnClaudeCodeProcess
15213
15316
  });
15214
15317
  const initConfig = {
15215
15318
  systemPrompt: customSystemPrompt,
@@ -15228,6 +15331,7 @@ function query({
15228
15331
  parent_tool_use_id: null
15229
15332
  }) + `
15230
15333
  `);
15334
+ queryInstance.handleSingleTurnInputComplete();
15231
15335
  } else {
15232
15336
  queryInstance.streamInput(prompt);
15233
15337
  }