@kvali/cli 0.6.7 → 0.7.0

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.
@@ -4,6 +4,8 @@ import type { EngineInterface, Register } from 'claude-code'
4
4
  import type { KvAction, KvLive, KvPhase, KvPlan, KvTask } from '../types'
5
5
  import {
6
6
  ASKS_PERSON,
7
+ addLimitSamples,
8
+ currentLoop,
7
9
  asksPerson,
8
10
  EMPTY_PLAN,
9
11
  EMPTY_USAGE,
@@ -16,20 +18,34 @@ import {
16
18
  autoPlanEnabled,
17
19
  ntfyBody,
18
20
  parsePhoneConfig,
21
+ PUSH_COLOR,
22
+ discordBody,
23
+ telegramText,
19
24
  PLAN_CONTEXT,
25
+ PLAN_ASK_AFTER,
26
+ PLAN_REMINDER,
20
27
  wantsPlanContext,
21
28
  phonePush,
22
29
  barCells,
23
30
  contextPercent,
24
31
  describeTool,
25
32
  endAction,
33
+ fmtAbout,
26
34
  fmtDuration,
35
+ fmtEta,
36
+ fmtMinutes,
27
37
  fmtTokens,
28
38
  isActivePhase,
39
+ limitLabel,
40
+ limitRunsOut,
29
41
  liveLine,
42
+ loopKey,
43
+ noteCall,
30
44
  parseTaskFile,
45
+ planEtaMs,
31
46
  progress,
32
47
  projectSlug,
48
+ resultText,
33
49
  pushAction,
34
50
  scanTranscript,
35
51
  sortTasks,
@@ -39,7 +55,11 @@ import {
39
55
  typicalMs,
40
56
  messagesLeftOf,
41
57
  QUIET_RESERVE,
58
+ type LimitSamples,
59
+ type LimitWindow,
60
+ type LoopStreak,
42
61
  type PhoneCfg,
62
+ type PhonePush,
43
63
  type PushKind,
44
64
  } from './model'
45
65
 
@@ -49,6 +69,8 @@ const PANE = 'kvali'
49
69
  const TICK_MS = 2_000
50
70
  const PULSE_EVERY_MS = 10_000
51
71
  const LONG_TURN_MS = 120_000
72
+ /** Every background agent is done and nothing woke the session in this time: the task is over. */
73
+ const HELD_RELEASE_MS = 30_000
52
74
  /** A question to the person is worth a push only after this long unanswered: sooner, they were at the computer. */
53
75
  const ASK_PUSH_AFTER_MS = 60_000
54
76
  /** `$.fs.read` copies at most 4 MiB into the plugin. */
@@ -65,6 +87,8 @@ type Running = {
65
87
  label: string
66
88
  detail?: string
67
89
  startedAt: number
90
+ /** The subagent whose call it is; absent for the main loop's. */
91
+ agent?: string
68
92
  asks?: string
69
93
  /** The same question for a phone push: no command text leaves the computer. */
70
94
  askPush?: string
@@ -127,8 +151,31 @@ type Runtime = {
127
151
  budgetLeft: number | undefined
128
152
  /** Ask Claude for a plan while there is none (`autoPlan` in ~/.kvali/config.json). */
129
153
  autoPlan: boolean
154
+ /** Tool calls of the main loop in this turn, and whether this turn was already asked for a plan. */
155
+ turnCalls: number
156
+ planAsked: boolean
157
+ /** The prompt just submitted carried the plan request: the turn it starts was asked. */
158
+ promptAsked: boolean
130
159
  /** The session's permission mode, as the last classic event carried it: who answers an ask. */
131
160
  mode: string | undefined
161
+ /** Agents the main loop started in the background, at work until their run ends. */
162
+ background: Map<string, { label: string; startedAt: number }>
163
+ /** Agents whose run's end was heard: the engine's list may call one running a moment longer. */
164
+ finished: Set<string>
165
+ /**
166
+ * A task whose answer handed work to background agents: its end (the phone, the toast) waits
167
+ * for theirs and for the turn their reports start. `idleSince`: all done, and nothing woke it.
168
+ */
169
+ held: { startedAt: number; sequence?: string; followed: boolean; idleSince?: number } | undefined
170
+ /** The subscription's usage windows as the last API response reported them, and their recent readings. */
171
+ limits: { at: number; windows: LimitWindow[] } | undefined
172
+ limitSamples: LimitSamples
173
+ /** Actions of the main loop that keep failing the same way, and the loop (its start) last pushed. */
174
+ loops: Map<string, LoopStreak>
175
+ pushedLoopFor: number
176
+ /** Telegram and Discord message ids of the latest turns' notifications, to update them in place. */
177
+ telegramIds: Map<string, number>
178
+ discordIds: Map<string, string>
132
179
  }
133
180
 
134
181
  const fresh = (): Runtime => ({
@@ -169,7 +216,19 @@ const fresh = (): Runtime => ({
169
216
  budgetAt: -Infinity,
170
217
  budgetLeft: undefined,
171
218
  autoPlan: true,
219
+ turnCalls: 0,
220
+ planAsked: false,
221
+ promptAsked: false,
172
222
  mode: undefined,
223
+ background: new Map(),
224
+ finished: new Set(),
225
+ held: undefined,
226
+ limits: undefined,
227
+ limitSamples: {},
228
+ loops: new Map(),
229
+ pushedLoopFor: 0,
230
+ telegramIds: new Map(),
231
+ discordIds: new Map(),
173
232
  })
174
233
 
175
234
  /** Marks a call as waiting for the person's permission. */
@@ -190,6 +249,12 @@ function derive(now: number): KvLive {
190
249
  const all = [...rt.running.values()]
191
250
  const asking = all.filter(r => r.asks).pop()
192
251
  if (asking) return { ...base, phase: 'needs-you', since: asking.askedAt ?? asking.startedAt, label: asking.asks }
252
+ // The turn is over and agents it started work on: they are what runs.
253
+ if (!rt.turnActive && rt.background.size) {
254
+ const n = rt.background.size
255
+ const since = Math.min(...[...rt.background.values()].map(b => b.startedAt))
256
+ return { ...base, phase: 'running', since, label: `${n} background agent${n > 1 ? 's' : ''}` }
257
+ }
193
258
  const last = all.pop()
194
259
  if (last) return { ...base, phase: 'running', since: last.startedAt, label: last.label, detail: last.detail }
195
260
  if (rt.stream) {
@@ -218,6 +283,12 @@ async function doRefresh($: Engine, force: boolean): Promise<void> {
218
283
  if (rt.stream && rt.pendingPhase && (rt.pendingPhase.phase !== rt.stream.phase || rt.pendingPhase.label !== rt.stream.label)) {
219
284
  rt.stream = { phase: rt.pendingPhase.phase, since: now, label: rt.pendingPhase.label }
220
285
  }
286
+ if (rt.held?.idleSince !== undefined && !rt.turnActive && now - rt.held.idleSince >= HELD_RELEASE_MS) {
287
+ const { startedAt, sequence, followed, idleSince } = rt.held
288
+ rt.held = undefined
289
+ rt.ended = { phase: 'done', since: idleSince, lastTurnMs: idleSince - startedAt }
290
+ quiet(finish($, 'done', idleSince - startedAt, sequence, followed, now))
291
+ }
221
292
  const l = derive(now)
222
293
  await loadPhone($, now)
223
294
  if (l.phase === 'needs-you' && rt.pushedNeedsFor !== l.since && now - l.since >= ASK_PUSH_AFTER_MS) {
@@ -228,6 +299,12 @@ async function doRefresh($: Engine, force: boolean): Promise<void> {
228
299
  rt.pushedStallFor = l.since
229
300
  quiet(push($, 'stalled', { quietMs: now - l.since }))
230
301
  }
302
+ const loop = rt.turnActive ? currentLoop(rt.loops, now) : undefined
303
+ if (loop && rt.pushedLoopFor !== loop.since) {
304
+ rt.pushedLoopFor = loop.since
305
+ const u = await read($, usage)
306
+ quiet(push($, 'loop', { loop: { what: loop.detail ?? loop.label, count: loop.count, sameError: loop.sameError, forMs: now - loop.since, tokens: totalTokens(u) - loop.tokensAtStart || undefined } }))
307
+ }
231
308
  if (rt.pendingPause && !rt.turnActive && now - rt.pendingPause.at >= ASK_PUSH_AFTER_MS) {
232
309
  const { workedMs, sequence } = rt.pendingPause
233
310
  rt.pendingPause = undefined
@@ -235,7 +312,7 @@ async function doRefresh($: Engine, force: boolean): Promise<void> {
235
312
  }
236
313
  const current = await read($, plan)
237
314
  const news = liveDue(current, now)
238
- if (news) quiet(push($, 'step', { sequence: turnSeq(now), doing: news.doing }))
315
+ if (news) quiet(push($, 'step', { sequence: turnSeq(now), doing: news.doing, etaMs: planEtaMs(current, now) }))
239
316
  const key = [l.phase, l.since, l.label ?? '', l.detail ?? ''].join('|')
240
317
  if (key !== rt.lastLiveKey || force) {
241
318
  rt.lastLiveKey = key
@@ -317,7 +394,7 @@ function turnSeq(now: number): string {
317
394
  */
318
395
  async function pulse($: Engine, l: KvLive, now: number, force: boolean): Promise<void> {
319
396
  if (!rt.pulseFile) return
320
- const key = [l.phase, l.since, l.label ?? ''].join('|')
397
+ const key = [l.phase, l.since, l.label ?? '', rt.background.size].join('|')
321
398
  const due = isActivePhase(l.phase) ? now - rt.lastPulseAt >= PULSE_EVERY_MS : false
322
399
  if (!force && key === rt.lastPulseKey && !due) return
323
400
  rt.lastPulseKey = key
@@ -336,6 +413,10 @@ async function pulse($: Engine, l: KvLive, now: number, force: boolean): Promise
336
413
  detail: l.detail,
337
414
  lastDataAt: l.lastDataAt,
338
415
  turnStartedAt: l.turnStartedAt,
416
+ background: rt.background.size,
417
+ limits: rt.limits
418
+ ? { at: rt.limits.at, windows: rt.limits.windows, samples: Object.fromEntries(Object.entries(rt.limitSamples).map(([kind, v]) => [kind, v.points])) }
419
+ : undefined,
339
420
  step: pr.current && p.step ? { title: pr.current.title, startedAt: p.step.startedAt, actions: p.step.actions, typicalMs: typicalMs(p) } : undefined,
340
421
  }
341
422
  try {
@@ -414,27 +495,143 @@ const PUSH_EVENT: Record<PushKind, 'needs-you' | 'done' | 'error' | 'stuck' | 's
414
495
  paused: 'done',
415
496
  error: 'error',
416
497
  stalled: 'stuck',
498
+ loop: 'stuck',
417
499
  step: 'steps',
418
500
  }
419
501
 
420
502
  /** Sends one push to the phone; a failure only costs that push. */
421
- async function push($: Engine, kind: PushKind, extra: { label?: string; workedMs?: number; quietMs?: number; sequence?: string; doing?: string } = {}): Promise<void> {
503
+ async function push(
504
+ $: Engine,
505
+ kind: PushKind,
506
+ extra: {
507
+ label?: string
508
+ workedMs?: number
509
+ quietMs?: number
510
+ sequence?: string
511
+ doing?: string
512
+ etaMs?: number
513
+ loop?: { what: string; count: number; sameError: boolean; forMs: number; tokens?: number }
514
+ } = {},
515
+ ): Promise<void> {
422
516
  const cfg = rt.phone
423
517
  if (!cfg) return
424
518
  const wanted = kind === 'step' ? cfg.events.includes('steps') || cfg.events.includes('actions') : cfg.events.includes(PUSH_EVENT[kind])
425
519
  if (!wanted) return
426
- if (kind === 'step' && !(await quietAllowed($, cfg))) return
520
+ if (kind === 'step' && cfg.topic && !(await quietAllowed($, cfg))) return
427
521
  const p = await read($, plan)
428
522
  const u = await read($, usage)
429
523
  const { sequence, ...info } = extra
430
- const body = ntfyBody(cfg, { ...phonePush(kind, { project: rt.project, plan: p, tokens: totalTokens(u) || undefined, ...info }, cfg.details), sequence })
431
- const headers: Record<string, string> = { 'Content-Type': 'application/json' }
432
- if (cfg.token) headers.Authorization = `Bearer ${cfg.token}`
524
+ const message: PhonePush = { ...phonePush(kind, { project: rt.project, plan: p, tokens: totalTokens(u) || undefined, ...info }, cfg.details), sequence }
525
+ // Every channel set up; a failure costs that channel's push only.
526
+ if (cfg.topic) {
527
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' }
528
+ if (cfg.token) headers.Authorization = `Bearer ${cfg.token}`
529
+ try {
530
+ const res = await $.http.fetch(cfg.server, { method: 'POST', headers, body: ntfyBody(cfg, message) })
531
+ if (res.ok && rt.budgetLeft !== undefined) rt.budgetLeft -= 1
532
+ } catch {
533
+ // offline or refused by policy: the pane still shows it
534
+ }
535
+ }
536
+ if (cfg.telegram) await toTelegram($, cfg.telegram, message).catch(() => undefined)
537
+ if (cfg.discord) await toDiscord($, cfg.discord.webhook, message, PUSH_COLOR[kind]).catch(() => undefined)
538
+ }
539
+
540
+ const JSON_HEADERS = { 'Content-Type': 'application/json' }
541
+
542
+ /**
543
+ * A turn's notification on Telegram: a silent progress update edits the message, an alert (the
544
+ * turn's end) replaces it with a new one, which notifies.
545
+ */
546
+ async function toTelegram($: Engine, t: { token: string; chatId: string }, push: PhonePush): Promise<void> {
547
+ const api = (method: string) => `https://api.telegram.org/bot${t.token}/${method}`
548
+ const text = telegramText(push)
549
+ const prev = push.sequence ? rt.telegramIds.get(push.sequence) : undefined
550
+ if (prev !== undefined && push.priority <= 2) {
551
+ const res = await $.http.fetch(api('editMessageText'), {
552
+ method: 'POST',
553
+ headers: JSON_HEADERS,
554
+ body: JSON.stringify({ chat_id: t.chatId, message_id: prev, text, parse_mode: 'HTML', link_preview_options: { is_disabled: true } }),
555
+ })
556
+ if (res.ok || /not modified/i.test(res.text)) return
557
+ } else if (prev !== undefined) {
558
+ await $.http.fetch(api('deleteMessage'), { method: 'POST', headers: JSON_HEADERS, body: JSON.stringify({ chat_id: t.chatId, message_id: prev }) }).catch(() => undefined)
559
+ }
560
+ const res = await $.http.fetch(api('sendMessage'), {
561
+ method: 'POST',
562
+ headers: JSON_HEADERS,
563
+ body: JSON.stringify({ chat_id: t.chatId, text, parse_mode: 'HTML', disable_notification: push.priority <= 2, link_preview_options: { is_disabled: true } }),
564
+ })
565
+ const id = res.ok ? (JSON.parse(res.text) as { result?: { message_id?: unknown } }).result?.message_id : undefined
566
+ if (push.sequence && typeof id === 'number') remember(rt.telegramIds, push.sequence, id)
567
+ }
568
+
569
+ /** The same on Discord, through the channel's webhook. */
570
+ async function toDiscord($: Engine, webhook: string, push: PhonePush, color: number): Promise<void> {
571
+ const body = discordBody(push, color)
572
+ const prev = push.sequence ? rt.discordIds.get(push.sequence) : undefined
573
+ if (prev !== undefined && push.priority <= 2) {
574
+ const { flags: _silent, ...edit } = body
575
+ const res = await $.http.fetch(`${webhook}/messages/${prev}`, { method: 'PATCH', headers: JSON_HEADERS, body: JSON.stringify(edit) })
576
+ if (res.ok) return
577
+ } else if (prev !== undefined) {
578
+ await $.http.fetch(`${webhook}/messages/${prev}`, { method: 'DELETE' }).catch(() => undefined)
579
+ }
580
+ const res = await $.http.fetch(`${webhook}?wait=true`, { method: 'POST', headers: JSON_HEADERS, body: JSON.stringify(body) })
581
+ const id = res.ok ? (JSON.parse(res.text) as { id?: unknown }).id : undefined
582
+ if (push.sequence && typeof id === 'string') remember(rt.discordIds, push.sequence, id)
583
+ }
584
+
585
+ function remember<V>(m: Map<string, V>, key: string, value: V): void {
586
+ m.set(key, value)
587
+ while (m.size > 20) m.delete(m.keys().next().value!)
588
+ }
589
+
590
+ /**
591
+ * A task's end on the phone and in Claude Code. A task the phone followed always gets its end,
592
+ * other tasks only when they were long; a stop in the middle of the plan asks the person
593
+ * something, so it waits like a question.
594
+ */
595
+ async function finish($: Engine, phase: KvPhase, workedMs: number, sequence: string | undefined, followed: boolean, now: number): Promise<void> {
596
+ if (phase === 'error') quiet(push($, 'error', { label: rt.ended?.label, sequence }))
597
+ if (phase === 'done' && (workedMs >= (rt.phone?.doneAfterSec ?? 120) * 1000 || followed)) {
598
+ const pr = progress((await read($, plan)).tasks)
599
+ if (pr.total > 0 && pr.done < pr.total) rt.pendingPause = { at: now, workedMs, sequence }
600
+ else quiet(push($, 'finished', { workedMs, sequence }))
601
+ }
602
+ if (workedMs >= LONG_TURN_MS && phase !== 'interrupted') {
603
+ const p = progress((await read($, plan)).tasks)
604
+ const text = phase === 'done' ? `Done in ${fmtDuration(workedMs)}${p.total ? ` · ${p.done}/${p.total} tasks` : ''}` : `Stopped: ${rt.ended?.label}`
605
+ $.ui.toast(text)
606
+ quiet($.ui.notify(text, { title: 'Claude Code' }))
607
+ }
608
+ }
609
+
610
+ /**
611
+ * Checks the background agents against the engine's own list, which knows one that ended unheard.
612
+ * After an answer, an agent of the main loop still at work is a background one (Kvali may have
613
+ * loaded after it started).
614
+ */
615
+ async function countBackground($: Engine, afterAnswer: boolean): Promise<void> {
616
+ let agents: Awaited<ReturnType<Engine['agent']['list']>>
433
617
  try {
434
- const res = await $.http.fetch(cfg.server, { method: 'POST', headers, body })
435
- if (res.ok && rt.budgetLeft !== undefined) rt.budgetLeft -= 1
618
+ agents = await $.agent.list()
436
619
  } catch {
437
- // offline or refused by policy: the pane still shows it
620
+ return
621
+ }
622
+ const now = await $.clock.now()
623
+ for (const a of agents) {
624
+ if (a.parentId || a.teammateId) continue
625
+ const atWork = a.status === 'running' || a.status === 'pending' || a.status === 'waiting'
626
+ if (!atWork) rt.background.delete(a.id)
627
+ else if (afterAnswer && !rt.background.has(a.id) && !rt.finished.has(a.id)) rt.background.set(a.id, { label: a.description, startedAt: now })
628
+ }
629
+ }
630
+
631
+ /** Forgets the calls of a finished loop: the main loop's, or a subagent's when `agent` is given. */
632
+ function dropCalls(agent?: string): void {
633
+ for (const [id, r] of rt.running) {
634
+ if (agent !== undefined ? r.agent === agent : !r.agent || !rt.background.has(r.agent)) rt.running.delete(id)
438
635
  }
439
636
  }
440
637
 
@@ -472,11 +669,23 @@ export const register: Register = on => {
472
669
  // The words are fixed and never contain anything from the prompt.
473
670
  on('prompt.submit', async ($, e, next) => {
474
671
  if (e.command || e.isMeta) return next(e)
672
+ rt.loops.clear() // the person spoke: whatever the agent was stuck on is theirs to judge
475
673
  await loadPhone($, await $.clock.now())
476
674
  if (!rt.autoPlan || !wantsPlanContext(await read($, plan))) return next(e)
675
+ rt.planAsked = true // a prompt queued into a running turn asks that turn
676
+ rt.promptAsked = true
477
677
  return next({ ...e, context: [...(e.context ?? []), PLAN_CONTEXT] })
478
678
  }).catch(($, e, next) => next(e))
479
679
 
680
+ // Claude Code keeps its task tools behind ToolSearch, where a model asked for a plan often
681
+ // does not find them ("I have no TaskCreate"), and the progress bar stays empty. While
682
+ // automatic planning is on they stay in the tool list. Answered once, when a session first
683
+ // shows its tools, so it never changes under a running thread.
684
+ on('tool.describe', { tool: ['TaskCreate', 'TaskUpdate', 'TodoWrite'] }, async ($, e, next) => {
685
+ const described = await next(e)
686
+ return rt.autoPlan ? { ...described, isDeferred: false } : described
687
+ }).catch(($, e, next) => next(e))
688
+
480
689
  on('turn.start', async ($, e, next) => {
481
690
  if (!e.agentId) {
482
691
  const now = await $.clock.now()
@@ -485,9 +694,14 @@ export const register: Register = on => {
485
694
  rt.betweenSince = now
486
695
  rt.ended = undefined
487
696
  rt.stream = undefined
488
- rt.running.clear()
489
- rt.turnSeq = turnSequence(rt.sessionId, now)
697
+ dropCalls()
698
+ // A turn that background agents' reports set going (or a prompt meanwhile) is part of their task.
699
+ rt.turnSeq = rt.held?.sequence ?? turnSequence(rt.sessionId, now)
700
+ if (rt.held) rt.held.idleSince = undefined
490
701
  rt.progressSent = false
702
+ rt.turnCalls = 0
703
+ rt.planAsked = rt.promptAsked
704
+ rt.promptAsked = false
491
705
  rt.pendingPause = undefined // the person answered
492
706
  rt.progressSentDone = progress((await read($, plan)).tasks).done
493
707
  quiet(refresh($))
@@ -549,7 +763,7 @@ export const register: Register = on => {
549
763
  if (!e.agentId) rt.turnActive = true
550
764
  if (!isPlan) {
551
765
  const d = describeTool(e.tool, input, rt.cwd)
552
- rt.running.set(id, { ...d, startedAt: now, asks: ASKS_PERSON[e.tool], askedAt: ASKS_PERSON[e.tool] ? now : undefined })
766
+ rt.running.set(id, { ...d, startedAt: now, agent: e.agentId, asks: ASKS_PERSON[e.tool], askedAt: ASKS_PERSON[e.tool] ? now : undefined })
553
767
  await update($, recent, list => pushAction(list, { id, label: d.label, detail: d.detail, startedAt: now }))
554
768
  await update($, plan, p => (p.step ? { ...p, step: { ...p.step, actions: p.step.actions + 1 } } : p))
555
769
  quiet(refresh($))
@@ -562,6 +776,9 @@ export const register: Register = on => {
562
776
  rt.betweenSince = await $.clock.now()
563
777
  }
564
778
  const end = await $.clock.now()
779
+ if (!isPlan && !e.agentId && ran.deny === undefined) {
780
+ noteCall(rt.loops, loopKey(e.tool, describeTool(e.tool, input, rt.cwd)), describeTool(e.tool, input, rt.cwd), ran.isError === true ? resultText(ran.result) : undefined, end, totalTokens(await read($, usage)))
781
+ }
565
782
  if (!isPlan) await update($, recent, list => endAction(list, id, end, ran.deny !== undefined || ran.isError === true))
566
783
  else if (ran.deny === undefined && !ran.isError && e.tool !== 'TaskList' && e.tool !== 'TaskGet') {
567
784
  const files = e.tool === 'TodoWrite' ? undefined : await taskFiles($)
@@ -570,6 +787,16 @@ export const register: Register = on => {
570
787
  await update($, plan, p => advance(p, tasks, end, files?.times))
571
788
  }
572
789
  await refresh($)
790
+ // A long turn that began without a plan (a resumed session, a prompt the model planned
791
+ // nothing for) is asked once, beside a tool's result, which the model reads and the person
792
+ // does not see.
793
+ if (!e.agentId && !isPlan && ran.deny === undefined && rt.autoPlan) {
794
+ rt.turnCalls += 1
795
+ if (rt.turnCalls >= PLAN_ASK_AFTER && !rt.planAsked && wantsPlanContext(await read($, plan))) {
796
+ rt.planAsked = true
797
+ return { ...ran, context: [...(ran.context ?? []), PLAN_REMINDER] }
798
+ }
799
+ }
573
800
  return ran
574
801
  }).catch(($, e, next) => next(e)) // an observer: if it fails, the call goes on as if it were not here
575
802
 
@@ -619,39 +846,78 @@ export const register: Register = on => {
619
846
  }
620
847
  }).catch(($, e, next) => next(e))
621
848
 
849
+ // The subscription's usage windows, as each API response reports them: the pane shows them and
850
+ // the editor, reading the heartbeat, warns before one runs out.
851
+ on('session.measure', async ($, e, next) => {
852
+ const r = await next(e)
853
+ try {
854
+ const windows = (e.rateLimits ?? []).map(w => ({ kind: w.kind, percentUsed: w.percentUsed, resetsAt: w.resetsAt }))
855
+ if (windows.length) {
856
+ const now = await $.clock.now()
857
+ rt.limits = { at: now, windows }
858
+ rt.limitSamples = addLimitSamples(rt.limitSamples, windows, now)
859
+ quiet(refresh($, true))
860
+ }
861
+ } catch {
862
+ // an observer: the measurement stands
863
+ }
864
+ return r
865
+ })
866
+
867
+ // An agent the model started in the background: the turn may end while it works on.
868
+ on('agent.spawn', async ($, e, next) => {
869
+ const r = await next(e)
870
+ try {
871
+ if (e.background && !e.parentAgentId && !e.isTeammate && !e.workflow && r.agentId) {
872
+ rt.background.set(r.agentId, { label: e.description, startedAt: await $.clock.now() })
873
+ quiet(refresh($))
874
+ }
875
+ } catch {
876
+ // an observer: the spawn stands
877
+ }
878
+ return r
879
+ })
880
+
622
881
  on('turn.complete', async ($, e, next) => {
623
882
  const result = await next(e)
624
- if (e.agentId) return result
625
883
  const now = await $.clock.now()
884
+ if (e.agentId) {
885
+ // A background agent's run ended: the task it was part of may be over.
886
+ rt.finished.add(e.agentId)
887
+ if (rt.background.delete(e.agentId)) {
888
+ dropCalls(e.agentId)
889
+ if (rt.background.size === 0 && rt.held && !rt.turnActive) rt.held.idleSince = now
890
+ quiet(refresh($, true))
891
+ }
892
+ return result
893
+ }
626
894
  rt.turnActive = false
627
895
  rt.stream = undefined
628
- rt.running.clear()
896
+ await countBackground($, e.reason === 'answer')
897
+ dropCalls()
629
898
  const phase: KvPhase = e.reason === 'answer' ? 'done' : e.reason === 'aborted' ? 'interrupted' : 'error'
899
+ // A task that background agents carried on is timed from its first turn.
900
+ const held = rt.held
901
+ const workedMs = held ? now - held.startedAt : e.durationMs
902
+ const sequence = held?.sequence ?? rt.turnSeq
903
+ const followed = rt.progressSent || held?.followed === true
630
904
  rt.ended = {
631
905
  phase,
632
906
  since: now,
633
- lastTurnMs: e.durationMs,
907
+ lastTurnMs: workedMs,
634
908
  label: e.reason === 'refusal' ? 'the model declined' : e.reason === 'error' ? 'an API error ended the turn' : undefined,
635
909
  }
636
- const sequence = rt.turnSeq
637
- const followed = rt.progressSent
638
910
  rt.turnSeq = undefined
639
911
  rt.progressSent = false
640
- await refresh($, true)
641
- if (phase === 'error') quiet(push($, 'error', { label: rt.ended.label, sequence }))
642
- // A turn the phone followed always gets its end; other turns only when they were long.
643
- // A stop in the middle of the plan asks the person something, so it waits like a question.
644
- if (phase === 'done' && (e.durationMs >= (rt.phone?.doneAfterSec ?? 120) * 1000 || followed)) {
645
- const pr = progress((await read($, plan)).tasks)
646
- if (pr.total > 0 && pr.done < pr.total) rt.pendingPause = { at: now, workedMs: e.durationMs, sequence }
647
- else quiet(push($, 'finished', { workedMs: e.durationMs, sequence }))
648
- }
649
- if (e.durationMs >= LONG_TURN_MS && phase !== 'interrupted') {
650
- const p = progress((await read($, plan)).tasks)
651
- const text = phase === 'done' ? `Done in ${fmtDuration(e.durationMs)}${p.total ? ` · ${p.done}/${p.total} tasks` : ''}` : `Stopped: ${rt.ended.label}`
652
- $.ui.toast(text)
653
- quiet($.ui.notify(text, { title: 'Claude Code' }))
912
+ if (phase === 'done' && rt.background.size > 0) {
913
+ // The answer handed work to agents in the background: the task ends when they are done.
914
+ rt.held = { startedAt: held?.startedAt ?? now - e.durationMs, sequence, followed }
915
+ await refresh($, true)
916
+ return result
654
917
  }
918
+ rt.held = undefined
919
+ await refresh($, true)
920
+ await finish($, phase, workedMs, sequence, followed, now)
655
921
  return result
656
922
  })
657
923
 
@@ -659,6 +925,8 @@ export const register: Register = on => {
659
925
  rt.turnActive = false
660
926
  rt.stream = undefined
661
927
  rt.running.clear()
928
+ rt.background.clear() // they end with the session
929
+ rt.held = undefined
662
930
  rt.ended = { phase: 'ended', since: await $.clock.now() }
663
931
  rt.pendingPause = undefined
664
932
  await refresh($, true).catch(() => undefined)
@@ -685,6 +953,12 @@ export const register: Register = on => {
685
953
  const tokens = totalTokens(u)
686
954
  const ctx = contextPercent(u)
687
955
  const showRecent = isActivePhase(l.phase) || (l.phase === 'done' && now - l.since < 10 * 60_000)
956
+ const eta = isActivePhase(l.phase) ? planEtaMs(p, now) : undefined
957
+ const loop = isActivePhase(l.phase) ? currentLoop(rt.loops, now) : undefined
958
+ const limits = (rt.limits?.windows ?? []).map(w => {
959
+ const reset = w.resetsAt ? Date.parse(w.resetsAt) : NaN
960
+ return { label: limitLabel(w.kind), pct: w.percentUsed, reset: Number.isFinite(reset) ? reset : undefined, out: limitRunsOut(rt.limitSamples[w.kind]?.points ?? [], w, now) }
961
+ })
688
962
 
689
963
  return (
690
964
  <Box flexDirection="column">
@@ -695,7 +969,7 @@ export const register: Register = on => {
695
969
  <Text mono color="suggestion">{cells.active}</Text>
696
970
  <Text mono dimColor>{cells.rest}</Text>
697
971
  <Text bold>{` ${pr.done}/${pr.total}`}</Text>
698
- <Text dimColor>{` · ${pr.percent}%`}</Text>
972
+ <Text dimColor>{` · ${pr.percent}%${eta !== undefined ? ` · ${fmtEta(eta)}` : ''}`}</Text>
699
973
  </Box>
700
974
  {pr.current ? <Text bold wrap="wrap">{pr.current.active ?? pr.current.title}</Text> : null}
701
975
  {pr.current && p.step ? (
@@ -709,6 +983,13 @@ export const register: Register = on => {
709
983
  ) : (
710
984
  <Text dimColor wrap="wrap">No plan yet. For multi-step work Claude keeps a task list, and its progress shows here.</Text>
711
985
  )}
986
+ {loop ? (
987
+ <Box marginTop={1}>
988
+ <Text color="warning" wrap="wrap">
989
+ {`⟳ Going in circles: “${loop.detail ?? loop.label}” failed ${loop.count}× in a row${loop.sameError ? ' with the same error' : ''} · ${fmtDuration(now - loop.since)}`}
990
+ </Text>
991
+ </Box>
992
+ ) : null}
712
993
  <Box marginTop={1}>
713
994
  <Text color={toneColor} wrap="wrap">{`${line.icon} ${line.text}`}</Text>
714
995
  </Box>
@@ -732,6 +1013,11 @@ export const register: Register = on => {
732
1013
  </Text>
733
1014
  </Box>
734
1015
  ) : null}
1016
+ {limits.length ? (
1017
+ <Text color={limits.some(x => x.out !== undefined) ? 'warning' : 'inactive'} wrap="wrap">
1018
+ {`Limits: ${limits.map(x => `${x.label} ${Math.round(x.pct)}%${x.out !== undefined ? (x.out <= now ? ' used up' : ` · runs out in ${fmtAbout(x.out - now)}`) : x.reset !== undefined && x.reset > now ? ` · resets in ${fmtMinutes(x.reset - now)}` : ''}`).join(' · ')}`}
1019
+ </Text>
1020
+ ) : null}
735
1021
  {pr.total > 0 ? (
736
1022
  <Box flexDirection="column" marginTop={1}>
737
1023
  <Button key="tasks" plain label={isOpen ? 'Hide tasks' : `Show all ${pr.total} tasks`} onPress={() => update($, showTasks, v => !v)} />