blun-king-cli 9.1.654 → 9.1.656

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/blun.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  // BLUN_BUILD_INPUT_SHA256:e50c78300e52dc6fc7d8003478fe2fa01fe7fdff8b1a749e108e6627de244e7e
3
+ import * as wave3Control from "./telegram-plugin/dist/console-control.mjs";
3
4
  import toolLiveness642 from "./tool-liveness642/index.cjs";
4
5
  /*! wasm-webp 0.1.0
5
6
  MIT License
@@ -5461,6 +5462,31 @@ function parsePattern(pattern) {
5461
5462
  argPattern
5462
5463
  };
5463
5464
  }
5465
+ function wave3NamesFileTool(pattern, target) {
5466
+ const group = /^\^?\((?:\?:)?([^()]+)\)\$?$/u.exec(pattern);
5467
+ const names = (group?.[1] ?? pattern).split('|');
5468
+ return names.every((name)=>/^\^?[A-Za-z][\w]*\$?$/u.test(name)) && names.some((name)=>name.replace(/^\^|\$$/gu, '') === target);
5469
+ }
5470
+ const RESTRICTED_FILE_BATCH_SUBJECTS = new Map([
5471
+ [
5472
+ 'ApplyPatch',
5473
+ [
5474
+ 'Write',
5475
+ 'Edit'
5476
+ ]
5477
+ ],
5478
+ [
5479
+ 'EditBatch',
5480
+ [
5481
+ 'Write',
5482
+ 'Edit',
5483
+ 'ApplyPatch'
5484
+ ]
5485
+ ]
5486
+ ]);
5487
+ function inheritedFileRestrictions(tool) {
5488
+ return RESTRICTED_FILE_BATCH_SUBJECTS.get(tool) ?? [];
5489
+ }
5464
5490
  function matchPermissionRule({ rule, toolName, execution }) {
5465
5491
  let parsed;
5466
5492
  try {
@@ -21194,7 +21220,10 @@ var init_types$20 = __esmMin((() => {}));
21194
21220
  var FLAG_DEFINITIONS;
21195
21221
  var InputControl, controls, CHANNEL_QUEUE_DEADLINE_MS, QueueDeadlineWatchdog, StoppedInputScopes, SEARCH_LIMITS, SearchStop, active, inside, sessionSearchRequests, ActiveInputDelivery;
21196
21222
  var init_registry$4 = __esmMin((() => {
21197
- FLAG_DEFINITIONS = [{ id: "original_history", title: "Original history", description: "Read a captured conversation independently of model context.", env: "BLUN_EXPERIMENTAL_ORIGINAL_HISTORY", default: false, surface: "both" },
21223
+ FLAG_DEFINITIONS = [
21224
+ {"id":"tui_turn_diagnostics","title":"Local turn diagnostics","description":"Show outcome, model timings, retry notices and prompt hook outcomes in the console.","env":"BLUN_EXPERIMENTAL_TUI_TURN_DIAGNOSTICS","default":false,"surface":"tui"},
21225
+ {"id":"telegram_session_control","title":"Telegram session controls","description":"Allow explicitly granted private Telegram session commands.","env":"BLUN_EXPERIMENTAL_TELEGRAM_SESSION_CONTROL","default":false,"surface":"tui"},
21226
+ {"id":"edit_batch","title":"Multi-file text edits","description":"Validate and apply exact text replacements across local workspace files.","env":"BLUN_EXPERIMENTAL_EDIT_BATCH","default":false,"surface":"core"},{ id: "original_history", title: "Original history", description: "Read a captured conversation independently of model context.", env: "BLUN_EXPERIMENTAL_ORIGINAL_HISTORY", default: false, surface: "both" },
21198
21227
  {
21199
21228
  id: "local_auth",
21200
21229
  title: "Local authentication",
@@ -29215,11 +29244,11 @@ var init_load = __esmMin((() => {
29215
29244
  }));
29216
29245
  var agent_default$1;
29217
29246
  var init_agent$3 = __esmMin((() => {
29218
- agent_default$1 = "name: agent\ndescription: Default BLUN King agent\n\nsystemPromptPath: ./system.md\npromptVars:\n roleAdditional: ''\n\ntools:\n - Read\n - ReadBatch\n - ProgrammaticTool\n - Write\n - Edit\n - ApplyPatch\n - Grep\n - Glob\n - Bash\n - TaskList\n - TaskOutput\n - TaskStop\n - TaskUpdate\n - TaskResume\n - CronCreate\n - CronList\n - CronRunList\n - CronRunOutput\n - CronDelete\n - ReadMediaFile\n - TodoList\n - CompactConversation\n - Skill\n - WebSearch\n - Agent\n - AgentSwarm\n - FetchURL\n - GenerateImage\n - GenerateVideo\n - GenerateSpeech\n - GetMedia\n - AskUserQuestion\n - MistakeRecord\n - CodebaseSearch\n - EnterPlanMode\n - ExitPlanMode\n - CreateGoal\n - GetGoal\n - SetGoalBudget\n - UpdateGoal\n - mcp__*\n\nsubagents:\n coder:\n description: General software engineering agent — the only subagent type with file-editing tools; use it for any delegated task that must modify code.\n explore:\n description: Fast codebase exploration with prompt-enforced read-only behavior.\n plan:\n description: Read-only implementation planning and architecture design.\n";
29247
+ agent_default$1 = "name: agent\ndescription: Default BLUN King agent\n\nsystemPromptPath: ./system.md\npromptVars:\n roleAdditional: ''\n\ntools:\n - Read\n - ReadBatch\n - ProgrammaticTool\n - Write\n - Edit\n - ApplyPatch\n - EditBatch\n - Grep\n - Glob\n - Bash\n - TaskList\n - TaskOutput\n - TaskStop\n - TaskUpdate\n - TaskResume\n - CronCreate\n - CronList\n - CronRunList\n - CronRunOutput\n - CronDelete\n - ReadMediaFile\n - TodoList\n - CompactConversation\n - Skill\n - WebSearch\n - Agent\n - AgentSwarm\n - FetchURL\n - GenerateImage\n - GenerateVideo\n - GenerateSpeech\n - GetMedia\n - AskUserQuestion\n - MistakeRecord\n - CodebaseSearch\n - EnterPlanMode\n - ExitPlanMode\n - CreateGoal\n - GetGoal\n - SetGoalBudget\n - UpdateGoal\n - mcp__*\n\nsubagents:\n coder:\n description: General software engineering agent — the only subagent type with file-editing tools; use it for any delegated task that must modify code.\n explore:\n description: Fast codebase exploration with prompt-enforced read-only behavior.\n plan:\n description: Read-only implementation planning and architecture design.\n";
29219
29248
  }));
29220
29249
  var coder_default;
29221
29250
  var init_coder = __esmMin((() => {
29222
- coder_default = "extends: agent\nname: coder\npromptVars:\n roleAdditional: |\n You are now running as a subagent. All the `user` messages are sent by the main agent. The main agent cannot see your context, it can only see your last message when you finish the task. You must treat the parent agent as your caller. Do not directly ask the end user questions. If something is unclear, explain the ambiguity in your final summary to the parent agent.\n\n Your final message is the entire handoff — the parent sees nothing else from your run. Make it technically complete: what you changed and why, the path of every file you touched, how you verified the change (tests or commands run, with results), and anything left undone or worth follow-up. A final message of only a sentence or two is treated as too brief and sent back to you for expansion, costing an extra turn.\nwhenToUse: |\n Use this agent for non-trivial software engineering work that may require reading files, editing code, running commands, and returning a compact but technically complete summary to the parent agent.\ntools:\n - Bash\n - Read\n - ReadBatch\n - ProgrammaticTool\n - ReadMediaFile\n - Glob\n - Grep\n - Write\n - Edit\n - ApplyPatch\n - MistakeRecord\n - WebSearch\n - FetchURL\n - mcp__*\n";
29251
+ coder_default = "extends: agent\nname: coder\npromptVars:\n roleAdditional: |\n You are now running as a subagent. All the `user` messages are sent by the main agent. The main agent cannot see your context, it can only see your last message when you finish the task. You must treat the parent agent as your caller. Do not directly ask the end user questions. If something is unclear, explain the ambiguity in your final summary to the parent agent.\n\n Your final message is the entire handoff — the parent sees nothing else from your run. Make it technically complete: what you changed and why, the path of every file you touched, how you verified the change (tests or commands run, with results), and anything left undone or worth follow-up. A final message of only a sentence or two is treated as too brief and sent back to you for expansion, costing an extra turn.\nwhenToUse: |\n Use this agent for non-trivial software engineering work that may require reading files, editing code, running commands, and returning a compact but technically complete summary to the parent agent.\ntools:\n - Bash\n - Read\n - ReadBatch\n - ProgrammaticTool\n - ReadMediaFile\n - Glob\n - Grep\n - Write\n - Edit\n - ApplyPatch\n - EditBatch\n - MistakeRecord\n - WebSearch\n - FetchURL\n - mcp__*\n";
29223
29252
  }));
29224
29253
  var explore_default;
29225
29254
  var init_explore = __esmMin((() => {
@@ -183578,6 +183607,7 @@ var init_subagent_batch = __esmMin((() => {
183578
183607
  description: task.description,
183579
183608
  swarmIndex: task.swarmIndex,
183580
183609
  runInBackground: task.runInBackground,
183610
+ foregroundTaskId: task.foregroundTaskId,
183581
183611
  signal: attempt.controller.signal,
183582
183612
  onReady: () => {
183583
183613
  this.markAttemptReady(attempt);
@@ -184261,13 +184291,32 @@ admissionClosed = false;
184261
184291
  if (profile === void 0) throw new Error(`Subagent profile "${profileName}" was not found`);
184262
184292
  return profile;
184263
184293
  }
184264
- runWithActiveChild(childId, options, run) {
184294
+ *foregroundClientToolWaits(parent, turnId, step) {
184295
+ for (const [childId, active] of this.activeChildren) {
184296
+ if (active.controller.signal.aborted) continue;
184297
+ const scope = active.foregroundScope;
184298
+ if (scope?.parent !== parent || scope.turnId !== turnId || scope.step !== step) continue;
184299
+ if (scope.taskId === undefined) {
184300
+ if (active.runInBackground) continue;
184301
+ } else {
184302
+ const task = parent.background.getTask(scope.taskId);
184303
+ if (task?.status !== "running" || task.detached !== false ||
184304
+ String(task.swarm?.turnId) !== String(turnId) || task.swarm?.toolCallId !== active.parentToolCallId) continue;
184305
+ }
184306
+ const count = this.session.getReadyAgent(childId)?.tools.clientToolWait?.count ?? 0;
184307
+ if (count > 0) yield { toolCallId: active.parentToolCallId, count };
184308
+ }
184309
+ }
184310
+ runWithActiveChild(childId, options, run) {
184265
184311
  this.assertAdmissionOpen();
184266
184312
  this.assertInputLease(options);
184267
184313
  if (this.activeChildren.has(childId)) throw new Error(`Agent instance "${childId}" is already running`);
184268
184314
  const controller = new AbortController();
184269
184315
  const unlinkAbortSignal = linkAbortSignal(options.signal, controller);
184270
- const active = {
184316
+ const parent = this.session.getReadyAgent(this.ownerAgentId);
184317
+ const step = parent?.turn.activeModelStep;
184318
+ const active = {
184319
+ foregroundScope: step > 0 ? { parent, step, turnId: parent.turn.currentId, taskId: options.foregroundTaskId } : undefined,
184271
184320
  controller,
184272
184321
  parentToolCallId: options.parentToolCallId,
184273
184322
  runInBackground: options.runInBackground
@@ -234394,9 +234443,13 @@ var init_context$3 = __esmMin((() => {
234394
234443
  return true;
234395
234444
  }
234396
234445
  data() {
234446
+ const { lastTurnEndReason } = this.agent;
234447
+ const { clientToolWait } = this.agent.tools;
234397
234448
  return {
234398
234449
  history: this.history,
234399
- tokenCount: this.tokenCount
234450
+ tokenCount: this.tokenCount,
234451
+ ...(lastTurnEndReason === undefined ? {} : { lastTurnEndReason }),
234452
+ ...(clientToolWait === undefined ? {} : { clientToolWait })
234400
234453
  };
234401
234454
  }
234402
234455
  resumeState() {
@@ -235435,7 +235488,7 @@ var init_engine = __esmMin((() => {
235435
235488
  return results;
235436
235489
  }
235437
235490
  hasUncoveredMatcher(event, target, previousTargets) {
235438
- const covered = new Set(this.matchingHooks(event, target));
235491
+ const covered = new Set(this.matchingHooks(event, target).filter(hook => wave3NamesFileTool(hook.matcher ?? "", target)));
235439
235492
  return previousTargets.some(previous => this.matchingHooks(event, previous).some(hook => !covered.has(hook)));
235440
235493
  }
235441
235494
  matchingHooks(event, matcherValue) {
@@ -239712,7 +239765,7 @@ var init_plan_mode_guard_deny = __esmMin((() => {
239712
239765
  evaluate(context) {
239713
239766
  if (!this.agent.planMode.isActive) return;
239714
239767
  const toolName = context.toolCall.name;
239715
- if (toolName === "ApplyPatch") return { kind: "deny", message: "ApplyPatch is not available in plan mode. Call ExitPlanMode before patching files." };
239768
+ if (toolName === "ApplyPatch" || toolName === "EditBatch") return { kind: "deny", message: `${toolName} is not available in plan mode. Call ExitPlanMode before patching files.` };
239716
239769
  if (toolName === "Write" || toolName === "Edit") {
239717
239770
  const planFilePath = this.agent.planMode.planFilePath;
239718
239771
  if (planFilePath === null) return {
@@ -239856,7 +239909,7 @@ var init_user_configured_rules = __esmMin((() => {
239856
239909
  firstMatchingRule(context, decision) {
239857
239910
  const rules = this.agent.permission.data().rules.filter((rule) => USER_CONFIGURED_SCOPES.has(rule.scope));
239858
239911
  const name = context.toolCall.name;
239859
- const subjects = name === "ApplyPatch" && decision !== "allow" ? [name, "Edit", "Write"] : [name];
239912
+ const subjects = decision !== "allow" ? [name, ...inheritedFileRestrictions(name)] : [name];
239860
239913
  for (const rule of rules) {
239861
239914
  if (rule.decision !== decision) continue;
239862
239915
  for (const toolName of subjects) {
@@ -240023,10 +240076,12 @@ var init_permission = __esmMin((() => {
240023
240076
  }
240024
240077
  async prepareToolCall(context) {
240025
240078
  context.signal.throwIfAborted();
240026
- if (context.toolCall.name === "ApplyPatch" && this.agent.hooks !== void 0) {
240079
+ const batchName = context.toolCall.name;
240080
+ const inherited = inheritedFileRestrictions(batchName);
240081
+ if (inherited.length > 0 && this.agent.hooks !== void 0) {
240027
240082
  for (const event of ["PreToolUse", "PermissionRequest"]) {
240028
- if (this.agent.hooks.hasUncoveredMatcher(event, "ApplyPatch", ["Edit", "Write"])) return {
240029
- block: true, reason: `ApplyPatch is not covered by an existing ${event} hook for Write or Edit. Use Write or Edit, or review the hook configuration.`
240083
+ if (this.agent.hooks.hasUncoveredMatcher(event, batchName, inherited)) return {
240084
+ block: true, reason: `${batchName} is not covered by an existing ${event} hook for ${inherited.join(" or ")}. Use Write or Edit, or review the hook configuration.`
240030
240085
  };
240031
240086
  }
240032
240087
  }
@@ -258343,7 +258398,7 @@ var init_agent_swarm = __esmMin((() => {
258343
258398
  }),
258344
258399
  start: async (sink) => {
258345
258400
  // The manager owns cancellation for the whole batch, including slots not yet launched.
258346
- const managed = tasks.map((task) => ({ ...task, runInBackground: true, signal: sink.signal }));
258401
+ const managed = tasks.map((task) => ({ ...task, runInBackground: true, signal: sink.signal, foregroundTaskId: detached ? undefined : taskId }));
258347
258402
  const result = await this.runSwarm(managed);
258348
258403
  sink.signal.throwIfAborted();
258349
258404
  outcomes = result.map(({ status }) => status);
@@ -259348,6 +259403,546 @@ const ApplyPatchTool = (() => {
259348
259403
  return ApplyPatchTool;
259349
259404
  })();
259350
259405
  // END WAVE 1 APPLY PATCH
259406
+ import { constants as batchConstants } from "node:fs";
259407
+ import { createHash as batchHash } from "node:crypto";
259408
+ let editBatchToolClass;
259409
+ function createEditBatchTool(kaos, workspace) {
259410
+ editBatchToolClass ??= (() => {
259411
+ const constants = batchConstants, createHash = batchHash;
259412
+ const { link, lstat, mkdir, mkdtemp, open, realpath, rename, rmdir, unlink } = wavePatchFs;
259413
+ const { dirname, isAbsolute, join, parse, relative } = wavePatchPath;
259414
+ const z = { array, string, boolean: boolean$1, strictObject: (shape) => object$1(shape).strict() };
259415
+ class ExactEditError extends Error {
259416
+ editNumber;
259417
+ constructor(editNumber, message){
259418
+ super(message), this.editNumber = editNumber;
259419
+ }
259420
+ }
259421
+ function planReplacements(content, path, edits) {
259422
+ const matches = [];
259423
+ for (const [index, { old_string: before, new_string: replacement, replace_all: all }] of edits.entries()){
259424
+ const editNumber = index + 1;
259425
+ if (!before) throw new ExactEditError(editNumber, 'old_string must not be empty.');
259426
+ let count = 0;
259427
+ for(let start = content.indexOf(before); start !== -1; start = content.indexOf(before, start + before.length)){
259428
+ count++;
259429
+ if (all || count === 1) matches.push({
259430
+ start,
259431
+ end: start + before.length,
259432
+ replacement,
259433
+ editNumber
259434
+ });
259435
+ }
259436
+ if (count === 0) {
259437
+ throw new ExactEditError(editNumber, `old_string not found in ${path}, the file contents may be out of date. Please use the Read Tool to reload the content.`);
259438
+ }
259439
+ if (!all && count > 1) {
259440
+ throw new ExactEditError(editNumber, `old_string is not unique in ${path} (found ${String(count)} occurrences). ` + 'To replace every occurrence, set replace_all=true. To replace only one occurrence, include more surrounding context in old_string.');
259441
+ }
259442
+ }
259443
+ matches.sort((a, b)=>a.start - b.start);
259444
+ let previousEnd = 0;
259445
+ for (const match of matches){
259446
+ if (match.start < previousEnd) throw new ExactEditError(match.editNumber, `Multiple edits overlap in ${path}. No file was changed.`);
259447
+ previousEnd = match.end;
259448
+ }
259449
+ return matches;
259450
+ }
259451
+ function applyReplacements(content, matches) {
259452
+ const output = [];
259453
+ let position = 0;
259454
+ for (const { start, end, replacement } of matches){
259455
+ output.push(content.slice(position, start), replacement);
259456
+ position = end;
259457
+ }
259458
+ output.push(content.slice(position));
259459
+ return output.join('');
259460
+ }
259461
+ function replaceExactText(raw, path, edits) {
259462
+ const modelView = toModelTextView(raw);
259463
+ const matches = planReplacements(modelView.text, path, edits);
259464
+ const text = materializeModelText(applyReplacements(modelView.text, matches), modelView.lineEndingStyle);
259465
+ return {
259466
+ text,
259467
+ count: matches.length
259468
+ };
259469
+ }
259470
+ function assertUniqueBatchPaths(paths) {
259471
+ const seen = new Set();
259472
+ const keys = paths.map((path)=>path.replaceAll('\\', '/').toLowerCase());
259473
+ for (const key of keys){
259474
+ if (seen.has(key)) throw new Error('Patch names the same file more than once.');
259475
+ seen.add(key);
259476
+ }
259477
+ for (const key of keys){
259478
+ for(let at = key.lastIndexOf('/'); at > 0; at = key.lastIndexOf('/', at - 1)){
259479
+ if (seen.has(key.slice(0, at))) throw new Error('Patch file targets overlap.');
259480
+ }
259481
+ }
259482
+ }
259483
+ async function commitPatchPlan(changes, apply, signal) {
259484
+ const undoStack = [];
259485
+ try {
259486
+ for (const change of changes){
259487
+ signal.throwIfAborted();
259488
+ await apply(change, (undo)=>undoStack.push(undo));
259489
+ }
259490
+ signal.throwIfAborted();
259491
+ } catch (cause) {
259492
+ const failures = [];
259493
+ for (const undo of undoStack.reverse()){
259494
+ try {
259495
+ await undo();
259496
+ } catch (error) {
259497
+ failures.push(error);
259498
+ }
259499
+ }
259500
+ if (failures.length !== 0) {
259501
+ throw new AggregateError(failures, 'Patch failed and could not be fully rolled back.', {
259502
+ cause
259503
+ });
259504
+ }
259505
+ throw cause;
259506
+ }
259507
+ }
259508
+ function unsafeDirectory() {
259509
+ return new Error('Patch parent must be a regular directory without path aliases.');
259510
+ }
259511
+ function changedFile() {
259512
+ return new Error('A patch target changed during validation. Retry with the current file.');
259513
+ }
259514
+ function assertPatchPathSpelling(path) {
259515
+ if (process.platform !== 'win32') return;
259516
+ const verbatim = /^(?:[/\\]{2}[?.][/\\]|[a-z]:[^/\\])/i;
259517
+ const reserved = /^(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|COM[0-9\u00b9\u00b2\u00b3]|LPT[0-9\u00b9\u00b2\u00b3])(?:\.|$)/i;
259518
+ if (verbatim.test(path) || path.slice(parse(path).root.length).split(/[/\\]+/).some((part)=>part !== '' && part !== '.' && part !== '..' && (/[<>:"|?*\x00-\x1f]/.test(part) || /[. ]$/.test(part) || reserved.test(part)))) throw new Error('Unsupported Windows path spelling for a patch target.');
259519
+ }
259520
+ async function statPatchPath(path) {
259521
+ try {
259522
+ return await lstat(path, {
259523
+ bigint: true
259524
+ });
259525
+ } catch (error) {
259526
+ if (error.code !== 'ENOENT') throw error;
259527
+ return undefined;
259528
+ }
259529
+ }
259530
+ async function inspectPatchDirectory(path) {
259531
+ const missing = [];
259532
+ for(let directory = path;; directory = dirname(directory)){
259533
+ const stat = await statPatchPath(directory);
259534
+ if (stat !== undefined) {
259535
+ if (!stat.isDirectory() || relative(directory, await realpath(directory)) !== '') throw unsafeDirectory();
259536
+ return {
259537
+ path: directory,
259538
+ stat,
259539
+ missing: missing.reverse()
259540
+ };
259541
+ }
259542
+ if (dirname(directory) === directory) throw unsafeDirectory();
259543
+ missing.push(directory);
259544
+ }
259545
+ }
259546
+ async function assertPatchDirectory(directory) {
259547
+ const current = await statPatchPath(directory.path);
259548
+ if (current === undefined || !current.isDirectory() || !samePatchFile(directory.stat, current) || relative(directory.path, await realpath(directory.path)) !== '') throw unsafeDirectory();
259549
+ }
259550
+ function samePatchFile(left, right) {
259551
+ return left.ino === right.ino && left.dev === right.dev;
259552
+ }
259553
+ function samePatchFileVersion(left, right) {
259554
+ return samePatchFile(left, right) && left.nlink === right.nlink && left.mode === right.mode && left.ctimeNs === right.ctimeNs && left.mtimeNs === right.mtimeNs && left.size === right.size;
259555
+ }
259556
+ async function inspectLocalPatchFile(path, signal) {
259557
+ signal.throwIfAborted();
259558
+ if (!isAbsolute(path)) throw new Error('Patch validation requires a resolved file path.');
259559
+ assertPatchPathSpelling(path);
259560
+ const directory = await inspectPatchDirectory(dirname(path));
259561
+ if (directory.missing.length !== 0) return undefined;
259562
+ const expected = await statPatchPath(path);
259563
+ if (expected === undefined) return undefined;
259564
+ if (!expected.isFile() || expected.nlink !== 1n || relative(path, await realpath(path)) !== '') {
259565
+ throw new Error('Patch target must be an unlinked regular file without path aliases.');
259566
+ }
259567
+ signal.throwIfAborted();
259568
+ const handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
259569
+ try {
259570
+ const opened = await handle.stat({
259571
+ bigint: true
259572
+ });
259573
+ await assertPatchDirectory(directory);
259574
+ if (!opened.isFile() || !samePatchFileVersion(opened, expected)) throw changedFile();
259575
+ const bytes = Buffer.allocUnsafe(Number(expected.size));
259576
+ let length = 0;
259577
+ while(length < bytes.length){
259578
+ signal.throwIfAborted();
259579
+ const { bytesRead } = await handle.read(bytes, length, bytes.length - length, length);
259580
+ if (bytesRead === 0) break;
259581
+ length += bytesRead;
259582
+ }
259583
+ const finished = await handle.stat({
259584
+ bigint: true
259585
+ });
259586
+ const current = await statPatchPath(path);
259587
+ await assertPatchDirectory(directory);
259588
+ signal.throwIfAborted();
259589
+ if (length !== bytes.length || current === undefined || !samePatchFileVersion(finished, expected) || !samePatchFileVersion(current, expected)) throw changedFile();
259590
+ let text;
259591
+ try {
259592
+ text = new TextDecoder('utf-8', {
259593
+ fatal: true,
259594
+ ignoreBOM: true
259595
+ }).decode(bytes);
259596
+ } catch {
259597
+ throw new Error('Patch target must contain UTF-8 text.');
259598
+ }
259599
+ if (text.includes('\0')) throw new Error('Patch target must contain UTF-8 text.');
259600
+ return {
259601
+ text,
259602
+ stat: expected
259603
+ };
259604
+ } finally{
259605
+ await handle.close();
259606
+ }
259607
+ }
259608
+ function changed() {
259609
+ return new Error('A patch target changed or became unavailable.');
259610
+ }
259611
+ async function requireFile(path, expected, links) {
259612
+ const stat = await statPatchPath(path);
259613
+ if (stat === undefined || !stat.isFile() || stat.nlink !== links || !samePatchFile(expected, stat)) {
259614
+ throw changed();
259615
+ }
259616
+ return stat;
259617
+ }
259618
+ async function requireVersion(path, expected) {
259619
+ if (!samePatchFileVersion(await requireFile(path, expected, 1n), expected)) throw changed();
259620
+ }
259621
+ async function parentFor(path, onRollback) {
259622
+ let parent = await inspectPatchDirectory(dirname(path));
259623
+ const missing = parent.missing;
259624
+ if (onRollback === undefined && missing.length !== 0) throw changed();
259625
+ for (const child of missing){
259626
+ await assertPatchDirectory(parent);
259627
+ await mkdir(child);
259628
+ const created = await inspectPatchDirectory(child);
259629
+ onRollback(()=>removeDirectory(created));
259630
+ parent = created;
259631
+ }
259632
+ await assertPatchDirectory(parent);
259633
+ return parent;
259634
+ }
259635
+ async function removeDirectory(directory) {
259636
+ await assertPatchDirectory(directory);
259637
+ await rmdir(directory.path);
259638
+ }
259639
+ async function writeThroughHandle(file, text) {
259640
+ const bytes = Buffer.from(text, 'utf8');
259641
+ let offset = 0;
259642
+ while(offset < bytes.length){
259643
+ const { bytesWritten } = await file.write(bytes, offset, bytes.length - offset, offset);
259644
+ if (bytesWritten === 0) throw new Error('Patch file write did not advance.');
259645
+ offset += bytesWritten;
259646
+ }
259647
+ await file.truncate(bytes.length);
259648
+ await file.sync();
259649
+ }
259650
+ async function createFile(path, text, onRollback, signal) {
259651
+ const parent = await parentFor(path, onRollback);
259652
+ signal.throwIfAborted();
259653
+ const file = await open(path, 'wx', 0o666);
259654
+ let created;
259655
+ onRollback(async ()=>{
259656
+ if (created === undefined) throw changed();
259657
+ await assertPatchDirectory(parent);
259658
+ await requireVersion(path, created);
259659
+ await unlink(path);
259660
+ });
259661
+ try {
259662
+ created = await file.stat({
259663
+ bigint: true
259664
+ });
259665
+ await assertPatchDirectory(parent);
259666
+ await requireVersion(path, created);
259667
+ signal.throwIfAborted();
259668
+ try {
259669
+ await writeThroughHandle(file, text);
259670
+ } finally{
259671
+ created = await file.stat({
259672
+ bigint: true
259673
+ });
259674
+ }
259675
+ } finally{
259676
+ await file.close();
259677
+ }
259678
+ }
259679
+ async function updateFile(path, parent, original, text, onRollback, signal) {
259680
+ const flags = constants.O_WRONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
259681
+ const withFile = async (expected, write)=>{
259682
+ await assertPatchDirectory(parent);
259683
+ await requireVersion(path, expected);
259684
+ const file = await open(path, flags);
259685
+ try {
259686
+ if (!samePatchFileVersion(expected, await file.stat({
259687
+ bigint: true
259688
+ }))) throw changed();
259689
+ await assertPatchDirectory(parent);
259690
+ await requireVersion(path, expected);
259691
+ await write(file);
259692
+ } finally{
259693
+ await file.close();
259694
+ }
259695
+ };
259696
+ await withFile(original.stat, async (file)=>{
259697
+ signal.throwIfAborted();
259698
+ let writtenVersion;
259699
+ onRollback(async ()=>{
259700
+ if (writtenVersion === undefined) throw changed();
259701
+ await withFile(writtenVersion, (restored)=>writeThroughHandle(restored, original.text));
259702
+ });
259703
+ try {
259704
+ await writeThroughHandle(file, text);
259705
+ } finally{
259706
+ writtenVersion = await file.stat({
259707
+ bigint: true
259708
+ });
259709
+ }
259710
+ });
259711
+ }
259712
+ async function moveFile(change, parent, onRollback, signal) {
259713
+ const { path, to, original } = change;
259714
+ const destination = await parentFor(to, onRollback);
259715
+ await assertPatchDirectory(parent);
259716
+ await requireVersion(path, original.stat);
259717
+ signal.throwIfAborted();
259718
+ await link(path, to);
259719
+ let moved = false;
259720
+ onRollback(async ()=>{
259721
+ await assertPatchDirectory(parent);
259722
+ await assertPatchDirectory(destination);
259723
+ const links = moved ? 1n : 2n;
259724
+ await requireFile(to, original.stat, links);
259725
+ if (moved) await link(to, path);
259726
+ await requireFile(path, original.stat, 2n);
259727
+ await requireFile(to, original.stat, 2n);
259728
+ await unlink(to);
259729
+ });
259730
+ await requireFile(to, original.stat, 2n);
259731
+ await assertPatchDirectory(parent);
259732
+ await requireFile(path, original.stat, 2n);
259733
+ signal.throwIfAborted();
259734
+ await unlink(path);
259735
+ moved = true;
259736
+ if (change.text !== original.text) {
259737
+ const stat = await requireFile(to, original.stat, 1n);
259738
+ if (stat.mtimeNs !== original.stat.mtimeNs || stat.size !== original.stat.size) throw changed();
259739
+ await updateFile(to, destination, {
259740
+ ...original,
259741
+ stat
259742
+ }, change.text, onRollback, signal);
259743
+ }
259744
+ }
259745
+ async function stageDeletion(path, parent, original, onRollback, onSuccess, signal) {
259746
+ await requireVersion(path, original.stat);
259747
+ signal.throwIfAborted();
259748
+ const stage = await inspectPatchDirectory(await mkdtemp(join(parent.path, '.blun-patch-')));
259749
+ onRollback(()=>removeDirectory(stage));
259750
+ const saved = join(stage.path, 'original');
259751
+ await assertPatchDirectory(parent);
259752
+ await assertPatchDirectory(stage);
259753
+ await requireVersion(path, original.stat);
259754
+ signal.throwIfAborted();
259755
+ await rename(path, saved);
259756
+ onRollback(async ()=>{
259757
+ await assertPatchDirectory(parent);
259758
+ await assertPatchDirectory(stage);
259759
+ await requireFile(saved, original.stat, 1n);
259760
+ await link(saved, path);
259761
+ await requireFile(path, original.stat, 2n);
259762
+ await requireFile(saved, original.stat, 2n);
259763
+ await unlink(saved);
259764
+ });
259765
+ const stored = await requireFile(saved, original.stat, 1n);
259766
+ onSuccess(async ()=>{
259767
+ await assertPatchDirectory(stage);
259768
+ await requireVersion(saved, stored);
259769
+ await unlink(saved);
259770
+ await removeDirectory(stage);
259771
+ });
259772
+ }
259773
+ async function commitLocalPatch(changes, signal) {
259774
+ if (changes.some((change)=>'text' in change && change.text.includes('\0'))) {
259775
+ throw new Error('Patch content must be UTF-8 text.');
259776
+ }
259777
+ const cleanups = [];
259778
+ await commitPatchPlan(changes, async (change, onRollback)=>{
259779
+ if (change.kind === 'add') return createFile(change.path, change.text, onRollback, signal);
259780
+ const parent = await parentFor(change.path);
259781
+ if (change.kind === 'move') return moveFile(change, parent, onRollback, signal);
259782
+ if (change.kind === 'delete') {
259783
+ return stageDeletion(change.path, parent, change.original, onRollback, (cleanup)=>cleanups.push(cleanup), signal);
259784
+ }
259785
+ return updateFile(change.path, parent, change.original, change.text, onRollback, signal);
259786
+ }, signal);
259787
+ const results = await Promise.allSettled(cleanups.map((cleanup)=>cleanup()));
259788
+ return {
259789
+ cleanupFailed: results.some((result)=>result.status === 'rejected')
259790
+ };
259791
+ }
259792
+ function resolveLocalBatchPath(raw, kaos, workspace) {
259793
+ if (/[\x00-\x1f\x7f\u202a-\u202e\u2066-\u2069]/.test(raw)) {
259794
+ throw new Error('A patch path contains unsupported control characters.');
259795
+ }
259796
+ assertPatchPathSpelling(raw);
259797
+ const path = resolvePathAccessPath(raw, {
259798
+ kaos,
259799
+ workspace,
259800
+ operation: 'write'
259801
+ });
259802
+ assertPatchPathSpelling(path);
259803
+ if (!isWithinWorkspace(path, workspace, kaos.pathClass())) {
259804
+ throw new Error('Every patch target must be inside the workspace.');
259805
+ }
259806
+ return path;
259807
+ }
259808
+ function localBatchAccess(name, targets, subject, kaos, workspace) {
259809
+ const options = {
259810
+ cwd: workspace.workspaceDir,
259811
+ pathClass: kaos.pathClass(),
259812
+ homeDir: kaos.gethome()
259813
+ };
259814
+ const matchesTargets = (pattern, any)=>{
259815
+ if (pattern.startsWith('batch:')) return pattern === subject;
259816
+ const matches = (path)=>matchesPathRuleSubject(pattern, path, options);
259817
+ return any ? targets.some(matches) : targets.every(matches);
259818
+ };
259819
+ return {
259820
+ accesses: targets.flatMap(ToolAccesses.readWriteFile),
259821
+ approvalRule: literalRulePattern(name, subject),
259822
+ matchesRule: (pattern, decision)=>matchesTargets(pattern, decision !== "allow")
259823
+ };
259824
+ }
259825
+ const InputSchema = z.strictObject({
259826
+ edits: z.array(z.strictObject({
259827
+ path: z.string().min(1).describe('An existing UTF-8 file inside the local workspace.'),
259828
+ edits: z.array(z.strictObject({
259829
+ oldText: z.string().min(1).describe('Exact text from Read, without the line numbers.'),
259830
+ newText: z.string().describe('Replacement text. Use LF for files shown with normalized CRLF endings.'),
259831
+ replaceAll: z.boolean().optional().describe('Replace all occurrences. Otherwise the match must be unique.')
259832
+ })).min(1).describe('Non-overlapping matches against the original contents of this file.')
259833
+ })).min(1).max(25).describe('Group replacements by file and name each target once.')
259834
+ });
259835
+ function fileFailure(error) {
259836
+ if (error instanceof PathSecurityError) {
259837
+ if (error.code === 'PATH_SENSITIVE') return 'Sensitive file access is blocked.';
259838
+ if (error.code === 'PATH_OUTSIDE_WORKSPACE') return 'Every target must be inside the workspace.';
259839
+ return 'Invalid file path.';
259840
+ }
259841
+ const code = error?.code;
259842
+ if (typeof code === 'string' && /^E[A-Z0-9_]+$/.test(code)) return `Could not access or modify a file (${code}).`;
259843
+ return error instanceof Error ? error.message : 'Could not edit the file.';
259844
+ }
259845
+ function quotePath(path) {
259846
+ return JSON.stringify(path).replace(/[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, (character)=>'\\u' + character.charCodeAt(0).toString(16).padStart(4, '0'));
259847
+ }
259848
+ function exceedsLineHint(text) {
259849
+ let lines = text.length > 0 && !/[\r\n]$/.test(text) ? 1 : 0;
259850
+ for (const _ of text.matchAll(/\r\n|[\r\n]/g)){
259851
+ if (++lines > 500) return true;
259852
+ }
259853
+ return false;
259854
+ }
259855
+ class EditBatchTool {
259856
+ kaos;
259857
+ workspace;
259858
+ name = 'EditBatch';
259859
+ description = 'Make exact text replacements across up to 25 existing local workspace files in one operation. ' + 'Read the files first. Every match is checked against the original contents before writing anything. ' + 'Failures or stops roll back applied changes; incomplete rollback is reported. Use Edit for one file, or ApplyPatch to add, move, or delete files.';
259860
+ parameters = toInputJsonSchema(InputSchema);
259861
+ constructor(kaos, workspace){
259862
+ this.kaos = kaos;
259863
+ this.workspace = workspace;
259864
+ }
259865
+ resolveExecution(args) {
259866
+ const files = args.edits.map((file)=>{
259867
+ const displayPath = quotePath(file.path);
259868
+ try {
259869
+ return {
259870
+ ...file,
259871
+ path: resolveLocalBatchPath(file.path, this.kaos, this.workspace),
259872
+ displayPath
259873
+ };
259874
+ } catch (error) {
259875
+ throw new Error(`${displayPath}: ${fileFailure(error)}`, {
259876
+ cause: error
259877
+ });
259878
+ }
259879
+ });
259880
+ const targets = files.map((file)=>file.path);
259881
+ assertUniqueBatchPaths(targets);
259882
+ const subject = 'batch:' + createHash('sha256').update(JSON.stringify(targets)).digest('hex');
259883
+ const summary = `Edit text in ${files.length} file(s)`;
259884
+ return {
259885
+ ...localBatchAccess(this.name, targets, subject, this.kaos, this.workspace),
259886
+ description: summary,
259887
+ display: {
259888
+ kind: 'generic',
259889
+ summary,
259890
+ detail: files.map(({ path, edits })=>`${quotePath(path)} (${edits.length} edit(s))`).join('\n')
259891
+ },
259892
+ execute: ({ signal })=>this.executeBatch(files, signal)
259893
+ };
259894
+ }
259895
+ async executeBatch(files, signal) {
259896
+ try {
259897
+ const changes = [];
259898
+ const longFiles = [];
259899
+ let replacements = 0;
259900
+ for (const { path, displayPath, edits } of files){
259901
+ try {
259902
+ signal.throwIfAborted();
259903
+ const original = await inspectLocalPatchFile(path, signal);
259904
+ if (original === undefined) throw new Error('File does not exist.');
259905
+ const noChange = edits.findIndex((edit)=>edit.oldText === edit.newText);
259906
+ if (noChange !== -1) throw new ExactEditError(noChange + 1, 'oldText and newText are identical.');
259907
+ const { text, count } = replaceExactText(original.text, displayPath, edits.map((edit)=>({
259908
+ old_string: edit.oldText,
259909
+ new_string: edit.newText,
259910
+ replace_all: edit.replaceAll
259911
+ })));
259912
+ if (text !== original.text) {
259913
+ changes.push({
259914
+ kind: 'update',
259915
+ path,
259916
+ original,
259917
+ text
259918
+ });
259919
+ replacements += count;
259920
+ if (exceedsLineHint(text)) longFiles.push(displayPath);
259921
+ }
259922
+ } catch (error) {
259923
+ return {
259924
+ isError: true,
259925
+ output: `${displayPath}${error instanceof ExactEditError ? ` edit ${error.editNumber}` : ''}: ${fileFailure(error)}`
259926
+ };
259927
+ }
259928
+ }
259929
+ const { cleanupFailed } = await commitLocalPatch(changes, signal);
259930
+ return {
259931
+ output: `EditBatch applied: ${replacements} replacements across ${changes.length} files.` + (longFiles.length ? ` ${longFiles.join(', ')}: over 500 lines; follow the project's own size guidance.` : '') + (cleanupFailed ? ' Some temporary recovery files could not be removed.' : '')
259932
+ };
259933
+ } catch (error) {
259934
+ return {
259935
+ isError: true,
259936
+ output: fileFailure(error)
259937
+ };
259938
+ }
259939
+ }
259940
+ }
259941
+ return EditBatchTool;
259942
+ })();
259943
+ return new editBatchToolClass(kaos, workspace);
259944
+ }
259945
+ // END WAVE 3 EDIT BATCH
259351
259946
  function makeEditInputSchema() {
259352
259947
  const pathSchema = string().describe("Path to the text file to edit. Relative paths resolve against the working directory; a path outside the working directory must be absolute.");
259353
259948
  const replacementSchema = object$1({
@@ -267095,6 +267690,7 @@ var init_turn = __esmMin((() => {
267095
267690
  "Write",
267096
267691
  "Edit",
267097
267692
  "ApplyPatch",
267693
+ "EditBatch",
267098
267694
  "Grep",
267099
267695
  "Glob",
267100
267696
  "Bash",
@@ -267375,7 +267971,10 @@ cancel(turnId, reason) {
267375
267971
  get currentId() {
267376
267972
  return this.turnId;
267377
267973
  }
267378
- get hasActiveTurn() {
267974
+ get activeModelStep() {
267975
+ return this.hasActiveTurn ? this.currentStepByTurn.get(this.currentId) : undefined;
267976
+ }
267977
+ get hasActiveTurn() {
267379
267978
  return this.activeTurn !== null && this.activeTurn !== "resuming";
267380
267979
  }
267381
267980
  ensureActiveTurn() {
@@ -270499,6 +271098,7 @@ var init_tool$1 = __esmMin((() => {
270499
271098
  agent;
270500
271099
  builtinTools = /* @__PURE__ */ new Map();
