@cmodjs/core 5.2.1 → 5.4.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 (88) hide show
  1. package/docs/commands.md +26 -2
  2. package/docs/dependencies.md +27 -0
  3. package/docs/install-steps.md +2 -0
  4. package/docs/jobs.md +1 -1
  5. package/docs/mod.md +9 -0
  6. package/docs/options.md +2 -0
  7. package/docs/state.md +1 -1
  8. package/docs/testing.md +2 -2
  9. package/docs/ui.md +1 -1
  10. package/jobs/program.d.ts.map +1 -1
  11. package/jobs/program.js +55 -4
  12. package/mod.d.ts +4 -0
  13. package/mod.d.ts.map +1 -1
  14. package/mod.js +3 -0
  15. package/options.d.ts +5 -0
  16. package/options.d.ts.map +1 -1
  17. package/options.js +52 -0
  18. package/package.json +1 -1
  19. package/records.d.ts +2 -2
  20. package/records.js +2 -2
  21. package/register.d.ts.map +1 -1
  22. package/register.js +23 -3
  23. package/runtime/claude.d.ts +2 -0
  24. package/runtime/claude.d.ts.map +1 -1
  25. package/runtime/conversations.js +8 -8
  26. package/runtime/deadline.d.ts +2 -0
  27. package/runtime/deadline.d.ts.map +1 -1
  28. package/runtime/deadline.js +17 -0
  29. package/runtime/dependencies.d.ts +1 -0
  30. package/runtime/dependencies.d.ts.map +1 -1
  31. package/runtime/dependencies.js +1 -0
  32. package/runtime/device.d.ts +13 -2
  33. package/runtime/device.d.ts.map +1 -1
  34. package/runtime/engine.d.ts +2 -0
  35. package/runtime/engine.d.ts.map +1 -1
  36. package/runtime/hooks.js +2 -2
  37. package/runtime/hotkeys.js +1 -1
  38. package/runtime/installer.js +1 -1
  39. package/runtime/lifecycle.d.ts.map +1 -1
  40. package/runtime/lifecycle.js +106 -75
  41. package/runtime/metadata.js +1 -1
  42. package/runtime/options.d.ts.map +1 -1
  43. package/runtime/options.js +6 -31
  44. package/runtime/pages.js +3 -3
  45. package/runtime/programs.d.ts +1 -0
  46. package/runtime/programs.d.ts.map +1 -1
  47. package/runtime/programs.js +6 -0
  48. package/runtime/sessions.js +1 -1
  49. package/runtime/state.d.ts +1 -0
  50. package/runtime/state.d.ts.map +1 -1
  51. package/runtime/state.js +6 -3
  52. package/runtime/toaster.d.ts +5 -0
  53. package/runtime/toaster.d.ts.map +1 -1
  54. package/runtime/toaster.js +27 -11
  55. package/runtime/ui.d.ts +1 -0
  56. package/runtime/ui.d.ts.map +1 -1
  57. package/runtime/ui.js +6 -6
  58. package/runtime/widgets.js +1 -1
  59. package/src/jobs/program.ts +60 -4
  60. package/src/mod.ts +5 -0
  61. package/src/options.ts +51 -0
  62. package/src/records.ts +2 -2
  63. package/src/register.ts +25 -3
  64. package/src/runtime/claude.ts +2 -0
  65. package/src/runtime/conversations.ts +8 -8
  66. package/src/runtime/deadline.ts +16 -0
  67. package/src/runtime/dependencies.ts +2 -0
  68. package/src/runtime/device.ts +7 -3
  69. package/src/runtime/engine.ts +2 -0
  70. package/src/runtime/hooks.ts +2 -2
  71. package/src/runtime/hotkeys.ts +1 -1
  72. package/src/runtime/installer.ts +1 -1
  73. package/src/runtime/lifecycle.ts +97 -67
  74. package/src/runtime/metadata.ts +1 -1
  75. package/src/runtime/options.ts +5 -26
  76. package/src/runtime/pages.ts +3 -3
  77. package/src/runtime/programs.ts +7 -0
  78. package/src/runtime/sessions.ts +1 -1
  79. package/src/runtime/state.ts +7 -3
  80. package/src/runtime/toaster.ts +47 -12
  81. package/src/runtime/ui.ts +6 -6
  82. package/src/runtime/widgets.ts +1 -1
  83. package/src/testing/fake-claude.ts +2 -0
  84. package/src/testing.ts +8 -4
  85. package/testing/fake-claude.d.ts.map +1 -1
  86. package/testing/fake-claude.js +2 -0
  87. package/testing.d.ts.map +1 -1
  88. package/testing.js +9 -4
package/src/register.ts CHANGED
@@ -3,10 +3,12 @@ import type { ModDefinition } from './mod.js'
3
3
  import type { Options } from './options.js'
