@kvali/cli 0.6.8 → 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
 
@@ -131,6 +151,11 @@ type Runtime = {
131
151
  budgetLeft: number | undefined
132
152
  /** Ask Claude for a plan while there is none (`autoPlan` in ~/.kvali/config.json). */
133
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
134
159
  /** The session's permission mode, as the last classic event carried it: who answers an ask. */
135
160
  mode: string | undefined
136
161
  /** Agents the main loop started in the background, at work until their run ends. */
@@ -142,6 +167,15 @@ type Runtime = {
142
167
  * for theirs and for the turn their reports start. `idleSince`: all done, and nothing woke it.
143
168
  */
144
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>
145
179
  }
146
180
 
147
181
  const fresh = (): Runtime => ({
@@ -182,10 +216,19 @@ const fresh = (): Runtime => ({
182
216
  budgetAt: -Infinity,
183
217
  budgetLeft: undefined,
184
218
  autoPlan: true,
219
+ turnCalls: 0,
220
+ planAsked: false,
221
+ promptAsked: false,
185
222
  mode: undefined,
186
223
  background: new Map(),
187
224
  finished: new Set(),
188
225
  held: undefined,
226
+ limits: undefined,
227
+ limitSamples: {},
228
+ loops: new Map(),
229
+ pushedLoopFor: 0,
230
+ telegramIds: new Map(),
231
+ discordIds: new Map(),
189
232
  })
190
233
 
191
234
  /** Marks a call as waiting for the person's permission. */
@@ -256,6 +299,12 @@ async function doRefresh($: Engine, force: boolean): Promise<void> {
256
299
  rt.pushedStallFor = l.since
257
300
  quiet(push($, 'stalled', { quietMs: now - l.since }))
258
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
+ }
259
308
  if (rt.pendingPause && !rt.turnActive && now - rt.pendingPause.at >= ASK_PUSH_AFTER_MS) {
260
309
  const { workedMs, sequence } = rt.pendingPause
261
310
  rt.pendingPause = undefined
@@ -263,7 +312,7 @@ async function doRefresh($: Engine, force: boolean): Promise<void> {
263
312
  }
264
313
  const current = await read($, plan)
265
314
  const news = liveDue(current, now)
266
- 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) }))
267
316
  const key = [l.phase, l.since, l.label ?? '', l.detail ?? ''].join('|')
268
317
  if (key !== rt.lastLiveKey || force) {
269
318
  rt.lastLiveKey = key
@@ -365,6 +414,9 @@ async function pulse($: Engine, l: KvLive, now: number, force: boolean): Promise
365
414
  lastDataAt: l.lastDataAt,
366
415
  turnStartedAt: l.turnStartedAt,
367
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,
368
420
  step: pr.current && p.step ? { title: pr.current.title, startedAt: p.step.startedAt, actions: p.step.actions, typicalMs: typicalMs(p) } : undefined,
369
421
  }
370
422
  try {
@@ -443,28 +495,96 @@ const PUSH_EVENT: Record<PushKind, 'needs-you' | 'done' | 'error' | 'stuck' | 's
443
495
  paused: 'done',
444
496
  error: 'error',
445
497
  stalled: 'stuck',
498
+ loop: 'stuck',
446
499
  step: 'steps',
447
500
  }
448
501
 
449
502
  /** Sends one push to the phone; a failure only costs that push. */
450
- 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> {
451
516
  const cfg = rt.phone
452
517
  if (!cfg) return
453
518
  const wanted = kind === 'step' ? cfg.events.includes('steps') || cfg.events.includes('actions') : cfg.events.includes(PUSH_EVENT[kind])
454
519
  if (!wanted) return
455
- if (kind === 'step' && !(await quietAllowed($, cfg))) return
520
+ if (kind === 'step' && cfg.topic && !(await quietAllowed($, cfg))) return
456
521
  const p = await read($, plan)
457
522
  const u = await read($, usage)
458
523
  const { sequence, ...info } = extra
459
- const body = ntfyBody(cfg, { ...phonePush(kind, { project: rt.project, plan: p, tokens: totalTokens(u) || undefined, ...info }, cfg.details), sequence })
460
- const headers: Record<string, string> = { 'Content-Type': 'application/json' }
461
- if (cfg.token) headers.Authorization = `Bearer ${cfg.token}`
462
- try {
463
- const res = await $.http.fetch(cfg.server, { method: 'POST', headers, body })
464
- if (res.ok && rt.budgetLeft !== undefined) rt.budgetLeft -= 1
465
- } catch {
466
- // offline or refused by policy: the pane still shows it
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)
467
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!)
468
588
  }
