blun-king-cli 9.1.654 → 9.1.655

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,9 @@ 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":"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"},
21225
+ {"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
21226
  {
21199
21227
  id: "local_auth",
21200
21228
  title: "Local authentication",
@@ -29215,11 +29243,11 @@ var init_load = __esmMin((() => {
29215
29243
  }));
29216
29244
  var agent_default$1;
29217
29245
  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";
29246
+ 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
29247
  }));
29220
29248
  var coder_default;
29221
29249
  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";
29250
+ 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
29251
  }));
29224
29252
  var explore_default;
29225
29253
  var init_explore = __esmMin((() => {
@@ -235435,7 +235463,7 @@ var init_engine = __esmMin((() => {
235435
235463
  return results;
235436
235464
  }
235437
235465
  hasUncoveredMatcher(event, target, previousTargets) {
235438
- const covered = new Set(this.matchingHooks(event, target));
235466
+ const covered = new Set(this.matchingHooks(event, target).filter(hook => wave3NamesFileTool(hook.matcher ?? "", target)));
235439
235467
  return previousTargets.some(previous => this.matchingHooks(event, previous).some(hook => !covered.has(hook)));
235440
235468
  }
235441
235469
  matchingHooks(event, matcherValue) {
@@ -239712,7 +239740,7 @@ var init_plan_mode_guard_deny = __esmMin((() => {
239712
239740
  evaluate(context) {
239713
239741
  if (!this.agent.planMode.isActive) return;
239714
239742
  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." };
239743
+ if (toolName === "ApplyPatch" || toolName === "EditBatch") return { kind: "deny", message: `${toolName} is not available in plan mode. Call ExitPlanMode before patching files.` };
239716
239744
  if (toolName === "Write" || toolName === "Edit") {
239717
239745
  const planFilePath = this.agent.planMode.planFilePath;
239718
239746
  if (planFilePath === null) return {
@@ -239856,7 +239884,7 @@ var init_user_configured_rules = __esmMin((() => {
239856
239884
  firstMatchingRule(context, decision) {
239857
239885
  const rules = this.agent.permission.data().rules.filter((rule) => USER_CONFIGURED_SCOPES.has(rule.scope));
239858
239886
  const name = context.toolCall.name;
239859
- const subjects = name === "ApplyPatch" && decision !== "allow" ? [name, "Edit", "Write"] : [name];
239887
+ const subjects = decision !== "allow" ? [name, ...inheritedFileRestrictions(name)] : [name];
239860
239888
  for (const rule of rules) {
239861
239889
  if (rule.decision !== decision) continue;
239862
239890
  for (const toolName of subjects) {
@@ -240023,10 +240051,12 @@ var init_permission = __esmMin((() => {
240023
240051
  }
240024
240052
  async prepareToolCall(context) {
240025
240053
  context.signal.throwIfAborted();
240026
- if (context.toolCall.name === "ApplyPatch" && this.agent.hooks !== void 0) {
240054
+ const batchName = context.toolCall.name;
240055
+ const inherited = inheritedFileRestrictions(batchName);
240056
+ if (inherited.length > 0 && this.agent.hooks !== void 0) {
240027
240057
  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.`
240058
+ if (this.agent.hooks.hasUncoveredMatcher(event, batchName, inherited)) return {
240059
+ 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
240060
  };
240031
240061
  }
240032
240062
  }
@@ -259348,6 +259378,546 @@ const ApplyPatchTool = (() => {
259348
259378
  return ApplyPatchTool;
259349
259379
  })();
259350
259380
  // END WAVE 1 APPLY PATCH
259381
+ import { constants as batchConstants } from "node:fs";
259382
+ import { createHash as batchHash } from "node:crypto";
259383
+ let editBatchToolClass;
259384
+ function createEditBatchTool(kaos, workspace) {
259385
+ editBatchToolClass ??= (() => {
259386
+ const constants = batchConstants, createHash = batchHash;
259387
+ const { link, lstat, mkdir, mkdtemp, open, realpath, rename, rmdir, unlink } = wavePatchFs;
259388
+ const { dirname, isAbsolute, join, parse, relative } = wavePatchPath;
259389
+ const z = { array, string, boolean: boolean$1, strictObject: (shape) => object$1(shape).strict() };
259390
+ class ExactEditError extends Error {
259391
+ editNumber;
259392
+ constructor(editNumber, message){
259393
+ super(message), this.editNumber = editNumber;
259394
+ }
259395
+ }
259396
+ function planReplacements(content, path, edits) {
259397
+ const matches = [];
259398
+ for (const [index, { old_string: before, new_string: replacement, replace_all: all }] of edits.entries()){
259399
+ const editNumber = index + 1;
259400
+ if (!before) throw new ExactEditError(editNumber, 'old_string must not be empty.');
259401
+ let count = 0;
259402
+ for(let start = content.indexOf(before); start !== -1; start = content.indexOf(before, start + before.length)){
259403
+ count++;
259404
+ if (all || count === 1) matches.push({
259405
+ start,
259406
+ end: start + before.length,
259407
+ replacement,
259408
+ editNumber
259409
+ });
259410
+ }
259411
+ if (count === 0) {
259412
+ 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.`);
259413
+ }
259414
+ if (!all && count > 1) {
259415
+ 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.');
259416
+ }
259417
+ }
259418
+ matches.sort((a, b)=>a.start - b.start);
259419
+ let previousEnd = 0;
259420
+ for (const match of matches){
259421
+ if (match.start < previousEnd) throw new ExactEditError(match.editNumber, `Multiple edits overlap in ${path}. No file was changed.`);
259422
+ previousEnd = match.end;
259423
+ }
259424
+ return matches;
259425
+ }
259426
+ function applyReplacements(content, matches) {
259427
+ const output = [];
259428
+ let position = 0;
259429
+ for (const { start, end, replacement } of matches){
259430
+ output.push(content.slice(position, start), replacement);
259431
+ position = end;
259432
+ }
259433
+ output.push(content.slice(position));
259434
+ return output.join('');
259435
+ }
259436
+ function replaceExactText(raw, path, edits) {
259437
+ const modelView = toModelTextView(raw);
259438
+ const matches = planReplacements(modelView.text, path, edits);
259439
+ const text = materializeModelText(applyReplacements(modelView.text, matches), modelView.lineEndingStyle);
259440
+ return {
259441
+ text,
259442
+ count: matches.length
259443
+ };
259444
+ }
259445
+ function assertUniqueBatchPaths(paths) {
259446
+ const seen = new Set();
259447
+ const keys = paths.map((path)=>path.replaceAll('\\', '/').toLowerCase());
259448
+ for (const key of keys){
259449
+ if (seen.has(key)) throw new Error('Patch names the same file more than once.');
259450
+ seen.add(key);
259451
+ }
259452
+ for (const key of keys){
259453
+ for(let at = key.lastIndexOf('/'); at > 0; at = key.lastIndexOf('/', at - 1)){
259454
+ if (seen.has(key.slice(0, at))) throw new Error('Patch file targets overlap.');
259455
+ }
259456
+ }
259457
+ }
259458
+ async function commitPatchPlan(changes, apply, signal) {
259459
+ const undoStack = [];
259460
+ try {
259461
+ for (const change of changes){
259462
+ signal.throwIfAborted();
259463
+ await apply(change, (undo)=>undoStack.push(undo));
259464
+ }
259465
+ signal.throwIfAborted();
259466
+ } catch (cause) {
259467
+ const failures = [];
259468
+ for (const undo of undoStack.reverse()){
259469
+ try {
259470
+ await undo();
259471
+ } catch (error) {
259472
+ failures.push(error);
259473
+ }
259474
+ }
259475
+ if (failures.length !== 0) {
259476
+ throw new AggregateError(failures, 'Patch failed and could not be fully rolled back.', {
259477
+ cause
259478
+ });
259479
+ }
259480
+ throw cause;
259481
+ }
259482
+ }
259483
+ function unsafeDirectory() {
259484
+ return new Error('Patch parent must be a regular directory without path aliases.');
259485
+ }
259486
+ function changedFile() {
259487
+ return new Error('A patch target changed during validation. Retry with the current file.');
259488
+ }
259489
+ function assertPatchPathSpelling(path) {
259490
+ if (process.platform !== 'win32') return;
259491
+ const verbatim = /^(?:[/\\]{2}[?.][/\\]|[a-z]:[^/\\])/i;
259492
+ const reserved = /^(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|COM[0-9\u00b9\u00b2\u00b3]|LPT[0-9\u00b9\u00b2\u00b3])(?:\.|$)/i;
259493
+ 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.');
259494
+ }
259495
+ async function statPatchPath(path) {
259496
+ try {
259497
+ return await lstat(path, {
259498
+ bigint: true
259499
+ });
259500
+ } catch (error) {
259501
+ if (error.code !== 'ENOENT') throw error;
259502
+ return undefined;
259503
+ }
259504
+ }
259505
+ async function inspectPatchDirectory(path) {
259506
+ const missing = [];
259507
+ for(let directory = path;; directory = dirname(directory)){
259508
+ const stat = await statPatchPath(directory);
259509
+ if (stat !== undefined) {
259510
+ if (!stat.isDirectory() || relative(directory, await realpath(directory)) !== '') throw unsafeDirectory();
259511
+ return {
259512
+ path: directory,
259513
+ stat,
259514
+ missing: missing.reverse()
259515
+ };
259516
+ }
259517
+ if (dirname(directory) === directory) throw unsafeDirectory();
259518
+ missing.push(directory);
259519
+ }
259520
+ }
259521
+ async function assertPatchDirectory(directory) {
259522
+ const current = await statPatchPath(directory.path);
259523
+ if (current === undefined || !current.isDirectory() || !samePatchFile(directory.stat, current) || relative(directory.path, await realpath(directory.path)) !== '') throw unsafeDirectory();
259524
+ }
259525
+ function samePatchFile(left, right) {
259526
+ return left.ino === right.ino && left.dev === right.dev;
259527
+ }
259528
+ function samePatchFileVersion(left, right) {
259529
+ return samePatchFile(left, right) && left.nlink === right.nlink && left.mode === right.mode && left.ctimeNs === right.ctimeNs && left.mtimeNs === right.mtimeNs && left.size === right.size;
259530
+ }
259531
+ async function inspectLocalPatchFile(path, signal) {
259532
+ signal.throwIfAborted();
259533
+ if (!isAbsolute(path)) throw new Error('Patch validation requires a resolved file path.');
259534
+ assertPatchPathSpelling(path);
259535
+ const directory = await inspectPatchDirectory(dirname(path));
259536
+ if (directory.missing.length !== 0) return undefined;
259537
+ const expected = await statPatchPath(path);
259538
+ if (expected === undefined) return undefined;
259539
+ if (!expected.isFile() || expected.nlink !== 1n || relative(path, await realpath(path)) !== '') {
259540
+ throw new Error('Patch target must be an unlinked regular file without path aliases.');
259541
+ }
259542
+ signal.throwIfAborted();
259543
+ const handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
259544
+ try {
259545
+ const opened = await handle.stat({
259546
+ bigint: true
259547
+ });
259548
+ await assertPatchDirectory(directory);
259549
+ if (!opened.isFile() || !samePatchFileVersion(opened, expected)) throw changedFile();
259550
+ const bytes = Buffer.allocUnsafe(Number(expected.size));
259551
+ let length = 0;
259552
+ while(length < bytes.length){
259553
+ signal.throwIfAborted();
259554
+ const { bytesRead } = await handle.read(bytes, length, bytes.length - length, length);
259555
+ if (bytesRead === 0) break;
259556
+ length += bytesRead;
259557
+ }
259558
+ const finished = await handle.stat({
259559
+ bigint: true
259560
+ });
259561
+ const current = await statPatchPath(path);
259562
+ await assertPatchDirectory(directory);
259563
+ signal.throwIfAborted();
259564
+ if (length !== bytes.length || current === undefined || !samePatchFileVersion(finished, expected) || !samePatchFileVersion(current, expected)) throw changedFile();
259565
+ let text;
259566
+ try {
259567
+ text = new TextDecoder('utf-8', {
259568
+ fatal: true,
259569
+ ignoreBOM: true
259570
+ }).decode(bytes);
259571
+ } catch {
259572
+ throw new Error('Patch target must contain UTF-8 text.');
259573
+ }
259574
+ if (text.includes('\0')) throw new Error('Patch target must contain UTF-8 text.');
259575
+ return {
259576
+ text,
259577
+ stat: expected
259578
+ };
259579
+ } finally{
259580
+ await handle.close();
259581
+ }
259582
+ }
259583
+ function changed() {
259584
+ return new Error('A patch target changed or became unavailable.');
259585
+ }
259586
+ async function requireFile(path, expected, links) {
259587
+ const stat = await statPatchPath(path);
259588
+ if (stat === undefined || !stat.isFile() || stat.nlink !== links || !samePatchFile(expected, stat)) {
259589
+ throw changed();
259590
+ }
259591
+ return stat;
259592
+ }
259593
+ async function requireVersion(path, expected) {
259594
+ if (!samePatchFileVersion(await requireFile(path, expected, 1n), expected)) throw changed();
259595
+ }
259596
+ async function parentFor(path, onRollback) {
259597
+ let parent = await inspectPatchDirectory(dirname(path));
259598
+ const missing = parent.missing;
259599
+ if (onRollback === undefined && missing.length !== 0) throw changed();
259600
+ for (const child of missing){
259601
+ await assertPatchDirectory(parent);
259602
+ await mkdir(child);
259603
+ const created = await inspectPatchDirectory(child);
259604
+ onRollback(()=>removeDirectory(created));
259605
+ parent = created;
259606
+ }
259607
+ await assertPatchDirectory(parent);
259608
+ return parent;
259609
+ }
259610
+ async function removeDirectory(directory) {
259611
+ await assertPatchDirectory(directory);
259612
+ await rmdir(directory.path);
259613
+ }
259614
+ async function writeThroughHandle(file, text) {
259615
+ const bytes = Buffer.from(text, 'utf8');
259616
+ let offset = 0;
259617
+ while(offset < bytes.length){
259618
+ const { bytesWritten } = await file.write(bytes, offset, bytes.length - offset, offset);
259619
+ if (bytesWritten === 0) throw new Error('Patch file write did not advance.');
259620
+ offset += bytesWritten;
259621
+ }
259622
+ await file.truncate(bytes.length);
259623
+ await file.sync();
259624
+ }
259625
+ async function createFile(path, text, onRollback, signal) {
259626
+ const parent = await parentFor(path, onRollback);
259627
+ signal.throwIfAborted();
259628
+ const file = await open(path, 'wx', 0o666);
259629
+ let created;
259630
+ onRollback(async ()=>{
259631
+ if (created === undefined) throw changed();
259632
+ await assertPatchDirectory(parent);
259633
+ await requireVersion(path, created);
259634
+ await unlink(path);
259635
+ });
259636
+ try {
259637
+ created = await file.stat({
259638
+ bigint: true
259639
+ });
259640
+ await assertPatchDirectory(parent);
259641
+ await requireVersion(path, created);
259642
+ signal.throwIfAborted();
259643
+ try {
259644
+ await writeThroughHandle(file, text);
259645
+ } finally{
259646
+ created = await file.stat({
259647
+ bigint: true
259648
+ });
259649
+ }
259650
+ } finally{
259651
+ await file.close();
259652
+ }
259653
+ }
259654
+ async function updateFile(path, parent, original, text, onRollback, signal) {
259655
+ const flags = constants.O_WRONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
259656
+ const withFile = async (expected, write)=>{
259657
+ await assertPatchDirectory(parent);
259658
+ await requireVersion(path, expected);
259659
+ const file = await open(path, flags);
259660
+ try {
259661
+ if (!samePatchFileVersion(expected, await file.stat({
259662
+ bigint: true
259663
+ }))) throw changed();
259664
+ await assertPatchDirectory(parent);
259665
+ await requireVersion(path, expected);
259666
+ await write(file);
259667
+ } finally{
259668
+ await file.close();
259669
+ }
259670
+ };
259671
+ await withFile(original.stat, async (file)=>{
259672
+ signal.throwIfAborted();
259673
+ let writtenVersion;
259674
+ onRollback(async ()=>{
259675
+ if (writtenVersion === undefined) throw changed();
259676
+ await withFile(writtenVersion, (restored)=>writeThroughHandle(restored, original.text));
259677
+ });
259678
+ try {
259679
+ await writeThroughHandle(file, text);
259680
+ } finally{
259681
+ writtenVersion = await file.stat({
259682
+ bigint: true
259683
+ });
259684
+ }
259685
+ });
259686
+ }
259687
+ async function moveFile(change, parent, onRollback, signal) {
259688
+ const { path, to, original } = change;
259689
+ const destination = await parentFor(to, onRollback);
259690
+ await assertPatchDirectory(parent);
259691
+ await requireVersion(path, original.stat);
259692
+ signal.throwIfAborted();
259693
+ await link(path, to);
259694
+ let moved = false;
259695
+ onRollback(async ()=>{
259696
+ await assertPatchDirectory(parent);
259697
+ await assertPatchDirectory(destination);
259698
+ const links = moved ? 1n : 2n;
259699
+ await requireFile(to, original.stat, links);
259700
+ if (moved) await link(to, path);
259701
+ await requireFile(path, original.stat, 2n);
259702
+ await requireFile(to, original.stat, 2n);
259703
+ await unlink(to);
259704
+ });
259705
+ await requireFile(to, original.stat, 2n);
259706
+ await assertPatchDirectory(parent);
259707
+ await requireFile(path, original.stat, 2n);
259708
+ signal.throwIfAborted();
259709
+ await unlink(path);
259710
+ moved = true;
259711
+ if (change.text !== original.text) {
259712
+ const stat = await requireFile(to, original.stat, 1n);
259713
+ if (stat.mtimeNs !== original.stat.mtimeNs || stat.size !== original.stat.size) throw changed();
259714
+ await updateFile(to, destination, {
259715
+ ...original,
259716
+ stat
259717
+ }, change.text, onRollback, signal);
259718
+ }
259719
+ }
259720
+ async function stageDeletion(path, parent, original, onRollback, onSuccess, signal) {
259721
+ await requireVersion(path, original.stat);
259722
+ signal.throwIfAborted();
259723
+ const stage = await inspectPatchDirectory(await mkdtemp(join(parent.path, '.blun-patch-')));
259724
+ onRollback(()=>removeDirectory(stage));
259725
+ const saved = join(stage.path, 'original');
259726
+ await assertPatchDirectory(parent);
259727
+ await assertPatchDirectory(stage);
259728
+ await requireVersion(path, original.stat);
259729
+ signal.throwIfAborted();
259730
+ await rename(path, saved);
259731
+ onRollback(async ()=>{
259732
+ await assertPatchDirectory(parent);
259733
+ await assertPatchDirectory(stage);
259734
+ await requireFile(saved, original.stat, 1n);
259735
+ await link(saved, path);
259736
+ await requireFile(path, original.stat, 2n);
259737
+ await requireFile(saved, original.stat, 2n);
259738
+ await unlink(saved);
259739
+ });
259740
+ const stored = await requireFile(saved, original.stat, 1n);
259741
+ onSuccess(async ()=>{
259742
+ await assertPatchDirectory(stage);
259743
+ await requireVersion(saved, stored);
259744
+ await unlink(saved);
259745
+ await removeDirectory(stage);
259746
+ });
259747
+ }
259748
+ async function commitLocalPatch(changes, signal) {
259749
+ if (changes.some((change)=>'text' in change && change.text.includes('\0'))) {
259750
+ throw new Error('Patch content must be UTF-8 text.');
259751
+ }
259752
+ const cleanups = [];
259753
+ await commitPatchPlan(changes, async (change, onRollback)=>{
259754
+ if (change.kind === 'add') return createFile(change.path, change.text, onRollback, signal);
259755
+ const parent = await parentFor(change.path);
259756
+ if (change.kind === 'move') return moveFile(change, parent, onRollback, signal);
259757
+ if (change.kind === 'delete') {
259758
+ return stageDeletion(change.path, parent, change.original, onRollback, (cleanup)=>cleanups.push(cleanup), signal);
259759
+ }
259760
+ return updateFile(change.path, parent, change.original, change.text, onRollback, signal);
259761
+ }, signal);
259762
+ const results = await Promise.allSettled(cleanups.map((cleanup)=>cleanup()));
259763
+ return {
259764
+ cleanupFailed: results.some((result)=>result.status === 'rejected')
259765
+ };
259766
+ }
259767
+ function resolveLocalBatchPath(raw, kaos, workspace) {
259768
+ if (/[\x00-\x1f\x7f\u202a-\u202e\u2066-\u2069]/.test(raw)) {
259769
+ throw new Error('A patch path contains unsupported control characters.');
259770
+ }
259771
+ assertPatchPathSpelling(raw);
259772
+ const path = resolvePathAccessPath(raw, {
259773
+ kaos,
259774
+ workspace,
259775
+ operation: 'write'
259776
+ });
259777
+ assertPatchPathSpelling(path);
259778
+ if (!isWithinWorkspace(path, workspace, kaos.pathClass())) {
259779
+ throw new Error('Every patch target must be inside the workspace.');
259780
+ }
259781
+ return path;
259782
+ }
259783
+ function localBatchAccess(name, targets, subject, kaos, workspace) {
259784
+ const options = {
259785
+ cwd: workspace.workspaceDir,
259786
+ pathClass: kaos.pathClass(),
259787
+ homeDir: kaos.gethome()
259788
+ };
259789
+ const matchesTargets = (pattern, any)=>{
259790
+ if (pattern.startsWith('batch:')) return pattern === subject;
259791
+ const matches = (path)=>matchesPathRuleSubject(pattern, path, options);
259792
+ return any ? targets.some(matches) : targets.every(matches);
259793
+ };
259794
+ return {
259795
+ accesses: targets.flatMap(ToolAccesses.readWriteFile),
259796
+ approvalRule: literalRulePattern(name, subject),
259797
+ matchesRule: (pattern, decision)=>matchesTargets(pattern, decision !== "allow")
259798
+ };
259799
+ }
259800
+ const InputSchema = z.strictObject({
259801
+ edits: z.array(z.strictObject({
259802
+ path: z.string().min(1).describe('An existing UTF-8 file inside the local workspace.'),
259803
+ edits: z.array(z.strictObject({
259804
+ oldText: z.string().min(1).describe('Exact text from Read, without the line numbers.'),
259805
+ newText: z.string().describe('Replacement text. Use LF for files shown with normalized CRLF endings.'),
259806
+ replaceAll: z.boolean().optional().describe('Replace all occurrences. Otherwise the match must be unique.')
259807
+ })).min(1).describe('Non-overlapping matches against the original contents of this file.')
259808
+ })).min(1).max(25).describe('Group replacements by file and name each target once.')
259809
+ });
259810
+ function fileFailure(error) {
259811
+ if (error instanceof PathSecurityError) {
259812
+ if (error.code === 'PATH_SENSITIVE') return 'Sensitive file access is blocked.';
259813
+ if (error.code === 'PATH_OUTSIDE_WORKSPACE') return 'Every target must be inside the workspace.';
259814
+ return 'Invalid file path.';
259815
+ }
259816
+ const code = error?.code;
259817
+ if (typeof code === 'string' && /^E[A-Z0-9_]+$/.test(code)) return `Could not access or modify a file (${code}).`;
259818
+ return error instanceof Error ? error.message : 'Could not edit the file.';
259819
+ }
259820
+ function quotePath(path) {
259821
+ return JSON.stringify(path).replace(/[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, (character)=>'\\u' + character.charCodeAt(0).toString(16).padStart(4, '0'));
259822
+ }
259823
+ function exceedsLineHint(text) {
259824
+ let lines = text.length > 0 && !/[\r\n]$/.test(text) ? 1 : 0;
259825
+ for (const _ of text.matchAll(/\r\n|[\r\n]/g)){
259826
+ if (++lines > 500) return true;
259827
+ }
259828
+ return false;
259829
+ }
259830
+ class EditBatchTool {
259831
+ kaos;
259832
+ workspace;
259833
+ name = 'EditBatch';
259834
+ 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.';
259835
+ parameters = toInputJsonSchema(InputSchema);
259836
+ constructor(kaos, workspace){
259837
+ this.kaos = kaos;
259838
+ this.workspace = workspace;
259839
+ }
259840
+ resolveExecution(args) {
259841
+ const files = args.edits.map((file)=>{
259842
+ const displayPath = quotePath(file.path);
259843
+ try {
259844
+ return {
259845
+ ...file,
259846
+ path: resolveLocalBatchPath(file.path, this.kaos, this.workspace),
259847
+ displayPath
259848
+ };
259849
+ } catch (error) {
259850
+ throw new Error(`${displayPath}: ${fileFailure(error)}`, {
259851
+ cause: error
259852
+ });
259853
+ }
259854
+ });
259855
+ const targets = files.map((file)=>file.path);
259856
+ assertUniqueBatchPaths(targets);
259857
+ const subject = 'batch:' + createHash('sha256').update(JSON.stringify(targets)).digest('hex');
259858
+ const summary = `Edit text in ${files.length} file(s)`;
259859
+ return {
259860
+ ...localBatchAccess(this.name, targets, subject, this.kaos, this.workspace),
259861
+ description: summary,
259862
+ display: {
259863
+ kind: 'generic',
259864
+ summary,
259865
+ detail: files.map(({ path, edits })=>`${quotePath(path)} (${edits.length} edit(s))`).join('\n')
259866
+ },
259867
+ execute: ({ signal })=>this.executeBatch(files, signal)
259868
+ };
259869
+ }
259870
+ async executeBatch(files, signal) {
259871
+ try {
259872
+ const changes = [];
259873
+ const longFiles = [];
259874
+ let replacements = 0;
259875
+ for (const { path, displayPath, edits } of files){
259876
+ try {
259877
+ signal.throwIfAborted();
259878
+ const original = await inspectLocalPatchFile(path, signal);
259879
+ if (original === undefined) throw new Error('File does not exist.');
259880
+ const noChange = edits.findIndex((edit)=>edit.oldText === edit.newText);
259881
+ if (noChange !== -1) throw new ExactEditError(noChange + 1, 'oldText and newText are identical.');
259882
+ const { text, count } = replaceExactText(original.text, displayPath, edits.map((edit)=>({
259883
+ old_string: edit.oldText,
259884
+ new_string: edit.newText,
259885
+ replace_all: edit.replaceAll
259886
+ })));
259887
+ if (text !== original.text) {
259888
+ changes.push({
259889
+ kind: 'update',
259890
+ path,
259891
+ original,
259892
+ text
259893
+ });
259894
+ replacements += count;
259895
+ if (exceedsLineHint(text)) longFiles.push(displayPath);
259896
+ }
259897
+ } catch (error) {
259898
+ return {
259899
+ isError: true,
259900
+ output: `${displayPath}${error instanceof ExactEditError ? ` edit ${error.editNumber}` : ''}: ${fileFailure(error)}`
259901
+ };
259902
+ }
259903
+ }
259904
+ const { cleanupFailed } = await commitLocalPatch(changes, signal);
259905
+ return {
259906
+ 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.' : '')
259907
+ };
259908
+ } catch (error) {
259909
+ return {
259910
+ isError: true,
259911
+ output: fileFailure(error)
259912
+ };
259913
+ }
259914
+ }
259915
+ }
259916
+ return EditBatchTool;
259917
+ })();
259918
+ return new editBatchToolClass(kaos, workspace);
259919
+ }
259920
+ // END WAVE 3 EDIT BATCH
259351
259921
  function makeEditInputSchema() {
259352
259922
  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
259923
  const replacementSchema = object$1({
@@ -267095,6 +267665,7 @@ var init_turn = __esmMin((() => {
267095
267665
  "Write",
267096
267666
  "Edit",
267097
267667
  "ApplyPatch",
267668
+ "EditBatch",
267098
267669
  "Grep",
267099
267670
  "Glob",
267100
267671
  "Bash",
@@ -270943,6 +271514,7 @@ var init_tool$1 = __esmMin((() => {
270943
271514
  new WriteTool(kaos, workspace, () => this.agent.context.history, toolServices?.lsp),
270944
271515
  new EditTool(kaos, workspace, () => this.agent.context.history, toolServices?.lsp),
270945
271516
  kaos instanceof LocalKaos && new ApplyPatchTool(kaos, { workspaceDir: cwd, additionalDirs: this.agent.getAdditionalDirs() }),
271517
+ kaos instanceof LocalKaos && this.agent.experimentalFlags.enabled("edit_batch") && createEditBatchTool(kaos, { workspaceDir: cwd, additionalDirs: this.agent.getAdditionalDirs() }),
270946
271518
  new GrepTool(kaos, workspace, this.agent.telemetry),
270947
271519
  new GlobTool(kaos, workspace, this.agent.telemetry),
270948
271520
  new BashTool(kaos, cwd, background, {
@@ -381450,6 +382022,7 @@ var init_stdin_buffer = __esmMin((() => {
381450
382022
  BRACKETED_PASTE_START = "\x1B[200~";
381451
382023
  BRACKETED_PASTE_END = "\x1B[201~";
381452
382024
  StdinBuffer = class extends EventEmitter {
382025
+ get bracketedPasteActive() { return this.pasteMode; }
381453
382026
  buffer = "";
381454
382027
  timeout = null;
381455
382028
  timeoutMs;
@@ -381633,6 +382206,7 @@ var init_terminal$2 = __esmMin((() => {
381633
382206
  KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS = 150;
381634
382207
  KITTY_KEYBOARD_PROTOCOL_QUERY = `\x1b[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1b[?u\x1b[c`;
381635
382208
  ProcessTerminal = class {
382209
+ get bracketedPasteActive() { return this.stdinBuffer?.bracketedPasteActive === true; }
381636
382210
  wasRaw = false;
381637
382211
  inputHandler;
381638
382212
  resizeHandler;
@@ -443307,12 +443881,13 @@ var init_custom_editor = __esmMin((() => {
443307
443881
  if (this.expandPasteMarkerAtCursor()) return;
443308
443882
  if (this.onPasteImage !== void 0) {
443309
443883
  const handler = this.onPasteImage;
443310
- handler().then((handled) => {
443884
+ this.wave3Paste = (this.wave3Paste ?? 0) + 1;
443885
+ Promise.resolve().then(() => handler()).then((handled) => {
443311
443886
  if (!handled) {
443312
443887
  this.onTextPaste?.();
443313
443888
  super.handleInput.call(this, normalized);
443314
443889
  }
443315
- });
443890
+ }).finally(() => { this.wave3Paste--; });
443316
443891
  return;
443317
443892
  }
443318
443893
  }
@@ -501771,6 +502346,57 @@ var init_telegram_channel = __esmMin((() => {
501771
502346
  BLUN_NODE_FALLBACK_SUBCOMMAND = "__plugin_run_node";
501772
502347
  PLACEHOLDER_RE = /replace|paste|your[-_]|xxxx/i;
501773
502348
  TelegramChannelController = class {
502349
+ wave3Published;
502350
+ wave3Running = false;
502351
+ wave3QuietBoundary(sessionId) {
502352
+ if (this.sessionQueueError !== undefined || this.sessionDelivery.inFlight.size || this.sessionDelivery.controlsInFlight.size) return;
502353
+ const captured = captureSessionQueueBoundary(this.queueFile);
502354
+ const saved = readSessionQueue(this.sessionDelivery.stateFile);
502355
+ if (captured === undefined && saved === undefined) return "absent";
502356
+ if (captured === undefined || saved === undefined || saved.activeSessionId !== sessionId ||
502357
+ saved.fileId !== captured.fileId || saved.frontier !== captured.frontier ||
502358
+ pendingSessionQueue(saved, sessionId).length || statSync(this.queueFile).size !== captured.frontier) return;
502359
+ return JSON.stringify(captured);
502360
+ }
502361
+ async wave3DrainControls() {
502362
+ if (this.stopped || !this.ownsChannel() || this.wave3Running) return;
502363
+ this.wave3Running = true;
502364
+ try {
502365
+ const sessionId = this.host.wave3ControlSession?.();
502366
+ if (sessionId === undefined) {
502367
+ if (this.wave3Published) wave3Control.clearBinding(this.dir, this.wave3Published);
502368
+ this.wave3Published = undefined;
502369
+ return;
502370
+ }
502371
+ const botId = wave3Control.readBotId(this.dir);
502372
+ if (botId === undefined) return;
502373
+ const binding = wave3Control.publishBinding(this.dir, this.ownerId, botId, sessionId, this.wave3Published);
502374
+ this.wave3Published = binding;
502375
+ if (!this.host.wave3ControlAvailable?.()) return;
502376
+ const boundary = this.wave3QuietBoundary(sessionId);
502377
+ if (boundary === undefined) return;
502378
+ const controls = new wave3Control.ConsoleControlState(this.dir, botId);
502379
+ for (const name of controls.names("pending")) {
502380
+ const control = controls.read("pending", name), address = wave3Control.controlAddress(name);
502381
+ if (!address || !control || control.ownerId !== binding.ownerId) continue;
502382
+ const canCommit = () => {
502383
+ try {
502384
+ return !this.stopped && this.ownsChannel() && this.host.wave3ControlSession?.() === sessionId &&
502385
+ wave3Control.controlIsFresh(control.queuedAt) &&
502386
+ wave3Control.readBotId(this.dir) === botId &&
502387
+ wave3Control.readBinding(this.dir, botId)?.ownerId === binding.ownerId &&
502388
+ wave3Control.hasSessionControlGrant(this.dir, address.chatId) &&
502389
+ this.wave3QuietBoundary(sessionId) === boundary;
502390
+ } catch { return false; }
502391
+ };
502392
+ if (!canCommit() || !controls.claim(name, control)) continue;
502393
+ const ok = await this.host.wave3RunControl?.(control.command, canCommit);
502394
+ if (wave3Control.hasSessionControlGrant(this.dir, address.chatId)) controls.complete(name, ok === true);
502395
+ return;
502396
+ }
502397
+ } catch { /* An unavailable binding cannot authorize a transition. */ }
502398
+ finally { this.wave3Running = false; }
502399
+ }
501774
502400
  host;
501775
502401
  dir;
501776
502402
  sessionScope;
@@ -502015,6 +502641,7 @@ var init_telegram_channel = __esmMin((() => {
502015
502641
  }
502016
502642
  beginStop() {
502017
502643
  if (this.stopped) return;
502644
+ if (this.wave3Published) try { wave3Control.clearBinding(this.dir, this.wave3Published); } catch {}
502018
502645
  this.stopped = true;
502019
502646
  this.activeOwner = false;
502020
502647
  if (this.heartbeatTimer !== void 0) clearInterval(this.heartbeatTimer);
@@ -502113,6 +502740,7 @@ var init_telegram_channel = __esmMin((() => {
502113
502740
  }
502114
502741
  if (this.sessionScope !== void 0) {
502115
502742
  this.pollSessionQueue(this.sessionScope());
502743
+ void this.wave3DrainControls();
502116
502744
  return;
502117
502745
  }
502118
502746
  let stats;
@@ -513031,17 +513659,22 @@ async function handleReloadTuiCommand(host) {
513031
513659
  const warning = await applyReloadedTuiConfigWithFallback(host, loaded.config) ?? loaded.warning;
513032
513660
  host.showStatus(warning ?? uiText("reload.tui.complete"), warning === void 0 ? "success" : "error");
513033
513661
  }
513034
- async function handleReloadCommand(host) {
513662
+ async function handleReloadCommand(host, beforeReload) {
513035
513663
  const loaded = await loadTuiConfigForReload();
513036
513664
  const session = host.session;
513037
513665
  if (session !== void 0) {
513038
- const reload = () => session.reloadSession({
513666
+ let didReload = false;
513667
+ const reload = () => {
513668
+ if (beforeReload && !beforeReload()) return;
513669
+ didReload = true;
513670
+ return session.reloadSession({
513039
513671
  forcePluginSessionStartReminder: true,
513040
513672
  mcpServers: sessionMcpServers()
513041
- });
513673
+ });
513674
+ };
513042
513675
  if (host.withGoalReplyReload !== void 0) await host.withGoalReplyReload(session, reload);
513043
513676
  else await reload();
513044
- if (host.session !== session) return;
513677
+ if (!didReload || host.session !== session) return;
513045
513678
  if (host.state.appState.modelFallbackAllowed === false) {
513046
513679
  const model = host.state.appState.model.trim();
513047
513680
  if (model.length > 0) await session.setModel(model, { allowFallback: false });
@@ -513054,6 +513687,7 @@ async function handleReloadCommand(host) {
513054
513687
  const warning = await applyReloadedTuiConfigWithFallback(host, loaded.config) ?? loaded.warning;
513055
513688
  if (session === void 0) host.showStatus(warning ?? uiText("reload.runtime.completeWithoutSession"), warning === void 0 ? "success" : "error");
513056
513689
  else if (warning !== void 0) host.showStatus(warning, "error");
513690
+ return session !== undefined && host.session === session;
513057
513691
  }
513058
513692
  async function loadTuiConfigForReload() {
513059
513693
  try {
@@ -549065,15 +549699,27 @@ activeApprovalPanel;
549065
549699
  this.updateEditorBorderHighlight();
549066
549700
  }
549067
549701
  localTransitionRequest;
549068
- tryLocalTransition(text) {
549702
+ wave3ControlUiSafe() {
549703
+ const { appState, editor, ui, terminal, btwPanelContainer, livePane } = this.state;
549704
+ return !this.aborted && !this.isShuttingDown && !this.gatewayStartup &&
549705
+ !this.state.externalEditorRunning && !this.editorReplacementActive && this.state.activeDialog === null &&
549706
+ livePane.pendingApproval === null && livePane.pendingQuestion === null &&
549707
+ !this.queueCommandRunning && !this.manualPromptInFlight && !this.queueSteerInFlight && !this.localShellConsentRequest &&
549708
+ !ui.hasOverlay() && editor.focused === true && editor.getText() === "" && !editor.wave3Paste &&
549709
+ appState.inputMode === "prompt" && !terminal.bracketedPasteActive && btwPanelContainer.children.length === 0 &&
549710
+ appState.streamingPhase === "idle" && !appState.isCompacting && !appState.isReplaying &&
549711
+ this.state.queuedMessages.length === 0 && !Array.from(this.sessionEventHandler.backgroundTasks.values()).some(info => !isTerminalBackgroundTask(info));
549712
+ }
549713
+ tryLocalTransition(text, remoteCommit) {
549069
549714
  const command = text.trim();
549070
549715
  const session = this.session;
549071
549716
  if ((command !== "/new" && command !== "/reload") || session?.connectionKind !== "embedded" || this.gatewayStartup || this.state.appState.isReplaying) return false;
549072
- if (this.localTransitionRequest !== void 0) return true;
549717
+ if (this.localTransitionRequest !== void 0) return remoteCommit === undefined;
549718
+ if (remoteCommit && (!remoteCommit() || !this.wave3ControlUiSafe())) return false;
549073
549719
  const request = {};
549074
549720
  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;
549721
+ if (!remoteCommit) this.track("input_command", { command: command.slice(1) });
549722
+ const current = () => this.localTransitionRequest === request && this.session === session && !this.aborted && !this.isShuttingDown && (!remoteCommit || (request.draft === undefined && remoteCommit() && this.wave3ControlUiSafe()));
549077
549723
  const run = async () => {
549078
549724
  let lease;
549079
549725
  try {
@@ -549088,16 +549734,16 @@ activeApprovalPanel;
549088
549734
  await new Promise(resolve => setTimeout(resolve, 25));
549089
549735
  }
549090
549736
  if (!current()) return;
549091
- await this.withTelegramQueuePaused(async (boundary) => {
549737
+ return await this.withTelegramQueuePaused(async (boundary) => {
549092
549738
  await session.waitForPromptAdmissions();
549093
549739
  if (!current() || this.state.queuedMessages.length !== 0) return;
549094
549740
  await lease.settle();
549095
549741
  if (!current() || this.state.queuedMessages.length !== 0) return;
549096
- if (command === "/new") await this.createNewSessionRuntime(boundary, current);
549097
- else await handleReloadCommand(this);
549742
+ if (command === "/new") return this.createNewSessionRuntime(boundary, current, remoteCommit !== undefined);
549743
+ return handleReloadCommand(this, remoteCommit ? current : undefined);
549098
549744
  });
549099
549745
  } catch {
549100
- if (current()) this.showError("Session change could not complete. Check the session before retrying.");
549746
+ if (!remoteCommit && current()) this.showError("Session change could not complete. Check the session before retrying.");
549101
549747
  } finally {
549102
549748
  lease?.release();
549103
549749
  if (this.localTransitionRequest === request) {
@@ -549107,6 +549753,7 @@ activeApprovalPanel;
549107
549753
  }
549108
549754
  }
549109
549755
  };
549756
+ if (remoteCommit) return run();
549110
549757
  void run();
549111
549758
  return true;
549112
549759
  }
@@ -550345,6 +550992,10 @@ releaseChannelQueueAtSafePoint() {
550345
550992
  }
550346
550993
  let controller;
550347
550994
  controller = new TelegramChannelController({
550995
+ wave3ControlSession: () => isExperimentalFlagEnabled("telegram_session_control") &&
550996
+ this.session?.connectionKind === "embedded" && this.telegramSessionScope?.sessionId === this.session.id ? this.session.id : undefined,
550997
+ wave3ControlAvailable: () => this.localTransitionRequest === undefined && !this.deferUserMessages && this.wave3ControlUiSafe(),
550998
+ wave3RunControl: (command, canCommit) => this.tryLocalTransition("/" + command, canCommit),
550348
550999
  inject: (envelope, acknowledge) => {
550349
551000
  this.injectChannelMessage(envelope, acknowledge);
550350
551001
  },
@@ -551399,21 +552050,52 @@ releaseChannelQueueAtSafePoint() {
551399
552050
  });
551400
552051
  }
551401
552052
  sessionBindingRequest;
551402
- async setSessionRuntime(session, queueScope, modelPrepared = false) {
552053
+ async setSessionRuntime(session, queueScope, modelPrepared = false, beforeAdoption) {
551403
552054
  if (this.aborted || this.isShuttingDown) return;
551404
552055
  const request = {};
551405
- this.sessionBindingRequest = request;
552056
+ const previousBindingRequest = this.sessionBindingRequest;
551406
552057
  const original = this.session;
551407
552058
  let owner = original;
551408
552059
  let adopted = false;
551409
552060
  const isCurrent = () => !this.aborted && !this.isShuttingDown && this.sessionBindingRequest === request && this.session === owner;
552061
+ let goalDetached = false;
552062
+ const restorePreviousBinding = async (memoryCleared) => {
552063
+ if (!isCurrent()) return;
552064
+ this.sessionBindingRequest = previousBindingRequest;
552065
+ if (original === void 0) return;
552066
+ try {
552067
+ if (goalDetached) await this.goalChannelReplies.restore(original, this.state.appState.goal ?? null);
552068
+ } finally {
552069
+ if (memoryCleared && !this.aborted && !this.isShuttingDown &&
552070
+ this.session === original && this.sessionBindingRequest === previousBindingRequest) {
552071
+ await this.personalMemoryController.refresh();
552072
+ }
552073
+ }
552074
+ };
551410
552075
  try {
552076
+ if (beforeAdoption && !beforeAdoption()) return;
552077
+ this.sessionBindingRequest = request;
551411
552078
  if (!modelPrepared) await session.setModel(BLUN_KING_MODEL_ALIAS, { allowFallback: false });
551412
552079
  if (!isCurrent()) return;
551413
- if (this.session !== session) await this.goalChannelReplies.detach();
552080
+ if (this.session !== session) {
552081
+ await this.goalChannelReplies.detach();
552082
+ goalDetached = true;
552083
+ }
551414
552084
  if (!isCurrent()) return;
552085
+ if (beforeAdoption && !beforeAdoption()) {
552086
+ await restorePreviousBinding(false);
552087
+ return;
552088
+ }
551415
552089
  await this.personalMemoryController.clear(this.session);
551416
552090
  if (!isCurrent()) return;
552091
+ if (beforeAdoption) {
552092
+ if (!beforeAdoption()) {
552093
+ await restorePreviousBinding(true);
552094
+ return;
552095
+ }
552096
+ this.resetSessionRuntime();
552097
+ this.sessionBindingRequest = request;
552098
+ }
551417
552099
  const previous = this.unloadCurrentSession(approvalCancellationFeedback("switching_session"));
551418
552100
  this.sessionBindingRequest = request;
551419
552101
  owner = void 0;
@@ -551887,7 +552569,7 @@ releaseChannelQueueAtSafePoint() {
551887
552569
  await this.createNewSessionRuntime(boundary);
551888
552570
  });
551889
552571
  }
551890
- async createNewSessionRuntime(boundary, canCommit = () => true) {
552572
+ async createNewSessionRuntime(boundary, canCommit = () => true, remote = false) {
551891
552573
  if (this.aborted || this.isShuttingDown) return;
551892
552574
  if (this.state.appState.isReplaying) {
551893
552575
  this.showError(uiText("blunTui.session.createReplayBlocked"));
@@ -551914,12 +552596,12 @@ releaseChannelQueueAtSafePoint() {
551914
552596
  this.showError(uiText("blunTui.session.createFailed", { error: msg }));
551915
552597
  return;
551916
552598
  }
551917
- this.resetSessionRuntime();
552599
+ if (!remote) this.resetSessionRuntime();
551918
552600
  const binding = await this.setSessionRuntime(session, {
551919
552601
  sessionId: session.id,
551920
552602
  mode: "new",
551921
552603
  boundary
551922
- }, true);
552604
+ }, true, remote ? isCurrent : undefined);
551923
552605
  if (this.aborted || this.isShuttingDown || this.session !== session) return;
551924
552606
  const isActive = () => !this.aborted && !this.isShuttingDown && this.session === session && binding !== void 0 && this.sessionBindingRequest === binding;
551925
552607
  if (!isActive()) return;
@@ -551947,6 +552629,7 @@ releaseChannelQueueAtSafePoint() {
551947
552629
  this.showStatus(uiText("blunTui.session.started", { sessionId: session.id }));
551948
552630
  this.showSessionWarnings(session);
551949
552631
  this.showConfigWarningsIfAny();
552632
+ return true;
551950
552633
  }
551951
552634
  /** Surface config.toml load warnings (degraded or kept-previous config) in the status bar. */
551952
552635
  async showConfigWarningsIfAny() {