@opencow-ai/opencow-agent-sdk 0.4.6 → 0.4.7

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/sdk.js CHANGED
@@ -63345,7 +63345,7 @@ function getToolNameForPermissionCheck(tool) {
63345
63345
  var init_mcpStringUtils = () => {};
63346
63346
 
63347
63347
  // src/constants/toolNames.ts
63348
- var AGENT_TOOL_NAME2 = "Agent", ASK_USER_QUESTION_TOOL_NAME = "AskUserQuestion", BASH_TOOL_NAME = "Bash", ENTER_PLAN_MODE_TOOL_NAME = "EnterPlanMode", ENTER_WORKTREE_TOOL_NAME = "EnterWorktree", EXIT_PLAN_MODE_TOOL_NAME = "ExitPlanMode", EXIT_PLAN_MODE_V2_TOOL_NAME = "ExitPlanMode", EXIT_WORKTREE_TOOL_NAME = "ExitWorktree", FILE_EDIT_TOOL_NAME = "Edit", FILE_READ_TOOL_NAME = "Read", FILE_WRITE_TOOL_NAME = "Write", GLOB_TOOL_NAME = "Glob", GREP_TOOL_NAME = "Grep", NOTEBOOK_EDIT_TOOL_NAME = "NotebookEdit", POWERSHELL_TOOL_NAME = "PowerShell", REPL_TOOL_NAME = "REPL", SEND_MESSAGE_TOOL_NAME = "SendMessage", SKILL_TOOL_NAME = "Skill", SLEEP_TOOL_NAME = "Sleep", SYNTHETIC_OUTPUT_TOOL_NAME = "StructuredOutput", TASK_CREATE_TOOL_NAME = "TaskCreate", TASK_GET_TOOL_NAME = "TaskGet", TASK_LIST_TOOL_NAME = "TaskList", TASK_OUTPUT_TOOL_NAME = "TaskOutput", TASK_STOP_TOOL_NAME = "TaskStop", TASK_UPDATE_TOOL_NAME = "TaskUpdate", TEAM_CREATE_TOOL_NAME = "TeamCreate", TEAM_DELETE_TOOL_NAME = "TeamDelete", TODO_WRITE_TOOL_NAME = "TodoWrite", TOOL_SEARCH_TOOL_NAME = "ToolSearch", EXPLORE_AGENT_TYPE = "Explore", PLAN_AGENT_TYPE = "Plan", WEB_FETCH_TOOL_NAME = "WebFetch", WEB_SEARCH_TOOL_NAME = "WebSearch";
63348
+ var AGENT_TOOL_NAME = "Agent", ASK_USER_QUESTION_TOOL_NAME = "AskUserQuestion", BASH_TOOL_NAME = "Bash", ENTER_PLAN_MODE_TOOL_NAME = "EnterPlanMode", ENTER_WORKTREE_TOOL_NAME = "EnterWorktree", EXIT_PLAN_MODE_TOOL_NAME = "ExitPlanMode", EXIT_PLAN_MODE_V2_TOOL_NAME = "ExitPlanMode", EXIT_WORKTREE_TOOL_NAME = "ExitWorktree", FILE_EDIT_TOOL_NAME = "Edit", FILE_READ_TOOL_NAME = "Read", FILE_WRITE_TOOL_NAME = "Write", GLOB_TOOL_NAME = "Glob", GREP_TOOL_NAME = "Grep", NOTEBOOK_EDIT_TOOL_NAME = "NotebookEdit", POWERSHELL_TOOL_NAME = "PowerShell", REPL_TOOL_NAME = "REPL", SEND_MESSAGE_TOOL_NAME = "SendMessage", SKILL_TOOL_NAME = "Skill", SLEEP_TOOL_NAME = "Sleep", SYNTHETIC_OUTPUT_TOOL_NAME = "StructuredOutput", TASK_CREATE_TOOL_NAME = "TaskCreate", TASK_GET_TOOL_NAME = "TaskGet", TASK_LIST_TOOL_NAME = "TaskList", TASK_OUTPUT_TOOL_NAME = "TaskOutput", TASK_STOP_TOOL_NAME = "TaskStop", TASK_UPDATE_TOOL_NAME = "TaskUpdate", TEAM_CREATE_TOOL_NAME = "TeamCreate", TEAM_DELETE_TOOL_NAME = "TeamDelete", TODO_WRITE_TOOL_NAME = "TodoWrite", TOOL_SEARCH_TOOL_NAME = "ToolSearch", EXPLORE_AGENT_TYPE = "Explore", PLAN_AGENT_TYPE = "Plan", WEB_FETCH_TOOL_NAME = "WebFetch", WEB_SEARCH_TOOL_NAME = "WebSearch";
63349
63349
 
63350
63350
  // src/permissions/permissionRuleParser.ts
63351
63351
  function normalizeLegacyToolName(name) {
@@ -63430,7 +63430,7 @@ function findLastUnescapedChar(str, char) {
63430
63430
  var LEGACY_TOOL_NAME_ALIASES;
63431
63431
  var init_permissionRuleParser = __esm(() => {
63432
63432
  LEGACY_TOOL_NAME_ALIASES = {
63433
- Task: AGENT_TOOL_NAME2,
63433
+ Task: AGENT_TOOL_NAME,
63434
63434
  KillShell: TASK_STOP_TOOL_NAME,
63435
63435
  AgentOutputTool: TASK_OUTPUT_TOOL_NAME,
63436
63436
  BashOutputTool: TASK_OUTPUT_TOOL_NAME,
@@ -96694,7 +96694,8 @@ class OpenAIShimMessages {
96694
96694
  const self2 = this;
96695
96695
  let httpResponse;
96696
96696
  const promise3 = (async () => {
96697
- const request = resolveProviderRequest({ model: self2.providerOverride?.model ?? params.model, baseUrl: self2.providerOverride?.baseURL, reasoningEffortOverride: self2.reasoningEffort });
96697
+ const overrideTransport = self2.providerOverride?.transport === "anthropic" ? undefined : self2.providerOverride?.transport;
96698
+ const request = resolveProviderRequest({ model: self2.providerOverride?.model ?? params.model, baseUrl: self2.providerOverride?.baseURL, reasoningEffortOverride: self2.reasoningEffort, transportOverride: overrideTransport });
96698
96699
  const response = await self2._doRequest(request, params, options);
96699
96700
  httpResponse = response;
96700
96701
  if (params.stream) {
@@ -96719,7 +96720,7 @@ class OpenAIShimMessages {
96719
96720
  }
96720
96721
  async _doRequest(request, params, options) {
96721
96722
  if (request.transport === "openai_responses") {
96722
- const credentials = resolveOpenAIResponsesCredentials();
96723
+ const credentials = this.providerOverride?.apiKey ? { apiKey: this.providerOverride.apiKey, source: "env-openai" } : resolveOpenAIResponsesCredentials();
96723
96724
  if (!credentials.apiKey) {
96724
96725
  const safeModel = redactSecretValueForDisplay(request.requestedModel, process.env) ?? "the requested model";
96725
96726
  const codexAuthHint = credentials.authPath ? `, set CODEX_API_KEY, or place a Codex auth.json at ${credentials.authPath}` : " or set CODEX_API_KEY";
@@ -96738,7 +96739,7 @@ class OpenAIShimMessages {
96738
96739
  ...options?.headers ?? {}
96739
96740
  },
96740
96741
  signal: options?.signal,
96741
- providerSpecific: readOpenAIResponsesProviderSpecific()
96742
+ providerSpecific: this.providerOverride?.providerSpecific?.openaiResponses ?? readOpenAIResponsesProviderSpecific()
96742
96743
  });
96743
96744
  }
96744
96745
  return this._doOpenAIRequest(request, params, options);
@@ -97045,7 +97046,6 @@ async function getNormalizedClient({
97045
97046
  }
97046
97047
  };
97047
97048
  if (providerOverride) {
97048
- const { createOpenAIShimClient: createOpenAIShimClient2 } = await Promise.resolve().then(() => (init_shim2(), exports_shim));
97049
97049
  const safeHeaders = {};
97050
97050
  for (const [k, v] of Object.entries(defaultHeaders)) {
97051
97051
  const lower = k.toLowerCase();
@@ -97053,6 +97053,18 @@ async function getNormalizedClient({
97053
97053
  continue;
97054
97054
  safeHeaders[k] = v;
97055
97055
  }
97056
+ if (providerOverride.transport === "anthropic") {
97057
+ const overrideToken = providerOverride.apiKey ?? getQueryEnvVar("ANTHROPIC_AUTH_TOKEN");
97058
+ return new Anthropic({
97059
+ apiKey: null,
97060
+ ...overrideToken ? { authToken: overrideToken } : {},
97061
+ ...providerOverride.baseURL ? { baseURL: providerOverride.baseURL } : {},
97062
+ ...ARGS,
97063
+ defaultHeaders: safeHeaders,
97064
+ ...isDebugToStdErr() && { logger: createStderrLogger() }
97065
+ });
97066
+ }
97067
+ const { createOpenAIShimClient: createOpenAIShimClient2 } = await Promise.resolve().then(() => (init_shim2(), exports_shim));
97056
97068
  return createOpenAIShimClient2({
97057
97069
  defaultHeaders: safeHeaders,
97058
97070
  maxRetries,
@@ -97530,6 +97542,13 @@ function resolveProviderFromEnv(envOverride) {
97530
97542
  const model = readEnv2(envOverride, "OPENAI_MODEL")?.trim() ?? "";
97531
97543
  return model && isCodexAlias(model) ? providers.codex() : providers.openai();
97532
97544
  }
97545
+ const transport = readEnv2(envOverride, QUERY_ENV_KEY_TRANSPORT_OVERRIDE)?.trim();
97546
+ if (transport === "openai_responses" || transport === "codex_responses") {
97547
+ return providers.codex();
97548
+ }
97549
+ if (transport === "chat_completions") {
97550
+ return providers.openai();
97551
+ }
97533
97552
  if (envOverride) {
97534
97553
  const hasOAuthToken = Boolean(readEnv2(envOverride, "CLAUDE_CODE_OAUTH_TOKEN"));
97535
97554
  return providers.anthropic({
@@ -107602,7 +107621,7 @@ var init_paths2 = __esm(() => {
107602
107621
  });
107603
107622
 
107604
107623
  // src/capabilities/tools/AgentTool/constants.ts
107605
- var AGENT_TOOL_NAME3 = "Agent", LEGACY_AGENT_TOOL_NAME = "Task", VERIFICATION_AGENT_TYPE2 = "verification", ONE_SHOT_BUILTIN_AGENT_TYPES;
107624
+ var AGENT_TOOL_NAME2 = "Agent", LEGACY_AGENT_TOOL_NAME = "Task", VERIFICATION_AGENT_TYPE = "verification", ONE_SHOT_BUILTIN_AGENT_TYPES;
107606
107625
  var init_constants4 = __esm(() => {
107607
107626
  ONE_SHOT_BUILTIN_AGENT_TYPES = new Set([
107608
107627
  "Explore",
@@ -107714,7 +107733,7 @@ function getDescription() {
107714
107733
  - Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+")
107715
107734
  - Filter files with glob parameter (e.g., "*.js", "**/*.tsx") or type parameter (e.g., "js", "py", "rust")
107716
107735
  - Output modes: "content" shows matching lines, "files_with_matches" shows only file paths (default), "count" shows match counts
107717
- - Use ${AGENT_TOOL_NAME3} tool for open-ended searches requiring multiple rounds
107736
+ - Use ${AGENT_TOOL_NAME2} tool for open-ended searches requiring multiple rounds
107718
107737
  - Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping (use \`interface\\{\\}\` to find \`interface{}\` in Go code)
107719
107738
  - Multiline matching: By default patterns match within single lines only. For cross-line patterns like \`struct \\{[\\s\\S]*?field\`, use \`multiline: true\`
107720
107739
  `;
@@ -107751,7 +107770,7 @@ var init_constants5 = __esm(() => {
107751
107770
  GREP_TOOL_NAME2,
107752
107771
  BASH_TOOL_NAME2,
107753
107772
  NOTEBOOK_EDIT_TOOL_NAME2,
107754
- AGENT_TOOL_NAME3
107773
+ AGENT_TOOL_NAME2
107755
107774
  ]);
107756
107775
  });
107757
107776
 
@@ -223847,7 +223866,7 @@ var init_tools = __esm(() => {
223847
223866
  TASK_OUTPUT_TOOL_NAME,
223848
223867
  EXIT_PLAN_MODE_V2_TOOL_NAME,
223849
223868
  ENTER_PLAN_MODE_TOOL_NAME,
223850
- ...process.env.USER_TYPE === "ant" ? [] : [AGENT_TOOL_NAME2],
223869
+ ...process.env.USER_TYPE === "ant" ? [] : [AGENT_TOOL_NAME],
223851
223870
  ASK_USER_QUESTION_TOOL_NAME,
223852
223871
  TASK_STOP_TOOL_NAME,
223853
223872
  ...[]
@@ -223881,7 +223900,7 @@ var init_tools = __esm(() => {
223881
223900
  ...[]
223882
223901
  ]);
223883
223902
  COORDINATOR_MODE_ALLOWED_TOOLS = new Set([
223884
- AGENT_TOOL_NAME2,
223903
+ AGENT_TOOL_NAME,
223885
223904
  TASK_STOP_TOOL_NAME,
223886
223905
  SEND_MESSAGE_TOOL_NAME,
223887
223906
  SYNTHETIC_OUTPUT_TOOL_NAME
@@ -231969,7 +231988,7 @@ var init_exploreAgent = __esm(() => {
231969
231988
  agentType: "Explore",
231970
231989
  whenToUse: EXPLORE_WHEN_TO_USE,
231971
231990
  disallowedTools: [
231972
- AGENT_TOOL_NAME2,
231991
+ AGENT_TOOL_NAME,
231973
231992
  EXIT_PLAN_MODE_TOOL_NAME,
231974
231993
  FILE_EDIT_TOOL_NAME,
231975
231994
  FILE_WRITE_TOOL_NAME,
@@ -232075,7 +232094,7 @@ var init_planAgent = __esm(() => {
232075
232094
  agentType: "Plan",
232076
232095
  whenToUse: "Software architect agent for designing implementation plans. Use this when you need to plan the implementation strategy for a task. Returns step-by-step plans, identifies critical files, and considers architectural trade-offs.",
232077
232096
  disallowedTools: [
232078
- AGENT_TOOL_NAME3,
232097
+ AGENT_TOOL_NAME2,
232079
232098
  EXIT_PLAN_MODE_TOOL_NAME,
232080
232099
  FILE_EDIT_TOOL_NAME,
232081
232100
  FILE_WRITE_TOOL_NAME,
@@ -232363,7 +232382,23 @@ Use the literal string \`VERDICT: \` followed by exactly one of \`PASS\`, \`FAIL
232363
232382
  - **PARTIAL**: what was verified, what could not be and why (missing tool/env), what the implementer should know.`;
232364
232383
  });
232365
232384
 
232385
+ // src/capabilities/tools/AgentTool/agentMerge.ts
232386
+ function mergeAgentsByType(base2, override) {
232387
+ const byType = new Map;
232388
+ for (const agent of base2)
232389
+ byType.set(agent.agentType, agent);
232390
+ for (const agent of override)
232391
+ byType.set(agent.agentType, agent);
232392
+ return [...byType.values()];
232393
+ }
232394
+
232366
232395
  // src/capabilities/tools/AgentTool/builtInAgents.ts
232396
+ var exports_builtInAgents = {};
232397
+ __export(exports_builtInAgents, {
232398
+ resolveSdkAgents: () => resolveSdkAgents,
232399
+ getBuiltInAgents: () => getBuiltInAgents,
232400
+ areExplorePlanAgentsEnabled: () => areExplorePlanAgentsEnabled
232401
+ });
232367
232402
  function areExplorePlanAgentsEnabled() {
232368
232403
  if (false) {}
232369
232404
  return false;
@@ -232387,6 +232422,9 @@ function getBuiltInAgents() {
232387
232422
  if (false) {}
232388
232423
  return agents;
232389
232424
  }
232425
+ function resolveSdkAgents(hostAgents) {
232426
+ return mergeAgentsByType(getBuiltInAgents(), hostAgents);
232427
+ }
232390
232428
  var init_builtInAgents = __esm(() => {
232391
232429
  init_state();
232392
232430
  init_envUtils();
@@ -234457,6 +234495,34 @@ var init_registerFrontmatterHooks = __esm(() => {
234457
234495
  init_sessionHooks();
234458
234496
  });
234459
234497
 
234498
+ // src/session/backgroundAbortRegistry.ts
234499
+ function registerBackgroundAgentAbort(agentId, controller) {
234500
+ runs.set(agentId, { controller, stopFired: false });
234501
+ }
234502
+ function unregisterBackgroundAgentAbort(agentId) {
234503
+ runs.delete(agentId);
234504
+ }
234505
+ function abortBackgroundAgentById(agentId) {
234506
+ const run = runs.get(agentId);
234507
+ if (!run)
234508
+ return false;
234509
+ run.controller.abort();
234510
+ return true;
234511
+ }
234512
+ function markSubagentStopFired(agentId) {
234513
+ const run = runs.get(agentId);
234514
+ if (run) {
234515
+ run.stopFired = true;
234516
+ }
234517
+ }
234518
+ function hasSubagentStopFired(agentId) {
234519
+ return runs.get(agentId)?.stopFired ?? false;
234520
+ }
234521
+ var runs;
234522
+ var init_backgroundAbortRegistry = __esm(() => {
234523
+ runs = new Map;
234524
+ });
234525
+
234460
234526
  // src/providers/shared/model/agent.ts
234461
234527
  function getDefaultSubagentModel() {
234462
234528
  return "inherit";
@@ -234508,6 +234574,12 @@ var init_agent = __esm(() => {
234508
234574
  });
234509
234575
 
234510
234576
  // src/providers/shared/routing.ts
234577
+ function resolveModelProvider(model, modelProviders) {
234578
+ const config2 = modelProviders?.[model];
234579
+ if (!config2)
234580
+ return null;
234581
+ return { model, ...config2 };
234582
+ }
234511
234583
  function normalize10(key) {
234512
234584
  return key.toLowerCase().replace(/[-_]/g, "");
234513
234585
  }
@@ -234811,6 +234883,12 @@ var init_caching = __esm(() => {
234811
234883
  });
234812
234884
 
234813
234885
  // src/providers/shared/model/antModels.ts
234886
+ function getAntModelOverrideConfig2() {
234887
+ if (process.env.USER_TYPE !== "ant") {
234888
+ return null;
234889
+ }
234890
+ return getFeatureValue_CACHED_MAY_BE_STALE("tengu_ant_model_override", null);
234891
+ }
234814
234892
  var init_antModels = () => {};
234815
234893
 
234816
234894
  // src/lib/fingerprint.ts
@@ -235043,7 +235121,7 @@ function filterToolsForAgent({
235043
235121
  }
235044
235122
  if (isAsync2 && !ASYNC_AGENT_ALLOWED_TOOLS.has(tool.name)) {
235045
235123
  if (isAgentSwarmsEnabled() && isInProcessTeammate()) {
235046
- if (toolMatchesName(tool, AGENT_TOOL_NAME3)) {
235124
+ if (toolMatchesName(tool, AGENT_TOOL_NAME2)) {
235047
235125
  return true;
235048
235126
  }
235049
235127
  if (IN_PROCESS_TEAMMATE_ALLOWED_TOOLS.has(tool.name)) {
@@ -235093,7 +235171,7 @@ function resolveAgentTools(agentDefinition, availableTools, isAsync2 = false, is
235093
235171
  let allowedAgentTypes;
235094
235172
  for (const toolSpec of agentTools) {
235095
235173
  const { toolName, ruleContent } = permissionRuleValueFromString(toolSpec);
235096
- if (toolName === AGENT_TOOL_NAME3) {
235174
+ if (toolName === AGENT_TOOL_NAME2) {
235097
235175
  if (ruleContent) {
235098
235176
  allowedAgentTypes = ruleContent.split(",").map((s) => s.trim());
235099
235177
  }
@@ -235312,6 +235390,8 @@ async function runAsyncAgentLifecycle({
235312
235390
  return;
235313
235391
  }
235314
235392
  const msg = errorMessage(error41);
235393
+ logForDebugging(`Background agent ${taskId} failed: ${msg}
235394
+ ${error41 instanceof Error ? error41.stack ?? "" : ""}`, { level: "error" });
235315
235395
  failAgentTask(taskId, msg, rootSetAppState);
235316
235396
  const worktreeResult = await getWorktreeResult();
235317
235397
  enqueueAgentNotification({
@@ -235466,6 +235546,49 @@ async function initializeAgentMcpServers(agentDefinition, parentClients) {
235466
235546
  function isRecordableMessage(msg) {
235467
235547
  return msg.type === "assistant" || msg.type === "user" || msg.type === "progress" || msg.type === "system" && "subtype" in msg && msg.subtype === "compact_boundary";
235468
235548
  }
235549
+ function simplifySubagentMessageBlocks(msg) {
235550
+ const content = msg.message.content;
235551
+ if (!Array.isArray(content))
235552
+ return [];
235553
+ const out = [];
235554
+ for (const raw of content) {
235555
+ if (!raw || typeof raw !== "object")
235556
+ continue;
235557
+ const block2 = raw;
235558
+ switch (block2.type) {
235559
+ case "text":
235560
+ if (typeof block2.text === "string" && block2.text) {
235561
+ out.push({ type: "text", text: block2.text });
235562
+ }
235563
+ break;
235564
+ case "thinking":
235565
+ if (typeof block2.thinking === "string" && block2.thinking) {
235566
+ out.push({ type: "thinking", thinking: block2.thinking });
235567
+ }
235568
+ break;
235569
+ case "tool_use":
235570
+ out.push({
235571
+ type: "tool_use",
235572
+ tool_use_id: block2.id,
235573
+ name: block2.name,
235574
+ input: block2.input ?? {}
235575
+ });
235576
+ break;
235577
+ case "tool_result": {
235578
+ const c6 = block2.content;
235579
+ const text = typeof c6 === "string" ? c6 : Array.isArray(c6) ? c6.map((p) => p && typeof p === "object" && p.type === "text" ? String(p.text ?? "") : "").join("") : "";
235580
+ out.push({
235581
+ type: "tool_result",
235582
+ tool_use_id: block2.tool_use_id,
235583
+ content: text,
235584
+ is_error: Boolean(block2.is_error)
235585
+ });
235586
+ break;
235587
+ }
235588
+ }
235589
+ }
235590
+ return out;
235591
+ }
235469
235592
  async function* runAgent({
235470
235593
  agentDefinition,
235471
235594
  promptMessages,
@@ -235488,13 +235611,14 @@ async function* runAgent({
235488
235611
  description,
235489
235612
  transcriptSubdir,
235490
235613
  onQueryProgress,
235614
+ onPartialAssistant,
235491
235615
  agentName
235492
235616
  }) {
235493
235617
  const appState = toolUseContext.getAppState();
235494
235618
  const permissionMode = appState.toolPermissionContext.mode;
235495
235619
  const rootSetAppState = toolUseContext.setAppStateForTasks ?? toolUseContext.setAppState;
235496
235620
  const resolvedAgentModel = getAgentModel(agentDefinition.model, toolUseContext.options.mainLoopModel, model, permissionMode);
235497
- const providerOverride = resolveAgentProvider(agentName, agentDefinition.agentType, getInitialSettings());
235621
+ const providerOverride = resolveAgentProvider(agentName, agentDefinition.agentType, getInitialSettings()) ?? resolveModelProvider(resolvedAgentModel, toolUseContext.options.modelProviders);
235498
235622
  const effectiveModel = providerOverride ? providerOverride.model : resolvedAgentModel;
235499
235623
  const agentId = override?.agentId ? override.agentId : createAgentId();
235500
235624
  if (transcriptSubdir) {
@@ -235565,8 +235689,11 @@ async function* runAgent({
235565
235689
  const additionalWorkingDirectories = Array.from(appState.toolPermissionContext.additionalWorkingDirectories.keys());
235566
235690
  const agentSystemPrompt = override?.systemPrompt ? override.systemPrompt : asSystemPrompt(await getAgentSystemPrompt(agentDefinition, toolUseContext, resolvedAgentModel, additionalWorkingDirectories, resolvedTools));
235567
235691
  const agentAbortController = override?.abortController ? override.abortController : isAsync2 ? new AbortController : toolUseContext.abortController;
235692
+ if (isAsync2) {
235693
+ registerBackgroundAgentAbort(agentId, agentAbortController);
235694
+ }
235568
235695
  const additionalContexts = [];
235569
- for await (const hookResult of executeSubagentStartHooks(agentId, agentDefinition.agentType, agentAbortController.signal)) {
235696
+ for await (const hookResult of executeSubagentStartHooks(agentId, agentDefinition.agentType, agentAbortController.signal, undefined, toolUseContext.toolUseId, isAsync2)) {
235570
235697
  if (hookResult.additionalContexts && hookResult.additionalContexts.length > 0) {
235571
235698
  additionalContexts.push(...hookResult.additionalContexts);
235572
235699
  }
@@ -235631,7 +235758,7 @@ async function* runAgent({
235631
235758
  verbose: toolUseContext.options.verbose,
235632
235759
  mainLoopModel: effectiveModel,
235633
235760
  providerOverride: providerOverride ?? undefined,
235634
- thinkingConfig: useExactTools ? toolUseContext.options.thinkingConfig : { type: "disabled" },
235761
+ thinkingConfig: toolUseContext.options.thinkingConfig,
235635
235762
  mcpClients: mergedMcpClients,
235636
235763
  mcpResources: toolUseContext.options.mcpResources,
235637
235764
  agentDefinitions: toolUseContext.options.agentDefinitions,
@@ -235669,6 +235796,12 @@ async function* runAgent({
235669
235796
  ...description && { description }
235670
235797
  }).catch((_err) => logForDebugging(`Failed to write agent metadata: ${_err}`));
235671
235798
  let lastRecordedUuid = initialMessages.at(-1)?.uuid ?? null;
235799
+ let partialBaseMessage = null;
235800
+ const partialTextByIndex = new Map;
235801
+ const PARTIAL_PROGRESS_HOOK_INTERVAL_MS = 100;
235802
+ let lastPartialProgressHookAt = 0;
235803
+ let lastAssistantForFallback = null;
235804
+ let agentRunError;
235672
235805
  try {
235673
235806
  for await (const message of query({
235674
235807
  messages: initialMessages,
@@ -235681,8 +235814,37 @@ async function* runAgent({
235681
235814
  maxTurns: maxTurns ?? agentDefinition.maxTurns
235682
235815
  })) {
235683
235816
  onQueryProgress?.();
235684
- if (message.type === "stream_event" && message.event.type === "message_start" && message.ttftMs != null) {
235685
- toolUseContext.pushApiMetricsEntry?.(message.ttftMs);
235817
+ if (message.type === "stream_event") {
235818
+ const ev = message.event;
235819
+ if (ev.type === "message_start") {
235820
+ if (message.ttftMs != null) {
235821
+ toolUseContext.pushApiMetricsEntry?.(message.ttftMs);
235822
+ }
235823
+ if ((onPartialAssistant || isAsync2) && ev.message) {
235824
+ partialBaseMessage = ev.message;
235825
+ partialTextByIndex.clear();
235826
+ }
235827
+ } else if ((onPartialAssistant || isAsync2) && partialBaseMessage && ev.type === "content_block_delta" && ev.delta?.type === "text_delta" && typeof ev.delta.text === "string") {
235828
+ const idx = ev.index ?? 0;
235829
+ const acc = (partialTextByIndex.get(idx) ?? "") + ev.delta.text;
235830
+ partialTextByIndex.set(idx, acc);
235831
+ onPartialAssistant?.({
235832
+ type: "assistant",
235833
+ message: {
235834
+ ...partialBaseMessage,
235835
+ content: [{ type: "text", text: acc, citations: null }]
235836
+ },
235837
+ uuid: randomUUID6(),
235838
+ timestamp: new Date().toISOString()
235839
+ });
235840
+ if (isAsync2) {
235841
+ const now = Date.now();
235842
+ if (now - lastPartialProgressHookAt >= PARTIAL_PROGRESS_HOOK_INTERVAL_MS) {
235843
+ lastPartialProgressHookAt = now;
235844
+ executeSubagentProgressHooks(agentId, agentDefinition.agentType, partialBaseMessage.id, toolUseContext.toolUseId, [{ type: "text", text: acc }]).catch(() => {});
235845
+ }
235846
+ }
235847
+ }
235686
235848
  continue;
235687
235849
  }
235688
235850
  if (message.type === "attachment") {
@@ -235707,6 +235869,16 @@ async function* runAgent({
235707
235869
  if (message.type !== "progress") {
235708
235870
  lastRecordedUuid = message.uuid;
235709
235871
  }
235872
+ if (isAsync2 && message.type === "assistant" && message.message.content.some((b) => b.type === "text" && b.text.trim().length > 0)) {
235873
+ lastAssistantForFallback = message;
235874
+ }
235875
+ if (isAsync2 && (message.type === "assistant" || message.type === "user")) {
235876
+ const blocks = simplifySubagentMessageBlocks(message);
235877
+ if (blocks.length > 0) {
235878
+ const messageId = (message.type === "assistant" ? message.message.id : undefined) ?? message.uuid;
235879
+ executeSubagentProgressHooks(agentId, agentDefinition.agentType, messageId, toolUseContext.toolUseId, blocks).catch(() => {});
235880
+ }
235881
+ }
235710
235882
  yield message;
235711
235883
  }
235712
235884
  }
@@ -235716,7 +235888,30 @@ async function* runAgent({
235716
235888
  if (isBuiltInAgent(agentDefinition) && agentDefinition.callback) {
235717
235889
  agentDefinition.callback();
235718
235890
  }
235891
+ } catch (err2) {
235892
+ agentRunError = err2;
235893
+ throw err2;
235719
235894
  } finally {
235895
+ const naturalStopAlreadyFired = isAsync2 && hasSubagentStopFired(agentId);
235896
+ if (isAsync2) {
235897
+ unregisterBackgroundAgentAbort(agentId);
235898
+ }
235899
+ if (isAsync2 && agentRunError !== undefined) {
235900
+ logForDebugging(`Background agent ${agentId} crashed: ${errorMessage(agentRunError)}
235901
+ ${agentRunError instanceof Error ? agentRunError.stack ?? "" : ""}`, { level: "error" });
235902
+ }
235903
+ if (isAsync2 && !naturalStopAlreadyFired) {
235904
+ try {
235905
+ const fallbackAppState = agentToolRuntimeContext.getAppState();
235906
+ const terminal = agentAbortController.signal.aborted ? { status: "stopped" } : agentRunError !== undefined ? { status: "failed", errorMessage: errorMessage(agentRunError) } : { status: "completed" };
235907
+ const fallbackStop = executeStopHooks(fallbackAppState.toolPermissionContext.mode, undefined, undefined, false, agentId, agentToolRuntimeContext, lastAssistantForFallback ? [lastAssistantForFallback] : undefined, agentDefinition.agentType, undefined, terminal);
235908
+ for await (const evt of fallbackStop) {}
235909
+ } catch (err2) {
235910
+ logForDebugging(`Fallback SubagentStop failed for ${agentId}: ${err2}`, {
235911
+ level: "warn"
235912
+ });
235913
+ }
235914
+ }
235720
235915
  await mcpCleanup();
235721
235916
  if (agentDefinition.hooks) {
235722
235917
  clearSessionHooks(rootSetAppState, agentId);
@@ -235812,6 +236007,7 @@ var init_runAgent = __esm(() => {
235812
236007
  init_registerFrontmatterHooks();
235813
236008
  init_sessionHooks();
235814
236009
  init_hooks2();
236010
+ init_backgroundAbortRegistry();
235815
236011
  init_messages4();
235816
236012
  init_agent();
235817
236013
  init_settings2();
@@ -236597,7 +236793,7 @@ var init_TodoWriteTool = __esm(() => {
236597
236793
  const base2 = `Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable`;
236598
236794
  const nudge = verificationNudgeNeeded ? `
236599
236795
 
236600
- NOTE: You just closed out 3+ tasks and none of them was a verification step. Before writing your final summary, spawn the verification agent (subagent_type="${VERIFICATION_AGENT_TYPE2}"). You cannot self-assign PARTIAL by listing caveats in your summary — only the verifier issues a verdict.` : "";
236796
+ NOTE: You just closed out 3+ tasks and none of them was a verification step. Before writing your final summary, spawn the verification agent (subagent_type="${VERIFICATION_AGENT_TYPE}"). You cannot self-assign PARTIAL by listing caveats in your summary — only the verifier issues a verdict.` : "";
236601
236797
  return {
236602
236798
  tool_use_id: toolUseID,
236603
236799
  type: "tool_result",
@@ -238522,7 +238718,9 @@ var init_coreSchemas = __esm(() => {
238522
238718
  SubagentStartHookInputSchema = lazySchema(() => BaseHookInputSchema().and(exports_external2.object({
238523
238719
  hook_event_name: exports_external2.literal("SubagentStart"),
238524
238720
  agent_id: exports_external2.string(),
238525
- agent_type: exports_external2.string()
238721
+ agent_type: exports_external2.string(),
238722
+ tool_use_id: exports_external2.string().optional().describe("tool_use id of the Agent tool call that launched this subagent. " + "Lets hosts correlate the subagent lifecycle back to the launching " + "tool call (e.g. to render an inline running indicator on its pill)."),
238723
+ is_background: exports_external2.boolean().optional().describe("True when the subagent was launched with run_in_background (async). " + "Lets hosts scope background-specific UI/notifications to async agents.")
238526
238724
  })));
238527
238725
  SubagentStopHookInputSchema = lazySchema(() => BaseHookInputSchema().and(exports_external2.object({
238528
238726
  hook_event_name: exports_external2.literal("SubagentStop"),
@@ -238530,7 +238728,9 @@ var init_coreSchemas = __esm(() => {
238530
238728
  agent_id: exports_external2.string(),
238531
238729
  agent_transcript_path: exports_external2.string(),
238532
238730
  agent_type: exports_external2.string(),
238533
- last_assistant_message: exports_external2.string().optional().describe("Text content of the last assistant message before stopping. " + "Avoids the need to read and parse the transcript file.")
238731
+ last_assistant_message: exports_external2.string().optional().describe("Text content of the last assistant message before stopping. " + "Avoids the need to read and parse the transcript file."),
238732
+ status: exports_external2.enum(["completed", "failed", "stopped"]).optional().describe("Terminal outcome carried by the guaranteed terminal delivery for " + "background subagents (fired from the run teardown). Absent on the " + "natural-stop path — hosts treat a missing status as completed."),
238733
+ error_message: exports_external2.string().optional().describe("Present when status is failed: the error that aborted the run.")
238534
238734
  })));
238535
238735
  PreCompactHookInputSchema = lazySchema(() => BaseHookInputSchema().and(exports_external2.object({
238536
238736
  hook_event_name: exports_external2.literal("PreCompact"),
@@ -250244,7 +250444,7 @@ ${forkEnabled ? "For fresh agents, terse" : "Terse"} command-style prompts produ
250244
250444
  <example>
250245
250445
  user: "What's left on this branch before we can ship?"
250246
250446
  assistant: <thinking>Forking this — it's a survey question. I want the punch list, not the git output in my context.</thinking>
250247
- ${AGENT_TOOL_NAME3}({
250447
+ ${AGENT_TOOL_NAME2}({
250248
250448
  name: "ship-audit",
250249
250449
  description: "Branch ship-readiness audit",
250250
250450
  prompt: "Audit what's left before this branch can ship. Check: uncommitted changes, commits ahead of main, whether tests exist, whether the GrowthBook gate is wired up, whether CI-relevant files changed. Report a punch list — done vs. missing. Under 200 words."
@@ -250271,7 +250471,7 @@ assistant: <thinking>I'll ask the code-reviewer agent — it won't see my analys
250271
250471
  <commentary>
250272
250472
  A subagent_type is specified, so the agent starts fresh. It needs full context in the prompt. The briefing explains what to assess and why.
250273
250473
  </commentary>
250274
- ${AGENT_TOOL_NAME3}({
250474
+ ${AGENT_TOOL_NAME2}({
250275
250475
  name: "migration-review",
250276
250476
  description: "Independent migration review",
250277
250477
  subagent_type: "code-reviewer",
@@ -250301,7 +250501,7 @@ function isPrime(n) {
250301
250501
  <commentary>
250302
250502
  Since a significant piece of code was written and the task was completed, now use the test-runner agent to run the tests
250303
250503
  </commentary>
250304
- assistant: Uses the ${AGENT_TOOL_NAME3} tool to launch the test-runner agent
250504
+ assistant: Uses the ${AGENT_TOOL_NAME2} tool to launch the test-runner agent
250305
250505
  </example>
250306
250506
 
250307
250507
  <example>
@@ -250309,7 +250509,7 @@ user: "Hello"
250309
250509
  <commentary>
250310
250510
  Since the user is greeting, use the greeting-responder agent to respond with a friendly joke
250311
250511
  </commentary>
250312
- assistant: "I'm going to use the ${AGENT_TOOL_NAME3} tool to launch the greeting-responder agent"
250512
+ assistant: "I'm going to use the ${AGENT_TOOL_NAME2} tool to launch the greeting-responder agent"
250313
250513
  </example>
250314
250514
  `;
250315
250515
  const listViaAttachment = shouldInjectAgentListInMessages();
@@ -250318,11 +250518,11 @@ ${effectiveAgents.map((agent) => formatAgentLine(agent)).join(`
250318
250518
  `)}`;
250319
250519
  const shared2 = `Launch a new agent to handle complex, multi-step tasks autonomously.
250320
250520
 
250321
- The ${AGENT_TOOL_NAME3} tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
250521
+ The ${AGENT_TOOL_NAME2} tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
250322
250522
 
250323
250523
  ${agentListSection}
250324
250524
 
250325
- ${forkEnabled ? `When using the ${AGENT_TOOL_NAME3} tool, specify a subagent_type to use a specialized agent, or omit it to fork yourself — a fork inherits your full conversation context.` : `When using the ${AGENT_TOOL_NAME3} tool, specify a subagent_type parameter to select which agent type to use. If omitted, the general-purpose agent is used.`}`;
250525
+ ${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.` : `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.`}`;
250326
250526
  if (isCoordinator) {
250327
250527
  return shared2;
250328
250528
  }
@@ -250330,10 +250530,10 @@ ${forkEnabled ? `When using the ${AGENT_TOOL_NAME3} tool, specify a subagent_typ
250330
250530
  const fileSearchHint = embedded ? "`find` via the Bash tool" : `the ${GLOB_TOOL_NAME2} tool`;
250331
250531
  const contentSearchHint = embedded ? "`grep` via the Bash tool" : `the ${GLOB_TOOL_NAME2} tool`;
250332
250532
  const whenNotToUseSection = forkEnabled ? "" : `
250333
- When NOT to use the ${AGENT_TOOL_NAME3} tool:
250334
- - If you want to read a specific file path, use the ${FILE_READ_TOOL_NAME2} tool or ${fileSearchHint} instead of the ${AGENT_TOOL_NAME3} tool, to find the match more quickly
250533
+ When NOT to use the ${AGENT_TOOL_NAME2} tool:
250534
+ - If you want to read a specific file path, use the ${FILE_READ_TOOL_NAME2} tool or ${fileSearchHint} instead of the ${AGENT_TOOL_NAME2} tool, to find the match more quickly
250335
250535
  - If you are searching for a specific class definition like "class Foo", use ${contentSearchHint} instead, to find the match more quickly
250336
- - If you are searching for code within a specific file or set of 2-3 files, use the ${FILE_READ_TOOL_NAME2} tool instead of the ${AGENT_TOOL_NAME3} tool, to find the match more quickly
250536
+ - If you are searching for code within a specific file or set of 2-3 files, use the ${FILE_READ_TOOL_NAME2} tool instead of the ${AGENT_TOOL_NAME2} tool, to find the match more quickly
250337
250537
  - Other tasks that are not related to the agent descriptions above
250338
250538
  `;
250339
250539
  const concurrencyNote = !listViaAttachment && getSubscriptionType() !== "pro" ? `
@@ -250350,7 +250550,7 @@ Usage notes:
250350
250550
  - The agent's outputs should generally be trusted
250351
250551
  - 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"}
250352
250552
  - 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.
250353
- - If the user specifies that they want you to run agents "in parallel", you MUST send a single message with multiple ${AGENT_TOOL_NAME3} tool use content blocks. For example, if you need to launch both a build-validator agent and a test-runner agent in parallel, send a single message with both tool calls.
250553
+ - 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. For example, if you need to launch both a build-validator agent and a test-runner agent in parallel, send a single message with both tool calls.
250354
250554
  - 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" ? `
250355
250555
  - 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() ? `
250356
250556
  - The run_in_background, name, team_name, and mode parameters are not available in this context. Only synchronous subagents are supported.` : isTeammate() ? `
@@ -250500,11 +250700,11 @@ var init_AgentTool = __esm(() => {
250500
250700
  }
250501
250701
  }
250502
250702
  const agentsWithMcpRequirementsMet = filterAgentsByMcpRequirements(agents, mcpServersWithTools);
250503
- const filteredAgents = filterDeniedAgents(agentsWithMcpRequirementsMet, toolPermissionContext, AGENT_TOOL_NAME3);
250703
+ const filteredAgents = filterDeniedAgents(agentsWithMcpRequirementsMet, toolPermissionContext, AGENT_TOOL_NAME2);
250504
250704
  const isCoordinator = false;
250505
250705
  return await getPrompt2(filteredAgents, isCoordinator, allowedAgentTypes);
250506
250706
  },
250507
- name: AGENT_TOOL_NAME3,
250707
+ name: AGENT_TOOL_NAME2,
250508
250708
  searchHint: "delegate work to a subagent",
250509
250709
  aliases: [LEGACY_AGENT_TOOL_NAME],
250510
250710
  maxResultSizeChars: 1e5,
@@ -250584,13 +250784,13 @@ var init_AgentTool = __esm(() => {
250584
250784
  const {
250585
250785
  allowedAgentTypes
250586
250786
  } = toolUseContext.options.agentDefinitions;
250587
- const agents = filterDeniedAgents(allowedAgentTypes ? allAgents.filter((a2) => allowedAgentTypes.includes(a2.agentType)) : allAgents, appState.toolPermissionContext, AGENT_TOOL_NAME3);
250787
+ const agents = filterDeniedAgents(allowedAgentTypes ? allAgents.filter((a2) => allowedAgentTypes.includes(a2.agentType)) : allAgents, appState.toolPermissionContext, AGENT_TOOL_NAME2);
250588
250788
  const found = agents.find((agent) => agent.agentType === effectiveType);
250589
250789
  if (!found) {
250590
250790
  const agentExistsButDenied = allAgents.find((agent) => agent.agentType === effectiveType);
250591
250791
  if (agentExistsButDenied) {
250592
- const denyRule = getDenyRuleForAgent(appState.toolPermissionContext, AGENT_TOOL_NAME3, effectiveType);
250593
- throw new Error(`Agent type '${effectiveType}' has been denied by permission rule '${AGENT_TOOL_NAME3}(${effectiveType})' from ${denyRule?.source ?? "settings"}.`);
250792
+ const denyRule = getDenyRuleForAgent(appState.toolPermissionContext, AGENT_TOOL_NAME2, effectiveType);
250793
+ throw new Error(`Agent type '${effectiveType}' has been denied by permission rule '${AGENT_TOOL_NAME2}(${effectiveType})' from ${denyRule?.source ?? "settings"}.`);
250594
250794
  }
250595
250795
  throw new Error(`Agent type '${effectiveType}' not found. Available agents: ${agents.map((a2) => a2.agentType).join(", ")}`);
250596
250796
  }
@@ -250961,6 +251161,19 @@ ${reasons}`);
250961
251161
  ...runAgentParams.override,
250962
251162
  agentId: syncAgentId
250963
251163
  },
251164
+ onPartialAssistant: onProgress ? (partial2) => {
251165
+ if (partial2.message.content.length === 0)
251166
+ return;
251167
+ onProgress({
251168
+ toolUseID: `agent_${assistantMessage.message.id}`,
251169
+ data: {
251170
+ message: partial2,
251171
+ type: "agent_progress",
251172
+ prompt: "",
251173
+ agentId: syncAgentId
251174
+ }
251175
+ });
251176
+ } : undefined,
250964
251177
  onCacheSafeParams: summaryTaskId && getSdkAgentProgressSummariesEnabled() ? (params) => {
250965
251178
  const {
250966
251179
  stop
@@ -251143,21 +251356,16 @@ ${reasons}`);
251143
251356
  }
251144
251357
  const normalizedNew = normalizeMessages([message]);
251145
251358
  for (const m of normalizedNew) {
251146
- for (const content of m.message.content) {
251147
- if (content.type !== "tool_use" && content.type !== "tool_result") {
251148
- continue;
251149
- }
251150
- if (onProgress) {
251151
- onProgress({
251152
- toolUseID: `agent_${assistantMessage.message.id}`,
251153
- data: {
251154
- message: m,
251155
- type: "agent_progress",
251156
- prompt: "",
251157
- agentId: syncAgentId
251158
- }
251159
- });
251160
- }
251359
+ if (onProgress && m.message.content.length > 0) {
251360
+ onProgress({
251361
+ toolUseID: `agent_${assistantMessage.message.id}`,
251362
+ data: {
251363
+ message: m,
251364
+ type: "agent_progress",
251365
+ prompt: "",
251366
+ agentId: syncAgentId
251367
+ }
251368
+ });
251161
251369
  }
251162
251370
  }
251163
251371
  }
@@ -251305,10 +251513,9 @@ Briefly tell the user what you launched and end your response.`
251305
251513
  if (data.status === "async_launched") {
251306
251514
  const prefix = `Async agent launched successfully.
251307
251515
  agentId: ${data.agentId} (internal ID - do not mention to user. Use SendMessage with to: '${data.agentId}' to continue this agent.)
251308
- The agent is working in the background. You will be notified automatically when it completes.`;
251309
- const instructions = data.canReadOutputFile ? `Do not duplicate this agent's work — avoid working with the same files or topics it is using. Work on non-overlapping tasks, or briefly tell the user what you launched and end your response.
251310
- output_file: ${data.outputFile}
251311
- If asked, you can check progress before completion by using ${FILE_READ_TOOL_NAME2} or ${BASH_TOOL_NAME2} tail on the output file.` : `Briefly tell the user what you launched and end your response. Do not generate any other text — agent results will arrive in a subsequent message.`;
251516
+ The agent is working in the background. Its result will be delivered to you automatically when it completes.`;
251517
+ const instructions = `Do not duplicate this agent's work — avoid working with the same files or topics it is using. Work on non-overlapping tasks, or briefly tell the user what you launched and end your response.
251518
+ Do NOT read its output/transcript file to check progress — its result will arrive automatically in a subsequent message.`;
251312
251519
  const text = `${prefix}
251313
251520
  ${instructions}`;
251314
251521
  return {
@@ -256809,7 +257016,7 @@ function toComparable(p) {
256809
257016
  return IS_WINDOWS ? posixForm.toLowerCase() : posixForm;
256810
257017
  }
256811
257018
  function detectSessionFileType(filePath) {
256812
- const configDir = getClaudeConfigHomeDir();
257019
+ const configDir = resolveConfigHomeDir();
256813
257020
  const normalized = toComparable(filePath);
256814
257021
  const configDirCmp = toComparable(configDir);
256815
257022
  if (!normalized.startsWith(configDirCmp)) {
@@ -256855,6 +257062,7 @@ var init_memoryFileDetection = __esm(() => {
256855
257062
  init_agentMemory();
256856
257063
  init_state2();
256857
257064
  init_paths();
257065
+ init_envUtils();
256858
257066
  init_windowsPaths();
256859
257067
  IS_WINDOWS = process.platform === "win32";
256860
257068
  });
@@ -258095,7 +258303,7 @@ Git Safety Protocol:
258095
258303
 
258096
258304
  Important notes:
258097
258305
  - NEVER run additional commands to read or explore code, besides git bash commands
258098
- - NEVER use the ${TodoWriteTool.name} or ${AGENT_TOOL_NAME3} tools
258306
+ - NEVER use the ${TodoWriteTool.name} or ${AGENT_TOOL_NAME2} tools
258099
258307
  - DO NOT push to the remote repository unless the user explicitly asks you to do so
258100
258308
  - IMPORTANT: Never use git commands with the -i flag (like git rebase -i or git add -i) since they require interactive input which is not supported.
258101
258309
  - IMPORTANT: Do not use --no-edit with git rebase commands, as the --no-edit flag is not a valid option for git rebase.
@@ -258141,7 +258349,7 @@ EOF
258141
258349
  </example>
258142
258350
 
258143
258351
  Important:
258144
- - DO NOT use the ${TodoWriteTool.name} or ${AGENT_TOOL_NAME3} tools
258352
+ - DO NOT use the ${TodoWriteTool.name} or ${AGENT_TOOL_NAME2} tools
258145
258353
  - Return the PR URL when you're done, so the user can see it
258146
258354
 
258147
258355
  # Other common operations
@@ -282266,7 +282474,7 @@ function getAnthropicEnvMetadata() {
282266
282474
  function getBuildAgeMinutes() {
282267
282475
  if (false)
282268
282476
  ;
282269
- const buildTime = new Date("2026-06-03T14:42:10.545Z").getTime();
282477
+ const buildTime = new Date("2026-06-10T13:40:16.658Z").getTime();
282270
282478
  if (isNaN(buildTime))
282271
282479
  return;
282272
282480
  return Math.floor((Date.now() - buildTime) / 60000);
@@ -286658,7 +286866,7 @@ function getDeferredToolsDeltaAttachment(tools, model, messages, scanContext) {
286658
286866
  function getAgentListingDeltaAttachment(toolUseContext, messages) {
286659
286867
  if (!shouldInjectAgentListInMessages())
286660
286868
  return [];
286661
- if (!toolUseContext.options.tools.some((t) => toolMatchesName2(t, AGENT_TOOL_NAME2))) {
286869
+ if (!toolUseContext.options.tools.some((t) => toolMatchesName2(t, AGENT_TOOL_NAME))) {
286662
286870
  return [];
286663
286871
  }
286664
286872
  const { activeAgents, allowedAgentTypes } = toolUseContext.options.agentDefinitions;
@@ -286669,7 +286877,7 @@ function getAgentListingDeltaAttachment(toolUseContext, messages) {
286669
286877
  mcpServers.add(info.serverName);
286670
286878
  }
286671
286879
  const permissionContext = toolUseContext.getAppState().toolPermissionContext;
286672
- let filtered = filterDeniedAgents(filterAgentsByMcpRequirements(activeAgents, [...mcpServers]), permissionContext, AGENT_TOOL_NAME2);
286880
+ let filtered = filterDeniedAgents(filterAgentsByMcpRequirements(activeAgents, [...mcpServers]), permissionContext, AGENT_TOOL_NAME);
286673
286881
  if (allowedAgentTypes) {
286674
286882
  filtered = filtered.filter((a2) => allowedAgentTypes.includes(a2.agentType));
286675
286883
  }
@@ -288796,6 +289004,7 @@ __export(exports_hooks, {
288796
289004
  executeTaskCreatedHooks: () => executeTaskCreatedHooks,
288797
289005
  executeTaskCompletedHooks: () => executeTaskCompletedHooks,
288798
289006
  executeSubagentStartHooks: () => executeSubagentStartHooks,
289007
+ executeSubagentProgressHooks: () => executeSubagentProgressHooks,
288799
289008
  executeStopHooks: () => executeStopHooks,
288800
289009
  executeStopFailureHooks: () => executeStopFailureHooks,
288801
289010
  executeStatusLineCommand: () => executeStatusLineCommand,
@@ -290856,13 +291065,16 @@ async function executeStopFailureHooks(lastMessage, toolUseContext, timeoutMs =
290856
291065
  matchQuery: error41
290857
291066
  });
290858
291067
  }
290859
- async function* executeStopHooks(permissionMode, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS, stopHookActive = false, subagentId, toolUseContext, messages, agentType, requestPrompt) {
291068
+ async function* executeStopHooks(permissionMode, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS, stopHookActive = false, subagentId, toolUseContext, messages, agentType, requestPrompt, terminal2) {
290860
291069
  const hookEvent = subagentId ? "SubagentStop" : "Stop";
290861
291070
  const appState = toolUseContext?.getAppState();
290862
291071
  const sessionId = toolUseContext?.agentId ?? getSessionId();
290863
291072
  if (!hasHookForEvent(hookEvent, appState, sessionId)) {
290864
291073
  return;
290865
291074
  }
291075
+ if (subagentId) {
291076
+ markSubagentStopFired(subagentId);
291077
+ }
290866
291078
  const lastAssistantMessage = messages ? getLastAssistantMessage(messages) : undefined;
290867
291079
  const lastAssistantText = lastAssistantMessage ? extractTextContent(lastAssistantMessage.message.content, `
290868
291080
  `).trim() || undefined : undefined;
@@ -290873,7 +291085,8 @@ async function* executeStopHooks(permissionMode, signal, timeoutMs = TOOL_HOOK_E
290873
291085
  agent_id: subagentId,
290874
291086
  agent_transcript_path: getAgentTranscriptPath(subagentId),
290875
291087
  agent_type: agentType ?? "",
290876
- last_assistant_message: lastAssistantText
291088
+ last_assistant_message: lastAssistantText,
291089
+ ...terminal2 ? { status: terminal2.status, error_message: terminal2.errorMessage } : {}
290877
291090
  } : {
290878
291091
  ...createBaseHookInput(permissionMode),
290879
291092
  hook_event_name: "Stop",
@@ -290992,12 +291205,14 @@ async function* executeSetupHooks(trigger, signal, timeoutMs = TOOL_HOOK_EXECUTI
290992
291205
  forceSyncExecution
290993
291206
  });
290994
291207
  }
290995
- async function* executeSubagentStartHooks(agentId, agentType, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS) {
291208
+ async function* executeSubagentStartHooks(agentId, agentType, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS, toolUseId, isBackground) {
290996
291209
  const hookInput = {
290997
291210
  ...createBaseHookInput(undefined),
290998
291211
  hook_event_name: "SubagentStart",
290999
291212
  agent_id: agentId,
291000
- agent_type: agentType
291213
+ agent_type: agentType,
291214
+ ...toolUseId !== undefined ? { tool_use_id: toolUseId } : {},
291215
+ ...isBackground !== undefined ? { is_background: isBackground } : {}
291001
291216
  };
291002
291217
  yield* executeHooks({
291003
291218
  hookInput,
@@ -291007,6 +291222,24 @@ async function* executeSubagentStartHooks(agentId, agentType, signal, timeoutMs
291007
291222
  timeoutMs
291008
291223
  });
291009
291224
  }
291225
+ async function executeSubagentProgressHooks(agentId, agentType, messageId, parentToolUseId, blocks, signal) {
291226
+ const hookInput = {
291227
+ ...createBaseHookInput(undefined),
291228
+ hook_event_name: "SubagentProgress",
291229
+ agent_id: agentId,
291230
+ agent_type: agentType,
291231
+ message_id: messageId,
291232
+ ...parentToolUseId !== undefined ? { parent_tool_use_id: parentToolUseId } : {},
291233
+ blocks
291234
+ };
291235
+ for await (const _hookResult of executeHooks({
291236
+ hookInput,
291237
+ toolUseID: randomUUID16(),
291238
+ matchQuery: agentType,
291239
+ signal,
291240
+ timeoutMs: TOOL_HOOK_EXECUTION_TIMEOUT_MS
291241
+ })) {}
291242
+ }
291010
291243
  async function executePreCompactHooks(compactData, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS) {
291011
291244
  const hookInput = {
291012
291245
  ...createBaseHookInput(undefined),
@@ -291646,6 +291879,7 @@ var init_hooks2 = __esm(() => {
291646
291879
  init_envUtils();
291647
291880
  init_errors5();
291648
291881
  init_state2();
291882
+ init_backgroundAbortRegistry();
291649
291883
  TOOL_HOOK_EXECUTION_TIMEOUT_MS = 10 * 60 * 1000;
291650
291884
  });
291651
291885
 
@@ -292012,7 +292246,7 @@ function getAntModelOverrideSection() {
292012
292246
  return null;
292013
292247
  if (isUndercover())
292014
292248
  return null;
292015
- return getAntModelOverrideConfig()?.defaultSystemPromptSuffix || null;
292249
+ return getAntModelOverrideConfig2()?.defaultSystemPromptSuffix || null;
292016
292250
  }
292017
292251
  function getLanguageSection(languagePreference) {
292018
292252
  if (!languagePreference)
@@ -292431,6 +292665,7 @@ var init_prompts2 = __esm(() => {
292431
292665
  init_debug();
292432
292666
  init_memdir();
292433
292667
  init_mcpInstructionsDelta();
292668
+ init_antModels();
292434
292669
  init_state2();
292435
292670
  CLAUDE_4_5_OR_4_6_MODEL_IDS = {
292436
292671
  opus: "claude-opus-4-6",
@@ -292794,7 +293029,7 @@ var init_api3 = __esm(() => {
292794
293029
  init_zodToJsonSchema2();
292795
293030
  SWARM_FIELDS_BY_TOOL = {
292796
293031
  [EXIT_PLAN_MODE_V2_TOOL_NAME]: ["launchSwarm", "teammateCount"],
292797
- [AGENT_TOOL_NAME2]: ["name", "team_name", "mode"]
293032
+ [AGENT_TOOL_NAME]: ["name", "team_name", "mode"]
292798
293033
  };
292799
293034
  });
292800
293035
 
@@ -298112,7 +298347,7 @@ ${attachment.removedNames.join(`
298112
298347
  }
298113
298348
  case "verify_plan_reminder": {
298114
298349
  const toolName = resolveEnvVar("VERIFY_PLAN") === "true" ? "VerifyPlanExecution" : "";
298115
- const content = `You have completed implementing the plan. Please call the "${toolName}" tool directly (NOT the ${AGENT_TOOL_NAME2} tool or an agent) to verify that all plan items were completed correctly.`;
298350
+ const content = `You have completed implementing the plan. Please call the "${toolName}" tool directly (NOT the ${AGENT_TOOL_NAME} tool or an agent) to verify that all plan items were completed correctly.`;
298116
298351
  return wrapMessagesInSystemReminder([
298117
298352
  createUserMessage({ content, isMeta: true })
298118
298353
  ]);
@@ -299393,7 +299628,7 @@ var init_mappers = __esm(() => {
299393
299628
  // src/session/messages/systemInit.ts
299394
299629
  import { randomUUID as randomUUID22 } from "crypto";
299395
299630
  function sdkCompatToolName(name) {
299396
- return name === AGENT_TOOL_NAME3 ? LEGACY_AGENT_TOOL_NAME : name;
299631
+ return name === AGENT_TOOL_NAME2 ? LEGACY_AGENT_TOOL_NAME : name;
299397
299632
  }
299398
299633
  function buildSystemInitMessage(inputs) {
299399
299634
  const settings = getSettings_DEPRECATED();
@@ -299562,7 +299797,8 @@ class QueryEngine {
299562
299797
  theme: resolveThemeSetting(getGlobalConfig().theme),
299563
299798
  maxBudgetUsd,
299564
299799
  maxOutputTokens,
299565
- contextWindow
299800
+ contextWindow,
299801
+ modelProviders: this.config.modelProviders
299566
299802
  },
299567
299803
  getAppState,
299568
299804
  setAppState,
@@ -299664,7 +299900,8 @@ class QueryEngine {
299664
299900
  agentDefinitions: { activeAgents: agents, allAgents: [] },
299665
299901
  maxBudgetUsd,
299666
299902
  maxOutputTokens,
299667
- contextWindow
299903
+ contextWindow,
299904
+ modelProviders: this.config.modelProviders
299668
299905
  },
299669
299906
  getAppState,
299670
299907
  setAppState,
@@ -300159,6 +300396,7 @@ async function* ask({
300159
300396
  appendSystemPrompt,
300160
300397
  userSpecifiedModel,
300161
300398
  fallbackModel,
300399
+ modelProviders,
300162
300400
  jsonSchema,
300163
300401
  getAppState,
300164
300402
  setAppState,
@@ -300186,6 +300424,7 @@ async function* ask({
300186
300424
  appendSystemPrompt,
300187
300425
  userSpecifiedModel,
300188
300426
  fallbackModel,
300427
+ modelProviders,
300189
300428
  thinkingConfig,
300190
300429
  maxTurns,
300191
300430
  maxBudgetUsd,
@@ -328902,6 +329141,8 @@ function registerSdkInlineSkillHandler() {
328902
329141
  }
328903
329142
 
328904
329143
  // src/session/sdkRuntime.ts
329144
+ init_LocalAgentTask();
329145
+ init_backgroundAbortRegistry();
328905
329146
  init_hooks2();
328906
329147
  init_debug();
328907
329148
  init_errors5();
@@ -329211,6 +329452,10 @@ function createQueryLike(generator, runtimeState, onClose) {
329211
329452
  runtimeState.abortController.abort();
329212
329453
  runtimeState.abortController = createAbortController();
329213
329454
  },
329455
+ killAgent(agentId) {
329456
+ abortBackgroundAgentById(agentId);
329457
+ killAsyncAgent(agentId, runtimeState.setAppState);
329458
+ },
329214
329459
  async close() {
329215
329460
  if (runtimeState.closed)
329216
329461
  return;
@@ -329378,6 +329623,9 @@ function runSdkQueryRuntime(params) {
329378
329623
  break;
329379
329624
  }
329380
329625
  runtimeState.runningTurn = true;
329626
+ const { resolveSdkAgents: resolveSdkAgents2 } = (init_builtInAgents(), __toCommonJS(exports_builtInAgents));
329627
+ const hostProvidedAgents = Array.isArray(options2.agents) ? options2.agents : [];
329628
+ const mergedAgents = resolveSdkAgents2(hostProvidedAgents);
329381
329629
  for await (const message of getAsk()({
329382
329630
  commands: allCommands,
329383
329631
  prompt: turn.prompt,
@@ -329403,12 +329651,13 @@ function runSdkQueryRuntime(params) {
329403
329651
  userSpecifiedModel: typeof options2.model === "string" && options2.model.length > 0 ? options2.model : undefined,
329404
329652
  fallbackModel: typeof options2.fallbackModel === "string" && options2.fallbackModel.length > 0 ? options2.fallbackModel : undefined,
329405
329653
  jsonSchema: options2.jsonSchema && typeof options2.jsonSchema === "object" ? options2.jsonSchema : undefined,
329654
+ modelProviders: options2.modelProviders && typeof options2.modelProviders === "object" ? options2.modelProviders : undefined,
329406
329655
  getAppState: appStateStore.getAppState,
329407
329656
  setAppState: appStateStore.setAppState,
329408
329657
  abortController: runtimeState.abortController,
329409
329658
  replayUserMessages: Boolean(options2.replayUserMessages),
329410
329659
  includePartialMessages: Boolean(options2.includePartialMessages),
329411
- agents: Array.isArray(options2.agents) ? options2.agents : [],
329660
+ agents: mergedAgents,
329412
329661
  onToolInvoke: typeof options2.onToolInvoke === "function" ? options2.onToolInvoke : undefined
329413
329662
  })) {
329414
329663
  if (runtimeState.closed)
@@ -329584,6 +329833,7 @@ function createSession(options2) {
329584
329833
 
329585
329834
  // src/client.ts
329586
329835
  init_observer();
329836
+ init_backgroundAbortRegistry();
329587
329837
  init_log2();
329588
329838
  init_log2();
329589
329839
  init_coreTypes();
@@ -331986,6 +332236,7 @@ function getTaskByType(type) {
331986
332236
 
331987
332237
  // src/tasks/stopTask.ts
331988
332238
  init_sdkEventQueue();
332239
+ init_backgroundAbortRegistry();
331989
332240
 
331990
332241
  class StopTaskError extends Error {
331991
332242
  code;
@@ -332000,6 +332251,9 @@ async function stopTask(taskId, context4) {
332000
332251
  const appState = getAppState();
332001
332252
  const task = appState.tasks?.[taskId];
332002
332253
  if (!task) {
332254
+ if (abortBackgroundAgentById(taskId)) {
332255
+ return { taskId, taskType: "local_agent", command: undefined };
332256
+ }
332003
332257
  throw new StopTaskError(`No task found with ID: ${taskId}`, "not_found");
332004
332258
  }
332005
332259
  if (task.status !== "running") {
@@ -332387,7 +332641,7 @@ var ExitPlanModeV2Tool = buildToolRuntime({
332387
332641
  }
332388
332642
  };
332389
332643
  });
332390
- const hasTaskTool = isAgentSwarmsEnabled() && context4.options.tools.some((t) => toolMatchesName(t, AGENT_TOOL_NAME3));
332644
+ const hasTaskTool = isAgentSwarmsEnabled() && context4.options.tools.some((t) => toolMatchesName(t, AGENT_TOOL_NAME2));
332391
332645
  return {
332392
332646
  data: {
332393
332647
  plan,
@@ -333328,7 +333582,7 @@ Task completed. Call TaskList now to find your next available task or see if you
333328
333582
  if (verificationNudgeNeeded) {
333329
333583
  resultContent += `
333330
333584
 
333331
- NOTE: You just closed out 3+ tasks and none of them was a verification step. Before writing your final summary, spawn the verification agent (subagent_type="${VERIFICATION_AGENT_TYPE2}"). You cannot self-assign PARTIAL by listing caveats in your summary — only the verifier issues a verdict.`;
333585
+ NOTE: You just closed out 3+ tasks and none of them was a verification step. Before writing your final summary, spawn the verification agent (subagent_type="${VERIFICATION_AGENT_TYPE}"). You cannot self-assign PARTIAL by listing caveats in your summary — only the verifier issues a verdict.`;
333332
333586
  }
333333
333587
  return {
333334
333588
  tool_use_id: toolUseID,
@@ -335403,6 +335657,7 @@ export {
335403
335657
  query2 as query,
335404
335658
  parseScopes,
335405
335659
  listSessions,
335660
+ abortBackgroundAgentById as killBackgroundAgent,
335406
335661
  isOAuthTokenExpired,
335407
335662
  getSessionMessages2 as getSessionMessages,
335408
335663
  getSessionInfo,
@@ -335447,4 +335702,4 @@ export {
335447
335702
  AbortError2 as AbortError
335448
335703
  };
335449
335704
 
335450
- //# debugId=FBE6B15D8EFBA32B64756E2164756E21
335705
+ //# debugId=2EFAF3B7FC2E44DC64756E2164756E21