@cmodjs/core 5.2.0 → 5.3.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.
Files changed (71) hide show
  1. package/docs/commands.md +4 -4
  2. package/docs/dependencies.md +2 -2
  3. package/docs/install-steps.md +2 -0
  4. package/docs/jobs.md +1 -1
  5. package/docs/state.md +1 -1
  6. package/docs/testing.md +1 -1
  7. package/docs/ui.md +1 -1
  8. package/jobs/program.d.ts.map +1 -1
  9. package/jobs/program.js +55 -4
  10. package/package.json +1 -1
  11. package/records.d.ts +2 -2
  12. package/records.js +2 -2
  13. package/register.d.ts.map +1 -1
  14. package/register.js +23 -3
  15. package/runtime/claude.d.ts +2 -0
  16. package/runtime/claude.d.ts.map +1 -1
  17. package/runtime/conversations.js +8 -8
  18. package/runtime/deadline.d.ts +2 -0
  19. package/runtime/deadline.d.ts.map +1 -1
  20. package/runtime/deadline.js +17 -0
  21. package/runtime/engine.d.ts +2 -0
  22. package/runtime/engine.d.ts.map +1 -1
  23. package/runtime/hooks.js +2 -2
  24. package/runtime/hotkeys.js +1 -1
  25. package/runtime/installer.js +1 -1
  26. package/runtime/lifecycle.d.ts.map +1 -1
  27. package/runtime/lifecycle.js +107 -74
  28. package/runtime/metadata.js +1 -1
  29. package/runtime/options.js +1 -1
  30. package/runtime/pages.js +3 -3
  31. package/runtime/programs.d.ts +1 -0
  32. package/runtime/programs.d.ts.map +1 -1
  33. package/runtime/programs.js +6 -0
  34. package/runtime/sessions.d.ts.map +1 -1
  35. package/runtime/sessions.js +46 -23
  36. package/runtime/state.d.ts +1 -0
  37. package/runtime/state.d.ts.map +1 -1
  38. package/runtime/state.js +6 -3
  39. package/runtime/toaster.d.ts +5 -0
  40. package/runtime/toaster.d.ts.map +1 -1
  41. package/runtime/toaster.js +27 -11
  42. package/runtime/ui.d.ts +1 -0
  43. package/runtime/ui.d.ts.map +1 -1
  44. package/runtime/ui.js +6 -6
  45. package/runtime/widgets.js +1 -1
  46. package/src/jobs/program.ts +60 -4
  47. package/src/records.ts +2 -2
  48. package/src/register.ts +25 -3
  49. package/src/runtime/claude.ts +2 -0
  50. package/src/runtime/conversations.ts +8 -8
  51. package/src/runtime/deadline.ts +16 -0
  52. package/src/runtime/engine.ts +2 -0
  53. package/src/runtime/hooks.ts +2 -2
  54. package/src/runtime/hotkeys.ts +1 -1
  55. package/src/runtime/installer.ts +1 -1
  56. package/src/runtime/lifecycle.ts +99 -66
  57. package/src/runtime/metadata.ts +1 -1
  58. package/src/runtime/options.ts +1 -1
  59. package/src/runtime/pages.ts +3 -3
  60. package/src/runtime/programs.ts +7 -0
  61. package/src/runtime/sessions.ts +46 -18
  62. package/src/runtime/state.ts +7 -3
  63. package/src/runtime/toaster.ts +47 -12
  64. package/src/runtime/ui.ts +6 -6
  65. package/src/runtime/widgets.ts +1 -1
  66. package/src/testing/fake-claude.ts +2 -0
  67. package/src/testing.ts +6 -2
  68. package/testing/fake-claude.d.ts.map +1 -1
  69. package/testing/fake-claude.js +2 -0
  70. package/testing.d.ts.map +1 -1
  71. package/testing.js +7 -2
@@ -7,7 +7,7 @@ import { dataFolder, finishStepsMethod, isAtLeast, isProgramNewer, oldestCmodVer
7
7
  import { homePrefix, ifMissing, relativePath } from '../utils/paths.js'
8
8
  import { firstLine, formatExit, messageOf } from '../utils/text.js'
9
9
  import type { Claude } from './claude.js'
10
- import { beforeDeadline } from './deadline.js'
10
+ import { beforeDeadline, settledAfterAbort } from './deadline.js'
11
11
  import { announcementMs, announcementOf } from './announce.js'
12
12
  import { bind } from './bound.js'
13
13
  import { serveConversations } from './conversations.js'
@@ -232,6 +232,12 @@ export function createLifecycle<State extends object, Declared extends Options =
232
232
  watchRecord()
233
233
  }
234
234
 
235
+ const notSetUp = () => {
236
+ const why = failure === undefined ? '' : messageOf(failure)
237
+ const own = `${definition.name}: `
238
+ return why === '' ? `${definition.name} is not set up.` : `${definition.name} is not set up: ${why.startsWith(own) ? why.slice(own.length) : why}`
239
+ }
240
+
235
241
  const installAgain = () => install()
236
242
  const updateAgain = () => claude().store.delete(cmodUpdatedKey).then(installAgain)
237
243
 
@@ -293,7 +299,7 @@ export function createLifecycle<State extends object, Declared extends Options =
293
299
 
