@opencow-ai/opencow-agent-sdk 0.4.18 → 0.4.20

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/dist/cli.mjs CHANGED
@@ -5556,7 +5556,7 @@ function classifyAxiosError(e) {
5556
5556
  }
5557
5557
  return { kind: "http", status, message };
5558
5558
  }
5559
- var ClaudeError, MalformedCommandError, AbortError, ConfigParseError, ShellError, TeleportOperationError, TelemetrySafeError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS;
5559
+ var ClaudeError, MalformedCommandError, AbortError, ToolContinuationStopError, ConfigParseError, ShellError, TeleportOperationError, TelemetrySafeError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS;
5560
5560
  var init_errors2 = __esm(() => {
5561
5561
  init_canonical();
5562
5562
  ClaudeError = class ClaudeError extends Error {
@@ -5573,6 +5573,12 @@ var init_errors2 = __esm(() => {
5573
5573
  this.name = "AbortError";
5574
5574
  }
5575
5575
  };
5576
+ ToolContinuationStopError = class ToolContinuationStopError extends Error {
5577
+ constructor(message, options) {
5578
+ super(message, options);
5579
+ this.name = "ToolContinuationStopError";
5580
+ }
5581
+ };
5576
5582
  ConfigParseError = class ConfigParseError extends Error {
5577
5583
  filePath;
5578
5584
  defaultConfig;
@@ -32091,6 +32097,21 @@ import { createHash } from "crypto";
32091
32097
  import { readFileSync as readFileSync5, realpathSync as realpathSync2, statSync as statSync4 } from "fs";
32092
32098
  import { open as open2, readFile as readFile3, realpath as realpath3, stat as stat4 } from "fs/promises";
32093
32099
  import { basename as basename3, dirname as dirname7, join as join12, resolve as resolve6, sep as sep4 } from "path";
32100
+ function hasValidGitMarker(gitPath) {
32101
+ const markerStat = statSync4(gitPath);
32102
+ if (markerStat.isDirectory()) {
32103
+ return statSync4(join12(gitPath, "HEAD")).isFile();
32104
+ }
32105
+ if (!markerStat.isFile()) {
32106
+ return false;
32107
+ }
32108
+ const marker = readFileSync5(gitPath, "utf-8").trim();
32109
+ if (!marker.startsWith("gitdir:")) {
32110
+ return false;
32111
+ }
32112
+ const gitDir = resolve6(dirname7(gitPath), marker.slice("gitdir:".length).trim());
32113
+ return statSync4(join12(gitDir, "HEAD")).isFile();
32114
+ }
32094
32115
  function createFindGitRoot() {
32095
32116
  function wrapper(startPath) {
32096
32117
  const result = findGitRootImpl(startPath);
@@ -32512,8 +32533,7 @@ var init_git = __esm(() => {
32512
32533
  try {
32513
32534
  const gitPath = join12(current, ".git");
32514
32535
  statCount++;
32515
- const stat5 = statSync4(gitPath);
32516
- if (stat5.isDirectory() || stat5.isFile()) {
32536
+ if (hasValidGitMarker(gitPath)) {
32517
32537
  logForDiagnosticsNoPII("info", "find_git_root_completed", {
32518
32538
  duration_ms: Date.now() - startTime,
32519
32539
  stat_count: statCount,
@@ -32531,8 +32551,7 @@ var init_git = __esm(() => {
32531
32551
  try {
32532
32552
  const gitPath = join12(root2, ".git");
32533
32553
  statCount++;
32534
- const stat5 = statSync4(gitPath);
32535
- if (stat5.isDirectory() || stat5.isFile()) {
32554
+ if (hasValidGitMarker(gitPath)) {
32536
32555
  logForDiagnosticsNoPII("info", "find_git_root_completed", {
32537
32556
  duration_ms: Date.now() - startTime,
32538
32557
  stat_count: statCount,
@@ -94620,7 +94639,7 @@ function printStartupScreen() {
94620
94639
  const sLen = ` ● ${sL} Ready — type /help to begin`.length;
94621
94640
  out.push(boxRow(sRow, W2, sLen));
94622
94641
  out.push(`${rgb(...BORDER)}╚${"═".repeat(W2 - 2)}╝${RESET}`);
94623
- out.push(` ${DIM}${rgb(...DIMCOL)}opencow ${RESET}${rgb(...ACCENT)}v${"0.4.18"}${RESET}`);
94642
+ out.push(` ${DIM}${rgb(...DIMCOL)}opencow ${RESET}${rgb(...ACCENT)}v${"0.4.20"}${RESET}`);
94624
94643
  out.push("");
94625
94644
  process.stdout.write(out.join(`
94626
94645
  `) + `
@@ -241530,6 +241549,9 @@ async function checkPermissionsAndCallTool(tool, toolUseID, input, toolUseContex
241530
241549
  logError(hookError);
241531
241550
  }
241532
241551
  }
241552
+ if (toolUseContext.abortController.signal.aborted) {
241553
+ throw new AbortError;
241554
+ }
241533
241555
  try {
241534
241556
  const result = await tool.call(callInput, {
241535
241557
  ...toolUseContext,
@@ -241830,19 +241852,24 @@ async function checkPermissionsAndCallTool(tool, toolUseID, input, toolUseContex
241830
241852
  }
241831
241853
  return [
241832
241854
  {
241833
- message: createUserMessage({
241834
- content: [
241835
- {
241836
- type: "tool_result",
241837
- content,
241838
- is_error: true,
241839
- tool_use_id: toolUseID
241840
- }
241841
- ],
241842
- toolUseResult: `Error: ${content}`,
241843
- mcpMeta: toolUseContext.agentId ? undefined : error41 instanceof McpToolCallError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS ? error41.mcpMeta : undefined,
241844
- sourceToolAssistantUUID: assistantMessage.uuid
241845
- })
241855
+ message: {
241856
+ ...createUserMessage({
241857
+ content: [
241858
+ {
241859
+ type: "tool_result",
241860
+ content,
241861
+ is_error: true,
241862
+ tool_use_id: toolUseID
241863
+ }
241864
+ ],
241865
+ toolUseResult: `Error: ${content}`,
241866
+ mcpMeta: toolUseContext.agentId ? undefined : error41 instanceof McpToolCallError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS ? error41.mcpMeta : undefined,
241867
+ sourceToolAssistantUUID: assistantMessage.uuid
241868
+ }),
241869
+ ...error41 instanceof ToolContinuationStopError && {
241870
+ preventContinuation: true
241871
+ }
241872
+ }
241846
241873
  },
241847
241874
  ...hookMessages
241848
241875
  ];
@@ -243670,6 +243697,9 @@ function* yieldMissingToolResultBlocks(assistantMessages, errorMessage2) {
243670
243697
  function isWithheldMaxOutputTokens(msg) {
243671
243698
  return msg?.type === "assistant" && msg.apiError === "max_output_tokens";
243672
243699
  }
243700
+ function messagePreventsContinuation(message) {
243701
+ return message.type === "user" && message.preventContinuation === true || message.type === "attachment" && message.attachment.type === "hook_stopped_continuation";
243702
+ }
243673
243703
  async function* query(params) {
243674
243704
  const consumedCommandUuids = [];
243675
243705
  const terminal = yield* queryLoop(params, consumedCommandUuids);
@@ -243837,6 +243867,7 @@ async function* queryLoop(params, consumedCommandUuids) {
243837
243867
  const toolResults = [];
243838
243868
  const toolUseBlocks = [];
243839
243869
  let needsFollowUp = false;
243870
+ let shouldPreventContinuation = false;
243840
243871
  queryCheckpoint("query_setup_start");
243841
243872
  const useStreamingToolExecution = config2.gates.streamingToolExecution;
243842
243873
  let streamingToolExecutor = useStreamingToolExecution ? new StreamingToolExecutor(toolUseContext.options.tools, canUseTool, toolUseContext) : null;
@@ -243934,6 +243965,7 @@ async function* queryLoop(params, consumedCommandUuids) {
243934
243965
  toolResults.length = 0;
243935
243966
  toolUseBlocks.length = 0;
243936
243967
  needsFollowUp = false;
243968
+ shouldPreventContinuation = false;
243937
243969
  if (streamingToolExecutor) {
243938
243970
  streamingToolExecutor.discard();
243939
243971
  streamingToolExecutor = new StreamingToolExecutor(toolUseContext.options.tools, canUseTool, toolUseContext);
@@ -243996,6 +244028,9 @@ async function* queryLoop(params, consumedCommandUuids) {
243996
244028
  for (const result of streamingToolExecutor.getCompletedResults()) {
243997
244029
  if (result.message) {
243998
244030
  yield result.message;
244031
+ if (messagePreventsContinuation(result.message)) {
244032
+ shouldPreventContinuation = true;
244033
+ }
243999
244034
  toolResults.push(...normalizeMessagesForAPI([result.message], toolUseContext.options.tools).filter((_) => _.type === "user"));
244000
244035
  }
244001
244036
  }
@@ -244012,6 +244047,7 @@ async function* queryLoop(params, consumedCommandUuids) {
244012
244047
  toolResults.length = 0;
244013
244048
  toolUseBlocks.length = 0;
244014
244049
  needsFollowUp = false;
244050
+ shouldPreventContinuation = false;
244015
244051
  if (streamingToolExecutor) {
244016
244052
  streamingToolExecutor.discard();
244017
244053
  streamingToolExecutor = new StreamingToolExecutor(toolUseContext.options.tools, canUseTool, toolUseContext);
@@ -244209,7 +244245,6 @@ async function* queryLoop(params, consumedCommandUuids) {
244209
244245
  if (false) {}
244210
244246
  return { reason: "completed" };
244211
244247
  }
244212
- let shouldPreventContinuation = false;
244213
244248
  let updatedToolRuntimeContext = toolUseContext;
244214
244249
  queryCheckpoint("query_tool_execution_start");
244215
244250
  if (streamingToolExecutor) {
@@ -244229,7 +244264,7 @@ async function* queryLoop(params, consumedCommandUuids) {
244229
244264
  for await (const update of toolUpdates) {
244230
244265
  if (update.message) {
244231
244266
  yield update.message;
244232
- if (update.message.type === "attachment" && update.message.attachment.type === "hook_stopped_continuation") {
244267
+ if (messagePreventsContinuation(update.message)) {
244233
244268
  shouldPreventContinuation = true;
244234
244269
  }
244235
244270
  toolResults.push(...normalizeMessagesForAPI([update.message], toolUseContext.options.tools).filter((_) => _.type === "user"));
@@ -244243,7 +244278,7 @@ async function* queryLoop(params, consumedCommandUuids) {
244243
244278
  }
244244
244279
  queryCheckpoint("query_tool_execution_end");
244245
244280
  let nextPendingToolUseSummary;
244246
- if (config2.gates.emitToolUseSummaries && toolUseBlocks.length > 0 && !toolUseContext.abortController.signal.aborted && !toolUseContext.agentId) {
244281
+ if (!shouldPreventContinuation && config2.gates.emitToolUseSummaries && toolUseBlocks.length > 0 && !toolUseContext.abortController.signal.aborted && !toolUseContext.agentId) {
244247
244282
  const lastAssistantMessage = assistantMessages.at(-1);
244248
244283
  let lastAssistantText;
244249
244284
  if (lastAssistantMessage) {
@@ -244610,7 +244645,7 @@ function getAnthropicEnvMetadata() {
244610
244645
  function getBuildAgeMinutes() {
244611
244646
  if (false)
244612
244647
  ;
244613
- const buildTime = new Date("2026-07-16T03:27:09.740Z").getTime();
244648
+ const buildTime = new Date("2026-07-21T10:56:17.312Z").getTime();
244614
244649
  if (isNaN(buildTime))
244615
244650
  return;
244616
244651
  return Math.floor((Date.now() - buildTime) / 60000);
@@ -247203,18 +247238,74 @@ var init_registerFrontmatterHooks = __esm(() => {
247203
247238
  });
247204
247239
 
247205
247240
  // src/session/backgroundAbortRegistry.ts
247206
- function registerBackgroundAgentAbort(agentId, controller) {
247207
- runs.set(agentId, { controller, stopFired: false });
247241
+ function registerBackgroundAgentAbort(agentId, actions) {
247242
+ if (runs.has(agentId)) {
247243
+ throw new Error(`Background agent '${agentId}' is already registered`);
247244
+ }
247245
+ let resolveSettled = () => {};
247246
+ const settled = new Promise((resolve18) => {
247247
+ resolveSettled = resolve18;
247248
+ });
247249
+ runs.set(agentId, {
247250
+ ...actions,
247251
+ stopFired: false,
247252
+ stopPromise: undefined,
247253
+ settled,
247254
+ resolveSettled,
247255
+ shellsStopped: false
247256
+ });
247208
247257
  }
247209
247258
  function unregisterBackgroundAgentAbort(agentId) {
247259
+ const run = runs.get(agentId);
247260
+ if (!run)
247261
+ return;
247210
247262
  runs.delete(agentId);
247263
+ run.resolveSettled();
247211
247264
  }
247212
247265
  function abortBackgroundAgentById(agentId) {
247213
247266
  const run = runs.get(agentId);
247214
247267
  if (!run)
247215
- return false;
247216
- run.controller.abort();
247217
- return true;
247268
+ return Promise.resolve();
247269
+ if (!run.stopPromise) {
247270
+ run.stopPromise = (async () => {
247271
+ const errors4 = [];
247272
+ let abortFailed = false;
247273
+ try {
247274
+ run.abort();
247275
+ } catch (error41) {
247276
+ abortFailed = true;
247277
+ errors4.push(error41);
247278
+ }
247279
+ try {
247280
+ stopBackgroundAgentShells(run);
247281
+ } catch (error41) {
247282
+ errors4.push(error41);
247283
+ }
247284
+ if (abortFailed) {
247285
+ throw new AggregateError(errors4, `Failed to stop background agent '${agentId}'`);
247286
+ }
247287
+ await run.settled;
247288
+ if (errors4.length > 0) {
247289
+ throw new AggregateError(errors4, `Failed to stop background agent '${agentId}'`);
247290
+ }
247291
+ })();
247292
+ }
247293
+ return run.stopPromise;
247294
+ }
247295
+ function hasBackgroundAgent(agentId) {
247296
+ return runs.has(agentId);
247297
+ }
247298
+ function stopBackgroundAgentShellsById(agentId) {
247299
+ const run = runs.get(agentId);
247300
+ if (run) {
247301
+ stopBackgroundAgentShells(run);
247302
+ }
247303
+ }
247304
+ function stopBackgroundAgentShells(run) {
247305
+ if (run.shellsStopped)
247306
+ return;
247307
+ run.shellsStopped = true;
247308
+ run.stopShells();
247218
247309
  }
247219
247310
  function markSubagentStopFired(agentId) {
247220
247311
  const run = runs.get(agentId);
@@ -248069,6 +248160,23 @@ var init_formatting = __esm(() => {
248069
248160
  init_xml();
248070
248161
  });
248071
248162
 
248163
+ // src/capabilities/tools/AgentTool/agentLifecycleFinalizer.ts
248164
+ function createAgentLifecycleFinalizer(onCleanupError) {
248165
+ let finalization;
248166
+ return (cleanups) => {
248167
+ finalization ??= (async () => {
248168
+ for (const cleanup of cleanups) {
248169
+ try {
248170
+ await cleanup();
248171
+ } catch (error41) {
248172
+ onCleanupError(error41);
248173
+ }
248174
+ }
248175
+ })();
248176
+ return finalization;
248177
+ };
248178
+ }
248179
+
248072
248180
  // src/capabilities/tools/AgentTool/runAgent.ts
248073
248181
  import { randomUUID as randomUUID10 } from "crypto";
248074
248182
  async function initializeAgentMcpServers(agentDefinition, parentClients) {
@@ -248091,44 +248199,6 @@ async function initializeAgentMcpServers(agentDefinition, parentClients) {
248091
248199
  const agentClients = [];
248092
248200
  const newlyCreatedClients = [];
248093
248201
  const agentTools = [];
248094
- for (const spec of agentDefinition.mcpServers) {
248095
- let config2 = null;
248096
- let name;
248097
- let isNewlyCreated = false;
248098
- if (typeof spec === "string") {
248099
- name = spec;
248100
- config2 = getMcpConfigByName(spec);
248101
- if (!config2) {
248102
- logForDebugging2(`[Agent: ${agentDefinition.agentType}] MCP server not found: ${spec}`, { level: "warn" });
248103
- continue;
248104
- }
248105
- } else {
248106
- const entries = Object.entries(spec);
248107
- if (entries.length !== 1) {
248108
- logForDebugging2(`[Agent: ${agentDefinition.agentType}] Invalid MCP server spec: expected exactly one key`, { level: "warn" });
248109
- continue;
248110
- }
248111
- const [serverName, serverConfig] = entries[0];
248112
- name = serverName;
248113
- config2 = {
248114
- ...serverConfig,
248115
- scope: "dynamic"
248116
- };
248117
- isNewlyCreated = true;
248118
- }
248119
- const client = await connectToServer(name, config2);
248120
- agentClients.push(client);
248121
- if (isNewlyCreated) {
248122
- newlyCreatedClients.push(client);
248123
- }
248124
- if (client.type === "connected") {
248125
- const tools = await fetchToolsForClient(client);
248126
- agentTools.push(...tools);
248127
- logForDebugging2(`[Agent: ${agentDefinition.agentType}] Connected to MCP server '${name}' with ${tools.length} tools`);
248128
- } else {
248129
- logForDebugging2(`[Agent: ${agentDefinition.agentType}] Failed to connect to MCP server '${name}': ${client.type}`, { level: "warn" });
248130
- }
248131
- }
248132
248202
  const cleanup = async () => {
248133
248203
  for (const client of newlyCreatedClients) {
248134
248204
  if (client.type === "connected") {
@@ -248140,6 +248210,49 @@ async function initializeAgentMcpServers(agentDefinition, parentClients) {
248140
248210
  }
248141
248211
  }
248142
248212
  };
248213
+ try {
248214
+ for (const spec of agentDefinition.mcpServers) {
248215
+ let config2 = null;
248216
+ let name;
248217
+ let isNewlyCreated = false;
248218
+ if (typeof spec === "string") {
248219
+ name = spec;
248220
+ config2 = getMcpConfigByName(spec);
248221
+ if (!config2) {
248222
+ logForDebugging2(`[Agent: ${agentDefinition.agentType}] MCP server not found: ${spec}`, { level: "warn" });
248223
+ continue;
248224
+ }
248225
+ } else {
248226
+ const entries = Object.entries(spec);
248227
+ if (entries.length !== 1) {
248228
+ logForDebugging2(`[Agent: ${agentDefinition.agentType}] Invalid MCP server spec: expected exactly one key`, { level: "warn" });
248229
+ continue;
248230
+ }
248231
+ const [serverName, serverConfig] = entries[0];
248232
+ name = serverName;
248233
+ config2 = {
248234
+ ...serverConfig,
248235
+ scope: "dynamic"
248236
+ };
248237
+ isNewlyCreated = true;
248238
+ }
248239
+ const client = await connectToServer(name, config2);
248240
+ agentClients.push(client);
248241
+ if (isNewlyCreated) {
248242
+ newlyCreatedClients.push(client);
248243
+ }
248244
+ if (client.type === "connected") {
248245
+ const tools = await fetchToolsForClient(client);
248246
+ agentTools.push(...tools);
248247
+ logForDebugging2(`[Agent: ${agentDefinition.agentType}] Connected to MCP server '${name}' with ${tools.length} tools`);
248248
+ } else {
248249
+ logForDebugging2(`[Agent: ${agentDefinition.agentType}] Failed to connect to MCP server '${name}': ${client.type}`, { level: "warn" });
248250
+ }
248251
+ }
248252
+ } catch (error41) {
248253
+ await cleanup();
248254
+ throw error41;
248255
+ }
248143
248256
  return {
248144
248257
  clients: [...parentClients, ...agentClients],
248145
248258
  tools: agentTools,
@@ -248292,121 +248405,140 @@ async function* runAgent({
248292
248405
  const additionalWorkingDirectories = Array.from(appState.toolPermissionContext.additionalWorkingDirectories.keys());
248293
248406
  const agentSystemPrompt = override?.systemPrompt ? override.systemPrompt : asSystemPrompt(await getAgentSystemPrompt(agentDefinition, toolUseContext, resolvedAgentModel, additionalWorkingDirectories, resolvedTools));
248294
248407
  const agentAbortController = override?.abortController ? override.abortController : isAsync2 ? new AbortController : toolUseContext.abortController;
248408
+ const stopOwnedShells = () => {
248409
+ killShellTasksForAgent(agentId, toolUseContext.getAppState, rootSetAppState);
248410
+ };
248295
248411
  if (isAsync2) {
248296
- registerBackgroundAgentAbort(agentId, agentAbortController);
248412
+ registerBackgroundAgentAbort(agentId, {
248413
+ abort: () => {
248414
+ killAsyncAgent(agentId, rootSetAppState);
248415
+ if (!agentAbortController.signal.aborted) {
248416
+ agentAbortController.abort();
248417
+ }
248418
+ },
248419
+ stopShells: stopOwnedShells
248420
+ });
248297
248421
  }
248298
- const additionalContexts = [];
248299
- for await (const hookResult of executeSubagentStartHooks(agentId, agentDefinition.agentType, agentAbortController.signal, undefined, toolUseContext.toolUseId, isAsync2)) {
248300
- if (hookResult.additionalContexts && hookResult.additionalContexts.length > 0) {
248301
- additionalContexts.push(...hookResult.additionalContexts);
248422
+ let agentToolRuntimeContext;
248423
+ let mcpCleanup = async () => {};
248424
+ let lastAssistantForFallback = null;
248425
+ let agentRunError;
248426
+ const finalizeLifecycle = createAgentLifecycleFinalizer((error41) => {
248427
+ logForDebugging2(`Agent ${agentId} cleanup failed: ${error41}`, {
248428
+ level: "warn"
248429
+ });
248430
+ });
248431
+ try {
248432
+ const additionalContexts = [];
248433
+ for await (const hookResult of executeSubagentStartHooks(agentId, agentDefinition.agentType, agentAbortController.signal, undefined, toolUseContext.toolUseId, isAsync2)) {
248434
+ if (hookResult.additionalContexts && hookResult.additionalContexts.length > 0) {
248435
+ additionalContexts.push(...hookResult.additionalContexts);
248436
+ }
248302
248437
  }
248303
- }
248304
- if (additionalContexts.length > 0) {
248305
- const contextMessage = createAttachmentMessage({
248306
- type: "hook_additional_context",
248307
- content: additionalContexts,
248308
- hookName: "SubagentStart",
248309
- toolUseID: randomUUID10(),
248310
- hookEvent: "SubagentStart"
248311
- });
248312
- initialMessages.push(contextMessage);
248313
- }
248314
- const hooksAllowedForThisAgent = !isRestrictedToPluginOnly("hooks") || isSourceAdminTrusted(agentDefinition.source);
248315
- if (agentDefinition.hooks && hooksAllowedForThisAgent) {
248316
- registerFrontmatterHooks(rootSetAppState, agentId, agentDefinition.hooks, `agent '${agentDefinition.agentType}'`, true);
248317
- }
248318
- const skillsToPreload = agentDefinition.skills ?? [];
248319
- if (skillsToPreload.length > 0) {
248320
- const allSkills = await getSkillToolCommands(getProjectRoot());
248321
- const validSkills = [];
248322
- for (const skillName of skillsToPreload) {
248323
- const resolvedName = resolveSkillName(skillName, allSkills, agentDefinition);
248324
- if (!resolvedName) {
248325
- logForDebugging2(`[Agent: ${agentDefinition.agentType}] Warning: Skill '${skillName}' specified in frontmatter was not found`, { level: "warn" });
248326
- continue;
248438
+ if (additionalContexts.length > 0) {
248439
+ const contextMessage = createAttachmentMessage({
248440
+ type: "hook_additional_context",
248441
+ content: additionalContexts,
248442
+ hookName: "SubagentStart",
248443
+ toolUseID: randomUUID10(),
248444
+ hookEvent: "SubagentStart"
248445
+ });
248446
+ initialMessages.push(contextMessage);
248447
+ }
248448
+ const hooksAllowedForThisAgent = !isRestrictedToPluginOnly("hooks") || isSourceAdminTrusted(agentDefinition.source);
248449
+ if (agentDefinition.hooks && hooksAllowedForThisAgent) {
248450
+ registerFrontmatterHooks(rootSetAppState, agentId, agentDefinition.hooks, `agent '${agentDefinition.agentType}'`, true);
248451
+ }
248452
+ const skillsToPreload = agentDefinition.skills ?? [];
248453
+ if (skillsToPreload.length > 0) {
248454
+ const allSkills = await getSkillToolCommands(getProjectRoot());
248455
+ const validSkills = [];
248456
+ for (const skillName of skillsToPreload) {
248457
+ const resolvedName = resolveSkillName(skillName, allSkills, agentDefinition);
248458
+ if (!resolvedName) {
248459
+ logForDebugging2(`[Agent: ${agentDefinition.agentType}] Warning: Skill '${skillName}' specified in frontmatter was not found`, { level: "warn" });
248460
+ continue;
248461
+ }
248462
+ const skill = getCommand2(resolvedName, allSkills);
248463
+ if (skill.type !== "prompt") {
248464
+ logForDebugging2(`[Agent: ${agentDefinition.agentType}] Warning: Skill '${skillName}' is not a prompt-based skill`, { level: "warn" });
248465
+ continue;
248466
+ }
248467
+ validSkills.push({ skillName, skill });
248327
248468
  }
248328
- const skill = getCommand2(resolvedName, allSkills);
248329
- if (skill.type !== "prompt") {
248330
- logForDebugging2(`[Agent: ${agentDefinition.agentType}] Warning: Skill '${skillName}' is not a prompt-based skill`, { level: "warn" });
248331
- continue;
248469
+ const loaded = await Promise.all(validSkills.map(async ({ skillName, skill }) => ({
248470
+ skillName,
248471
+ skill,
248472
+ content: await skill.getPromptForCommand("", toolUseContext)
248473
+ })));
248474
+ for (const { skillName, skill, content } of loaded) {
248475
+ logForDebugging2(`[Agent: ${agentDefinition.agentType}] Preloaded skill '${skillName}'`);
248476
+ const metadata = formatSkillLoadingMetadata(skillName, skill.progressMessage);
248477
+ initialMessages.push(createUserMessage({
248478
+ content: [{ type: "text", text: metadata }, ...content],
248479
+ isMeta: true
248480
+ }));
248332
248481
  }
248333
- validSkills.push({ skillName, skill });
248334
248482
  }
248335
- const loaded = await Promise.all(validSkills.map(async ({ skillName, skill }) => ({
248336
- skillName,
248337
- skill,
248338
- content: await skill.getPromptForCommand("", toolUseContext)
248339
- })));
248340
- for (const { skillName, skill, content } of loaded) {
248341
- logForDebugging2(`[Agent: ${agentDefinition.agentType}] Preloaded skill '${skillName}'`);
248342
- const metadata = formatSkillLoadingMetadata(skillName, skill.progressMessage);
248343
- initialMessages.push(createUserMessage({
248344
- content: [{ type: "text", text: metadata }, ...content],
248345
- isMeta: true
248346
- }));
248347
- }
248348
- }
248349
- const {
248350
- clients: mergedMcpClients,
248351
- tools: agentMcpTools,
248352
- cleanup: mcpCleanup
248353
- } = await initializeAgentMcpServers(agentDefinition, toolUseContext.options.mcpClients);
248354
- const allTools = agentMcpTools.length > 0 ? uniqBy_default([...resolvedTools, ...agentMcpTools], "name") : resolvedTools;
248355
- const agentOptions = {
248356
- isNonInteractiveSession: useExactTools ? toolUseContext.options.isNonInteractiveSession : isAsync2 ? true : toolUseContext.options.isNonInteractiveSession ?? false,
248357
- appendSystemPrompt: toolUseContext.options.appendSystemPrompt,
248358
- tools: allTools,
248359
- commands: [],
248360
- debug: toolUseContext.options.debug,
248361
- verbose: toolUseContext.options.verbose,
248362
- mainLoopModel: effectiveModel,
248363
- providerOverride: providerOverride ?? undefined,
248364
- thinkingConfig: toolUseContext.options.thinkingConfig,
248365
- mcpClients: mergedMcpClients,
248366
- mcpResources: toolUseContext.options.mcpResources,
248367
- agentDefinitions: toolUseContext.options.agentDefinitions,
248368
- subagentDisallowedTools: toolUseContext.options.subagentDisallowedTools,
248369
- ...useExactTools && { querySource }
248370
- };
248371
- const agentToolRuntimeContext = createSubagentContext(toolUseContext, {
248372
- options: agentOptions,
248373
- agentId,
248374
- agentType: agentDefinition.agentType,
248375
- messages: initialMessages,
248376
- readFileState: agentReadFileState,
248377
- abortController: agentAbortController,
248378
- getAppState: agentGetAppState,
248379
- shareSetAppState: !isAsync2,
248380
- shareSetResponseLength: true,
248381
- criticalSystemReminder_EXPERIMENTAL: agentDefinition.criticalSystemReminder_EXPERIMENTAL,
248382
- contentReplacementState
248383
- });
248384
- if (preserveToolUseResults) {
248385
- agentToolRuntimeContext.preserveToolUseResults = true;
248386
- }
248387
- if (onCacheSafeParams) {
248388
- onCacheSafeParams({
248389
- systemPrompt: agentSystemPrompt,
248390
- userContext: resolvedUserContext,
248391
- systemContext: resolvedSystemContext,
248392
- toolUseContext: agentToolRuntimeContext,
248393
- forkContextMessages: initialMessages
248394
- });
248395
- }
248396
- recordSidechainTranscript(initialMessages, agentId).catch((_err) => logForDebugging2(`Failed to record sidechain transcript: ${_err}`));
248397
- writeAgentMetadata(agentId, {
248398
- agentType: agentDefinition.agentType,
248399
- ...worktreePath && { worktreePath },
248400
- ...description && { description }
248401
- }).catch((_err) => logForDebugging2(`Failed to write agent metadata: ${_err}`));
248402
- let lastRecordedUuid = initialMessages.at(-1)?.uuid ?? null;
248403
- let partialBaseMessage = null;
248404
- const partialTextByIndex = new Map;
248405
- const PARTIAL_PROGRESS_HOOK_INTERVAL_MS = 100;
248406
- let lastPartialProgressHookAt = 0;
248407
- let lastAssistantForFallback = null;
248408
- let agentRunError;
248409
- try {
248483
+ const mcp = await initializeAgentMcpServers(agentDefinition, toolUseContext.options.mcpClients);
248484
+ const {
248485
+ clients: mergedMcpClients,
248486
+ tools: agentMcpTools
248487
+ } = mcp;
248488
+ mcpCleanup = mcp.cleanup;
248489
+ const allTools = agentMcpTools.length > 0 ? uniqBy_default([...resolvedTools, ...agentMcpTools], "name") : resolvedTools;
248490
+ const agentOptions = {
248491
+ isNonInteractiveSession: useExactTools ? toolUseContext.options.isNonInteractiveSession : isAsync2 ? true : toolUseContext.options.isNonInteractiveSession ?? false,
248492
+ appendSystemPrompt: toolUseContext.options.appendSystemPrompt,
248493
+ tools: allTools,
248494
+ commands: [],
248495
+ debug: toolUseContext.options.debug,
248496
+ verbose: toolUseContext.options.verbose,
248497
+ mainLoopModel: effectiveModel,
248498
+ providerOverride: providerOverride ?? undefined,
248499
+ thinkingConfig: toolUseContext.options.thinkingConfig,
248500
+ mcpClients: mergedMcpClients,
248501
+ mcpResources: toolUseContext.options.mcpResources,
248502
+ agentDefinitions: toolUseContext.options.agentDefinitions,
248503
+ subagentDisallowedTools: toolUseContext.options.subagentDisallowedTools,
248504
+ ...useExactTools && { querySource }
248505
+ };
248506
+ agentToolRuntimeContext = createSubagentContext(toolUseContext, {
248507
+ options: agentOptions,
248508
+ agentId,
248509
+ agentType: agentDefinition.agentType,
248510
+ messages: initialMessages,
248511
+ readFileState: agentReadFileState,
248512
+ abortController: agentAbortController,
248513
+ getAppState: agentGetAppState,
248514
+ shareSetAppState: !isAsync2,
248515
+ shareSetResponseLength: true,
248516
+ criticalSystemReminder_EXPERIMENTAL: agentDefinition.criticalSystemReminder_EXPERIMENTAL,
248517
+ contentReplacementState
248518
+ });
248519
+ if (preserveToolUseResults) {
248520
+ agentToolRuntimeContext.preserveToolUseResults = true;
248521
+ }
248522
+ if (onCacheSafeParams) {
248523
+ onCacheSafeParams({
248524
+ systemPrompt: agentSystemPrompt,
248525
+ userContext: resolvedUserContext,
248526
+ systemContext: resolvedSystemContext,
248527
+ toolUseContext: agentToolRuntimeContext,
248528
+ forkContextMessages: initialMessages
248529
+ });
248530
+ }
248531
+ recordSidechainTranscript(initialMessages, agentId).catch((_err) => logForDebugging2(`Failed to record sidechain transcript: ${_err}`));
248532
+ writeAgentMetadata(agentId, {
248533
+ agentType: agentDefinition.agentType,
248534
+ ...worktreePath && { worktreePath },
248535
+ ...description && { description }
248536
+ }).catch((_err) => logForDebugging2(`Failed to write agent metadata: ${_err}`));
248537
+ let lastRecordedUuid = initialMessages.at(-1)?.uuid ?? null;
248538
+ let partialBaseMessage = null;
248539
+ const partialTextByIndex = new Map;
248540
+ const PARTIAL_PROGRESS_HOOK_INTERVAL_MS = 100;
248541
+ let lastPartialProgressHookAt = 0;
248410
248542
  for await (const message of query({
248411
248543
  messages: initialMessages,
248412
248544
  systemPrompt: agentSystemPrompt,
@@ -248496,43 +248628,65 @@ async function* runAgent({
248496
248628
  agentRunError = err2;
248497
248629
  throw err2;
248498
248630
  } finally {
248499
- const naturalStopAlreadyFired = isAsync2 && hasSubagentStopFired(agentId);
248500
- if (isAsync2) {
248501
- unregisterBackgroundAgentAbort(agentId);
248502
- }
248503
- if (isAsync2 && agentRunError !== undefined) {
248504
- logForDebugging2(`Background agent ${agentId} crashed: ${errorMessage(agentRunError)}
248631
+ await finalizeLifecycle([
248632
+ async () => {
248633
+ const naturalStopAlreadyFired = isAsync2 && hasSubagentStopFired(agentId);
248634
+ if (isAsync2 && agentRunError !== undefined) {
248635
+ logForDebugging2(`Background agent ${agentId} crashed: ${errorMessage(agentRunError)}
248505
248636
  ${agentRunError instanceof Error ? agentRunError.stack ?? "" : ""}`, { level: "error" });
248506
- }
248507
- if (isAsync2 && !naturalStopAlreadyFired) {
248508
- try {
248509
- const fallbackAppState = agentToolRuntimeContext.getAppState();
248510
- const terminal = agentAbortController.signal.aborted ? { status: "stopped" } : agentRunError !== undefined ? { status: "failed", errorMessage: errorMessage(agentRunError) } : { status: "completed" };
248511
- const fallbackStop = executeStopHooks(fallbackAppState.toolPermissionContext.mode, undefined, undefined, false, agentId, agentToolRuntimeContext, lastAssistantForFallback ? [lastAssistantForFallback] : undefined, agentDefinition.agentType, undefined, terminal);
248512
- for await (const evt of fallbackStop) {}
248513
- } catch (err2) {
248514
- logForDebugging2(`Fallback SubagentStop failed for ${agentId}: ${err2}`, {
248515
- level: "warn"
248637
+ }
248638
+ if (isAsync2 && !naturalStopAlreadyFired) {
248639
+ try {
248640
+ const terminalContext = agentToolRuntimeContext ?? toolUseContext;
248641
+ const fallbackAppState = terminalContext.getAppState();
248642
+ const terminal = agentAbortController.signal.aborted ? { status: "stopped" } : agentRunError !== undefined ? { status: "failed", errorMessage: errorMessage(agentRunError) } : { status: "completed" };
248643
+ const fallbackStop = executeStopHooks(fallbackAppState.toolPermissionContext.mode, undefined, undefined, false, agentId, terminalContext, lastAssistantForFallback ? [lastAssistantForFallback] : undefined, agentDefinition.agentType, undefined, terminal);
248644
+ for await (const evt of fallbackStop) {}
248645
+ } catch (err2) {
248646
+ logForDebugging2(`Fallback SubagentStop failed for ${agentId}: ${err2}`, {
248647
+ level: "warn"
248648
+ });
248649
+ }
248650
+ }
248651
+ },
248652
+ mcpCleanup,
248653
+ () => {
248654
+ if (agentDefinition.hooks) {
248655
+ clearSessionHooks(rootSetAppState, agentId);
248656
+ }
248657
+ },
248658
+ () => {
248659
+ if (false) {}
248660
+ },
248661
+ () => agentToolRuntimeContext?.readFileState.clear(),
248662
+ () => {
248663
+ initialMessages.length = 0;
248664
+ },
248665
+ () => unregisterAgent(agentId),
248666
+ () => clearAgentTranscriptSubdir(agentId),
248667
+ () => {
248668
+ rootSetAppState((prev) => {
248669
+ if (!(agentId in prev.todos))
248670
+ return prev;
248671
+ const { [agentId]: _removed, ...todos } = prev.todos;
248672
+ return { ...prev, todos };
248516
248673
  });
248674
+ },
248675
+ () => {
248676
+ if (isAsync2) {
248677
+ stopBackgroundAgentShellsById(agentId);
248678
+ } else {
248679
+ stopOwnedShells();
248680
+ }
248681
+ },
248682
+ () => {
248683
+ if (false) {}
248684
+ },
248685
+ () => {
248686
+ if (isAsync2)
248687
+ unregisterBackgroundAgentAbort(agentId);
248517
248688
  }
248518
- }
248519
- await mcpCleanup();
248520
- if (agentDefinition.hooks) {
248521
- clearSessionHooks(rootSetAppState, agentId);
248522
- }
248523
- if (false) {}
248524
- agentToolRuntimeContext.readFileState.clear();
248525
- initialMessages.length = 0;
248526
- unregisterAgent(agentId);
248527
- clearAgentTranscriptSubdir(agentId);
248528
- rootSetAppState((prev) => {
248529
- if (!(agentId in prev.todos))
248530
- return prev;
248531
- const { [agentId]: _removed, ...todos } = prev.todos;
248532
- return { ...prev, todos };
248533
- });
248534
- killShellTasksForAgent(agentId, toolUseContext.getAppState, rootSetAppState);
248535
- if (false) {}
248689
+ ]);
248536
248690
  }
248537
248691
  }
248538
248692
  function filterIncompleteToolCalls(messages) {
@@ -248604,6 +248758,7 @@ var init_runAgent = __esm(() => {
248604
248758
  init_config7();
248605
248759
  init_permissions2();
248606
248760
  init_killShellTasks();
248761
+ init_LocalAgentTask();
248607
248762
  init_attachments();
248608
248763
  init_errors2();
248609
248764
  init_file();
@@ -250468,6 +250623,21 @@ var init_RemoteAgentTask = __esm(() => {
250468
250623
  };
250469
250624
  });
250470
250625
 
250626
+ // src/lib/zodToJsonSchema.ts
250627
+ function zodToJsonSchema3(schema) {
250628
+ const hit = cache2.get(schema);
250629
+ if (hit)
250630
+ return hit;
250631
+ const result = toJSONSchema(schema);
250632
+ cache2.set(schema, result);
250633
+ return result;
250634
+ }
250635
+ var cache2;
250636
+ var init_zodToJsonSchema2 = __esm(() => {
250637
+ init_v4();
250638
+ cache2 = new WeakMap;
250639
+ });
250640
+
250471
250641
  // src/session/systemPrompt.ts
250472
250642
  function buildEffectiveSystemPrompt({
250473
250643
  mainThreadAgentDefinition,
@@ -250511,6 +250681,67 @@ function getTeleportLauncher() {
250511
250681
  }
250512
250682
  var _launcher = null;
250513
250683
 
250684
+ // src/capabilities/worktreeAvailability.ts
250685
+ import { spawnSync as spawnSync2 } from "child_process";
250686
+ import { resolve as resolve18 } from "path";
250687
+ function resolveGitWorktreeAvailability(cwd, gitExecutable = "git") {
250688
+ try {
250689
+ const rootResult = spawnSync2(gitExecutable, ["rev-parse", "--show-toplevel"], {
250690
+ cwd,
250691
+ encoding: "utf8",
250692
+ stdio: ["ignore", "pipe", "ignore"],
250693
+ windowsHide: true
250694
+ });
250695
+ if (rootResult.error) {
250696
+ return { available: false, reason: "git_unavailable" };
250697
+ }
250698
+ const gitRoot = rootResult.stdout.trim();
250699
+ if (rootResult.status !== 0 || !gitRoot) {
250700
+ return { available: false, reason: "not_git_repository" };
250701
+ }
250702
+ const headResult = spawnSync2(gitExecutable, ["rev-parse", "--verify", "HEAD^{commit}"], {
250703
+ cwd: gitRoot,
250704
+ encoding: "utf8",
250705
+ stdio: ["ignore", "pipe", "ignore"],
250706
+ windowsHide: true
250707
+ });
250708
+ if (headResult.error) {
250709
+ return { available: false, reason: "git_unavailable" };
250710
+ }
250711
+ const headCommit = headResult.stdout.trim();
250712
+ if (headResult.status !== 0 || !headCommit) {
250713
+ return { available: false, reason: "unborn_head" };
250714
+ }
250715
+ return {
250716
+ available: true,
250717
+ gitRoot: resolve18(gitRoot).normalize("NFC"),
250718
+ headCommit
250719
+ };
250720
+ } catch {
250721
+ return { available: false, reason: "git_unavailable" };
250722
+ }
250723
+ }
250724
+ function isGitWorktreeIsolationAvailable(cwd, gitExecutable = "git", cache3) {
250725
+ const cacheKey = `${resolve18(cwd).normalize("NFC")}\x00${gitExecutable}`;
250726
+ const cached3 = cache3?.get(cacheKey);
250727
+ if (cached3 !== undefined)
250728
+ return cached3;
250729
+ const available = resolveGitWorktreeAvailability(cwd, gitExecutable).available;
250730
+ cache3?.set(cacheKey, available);
250731
+ return available;
250732
+ }
250733
+ var WorktreeUnavailableError;
250734
+ var init_worktreeAvailability = __esm(() => {
250735
+ WorktreeUnavailableError = class WorktreeUnavailableError extends Error {
250736
+ reason;
250737
+ constructor(reason) {
250738
+ super(`Agent worktree is unavailable (${reason})`);
250739
+ this.reason = reason;
250740
+ this.name = "WorktreeUnavailableError";
250741
+ }
250742
+ };
250743
+ });
250744
+
250514
250745
  // src/session/agentId.ts
250515
250746
  function formatAgentId(agentName, teamName) {
250516
250747
  return `${agentName}@${teamName}`;
@@ -257885,13 +258116,13 @@ var init_sedValidation = __esm(() => {
257885
258116
 
257886
258117
  // src/capabilities/tools/BashTool/pathValidation.ts
257887
258118
  import { homedir as homedir18 } from "os";
257888
- import { isAbsolute as isAbsolute13, resolve as resolve18 } from "path";
258119
+ import { isAbsolute as isAbsolute13, resolve as resolve19 } from "path";
257889
258120
  function checkDangerousRemovalPaths(command, args, cwd) {
257890
258121
  const extractor = PATH_EXTRACTORS[command];
257891
258122
  const paths2 = extractor(args);
257892
258123
  for (const path11 of paths2) {
257893
258124
  const cleanPath = expandTilde(path11.replace(/^['"]|['"]$/g, ""));
257894
- const absolutePath = isAbsolute13(cleanPath) ? cleanPath : resolve18(cwd, cleanPath);
258125
+ const absolutePath = isAbsolute13(cleanPath) ? cleanPath : resolve19(cwd, cleanPath);
257895
258126
  if (isDangerousRemovalPath(absolutePath)) {
257896
258127
  return {
257897
258128
  behavior: "ask",
@@ -261619,7 +261850,7 @@ function createInProcessCanUseTool(identity4, abortController, onPermissionWaitM
261619
261850
  }
261620
261851
  const setToolUseConfirmQueue = getLeaderToolUseConfirmQueue();
261621
261852
  if (setToolUseConfirmQueue) {
261622
- return new Promise((resolve19) => {
261853
+ return new Promise((resolve20) => {
261623
261854
  let decisionMade = false;
261624
261855
  const permissionStartMs = Date.now();
261625
261856
  const reportPermissionWait = () => {
@@ -261630,7 +261861,7 @@ function createInProcessCanUseTool(identity4, abortController, onPermissionWaitM
261630
261861
  return;
261631
261862
  decisionMade = true;
261632
261863
  reportPermissionWait();
261633
- resolve19({ behavior: "ask", message: SUBAGENT_REJECT_MESSAGE });
261864
+ resolve20({ behavior: "ask", message: SUBAGENT_REJECT_MESSAGE });
261634
261865
  setToolUseConfirmQueue((queue3) => queue3.filter((item) => item.toolUseID !== toolUseID));
261635
261866
  };
261636
261867
  abortController.signal.addEventListener("abort", onAbortListener, {
@@ -261655,7 +261886,7 @@ function createInProcessCanUseTool(identity4, abortController, onPermissionWaitM
261655
261886
  decisionMade = true;
261656
261887
  abortController.signal.removeEventListener("abort", onAbortListener);
261657
261888
  reportPermissionWait();
261658
- resolve19({ behavior: "ask", message: SUBAGENT_REJECT_MESSAGE });
261889
+ resolve20({ behavior: "ask", message: SUBAGENT_REJECT_MESSAGE });
261659
261890
  },
261660
261891
  async onAllow(updatedInput, permissionUpdates, feedback, contentBlocks) {
261661
261892
  if (decisionMade)
@@ -261675,7 +261906,7 @@ function createInProcessCanUseTool(identity4, abortController, onPermissionWaitM
261675
261906
  }
261676
261907
  }
261677
261908
  const trimmedFeedback = feedback?.trim();
261678
- resolve19({
261909
+ resolve20({
261679
261910
  behavior: "allow",
261680
261911
  updatedInput,
261681
261912
  userModified: false,
@@ -261690,7 +261921,7 @@ function createInProcessCanUseTool(identity4, abortController, onPermissionWaitM
261690
261921
  abortController.signal.removeEventListener("abort", onAbortListener);
261691
261922
  reportPermissionWait();
261692
261923
  const message = feedback ? `${SUBAGENT_REJECT_MESSAGE_WITH_REASON_PREFIX}${feedback}` : SUBAGENT_REJECT_MESSAGE;
261693
- resolve19({ behavior: "ask", message, contentBlocks });
261924
+ resolve20({ behavior: "ask", message, contentBlocks });
261694
261925
  },
261695
261926
  async recheckPermission() {
261696
261927
  if (decisionMade)
@@ -261701,7 +261932,7 @@ function createInProcessCanUseTool(identity4, abortController, onPermissionWaitM
261701
261932
  abortController.signal.removeEventListener("abort", onAbortListener);
261702
261933
  reportPermissionWait();
261703
261934
  setToolUseConfirmQueue((queue4) => queue4.filter((item) => item.toolUseID !== toolUseID));
261704
- resolve19({
261935
+ resolve20({
261705
261936
  ...freshResult,
261706
261937
  updatedInput: input,
261707
261938
  userModified: false
@@ -261712,7 +261943,7 @@ function createInProcessCanUseTool(identity4, abortController, onPermissionWaitM
261712
261943
  ]);
261713
261944
  });
261714
261945
  }
261715
- return new Promise((resolve19) => {
261946
+ return new Promise((resolve20) => {
261716
261947
  const request = createPermissionRequest({
261717
261948
  toolName: tool.name,
261718
261949
  toolUseId: toolUseID,
@@ -261731,7 +261962,7 @@ function createInProcessCanUseTool(identity4, abortController, onPermissionWaitM
261731
261962
  cleanup();
261732
261963
  persistPermissionUpdates(permissionUpdates);
261733
261964
  const finalInput = updatedInput && Object.keys(updatedInput).length > 0 ? updatedInput : input;
261734
- resolve19({
261965
+ resolve20({
261735
261966
  behavior: "allow",
261736
261967
  updatedInput: finalInput,
261737
261968
  userModified: false,
@@ -261741,14 +261972,14 @@ function createInProcessCanUseTool(identity4, abortController, onPermissionWaitM
261741
261972
  onReject(feedback, contentBlocks) {
261742
261973
  cleanup();
261743
261974
  const message = feedback ? `${SUBAGENT_REJECT_MESSAGE_WITH_REASON_PREFIX}${feedback}` : SUBAGENT_REJECT_MESSAGE;
261744
- resolve19({ behavior: "ask", message, contentBlocks });
261975
+ resolve20({ behavior: "ask", message, contentBlocks });
261745
261976
  }
261746
261977
  });
261747
261978
  sendPermissionRequestViaMailbox(request);
261748
- const pollInterval = setInterval(async (abortController2, cleanup2, resolve20, identity5, request2) => {
261979
+ const pollInterval = setInterval(async (abortController2, cleanup2, resolve21, identity5, request2) => {
261749
261980
  if (abortController2.signal.aborted) {
261750
261981
  cleanup2();
261751
- resolve20({ behavior: "ask", message: SUBAGENT_REJECT_MESSAGE });
261982
+ resolve21({ behavior: "ask", message: SUBAGENT_REJECT_MESSAGE });
261752
261983
  return;
261753
261984
  }
261754
261985
  const allMessages = await readMailbox(identity5.agentName, identity5.teamName);
@@ -261776,10 +262007,10 @@ function createInProcessCanUseTool(identity4, abortController, onPermissionWaitM
261776
262007
  }
261777
262008
  }
261778
262009
  }
261779
- }, PERMISSION_POLL_INTERVAL_MS, abortController, cleanup, resolve19, identity4, request);
262010
+ }, PERMISSION_POLL_INTERVAL_MS, abortController, cleanup, resolve20, identity4, request);
261780
262011
  const onAbortListener = () => {
261781
262012
  cleanup();
261782
- resolve19({ behavior: "ask", message: SUBAGENT_REJECT_MESSAGE });
262013
+ resolve20({ behavior: "ask", message: SUBAGENT_REJECT_MESSAGE });
261783
262014
  };
261784
262015
  abortController.signal.addEventListener("abort", onAbortListener, {
261785
262016
  once: true
@@ -263001,8 +263232,8 @@ function waitForPaneShellReady() {
263001
263232
  }
263002
263233
  function acquirePaneCreationLock() {
263003
263234
  let release;
263004
- const newLock = new Promise((resolve19) => {
263005
- release = resolve19;
263235
+ const newLock = new Promise((resolve20) => {
263236
+ release = resolve20;
263006
263237
  });
263007
263238
  const previousLock = paneCreationLock;
263008
263239
  paneCreationLock = newLock;
@@ -263449,8 +263680,8 @@ __export(exports_ITermBackend, {
263449
263680
  });
263450
263681
  function acquirePaneCreationLock2() {
263451
263682
  let release;
263452
- const newLock = new Promise((resolve19) => {
263453
- release = resolve19;
263683
+ const newLock = new Promise((resolve20) => {
263684
+ release = resolve20;
263454
263685
  });
263455
263686
  const previousLock = paneCreationLock2;
263456
263687
  paneCreationLock2 = newLock;
@@ -264481,6 +264712,96 @@ var init_spawnMultiAgent = __esm(() => {
264481
264712
  init_loadAgentsDir();
264482
264713
  });
264483
264714
 
264715
+ // src/capabilities/tools/AgentTool/agentInvocationDedupe.ts
264716
+ import { isDeepStrictEqual } from "node:util";
264717
+ function isToolUseBlock(value) {
264718
+ if (!value || typeof value !== "object")
264719
+ return false;
264720
+ const block2 = value;
264721
+ return block2.type === "tool_use" && typeof block2.id === "string" && typeof block2.name === "string";
264722
+ }
264723
+ function isAgentToolUseBlock(block2) {
264724
+ return block2.name === AGENT_TOOL_NAME2 || block2.name === LEGACY_AGENT_TOOL_NAME2;
264725
+ }
264726
+ function findEarlierDuplicateAgentToolUse(assistantMessage, currentToolUseId) {
264727
+ if (!currentToolUseId || !Array.isArray(assistantMessage?.message?.content)) {
264728
+ return;
264729
+ }
264730
+ const earlierAgentToolUses = [];
264731
+ for (const block2 of assistantMessage.message.content) {
264732
+ if (!isToolUseBlock(block2))
264733
+ continue;
264734
+ if (block2.id === currentToolUseId) {
264735
+ if (!isAgentToolUseBlock(block2))
264736
+ return;
264737
+ return earlierAgentToolUses.find((candidate) => isDeepStrictEqual(candidate.input, block2.input))?.id;
264738
+ }
264739
+ if (isAgentToolUseBlock(block2))
264740
+ earlierAgentToolUses.push(block2);
264741
+ }
264742
+ return;
264743
+ }
264744
+ var init_agentInvocationDedupe = __esm(() => {
264745
+ init_constants4();
264746
+ });
264747
+
264748
+ // src/capabilities/tools/AgentTool/worktreeIsolation.ts
264749
+ function getWorktreeIsolationUnavailableMessage(reason) {
264750
+ switch (reason) {
264751
+ case "not_git_repository":
264752
+ return "Worktree isolation is unavailable: the current directory is not a Git repository and no WorktreeCreate hook is configured. This model continuation has been stopped. Run the Agent task again without `isolation` only if using the current directory is safe; otherwise select a Git repository or configure a WorktreeCreate hook.";
264753
+ case "unborn_head":
264754
+ return "Worktree isolation is unavailable: the Git repository has no resolvable HEAD commit. This model continuation has been stopped. Run the Agent task again without `isolation` only if using the current directory is safe; otherwise create the initial commit.";
264755
+ case "git_unavailable":
264756
+ return "Worktree isolation is unavailable because Git could not be inspected. This model continuation has been stopped. Check that Git is installed and accessible, or run the Agent task again without `isolation` only if using the current directory is safe.";
264757
+ default: {
264758
+ const exhaustive = reason;
264759
+ return exhaustive;
264760
+ }
264761
+ }
264762
+ }
264763
+ var WORKTREE_ISOLATION_SCHEMA_DESCRIPTION = 'Isolation mode. Set "worktree" only when the user explicitly requests worktree isolation. It requires a Git repository with a resolvable HEAD commit or a configured WorktreeCreate hook; omit it for ordinary tasks, including read-only research.', WORKTREE_ISOLATION_USAGE_GUIDANCE = 'Only set `isolation: "worktree"` when the user explicitly requests worktree isolation. Omit it for ordinary tasks, including read-only research. Worktree isolation requires a Git repository with a resolvable HEAD commit or a configured WorktreeCreate hook.';
264764
+
264765
+ // src/capabilities/tools/AgentTool/inputSchema.ts
264766
+ function buildAgentInputSchema(options2) {
264767
+ const capabilityAwareSchema = options2.worktreeIsolationAvailable ? fullInputSchema() : inputSchemaWithoutWorktreeIsolation();
264768
+ const schema = options2.includeCwd ? capabilityAwareSchema : capabilityAwareSchema.omit({
264769
+ cwd: true
264770
+ });
264771
+ return options2.includeRunInBackground ? schema : schema.omit({
264772
+ run_in_background: true
264773
+ });
264774
+ }
264775
+ var baseInputSchema, fullInputSchema, inputSchemaWithoutWorktreeIsolation;
264776
+ var init_inputSchema = __esm(() => {
264777
+ init_v4();
264778
+ init_PermissionMode();
264779
+ baseInputSchema = lazySchema(() => exports_external.object({
264780
+ description: exports_external.string().describe("A short (3-5 word) description of the task"),
264781
+ prompt: exports_external.string().describe("The task for the agent to perform"),
264782
+ subagent_type: exports_external.string().optional().describe("The type of specialized agent to use for this task"),
264783
+ model: exports_external.enum(["sonnet", "opus", "haiku"]).optional().describe("Optional model override for this agent. Takes precedence over the agent definition's model frontmatter. If omitted, uses the agent definition's model, or inherits from the parent."),
264784
+ run_in_background: exports_external.boolean().optional().describe("Set to true to run this agent in the background. You will be notified when it completes.")
264785
+ }));
264786
+ fullInputSchema = lazySchema(() => {
264787
+ const multiAgentInputSchema = exports_external.object({
264788
+ name: exports_external.string().optional().describe("Name for the spawned agent. Makes it addressable via SendMessage({to: name}) while running."),
264789
+ team_name: exports_external.string().optional().describe("Team name for spawning. Uses current team context if omitted."),
264790
+ mode: permissionModeSchema().optional().describe('Permission mode for spawned teammate (e.g., "plan" to require plan approval).')
264791
+ });
264792
+ const isolationInputSchema = exports_external.object({
264793
+ isolation: exports_external.enum(["worktree"]).optional().describe(WORKTREE_ISOLATION_SCHEMA_DESCRIPTION)
264794
+ });
264795
+ return baseInputSchema().merge(multiAgentInputSchema).extend({
264796
+ cwd: exports_external.string().optional().describe('Absolute path to run the agent in. Overrides the working directory for all filesystem and shell operations within this agent. Mutually exclusive with isolation: "worktree".')
264797
+ }).merge(isolationInputSchema);
264798
+ });
264799
+ inputSchemaWithoutWorktreeIsolation = lazySchema(() => {
264800
+ const schema = fullInputSchema().omit({ isolation: true });
264801
+ return schema;
264802
+ });
264803
+ });
264804
+
264484
264805
  // src/capabilities/tools/AgentTool/forkSubagent.ts
264485
264806
  import { randomUUID as randomUUID12 } from "crypto";
264486
264807
  function isForkSubagentEnabled() {
@@ -264726,7 +265047,11 @@ The ${AGENT_TOOL_NAME2} tool launches specialized agents (subprocesses) that aut
264726
265047
 
264727
265048
  ${agentListSection}
264728
265049
 
264729
- ${forkEnabled ? `When using the ${AGENT_TOOL_NAME2} tool, specify a subagent_type to use a specialized agent, or omit it to fork yourself — a fork inherits your full conversation context. Only use subagent_type values that appear in the available agent types; never invent an agent type from an example.` : `When using the ${AGENT_TOOL_NAME2} tool, specify a subagent_type parameter to select which agent type to use. If omitted, the general-purpose agent is used. Only use subagent_type values that appear in the available agent types; never invent an agent type from an example.`}`;
265050
+ ${forkEnabled ? `When using the ${AGENT_TOOL_NAME2} tool, specify a subagent_type to use a specialized agent, or omit it to fork yourself — a fork inherits your full conversation context. Only use subagent_type values that appear in the available agent types; never invent an agent type from an example.` : `When using the ${AGENT_TOOL_NAME2} tool, specify a subagent_type parameter to select which agent type to use. If omitted, the general-purpose agent is used. Only use subagent_type values that appear in the available agent types; never invent an agent type from an example.`}
265051
+
265052
+ Do not launch multiple Agent calls with exactly the same input.
265053
+
265054
+ ${WORKTREE_ISOLATION_USAGE_GUIDANCE}`;
264730
265055
  if (isCoordinator) {
264731
265056
  return shared2;
264732
265057
  }
@@ -264741,7 +265066,7 @@ When NOT to use the ${AGENT_TOOL_NAME2} tool:
264741
265066
  - Other tasks that are not related to the agent descriptions above
264742
265067
  `;
264743
265068
  const concurrencyNote = !listViaAttachment && getSubscriptionType() !== "pro" ? `
264744
- - Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses` : "";
265069
+ - Launch multiple agents concurrently for independent, non-overlapping tasks; to do that, use a single message with multiple tool uses` : "";
264745
265070
  return `${shared2}
264746
265071
  ${whenNotToUseSection}
264747
265072
 
@@ -264755,7 +265080,7 @@ Usage notes:
264755
265080
  - Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.)${forkEnabled ? "" : ", since it is not aware of the user's intent"}
264756
265081
  - If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.
264757
265082
  - If the user specifies that they want you to run agents "in parallel", you MUST send a single message with multiple ${AGENT_TOOL_NAME2} tool use content blocks. Each call must either omit subagent_type or use an exact type from the available agent list.
264758
- - You can optionally set \`isolation: "worktree"\` to run the agent in a temporary git worktree, giving it an isolated copy of the repository. The worktree is automatically cleaned up if the agent makes no changes; if changes are made, the worktree path and branch are returned in the result.${process.env.USER_TYPE === "ant" ? `
265083
+ ${process.env.USER_TYPE === "ant" ? `
264759
265084
  - You can set \`isolation: "remote"\` to run the agent in a remote CCR environment. This is always a background task; you'll be notified when it completes. Use for long-running tasks that need a fresh sandbox.` : ""}${isInProcessTeammate() ? `
264760
265085
  - The run_in_background, name, team_name, and mode parameters are not available in this context. Only synchronous subagents are supported.` : isTeammate() ? `
264761
265086
  - The name, team_name, and mode parameters are not available in this context — teammates cannot spawn other teammates. Omit them to spawn a subagent.` : ""}${whenToForkSection}${writingThePromptSection}
@@ -264781,12 +265106,57 @@ function getAutoBackgroundMs() {
264781
265106
  }
264782
265107
  return 0;
264783
265108
  }
265109
+ function buildConfiguredAgentInputSchema(worktreeIsolationAvailable) {
265110
+ const options2 = {
265111
+ worktreeIsolationAvailable,
265112
+ includeRunInBackground: !isBackgroundTasksDisabled && !isForkSubagentEnabled()
265113
+ };
265114
+ return buildAgentInputSchema({
265115
+ ...options2,
265116
+ includeCwd: false
265117
+ });
265118
+ }
265119
+ function getAdvertisedWorktreeAvailabilityCache() {
265120
+ try {
265121
+ const queryContext = getQueryContext();
265122
+ const now = Date.now();
265123
+ let cache3 = advertisedWorktreeAvailabilityByQuery.get(queryContext);
265124
+ if (!cache3 || cache3.expiresAt <= now || cache3.totalToolDuration !== queryContext.cost.totalToolDuration) {
265125
+ cache3 = {
265126
+ expiresAt: now + WORKTREE_AVAILABILITY_CACHE_TTL_MS,
265127
+ totalToolDuration: queryContext.cost.totalToolDuration,
265128
+ values: new Map
265129
+ };
265130
+ advertisedWorktreeAvailabilityByQuery.set(queryContext, cache3);
265131
+ }
265132
+ return cache3.values;
265133
+ } catch {
265134
+ return;
265135
+ }
265136
+ }
265137
+ function getAdvertisedAgentInputJSONSchema() {
265138
+ const worktreeIsolationAvailable = isAgentWorktreeIsolationAvailable({
265139
+ gitAvailabilityCache: getAdvertisedWorktreeAvailabilityCache()
265140
+ });
265141
+ const schemaVariant = "standard";
265142
+ const includeRunInBackground = !isBackgroundTasksDisabled && !isForkSubagentEnabled();
265143
+ const cacheKey = `${worktreeIsolationAvailable}:${schemaVariant}:${includeRunInBackground}`;
265144
+ const cached3 = advertisedInputJSONSchemaCache.get(cacheKey);
265145
+ if (cached3)
265146
+ return cached3;
265147
+ const schema = {
265148
+ ...zodToJsonSchema3(buildConfiguredAgentInputSchema(worktreeIsolationAvailable)),
265149
+ type: "object"
265150
+ };
265151
+ advertisedInputJSONSchemaCache.set(cacheKey, schema);
265152
+ return schema;
265153
+ }
264784
265154
  function resolveTeamName(input, appState) {
264785
265155
  if (!isAgentSwarmsEnabled())
264786
265156
  return;
264787
265157
  return input.team_name || appState.teamContext?.teamName;
264788
265158
  }
264789
- var getBackgroundHintJSX, renderGroupedAgentToolUse, renderToolResultMessage4, renderToolUseErrorMessage2, renderToolUseMessage4, renderToolUseProgressMessage2, renderToolUseRejectedMessage, renderToolUseTag2, userFacingName2, userFacingNameBackgroundColor, proactiveModule = null, PROGRESS_THRESHOLD_MS = 2000, isBackgroundTasksDisabled, baseInputSchema, fullInputSchema, inputSchema7, outputSchema6, AgentTool;
265159
+ var getBackgroundHintJSX, renderGroupedAgentToolUse, renderToolResultMessage4, renderToolUseErrorMessage2, renderToolUseMessage4, renderToolUseProgressMessage2, renderToolUseRejectedMessage, renderToolUseTag2, userFacingName2, userFacingNameBackgroundColor, proactiveModule = null, PROGRESS_THRESHOLD_MS = 2000, isBackgroundTasksDisabled, inputSchema7 = () => buildConfiguredAgentInputSchema(true), outputSchema6, advertisedInputJSONSchemaCache, WORKTREE_AVAILABILITY_CACHE_TTL_MS = 30000, advertisedWorktreeAvailabilityByQuery, agentToolRuntime, AgentTool;
264790
265160
  var init_AgentTool = __esm(() => {
264791
265161
  init_toolRuntime();
264792
265162
  init_promptCategory();
@@ -264805,9 +265175,9 @@ var init_AgentTool = __esm(() => {
264805
265175
  init_debug();
264806
265176
  init_envUtils();
264807
265177
  init_errors2();
265178
+ init_zodToJsonSchema2();
264808
265179
  init_messages4();
264809
265180
  init_agent();
264810
- init_PermissionMode();
264811
265181
  init_permissions2();
264812
265182
  init_sdkEventQueue();
264813
265183
  init_sessionStorage();
@@ -264818,11 +265188,14 @@ var init_AgentTool = __esm(() => {
264818
265188
  init_tokens();
264819
265189
  init_uuid();
264820
265190
  init_worktree();
265191
+ init_worktreeAvailability();
264821
265192
  init_toolUIRegistry();
264822
265193
  init_prompt();
264823
265194
  init_spawnMultiAgent();
264824
265195
  init_agentColorManager();
265196
+ init_agentInvocationDedupe();
264825
265197
  init_agentToolUtils();
265198
+ init_inputSchema();
264826
265199
  init_generalPurposeAgent();
264827
265200
  init_constants4();
264828
265201
  init_forkSubagent();
@@ -264843,32 +265216,6 @@ var init_AgentTool = __esm(() => {
264843
265216
  userFacingNameBackgroundColor
264844
265217
  } = lazyUI("Agent"));
264845
265218
  isBackgroundTasksDisabled = isEnvTruthy(resolveEnvVar("DISABLE_BACKGROUND_TASKS"));
264846
- baseInputSchema = lazySchema(() => exports_external.object({
264847
- description: exports_external.string().describe("A short (3-5 word) description of the task"),
264848
- prompt: exports_external.string().describe("The task for the agent to perform"),
264849
- subagent_type: exports_external.string().optional().describe("The type of specialized agent to use for this task"),
264850
- model: exports_external.enum(["sonnet", "opus", "haiku"]).optional().describe("Optional model override for this agent. Takes precedence over the agent definition's model frontmatter. If omitted, uses the agent definition's model, or inherits from the parent."),
264851
- run_in_background: exports_external.boolean().optional().describe("Set to true to run this agent in the background. You will be notified when it completes.")
264852
- }));
264853
- fullInputSchema = lazySchema(() => {
264854
- const multiAgentInputSchema = exports_external.object({
264855
- name: exports_external.string().optional().describe("Name for the spawned agent. Makes it addressable via SendMessage({to: name}) while running."),
264856
- team_name: exports_external.string().optional().describe("Team name for spawning. Uses current team context if omitted."),
264857
- mode: permissionModeSchema().optional().describe('Permission mode for spawned teammate (e.g., "plan" to require plan approval).')
264858
- });
264859
- return baseInputSchema().merge(multiAgentInputSchema).extend({
264860
- isolation: exports_external.enum(["worktree"]).optional().describe('Isolation mode. "worktree" creates a temporary git worktree so the agent works on an isolated copy of the repo.'),
264861
- cwd: exports_external.string().optional().describe('Absolute path to run the agent in. Overrides the working directory for all filesystem and shell operations within this agent. Mutually exclusive with isolation: "worktree".')
264862
- });
264863
- });
264864
- inputSchema7 = lazySchema(() => {
264865
- const schema = fullInputSchema().omit({
264866
- cwd: true
264867
- });
264868
- return isBackgroundTasksDisabled || isForkSubagentEnabled() ? schema.omit({
264869
- run_in_background: true
264870
- }) : schema;
264871
- });
264872
265219
  outputSchema6 = lazySchema(() => {
264873
265220
  const syncOutputSchema = agentToolResultSchema().extend({
264874
265221
  status: exports_external.literal("completed"),
@@ -264884,7 +265231,9 @@ var init_AgentTool = __esm(() => {
264884
265231
  });
264885
265232
  return exports_external.union([syncOutputSchema, asyncOutputSchema]);
264886
265233
  });
264887
- AgentTool = buildToolRuntime({
265234
+ advertisedInputJSONSchemaCache = new Map;
265235
+ advertisedWorktreeAvailabilityByQuery = new WeakMap;
265236
+ agentToolRuntime = buildToolRuntime({
264888
265237
  async prompt({
264889
265238
  agents,
264890
265239
  tools,
@@ -264914,9 +265263,7 @@ var init_AgentTool = __esm(() => {
264914
265263
  async description() {
264915
265264
  return "Launch a new agent";
264916
265265
  },
264917
- get inputSchema() {
264918
- return inputSchema7();
264919
- },
265266
+ inputSchema: inputSchema7(),
264920
265267
  get outputSchema() {
264921
265268
  return outputSchema6();
264922
265269
  },
@@ -264932,6 +265279,10 @@ var init_AgentTool = __esm(() => {
264932
265279
  isolation,
264933
265280
  cwd
264934
265281
  }, toolUseContext, canUseTool, assistantMessage, onProgress) {
265282
+ const earlierDuplicateId = findEarlierDuplicateAgentToolUse(assistantMessage, toolUseContext.toolUseId);
265283
+ if (earlierDuplicateId) {
265284
+ throw new Error(`Duplicate Agent call skipped: this input duplicates earlier call ${earlierDuplicateId}. Do not retry it; wait for the earlier Agent result.`);
265285
+ }
264935
265286
  const startTime = Date.now();
264936
265287
  const model = isCoordinatorMode() ? undefined : modelParam;
264937
265288
  const appState = toolUseContext.getAppState();
@@ -265168,15 +265519,16 @@ ${reasons}`);
265168
265519
  try {
265169
265520
  worktreeInfo = await createAgentWorktree(slug);
265170
265521
  } catch (error41) {
265171
- const message = error41 instanceof Error ? error41.message : String(error41);
265172
- if (message.includes("Cannot create agent worktree: not in a git repository")) {
265173
- if (isolation === "worktree") {
265174
- throw error41;
265175
- }
265176
- logForDebugging2("Agent worktree isolation unavailable outside a git repository; falling back to the current working directory.");
265177
- } else {
265522
+ if (!(error41 instanceof WorktreeUnavailableError)) {
265178
265523
  throw error41;
265179
265524
  }
265525
+ const unavailableMessage = getWorktreeIsolationUnavailableMessage(error41.reason);
265526
+ if (isolation === "worktree") {
265527
+ throw new ToolContinuationStopError(unavailableMessage, {
265528
+ cause: error41
265529
+ });
265530
+ }
265531
+ logForDebugging2(`${unavailableMessage} Falling back to the current working directory.`);
265180
265532
  }
265181
265533
  }
265182
265534
  if (isForkPath && worktreeInfo) {
@@ -265769,6 +266121,15 @@ duration_ms: ${data.totalDurationMs}</usage>`
265769
266121
  renderToolUseErrorMessage: renderToolUseErrorMessage2,
265770
266122
  renderGroupedToolUse: renderGroupedAgentToolUse
265771
266123
  });
266124
+ AgentTool = {
266125
+ ...agentToolRuntime,
266126
+ get inputSchema() {
266127
+ return inputSchema7();
266128
+ },
266129
+ get inputJSONSchema() {
266130
+ return getAdvertisedAgentInputJSONSchema();
266131
+ }
266132
+ };
265772
266133
  });
265773
266134
 
265774
266135
  // src/capabilities/diagnostics.ts
@@ -266147,12 +266508,12 @@ var init_LSPDiagnosticRegistry = __esm(() => {
266147
266508
  });
266148
266509
 
266149
266510
  // src/capabilities/plugins/lspPluginIntegration.ts
266150
- import { join as join57, relative as relative7, resolve as resolve19 } from "path";
266511
+ import { join as join57, relative as relative7, resolve as resolve20 } from "path";
266151
266512
  function validatePathWithinPlugin(pluginPath, relativePath) {
266152
- const resolvedPluginPath = resolve19(pluginPath);
266153
- const resolvedFilePath = resolve19(pluginPath, relativePath);
266513
+ const resolvedPluginPath = resolve20(pluginPath);
266514
+ const resolvedFilePath = resolve20(pluginPath, relativePath);
266154
266515
  const rel = relative7(resolvedPluginPath, resolvedFilePath);
266155
- if (rel.startsWith("..") || resolve19(rel) === rel) {
266516
+ if (rel.startsWith("..") || resolve20(rel) === rel) {
266156
266517
  return null;
266157
266518
  }
266158
266519
  return resolvedFilePath;
@@ -267386,8 +267747,8 @@ var require_semaphore = __commonJS((exports) => {
267386
267747
  this._waiting = [];
267387
267748
  }
267388
267749
  lock(thunk) {
267389
- return new Promise((resolve20, reject2) => {
267390
- this._waiting.push({ thunk, resolve: resolve20, reject: reject2 });
267750
+ return new Promise((resolve21, reject2) => {
267751
+ this._waiting.push({ thunk, resolve: resolve21, reject: reject2 });
267391
267752
  this.runNext();
267392
267753
  });
267393
267754
  }
@@ -268878,9 +269239,9 @@ ${JSON.stringify(message, null, 4)}`);
268878
269239
  if (typeof cancellationStrategy.sender.enableCancellation === "function") {
268879
269240
  cancellationStrategy.sender.enableCancellation(requestMessage);
268880
269241
  }
268881
- return new Promise(async (resolve20, reject2) => {
269242
+ return new Promise(async (resolve21, reject2) => {
268882
269243
  const resolveWithCleanup = (r) => {
268883
- resolve20(r);
269244
+ resolve21(r);
268884
269245
  cancellationStrategy.sender.cleanup(id);
268885
269246
  disposable?.dispose();
268886
269247
  };
@@ -269289,10 +269650,10 @@ var require_ril = __commonJS((exports) => {
269289
269650
  return api_1.Disposable.create(() => this.stream.off("end", listener2));
269290
269651
  }
269291
269652
  write(data, encoding) {
269292
- return new Promise((resolve20, reject2) => {
269653
+ return new Promise((resolve21, reject2) => {
269293
269654
  const callback = (error41) => {
269294
269655
  if (error41 === undefined || error41 === null) {
269295
- resolve20();
269656
+ resolve21();
269296
269657
  } else {
269297
269658
  reject2(error41);
269298
269659
  }
@@ -269551,10 +269912,10 @@ var require_main = __commonJS((exports) => {
269551
269912
  exports.generateRandomPipeName = generateRandomPipeName;
269552
269913
  function createClientPipeTransport(pipeName, encoding = "utf-8") {
269553
269914
  let connectResolve;
269554
- const connected = new Promise((resolve20, _reject) => {
269555
- connectResolve = resolve20;
269915
+ const connected = new Promise((resolve21, _reject) => {
269916
+ connectResolve = resolve21;
269556
269917
  });
269557
- return new Promise((resolve20, reject2) => {
269918
+ return new Promise((resolve21, reject2) => {
269558
269919
  let server = (0, net_1.createServer)((socket) => {
269559
269920
  server.close();
269560
269921
  connectResolve([
@@ -269565,7 +269926,7 @@ var require_main = __commonJS((exports) => {
269565
269926
  server.on("error", reject2);
269566
269927
  server.listen(pipeName, () => {
269567
269928
  server.removeListener("error", reject2);
269568
- resolve20({
269929
+ resolve21({
269569
269930
  onConnected: () => {
269570
269931
  return connected;
269571
269932
  }
@@ -269584,10 +269945,10 @@ var require_main = __commonJS((exports) => {
269584
269945
  exports.createServerPipeTransport = createServerPipeTransport;
269585
269946
  function createClientSocketTransport(port, encoding = "utf-8") {
269586
269947
  let connectResolve;
269587
- const connected = new Promise((resolve20, _reject) => {
269588
- connectResolve = resolve20;
269948
+ const connected = new Promise((resolve21, _reject) => {
269949
+ connectResolve = resolve21;
269589
269950
  });
269590
- return new Promise((resolve20, reject2) => {
269951
+ return new Promise((resolve21, reject2) => {
269591
269952
  const server = (0, net_1.createServer)((socket) => {
269592
269953
  server.close();
269593
269954
  connectResolve([
@@ -269598,7 +269959,7 @@ var require_main = __commonJS((exports) => {
269598
269959
  server.on("error", reject2);
269599
269960
  server.listen(port, "127.0.0.1", () => {
269600
269961
  server.removeListener("error", reject2);
269601
- resolve20({
269962
+ resolve21({
269602
269963
  onConnected: () => {
269603
269964
  return connected;
269604
269965
  }
@@ -269677,10 +270038,10 @@ function createLSPClient(serverName, onCrash) {
269677
270038
  throw new Error("LSP server process stdio not available");
269678
270039
  }
269679
270040
  const spawnedProcess = process14;
269680
- await new Promise((resolve20, reject2) => {
270041
+ await new Promise((resolve21, reject2) => {
269681
270042
  const onSpawn = () => {
269682
270043
  cleanup();
269683
- resolve20();
270044
+ resolve21();
269684
270045
  };
269685
270046
  const onError = (error41) => {
269686
270047
  cleanup();
@@ -273545,7 +273906,7 @@ ${filenames.join(`
273545
273906
  var DESCRIPTION6 = "Replace the contents of a specific cell in a Jupyter notebook.", PROMPT4 = `Completely replaces the contents of a specific cell in a Jupyter notebook (.ipynb file) with new source. Jupyter notebooks are interactive documents that combine code, text, and visualizations, commonly used for data analysis and scientific computing. The notebook_path parameter must be an absolute path, not a relative path. The cell_number is 0-indexed. Use edit_mode=insert to add a new cell at the index specified by cell_number. Use edit_mode=delete to delete the cell at the index specified by cell_number.`;
273546
273907
 
273547
273908
  // src/capabilities/tools/NotebookEditTool/NotebookEditTool.ts
273548
- import { extname as extname7, isAbsolute as isAbsolute18, resolve as resolve21 } from "path";
273909
+ import { extname as extname7, isAbsolute as isAbsolute18, resolve as resolve22 } from "path";
273549
273910
  var getToolUseSummary6, renderToolResultMessage9, renderToolUseErrorMessage7, renderToolUseMessage9, renderToolUseRejectedMessage4, inputSchema12, outputSchema11, NotebookEditTool;
273550
273911
  var init_NotebookEditTool = __esm(() => {
273551
273912
  init_fileHistory();
@@ -273660,7 +274021,7 @@ var init_NotebookEditTool = __esm(() => {
273660
274021
  renderToolUseErrorMessage: renderToolUseErrorMessage7,
273661
274022
  renderToolResultMessage: renderToolResultMessage9,
273662
274023
  async validateInput({ notebook_path, cell_type, cell_id, edit_mode = "replace" }, toolUseContext) {
273663
- const fullPath = isAbsolute18(notebook_path) ? notebook_path : resolve21(getCwd3(), notebook_path);
274024
+ const fullPath = isAbsolute18(notebook_path) ? notebook_path : resolve22(getCwd3(), notebook_path);
273664
274025
  if (fullPath.startsWith("\\\\") || fullPath.startsWith("//")) {
273665
274026
  return { result: true };
273666
274027
  }
@@ -273759,7 +274120,7 @@ var init_NotebookEditTool = __esm(() => {
273759
274120
  cell_type,
273760
274121
  edit_mode: originalEditMode
273761
274122
  }, { readFileState, updateFileHistoryState }, _, parentMessage) {
273762
- const fullPath = isAbsolute18(notebook_path) ? notebook_path : resolve21(getCwd3(), notebook_path);
274123
+ const fullPath = isAbsolute18(notebook_path) ? notebook_path : resolve22(getCwd3(), notebook_path);
273763
274124
  if (fileHistoryEnabled()) {
273764
274125
  await fileHistoryTrackEdit(updateFileHistoryState, fullPath, parentMessage.uuid);
273765
274126
  }
@@ -274090,7 +274451,7 @@ var init_gitOperationTracking = __esm(() => {
274090
274451
  });
274091
274452
 
274092
274453
  // src/session/fullscreen.ts
274093
- import { spawnSync as spawnSync2 } from "child_process";
274454
+ import { spawnSync as spawnSync3 } from "child_process";
274094
274455
  function isTmuxControlModeEnvHeuristic() {
274095
274456
  if (!process.env.TMUX)
274096
274457
  return false;
@@ -274109,7 +274470,7 @@ function probeTmuxControlModeSync() {
274109
274470
  return;
274110
274471
  let result;
274111
274472
  try {
274112
- result = spawnSync2("tmux", ["display-message", "-p", "#{client_control_mode}"], { encoding: "utf8", timeout: 2000 });
274473
+ result = spawnSync3("tmux", ["display-message", "-p", "#{client_control_mode}"], { encoding: "utf8", timeout: 2000 });
274113
274474
  } catch {
274114
274475
  return;
274115
274476
  }
@@ -275066,8 +275427,8 @@ function registerAgentForeground({
275066
275427
  diskLoaded: false
275067
275428
  };
275068
275429
  let resolveBackgroundSignal;
275069
- const backgroundSignal = new Promise((resolve22) => {
275070
- resolveBackgroundSignal = resolve22;
275430
+ const backgroundSignal = new Promise((resolve23) => {
275431
+ resolveBackgroundSignal = resolve23;
275071
275432
  });
275072
275433
  backgroundSignalResolvers.set(agentId, resolveBackgroundSignal);
275073
275434
  registerTask(taskState, setAppState);
@@ -275179,6 +275540,67 @@ var init_LocalAgentTask = __esm(() => {
275179
275540
  backgroundSignalResolvers = new Map;
275180
275541
  });
275181
275542
 
275543
+ // src/session/backgroundTaskScope.ts
275544
+ class BackgroundTaskScope {
275545
+ tasks = new Set;
275546
+ stopPromise;
275547
+ stopped = false;
275548
+ register(task) {
275549
+ let registered = true;
275550
+ const unregister = () => {
275551
+ if (!registered)
275552
+ return;
275553
+ registered = false;
275554
+ this.tasks.delete(task);
275555
+ };
275556
+ this.tasks.add(task);
275557
+ task.settled.then(unregister, unregister);
275558
+ if (this.stopped) {
275559
+ this.stopTask(task).finally(unregister).catch(() => {});
275560
+ }
275561
+ return unregister;
275562
+ }
275563
+ stop() {
275564
+ if (!this.stopPromise) {
275565
+ this.stopPromise = this.drain().finally(() => {
275566
+ this.stopped = true;
275567
+ });
275568
+ }
275569
+ return this.stopPromise;
275570
+ }
275571
+ async drain() {
275572
+ const failures = [];
275573
+ while (this.tasks.size > 0) {
275574
+ const tasks = [...this.tasks];
275575
+ const results = await Promise.allSettled(tasks.map((task) => this.stopTask(task)));
275576
+ for (const result of results) {
275577
+ if (result.status === "rejected")
275578
+ failures.push(result.reason);
275579
+ }
275580
+ for (const task of tasks) {
275581
+ this.tasks.delete(task);
275582
+ }
275583
+ }
275584
+ if (failures.length > 0) {
275585
+ throw new AggregateError(failures, "BackgroundTaskScope cleanup failed");
275586
+ }
275587
+ }
275588
+ async stopTask(task) {
275589
+ try {
275590
+ await task.stop();
275591
+ } finally {
275592
+ await task.settled;
275593
+ }
275594
+ }
275595
+ }
275596
+ function getBackgroundTaskScope(setAppState) {
275597
+ return scopesBySetAppState.get(setAppState);
275598
+ }
275599
+ var scopesBySetAppState;
275600
+ var init_backgroundTaskScope = __esm(() => {
275601
+ scopesBySetAppState = new WeakMap;
275602
+ });
275603
+
275182
275604
  // src/tasks/LocalShellTask/LocalShellTask.ts
275183
275605
  function looksLikePrompt(tail) {
275184
275606
  const lastLine = tail.trimEnd().split(`
@@ -275307,26 +275729,9 @@ async function spawnShellTask(input, context4) {
275307
275729
  taskOutput
275308
275730
  } = shellCommand;
275309
275731
  const taskId = taskOutput.taskId;
275310
- const unregisterCleanup = registerCleanup(async () => {
275311
- killTask(taskId, setAppState);
275312
- });
275313
- const taskState = {
275314
- ...createTaskStateBase(taskId, "local_bash", description, toolUseId),
275315
- type: "local_bash",
275316
- status: "running",
275317
- command,
275318
- completionStatusSentInAttachment: false,
275319
- shellCommand,
275320
- unregisterCleanup,
275321
- lastReportedTotalLines: 0,
275322
- isBackgrounded: true,
275323
- agentId,
275324
- kind
275325
- };
275326
- registerTask(taskState, setAppState);
275327
- shellCommand.background(taskId);
275328
- const cancelStallWatchdog = startStallWatchdog(taskId, description, kind, toolUseId, agentId);
275329
- shellCommand.result.then(async (result) => {
275732
+ let unregisterCleanup = () => {};
275733
+ let cancelStallWatchdog = () => {};
275734
+ const settled = shellCommand.result.then(async (result) => {
275330
275735
  cancelStallWatchdog();
275331
275736
  await flushAndCleanup(shellCommand);
275332
275737
  let wasKilled = false;
@@ -275349,12 +275754,43 @@ async function spawnShellTask(input, context4) {
275349
275754
  });
275350
275755
  enqueueShellNotification(taskId, description, wasKilled ? "killed" : result.code === 0 ? "completed" : "failed", result.code, setAppState, toolUseId, kind, agentId);
275351
275756
  evictTaskOutput(taskId);
275757
+ }).catch((error41) => {
275758
+ cancelStallWatchdog();
275759
+ logError(error41);
275760
+ }).finally(() => {
275761
+ unregisterCleanup();
275352
275762
  });
275763
+ const stopAndSettle = async () => {
275764
+ killTask(taskId, setAppState);
275765
+ await settled;
275766
+ };
275767
+ const cleanupRegistration = () => {
275768
+ unregisterCleanup();
275769
+ };
275770
+ const taskState = {
275771
+ ...createTaskStateBase(taskId, "local_bash", description, toolUseId),
275772
+ type: "local_bash",
275773
+ status: "running",
275774
+ command,
275775
+ completionStatusSentInAttachment: false,
275776
+ shellCommand,
275777
+ unregisterCleanup: cleanupRegistration,
275778
+ lastReportedTotalLines: 0,
275779
+ isBackgrounded: true,
275780
+ agentId,
275781
+ kind
275782
+ };
275783
+ registerTask(taskState, setAppState);
275784
+ const owner = getBackgroundTaskScope(setAppState);
275785
+ unregisterCleanup = owner ? owner.register({
275786
+ stop: stopAndSettle,
275787
+ settled
275788
+ }) : registerCleanup(stopAndSettle);
275789
+ shellCommand.background(taskId);
275790
+ cancelStallWatchdog = startStallWatchdog(taskId, description, kind, toolUseId, agentId);
275353
275791
  return {
275354
275792
  taskId,
275355
- cleanup: () => {
275356
- unregisterCleanup();
275357
- }
275793
+ cleanup: cleanupRegistration
275358
275794
  };
275359
275795
  }
275360
275796
  function registerForeground(input, setAppState, toolUseId) {
@@ -275578,6 +276014,7 @@ var init_LocalShellTask = __esm(() => {
275578
276014
  init_LocalAgentTask();
275579
276015
  init_killShellTasks();
275580
276016
  init_fsOperations();
276017
+ init_backgroundTaskScope();
275581
276018
  PROMPT_PATTERNS = [
275582
276019
  /\(y\/n\)/i,
275583
276020
  /\[y\/n\]/i,
@@ -276647,8 +277084,8 @@ async function* runShellCommand({
276647
277084
  let assistantAutoBackgrounded = false;
276648
277085
  let resolveProgress = null;
276649
277086
  function createProgressSignal() {
276650
- return new Promise((resolve22) => {
276651
- resolveProgress = () => resolve22(null);
277087
+ return new Promise((resolve23) => {
277088
+ resolveProgress = () => resolve23(null);
276652
277089
  });
276653
277090
  }
276654
277091
  const shouldAutoBackground = !isBackgroundTasksDisabled2 && isAutobackgroundingAllowed(command);
@@ -276659,10 +277096,10 @@ async function* runShellCommand({
276659
277096
  fullOutput = allLines;
276660
277097
  lastTotalLines = totalLines;
276661
277098
  lastTotalBytes = isIncomplete ? totalBytes : 0;
276662
- const resolve22 = resolveProgress;
276663
- if (resolve22) {
277099
+ const resolve23 = resolveProgress;
277100
+ if (resolve23) {
276664
277101
  resolveProgress = null;
276665
- resolve22();
277102
+ resolve23();
276666
277103
  }
276667
277104
  },
276668
277105
  preventCwdChanges,
@@ -276700,10 +277137,10 @@ async function* runShellCommand({
276700
277137
  }
276701
277138
  spawnBackgroundTask().then((shellId) => {
276702
277139
  backgroundShellId = shellId;
276703
- const resolve22 = resolveProgress;
276704
- if (resolve22) {
277140
+ const resolve23 = resolveProgress;
277141
+ if (resolve23) {
276705
277142
  resolveProgress = null;
276706
- resolve22();
277143
+ resolve23();
276707
277144
  }
276708
277145
  logEvent(eventName, {
276709
277146
  command_type: getCommandTypeForLogging(command)
@@ -276735,8 +277172,8 @@ async function* runShellCommand({
276735
277172
  const startTime = Date.now();
276736
277173
  let foregroundTaskId = undefined;
276737
277174
  {
276738
- const initialResult = await Promise.race([resultPromise, new Promise((resolve22) => {
276739
- const t = setTimeout((r) => r(null), PROGRESS_THRESHOLD_MS2, resolve22);
277175
+ const initialResult = await Promise.race([resultPromise, new Promise((resolve23) => {
277176
+ const t = setTimeout((r) => r(null), PROGRESS_THRESHOLD_MS2, resolve23);
276740
277177
  t.unref();
276741
277178
  })]);
276742
277179
  if (initialResult !== null) {
@@ -278259,7 +278696,7 @@ var init_parser5 = __esm(() => {
278259
278696
  });
278260
278697
 
278261
278698
  // src/capabilities/tools/PowerShellTool/gitSafety.ts
278262
- import { basename as basename15, posix as posix5, resolve as resolve22, sep as sep15 } from "path";
278699
+ import { basename as basename15, posix as posix5, resolve as resolve23, sep as sep15 } from "path";
278263
278700
  function resolveCwdReentry(normalized) {
278264
278701
  if (!normalized.startsWith("../../../tools"))
278265
278702
  return normalized;
@@ -278307,7 +278744,7 @@ function normalizeGitPathArg(arg) {
278307
278744
  }
278308
278745
  function resolveEscapingPathToCwdRelative(n2) {
278309
278746
  const cwd = getCwd3();
278310
- const abs = resolve22(cwd, n2);
278747
+ const abs = resolve23(cwd, n2);
278311
278748
  const cwdWithSep = cwd.endsWith(sep15) ? cwd : cwd + sep15;
278312
278749
  const absLower = abs.toLowerCase();
278313
278750
  const cwdLower = cwd.toLowerCase();
@@ -279580,7 +280017,7 @@ var init_modeValidation2 = __esm(() => {
279580
280017
 
279581
280018
  // src/capabilities/tools/PowerShellTool/pathValidation.ts
279582
280019
  import { homedir as homedir20 } from "os";
279583
- import { isAbsolute as isAbsolute19, resolve as resolve23 } from "path";
280020
+ import { isAbsolute as isAbsolute19, resolve as resolve24 } from "path";
279584
280021
  function matchesParam(paramLower, paramList) {
279585
280022
  for (const p of paramList) {
279586
280023
  if (p === paramLower || paramLower.length > 1 && p.startsWith(paramLower)) {
@@ -279688,7 +280125,7 @@ function checkDenyRuleForGuessedPath(strippedPath, cwd, toolPermissionContext, o
279688
280125
  if (!strippedPath || strippedPath.includes("\x00"))
279689
280126
  return null;
279690
280127
  const tildeExpanded = expandTilde2(strippedPath);
279691
- const abs = isAbsolute19(tildeExpanded) ? tildeExpanded : resolve23(cwd, tildeExpanded);
280128
+ const abs = isAbsolute19(tildeExpanded) ? tildeExpanded : resolve24(cwd, tildeExpanded);
279692
280129
  const { resolvedPath } = safeResolvePath(getFsImplementation(), abs);
279693
280130
  const permissionType = operationType === "read" ? "read" : "edit";
279694
280131
  const denyRule = matchingRuleForInput(resolvedPath, toolPermissionContext, permissionType, "deny");
@@ -279778,7 +280215,7 @@ function validatePath2(filePath, cwd, toolPermissionContext, operationType) {
279778
280215
  };
279779
280216
  }
279780
280217
  if (containsPathTraversal(normalizedPath)) {
279781
- const absolutePath2 = isAbsolute19(normalizedPath) ? normalizedPath : resolve23(cwd, normalizedPath);
280218
+ const absolutePath2 = isAbsolute19(normalizedPath) ? normalizedPath : resolve24(cwd, normalizedPath);
279782
280219
  const { resolvedPath: resolvedPath3, isCanonical: isCanonical2 } = safeResolvePath(getFsImplementation(), absolutePath2);
279783
280220
  const result2 = isPathAllowed2(resolvedPath3, toolPermissionContext, operationType, isCanonical2 ? [resolvedPath3] : undefined);
279784
280221
  return {
@@ -279788,7 +280225,7 @@ function validatePath2(filePath, cwd, toolPermissionContext, operationType) {
279788
280225
  };
279789
280226
  }
279790
280227
  const basePath = getGlobBaseDirectory2(normalizedPath);
279791
- const absoluteBasePath = isAbsolute19(basePath) ? basePath : resolve23(cwd, basePath);
280228
+ const absoluteBasePath = isAbsolute19(basePath) ? basePath : resolve24(cwd, basePath);
279792
280229
  const { resolvedPath: resolvedPath2 } = safeResolvePath(getFsImplementation(), absoluteBasePath);
279793
280230
  const permissionType = operationType === "read" ? "read" : "edit";
279794
280231
  const denyRule = matchingRuleForInput(resolvedPath2, toolPermissionContext, permissionType, "deny");
@@ -279808,7 +280245,7 @@ function validatePath2(filePath, cwd, toolPermissionContext, operationType) {
279808
280245
  }
279809
280246
  };
279810
280247
  }
279811
- const absolutePath = isAbsolute19(normalizedPath) ? normalizedPath : resolve23(cwd, normalizedPath);
280248
+ const absolutePath = isAbsolute19(normalizedPath) ? normalizedPath : resolve24(cwd, normalizedPath);
279812
280249
  const { resolvedPath, isCanonical } = safeResolvePath(getFsImplementation(), absolutePath);
279813
280250
  const result = isPathAllowed2(resolvedPath, toolPermissionContext, operationType, isCanonical ? [resolvedPath] : undefined);
279814
280251
  return {
@@ -281738,7 +282175,7 @@ var init_powershellSecurity = __esm(() => {
281738
282175
  var POWERSHELL_TOOL_NAME3 = "PowerShell";
281739
282176
 
281740
282177
  // src/capabilities/tools/PowerShellTool/powershellPermissions.ts
281741
- import { resolve as resolve24 } from "path";
282178
+ import { resolve as resolve25 } from "path";
281742
282179
  async function extractCommandName(command) {
281743
282180
  const trimmed = command.trim();
281744
282181
  if (!trimmed) {
@@ -282351,7 +282788,7 @@ async function powershellToolHasPermission(input, context4) {
282351
282788
  const canonical = resolveToCanonical(element.name);
282352
282789
  if (canonical === "set-location" && element.args.length > 0) {
282353
282790
  const target = element.args.find((a2) => a2.length === 0 || !PS_TOKENIZER_DASH_CHARS.has(a2[0]));
282354
- if (target && resolve24(getCwd3(), target) === getCwd3()) {
282791
+ if (target && resolve25(getCwd3(), target) === getCwd3()) {
282355
282792
  return false;
282356
282793
  }
282357
282794
  }
@@ -282747,8 +283184,8 @@ async function* runPowerShellCommand({
282747
283184
  let assistantAutoBackgrounded = false;
282748
283185
  let resolveProgress = null;
282749
283186
  function createProgressSignal() {
282750
- return new Promise((resolve25) => {
282751
- resolveProgress = () => resolve25(null);
283187
+ return new Promise((resolve26) => {
283188
+ resolveProgress = () => resolve26(null);
282752
283189
  });
282753
283190
  }
282754
283191
  const shouldAutoBackground = !isBackgroundTasksDisabled3 && isAutobackgroundingAllowed2(command);
@@ -282818,10 +283255,10 @@ async function* runPowerShellCommand({
282818
283255
  }
282819
283256
  spawnBackgroundTask().then((shellId) => {
282820
283257
  backgroundShellId = shellId;
282821
- const resolve25 = resolveProgress;
282822
- if (resolve25) {
283258
+ const resolve26 = resolveProgress;
283259
+ if (resolve26) {
282823
283260
  resolveProgress = null;
282824
- resolve25();
283261
+ resolve26();
282825
283262
  }
282826
283263
  logEvent(eventName, {
282827
283264
  command_type: getCommandTypeForLogging2(command)
@@ -282859,7 +283296,7 @@ async function* runPowerShellCommand({
282859
283296
  const now = Date.now();
282860
283297
  const timeUntilNextProgress = Math.max(0, nextProgressTime - now);
282861
283298
  const progressSignal = createProgressSignal();
282862
- const result = await Promise.race([resultPromise, new Promise((resolve25) => setTimeout((r) => r(null), timeUntilNextProgress, resolve25).unref()), progressSignal]);
283299
+ const result = await Promise.race([resultPromise, new Promise((resolve26) => setTimeout((r) => r(null), timeUntilNextProgress, resolve26).unref()), progressSignal]);
282863
283300
  if (result !== null) {
282864
283301
  if (result.backgroundTaskId !== undefined) {
282865
283302
  markTaskNotified2(result.backgroundTaskId, setAppState);
@@ -284828,10 +285265,10 @@ var init_marketplaceHelpers = __esm(() => {
284828
285265
  });
284829
285266
 
284830
285267
  // src/capabilities/plugins/officialMarketplaceGcs.ts
284831
- import { dirname as dirname31, join as join65, resolve as resolve25, sep as sep16 } from "path";
285268
+ import { dirname as dirname31, join as join65, resolve as resolve26, sep as sep16 } from "path";
284832
285269
  async function fetchOfficialMarketplaceFromGcs(installLocation, marketplacesCacheDir) {
284833
- const cacheDir = resolve25(marketplacesCacheDir);
284834
- const resolvedLoc = resolve25(installLocation);
285270
+ const cacheDir = resolve26(marketplacesCacheDir);
285271
+ const resolvedLoc = resolve26(installLocation);
284835
285272
  if (resolvedLoc !== cacheDir && !resolvedLoc.startsWith(cacheDir + sep16)) {
284836
285273
  logForDebugging2(`fetchOfficialMarketplaceFromGcs: refusing path outside cache dir: ${installLocation}`, { level: "error" });
284837
285274
  return null;
@@ -284948,7 +285385,7 @@ var init_officialMarketplaceGcs = __esm(() => {
284948
285385
  });
284949
285386
 
284950
285387
  // src/capabilities/plugins/marketplaceManager.ts
284951
- import { basename as basename19, dirname as dirname32, isAbsolute as isAbsolute20, join as join66, resolve as resolve26, sep as sep17 } from "path";
285388
+ import { basename as basename19, dirname as dirname32, isAbsolute as isAbsolute20, join as join66, resolve as resolve27, sep as sep17 } from "path";
284952
285389
  function getKnownMarketplacesFile() {
284953
285390
  return join66(getPluginsDirectory(), "known_marketplaces.json");
284954
285391
  }
@@ -285626,14 +286063,14 @@ async function loadAndCacheMarketplace(source, onProgress) {
285626
286063
  throw new Error("NPM marketplace sources not yet implemented");
285627
286064
  }
285628
286065
  case "file": {
285629
- const absPath = resolve26(source.path);
286066
+ const absPath = resolve27(source.path);
285630
286067
  marketplacePath = absPath;
285631
286068
  temporaryCachePath = dirname32(dirname32(absPath));
285632
286069
  cleanupNeeded = false;
285633
286070
  break;
285634
286071
  }
285635
286072
  case "directory": {
285636
- const absPath = resolve26(source.path);
286073
+ const absPath = resolve27(source.path);
285637
286074
  marketplacePath = join66(absPath, ".claude-plugin", "marketplace.json");
285638
286075
  temporaryCachePath = absPath;
285639
286076
  cleanupNeeded = false;
@@ -285665,8 +286102,8 @@ async function loadAndCacheMarketplace(source, onProgress) {
285665
286102
  throw new Error(`Failed to parse marketplace file at ${marketplacePath}: ${errorMessage(e)}`);
285666
286103
  }
285667
286104
  const finalCachePath = join66(cacheDir, marketplace.name);
285668
- const resolvedFinal = resolve26(finalCachePath);
285669
- const resolvedCacheDir = resolve26(cacheDir);
286105
+ const resolvedFinal = resolve27(finalCachePath);
286106
+ const resolvedCacheDir = resolve27(cacheDir);
285670
286107
  if (!resolvedFinal.startsWith(resolvedCacheDir + sep17)) {
285671
286108
  throw new Error(`Marketplace name '${marketplace.name}' resolves to a path outside the cache directory`);
285672
286109
  }
@@ -285703,7 +286140,7 @@ Technical details: ${errorMsg}`);
285703
286140
  async function addMarketplaceSource(source, onProgress) {
285704
286141
  let resolvedSource = source;
285705
286142
  if (isLocalMarketplaceSource(source) && !isAbsolute20(source.path)) {
285706
- resolvedSource = { ...source, path: resolve26(source.path) };
286143
+ resolvedSource = { ...source, path: resolve27(source.path) };
285707
286144
  }
285708
286145
  if (!isSourceAllowedByPolicy(resolvedSource)) {
285709
286146
  if (isSourceInBlocklist(resolvedSource)) {
@@ -285751,9 +286188,9 @@ Tip: The shorthand "${resolvedSource.repo}" assumes github.com. ` + `For interna
285751
286188
  }
285752
286189
  logForDebugging2(`Marketplace '${marketplace.name}' exists with different source — overwriting`);
285753
286190
  if (!isLocalMarketplaceSource(oldEntry.source)) {
285754
- const cacheDir = resolve26(getMarketplacesCacheDir());
285755
- const resolvedOld = resolve26(oldEntry.installLocation);
285756
- const resolvedNew = resolve26(cachePath);
286191
+ const cacheDir = resolve27(getMarketplacesCacheDir());
286192
+ const resolvedOld = resolve27(oldEntry.installLocation);
286193
+ const resolvedNew = resolve27(cachePath);
285757
286194
  if (resolvedOld === resolvedNew) {} else if (resolvedOld === cacheDir || resolvedOld.startsWith(cacheDir + sep17)) {
285758
286195
  const fs2 = getFsImplementation();
285759
286196
  await fs2.rm(oldEntry.installLocation, { recursive: true, force: true });
@@ -285980,8 +286417,8 @@ async function refreshMarketplace(name, onProgress, options2) {
285980
286417
  throw new Error(`Marketplace '${name}' is seed-managed (${seedDir}) and its content is ` + `controlled by the seed image. To update: ask your admin to update the seed.`);
285981
286418
  }
285982
286419
  if (!isLocalMarketplaceSource(source)) {
285983
- const cacheDir = resolve26(getMarketplacesCacheDir());
285984
- const resolvedLoc = resolve26(installLocation);
286420
+ const cacheDir = resolve27(getMarketplacesCacheDir());
286421
+ const resolvedLoc = resolve27(installLocation);
285985
286422
  if (resolvedLoc !== cacheDir && !resolvedLoc.startsWith(cacheDir + sep17)) {
285986
286423
  throw new Error(`Marketplace '${name}' has a corrupted installLocation ` + `(${installLocation}) — expected a path inside ${cacheDir}. ` + `This can happen after cross-platform path writes or manual edits ` + `to known_marketplaces.json. ` + `Run: claude plugin marketplace remove "${name}" and re-add it.`);
285987
286424
  }
@@ -286799,14 +287236,14 @@ var init_pluginVersioning = __esm(() => {
286799
287236
 
286800
287237
  // src/capabilities/plugins/pluginInstallationHelpers.ts
286801
287238
  import { randomBytes as randomBytes7 } from "crypto";
286802
- import { dirname as dirname34, join as join68, resolve as resolve27, sep as sep19 } from "path";
287239
+ import { dirname as dirname34, join as join68, resolve as resolve28, sep as sep19 } from "path";
286803
287240
  function getCurrentTimestamp() {
286804
287241
  return new Date().toISOString();
286805
287242
  }
286806
287243
  function validatePathWithinBase(basePath, relativePath) {
286807
- const resolvedPath = resolve27(basePath, relativePath);
286808
- const normalizedBase = resolve27(basePath) + sep19;
286809
- if (!resolvedPath.startsWith(normalizedBase) && resolvedPath !== resolve27(basePath)) {
287244
+ const resolvedPath = resolve28(basePath, relativePath);
287245
+ const normalizedBase = resolve28(basePath) + sep19;
287246
+ if (!resolvedPath.startsWith(normalizedBase) && resolvedPath !== resolve28(basePath)) {
286810
287247
  throw new Error(`Path traversal detected: "${relativePath}" would escape the base directory`);
286811
287248
  }
286812
287249
  return resolvedPath;
@@ -287046,7 +287483,7 @@ var init_pluginInstallationHelpers = __esm(() => {
287046
287483
  });
287047
287484
 
287048
287485
  // src/capabilities/plugins/pluginLoader.ts
287049
- import { basename as basename20, dirname as dirname35, join as join69, relative as relative11, resolve as resolve28, sep as sep20 } from "path";
287486
+ import { basename as basename20, dirname as dirname35, join as join69, relative as relative11, resolve as resolve29, sep as sep20 } from "path";
287050
287487
  function getPluginCachePath() {
287051
287488
  return join69(getPluginsDirectory(), "cache");
287052
287489
  }
@@ -288400,7 +288837,7 @@ async function loadSessionOnlyPlugins(sessionPluginPaths) {
288400
288837
  const errors4 = [];
288401
288838
  for (const [index, pluginPath] of sessionPluginPaths.entries()) {
288402
288839
  try {
288403
- const resolvedPath = resolve28(pluginPath);
288840
+ const resolvedPath = resolve29(pluginPath);
288404
288841
  if (!await pathExists(resolvedPath)) {
288405
288842
  logForDebugging2(`Plugin path does not exist: ${resolvedPath}, skipping`, { level: "warn" });
288406
288843
  errors4.push({
@@ -290258,14 +290695,14 @@ function waitForCallback(port, expectedState, abortSignal, onListening) {
290258
290695
  abortHandler = null;
290259
290696
  }
290260
290697
  };
290261
- return new Promise((resolve29, reject2) => {
290698
+ return new Promise((resolve30, reject2) => {
290262
290699
  let resolved = false;
290263
290700
  const resolveOnce = (v) => {
290264
290701
  if (resolved)
290265
290702
  return;
290266
290703
  resolved = true;
290267
290704
  cleanup();
290268
- resolve29(v);
290705
+ resolve30(v);
290269
290706
  };
290270
290707
  const rejectOnce = (e) => {
290271
290708
  if (resolved)
@@ -290871,13 +291308,13 @@ async function performMCPOAuthFlow(serverName, serverConfig, onAuthorizationUrl,
290871
291308
  }
290872
291309
  logMCPDebug(serverName, `MCP OAuth server cleaned up`);
290873
291310
  };
290874
- const authorizationCode = await new Promise((resolve29, reject2) => {
291311
+ const authorizationCode = await new Promise((resolve30, reject2) => {
290875
291312
  let resolved = false;
290876
291313
  const resolveOnce = (code) => {
290877
291314
  if (resolved)
290878
291315
  return;
290879
291316
  resolved = true;
290880
- resolve29(code);
291317
+ resolve30(code);
290881
291318
  };
290882
291319
  const rejectOnce = (error41) => {
290883
291320
  if (resolved)
@@ -291692,7 +292129,7 @@ async function readClientSecret() {
291692
292129
  if (!process.stdin.isTTY) {
291693
292130
  throw new Error("No TTY available to prompt for client secret. Set MCP_CLIENT_SECRET env var instead.");
291694
292131
  }
291695
- return new Promise((resolve29, reject2) => {
292132
+ return new Promise((resolve30, reject2) => {
291696
292133
  process.stderr.write("Enter OAuth client secret: ");
291697
292134
  process.stdin.setRawMode?.(true);
291698
292135
  let secret = "";
@@ -291704,7 +292141,7 @@ async function readClientSecret() {
291704
292141
  process.stdin.removeListener("data", onData);
291705
292142
  process.stderr.write(`
291706
292143
  `);
291707
- resolve29(secret);
292144
+ resolve30(secret);
291708
292145
  } else if (c6 === "\x03") {
291709
292146
  process.stdin.setRawMode?.(false);
291710
292147
  process.stdin.removeListener("data", onData);
@@ -291855,8 +292292,8 @@ function createMcpAuthTool(serverName, config2) {
291855
292292
  }
291856
292293
  const sseOrHttpConfig = config2;
291857
292294
  let resolveAuthUrl;
291858
- const authUrlPromise = new Promise((resolve29) => {
291859
- resolveAuthUrl = resolve29;
292295
+ const authUrlPromise = new Promise((resolve30) => {
292296
+ resolveAuthUrl = resolve30;
291860
292297
  });
291861
292298
  const controller = new AbortController;
291862
292299
  const { setAppState } = context4;
@@ -292338,15 +292775,15 @@ class WebSocketTransport {
292338
292775
  isBun = typeof Bun !== "undefined";
292339
292776
  constructor(ws) {
292340
292777
  this.ws = ws;
292341
- this.opened = new Promise((resolve29, reject2) => {
292778
+ this.opened = new Promise((resolve30, reject2) => {
292342
292779
  if (this.ws.readyState === WS_OPEN) {
292343
- resolve29();
292780
+ resolve30();
292344
292781
  } else if (this.isBun) {
292345
292782
  const nws = this.ws;
292346
292783
  const onOpen = () => {
292347
292784
  nws.removeEventListener("open", onOpen);
292348
292785
  nws.removeEventListener("error", onError);
292349
- resolve29();
292786
+ resolve30();
292350
292787
  };
292351
292788
  const onError = (event) => {
292352
292789
  nws.removeEventListener("open", onOpen);
@@ -292359,7 +292796,7 @@ class WebSocketTransport {
292359
292796
  } else {
292360
292797
  const nws = this.ws;
292361
292798
  nws.on("open", () => {
292362
- resolve29();
292799
+ resolve30();
292363
292800
  });
292364
292801
  nws.on("error", (error41) => {
292365
292802
  logForDiagnosticsNoPII("error", "mcp_websocket_connect_fail");
@@ -292458,12 +292895,12 @@ class WebSocketTransport {
292458
292895
  if (this.isBun) {
292459
292896
  this.ws.send(json2);
292460
292897
  } else {
292461
- await new Promise((resolve29, reject2) => {
292898
+ await new Promise((resolve30, reject2) => {
292462
292899
  this.ws.send(json2, (error41) => {
292463
292900
  if (error41) {
292464
292901
  reject2(error41);
292465
292902
  } else {
292466
- resolve29();
292903
+ resolve30();
292467
292904
  }
292468
292905
  });
292469
292906
  });
@@ -292725,9 +293162,9 @@ function registerElicitationHandler(client, serverName, setAppState) {
292725
293162
  return hookResponse;
292726
293163
  }
292727
293164
  const elicitationId = mode === "url" && "elicitationId" in request.params ? request.params.elicitationId : undefined;
292728
- const response = new Promise((resolve29) => {
293165
+ const response = new Promise((resolve30) => {
292729
293166
  const onAbort = () => {
292730
- resolve29({ action: "cancel" });
293167
+ resolve30({ action: "cancel" });
292731
293168
  };
292732
293169
  if (extra.signal.aborted) {
292733
293170
  onAbort();
@@ -292751,7 +293188,7 @@ function registerElicitationHandler(client, serverName, setAppState) {
292751
293188
  mode,
292752
293189
  action: result2.action
292753
293190
  });
292754
- resolve29(result2);
293191
+ resolve30(result2);
292755
293192
  }
292756
293193
  }
292757
293194
  ]
@@ -296437,8 +296874,8 @@ function getMcpAuthCache() {
296437
296874
  return authCachePromise;
296438
296875
  }
296439
296876
  async function isMcpAuthCached(serverId) {
296440
- const cache2 = await getMcpAuthCache();
296441
- const entry = cache2[serverId];
296877
+ const cache3 = await getMcpAuthCache();
296878
+ const entry = cache3[serverId];
296442
296879
  if (!entry) {
296443
296880
  return false;
296444
296881
  }
@@ -296446,11 +296883,11 @@ async function isMcpAuthCached(serverId) {
296446
296883
  }
296447
296884
  function setMcpAuthCacheEntry(serverId) {
296448
296885
  writeChain = writeChain.then(async () => {
296449
- const cache2 = await getMcpAuthCache();
296450
- cache2[serverId] = { timestamp: Date.now() };
296886
+ const cache3 = await getMcpAuthCache();
296887
+ cache3[serverId] = { timestamp: Date.now() };
296451
296888
  const cachePath = getMcpAuthCachePath();
296452
296889
  await getFsImplementation().mkdir(dirname37(cachePath), { recursive: true });
296453
- await getFsImplementation().writeFile(cachePath, jsonStringify(cache2));
296890
+ await getFsImplementation().writeFile(cachePath, jsonStringify(cache3));
296454
296891
  authCachePromise = null;
296455
296892
  }).catch(() => {});
296456
296893
  }
@@ -296770,12 +297207,12 @@ async function getMcpToolsCommandsAndResources(onConnectionAttempt, mcpConfigs)
296770
297207
  ]);
296771
297208
  }
296772
297209
  function prefetchAllMcpResources(mcpConfigs) {
296773
- return new Promise((resolve29) => {
297210
+ return new Promise((resolve30) => {
296774
297211
  let pendingCount = 0;
296775
297212
  let completedCount = 0;
296776
297213
  pendingCount = Object.keys(mcpConfigs).length;
296777
297214
  if (pendingCount === 0) {
296778
- resolve29({
297215
+ resolve30({
296779
297216
  clients: [],
296780
297217
  tools: [],
296781
297218
  commands: []
@@ -296800,7 +297237,7 @@ function prefetchAllMcpResources(mcpConfigs) {
296800
297237
  commands_count: commands.length,
296801
297238
  commands_metadata_length: commandsMetadataLength
296802
297239
  });
296803
- resolve29({
297240
+ resolve30({
296804
297241
  clients,
296805
297242
  tools,
296806
297243
  commands
@@ -296808,7 +297245,7 @@ function prefetchAllMcpResources(mcpConfigs) {
296808
297245
  }
296809
297246
  }, mcpConfigs).catch((error41) => {
296810
297247
  logMCPError("prefetchAllMcpResources", `Failed to get MCP resources: ${errorMessage(error41)}`);
296811
- resolve29({
297248
+ resolve30({
296812
297249
  clients: [],
296813
297250
  tools: [],
296814
297251
  commands: []
@@ -296988,9 +297425,9 @@ async function callMCPToolWithUrlElicitationRetry({
296988
297425
  actionLabel: "Retry now",
296989
297426
  showCancel: true
296990
297427
  };
296991
- userResult = await new Promise((resolve29) => {
297428
+ userResult = await new Promise((resolve30) => {
296992
297429
  const onAbort = () => {
296993
- resolve29({ action: "cancel" });
297430
+ resolve30({ action: "cancel" });
296994
297431
  };
296995
297432
  if (signal.aborted) {
296996
297433
  onAbort();
@@ -297013,14 +297450,14 @@ async function callMCPToolWithUrlElicitationRetry({
297013
297450
  return;
297014
297451
  }
297015
297452
  signal.removeEventListener("abort", onAbort);
297016
- resolve29(result);
297453
+ resolve30(result);
297017
297454
  },
297018
297455
  onWaitingDismiss: (action) => {
297019
297456
  signal.removeEventListener("abort", onAbort);
297020
297457
  if (action === "retry") {
297021
- resolve29({ action: "accept" });
297458
+ resolve30({ action: "accept" });
297022
297459
  } else {
297023
- resolve29({ action: "cancel" });
297460
+ resolve30({ action: "cancel" });
297024
297461
  }
297025
297462
  }
297026
297463
  }
@@ -297774,7 +298211,7 @@ var init_client5 = __esm(() => {
297774
298211
  logMCPDebug(name, `Error sending SIGINT: ${error41}`);
297775
298212
  return;
297776
298213
  }
297777
- await new Promise(async (resolve29) => {
298214
+ await new Promise(async (resolve30) => {
297778
298215
  let resolved = false;
297779
298216
  const checkInterval = setInterval(() => {
297780
298217
  try {
@@ -297785,7 +298222,7 @@ var init_client5 = __esm(() => {
297785
298222
  clearInterval(checkInterval);
297786
298223
  clearTimeout(failsafeTimeout);
297787
298224
  logMCPDebug(name, "MCP server process exited cleanly");
297788
- resolve29();
298225
+ resolve30();
297789
298226
  }
297790
298227
  }
297791
298228
  }, 50);
@@ -297794,7 +298231,7 @@ var init_client5 = __esm(() => {
297794
298231
  resolved = true;
297795
298232
  clearInterval(checkInterval);
297796
298233
  logMCPDebug(name, "Cleanup timeout reached, stopping process monitoring");
297797
- resolve29();
298234
+ resolve30();
297798
298235
  }
297799
298236
  }, 600);
297800
298237
  try {
@@ -297810,14 +298247,14 @@ var init_client5 = __esm(() => {
297810
298247
  resolved = true;
297811
298248
  clearInterval(checkInterval);
297812
298249
  clearTimeout(failsafeTimeout);
297813
- resolve29();
298250
+ resolve30();
297814
298251
  return;
297815
298252
  }
297816
298253
  } catch {
297817
298254
  resolved = true;
297818
298255
  clearInterval(checkInterval);
297819
298256
  clearTimeout(failsafeTimeout);
297820
- resolve29();
298257
+ resolve30();
297821
298258
  return;
297822
298259
  }
297823
298260
  await sleep2(400);
@@ -297834,7 +298271,7 @@ var init_client5 = __esm(() => {
297834
298271
  resolved = true;
297835
298272
  clearInterval(checkInterval);
297836
298273
  clearTimeout(failsafeTimeout);
297837
- resolve29();
298274
+ resolve30();
297838
298275
  }
297839
298276
  }
297840
298277
  }
@@ -297842,14 +298279,14 @@ var init_client5 = __esm(() => {
297842
298279
  resolved = true;
297843
298280
  clearInterval(checkInterval);
297844
298281
  clearTimeout(failsafeTimeout);
297845
- resolve29();
298282
+ resolve30();
297846
298283
  }
297847
298284
  } catch {
297848
298285
  if (!resolved) {
297849
298286
  resolved = true;
297850
298287
  clearInterval(checkInterval);
297851
298288
  clearTimeout(failsafeTimeout);
297852
- resolve29();
298289
+ resolve30();
297853
298290
  }
297854
298291
  }
297855
298292
  });
@@ -298352,7 +298789,7 @@ var init_idePathConversion = () => {};
298352
298789
  // src/capabilities/ide.ts
298353
298790
  import { createConnection } from "net";
298354
298791
  import * as os4 from "os";
298355
- import { basename as basename21, join as join76, sep as pathSeparator, resolve as resolve29 } from "path";
298792
+ import { basename as basename21, join as join76, sep as pathSeparator, resolve as resolve30 } from "path";
298356
298793
  function isProcessRunning2(pid) {
298357
298794
  try {
298358
298795
  process.kill(pid, 0);
@@ -298463,7 +298900,7 @@ async function readIdeLockfile(path13) {
298463
298900
  }
298464
298901
  async function checkIdeConnection(host, port, timeout = 500) {
298465
298902
  try {
298466
- return new Promise((resolve30) => {
298903
+ return new Promise((resolve31) => {
298467
298904
  const socket = createConnection({
298468
298905
  host,
298469
298906
  port,
@@ -298471,14 +298908,14 @@ async function checkIdeConnection(host, port, timeout = 500) {
298471
298908
  });
298472
298909
  socket.on("connect", () => {
298473
298910
  socket.destroy();
298474
- resolve30(true);
298911
+ resolve31(true);
298475
298912
  });
298476
298913
  socket.on("error", () => {
298477
- resolve30(false);
298914
+ resolve31(false);
298478
298915
  });
298479
298916
  socket.on("timeout", () => {
298480
298917
  socket.destroy();
298481
- resolve30(false);
298918
+ resolve31(false);
298482
298919
  });
298483
298920
  });
298484
298921
  } catch (_) {
@@ -298496,7 +298933,7 @@ async function getIdeLockfilesPaths() {
298496
298933
  if (windowsHome) {
298497
298934
  const converter = new WindowsToWSLConverter(process.env.WSL_DISTRO_NAME);
298498
298935
  const wslPath = converter.toLocalPath(windowsHome);
298499
- paths2.push(resolve29(wslPath, BUILT_IN_BINDINGS.claude.configDir, PATH_SEGMENTS.runtime.ideDir));
298936
+ paths2.push(resolve30(wslPath, BUILT_IN_BINDINGS.claude.configDir, PATH_SEGMENTS.runtime.ideDir));
298500
298937
  }
298501
298938
  try {
298502
298939
  const usersDir = "/mnt/c/Users";
@@ -298640,14 +299077,14 @@ async function detectIDEs(includeInvalid) {
298640
299077
  if (!checkWSLDistroMatch(idePath, process.env.WSL_DISTRO_NAME)) {
298641
299078
  return false;
298642
299079
  }
298643
- const resolvedOriginal = resolve29(localPath).normalize("NFC");
299080
+ const resolvedOriginal = resolve30(localPath).normalize("NFC");
298644
299081
  if (cwd === resolvedOriginal || cwd.startsWith(resolvedOriginal + pathSeparator)) {
298645
299082
  return true;
298646
299083
  }
298647
299084
  const converter = new WindowsToWSLConverter(process.env.WSL_DISTRO_NAME);
298648
299085
  localPath = converter.toLocalPath(idePath);
298649
299086
  }
298650
- const resolvedPath = resolve29(localPath).normalize("NFC");
299087
+ const resolvedPath = resolve30(localPath).normalize("NFC");
298651
299088
  if (getPlatform() === "windows") {
298652
299089
  const normalizedCwd = cwd.replace(/^[a-zA-Z]:/, (match) => match.toUpperCase());
298653
299090
  const normalizedResolvedPath = resolvedPath.replace(/^[a-zA-Z]:/, (match) => match.toUpperCase());
@@ -299040,9 +299477,9 @@ async function installFromArtifactory(command) {
299040
299477
  responseType: "stream"
299041
299478
  });
299042
299479
  const writeStream = getFsImplementation().createWriteStream(tempVsixPath);
299043
- await new Promise((resolve30, reject2) => {
299480
+ await new Promise((resolve31, reject2) => {
299044
299481
  vsixResponse.data.pipe(writeStream);
299045
- writeStream.on("finish", resolve30);
299482
+ writeStream.on("finish", resolve31);
299046
299483
  writeStream.on("error", reject2);
299047
299484
  });
299048
299485
  await sleep2(500);
@@ -299758,7 +300195,7 @@ var init_findRelevantMemories = __esm(() => {
299758
300195
  });
299759
300196
 
299760
300197
  // src/session/attachments.ts
299761
- import { dirname as dirname38, parse as parse12, relative as relative12, resolve as resolve30 } from "path";
300198
+ import { dirname as dirname38, parse as parse12, relative as relative12, resolve as resolve31 } from "path";
299762
300199
  import { randomUUID as randomUUID16 } from "crypto";
299763
300200
  async function getAttachments(input, toolUseContext, ideSelection, queuedCommands, messages, querySource, options2) {
299764
300201
  if (isEnvTruthy(resolveEnvVar("DISABLE_ATTACHMENTS")) || isEnvTruthy(resolveEnvVar("SIMPLE"))) {
@@ -300136,7 +300573,7 @@ async function getSelectedLinesFromIDE(ideSelection, toolUseContext) {
300136
300573
  ];
300137
300574
  }
300138
300575
  function getDirectoriesToProcess(targetPath, originalCwd) {
300139
- const targetDir = dirname38(resolve30(targetPath));
300576
+ const targetDir = dirname38(resolve31(targetPath));
300140
300577
  const nestedDirs = [];
300141
300578
  let currentDir = targetDir;
300142
300579
  while (currentDir !== originalCwd && currentDir !== parse12(currentDir).root) {
@@ -300592,7 +301029,7 @@ async function getDynamicSkillAttachments(toolUseContext) {
300592
301029
  const candidates = entries.filter((e) => e.isDirectory() || e.isSymbolicLink()).map((e) => e.name);
300593
301030
  const checked = await Promise.all(candidates.map(async (name) => {
300594
301031
  try {
300595
- await getFsImplementation().stat(resolve30(skillDir, name, "SKILL.md"));
301032
+ await getFsImplementation().stat(resolve31(skillDir, name, "SKILL.md"));
300596
301033
  return name;
300597
301034
  } catch {
300598
301035
  return null;
@@ -302931,10 +303368,10 @@ function DANGEROUS_uncachedSystemPromptSection(name, compute, _reason) {
302931
303368
  return { name, compute, cacheBreak: true };
302932
303369
  }
302933
303370
  async function resolveSystemPromptSections(sections) {
302934
- const cache2 = getSystemPromptSectionCache();
303371
+ const cache3 = getSystemPromptSectionCache();
302935
303372
  return Promise.all(sections.map(async (s) => {
302936
- if (!s.cacheBreak && cache2.has(s.name)) {
302937
- return cache2.get(s.name) ?? null;
303373
+ if (!s.cacheBreak && cache3.has(s.name)) {
303374
+ return cache3.get(s.name) ?? null;
302938
303375
  }
302939
303376
  const value = await s.compute();
302940
303377
  setSystemPromptSectionCacheEntry(s.name, value);
@@ -304421,21 +304858,6 @@ var init_analyzeContext = __esm(() => {
304421
304858
  init_state2();
304422
304859
  });
304423
304860
 
304424
- // src/lib/zodToJsonSchema.ts
304425
- function zodToJsonSchema3(schema) {
304426
- const hit = cache2.get(schema);
304427
- if (hit)
304428
- return hit;
304429
- const result = toJSONSchema(schema);
304430
- cache2.set(schema, result);
304431
- return result;
304432
- }
304433
- var cache2;
304434
- var init_zodToJsonSchema2 = __esm(() => {
304435
- init_v4();
304436
- cache2 = new WeakMap;
304437
- });
304438
-
304439
304861
  // src/controller/toolSearch.ts
304440
304862
  var exports_toolSearch = {};
304441
304863
  __export(exports_toolSearch, {
@@ -304565,7 +304987,8 @@ async function calculateDeferredToolDescriptionChars(tools, getToolPermissionCon
304565
304987
  tools,
304566
304988
  agents
304567
304989
  });
304568
- const inputSchema17 = tool.inputJSONSchema ? jsonStringify(tool.inputJSONSchema) : tool.inputSchema ? jsonStringify(zodToJsonSchema3(tool.inputSchema)) : "";
304990
+ const inputJSONSchema = tool.inputJSONSchema;
304991
+ const inputSchema17 = inputJSONSchema ? jsonStringify(inputJSONSchema) : tool.inputSchema ? jsonStringify(zodToJsonSchema3(tool.inputSchema)) : "";
304569
304992
  return tool.name.length + description.length + inputSchema17.length;
304570
304993
  }));
304571
304994
  return sizes.reduce((total, size) => total + size, 0);
@@ -306264,12 +306687,13 @@ function filterSwarmFieldsFromSchema(toolName, schema) {
306264
306687
  return filtered;
306265
306688
  }
306266
306689
  async function toolToAPISchema(tool, options2) {
306267
- const cacheKey = "inputJSONSchema" in tool && tool.inputJSONSchema ? `${tool.name}:${jsonStringify(tool.inputJSONSchema)}` : tool.name;
306690
+ const inputJSONSchema = tool.inputJSONSchema;
306691
+ const cacheKey = inputJSONSchema ? `${tool.name}:${jsonStringify(inputJSONSchema)}` : tool.name;
306268
306692
  const cache3 = getToolSchemaCache();
306269
306693
  let base2 = cache3.get(cacheKey);
306270
306694
  if (!base2) {
306271
306695
  const strictToolsEnabled = checkStatsigFeatureGate_CACHED_MAY_BE_STALE("tengu_tool_pear");
306272
- let input_schema = "inputJSONSchema" in tool && tool.inputJSONSchema ? tool.inputJSONSchema : zodToJsonSchema3(tool.inputSchema);
306696
+ let input_schema = inputJSONSchema ?? zodToJsonSchema3(tool.inputSchema);
306273
306697
  if (!isAgentSwarmsEnabled()) {
306274
306698
  input_schema = filterSwarmFieldsFromSchema(tool.name, input_schema);
306275
306699
  }
@@ -306512,11 +306936,13 @@ async function logContextMetrics(mcpConfigs, toolPermissionContext) {
306512
306936
  }
306513
306937
  mcpServersCount = serverNames.size;
306514
306938
  for (const tool of mcpTools) {
306515
- const schema = "inputJSONSchema" in tool && tool.inputJSONSchema ? tool.inputJSONSchema : zodToJsonSchema3(tool.inputSchema);
306939
+ const inputJSONSchema = tool.inputJSONSchema;
306940
+ const schema = inputJSONSchema ?? zodToJsonSchema3(tool.inputSchema);
306516
306941
  mcpToolsTokens += roughTokenCountEstimation(jsonStringify(schema));
306517
306942
  }
306518
306943
  for (const tool of nonMcpTools) {
306519
- const schema = "inputJSONSchema" in tool && tool.inputJSONSchema ? tool.inputJSONSchema : zodToJsonSchema3(tool.inputSchema);
306944
+ const inputJSONSchema = tool.inputJSONSchema;
306945
+ const schema = inputJSONSchema ?? zodToJsonSchema3(tool.inputSchema);
306520
306946
  nonMcpToolsTokens += roughTokenCountEstimation(jsonStringify(schema));
306521
306947
  }
306522
306948
  logEvent("tengu_context_size", {
@@ -309470,14 +309896,14 @@ var init_permissions2 = __esm(() => {
309470
309896
  });
309471
309897
 
309472
309898
  // src/lib/addDirValidation.ts
309473
- import { dirname as dirname40, resolve as resolve31 } from "path";
309899
+ import { dirname as dirname40, resolve as resolve32 } from "path";
309474
309900
  async function validateDirectoryForWorkspace(directoryPath, permissionContext) {
309475
309901
  if (!directoryPath) {
309476
309902
  return {
309477
309903
  resultType: "emptyPath"
309478
309904
  };
309479
309905
  }
309480
- const absolutePath = resolve31(expandPath(directoryPath));
309906
+ const absolutePath = resolve32(expandPath(directoryPath));
309481
309907
  try {
309482
309908
  const stats = await getFsImplementation().stat(absolutePath);
309483
309909
  if (!stats.isDirectory()) {
@@ -309539,7 +309965,7 @@ var init_addDirValidation = __esm(() => {
309539
309965
 
309540
309966
  // src/permissions/permissionSetup.ts
309541
309967
  import { relative as relative14 } from "path";
309542
- import { resolve as resolve32 } from "path";
309968
+ import { resolve as resolve33 } from "path";
309543
309969
  function isDangerousBashPermission(toolName, ruleContent) {
309544
309970
  if (toolName !== BASH_TOOL_NAME) {
309545
309971
  return false;
@@ -309854,7 +310280,7 @@ function isSymlinkTo({
309854
310280
  originalCwd
309855
310281
  }) {
309856
310282
  const { resolvedPath: resolvedProcessPwd, isSymlink: isProcessPwdSymlink } = safeResolvePath(getFsImplementation(), processPwd);
309857
- return isProcessPwdSymlink ? resolvedProcessPwd === resolve32(originalCwd) : false;
310283
+ return isProcessPwdSymlink ? resolvedProcessPwd === resolve33(originalCwd) : false;
309858
310284
  }
309859
310285
  function initialPermissionModeFromCLI({
309860
310286
  permissionModeCli,
@@ -310160,7 +310586,7 @@ var init_permissionSetup = __esm(() => {
310160
310586
 
310161
310587
  // src/capabilities/markdownConfigLoader.ts
310162
310588
  import { homedir as homedir23 } from "os";
310163
- import { dirname as dirname41, join as join79, resolve as resolve33, sep as sep21 } from "path";
310589
+ import { dirname as dirname41, join as join79, resolve as resolve34, sep as sep21 } from "path";
310164
310590
  function extractDescriptionFromMarkdown(content, defaultDescription = "Custom item") {
310165
310591
  const lines = content.split(`
310166
310592
  `);
@@ -310242,9 +310668,9 @@ function resolveStopBoundary(cwd) {
310242
310668
  return cwdGitRoot;
310243
310669
  }
310244
310670
  function getProjectDirsUpToHome(subdir, cwd) {
310245
- const home = resolve33(homedir23()).normalize("NFC");
310671
+ const home = resolve34(homedir23()).normalize("NFC");
310246
310672
  const gitRoot = resolveStopBoundary(cwd);
310247
- let current = resolve33(cwd);
310673
+ let current = resolve34(cwd);
310248
310674
  const dirs = [];
310249
310675
  while (true) {
310250
310676
  if (normalizePathForComparison(current) === normalizePathForComparison(home)) {
@@ -314525,8 +314951,8 @@ class Project {
314525
314951
  decrementPendingWrites() {
314526
314952
  this.pendingWriteCount--;
314527
314953
  if (this.pendingWriteCount === 0) {
314528
- for (const resolve34 of this.flushResolvers) {
314529
- resolve34();
314954
+ for (const resolve35 of this.flushResolvers) {
314955
+ resolve35();
314530
314956
  }
314531
314957
  this.flushResolvers = [];
314532
314958
  }
@@ -314540,13 +314966,13 @@ class Project {
314540
314966
  }
314541
314967
  }
314542
314968
  enqueueWrite(filePath, entry) {
314543
- return new Promise((resolve34) => {
314969
+ return new Promise((resolve35) => {
314544
314970
  let queue3 = this.writeQueues.get(filePath);
314545
314971
  if (!queue3) {
314546
314972
  queue3 = [];
314547
314973
  this.writeQueues.set(filePath, queue3);
314548
314974
  }
314549
- queue3.push({ entry, resolve: resolve34 });
314975
+ queue3.push({ entry, resolve: resolve35 });
314550
314976
  this.scheduleDrain();
314551
314977
  });
314552
314978
  }
@@ -314580,7 +315006,7 @@ class Project {
314580
315006
  const batch = queue3.splice(0);
314581
315007
  let content = "";
314582
315008
  const resolvers = [];
314583
- for (const { entry, resolve: resolve34 } of batch) {
315009
+ for (const { entry, resolve: resolve35 } of batch) {
314584
315010
  const line = jsonStringify(entry) + `
314585
315011
  `;
314586
315012
  if (content.length + line.length >= this.MAX_CHUNK_BYTES) {
@@ -314592,7 +315018,7 @@ class Project {
314592
315018
  content = "";
314593
315019
  }
314594
315020
  content += line;
314595
- resolvers.push(resolve34);
315021
+ resolvers.push(resolve35);
314596
315022
  }
314597
315023
  if (content.length > 0) {
314598
315024
  await this.appendToFile(filePath, content);
@@ -314715,8 +315141,8 @@ class Project {
314715
315141
  if (this.pendingWriteCount === 0) {
314716
315142
  return;
314717
315143
  }
314718
- return new Promise((resolve34) => {
314719
- this.flushResolvers.push(resolve34);
315144
+ return new Promise((resolve35) => {
315145
+ this.flushResolvers.push(resolve35);
314720
315146
  });
314721
315147
  }
314722
315148
  async removeMessageByUuid(targetUuid) {
@@ -315568,7 +315994,7 @@ function applySnipRemovals(messages) {
315568
315994
  messages.delete(uuid3);
315569
315995
  removedCount++;
315570
315996
  }
315571
- const resolve34 = (start) => {
315997
+ const resolve35 = (start) => {
315572
315998
  const path13 = [];
315573
315999
  let cur = start;
315574
316000
  while (cur && toDelete.has(cur)) {
@@ -315587,7 +316013,7 @@ function applySnipRemovals(messages) {
315587
316013
  for (const [uuid3, msg] of messages) {
315588
316014
  if (!msg.parentUuid || !toDelete.has(msg.parentUuid))
315589
316015
  continue;
315590
- messages.set(uuid3, { ...msg, parentUuid: resolve34(msg.parentUuid) });
316016
+ messages.set(uuid3, { ...msg, parentUuid: resolve35(msg.parentUuid) });
315591
316017
  relinkedCount++;
315592
316018
  }
315593
316019
  logEvent("tengu_snip_resume_filtered", {
@@ -318588,8 +319014,8 @@ class DiskTaskOutput {
318588
319014
  this.#queue.push(content);
318589
319015
  }
318590
319016
  if (!this.#flushPromise) {
318591
- this.#flushPromise = new Promise((resolve34) => {
318592
- this.#flushResolve = resolve34;
319017
+ this.#flushPromise = new Promise((resolve35) => {
319018
+ this.#flushResolve = resolve35;
318593
319019
  });
318594
319020
  track(this.#drain());
318595
319021
  }
@@ -318655,10 +319081,10 @@ class DiskTaskOutput {
318655
319081
  }
318656
319082
  }
318657
319083
  } finally {
318658
- const resolve34 = this.#flushResolve;
319084
+ const resolve35 = this.#flushResolve;
318659
319085
  this.#flushPromise = null;
318660
319086
  this.#flushResolve = null;
318661
- resolve34();
319087
+ resolve35();
318662
319088
  }
318663
319089
  }
318664
319090
  }
@@ -318944,17 +319370,17 @@ class ShellCommandImpl {
318944
319370
  });
318945
319371
  this.#childProcess.once("exit", this.#exitHandler.bind(this));
318946
319372
  this.#childProcess.once("error", this.#errorHandler.bind(this));
318947
- this.#stdioClosedPromise = new Promise((resolve34) => {
319373
+ this.#stdioClosedPromise = new Promise((resolve35) => {
318948
319374
  this.#childProcess.once("close", () => {
318949
- resolve34();
319375
+ resolve35();
318950
319376
  });
318951
319377
  });
318952
319378
  this.#timeoutId = setTimeout(ShellCommandImpl.#handleTimeout, this.#timeout, this);
318953
- const exitPromise = new Promise((resolve34) => {
318954
- this.#exitCodeResolver = resolve34;
319379
+ const exitPromise = new Promise((resolve35) => {
319380
+ this.#exitCodeResolver = resolve35;
318955
319381
  });
318956
- return new Promise((resolve34) => {
318957
- this.#resultResolver = resolve34;
319382
+ return new Promise((resolve35) => {
319383
+ this.#resultResolver = resolve35;
318958
319384
  exitPromise.then(this.#handleExit.bind(this));
318959
319385
  });
318960
319386
  }
@@ -319002,8 +319428,8 @@ class ShellCommandImpl {
319002
319428
  const graceMs = code === 0 ? OUTPUT_CLOSE_GRACE_MS : ERROR_OUTPUT_CLOSE_GRACE_MS;
319003
319429
  await Promise.race([
319004
319430
  stdioClosedPromise,
319005
- new Promise((resolve34) => {
319006
- const timeout = setTimeout(resolve34, graceMs);
319431
+ new Promise((resolve35) => {
319432
+ const timeout = setTimeout(resolve35, graceMs);
319007
319433
  timeout.unref();
319008
319434
  })
319009
319435
  ]);
@@ -320126,7 +320552,7 @@ function executeInBackground({
320126
320552
  }) {
320127
320553
  if (asyncRewake) {
320128
320554
  shellCommand.result.then(async (result) => {
320129
- await new Promise((resolve34) => setImmediate(resolve34));
320555
+ await new Promise((resolve35) => setImmediate(resolve35));
320130
320556
  const stdout = await shellCommand.taskOutput.getStdout();
320131
320557
  const stderr = shellCommand.taskOutput.getStderr();
320132
320558
  shellCommand.cleanup();
@@ -320569,8 +320995,8 @@ async function execCommandHook(hook, hookEvent, hookName, jsonInput, signal, hoo
320569
320995
  child.stderr.setEncoding("utf8");
320570
320996
  let initialResponseChecked = false;
320571
320997
  let asyncResolve = null;
320572
- const childIsAsyncPromise = new Promise((resolve34) => {
320573
- asyncResolve = resolve34;
320998
+ const childIsAsyncPromise = new Promise((resolve35) => {
320999
+ asyncResolve = resolve35;
320574
321000
  });
320575
321001
  const processedPromptLines = new Set;
320576
321002
  let promptChain = Promise.resolve();
@@ -320661,13 +321087,13 @@ async function execCommandHook(hook, hookEvent, hookName, jsonInput, signal, hoo
320661
321087
  hookEvent,
320662
321088
  getOutput: async () => ({ stdout, stderr, output })
320663
321089
  });
320664
- const stdoutEndPromise = new Promise((resolve34) => {
320665
- child.stdout.on("end", () => resolve34());
321090
+ const stdoutEndPromise = new Promise((resolve35) => {
321091
+ child.stdout.on("end", () => resolve35());
320666
321092
  });
320667
- const stderrEndPromise = new Promise((resolve34) => {
320668
- child.stderr.on("end", () => resolve34());
321093
+ const stderrEndPromise = new Promise((resolve35) => {
321094
+ child.stderr.on("end", () => resolve35());
320669
321095
  });
320670
- const stdinWritePromise = stdinWritten ? Promise.resolve() : new Promise((resolve34, reject2) => {
321096
+ const stdinWritePromise = stdinWritten ? Promise.resolve() : new Promise((resolve35, reject2) => {
320671
321097
  child.stdin.on("error", (err2) => {
320672
321098
  if (!requestPrompt) {
320673
321099
  reject2(err2);
@@ -320680,12 +321106,12 @@ async function execCommandHook(hook, hookEvent, hookName, jsonInput, signal, hoo
320680
321106
  if (!requestPrompt) {
320681
321107
  child.stdin.end();
320682
321108
  }
320683
- resolve34();
321109
+ resolve35();
320684
321110
  });
320685
321111
  const childErrorPromise = new Promise((_, reject2) => {
320686
321112
  child.on("error", reject2);
320687
321113
  });
320688
- const childClosePromise = new Promise((resolve34) => {
321114
+ const childClosePromise = new Promise((resolve35) => {
320689
321115
  let exitCode = null;
320690
321116
  child.on("close", (code) => {
320691
321117
  exitCode = code ?? 1;
@@ -320693,7 +321119,7 @@ async function execCommandHook(hook, hookEvent, hookName, jsonInput, signal, hoo
320693
321119
  const finalStdout = processedPromptLines.size === 0 ? stdout : stdout.split(`
320694
321120
  `).filter((line) => !processedPromptLines.has(line.trim())).join(`
320695
321121
  `);
320696
- resolve34({
321122
+ resolve35({
320697
321123
  stdout: finalStdout,
320698
321124
  stderr,
320699
321125
  output,
@@ -322748,12 +323174,12 @@ async function executeFunctionHook({
322748
323174
  hook
322749
323175
  };
322750
323176
  }
322751
- const passed = await new Promise((resolve34, reject2) => {
323177
+ const passed = await new Promise((resolve35, reject2) => {
322752
323178
  const onAbort = () => reject2(new Error("Function hook cancelled"));
322753
323179
  abortSignal.addEventListener("abort", onAbort);
322754
323180
  Promise.resolve(hook.callback(messages, abortSignal)).then((result) => {
322755
323181
  abortSignal.removeEventListener("abort", onAbort);
322756
- resolve34(result);
323182
+ resolve35(result);
322757
323183
  }).catch((error41) => {
322758
323184
  abortSignal.removeEventListener("abort", onAbort);
322759
323185
  reject2(error41);
@@ -322965,6 +323391,7 @@ __export(exports_worktree, {
322965
323391
  killTmuxSession: () => killTmuxSession,
322966
323392
  keepWorktree: () => keepWorktree,
322967
323393
  isTmuxAvailable: () => isTmuxAvailable2,
323394
+ isAgentWorktreeIsolationAvailable: () => isAgentWorktreeIsolationAvailable,
322968
323395
  hasWorktreeChanges: () => hasWorktreeChanges,
322969
323396
  getTmuxInstallInstructions: () => getTmuxInstallInstructions2,
322970
323397
  getCurrentWorktreeSession: () => getCurrentWorktreeSession,
@@ -322977,7 +323404,7 @@ __export(exports_worktree, {
322977
323404
  cleanupWorktree: () => cleanupWorktree,
322978
323405
  cleanupStaleAgentWorktrees: () => cleanupStaleAgentWorktrees
322979
323406
  });
322980
- import { spawnSync as spawnSync3 } from "child_process";
323407
+ import { spawnSync as spawnSync4 } from "child_process";
322981
323408
  import { basename as basename26, dirname as dirname43, join as join84 } from "path";
322982
323409
  function validateWorktreeSlug(slug) {
322983
323410
  if (slug.length > MAX_WORKTREE_SLUG_LENGTH) {
@@ -323406,10 +323833,11 @@ async function createAgentWorktree(slug) {
323406
323833
  logForDebugging2(`Created hook-based agent worktree at: ${hookResult.worktreePath}`);
323407
323834
  return { worktreePath: hookResult.worktreePath, hookBased: true };
323408
323835
  }
323409
- const gitRoot = findCanonicalGitRoot(getCwd3());
323410
- if (!gitRoot) {
323411
- throw new Error("Cannot create agent worktree: not in a git repository and no WorktreeCreate hooks are configured. " + "Configure WorktreeCreate/WorktreeRemove hooks in settings.json to use worktree isolation with other VCS systems.");
323836
+ const availability = resolveGitWorktreeAvailability(getCwd3(), gitExe());
323837
+ if (!availability.available) {
323838
+ throw new WorktreeUnavailableError(availability.reason);
323412
323839
  }
323840
+ const gitRoot = findCanonicalGitRoot(availability.gitRoot) ?? availability.gitRoot;
323413
323841
  const { worktreePath, worktreeBranch, headCommit, existed } = await getOrCreateWorktree(gitRoot, slug);
323414
323842
  if (!existed) {
323415
323843
  logForDebugging2(`Created agent worktree at: ${worktreePath} on branch: ${worktreeBranch}`);
@@ -323421,6 +323849,16 @@ async function createAgentWorktree(slug) {
323421
323849
  }
323422
323850
  return { worktreePath, worktreeBranch, headCommit, gitRoot };
323423
323851
  }
323852
+ function isAgentWorktreeIsolationAvailable(options2 = {}) {
323853
+ try {
323854
+ if (options2.hasCreateHook ?? hasWorktreeCreateHook()) {
323855
+ return true;
323856
+ }
323857
+ return isGitWorktreeIsolationAvailable(options2.cwd ?? getCwd3(), gitExe(), options2.gitAvailabilityCache);
323858
+ } catch {
323859
+ return false;
323860
+ }
323861
+ }
323424
323862
  async function removeAgentWorktree(worktreePath, worktreeBranch, gitRoot, hookBased) {
323425
323863
  if (hookBased) {
323426
323864
  const hookRan = await executeWorktreeRemoveHook(worktreePath);
@@ -323536,7 +323974,7 @@ async function execIntoTmuxWorktree(args) {
323536
323974
  error: "Error: --tmux is not supported on Windows"
323537
323975
  };
323538
323976
  }
323539
- const tmuxCheck = spawnSync3("tmux", ["-V"], { encoding: "utf-8" });
323977
+ const tmuxCheck = spawnSync4("tmux", ["-V"], { encoding: "utf-8" });
323540
323978
  if (tmuxCheck.status !== 0) {
323541
323979
  const installHint = process.platform === "darwin" ? "Install tmux with: brew install tmux" : "Install tmux with: sudo apt install tmux";
323542
323980
  return {
@@ -323641,7 +324079,7 @@ async function execIntoTmuxWorktree(args) {
323641
324079
  newArgs.push(arg);
323642
324080
  }
323643
324081
  let tmuxPrefix = "C-b";
323644
- const prefixResult = spawnSync3("tmux", ["show-options", "-g", "prefix"], {
324082
+ const prefixResult = spawnSync4("tmux", ["show-options", "-g", "prefix"], {
323645
324083
  encoding: "utf-8"
323646
324084
  });
323647
324085
  if (prefixResult.status === 0 && prefixResult.stdout) {
@@ -323668,7 +324106,7 @@ async function execIntoTmuxWorktree(args) {
323668
324106
  CLAUDE_CODE_TMUX_PREFIX: tmuxPrefix,
323669
324107
  CLAUDE_CODE_TMUX_PREFIX_CONFLICTS: prefixConflicts ? "1" : ""
323670
324108
  };
323671
- const hasSessionResult = spawnSync3("tmux", ["has-session", "-t", tmuxSessionName], { encoding: "utf-8" });
324109
+ const hasSessionResult = spawnSync4("tmux", ["has-session", "-t", tmuxSessionName], { encoding: "utf-8" });
323672
324110
  const sessionExists = hasSessionResult.status === 0;
323673
324111
  const isAlreadyInTmux = Boolean(process.env.TMUX);
323674
324112
  const useControlMode = isInITerm2() && !forceClassicTmux && !isAlreadyInTmux;
@@ -323686,7 +324124,7 @@ ${y2("╭─ iTerm2 Tip ──────────────────
323686
324124
  const isClaudeCliInternal = repoName === "claude-cli-internal";
323687
324125
  const shouldSetupDevPanes = isAnt && isClaudeCliInternal && !sessionExists;
323688
324126
  if (shouldSetupDevPanes) {
323689
- spawnSync3("tmux", [
324127
+ spawnSync4("tmux", [
323690
324128
  "new-session",
323691
324129
  "-d",
323692
324130
  "-s",
@@ -323697,21 +324135,21 @@ ${y2("╭─ iTerm2 Tip ──────────────────
323697
324135
  process.execPath,
323698
324136
  ...newArgs
323699
324137
  ], { cwd: worktreeDir, env: tmuxEnv });
323700
- spawnSync3("tmux", ["split-window", "-h", "-t", tmuxSessionName, "-c", worktreeDir], { cwd: worktreeDir });
323701
- spawnSync3("tmux", ["send-keys", "-t", tmuxSessionName, "bun run watch", "Enter"], { cwd: worktreeDir });
323702
- spawnSync3("tmux", ["split-window", "-v", "-t", tmuxSessionName, "-c", worktreeDir], { cwd: worktreeDir });
323703
- spawnSync3("tmux", ["send-keys", "-t", tmuxSessionName, "bun run start"], {
324138
+ spawnSync4("tmux", ["split-window", "-h", "-t", tmuxSessionName, "-c", worktreeDir], { cwd: worktreeDir });
324139
+ spawnSync4("tmux", ["send-keys", "-t", tmuxSessionName, "bun run watch", "Enter"], { cwd: worktreeDir });
324140
+ spawnSync4("tmux", ["split-window", "-v", "-t", tmuxSessionName, "-c", worktreeDir], { cwd: worktreeDir });
324141
+ spawnSync4("tmux", ["send-keys", "-t", tmuxSessionName, "bun run start"], {
323704
324142
  cwd: worktreeDir
323705
324143
  });
323706
- spawnSync3("tmux", ["select-pane", "-t", `${tmuxSessionName}:0.0`], {
324144
+ spawnSync4("tmux", ["select-pane", "-t", `${tmuxSessionName}:0.0`], {
323707
324145
  cwd: worktreeDir
323708
324146
  });
323709
324147
  if (isAlreadyInTmux) {
323710
- spawnSync3("tmux", ["switch-client", "-t", tmuxSessionName], {
324148
+ spawnSync4("tmux", ["switch-client", "-t", tmuxSessionName], {
323711
324149
  stdio: "inherit"
323712
324150
  });
323713
324151
  } else {
323714
- spawnSync3("tmux", [...tmuxGlobalArgs, "attach-session", "-t", tmuxSessionName], {
324152
+ spawnSync4("tmux", [...tmuxGlobalArgs, "attach-session", "-t", tmuxSessionName], {
323715
324153
  stdio: "inherit",
323716
324154
  cwd: worktreeDir
323717
324155
  });
@@ -323719,11 +324157,11 @@ ${y2("╭─ iTerm2 Tip ──────────────────
323719
324157
  } else {
323720
324158
  if (isAlreadyInTmux) {
323721
324159
  if (sessionExists) {
323722
- spawnSync3("tmux", ["switch-client", "-t", tmuxSessionName], {
324160
+ spawnSync4("tmux", ["switch-client", "-t", tmuxSessionName], {
323723
324161
  stdio: "inherit"
323724
324162
  });
323725
324163
  } else {
323726
- spawnSync3("tmux", [
324164
+ spawnSync4("tmux", [
323727
324165
  "new-session",
323728
324166
  "-d",
323729
324167
  "-s",
@@ -323734,7 +324172,7 @@ ${y2("╭─ iTerm2 Tip ──────────────────
323734
324172
  process.execPath,
323735
324173
  ...newArgs
323736
324174
  ], { cwd: worktreeDir, env: tmuxEnv });
323737
- spawnSync3("tmux", ["switch-client", "-t", tmuxSessionName], {
324175
+ spawnSync4("tmux", ["switch-client", "-t", tmuxSessionName], {
323738
324176
  stdio: "inherit"
323739
324177
  });
323740
324178
  }
@@ -323751,7 +324189,7 @@ ${y2("╭─ iTerm2 Tip ──────────────────
323751
324189
  process.execPath,
323752
324190
  ...newArgs
323753
324191
  ];
323754
- spawnSync3("tmux", tmuxArgs, {
324192
+ spawnSync4("tmux", tmuxArgs, {
323755
324193
  stdio: "inherit",
323756
324194
  cwd: worktreeDir,
323757
324195
  env: tmuxEnv
@@ -323778,6 +324216,7 @@ var init_worktree = __esm(() => {
323778
324216
  init_settings2();
323779
324217
  init_detection();
323780
324218
  init_fsOperations();
324219
+ init_worktreeAvailability();
323781
324220
  import_ignore4 = __toESM(require_ignore(), 1);
323782
324221
  VALID_WORKTREE_SLUG_SEGMENT = /^[a-zA-Z0-9._-]+$/;
323783
324222
  GIT_NO_PROMPT_ENV2 = {
@@ -324007,10 +324446,10 @@ function sequential(fn) {
324007
324446
  return;
324008
324447
  processing = true;
324009
324448
  while (queue3.length > 0) {
324010
- const { args, resolve: resolve34, reject: reject2, context: context4 } = queue3.shift();
324449
+ const { args, resolve: resolve35, reject: reject2, context: context4 } = queue3.shift();
324011
324450
  try {
324012
324451
  const result = await fn.apply(context4, args);
324013
- resolve34(result);
324452
+ resolve35(result);
324014
324453
  } catch (error41) {
324015
324454
  reject2(error41);
324016
324455
  }
@@ -324021,8 +324460,8 @@ function sequential(fn) {
324021
324460
  }
324022
324461
  }
324023
324462
  return function(...args) {
324024
- return new Promise((resolve34, reject2) => {
324025
- queue3.push({ args, resolve: resolve34, reject: reject2, context: this });
324463
+ return new Promise((resolve35, reject2) => {
324464
+ queue3.push({ args, resolve: resolve35, reject: reject2, context: this });
324026
324465
  processQueue();
324027
324466
  });
324028
324467
  };
@@ -326550,14 +326989,14 @@ See https://react.dev/link/invalid-hook-call for tips about how to debug and fix
326550
326989
  prevActScopeDepth !== actScopeDepth - 1 && console.error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. ");
326551
326990
  actScopeDepth = prevActScopeDepth;
326552
326991
  }
326553
- function recursivelyFlushAsyncActWork(returnValue2, resolve34, reject2) {
326992
+ function recursivelyFlushAsyncActWork(returnValue2, resolve35, reject2) {
326554
326993
  var queue3 = ReactSharedInternals.actQueue;
326555
326994
  if (queue3 !== null)
326556
326995
  if (queue3.length !== 0)
326557
326996
  try {
326558
326997
  flushActQueue(queue3);
326559
326998
  enqueueTask(function() {
326560
- return recursivelyFlushAsyncActWork(returnValue2, resolve34, reject2);
326999
+ return recursivelyFlushAsyncActWork(returnValue2, resolve35, reject2);
326561
327000
  });
326562
327001
  return;
326563
327002
  } catch (error41) {
@@ -326565,7 +327004,7 @@ See https://react.dev/link/invalid-hook-call for tips about how to debug and fix
326565
327004
  }
326566
327005
  else
326567
327006
  ReactSharedInternals.actQueue = null;
326568
- 0 < ReactSharedInternals.thrownErrors.length ? (queue3 = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject2(queue3)) : resolve34(returnValue2);
327007
+ 0 < ReactSharedInternals.thrownErrors.length ? (queue3 = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject2(queue3)) : resolve35(returnValue2);
326569
327008
  }
326570
327009
  function flushActQueue(queue3) {
326571
327010
  if (!isFlushing) {
@@ -326741,14 +327180,14 @@ See https://react.dev/link/invalid-hook-call for tips about how to debug and fix
326741
327180
  didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"));
326742
327181
  });
326743
327182
  return {
326744
- then: function(resolve34, reject2) {
327183
+ then: function(resolve35, reject2) {
326745
327184
  didAwaitActCall = true;
326746
327185
  thenable.then(function(returnValue2) {
326747
327186
  popActScope(prevActQueue, prevActScopeDepth);
326748
327187
  if (prevActScopeDepth === 0) {
326749
327188
  try {
326750
327189
  flushActQueue(queue3), enqueueTask(function() {
326751
- return recursivelyFlushAsyncActWork(returnValue2, resolve34, reject2);
327190
+ return recursivelyFlushAsyncActWork(returnValue2, resolve35, reject2);
326752
327191
  });
326753
327192
  } catch (error$0) {
326754
327193
  ReactSharedInternals.thrownErrors.push(error$0);
@@ -326759,7 +327198,7 @@ See https://react.dev/link/invalid-hook-call for tips about how to debug and fix
326759
327198
  reject2(_thrownError);
326760
327199
  }
326761
327200
  } else
326762
- resolve34(returnValue2);
327201
+ resolve35(returnValue2);
326763
327202
  }, function(error41) {
326764
327203
  popActScope(prevActQueue, prevActScopeDepth);
326765
327204
  0 < ReactSharedInternals.thrownErrors.length ? (error41 = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject2(error41)) : reject2(error41);
@@ -326775,11 +327214,11 @@ See https://react.dev/link/invalid-hook-call for tips about how to debug and fix
326775
327214
  if (0 < ReactSharedInternals.thrownErrors.length)
326776
327215
  throw callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
326777
327216
  return {
326778
- then: function(resolve34, reject2) {
327217
+ then: function(resolve35, reject2) {
326779
327218
  didAwaitActCall = true;
326780
327219
  prevActScopeDepth === 0 ? (ReactSharedInternals.actQueue = queue3, enqueueTask(function() {
326781
- return recursivelyFlushAsyncActWork(returnValue$jscomp$0, resolve34, reject2);
326782
- })) : resolve34(returnValue$jscomp$0);
327220
+ return recursivelyFlushAsyncActWork(returnValue$jscomp$0, resolve35, reject2);
327221
+ })) : resolve35(returnValue$jscomp$0);
326783
327222
  }
326784
327223
  };
326785
327224
  };
@@ -333406,8 +333845,8 @@ It can also happen if the client has a browser extension installed which messes
333406
333845
  currentEntangledActionThenable = {
333407
333846
  status: "pending",
333408
333847
  value: undefined,
333409
- then: function(resolve34) {
333410
- entangledListeners.push(resolve34);
333848
+ then: function(resolve35) {
333849
+ entangledListeners.push(resolve35);
333411
333850
  }
333412
333851
  };
333413
333852
  }
@@ -333431,8 +333870,8 @@ It can also happen if the client has a browser extension installed which messes
333431
333870
  status: "pending",
333432
333871
  value: null,
333433
333872
  reason: null,
333434
- then: function(resolve34) {
333435
- listeners.push(resolve34);
333873
+ then: function(resolve35) {
333874
+ listeners.push(resolve35);
333436
333875
  }
333437
333876
  };
333438
333877
  thenable.then(function() {
@@ -342767,13 +343206,13 @@ function getEventPriority(eventType) {
342767
343206
  case "focus":
342768
343207
  case "blur":
342769
343208
  case "paste":
342770
- return import_constants52.DiscreteEventPriority;
343209
+ return import_constants53.DiscreteEventPriority;
342771
343210
  case "resize":
342772
343211
  case "scroll":
342773
343212
  case "mousemove":
342774
- return import_constants52.ContinuousEventPriority;
343213
+ return import_constants53.ContinuousEventPriority;
342775
343214
  default:
342776
- return import_constants52.DefaultEventPriority;
343215
+ return import_constants53.DefaultEventPriority;
342777
343216
  }
342778
343217
  }
342779
343218
 
@@ -342788,7 +343227,7 @@ class Dispatcher {
342788
343227
  if (this.currentEvent) {
342789
343228
  return getEventPriority(this.currentEvent.type);
342790
343229
  }
342791
- return import_constants52.DefaultEventPriority;
343230
+ return import_constants53.DefaultEventPriority;
342792
343231
  }
342793
343232
  dispatch(target, event) {
342794
343233
  const previousEvent = this.currentEvent;
@@ -342813,18 +343252,18 @@ class Dispatcher {
342813
343252
  dispatchContinuous(target, event) {
342814
343253
  const previousPriority = this.currentUpdatePriority;
342815
343254
  try {
342816
- this.currentUpdatePriority = import_constants52.ContinuousEventPriority;
343255
+ this.currentUpdatePriority = import_constants53.ContinuousEventPriority;
342817
343256
  return this.dispatch(target, event);
342818
343257
  } finally {
342819
343258
  this.currentUpdatePriority = previousPriority;
342820
343259
  }
342821
343260
  }
342822
343261
  }
342823
- var import_constants52, NO_EVENT_PRIORITY = 0;
343262
+ var import_constants53, NO_EVENT_PRIORITY = 0;
342824
343263
  var init_dispatcher = __esm(() => {
342825
343264
  init_log2();
342826
343265
  init_event_handlers();
342827
- import_constants52 = __toESM(require_constants9(), 1);
343266
+ import_constants53 = __toESM(require_constants9(), 1);
342828
343267
  });
342829
343268
 
342830
343269
  // src/cli/events/terminal-event.ts
@@ -345126,8 +345565,8 @@ function setTerminalFocused(v) {
345126
345565
  cb();
345127
345566
  }
345128
345567
  if (!v) {
345129
- for (const resolve34 of resolvers) {
345130
- resolve34();
345568
+ for (const resolve35 of resolvers) {
345569
+ resolve35();
345131
345570
  }
345132
345571
  resolvers.clear();
345133
345572
  }
@@ -345165,18 +345604,18 @@ class TerminalQuerier {
345165
345604
  this.stdout = stdout;
345166
345605
  }
345167
345606
  send(query2) {
345168
- return new Promise((resolve34) => {
345607
+ return new Promise((resolve35) => {
345169
345608
  this.queue.push({
345170
345609
  kind: "query",
345171
345610
  match: query2.match,
345172
- resolve: (r) => resolve34(r)
345611
+ resolve: (r) => resolve35(r)
345173
345612
  });
345174
345613
  this.stdout.write(query2.request);
345175
345614
  });
345176
345615
  }
345177
345616
  flush() {
345178
- return new Promise((resolve34) => {
345179
- this.queue.push({ kind: "sentinel", resolve: resolve34 });
345617
+ return new Promise((resolve35) => {
345618
+ this.queue.push({ kind: "sentinel", resolve: resolve35 });
345180
345619
  this.stdout.write(SENTINEL);
345181
345620
  });
345182
345621
  }
@@ -349126,7 +349565,7 @@ function applyPositionedHighlight(screen, stylePool, positions, rowOffset, curre
349126
349565
  }
349127
349566
  return true;
349128
349567
  }
349129
- var import_constants54, timing;
349568
+ var import_constants55, timing;
349130
349569
  var init_render_to_screen = __esm(() => {
349131
349570
  init_debug();
349132
349571
  init_dom();
@@ -349135,7 +349574,7 @@ var init_render_to_screen = __esm(() => {
349135
349574
  init_reconciler();
349136
349575
  init_render_node_to_output();
349137
349576
  init_screen();
349138
- import_constants54 = __toESM(require_constants9(), 1);
349577
+ import_constants55 = __toESM(require_constants9(), 1);
349139
349578
  timing = { reconcile: 0, yoga: 0, paint: 0, scan: 0, calls: 0 };
349140
349579
  });
349141
349580
 
@@ -349452,7 +349891,7 @@ class Ink {
349452
349891
  };
349453
349892
  }
349454
349893
  };
349455
- this.container = reconciler_default.createContainer(this.rootNode, import_constants55.LegacyRoot, null, false, null, "id", noop_default, (error41) => {
349894
+ this.container = reconciler_default.createContainer(this.rootNode, import_constants56.LegacyRoot, null, false, null, "id", noop_default, (error41) => {
349456
349895
  this.reportRenderError("uncaught", error41);
349457
349896
  }, (error41) => {
349458
349897
  this.reportRenderError("caught", error41);
@@ -350165,8 +350604,8 @@ class Ink {
350165
350604
  }
350166
350605
  }
350167
350606
  async waitUntilExit() {
350168
- this.exitPromise ||= new Promise((resolve34, reject2) => {
350169
- this.resolveExitPromise = resolve34;
350607
+ this.exitPromise ||= new Promise((resolve35, reject2) => {
350608
+ this.resolveExitPromise = resolve35;
350170
350609
  this.rejectExitPromise = reject2;
350171
350610
  });
350172
350611
  return this.exitPromise;
@@ -350273,7 +350712,7 @@ function drainStdin(stdin = process.stdin) {
350273
350712
  }
350274
350713
  }
350275
350714
  }
350276
- var import_constants55, jsx_dev_runtime9, ALT_SCREEN_ANCHOR_CURSOR, CURSOR_HOME_PATCH, ERASE_THEN_HOME_PATCH, CONSOLE_STDOUT_METHODS, CONSOLE_STDERR_METHODS;
350715
+ var import_constants56, jsx_dev_runtime9, ALT_SCREEN_ANCHOR_CURSOR, CURSOR_HOME_PATCH, ERASE_THEN_HOME_PATCH, CONSOLE_STDOUT_METHODS, CONSOLE_STDERR_METHODS;
350277
350716
  var init_ink = __esm(() => {
350278
350717
  init_noop();
350279
350718
  init_throttle2();
@@ -350305,7 +350744,7 @@ var init_ink = __esm(() => {
350305
350744
  init_dec2();
350306
350745
  init_osc2();
350307
350746
  init_useTerminalNotification();
350308
- import_constants55 = __toESM(require_constants9(), 1);
350747
+ import_constants56 = __toESM(require_constants9(), 1);
350309
350748
  jsx_dev_runtime9 = __toESM(require_jsx_dev_runtime(), 1);
350310
350749
  ALT_SCREEN_ANCHOR_CURSOR = Object.freeze({
350311
350750
  x: 0,
@@ -353739,8 +354178,8 @@ class Mailbox {
353739
354178
  return Promise.resolve(msg);
353740
354179
  }
353741
354180
  }
353742
- return new Promise((resolve34) => {
353743
- this.waiters.push({ fn, resolve: resolve34 });
354181
+ return new Promise((resolve35) => {
354182
+ this.waiters.push({ fn, resolve: resolve35 });
353744
354183
  });
353745
354184
  }
353746
354185
  subscribe = this.changed.subscribe;
@@ -358378,7 +358817,7 @@ var init_option_map = __esm(() => {
358378
358817
  });
358379
358818
 
358380
358819
  // src/cli/components/CustomSelect/use-select-navigation.ts
358381
- import { isDeepStrictEqual } from "util";
358820
+ import { isDeepStrictEqual as isDeepStrictEqual2 } from "util";
358382
358821
  function useSelectNavigation({
358383
358822
  visibleOptionCount = 5,
358384
358823
  options: options2,
@@ -358394,7 +358833,7 @@ function useSelectNavigation({
358394
358833
  const onFocusRef = import_react46.useRef(onFocus);
358395
358834
  onFocusRef.current = onFocus;
358396
358835
  const [lastOptions, setLastOptions] = import_react46.useState(options2);
358397
- if (options2 !== lastOptions && !isDeepStrictEqual(options2, lastOptions)) {
358836
+ if (options2 !== lastOptions && !isDeepStrictEqual2(options2, lastOptions)) {
358398
358837
  dispatch({
358399
358838
  type: "reset",
358400
358839
  state: createDefaultState({
@@ -358708,7 +359147,7 @@ var init_use_select_navigation = __esm(() => {
358708
359147
  });
358709
359148
 
358710
359149
  // src/cli/components/CustomSelect/use-multi-select-state.ts
358711
- import { isDeepStrictEqual as isDeepStrictEqual2 } from "util";
359150
+ import { isDeepStrictEqual as isDeepStrictEqual3 } from "util";
358712
359151
  function useMultiSelectState({
358713
359152
  isDisabled = false,
358714
359153
  visibleOptionCount = 5,
@@ -358728,7 +359167,7 @@ function useMultiSelectState({
358728
359167
  const [selectedValues, setSelectedValues] = import_react47.useState(defaultValue);
358729
359168
  const [isSubmitFocused, setIsSubmitFocused] = import_react47.useState(false);
358730
359169
  const [lastOptions, setLastOptions] = import_react47.useState(options2);
358731
- if (options2 !== lastOptions && !isDeepStrictEqual2(options2, lastOptions)) {
359170
+ if (options2 !== lastOptions && !isDeepStrictEqual3(options2, lastOptions)) {
358732
359171
  setSelectedValues(defaultValue);
358733
359172
  setLastOptions(options2);
358734
359173
  }
@@ -360913,7 +361352,7 @@ async function checkManagedSettingsSecurity(cachedSettings, newSettings) {
360913
361352
  return "no_check_needed";
360914
361353
  }
360915
361354
  logEvent("tengu_managed_settings_security_dialog_shown", {});
360916
- return new Promise((resolve34) => {
361355
+ return new Promise((resolve35) => {
360917
361356
  (async () => {
360918
361357
  const {
360919
361358
  unmount
@@ -360924,12 +361363,12 @@ async function checkManagedSettingsSecurity(cachedSettings, newSettings) {
360924
361363
  onAccept: () => {
360925
361364
  logEvent("tengu_managed_settings_security_dialog_accepted", {});
360926
361365
  unmount();
360927
- resolve34("approved");
361366
+ resolve35("approved");
360928
361367
  },
360929
361368
  onReject: () => {
360930
361369
  logEvent("tengu_managed_settings_security_dialog_rejected", {});
360931
361370
  unmount();
360932
- resolve34("rejected");
361371
+ resolve35("rejected");
360933
361372
  }
360934
361373
  }, undefined, false, undefined, this)
360935
361374
  }, undefined, false, undefined, this)
@@ -360968,8 +361407,8 @@ function initializeRemoteManagedSettingsLoadingPromise() {
360968
361407
  return;
360969
361408
  }
360970
361409
  if (isRemoteManagedSettingsEligible()) {
360971
- loadingCompletePromise2 = new Promise((resolve34) => {
360972
- loadingCompleteResolve2 = resolve34;
361410
+ loadingCompletePromise2 = new Promise((resolve35) => {
361411
+ loadingCompleteResolve2 = resolve35;
360973
361412
  setTimeout(() => {
360974
361413
  if (loadingCompleteResolve2) {
360975
361414
  logForDebugging2("Remote settings: Loading promise timed out, resolving anyway");
@@ -361224,8 +361663,8 @@ async function fetchAndLoadRemoteManagedSettings() {
361224
361663
  }
361225
361664
  async function loadRemoteManagedSettings() {
361226
361665
  if (isRemoteManagedSettingsEligible() && !loadingCompletePromise2) {
361227
- loadingCompletePromise2 = new Promise((resolve34) => {
361228
- loadingCompleteResolve2 = resolve34;
361666
+ loadingCompletePromise2 = new Promise((resolve35) => {
361667
+ loadingCompleteResolve2 = resolve35;
361229
361668
  });
361230
361669
  }
361231
361670
  if (getRemoteManagedSettingsSyncFromCache() && loadingCompleteResolve2) {
@@ -361497,7 +361936,7 @@ async function startNodeRelay(wsUrl, authHeader, wsAuthHeader) {
361497
361936
  cleanupConn(states.get(sock));
361498
361937
  });
361499
361938
  });
361500
- return new Promise((resolve34, reject2) => {
361939
+ return new Promise((resolve35, reject2) => {
361501
361940
  server.once("error", reject2);
361502
361941
  server.listen(0, "127.0.0.1", () => {
361503
361942
  const addr = server.address();
@@ -361505,7 +361944,7 @@ async function startNodeRelay(wsUrl, authHeader, wsAuthHeader) {
361505
361944
  reject2(new Error("upstreamproxy: server has no TCP address"));
361506
361945
  return;
361507
361946
  }
361508
- resolve34({
361947
+ resolve35({
361509
361948
  port: addr.port,
361510
361949
  stop: () => server.close()
361511
361950
  });
@@ -381298,7 +381737,7 @@ var HttpClient = class {
381298
381737
  } else if (extractStatus.status === "failed" || extractStatus.status === "cancelled") {
381299
381738
  throw new FirecrawlError(`Extract job ${extractStatus.status}. Error: ${extractStatus.error}`, statusResponse.status);
381300
381739
  }
381301
- await new Promise((resolve34) => setTimeout(resolve34, 1000));
381740
+ await new Promise((resolve35) => setTimeout(resolve35, 1000));
381302
381741
  } while (extractStatus.status !== "completed");
381303
381742
  } else {
381304
381743
  this.handleError(response, "extract");
@@ -381397,7 +381836,7 @@ var HttpClient = class {
381397
381836
  }
381398
381837
  } else if (["active", "paused", "pending", "queued", "waiting", "scraping"].includes(statusData.status)) {
381399
381838
  checkInterval = Math.max(checkInterval, 2);
381400
- await new Promise((resolve34) => setTimeout(resolve34, checkInterval * 1000));
381839
+ await new Promise((resolve35) => setTimeout(resolve35, checkInterval * 1000));
381401
381840
  } else {
381402
381841
  throw new FirecrawlError(`Crawl job failed or was stopped. Status: ${statusData.status}`, 500);
381403
381842
  }
@@ -381411,7 +381850,7 @@ var HttpClient = class {
381411
381850
  if (this.isRetryableError(error41) && networkRetries < maxNetworkRetries) {
381412
381851
  networkRetries++;
381413
381852
  const backoffDelay = Math.min(1000 * Math.pow(2, networkRetries - 1), 1e4);
381414
- await new Promise((resolve34) => setTimeout(resolve34, backoffDelay));
381853
+ await new Promise((resolve35) => setTimeout(resolve35, backoffDelay));
381415
381854
  continue;
381416
381855
  }
381417
381856
  throw new FirecrawlError(error41, 500);
@@ -381494,7 +381933,7 @@ var HttpClient = class {
381494
381933
  if (researchStatus.status !== "processing") {
381495
381934
  break;
381496
381935
  }
381497
- await new Promise((resolve34) => setTimeout(resolve34, 2000));
381936
+ await new Promise((resolve35) => setTimeout(resolve35, 2000));
381498
381937
  }
381499
381938
  return { success: false, error: "Research job terminated unexpectedly" };
381500
381939
  } catch (error41) {
@@ -381582,7 +382021,7 @@ var HttpClient = class {
381582
382021
  if (researchStatus.status !== "processing") {
381583
382022
  break;
381584
382023
  }
381585
- await new Promise((resolve34) => setTimeout(resolve34, 2000));
382024
+ await new Promise((resolve35) => setTimeout(resolve35, 2000));
381586
382025
  }
381587
382026
  return { success: false, error: "Research job terminated unexpectedly" };
381588
382027
  } catch (error41) {
@@ -381653,7 +382092,7 @@ var HttpClient = class {
381653
382092
  if (generationStatus.status !== "processing") {
381654
382093
  break;
381655
382094
  }
381656
- await new Promise((resolve34) => setTimeout(resolve34, 2000));
382095
+ await new Promise((resolve35) => setTimeout(resolve35, 2000));
381657
382096
  }
381658
382097
  return { success: false, error: "LLMs.txt generation job terminated unexpectedly" };
381659
382098
  } catch (error41) {
@@ -382400,7 +382839,8 @@ async function stopTask(taskId, context4) {
382400
382839
  const appState = getAppState();
382401
382840
  const task = appState.tasks?.[taskId];
382402
382841
  if (!task) {
382403
- if (abortBackgroundAgentById(taskId)) {
382842
+ if (hasBackgroundAgent(taskId)) {
382843
+ await abortBackgroundAgentById(taskId);
382404
382844
  return { taskId, taskType: "local_agent", command: undefined };
382405
382845
  }
382406
382846
  throw new StopTaskError(`No task found with ID: ${taskId}`, "not_found");
@@ -382412,7 +382852,11 @@ async function stopTask(taskId, context4) {
382412
382852
  if (!taskImpl) {
382413
382853
  throw new StopTaskError(`Unsupported task type: ${task.type}`, "unsupported_type");
382414
382854
  }
382415
- await taskImpl.kill(taskId, setAppState);
382855
+ if (task.type === "local_agent" && hasBackgroundAgent(taskId)) {
382856
+ await abortBackgroundAgentById(taskId);
382857
+ } else {
382858
+ await taskImpl.kill(taskId, setAppState);
382859
+ }
382416
382860
  if (isLocalShellTask(task)) {
382417
382861
  let suppressed = false;
382418
382862
  setAppState((prev) => {
@@ -382470,6 +382914,7 @@ var init_TaskStopTool = __esm(() => {
382470
382914
  init_stopTask();
382471
382915
  init_slowOperations();
382472
382916
  init_toolUIRegistry();
382917
+ init_backgroundAbortRegistry();
382473
382918
  ({
382474
382919
  renderToolResultMessage: renderToolResultMessage15,
382475
382920
  renderToolUseMessage: renderToolUseMessage15
@@ -382515,6 +382960,9 @@ var init_TaskStopTool = __esm(() => {
382515
382960
  const appState = getAppState();
382516
382961
  const task = appState.tasks?.[id];
382517
382962
  if (!task) {
382963
+ if (hasBackgroundAgent(id)) {
382964
+ return { result: true };
382965
+ }
382518
382966
  return {
382519
382967
  result: false,
382520
382968
  message: `No task found with ID: ${id}`,
@@ -389481,9 +389929,9 @@ var require_needle = __commonJS((exports, module) => {
389481
389929
  verb = args.shift();
389482
389930
  if (verb.match(/get|head/i) && args.length == 2)
389483
389931
  args.splice(1, 0, null);
389484
- return new Promise(function(resolve34, reject2) {
389932
+ return new Promise(function(resolve35, reject2) {
389485
389933
  module.exports.request(verb, args[0], args[1], args[2], function(err2, resp) {
389486
- return err2 ? reject2(err2) : resolve34(resp);
389934
+ return err2 ? reject2(err2) : resolve35(resp);
389487
389935
  });
389488
389936
  });
389489
389937
  };
@@ -396884,7 +397332,7 @@ async function showInvalidConfigDialog({
396884
397332
  ...getBaseRenderOptions(false),
396885
397333
  theme: SAFE_ERROR_THEME_NAME
396886
397334
  };
396887
- await new Promise(async (resolve34) => {
397335
+ await new Promise(async (resolve35) => {
396888
397336
  const {
396889
397337
  unmount
396890
397338
  } = await render(/* @__PURE__ */ jsx_dev_runtime44.jsxDEV(AppStateProvider, {
@@ -396894,7 +397342,7 @@ async function showInvalidConfigDialog({
396894
397342
  errorDescription: error41.message,
396895
397343
  onExit: () => {
396896
397344
  unmount();
396897
- resolve34();
397345
+ resolve35();
396898
397346
  process.exit(1);
396899
397347
  },
396900
397348
  onReset: () => {
@@ -396903,7 +397351,7 @@ async function showInvalidConfigDialog({
396903
397351
  encoding: "utf8"
396904
397352
  });
396905
397353
  unmount();
396906
- resolve34();
397354
+ resolve35();
396907
397355
  process.exit(0);
396908
397356
  }
396909
397357
  }, undefined, false, undefined, this)
@@ -401262,14 +401710,14 @@ class AuthCodeListener {
401262
401710
  this.callbackPath = callbackPath;
401263
401711
  }
401264
401712
  async start(port) {
401265
- return new Promise((resolve34, reject2) => {
401713
+ return new Promise((resolve35, reject2) => {
401266
401714
  this.localServer.once("error", (err2) => {
401267
401715
  reject2(new Error(`Failed to start OAuth callback server: ${err2.message}`));
401268
401716
  });
401269
401717
  this.localServer.listen({ port: port ?? 0, host: "::", ipv6Only: false }, () => {
401270
401718
  const address = this.localServer.address();
401271
401719
  this.port = address.port;
401272
- resolve34(this.port);
401720
+ resolve35(this.port);
401273
401721
  });
401274
401722
  });
401275
401723
  }
@@ -401280,8 +401728,8 @@ class AuthCodeListener {
401280
401728
  return this.pendingResponse !== null;
401281
401729
  }
401282
401730
  async waitForAuthorization(state4, onReady) {
401283
- return new Promise((resolve34, reject2) => {
401284
- this.promiseResolver = resolve34;
401731
+ return new Promise((resolve35, reject2) => {
401732
+ this.promiseResolver = resolve35;
401285
401733
  this.promiseRejecter = reject2;
401286
401734
  this.expectedState = state4;
401287
401735
  this.startLocalListener(onReady);
@@ -401450,11 +401898,11 @@ class OAuthService {
401450
401898
  }
401451
401899
  }
401452
401900
  async waitForAuthorizationCode(state4, onReady) {
401453
- return new Promise((resolve34, reject2) => {
401454
- this.manualAuthCodeResolver = resolve34;
401901
+ return new Promise((resolve35, reject2) => {
401902
+ this.manualAuthCodeResolver = resolve35;
401455
401903
  this.authCodeListener?.waitForAuthorization(state4, onReady).then((authorizationCode) => {
401456
401904
  this.manualAuthCodeResolver = null;
401457
- resolve34(authorizationCode);
401905
+ resolve35(authorizationCode);
401458
401906
  }).catch((error41) => {
401459
401907
  this.manualAuthCodeResolver = null;
401460
401908
  reject2(error41);
@@ -419069,7 +419517,7 @@ function extractFirstFrame(output) {
419069
419517
  return output.slice(contentStart, endIndex);
419070
419518
  }
419071
419519
  function renderToAnsiString(node, columns) {
419072
- return new Promise(async (resolve34) => {
419520
+ return new Promise(async (resolve35) => {
419073
419521
  let output = "";
419074
419522
  const stream4 = new PassThrough3;
419075
419523
  if (columns !== undefined) {
@@ -419085,7 +419533,7 @@ function renderToAnsiString(node, columns) {
419085
419533
  patchConsole: false
419086
419534
  });
419087
419535
  await instance.waitUntilExit();
419088
- await resolve34(extractFirstFrame(output));
419536
+ await resolve35(extractFirstFrame(output));
419089
419537
  });
419090
419538
  }
419091
419539
  async function renderToString(node, columns) {
@@ -419188,7 +419636,7 @@ var init_exportRenderer = __esm(() => {
419188
419636
  // src/lib/editor.ts
419189
419637
  import {
419190
419638
  spawn as spawn8,
419191
- spawnSync as spawnSync4
419639
+ spawnSync as spawnSync5
419192
419640
  } from "child_process";
419193
419641
  import { basename as basename32 } from "path";
419194
419642
  function isCommandAvailable3(command) {
@@ -419239,7 +419687,7 @@ function openFileInExternalEditor(filePath, line) {
419239
419687
  let result;
419240
419688
  if (process.platform === "win32") {
419241
419689
  const lineArg = useGotoLine ? `+${line} ` : "";
419242
- result = spawnSync4(`${editor} ${lineArg}"${filePath}"`, {
419690
+ result = spawnSync5(`${editor} ${lineArg}"${filePath}"`, {
419243
419691
  ...syncOpts,
419244
419692
  shell: true
419245
419693
  });
@@ -419248,7 +419696,7 @@ function openFileInExternalEditor(filePath, line) {
419248
419696
  ...editorArgs,
419249
419697
  ...useGotoLine ? [`+${line}`, filePath] : [filePath]
419250
419698
  ];
419251
- result = spawnSync4(base2, args, syncOpts);
419699
+ result = spawnSync5(base2, args, syncOpts);
419252
419700
  }
419253
419701
  if (result.error) {
419254
419702
  logForDebugging2(`editor spawn failed: ${result.error}`, {
@@ -430804,10 +431252,28 @@ function deserializeMessagesWithInterruptDetection(serializedMessages) {
430804
431252
  throw error41;
430805
431253
  }
430806
431254
  }
431255
+ function hasTerminalContinuationStop(messages) {
431256
+ let lastToolUseIdx = -1;
431257
+ for (let index = messages.length - 1;index >= 0; index--) {
431258
+ const message = messages[index];
431259
+ if (message.type === "assistant" && !message.isApiErrorMessage && message.message.content.some((block2) => block2.type === "tool_use")) {
431260
+ lastToolUseIdx = index;
431261
+ break;
431262
+ }
431263
+ }
431264
+ if (lastToolUseIdx === -1)
431265
+ return false;
431266
+ const terminalBatch = messages.slice(lastToolUseIdx + 1);
431267
+ const hasLaterHumanPrompt = terminalBatch.some((message) => message.type === "user" && !message.isMeta && !message.isCompactSummary && !isToolUseResultMessage(message));
431268
+ return !hasLaterHumanPrompt && terminalBatch.some((message) => message.type === "user" && message.preventContinuation === true);
431269
+ }
430807
431270
  function detectTurnInterruption(messages) {
430808
431271
  if (messages.length === 0) {
430809
431272
  return { kind: "none" };
430810
431273
  }
431274
+ if (hasTerminalContinuationStop(messages)) {
431275
+ return { kind: "none" };
431276
+ }
430811
431277
  const lastMessageIdx = messages.findLastIndex((m) => m.type !== "system" && m.type !== "progress" && !(m.type === "assistant" && m.isApiErrorMessage));
430812
431278
  const lastMessage = lastMessageIdx !== -1 ? messages[lastMessageIdx] : undefined;
430813
431279
  if (!lastMessage) {
@@ -431787,7 +432253,7 @@ async function handleTeleportPrerequisites(root2, errorsToIgnore) {
431787
432253
  error_types: Array.from(errors4).join(","),
431788
432254
  errors_ignored: Array.from(errorsToIgnore || []).join(",")
431789
432255
  });
431790
- await new Promise((resolve34) => {
432256
+ await new Promise((resolve35) => {
431791
432257
  root2.render(/* @__PURE__ */ jsx_dev_runtime160.jsxDEV(AppStateProvider, {
431792
432258
  children: /* @__PURE__ */ jsx_dev_runtime160.jsxDEV(KeybindingSetup, {
431793
432259
  children: /* @__PURE__ */ jsx_dev_runtime160.jsxDEV(TeleportError, {
@@ -431796,7 +432262,7 @@ async function handleTeleportPrerequisites(root2, errorsToIgnore) {
431796
432262
  logEvent("tengu_teleport_errors_resolved", {
431797
432263
  error_types: Array.from(errors4).join(",")
431798
432264
  });
431799
- resolve34();
432265
+ resolve35();
431800
432266
  }
431801
432267
  }, undefined, false, undefined, this)
431802
432268
  }, undefined, false, undefined, this)
@@ -442095,7 +442561,7 @@ import {
442095
442561
  writeFile as writeFile7
442096
442562
  } from "fs/promises";
442097
442563
  import { homedir as homedir32 } from "os";
442098
- import { basename as basename45, delimiter as delimiter3, dirname as dirname47, join as join103, resolve as resolve34 } from "path";
442564
+ import { basename as basename45, delimiter as delimiter3, dirname as dirname47, join as join103, resolve as resolve35 } from "path";
442099
442565
  function getPlatform3() {
442100
442566
  const os5 = env3.platform;
442101
442567
  const arch = process.arch === "x64" ? "x64" : process.arch === "arm64" ? "arm64" : null;
@@ -442509,8 +442975,8 @@ async function updateSymlink(symlinkPath, targetPath) {
442509
442975
  if (symlinkExists) {
442510
442976
  try {
442511
442977
  const currentTarget = await readlink(symlinkPath);
442512
- const resolvedCurrentTarget = resolve34(dirname47(symlinkPath), currentTarget);
442513
- const resolvedTargetPath = resolve34(targetPath);
442978
+ const resolvedCurrentTarget = resolve35(dirname47(symlinkPath), currentTarget);
442979
+ const resolvedTargetPath = resolve35(targetPath);
442514
442980
  if (resolvedCurrentTarget === resolvedTargetPath) {
442515
442981
  return false;
442516
442982
  }
@@ -442550,7 +443016,7 @@ async function checkInstall(force = false) {
442550
443016
  const dirs = getBaseDirectories();
442551
443017
  const messages = [];
442552
443018
  const localBinDir = dirname47(dirs.executable);
442553
- const resolvedLocalBinPath = resolve34(localBinDir);
443019
+ const resolvedLocalBinPath = resolve35(localBinDir);
442554
443020
  const platform6 = getPlatform3();
442555
443021
  const isWindows2 = platform6.startsWith("win32");
442556
443022
  try {
@@ -442573,7 +443039,7 @@ async function checkInstall(force = false) {
442573
443039
  } else {
442574
443040
  try {
442575
443041
  const target = await readlink(dirs.executable);
442576
- const absoluteTarget = resolve34(dirname47(dirs.executable), target);
443042
+ const absoluteTarget = resolve35(dirname47(dirs.executable), target);
442577
443043
  if (!await isPossibleClaudeBinary(absoluteTarget)) {
442578
443044
  messages.push({
442579
443045
  message: `Claude symlink points to missing or invalid binary: ${target}`,
@@ -442601,7 +443067,7 @@ async function checkInstall(force = false) {
442601
443067
  }
442602
443068
  const isInCurrentPath = (process.env.PATH || "").split(delimiter3).some((entry) => {
442603
443069
  try {
442604
- const resolvedEntry = resolve34(entry);
443070
+ const resolvedEntry = resolve35(entry);
442605
443071
  if (isWindows2) {
442606
443072
  return resolvedEntry.toLowerCase() === resolvedLocalBinPath.toLowerCase();
442607
443073
  }
@@ -442680,7 +443146,7 @@ async function installLatestImpl(channelOrVersion, forceReinstall = false) {
442680
443146
  async function getVersionFromSymlink(symlinkPath) {
442681
443147
  try {
442682
443148
  const target = await readlink(symlinkPath);
442683
- const absoluteTarget = resolve34(dirname47(symlinkPath), target);
443149
+ const absoluteTarget = resolve35(dirname47(symlinkPath), target);
442684
443150
  if (await isPossibleClaudeBinary(absoluteTarget)) {
442685
443151
  return absoluteTarget;
442686
443152
  }
@@ -442696,7 +443162,7 @@ async function lockCurrentVersion() {
442696
443162
  if (!process.execPath.includes(dirs.versions)) {
442697
443163
  return;
442698
443164
  }
442699
- const versionPath = resolve34(process.execPath);
443165
+ const versionPath = resolve35(process.execPath);
442700
443166
  try {
442701
443167
  const lockfilePath = getLockFilePathFromVersionPath(dirs, versionPath);
442702
443168
  await mkdir11(dirs.locks, { recursive: true });
@@ -442864,7 +443330,7 @@ async function cleanupOldVersions() {
442864
443330
  versionFiles.push({
442865
443331
  name: entry,
442866
443332
  path: entryPath,
442867
- resolvedPath: resolve34(entryPath),
443333
+ resolvedPath: resolve35(entryPath),
442868
443334
  mtime: stats.mtime
442869
443335
  });
442870
443336
  } catch {}
@@ -442882,7 +443348,7 @@ async function cleanupOldVersions() {
442882
443348
  const currentBinaryPath = process.execPath;
442883
443349
  const protectedVersions = new Set;
442884
443350
  if (currentBinaryPath && currentBinaryPath.includes(dirs.versions)) {
442885
- protectedVersions.add(resolve34(currentBinaryPath));
443351
+ protectedVersions.add(resolve35(currentBinaryPath));
442886
443352
  }
442887
443353
  const currentSymlinkVersion = await getVersionFromSymlink(dirs.executable);
442888
443354
  if (currentSymlinkVersion) {
@@ -447089,8 +447555,8 @@ class FileIndex {
447089
447555
  }
447090
447556
  loadFromFileListAsync(fileList) {
447091
447557
  let markQueryable = () => {};
447092
- const queryable = new Promise((resolve35) => {
447093
- markQueryable = resolve35;
447558
+ const queryable = new Promise((resolve36) => {
447559
+ markQueryable = resolve36;
447094
447560
  });
447095
447561
  const done = this.buildAsync(fileList, markQueryable);
447096
447562
  return { queryable, done };
@@ -447271,7 +447737,7 @@ function isUpper(code) {
447271
447737
  return code >= 65 && code <= 90;
447272
447738
  }
447273
447739
  function yieldToEventLoop() {
447274
- return new Promise((resolve35) => setImmediate(resolve35));
447740
+ return new Promise((resolve36) => setImmediate(resolve36));
447275
447741
  }
447276
447742
  function computeTopLevelEntries(paths2, limit) {
447277
447743
  const topLevel = new Set;
@@ -453365,10 +453831,10 @@ var require_browser2 = __commonJS((exports) => {
453365
453831
  text = canvas;
453366
453832
  canvas = undefined;
453367
453833
  }
453368
- return new Promise(function(resolve35, reject2) {
453834
+ return new Promise(function(resolve36, reject2) {
453369
453835
  try {
453370
453836
  const data = QRCode.create(text, opts);
453371
- resolve35(renderFunc(data, canvas, opts));
453837
+ resolve36(renderFunc(data, canvas, opts));
453372
453838
  } catch (e2) {
453373
453839
  reject2(e2);
453374
453840
  }
@@ -453424,11 +453890,11 @@ function getStringRendererFromType(type) {
453424
453890
  }
453425
453891
  function render2(renderFunc, text, params) {
453426
453892
  if (!params.cb) {
453427
- return new Promise(function(resolve35, reject2) {
453893
+ return new Promise(function(resolve36, reject2) {
453428
453894
  try {
453429
453895
  const data = QRCode.create(text, params.opts);
453430
453896
  return renderFunc(data, params.opts, function(err2, data2) {
453431
- return err2 ? reject2(err2) : resolve35(data2);
453897
+ return err2 ? reject2(err2) : resolve36(data2);
453432
453898
  });
453433
453899
  } catch (e2) {
453434
453900
  reject2(e2);
@@ -471445,7 +471911,7 @@ var init_channelPermissions = __esm(() => {
471445
471911
  });
471446
471912
 
471447
471913
  // src/cli/hooks/toolPermission/PermissionContext.ts
471448
- function createResolveOnce(resolve35) {
471914
+ function createResolveOnce(resolve36) {
471449
471915
  let claimed = false;
471450
471916
  let delivered = false;
471451
471917
  return {
@@ -471454,7 +471920,7 @@ function createResolveOnce(resolve35) {
471454
471920
  return;
471455
471921
  delivered = true;
471456
471922
  claimed = true;
471457
- resolve35(value);
471923
+ resolve36(value);
471458
471924
  },
471459
471925
  isResolved() {
471460
471926
  return claimed;
@@ -471499,11 +471965,11 @@ function createPermissionContext(tool, input, toolUseContext, assistantMessage,
471499
471965
  setToolPermissionContext(applyPermissionUpdates(appState.toolPermissionContext, updates));
471500
471966
  return updates.some((update) => supportsPersistence(update.destination));
471501
471967
  },
471502
- resolveIfAborted(resolve35) {
471968
+ resolveIfAborted(resolve36) {
471503
471969
  if (!toolUseContext.abortController.signal.aborted)
471504
471970
  return false;
471505
471971
  this.logCancelled();
471506
- resolve35(this.cancelAndAbort(undefined, true));
471972
+ resolve36(this.cancelAndAbort(undefined, true));
471507
471973
  return true;
471508
471974
  },
471509
471975
  cancelAndAbort(feedback, isAbort, contentBlocks) {
@@ -471617,7 +472083,7 @@ var init_PermissionContext = __esm(() => {
471617
472083
 
471618
472084
  // src/cli/hooks/toolPermission/handlers/interactiveHandler.ts
471619
472085
  import { randomUUID as randomUUID34 } from "crypto";
471620
- function handleInteractivePermission(params, resolve35) {
472086
+ function handleInteractivePermission(params, resolve36) {
471621
472087
  const {
471622
472088
  ctx,
471623
472089
  description,
@@ -471626,7 +472092,7 @@ function handleInteractivePermission(params, resolve35) {
471626
472092
  bridgeCallbacks,
471627
472093
  channelCallbacks
471628
472094
  } = params;
471629
- const { resolve: resolveOnce, isResolved, claim } = createResolveOnce(resolve35);
472095
+ const { resolve: resolveOnce, isResolved, claim } = createResolveOnce(resolve36);
471630
472096
  let userInteracted = false;
471631
472097
  let checkmarkTransitionTimer;
471632
472098
  let checkmarkAbortHandler;
@@ -471813,8 +472279,8 @@ async function handleSwarmWorkerPermission(params) {
471813
472279
  ...prev,
471814
472280
  pendingWorkerRequest: null
471815
472281
  }));
471816
- const decision = await new Promise((resolve35) => {
471817
- const { resolve: resolveOnce, claim } = createResolveOnce(resolve35);
472282
+ const decision = await new Promise((resolve36) => {
472283
+ const { resolve: resolveOnce, claim } = createResolveOnce(resolve36);
471818
472284
  const request = createPermissionRequest({
471819
472285
  toolName: ctx.tool.name,
471820
472286
  toolUseId: ctx.toolUseID,
@@ -471880,15 +472346,15 @@ function useCanUseTool(setToolUseConfirmQueue, setToolPermissionContext) {
471880
472346
  const $2 = import_react_compiler_runtime191.c(3);
471881
472347
  let t0;
471882
472348
  if ($2[0] !== setToolPermissionContext || $2[1] !== setToolUseConfirmQueue) {
471883
- t0 = async (tool, input, toolUseContext, assistantMessage, toolUseID, forceDecision) => new Promise((resolve35) => {
472349
+ t0 = async (tool, input, toolUseContext, assistantMessage, toolUseID, forceDecision) => new Promise((resolve36) => {
471884
472350
  const ctx = createPermissionContext(tool, input, toolUseContext, assistantMessage, toolUseID, setToolPermissionContext, createPermissionQueueOps(setToolUseConfirmQueue));
471885
- if (ctx.resolveIfAborted(resolve35)) {
472351
+ if (ctx.resolveIfAborted(resolve36)) {
471886
472352
  return;
471887
472353
  }
471888
472354
  const decisionPromise = forceDecision !== undefined ? Promise.resolve(forceDecision) : hasPermissionsToUseTool(tool, input, toolUseContext, assistantMessage, toolUseID);
471889
472355
  return decisionPromise.then(async (result) => {
471890
472356
  if (result.behavior === "allow") {
471891
- if (ctx.resolveIfAborted(resolve35)) {
472357
+ if (ctx.resolveIfAborted(resolve36)) {
471892
472358
  return;
471893
472359
  }
471894
472360
  if (false) {}
@@ -471896,7 +472362,7 @@ function useCanUseTool(setToolUseConfirmQueue, setToolPermissionContext) {
471896
472362
  decision: "accept",
471897
472363
  source: "config"
471898
472364
  });
471899
- resolve35(ctx.buildAllow(result.updatedInput ?? input, {
472365
+ resolve36(ctx.buildAllow(result.updatedInput ?? input, {
471900
472366
  decisionReason: result.decisionReason
471901
472367
  }));
471902
472368
  return;
@@ -471907,7 +472373,7 @@ function useCanUseTool(setToolUseConfirmQueue, setToolPermissionContext) {
471907
472373
  toolPermissionContext: appState.toolPermissionContext,
471908
472374
  tools: toolUseContext.options.tools
471909
472375
  });
471910
- if (ctx.resolveIfAborted(resolve35)) {
472376
+ if (ctx.resolveIfAborted(resolve36)) {
471911
472377
  return;
471912
472378
  }
471913
472379
  switch (result.behavior) {
@@ -471923,7 +472389,7 @@ function useCanUseTool(setToolUseConfirmQueue, setToolPermissionContext) {
471923
472389
  source: "config"
471924
472390
  });
471925
472391
  if (false) {}
471926
- resolve35(result);
472392
+ resolve36(result);
471927
472393
  return;
471928
472394
  }
471929
472395
  case "ask": {
@@ -471936,11 +472402,11 @@ function useCanUseTool(setToolUseConfirmQueue, setToolPermissionContext) {
471936
472402
  permissionMode: appState.toolPermissionContext.mode
471937
472403
  });
471938
472404
  if (coordinatorDecision) {
471939
- resolve35(coordinatorDecision);
472405
+ resolve36(coordinatorDecision);
471940
472406
  return;
471941
472407
  }
471942
472408
  }
471943
- if (ctx.resolveIfAborted(resolve35)) {
472409
+ if (ctx.resolveIfAborted(resolve36)) {
471944
472410
  return;
471945
472411
  }
471946
472412
  const swarmDecision = await handleSwarmWorkerPermission({
@@ -471951,7 +472417,7 @@ function useCanUseTool(setToolUseConfirmQueue, setToolPermissionContext) {
471951
472417
  suggestions: result.suggestions
471952
472418
  });
471953
472419
  if (swarmDecision) {
471954
- resolve35(swarmDecision);
472420
+ resolve36(swarmDecision);
471955
472421
  return;
471956
472422
  }
471957
472423
  if (false) {}
@@ -471962,7 +472428,7 @@ function useCanUseTool(setToolUseConfirmQueue, setToolPermissionContext) {
471962
472428
  awaitAutomatedChecksBeforeDialog: appState.toolPermissionContext.awaitAutomatedChecksBeforeDialog,
471963
472429
  bridgeCallbacks: undefined,
471964
472430
  channelCallbacks: undefined
471965
- }, resolve35);
472431
+ }, resolve36);
471966
472432
  return;
471967
472433
  }
471968
472434
  }
@@ -471970,10 +472436,10 @@ function useCanUseTool(setToolUseConfirmQueue, setToolPermissionContext) {
471970
472436
  if (error41 instanceof AbortError || error41 instanceof CanonicalUserAbortError) {
471971
472437
  logForDebugging2(`Permission check threw ${error41.constructor.name} for tool=${tool.name}: ${error41.message}`);
471972
472438
  ctx.logCancelled();
471973
- resolve35(ctx.cancelAndAbort(undefined, true));
472439
+ resolve36(ctx.cancelAndAbort(undefined, true));
471974
472440
  } else {
471975
472441
  logError(error41);
471976
- resolve35(ctx.cancelAndAbort(undefined, true));
472442
+ resolve36(ctx.cancelAndAbort(undefined, true));
471977
472443
  }
471978
472444
  }).finally(() => {
471979
472445
  clearClassifierChecking(toolUseID);
@@ -476098,8 +476564,8 @@ function useManageMCPConnections(dynamicMcpConfig, isStrictMcpConfig = false) {
476098
476564
  }
476099
476565
  const backoffMs = Math.min(INITIAL_BACKOFF_MS * Math.pow(2, attempt - 1), MAX_BACKOFF_MS);
476100
476566
  logMCPDebug(client.name, `Scheduling reconnection attempt ${attempt + 1} in ${backoffMs}ms`);
476101
- await new Promise((resolve36) => {
476102
- const timer = setTimeout(resolve36, backoffMs);
476567
+ await new Promise((resolve37) => {
476568
+ const timer = setTimeout(resolve37, backoffMs);
476103
476569
  reconnectTimersRef.current.set(client.name, timer);
476104
476570
  });
476105
476571
  }
@@ -479203,7 +479669,7 @@ class StructuredIO {
479203
479669
  });
479204
479670
  }
479205
479671
  try {
479206
- return await new Promise((resolve36, reject2) => {
479672
+ return await new Promise((resolve37, reject2) => {
479207
479673
  this.pendingRequests.set(requestId, {
479208
479674
  request: {
479209
479675
  type: "control_request",
@@ -479211,7 +479677,7 @@ class StructuredIO {
479211
479677
  request
479212
479678
  },
479213
479679
  resolve: (result) => {
479214
- resolve36(result);
479680
+ resolve37(result);
479215
479681
  },
479216
479682
  reject: reject2,
479217
479683
  schema
@@ -480416,7 +480882,7 @@ function usePluginRecommendationBase() {
480416
480882
  const isCheckingRef = React95.useRef(false);
480417
480883
  let t0;
480418
480884
  if ($2[0] !== recommendation) {
480419
- t0 = (resolve36) => {
480885
+ t0 = (resolve37) => {
480420
480886
  if (getIsRemoteMode()) {
480421
480887
  return;
480422
480888
  }
@@ -480427,7 +480893,7 @@ function usePluginRecommendationBase() {
480427
480893
  return;
480428
480894
  }
480429
480895
  isCheckingRef.current = true;
480430
- resolve36().then((rec) => {
480896
+ resolve37().then((rec) => {
480431
480897
  if (rec) {
480432
480898
  setRecommendation(rec);
480433
480899
  }
@@ -481866,7 +482332,7 @@ var init_usePluginAutoupdateNotification = __esm(() => {
481866
482332
  });
481867
482333
 
481868
482334
  // src/capabilities/plugins/reconciler.ts
481869
- import { isAbsolute as isAbsolute23, resolve as resolve36 } from "path";
482335
+ import { isAbsolute as isAbsolute23, resolve as resolve37 } from "path";
481870
482336
  function diffMarketplaces(declared, materialized, opts) {
481871
482337
  const missing = [];
481872
482338
  const sourceChanged = [];
@@ -481979,7 +482445,7 @@ function normalizeSource(source, projectRoot) {
481979
482445
  const canonicalRoot = findCanonicalGitRoot(base2);
481980
482446
  return {
481981
482447
  ...source,
481982
- path: resolve36(canonicalRoot ?? base2, source.path)
482448
+ path: resolve37(canonicalRoot ?? base2, source.path)
481983
482449
  };
481984
482450
  }
481985
482451
  return source;
@@ -485635,12 +486101,12 @@ Error: sandbox required but unavailable: ${reason}
485635
486101
  return () => unregisterLeaderSetToolPermissionContext();
485636
486102
  }, [setToolPermissionContext]);
485637
486103
  const canUseTool = useCanUseTool_default(setToolUseConfirmQueue, setToolPermissionContext);
485638
- const requestPrompt = import_react234.useCallback((title, toolInputSummary) => (request) => new Promise((resolve37, reject2) => {
486104
+ const requestPrompt = import_react234.useCallback((title, toolInputSummary) => (request) => new Promise((resolve38, reject2) => {
485639
486105
  setPromptQueue((prev) => [...prev, {
485640
486106
  request,
485641
486107
  title,
485642
486108
  toolInputSummary,
485643
- resolve: resolve37,
486109
+ resolve: resolve38,
485644
486110
  reject: reject2
485645
486111
  }]);
485646
486112
  }), []);
@@ -491619,7 +492085,7 @@ function buildPrimarySection() {
491619
492085
  }, undefined, false, undefined, this);
491620
492086
  return [{
491621
492087
  label: "Version",
491622
- value: "0.4.18"
492088
+ value: "0.4.20"
491623
492089
  }, {
491624
492090
  label: "Session name",
491625
492091
  value: nameValue
@@ -497743,7 +498209,7 @@ var init_useTurnDiffs = __esm(() => {
497743
498209
  });
497744
498210
 
497745
498211
  // src/cli/components/diff/DiffDetailView.tsx
497746
- import { resolve as resolve37 } from "path";
498212
+ import { resolve as resolve38 } from "path";
497747
498213
  function DiffDetailView(t0) {
497748
498214
  const $2 = import_react_compiler_runtime243.c(53);
497749
498215
  const {
@@ -497776,7 +498242,7 @@ function DiffDetailView(t0) {
497776
498242
  let content;
497777
498243
  let t22;
497778
498244
  if ($2[1] !== filePath) {
497779
- const fullPath = resolve37(getCwd3(), filePath);
498245
+ const fullPath = resolve38(getCwd3(), filePath);
497780
498246
  content = readFileSafe(fullPath);
497781
498247
  t22 = content?.split(`
497782
498248
  `)[0] ?? null;
@@ -501159,7 +501625,7 @@ function getGithubDeviceFlowClientId() {
501159
501625
  return process.env.GITHUB_DEVICE_FLOW_CLIENT_ID?.trim() || DEFAULT_GITHUB_DEVICE_FLOW_CLIENT_ID;
501160
501626
  }
501161
501627
  function sleep4(ms) {
501162
- return new Promise((resolve38) => setTimeout(resolve38, ms));
501628
+ return new Promise((resolve39) => setTimeout(resolve39, ms));
501163
501629
  }
501164
501630
  async function requestDeviceCode(options2) {
501165
501631
  const clientId = options2?.clientId ?? getGithubDeviceFlowClientId();
@@ -510799,7 +511265,7 @@ var init_mcp = __esm(() => {
510799
511265
 
510800
511266
  // src/capabilities/plugins/parseMarketplaceInput.ts
510801
511267
  import { homedir as homedir36 } from "os";
510802
- import { resolve as resolve38 } from "path";
511268
+ import { resolve as resolve39 } from "path";
510803
511269
  async function parseMarketplaceInput(input) {
510804
511270
  const trimmed = input.trim();
510805
511271
  const fs4 = getFsImplementation();
@@ -510834,7 +511300,7 @@ async function parseMarketplaceInput(input) {
510834
511300
  const isWindows2 = process.platform === "win32";
510835
511301
  const isWindowsPath = isWindows2 && (trimmed.startsWith(".\\") || trimmed.startsWith("..\\") || /^[a-zA-Z]:[/\\]/.test(trimmed));
510836
511302
  if (trimmed.startsWith("../../utils/plugins") || trimmed.startsWith("../../utils") || trimmed.startsWith("/") || trimmed.startsWith("~") || isWindowsPath) {
510837
- const resolvedPath = resolve38(trimmed.startsWith("~") ? trimmed.replace(/^~/, homedir36()) : trimmed);
511303
+ const resolvedPath = resolve39(trimmed.startsWith("~") ? trimmed.replace(/^~/, homedir36()) : trimmed);
510838
511304
  let stats;
510839
511305
  try {
510840
511306
  stats = await fs4.stat(resolvedPath);
@@ -539762,7 +540228,7 @@ var init_bridge_kick = __esm(() => {
539762
540228
  var call58 = async () => {
539763
540229
  return {
539764
540230
  type: "text",
539765
- value: `${"99.0.0"} (built ${"2026-07-16T03:27:09.740Z"})`
540231
+ value: `${"99.0.0"} (built ${"2026-07-21T10:56:17.312Z"})`
539766
540232
  };
539767
540233
  }, version2, version_default;
539768
540234
  var init_version = __esm(() => {
@@ -543899,8 +544365,8 @@ async function withStatsCacheLock(fn) {
543899
544365
  await statsCacheLockPromise;
543900
544366
  }
543901
544367
  let releaseLock2;
543902
- statsCacheLockPromise = new Promise((resolve40) => {
543903
- releaseLock2 = resolve40;
544368
+ statsCacheLockPromise = new Promise((resolve41) => {
544369
+ releaseLock2 = resolve41;
543904
544370
  });
543905
544371
  try {
543906
544372
  return await fn();
@@ -548246,7 +548712,7 @@ async function scanAllSessions() {
548246
548712
  });
548247
548713
  }
548248
548714
  if (i3 % 10 === 9) {
548249
- await new Promise((resolve40) => setImmediate(resolve40));
548715
+ await new Promise((resolve41) => setImmediate(resolve41));
548250
548716
  }
548251
548717
  }
548252
548718
  allSessions.sort((a2, b) => b.mtime - a2.mtime);
@@ -552445,7 +552911,7 @@ __export(exports_UI12, {
552445
552911
  getToolUseSummary: () => getToolUseSummary11,
552446
552912
  countLines: () => countLines
552447
552913
  });
552448
- import { isAbsolute as isAbsolute24, relative as relative31, resolve as resolve40 } from "path";
552914
+ import { isAbsolute as isAbsolute24, relative as relative31, resolve as resolve41 } from "path";
552449
552915
  function countLines(content) {
552450
552916
  const parts = content.split(EOL5);
552451
552917
  return content.endsWith(EOL5) ? parts.length - 1 : parts.length;
@@ -552769,7 +553235,7 @@ function WriteRejectionBody(t0) {
552769
553235
  }
552770
553236
  async function loadRejectionDiff2(filePath, content) {
552771
553237
  try {
552772
- const fullFilePath = isAbsolute24(filePath) ? filePath : resolve40(getCwd3(), filePath);
553238
+ const fullFilePath = isAbsolute24(filePath) ? filePath : resolve41(getCwd3(), filePath);
552773
553239
  const handle = await openForScan(fullFilePath);
552774
553240
  if (handle === null)
552775
553241
  return {
@@ -555527,12 +555993,12 @@ async function getMessagesForSlashCommand(commandName, args, setToolJSX, context
555527
555993
  try {
555528
555994
  switch (command9.type) {
555529
555995
  case "local-jsx": {
555530
- return new Promise((resolve41) => {
555996
+ return new Promise((resolve42) => {
555531
555997
  let doneWasCalled = false;
555532
555998
  const onDone = (result, options2) => {
555533
555999
  doneWasCalled = true;
555534
556000
  if (options2?.display === "skip") {
555535
- resolve41({
556001
+ resolve42({
555536
556002
  messages: [],
555537
556003
  shouldQuery: false,
555538
556004
  command: command9,
@@ -555546,7 +556012,7 @@ async function getMessagesForSlashCommand(commandName, args, setToolJSX, context
555546
556012
  isMeta: true
555547
556013
  }));
555548
556014
  const skipTranscript = isFullscreenEnvEnabled() && typeof result === "string" && result.endsWith(" dismissed");
555549
- resolve41({
556015
+ resolve42({
555550
556016
  messages: options2?.display === "system" ? skipTranscript ? metaMessages : [createCommandInputMessage(formatCommandInput(command9, args)), createCommandInputMessage(`<local-command-stdout>${result}</local-command-stdout>`), ...metaMessages] : [createUserMessage({
555551
556017
  content: prepareUserContent({
555552
556018
  inputString: formatCommandInput(command9, args),
@@ -555570,7 +556036,7 @@ async function getMessagesForSlashCommand(commandName, args, setToolJSX, context
555570
556036
  if (jsx == null)
555571
556037
  return;
555572
556038
  if (context7.options.isNonInteractiveSession) {
555573
- resolve41({
556039
+ resolve42({
555574
556040
  messages: [],
555575
556041
  shouldQuery: false,
555576
556042
  command: command9
@@ -555596,7 +556062,7 @@ async function getMessagesForSlashCommand(commandName, args, setToolJSX, context
555596
556062
  shouldHidePromptInput: false,
555597
556063
  clearLocalJSX: true
555598
556064
  });
555599
- resolve41({
556065
+ resolve42({
555600
556066
  messages: [],
555601
556067
  shouldQuery: false,
555602
556068
  command: command9
@@ -556580,12 +557046,12 @@ var init_It2SetupPrompt = __esm(() => {
556580
557046
  });
556581
557047
 
556582
557048
  // src/cli/utils/swarm/it2SetupLauncherImpl.tsx
556583
- var React161, launchIt2Setup = ({ setToolJSX, tmuxAvailable: tmuxAvailable2 }) => new Promise((resolve41) => {
557049
+ var React161, launchIt2Setup = ({ setToolJSX, tmuxAvailable: tmuxAvailable2 }) => new Promise((resolve42) => {
556584
557050
  setToolJSX({
556585
557051
  jsx: React161.createElement(It2SetupPrompt, {
556586
557052
  onDone: (result) => {
556587
557053
  setToolJSX(null);
556588
- resolve41(result);
557054
+ resolve42(result);
556589
557055
  },
556590
557056
  tmuxAvailable: tmuxAvailable2
556591
557057
  }),
@@ -556937,8 +557403,8 @@ async function handleMcpjsonServerApprovals(root2) {
556937
557403
  if (pendingServers.length === 0) {
556938
557404
  return;
556939
557405
  }
556940
- await new Promise((resolve41) => {
556941
- const done = () => void resolve41();
557406
+ await new Promise((resolve42) => {
557407
+ const done = () => void resolve42();
556942
557408
  if (pendingServers.length === 1 && pendingServers[0] !== undefined) {
556943
557409
  const serverName = pendingServers[0];
556944
557410
  root2.render(/* @__PURE__ */ jsx_dev_runtime465.jsxDEV(AppStateProvider, {
@@ -557529,7 +557995,7 @@ function WelcomeV2() {
557529
557995
  dimColor: true,
557530
557996
  children: [
557531
557997
  "v",
557532
- "0.4.18",
557998
+ "0.4.20",
557533
557999
  " "
557534
558000
  ]
557535
558001
  }, undefined, true, undefined, this)
@@ -557729,7 +558195,7 @@ function WelcomeV2() {
557729
558195
  dimColor: true,
557730
558196
  children: [
557731
558197
  "v",
557732
- "0.4.18",
558198
+ "0.4.20",
557733
558199
  " "
557734
558200
  ]
557735
558201
  }, undefined, true, undefined, this)
@@ -557955,7 +558421,7 @@ function AppleTerminalWelcomeV2(t0) {
557955
558421
  dimColor: true,
557956
558422
  children: [
557957
558423
  "v",
557958
- "0.4.18",
558424
+ "0.4.20",
557959
558425
  " "
557960
558426
  ]
557961
558427
  }, undefined, true, undefined, this);
@@ -558209,7 +558675,7 @@ function AppleTerminalWelcomeV2(t0) {
558209
558675
  dimColor: true,
558210
558676
  children: [
558211
558677
  "v",
558212
- "0.4.18",
558678
+ "0.4.20",
558213
558679
  " "
558214
558680
  ]
558215
558681
  }, undefined, true, undefined, this);
@@ -559713,8 +560179,8 @@ function completeOnboarding() {
559713
560179
  }));
559714
560180
  }
559715
560181
  function showDialog(root2, renderer) {
559716
- return new Promise((resolve41) => {
559717
- const done = (result) => void resolve41(result);
560182
+ return new Promise((resolve42) => {
560183
+ const done = (result) => void resolve42(result);
559718
560184
  root2.render(renderer(done));
559719
560185
  });
559720
560186
  }
@@ -564857,6 +565323,27 @@ var init_server3 = __esm(() => {
564857
565323
  };
564858
565324
  });
564859
565325
 
565326
+ // src/cli/entrypoints/mcpToolDefinition.ts
565327
+ async function toMCPToolDefinition(tool, promptOptions) {
565328
+ const inputJSONSchema = tool.inputJSONSchema;
565329
+ let outputSchema32;
565330
+ if (tool.outputSchema) {
565331
+ const convertedSchema = zodToJsonSchema3(tool.outputSchema);
565332
+ if (typeof convertedSchema === "object" && convertedSchema !== null && "type" in convertedSchema && convertedSchema.type === "object") {
565333
+ outputSchema32 = convertedSchema;
565334
+ }
565335
+ }
565336
+ return {
565337
+ name: tool.name,
565338
+ description: await tool.prompt(promptOptions),
565339
+ inputSchema: inputJSONSchema ?? zodToJsonSchema3(tool.inputSchema),
565340
+ ...outputSchema32 && { outputSchema: outputSchema32 }
565341
+ };
565342
+ }
565343
+ var init_mcpToolDefinition = __esm(() => {
565344
+ init_zodToJsonSchema2();
565345
+ });
565346
+
564860
565347
  // src/cli/entrypoints/mcp.ts
564861
565348
  var exports_mcp2 = {};
564862
565349
  __export(exports_mcp2, {
@@ -564878,25 +565365,11 @@ async function startMCPServer(cwd, debug, verbose) {
564878
565365
  const toolPermissionContext = getEmptyToolPermissionContext2();
564879
565366
  const tools = getTools(toolPermissionContext);
564880
565367
  return {
564881
- tools: await Promise.all(tools.map(async (tool) => {
564882
- let outputSchema32;
564883
- if (tool.outputSchema) {
564884
- const convertedSchema = zodToJsonSchema3(tool.outputSchema);
564885
- if (typeof convertedSchema === "object" && convertedSchema !== null && "type" in convertedSchema && convertedSchema.type === "object") {
564886
- outputSchema32 = convertedSchema;
564887
- }
564888
- }
564889
- return {
564890
- ...tool,
564891
- description: await tool.prompt({
564892
- getToolPermissionContext: async () => toolPermissionContext,
564893
- tools,
564894
- agents: []
564895
- }),
564896
- inputSchema: zodToJsonSchema3(tool.inputSchema),
564897
- outputSchema: outputSchema32
564898
- };
564899
- }))
565368
+ tools: await Promise.all(tools.map((tool) => toMCPToolDefinition(tool, {
565369
+ getToolPermissionContext: async () => toolPermissionContext,
565370
+ tools,
565371
+ agents: []
565372
+ })))
564900
565373
  };
564901
565374
  });
564902
565375
  server.setRequestHandler(CallToolRequestSchema, async ({ params: { name, arguments: args } }) => {
@@ -564988,7 +565461,7 @@ var init_mcp4 = __esm(() => {
564988
565461
  init_Shell();
564989
565462
  init_slowOperations();
564990
565463
  init_toolErrors();
564991
- init_zodToJsonSchema2();
565464
+ init_mcpToolDefinition();
564992
565465
  if (resolveEnvVar("DISABLE_EXPERIMENTAL_BETAS") === undefined) {
564993
565466
  setEnvVar("DISABLE_EXPERIMENTAL_BETAS", "true");
564994
565467
  }
@@ -565169,7 +565642,7 @@ async function mcpDoctorHandler(name, options2) {
565169
565642
  process.stdout.write(`${formatDoctorReport(report)}
565170
565643
  `);
565171
565644
  }
565172
- await new Promise((resolve41) => setTimeout(resolve41, 50));
565645
+ await new Promise((resolve42) => setTimeout(resolve42, 50));
565173
565646
  process.exit(report.summary.blocking > 0 ? 1 : 0);
565174
565647
  return;
565175
565648
  } catch (error41) {
@@ -566825,8 +567298,8 @@ class SerialBatchEventUploader {
566825
567298
  if (items.length === 0)
566826
567299
  return;
566827
567300
  while (this.pending.length + items.length > this.config.maxQueueSize && !this.closed) {
566828
- await new Promise((resolve41) => {
566829
- this.backpressureResolvers.push(resolve41);
567301
+ await new Promise((resolve42) => {
567302
+ this.backpressureResolvers.push(resolve42);
566830
567303
  });
566831
567304
  }
566832
567305
  if (this.closed)
@@ -566839,8 +567312,8 @@ class SerialBatchEventUploader {
566839
567312
  return Promise.resolve();
566840
567313
  }
566841
567314
  this.drain();
566842
- return new Promise((resolve41) => {
566843
- this.flushResolvers.push(resolve41);
567315
+ return new Promise((resolve42) => {
567316
+ this.flushResolvers.push(resolve42);
566844
567317
  });
566845
567318
  }
566846
567319
  close() {
@@ -566851,11 +567324,11 @@ class SerialBatchEventUploader {
566851
567324
  this.pending = [];
566852
567325
  this.sleepResolve?.();
566853
567326
  this.sleepResolve = null;
566854
- for (const resolve41 of this.backpressureResolvers)
566855
- resolve41();
567327
+ for (const resolve42 of this.backpressureResolvers)
567328
+ resolve42();
566856
567329
  this.backpressureResolvers = [];
566857
- for (const resolve41 of this.flushResolvers)
566858
- resolve41();
567330
+ for (const resolve42 of this.flushResolvers)
567331
+ resolve42();
566859
567332
  this.flushResolvers = [];
566860
567333
  }
566861
567334
  async drain() {
@@ -566890,8 +567363,8 @@ class SerialBatchEventUploader {
566890
567363
  } finally {
566891
567364
  this.draining = false;
566892
567365
  if (this.pending.length === 0) {
566893
- for (const resolve41 of this.flushResolvers)
566894
- resolve41();
567366
+ for (const resolve42 of this.flushResolvers)
567367
+ resolve42();
566895
567368
  this.flushResolvers = [];
566896
567369
  }
566897
567370
  }
@@ -566930,16 +567403,16 @@ class SerialBatchEventUploader {
566930
567403
  releaseBackpressure() {
566931
567404
  const resolvers2 = this.backpressureResolvers;
566932
567405
  this.backpressureResolvers = [];
566933
- for (const resolve41 of resolvers2)
566934
- resolve41();
567406
+ for (const resolve42 of resolvers2)
567407
+ resolve42();
566935
567408
  }
566936
567409
  sleep(ms) {
566937
- return new Promise((resolve41) => {
566938
- this.sleepResolve = resolve41;
566939
- setTimeout((self2, resolve42) => {
567410
+ return new Promise((resolve42) => {
567411
+ this.sleepResolve = resolve42;
567412
+ setTimeout((self2, resolve43) => {
566940
567413
  self2.sleepResolve = null;
566941
- resolve42();
566942
- }, ms, this, resolve41);
567414
+ resolve43();
567415
+ }, ms, this, resolve42);
566943
567416
  });
566944
567417
  }
566945
567418
  }
@@ -573994,8 +574467,8 @@ ${m.text}
573994
574467
  const controller = new AbortController;
573995
574468
  activeOAuthFlows.set(serverName, controller);
573996
574469
  let resolveAuthUrl;
573997
- const authUrlPromise = new Promise((resolve41) => {
573998
- resolveAuthUrl = resolve41;
574470
+ const authUrlPromise = new Promise((resolve42) => {
574471
+ resolveAuthUrl = resolve42;
573999
574472
  });
574000
574473
  const oauthPromise = performMCPOAuthFlow(serverName, config3, (url3) => resolveAuthUrl(url3), controller.signal, {
574001
574474
  skipBrowserOpen: true,
@@ -574108,8 +574581,8 @@ ${m.text}
574108
574581
  });
574109
574582
  const service = new OAuthService;
574110
574583
  let urlResolver;
574111
- const urlPromise = new Promise((resolve41) => {
574112
- urlResolver = resolve41;
574584
+ const urlPromise = new Promise((resolve42) => {
574585
+ urlResolver = resolve42;
574113
574586
  });
574114
574587
  const flow = service.startOAuthFlow(async (manualUrl, automaticUrl) => {
574115
574588
  urlResolver({ manualUrl, automaticUrl });
@@ -574495,8 +574968,8 @@ function createCanUseToolWithPermissionPrompt(permissionPromptTool) {
574495
574968
  }
574496
574969
  };
574497
574970
  }
574498
- const abortPromise = new Promise((resolve41) => {
574499
- combinedSignal.addEventListener("abort", () => resolve41("aborted"), {
574971
+ const abortPromise = new Promise((resolve42) => {
574972
+ combinedSignal.addEventListener("abort", () => resolve42("aborted"), {
574500
574973
  once: true
574501
574974
  });
574502
574975
  });
@@ -576656,7 +577129,7 @@ async function setupTokenHandler(root2) {
576656
577129
  const {
576657
577130
  ConsoleOAuthFlow: ConsoleOAuthFlow2
576658
577131
  } = await Promise.resolve().then(() => (init_ConsoleOAuthFlow(), exports_ConsoleOAuthFlow));
576659
- await new Promise((resolve41) => {
577132
+ await new Promise((resolve42) => {
576660
577133
  root2.render(/* @__PURE__ */ jsx_dev_runtime486.jsxDEV(AppStateProvider, {
576661
577134
  onChangeAppState,
576662
577135
  children: /* @__PURE__ */ jsx_dev_runtime486.jsxDEV(KeybindingSetup, {
@@ -576680,7 +577153,7 @@ async function setupTokenHandler(root2) {
576680
577153
  }, undefined, true, undefined, this),
576681
577154
  /* @__PURE__ */ jsx_dev_runtime486.jsxDEV(ConsoleOAuthFlow2, {
576682
577155
  onDone: () => {
576683
- resolve41();
577156
+ resolve42();
576684
577157
  },
576685
577158
  mode: "setup-token",
576686
577159
  startingMessage: "This will guide you through long-lived (1-year) auth token setup for your Claude account. Claude subscription required."
@@ -576716,7 +577189,7 @@ function DoctorWithPlugins(t0) {
576716
577189
  }
576717
577190
  async function doctorHandler(root2) {
576718
577191
  logEvent("tengu_doctor_command", {});
576719
- await new Promise((resolve41) => {
577192
+ await new Promise((resolve42) => {
576720
577193
  root2.render(/* @__PURE__ */ jsx_dev_runtime486.jsxDEV(AppStateProvider, {
576721
577194
  children: /* @__PURE__ */ jsx_dev_runtime486.jsxDEV(KeybindingSetup, {
576722
577195
  children: /* @__PURE__ */ jsx_dev_runtime486.jsxDEV(MCPConnectionManager, {
@@ -576724,7 +577197,7 @@ async function doctorHandler(root2) {
576724
577197
  isStrictMcpConfig: false,
576725
577198
  children: /* @__PURE__ */ jsx_dev_runtime486.jsxDEV(DoctorWithPlugins, {
576726
577199
  onDone: () => {
576727
- resolve41();
577200
+ resolve42();
576728
577201
  }
576729
577202
  }, undefined, false, undefined, this)
576730
577203
  }, undefined, false, undefined, this)
@@ -576742,14 +577215,14 @@ async function installHandler(target, options2) {
576742
577215
  const {
576743
577216
  install: install2
576744
577217
  } = await Promise.resolve().then(() => (init_install(), exports_install));
576745
- await new Promise((resolve41) => {
577218
+ await new Promise((resolve42) => {
576746
577219
  const args = [];
576747
577220
  if (target)
576748
577221
  args.push(target);
576749
577222
  if (options2.force)
576750
577223
  args.push("--force");
576751
577224
  install2.call((result) => {
576752
- resolve41();
577225
+ resolve42();
576753
577226
  process.exit(result.includes("failed") ? 1 : 0);
576754
577227
  }, {}, args);
576755
577228
  });
@@ -577195,7 +577668,7 @@ __export(exports_main, {
577195
577668
  main: () => main
577196
577669
  });
577197
577670
  import { readFileSync as readFileSync7 } from "fs";
577198
- import { resolve as resolve41 } from "path";
577671
+ import { resolve as resolve42 } from "path";
577199
577672
  function logManagedSettings() {
577200
577673
  try {
577201
577674
  const policySettings = getSettingsForSource("policySettings");
@@ -577752,12 +578225,12 @@ ${getTmuxInstallInstructions2()}
577752
578225
  process.exit(1);
577753
578226
  }
577754
578227
  try {
577755
- const filePath = resolve41(options2.systemPromptFile);
578228
+ const filePath = resolve42(options2.systemPromptFile);
577756
578229
  systemPrompt = readFileSync7(filePath, "utf8");
577757
578230
  } catch (error41) {
577758
578231
  const code = getErrnoCode(error41);
577759
578232
  if (code === "ENOENT") {
577760
- process.stderr.write(source_default.red(`Error: System prompt file not found: ${resolve41(options2.systemPromptFile)}
578233
+ process.stderr.write(source_default.red(`Error: System prompt file not found: ${resolve42(options2.systemPromptFile)}
577761
578234
  `));
577762
578235
  process.exit(1);
577763
578236
  }
@@ -577774,12 +578247,12 @@ ${getTmuxInstallInstructions2()}
577774
578247
  process.exit(1);
577775
578248
  }
577776
578249
  try {
577777
- const filePath = resolve41(options2.appendSystemPromptFile);
578250
+ const filePath = resolve42(options2.appendSystemPromptFile);
577778
578251
  appendSystemPrompt = readFileSync7(filePath, "utf8");
577779
578252
  } catch (error41) {
577780
578253
  const code = getErrnoCode(error41);
577781
578254
  if (code === "ENOENT") {
577782
- process.stderr.write(source_default.red(`Error: Append system prompt file not found: ${resolve41(options2.appendSystemPromptFile)}
578255
+ process.stderr.write(source_default.red(`Error: Append system prompt file not found: ${resolve42(options2.appendSystemPromptFile)}
577783
578256
  `));
577784
578257
  process.exit(1);
577785
578258
  }
@@ -577825,7 +578298,7 @@ ${addendum}` : addendum;
577825
578298
  errors4 = result.errors;
577826
578299
  }
577827
578300
  } else {
577828
- const configPath = resolve41(configItem);
578301
+ const configPath = resolve42(configItem);
577829
578302
  const result = parseMcpConfigFromFilePath({
577830
578303
  filePath: configPath,
577831
578304
  expandVars: true,
@@ -578575,8 +579048,8 @@ ${customInstructions}` : customInstructions;
578575
579048
  return connectMcpBatch(dedupedClaudeAi, "claudeai");
578576
579049
  });
578577
579050
  let claudeaiTimer;
578578
- const claudeaiTimedOut = await Promise.race([claudeaiConnect.then(() => false), new Promise((resolve42) => {
578579
- claudeaiTimer = setTimeout((r) => r(true), CLAUDE_AI_MCP_TIMEOUT_MS, resolve42);
579051
+ const claudeaiTimedOut = await Promise.race([claudeaiConnect.then(() => false), new Promise((resolve43) => {
579052
+ claudeaiTimer = setTimeout((r) => r(true), CLAUDE_AI_MCP_TIMEOUT_MS, resolve43);
578580
579053
  })]);
578581
579054
  if (claudeaiTimer)
578582
579055
  clearTimeout(claudeaiTimer);
@@ -579047,7 +579520,7 @@ Usage: claude --remote "your task description"`, () => gracefulShutdown(1));
579047
579520
  }
579048
579521
  }
579049
579522
  if (options2.resume && typeof options2.resume === "string" && !maybeSessionId) {
579050
- const resolvedPath = resolve41(options2.resume);
579523
+ const resolvedPath = resolve42(options2.resume);
579051
579524
  try {
579052
579525
  const resumeStart = performance.now();
579053
579526
  let logOption;
@@ -579191,7 +579664,7 @@ Usage: claude --remote "your task description"`, () => gracefulShutdown(1));
579191
579664
  pendingHookMessages
579192
579665
  }, renderAndRun);
579193
579666
  }
579194
- }).version("0.4.18 (OpenCow)", "-v, --version", "Output the version number");
579667
+ }).version("0.4.20 (OpenCow)", "-v, --version", "Output the version number");
579195
579668
  program2.option("-w, --worktree [name]", "Create a new git worktree for this session (optionally specify a name)");
579196
579669
  program2.option("--tmux", "Create a tmux session for the worktree (requires --worktree). Uses iTerm2 native panes when available; use --tmux=classic for traditional tmux.");
579197
579670
  if (canUserConfigureAdvisor()) {
@@ -579836,7 +580309,7 @@ if (false) {}
579836
580309
  async function main2() {
579837
580310
  const args = process.argv.slice(2);
579838
580311
  if (args.length === 1 && (args[0] === "--version" || args[0] === "-v" || args[0] === "-V")) {
579839
- console.log(`${"0.4.18"} (OpenCow)`);
580312
+ console.log(`${"0.4.20"} (OpenCow)`);
579840
580313
  return;
579841
580314
  }
579842
580315
  if (args.includes("--provider")) {
@@ -579954,4 +580427,4 @@ async function main2() {
579954
580427
  }
579955
580428
  main2();
579956
580429
 
579957
- //# debugId=B28B6A1F66E05E3B64756E2164756E21
580430
+ //# debugId=ED002285A2B093B464756E2164756E21