// Force strict mode and setup for ESM
"use strict";
import {
  getTeammateContext,
  isTeammate
} from "./chunk-GO6LNQXT.js";
import {
  ToolNames
} from "./chunk-MJKMIQMK.js";
import {
  init_esbuild_shims
} from "./chunk-A4BMJM77.js";
import {
  __name
} from "./chunk-J2S4EL5Y.js";

// packages/core/src/subagents/types.ts
init_esbuild_shims();
var BUBBLE_APPROVAL_MODE = "bubble";
var SubagentError = class extends Error {
  constructor(message, code, subagentName) {
    super(message);
    this.code = code;
    this.subagentName = subagentName;
    this.name = "SubagentError";
  }
  static {
    __name(this, "SubagentError");
  }
};
var SubagentErrorCode = {
  NOT_FOUND: "NOT_FOUND",
  ALREADY_EXISTS: "ALREADY_EXISTS",
  INVALID_CONFIG: "INVALID_CONFIG",
  INVALID_NAME: "INVALID_NAME",
  FILE_ERROR: "FILE_ERROR",
  VALIDATION_ERROR: "VALIDATION_ERROR",
  TOOL_NOT_FOUND: "TOOL_NOT_FOUND"
};

// packages/core/src/tools/agent/fork-subagent.ts
init_esbuild_shims();
import { AsyncLocalStorage } from "node:async_hooks";
var FORK_SUBAGENT_TYPE = "fork";
function isForkSubagentEnabled(config) {
  return config.isInteractive();
}
__name(isForkSubagentEnabled, "isForkSubagentEnabled");
var FORK_BOILERPLATE_TAG = "fork-boilerplate";
var FORK_DIRECTIVE_PREFIX = "Directive: ";
var FORK_AGENT = {
  name: FORK_SUBAGENT_TYPE,
  description: 'Fork yourself \u2014 inherits your full conversation context. Selected explicitly via `subagent_type: "fork"` (only in interactive sessions). Runs detached in the background; you are notified when it completes.',
  tools: ["*"],
  systemPrompt: "You are a forked worker process. Follow the directive in the conversation history. Execute tasks directly using available tools. Do not spawn sub-agents.",
  // `bubble` surfaces this fork's permission prompts to the parent's Background-
  // tasks UI; a detached fork has no inline UI, so 'default' would auto-deny them.
  approvalMode: BUBBLE_APPROVAL_MODE,
  level: "session"
};
var FORK_DEFAULT_MAX_TURNS = 200;
var forkExecutionStorage = new AsyncLocalStorage();
function runInForkContext(fn) {
  return forkExecutionStorage.run({ marker: true }, fn);
}
__name(runInForkContext, "runInForkContext");
function isInForkExecution() {
  return forkExecutionStorage.getStore() !== void 0;
}
__name(isInForkExecution, "isInForkExecution");
var FORK_PLACEHOLDER_RESULT = "Fork started \u2014 processing in background";
function buildFunctionResponseParts(assistantMessage, placeholderOutput) {
  return (assistantMessage.parts?.filter((part) => part.functionCall) ?? []).map((part) => ({
    functionResponse: {
      id: part.functionCall.id,
      name: part.functionCall.name,
      response: { output: placeholderOutput }
    }
  }));
}
__name(buildFunctionResponseParts, "buildFunctionResponseParts");
function buildForkedMessages(directive, assistantMessage) {
  const toolUseParts = assistantMessage.parts?.filter((part) => part.functionCall) || [];
  if (toolUseParts.length === 0) {
    return [];
  }
  const fullAssistantMessage = {
    role: assistantMessage.role,
    parts: [...assistantMessage.parts || []]
  };
  const toolResultParts = buildFunctionResponseParts(
    assistantMessage,
    FORK_PLACEHOLDER_RESULT
  );
  const toolResultMessage = {
    role: "user",
    parts: [
      ...toolResultParts,
      {
        text: buildChildMessage(directive)
      }
    ]
  };
  return [fullAssistantMessage, toolResultMessage];
}
__name(buildForkedMessages, "buildForkedMessages");
function buildWorktreeNotice(parentCwd, worktreeCwd) {
  return `You are operating in an isolated git worktree at ${worktreeCwd}. The parent agent is in ${parentCwd}. Same repository, same relative file layout, separate working copy. All your file edits, writes, and shell commands MUST target paths under ${worktreeCwd}. When the inherited context references a path under ${parentCwd}, translate it to the corresponding path under ${worktreeCwd} before acting on it. Re-read any file you intend to edit (the parent may have modified it after the snapshot in your context). Your changes stay in this worktree and do not affect the parent's working tree.`;
}
__name(buildWorktreeNotice, "buildWorktreeNotice");
function buildChildMessage(directive) {
  return `<${FORK_BOILERPLATE_TAG}>
STOP. READ THIS FIRST.

You are a forked worker process. You are NOT the main agent.

RULES (non-negotiable):
1. You ARE the fork. Do NOT spawn sub-agents; execute directly.
2. Do NOT converse, ask questions, or suggest next steps
3. Do NOT editorialize or add meta-commentary
4. USE your tools directly: Bash, Read, Write, etc.
5. If you modify files, commit your changes before reporting. Include the commit hash in your report.
6. Do NOT emit text between tool calls. Use tools silently, then report once at the end.
7. Stay strictly within your directive's scope. If you discover related systems outside your scope, mention them in one sentence at most \u2014 other workers cover those areas.
8. Keep your report under 500 words unless the directive specifies otherwise. Be factual and concise.
9. Your response MUST begin with "Scope:". No preamble, no thinking-out-loud.
10. REPORT structured facts, then stop

Output format (plain text labels, not markdown headers):
  Scope: <echo back your assigned scope in one sentence>
  Result: <the answer or key findings, limited to the scope above>
  Key files: <relevant file paths \u2014 include for research tasks>
  Files changed: <list with commit hash \u2014 include only if you modified files>
  Issues: <list \u2014 include only if there are issues to flag>
</${FORK_BOILERPLATE_TAG}>

${FORK_DIRECTIVE_PREFIX}${directive}`;
}
__name(buildChildMessage, "buildChildMessage");

