blun-king-cli 9.1.655 → 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/LIESMICH.txt CHANGED
@@ -1,4 +1,4 @@
1
- # blun-king-cli 9.1.655
1
+ # blun-king-cli 9.1.656
2
2
 
3
3
 
4
4
  ## Installieren und fortsetzen
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # blun-king-cli 9.1.655
1
+ # blun-king-cli 9.1.656
2
2
 
3
3
 
4
4
  ## Installieren und fortsetzen
package/blun.mjs CHANGED
@@ -21221,6 +21221,7 @@ var FLAG_DEFINITIONS;
21221
21221
  var InputControl, controls, CHANNEL_QUEUE_DEADLINE_MS, QueueDeadlineWatchdog, StoppedInputScopes, SEARCH_LIMITS, SearchStop, active, inside, sessionSearchRequests, ActiveInputDelivery;
21222
21222
  var init_registry$4 = __esmMin((() => {
21223
21223
  FLAG_DEFINITIONS = [
21224
+ {"id":"tui_turn_diagnostics","title":"Local turn diagnostics","description":"Show outcome, model timings, retry notices and prompt hook outcomes in the console.","env":"BLUN_EXPERIMENTAL_TUI_TURN_DIAGNOSTICS","default":false,"surface":"tui"},
21224
21225
  {"id":"telegram_session_control","title":"Telegram session controls","description":"Allow explicitly granted private Telegram session commands.","env":"BLUN_EXPERIMENTAL_TELEGRAM_SESSION_CONTROL","default":false,"surface":"tui"},
21225
21226
  {"id":"edit_batch","title":"Multi-file text edits","description":"Validate and apply exact text replacements across local workspace files.","env":"BLUN_EXPERIMENTAL_EDIT_BATCH","default":false,"surface":"core"},{ id: "original_history", title: "Original history", description: "Read a captured conversation independently of model context.", env: "BLUN_EXPERIMENTAL_ORIGINAL_HISTORY", default: false, surface: "both" },
21226
21227
  {
@@ -183606,6 +183607,7 @@ var init_subagent_batch = __esmMin((() => {
183606
183607
  description: task.description,
183607
183608
  swarmIndex: task.swarmIndex,
183608
183609
  runInBackground: task.runInBackground,
183610
+ foregroundTaskId: task.foregroundTaskId,
183609
183611
  signal: attempt.controller.signal,
183610
183612
  onReady: () => {
183611
183613
  this.markAttemptReady(attempt);
@@ -184289,13 +184291,32 @@ admissionClosed = false;
184289
184291
  if (profile === void 0) throw new Error(`Subagent profile "${profileName}" was not found`);
184290
184292
  return profile;
184291
184293
  }
184292
- runWithActiveChild(childId, options, run) {
184294
+ *foregroundClientToolWaits(parent, turnId, step) {
184295
+ for (const [childId, active] of this.activeChildren) {
184296
+ if (active.controller.signal.aborted) continue;
184297
+ const scope = active.foregroundScope;
184298
+ if (scope?.parent !== parent || scope.turnId !== turnId || scope.step !== step) continue;
184299
+ if (scope.taskId === undefined) {
184300
+ if (active.runInBackground) continue;
184301
+ } else {
184302
+ const task = parent.background.getTask(scope.taskId);
184303
+ if (task?.status !== "running" || task.detached !== false ||
184304
+ String(task.swarm?.turnId) !== String(turnId) || task.swarm?.toolCallId !== active.parentToolCallId) continue;
184305
+ }
184306
+ const count = this.session.getReadyAgent(childId)?.tools.clientToolWait?.count ?? 0;
184307
+ if (count > 0) yield { toolCallId: active.parentToolCallId, count };
184308
+ }
184309
+ }
184310
+ runWithActiveChild(childId, options, run) {
184293
184311
  this.assertAdmissionOpen();
184294
184312
  this.assertInputLease(options);
184295
184313
  if (this.activeChildren.has(childId)) throw new Error(`Agent instance "${childId}" is already running`);
184296
184314
  const controller = new AbortController();
184297
184315
  const unlinkAbortSignal = linkAbortSignal(options.signal, controller);
184298
- const active = {
184316
+ const parent = this.session.getReadyAgent(this.ownerAgentId);
184317
+ const step = parent?.turn.activeModelStep;
184318
+ const active = {
184319
+ foregroundScope: step > 0 ? { parent, step, turnId: parent.turn.currentId, taskId: options.foregroundTaskId } : undefined,
184299
184320
  controller,
184300
184321
  parentToolCallId: options.parentToolCallId,
184301
184322
  runInBackground: options.runInBackground
@@ -234422,9 +234443,13 @@ var init_context$3 = __esmMin((() => {
234422
234443
  return true;
234423
234444
  }
234424
234445
  data() {
234446
+ const { lastTurnEndReason } = this.agent;
234447
+ const { clientToolWait } = this.agent.tools;
234425
234448
  return {
234426
234449
  history: this.history,
234427
- tokenCount: this.tokenCount
234450
+ tokenCount: this.tokenCount,
234451
+ ...(lastTurnEndReason === undefined ? {} : { lastTurnEndReason }),
234452
+ ...(clientToolWait === undefined ? {} : { clientToolWait })
234428
234453
  };
234429
234454
  }
234430
234455
  resumeState() {
@@ -258373,7 +258398,7 @@ var init_agent_swarm = __esmMin((() => {
258373
258398
  }),
258374
258399
  start: async (sink) => {
258375
258400
  // The manager owns cancellation for the whole batch, including slots not yet launched.
258376
- const managed = tasks.map((task) => ({ ...task, runInBackground: true, signal: sink.signal }));
258401
+ const managed = tasks.map((task) => ({ ...task, runInBackground: true, signal: sink.signal, foregroundTaskId: detached ? undefined : taskId }));
258377
258402
  const result = await this.runSwarm(managed);
258378
258403
  sink.signal.throwIfAborted();
258379
258404
  outcomes = result.map(({ status }) => status);
@@ -267946,7 +267971,10 @@ cancel(turnId, reason) {
267946
267971
  get currentId() {
267947
267972
  return this.turnId;
267948
267973
  }
267949
- get hasActiveTurn() {
267974
+ get activeModelStep() {
267975
+ return this.hasActiveTurn ? this.currentStepByTurn.get(this.currentId) : undefined;
267976
+ }
267977
+ get hasActiveTurn() {
267950
267978
  return this.activeTurn !== null && this.activeTurn !== "resuming";
267951
267979
  }
267952
267980
  ensureActiveTurn() {
@@ -271070,6 +271098,7 @@ var init_tool$1 = __esmMin((() => {
271070
271098
  agent;
271071
271099
  builtinTools = /* @__PURE__ */ new Map();
271072
271100
  userTools = /* @__PURE__ */ new Map();
271101
+ clientToolCalls = new Set();
271073
271102
  mcpTools = /* @__PURE__ */ new Map();
271074
271103
  loopToolsOverride;
271075
271104
  /** server name → list of qualified tool names registered for that server. */
@@ -271256,7 +271285,33 @@ var init_tool$1 = __esmMin((() => {
271256
271285
  cancelShellCommand(commandId) {
271257
271286
  this.shellCommandControllers.get(commandId)?.abort();
271258
271287
  }
271259
- registerUserTool(input) {
271288
+ get clientToolWait() {
271289
+ const { currentId: turnId, activeModelStep: step } = this.agent.turn;
271290
+ if (step === undefined || step === 0) return undefined;
271291
+ const countsByCall = new Map();
271292
+ const add = (toolCallId, count)=>{
271293
+ countsByCall.set(toolCallId, (countsByCall.get(toolCallId) ?? 0) + count);
271294
+ };
271295
+ for (const call of this.clientToolCalls){
271296
+ if (call.turnId === turnId && call.step === step && !call.signal.aborted) add(call.toolCallId, 1);
271297
+ }
271298
+ const children = this.agent.subagentHost?.foregroundClientToolWaits?.(this.agent, turnId, step);
271299
+ if (children !== undefined) {
271300
+ for (const call of children)add(call.toolCallId, call.count);
271301
+ }
271302
+ if (countsByCall.size === 0) return undefined;
271303
+ const calls = Array.from(countsByCall, ([toolCallId, count])=>({
271304
+ toolCallId,
271305
+ count
271306
+ }));
271307
+ return {
271308
+ turnId,
271309
+ step,
271310
+ calls,
271311
+ count: calls.reduce((sum, call)=>sum + call.count, 0)
271312
+ };
271313
+ }
271314
+ registerUserTool(input) {
271260
271315
  this.agent.records.logRecord({
271261
271316
  type: "tools.register_user_tool",
271262
271317
  ...input
@@ -271270,12 +271325,17 @@ var init_tool$1 = __esmMin((() => {
271270
271325
  return {
271271
271326
  approvalRule: name,
271272
271327
  execute: async (context) => {
271273
- return this.agent.rpc.toolCall({
271328
+ const call = { turnId: Number(context.turnId), step: this.agent.turn.activeModelStep,
271329
+ toolCallId: context.toolCallId, signal: context.signal };
271330
+ this.clientToolCalls.add(call);
271331
+ try {
271332
+ return await this.agent.rpc.toolCall({
271274
271333
  turnId: Number(context.turnId),
271275
271334
  toolCallId: context.toolCallId,
271276
271335
  toolName: name,
271277
271336
  args
271278
271337
  }, { signal: context.signal });
271338
+ } finally { this.clientToolCalls.delete(call); }
271279
271339
  }
271280
271340
  };
271281
271341
  }
@@ -273032,9 +273092,11 @@ var init_agent = __esmMin((() => {
273032
273092
  if (phase === "start") injector.recordToolStart(event);
273033
273093
  else injector.recordToolResult(event);
273034
273094
  }
273035
- emitEvent(event) {
273095
+ lastTurnEndReason;
273096
+ emitEvent(event) {
273036
273097
  if (this.records.restoring) return;
273037
- this.cron?.observeAgentEvent(event);
273098
+ if (event.type === "turn.ended" && event.turnId === this.turn.currentId) this.lastTurnEndReason = event.reason;
273099
+ this.cron?.observeAgentEvent(event);
273038
273100
  return this.rpc?.emitEvent?.(event);
273039
273101
  }
273040
273102
  contextMetrics() {
@@ -353147,10 +353209,6 @@ var init_rpc = __esmMin((() => {
353147
353209
  sessionId: input.sessionId,
353148
353210
  agentId
353149
353211
  });
353150
- const context = await rpc.getContext({
353151
- sessionId: input.sessionId,
353152
- agentId
353153
- });
353154
353212
  const permission = await rpc.getPermission({
353155
353213
  sessionId: input.sessionId,
353156
353214
  agentId
@@ -353167,6 +353225,10 @@ var init_rpc = __esmMin((() => {
353167
353225
  sessionId: input.sessionId,
353168
353226
  agentId
353169
353227
  });
353228
+ const context = await rpc.getContext({
353229
+ sessionId: input.sessionId,
353230
+ agentId
353231
+ });
353170
353232
  const maxContextTokens = context.effectiveMaxContextTokens ?? config.modelCapabilities?.max_context_tokens ?? 0;
353171
353233
  const contextTokens = context.projectedTokenCount ?? context.tokenCount;
353172
353234
  const contextUsage = maxContextTokens > 0 ? Math.min(1, Math.max(0, contextTokens / maxContextTokens)) : 0;
@@ -353183,7 +353245,9 @@ var init_rpc = __esmMin((() => {
353183
353245
  maxContextTokens,
353184
353246
  compactionBudgetTokens: context.compactionBudgetTokens,
353185
353247
  contextUsage,
353186
- usage: hasUsage ? usage : void 0
353248
+ usage: hasUsage ? usage : void 0,
353249
+ lastTurnEndReason: context.lastTurnEndReason,
353250
+ clientToolWait: context.clientToolWait
353187
353251
  };
353188
353252
  }
353189
353253
  async listTools(input) {
@@ -497315,6 +497379,52 @@ function contextValues(options) {
497315
497379
  maxTokens
497316
497380
  };
497317
497381
  }
497382
+ const FOREGROUND_LABELS = {
497383
+ idle: 'Foreground idle',
497384
+ waiting: 'Waiting for output',
497385
+ thinking: 'Thinking',
497386
+ composing: 'Streaming response',
497387
+ shell: 'Running shell command',
497388
+ approval: 'Approval required',
497389
+ question: 'Answer required',
497390
+ compaction: 'Compacting context',
497391
+ 'client-tool': 'Waiting for client tools'
497392
+ };
497393
+ const TURN_END_LABELS = {
497394
+ completed: 'Ended',
497395
+ cancelled: 'Interrupted',
497396
+ failed: 'Failed',
497397
+ filtered: 'Response filtered'
497398
+ };
497399
+ function workStatusLines(work, accent, value, muted) {
497400
+ const lines = [
497401
+ '',
497402
+ accent('Current work'),
497403
+ ` ${value(FOREGROUND_LABELS[work.foreground])}`
497404
+ ];
497405
+ if (work.clientToolWaitCount !== undefined) {
497406
+ const count = work.clientToolWaitCount;
497407
+ lines.push(` ${muted(`${count} ${count === 1 ? 'request' : 'requests'} pending`)}`);
497408
+ lines.push(` ${muted('Source: session SDK client')}`);
497409
+ lines.push(` ${muted('Wait for the client or stop the turn')}`);
497410
+ }
497411
+ if (work.lastTurnEndReason !== undefined) {
497412
+ lines.push(` ${muted(`Last turn: ${TURN_END_LABELS[work.lastTurnEndReason]}`)}`);
497413
+ }
497414
+ if (work.queuedInputs > 0) lines.push(` ${muted(`Input: ${work.queuedInputs} queued`)}`);
497415
+ if (work.background === undefined) {
497416
+ lines.push(` ${muted('Task status unavailable')}`);
497417
+ } else if (work.background.length === 0) {
497418
+ lines.push(` ${muted('No running background tasks')}`);
497419
+ } else {
497420
+ lines.push(` ${value(`Background: ${work.background.length} running`)} ${muted('/tasks')}`);
497421
+ for (const { taskId, kind } of work.background.slice(0, 3)){
497422
+ const id = taskId.length > 0 && taskId.length <= 64 && !/[^a-z\d_-]/iu.test(taskId) ? ` ${taskId}` : '';
497423
+ lines.push(` ${muted(`${kind}${id}`)}`);
497424
+ }
497425
+ }
497426
+ return lines;
497427
+ }
497318
497428
  function buildStatusReportLines(options) {
497319
497429
  const accent = (text) => currentTheme.boldFg("primary", text);
497320
497430
  const value = (text) => currentTheme.fg("text", text);
@@ -497363,6 +497473,7 @@ function buildStatusReportLines(options) {
497363
497473
  });
497364
497474
  const lines = [`${accent(`>_ ${PRODUCT_NAME}`)} ${muted(`(v${sanitizeTerminalText(options.version)})`)}`, ""];
497365
497475
  addFieldRows(lines, rows, muted, value, errorStyle);
497476
+ if (options.work) lines.push(...workStatusLines(options.work, accent, value, muted));
497366
497477
  const { ratio, tokens, maxTokens } = contextValues(options);
497367
497478
  lines.push("");
497368
497479
  lines.push(accent(uiText("usage.context.title")));
@@ -499044,15 +499155,48 @@ async function showUsage(host) {
499044
499155
  host.state.transcriptContainer.addChild(panel);
499045
499156
  host.state.ui.requestRender();
499046
499157
  }
499158
+ function liveClientToolWaitCount(host, wait) {
499159
+ if (wait === undefined || !Array.isArray(wait.calls)) return undefined;
499160
+ const { turnId, step } = host.streamingUI.getTurnContext();
499161
+ if (turnId === undefined || step < 1 || String(wait.turnId) !== turnId || wait.step !== step) {
499162
+ return undefined;
499163
+ }
499164
+ const seen = new Set();
499165
+ let count = 0;
499166
+ for (const { toolCallId, count: pending } of wait.calls){
499167
+ if (seen.has(toolCallId) || !Number.isSafeInteger(pending) || pending < 1) continue;
499168
+ const active = host.streamingUI.getActiveToolCall(toolCallId);
499169
+ if (active?.turnId !== turnId || active?.step !== step) continue;
499170
+ seen.add(toolCallId);
499171
+ count += pending;
499172
+ }
499173
+ return Number.isSafeInteger(count) && count > 0 ? count : undefined;
499174
+ }
499175
+ async function loadRunningTasks(session) {
499176
+ if (session === undefined) return undefined;
499177
+ try {
499178
+ const tasks = await session.listBackgroundTasks({
499179
+ activeOnly: true
499180
+ });
499181
+ return tasks.filter((task)=>task.status === 'running').map(({ taskId, kind })=>({
499182
+ taskId,
499183
+ kind
499184
+ }));
499185
+ } catch {
499186
+ return undefined;
499187
+ }
499188
+ }
499047
499189
  async function showStatusReport(host) {
499048
499190
  const owner = host.session;
499049
499191
  const model = host.state.appState.model;
499050
499192
  const agentId = owner?.connectionKind === "gateway" ? void 0 : host.harness.interactiveAgentId;
499051
- const isCurrent = () => !host.aborted && host.session === owner && host.state.appState.model === model && (owner?.connectionKind === "gateway" || host.harness.interactiveAgentId === agentId);
499193
+ const isCurrent = () => !host.aborted && host.session === owner && owner?.isClosed !== true && host.state.appState.model === model && (owner?.connectionKind === "gateway" || host.harness.interactiveAgentId === agentId);
499052
499194
  if (!isCurrent()) return;
499053
- const [runtimeStatus, managedUsage] = await Promise.all([loadRuntimeStatusReport(host), loadManagedUsageReport(host)]);
499195
+ const [runtimeStatus, managedUsage, background] = await Promise.all([loadRuntimeStatusReport(host), loadManagedUsageReport(host), owner?.connectionKind === "gateway" ? undefined : loadRunningTasks(owner)]);
499054
499196
  if (!isCurrent()) return;
499055
- const appState = host.state.appState;
499197
+ const { appState, livePane, queuedMessages } = host.state;
499198
+ const clientToolWaitCount = appState.streamingPhase === 'idle' || appState.streamingPhase === 'shell' ? undefined : liveClientToolWaitCount(host, runtimeStatus.status?.clientToolWait);
499199
+ const foreground = livePane.pendingApproval !== null ? 'approval' : livePane.pendingQuestion !== null ? 'question' : appState.isCompacting ? 'compaction' : clientToolWaitCount !== undefined ? 'client-tool' : appState.streamingPhase;
499056
499200
  const reportArgs = {
499057
499201
  version: appState.version,
499058
499202
  model: appState.model,
@@ -499068,6 +499212,9 @@ async function showStatusReport(host) {
499068
499212
  availableModels: appState.availableModels,
499069
499213
  status: runtimeStatus.status,
499070
499214
  gatewayConnectionState: owner?.connectionKind === "gateway" ? appState.gatewayConnectionState : void 0,
499215
+ work: owner === undefined ? undefined : { foreground, queuedInputs: queuedMessages.length, background,
499216
+ lastTurnEndReason: runtimeStatus.status?.lastTurnEndReason,
499217
+ clientToolWaitCount: foreground === "client-tool" ? clientToolWaitCount : undefined },
499071
499218
  statusError: runtimeStatus.error,
499072
499219
  managedUsage: managedUsage?.usage,
499073
499220
  managedUsageError: managedUsage?.error
@@ -505563,7 +505710,158 @@ function isMultilineChatInput(input) {
505563
505710
  "aside"
505564
505711
  ].includes(parsed.name);
505565
505712
  }
505713
+ const LOCAL_DIAGNOSTICS = /^\s*\/\s*diagnostics(?=\s|$)/iu;
505714
+ function isLocalDiagnosticsInput(input) {
505715
+ return LOCAL_DIAGNOSTICS.test(input);
505716
+ }
505717
+ const TUI_TURN_DIAGNOSTICS_FLAG = 'tui_turn_diagnostics';
505718
+ const TUI_DIAGNOSTIC_MAX_TRACKED_TURNS = 8;
505719
+ function tuiDiagnosticMillis(value) {
505720
+ return value !== undefined && value >= 0 && value <= Number.MAX_SAFE_INTEGER ? Math.round(value) : undefined;
505721
+ }
505722
+ class TurnDiagnostics {
505723
+ now;
505724
+ owner;
505725
+ active = new Map();
505726
+ order = 0;
505727
+ last;
505728
+ constructor(now = ()=>performance.now()){
505729
+ this.now = now;
505730
+ }
505731
+ reset() {
505732
+ this.owner = undefined;
505733
+ this.active.clear();
505734
+ this.order = 0;
505735
+ this.last = undefined;
505736
+ }
505737
+ record(event) {
505738
+ if (event.agentId !== 'main' || this.owner !== undefined && this.owner !== event.sessionId) return;
505739
+ if (event.type === 'turn.started') {
505740
+ const previous = this.active.get(event.turnId);
505741
+ if (previous !== undefined && previous.instance === event.turnInstanceId) return;
505742
+ this.owner = event.sessionId;
505743
+ this.active.delete(event.turnId);
505744
+ this.active.set(event.turnId, {
505745
+ instance: event.turnInstanceId,
505746
+ order: ++this.order,
505747
+ startedAt: this.now(),
505748
+ sample: {
505749
+ outcome: 'running',
505750
+ retryEvents: 0
505751
+ },
505752
+ stepBase: 0
505753
+ });
505754
+ if (this.active.size > TUI_DIAGNOSTIC_MAX_TRACKED_TURNS) {
505755
+ const oldest = this.active.keys().next();
505756
+ if (!oldest.done) this.active.delete(oldest.value);
505757
+ }
505758
+ return;
505759
+ }
505760
+ if (!('turnId' in event) || event.turnId === undefined) return;
505761
+ const active = this.active.get(event.turnId);
505762
+ if (active === undefined) return;
505763
+ const sample = active.sample;
505764
+ switch(event.type){
505765
+ case 'turn.step.started':
505766
+ if (!Number.isSafeInteger(event.step) || event.step < 0) break;
505767
+ if (active.step?.number !== event.step || active.step.id !== event.stepId) {
505768
+ if (active.step !== undefined && event.step <= active.step.number) {
505769
+ active.stepBase += active.step.number;
505770
+ }
505771
+ sample.lastStep = active.stepBase + event.step;
505772
+ active.step = {
505773
+ number: event.step,
505774
+ id: event.stepId
505775
+ };
505776
+ sample.firstTokenMs = undefined;
505777
+ sample.streamMs = undefined;
505778
+ }
505779
+ break;
505780
+ case 'turn.step.completed':
505781
+ if (active.step !== undefined && (active.step.number !== event.step || active.step.id !== undefined && event.stepId !== undefined && active.step.id !== event.stepId)) break;
505782
+ sample.firstTokenMs = tuiDiagnosticMillis(event.llmFirstTokenLatencyMs);
505783
+ sample.streamMs = tuiDiagnosticMillis(event.llmStreamDurationMs);
505784
+ break;
505785
+ case 'turn.step.retrying':
505786
+ {
505787
+ sample.retryEvents = Math.min(Number.MAX_SAFE_INTEGER, sample.retryEvents + 1);
505788
+ const status = event.statusCode;
505789
+ if (status !== undefined && Number.isInteger(status) && status >= 100 && status <= 599) {
505790
+ sample.lastRetryHttpStatus = status;
505791
+ }
505792
+ break;
505793
+ }
505794
+ case 'hook.result':
505795
+ if (event.hookEvent === 'UserPromptSubmit') {
505796
+ sample.promptHook = event.blocked === true ? 'blocked' : sample.promptHook ?? 'reported';
505797
+ }
505798
+ break;
505799
+ case 'turn.ended':
505800
+ this.active.delete(event.turnId);
505801
+ if (event.reason !== 'completed' && event.reason !== 'cancelled' && event.reason !== 'failed' && event.reason !== 'filtered') return;
505802
+ if (this.last !== undefined && this.last.order > active.order) return;
505803
+ this.last = {
505804
+ order: active.order,
505805
+ sample: {
505806
+ ...sample,
505807
+ outcome: event.reason,
505808
+ durationMs: tuiDiagnosticMillis(event.durationMs) ?? tuiDiagnosticMillis(this.now() - active.startedAt),
505809
+ stepLimitReached: event.error?.code === 'loop.max_steps_exceeded' ? true : undefined
505810
+ }
505811
+ };
505812
+ break;
505813
+ }
505814
+ }
505815
+ snapshot() {
505816
+ let active;
505817
+ for (const turn of this.active.values())active = turn;
505818
+ return {
505819
+ ...active?.order !== this.order ? {} : {
505820
+ active: {
505821
+ ...active.sample,
505822
+ durationMs: tuiDiagnosticMillis(this.now() - active.startedAt)
505823
+ }
505824
+ },
505825
+ ...this.last === undefined ? {} : {
505826
+ last: {
505827
+ ...this.last.sample
505828
+ }
505829
+ }
505830
+ };
505831
+ }
505832
+ }
505833
+ function buildTurnDiagnosticLines(snapshot) {
505834
+ const lines = [];
505835
+ for (const [label, turn] of [
505836
+ [
505837
+ 'Active',
505838
+ snapshot.active
505839
+ ],
505840
+ [
505841
+ 'Last',
505842
+ snapshot.last
505843
+ ]
505844
+ ]){
505845
+ if (turn === undefined) continue;
505846
+ const elapsed = turn.durationMs === undefined ? '' : ` (${turn.durationMs} ms)`;
505847
+ lines.push(`${label}: ${turn.outcome}${elapsed}`);
505848
+ if (turn.lastStep !== undefined) lines.push(` Model step: ${turn.lastStep}`);
505849
+ lines.push(` Retry notices: ${turn.retryEvents}`);
505850
+ if (turn.lastRetryHttpStatus !== undefined) lines.push(` Last retry HTTP: ${turn.lastRetryHttpStatus}`);
505851
+ if (turn.firstTokenMs !== undefined) lines.push(` First token: ${turn.firstTokenMs} ms`);
505852
+ if (turn.streamMs !== undefined) lines.push(` Stream: ${turn.streamMs} ms`);
505853
+ if (turn.promptHook !== undefined) lines.push(` Prompt hook: ${turn.promptHook}`);
505854
+ if (turn.stepLimitReached === true) lines.push(' Model step limit reached');
505855
+ }
505856
+ return lines.length === 0 ? [
505857
+ 'No turn observed in this console.'
505858
+ ] : lines;
505859
+ }
505566
505860
  function parseSlashInput(input) {
505861
+ const diagnostics = LOCAL_DIAGNOSTICS.exec(input);
505862
+ if (diagnostics !== null) {
505863
+ return { name: "diagnostics", args: input.slice(diagnostics[0].length).trim() };
505864
+ }
505567
505865
  if (!input.startsWith("/")) return null;
505568
505866
  const trimmed = input.slice(1).trim();
505569
505867
  if (trimmed.length === 0) return null;
@@ -506314,7 +506612,7 @@ function researchAvailability(args) {
506314
506612
  function getBuiltinSlashCommands() {
506315
506613
  return BUILTIN_SLASH_COMMAND_DEFINITIONS.map(({ descriptionKey, ...command }) => ({
506316
506614
  ...command,
506317
- description: uiText(descriptionKey)
506615
+ description: command.description ?? uiText(descriptionKey)
506318
506616
  }));
506319
506617
  }
506320
506618
  function findBuiltInSlashCommand(commandName) {
@@ -506343,6 +506641,8 @@ var init_registry$1 = __esmMin((() => {
506343
506641
  init_queue();
506344
506642
  init_experimental_flags();
506345
506643
  BUILTIN_SLASH_COMMAND_DEFINITIONS = [
506644
+ { name: "diagnostics", aliases: [], description: "Show recent turn diagnostics",
506645
+ availability: "always", priority: 60, experimentalFlag: "tui_turn_diagnostics" },
506346
506646
  {
506347
506647
  name: "reset",
506348
506648
  aliases: [],
@@ -528158,7 +528458,19 @@ function tryCancelSessionSearchInput(host, text) {
528158
528458
  sessionSearchRequests.get(host)?.abort();
528159
528459
  return true;
528160
528460
  }
528461
+ function runLocalTurnDiagnostics(host, text) {
528462
+ if (!isLocalDiagnosticsInput(text)) return false;
528463
+ if (!isExperimentalFlagEnabled(TUI_TURN_DIAGNOSTICS_FLAG)) {
528464
+ host.showStatus("/diagnostics is disabled. Enable Local turn diagnostics in /experiments.");
528465
+ } else if (parseSlashInput(text).args !== "") {
528466
+ host.showError("Usage: /diagnostics");
528467
+ } else {
528468
+ host.showTurnDiagnostics();
528469
+ }
528470
+ return true;
528471
+ }
528161
528472
  function dispatchInput(host, text) {
528473
+ if (runLocalTurnDiagnostics(host, text)) return Promise.resolve();
528162
528474
  if (tryCancelSessionSearchInput(host, text)) return Promise.resolve();
528163
528475
  if (isExperimentalFlagEnabled("multiline_chat_input") && isMultilineChatInput(text)) {
528164
528476
  host.sendNormalUserInput(text);
@@ -528191,6 +528503,7 @@ function dispatchInput(host, text) {
528191
528503
  return Promise.resolve();
528192
528504
  }
528193
528505
  async function executeSlashCommand(host, input) {
528506
+ if (runLocalTurnDiagnostics(host, input)) return;
528194
528507
  const parsedCommand = parseSlashInput(input);
528195
528508
  const intent = resolveSlashCommandInput({
528196
528509
  input,
@@ -539561,8 +539874,10 @@ var init_session_event_handler = __esmMin((() => {
539561
539874
  lastCompactionInstruction;
539562
539875
  pendingCompactionRetry;
539563
539876
  compactionRetryPanel;
539877
+ turnDiagnostics = new TurnDiagnostics();
539564
539878
  resetRuntimeState() {
539565
539879
  this.assistantMediaAttempts.clear();
539880
+ this.turnDiagnostics.reset();
539566
539881
  for (const component of this.pluginTraceComponents) this.host.state.transcriptContainer.removeChild(component);
539567
539882
  this.pluginTraceComponents.length = 0;
539568
539883
  this.pluginTraceSessionId = void 0;
@@ -539706,6 +540021,7 @@ clearAgentSwarmProgress() {
539706
540021
  });
539707
540022
  }
539708
540023
  handleEvent(event, sendQueued) {
540024
+ if (isExperimentalFlagEnabled(TUI_TURN_DIAGNOSTICS_FLAG)) this.turnDiagnostics.record(event);
539709
540025
  if (event.type === "plugin.trace") {
539710
540026
  this.handlePluginTrace(event);
539711
540027
  return;
@@ -549773,7 +550089,8 @@ activeApprovalPanel;
549773
550089
  return;
549774
550090
  }
549775
550091
  const historyText = wasBashMode ? `!${text}` : text;
549776
- this.persistInputHistory(historyText);
550092
+ if (wasBashMode || !isLocalDiagnosticsInput(text)) this.persistInputHistory(historyText);
550093
+ if (!wasBashMode && this.localTransitionRequest === void 0 && runLocalTurnDiagnostics(this, text)) return;
549777
550094
  if (this.localTransitionRequest !== void 0) {
549778
550095
  this.localTransitionRequest.draft = historyText;
549779
550096
  this.state.editor.setText(historyText);
@@ -550512,6 +550829,11 @@ releaseChannelQueueAtSafePoint() {
550512
550829
  this.queuePolicySteerTimer.unref?.();
550513
550830
  }
550514
550831
  flushQueuedMessages(draft, draftMode) {
550832
+ if (draftMode !== "bash" && isLocalDiagnosticsInput(draft)) {
550833
+ if (this.localTransitionRequest === void 0) this.state.editor.setText("");
550834
+ this.handleUserInput(draft);
550835
+ return;
550836
+ }
550515
550837
  this.automaticSteerBatch = false;
550516
550838
  if (draft.length > 0) {
550517
550839
  this.state.editor.setText("");
@@ -552112,6 +552434,10 @@ releaseChannelQueueAtSafePoint() {
552112
552434
  this.pendingChannelReplyGuard = void 0;
552113
552435
  }
552114
552436
  resetChannelPreambleState(this.channelPreamble);
552437
+ if (this.session !== session) {
552438
+ this.sessionEventHandler.turnDiagnostics.reset();
552439
+ this.clearTurnDiagnosticsPanel();
552440
+ }
552115
552441
  this.session = session;
552116
552442
  owner = session;
552117
552443
  adopted = true;
@@ -552243,6 +552569,8 @@ releaseChannelQueueAtSafePoint() {
552243
552569
  if (previous !== this.session) await previous?.close();
552244
552570
  }
552245
552571
  unloadCurrentSession(reason) {
552572
+ this.sessionEventHandler.turnDiagnostics.reset();
552573
+ this.clearTurnDiagnosticsPanel();
552246
552574
  this.foregroundSwarm = void 0;
552247
552575
  this.exportLifetime?.abort();
552248
552576
  this.exportLifetime = new AbortController();
@@ -552331,6 +552659,7 @@ releaseChannelQueueAtSafePoint() {
552331
552659
  this.state.terminal.setTitle(label);
552332
552660
  }
552333
552661
  resetSessionRuntime() {
552662
+ this.clearTurnDiagnosticsPanel();
552334
552663
  void this.journalHistory.close();
552335
552664
  this.scrollbackController?.invalidateOriginalHistory?.();
552336
552665
  this.shellOutputStreams.clear();
@@ -552505,6 +552834,10 @@ releaseChannelQueueAtSafePoint() {
552505
552834
  this.sessionBindingRequest = request;
552506
552835
  await session.setModel(BLUN_KING_MODEL_ALIAS, { allowFallback: false });
552507
552836
  if (!isCurrent()) return;
552837
+ if (this.session !== session) {
552838
+ this.sessionEventHandler.turnDiagnostics.reset();
552839
+ this.clearTurnDiagnosticsPanel();
552840
+ }
552508
552841
  this.session = session;
552509
552842
  owner = session;
552510
552843
  await this.refreshSessionQueuePolicy(session);
@@ -552955,6 +553288,7 @@ releaseChannelQueueAtSafePoint() {
552955
553288
  for (const child of this.state.transcriptContainer.children) if (hasDispose(child)) child.dispose();
552956
553289
  }
552957
553290
  clearTranscriptAndRedraw() {
553291
+ this.clearTurnDiagnosticsPanel();
552958
553292
  void this.journalHistory.close();
552959
553293
  this.scrollbackController?.invalidateOriginalHistory?.();
552960
553294
  this.streamingUI.discardPending();
@@ -552975,6 +553309,7 @@ releaseChannelQueueAtSafePoint() {
552975
553309
  this.state.ui.requestRender(true);
552976
553310
  }
552977
553311
  prepareReplayTranscript() {
553312
+ this.clearTurnDiagnosticsPanel();
552978
553313
  void this.journalHistory.close();
552979
553314
  this.scrollbackController?.invalidateOriginalHistory?.();
552980
553315
  this.disposeTranscriptChildren();
@@ -553013,7 +553348,7 @@ releaseChannelQueueAtSafePoint() {
553013
553348
  const componentsToRemove = [];
553014
553349
  for (let i = 0; i < cutoff; i++) {
553015
553350
  const child = children[i];
553016
- if (child instanceof WelcomeComponent) continue;
553351
+ if (child instanceof WelcomeComponent || child === this.turnDiagnosticsPanel) continue;
553017
553352
  componentsToRemove.push(child);
553018
553353
  }
553019
553354
  if (componentsToRemove.length === 0 || !this.scrollbackController.archiveComponents(componentsToRemove)) return false;
@@ -553026,7 +553361,24 @@ releaseChannelQueueAtSafePoint() {
553026
553361
  this.state.transcriptEntries = this.state.transcriptEntries.filter((e) => !toRemove.has(e));
553027
553362
  return true;
553028
553363
  }
553029
- mergeCurrentTurnSteps() {
553364
+ showTurnDiagnostics() {
553365
+ if (this.session === undefined || this.session.isClosed) {
553366
+ this.clearTurnDiagnosticsPanel();
553367
+ this.showStatus('No open session for /diagnostics.');
553368
+ return;
553369
+ }
553370
+ const lines = buildTurnDiagnosticLines(this.sessionEventHandler.turnDiagnostics.snapshot());
553371
+ this.clearTurnDiagnosticsPanel();
553372
+ this.turnDiagnosticsPanel = new UsagePanelComponent(()=>lines, 'primary', ' Turn diagnostics ');
553373
+ this.state.transcriptContainer.addChild(this.turnDiagnosticsPanel);
553374
+ this.state.ui.requestRender();
553375
+ }
553376
+ clearTurnDiagnosticsPanel() {
553377
+ if (this.turnDiagnosticsPanel === undefined) return;
553378
+ this.state.transcriptContainer.removeChild(this.turnDiagnosticsPanel);
553379
+ this.turnDiagnosticsPanel = undefined;
553380
+ }
553381
+ mergeCurrentTurnSteps() {
553030
553382
  if (TRANSCRIPT_KEEP_RECENT_STEPS <= 0) return false;
553031
553383
  const children = this.state.transcriptContainer.children;
553032
553384
  let turnStart = -1;
@@ -553043,7 +553395,7 @@ releaseChannelQueueAtSafePoint() {
553043
553395
  summaryIndex = i;
553044
553396
  continue;
553045
553397
  }
553046
- if (child instanceof AssistantMessageComponent) continue;
553398
+ if (child instanceof AssistantMessageComponent || child === this.turnDiagnosticsPanel) continue;
553047
553399
  stepIndices.push(i);
553048
553400
  }
553049
553401
  if (stepIndices.length <= TRANSCRIPT_KEEP_RECENT_STEPS) return false;
@@ -553099,7 +553451,7 @@ releaseChannelQueueAtSafePoint() {
553099
553451
  for (let i = turnStart + 1; i < turnEnd; i++) {
553100
553452
  const child = children[i];
553101
553453
  if (child instanceof StepSummaryComponent) summaryIndex = i;
553102
- else if (child instanceof AssistantMessageComponent) continue;
553454
+ else if (child instanceof AssistantMessageComponent || child === this.turnDiagnosticsPanel) continue;
553103
553455
  else stepIndices.push(i);
553104
553456
  }
553105
553457
  if (stepIndices.length > TRANSCRIPT_KEEP_RECENT_STEPS) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blun-king-cli",
3
- "version": "9.1.655",
3
+ "version": "9.1.656",
4
4
  "description": "BLUN CLI - your own AI agent with a Telegram channel. Get it done. With BLUN.",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -291,6 +291,7 @@ export function setGrammyErrorType(type) { isGrammyError = error => error instan
291
291
  const BINDING_FILE = 'tui-session-control.json';
292
292
  const BINDING_TTL_MS = 90_000;
293
293
  const BINDING_REFRESH_MS = 10_000;
294
+ const LEASE_CLOCK_SKEW_MS = 5_000;
294
295
  const BOT_ID = /^[1-9]\d{0,18}$/u;
295
296
 
296
297
  function underLease(dir, owner, pid) {
@@ -301,7 +302,7 @@ function underLease(dir, owner, pid) {
301
302
  try {
302
303
  const named = lstatSync(file);
303
304
  const age = Date.now() - Math.floor(named.mtimeMs);
304
- if (!named.isFile() || named.nlink !== 1 || named.size > 16 || age < 0 || age >= BINDING_TTL_MS) return false;
305
+ if (!named.isFile() || named.nlink !== 1 || named.size > 16 || age < -LEASE_CLOCK_SKEW_MS || age >= BINDING_TTL_MS) return false;
305
306
  fd = openSync(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
306
307
  const info = fstatSync(fd);
307
308
  if (info.dev !== named.dev || info.ino !== named.ino || info.nlink !== 1 || !info.isFile()) return false;
package/worker-host.mjs CHANGED
@@ -20994,6 +20994,7 @@ function isRecord$7(value) {
20994
20994
  * not equal the master switch 'BLUN_EXPERIMENTAL_FLAG'; `id` must not be 'flag'.
20995
20995
  */
20996
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"},
20997
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"},
20998
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"},
20999
21000
  {
@@ -183260,6 +183261,7 @@ var SubagentBatch = class {
183260
183261
  description: task.description,
183261
183262
  swarmIndex: task.swarmIndex,
183262
183263
  runInBackground: task.runInBackground,
183264
+ foregroundTaskId: task.foregroundTaskId,
183263
183265
  signal: attempt.controller.signal,
183264
183266
  onReady: () => {
183265
183267
  this.markAttemptReady(attempt);
@@ -183916,13 +183918,32 @@ admissionClosed = false;
183916
183918
  if (profile === void 0) throw new Error(`Subagent profile "${profileName}" was not found`);
183917
183919
  return profile;
183918
183920
  }
183919
- 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) {
183920
183938
  this.assertAdmissionOpen();
183921
183939
  this.assertInputLease(options);
183922
183940
  if (this.activeChildren.has(childId)) throw new Error(`Agent instance "${childId}" is already running`);
183923
183941
  const controller = new AbortController();
183924
183942
  const unlinkAbortSignal = linkAbortSignal(options.signal, controller);
183925
- 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,
183926
183947
  controller,
183927
183948
  parentToolCallId: options.parentToolCallId,
183928
183949
  runInBackground: options.runInBackground
@@ -233953,9 +233974,13 @@ var ContextMemory = class {
233953
233974
  return true;
233954
233975
  }
233955
233976
  data() {
233977
+ const { lastTurnEndReason } = this.agent;
233978
+ const { clientToolWait } = this.agent.tools;
233956
233979
  return {
233957
233980
  history: this.history,
233958
- tokenCount: this.tokenCount
233981
+ tokenCount: this.tokenCount,
233982
+ ...(lastTurnEndReason === undefined ? {} : { lastTurnEndReason }),
233983
+ ...(clientToolWait === undefined ? {} : { clientToolWait })
233959
233984
  };
233960
233985
  }
233961
233986
  resumeState() {
@@ -257943,7 +257968,7 @@ var AgentSwarmTool = class AgentSwarmTool {
257943
257968
  }),
257944
257969
  start: async (sink) => {
257945
257970
  // The manager owns cancellation for the whole batch, including slots not yet launched.
257946
- 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 }));
257947
257972
  const result = await this.runSwarm(managed);
257948
257973
  sink.signal.throwIfAborted();
257949
257974
  outcomes = result.map(({ status }) => status);
@@ -267182,7 +267207,10 @@ cancel(turnId, reason) {
267182
267207
  get currentId() {
267183
267208
  return this.turnId;
267184
267209
  }
267185
- get hasActiveTurn() {
267210
+ get activeModelStep() {
267211
+ return this.hasActiveTurn ? this.currentStepByTurn.get(this.currentId) : undefined;
267212
+ }
267213
+ get hasActiveTurn() {
267186
267214
  return this.activeTurn !== null && this.activeTurn !== "resuming";
267187
267215
  }
267188
267216
  ensureActiveTurn() {
@@ -270396,6 +270424,7 @@ var ToolManager = class {
270396
270424
  agent;
270397
270425
  builtinTools = /* @__PURE__ */ new Map();
270398
270426
  userTools = /* @__PURE__ */ new Map();
270427
+ clientToolCalls = new Set();
270399
270428
  mcpTools = /* @__PURE__ */ new Map();
270400
270429
  loopToolsOverride;
270401
270430
  /** server name → list of qualified tool names registered for that server. */
@@ -270582,7 +270611,33 @@ var ToolManager = class {
270582
270611
  cancelShellCommand(commandId) {
270583
270612
  this.shellCommandControllers.get(commandId)?.abort();
270584
270613
  }
270585
- 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) {
270586
270641
  this.agent.records.logRecord({
270587
270642
  type: "tools.register_user_tool",
270588
270643
  ...input
@@ -270596,12 +270651,17 @@ var ToolManager = class {
270596
270651
  return {
270597
270652
  approvalRule: name,
270598
270653
  execute: async (context) => {
270599
- 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({
270600
270659
  turnId: Number(context.turnId),
270601
270660
  toolCallId: context.toolCallId,
270602
270661
  toolName: name,
270603
270662
  args
270604
270663
  }, { signal: context.signal });
270664
+ } finally { this.clientToolCalls.delete(call); }
270605
270665
  }
270606
270666
  };
270607
270667
  }
@@ -272292,9 +272352,11 @@ var Agent$1 = class {
272292
272352
  if (phase === "start") injector.recordToolStart(event);
272293
272353
  else injector.recordToolResult(event);
272294
272354
  }
272295
- emitEvent(event) {
272355
+ lastTurnEndReason;
272356
+ emitEvent(event) {
272296
272357
  if (this.records.restoring) return;
272297
- this.cron?.observeAgentEvent(event);
272358
+ if (event.type === "turn.ended" && event.turnId === this.turn.currentId) this.lastTurnEndReason = event.reason;
272359
+ this.cron?.observeAgentEvent(event);
272298
272360
  return this.rpc?.emitEvent?.(event);
272299
272361
  }
272300
272362
  contextMetrics() {
@@ -350173,10 +350235,6 @@ var SDKRpcClientBase = class {
350173
350235
  sessionId: input.sessionId,
350174
350236
  agentId
350175
350237
  });
350176
- const context = await rpc.getContext({
350177
- sessionId: input.sessionId,
350178
- agentId
350179
- });
350180
350238
  const permission = await rpc.getPermission({
350181
350239
  sessionId: input.sessionId,
350182
350240
  agentId
@@ -350193,6 +350251,10 @@ var SDKRpcClientBase = class {
350193
350251
  sessionId: input.sessionId,
350194
350252
  agentId
350195
350253
  });
350254
+ const context = await rpc.getContext({
350255
+ sessionId: input.sessionId,
350256
+ agentId
350257
+ });
350196
350258
  const maxContextTokens = context.effectiveMaxContextTokens ?? config.modelCapabilities?.max_context_tokens ?? 0;
350197
350259
  const contextTokens = context.projectedTokenCount ?? context.tokenCount;
350198
350260
  const contextUsage = maxContextTokens > 0 ? Math.min(1, Math.max(0, contextTokens / maxContextTokens)) : 0;
@@ -350209,7 +350271,9 @@ var SDKRpcClientBase = class {
350209
350271
  maxContextTokens,
350210
350272
  compactionBudgetTokens: context.compactionBudgetTokens,
350211
350273
  contextUsage,
350212
- usage: hasUsage ? usage : void 0
350274
+ usage: hasUsage ? usage : void 0,
350275
+ lastTurnEndReason: context.lastTurnEndReason,
350276
+ clientToolWait: context.clientToolWait
350213
350277
  };
350214
350278
  }
350215
350279
  async listTools(input) {