270501
271100
  userTools = /* @__PURE__ */ new Map();
271101
+ clientToolCalls = new Set();
270502
271102
  mcpTools = /* @__PURE__ */ new Map();
270503
271103
  loopToolsOverride;
270504
271104
  /** server name → list of qualified tool names registered for that server. */
@@ -270685,7 +271285,33 @@ var init_tool$1 = __esmMin((() => {
270685
271285
  cancelShellCommand(commandId) {
270686
271286
  this.shellCommandControllers.get(commandId)?.abort();
270687
271287
  }
270688
- registerUserTool(input) {
271288
+ get clientToolWait() {
271289
+ const { currentId: turnId, activeModelStep: step } = this.agent.turn;
271290
+ if (step === undefined || step === 0) return undefined;
271291
+ const countsByCall = new Map();
271292
+ const add = (toolCallId, count)=>{
271293
+ countsByCall.set(toolCallId, (countsByCall.get(toolCallId) ?? 0) + count);
271294
+ };
271295
+ for (const call of this.clientToolCalls){
271296
+ if (call.turnId === turnId && call.step === step && !call.signal.aborted) add(call.toolCallId, 1);
271297
+ }
271298
+ const children = this.agent.subagentHost?.foregroundClientToolWaits?.(this.agent, turnId, step);
271299
+ if (children !== undefined) {
271300
+ for (const call of children)add(call.toolCallId, call.count);
271301
+ }
271302
+ if (countsByCall.size === 0) return undefined;
271303
+ const calls = Array.from(countsByCall, ([toolCallId, count])=>({
271304
+ toolCallId,
271305
+ count
271306
+ }));
271307
+ return {
271308
+ turnId,
271309
+ step,
271310
+ calls,
271311
+ count: calls.reduce((sum, call)=>sum + call.count, 0)
271312
+ };
271313
+ }
271314
+ registerUserTool(input) {
270689
271315
  this.agent.records.logRecord({
270690
271316
  type: "tools.register_user_tool",
270691
271317
  ...input
@@ -270699,12 +271325,17 @@ var init_tool$1 = __esmMin((() => {
270699
271325
  return {
270700
271326
  approvalRule: name,
270701
271327
  execute: async (context) => {
270702
- return this.agent.rpc.toolCall({
271328
+ const call = { turnId: Number(context.turnId), step: this.agent.turn.activeModelStep,
271329
+ toolCallId: context.toolCallId, signal: context.signal };
271330
+ this.clientToolCalls.add(call);
271331
+ try {
271332
+ return await this.agent.rpc.toolCall({
270703
271333
  turnId: Number(context.turnId),
270704
271334
  toolCallId: context.toolCallId,
270705
271335
  toolName: name,
270706
271336
  args
270707
271337
  }, { signal: context.signal });
271338
+ } finally { this.clientToolCalls.delete(call); }
270708
271339
  }
270709
271340
  };
270710
271341
  }
@@ -270943,6 +271574,7 @@ var init_tool$1 = __esmMin((() => {
270943
271574
  new WriteTool(kaos, workspace, () => this.agent.context.history, toolServices?.lsp),
270944
271575
  new EditTool(kaos, workspace, () => this.agent.context.history, toolServices?.lsp),
270945
271576
  kaos instanceof LocalKaos && new ApplyPatchTool(kaos, { workspaceDir: cwd, additionalDirs: this.agent.getAdditionalDirs() }),
271577
+ kaos instanceof LocalKaos && this.agent.experimentalFlags.enabled("edit_batch") && createEditBatchTool(kaos, { workspaceDir: cwd, additionalDirs: this.agent.getAdditionalDirs() }),
270946
271578
  new GrepTool(kaos, workspace, this.agent.telemetry),
270947
271579
  new GlobTool(kaos, workspace, this.agent.telemetry),
270948
271580
  new BashTool(kaos, cwd, background, {
@@ -272460,9 +273092,11 @@ var init_agent = __esmMin((() => {
272460
273092
  if (phase === "start") injector.recordToolStart(event);
272461
273093
  else injector.recordToolResult(event);
272462
273094
  }
272463
- emitEvent(event) {
273095
+ lastTurnEndReason;
273096
+ emitEvent(event) {
272464
273097
  if (this.records.restoring) return;
272465
- this.cron?.observeAgentEvent(event);
273098
+ if (event.type === "turn.ended" && event.turnId === this.turn.currentId) this.lastTurnEndReason = event.reason;
273099
+ this.cron?.observeAgentEvent(event);
272466
273100
  return this.rpc?.emitEvent?.(event);
272467
273101
  }
272468
273102
  contextMetrics() {
@@ -352575,10 +353209,6 @@ var init_rpc = __esmMin((() => {
352575
353209
  sessionId: input.sessionId,
352576
353210
  agentId
352577
353211
  });
352578
- const context = await rpc.getContext({
352579
- sessionId: input.sessionId,
352580
- agentId
352581
- });
352582
353212
  const permission = await rpc.getPermission({
352583
353213
  sessionId: input.sessionId,
352584
353214
  agentId
@@ -352595,6 +353225,10 @@ var init_rpc = __esmMin((() => {
352595
353225
  sessionId: input.sessionId,
352596
353226
  agentId
352597
353227
  });
353228
+ const context = await rpc.getContext({
353229
+ sessionId: input.sessionId,
353230
+ agentId
353231
+ });
352598
353232
  const maxContextTokens = context.effectiveMaxContextTokens ?? config.modelCapabilities?.max_context_tokens ?? 0;
352599
353233
  const contextTokens = context.projectedTokenCount ?? context.tokenCount;
352600
353234
  const contextUsage = maxContextTokens > 0 ? Math.min(1, Math.max(0, contextTokens / maxContextTokens)) : 0;
@@ -352611,7 +353245,9 @@ var init_rpc = __esmMin((() => {
352611
353245
  maxContextTokens,
352612
353246
  compactionBudgetTokens: context.compactionBudgetTokens,
352613
353247
  contextUsage,
352614
- usage: hasUsage ? usage : void 0
353248
+ usage: hasUsage ? usage : void 0,
353249
+ lastTurnEndReason: context.lastTurnEndReason,
353250
+ clientToolWait: context.clientToolWait
352615
353251
  };
352616
353252
  }
352617
353253
  async listTools(input) {
@@ -381450,6 +382086,7 @@ var init_stdin_buffer = __esmMin((() => {
381450
382086
  BRACKETED_PASTE_START = "\x1B[200~";
381451
382087
  BRACKETED_PASTE_END = "\x1B[201~";
381452
382088
  StdinBuffer = class extends EventEmitter {
382089
+ get bracketedPasteActive() { return this.pasteMode; }
381453
382090
  buffer = "";
381454
382091
  timeout = null;
381455
382092
  timeoutMs;
@@ -381633,6 +382270,7 @@ var init_terminal$2 = __esmMin((() => {
381633
382270
  KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS = 150;
381634
382271
  KITTY_KEYBOARD_PROTOCOL_QUERY = `\x1b[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1b[?u\x1b[c`;
381635
382272
  ProcessTerminal = class {
382273
+ get bracketedPasteActive() { return this.stdinBuffer?.bracketedPasteActive === true; }
381636
382274
  wasRaw = false;
381637
382275
  inputHandler;
381638
382276
  resizeHandler;
@@ -443307,12 +443945,13 @@ var init_custom_editor = __esmMin((() => {
443307
443945
  if (this.expandPasteMarkerAtCursor()) return;
443308
443946
  if (this.onPasteImage !== void 0) {
443309
443947
  const handler = this.onPasteImage;
443310
- handler().then((handled) => {
443948
+ this.wave3Paste = (this.wave3Paste ?? 0) + 1;
443949
+ Promise.resolve().then(() => handler()).then((handled) => {
443311
443950
  if (!handled) {
443312
443951
  this.onTextPaste?.();
443313
443952
  super.handleInput.call(this, normalized);
443314
443953
  }
443315
- });
443954
+ }).finally(() => { this.wave3Paste--; });
443316
443955
  return;
443317
443956
  }
443318
443957
  }
@@ -496740,6 +497379,52 @@ function contextValues(options) {
496740
497379
  maxTokens
496741
497380
  };
496742
497381
  }
497382
+ const FOREGROUND_LABELS = {
497383
+ idle: 'Foreground idle',
497384
+ waiting: 'Waiting for output',
497385
+ thinking: 'Thinking',
497386
+ composing: 'Streaming response',
497387
+ shell: 'Running shell command',
497388
+ approval: 'Approval required',
497389
+ question: 'Answer required',
497390
+ compaction: 'Compacting context',
497391
+ 'client-tool': 'Waiting for client tools'
497392
+ };
497393
+ const TURN_END_LABELS = {
497394
+ completed: 'Ended',
497395
+ cancelled: 'Interrupted',
497396
+ failed: 'Failed',
497397
+ filtered: 'Response filtered'
497398
+ };
497399
+ function workStatusLines(work, accent, value, muted) {
497400
+ const lines = [
497401
+ '',
497402
+ accent('Current work'),
497403
+ ` ${value(FOREGROUND_LABELS[work.foreground])}`
497404
+ ];
497405
+ if (work.clientToolWaitCount !== undefined) {
497406
+ const count = work.clientToolWaitCount;
497407
+ lines.push(` ${muted(`${count} ${count === 1 ? 'request' : 'requests'} pending`)}`);
497408
+ lines.push(` ${muted('Source: session SDK client')}`);
497409
+ lines.push(` ${muted('Wait for the client or stop the turn')}`);
497410
+ }
497411
+ if (work.lastTurnEndReason !== undefined) {
497412
+ lines.push(` ${muted(`Last turn: ${TURN_END_LABELS[work.lastTurnEndReason]}`)}`);
497413
+ }
497414
+ if (work.queuedInputs > 0) lines.push(` ${muted(`Input: ${work.queuedInputs} queued`)}`);
497415
+ if (work.background === undefined) {
497416
+ lines.push(` ${muted('Task status unavailable')}`);
497417
+ } else if (work.background.length === 0) {
497418
+ lines.push(` ${muted('No running background tasks')}`);
497419
+ } else {
497420
+ lines.push(` ${value(`Background: ${work.background.length} running`)} ${muted('/tasks')}`);
497421
+ for (const { taskId, kind } of work.background.slice(0, 3)){
497422
+ const id = taskId.length > 0 && taskId.length <= 64 && !/[^a-z\d_-]/iu.test(taskId) ? ` ${taskId}` : '';
497423
+ lines.push(` ${muted(`${kind}${id}`)}`);
497424
+ }
497425
+ }
497426
+ return lines;
497427
+ }
496743
497428
  function buildStatusReportLines(options) {
496744
497429
  const accent = (text) => currentTheme.boldFg("primary", text);
496745
497430
  const value = (text) => currentTheme.fg("text", text);
@@ -496788,6 +497473,7 @@ function buildStatusReportLines(options) {
496788
497473
  });
496789
497474
  const lines = [`${accent(`>_ ${PRODUCT_NAME}`)} ${muted(`(v${sanitizeTerminalText(options.version)})`)}`, ""];
496790
497475
  addFieldRows(lines, rows, muted, value, errorStyle);
497476
+ if (options.work) lines.push(...workStatusLines(options.work, accent, value, muted));
496791
497477
  const { ratio, tokens, maxTokens } = contextValues(options);
496792
497478
  lines.push("");
496793
497479
  lines.push(accent(uiText("usage.context.title")));
@@ -498469,15 +499155,48 @@ async function showUsage(host) {
498469
499155
  host.state.transcriptContainer.addChild(panel);
498470
499156
  host.state.ui.requestRender();
498471
499157
  }
499158
+ function liveClientToolWaitCount(host, wait) {
499159
+ if (wait === undefined || !Array.isArray(wait.calls)) return undefined;
499160
+ const { turnId, step } = host.streamingUI.getTurnContext();
499161
+ if (turnId === undefined || step < 1 || String(wait.turnId) !== turnId || wait.step !== step) {
499162
+ return undefined;
499163
+ }
499164
+ const seen = new Set();
499165
+ let count = 0;
499166
+ for (const { toolCallId, count: pending } of wait.calls){
499167
+ if (seen.has(toolCallId) || !Number.isSafeInteger(pending) || pending < 1) continue;
499168
+ const active = host.streamingUI.getActiveToolCall(toolCallId);
499169
+ if (active?.turnId !== turnId || active?.step !== step) continue;
499170
+ seen.add(toolCallId);
499171
+ count += pending;
499172
+ }
499173
+ return Number.isSafeInteger(count) && count > 0 ? count : undefined;
499174
+ }
499175
+ async function loadRunningTasks(session) {
499176
+ if (session === undefined) return undefined;
499177
+ try {
499178
+ const tasks = await session.listBackgroundTasks({
499179
+ activeOnly: true
499180
+ });
499181
+ return tasks.filter((task)=>task.status === 'running').map(({ taskId, kind })=>({
499182
+ taskId,
499183
+ kind
499184
+ }));
499185
+ } catch {
499186
+ return undefined;
499187
+ }
499188
+ }
498472
499189
  async function showStatusReport(host) {
498473
499190
  const owner = host.session;
498474
499191
  const model = host.state.appState.model;
498475
499192
  const agentId = owner?.connectionKind === "gateway" ? void 0 : host.harness.interactiveAgentId;
498476
- const isCurrent = () => !host.aborted && host.session === owner && host.state.appState.model === model && (owner?.connectionKind === "gateway" || host.harness.interactiveAgentId === agentId);
499193
+ const isCurrent = () => !host.aborted && host.session === owner && owner?.isClosed !== true && host.state.appState.model === model && (owner?.connectionKind === "gateway" || host.harness.interactiveAgentId === agentId);
498477
499194
  if (!isCurrent()) return;
498478
- const [runtimeStatus, managedUsage] = await Promise.all([loadRuntimeStatusReport(host), loadManagedUsageReport(host)]);
499195
+ const [runtimeStatus, managedUsage, background] = await Promise.all([loadRuntimeStatusReport(host), loadManagedUsageReport(host), owner?.connectionKind === "gateway" ? undefined : loadRunningTasks(owner)]);
498479
499196
  if (!isCurrent()) return;
498480
- const appState = host.state.appState;
499197
+ const { appState, livePane, queuedMessages } = host.state;
499198
+ const clientToolWaitCount = appState.streamingPhase === 'idle' || appState.streamingPhase === 'shell' ? undefined : liveClientToolWaitCount(host, runtimeStatus.status?.clientToolWait);
499199
+ const foreground = livePane.pendingApproval !== null ? 'approval' : livePane.pendingQuestion !== null ? 'question' : appState.isCompacting ? 'compaction' : clientToolWaitCount !== undefined ? 'client-tool' : appState.streamingPhase;
498481
499200
  const reportArgs = {
498482
499201
  version: appState.version,
498483
499202
  model: appState.model,
@@ -498493,6 +499212,9 @@ async function showStatusReport(host) {
498493
499212
  availableModels: appState.availableModels,
498494
499213
  status: runtimeStatus.status,
498495
499214
  gatewayConnectionState: owner?.connectionKind === "gateway" ? appState.gatewayConnectionState : void 0,
499215
+ work: owner === undefined ? undefined : { foreground, queuedInputs: queuedMessages.length, background,
499216
+ lastTurnEndReason: runtimeStatus.status?.lastTurnEndReason,
499217
+ clientToolWaitCount: foreground === "client-tool" ? clientToolWaitCount : undefined },
498496
499218
  statusError: runtimeStatus.error,
498497
499219
  managedUsage: managedUsage?.usage,
498498
499220
  managedUsageError: managedUsage?.error
@@ -501771,6 +502493,57 @@ var init_telegram_channel = __esmMin((() => {
501771
502493
  BLUN_NODE_FALLBACK_SUBCOMMAND = "__plugin_run_node";
501772
502494
  PLACEHOLDER_RE = /replace|paste|your[-_]|xxxx/i;
501773
502495
  TelegramChannelController = class {
502496
+ wave3Published;
502497
+ wave3Running = false;
502498
+ wave3QuietBoundary(sessionId) {
502499
+ if (this.sessionQueueError !== undefined || this.sessionDelivery.inFlight.size || this.sessionDelivery.controlsInFlight.size) return;
502500
+ const captured = captureSessionQueueBoundary(this.queueFile);
502501
+ const saved = readSessionQueue(this.sessionDelivery.stateFile);
502502
+ if (captured === undefined && saved === undefined) return "absent";
502503
+ if (captured === undefined || saved === undefined || saved.activeSessionId !== sessionId ||
502504
+ saved.fileId !== captured.fileId || saved.frontier !== captured.frontier ||
502505
+ pendingSessionQueue(saved, sessionId).length || statSync(this.queueFile).size !== captured.frontier) return;
502506
+ return JSON.stringify(captured);
502507
+ }
502508
+ async wave3DrainControls() {
502509
+ if (this.stopped || !this.ownsChannel() || this.wave3Running) return;
502510
+ this.wave3Running = true;
502511
+ try {
502512
+ const sessionId = this.host.wave3ControlSession?.();
502513
+ if (sessionId === undefined) {
502514
+ if (this.wave3Published) wave3Control.clearBinding(this.dir, this.wave3Published);
502515
+ this.wave3Published = undefined;
502516
+ return;
502517
+ }
502518
+ const botId = wave3Control.readBotId(this.dir);
502519
+ if (botId === undefined) return;
502520
+ const binding = wave3Control.publishBinding(this.dir, this.ownerId, botId, sessionId, this.wave3Published);
502521
+ this.wave3Published = binding;
502522
+ if (!this.host.wave3ControlAvailable?.()) return;
502523
+ const boundary = this.wave3QuietBoundary(sessionId);
502524
+ if (boundary === undefined) return;
502525
+ const controls = new wave3Control.ConsoleControlState(this.dir, botId);
502526
+ for (const name of controls.names("pending")) {
502527
+ const control = controls.read("pending", name), address = wave3Control.controlAddress(name);
502528
+ if (!address || !control || control.ownerId !== binding.ownerId) continue;
502529
+ const canCommit = () => {
502530
+ try {
502531
+ return !this.stopped && this.ownsChannel() && this.host.wave3ControlSession?.() === sessionId &&
502532
+ wave3Control.controlIsFresh(control.queuedAt) &&
502533
+ wave3Control.readBotId(this.dir) === botId &&
502534
+ wave3Control.readBinding(this.dir, botId)?.ownerId === binding.ownerId &&
502535
+ wave3Control.hasSessionControlGrant(this.dir, address.chatId) &&
502536
+ this.wave3QuietBoundary(sessionId) === boundary;
502537
+ } catch { return false; }
502538
+ };
502539
+ if (!canCommit() || !controls.claim(name, control)) continue;
502540
+ const ok = await this.host.wave3RunControl?.(control.command, canCommit);
502541
+ if (wave3Control.hasSessionControlGrant(this.dir, address.chatId)) controls.complete(name, ok === true);
502542
+ return;
502543
+ }
502544
+ } catch { /* An unavailable binding cannot authorize a transition. */ }
502545
+ finally { this.wave3Running = false; }
502546
+ }
501774
502547
  host;
501775
502548
  dir;
501776
502549
  sessionScope;
@@ -502015,6 +502788,7 @@ var init_telegram_channel = __esmMin((() => {
502015
502788
  }
502016
502789
  beginStop() {
502017
502790
  if (this.stopped) return;
502791
+ if (this.wave3Published) try { wave3Control.clearBinding(this.dir, this.wave3Published); } catch {}
502018
502792
  this.stopped = true;
502019
502793
  this.activeOwner = false;
502020
502794
  if (this.heartbeatTimer !== void 0) clearInterval(this.heartbeatTimer);
@@ -502113,6 +502887,7 @@ var init_telegram_channel = __esmMin((() => {
502113
502887
  }
502114
502888
  if (this.sessionScope !== void 0) {
502115
502889
  this.pollSessionQueue(this.sessionScope());
502890
+ void this.wave3DrainControls();
502116
502891
  return;
502117
502892
  }
502118
502893
  let stats;
@@ -504935,7 +505710,158 @@ function isMultilineChatInput(input) {
504935
505710
  "aside"
504936
505711
  ].includes(parsed.name);
504937
505712
  }
505713
+ const LOCAL_DIAGNOSTICS = /^\s*\/\s*diagnostics(?=\s|$)/iu;
505714
+ function isLocalDiagnosticsInput(input) {
505715
+ return LOCAL_DIAGNOSTICS.test(input);
505716
+ }
505717
+ const TUI_TURN_DIAGNOSTICS_FLAG = 'tui_turn_diagnostics';
505718
+ const TUI_DIAGNOSTIC_MAX_TRACKED_TURNS = 8;
505719
+ function tuiDiagnosticMillis(value) {
505720
+ return value !== undefined && value >= 0 && value <= Number.MAX_SAFE_INTEGER ? Math.round(value) : undefined;
505721
+ }
505722
+ class TurnDiagnostics {
505723
+ now;
505724
+ owner;
505725
+ active = new Map();
505726
+ order = 0;
505727
+ last;
505728
+ constructor(now = ()=>performance.now()){
505729
+ this.now = now;
505730
+ }
505731
+ reset() {
505732
+ this.owner = undefined;
505733
+ this.active.clear();
505734
+ this.order = 0;
505735
+ this.last = undefined;
505736
+ }
505737
+ record(event) {
505738
+ if (event.agentId !== 'main' || this.owner !== undefined && this.owner !== event.sessionId) return;
505739
+ if (event.type === 'turn.started') {
505740
+ const previous = this.active.get(event.turnId);
505741
+ if (previous !== undefined && previous.instance === event.turnInstanceId) return;
505742
+ this.owner = event.sessionId;
505743
+ this.active.delete(event.turnId);
505744
+ this.active.set(event.turnId, {
505745
+ instance: event.turnInstanceId,
505746
+ order: ++this.order,
505747
+ startedAt: this.now(),
505748
+ sample: {
505749
+ outcome: 'running',
505750
+ retryEvents: 0
505751
+ },
505752
+ stepBase: 0
505753
+ });
505754
+ if (this.active.size > TUI_DIAGNOSTIC_MAX_TRACKED_TURNS) {
505755
+ const oldest = this.active.keys().next();
505756
+ if (!oldest.done) this.active.delete(oldest.value);
505757
+ }
505758
+ return;
505759
+ }
505760
+ if (!('turnId' in event) || event.turnId === undefined) return;
505761
+ const active = this.active.get(event.turnId);
505762
+ if (active === undefined) return;
505763
+ const sample = active.sample;
505764
+ switch(event.type){
505765
+ case 'turn.step.started':
505766
+ if (!Number.isSafeInteger(event.step) || event.step < 0) break;
505767
+ if (active.step?.number !== event.step || active.step.id !== event.stepId) {
505768
+ if (active.step !== undefined && event.step <= active.step.number) {
505769
+ active.stepBase += active.step.number;
505770
+ }
505771
+ sample.lastStep = active.stepBase + event.step;
505772
+ active.step = {
505773
+ number: event.step,
505774
+ id: event.stepId
505775
+ };
505776
+ sample.firstTokenMs = undefined;
505777
+ sample.streamMs = undefined;
505778
+ }
505779
+ break;
505780
+ case 'turn.step.completed':
505781
+ if (active.step !== undefined && (active.step.number !== event.step || active.step.id !== undefined && event.stepId !== undefined && active.step.id !== event.stepId)) break;
505782
+ sample.firstTokenMs = tuiDiagnosticMillis(event.llmFirstTokenLatencyMs);
505783
+ sample.streamMs = tuiDiagnosticMillis(event.llmStreamDurationMs);
505784
+ break;
505785
+ case 'turn.step.retrying':
505786
+ {
505787
+ sample.retryEvents = Math.min(Number.MAX_SAFE_INTEGER, sample.retryEvents + 1);
505788
+ const status = event.statusCode;
505789
+ if (status !== undefined && Number.isInteger(status) && status >= 100 && status <= 599) {
505790
+ sample.lastRetryHttpStatus = status;
505791
+ }
505792
+ break;
505793
+ }
505794
+ case 'hook.result':
505795
+ if (event.hookEvent === 'UserPromptSubmit') {
505796
+ sample.promptHook = event.blocked === true ? 'blocked' : sample.promptHook ?? 'reported';
505797
+ }
505798
+ break;
505799
+ case 'turn.ended':
505800
+ this.active.delete(event.turnId);
505801
+ if (event.reason !== 'completed' && event.reason !== 'cancelled' && event.reason !== 'failed' && event.reason !== 'filtered') return;
505802
+ if (this.last !== undefined && this.last.order > active.order) return;
505803
+ this.last = {
505804
+ order: active.order,
505805
+ sample: {
505806
+ ...sample,
505807
+ outcome: event.reason,
505808
+ durationMs: tuiDiagnosticMillis(event.durationMs) ?? tuiDiagnosticMillis(this.now() - active.startedAt),
505809
+ stepLimitReached: event.error?.code === 'loop.max_steps_exceeded' ? true : undefined
505810
+ }
505811
+ };
505812
+ break;
505813
+ }
505814
+ }
505815
+ snapshot() {
505816
+ let active;
505817
+ for (const turn of this.active.values())active = turn;
505818
+ return {
505819
+ ...active?.order !== this.order ? {} : {
505820
+ active: {
505821
+ ...active.sample,
505822
+ durationMs: tuiDiagnosticMillis(this.now() - active.startedAt)
505823
+ }
505824
+ },
505825
+ ...this.last === undefined ? {} : {
505826
+ last: {
505827
+ ...this.last.sample
505828
+ }
505829
+ }
505830
+ };
505831
+ }
505832
+ }
505833
+ function buildTurnDiagnosticLines(snapshot) {
505834
+ const lines = [];
505835
+ for (const [label, turn] of [
505836
+ [
505837
+ 'Active',
505838
+ snapshot.active
505839
+ ],
505840
+ [
505841
+ 'Last',
505842
+ snapshot.last
505843
+ ]
505844
+ ]){
505845
+ if (turn === undefined) continue;
505846
+ const elapsed = turn.durationMs === undefined ? '' : ` (${turn.durationMs} ms)`;
505847
+ lines.push(`${label}: ${turn.outcome}${elapsed}`);
505848
+ if (turn.lastStep !== undefined) lines.push(` Model step: ${turn.lastStep}`);
505849
+ lines.push(` Retry notices: ${turn.retryEvents}`);
505850
+ if (turn.lastRetryHttpStatus !== undefined) lines.push(` Last retry HTTP: ${turn.lastRetryHttpStatus}`);
505851
+ if (turn.firstTokenMs !== undefined) lines.push(` First token: ${turn.firstTokenMs} ms`);
505852
+ if (turn.streamMs !== undefined) lines.push(` Stream: ${turn.streamMs} ms`);
505853
+ if (turn.promptHook !== undefined) lines.push(` Prompt hook: ${turn.promptHook}`);
505854
+ if (turn.stepLimitReached === true) lines.push(' Model step limit reached');
505855
+ }
505856
+ return lines.length === 0 ? [
505857
+ 'No turn observed in this console.'
505858
+ ] : lines;
505859
+ }
504938
505860
  function parseSlashInput(input) {
505861
+ const diagnostics = LOCAL_DIAGNOSTICS.exec(input);
505862
+ if (diagnostics !== null) {
505863
+ return { name: "diagnostics", args: input.slice(diagnostics[0].length).trim() };
505864
+ }
504939
505865
  if (!input.startsWith("/")) return null;
504940
505866
  const trimmed = input.slice(1).trim();
504941
505867
  if (trimmed.length === 0) return null;
@@ -505686,7 +506612,7 @@ function researchAvailability(args) {
505686
506612
  function getBuiltinSlashCommands() {
505687
506613
  return BUILTIN_SLASH_COMMAND_DEFINITIONS.map(({ descriptionKey, ...command }) => ({
505688
506614
  ...command,
505689
- description: uiText(descriptionKey)
506615
+ description: command.description ?? uiText(descriptionKey)
505690
506616
  }));
505691
506617
  }
505692
506618
  function findBuiltInSlashCommand(commandName) {
@@ -505715,6 +506641,8 @@ var init_registry$1 = __esmMin((() => {
505715
506641
  init_queue();
505716
506642
  init_experimental_flags();
505717
506643
  BUILTIN_SLASH_COMMAND_DEFINITIONS = [
506644
+ { name: "diagnostics", aliases: [], description: "Show recent turn diagnostics",
506645
+ availability: "always", priority: 60, experimentalFlag: "tui_turn_diagnostics" },
505718
506646
  {
505719
506647
  name: "reset",
505720
506648
  aliases: [],
@@ -513031,17 +513959,22 @@ async function handleReloadTuiCommand(host) {
513031
513959
  const warning = await applyReloadedTuiConfigWithFallback(host, loaded.config) ?? loaded.warning;
513032
513960
  host.showStatus(warning ?? uiText("reload.tui.complete"), warning === void 0 ? "success" : "error");
513033
513961
  }
513034
- async function handleReloadCommand(host) {
513962
+ async function handleReloadCommand(host, beforeReload) {
513035
513963
  const loaded = await loadTuiConfigForReload();
513036
513964
  const session = host.session;
513037
513965
  if (session !== void 0) {
513038
- const reload = () => session.reloadSession({
513966
+ let didReload = false;
513967
+ const reload = () => {
513968
+ if (beforeReload && !beforeReload()) return;
513969
+ didReload = true;
513970
+ return session.reloadSession({
513039
513971
  forcePluginSessionStartReminder: true,
513040
513972
  mcpServers: sessionMcpServers()
513041
- });
513973
+ });
513974
+ };
513042
513975
  if (host.withGoalReplyReload !== void 0) await host.withGoalReplyReload(session, reload);
513043
513976
  else await reload();
513044
- if (host.session !== session) return;
513977
+ if (!didReload || host.session !== session) return;
513045
513978
  if (host.state.appState.modelFallbackAllowed === false) {
513046
513979
  const model = host.state.appState.model.trim();
513047
513980
  if (model.length > 0) await session.setModel(model, { allowFallback: false });
@@ -513054,6 +513987,7 @@ async function handleReloadCommand(host) {
513054
513987
  const warning = await applyReloadedTuiConfigWithFallback(host, loaded.config) ?? loaded.warning;
513055
513988
  if (session === void 0) host.showStatus(warning ?? uiText("reload.runtime.completeWithoutSession"), warning === void 0 ? "success" : "error");
513056
513989
  else if (warning !== void 0) host.showStatus(warning, "error");
513990
+ return session !== undefined && host.session === session;
513057
513991
  }
513058
513992
  async function loadTuiConfigForReload() {
513059
513993
  try {
@@ -527524,7 +528458,19 @@ function tryCancelSessionSearchInput(host, text) {
527524
528458
  sessionSearchRequests.get(host)?.abort();
527525
528459
  return true;
527526
528460
  }
528461
+ function runLocalTurnDiagnostics(host, text) {
528462
+ if (!isLocalDiagnosticsInput(text)) return false;
528463
+ if (!isExperimentalFlagEnabled(TUI_TURN_DIAGNOSTICS_FLAG)) {
528464
+ host.showStatus("/diagnostics is disabled. Enable Local turn diagnostics in /experiments.");
528465
+ } else if (parseSlashInput(text).args !== "") {
528466
+ host.showError("Usage: /diagnostics");
528467
+ } else {
528468
+ host.showTurnDiagnostics();
528469
+ }
528470
+ return true;
528471
+ }
527527
528472
  function dispatchInput(host, text) {
528473
+ if (runLocalTurnDiagnostics(host, text)) return Promise.resolve();
527528
528474
  if (tryCancelSessionSearchInput(host, text)) return Promise.resolve();
527529
528475
  if (isExperimentalFlagEnabled("multiline_chat_input") && isMultilineChatInput(text)) {
527530
528476
  host.sendNormalUserInput(text);
@@ -527557,6 +528503,7 @@ function dispatchInput(host, text) {
527557
528503
  return Promise.resolve();
527558
528504
  }
527559
528505
  async function executeSlashCommand(host, input) {
528506
+ if (runLocalTurnDiagnostics(host, input)) return;
527560
528507
  const parsedCommand = parseSlashInput(input);
527561
528508
  const intent = resolveSlashCommandInput({
527562
528509
  input,
@@ -538927,8 +539874,10 @@ var init_session_event_handler = __esmMin((() => {
538927
539874
  lastCompactionInstruction;
538928
539875
  pendingCompactionRetry;
538929
539876
  compactionRetryPanel;
539877
+ turnDiagnostics = new TurnDiagnostics();
538930
539878
  resetRuntimeState() {
538931
539879
  this.assistantMediaAttempts.clear();
539880
+ this.turnDiagnostics.reset();
538932
539881
  for (const component of this.pluginTraceComponents) this.host.state.transcriptContainer.removeChild(component);
538933
539882
  this.pluginTraceComponents.length = 0;
538934
539883
  this.pluginTraceSessionId = void 0;
@@ -539072,6 +540021,7 @@ clearAgentSwarmProgress() {
539072
540021
  });
539073
540022
  }
539074
540023
  handleEvent(event, sendQueued) {
540024
+ if (isExperimentalFlagEnabled(TUI_TURN_DIAGNOSTICS_FLAG)) this.turnDiagnostics.record(event);
539075
540025
  if (event.type === "plugin.trace") {
539076
540026
  this.handlePluginTrace(event);
539077
540027
  return;
@@ -549065,15 +550015,27 @@ activeApprovalPanel;
549065
550015
  this.updateEditorBorderHighlight();
549066
550016
  }
549067
550017
  localTransitionRequest;
549068
- tryLocalTransition(text) {
550018
+ wave3ControlUiSafe() {
550019
+ const { appState, editor, ui, terminal, btwPanelContainer, livePane } = this.state;
550020
+ return !this.aborted && !this.isShuttingDown && !this.gatewayStartup &&
550021
+ !this.state.externalEditorRunning && !this.editorReplacementActive && this.state.activeDialog === null &&
550022
+ livePane.pendingApproval === null && livePane.pendingQuestion === null &&
550023
+ !this.queueCommandRunning && !this.manualPromptInFlight && !this.queueSteerInFlight && !this.localShellConsentRequest &&
550024
+ !ui.hasOverlay() && editor.focused === true && editor.getText() === "" && !editor.wave3Paste &&
550025
+ appState.inputMode === "prompt" && !terminal.bracketedPasteActive && btwPanelContainer.children.length === 0 &&
550026
+ appState.streamingPhase === "idle" && !appState.isCompacting && !appState.isReplaying &&
550027
+ this.state.queuedMessages.length === 0 && !Array.from(this.sessionEventHandler.backgroundTasks.values()).some(info => !isTerminalBackgroundTask(info));
550028
+ }
550029
+ tryLocalTransition(text, remoteCommit) {
549069
550030
  const command = text.trim();
549070
550031
  const session = this.session;
549071
550032
  if ((command !== "/new" && command !== "/reload") || session?.connectionKind !== "embedded" || this.gatewayStartup || this.state.appState.isReplaying) return false;
549072
- if (this.localTransitionRequest !== void 0) return true;
550033
+ if (this.localTransitionRequest !== void 0) return remoteCommit === undefined;
550034
+ if (remoteCommit && (!remoteCommit() || !this.wave3ControlUiSafe())) return false;
549073
550035
  const request = {};
549074
550036
  this.localTransitionRequest = request;
549075
- this.track("input_command", { command: command.slice(1) });
549076
- const current = () => this.localTransitionRequest === request && this.session === session && !this.aborted && !this.isShuttingDown;
550037
+ if (!remoteCommit) this.track("input_command", { command: command.slice(1) });
550038
+ const current = () => this.localTransitionRequest === request && this.session === session && !this.aborted && !this.isShuttingDown && (!remoteCommit || (request.draft === undefined && remoteCommit() && this.wave3ControlUiSafe()));
549077
550039
  const run = async () => {
549078
550040
  let lease;
549079
550041
  try {
@@ -549088,16 +550050,16 @@ activeApprovalPanel;
549088
550050
  await new Promise(resolve => setTimeout(resolve, 25));
549089
550051
  }
549090
550052
  if (!current()) return;
549091
- await this.withTelegramQueuePaused(async (boundary) => {
550053
+ return await this.withTelegramQueuePaused(async (boundary) => {
549092
550054
  await session.waitForPromptAdmissions();
549093
550055
  if (!current() || this.state.queuedMessages.length !== 0) return;
549094
550056
  await lease.settle();
549095
550057
  if (!current() || this.state.queuedMessages.length !== 0) return;
549096
- if (command === "/new") await this.createNewSessionRuntime(boundary, current);
549097
- else await handleReloadCommand(this);
550058
+ if (command === "/new") return this.createNewSessionRuntime(boundary, current, remoteCommit !== undefined);
550059
+ return handleReloadCommand(this, remoteCommit ? current : undefined);
549098
550060
  });
549099
550061
  } catch {
549100
- if (current()) this.showError("Session change could not complete. Check the session before retrying.");
550062
+ if (!remoteCommit && current()) this.showError("Session change could not complete. Check the session before retrying.");
549101
550063
  } finally {
549102
550064
  lease?.release();
549103
550065
  if (this.localTransitionRequest === request) {
@@ -549107,6 +550069,7 @@ activeApprovalPanel;
549107
550069
  }
549108
550070
  }
549109
550071
  };
550072
+ if (remoteCommit) return run();
549110
550073
  void run();
549111
550074
  return true;
549112
550075
  }
@@ -549126,7 +550089,8 @@ activeApprovalPanel;
549126
550089
  return;
549127
550090
  }
549128
550091
  const historyText = wasBashMode ? `!${text}` : text;
549129
- this.persistInputHistory(historyText);
550092
+ if (wasBashMode || !isLocalDiagnosticsInput(text)) this.persistInputHistory(historyText);
550093
+ if (!wasBashMode && this.localTransitionRequest === void 0 && runLocalTurnDiagnostics(this, text)) return;
549130
550094
  if (this.localTransitionRequest !== void 0) {
549131
550095
  this.localTransitionRequest.draft = historyText;
549132
550096
  this.state.editor.setText(historyText);
@@ -549865,6 +550829,11 @@ releaseChannelQueueAtSafePoint() {
549865
550829
  this.queuePolicySteerTimer.unref?.();
549866
550830
  }
549867
550831
  flushQueuedMessages(draft, draftMode) {
550832
+ if (draftMode !== "bash" && isLocalDiagnosticsInput(draft)) {
550833
+ if (this.localTransitionRequest === void 0) this.state.editor.setText("");
550834
+ this.handleUserInput(draft);
550835
+ return;
550836
+ }
549868
550837
  this.automaticSteerBatch = false;
549869
550838
  if (draft.length > 0) {
549870
550839
  this.state.editor.setText("");
@@ -550345,6 +551314,10 @@ releaseChannelQueueAtSafePoint() {
550345
551314
  }
550346
551315
  let controller;
550347
551316
  controller = new TelegramChannelController({
551317
+ wave3ControlSession: () => isExperimentalFlagEnabled("telegram_session_control") &&
551318
+ this.session?.connectionKind === "embedded" && this.telegramSessionScope?.sessionId === this.session.id ? this.session.id : undefined,
551319
+ wave3ControlAvailable: () => this.localTransitionRequest === undefined && !this.deferUserMessages && this.wave3ControlUiSafe(),
551320
+ wave3RunControl: (command, canCommit) => this.tryLocalTransition("/" + command, canCommit),
550348
551321
  inject: (envelope, acknowledge) => {
550349
551322
  this.injectChannelMessage(envelope, acknowledge);
550350
551323
  },
@@ -551399,21 +552372,52 @@ releaseChannelQueueAtSafePoint() {
551399
552372
  });
551400
552373
  }
551401
552374
  sessionBindingRequest;
551402
- async setSessionRuntime(session, queueScope, modelPrepared = false) {
552375
+ async setSessionRuntime(session, queueScope, modelPrepared = false, beforeAdoption) {
551403
552376
  if (this.aborted || this.isShuttingDown) return;
551404
552377
  const request = {};
551405
- this.sessionBindingRequest = request;
552378
+ const previousBindingRequest = this.sessionBindingRequest;
551406
552379
  const original = this.session;
551407
552380
  let owner = original;
551408
552381
  let adopted = false;
551409
552382
  const isCurrent = () => !this.aborted && !this.isShuttingDown && this.sessionBindingRequest === request && this.session === owner;
552383
+ let goalDetached = false;
552384
+ const restorePreviousBinding = async (memoryCleared) => {
552385
+ if (!isCurrent()) return;
552386
+ this.sessionBindingRequest = previousBindingRequest;
552387
+ if (original === void 0) return;
552388
+ try {
552389
+ if (goalDetached) await this.goalChannelReplies.restore(original, this.state.appState.goal ?? null);
552390
+ } finally {
552391
+ if (memoryCleared && !this.aborted && !this.isShuttingDown &&
552392
+ this.session === original && this.sessionBindingRequest === previousBindingRequest) {
552393
+ await this.personalMemoryController.refresh();
552394
+ }
552395
+ }
552396
+ };
551410
552397
  try {
552398
+ if (beforeAdoption && !beforeAdoption()) return;
552399
+ this.sessionBindingRequest = request;
551411
552400
  if (!modelPrepared) await session.setModel(BLUN_KING_MODEL_ALIAS, { allowFallback: false });
551412
552401
  if (!isCurrent()) return;
551413
- if (this.session !== session) await this.goalChannelReplies.detach();
552402
+ if (this.session !== session) {
552403
+ await this.goalChannelReplies.detach();
552404
+ goalDetached = true;
552405
+ }
551414
552406
  if (!isCurrent()) return;
552407
+ if (beforeAdoption && !beforeAdoption()) {
552408
+ await restorePreviousBinding(false);
552409
+ return;
552410
+ }
551415
552411
  await this.personalMemoryController.clear(this.session);
551416
552412
  if (!isCurrent()) return;
552413
+ if (beforeAdoption) {
552414
+ if (!beforeAdoption()) {
552415
+ await restorePreviousBinding(true);
552416
+ return;
552417
+ }
552418
+ this.resetSessionRuntime();
552419
+ this.sessionBindingRequest = request;
552420
+ }
551417
552421
  const previous = this.unloadCurrentSession(approvalCancellationFeedback("switching_session"));
551418
552422
  this.sessionBindingRequest = request;
551419
552423
  owner = void 0;
@@ -551430,6 +552434,10 @@ releaseChannelQueueAtSafePoint() {
551430
552434
  this.pendingChannelReplyGuard = void 0;
551431
552435
  }
551432
552436
  resetChannelPreambleState(this.channelPreamble);
552437
+ if (this.session !== session) {
552438
+ this.sessionEventHandler.turnDiagnostics.reset();
552439
+ this.clearTurnDiagnosticsPanel();
552440
+ }
551433
552441
  this.session = session;
551434
552442
  owner = session;
551435
552443
  adopted = true;
@@ -551561,6 +552569,8 @@ releaseChannelQueueAtSafePoint() {
551561
552569
  if (previous !== this.session) await previous?.close();
551562
552570
  }
551563
552571
  unloadCurrentSession(reason) {
552572
+ this.sessionEventHandler.turnDiagnostics.reset();
552573
+ this.clearTurnDiagnosticsPanel();
551564
552574
  this.foregroundSwarm = void 0;
551565
552575
  this.exportLifetime?.abort();
551566
552576
  this.exportLifetime = new AbortController();
@@ -551649,6 +552659,7 @@ releaseChannelQueueAtSafePoint() {
551649
552659
  this.state.terminal.setTitle(label);
551650
552660
  }
551651
552661
  resetSessionRuntime() {
552662
+ this.clearTurnDiagnosticsPanel();
551652
552663
  void this.journalHistory.close();
551653
552664
  this.scrollbackController?.invalidateOriginalHistory?.();
551654
552665
  this.shellOutputStreams.clear();
@@ -551823,6 +552834,10 @@ releaseChannelQueueAtSafePoint() {
551823
552834
  this.sessionBindingRequest = request;
551824
552835
  await session.setModel(BLUN_KING_MODEL_ALIAS, { allowFallback: false });
551825
552836
  if (!isCurrent()) return;
552837
+ if (this.session !== session) {
552838
+ this.sessionEventHandler.turnDiagnostics.reset();
552839
+ this.clearTurnDiagnosticsPanel();
552840
+ }
551826
552841
  this.session = session;
551827
552842
  owner = session;
551828
552843
  await this.refreshSessionQueuePolicy(session);
@@ -551887,7 +552902,7 @@ releaseChannelQueueAtSafePoint() {
551887
552902
  await this.createNewSessionRuntime(boundary);
551888
552903
  });
551889
552904
  }
551890
- async createNewSessionRuntime(boundary, canCommit = () => true) {
552905
+ async createNewSessionRuntime(boundary, canCommit = () => true, remote = false) {
551891
552906
  if (this.aborted || this.isShuttingDown) return;
551892
552907
  if (this.state.appState.isReplaying) {
551893
552908
  this.showError(uiText("blunTui.session.createReplayBlocked"));
@@ -551914,12 +552929,12 @@ releaseChannelQueueAtSafePoint() {
551914
552929
  this.showError(uiText("blunTui.session.createFailed", { error: msg }));
551915
552930
  return;
551916
552931
  }
551917
- this.resetSessionRuntime();
552932
+ if (!remote) this.resetSessionRuntime();
551918
552933
  const binding = await this.setSessionRuntime(session, {
551919
552934
  sessionId: session.id,
551920
552935
  mode: "new",
551921
552936
  boundary
551922
- }, true);
552937
+ }, true, remote ? isCurrent : undefined);
551923
552938
  if (this.aborted || this.isShuttingDown || this.session !== session) return;
551924
552939
  const isActive = () => !this.aborted && !this.isShuttingDown && this.session === session && binding !== void 0 && this.sessionBindingRequest === binding;
551925
552940
  if (!isActive()) return;
@@ -551947,6 +552962,7 @@ releaseChannelQueueAtSafePoint() {
551947
552962
  this.showStatus(uiText("blunTui.session.started", { sessionId: session.id }));
551948
552963
  this.showSessionWarnings(session);
551949
552964
  this.showConfigWarningsIfAny();
552965
+ return true;
551950
552966
  }
551951
552967
  /** Surface config.toml load warnings (degraded or kept-previous config) in the status bar. */
551952
552968
  async showConfigWarningsIfAny() {
@@ -552272,6 +553288,7 @@ releaseChannelQueueAtSafePoint() {
552272
553288
  for (const child of this.state.transcriptContainer.children) if (hasDispose(child)) child.dispose();
552273
553289
  }
552274
553290
  clearTranscriptAndRedraw() {
553291
+ this.clearTurnDiagnosticsPanel();
552275
553292
  void this.journalHistory.close();
552276
553293
  this.scrollbackController?.invalidateOriginalHistory?.();
552277
553294
  this.streamingUI.discardPending();
@@ -552292,6 +553309,7 @@ releaseChannelQueueAtSafePoint() {
552292
553309
  this.state.ui.requestRender(true);
552293
553310
  }
552294
553311
  prepareReplayTranscript() {
553312
+ this.clearTurnDiagnosticsPanel();
552295
553313
  void this.journalHistory.close();
552296
553314
  this.scrollbackController?.invalidateOriginalHistory?.();
552297
553315
  this.disposeTranscriptChildren();
@@ -552330,7 +553348,7 @@ releaseChannelQueueAtSafePoint() {
552330
553348
  const componentsToRemove = [];
552331
553349
  for (let i = 0; i < cutoff; i++) {
552332
553350
  const child = children[i];
552333
- if (child instanceof WelcomeComponent) continue;
553351
+ if (child instanceof WelcomeComponent || child === this.turnDiagnosticsPanel) continue;
552334
553352
  componentsToRemove.push(child);
552335
553353
  }
552336
553354
  if (componentsToRemove.length === 0 || !this.scrollbackController.archiveComponents(componentsToRemove)) return false;
@@ -552343,7 +553361,24 @@ releaseChannelQueueAtSafePoint() {
552343
553361
  this.state.transcriptEntries = this.state.transcriptEntries.filter((e) => !toRemove.has(e));
552344
553362
  return true;
552345
553363
  }
552346
- mergeCurrentTurnSteps() {
553364
+ showTurnDiagnostics() {
553365
+ if (this.session === undefined || this.session.isClosed) {
553366
+ this.clearTurnDiagnosticsPanel();
553367
+ this.showStatus('No open session for /diagnostics.');
553368
+ return;
553369
+ }
553370
+ const lines = buildTurnDiagnosticLines(this.sessionEventHandler.turnDiagnostics.snapshot());
553371
+ this.clearTurnDiagnosticsPanel();
553372
+ this.turnDiagnosticsPanel = new UsagePanelComponent(()=>lines, 'primary', ' Turn diagnostics ');
553373
+ this.state.transcriptContainer.addChild(this.turnDiagnosticsPanel);
553374
+ this.state.ui.requestRender();
553375
+ }
553376
+ clearTurnDiagnosticsPanel() {
553377
+ if (this.turnDiagnosticsPanel === undefined) return;
553378
+ this.state.transcriptContainer.removeChild(this.turnDiagnosticsPanel);
553379
+ this.turnDiagnosticsPanel = undefined;
553380
+ }
553381
+ mergeCurrentTurnSteps() {
552347
553382
  if (TRANSCRIPT_KEEP_RECENT_STEPS <= 0) return false;
552348
553383
  const children = this.state.transcriptContainer.children;
552349
553384
  let turnStart = -1;
@@ -552360,7 +553395,7 @@ releaseChannelQueueAtSafePoint() {
552360
553395
  summaryIndex = i;
552361
553396
  continue;
552362
553397
  }
552363
- if (child instanceof AssistantMessageComponent) continue;
553398
+ if (child instanceof AssistantMessageComponent || child === this.turnDiagnosticsPanel) continue;
552364
553399
  stepIndices.push(i);
552365
553400
  }
552366
553401
  if (stepIndices.length <= TRANSCRIPT_KEEP_RECENT_STEPS) return false;
@@ -552416,7 +553451,7 @@ releaseChannelQueueAtSafePoint() {
552416
553451
  for (let i = turnStart + 1; i < turnEnd; i++) {
552417
553452
  const child = children[i];
552418
553453
  if (child instanceof StepSummaryComponent) summaryIndex = i;
552419
- else if (child instanceof AssistantMessageComponent) continue;
553454
+ else if (child instanceof AssistantMessageComponent || child === this.turnDiagnosticsPanel) continue;
552420
553455
  else stepIndices.push(i);
552421
553456
  }
552422
553457
  if (stepIndices.length > TRANSCRIPT_KEEP_RECENT_STEPS) {