// packages/core/src/agents/runtime/agent-context.ts
init_esbuild_shims();
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
var storage = new AsyncLocalStorage2();
function runWithAgentContext(agentId, fn, depthOverride) {
  const current = storage.getStore() ?? {};
  const depth = depthOverride ?? (current.depth ?? -1) + 1;
  return storage.run({ ...current, agentId, depth }, fn);
}
__name(runWithAgentContext, "runWithAgentContext");
function runWithRuntimeContentGenerator(view, fn) {
  const current = storage.getStore() ?? {};
  return storage.run({ ...current, runtimeView: view }, fn);
}
__name(runWithRuntimeContentGenerator, "runWithRuntimeContentGenerator");
function getCurrentAgentId() {
  return storage.getStore()?.agentId ?? null;
}
__name(getCurrentAgentId, "getCurrentAgentId");
function getCurrentAgentDepth() {
  return storage.getStore()?.depth ?? 0;
}
__name(getCurrentAgentDepth, "getCurrentAgentDepth");
function getRuntimeContentGenerator() {
  return storage.getStore()?.runtimeView;
}
__name(getRuntimeContentGenerator, "getRuntimeContentGenerator");
function isTopLevelSession() {
  return getCurrentAgentId() === null;
}
__name(isTopLevelSession, "isTopLevelSession");
function childLaunchDepth() {
  return getCurrentAgentId() !== null ? getCurrentAgentDepth() + 1 : 0;
}
__name(childLaunchDepth, "childLaunchDepth");
function canSpawnNestedAgent(maxDepth) {
  return childLaunchDepth() + 1 <= maxDepth;
}
__name(canSpawnNestedAgent, "canSpawnNestedAgent");
function spawnBlockReason(maxDepth) {
  if (!canSpawnNestedAgent(maxDepth)) return "depth";
  if (isTeammate()) return "teammate";
  if (isInForkExecution()) return "fork";
  return null;
}
__name(spawnBlockReason, "spawnBlockReason");