469
589
 
470
590
  /**
@@ -549,11 +669,23 @@ export const register: Register = on => {
549
669
  // The words are fixed and never contain anything from the prompt.
550
670
  on('prompt.submit', async ($, e, next) => {
551
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
552
673
  await loadPhone($, await $.clock.now())
553
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
554
677
  return next({ ...e, context: [...(e.context ?? []), PLAN_CONTEXT] })
555
678
  }).catch(($, e, next) => next(e))
556
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
+
557
689
  on('turn.start', async ($, e, next) => {
558
690
  if (!e.agentId) {
559
691
  const now = await $.clock.now()
@@ -567,6 +699,9 @@ export const register: Register = on => {
567
699
  rt.turnSeq = rt.held?.sequence ?? turnSequence(rt.sessionId, now)
568
700
  if (rt.held) rt.held.idleSince = undefined
569
701
  rt.progressSent = false
702
+ rt.turnCalls = 0
703
+ rt.planAsked = rt.promptAsked
704
+ rt.promptAsked = false
570
705
  rt.pendingPause = undefined // the person answered
571
706
  rt.progressSentDone = progress((await read($, plan)).tasks).done
572
707
  quiet(refresh($))
@@ -641,6 +776,9 @@ export const register: Register = on => {
641
776
  rt.betweenSince = await $.clock.now()
642
777
  }
643
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
+ }
644
782
  if (!isPlan) await update($, recent, list => endAction(list, id, end, ran.deny !== undefined || ran.isError === true))
645
783
  else if (ran.deny === undefined && !ran.isError && e.tool !== 'TaskList' && e.tool !== 'TaskGet') {
646
784
  const files = e.tool === 'TodoWrite' ? undefined : await taskFiles($)
@@ -649,6 +787,16 @@ export const register: Register = on => {
649
787
  await update($, plan, p => advance(p, tasks, end, files?.times))
650
788
  }
651
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
+ }
652
800
  return ran
653
801
  }).catch(($, e, next) => next(e)) // an observer: if it fails, the call goes on as if it were not here
654
802
 
@@ -698,6 +846,24 @@ export const register: Register = on => {
698
846
  }
699
847
  }).catch(($, e, next) => next(e))
700
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
+
701
867
  // An agent the model started in the background: the turn may end while it works on.
702
868
  on('agent.spawn', async ($, e, next) => {
703
869
  const r = await next(e)
@@ -787,6 +953,12 @@ export const register: Register = on => {
787
953
  const tokens = totalTokens(u)
788
954
  const ctx = contextPercent(u)
789
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
+ })
790
962
 
791
963
  return (
792
964
  <Box flexDirection="column">
@@ -797,7 +969,7 @@ export const register: Register = on => {
797
969
  <Text mono color="suggestion">{cells.active}</Text>
798
970
  <Text mono dimColor>{cells.rest}</Text>
799
971
  <Text bold>{` ${pr.done}/${pr.total}`}</Text>
800
- <Text dimColor>{` · ${pr.percent}%`}</Text>
972
+ <Text dimColor>{` · ${pr.percent}%${eta !== undefined ? ` · ${fmtEta(eta)}` : ''}`}</Text>
801
973
  </Box>
802
974
  {pr.current ? <Text bold wrap="wrap">{pr.current.active ?? pr.current.title}</Text> : null}
803
975
  {pr.current && p.step ? (
@@ -811,6 +983,13 @@ export const register: Register = on => {
811
983
  ) : (
812
984
  <Text dimColor wrap="wrap">No plan yet. For multi-step work Claude keeps a task list, and its progress shows here.</Text>
813
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}
814
993
  <Box marginTop={1}>
815
994
  <Text color={toneColor} wrap="wrap">{`${line.icon} ${line.text}`}</Text>
816
995
  </Box>
@@ -834,6 +1013,11 @@ export const register: Register = on => {
834
1013
  </Text>
835
1014
  </Box>
836
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}
837
1021
  {pr.total > 0 ? (
838
1022
  <Box flexDirection="column" marginTop={1}>
839
1023
  <Button key="tasks" plain label={isOpen ? 'Hide tasks' : `Show all ${pr.total} tasks`} onPress={() => update($, showTasks, v => !v)} />