4
4
  import type { Claude } from './runtime/claude.js'
5
5
  import type { RoutedEvent } from './runtime/hooks.js'
6
+ import { settledAfterAbort } from './runtime/deadline.js'
6
7
  import { cmodPluginName } from './runtime/dependencies.js'
7
8
  import { readDevice } from './runtime/device.js'
8
9
  import { createLifecycle, readPlugin, type Lifecycle } from './runtime/lifecycle.js'
9
10
  import { permissionRoutes, type PermissionRoutes } from './runtime/permission-check.js'
11
+ import { messageOf } from './utils/text.js'
10
12
 
11
13
  let lifecycle: Lifecycle<object>
12
14
 
@@ -18,11 +20,30 @@ export function registeredMod(): ModDefinition<object> | undefined {
18
20
  return registered
19
21
  }
20
22
 
23
+ const lockedRetryMs = [100, 300, 600] as const
24
+
25
+ const heldLock = 'Lock file is already being held'
26
+
27
+ const timers = globalThis as unknown as { setTimeout(run: () => void, ms: number): unknown }
28
+
29
+ async function whenUnlocked(write: () => Promise<void>): Promise<void> {
30
+ for (const waitMs of lockedRetryMs) {
31
+ try {
32
+ return await write()
33
+ } catch (error) {
34
+ if (!messageOf(error).includes(heldLock)) throw error
35
+ await new Promise<void>((resolve) => void timers.setTimeout(resolve, waitMs))
36
+ }
37
+ }
38
+ return write()
39
+ }
40
+
21
41
  async function startMod($: EngineInterface, eventInput: Frozen<Args<'session.start'>>, passOn: Next<'session.start'>): Promise<EventResult<'session.start'>> {
22
42
  const claude: Claude = {
23
43
  plugin: { name: $.plugin.name, root: $.plugin.root },
24
44
  ui: {
25
45
  log: (text, options) => $.ui.log(text, options),
46
+ warn: (_id, text) => $.ui.log(text, { to: 'debug' }),
26
47
  notice: (toolUseId, text) => $.ui.notice(toolUseId, text),
27
48
  toast: (text, options) => $.ui.toast(text, options),
28
49
  invalidate: (event) => $.ui.invalidate(event),
@@ -51,8 +72,8 @@ async function startMod($: EngineInterface, eventInput: Frozen<Args<'session.sta
51
72
  config: { list: () => $.config.list() },
52
73
  store: {
53
74
  get: (key) => $.store.get(key),
54
- set: (key, value) => $.store.set(key, value),
55
- delete: (key) => $.store.delete(key),
75
+ set: (key, value) => whenUnlocked(() => $.store.set(key, value)),
76
+ delete: (key) => whenUnlocked(() => $.store.delete(key)),
56
77
  keys: () => $.store.keys(),
57
78
  },
58
79
  clock: {
@@ -67,6 +88,7 @@ async function startMod($: EngineInterface, eventInput: Frozen<Args<'session.sta
67
88
  model: () => $.session.model(),
68
89
  usage: () => $.session.usage(),
69
90
  surfaces: () => $.session.surfaces(),
91
+ version: async () => (await $.session.version()).version,
70
92
  messages: ((args?: Parameters<Claude['session']['messages']>[0]) => (args === undefined ? $.session.messages() : $.session.messages(args))) as Claude['session']['messages'],
71
93
  append: (args) => $.session.append(args),
72
94
  send: (args) => $.session.send(args),
@@ -88,7 +110,7 @@ async function startMod($: EngineInterface, eventInput: Frozen<Args<'session.sta
88
110
  device: { read: () => readDevice(claude) },
89
111
  cmod: { call: (input) => $.cmod.call(input) },
90
112
  }
91
- const [, answer] = await Promise.all([lifecycle.start(claude, readPlugin), passOn(eventInput)])
113
+ const [, answer] = await settledAfterAbort(Promise.all([lifecycle.start(claude, readPlugin), passOn(eventInput)]), passOn.signal)
92
114
  return answer
93
115
  }
94
116
 
@@ -49,6 +49,7 @@ export type Claude = {
49
49
  readonly plugin: { readonly name: string; readonly root: string }
50
50
  readonly ui: {
51
51
  log(text: string, options?: UiLogOptions): void
52
+ warn(id: string, text: string): void
52
53
  notice(toolUseId: string, text: string | undefined): void
53
54
  toast(text: string, options?: ToastOptions): void
54
55
  invalidate(event: InvalidatableEventName): void
@@ -93,6 +94,7 @@ export type Claude = {
93
94
  model(): Promise<string>
94
95
  usage(): Promise<SessionUsage>
95
96
  surfaces(): Promise<readonly RenderSurface[]>
97
+ version(): Promise<string>
96
98
  messages: EngineInterface['session']['messages']
97
99
  append: EngineInterface['session']['append']
98
100
  send: EngineInterface['session']['send']
@@ -259,7 +259,7 @@ export function serveConversations({
259
259
 
260
260
  const publishWatches = (isEnding = false) => {
261
261
  const next = publishing.then(() => publishNow(isEnding))
262
- publishing = next.catch((error: unknown) => claude.ui.log(`cmod: publishing before listeners failed: ${messageOf(error)}`, { to: 'debug' }))
262
+ publishing = next.catch((error: unknown) => claude.ui.warn('before:publish', `cmod: publishing before listeners failed: ${messageOf(error)}`))
263
263
  return next
264
264
  }
265
265
 
@@ -275,7 +275,7 @@ export function serveConversations({
275
275
  published = new Set(list.map((watch) => watch.target))
276
276
  const running = targets.has(everySession) ? (await json<SessionData[]>(['history', 'sessions', '--running'])).map((each) => each.id) : []
277
277
  const told = new Set([...running, ...targets].filter((id) => id !== everySession && id !== session))
278
- await Promise.all([...told].map((id) => post(id, { kind: 'watch' }).catch((error: unknown) => claude.ui.log(`cmod: session ${id} did not hear of a before listener: ${messageOf(error)}`, { to: 'debug' }))))
278
+ await Promise.all([...told].map((id) => post(id, { kind: 'watch' }).catch((error: unknown) => claude.ui.warn('before:tell', `cmod: session ${id} did not hear of a before listener: ${messageOf(error)}`))))
279
279
  }
280
280
 
281
281
  const hear = (caller: string, id: string, list: readonly Listened[]) => {
@@ -289,7 +289,7 @@ export function serveConversations({
289
289
 
290
290
  const onListenerFiles = <Value>(work: () => Promise<Value>) => {
291
291
  const next = listenerFiles.then(work)
292
- listenerFiles = next.catch((error: unknown) => claude.ui.log(`cmod: reading or writing the mods' listeners failed: ${messageOf(error)}`, { to: 'debug' }))
292
+ listenerFiles = next.catch((error: unknown) => claude.ui.warn('listeners:files', `cmod: reading or writing the mods' listeners failed: ${messageOf(error)}`))
293
293
  return next
294
294
  }
295
295
 
@@ -325,7 +325,7 @@ export function serveConversations({
325
325
  list = JSON.parse(text) as readonly Watch[]
326
326
  } catch (error) {
327
327
  if (from === session || !(error instanceof SyntaxError)) throw error
328
- claude.ui.log(`cmod: session ${from} was writing its before listeners, so it keeps the ones from before until it relays that it changed them`, { to: 'debug' })
328
+ claude.ui.warn('before:read', `cmod: session ${from} was writing its before listeners, so it keeps the ones from before until it relays that it changed them`)
329
329
  found.push(...watchers.filter((watch) => watch.from === from))
330
330
  continue
331
331
  }
@@ -375,7 +375,7 @@ export function serveConversations({
375
375
  throw error
376
376
  }
377
377
  watchers = watchers.filter((each) => each.from !== watcher.from)
378
- claude.ui.log(`cmod: session ${watcher.from} ended without clearing its before listeners, so they are cleared now`, { to: 'debug' })
378
+ claude.ui.warn('before:ended', `cmod: session ${watcher.from} ended without clearing its before listeners, so they are cleared now`)
379
379
  await clearWatches(watcher.from)
380
380
  return undefined
381
381
  }
@@ -640,7 +640,7 @@ export function serveConversations({
640
640
  const { session: from, ...task } = JSON.parse(asked) as TaskData & { readonly session: string }
641
641
  const ended: TaskData = { ...task, id: session, closedAt: new Date().toISOString() }
642
642
  await claude.fs.write(`${backgroundTasks}/${from}/${session}.json`, JSON.stringify(ended))
643
- await post(from, { kind: 'taskEnd', task: ended }).catch((error: unknown) => claude.ui.log(`cmod: session ${from} did not hear that its task ${session} answered: ${messageOf(error)}`, { to: 'debug' }))
643
+ await post(from, { kind: 'taskEnd', task: ended }).catch((error: unknown) => claude.ui.warn('task:answered', `cmod: session ${from} did not hear that its task ${session} answered: ${messageOf(error)}`))
644
644
  }
645
645
 
646
646
  const actElsewhere = async (caller: string, target: string, action: Act, input: unknown, task: string | undefined): Promise<unknown> => {
@@ -741,7 +741,7 @@ export function serveConversations({
741
741
  if (id !== session) return saved
742
742
  await starting
743
743
  const kept = liveTasks().filter((task) => isNested || task.parent === request['task'])
744
- const running = await claude.agent.list().catch((error: unknown) => (claude.ui.log(`cmod: the tasks show no status, because Claude Code listed no agents: ${messageOf(error)}`, { to: 'debug' }), []))
744
+ const running = await claude.agent.list().catch((error: unknown) => (claude.ui.warn('tasks:status', `cmod: the tasks show no status, because Claude Code listed no agents: ${messageOf(error)}`), []))
745
745
  const background = saved.flatMap(({ id, status }) => (status === undefined ? [] : [{ id, status }]))
746
746
  return tasksWithAgents(merged(saved, kept, (task) => task.id), [...running, ...background])
747
747
  },
@@ -764,7 +764,7 @@ export function serveConversations({
764
764
  if (id === session) changeGoal(task, text)
765
765
  else {
766
766
  dispatch(id, [{ type: GoalChange, goal: { text, ...(task === undefined ? {} : { task }) } }])
767
- await post(id, { kind: 'goal', ...(task === undefined ? {} : { task }), text }).catch((error: unknown) => claude.ui.log(`cmod: session ${id} keeps its goal until it starts again: ${messageOf(error)}`, { to: 'debug' }))
767
+ await post(id, { kind: 'goal', ...(task === undefined ? {} : { task }), text }).catch((error: unknown) => claude.ui.warn('goal:tell', `cmod: session ${id} keeps its goal until it starts again: ${messageOf(error)}`))
768
768
  }
769
769
  return null
770
770
  },
@@ -49,6 +49,22 @@ export async function withinTime<Value>(clock: Pick<Claude['clock'], 'now'>, met
49
49
  }
50
50
  }
51
51
 
52
+ export const abortGraceMs = 1000
53
+
54
+ export function settledAfterAbort<Value>(work: Promise<Value>, signal: AbortSignal | undefined): Promise<Value> {
55
+ if (signal === undefined) return work
56
+ return new Promise<Value>((resolve, reject) => {
57
+ let timer: unknown
58
+ const giveUp = () => void (timer = timers.setTimeout(() => reject(signal.reason), abortGraceMs))
59
+ if (signal.aborted) giveUp()
60
+ else signal.addEventListener('abort', giveUp, { once: true })
61
+ work.then(resolve, reject).finally(() => {
62
+ timers.clearTimeout(timer)
63
+ signal.removeEventListener('abort', giveUp)
64
+ })
65
+ })
66
+ }
67
+
52
68
  export function beforeDeadline<Value>(claude: Claude, { ms, job }: Deadline, call: string, task: Promise<Value>): Promise<Value> {
53
69
  return new Promise<Value>((resolve, reject) => {
54
70
  const passed = job === undefined ? `its ${ms / 1000} s deadline` : `the ${ms / 1000} s deadline of ${job}`
@@ -6,6 +6,8 @@ import type { Router } from './router.js'
6
6
 
7
7
  export const cmodPluginName = 'cmod'
8
8
 
9
+ export const loadedMethod = 'cmod:isLoaded'
10
+
9
11
  export async function answerCall(name: string, api: { readonly [method: string]: (input: never) => unknown }, e: Frozen<Args<'cmod.call'>>): Promise<EventResult<'cmod.call'>> {
10
12
  const method = Object.hasOwn(api, e.method) ? api[e.method] : undefined
11
13
  if (method === undefined) return { deny: `${name} has no method ${e.method}.` }
@@ -1,7 +1,6 @@
1
1
  import type { Device } from '../session/context/turn/device.js'
2
2
  import { ifMissing } from '../utils/paths.js'
3
3
  import { formatExit } from '../utils/text.js'
4
- import type { Claude } from './claude.js'
5
4
 
6
5
  const cmodAppId = '1fd8a8ee972047c4a89640fd51048522'
7
6
 
@@ -19,7 +18,12 @@ const machineIdFiles = ['/etc/machine-id', '/var/lib/dbus/machine-id'] as const
19
18
 
20
19
  export class MissingMachineId extends Error {}
21
20
 
22
- export async function readDevice(claude: Pick<Claude, 'process' | 'fs'>): Promise<Device> {
21
+ export type DeviceSources = {
22
+ readonly process: { run(argv: readonly string[]): Promise<{ readonly exitCode: number; readonly stdout: string; readonly stderr: string }> }
23
+ readonly fs: { read(path: string): Promise<string> }
24
+ }
25
+
26
+ export async function readDevice(claude: DeviceSources): Promise<Device> {
23
27
  const output = async (argv: readonly string[]) => {
24
28
  const { exitCode, stdout, stderr } = await claude.process.run(argv)
25
29
  if (exitCode !== 0) throw new Error(`cmod could not read this computer: ${argv.join(' ')} ${formatExit(exitCode, stderr)}`)
@@ -37,7 +41,7 @@ export async function readDevice(claude: Pick<Claude, 'process' | 'fs'>): Promis
37
41
  return { id: await appSpecific(uuid.replaceAll('-', '').toLowerCase()), name, os, arch }
38
42
  }
39
43
 
40
- async function linuxMachineId(fs: Pick<Claude['fs'], 'read'>): Promise<string> {
44
+ async function linuxMachineId(fs: DeviceSources['fs']): Promise<string> {
41
45
  for (const path of machineIdFiles) {
42
46
  const id = (await fs.read(path).catch(ifMissing(''))).trim()
43
47
  if (machineId.test(id)) return id
@@ -4,6 +4,7 @@ import type { Pages } from './pages.js'
4
4
  import type { Router } from './router.js'
5
5
  import type { Failure } from './toaster.js'
6
6
  import type { ToolCalls } from './tool-calls.js'
7
+ import type { Watches } from './watches.js'
7
8
  import type { Widgets } from './widgets.js'
8
9
 
9
10
  export type Engine = {
@@ -14,6 +15,7 @@ export type Engine = {
14
15
  readonly hasPermissionCheck: () => boolean
15
16
  readonly answerInput: <Answer>(run: () => Promise<Answer>, passOn: () => Promise<unknown>) => Promise<Answer>
16
17
  readonly spawnCmod: (args: readonly string[], env?: Readonly<Record<string, string>>) => HookStream<ProcessSpawnChunk, ProcessSpawnResult>
18
+ readonly watches: Watches
17
19
  readonly widgets?: Widgets
18
20
  readonly pages?: Pages
19
21
  }
@@ -90,13 +90,13 @@ export async function callFiles(name: string, claude: Claude, folders: Promise<H
90
90
  const { shell, reads, writes } = callEffects(use, { cwd, home, ...(configRoot === undefined ? {} : { configRoot }), fs: claude.fs })
91
91
  const known = (accesses: FileAccess[]) => accesses.map(({ path }) => path).filter((path) => shell === undefined || !dynamicPattern.test(path))
92
92
  const unchecked = (path: string) => (error: unknown) => {
93
- if (!isMissing(error)) claude.ui.log(`${name}: the ${use.tool} call reads ${path}, which could not be checked: ${messageOf(error)}`, { to: 'debug' })
93
+ if (!isMissing(error)) claude.ui.warn('call:files', `${name}: the ${use.tool} call reads ${path}, which could not be checked: ${messageOf(error)}`)
94
94
  return undefined
95
95
  }
96
96
  const read = await Promise.all(known(reads).map(async (path) => ((await claude.fs.stat(path).catch(unchecked(path)))?.kind === 'file' ? [path] : [])))
97
97
  return { read: read.flat(), changed: known(writes) }
98
98
  } catch (error) {
99
- claude.ui.log(`${name}: the ${use.tool} call lists no files: ${messageOf(error)}`, { to: 'debug' })
99
+ claude.ui.warn('call:files', `${name}: the ${use.tool} call lists no files: ${messageOf(error)}`)
100
100
  return { read: [], changed: [] }
101
101
  }
102
102
  }
@@ -13,7 +13,7 @@ export async function readCombos(claude: Claude, configRoot: string | undefined)
13
13
  try {
14
14
  return boundCombos(JSON.parse(text))
15
15
  } catch (error) {
16
- claude.ui.log(`${configRoot}/keybindings.json is not JSON, so cmod reads no combos from it: ${messageOf(error)}`, { to: 'debug' })
16
+ claude.ui.warn('hotkeys:read', `${configRoot}/keybindings.json is not JSON, so cmod reads no combos from it: ${messageOf(error)}`)
17
17
  return new Map()
18
18
  }
19
19
  }
@@ -43,7 +43,7 @@ export function createInstaller(name: string, claude: () => Claude, waiting: { s
43
43
  await withBareRefusals(claude()).cmod.call({ to: cmodPluginName, method: partMethods.changed, input: update })
44
44
  }
45
45
 
46
- const log = (what: string) => (error: unknown) => claude().ui.log(`${name}: ${what}: ${messageOf(error)}`, { to: 'debug' })
46
+ const log = (what: string) => (error: unknown) => claude().ui.warn('installer:page', `${name}: ${what}: ${messageOf(error)}`)
47
47
 
48
48
  const open = (isAsked: boolean) => send({ requests: [{ open: installPage, focus: true }], ...(isAsked ? { isAsked: true } : {}) })
49
49
 
@@ -7,11 +7,11 @@ 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'
14
- import { answerCall, answeringOwnCalls, cmodPluginName, dependencyCalls, withBareRefusals } from './dependencies.js'
14
+ import { answerCall, answeringOwnCalls, cmodPluginName, dependencyCalls, loadedMethod, withBareRefusals } from './dependencies.js'
15
15
  import type { Device } from '../session/context/turn/device.js'
16
16
  import { keepEngine } from './engine.js'
17
17
  import { classicFailure, classicHook, userSkillHook, type Hook, type HookFields, type HookListener, type RoutedEvent } from './hooks.js'
@@ -299,7 +299,7 @@ export function createLifecycle<State extends object, Declared extends Options =
299
299
 
300
300
  const record = () => {
301
301
  recording ??= recordThroughCmod()
302
- .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)}`))
303
303
  .finally(() => {
304
304
  recording = undefined
305
305
  })
@@ -414,10 +414,10 @@ export function createLifecycle<State extends object, Declared extends Options =
414
414
  const { additionalContext, ...unread } = answer as { readonly additionalContext?: readonly string[] } & Record<string, unknown>
415
415
  for (const text of additionalContext ?? []) {
416
416
  const added = await claude().session.append({ message: { type: 'user', content: [{ type: 'text', text }] } })
417
- 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}`)
418
418
  }
419
419
  if (Object.keys(unread).length > 0) {
420
- 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.`)
421
421
  }
422
422
  }
423
423
 
@@ -550,11 +550,12 @@ export function createLifecycle<State extends object, Declared extends Options =
550
550
  }
551
551
  let recordCheck: Timer | undefined
552
552
  let checking: Promise<void> | undefined
553
+ let startingSession: string | undefined
553
554
  const watchRecord = () => {
554
555
  recordCheck ??= claude().clock.every(recordCheckMs, () => {
555
556
  checking ??= recover()
556
557
  .then(() => undefined)
557
- .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)}`))
558
559
  .finally(() => {
559
560
  checking = undefined
560
561
  })
@@ -570,17 +571,79 @@ export function createLifecycle<State extends object, Declared extends Options =
570
571
  if (activation !== undefined && phase !== 'active') await activation
571
572
  }
572
573
 
573
- const holdUntilStarted = (): Promise<void> =>
574
+ const held = (work: Promise<void>, signal: AbortSignal | undefined): Promise<void> =>
574
575
  runtime === undefined
575
- ? startSettled.then(whenActive)
576
+ ? work
576
577
  : new Promise<void>((resolve) => {
577
578
  const limit = claude().clock.after(startHoldMs, resolve)
578
- void startSettled.then(whenActive).then(() => {
579
+ if (signal?.aborted === true) resolve()
580
+ signal?.addEventListener('abort', () => resolve(), { once: true })
581
+ void work.then(() => {
579
582
  limit.cancel()
580
583
  resolve()
581
584
  })
582
585
  })
583
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
+
584
647
  return {
585
648
  get phase() {
586
649
  return phase
@@ -601,9 +664,14 @@ export function createLifecycle<State extends object, Declared extends Options =
601
664
  },
602
665
  async start(claudeCalls, read) {
603
666
  if (runtime !== undefined) return
604
- programs = locatingPrograms(claudeCalls)
605
- const callingCmod: Claude = {
667
+ const naming: Claude = {
606
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,
607
675
  cmod: {
608
676
  async call(input) {
609
677
  if (input.to === definition.name) await holdUntilStarted()
@@ -622,56 +690,14 @@ export function createLifecycle<State extends object, Declared extends Options =
622
690
  }
623
691
  },
624
692
  async route<N extends RoutedEvent>(event: N, e: Frozen<Args<N>>, next: RouterNext<N>, signal?: AbortSignal): Promise<EventResult<N>> {
625
- if (imports !== undefined) bind(imports)
626
- const asked = e as Frozen<Args<'cmod.call'>> & { readonly caller?: string }
627
- if (event === 'cmod.call' && asked.to === definition.name && asked.caller === cmodPluginName) {
628
- if (asked.method === partMethods.shown) installer.hear(asked.input as ShownPages)
629
- const answered = installer.answer(asked.method, asked.input)
630
- if (answered !== undefined) return (await answered.catch((error: unknown) => ({ deny: `${definition.name}: ${messageOf(error)}` }))) as EventResult<N>
631
- if (asked.method === partMethods.shown && phase !== 'active') return { value: null } as EventResult<N>
632
- }
633
- if (event === 'classic.SessionStart') {
634
- missedSessionStart = undefined
635
- hasHeardSessionStart = true
636
- }
637
- if (event === 'classic.SessionStart' && runtime === undefined) {
638
- missedSessionStart = e as Frozen<Args<'classic.SessionStart'>>
639
- return next(e)
640
- }
641
- if (shouldRecord && event === 'classic.UserPromptSubmit') record()
642
- if (event === 'classic.UserPromptSubmit' || event === 'classic.SessionStart') await recover().catch((error: unknown) => claude().ui.log(`${definition.name} stays stopped: ${messageOf(error)}`, { to: 'debug' }))
643
- const tool = (e as { readonly tool?: unknown }).tool
644
- 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}__`))
645
- if (event === 'cmod.call' && !isCallToThisMod) return next(e)
646
- await (event === 'classic.SessionStart' || event === 'session.append' || isCallToThisMod ? holdUntilStarted() : whenActive())
647
- if (event === 'classic.SessionStart' && phase !== 'active') {
648
- missedSessionStart = e as Frozen<Args<'classic.SessionStart'>>
649
- return next(e)
650
- }
651
- if (isCallToThisMod && phase !== 'active') {
652
- if (event === 'cmod.call' && listenMethods.includes(asked.method)) {
653
- heldListens.set(`${asked.caller}\n${asked.method}\n${String((asked.input as { readonly session?: unknown }).session)}`, asked)
654
- return { value: null } as EventResult<N>
655
- }
656
- return { deny: phase === 'failed' ? notSetUp() : `${definition.name} is installing. Try again when it's ready.` } as EventResult<N>
657
- }
658
- const call = e as Frozen<Args<'cmod.call'>>
659
- if (event === 'cmod.call' && call.to === definition.name && mod !== undefined) {
660
- if (call.method === pendingStepsMethod) return { value: await pendingSteps(mod) } as EventResult<N>
661
- if (call.method === finishStepsMethod) {
662
- const active = mod
663
- 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()]))
664
- return { value: opened } as EventResult<N>
665
- }
666
- }
667
- if (event === 'classic.UserPromptSubmit' && phase === 'active' && !hasHeardSessionStart) {
668
- const { session_id, transcript_path, cwd } = e as Frozen<Args<'classic.UserPromptSubmit'>>
669
- 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
670
700
  }
671
- const answer = router.dispatch(event, e, next, signal)
672
- const render = e as Frozen<Args<'ui.render'>>
673
- if (event !== 'ui.render' || render.component !== 'AbovePrompt' || runtime === undefined) return answer
674
- return runtime.toaster.draw((await answer) as EventResult<'ui.render'>, runtime.claude.ui.resolve(render), render.props, render.requestId) as EventResult<N>
675
701
  },
676
702
  async caught<N extends RoutedEvent>(event: N, e: Frozen<Args<N>>, next: RouterNext<N>, { error: { kind, message }, called }: Caught): Promise<EventResult<N>> {
677
703
  const call = e as Frozen<Args<'cmod.call'>>
@@ -719,7 +745,7 @@ async function createMod<State extends object, Declared extends Options>(definit
719
745
  const parent = await claude.cmod.call({ to: cmodPluginName, method: 'forkParent', input: null })
720
746
  return typeof parent === 'string' ? parent : undefined
721
747
  } catch (error) {
722
- 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)}`)
723
749
  return undefined
724
750
  }
725
751
  }
@@ -831,6 +857,9 @@ async function createMod<State extends object, Declared extends Options>(definit
831
857
  await toaster.copy(text)
832
858
  },
833
859
  },
860
+ mods: {
861
+ isLoaded: async (name) => (await claude.cmod.call({ to: cmodPluginName, method: loadedMethod, input: { name } })) === true,
862
+ },
834
863
  }
835
864
  const timer = (ms: number, subject: string, repeats: boolean, listener: () => unknown): ModTimer => {
836
865
  let isFiring = false
@@ -921,8 +950,8 @@ async function createMod<State extends object, Declared extends Options>(definit
921
950
  report({ id: 'cmod:follow', message: `Keeps the state of ${modState.root} until the next prompt or folder move`, error })
922
951
  }
923
952
  }
924
- const followCurrent = async (title: string | undefined) => {
925
- const [id, model, usage] = await Promise.all([claude.session.id(), claude.session.model(), claude.session.usage()])
953
+ const followCurrent = async (id: string, title: string | undefined) => {
954
+ const [model, usage] = await Promise.all([claude.session.model(), claude.session.usage()])
926
955
  followed = { id, title: title ?? '', project: modState.root, cwd, model, startedAt: new Date(usage.startedAt).toISOString(), ...(forkedFrom === undefined ? {} : { forkedFrom }), ...(agentType === undefined ? {} : { agentType }) }
927
956
  client.follow(followed)
928
957
  }
@@ -935,17 +964,17 @@ async function createMod<State extends object, Declared extends Options>(definit
935
964
  parentAsked = undefined
936
965
  }
937
966
  hasEarlierPrompts = e.source !== 'startup' && e.source !== 'clear'
967
+ 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 }))
938
968
  await modState.switchSession(e.session_id, e.source, e.transcript_path).catch((error: unknown) => {
939
969
  report({ id: 'cmod:session', message: `Kept its session values from before the ${e.source}`, error })
940
970
  })
941
- await followCurrent(e.session_title).catch((error: unknown) => report({ id: 'cmod:current', message: 'Kept the details of the session from before', error }))
942
971
  return next(e)
943
972
  })
944
973
  router.add('classic.UserPromptSubmit', async (e, next) => {
945
974
  staleCwd = undefined
946
975
  await followSession()
947
976
  const isPerson = e.source === undefined || e.source === 'user' || e.source === 'sdk'
948
- 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 }))
977
+ 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 }))
949
978
  return next(e)
950
979
  })
951
980
  for (const event of ['classic.PostToolUse', 'classic.PostToolUseFailure'] as const) {
@@ -979,7 +1008,7 @@ async function createMod<State extends object, Declared extends Options>(definit
979
1008
  pages = widgets === undefined ? undefined : servePages({ claude, router, report: reportPart, widgets, parts, tellStylers: area.restyled })
980
1009
  const tellColor = (to: string, told: SessionColor) => {
981
1010
  if (told.session === '' || to === cmodPluginName) return
982
- 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' })))
1011
+ 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)}`)))
983
1012
  }
984
1013
  conversations?.onColor((told) => {
985
1014
  client.recolor(told)
@@ -1025,6 +1054,7 @@ async function createMod<State extends object, Declared extends Options>(definit
1025
1054
  hasPermissionCheck: () => runtime.permissionRoutes() !== undefined,
1026
1055
  answerInput: area.answerInput,
1027
1056
  spawnCmod: (args, env) => spawnCmod(claude, args, session, env),
1057
+ watches,
1028
1058
  ...(widgets === undefined ? {} : { widgets }),
1029
1059
  ...(pages === undefined ? {} : { pages }),
1030
1060
  })
@@ -1039,7 +1069,7 @@ async function createMod<State extends object, Declared extends Options>(definit
1039
1069
  await failsAs('its options did not load', () => modOptions.load(root))
1040
1070
  const missing = modOptions.missing
1041
1071
  if (missing.length > 0) throw new MissingOptions(missing, missing.map((key) => definition.options?.[key]?.title ?? key))
1042
- await failsAs('the details of its session did not load', () => followCurrent(undefined))
1072
+ await failsAs('the details of its session did not load', () => followCurrent(session, undefined))
1043
1073
  const returned = await failsAs('its setup function threw', () => definition.setup(mod))
1044
1074
  api = apiOf(definition.name, returned)
1045
1075
  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
  }
@@ -1,6 +1,6 @@
1
1
  import type { PluginOptions } from 'claude-code'
2
- import { fitsOption, isUnset, type Option, type Options } from '../options.js'
3
- import { configFolders, secretFix } from '../records.js'
2
+ import { fitsOption, isUnset, projectOptionsOf, type Option, type Options } from '../options.js'
3
+ import { configFolders } from '../records.js'
4
4
  import { listed, messageOf } from '../utils/text.js'
5
5
  import type { Claude } from './claude.js'
6
6
  import type { Failure } from './toaster.js'
@@ -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)))
@@ -56,29 +56,8 @@ export function createOptions({
56
56
  if (project === undefined) return {}
57
57
  const path = `${project.folder}/options.json`
58
58
  if (!(await claude.fs.exists(path))) return {}
59
- const ignore = (reason: string) => report({ id: `options:${path} ${reason}`, message: `Ignores part of ${path}`, description: `${path} ${reason}` })
60
- let file: unknown
61
- try {
62
- file = JSON.parse(await claude.fs.read(path))
63
- } catch (error) {
64
- ignore(`is not JSON (${messageOf(error)}). Fix the file; ${name} uses its other options until then.`)
65
- return {}
66
- }
67
- if (typeof file !== 'object' || file === null || Array.isArray(file)) {
68
- ignore('is not a JSON object. Write one, such as { "branch": "main" }.')
69
- return {}
70
- }
71
- const kept: Record<string, unknown> = {}
72
- for (const [key, value] of Object.entries(file)) {
73
- const option = declared[key]
74
- if (option === undefined) ignore(`sets ${key}, which ${name} does not declare. ${Object.keys(declared).length === 0 ? 'Remove it.' : `Remove it, or use one of: ${Object.keys(declared).join(', ')}.`}`)
75
- else if (option.type === 'secret') ignore(`sets ${key}, a secret, and a project file is committed for everyone to read. Remove it. ${secretFix}`)
76
- else {
77
- const misfit = fitsOption(option, value)
78
- if (misfit === undefined) kept[key] = value
79
- else ignore(`sets ${key} to ${JSON.stringify(value)}, and ${option.title} ${misfit}.`)
80
- }
81
- }
59
+ const { values: kept, ignored } = projectOptionsOf(name, declared, await claude.fs.read(path))
60
+ for (const reason of ignored) report({ id: `options:${path} ${reason}`, message: `Ignores part of ${path}`, description: `${path} ${reason}` })
82
61
  return kept
83
62
  }
84
63