// packages/core/src/config/approval-mode.ts
init_esbuild_shims();
var ApprovalMode = /* @__PURE__ */ ((ApprovalMode2) => {
  ApprovalMode2["PLAN"] = "plan";
  ApprovalMode2["DEFAULT"] = "default";
  ApprovalMode2["AUTO_EDIT"] = "auto-edit";
  ApprovalMode2["AUTO"] = "auto";
  ApprovalMode2["YOLO"] = "yolo";
  return ApprovalMode2;
})(ApprovalMode || {});
var APPROVAL_MODES = Object.values(ApprovalMode);

// packages/core/src/agents/runtime/subagent-plan-tool-policy.ts
init_esbuild_shims();
var SUBAGENT_PLAN_LIFECYCLE_TOOLS = /* @__PURE__ */ new Set([
  ToolNames.ENTER_PLAN_MODE,
  ToolNames.EXIT_PLAN_MODE
]);
var PLAN_REQUIRED_TEAMMATE_PRE_APPROVAL_TOOLS = /* @__PURE__ */ new Set([
  ToolNames.EXIT_PLAN_MODE,
  ToolNames.READ_FILE,
  ToolNames.GREP,
  ToolNames.GLOB,
  ToolNames.LS,
  ToolNames.LSP,
  ToolNames.TASK_LIST,
  ToolNames.TOOL_SEARCH,
  ToolNames.READ_MCP_RESOURCE
]);
var PRE_APPROVAL_TASK_CLAIM_KEYS = /* @__PURE__ */ new Set([
  "taskId",
  "status",
  "owner",
  "addBlocks",
  "addBlockedBy"
]);
function isSubagentLikeExecutionContext() {
  return getCurrentAgentId() !== null || isTeammate();
}
__name(isSubagentLikeExecutionContext, "isSubagentLikeExecutionContext");
function isPlanRequiredTeammateContext() {
  return getTeammateContext()?.planModeRequired === true;
}
__name(isPlanRequiredTeammateContext, "isPlanRequiredTeammateContext");
function isPlanRequiredTeammateAwaitingApproval(config) {
  return isPlanRequiredTeammateContext() && config.getApprovalMode() === "plan" /* PLAN */;
}
__name(isPlanRequiredTeammateAwaitingApproval, "isPlanRequiredTeammateAwaitingApproval");
function isPlanLifecycleToolUnavailableInSubagent(toolName) {
  if (!isSubagentLikeExecutionContext()) return false;
  if (toolName === ToolNames.ENTER_PLAN_MODE) return true;
  if (toolName === ToolNames.EXIT_PLAN_MODE) {
    return !isPlanRequiredTeammateContext();
  }
  return false;
}
__name(isPlanLifecycleToolUnavailableInSubagent, "isPlanLifecycleToolUnavailableInSubagent");
function shouldUsePlanOnlyReminderInSubagentContext() {
  return isSubagentLikeExecutionContext() && !isPlanRequiredTeammateContext();
}
__name(shouldUsePlanOnlyReminderInSubagentContext, "shouldUsePlanOnlyReminderInSubagentContext");
function isLeaderOnlyToolUnavailableInSubagent(toolName) {
  return isSubagentLikeExecutionContext() && toolName === ToolNames.TEAM_PLAN_APPROVAL;
}
__name(isLeaderOnlyToolUnavailableInSubagent, "isLeaderOnlyToolUnavailableInSubagent");
function getLeaderOnlyToolUnavailableMessage(toolName) {
  return `${toolName} is only available to the team leader. Subagents and teammates cannot approve teammate plans.`;
}
__name(getLeaderOnlyToolUnavailableMessage, "getLeaderOnlyToolUnavailableMessage");
function getPlanRequiredTeammatePreApprovalMessage(toolName) {
  return `${toolName} is not available while this plan-required teammate is waiting for leader approval. Finish investigation, call exit_plan_mode with the proposed plan, and wait for the leader to approve it before taking execution actions.`;
}
__name(getPlanRequiredTeammatePreApprovalMessage, "getPlanRequiredTeammatePreApprovalMessage");
function isPlanRequiredTeammatePreApprovalAllowedTool(toolName, params) {
  if (PLAN_REQUIRED_TEAMMATE_PRE_APPROVAL_TOOLS.has(toolName)) {
    return true;
  }
  if (toolName !== ToolNames.TASK_UPDATE) {
    return false;
  }
  return isPreApprovalClaimOnlyTaskUpdate(params);
}
__name(isPlanRequiredTeammatePreApprovalAllowedTool, "isPlanRequiredTeammatePreApprovalAllowedTool");
function isPreApprovalClaimOnlyTaskUpdate(params) {
  if (typeof params !== "object" || params === null || Array.isArray(params)) {
    return false;
  }
  const taskParams = params;
  for (const key of Object.keys(taskParams)) {
    if (!PRE_APPROVAL_TASK_CLAIM_KEYS.has(key)) {
      return false;
    }
  }
  const agentName = getTeammateContext()?.agentName;
  return typeof taskParams["taskId"] === "string" && taskParams["status"] === "in_progress" && (taskParams["owner"] === void 0 || taskParams["owner"] === agentName) && isAbsentOrEmptyArray(taskParams["addBlocks"]) && isAbsentOrEmptyArray(taskParams["addBlockedBy"]);
}
__name(isPreApprovalClaimOnlyTaskUpdate, "isPreApprovalClaimOnlyTaskUpdate");
function isAbsentOrEmptyArray(value) {
  return value === void 0 || Array.isArray(value) && value.length === 0;
}
__name(isAbsentOrEmptyArray, "isAbsentOrEmptyArray");
function getSubagentPlanToolUnavailableMessage(toolName) {
  return `${toolName} is not available inside subagents or team agents. Plan mode is owned by the caller/main session; return your plan, findings, or constraints to the caller in your normal response instead of entering or exiting plan mode.`;
}
__name(getSubagentPlanToolUnavailableMessage, "getSubagentPlanToolUnavailableMessage");
function buildSubagentPlanToolBlockedResult(toolName, logTag, logger) {
  const message = getSubagentPlanToolUnavailableMessage(toolName);
  logger.warn(
    `[${logTag}] Blocked plan lifecycle tool call from subagent: ${toolName}`
  );
  return {
    llmContent: message,
    returnDisplay: message,
    error: { message }
  };
}
__name(buildSubagentPlanToolBlockedResult, "buildSubagentPlanToolBlockedResult");