294
300
  const record = () => {
295
301
  recording ??= recordThroughCmod()
296
- .catch((error: unknown) => claude().ui.log(`${definition.name} has no cmod record yet: ${messageOf(error)}`, { to: 'debug' }))
302
+ .catch((error: unknown) => claude().ui.warn('record', `${definition.name} has no cmod record yet: ${messageOf(error)}`))
297
303
  .finally(() => {
298
304
  recording = undefined
299
305
  })
@@ -408,10 +414,10 @@ export function createLifecycle<State extends object, Declared extends Options =
408
414
  const { additionalContext, ...unread } = answer as { readonly additionalContext?: readonly string[] } & Record<string, unknown>
409
415
  for (const text of additionalContext ?? []) {
410
416
  const added = await claude().session.append({ message: { type: 'user', content: [{ type: 'text', text }] } })
411
- if (added.deny !== undefined) claude().ui.log(`${definition.name}: Claude Code refused its SessionStart note: ${added.deny}`, { to: 'debug' })
417
+ if (added.deny !== undefined) claude().ui.warn('session-start:note', `${definition.name}: Claude Code refused its SessionStart note: ${added.deny}`)
412
418
  }
413
419
  if (Object.keys(unread).length > 0) {
414
- claude().ui.log(`${definition.name} started after Claude Code's SessionStart, so Claude Code did not read ${Object.keys(unread).join(', ')} from its SessionStart hooks.`, { to: 'debug' })
420
+ claude().ui.warn('session-start:late', `${definition.name} started after Claude Code's SessionStart, so Claude Code did not read ${Object.keys(unread).join(', ')} from its SessionStart hooks.`)
415
421
  }
416
422
  }
417
423
 
@@ -544,11 +550,12 @@ export function createLifecycle<State extends object, Declared extends Options =
544
550
  }
545
551
  let recordCheck: Timer | undefined
546
552
  let checking: Promise<void> | undefined
