@rdmind/rdmind 0.1.3-alpha.2 → 0.1.3-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/cli.js +848 -438
  2. package/locales/zh.js +1 -1
  3. package/package.json +2 -2
package/cli.js CHANGED
@@ -89829,7 +89829,7 @@ var init_mcp_tool = __esm({
89829
89829
  // Display original tool name in confirmation
89830
89830
  toolDisplayName: this.displayName,
89831
89831
  // Display global registry name exposed to model and user
89832
- onConfirm: /* @__PURE__ */ __name(async (outcome) => {
89832
+ onConfirm: /* @__PURE__ */ __name(async (outcome, _payload) => {
89833
89833
  if (outcome === "proceed_always_server" /* ProceedAlwaysServer */) {
89834
89834
  _DiscoveredMCPToolInvocation.allowlist.add(serverAllowListKey);
89835
89835
  } else if (outcome === "proceed_always_tool" /* ProceedAlwaysTool */) {
@@ -160739,7 +160739,7 @@ function createContentGeneratorConfig(config2, authType, generationConfig) {
160739
160739
  };
160740
160740
  }
160741
160741
  async function createContentGenerator(config2, gcConfig, isInitialAuth) {
160742
- const version3 = "0.1.3-alpha.2";
160742
+ const version3 = "0.1.3-alpha.3";
160743
160743
  const userAgent2 = `QwenCode/${version3} (${process.platform}; ${process.arch})`;
160744
160744
  const baseHeaders = {
160745
160745
  "User-Agent": userAgent2
@@ -164752,11 +164752,11 @@ function getToolCallExamples(model) {
164752
164752
  function getSubagentSystemReminder(agentTypes) {
164753
164753
  return `<system-reminder>You have powerful specialized agents at your disposal, available agent types are: ${agentTypes.join(", ")}. PROACTIVELY use the ${ToolNames.TASK} tool to delegate user's task to appropriate agent when user's task matches agent capabilities. Ignore this message if user's task is not relevant to any agent. This message is for internal use only. Do not mention this to user in your response.</system-reminder>`;
164754
164754
  }
164755
- function getPlanModeSystemReminder() {
164755
+ function getPlanModeSystemReminder(planOnly = false) {
164756
164756
  return `<system-reminder>
164757
164757
  Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supercedes any other instructions you have received (for example, to make edits). Instead, you should:
164758
164758
  1. Answer the user's query comprehensively
164759
- 2. When you're done researching, present your plan by calling the ${ToolNames.EXIT_PLAN_MODE} tool, which will prompt the user to confirm the plan. Do NOT make any file changes or run any tools that modify the system state in any way until the user has confirmed the plan.
164759
+ 2. When you're done researching, present your plan ${planOnly ? "directly" : `by calling the ${ToolNames.EXIT_PLAN_MODE} tool, which will prompt the user to confirm the plan`}. Do NOT make any file changes or run any tools that modify the system state in any way until the user has confirmed the plan.
164760
164760
  </system-reminder>`;
164761
164761
  }
164762
164762
  var generalToolCallExamples, qwenCoderToolCallExamples, qwenVlToolCallExamples;
@@ -178051,7 +178051,7 @@ var init_shell = __esm({
178051
178051
  title: "Confirm Shell Command",
178052
178052
  command: this.params.command,
178053
178053
  rootCommand: commandsToConfirm.join(", "),
178054
- onConfirm: /* @__PURE__ */ __name(async (outcome) => {
178054
+ onConfirm: /* @__PURE__ */ __name(async (outcome, _payload) => {
178055
178055
  if (outcome === "proceed_always" /* ProceedAlways */) {
178056
178056
  commandsToConfirm.forEach((command3) => this.allowlist.add(command3));
178057
178057
  }
@@ -178848,7 +178848,7 @@ var init_coreToolScheduler = __esm({
178848
178848
  );
178849
178849
  this.setStatusInternal(reqInfo.callId, "scheduled");
178850
178850
  } else {
178851
- const shouldAutoDeny = !this.config.isInteractive() && !this.config.getIdeMode() && !this.config.getExperimentalZedIntegration();
178851
+ const shouldAutoDeny = !this.config.isInteractive() && !this.config.getIdeMode() && !this.config.getExperimentalZedIntegration() && this.config.getInputFormat() !== "stream-json" /* STREAM_JSON */;
178852
178852
  if (shouldAutoDeny) {
178853
178853
  const errorMessage = `RDMind requires permission to use "${reqInfo.name}", but that permission was declined.`;
178854
178854
  this.setStatusInternal(
@@ -178928,19 +178928,14 @@ var init_coreToolScheduler = __esm({
178928
178928
  const toolCall = this.toolCalls.find(
178929
178929
  (c3) => c3.request.callId === callId && c3.status === "awaiting_approval"
178930
178930
  );
178931
- if (toolCall && toolCall.status === "awaiting_approval") {
178932
- await originalOnConfirm(outcome);
178933
- }
178931
+ await originalOnConfirm(outcome, payload);
178934
178932
  if (outcome === "proceed_always" /* ProceedAlways */) {
178935
178933
  await this.autoApproveCompatiblePendingTools(signal, callId);
178936
178934
  }
178937
178935
  this.setToolCallOutcome(callId, outcome);
178938
178936
  if (outcome === "cancel" /* Cancel */ || signal.aborted) {
178939
- this.setStatusInternal(
178940
- callId,
178941
- "cancelled",
178942
- "User did not allow tool call"
178943
- );
178937
+ const cancelMessage = payload?.cancelMessage || "User did not allow tool call";
178938
+ this.setStatusInternal(callId, "cancelled", cancelMessage);
178944
178939
  } else if (outcome === "modify_with_editor" /* ModifyWithEditor */) {
178945
178940
  const waitingToolCall = toolCall;
178946
178941
  if (isModifiableDeclarativeTool(waitingToolCall.tool)) {
@@ -178986,7 +178981,7 @@ var init_coreToolScheduler = __esm({
178986
178981
  * @private
178987
178982
  */
178988
178983
  async _applyInlineModify(toolCall, payload, signal) {
178989
- if (toolCall.confirmationDetails.type !== "edit" || !isModifiableDeclarativeTool(toolCall.tool)) {
178984
+ if (toolCall.confirmationDetails.type !== "edit" || !isModifiableDeclarativeTool(toolCall.tool) || !payload.newContent) {
178990
178985
  return;
178991
178986
  }
178992
178987
  const modifyContext = toolCall.tool.getModifyContext(signal);
@@ -185714,7 +185709,9 @@ var init_client2 = __esm({
185714
185709
  systemReminders.push(getSubagentSystemReminder(subagents));
185715
185710
  }
185716
185711
  if (this.config.getApprovalMode() === "plan" /* PLAN */) {
185717
- systemReminders.push(getPlanModeSystemReminder());
185712
+ systemReminders.push(
185713
+ getPlanModeSystemReminder(this.config.getSdkMode())
185714
+ );
185718
185715
  }
185719
185716
  requestToSent = [...systemReminders, ...requestToSent];
185720
185717
  }
@@ -224711,6 +224708,13 @@ var init_subagent_manager = __esm({
224711
224708
  */
224712
224709
  async createSubagent(config2, options2) {
224713
224710
  this.validator.validateOrThrow(config2);
224711
+ if (options2.level === "session") {
224712
+ throw new SubagentError(
224713
+ `Cannot create session-level subagent "${config2.name}". Session agents are read-only and provided at runtime.`,
224714
+ SubagentErrorCode.INVALID_CONFIG,
224715
+ config2.name
224716
+ );
224717
+ }
224714
224718
  const filePath = options2.customPath || this.getSubagentPath(config2.name, options2.level);
224715
224719
  if (!options2.overwrite) {
224716
224720
  try {
@@ -224757,8 +224761,17 @@ var init_subagent_manager = __esm({
224757
224761
  if (level === "builtin") {
224758
224762
  return BuiltinAgentRegistry.getBuiltinAgent(name3);
224759
224763
  }
224764
+ if (level === "session") {
224765
+ const sessionSubagents2 = this.subagentsCache?.get("session") || [];
224766
+ return sessionSubagents2.find((agent) => agent.name === name3) || null;
224767
+ }
224760
224768
  return this.findSubagentByNameAtLevel(name3, level);
224761
224769
  }
224770
+ const sessionSubagents = this.subagentsCache?.get("session") || [];
224771
+ const sessionConfig = sessionSubagents.find((agent) => agent.name === name3);
224772
+ if (sessionConfig) {
224773
+ return sessionConfig;
224774
+ }
224762
224775
  const projectConfig = await this.findSubagentByNameAtLevel(name3, "project");
224763
224776
  if (projectConfig) {
224764
224777
  return projectConfig;
@@ -224792,8 +224805,22 @@ var init_subagent_manager = __esm({
224792
224805
  name3
224793
224806
  );
224794
224807
  }
224808
+ if (existing.level === "session") {
224809
+ throw new SubagentError(
224810
+ `Cannot update session-level subagent "${name3}"`,
224811
+ SubagentErrorCode.INVALID_CONFIG,
224812
+ name3
224813
+ );
224814
+ }
224795
224815
  const updatedConfig = this.mergeConfigurations(existing, updates);
224796
224816
  this.validator.validateOrThrow(updatedConfig);
224817
+ if (!existing.filePath) {
224818
+ throw new SubagentError(
224819
+ `Cannot update subagent "${name3}": no file path available`,
224820
+ SubagentErrorCode.FILE_ERROR,
224821
+ name3
224822
+ );
224823
+ }
224797
224824
  const content = this.serializeSubagent(updatedConfig);
224798
224825
  try {
224799
224826
  await fs47.writeFile(existing.filePath, content, "utf8");
@@ -224824,7 +224851,7 @@ var init_subagent_manager = __esm({
224824
224851
  const levelsToCheck = level ? [level] : ["project", "user"];
224825
224852
  let deleted = false;
224826
224853
  for (const currentLevel of levelsToCheck) {
224827
- if (currentLevel === "builtin") {
224854
+ if (currentLevel === "builtin" || currentLevel === "session") {
224828
224855
  continue;
224829
224856
  }
224830
224857
  const config2 = await this.findSubagentByNameAtLevel(name3, currentLevel);
@@ -224854,6 +224881,20 @@ var init_subagent_manager = __esm({
224854
224881
  async listSubagents(options2 = {}) {
224855
224882
  const subagents = [];
224856
224883
  const seenNames = /* @__PURE__ */ new Set();
224884
+ if (this.config.getSdkMode()) {
224885
+ const levelsToCheck2 = options2.level ? [options2.level] : ["session"];
224886
+ for (const level of levelsToCheck2) {
224887
+ const levelSubagents = this.subagentsCache?.get(level) || [];
224888
+ for (const subagent of levelSubagents) {
224889
+ if (options2.hasTool && (!subagent.tools || !subagent.tools.includes(options2.hasTool))) {
224890
+ continue;
224891
+ }
224892
+ subagents.push(subagent);
224893
+ seenNames.add(subagent.name);
224894
+ }
224895
+ }
224896
+ return subagents;
224897
+ }
224857
224898
  const levelsToCheck = options2.level ? [options2.level] : ["project", "user", "builtin"];
224858
224899
  const shouldUseCache = !options2.force && this.subagentsCache !== null;
224859
224900
  if (!shouldUseCache) {
@@ -224880,7 +224921,7 @@ var init_subagent_manager = __esm({
224880
224921
  comparison = a.name.localeCompare(b.name);
224881
224922
  break;
224882
224923
  case "level": {
224883
- const levelOrder = { project: 0, user: 1, builtin: 2 };
224924
+ const levelOrder = { project: 0, user: 1, builtin: 2, session: 3 };
224884
224925
  comparison = levelOrder[a.level] - levelOrder[b.level];
224885
224926
  break;
224886
224927
  }
@@ -224893,6 +224934,24 @@ var init_subagent_manager = __esm({
224893
224934
  }
224894
224935
  return subagents;
224895
224936
  }
224937
+ /**
224938
+ * Loads session-level subagents into the cache.
224939
+ * Session subagents are provided directly via config and are read-only.
224940
+ *
224941
+ * @param subagents - Array of session subagent configurations
224942
+ */
224943
+ loadSessionSubagents(subagents) {
224944
+ if (!this.subagentsCache) {
224945
+ this.subagentsCache = /* @__PURE__ */ new Map();
224946
+ }
224947
+ const sessionSubagents = subagents.map((config2) => ({
224948
+ ...config2,
224949
+ level: "session",
224950
+ filePath: `<session:${config2.name}>`
224951
+ }));
224952
+ this.subagentsCache.set("session", sessionSubagents);
224953
+ this.notifyChangeListeners();
224954
+ }
224896
224955
  /**
224897
224956
  * Refreshes the subagents cache by loading all subagents from disk.
224898
224957
  * This method is called automatically when cache is null or when force=true.
@@ -225157,6 +225216,9 @@ ${config2.systemPrompt}
225157
225216
  if (level === "builtin") {
225158
225217
  return `<builtin:${name3}>`;
225159
225218
  }
225219
+ if (level === "session") {
225220
+ return `<session:${name3}>`;
225221
+ }
225160
225222
  const baseDir = level === "project" ? path52.join(
225161
225223
  this.config.getProjectRoot(),
225162
225224
  QWEN_CONFIG_DIR2,
@@ -225642,7 +225704,9 @@ var init_config3 = __esm({
225642
225704
  toolCallCommand;
225643
225705
  mcpServerCommand;
225644
225706
  mcpServers;
225707
+ sessionSubagents;
225645
225708
  userMemory;
225709
+ sdkMode;
225646
225710
  geminiMdFileCount;
225647
225711
  approvalMode;
225648
225712
  showMemoryUsage;
@@ -225726,6 +225790,8 @@ var init_config3 = __esm({
225726
225790
  this.toolCallCommand = params.toolCallCommand;
225727
225791
  this.mcpServerCommand = params.mcpServerCommand;
225728
225792
  this.mcpServers = params.mcpServers;
225793
+ this.sessionSubagents = params.sessionSubagents ?? [];
225794
+ this.sdkMode = params.sdkMode ?? false;
225729
225795
  this.userMemory = params.userMemory ?? "";
225730
225796
  this.geminiMdFileCount = params.geminiMdFileCount ?? 0;
225731
225797
  this.approvalMode = params.approvalMode ?? "default" /* DEFAULT */;
@@ -225785,7 +225851,7 @@ var init_config3 = __esm({
225785
225851
  this.webSearch = params.webSearch;
225786
225852
  this.useRipgrep = params.useRipgrep ?? true;
225787
225853
  this.useBuiltinRipgrep = params.useBuiltinRipgrep ?? true;
225788
- this.shouldUseNodePtyShell = params.shouldUseNodePtyShell ?? false;
225854
+ this.shouldUseNodePtyShell = params.shouldUseNodePtyShell ?? true;
225789
225855
  this.skipNextSpeakerCheck = params.skipNextSpeakerCheck ?? true;
225790
225856
  this.shellExecutionConfig = {
225791
225857
  terminalWidth: params.shellExecutionConfig?.terminalWidth ?? 80,
@@ -225829,6 +225895,9 @@ var init_config3 = __esm({
225829
225895
  }
225830
225896
  this.promptRegistry = new PromptRegistry();
225831
225897
  this.subagentManager = new SubagentManager(this);
225898
+ if (this.sessionSubagents.length > 0) {
225899
+ this.subagentManager.loadSessionSubagents(this.sessionSubagents);
225900
+ }
225832
225901
  this.toolRegistry = await this.createToolRegistry();
225833
225902
  await this.geminiClient.initialize();
225834
225903
  logStartSession(this, new StartSessionEvent(this));
@@ -225999,6 +226068,27 @@ var init_config3 = __esm({
225999
226068
  getMcpServers() {
226000
226069
  return this.mcpServers;
226001
226070
  }
226071
+ addMcpServers(servers) {
226072
+ if (this.initialized) {
226073
+ throw new Error("Cannot modify mcpServers after initialization");
226074
+ }
226075
+ this.mcpServers = { ...this.mcpServers, ...servers };
226076
+ }
226077
+ getSessionSubagents() {
226078
+ return this.sessionSubagents;
226079
+ }
226080
+ setSessionSubagents(subagents) {
226081
+ if (this.initialized) {
226082
+ throw new Error("Cannot modify sessionSubagents after initialization");
226083
+ }
226084
+ this.sessionSubagents = subagents;
226085
+ }
226086
+ getSdkMode() {
226087
+ return this.sdkMode;
226088
+ }
226089
+ setSdkMode(value) {
226090
+ this.sdkMode = value;
226091
+ }
226002
226092
  getUserMemory() {
226003
226093
  return this.userMemory;
226004
226094
  }
@@ -226341,7 +226431,7 @@ var init_config3 = __esm({
226341
226431
  registerCoreTool(ShellTool, this);
226342
226432
  registerCoreTool(MemoryTool);
226343
226433
  registerCoreTool(TodoWriteTool, this);
226344
- registerCoreTool(ExitPlanModeTool, this);
226434
+ !this.sdkMode && registerCoreTool(ExitPlanModeTool, this);
226345
226435
  registerCoreTool(WebFetchTool, this);
226346
226436
  registerCoreTool(ReadKnowledgeExtTool);
226347
226437
  registerCoreTool(ListKnowledgeExtTool);
@@ -235608,8 +235698,8 @@ var init_git_commit = __esm({
235608
235698
  "packages/core/src/generated/git-commit.ts"() {
235609
235699
  "use strict";
235610
235700
  init_esbuild_shims();
235611
- GIT_COMMIT_INFO = "88408513";
235612
- CLI_VERSION = "0.1.3-alpha.2";
235701
+ GIT_COMMIT_INFO = "398f69c0";
235702
+ CLI_VERSION = "0.1.3-alpha.3";
235613
235703
  }
235614
235704
  });
235615
235705
 
@@ -276143,8 +276233,8 @@ var init_settingsSchema = __esm({
276143
276233
  label: "Enable Interactive Shell",
276144
276234
  category: "Tools",
276145
276235
  requiresRestart: true,
276146
- default: false,
276147
- description: "Use node-pty for an interactive shell experience. Fallback to child_process still applies.",
276236
+ default: true,
276237
+ description: "Use node-pty for an interactive shell experience. Allows input to interactive commands (e.g., sudo password prompts). Fallback to child_process still applies.",
276148
276238
  showInDialog: true
276149
276239
  },
276150
276240
  pager: {
@@ -307471,7 +307561,7 @@ var init_zh = __esm({
307471
307561
  'Theme "{{themeName}}" not found.': '\u672A\u627E\u5230\u4E3B\u9898 "{{themeName}}"\u3002',
307472
307562
  'Theme "{{themeName}}" not found in selected scope.': '\u5728\u6240\u9009\u4F5C\u7528\u57DF\u4E2D\u672A\u627E\u5230\u4E3B\u9898 "{{themeName}}"\u3002',
307473
307563
  "clear the screen and conversation history": "\u6E05\u5C4F\u5E76\u6E05\u9664\u5BF9\u8BDD\u5386\u53F2",
307474
- "Clear conversation history and free up context": "\u6E05\u9664\u5BF9\u8BDD\u5386\u53F2\u5E76\u91CA\u653E\u4E0A\u4E0B\u6587",
307564
+ "Clear conversation history and free up context": "\u6E05\u9664\u5BF9\u8BDD\u5386\u53F2",
307475
307565
  "Compresses the context by replacing it with a summary.": "\u901A\u8FC7\u7528\u6458\u8981\u66FF\u6362\u6765\u538B\u7F29\u4E0A\u4E0B\u6587",
307476
307566
  "open full RDMind documentation in your browser": "\u5728\u6D4F\u89C8\u5668\u4E2D\u6253\u5F00\u5B8C\u6574\u7684 RDMind \u6587\u6863",
307477
307567
  "Configuration not available.": "\u914D\u7F6E\u4E0D\u53EF\u7528",
@@ -346095,7 +346185,7 @@ __name(getPackageJson, "getPackageJson");
346095
346185
  // packages/cli/src/utils/version.ts
346096
346186
  async function getCliVersion() {
346097
346187
  const pkgJson = await getPackageJson();
346098
- return "0.1.3-alpha.2";
346188
+ return "0.1.3-alpha.3";
346099
346189
  }
346100
346190
  __name(getCliVersion, "getCliVersion");
346101
346191
 
@@ -349092,6 +349182,28 @@ async function parseArguments(settings) {
349092
349182
  }).option("resume", {
349093
349183
  type: "string",
349094
349184
  description: "Resume a specific session by its ID. Use without an ID to show session picker."
349185
+ }).option("max-session-turns", {
349186
+ type: "number",
349187
+ description: "Maximum number of session turns"
349188
+ }).option("core-tools", {
349189
+ type: "array",
349190
+ string: true,
349191
+ description: "Core tool paths",
349192
+ coerce: /* @__PURE__ */ __name((tools) => tools.flatMap((tool) => tool.split(",").map((t4) => t4.trim())), "coerce")
349193
+ }).option("exclude-tools", {
349194
+ type: "array",
349195
+ string: true,
349196
+ description: "Tools to exclude",
349197
+ coerce: /* @__PURE__ */ __name((tools) => tools.flatMap((tool) => tool.split(",").map((t4) => t4.trim())), "coerce")
349198
+ }).option("allowed-tools", {
349199
+ type: "array",
349200
+ string: true,
349201
+ description: "Tools to allow, will bypass confirmation",
349202
+ coerce: /* @__PURE__ */ __name((tools) => tools.flatMap((tool) => tool.split(",").map((t4) => t4.trim())), "coerce")
349203
+ }).option("auth-type", {
349204
+ type: "string",
349205
+ choices: ["openai" /* USE_OPENAI */, "qwen-oauth" /* QWEN_OAUTH */],
349206
+ description: "Authentication type"
349095
349207
  }).deprecateOption(
349096
349208
  "show-memory-usage",
349097
349209
  'Use the "ui.showMemoryUsage" setting in settings.json instead. This flag will be removed in a future version.'
@@ -349292,7 +349404,7 @@ async function loadCliConfig(settings, extensions, extensionEnablementManager, a
349292
349404
  interactive = false;
349293
349405
  }
349294
349406
  const extraExcludes = [];
349295
- if (!interactive && !argv.experimentalAcp) {
349407
+ if (!interactive && !argv.experimentalAcp && inputFormat !== "stream-json" /* STREAM_JSON */) {
349296
349408
  switch (approvalMode) {
349297
349409
  case "plan" /* PLAN */:
349298
349410
  case "default" /* DEFAULT */:
@@ -349310,7 +349422,8 @@ async function loadCliConfig(settings, extensions, extensionEnablementManager, a
349310
349422
  const excludeTools = mergeExcludeTools(
349311
349423
  settings,
349312
349424
  activeExtensions,
349313
- extraExcludes.length > 0 ? extraExcludes : void 0
349425
+ extraExcludes.length > 0 ? extraExcludes : void 0,
349426
+ argv.excludeTools
349314
349427
  );
349315
349428
  const blockedMcpServers = [];
349316
349429
  if (!argv.allowedMcpServerNames) {
@@ -349373,7 +349486,7 @@ async function loadCliConfig(settings, extensions, extensionEnablementManager, a
349373
349486
  debugMode,
349374
349487
  question,
349375
349488
  fullContext: argv.allFiles || false,
349376
- coreTools: settings.tools?.core || void 0,
349489
+ coreTools: argv.coreTools || settings.tools?.core || void 0,
349377
349490
  allowedTools: argv.allowedTools || settings.tools?.allowed || void 0,
349378
349491
  excludeTools,
349379
349492
  toolDiscoveryCommand: settings.tools?.discoveryCommand,
@@ -349399,13 +349512,13 @@ async function loadCliConfig(settings, extensions, extensionEnablementManager, a
349399
349512
  model: resolvedModel,
349400
349513
  extensionContextFilePaths,
349401
349514
  sessionTokenLimit: settings.model?.sessionTokenLimit ?? -1,
349402
- maxSessionTurns: settings.model?.maxSessionTurns ?? -1,
349515
+ maxSessionTurns: argv.maxSessionTurns ?? settings.model?.maxSessionTurns ?? -1,
349403
349516
  experimentalZedIntegration: argv.experimentalAcp || false,
349404
349517
  listExtensions: argv.listExtensions || false,
349405
349518
  extensions: allExtensions,
349406
349519
  blockedMcpServers,
349407
349520
  noBrowser: !!process.env["NO_BROWSER"],
349408
- authType: settings.security?.auth?.selectedType,
349521
+ authType: argv.authType || settings.security?.auth?.selectedType,
349409
349522
  inputFormat,
349410
349523
  outputFormat,
349411
349524
  includePartialMessages,
@@ -349501,8 +349614,9 @@ function mergeMcpServers(settings, extensions) {
349501
349614
  return mcpServers;
349502
349615
  }
349503
349616
  __name(mergeMcpServers, "mergeMcpServers");
349504
- function mergeExcludeTools(settings, extensions, extraExcludes) {
349617
+ function mergeExcludeTools(settings, extensions, extraExcludes, cliExcludeTools) {
349505
349618
  const allExcludeTools = /* @__PURE__ */ new Set([
349619
+ ...cliExcludeTools || [],
349506
349620
  ...settings.tools?.exclude || [],
349507
349621
  ...extraExcludes || []
349508
349622
  ]);
@@ -352438,7 +352552,7 @@ var formatDuration = /* @__PURE__ */ __name((milliseconds) => {
352438
352552
 
352439
352553
  // packages/cli/src/generated/git-commit.ts
352440
352554
  init_esbuild_shims();
352441
- var GIT_COMMIT_INFO2 = "88408513";
352555
+ var GIT_COMMIT_INFO2 = "398f69c0";
352442
352556
 
352443
352557
  // packages/cli/src/utils/systemInfo.ts
352444
352558
  async function getNpmVersion() {
@@ -359172,7 +359286,7 @@ async function buildSystemMessage(config2, sessionId, permissionMode) {
359172
359286
  tools,
359173
359287
  mcp_servers: mcpServerList,
359174
359288
  model: config2.getModel(),
359175
- permissionMode,
359289
+ permission_mode: permissionMode,
359176
359290
  slash_commands: slashCommands,
359177
359291
  qwen_code_version: config2.getCliVersion() || "unknown",
359178
359292
  agents: agentNames
@@ -359678,6 +359792,16 @@ ${event.value}`, null);
359678
359792
  }
359679
359793
  this.finalizePendingBlocks(state, null);
359680
359794
  break;
359795
+ case "error" /* Error */: {
359796
+ const errorText = parseAndFormatApiError(
359797
+ event.value.error,
359798
+ this.config.getContentGeneratorConfig()?.authType,
359799
+ void 0,
359800
+ this.config.getModel()
359801
+ );
359802
+ this.appendText(state, errorText, null);
359803
+ break;
359804
+ }
359681
359805
  default:
359682
359806
  break;
359683
359807
  }
@@ -359934,14 +360058,30 @@ ${event.value}`, null);
359934
360058
  };
359935
360059
  this.emitMessageImpl(message);
359936
360060
  }
360061
+ /**
360062
+ * Checks if responseParts contain any functionResponse with an error.
360063
+ * This handles cancelled responses and other error cases where the error
360064
+ * is embedded in responseParts rather than the top-level error field.
360065
+ * @param responseParts - Array of Part objects
360066
+ * @returns Error message if found, undefined otherwise
360067
+ */
360068
+ checkResponsePartsForError(responseParts) {
360069
+ return checkResponsePartsForError(responseParts);
360070
+ }
359937
360071
  /**
359938
360072
  * Emits a tool result message.
359939
360073
  * Collects execution denied tool calls for inclusion in result messages.
360074
+ * Handles both explicit errors (response.error) and errors embedded in
360075
+ * responseParts (e.g., cancelled responses).
359940
360076
  * @param request - Tool call request info
359941
360077
  * @param response - Tool call response info
359942
360078
  * @param parentToolUseId - Parent tool use ID (null for main agent)
359943
360079
  */
359944
360080
  emitToolResult(request4, response, parentToolUseId = null) {
360081
+ const responsePartsError = this.checkResponsePartsForError(
360082
+ response.responseParts
360083
+ );
360084
+ const hasError = Boolean(response.error) || Boolean(responsePartsError);
359945
360085
  if (response.error && response.errorType === "execution_denied" /* EXECUTION_DENIED */) {
359946
360086
  const denial = {
359947
360087
  tool_name: request4.name,
@@ -359953,7 +360093,7 @@ ${event.value}`, null);
359953
360093
  const block2 = {
359954
360094
  type: "tool_result",
359955
360095
  tool_use_id: request4.callId,
359956
- is_error: Boolean(response.error)
360096
+ is_error: hasError
359957
360097
  };
359958
360098
  const content = toolResultContent(response);
359959
360099
  if (content !== void 0) {
@@ -360092,10 +360232,27 @@ function partsToContentBlock(parts) {
360092
360232
  return blocks;
360093
360233
  }
360094
360234
  __name(partsToContentBlock, "partsToContentBlock");
360235
+ function checkResponsePartsForError(responseParts) {
360236
+ if (!responseParts || responseParts.length === 0) {
360237
+ return void 0;
360238
+ }
360239
+ for (const part of responseParts) {
360240
+ if ("functionResponse" in part && part.functionResponse?.response && typeof part.functionResponse.response === "object" && "error" in part.functionResponse.response && part.functionResponse.response["error"]) {
360241
+ const error2 = part.functionResponse.response["error"];
360242
+ return typeof error2 === "string" ? error2 : String(error2);
360243
+ }
360244
+ }
360245
+ return void 0;
360246
+ }
360247
+ __name(checkResponsePartsForError, "checkResponsePartsForError");
360095
360248
  function toolResultContent(response) {
360096
360249
  if (response.error) {
360097
360250
  return response.error.message;
360098
360251
  }
360252
+ const responsePartsError = checkResponsePartsForError(response.responseParts);
360253
+ if (responsePartsError) {
360254
+ return responsePartsError;
360255
+ }
360099
360256
  if (typeof response.resultDisplay === "string" && response.resultDisplay.trim().length > 0) {
360100
360257
  return response.resultDisplay;
360101
360258
  }
@@ -361681,6 +361838,15 @@ async function runNonInteractive(config2, settings, input, prompt_id, options2 =
361681
361838
  process.stdout.write(event.value);
361682
361839
  } else if (event.type === "tool_call_request" /* ToolCallRequest */) {
361683
361840
  toolCallRequests.push(event.value);
361841
+ } else if (event.type === "error" /* Error */) {
361842
+ const errorText = parseAndFormatApiError(
361843
+ event.value.error,
361844
+ config2.getContentGeneratorConfig()?.authType,
361845
+ void 0,
361846
+ config2.getModel()
361847
+ );
361848
+ process.stderr.write(`${errorText}
361849
+ `);
361684
361850
  }
361685
361851
  }
361686
361852
  }
@@ -361692,6 +361858,8 @@ async function runNonInteractive(config2, settings, input, prompt_id, options2 =
361692
361858
  const toolResponseParts = [];
361693
361859
  for (const requestInfo of toolCallRequests) {
361694
361860
  const finalRequestInfo = requestInfo;
361861
+ const inputFormat = typeof config2.getInputFormat === "function" ? config2.getInputFormat() : "text" /* TEXT */;
361862
+ const toolCallUpdateCallback = inputFormat === "stream-json" /* STREAM_JSON */ && options2.controlService ? options2.controlService.permission.getToolCallUpdateCallback() : void 0;
361695
361863
  const isTaskTool = finalRequestInfo.name === "task";
361696
361864
  const taskToolProgress = isTaskTool ? createTaskToolProgressHandler(
361697
361865
  config2,
@@ -361704,12 +361872,10 @@ async function runNonInteractive(config2, settings, input, prompt_id, options2 =
361704
361872
  finalRequestInfo,
361705
361873
  abortController.signal,
361706
361874
  isTaskTool && taskToolProgressHandler ? {
361707
- outputUpdateHandler: taskToolProgressHandler
361708
- /*
361709
- toolCallUpdateCallback
361710
- ? { onToolCallsUpdate: toolCallUpdateCallback }
361711
- : undefined,
361712
- */
361875
+ outputUpdateHandler: taskToolProgressHandler,
361876
+ onToolCallsUpdate: toolCallUpdateCallback
361877
+ } : toolCallUpdateCallback ? {
361878
+ onToolCallsUpdate: toolCallUpdateCallback
361713
361879
  } : void 0
361714
361880
  );
361715
361881
  if (toolResponse.error) {
@@ -361991,10 +362157,57 @@ var SystemController = class extends BaseController {
361991
362157
  * Registers SDK MCP servers and returns capabilities
361992
362158
  */
361993
362159
  async handleInitialize(payload) {
361994
- if (payload.sdkMcpServers && Array.isArray(payload.sdkMcpServers)) {
361995
- for (const serverName of payload.sdkMcpServers) {
362160
+ this.context.config.setSdkMode(true);
362161
+ if (payload.sdkMcpServers && typeof payload.sdkMcpServers === "object") {
362162
+ for (const serverName of Object.keys(payload.sdkMcpServers)) {
361996
362163
  this.context.sdkMcpServers.add(serverName);
361997
362164
  }
362165
+ try {
362166
+ this.context.config.addMcpServers(payload.sdkMcpServers);
362167
+ if (this.context.debugMode) {
362168
+ console.error(
362169
+ `[SystemController] Added ${Object.keys(payload.sdkMcpServers).length} SDK MCP servers to config`
362170
+ );
362171
+ }
362172
+ } catch (error2) {
362173
+ if (this.context.debugMode) {
362174
+ console.error(
362175
+ "[SystemController] Failed to add SDK MCP servers:",
362176
+ error2
362177
+ );
362178
+ }
362179
+ }
362180
+ }
362181
+ if (payload.mcpServers && typeof payload.mcpServers === "object") {
362182
+ try {
362183
+ this.context.config.addMcpServers(payload.mcpServers);
362184
+ if (this.context.debugMode) {
362185
+ console.error(
362186
+ `[SystemController] Added ${Object.keys(payload.mcpServers).length} MCP servers to config`
362187
+ );
362188
+ }
362189
+ } catch (error2) {
362190
+ if (this.context.debugMode) {
362191
+ console.error("[SystemController] Failed to add MCP servers:", error2);
362192
+ }
362193
+ }
362194
+ }
362195
+ if (payload.agents && Array.isArray(payload.agents)) {
362196
+ try {
362197
+ this.context.config.setSessionSubagents(payload.agents);
362198
+ if (this.context.debugMode) {
362199
+ console.error(
362200
+ `[SystemController] Added ${payload.agents.length} session subagents to config`
362201
+ );
362202
+ }
362203
+ } catch (error2) {
362204
+ if (this.context.debugMode) {
362205
+ console.error(
362206
+ "[SystemController] Failed to add session subagents:",
362207
+ error2
362208
+ );
362209
+ }
362210
+ }
361998
362211
  }
361999
362212
  const capabilities = this.buildControlCapabilities();
362000
362213
  if (this.context.debugMode) {
@@ -362017,29 +362230,12 @@ var SystemController = class extends BaseController {
362017
362230
  buildControlCapabilities() {
362018
362231
  const capabilities = {
362019
362232
  can_handle_can_use_tool: true,
362020
- can_handle_hook_callback: true,
362233
+ can_handle_hook_callback: false,
362021
362234
  can_set_permission_mode: typeof this.context.config.setApprovalMode === "function",
362022
- can_set_model: typeof this.context.config.setModel === "function"
362235
+ can_set_model: typeof this.context.config.setModel === "function",
362236
+ /* TODO: sdkMcpServers support */
362237
+ can_handle_mcp_message: false
362023
362238
  };
362024
- try {
362025
- const mcpProvider = this.context.config;
362026
- if (typeof mcpProvider.getMcpServers === "function") {
362027
- const servers = mcpProvider.getMcpServers();
362028
- capabilities["can_handle_mcp_message"] = Boolean(
362029
- servers && Object.keys(servers).length > 0
362030
- );
362031
- } else {
362032
- capabilities["can_handle_mcp_message"] = false;
362033
- }
362034
- } catch (error2) {
362035
- if (this.context.debugMode) {
362036
- console.error(
362037
- "[SystemController] Failed to determine MCP capability:",
362038
- error2
362039
- );
362040
- }
362041
- capabilities["can_handle_mcp_message"] = false;
362042
- }
362043
362239
  return capabilities;
362044
362240
  }
362045
362241
  /**
@@ -362094,27 +362290,377 @@ var SystemController = class extends BaseController {
362094
362290
  /**
362095
362291
  * Handle supported_commands request
362096
362292
  *
362097
- * Returns list of supported control commands
362098
- *
362099
- * Note: This list should match the ControlRequestType enum in
362100
- * packages/sdk/typescript/src/types/controlRequests.ts
362293
+ * Returns list of supported slash commands loaded dynamically
362101
362294
  */
362102
362295
  async handleSupportedCommands() {
362103
- const commands = [
362104
- "initialize",
362105
- "interrupt",
362106
- "set_model",
362107
- "supported_commands",
362108
- "can_use_tool",
362109
- "set_permission_mode",
362110
- "mcp_message",
362111
- "mcp_server_status",
362112
- "hook_callback"
362113
- ];
362296
+ const slashCommands = await this.loadSlashCommandNames();
362114
362297
  return {
362115
362298
  subtype: "supported_commands",
362116
- commands
362299
+ commands: slashCommands
362300
+ };
362301
+ }
362302
+ /**
362303
+ * Load slash command names using CommandService
362304
+ *
362305
+ * @returns Promise resolving to array of slash command names
362306
+ */
362307
+ async loadSlashCommandNames() {
362308
+ const controller = new AbortController();
362309
+ try {
362310
+ const service = await CommandService.create(
362311
+ [new BuiltinCommandLoader(this.context.config)],
362312
+ controller.signal
362313
+ );
362314
+ const names = /* @__PURE__ */ new Set();
362315
+ const commands = service.getCommands();
362316
+ for (const command2 of commands) {
362317
+ names.add(command2.name);
362318
+ }
362319
+ return Array.from(names).sort();
362320
+ } catch (error2) {
362321
+ if (this.context.debugMode) {
362322
+ console.error(
362323
+ "[SystemController] Failed to load slash commands:",
362324
+ error2
362325
+ );
362326
+ }
362327
+ return [];
362328
+ } finally {
362329
+ controller.abort();
362330
+ }
362331
+ }
362332
+ };
362333
+
362334
+ // packages/cli/src/nonInteractive/control/controllers/permissionController.ts
362335
+ init_esbuild_shims();
362336
+ init_core4();
362337
+ var PermissionController = class extends BaseController {
362338
+ static {
362339
+ __name(this, "PermissionController");
362340
+ }
362341
+ pendingOutgoingRequests = /* @__PURE__ */ new Set();
362342
+ /**
362343
+ * Handle permission control requests
362344
+ */
362345
+ async handleRequestPayload(payload, _signal) {
362346
+ switch (payload.subtype) {
362347
+ case "can_use_tool":
362348
+ return this.handleCanUseTool(payload);
362349
+ case "set_permission_mode":
362350
+ return this.handleSetPermissionMode(
362351
+ payload
362352
+ );
362353
+ default:
362354
+ throw new Error(`Unsupported request subtype in PermissionController`);
362355
+ }
362356
+ }
362357
+ /**
362358
+ * Handle can_use_tool request
362359
+ *
362360
+ * Comprehensive permission evaluation based on:
362361
+ * - Permission mode (approval level)
362362
+ * - Tool registry validation
362363
+ * - Error handling with safe defaults
362364
+ */
362365
+ async handleCanUseTool(payload) {
362366
+ const toolName = payload.tool_name;
362367
+ if (!toolName || typeof toolName !== "string" || toolName.trim().length === 0) {
362368
+ return {
362369
+ subtype: "can_use_tool",
362370
+ behavior: "deny",
362371
+ message: "Missing or invalid tool_name in can_use_tool request"
362372
+ };
362373
+ }
362374
+ let behavior = "allow";
362375
+ let message;
362376
+ try {
362377
+ const permissionResult = this.checkPermissionMode();
362378
+ if (!permissionResult.allowed) {
362379
+ behavior = "deny";
362380
+ message = permissionResult.message;
362381
+ }
362382
+ if (behavior === "allow") {
362383
+ const registryResult = this.checkToolRegistry(toolName);
362384
+ if (!registryResult.allowed) {
362385
+ behavior = "deny";
362386
+ message = registryResult.message;
362387
+ }
362388
+ }
362389
+ } catch (error2) {
362390
+ behavior = "deny";
362391
+ message = error2 instanceof Error ? `Failed to evaluate tool permission: ${error2.message}` : "Failed to evaluate tool permission";
362392
+ }
362393
+ const response = {
362394
+ subtype: "can_use_tool",
362395
+ behavior
362117
362396
  };
362397
+ if (message) {
362398
+ response["message"] = message;
362399
+ }
362400
+ return response;
362401
+ }
362402
+ /**
362403
+ * Check permission mode for tool execution
362404
+ */
362405
+ checkPermissionMode() {
362406
+ const mode = this.context.permissionMode;
362407
+ switch (mode) {
362408
+ case "yolo":
362409
+ // Allow all tools
362410
+ case "auto-edit":
362411
+ // Auto-approve edit operations
362412
+ case "plan":
362413
+ return { allowed: true };
362414
+ case "default":
362415
+ // TODO: allow all tools for test
362416
+ default:
362417
+ return {
362418
+ allowed: false,
362419
+ message: "Tool execution requires manual approval. Update permission mode or approve via host."
362420
+ };
362421
+ }
362422
+ }
362423
+ /**
362424
+ * Check if tool exists in registry
362425
+ */
362426
+ checkToolRegistry(toolName) {
362427
+ try {
362428
+ const config2 = this.context.config;
362429
+ const registryProvider = config2;
362430
+ if (typeof registryProvider.getToolRegistry === "function") {
362431
+ const registry2 = registryProvider.getToolRegistry();
362432
+ if (registry2 && typeof registry2.getTool === "function" && !registry2.getTool(toolName)) {
362433
+ return {
362434
+ allowed: false,
362435
+ message: `Tool "${toolName}" is not registered.`
362436
+ };
362437
+ }
362438
+ }
362439
+ return { allowed: true };
362440
+ } catch (error2) {
362441
+ return {
362442
+ allowed: false,
362443
+ message: `Failed to check tool registry: ${error2 instanceof Error ? error2.message : "Unknown error"}`
362444
+ };
362445
+ }
362446
+ }
362447
+ /**
362448
+ * Handle set_permission_mode request
362449
+ *
362450
+ * Updates the permission mode in the context
362451
+ */
362452
+ async handleSetPermissionMode(payload) {
362453
+ const mode = payload.mode;
362454
+ const validModes = [
362455
+ "default",
362456
+ "plan",
362457
+ "auto-edit",
362458
+ "yolo"
362459
+ ];
362460
+ if (!validModes.includes(mode)) {
362461
+ throw new Error(
362462
+ `Invalid permission mode: ${mode}. Valid values are: ${validModes.join(", ")}`
362463
+ );
362464
+ }
362465
+ this.context.permissionMode = mode;
362466
+ this.context.config.setApprovalMode(mode);
362467
+ if (this.context.debugMode) {
362468
+ console.error(
362469
+ `[PermissionController] Permission mode updated to: ${mode}`
362470
+ );
362471
+ }
362472
+ return { status: "updated", mode };
362473
+ }
362474
+ /**
362475
+ * Build permission suggestions for tool confirmation UI
362476
+ *
362477
+ * This method creates UI suggestions based on tool confirmation details,
362478
+ * helping the host application present appropriate permission options.
362479
+ */
362480
+ buildPermissionSuggestions(confirmationDetails) {
362481
+ if (!confirmationDetails || typeof confirmationDetails !== "object" || !("type" in confirmationDetails)) {
362482
+ return null;
362483
+ }
362484
+ const details = confirmationDetails;
362485
+ const type = String(details["type"] ?? "");
362486
+ const title = typeof details["title"] === "string" ? details["title"] : void 0;
362487
+ const confirmationType = type;
362488
+ switch (confirmationType) {
362489
+ case "exec":
362490
+ return [
362491
+ {
362492
+ type: "allow",
362493
+ label: "Allow Command",
362494
+ description: `Execute: ${details["command"]}`
362495
+ },
362496
+ {
362497
+ type: "deny",
362498
+ label: "Deny",
362499
+ description: "Block this command execution"
362500
+ }
362501
+ ];
362502
+ case "edit":
362503
+ return [
362504
+ {
362505
+ type: "allow",
362506
+ label: "Allow Edit",
362507
+ description: `Edit file: ${details["fileName"]}`
362508
+ },
362509
+ {
362510
+ type: "deny",
362511
+ label: "Deny",
362512
+ description: "Block this file edit"
362513
+ },
362514
+ {
362515
+ type: "modify",
362516
+ label: "Review Changes",
362517
+ description: "Review the proposed changes before applying"
362518
+ }
362519
+ ];
362520
+ case "plan":
362521
+ return [
362522
+ {
362523
+ type: "allow",
362524
+ label: "Approve Plan",
362525
+ description: title || "Execute the proposed plan"
362526
+ },
362527
+ {
362528
+ type: "deny",
362529
+ label: "Reject Plan",
362530
+ description: "Do not execute this plan"
362531
+ }
362532
+ ];
362533
+ case "mcp":
362534
+ return [
362535
+ {
362536
+ type: "allow",
362537
+ label: "Allow MCP Call",
362538
+ description: `${details["serverName"]}: ${details["toolName"]}`
362539
+ },
362540
+ {
362541
+ type: "deny",
362542
+ label: "Deny",
362543
+ description: "Block this MCP server call"
362544
+ }
362545
+ ];
362546
+ case "info":
362547
+ return [
362548
+ {
362549
+ type: "allow",
362550
+ label: "Allow Info Request",
362551
+ description: title || "Allow information request"
362552
+ },
362553
+ {
362554
+ type: "deny",
362555
+ label: "Deny",
362556
+ description: "Block this information request"
362557
+ }
362558
+ ];
362559
+ default:
362560
+ return [
362561
+ {
362562
+ type: "allow",
362563
+ label: "Allow",
362564
+ description: title || `Allow ${type} operation`
362565
+ },
362566
+ {
362567
+ type: "deny",
362568
+ label: "Deny",
362569
+ description: `Block ${type} operation`
362570
+ }
362571
+ ];
362572
+ }
362573
+ }
362574
+ /**
362575
+ * Get callback for monitoring tool calls and handling outgoing permission requests
362576
+ * This is passed to executeToolCall to hook into CoreToolScheduler updates
362577
+ */
362578
+ getToolCallUpdateCallback() {
362579
+ return (toolCalls) => {
362580
+ for (const call of toolCalls) {
362581
+ if (call && typeof call === "object" && call.status === "awaiting_approval") {
362582
+ const awaiting = call;
362583
+ if (typeof awaiting.confirmationDetails?.onConfirm === "function" && !this.pendingOutgoingRequests.has(awaiting.request.callId)) {
362584
+ this.pendingOutgoingRequests.add(awaiting.request.callId);
362585
+ void this.handleOutgoingPermissionRequest(awaiting);
362586
+ }
362587
+ }
362588
+ }
362589
+ };
362590
+ }
362591
+ /**
362592
+ * Handle outgoing permission request
362593
+ *
362594
+ * Behavior depends on input format:
362595
+ * - stream-json mode: Send can_use_tool to SDK and await response
362596
+ * - Other modes: Check local approval mode and decide immediately
362597
+ */
362598
+ async handleOutgoingPermissionRequest(toolCall) {
362599
+ try {
362600
+ const inputFormat = this.context.config.getInputFormat?.();
362601
+ const isStreamJsonMode = inputFormat === "stream-json" /* STREAM_JSON */;
362602
+ if (!isStreamJsonMode) {
362603
+ const modeCheck = this.checkPermissionMode();
362604
+ const outcome = modeCheck.allowed ? "proceed_once" /* ProceedOnce */ : "cancel" /* Cancel */;
362605
+ await toolCall.confirmationDetails.onConfirm(outcome);
362606
+ return;
362607
+ }
362608
+ const permissionSuggestions = this.buildPermissionSuggestions(
362609
+ toolCall.confirmationDetails
362610
+ );
362611
+ const response = await this.sendControlRequest({
362612
+ subtype: "can_use_tool",
362613
+ tool_name: toolCall.request.name,
362614
+ tool_use_id: toolCall.request.callId,
362615
+ input: toolCall.request.args,
362616
+ permission_suggestions: permissionSuggestions,
362617
+ blocked_path: null
362618
+ });
362619
+ if (response.subtype !== "success") {
362620
+ await toolCall.confirmationDetails.onConfirm(
362621
+ "cancel" /* Cancel */
362622
+ );
362623
+ return;
362624
+ }
362625
+ const payload = response.response || {};
362626
+ const behavior = String(payload["behavior"] || "").toLowerCase();
362627
+ if (behavior === "allow") {
362628
+ const updatedInput = payload["updatedInput"];
362629
+ if (updatedInput && typeof updatedInput === "object") {
362630
+ toolCall.request.args = updatedInput;
362631
+ }
362632
+ await toolCall.confirmationDetails.onConfirm(
362633
+ "proceed_once" /* ProceedOnce */
362634
+ );
362635
+ } else {
362636
+ const cancelMessage = typeof payload["message"] === "string" ? payload["message"] : void 0;
362637
+ await toolCall.confirmationDetails.onConfirm(
362638
+ "cancel" /* Cancel */,
362639
+ cancelMessage ? { cancelMessage } : void 0
362640
+ );
362641
+ }
362642
+ } catch (error2) {
362643
+ if (this.context.debugMode) {
362644
+ console.error(
362645
+ "[PermissionController] Outgoing permission failed:",
362646
+ error2
362647
+ );
362648
+ }
362649
+ const confirmationType = toolCall.confirmationDetails.type;
362650
+ if (["edit", "exec", "mcp"].includes(confirmationType)) {
362651
+ const execOrMcpDetails = toolCall.confirmationDetails;
362652
+ await execOrMcpDetails.onConfirm(
362653
+ "cancel" /* Cancel */,
362654
+ void 0
362655
+ );
362656
+ } else {
362657
+ await toolCall.confirmationDetails.onConfirm(
362658
+ "cancel" /* Cancel */
362659
+ );
362660
+ }
362661
+ } finally {
362662
+ this.pendingOutgoingRequests.delete(toolCall.request.callId);
362663
+ }
362118
362664
  }
362119
362665
  };
362120
362666
 
@@ -362126,7 +362672,7 @@ var ControlDispatcher = class {
362126
362672
  context;
362127
362673
  // Make controllers publicly accessible
362128
362674
  systemController;
362129
- // readonly permissionController: PermissionController;
362675
+ permissionController;
362130
362676
  // readonly mcpController: MCPController;
362131
362677
  // readonly hookController: HookController;
362132
362678
  // Central pending request registries
@@ -362139,6 +362685,11 @@ var ControlDispatcher = class {
362139
362685
  this,
362140
362686
  "SystemController"
362141
362687
  );
362688
+ this.permissionController = new PermissionController(
362689
+ context2,
362690
+ this,
362691
+ "PermissionController"
362692
+ );
362142
362693
  this.context.abortSignal.addEventListener("abort", () => {
362143
362694
  this.shutdown();
362144
362695
  });
@@ -362243,6 +362794,7 @@ var ControlDispatcher = class {
362243
362794
  }
362244
362795
  this.pendingOutgoingRequests.clear();
362245
362796
  this.systemController.cleanup();
362797
+ this.permissionController.cleanup();
362246
362798
  }
362247
362799
  /**
362248
362800
  * Registers an incoming request in the pending registry
@@ -362295,9 +362847,9 @@ var ControlDispatcher = class {
362295
362847
  case "set_model":
362296
362848
  case "supported_commands":
362297
362849
  return this.systemController;
362298
- // case 'can_use_tool':
362299
- // case 'set_permission_mode':
362300
- // return this.permissionController;
362850
+ case "can_use_tool":
362851
+ case "set_permission_mode":
362852
+ return this.permissionController;
362301
362853
  // case 'mcp_message':
362302
362854
  // case 'mcp_server_status':
362303
362855
  // return this.mcpController;
@@ -362359,43 +362911,28 @@ var ControlService = class {
362359
362911
  * Handles tool execution permissions, approval checks, and callbacks.
362360
362912
  * Delegates to the shared PermissionController instance.
362361
362913
  */
362362
- // get permission(): PermissionServiceAPI {
362363
- // const controller = this.dispatcher.permissionController;
362364
- // return {
362365
- // /**
362366
- // * Check if a tool should be allowed based on current permission settings
362367
- // *
362368
- // * Evaluates permission mode and tool registry to determine if execution
362369
- // * should proceed. Can optionally modify tool arguments based on confirmation details.
362370
- // *
362371
- // * @param toolRequest - Tool call request information
362372
- // * @param confirmationDetails - Optional confirmation details for UI
362373
- // * @returns Permission decision with optional updated arguments
362374
- // */
362375
- // shouldAllowTool: controller.shouldAllowTool.bind(controller),
362376
- //
362377
- // /**
362378
- // * Build UI suggestions for tool confirmation dialogs
362379
- // *
362380
- // * Creates actionable permission suggestions based on tool confirmation details.
362381
- // *
362382
- // * @param confirmationDetails - Tool confirmation details
362383
- // * @returns Array of permission suggestions or null
362384
- // */
362385
- // buildPermissionSuggestions:
362386
- // controller.buildPermissionSuggestions.bind(controller),
362387
- //
362388
- // /**
362389
- // * Get callback for monitoring tool call status updates
362390
- // *
362391
- // * Returns callback function for integration with CoreToolScheduler.
362392
- // *
362393
- // * @returns Callback function for tool call updates
362394
- // */
362395
- // getToolCallUpdateCallback:
362396
- // controller.getToolCallUpdateCallback.bind(controller),
362397
- // };
362398
- // }
362914
+ get permission() {
362915
+ const controller = this.dispatcher.permissionController;
362916
+ return {
362917
+ /**
362918
+ * Build UI suggestions for tool confirmation dialogs
362919
+ *
362920
+ * Creates actionable permission suggestions based on tool confirmation details.
362921
+ *
362922
+ * @param confirmationDetails - Tool confirmation details
362923
+ * @returns Array of permission suggestions or null
362924
+ */
362925
+ buildPermissionSuggestions: controller.buildPermissionSuggestions.bind(controller),
362926
+ /**
362927
+ * Get callback for monitoring tool call status updates
362928
+ *
362929
+ * Returns callback function for integration with CoreToolScheduler.
362930
+ *
362931
+ * @returns Callback function for tool call updates
362932
+ */
362933
+ getToolCallUpdateCallback: controller.getToolCallUpdateCallback.bind(controller)
362934
+ };
362935
+ }
362399
362936
  /**
362400
362937
  * System Domain API
362401
362938
  *
@@ -362573,17 +363110,10 @@ var ConsolePatcher = class {
362573
363110
  };
362574
363111
 
362575
363112
  // packages/cli/src/nonInteractive/session.ts
362576
- var SESSION_STATE = {
362577
- INITIALIZING: "initializing",
362578
- IDLE: "idle",
362579
- PROCESSING_QUERY: "processing_query",
362580
- SHUTTING_DOWN: "shutting_down"
362581
- };
362582
- var SessionManager = class {
363113
+ var Session2 = class {
362583
363114
  static {
362584
- __name(this, "SessionManager");
363115
+ __name(this, "Session");
362585
363116
  }
362586
- state = SESSION_STATE.INITIALIZING;
362587
363117
  userMessageQueue = [];
362588
363118
  abortController;
362589
363119
  config;
@@ -362598,6 +363128,9 @@ var SessionManager = class {
362598
363128
  debugMode;
362599
363129
  shutdownHandler = null;
362600
363130
  initialPrompt = null;
363131
+ processingPromise = null;
363132
+ isShuttingDown = false;
363133
+ configInitialized = false;
362601
363134
  constructor(config2, initialPrompt) {
362602
363135
  this.config = config2;
362603
363136
  this.sessionId = config2.getSessionId();
@@ -362611,106 +363144,25 @@ var SessionManager = class {
362611
363144
  );
362612
363145
  this.setupSignalHandlers();
362613
363146
  }
362614
- /**
362615
- * Get next prompt ID
362616
- */
362617
363147
  getNextPromptId() {
362618
363148
  this.promptIdCounter++;
362619
363149
  return `${this.sessionId}########${this.promptIdCounter}`;
362620
363150
  }
362621
- /**
362622
- * Route a message to the appropriate handler based on its type
362623
- *
362624
- * Classifies incoming messages and routes them to appropriate handlers.
362625
- */
362626
- route(message) {
362627
- if (isControlRequest(message)) {
362628
- return { type: "control_request", message };
362629
- }
362630
- if (isControlResponse(message)) {
362631
- return { type: "control_response", message };
362632
- }
362633
- if (isControlCancel(message)) {
362634
- return { type: "control_cancel", message };
362635
- }
362636
- if (isCLIUserMessage(message)) {
362637
- return { type: "user", message };
362638
- }
362639
- if (isCLIAssistantMessage(message)) {
362640
- return { type: "assistant", message };
362641
- }
362642
- if (isCLISystemMessage(message)) {
362643
- return { type: "system", message };
362644
- }
362645
- if (isCLIResultMessage(message)) {
362646
- return { type: "result", message };
362647
- }
362648
- if (isCLIPartialAssistantMessage(message)) {
362649
- return { type: "stream_event", message };
363151
+ async ensureConfigInitialized() {
363152
+ if (this.configInitialized) {
363153
+ return;
362650
363154
  }
362651
363155
  if (this.debugMode) {
362652
- console.error(
362653
- "[SessionManager] Unknown message type:",
362654
- JSON.stringify(message, null, 2)
362655
- );
363156
+ console.error("[Session] Initializing config");
362656
363157
  }
362657
- return { type: "unknown", message };
362658
- }
362659
- /**
362660
- * Process a single message with unified logic for both initial prompt and stream messages.
362661
- *
362662
- * Handles:
362663
- * - Abort check
362664
- * - First message detection and handling
362665
- * - Normal message processing
362666
- * - Shutdown state checks
362667
- *
362668
- * @param message - Message to process
362669
- * @returns true if the calling code should exit (break/return), false to continue
362670
- */
362671
- async processSingleMessage(message) {
362672
- if (this.abortController.signal.aborted) {
362673
- return true;
362674
- }
362675
- if (this.controlSystemEnabled === null) {
362676
- const handled = await this.handleFirstMessage(message);
362677
- if (handled) {
362678
- return this.state === SESSION_STATE.SHUTTING_DOWN;
362679
- }
362680
- }
362681
- await this.processMessage(message);
362682
- return this.state === SESSION_STATE.SHUTTING_DOWN;
362683
- }
362684
- /**
362685
- * Main entry point - run the session
362686
- */
362687
- async run() {
362688
363158
  try {
362689
- if (this.debugMode) {
362690
- console.error("[SessionManager] Starting session", this.sessionId);
362691
- }
362692
- if (this.initialPrompt !== null) {
362693
- const shouldExit = await this.processSingleMessage(this.initialPrompt);
362694
- if (shouldExit) {
362695
- await this.shutdown();
362696
- return;
362697
- }
362698
- }
362699
- for await (const message of this.inputReader.read()) {
362700
- const shouldExit = await this.processSingleMessage(message);
362701
- if (shouldExit) {
362702
- break;
362703
- }
362704
- }
362705
- await this.shutdown();
363159
+ await this.config.initialize();
363160
+ this.configInitialized = true;
362706
363161
  } catch (error2) {
362707
363162
  if (this.debugMode) {
362708
- console.error("[SessionManager] Error:", error2);
363163
+ console.error("[Session] Failed to initialize config:", error2);
362709
363164
  }
362710
- await this.shutdown();
362711
363165
  throw error2;
362712
- } finally {
362713
- this.cleanupSignalHandlers();
362714
363166
  }
362715
363167
  }
362716
363168
  ensureControlSystem() {
@@ -362741,219 +363193,64 @@ var SessionManager = class {
362741
363193
  return this.dispatcher;
362742
363194
  }
362743
363195
  async handleFirstMessage(message) {
362744
- const routed = this.route(message);
362745
- if (routed.type === "control_request") {
362746
- const request4 = routed.message;
363196
+ if (isControlRequest(message)) {
363197
+ const request4 = message;
362747
363198
  this.controlSystemEnabled = true;
362748
363199
  this.ensureControlSystem();
362749
363200
  if (request4.request.subtype === "initialize") {
362750
363201
  await this.dispatcher?.dispatch(request4);
362751
- this.state = SESSION_STATE.IDLE;
363202
+ await this.ensureConfigInitialized();
362752
363203
  return true;
362753
363204
  }
362754
- return false;
363205
+ if (this.debugMode) {
363206
+ console.error(
363207
+ "[Session] Ignoring non-initialize control request during initialization"
363208
+ );
363209
+ }
363210
+ return true;
362755
363211
  }
362756
- if (routed.type === "user") {
363212
+ if (isCLIUserMessage(message)) {
362757
363213
  this.controlSystemEnabled = false;
362758
- this.state = SESSION_STATE.PROCESSING_QUERY;
362759
- this.userMessageQueue.push(routed.message);
362760
- await this.processUserMessageQueue();
363214
+ await this.ensureConfigInitialized();
363215
+ this.enqueueUserMessage(message);
362761
363216
  return true;
362762
363217
  }
362763
363218
  this.controlSystemEnabled = false;
362764
363219
  return false;
362765
363220
  }
362766
- /**
362767
- * Process a single message from the stream
362768
- */
362769
- async processMessage(message) {
362770
- const routed = this.route(message);
362771
- if (this.debugMode) {
362772
- console.error(
362773
- `[SessionManager] State: ${this.state}, Message type: ${routed.type}`
362774
- );
362775
- }
362776
- switch (this.state) {
362777
- case SESSION_STATE.INITIALIZING:
362778
- await this.handleInitializingState(routed);
362779
- break;
362780
- case SESSION_STATE.IDLE:
362781
- await this.handleIdleState(routed);
362782
- break;
362783
- case SESSION_STATE.PROCESSING_QUERY:
362784
- await this.handleProcessingState(routed);
362785
- break;
362786
- case SESSION_STATE.SHUTTING_DOWN:
362787
- break;
362788
- default: {
362789
- const _exhaustiveCheck = this.state;
362790
- if (this.debugMode) {
362791
- console.error("[SessionManager] Unknown state:", _exhaustiveCheck);
362792
- }
362793
- break;
362794
- }
362795
- }
362796
- }
362797
- /**
362798
- * Handle messages in initializing state
362799
- */
362800
- async handleInitializingState(routed) {
362801
- if (routed.type === "control_request") {
362802
- const request4 = routed.message;
362803
- const dispatcher = this.getDispatcher();
362804
- if (!dispatcher) {
362805
- if (this.debugMode) {
362806
- console.error(
362807
- "[SessionManager] Control request received before control system initialization"
362808
- );
362809
- }
362810
- return;
362811
- }
362812
- if (request4.request.subtype === "initialize") {
362813
- await dispatcher.dispatch(request4);
362814
- this.state = SESSION_STATE.IDLE;
362815
- if (this.debugMode) {
362816
- console.error("[SessionManager] Initialized, transitioning to idle");
362817
- }
362818
- } else {
362819
- if (this.debugMode) {
362820
- console.error(
362821
- "[SessionManager] Ignoring non-initialize control request during initialization"
362822
- );
362823
- }
362824
- }
362825
- } else {
362826
- if (this.debugMode) {
362827
- console.error(
362828
- "[SessionManager] Ignoring non-control message during initialization"
362829
- );
362830
- }
362831
- }
362832
- }
362833
- /**
362834
- * Handle messages in idle state
362835
- */
362836
- async handleIdleState(routed) {
363221
+ async handleControlRequest(request4) {
362837
363222
  const dispatcher = this.getDispatcher();
362838
- if (routed.type === "control_request") {
362839
- if (!dispatcher) {
362840
- if (this.debugMode) {
362841
- console.error("[SessionManager] Ignoring control request (disabled)");
362842
- }
362843
- return;
362844
- }
362845
- const request4 = routed.message;
362846
- await dispatcher.dispatch(request4);
362847
- } else if (routed.type === "control_response") {
362848
- if (!dispatcher) {
362849
- return;
362850
- }
362851
- const response = routed.message;
362852
- dispatcher.handleControlResponse(response);
362853
- } else if (routed.type === "control_cancel") {
362854
- if (!dispatcher) {
362855
- return;
362856
- }
362857
- const cancelRequest = routed.message;
362858
- dispatcher.handleCancel(cancelRequest.request_id);
362859
- } else if (routed.type === "user") {
362860
- const userMessage = routed.message;
362861
- this.userMessageQueue.push(userMessage);
362862
- await this.processUserMessageQueue();
362863
- } else {
363223
+ if (!dispatcher) {
362864
363224
  if (this.debugMode) {
362865
- console.error(
362866
- "[SessionManager] Ignoring message type in idle state:",
362867
- routed.type
362868
- );
363225
+ console.error("[Session] Control system not enabled");
362869
363226
  }
363227
+ return;
362870
363228
  }
363229
+ await dispatcher.dispatch(request4);
362871
363230
  }
362872
- /**
362873
- * Handle messages in processing state
362874
- */
362875
- async handleProcessingState(routed) {
363231
+ handleControlResponse(response) {
362876
363232
  const dispatcher = this.getDispatcher();
362877
- if (routed.type === "control_request") {
362878
- if (!dispatcher) {
362879
- if (this.debugMode) {
362880
- console.error(
362881
- "[SessionManager] Control request ignored during processing (disabled)"
362882
- );
362883
- }
362884
- return;
362885
- }
362886
- const request4 = routed.message;
362887
- await dispatcher.dispatch(request4);
362888
- } else if (routed.type === "control_response") {
362889
- if (!dispatcher) {
362890
- return;
362891
- }
362892
- const response = routed.message;
362893
- dispatcher.handleControlResponse(response);
362894
- } else if (routed.type === "user") {
362895
- const userMessage = routed.message;
362896
- this.userMessageQueue.push(userMessage);
362897
- if (this.debugMode) {
362898
- console.error(
362899
- "[SessionManager] Enqueued user message during processing"
362900
- );
362901
- }
362902
- } else {
362903
- if (this.debugMode) {
362904
- console.error(
362905
- "[SessionManager] Ignoring message type during processing:",
362906
- routed.type
362907
- );
362908
- }
363233
+ if (!dispatcher) {
363234
+ return;
362909
363235
  }
363236
+ dispatcher.handleControlResponse(response);
362910
363237
  }
362911
- /**
362912
- * Process user message queue (FIFO)
362913
- */
362914
- async processUserMessageQueue() {
362915
- while (this.userMessageQueue.length > 0 && !this.abortController.signal.aborted) {
362916
- this.state = SESSION_STATE.PROCESSING_QUERY;
362917
- const userMessage = this.userMessageQueue.shift();
362918
- try {
362919
- await this.processUserMessage(userMessage);
362920
- } catch (error2) {
362921
- if (this.debugMode) {
362922
- console.error(
362923
- "[SessionManager] Error processing user message:",
362924
- error2
362925
- );
362926
- }
362927
- this.emitErrorResult(error2);
362928
- }
362929
- }
362930
- if (!this.abortController.signal.aborted && this.state === SESSION_STATE.PROCESSING_QUERY && this.controlSystemEnabled === false && this.userMessageQueue.length === 0) {
362931
- if (this.debugMode) {
362932
- console.error(
362933
- "[SessionManager] Single-query mode: queue processed, shutting down"
362934
- );
362935
- }
362936
- this.state = SESSION_STATE.SHUTTING_DOWN;
363238
+ handleControlCancel(cancelRequest) {
363239
+ const dispatcher = this.getDispatcher();
363240
+ if (!dispatcher) {
362937
363241
  return;
362938
363242
  }
362939
- if (!this.abortController.signal.aborted && this.state === SESSION_STATE.PROCESSING_QUERY) {
362940
- this.state = SESSION_STATE.IDLE;
362941
- if (this.debugMode) {
362942
- console.error("[SessionManager] Queue processed, returning to idle");
362943
- }
362944
- }
363243
+ dispatcher.handleCancel(cancelRequest.request_id);
362945
363244
  }
362946
- /**
362947
- * Process a single user message
362948
- */
362949
363245
  async processUserMessage(userMessage) {
362950
363246
  const input = extractUserMessageText(userMessage);
362951
363247
  if (!input) {
362952
363248
  if (this.debugMode) {
362953
- console.error("[SessionManager] No text content in user message");
363249
+ console.error("[Session] No text content in user message");
362954
363250
  }
362955
363251
  return;
362956
363252
  }
363253
+ await this.ensureConfigInitialized();
362957
363254
  const promptId = this.getNextPromptId();
362958
363255
  try {
362959
363256
  await runNonInteractive(
@@ -362969,13 +363266,41 @@ var SessionManager = class {
362969
363266
  );
362970
363267
  } catch (error2) {
362971
363268
  if (this.debugMode) {
362972
- console.error("[SessionManager] Query execution error:", error2);
363269
+ console.error("[Session] Query execution error:", error2);
362973
363270
  }
362974
363271
  }
362975
363272
  }
362976
- /**
362977
- * Send tool results as user message
362978
- */
363273
+ async processUserMessageQueue() {
363274
+ if (this.isShuttingDown || this.abortController.signal.aborted) {
363275
+ return;
363276
+ }
363277
+ while (this.userMessageQueue.length > 0 && !this.isShuttingDown && !this.abortController.signal.aborted) {
363278
+ const userMessage = this.userMessageQueue.shift();
363279
+ try {
363280
+ await this.processUserMessage(userMessage);
363281
+ } catch (error2) {
363282
+ if (this.debugMode) {
363283
+ console.error("[Session] Error processing user message:", error2);
363284
+ }
363285
+ this.emitErrorResult(error2);
363286
+ }
363287
+ }
363288
+ }
363289
+ enqueueUserMessage(userMessage) {
363290
+ this.userMessageQueue.push(userMessage);
363291
+ this.ensureProcessingStarted();
363292
+ }
363293
+ ensureProcessingStarted() {
363294
+ if (this.processingPromise) {
363295
+ return;
363296
+ }
363297
+ this.processingPromise = this.processUserMessageQueue().finally(() => {
363298
+ this.processingPromise = null;
363299
+ if (this.userMessageQueue.length > 0 && !this.isShuttingDown && !this.abortController.signal.aborted) {
363300
+ this.ensureProcessingStarted();
363301
+ }
363302
+ });
363303
+ }
362979
363304
  emitErrorResult(error2, numTurns = 0, durationMs = 0, apiDurationMs = 0) {
362980
363305
  const message = error2 instanceof Error ? error2.message : String(error2);
362981
363306
  this.outputAdapter.emitResult({
@@ -362987,46 +363312,44 @@ var SessionManager = class {
362987
363312
  usage: void 0
362988
363313
  });
362989
363314
  }
362990
- /**
362991
- * Handle interrupt control request
362992
- */
362993
363315
  handleInterrupt() {
362994
363316
  if (this.debugMode) {
362995
- console.error("[SessionManager] Interrupt requested");
362996
- }
362997
- if (this.state === SESSION_STATE.PROCESSING_QUERY) {
362998
- this.abortController.abort();
362999
- this.abortController = new AbortController();
363317
+ console.error("[Session] Interrupt requested");
363000
363318
  }
363319
+ this.abortController.abort();
363320
+ this.abortController = new AbortController();
363001
363321
  }
363002
- /**
363003
- * Setup signal handlers for graceful shutdown
363004
- */
363005
363322
  setupSignalHandlers() {
363006
363323
  this.shutdownHandler = () => {
363007
363324
  if (this.debugMode) {
363008
- console.error("[SessionManager] Shutdown signal received");
363325
+ console.error("[Session] Shutdown signal received");
363009
363326
  }
363327
+ this.isShuttingDown = true;
363010
363328
  this.abortController.abort();
363011
- this.state = SESSION_STATE.SHUTTING_DOWN;
363012
363329
  };
363013
363330
  process.on("SIGINT", this.shutdownHandler);
363014
363331
  process.on("SIGTERM", this.shutdownHandler);
363015
363332
  }
363016
- /**
363017
- * Shutdown session and cleanup resources
363018
- */
363019
363333
  async shutdown() {
363020
363334
  if (this.debugMode) {
363021
- console.error("[SessionManager] Shutting down");
363335
+ console.error("[Session] Shutting down");
363336
+ }
363337
+ this.isShuttingDown = true;
363338
+ if (this.processingPromise) {
363339
+ try {
363340
+ await this.processingPromise;
363341
+ } catch (error2) {
363342
+ if (this.debugMode) {
363343
+ console.error(
363344
+ "[Session] Error waiting for processing to complete:",
363345
+ error2
363346
+ );
363347
+ }
363348
+ }
363022
363349
  }
363023
- this.state = SESSION_STATE.SHUTTING_DOWN;
363024
363350
  this.dispatcher?.shutdown();
363025
363351
  this.cleanupSignalHandlers();
363026
363352
  }
363027
- /**
363028
- * Remove signal handlers to prevent memory leaks
363029
- */
363030
363353
  cleanupSignalHandlers() {
363031
363354
  if (this.shutdownHandler) {
363032
363355
  process.removeListener("SIGINT", this.shutdownHandler);
@@ -363034,6 +363357,81 @@ var SessionManager = class {
363034
363357
  this.shutdownHandler = null;
363035
363358
  }
363036
363359
  }
363360
+ async run() {
363361
+ try {
363362
+ if (this.debugMode) {
363363
+ console.error("[Session] Starting session", this.sessionId);
363364
+ }
363365
+ if (this.initialPrompt !== null) {
363366
+ const handled = await this.handleFirstMessage(this.initialPrompt);
363367
+ if (handled && this.isShuttingDown) {
363368
+ await this.shutdown();
363369
+ return;
363370
+ }
363371
+ }
363372
+ try {
363373
+ for await (const message of this.inputReader.read()) {
363374
+ if (this.abortController.signal.aborted) {
363375
+ break;
363376
+ }
363377
+ if (this.controlSystemEnabled === null) {
363378
+ const handled = await this.handleFirstMessage(message);
363379
+ if (handled) {
363380
+ if (this.isShuttingDown) {
363381
+ break;
363382
+ }
363383
+ continue;
363384
+ }
363385
+ }
363386
+ if (isControlRequest(message)) {
363387
+ await this.handleControlRequest(message);
363388
+ } else if (isControlResponse(message)) {
363389
+ this.handleControlResponse(message);
363390
+ } else if (isControlCancel(message)) {
363391
+ this.handleControlCancel(message);
363392
+ } else if (isCLIUserMessage(message)) {
363393
+ this.enqueueUserMessage(message);
363394
+ } else if (this.debugMode) {
363395
+ if (!isCLIAssistantMessage(message) && !isCLISystemMessage(message) && !isCLIResultMessage(message) && !isCLIPartialAssistantMessage(message)) {
363396
+ console.error(
363397
+ "[Session] Unknown message type:",
363398
+ JSON.stringify(message, null, 2)
363399
+ );
363400
+ }
363401
+ }
363402
+ if (this.isShuttingDown) {
363403
+ break;
363404
+ }
363405
+ }
363406
+ } catch (streamError) {
363407
+ if (this.debugMode) {
363408
+ console.error("[Session] Stream reading error:", streamError);
363409
+ }
363410
+ throw streamError;
363411
+ }
363412
+ while (this.processingPromise) {
363413
+ if (this.debugMode) {
363414
+ console.error("[Session] Waiting for final processing to complete");
363415
+ }
363416
+ try {
363417
+ await this.processingPromise;
363418
+ } catch (error2) {
363419
+ if (this.debugMode) {
363420
+ console.error("[Session] Error in final processing:", error2);
363421
+ }
363422
+ }
363423
+ }
363424
+ await this.shutdown();
363425
+ } catch (error2) {
363426
+ if (this.debugMode) {
363427
+ console.error("[Session] Error:", error2);
363428
+ }
363429
+ await this.shutdown();
363430
+ throw error2;
363431
+ } finally {
363432
+ this.cleanupSignalHandlers();
363433
+ }
363434
+ }
363037
363435
  };
363038
363436
  function extractUserMessageText(message) {
363039
363437
  const content = message.message.content;
@@ -363074,7 +363472,7 @@ async function runNonInteractiveStreamJson(config2, input) {
363074
363472
  parent_tool_use_id: null
363075
363473
  };
363076
363474
  }
363077
- const manager = new SessionManager(config2, initialPrompt);
363475
+ const manager = new Session2(config2, initialPrompt);
363078
363476
  await manager.run();
363079
363477
  } finally {
363080
363478
  consolePatcher.cleanup();
@@ -383548,7 +383946,7 @@ var AgentSelectionStep = /* @__PURE__ */ __name(({
383548
383946
  return /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { flexDirection: "column", children: [
383549
383947
  projectAgents.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
383550
383948
  /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text3, { color: theme.text.primary, bold: true, children: t3("Project Level ({{path}})", {
383551
- path: projectAgents[0].filePath.replace(/\/[^/]+$/, "")
383949
+ path: projectAgents[0].filePath?.replace(/\/[^/]+$/, "") || ""
383552
383950
  }) }),
383553
383951
  /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: projectAgents.map((agent, index) => {
383554
383952
  const isSelected = navigation.currentBlock === "project" && navigation.projectIndex === index;
@@ -383562,7 +383960,7 @@ var AgentSelectionStep = /* @__PURE__ */ __name(({
383562
383960
  marginBottom: builtinAgents.length > 0 ? 1 : 0,
383563
383961
  children: [
383564
383962
  /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text3, { color: theme.text.primary, bold: true, children: t3("User Level ({{path}})", {
383565
- path: userAgents[0].filePath.replace(/\/[^/]+$/, "")
383963
+ path: userAgents[0].filePath?.replace(/\/[^/]+$/, "") || ""
383566
383964
  }) }),
383567
383965
  /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: userAgents.map((agent, index) => {
383568
383966
  const isSelected = navigation.currentBlock === "user" && navigation.userIndex === index;
@@ -383725,7 +384123,10 @@ function EditOptionsStep({
383725
384123
  setError(null);
383726
384124
  if (selectedValue === "editor") {
383727
384125
  try {
383728
- await launchEditor(selectedAgent?.filePath);
384126
+ if (!selectedAgent.filePath) {
384127
+ throw new Error("Agent has no file path");
384128
+ }
384129
+ await launchEditor(selectedAgent.filePath);
383729
384130
  } catch (err) {
383730
384131
  setError(
383731
384132
  t3("Failed to launch editor: {{error}}", {
@@ -402682,7 +403083,11 @@ function getRdmindSsoId3() {
402682
403083
  }
402683
403084
  }
402684
403085
  __name(getRdmindSsoId3, "getRdmindSsoId");
402685
- function useWebSocket({ onReloadCommands, debug: debug2, sessionId }) {
403086
+ function useWebSocket({
403087
+ onReloadCommands,
403088
+ debug: debug2,
403089
+ sessionId
403090
+ }) {
402686
403091
  const wsClientRef = (0, import_react133.useRef)(null);
402687
403092
  (0, import_react133.useEffect)(() => {
402688
403093
  const wsRuntimeConfig = loadWebSocketRuntimeConfig(debug2);
@@ -405012,7 +405417,7 @@ async function validateNonInteractiveAuth(configuredAuthType, useExternalAuth, n
405012
405417
  throw new Error(message);
405013
405418
  }
405014
405419
  }
405015
- const effectiveAuthType = enforcedType || getAuthTypeFromEnv() || configuredAuthType;
405420
+ const effectiveAuthType = enforcedType || configuredAuthType || getAuthTypeFromEnv();
405016
405421
  if (!effectiveAuthType) {
405017
405422
  const message = `Please set an Auth method in your ${USER_SETTINGS_PATH} or specify one of the following environment variables before running: QWEN_OAUTH, OPENAI_API_KEY`;
405018
405423
  throw new Error(message);
@@ -406706,7 +407111,7 @@ var SubAgentTracker = class {
406706
407111
 
406707
407112
  // packages/cli/src/acp-integration/session/Session.ts
406708
407113
  var ALLOWED_BUILTIN_COMMANDS_FOR_ACP = ["init"];
406709
- var Session2 = class {
407114
+ var Session3 = class {
406710
407115
  constructor(id, chat, config2, client, settings) {
406711
407116
  this.chat = chat;
406712
407117
  this.config = config2;
@@ -407447,7 +407852,7 @@ var GeminiAgent = class {
407447
407852
  name: APPROVAL_MODE_INFO[mode].name,
407448
407853
  description: APPROVAL_MODE_INFO[mode].description
407449
407854
  }));
407450
- const version3 = "0.1.3-alpha.2";
407855
+ const version3 = "0.1.3-alpha.3";
407451
407856
  return {
407452
407857
  protocolVersion: PROTOCOL_VERSION,
407453
407858
  agentInfo: {
@@ -407615,7 +408020,7 @@ var GeminiAgent = class {
407615
408020
  const geminiClient = config2.getGeminiClient();
407616
408021
  const history = conversation ? buildApiHistoryFromConversation(conversation) : void 0;
407617
408022
  const chat = history ? await geminiClient.startChat(history) : await geminiClient.startChat();
407618
- const session = new Session2(
408023
+ const session = new Session3(
407619
408024
  sessionId,
407620
408025
  chat,
407621
408026
  config2,
@@ -407883,7 +408288,11 @@ ${finalArgs[promptIndex + 1]}`;
407883
408288
  kittyProtocolDetectionComplete = detectAndEnableKittyProtocol();
407884
408289
  }
407885
408290
  setMaxSizedBoxDebugging(isDebugMode2);
407886
- const initializationResult = await initializeApp(config2, settings);
408291
+ const inputFormat = typeof config2.getInputFormat === "function" ? config2.getInputFormat() : "text" /* TEXT */;
408292
+ let initializationResult;
408293
+ if (inputFormat !== "stream-json" /* STREAM_JSON */) {
408294
+ initializationResult = await initializeApp(config2, settings);
408295
+ }
407887
408296
  if (settings.merged.security?.auth?.selectedType === "oauth-personal" /* LOGIN_WITH_GOOGLE */ && config2.isBrowserLaunchSuppressed()) {
407888
408297
  await getOauthClient(settings.merged.security.auth.selectedType, config2);
407889
408298
  }
@@ -407937,8 +408346,9 @@ ${finalArgs[promptIndex + 1]}`;
407937
408346
  );
407938
408347
  return;
407939
408348
  }
407940
- await config2.initialize();
407941
- const inputFormat = typeof config2.getInputFormat === "function" ? config2.getInputFormat() : "text" /* TEXT */;
408349
+ if (inputFormat !== "stream-json" /* STREAM_JSON */) {
408350
+ await config2.initialize();
408351
+ }
407942
408352
  if (inputFormat !== "stream-json" /* STREAM_JSON */ && !process.stdin.isTTY) {
407943
408353
  const stdinData = await readStdin();
407944
408354
  if (stdinData) {
@@ -407948,7 +408358,7 @@ ${input}`;
407948
408358
  }
407949
408359
  }
407950
408360
  const nonInteractiveConfig = await validateNonInteractiveAuth(
407951
- settings.merged.security?.auth?.selectedType,
408361
+ settings.merged.security?.auth?.selectedType || argv.authType,
407952
408362
  settings.merged.security?.auth?.useExternal,
407953
408363
  config2,
407954
408364
  settings