export {
  BUBBLE_APPROVAL_MODE,
  SubagentError,
  SubagentErrorCode,
  FORK_SUBAGENT_TYPE,
  isForkSubagentEnabled,
  FORK_AGENT,
  FORK_DEFAULT_MAX_TURNS,
  runInForkContext,
  FORK_PLACEHOLDER_RESULT,
  buildFunctionResponseParts,
  buildForkedMessages,
  buildWorktreeNotice,
  buildChildMessage,
  runWithAgentContext,
  runWithRuntimeContentGenerator,
  getCurrentAgentId,
  getCurrentAgentDepth,
  getRuntimeContentGenerator,
  isTopLevelSession,
  childLaunchDepth,
  spawnBlockReason,
  ApprovalMode,
  APPROVAL_MODES,
  SUBAGENT_PLAN_LIFECYCLE_TOOLS,
  isSubagentLikeExecutionContext,
  isPlanRequiredTeammateContext,
  isPlanRequiredTeammateAwaitingApproval,
  isPlanLifecycleToolUnavailableInSubagent,
  shouldUsePlanOnlyReminderInSubagentContext,
  isLeaderOnlyToolUnavailableInSubagent,
  getLeaderOnlyToolUnavailableMessage,
  getPlanRequiredTeammatePreApprovalMessage,
  isPlanRequiredTeammatePreApprovalAllowedTool,
  getSubagentPlanToolUnavailableMessage,
  buildSubagentPlanToolBlockedResult
};
/**
 * @license
 * Copyright 2025 Qwen
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