553
+ let startingSession: string | undefined
547
554
  const watchRecord = () => {
548
555
  recordCheck ??= claude().clock.every(recordCheckMs, () => {
549
556
  checking ??= recover()
550
557
  .then(() => undefined)
551
- .catch((error: unknown) => claude().ui.log(`${definition.name} could not read whether another cmod installed it: ${messageOf(error)}`, { to: 'debug' }))
558
+ .catch((error: unknown) => claude().ui.warn('record:watch', `${definition.name} could not read whether another cmod installed it: ${messageOf(error)}`))
552
559
  .finally(() => {
553
560
  checking = undefined
554
561
  })
@@ -564,17 +571,79 @@ export function createLifecycle<State extends object, Declared extends Options =
564
571
  if (activation !== undefined && phase !== 'active') await activation
565
572
  }
566
573
 
567
- const holdUntilStarted = (): Promise<void> =>
574
+ const held = (work: Promise<void>, signal: AbortSignal | undefined): Promise<void> =>
568
575
  runtime === undefined
569
- ? startSettled.then(whenActive)
576
+ ? work
570
577
  : new Promise<void>((resolve) => {
571
578
  const limit = claude().clock.after(startHoldMs, resolve)
572
- void startSettled.then(whenActive).then(() => {
579
+ if (signal?.aborted === true) resolve()
580
+ signal?.addEventListener('abort', () => resolve(), { once: true })
581
+ void work.then(() => {
573
582
  limit.cancel()
574
583
  resolve()
575
584
  })
576
585
  })
577
586
 
587
+ const holdUntilStarted = (signal?: AbortSignal): Promise<void> => held(startSettled.then(whenActive), signal)
588
+
589
+ const holdUntilActive = (signal: AbortSignal | undefined): Promise<void> => {
590
+ const activating = whenActive()
591
+ return activation !== undefined && phase !== 'active' ? held(activating, signal) : activating
592
+ }
593
+
594
+ const routed = async <N extends RoutedEvent>(event: N, e: Frozen<Args<N>>, next: RouterNext<N>, signal?: AbortSignal): Promise<EventResult<N>> => {
595
+ if (imports !== undefined) bind(imports)
596
+ const asked = e as Frozen<Args<'cmod.call'>> & { readonly caller?: string }
597
+ if (event === 'cmod.call' && asked.to === definition.name && asked.caller === cmodPluginName) {
598
+ if (asked.method === partMethods.shown) installer.hear(asked.input as ShownPages)
599
+ const answered = installer.answer(asked.method, asked.input)
600
+ if (answered !== undefined) return (await answered.catch((error: unknown) => ({ deny: `${definition.name}: ${messageOf(error)}` }))) as EventResult<N>
601
+ if (asked.method === partMethods.shown && phase !== 'active') return { value: null } as EventResult<N>
602
+ }
603
+ if (event === 'classic.SessionStart') {
604
+ missedSessionStart = undefined
605
+ hasHeardSessionStart = true
606
+ }
607
+ if (event === 'classic.SessionStart' && runtime === undefined) {
608
+ missedSessionStart = e as Frozen<Args<'classic.SessionStart'>>
609
+ return next(e)
610
+ }
611
+ if (shouldRecord && event === 'classic.UserPromptSubmit') record()
612
+ if (event === 'classic.UserPromptSubmit' || event === 'classic.SessionStart') await recover().catch((error: unknown) => claude().ui.warn('recover', `${definition.name} stays stopped: ${messageOf(error)}`))
613
+ const tool = (e as { readonly tool?: unknown }).tool
614
+ const isCallToThisMod = (event === 'cmod.call' && (e as Frozen<Args<'cmod.call'>>).to === definition.name) || (event === 'tool.call' && typeof tool === 'string' && tool.startsWith(`mcp__${definition.name}__`))
615
+ if (event === 'cmod.call' && !isCallToThisMod) return next(e)
616
+ await (event === 'classic.SessionStart' || event === 'session.append' || isCallToThisMod ? holdUntilStarted(signal) : holdUntilActive(signal))
617
+ if (event === 'classic.SessionStart' && phase !== 'active') {
618
+ missedSessionStart = e as Frozen<Args<'classic.SessionStart'>>
619
+ return next(e)
620
+ }
621
+ if (isCallToThisMod && phase !== 'active') {
622
+ if (event === 'cmod.call' && listenMethods.includes(asked.method)) {
623
+ heldListens.set(`${asked.caller}\n${asked.method}\n${String((asked.input as { readonly session?: unknown }).session)}`, asked)
624
+ return { value: null } as EventResult<N>
625
+ }
626
+ return { deny: phase === 'failed' ? notSetUp() : `${definition.name} is installing. Try again when it's ready.` } as EventResult<N>
627
+ }
628
+ const call = e as Frozen<Args<'cmod.call'>>
629
+ if (event === 'cmod.call' && call.to === definition.name && mod !== undefined) {
630
+ if (call.method === pendingStepsMethod) return { value: await pendingSteps(mod) } as EventResult<N>
631
+ if (call.method === finishStepsMethod) {
632
+ const active = mod
633
+ const opened = await installer.collect(() => Promise.race([runSteps(active).catch((error: unknown) => void toastFailure({ id: 'cmod:steps', message: 'Could not finish the setup', error, isCritical: true })), installer.shown()]))
634
+ return { value: opened } as EventResult<N>
635
+ }
636
+ }
637
+ if (event === 'classic.UserPromptSubmit' && phase === 'active' && !hasHeardSessionStart) {
638
+ const { session_id, transcript_path, cwd } = e as Frozen<Args<'classic.UserPromptSubmit'>>
639
+ await replaySessionStart({ session_id, transcript_path, cwd, hook_event_name: 'SessionStart', source: 'resume' })
640
+ }
641
+ const answer = router.dispatch(event, e, next, signal)
642
+ const render = e as Frozen<Args<'ui.render'>>
643
+ if (event !== 'ui.render' || render.component !== 'AbovePrompt' || runtime === undefined) return answer
644
+ return runtime.toaster.draw((await answer) as EventResult<'ui.render'>, runtime.claude.ui.resolve(render), render.props, render.requestId) as EventResult<N>
645
+ }
646
+
578
647
  return {
579
648
  get phase() {
580
649
  return phase
@@ -595,9 +664,14 @@ export function createLifecycle<State extends object, Declared extends Options =
595
664
  },
596
665
  async start(claudeCalls, read) {
597
666
  if (runtime !== undefined) return
598
- programs = locatingPrograms(claudeCalls)
599
- const callingCmod: Claude = {
667
+ const naming: Claude = {
600
668
  ...claudeCalls,
669
+ ui: { ...claudeCalls.ui, warn: (id, text) => (runtime === undefined ? claudeCalls.ui.warn(id, text) : runtime.toaster.warn(id, text)) },
670
+ session: { ...claudeCalls.session, id: async () => startingSession ?? claudeCalls.session.id() },
671
+ }
672
+ programs = locatingPrograms(naming)
673
+ const callingCmod: Claude = {
674
+ ...naming,
601
675
  cmod: {
602
676
  async call(input) {
603
677
  if (input.to === definition.name) await holdUntilStarted()
@@ -616,56 +690,14 @@ export function createLifecycle<State extends object, Declared extends Options =
616
690
  }
617
691
  },
618
692
  async route<N extends RoutedEvent>(event: N, e: Frozen<Args<N>>, next: RouterNext<N>, signal?: AbortSignal): Promise<EventResult<N>> {
619
- if (imports !== undefined) bind(imports)
620
- const asked = e as Frozen<Args<'cmod.call'>> & { readonly caller?: string }
621
- if (event === 'cmod.call' && asked.to === definition.name && asked.caller === cmodPluginName) {
622
- if (asked.method === partMethods.shown) installer.hear(asked.input as ShownPages)
623
- const answered = installer.answer(asked.method, asked.input)
624
- if (answered !== undefined) return (await answered.catch((error: unknown) => ({ deny: `${definition.name}: ${messageOf(error)}` }))) as EventResult<N>
625
- if (asked.method === partMethods.shown && phase !== 'active') return { value: null } as EventResult<N>
626
- }
627
- if (event === 'classic.SessionStart') {
628
- missedSessionStart = undefined
629
- hasHeardSessionStart = true
630
- }
631
- if (event === 'classic.SessionStart' && runtime === undefined) {
632
- missedSessionStart = e as Frozen<Args<'classic.SessionStart'>>
633
- return next(e)
634
- }
635
- if (shouldRecord && event === 'classic.UserPromptSubmit') record()
636
- if (event === 'classic.UserPromptSubmit' || event === 'classic.SessionStart') await recover().catch((error: unknown) => claude().ui.log(`${definition.name} stays stopped: ${messageOf(error)}`, { to: 'debug' }))
637
- const tool = (e as { readonly tool?: unknown }).tool
638
- const isCallToThisMod = (event === 'cmod.call' && (e as Frozen<Args<'cmod.call'>>).to === definition.name) || (event === 'tool.call' && typeof tool === 'string' && tool.startsWith(`mcp__${definition.name}__`))
639
- if (event === 'cmod.call' && !isCallToThisMod) return next(e)
640
- await (event === 'classic.SessionStart' || event === 'session.append' || isCallToThisMod ? holdUntilStarted() : whenActive())
641
- if (event === 'classic.SessionStart' && phase !== 'active') {
642
- missedSessionStart = e as Frozen<Args<'classic.SessionStart'>>
643
- return next(e)
644
- }
645
- if (isCallToThisMod && phase !== 'active') {
646
- if (event === 'cmod.call' && listenMethods.includes(asked.method)) {
647
- heldListens.set(`${asked.caller}\n${asked.method}\n${String((asked.input as { readonly session?: unknown }).session)}`, asked)
648
- return { value: null } as EventResult<N>
649
- }
650
- return { deny: phase === 'failed' ? `${definition.name} is not set up. Its toast says why.` : `${definition.name} is installing. Try again when it's ready.` } as EventResult<N>
651
- }
652
- const call = e as Frozen<Args<'cmod.call'>>
653
- if (event === 'cmod.call' && call.to === definition.name && mod !== undefined) {
654
- if (call.method === pendingStepsMethod) return { value: await pendingSteps(mod) } as EventResult<N>
655
- if (call.method === finishStepsMethod) {
656
- const active = mod
657
- const opened = await installer.collect(() => Promise.race([runSteps(active).catch((error: unknown) => void toastFailure({ id: 'cmod:steps', message: 'Could not finish the setup', error, isCritical: true })), installer.shown()]))
658
- return { value: opened } as EventResult<N>
659
- }
660
- }
661
- if (event === 'classic.UserPromptSubmit' && phase === 'active' && !hasHeardSessionStart) {
662
- const { session_id, transcript_path, cwd } = e as Frozen<Args<'classic.UserPromptSubmit'>>
663
- await replaySessionStart({ session_id, transcript_path, cwd, hook_event_name: 'SessionStart', source: 'resume' })
693
+ if (event !== 'classic.SessionStart') return settledAfterAbort(routed(event, e, next, signal), signal)
694
+ const started = (e as Frozen<Args<'classic.SessionStart'>>).session_id
695
+ startingSession = started
696
+ try {
697
+ return await settledAfterAbort(routed(event, e, next, signal), signal)
698
+ } finally {
699
+ if (startingSession === started) startingSession = undefined
664
700
  }
665
- const answer = router.dispatch(event, e, next, signal)
666
- const render = e as Frozen<Args<'ui.render'>>
667
- if (event !== 'ui.render' || render.component !== 'AbovePrompt' || runtime === undefined) return answer
668
- return runtime.toaster.draw((await answer) as EventResult<'ui.render'>, runtime.claude.ui.resolve(render), render.props, render.requestId) as EventResult<N>
669
701
  },
670
702
  async caught<N extends RoutedEvent>(event: N, e: Frozen<Args<N>>, next: RouterNext<N>, { error: { kind, message }, called }: Caught): Promise<EventResult<N>> {
671
703
  const call = e as Frozen<Args<'cmod.call'>>
@@ -713,7 +745,7 @@ async function createMod<State extends object, Declared extends Options>(definit
713
745
  const parent = await claude.cmod.call({ to: cmodPluginName, method: 'forkParent', input: null })
714
746
  return typeof parent === 'string' ? parent : undefined
715
747
  } catch (error) {
716
- claude.ui.log(`${definition.name} starts without the session values of the conversation it was forked from: ${messageOf(error)}`, { to: 'debug' })
748
+ claude.ui.warn('fork:values', `${definition.name} starts without the session values of the conversation it was forked from: ${messageOf(error)}`)
717
749
  return undefined
718
750
  }
719
751
  }
@@ -915,8 +947,8 @@ async function createMod<State extends object, Declared extends Options>(definit
915
947
  report({ id: 'cmod:follow', message: `Keeps the state of ${modState.root} until the next prompt or folder move`, error })
916
948
  }
917
949
  }
918
- const followCurrent = async (title: string | undefined) => {
919
- const [id, model, usage] = await Promise.all([claude.session.id(), claude.session.model(), claude.session.usage()])
950
+ const followCurrent = async (id: string, title: string | undefined) => {
951
+ const [model, usage] = await Promise.all([claude.session.model(), claude.session.usage()])
920
952
  followed = { id, title: title ?? '', project: modState.root, cwd, model, startedAt: new Date(usage.startedAt).toISOString(), ...(forkedFrom === undefined ? {} : { forkedFrom }), ...(agentType === undefined ? {} : { agentType }) }
921
953
  client.follow(followed)
922
954
  }
@@ -929,17 +961,17 @@ async function createMod<State extends object, Declared extends Options>(definit
929
961
  parentAsked = undefined
930
962
  }
931
963
  hasEarlierPrompts = e.source !== 'startup' && e.source !== 'clear'
964
+ await followCurrent(e.session_id, e.session_title).catch((error: unknown) => report({ id: 'cmod:current', message: 'Kept the details of the session from before', error }))
932
965
  await modState.switchSession(e.session_id, e.source, e.transcript_path).catch((error: unknown) => {
933
966
  report({ id: 'cmod:session', message: `Kept its session values from before the ${e.source}`, error })
934
967
  })
935
- await followCurrent(e.session_title).catch((error: unknown) => report({ id: 'cmod:current', message: 'Kept the details of the session from before', error }))
936
968
  return next(e)
937
969
  })
938
970
  router.add('classic.UserPromptSubmit', async (e, next) => {
939
971
  staleCwd = undefined
940
972
  await followSession()
941
973
  const isPerson = e.source === undefined || e.source === 'user' || e.source === 'sdk'
942
- await followCurrent(e.session_title || (isPerson && !hasEarlierPrompts && client.sessions.current.title === '' ? firstLine(e.prompt) : undefined)).catch((error: unknown) => report({ id: 'cmod:current', message: 'Kept the details of the session from before', error }))
974
+ await followCurrent(e.session_id, e.session_title || (isPerson && !hasEarlierPrompts && client.sessions.current.title === '' ? firstLine(e.prompt) : undefined)).catch((error: unknown) => report({ id: 'cmod:current', message: 'Kept the details of the session from before', error }))
943
975
  return next(e)
944
976
  })
945
977
  for (const event of ['classic.PostToolUse', 'classic.PostToolUseFailure'] as const) {
@@ -973,7 +1005,7 @@ async function createMod<State extends object, Declared extends Options>(definit
973
1005
  pages = widgets === undefined ? undefined : servePages({ claude, router, report: reportPart, widgets, parts, tellStylers: area.restyled })
974
1006
  const tellColor = (to: string, told: SessionColor) => {
975
1007
  if (told.session === '' || to === cmodPluginName) return
976
- claude.clock.after(0, () => void claude.cmod.call({ to, method: conversationMethods.sessionColor, input: told }).catch((error: unknown) => claude.ui.log(`cmod: ${to} did not hear the session's color: ${messageOf(error)}`, { to: 'debug' })))
1008
+ claude.clock.after(0, () => void claude.cmod.call({ to, method: conversationMethods.sessionColor, input: told }).catch((error: unknown) => claude.ui.warn('color:tell', `cmod: ${to} did not hear the session's color: ${messageOf(error)}`)))
977
1009
  }
978
1010
  conversations?.onColor((told) => {
979
1011
  client.recolor(told)
@@ -1019,6 +1051,7 @@ async function createMod<State extends object, Declared extends Options>(definit
1019
1051
  hasPermissionCheck: () => runtime.permissionRoutes() !== undefined,
1020
1052
  answerInput: area.answerInput,
1021
1053
  spawnCmod: (args, env) => spawnCmod(claude, args, session, env),
1054
+ watches,
1022
1055
  ...(widgets === undefined ? {} : { widgets }),
1023
1056
  ...(pages === undefined ? {} : { pages }),
1024
1057
  })
@@ -1033,7 +1066,7 @@ async function createMod<State extends object, Declared extends Options>(definit
1033
1066
  await failsAs('its options did not load', () => modOptions.load(root))
1034
1067
  const missing = modOptions.missing
1035
1068
  if (missing.length > 0) throw new MissingOptions(missing, missing.map((key) => definition.options?.[key]?.title ?? key))
1036
- await failsAs('the details of its session did not load', () => followCurrent(undefined))
1069
+ await failsAs('the details of its session did not load', () => followCurrent(session, undefined))
1037
1070
  const returned = await failsAs('its setup function threw', () => definition.setup(mod))
1038
1071
  api = apiOf(definition.name, returned)
1039
1072
  await failsAs('its open panes did not load', () => area.restorePanes())
@@ -71,7 +71,7 @@ export function createModFiles({
71
71
  const skipped = <Value>(path: string, value: Value) => (error: unknown): Value => {
72
72
  if (isMissing(error)) return value
73
73
  const reason = `${name}: fs.find skipped ${path}: ${messageOf(error)}`
74
- if (!logged.has(reason)) claude.ui.log(reason, { to: 'debug' })
74
+ if (!logged.has(reason)) claude.ui.warn('fs:find', reason)
75
75
  logged.add(reason)
76
76
  return value
77
77
  }
@@ -44,7 +44,7 @@ export function createOptions({
44
44
  const readLocked = async () => {
45
45
  if (Object.keys(declared).length === 0) return new Set<string>()
46
46
  const rows = await claude.config.list().catch((error: unknown) => {
47
- claude.ui.log(`${name} could not read /config, so a project's options.json may override a value your organization set: ${messageOf(error)}`, { to: 'debug' })
47
+ claude.ui.warn('options:config', `${name} could not read /config, so a project's options.json may override a value your organization set: ${messageOf(error)}`)
48
48
  return []
49
49
  })
50
50
  return new Set(rows.filter((row) => row.isLocked && row.key.startsWith(`${name}.`)).map((row) => row.key.slice(name.length + 1)))
@@ -90,7 +90,7 @@ export function servePages({
90
90
  .call({ to: mod, method: partMethods.list, input: null })
91
91
  .then(
92
92
  (parts) => void declared.set(mod, pagesOf(parts)),
93
- (error: unknown) => claude.ui.log(`cmod: ${mod} did not list its pages: ${messageOf(error)}`, { to: 'debug' }),
93
+ (error: unknown) => claude.ui.warn(`pages:list:${mod}`, `cmod: ${mod} did not list its pages: ${messageOf(error)}`),
94
94
  )
95
95
  .finally(() => asking.delete(mod))
96
96
  asking.set(mod, pending)
@@ -104,7 +104,7 @@ export function servePages({
104
104
  const listed = [...stylers]
105
105
  tellStylers(listed)
106
106
  for (const told of declared.keys()) {
107
- if (told !== cmodPluginName) void claude.cmod.call({ to: told, method: partMethods.stylers, input: listed }).catch((error: unknown) => claude.ui.log(`cmod: ${told} did not hear which mods style markdown: ${messageOf(error)}`, { to: 'debug' }))
107
+ if (told !== cmodPluginName) void claude.cmod.call({ to: told, method: partMethods.stylers, input: listed }).catch((error: unknown) => claude.ui.warn(`pages:stylers:${told}`, `cmod: ${told} did not hear which mods style markdown: ${messageOf(error)}`))
108
108
  }
109
109
  }
110
110
 
@@ -162,7 +162,7 @@ export function servePages({
162
162
  press,
163
163
  update,
164
164
  tell(mod, shown) {
165
- void claude.cmod.call({ to: mod, method: partMethods.shown, input: plain(shown) }).catch((error: unknown) => claude.ui.log(`cmod: ${mod} did not hear which of its pages show: ${messageOf(error)}`, { to: 'debug' }))
165
+ void claude.cmod.call({ to: mod, method: partMethods.shown, input: plain(shown) }).catch((error: unknown) => claude.ui.warn(`pages:shown:${mod}`, `cmod: ${mod} did not hear which of its pages show: ${messageOf(error)}`))
166
166
  },
167
167
  apply(listener) {
168
168
  applyTo = listener
@@ -39,6 +39,13 @@ export function spawnCmod(claude: Claude, args: readonly string[], session: stri
39
39
  return claude.process.spawn({ argv: ['cmod', ...args], env: { ...env, CLAUDE_CODE_SESSION_ID: session } })
40
40
  }
41
41
 
42
+ export async function isHeld(claude: Claude, lock: string, staleMs: number): Promise<boolean> {
43
+ const now = await claude.clock.now()
44
+ const holders = await claude.fs.list(lock).catch(ifMissing([]))
45
+ const touched = await Promise.all(holders.map(async ({ name }) => (await claude.fs.stat(`${lock}/${name}`).catch(ifMissing(undefined)))?.mtimeMs ?? 0))
46
+ return touched.some((at) => now - at < staleMs)
47
+ }
48
+
42
49
  export async function runCmod(claude: Claude, args: readonly string[], session: string): Promise<string> {
43
50
  const lines: string[] = []
44
51
  const { code, lastError } = await readLines(spawnCmod(claude, args, session), (line) => void lines.push(line))
@@ -145,6 +145,7 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
145
145
  const deciding = new Map<string, Set<Listening>>()
146
146
  const queued = new Set<string>()
147
147
  const parents = new Map<string, Map<string, string | undefined>>()
148
+ const readingParents = new Map<string, Promise<Map<string, string | undefined>>>()
148
149
  const known = new Map<string, SessionData>()
149
150
  let current: SessionData = { id: '', title: '', project: '', cwd: '', model: '', startedAt: '', lastAt: '', isRunning: true }
150
151
  let told: SessionColor = { session: '' }
@@ -161,28 +162,50 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
161
162
  const heard = (from: Map<string, Set<Listening>>): Listened[] =>
162
163
  [...(from.get(key) ?? [])].map(({ event, matcher, options, scope }) => ({ event, matcher: matcher === undefined ? undefined : sentMatcher(matcher), ...(options.onFailure === 'refuse' ? { onFailure: 'refuse' as const, scope } : {}) }))
163
164
  const tracksTasks = [...(listening.get(key) ?? []), ...(deciding.get(key) ?? [])].some(({ scope }) => scope.task !== undefined || scope.isGoal === true)
164
- if (tracksTasks) void learnTasks(key).catch((error: unknown) => report(`tasks:${key}`, 'Could not read the tasks it listens under', error))
165
165
  const subscriptions = [...heard(listening), ...(tracksTasks ? [{ event: TaskStart }] : [])]
166
166
  await call(conversationMethods.subscribe, { session: key, subscriptions }).catch((error: unknown) => report(`sessions:${key}`, `Hears nothing from ${key === everySession ? 'the other sessions' : `session ${key}`}`, error))
167
167
  await call(conversationMethods.watchBefore, { session: key, subscriptions: heard(deciding) }).catch((error: unknown) => report(`before:${key}`, `Changes nothing in ${key === everySession ? 'the other sessions' : `session ${key}`}`, error))
168
168
  })
169
169
  }
170
170
 
171
- const learnTasks = async (session: string) => {
172
- if (parents.has(session)) return
173
- const tree = new Map<string, string | undefined>()
174
- parents.set(session, tree)
175
- for (const task of await call<TaskData[]>(conversationMethods.tasks, { session, all: true })) tree.set(task.id, task.parent)
171
+ const parentsOf = (session: string) => {
172
+ const known = parents.get(session)
173
+ if (known !== undefined) return known
174
+ const reading = readingParents.get(session)
175
+ if (reading !== undefined) return reading
176
+ const read = call<TaskData[]>(conversationMethods.tasks, { session, all: true })
177
+ .then((tasks) => {
178
+ const tree = new Map(tasks.map((task) => [task.id, task.parent]))
179
+ parents.set(session, tree)
180
+ return tree
181
+ })
182
+ .finally(() => readingParents.delete(session))
183
+ readingParents.set(session, read)
184
+ return read
176
185
  }
177
186
 
178
- const isUnderIn = (session: string) => (task: string, ancestor: string) => {
179
- const tree = parents.get(session)
187
+ const isUnderIn = (tree: ReadonlyMap<string, string | undefined> | undefined) => (task: string, ancestor: string) => {
180
188
  for (let at: string | undefined = task, steps = 0; at !== undefined && steps < 64; at = tree?.get(at), steps += 1) if (at === ancestor) return true
181
189
  return false
182
190
  }
183
191
 
192
+ const inScope = ({ scope }: Listening, session: string, change: SessionChange): boolean | Promise<boolean> => {
193
+ if (scope.task === undefined || scope.isAgent === true) return isInScope(scope, session, change, isUnderIn(undefined))
194
+ const tree = parentsOf(session)
195
+ if (tree instanceof Map) return isInScope(scope, session, change, isUnderIn(tree))
196
+ return tree.then(
197
+ (read) => isInScope(scope, session, change, isUnderIn(read)),
198
+ (error: unknown) => (report(`tasks:${session}`, 'Could not read the tasks it listens under', error), false),
199
+ )
200
+ }
201
+
184
202
  const remember = (session: string, change: SessionChange) => {
185
- if (change.type === TaskStart) parents.get(session)?.set(change.task.id, change.task.parent)
203
+ if (change.type !== TaskStart) return
204
+ parents.get(session)?.set(change.task.id, change.task.parent)
205
+ void readingParents.get(session)?.then(
206
+ (tree) => tree.set(change.task.id, change.task.parent),
207
+ (error: unknown) => claude.ui.warn('tasks:read', `${name}: the tasks of ${session} stay unread until the next change: ${messageOf(error)}`),
208
+ )
186
209
  }
187
210
 
188
211
  const add = (into: Map<string, Set<Listening>>, scope: Scope, event: SessionEvent, method: string, args: readonly unknown[], onChange: (key: string) => void): Subscription => {
@@ -215,12 +238,12 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
215
238
 
216
239
  const decidersOf = (session: string, event: BeforeEvent, isInProject: boolean) => [...(deciding.get(session) ?? []), ...(isInProject ? (deciding.get(everySession) ?? []) : [])].filter((entry) => entry.event === event)
217
240
 
218
- const decides = (entry: Listening, session: string, change: SessionChange) => isInScope(entry.scope, session, change, isUnderIn(session)) && (entry.matcher === undefined || matches(payloadOf(change), entry.matcher))
241
+ const decides = async (entry: Listening, session: string, change: SessionChange) => (entry.matcher === undefined || matches(payloadOf(change), entry.matcher)) && (await inScope(entry, session, change))
219
242
 
220
243
  const combined = async (session: string, event: BeforeEvent, change: SessionChange, isInProject: boolean, cancel: AbortSignal): Promise<Partial<Answers> | undefined> => {
221
244
  const askers = decidersOf(session, event, isInProject)
222
245
  .map((entry) => async (latest: SessionChange) => {
223
- if (!decides(entry, session, latest)) return undefined
246
+ if (!(await decides(entry, session, latest))) return undefined
224
247
  const payload = await payloadFor(session, latest)
225
248
  return invoke(entry.method, entry.options, cancel, async (time) => takenAnswer(entry.method, beforeAnswerKeys[event], await entry.listener(payload as never, time)), beforeAnswerKeys[event])
226
249
  })
@@ -577,7 +600,7 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
577
600
  const every = eventMethods(() => ({}), false)
578
601
 
579
602
  const failedBefore = (session: string, event: BeforeEvent, change: SessionChange, isInProject: boolean, error: Error) => {
580
- const asked = decidersOf(session, event, isInProject).filter((entry) => decides(entry, session, change))
603
+ const asked = decidersOf(session, event, isInProject).filter((entry) => isInScope(entry.scope, session, change, isUnderIn(parents.get(session))) && (entry.matcher === undefined || matches(payloadOf(change), entry.matcher)))
581
604
  return asked.map((entry) => refusalOf(entry.options, beforeAnswerKeys[event], error)).find((answer) => answer !== undefined)
582
605
  }
583
606
 
@@ -602,12 +625,17 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
602
625
  remember(session, change)
603
626
  let payload: Promise<unknown> | undefined
604
627
  for (const key of isInProject ? [session, everySession] : [session]) {
605
- for (const { scope, event, method, matcher, listener, options } of listening.get(key) ?? []) {
606
- if (!isHeardBy(event, matcher, change) || !isInScope(scope, session, change, isUnderIn(session))) continue
607
- payload ??= payloadFor(session, change)
608
- void payload
609
- .then((heard) => invoke(method, options, cancel, (time) => listener(heard as never, time)))
610
- .catch((error: unknown) => report(`session:${method}`, `The ${method} listener failed`, error))
628
+ for (const entry of listening.get(key) ?? []) {
629
+ const { event, method, matcher, listener, options } = entry
630
+ const deliver = () => {
631
+ payload ??= payloadFor(session, change)
632
+ void payload
633
+ .then((heard) => invoke(method, options, cancel, (time) => listener(heard as never, time)))
634
+ .catch((error: unknown) => report(`session:${method}`, `The ${method} listener failed`, error))
635
+ }
636
+ const isHeard = isHeardBy(event, matcher, change) && inScope(entry, session, change)
637
+ if (isHeard === true) deliver()
638
+ else if (isHeard !== false) void isHeard.then((isIn) => isIn && deliver())
611
639
  }
612
640
  }
613
641
  },
@@ -42,8 +42,12 @@ export function onStateChange(state: object, listener: () => void): Subscription
42
42
  return { remove: () => void own.delete(listener) }
43
43
  }
44
44
 
45
+ export function sessionKeyOf(name: string, key: string, session: string): string {
46
+ return `${name}.${key}.sessions.${session}`
47
+ }
48
+
45
49
  export async function sessionsWith(claude: Pick<Claude, 'store'>, name: string, key: string, value: unknown): Promise<string[]> {
46
- const prefix = `${name}.${key}.sessions.`
50
+ const prefix = sessionKeyOf(name, key, '')
47
51
  const found: string[] = []
48
52
  for (const stored of (await claude.store.keys()).filter((each) => each.startsWith(prefix))) {
49
53
  if ((await claude.store.get(stored)) === value) found.push(stored.slice(prefix.length))
@@ -68,7 +72,7 @@ export function createState<State extends object>({ name, initial, session, root
68
72
  return run
69
73
  }
70
74
 
71
- const ownersKey = (lifetime: Exclude<SavedLifetime, 'global'>, key: string) => `${name}.${key}.${lifetime === 'project' ? 'projects' : 'sessions'}.`
75
+ const ownersKey = (lifetime: Exclude<SavedLifetime, 'global'>, key: string) => (lifetime === 'project' ? `${name}.${key}.projects.` : sessionKeyOf(name, key, ''))
72
76
 
73
77
  const storeKey = (lifetime: SavedLifetime, key: string, owner: string) => (lifetime === 'global' ? `${name}.${key}` : `${ownersKey(lifetime, key)}${owner}`)
74
78
 
@@ -131,7 +135,7 @@ export function createState<State extends object>({ name, initial, session, root
131
135
  if (lifetime !== 'memory') {
132
136
  const owner = lifetime === 'project' ? projectRoot : sessionId
133
137
  inTurn(() => write(lifetime, key, value, owner)).catch((error: unknown) => {
134
- report({ id: `state:${lifetime}.${key}`, message: `Could not keep state.${lifetime}.${key}. Keep only JSON data in mod.state`, error })
138
+ report({ id: `state:${lifetime}.${key}`, message: `Could not keep state.${lifetime}.${key}`, error })
135
139
  })
136
140
  }
137
141
  changed()
@@ -11,7 +11,21 @@ export type ShownToast = { readonly type: ToastType; readonly message: string; r
11
11
 
12
12
  export type Failure = { readonly id: string; readonly message: string; readonly error?: unknown; readonly description?: string; readonly retry?: () => unknown; readonly isCritical?: boolean }
13
13
 
14
- export type LoggedFailure = { readonly mod: string; readonly id: string; readonly message: string; readonly details: string; readonly at: string; readonly isCritical: boolean; readonly root: string; readonly contact?: Contact }
14
+ export type LogLevel = 'error' | 'warning'
15
+
16
+ export type LoggedFailure = {
17
+ readonly mod: string
18
+ readonly id: string
19
+ readonly message: string
20
+ readonly details: string
21
+ readonly at: string
22
+ readonly isCritical: boolean
23
+ readonly root: string
24
+ readonly contact?: Contact
25
+ readonly level?: LogLevel
26
+ readonly version?: string
27
+ readonly core?: string
28
+ }
15
29
 
16
30
  export const failedMethod = 'cmod:failed'
17
31
 
@@ -19,6 +33,7 @@ export type Toaster = {
19
33
  readonly toast: Toast
20
34
  copy(text: string): Promise<void>
21
35
  fail(failure: Failure): ToastId
36
+ warn(id: string, text: string): void
22
37
  readonly shown: readonly ShownToast[]
23
38
  draw(drawn: RenderElement, table: ElementTable, band: RenderPropsOf['AbovePrompt'], bandId: string): RenderElement
24
39
  }
@@ -75,7 +90,7 @@ export function createToaster(claude: Claude, name: string, version: () => strin
75
90
  if (typeof saved !== 'object' || saved === null) return
76
91
  for (const [id, hides] of Object.entries(saved)) if (typeof hides === 'string' && !hidden.has(id)) hidden.set(id, hides)
77
92
  },
78
- (error: unknown) => claude.ui.log(`${name}: could not read the failures you hid: ${messageOf(error)}`, { to: 'debug' }),
93
+ (error: unknown) => warn('hidden:read', `${name}: could not read the failures you hid: ${messageOf(error)}`),
79
94
  )
80
95
  let lastId = 0
81
96
  let frame = 0
@@ -157,7 +172,7 @@ export function createToaster(claude: Claude, name: string, version: () => strin
157
172
  dismiss(entry.id)
158
173
  if (entry.hides === undefined) return
159
174
  hidden.set(String(entry.id), entry.hides)
160
- void claude.store.set(hiddenKey, Object.fromEntries(hidden)).catch((error: unknown) => claude.ui.log(`${name}: could not remember the failure you hid: ${messageOf(error)}`, { to: 'debug' }))
175
+ void claude.store.set(hiddenKey, Object.fromEntries(hidden)).catch((error: unknown) => warn('hidden:write', `${name}: could not remember the failure you hid: ${messageOf(error)}`))
161
176
  }
162
177
 
163
178
  const toast: Toast = Object.assign(show('default'), {
@@ -198,6 +213,30 @@ export function createToaster(claude: Claude, name: string, version: () => strin
198
213
 
199
214
  const logFailure = (failure: LoggedFailure) => claude.cmod.call({ to: cmodPluginName, method: failedMethod, input: failure })
200
215
 
216
+ const modVersion = () =>
217
+ claude.fs
218
+ .read(`${claude.plugin.root}/.claude-plugin/plugin.json`)
219
+ .then((text) => String((JSON.parse(text) as { version?: unknown }).version))
220
+ .catch((failure: unknown) => `unknown (${messageOf(failure)})`)
221
+
222
+ const detailsOf = (version: string, at: Date, text: string) => `${name} ${version}, @cmodjs/core ${coreVersion}, at ${at.toISOString()}\n${text}`
223
+
224
+ const warned = new Map<string, string>()
225
+
226
+ const warn = (id: string, text: string) => {
227
+ claude.ui.log(text, { to: 'debug' })
228
+ const at = new Date()
229
+ const repeat = `${text}\n${at.toISOString().slice(0, 16)}`
230
+ if (warned.get(id) === repeat) return
231
+ warned.set(id, repeat)
232
+ claude.clock.after(0, () => {
233
+ void (async () => {
234
+ const version = await modVersion()
235
+ await logFailure({ mod: name, id, message: text, details: detailsOf(version, at, text), at: at.toISOString(), isCritical: false, root: claude.plugin.root, level: 'warning', version, core: coreVersion })
236
+ })().catch(() => undefined)
237
+ })
238
+ }
239
+
201
240
  const showsToast = async (failure: LoggedFailure, isShown: boolean): Promise<boolean | undefined> => {
202
241
  try {
203
242
  const logged = logFailure(failure)
@@ -217,16 +256,11 @@ export function createToaster(claude: Claude, name: string, version: () => strin
217
256
  if (sent.get(id) === repeat) return id
218
257
  sent.set(id, repeat)
219
258
  const stack = error instanceof Error && error.stack !== undefined ? `\n\n${error.stack}` : ''
220
- const details = async (failedAt: Date) => {
221
- const modVersion = await claude.fs
222
- .read(`${claude.plugin.root}/.claude-plugin/plugin.json`)
223
- .then((text) => String((JSON.parse(text) as { version?: unknown }).version))
224
- .catch((failure: unknown) => `unknown (${messageOf(failure)})`)
225
- return `${name} ${modVersion}, @cmodjs/core ${coreVersion}, at ${failedAt.toISOString()}\n${message}${description === undefined ? '' : `\n${description}`}${stack}`
226
- }
259
+ const details = async (failedAt: Date) => detailsOf(await modVersion(), failedAt, `${message}${description === undefined ? '' : `\n${description}`}${stack}`)
227
260
  const logged = async () => {
228
261
  const contact = await contactOf(claude)
229
- const failure: LoggedFailure = { mod: name, id, message, details: await details(at), at: at.toISOString(), isCritical, root: claude.plugin.root, ...(contact === undefined ? {} : { contact }) }
262
+ const version = await modVersion()
263
+ const failure: LoggedFailure = { mod: name, id, message, details: detailsOf(version, at, `${message}${description === undefined ? '' : `\n${description}`}${stack}`), at: at.toISOString(), isCritical, root: claude.plugin.root, ...(contact === undefined ? {} : { contact }), level: 'error', version, core: coreVersion }
230
264
  const shows = await showsToast(failure, isCritical)
231
265
  if (isCritical) return
232
266
  if (shows !== false) return show()
@@ -253,7 +287,7 @@ export function createToaster(claude: Claude, name: string, version: () => strin
253
287
  changed()
254
288
  if (bandId === undefined) return
255
289
  const focused = await claude.ui.focus({ requestId: bandId, key: `toast:${id}:ask-claude` })
256
- if ('deny' in focused) claude.ui.log(`${name}: the Report choices did not take the keys: ${String(focused.deny)}`, { to: 'debug' })
290
+ if ('deny' in focused) warn('report:focus', `${name}: the Report choices did not take the keys: ${String(focused.deny)}`)
257
291
  }
258
292
  const tryAgain = async () => {
259
293
  const shown = entries.get(id)
@@ -346,6 +380,7 @@ export function createToaster(claude: Claude, name: string, version: () => strin
346
380
  toast,
347
381
  copy,
348
382
  fail,
383
+ warn,
349
384
  get shown() {
350
385
  return [...entries.values()].map(({ type, message, options }) => ({ type, message, ...(typeof options.description === 'string' ? { description: options.description } : {}) }))
351
386
  },