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/worker-host.mjs CHANGED
@@ -5411,6 +5411,31 @@ function parsePattern(pattern) {
5411
5411
  argPattern
5412
5412
  };
5413
5413
  }
5414
+ function wave3NamesFileTool(pattern, target) {
5415
+ const group = /^\^?\((?:\?:)?([^()]+)\)\$?$/u.exec(pattern);
5416
+ const names = (group?.[1] ?? pattern).split('|');
5417
+ return names.every((name)=>/^\^?[A-Za-z][\w]*\$?$/u.test(name)) && names.some((name)=>name.replace(/^\^|\$$/gu, '') === target);
5418
+ }
5419
+ const RESTRICTED_FILE_BATCH_SUBJECTS = new Map([
5420
+ [
5421
+ 'ApplyPatch',
5422
+ [
5423
+ 'Write',
5424
+ 'Edit'
5425
+ ]
5426
+ ],
5427
+ [
5428
+ 'EditBatch',
5429
+ [
5430
+ 'Write',
5431
+ 'Edit',
5432
+ 'ApplyPatch'
5433
+ ]
5434
+ ]
5435
+ ]);
5436
+ function inheritedFileRestrictions(tool) {
5437
+ return RESTRICTED_FILE_BATCH_SUBJECTS.get(tool) ?? [];
5438
+ }
5414
5439
  function matchPermissionRule({ rule, toolName, execution }) {
5415
5440
  let parsed;
5416
5441
  try {
@@ -20969,6 +20994,9 @@ function isRecord$7(value) {
20969
20994
  * not equal the master switch 'BLUN_EXPERIMENTAL_FLAG'; `id` must not be 'flag'.
20970
20995
  */
20971
20996
  const FLAG_DEFINITIONS = [
20997
+ {"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"},
20998
+ {"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"},
20999
+ {"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"},
20972
21000
  {
20973
21001
  id: "local_auth",
20974
21002
  title: "Local authentication",
@@ -28962,8 +28990,8 @@ function readRequiredSource(sources, path) {
28962
28990
  function normalizeSourcePath(path) {
28963
28991
  return normalize$3(path.replaceAll("\\", "/")).replace(/^\.\//, "");
28964
28992
  }
28965
- var 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";
28966
- var 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";
28993
+ var 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";
28994
+ var 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";
28967
28995
  var explore_default = "extends: agent\nname: explore\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 You are a codebase exploration specialist. Your role is EXCLUSIVELY to search, read, and analyze existing code and resources. You do NOT have access to project file editing tools. MistakeRecord is the sole write-capable exception: it may record a concrete refutation in shared BLUN learning memory, never modify project files.\n\n Your strengths:\n - Rapidly finding files using glob patterns\n - Searching code and text with powerful regex patterns\n - Reading and analyzing file contents\n - Running read-only shell commands (git log, git diff, ls, find, etc.)\n\n Guidelines:\n - Use Glob for broad file pattern matching. Prefer patterns with a literal anchor (extension or subdirectory); pure wildcards like `*` or `**/*` are allowed but usually truncate at the match cap.\n - Use Grep for searching file contents with regex\n - Use Read when you know the specific file path\n - Use Bash ONLY for read-only operations (ls, git status, git log, git diff, find)\n - NEVER use Bash for any file creation or modification commands\n - Use WebSearch or FetchURL when a question needs external context (library documentation, error messages, upstream APIs); the local codebase remains your primary domain\n - Adapt your search depth based on the thoroughness level specified by the caller\n - Wherever possible, spawn multiple parallel tool calls for grepping and reading files to maximize speed\n\n If the prompt includes a <git-context> block, use it to orient yourself about the repository state before starting your investigation.\n\n You are meant to be a fast agent. Complete the search request efficiently and report your findings clearly in a structured format.\nwhenToUse: |\n Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (e.g. \"src/**/*.yaml\"), search code for keywords (e.g. \"database connection\"), or answer questions about the codebase (e.g. \"how does the auth module work?\"). When calling this agent, specify the desired thoroughness level: \"quick\" for basic searches, \"medium\" for moderate exploration, or \"thorough\" for comprehensive analysis across multiple locations and naming conventions. Use this agent for any read-only exploration that will clearly require more than 3 search queries. Prefer launching multiple explore agents concurrently when investigating independent questions.\ntools:\n - Bash\n - Read\n - ReadBatch\n - ProgrammaticTool\n - ReadMediaFile\n - Glob\n - Grep\n - MistakeRecord\n - WebSearch\n - FetchURL\n";
28968
28996
  var init_default = "You are a software engineering expert with many years of programming experience. Please explore the current project directory to understand the project's architecture and main details.\n\nTask requirements:\n1. Analyze the project structure and identify key configuration files (such as pyproject.toml, package.json, Cargo.toml, etc.).\n2. Understand the project's technology stack, build process and runtime architecture.\n3. Identify how the code is organized and main module divisions.\n4. Discover project-specific development conventions, testing strategies, and deployment processes.\n\nAfter the exploration, do a thorough summary of your findings and write it to the `AGENTS.md` file in the project root, replacing the file's previous content. If the file already exists, read it first and carry forward whatever is still accurate — the result should be one coherent, up-to-date file, not an append.\n\nFor your information, `AGENTS.md` is a file intended to be read by AI coding agents. Expect the reader of this file to know nothing about the project.\n\nYou should compose this file according to the actual project content. Do not make any assumptions or generalizations. Ensure the information is accurate and useful. You must use the natural language that is mainly used in the project's comments and documentation.\n\nPopular sections that people usually write in `AGENTS.md` are:\n\n- Project overview\n- Build and test commands\n- Code style guidelines\n- Testing instructions\n- Security considerations\n";
28969
28997
  const PROFILE_SOURCES = {
@@ -183233,6 +183261,7 @@ var SubagentBatch = class {
183233
183261
  description: task.description,
183234
183262
  swarmIndex: task.swarmIndex,
183235
183263
  runInBackground: task.runInBackground,
183264
+ foregroundTaskId: task.foregroundTaskId,
183236
183265
  signal: attempt.controller.signal,
183237
183266
  onReady: () => {
183238
183267
  this.markAttemptReady(attempt);
@@ -183889,13 +183918,32 @@ admissionClosed = false;
183889
183918
  if (profile === void 0) throw new Error(`Subagent profile "${profileName}" was not found`);
183890
183919
  return profile;
183891
183920
  }
183892
- runWithActiveChild(childId, options, run) {
183921
+ *foregroundClientToolWaits(parent, turnId, step) {
183922
+ for (const [childId, active] of this.activeChildren) {
183923
+ if (active.controller.signal.aborted) continue;
183924
+ const scope = active.foregroundScope;
183925
+ if (scope?.parent !== parent || scope.turnId !== turnId || scope.step !== step) continue;
183926
+ if (scope.taskId === undefined) {
183927
+ if (active.runInBackground) continue;
183928
+ } else {
183929
+ const task = parent.background.getTask(scope.taskId);
183930
+ if (task?.status !== "running" || task.detached !== false ||
183931
+ String(task.swarm?.turnId) !== String(turnId) || task.swarm?.toolCallId !== active.parentToolCallId) continue;
183932
+ }
183933
+ const count = this.session.getReadyAgent(childId)?.tools.clientToolWait?.count ?? 0;
183934
+ if (count > 0) yield { toolCallId: active.parentToolCallId, count };
183935
+ }
183936
+ }
183937
+ runWithActiveChild(childId, options, run) {
183893
183938
  this.assertAdmissionOpen();
183894
183939
  this.assertInputLease(options);
183895
183940
  if (this.activeChildren.has(childId)) throw new Error(`Agent instance "${childId}" is already running`);
183896
183941
  const controller = new AbortController();
183897
183942
  const unlinkAbortSignal = linkAbortSignal(options.signal, controller);
183898
- const active = {
183943
+ const parent = this.session.getReadyAgent(this.ownerAgentId);
183944
+ const step = parent?.turn.activeModelStep;
183945
+ const active = {
183946
+ foregroundScope: step > 0 ? { parent, step, turnId: parent.turn.currentId, taskId: options.foregroundTaskId } : undefined,
183899
183947
  controller,
183900
183948
  parentToolCallId: options.parentToolCallId,
183901
183949
  runInBackground: options.runInBackground
@@ -233926,9 +233974,13 @@ var ContextMemory = class {
233926
233974
  return true;
233927
233975
  }
233928
233976
  data() {
233977
+ const { lastTurnEndReason } = this.agent;
233978
+ const { clientToolWait } = this.agent.tools;
233929
233979
  return {
233930
233980
  history: this.history,
233931
- tokenCount: this.tokenCount
233981
+ tokenCount: this.tokenCount,
233982
+ ...(lastTurnEndReason === undefined ? {} : { lastTurnEndReason }),
233983
+ ...(clientToolWait === undefined ? {} : { clientToolWait })
233932
233984
  };
233933
233985
  }
233934
233986
  resumeState() {
@@ -234994,7 +235046,7 @@ var HookEngine = class {
234994
235046
  return results;
234995
235047
  }
234996
235048
  hasUncoveredMatcher(event, target, previousTargets) {
234997
- const covered = new Set(this.matchingHooks(event, target));
235049
+ const covered = new Set(this.matchingHooks(event, target).filter(hook => wave3NamesFileTool(hook.matcher ?? "", target)));
234998
235050
  return previousTargets.some(previous => this.matchingHooks(event, previous).some(hook => !covered.has(hook)));
234999
235051
  }
235000
235052
  matchingHooks(event, matcherValue) {
@@ -239164,7 +239216,7 @@ var PlanModeGuardDenyPermissionPolicy = class {
239164
239216
  evaluate(context) {
239165
239217
  if (!this.agent.planMode.isActive) return;
239166
239218
  const toolName = context.toolCall.name;
239167
- if (toolName === "ApplyPatch") return { kind: "deny", message: "ApplyPatch is not available in plan mode. Call ExitPlanMode before patching files." };
239219
+ if (toolName === "ApplyPatch" || toolName === "EditBatch") return { kind: "deny", message: `${toolName} is not available in plan mode. Call ExitPlanMode before patching files.` };
239168
239220
  if (toolName === "Write" || toolName === "Edit") {
239169
239221
  const planFilePath = this.agent.planMode.planFilePath;
239170
239222
  if (planFilePath === null) return {
@@ -239287,7 +239339,7 @@ var UserConfiguredPermissionPolicy = class {
239287
239339
  firstMatchingRule(context, decision) {
239288
239340
  const rules = this.agent.permission.data().rules.filter((rule) => USER_CONFIGURED_SCOPES.has(rule.scope));
239289
239341
  const name = context.toolCall.name;
239290
- const subjects = name === "ApplyPatch" && decision !== "allow" ? [name, "Edit", "Write"] : [name];
239342
+ const subjects = decision !== "allow" ? [name, ...inheritedFileRestrictions(name)] : [name];
239291
239343
  for (const rule of rules) {
239292
239344
  if (rule.decision !== decision) continue;
239293
239345
  for (const toolName of subjects) {
@@ -239436,10 +239488,12 @@ var PermissionManager = class {
239436
239488
  }
239437
239489
  async prepareToolCall(context) {
239438
239490
  context.signal.throwIfAborted();
239439
- if (context.toolCall.name === "ApplyPatch" && this.agent.hooks !== void 0) {
239491
+ const batchName = context.toolCall.name;
239492
+ const inherited = inheritedFileRestrictions(batchName);
239493
+ if (inherited.length > 0 && this.agent.hooks !== void 0) {
239440
239494
  for (const event of ["PreToolUse", "PermissionRequest"]) {
239441
- if (this.agent.hooks.hasUncoveredMatcher(event, "ApplyPatch", ["Edit", "Write"])) return {
239442
- 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.`
239495
+ if (this.agent.hooks.hasUncoveredMatcher(event, batchName, inherited)) return {
239496
+ 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.`
239443
239497
  };
239444
239498
  }
239445
239499
  }
@@ -257914,7 +257968,7 @@ var AgentSwarmTool = class AgentSwarmTool {
257914
257968
  }),
257915
257969
  start: async (sink) => {
257916
257970
  // The manager owns cancellation for the whole batch, including slots not yet launched.
257917
- const managed = tasks.map((task) => ({ ...task, runInBackground: true, signal: sink.signal }));
257971
+ const managed = tasks.map((task) => ({ ...task, runInBackground: true, signal: sink.signal, foregroundTaskId: detached ? undefined : taskId }));
257918
257972
  const result = await this.runSwarm(managed);
257919
257973
  sink.signal.throwIfAborted();
257920
257974
  outcomes = result.map(({ status }) => status);
@@ -258965,6 +259019,546 @@ const ApplyPatchTool = (() => {
258965
259019
  return ApplyPatchTool;
258966
259020
  })();
258967
259021
  // END WAVE 1 APPLY PATCH
259022
+ import { constants as batchConstants } from "node:fs";
259023
+ import { createHash as batchHash } from "node:crypto";
259024
+ let editBatchToolClass;
259025
+ function createEditBatchTool(kaos, workspace) {
259026
+ editBatchToolClass ??= (() => {
259027
+ const constants = batchConstants, createHash = batchHash;
259028
+ const { link, lstat, mkdir, mkdtemp, open, realpath, rename, rmdir, unlink } = wavePatchFs;
259029
+ const { dirname, isAbsolute, join, parse, relative } = wavePatchPath;
259030
+ const z = { array, string, boolean: boolean$1, strictObject: (shape) => object(shape).strict() };
259031
+ class ExactEditError extends Error {
259032
+ editNumber;
259033
+ constructor(editNumber, message){
259034
+ super(message), this.editNumber = editNumber;
259035
+ }
259036
+ }
259037
+ function planReplacements(content, path, edits) {
259038
+ const matches = [];
259039
+ for (const [index, { old_string: before, new_string: replacement, replace_all: all }] of edits.entries()){
259040
+ const editNumber = index + 1;
259041
+ if (!before) throw new ExactEditError(editNumber, 'old_string must not be empty.');
259042
+ let count = 0;
259043
+ for(let start = content.indexOf(before); start !== -1; start = content.indexOf(before, start + before.length)){
259044
+ count++;
259045
+ if (all || count === 1) matches.push({
259046
+ start,
259047
+ end: start + before.length,
259048
+ replacement,
259049
+ editNumber
259050
+ });
259051
+ }
259052
+ if (count === 0) {
259053
+ 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.`);
259054
+ }
259055
+ if (!all && count > 1) {
259056
+ 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.');
259057
+ }
259058
+ }
259059
+ matches.sort((a, b)=>a.start - b.start);
259060
+ let previousEnd = 0;
259061
+ for (const match of matches){
259062
+ if (match.start < previousEnd) throw new ExactEditError(match.editNumber, `Multiple edits overlap in ${path}. No file was changed.`);
259063
+ previousEnd = match.end;
259064
+ }
259065
+ return matches;
259066
+ }
259067
+ function applyReplacements(content, matches) {
259068
+ const output = [];
259069
+ let position = 0;
259070
+ for (const { start, end, replacement } of matches){
259071
+ output.push(content.slice(position, start), replacement);
259072
+ position = end;
259073
+ }
259074
+ output.push(content.slice(position));
259075
+ return output.join('');
259076
+ }
259077
+ function replaceExactText(raw, path, edits) {
259078
+ const modelView = toModelTextView(raw);
259079
+ const matches = planReplacements(modelView.text, path, edits);
259080
+ const text = materializeModelText(applyReplacements(modelView.text, matches), modelView.lineEndingStyle);
259081
+ return {
259082
+ text,
259083
+ count: matches.length
259084
+ };
259085
+ }
259086
+ function assertUniqueBatchPaths(paths) {
259087
+ const seen = new Set();
259088
+ const keys = paths.map((path)=>path.replaceAll('\\', '/').toLowerCase());
259089
+ for (const key of keys){
259090
+ if (seen.has(key)) throw new Error('Patch names the same file more than once.');
259091
+ seen.add(key);
259092
+ }
259093
+ for (const key of keys){
259094
+ for(let at = key.lastIndexOf('/'); at > 0; at = key.lastIndexOf('/', at - 1)){
259095
+ if (seen.has(key.slice(0, at))) throw new Error('Patch file targets overlap.');
259096
+ }
259097
+ }
259098
+ }
259099
+ async function commitPatchPlan(changes, apply, signal) {
259100
+ const undoStack = [];
259101
+ try {
259102
+ for (const change of changes){
259103
+ signal.throwIfAborted();
259104
+ await apply(change, (undo)=>undoStack.push(undo));
259105
+ }
259106
+ signal.throwIfAborted();
259107
+ } catch (cause) {
259108
+ const failures = [];
259109
+ for (const undo of undoStack.reverse()){
259110
+ try {
259111
+ await undo();
259112
+ } catch (error) {
259113
+ failures.push(error);
259114
+ }
259115
+ }
259116
+ if (failures.length !== 0) {
259117
+ throw new AggregateError(failures, 'Patch failed and could not be fully rolled back.', {
259118
+ cause
259119
+ });
259120
+ }
259121
+ throw cause;
259122
+ }
259123
+ }
259124
+ function unsafeDirectory() {
259125
+ return new Error('Patch parent must be a regular directory without path aliases.');
259126
+ }
259127
+ function changedFile() {
259128
+ return new Error('A patch target changed during validation. Retry with the current file.');
259129
+ }
259130
+ function assertPatchPathSpelling(path) {
259131
+ if (process.platform !== 'win32') return;
259132
+ const verbatim = /^(?:[/\\]{2}[?.][/\\]|[a-z]:[^/\\])/i;
259133
+ const reserved = /^(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|COM[0-9\u00b9\u00b2\u00b3]|LPT[0-9\u00b9\u00b2\u00b3])(?:\.|$)/i;
259134
+ 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.');
259135
+ }
259136
+ async function statPatchPath(path) {
259137
+ try {
259138
+ return await lstat(path, {
259139
+ bigint: true
259140
+ });
259141
+ } catch (error) {
259142
+ if (error.code !== 'ENOENT') throw error;
259143
+ return undefined;
259144
+ }
259145
+ }
259146
+ async function inspectPatchDirectory(path) {
259147
+ const missing = [];
259148
+ for(let directory = path;; directory = dirname(directory)){
259149
+ const stat = await statPatchPath(directory);
259150
+ if (stat !== undefined) {
259151
+ if (!stat.isDirectory() || relative(directory, await realpath(directory)) !== '') throw unsafeDirectory();
259152
+ return {
259153
+ path: directory,
259154
+ stat,
259155
+ missing: missing.reverse()
259156
+ };
259157
+ }
259158
+ if (dirname(directory) === directory) throw unsafeDirectory();
259159
+ missing.push(directory);
259160
+ }
259161
+ }
259162
+ async function assertPatchDirectory(directory) {
259163
+ const current = await statPatchPath(directory.path);
259164
+ if (current === undefined || !current.isDirectory() || !samePatchFile(directory.stat, current) || relative(directory.path, await realpath(directory.path)) !== '') throw unsafeDirectory();
259165
+ }
259166
+ function samePatchFile(left, right) {
259167
+ return left.ino === right.ino && left.dev === right.dev;
259168
+ }
259169
+ function samePatchFileVersion(left, right) {
259170
+ return samePatchFile(left, right) && left.nlink === right.nlink && left.mode === right.mode && left.ctimeNs === right.ctimeNs && left.mtimeNs === right.mtimeNs && left.size === right.size;
259171
+ }
259172
+ async function inspectLocalPatchFile(path, signal) {
259173
+ signal.throwIfAborted();
259174
+ if (!isAbsolute(path)) throw new Error('Patch validation requires a resolved file path.');
259175
+ assertPatchPathSpelling(path);
259176
+ const directory = await inspectPatchDirectory(dirname(path));
259177
+ if (directory.missing.length !== 0) return undefined;
259178
+ const expected = await statPatchPath(path);
259179
+ if (expected === undefined) return undefined;
259180
+ if (!expected.isFile() || expected.nlink !== 1n || relative(path, await realpath(path)) !== '') {
259181
+ throw new Error('Patch target must be an unlinked regular file without path aliases.');
259182
+ }
259183
+ signal.throwIfAborted();
259184
+ const handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
259185
+ try {
259186
+ const opened = await handle.stat({
259187
+ bigint: true
259188
+ });
259189
+ await assertPatchDirectory(directory);
259190
+ if (!opened.isFile() || !samePatchFileVersion(opened, expected)) throw changedFile();
259191
+ const bytes = Buffer.allocUnsafe(Number(expected.size));
259192
+ let length = 0;
259193
+ while(length < bytes.length){
259194
+ signal.throwIfAborted();
259195
+ const { bytesRead } = await handle.read(bytes, length, bytes.length - length, length);
259196
+ if (bytesRead === 0) break;
259197
+ length += bytesRead;
259198
+ }
259199
+ const finished = await handle.stat({
259200
+ bigint: true
259201
+ });
259202
+ const current = await statPatchPath(path);
259203
+ await assertPatchDirectory(directory);
259204
+ signal.throwIfAborted();
259205
+ if (length !== bytes.length || current === undefined || !samePatchFileVersion(finished, expected) || !samePatchFileVersion(current, expected)) throw changedFile();
259206
+ let text;
259207
+ try {
259208
+ text = new TextDecoder('utf-8', {
259209
+ fatal: true,
259210
+ ignoreBOM: true
259211
+ }).decode(bytes);
259212
+ } catch {
259213
+ throw new Error('Patch target must contain UTF-8 text.');
259214
+ }
259215
+ if (text.includes('\0')) throw new Error('Patch target must contain UTF-8 text.');
259216
+ return {
259217
+ text,
259218
+ stat: expected
259219
+ };
259220
+ } finally{
259221
+ await handle.close();
259222
+ }
259223
+ }
259224
+ function changed() {
259225
+ return new Error('A patch target changed or became unavailable.');
259226
+ }
259227
+ async function requireFile(path, expected, links) {
259228
+ const stat = await statPatchPath(path);
259229
+ if (stat === undefined || !stat.isFile() || stat.nlink !== links || !samePatchFile(expected, stat)) {
259230
+ throw changed();
259231
+ }
259232
+ return stat;
259233
+ }
259234
+ async function requireVersion(path, expected) {
259235
+ if (!samePatchFileVersion(await requireFile(path, expected, 1n), expected)) throw changed();
259236
+ }
259237
+ async function parentFor(path, onRollback) {
259238
+ let parent = await inspectPatchDirectory(dirname(path));
259239
+ const missing = parent.missing;
259240
+ if (onRollback === undefined && missing.length !== 0) throw changed();
259241
+ for (const child of missing){
259242
+ await assertPatchDirectory(parent);
259243
+ await mkdir(child);
259244
+ const created = await inspectPatchDirectory(child);
259245
+ onRollback(()=>removeDirectory(created));
259246
+ parent = created;
259247
+ }
259248
+ await assertPatchDirectory(parent);
259249
+ return parent;
259250
+ }
259251
+ async function removeDirectory(directory) {
259252
+ await assertPatchDirectory(directory);
259253
+ await rmdir(directory.path);
259254
+ }
259255
+ async function writeThroughHandle(file, text) {
259256
+ const bytes = Buffer.from(text, 'utf8');
259257
+ let offset = 0;
259258
+ while(offset < bytes.length){
259259
+ const { bytesWritten } = await file.write(bytes, offset, bytes.length - offset, offset);
259260
+ if (bytesWritten === 0) throw new Error('Patch file write did not advance.');
259261
+ offset += bytesWritten;
259262
+ }
259263
+ await file.truncate(bytes.length);
259264
+ await file.sync();
259265
+ }
259266
+ async function createFile(path, text, onRollback, signal) {
259267
+ const parent = await parentFor(path, onRollback);
259268
+ signal.throwIfAborted();
259269
+ const file = await open(path, 'wx', 0o666);
259270
+ let created;
259271
+ onRollback(async ()=>{
259272
+ if (created === undefined) throw changed();
259273
+ await assertPatchDirectory(parent);
259274
+ await requireVersion(path, created);
259275
+ await unlink(path);
259276
+ });
259277
+ try {
259278
+ created = await file.stat({
259279
+ bigint: true
259280
+ });
259281
+ await assertPatchDirectory(parent);
259282
+ await requireVersion(path, created);
259283
+ signal.throwIfAborted();
259284
+ try {
259285
+ await writeThroughHandle(file, text);
259286
+ } finally{
259287
+ created = await file.stat({
259288
+ bigint: true
259289
+ });
259290
+ }
259291
+ } finally{
259292
+ await file.close();
259293
+ }
259294
+ }
259295
+ async function updateFile(path, parent, original, text, onRollback, signal) {
259296
+ const flags = constants.O_WRONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
259297
+ const withFile = async (expected, write)=>{
259298
+ await assertPatchDirectory(parent);
259299
+ await requireVersion(path, expected);
259300
+ const file = await open(path, flags);
259301
+ try {
259302
+ if (!samePatchFileVersion(expected, await file.stat({
259303
+ bigint: true
259304
+ }))) throw changed();
259305
+ await assertPatchDirectory(parent);
259306
+ await requireVersion(path, expected);
259307
+ await write(file);
259308
+ } finally{
259309
+ await file.close();
259310
+ }
259311
+ };
259312
+ await withFile(original.stat, async (file)=>{
259313
+ signal.throwIfAborted();
259314
+ let writtenVersion;
259315
+ onRollback(async ()=>{
259316
+ if (writtenVersion === undefined) throw changed();
259317
+ await withFile(writtenVersion, (restored)=>writeThroughHandle(restored, original.text));
259318
+ });
259319
+ try {
259320
+ await writeThroughHandle(file, text);
259321
+ } finally{
259322
+ writtenVersion = await file.stat({
259323
+ bigint: true
259324
+ });
259325
+ }
259326
+ });
259327
+ }
259328
+ async function moveFile(change, parent, onRollback, signal) {
259329
+ const { path, to, original } = change;
259330
+ const destination = await parentFor(to, onRollback);
259331
+ await assertPatchDirectory(parent);
259332
+ await requireVersion(path, original.stat);
259333
+ signal.throwIfAborted();
259334
+ await link(path, to);
259335
+ let moved = false;
259336
+ onRollback(async ()=>{
259337
+ await assertPatchDirectory(parent);
259338
+ await assertPatchDirectory(destination);
259339
+ const links = moved ? 1n : 2n;
259340
+ await requireFile(to, original.stat, links);
259341
+ if (moved) await link(to, path);
259342
+ await requireFile(path, original.stat, 2n);
259343
+ await requireFile(to, original.stat, 2n);
259344
+ await unlink(to);
259345
+ });
259346
+ await requireFile(to, original.stat, 2n);
259347
+ await assertPatchDirectory(parent);
259348
+ await requireFile(path, original.stat, 2n);
259349
+ signal.throwIfAborted();
259350
+ await unlink(path);
259351
+ moved = true;
259352
+ if (change.text !== original.text) {
259353
+ const stat = await requireFile(to, original.stat, 1n);
259354
+ if (stat.mtimeNs !== original.stat.mtimeNs || stat.size !== original.stat.size) throw changed();
259355
+ await updateFile(to, destination, {
259356
+ ...original,
259357
+ stat
259358
+ }, change.text, onRollback, signal);
259359
+ }
259360
+ }
259361
+ async function stageDeletion(path, parent, original, onRollback, onSuccess, signal) {
259362
+ await requireVersion(path, original.stat);
259363
+ signal.throwIfAborted();
259364
+ const stage = await inspectPatchDirectory(await mkdtemp(join(parent.path, '.blun-patch-')));
259365
+ onRollback(()=>removeDirectory(stage));
259366
+ const saved = join(stage.path, 'original');
259367
+ await assertPatchDirectory(parent);
259368
+ await assertPatchDirectory(stage);
259369
+ await requireVersion(path, original.stat);
259370
+ signal.throwIfAborted();
259371
+ await rename(path, saved);
259372
+ onRollback(async ()=>{
259373
+ await assertPatchDirectory(parent);
259374
+ await assertPatchDirectory(stage);
259375
+ await requireFile(saved, original.stat, 1n);
259376
+ await link(saved, path);
259377
+ await requireFile(path, original.stat, 2n);
259378
+ await requireFile(saved, original.stat, 2n);
259379
+ await unlink(saved);
259380
+ });
259381
+ const stored = await requireFile(saved, original.stat, 1n);
259382
+ onSuccess(async ()=>{
259383
+ await assertPatchDirectory(stage);
259384
+ await requireVersion(saved, stored);
259385
+ await unlink(saved);
259386
+ await removeDirectory(stage);
259387
+ });
259388
+ }
259389
+ async function commitLocalPatch(changes, signal) {
259390
+ if (changes.some((change)=>'text' in change && change.text.includes('\0'))) {
259391
+ throw new Error('Patch content must be UTF-8 text.');
259392
+ }
259393
+ const cleanups = [];
259394
+ await commitPatchPlan(changes, async (change, onRollback)=>{
259395
+ if (change.kind === 'add') return createFile(change.path, change.text, onRollback, signal);
259396
+ const parent = await parentFor(change.path);
259397
+ if (change.kind === 'move') return moveFile(change, parent, onRollback, signal);
259398
+ if (change.kind === 'delete') {
259399
+ return stageDeletion(change.path, parent, change.original, onRollback, (cleanup)=>cleanups.push(cleanup), signal);
259400
+ }
259401
+ return updateFile(change.path, parent, change.original, change.text, onRollback, signal);
259402
+ }, signal);
259403
+ const results = await Promise.allSettled(cleanups.map((cleanup)=>cleanup()));
259404
+ return {
259405
+ cleanupFailed: results.some((result)=>result.status === 'rejected')
259406
+ };
259407
+ }
259408
+ function resolveLocalBatchPath(raw, kaos, workspace) {
259409
+ if (/[\x00-\x1f\x7f\u202a-\u202e\u2066-\u2069]/.test(raw)) {
259410
+ throw new Error('A patch path contains unsupported control characters.');
259411
+ }
259412
+ assertPatchPathSpelling(raw);
259413
+ const path = resolvePathAccessPath(raw, {
259414
+ kaos,
259415
+ workspace,
259416
+ operation: 'write'
259417
+ });
259418
+ assertPatchPathSpelling(path);
259419
+ if (!isWithinWorkspace(path, workspace, kaos.pathClass())) {
259420
+ throw new Error('Every patch target must be inside the workspace.');
259421
+ }
259422
+ return path;
259423
+ }
259424
+ function localBatchAccess(name, targets, subject, kaos, workspace) {
259425
+ const options = {
259426
+ cwd: workspace.workspaceDir,
259427
+ pathClass: kaos.pathClass(),
259428
+ homeDir: kaos.gethome()
259429
+ };
259430
+ const matchesTargets = (pattern, any)=>{
259431
+ if (pattern.startsWith('batch:')) return pattern === subject;
259432
+ const matches = (path)=>matchesPathRuleSubject(pattern, path, options);
259433
+ return any ? targets.some(matches) : targets.every(matches);
259434
+ };
259435
+ return {
259436
+ accesses: targets.flatMap(ToolAccesses.readWriteFile),
259437
+ approvalRule: literalRulePattern(name, subject),
259438
+ matchesRule: (pattern, decision)=>matchesTargets(pattern, decision !== "allow")
259439
+ };
259440
+ }
259441
+ const InputSchema = z.strictObject({
259442
+ edits: z.array(z.strictObject({
259443
+ path: z.string().min(1).describe('An existing UTF-8 file inside the local workspace.'),
259444
+ edits: z.array(z.strictObject({
259445
+ oldText: z.string().min(1).describe('Exact text from Read, without the line numbers.'),
259446
+ newText: z.string().describe('Replacement text. Use LF for files shown with normalized CRLF endings.'),
259447
+ replaceAll: z.boolean().optional().describe('Replace all occurrences. Otherwise the match must be unique.')
259448
+ })).min(1).describe('Non-overlapping matches against the original contents of this file.')
259449
+ })).min(1).max(25).describe('Group replacements by file and name each target once.')
259450
+ });
259451
+ function fileFailure(error) {
259452
+ if (error instanceof PathSecurityError) {
259453
+ if (error.code === 'PATH_SENSITIVE') return 'Sensitive file access is blocked.';
259454
+ if (error.code === 'PATH_OUTSIDE_WORKSPACE') return 'Every target must be inside the workspace.';
259455
+ return 'Invalid file path.';
259456
+ }
259457
+ const code = error?.code;
259458
+ if (typeof code === 'string' && /^E[A-Z0-9_]+$/.test(code)) return `Could not access or modify a file (${code}).`;
259459
+ return error instanceof Error ? error.message : 'Could not edit the file.';
259460
+ }
259461
+ function quotePath(path) {
259462
+ return JSON.stringify(path).replace(/[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, (character)=>'\\u' + character.charCodeAt(0).toString(16).padStart(4, '0'));
259463
+ }
259464
+ function exceedsLineHint(text) {
259465
+ let lines = text.length > 0 && !/[\r\n]$/.test(text) ? 1 : 0;
259466
+ for (const _ of text.matchAll(/\r\n|[\r\n]/g)){
259467
+ if (++lines > 500) return true;
259468
+ }
259469
+ return false;
259470
+ }
259471
+ class EditBatchTool {
259472
+ kaos;
259473
+ workspace;
259474
+ name = 'EditBatch';
259475
+ 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.';
259476
+ parameters = toInputJsonSchema(InputSchema);
259477
+ constructor(kaos, workspace){
259478
+ this.kaos = kaos;
259479
+ this.workspace = workspace;
259480
+ }
259481
+ resolveExecution(args) {
259482
+ const files = args.edits.map((file)=>{
259483
+ const displayPath = quotePath(file.path);
259484
+ try {
259485
+ return {
259486
+ ...file,
259487
+ path: resolveLocalBatchPath(file.path, this.kaos, this.workspace),
259488
+ displayPath
259489
+ };
259490
+ } catch (error) {
259491
+ throw new Error(`${displayPath}: ${fileFailure(error)}`, {
259492
+ cause: error
259493
+ });
259494
+ }
259495
+ });
259496
+ const targets = files.map((file)=>file.path);
259497
+ assertUniqueBatchPaths(targets);
259498
+ const subject = 'batch:' + createHash('sha256').update(JSON.stringify(targets)).digest('hex');
259499
+ const summary = `Edit text in ${files.length} file(s)`;
259500
+ return {
259501
+ ...localBatchAccess(this.name, targets, subject, this.kaos, this.workspace),
259502
+ description: summary,
259503
+ display: {
259504
+ kind: 'generic',
259505
+ summary,
259506
+ detail: files.map(({ path, edits })=>`${quotePath(path)} (${edits.length} edit(s))`).join('\n')
259507
+ },
259508
+ execute: ({ signal })=>this.executeBatch(files, signal)
259509
+ };
259510
+ }
259511
+ async executeBatch(files, signal) {
259512
+ try {
259513
+ const changes = [];
259514
+ const longFiles = [];
259515
+ let replacements = 0;
259516
+ for (const { path, displayPath, edits } of files){
259517
+ try {
259518
+ signal.throwIfAborted();
259519
+ const original = await inspectLocalPatchFile(path, signal);
259520
+ if (original === undefined) throw new Error('File does not exist.');
259521
+ const noChange = edits.findIndex((edit)=>edit.oldText === edit.newText);
259522
+ if (noChange !== -1) throw new ExactEditError(noChange + 1, 'oldText and newText are identical.');
259523
+ const { text, count } = replaceExactText(original.text, displayPath, edits.map((edit)=>({
259524
+ old_string: edit.oldText,
259525
+ new_string: edit.newText,
259526
+ replace_all: edit.replaceAll
259527
+ })));
259528
+ if (text !== original.text) {
259529
+ changes.push({
259530
+ kind: 'update',
259531
+ path,
259532
+ original,
259533
+ text
259534
+ });
259535
+ replacements += count;
259536
+ if (exceedsLineHint(text)) longFiles.push(displayPath);
259537
+ }
259538
+ } catch (error) {
259539
+ return {
259540
+ isError: true,
259541
+ output: `${displayPath}${error instanceof ExactEditError ? ` edit ${error.editNumber}` : ''}: ${fileFailure(error)}`
259542
+ };
259543
+ }
259544
+ }
259545
+ const { cleanupFailed } = await commitLocalPatch(changes, signal);
259546
+ return {
259547
+ 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.' : '')
259548
+ };
259549
+ } catch (error) {
259550
+ return {
259551
+ isError: true,
259552
+ output: fileFailure(error)
259553
+ };
259554
+ }
259555
+ }
259556
+ }
259557
+ return EditBatchTool;
259558
+ })();
259559
+ return new editBatchToolClass(kaos, workspace);
259560
+ }
259561
+ // END WAVE 3 EDIT BATCH
258968
259562
  function makeEditInputSchema() {
258969
259563
  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.");
258970
259564
  const replacementSchema = object({
@@ -266222,6 +266816,7 @@ const BLUN_LEAN_TOOL_NAMES = new Set([
266222
266816
  "Write",
266223
266817
  "Edit",
266224
266818
  "ApplyPatch",
266819
+ "EditBatch",
266225
266820
  "Grep",
266226
266821
  "Glob",
266227
266822
  "Bash",
@@ -266612,7 +267207,10 @@ cancel(turnId, reason) {
266612
267207
  get currentId() {
266613
267208
  return this.turnId;
266614
267209
  }
266615
- get hasActiveTurn() {
267210
+ get activeModelStep() {
267211
+ return this.hasActiveTurn ? this.currentStepByTurn.get(this.currentId) : undefined;
267212
+ }
267213
+ get hasActiveTurn() {
266616
267214
  return this.activeTurn !== null && this.activeTurn !== "resuming";
266617
267215
  }
266618
267216
  ensureActiveTurn() {
@@ -269826,6 +270424,7 @@ var ToolManager = class {
269826
270424
  agent;
269827
270425
  builtinTools = /* @__PURE__ */ new Map();
269828
270426
  userTools = /* @__PURE__ */ new Map();
270427
+ clientToolCalls = new Set();
269829
270428
  mcpTools = /* @__PURE__ */ new Map();
269830
270429
  loopToolsOverride;
269831
270430
  /** server name → list of qualified tool names registered for that server. */
@@ -270012,7 +270611,33 @@ var ToolManager = class {
270012
270611
  cancelShellCommand(commandId) {
270013
270612
  this.shellCommandControllers.get(commandId)?.abort();
270014
270613
  }
270015
- registerUserTool(input) {
270614
+ get clientToolWait() {
270615
+ const { currentId: turnId, activeModelStep: step } = this.agent.turn;
270616
+ if (step === undefined || step === 0) return undefined;
270617
+ const countsByCall = new Map();
270618
+ const add = (toolCallId, count)=>{
270619
+ countsByCall.set(toolCallId, (countsByCall.get(toolCallId) ?? 0) + count);
270620
+ };
270621
+ for (const call of this.clientToolCalls){
270622
+ if (call.turnId === turnId && call.step === step && !call.signal.aborted) add(call.toolCallId, 1);
270623
+ }
270624
+ const children = this.agent.subagentHost?.foregroundClientToolWaits?.(this.agent, turnId, step);
270625
+ if (children !== undefined) {
270626
+ for (const call of children)add(call.toolCallId, call.count);
270627
+ }
270628
+ if (countsByCall.size === 0) return undefined;
270629
+ const calls = Array.from(countsByCall, ([toolCallId, count])=>({
270630
+ toolCallId,
270631
+ count
270632
+ }));
270633
+ return {
270634
+ turnId,
270635
+ step,
270636
+ calls,
270637
+ count: calls.reduce((sum, call)=>sum + call.count, 0)
270638
+ };
270639
+ }
270640
+ registerUserTool(input) {
270016
270641
  this.agent.records.logRecord({
270017
270642
  type: "tools.register_user_tool",
270018
270643
  ...input
@@ -270026,12 +270651,17 @@ var ToolManager = class {
270026
270651
  return {
270027
270652
  approvalRule: name,
270028
270653
  execute: async (context) => {
270029
- return this.agent.rpc.toolCall({
270654
+ const call = { turnId: Number(context.turnId), step: this.agent.turn.activeModelStep,
270655
+ toolCallId: context.toolCallId, signal: context.signal };
270656
+ this.clientToolCalls.add(call);
270657
+ try {
270658
+ return await this.agent.rpc.toolCall({
270030
270659
  turnId: Number(context.turnId),
270031
270660
  toolCallId: context.toolCallId,
270032
270661
  toolName: name,
270033
270662
  args
270034
270663
  }, { signal: context.signal });
270664
+ } finally { this.clientToolCalls.delete(call); }
270035
270665
  }
270036
270666
  };
270037
270667
  }
@@ -270270,6 +270900,7 @@ var ToolManager = class {
270270
270900
  new WriteTool(kaos, workspace, () => this.agent.context.history, toolServices?.lsp),
270271
270901
  new EditTool(kaos, workspace, () => this.agent.context.history, toolServices?.lsp),
270272
270902
  kaos instanceof LocalKaos && new ApplyPatchTool(kaos, { workspaceDir: cwd, additionalDirs: this.agent.getAdditionalDirs() }),
270903
+ kaos instanceof LocalKaos && this.agent.experimentalFlags.enabled("edit_batch") && createEditBatchTool(kaos, { workspaceDir: cwd, additionalDirs: this.agent.getAdditionalDirs() }),
270273
270904
  new GrepTool(kaos, workspace, this.agent.telemetry),
270274
270905
  new GlobTool(kaos, workspace, this.agent.telemetry),
270275
270906
  new BashTool(kaos, cwd, background, {
@@ -271721,9 +272352,11 @@ var Agent$1 = class {
271721
272352
  if (phase === "start") injector.recordToolStart(event);
271722
272353
  else injector.recordToolResult(event);
271723
272354
  }
271724
- emitEvent(event) {
272355
+ lastTurnEndReason;
272356
+ emitEvent(event) {
271725
272357
  if (this.records.restoring) return;
271726
- this.cron?.observeAgentEvent(event);
272358
+ if (event.type === "turn.ended" && event.turnId === this.turn.currentId) this.lastTurnEndReason = event.reason;
272359
+ this.cron?.observeAgentEvent(event);
271727
272360
  return this.rpc?.emitEvent?.(event);
271728
272361
  }
271729
272362
  contextMetrics() {
@@ -349602,10 +350235,6 @@ var SDKRpcClientBase = class {
349602
350235
  sessionId: input.sessionId,
349603
350236
  agentId
349604
350237
  });
349605
- const context = await rpc.getContext({
349606
- sessionId: input.sessionId,
349607
- agentId
349608
- });
349609
350238
  const permission = await rpc.getPermission({
349610
350239
  sessionId: input.sessionId,
349611
350240
  agentId
@@ -349622,6 +350251,10 @@ var SDKRpcClientBase = class {
349622
350251
  sessionId: input.sessionId,
349623
350252
  agentId
349624
350253
  });
350254
+ const context = await rpc.getContext({
350255
+ sessionId: input.sessionId,
350256
+ agentId
350257
+ });
349625
350258
  const maxContextTokens = context.effectiveMaxContextTokens ?? config.modelCapabilities?.max_context_tokens ?? 0;
349626
350259
  const contextTokens = context.projectedTokenCount ?? context.tokenCount;
349627
350260
  const contextUsage = maxContextTokens > 0 ? Math.min(1, Math.max(0, contextTokens / maxContextTokens)) : 0;
@@ -349638,7 +350271,9 @@ var SDKRpcClientBase = class {
349638
350271
  maxContextTokens,
349639
350272
  compactionBudgetTokens: context.compactionBudgetTokens,
349640
350273
  contextUsage,
349641
- usage: hasUsage ? usage : void 0
350274
+ usage: hasUsage ? usage : void 0,
350275
+ lastTurnEndReason: context.lastTurnEndReason,
350276
+ clientToolWait: context.clientToolWait
349642
350277
  };
349643
350278
  }
349644
350279
  async listTools(input) {