@rdmind/rdmind 0.1.3-alpha.1 → 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.
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.1";
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.1";
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: {
@@ -306612,6 +306702,7 @@ var init_en3 = __esm({
306612
306702
  'Theme "{{themeName}}" not found.': 'Theme "{{themeName}}" not found.',
306613
306703
  'Theme "{{themeName}}" not found in selected scope.': 'Theme "{{themeName}}" not found in selected scope.',
306614
306704
  "clear the screen and conversation history": "clear the screen and conversation history",
306705
+ "Clear conversation history and free up context": "Clear conversation history and free up context",
306615
306706
  "Compresses the context by replacing it with a summary.": "Compresses the context by replacing it with a summary.",
306616
306707
  "open full RDMind documentation in your browser": "open full RDMind documentation in your browser",
306617
306708
  "Configuration not available.": "Configuration not available.",
@@ -307470,6 +307561,7 @@ var init_zh = __esm({
307470
307561
  'Theme "{{themeName}}" not found.': '\u672A\u627E\u5230\u4E3B\u9898 "{{themeName}}"\u3002',
307471
307562
  'Theme "{{themeName}}" not found in selected scope.': '\u5728\u6240\u9009\u4F5C\u7528\u57DF\u4E2D\u672A\u627E\u5230\u4E3B\u9898 "{{themeName}}"\u3002',
307472
307563
  "clear the screen and conversation history": "\u6E05\u5C4F\u5E76\u6E05\u9664\u5BF9\u8BDD\u5386\u53F2",
307564
+ "Clear conversation history and free up context": "\u6E05\u9664\u5BF9\u8BDD\u5386\u53F2",
307473
307565
  "Compresses the context by replacing it with a summary.": "\u901A\u8FC7\u7528\u6458\u8981\u66FF\u6362\u6765\u538B\u7F29\u4E0A\u4E0B\u6587",
307474
307566
  "open full RDMind documentation in your browser": "\u5728\u6D4F\u89C8\u5668\u4E2D\u6253\u5F00\u5B8C\u6574\u7684 RDMind \u6587\u6863",
307475
307567
  "Configuration not available.": "\u914D\u7F6E\u4E0D\u53EF\u7528",
@@ -346093,7 +346185,7 @@ __name(getPackageJson, "getPackageJson");
346093
346185
  // packages/cli/src/utils/version.ts
346094
346186
  async function getCliVersion() {
346095
346187
  const pkgJson = await getPackageJson();
346096
- return "0.1.3-alpha.1";
346188
+ return "0.1.3-alpha.3";
346097
346189
  }
346098
346190
  __name(getCliVersion, "getCliVersion");
346099
346191
 
@@ -349090,6 +349182,28 @@ async function parseArguments(settings) {
349090
349182
  }).option("resume", {
349091
349183
  type: "string",
349092
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"
349093
349207
  }).deprecateOption(
349094
349208
  "show-memory-usage",
349095
349209
  'Use the "ui.showMemoryUsage" setting in settings.json instead. This flag will be removed in a future version.'
@@ -349290,7 +349404,7 @@ async function loadCliConfig(settings, extensions, extensionEnablementManager, a
349290
349404
  interactive = false;
349291
349405
  }
349292
349406
  const extraExcludes = [];
349293
- if (!interactive && !argv.experimentalAcp) {
349407
+ if (!interactive && !argv.experimentalAcp && inputFormat !== "stream-json" /* STREAM_JSON */) {
349294
349408
  switch (approvalMode) {
349295
349409
  case "plan" /* PLAN */:
349296
349410
  case "default" /* DEFAULT */:
@@ -349308,7 +349422,8 @@ async function loadCliConfig(settings, extensions, extensionEnablementManager, a
349308
349422
  const excludeTools = mergeExcludeTools(
349309
349423
  settings,
349310
349424
  activeExtensions,
349311
- extraExcludes.length > 0 ? extraExcludes : void 0
349425
+ extraExcludes.length > 0 ? extraExcludes : void 0,
349426
+ argv.excludeTools
349312
349427
  );
349313
349428
  const blockedMcpServers = [];
349314
349429
  if (!argv.allowedMcpServerNames) {
@@ -349371,7 +349486,7 @@ async function loadCliConfig(settings, extensions, extensionEnablementManager, a
349371
349486
  debugMode,
349372
349487
  question,
349373
349488
  fullContext: argv.allFiles || false,
349374
- coreTools: settings.tools?.core || void 0,
349489
+ coreTools: argv.coreTools || settings.tools?.core || void 0,
349375
349490
  allowedTools: argv.allowedTools || settings.tools?.allowed || void 0,
349376
349491
  excludeTools,
349377
349492
  toolDiscoveryCommand: settings.tools?.discoveryCommand,
@@ -349397,13 +349512,13 @@ async function loadCliConfig(settings, extensions, extensionEnablementManager, a
349397
349512
  model: resolvedModel,
349398
349513
  extensionContextFilePaths,
349399
349514
  sessionTokenLimit: settings.model?.sessionTokenLimit ?? -1,
349400
- maxSessionTurns: settings.model?.maxSessionTurns ?? -1,
349515
+ maxSessionTurns: argv.maxSessionTurns ?? settings.model?.maxSessionTurns ?? -1,
349401
349516
  experimentalZedIntegration: argv.experimentalAcp || false,
349402
349517
  listExtensions: argv.listExtensions || false,
349403
349518
  extensions: allExtensions,
349404
349519
  blockedMcpServers,
349405
349520
  noBrowser: !!process.env["NO_BROWSER"],
349406
- authType: settings.security?.auth?.selectedType,
349521
+ authType: argv.authType || settings.security?.auth?.selectedType,
349407
349522
  inputFormat,
349408
349523
  outputFormat,
349409
349524
  includePartialMessages,
@@ -349499,8 +349614,9 @@ function mergeMcpServers(settings, extensions) {
349499
349614
  return mcpServers;
349500
349615
  }
349501
349616
  __name(mergeMcpServers, "mergeMcpServers");
349502
- function mergeExcludeTools(settings, extensions, extraExcludes) {
349617
+ function mergeExcludeTools(settings, extensions, extraExcludes, cliExcludeTools) {
349503
349618
  const allExcludeTools = /* @__PURE__ */ new Set([
349619
+ ...cliExcludeTools || [],
349504
349620
  ...settings.tools?.exclude || [],
349505
349621
  ...extraExcludes || []
349506
349622
  ]);
@@ -352436,7 +352552,7 @@ var formatDuration = /* @__PURE__ */ __name((milliseconds) => {
352436
352552
 
352437
352553
  // packages/cli/src/generated/git-commit.ts
352438
352554
  init_esbuild_shims();
352439
- var GIT_COMMIT_INFO2 = "88408513";
352555
+ var GIT_COMMIT_INFO2 = "398f69c0";
352440
352556
 
352441
352557
  // packages/cli/src/utils/systemInfo.ts
352442
352558
  async function getNpmVersion() {
@@ -359170,7 +359286,7 @@ async function buildSystemMessage(config2, sessionId, permissionMode) {
359170
359286
  tools,
359171
359287
  mcp_servers: mcpServerList,
359172
359288
  model: config2.getModel(),
359173
- permissionMode,
359289
+ permission_mode: permissionMode,
359174
359290
  slash_commands: slashCommands,
359175
359291
  qwen_code_version: config2.getCliVersion() || "unknown",
359176
359292
  agents: agentNames
@@ -359676,6 +359792,16 @@ ${event.value}`, null);
359676
359792
  }
359677
359793
  this.finalizePendingBlocks(state, null);
359678
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
+ }
359679
359805
  default:
359680
359806
  break;
359681
359807
  }
@@ -359932,14 +360058,30 @@ ${event.value}`, null);
359932
360058
  };
359933
360059
  this.emitMessageImpl(message);
359934
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
+ }
359935
360071
  /**
359936
360072
  * Emits a tool result message.
359937
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).
359938
360076
  * @param request - Tool call request info
359939
360077
  * @param response - Tool call response info
359940
360078
  * @param parentToolUseId - Parent tool use ID (null for main agent)
359941
360079
  */
359942
360080
  emitToolResult(request4, response, parentToolUseId = null) {
360081
+ const responsePartsError = this.checkResponsePartsForError(
360082
+ response.responseParts
360083
+ );
360084
+ const hasError = Boolean(response.error) || Boolean(responsePartsError);
359943
360085
  if (response.error && response.errorType === "execution_denied" /* EXECUTION_DENIED */) {
359944
360086
  const denial = {
359945
360087
  tool_name: request4.name,
@@ -359951,7 +360093,7 @@ ${event.value}`, null);
359951
360093
  const block2 = {
359952
360094
  type: "tool_result",
359953
360095
  tool_use_id: request4.callId,
359954
- is_error: Boolean(response.error)
360096
+ is_error: hasError
359955
360097
  };
359956
360098
  const content = toolResultContent(response);
359957
360099
  if (content !== void 0) {
@@ -360090,10 +360232,27 @@ function partsToContentBlock(parts) {
360090
360232
  return blocks;
360091
360233
  }
360092
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");
360093
360248
  function toolResultContent(response) {
360094
360249
  if (response.error) {
360095
360250
  return response.error.message;
360096
360251
  }
360252
+ const responsePartsError = checkResponsePartsForError(response.responseParts);
360253
+ if (responsePartsError) {
360254
+ return responsePartsError;
360255
+ }
360097
360256
  if (typeof response.resultDisplay === "string" && response.resultDisplay.trim().length > 0) {
360098
360257
  return response.resultDisplay;
360099
360258
  }
@@ -361679,6 +361838,15 @@ async function runNonInteractive(config2, settings, input, prompt_id, options2 =
361679
361838
  process.stdout.write(event.value);
361680
361839
  } else if (event.type === "tool_call_request" /* ToolCallRequest */) {
361681
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
+ `);
361682
361850
  }
361683
361851
  }
361684
361852
  }
@@ -361690,6 +361858,8 @@ async function runNonInteractive(config2, settings, input, prompt_id, options2 =
361690
361858
  const toolResponseParts = [];
361691
361859
  for (const requestInfo of toolCallRequests) {
361692
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;
361693
361863
  const isTaskTool = finalRequestInfo.name === "task";
361694
361864
  const taskToolProgress = isTaskTool ? createTaskToolProgressHandler(
361695
361865
  config2,
@@ -361702,12 +361872,10 @@ async function runNonInteractive(config2, settings, input, prompt_id, options2 =
361702
361872
  finalRequestInfo,
361703
361873
  abortController.signal,
361704
361874
  isTaskTool && taskToolProgressHandler ? {
361705
- outputUpdateHandler: taskToolProgressHandler
361706
- /*
361707
- toolCallUpdateCallback
361708
- ? { onToolCallsUpdate: toolCallUpdateCallback }
361709
- : undefined,
361710
- */
361875
+ outputUpdateHandler: taskToolProgressHandler,
361876
+ onToolCallsUpdate: toolCallUpdateCallback
361877
+ } : toolCallUpdateCallback ? {
361878
+ onToolCallsUpdate: toolCallUpdateCallback
361711
361879
  } : void 0
361712
361880
  );
361713
361881
  if (toolResponse.error) {
@@ -361989,10 +362157,57 @@ var SystemController = class extends BaseController {
361989
362157
  * Registers SDK MCP servers and returns capabilities
361990
362158
  */
361991
362159
  async handleInitialize(payload) {
361992
- if (payload.sdkMcpServers && Array.isArray(payload.sdkMcpServers)) {
361993
- 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)) {
361994
362163
  this.context.sdkMcpServers.add(serverName);
361995
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
+ }
361996
362211
  }
361997
362212
  const capabilities = this.buildControlCapabilities();
361998
362213
  if (this.context.debugMode) {
@@ -362015,29 +362230,12 @@ var SystemController = class extends BaseController {
362015
362230
  buildControlCapabilities() {
362016
362231
  const capabilities = {
362017
362232
  can_handle_can_use_tool: true,
362018
- can_handle_hook_callback: true,
362233
+ can_handle_hook_callback: false,
362019
362234
  can_set_permission_mode: typeof this.context.config.setApprovalMode === "function",
362020
- 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
362021
362238
  };
362022
- try {
362023
- const mcpProvider = this.context.config;
362024
- if (typeof mcpProvider.getMcpServers === "function") {
362025
- const servers = mcpProvider.getMcpServers();
362026
- capabilities["can_handle_mcp_message"] = Boolean(
362027
- servers && Object.keys(servers).length > 0
362028
- );
362029
- } else {
362030
- capabilities["can_handle_mcp_message"] = false;
362031
- }
362032
- } catch (error2) {
362033
- if (this.context.debugMode) {
362034
- console.error(
362035
- "[SystemController] Failed to determine MCP capability:",
362036
- error2
362037
- );
362038
- }
362039
- capabilities["can_handle_mcp_message"] = false;
362040
- }
362041
362239
  return capabilities;
362042
362240
  }
362043
362241
  /**
@@ -362092,27 +362290,377 @@ var SystemController = class extends BaseController {
362092
362290
  /**
362093
362291
  * Handle supported_commands request
362094
362292
  *
362095
- * Returns list of supported control commands
362096
- *
362097
- * Note: This list should match the ControlRequestType enum in
362098
- * packages/sdk/typescript/src/types/controlRequests.ts
362293
+ * Returns list of supported slash commands loaded dynamically
362099
362294
  */
362100
362295
  async handleSupportedCommands() {
362101
- const commands = [
362102
- "initialize",
362103
- "interrupt",
362104
- "set_model",
362105
- "supported_commands",
362106
- "can_use_tool",
362107
- "set_permission_mode",
362108
- "mcp_message",
362109
- "mcp_server_status",
362110
- "hook_callback"
362111
- ];
362296
+ const slashCommands = await this.loadSlashCommandNames();
362112
362297
  return {
362113
362298
  subtype: "supported_commands",
362114
- 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
362115
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
+ }
362116
362664
  }
362117
362665
  };
362118
362666
 
@@ -362124,7 +362672,7 @@ var ControlDispatcher = class {
362124
362672
  context;
362125
362673
  // Make controllers publicly accessible
362126
362674
  systemController;
362127
- // readonly permissionController: PermissionController;
362675
+ permissionController;
362128
362676
  // readonly mcpController: MCPController;
362129
362677
  // readonly hookController: HookController;
362130
362678
  // Central pending request registries
@@ -362137,6 +362685,11 @@ var ControlDispatcher = class {
362137
362685
  this,
362138
362686
  "SystemController"
362139
362687
  );
362688
+ this.permissionController = new PermissionController(
362689
+ context2,
362690
+ this,
362691
+ "PermissionController"
362692
+ );
362140
362693
  this.context.abortSignal.addEventListener("abort", () => {
362141
362694
  this.shutdown();
362142
362695
  });
@@ -362241,6 +362794,7 @@ var ControlDispatcher = class {
362241
362794
  }
362242
362795
  this.pendingOutgoingRequests.clear();
362243
362796
  this.systemController.cleanup();
362797
+ this.permissionController.cleanup();
362244
362798
  }
362245
362799
  /**
362246
362800
  * Registers an incoming request in the pending registry
@@ -362293,9 +362847,9 @@ var ControlDispatcher = class {
362293
362847
  case "set_model":
362294
362848
  case "supported_commands":
362295
362849
  return this.systemController;
362296
- // case 'can_use_tool':
362297
- // case 'set_permission_mode':
362298
- // return this.permissionController;
362850
+ case "can_use_tool":
362851
+ case "set_permission_mode":
362852
+ return this.permissionController;
362299
362853
  // case 'mcp_message':
362300
362854
  // case 'mcp_server_status':
362301
362855
  // return this.mcpController;
@@ -362357,43 +362911,28 @@ var ControlService = class {
362357
362911
  * Handles tool execution permissions, approval checks, and callbacks.
362358
362912
  * Delegates to the shared PermissionController instance.
362359
362913
  */
362360
- // get permission(): PermissionServiceAPI {
362361
- // const controller = this.dispatcher.permissionController;
362362
- // return {
362363
- // /**
362364
- // * Check if a tool should be allowed based on current permission settings
362365
- // *
362366
- // * Evaluates permission mode and tool registry to determine if execution
362367
- // * should proceed. Can optionally modify tool arguments based on confirmation details.
362368
- // *
362369
- // * @param toolRequest - Tool call request information
362370
- // * @param confirmationDetails - Optional confirmation details for UI
362371
- // * @returns Permission decision with optional updated arguments
362372
- // */
362373
- // shouldAllowTool: controller.shouldAllowTool.bind(controller),
362374
- //
362375
- // /**
362376
- // * Build UI suggestions for tool confirmation dialogs
362377
- // *
362378
- // * Creates actionable permission suggestions based on tool confirmation details.
362379
- // *
362380
- // * @param confirmationDetails - Tool confirmation details
362381
- // * @returns Array of permission suggestions or null
362382
- // */
362383
- // buildPermissionSuggestions:
362384
- // controller.buildPermissionSuggestions.bind(controller),
362385
- //
362386
- // /**
362387
- // * Get callback for monitoring tool call status updates
362388
- // *
362389
- // * Returns callback function for integration with CoreToolScheduler.
362390
- // *
362391
- // * @returns Callback function for tool call updates
362392
- // */
362393
- // getToolCallUpdateCallback:
362394
- // controller.getToolCallUpdateCallback.bind(controller),
362395
- // };
362396
- // }
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
+ }
362397
362936
  /**
362398
362937
  * System Domain API
362399
362938
  *
@@ -362571,17 +363110,10 @@ var ConsolePatcher = class {
362571
363110
  };
362572
363111
 
362573
363112
  // packages/cli/src/nonInteractive/session.ts
362574
- var SESSION_STATE = {
362575
- INITIALIZING: "initializing",
362576
- IDLE: "idle",
362577
- PROCESSING_QUERY: "processing_query",
362578
- SHUTTING_DOWN: "shutting_down"
362579
- };
362580
- var SessionManager = class {
363113
+ var Session2 = class {
362581
363114
  static {
362582
- __name(this, "SessionManager");
363115
+ __name(this, "Session");
362583
363116
  }
362584
- state = SESSION_STATE.INITIALIZING;
362585
363117
  userMessageQueue = [];
362586
363118
  abortController;
362587
363119
  config;
@@ -362596,6 +363128,9 @@ var SessionManager = class {
362596
363128
  debugMode;
362597
363129
  shutdownHandler = null;
362598
363130
  initialPrompt = null;
363131
+ processingPromise = null;
363132
+ isShuttingDown = false;
363133
+ configInitialized = false;
362599
363134
  constructor(config2, initialPrompt) {
362600
363135
  this.config = config2;
362601
363136
  this.sessionId = config2.getSessionId();
@@ -362609,106 +363144,25 @@ var SessionManager = class {
362609
363144
  );
362610
363145
  this.setupSignalHandlers();
362611
363146
  }
362612
- /**
362613
- * Get next prompt ID
362614
- */
362615
363147
  getNextPromptId() {
362616
363148
  this.promptIdCounter++;
362617
363149
  return `${this.sessionId}########${this.promptIdCounter}`;
362618
363150
  }
362619
- /**
362620
- * Route a message to the appropriate handler based on its type
362621
- *
362622
- * Classifies incoming messages and routes them to appropriate handlers.
362623
- */
362624
- route(message) {
362625
- if (isControlRequest(message)) {
362626
- return { type: "control_request", message };
362627
- }
362628
- if (isControlResponse(message)) {
362629
- return { type: "control_response", message };
362630
- }
362631
- if (isControlCancel(message)) {
362632
- return { type: "control_cancel", message };
362633
- }
362634
- if (isCLIUserMessage(message)) {
362635
- return { type: "user", message };
362636
- }
362637
- if (isCLIAssistantMessage(message)) {
362638
- return { type: "assistant", message };
362639
- }
362640
- if (isCLISystemMessage(message)) {
362641
- return { type: "system", message };
362642
- }
362643
- if (isCLIResultMessage(message)) {
362644
- return { type: "result", message };
362645
- }
362646
- if (isCLIPartialAssistantMessage(message)) {
362647
- return { type: "stream_event", message };
363151
+ async ensureConfigInitialized() {
363152
+ if (this.configInitialized) {
363153
+ return;
362648
363154
  }
362649
363155
  if (this.debugMode) {
362650
- console.error(
362651
- "[SessionManager] Unknown message type:",
362652
- JSON.stringify(message, null, 2)
362653
- );
363156
+ console.error("[Session] Initializing config");
362654
363157
  }
362655
- return { type: "unknown", message };
362656
- }
362657
- /**
362658
- * Process a single message with unified logic for both initial prompt and stream messages.
362659
- *
362660
- * Handles:
362661
- * - Abort check
362662
- * - First message detection and handling
362663
- * - Normal message processing
362664
- * - Shutdown state checks
362665
- *
362666
- * @param message - Message to process
362667
- * @returns true if the calling code should exit (break/return), false to continue
362668
- */
362669
- async processSingleMessage(message) {
362670
- if (this.abortController.signal.aborted) {
362671
- return true;
362672
- }
362673
- if (this.controlSystemEnabled === null) {
362674
- const handled = await this.handleFirstMessage(message);
362675
- if (handled) {
362676
- return this.state === SESSION_STATE.SHUTTING_DOWN;
362677
- }
362678
- }
362679
- await this.processMessage(message);
362680
- return this.state === SESSION_STATE.SHUTTING_DOWN;
362681
- }
362682
- /**
362683
- * Main entry point - run the session
362684
- */
362685
- async run() {
362686
363158
  try {
362687
- if (this.debugMode) {
362688
- console.error("[SessionManager] Starting session", this.sessionId);
362689
- }
362690
- if (this.initialPrompt !== null) {
362691
- const shouldExit = await this.processSingleMessage(this.initialPrompt);
362692
- if (shouldExit) {
362693
- await this.shutdown();
362694
- return;
362695
- }
362696
- }
362697
- for await (const message of this.inputReader.read()) {
362698
- const shouldExit = await this.processSingleMessage(message);
362699
- if (shouldExit) {
362700
- break;
362701
- }
362702
- }
362703
- await this.shutdown();
363159
+ await this.config.initialize();
363160
+ this.configInitialized = true;
362704
363161
  } catch (error2) {
362705
363162
  if (this.debugMode) {
362706
- console.error("[SessionManager] Error:", error2);
363163
+ console.error("[Session] Failed to initialize config:", error2);
362707
363164
  }
362708
- await this.shutdown();
362709
363165
  throw error2;
362710
- } finally {
362711
- this.cleanupSignalHandlers();
362712
363166
  }
362713
363167
  }
362714
363168
  ensureControlSystem() {
@@ -362739,219 +363193,64 @@ var SessionManager = class {
362739
363193
  return this.dispatcher;
362740
363194
  }
362741
363195
  async handleFirstMessage(message) {
362742
- const routed = this.route(message);
362743
- if (routed.type === "control_request") {
362744
- const request4 = routed.message;
363196
+ if (isControlRequest(message)) {
363197
+ const request4 = message;
362745
363198
  this.controlSystemEnabled = true;
362746
363199
  this.ensureControlSystem();
362747
363200
  if (request4.request.subtype === "initialize") {
362748
363201
  await this.dispatcher?.dispatch(request4);
362749
- this.state = SESSION_STATE.IDLE;
363202
+ await this.ensureConfigInitialized();
362750
363203
  return true;
362751
363204
  }
362752
- return false;
363205
+ if (this.debugMode) {
363206
+ console.error(
363207
+ "[Session] Ignoring non-initialize control request during initialization"
363208
+ );
363209
+ }
363210
+ return true;
362753
363211
  }
362754
- if (routed.type === "user") {
363212
+ if (isCLIUserMessage(message)) {
362755
363213
  this.controlSystemEnabled = false;
362756
- this.state = SESSION_STATE.PROCESSING_QUERY;
362757
- this.userMessageQueue.push(routed.message);
362758
- await this.processUserMessageQueue();
363214
+ await this.ensureConfigInitialized();
363215
+ this.enqueueUserMessage(message);
362759
363216
  return true;
362760
363217
  }
362761
363218
  this.controlSystemEnabled = false;
362762
363219
  return false;
362763
363220
  }
362764
- /**
362765
- * Process a single message from the stream
362766
- */
362767
- async processMessage(message) {
362768
- const routed = this.route(message);
362769
- if (this.debugMode) {
362770
- console.error(
362771
- `[SessionManager] State: ${this.state}, Message type: ${routed.type}`
362772
- );
362773
- }
362774
- switch (this.state) {
362775
- case SESSION_STATE.INITIALIZING:
362776
- await this.handleInitializingState(routed);
362777
- break;
362778
- case SESSION_STATE.IDLE:
362779
- await this.handleIdleState(routed);
362780
- break;
362781
- case SESSION_STATE.PROCESSING_QUERY:
362782
- await this.handleProcessingState(routed);
362783
- break;
362784
- case SESSION_STATE.SHUTTING_DOWN:
362785
- break;
362786
- default: {
362787
- const _exhaustiveCheck = this.state;
362788
- if (this.debugMode) {
362789
- console.error("[SessionManager] Unknown state:", _exhaustiveCheck);
362790
- }
362791
- break;
362792
- }
362793
- }
362794
- }
362795
- /**
362796
- * Handle messages in initializing state
362797
- */
362798
- async handleInitializingState(routed) {
362799
- if (routed.type === "control_request") {
362800
- const request4 = routed.message;
362801
- const dispatcher = this.getDispatcher();
362802
- if (!dispatcher) {
362803
- if (this.debugMode) {
362804
- console.error(
362805
- "[SessionManager] Control request received before control system initialization"
362806
- );
362807
- }
362808
- return;
362809
- }
362810
- if (request4.request.subtype === "initialize") {
362811
- await dispatcher.dispatch(request4);
362812
- this.state = SESSION_STATE.IDLE;
362813
- if (this.debugMode) {
362814
- console.error("[SessionManager] Initialized, transitioning to idle");
362815
- }
362816
- } else {
362817
- if (this.debugMode) {
362818
- console.error(
362819
- "[SessionManager] Ignoring non-initialize control request during initialization"
362820
- );
362821
- }
362822
- }
362823
- } else {
362824
- if (this.debugMode) {
362825
- console.error(
362826
- "[SessionManager] Ignoring non-control message during initialization"
362827
- );
362828
- }
362829
- }
362830
- }
362831
- /**
362832
- * Handle messages in idle state
362833
- */
362834
- async handleIdleState(routed) {
363221
+ async handleControlRequest(request4) {
362835
363222
  const dispatcher = this.getDispatcher();
362836
- if (routed.type === "control_request") {
362837
- if (!dispatcher) {
362838
- if (this.debugMode) {
362839
- console.error("[SessionManager] Ignoring control request (disabled)");
362840
- }
362841
- return;
362842
- }
362843
- const request4 = routed.message;
362844
- await dispatcher.dispatch(request4);
362845
- } else if (routed.type === "control_response") {
362846
- if (!dispatcher) {
362847
- return;
362848
- }
362849
- const response = routed.message;
362850
- dispatcher.handleControlResponse(response);
362851
- } else if (routed.type === "control_cancel") {
362852
- if (!dispatcher) {
362853
- return;
362854
- }
362855
- const cancelRequest = routed.message;
362856
- dispatcher.handleCancel(cancelRequest.request_id);
362857
- } else if (routed.type === "user") {
362858
- const userMessage = routed.message;
362859
- this.userMessageQueue.push(userMessage);
362860
- await this.processUserMessageQueue();
362861
- } else {
363223
+ if (!dispatcher) {
362862
363224
  if (this.debugMode) {
362863
- console.error(
362864
- "[SessionManager] Ignoring message type in idle state:",
362865
- routed.type
362866
- );
363225
+ console.error("[Session] Control system not enabled");
362867
363226
  }
363227
+ return;
362868
363228
  }
363229
+ await dispatcher.dispatch(request4);
362869
363230
  }
362870
- /**
362871
- * Handle messages in processing state
362872
- */
362873
- async handleProcessingState(routed) {
363231
+ handleControlResponse(response) {
362874
363232
  const dispatcher = this.getDispatcher();
362875
- if (routed.type === "control_request") {
362876
- if (!dispatcher) {
362877
- if (this.debugMode) {
362878
- console.error(
362879
- "[SessionManager] Control request ignored during processing (disabled)"
362880
- );
362881
- }
362882
- return;
362883
- }
362884
- const request4 = routed.message;
362885
- await dispatcher.dispatch(request4);
362886
- } else if (routed.type === "control_response") {
362887
- if (!dispatcher) {
362888
- return;
362889
- }
362890
- const response = routed.message;
362891
- dispatcher.handleControlResponse(response);
362892
- } else if (routed.type === "user") {
362893
- const userMessage = routed.message;
362894
- this.userMessageQueue.push(userMessage);
362895
- if (this.debugMode) {
362896
- console.error(
362897
- "[SessionManager] Enqueued user message during processing"
362898
- );
362899
- }
362900
- } else {
362901
- if (this.debugMode) {
362902
- console.error(
362903
- "[SessionManager] Ignoring message type during processing:",
362904
- routed.type
362905
- );
362906
- }
363233
+ if (!dispatcher) {
363234
+ return;
362907
363235
  }
363236
+ dispatcher.handleControlResponse(response);
362908
363237
  }
362909
- /**
362910
- * Process user message queue (FIFO)
362911
- */
362912
- async processUserMessageQueue() {
362913
- while (this.userMessageQueue.length > 0 && !this.abortController.signal.aborted) {
362914
- this.state = SESSION_STATE.PROCESSING_QUERY;
362915
- const userMessage = this.userMessageQueue.shift();
362916
- try {
362917
- await this.processUserMessage(userMessage);
362918
- } catch (error2) {
362919
- if (this.debugMode) {
362920
- console.error(
362921
- "[SessionManager] Error processing user message:",
362922
- error2
362923
- );
362924
- }
362925
- this.emitErrorResult(error2);
362926
- }
362927
- }
362928
- if (!this.abortController.signal.aborted && this.state === SESSION_STATE.PROCESSING_QUERY && this.controlSystemEnabled === false && this.userMessageQueue.length === 0) {
362929
- if (this.debugMode) {
362930
- console.error(
362931
- "[SessionManager] Single-query mode: queue processed, shutting down"
362932
- );
362933
- }
362934
- this.state = SESSION_STATE.SHUTTING_DOWN;
363238
+ handleControlCancel(cancelRequest) {
363239
+ const dispatcher = this.getDispatcher();
363240
+ if (!dispatcher) {
362935
363241
  return;
362936
363242
  }
362937
- if (!this.abortController.signal.aborted && this.state === SESSION_STATE.PROCESSING_QUERY) {
362938
- this.state = SESSION_STATE.IDLE;
362939
- if (this.debugMode) {
362940
- console.error("[SessionManager] Queue processed, returning to idle");
362941
- }
362942
- }
363243
+ dispatcher.handleCancel(cancelRequest.request_id);
362943
363244
  }
362944
- /**
362945
- * Process a single user message
362946
- */
362947
363245
  async processUserMessage(userMessage) {
362948
363246
  const input = extractUserMessageText(userMessage);
362949
363247
  if (!input) {
362950
363248
  if (this.debugMode) {
362951
- console.error("[SessionManager] No text content in user message");
363249
+ console.error("[Session] No text content in user message");
362952
363250
  }
362953
363251
  return;
362954
363252
  }
363253
+ await this.ensureConfigInitialized();
362955
363254
  const promptId = this.getNextPromptId();
362956
363255
  try {
362957
363256
  await runNonInteractive(
@@ -362967,13 +363266,41 @@ var SessionManager = class {
362967
363266
  );
362968
363267
  } catch (error2) {
362969
363268
  if (this.debugMode) {
362970
- console.error("[SessionManager] Query execution error:", error2);
363269
+ console.error("[Session] Query execution error:", error2);
362971
363270
  }
362972
363271
  }
362973
363272
  }
362974
- /**
362975
- * Send tool results as user message
362976
- */
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
+ }
362977
363304
  emitErrorResult(error2, numTurns = 0, durationMs = 0, apiDurationMs = 0) {
362978
363305
  const message = error2 instanceof Error ? error2.message : String(error2);
362979
363306
  this.outputAdapter.emitResult({
@@ -362985,46 +363312,44 @@ var SessionManager = class {
362985
363312
  usage: void 0
362986
363313
  });
362987
363314
  }
362988
- /**
362989
- * Handle interrupt control request
362990
- */
362991
363315
  handleInterrupt() {
362992
363316
  if (this.debugMode) {
362993
- console.error("[SessionManager] Interrupt requested");
362994
- }
362995
- if (this.state === SESSION_STATE.PROCESSING_QUERY) {
362996
- this.abortController.abort();
362997
- this.abortController = new AbortController();
363317
+ console.error("[Session] Interrupt requested");
362998
363318
  }
363319
+ this.abortController.abort();
363320
+ this.abortController = new AbortController();
362999
363321
  }
363000
- /**
363001
- * Setup signal handlers for graceful shutdown
363002
- */
363003
363322
  setupSignalHandlers() {
363004
363323
  this.shutdownHandler = () => {
363005
363324
  if (this.debugMode) {
363006
- console.error("[SessionManager] Shutdown signal received");
363325
+ console.error("[Session] Shutdown signal received");
363007
363326
  }
363327
+ this.isShuttingDown = true;
363008
363328
  this.abortController.abort();
363009
- this.state = SESSION_STATE.SHUTTING_DOWN;
363010
363329
  };
363011
363330
  process.on("SIGINT", this.shutdownHandler);
363012
363331
  process.on("SIGTERM", this.shutdownHandler);
363013
363332
  }
363014
- /**
363015
- * Shutdown session and cleanup resources
363016
- */
363017
363333
  async shutdown() {
363018
363334
  if (this.debugMode) {
363019
- 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
+ }
363020
363349
  }
363021
- this.state = SESSION_STATE.SHUTTING_DOWN;
363022
363350
  this.dispatcher?.shutdown();
363023
363351
  this.cleanupSignalHandlers();
363024
363352
  }
363025
- /**
363026
- * Remove signal handlers to prevent memory leaks
363027
- */
363028
363353
  cleanupSignalHandlers() {
363029
363354
  if (this.shutdownHandler) {
363030
363355
  process.removeListener("SIGINT", this.shutdownHandler);
@@ -363032,6 +363357,81 @@ var SessionManager = class {
363032
363357
  this.shutdownHandler = null;
363033
363358
  }
363034
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
+ }
363035
363435
  };
363036
363436
  function extractUserMessageText(message) {
363037
363437
  const content = message.message.content;
@@ -363072,7 +363472,7 @@ async function runNonInteractiveStreamJson(config2, input) {
363072
363472
  parent_tool_use_id: null
363073
363473
  };
363074
363474
  }
363075
- const manager = new SessionManager(config2, initialPrompt);
363475
+ const manager = new Session2(config2, initialPrompt);
363076
363476
  await manager.run();
363077
363477
  } finally {
363078
363478
  consolePatcher.cleanup();
@@ -383546,7 +383946,7 @@ var AgentSelectionStep = /* @__PURE__ */ __name(({
383546
383946
  return /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { flexDirection: "column", children: [
383547
383947
  projectAgents.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
383548
383948
  /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text3, { color: theme.text.primary, bold: true, children: t3("Project Level ({{path}})", {
383549
- path: projectAgents[0].filePath.replace(/\/[^/]+$/, "")
383949
+ path: projectAgents[0].filePath?.replace(/\/[^/]+$/, "") || ""
383550
383950
  }) }),
383551
383951
  /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: projectAgents.map((agent, index) => {
383552
383952
  const isSelected = navigation.currentBlock === "project" && navigation.projectIndex === index;
@@ -383560,7 +383960,7 @@ var AgentSelectionStep = /* @__PURE__ */ __name(({
383560
383960
  marginBottom: builtinAgents.length > 0 ? 1 : 0,
383561
383961
  children: [
383562
383962
  /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text3, { color: theme.text.primary, bold: true, children: t3("User Level ({{path}})", {
383563
- path: userAgents[0].filePath.replace(/\/[^/]+$/, "")
383963
+ path: userAgents[0].filePath?.replace(/\/[^/]+$/, "") || ""
383564
383964
  }) }),
383565
383965
  /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: userAgents.map((agent, index) => {
383566
383966
  const isSelected = navigation.currentBlock === "user" && navigation.userIndex === index;
@@ -383723,7 +384123,10 @@ function EditOptionsStep({
383723
384123
  setError(null);
383724
384124
  if (selectedValue === "editor") {
383725
384125
  try {
383726
- await launchEditor(selectedAgent?.filePath);
384126
+ if (!selectedAgent.filePath) {
384127
+ throw new Error("Agent has no file path");
384128
+ }
384129
+ await launchEditor(selectedAgent.filePath);
383727
384130
  } catch (err) {
383728
384131
  setError(
383729
384132
  t3("Failed to launch editor: {{error}}", {
@@ -402680,7 +403083,11 @@ function getRdmindSsoId3() {
402680
403083
  }
402681
403084
  }
402682
403085
  __name(getRdmindSsoId3, "getRdmindSsoId");
402683
- function useWebSocket({ onReloadCommands, debug: debug2, sessionId }) {
403086
+ function useWebSocket({
403087
+ onReloadCommands,
403088
+ debug: debug2,
403089
+ sessionId
403090
+ }) {
402684
403091
  const wsClientRef = (0, import_react133.useRef)(null);
402685
403092
  (0, import_react133.useEffect)(() => {
402686
403093
  const wsRuntimeConfig = loadWebSocketRuntimeConfig(debug2);
@@ -405010,7 +405417,7 @@ async function validateNonInteractiveAuth(configuredAuthType, useExternalAuth, n
405010
405417
  throw new Error(message);
405011
405418
  }
405012
405419
  }
405013
- const effectiveAuthType = enforcedType || getAuthTypeFromEnv() || configuredAuthType;
405420
+ const effectiveAuthType = enforcedType || configuredAuthType || getAuthTypeFromEnv();
405014
405421
  if (!effectiveAuthType) {
405015
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`;
405016
405423
  throw new Error(message);
@@ -406704,7 +407111,7 @@ var SubAgentTracker = class {
406704
407111
 
406705
407112
  // packages/cli/src/acp-integration/session/Session.ts
406706
407113
  var ALLOWED_BUILTIN_COMMANDS_FOR_ACP = ["init"];
406707
- var Session2 = class {
407114
+ var Session3 = class {
406708
407115
  constructor(id, chat, config2, client, settings) {
406709
407116
  this.chat = chat;
406710
407117
  this.config = config2;
@@ -407445,7 +407852,7 @@ var GeminiAgent = class {
407445
407852
  name: APPROVAL_MODE_INFO[mode].name,
407446
407853
  description: APPROVAL_MODE_INFO[mode].description
407447
407854
  }));
407448
- const version3 = "0.1.3-alpha.1";
407855
+ const version3 = "0.1.3-alpha.3";
407449
407856
  return {
407450
407857
  protocolVersion: PROTOCOL_VERSION,
407451
407858
  agentInfo: {
@@ -407613,7 +408020,7 @@ var GeminiAgent = class {
407613
408020
  const geminiClient = config2.getGeminiClient();
407614
408021
  const history = conversation ? buildApiHistoryFromConversation(conversation) : void 0;
407615
408022
  const chat = history ? await geminiClient.startChat(history) : await geminiClient.startChat();
407616
- const session = new Session2(
408023
+ const session = new Session3(
407617
408024
  sessionId,
407618
408025
  chat,
407619
408026
  config2,
@@ -407881,7 +408288,11 @@ ${finalArgs[promptIndex + 1]}`;
407881
408288
  kittyProtocolDetectionComplete = detectAndEnableKittyProtocol();
407882
408289
  }
407883
408290
  setMaxSizedBoxDebugging(isDebugMode2);
407884
- 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
+ }
407885
408296
  if (settings.merged.security?.auth?.selectedType === "oauth-personal" /* LOGIN_WITH_GOOGLE */ && config2.isBrowserLaunchSuppressed()) {
407886
408297
  await getOauthClient(settings.merged.security.auth.selectedType, config2);
407887
408298
  }
@@ -407935,8 +408346,9 @@ ${finalArgs[promptIndex + 1]}`;
407935
408346
  );
407936
408347
  return;
407937
408348
  }
407938
- await config2.initialize();
407939
- const inputFormat = typeof config2.getInputFormat === "function" ? config2.getInputFormat() : "text" /* TEXT */;
408349
+ if (inputFormat !== "stream-json" /* STREAM_JSON */) {
408350
+ await config2.initialize();
408351
+ }
407940
408352
  if (inputFormat !== "stream-json" /* STREAM_JSON */ && !process.stdin.isTTY) {
407941
408353
  const stdinData = await readStdin();
407942
408354
  if (stdinData) {
@@ -407946,7 +408358,7 @@ ${input}`;
407946
408358
  }
407947
408359
  }
407948
408360
  const nonInteractiveConfig = await validateNonInteractiveAuth(
407949
- settings.merged.security?.auth?.selectedType,
408361
+ settings.merged.security?.auth?.selectedType || argv.authType,
407950
408362
  settings.merged.security?.auth?.useExternal,
407951
408363
  config2,
407952
408364
  settings