@cmodjs/core 5.2.1 → 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 (69) hide show
  1. package/docs/commands.md +2 -2
  2. package/docs/install-steps.md +2 -0
  3. package/docs/jobs.md +1 -1
  4. package/docs/state.md +1 -1
  5. package/docs/testing.md +1 -1
  6. package/docs/ui.md +1 -1
  7. package/jobs/program.d.ts.map +1 -1
  8. package/jobs/program.js +55 -4
  9. package/package.json +1 -1
  10. package/records.d.ts +2 -2
  11. package/records.js +2 -2
  12. package/register.d.ts.map +1 -1
  13. package/register.js +23 -3
  14. package/runtime/claude.d.ts +2 -0
  15. package/runtime/claude.d.ts.map +1 -1
  16. package/runtime/conversations.js +8 -8
  17. package/runtime/deadline.d.ts +2 -0
  18. package/runtime/deadline.d.ts.map +1 -1
  19. package/runtime/deadline.js +17 -0
  20. package/runtime/engine.d.ts +2 -0
  21. package/runtime/engine.d.ts.map +1 -1
  22. package/runtime/hooks.js +2 -2
  23. package/runtime/hotkeys.js +1 -1
  24. package/runtime/installer.js +1 -1
  25. package/runtime/lifecycle.d.ts.map +1 -1
  26. package/runtime/lifecycle.js +102 -74
  27. package/runtime/metadata.js +1 -1
  28. package/runtime/options.js +1 -1
  29. package/runtime/pages.js +3 -3
  30. package/runtime/programs.d.ts +1 -0
  31. package/runtime/programs.d.ts.map +1 -1
  32. package/runtime/programs.js +6 -0
  33. package/runtime/sessions.js +1 -1
  34. package/runtime/state.d.ts +1 -0
  35. package/runtime/state.d.ts.map +1 -1
  36. package/runtime/state.js +6 -3
  37. package/runtime/toaster.d.ts +5 -0
  38. package/runtime/toaster.d.ts.map +1 -1
  39. package/runtime/toaster.js +27 -11
  40. package/runtime/ui.d.ts +1 -0
  41. package/runtime/ui.d.ts.map +1 -1
  42. package/runtime/ui.js +6 -6
  43. package/runtime/widgets.js +1 -1
  44. package/src/jobs/program.ts +60 -4
  45. package/src/records.ts +2 -2
  46. package/src/register.ts +25 -3
  47. package/src/runtime/claude.ts +2 -0
  48. package/src/runtime/conversations.ts +8 -8
  49. package/src/runtime/deadline.ts +16 -0
  50. package/src/runtime/engine.ts +2 -0
  51. package/src/runtime/hooks.ts +2 -2
  52. package/src/runtime/hotkeys.ts +1 -1
  53. package/src/runtime/installer.ts +1 -1
  54. package/src/runtime/lifecycle.ts +93 -66
  55. package/src/runtime/metadata.ts +1 -1
  56. package/src/runtime/options.ts +1 -1
  57. package/src/runtime/pages.ts +3 -3
  58. package/src/runtime/programs.ts +7 -0
  59. package/src/runtime/sessions.ts +1 -1
  60. package/src/runtime/state.ts +7 -3
  61. package/src/runtime/toaster.ts +47 -12
  62. package/src/runtime/ui.ts +6 -6
  63. package/src/runtime/widgets.ts +1 -1
  64. package/src/testing/fake-claude.ts +2 -0
  65. package/src/testing.ts +6 -2
  66. package/testing/fake-claude.d.ts.map +1 -1
  67. package/testing/fake-claude.js +2 -0
  68. package/testing.d.ts.map +1 -1
  69. package/testing.js +7 -2
package/runtime/ui.js CHANGED
@@ -111,7 +111,7 @@ export function merged(updates) {
111
111
  const isRedrawn = updates.some((update) => update.redraw === true);
112
112
  return { ...(parts === undefined ? {} : { parts }), ...(isRedrawn ? { redraw: true } : {}), ...(requests.length === 0 ? {} : { requests }) };
113
113
  }
114
- const keptDrawInputs = 200;
114
+ export const keptDrawInputs = 200;
115
115
  export function createUi({ name, claude, router, report, announce, mod, borrowed, nextDraw }) {
116
116
  const panes = new Map();
117
117
  const paneLogs = new Map();
@@ -131,7 +131,7 @@ export function createUi({ name, claude, router, report, announce, mod, borrowed
131
131
  paneStates.set(id, { isShown: open.isShown, isFocused: open.isFocused });
132
132
  }
133
133
  };
134
- const readPanes = () => syncPanes().catch((error) => claude.ui.log(`${name} keeps its panes' open, shown, and focused state from before: ${messageOf(error)}`, { to: 'debug' }));
134
+ const readPanes = () => syncPanes().catch((error) => claude.ui.warn('panes:read', `${name} keeps its panes' open, shown, and focused state from before: ${messageOf(error)}`));
135
135
  const requestedSizes = new Map();
136
136
  const styles = new Set();
137
137
  const markdownRenders = new Map();
@@ -185,7 +185,7 @@ export function createUi({ name, claude, router, report, announce, mod, borrowed
185
185
  return true;
186
186
  }
187
187
  catch (error) {
188
- claude.ui.log(`${name}: the ${key} drawing threw, so the cmod plugin asks for it again: ${messageOf(error)}`, { to: 'debug' });
188
+ claude.ui.warn(`drawing:${key}`, `${name}: the ${key} drawing threw, so the cmod plugin asks for it again: ${messageOf(error)}`);
189
189
  return true;
190
190
  }
191
191
  const latest = sent.draws.at(-1);
@@ -219,7 +219,7 @@ export function createUi({ name, claude, router, report, announce, mod, borrowed
219
219
  unheldRequests += 1;
220
220
  if (isObject(answer) && name !== cmodPluginName)
221
221
  hear(answer['stylers'], false);
222
- }, (error) => claude.ui.log(`${name}: the cmod plugin did not hear about its pages and widgets: ${messageOf(error)}`, { to: 'debug' }));
222
+ }, (error) => claude.ui.warn('parts:tell', `${name}: the cmod plugin did not hear about its pages and widgets: ${messageOf(error)}`));
223
223
  };
224
224
  if (!isAsked)
225
225
  return Promise.resolve().then(tell);
@@ -353,7 +353,7 @@ export function createUi({ name, claude, router, report, announce, mod, borrowed
353
353
  await openAt(pane, size);
354
354
  }
355
355
  catch (error) {
356
- claude.ui.log(`${name}: the ${pane.title} pane kept its size: ${messageOf(error)}`, { to: 'debug' });
356
+ claude.ui.warn(`pane:resize:${pane.id}`, `${name}: the ${pane.title} pane kept its size: ${messageOf(error)}`);
357
357
  }
358
358
  };
359
359
  const handle = async (pane, handler, run) => {
@@ -455,7 +455,7 @@ export function createUi({ name, claude, router, report, announce, mod, borrowed
455
455
  panes.delete(init.id);
456
456
  paneLogs.delete(init.id);
457
457
  if (openPanes.has(init.id))
458
- void claude.ui.close({ id: init.id }).catch((error) => claude.ui.log(`${name}: the ${init.title} pane stayed open: ${messageOf(error)}`, { to: 'debug' }));
458
+ void claude.ui.close({ id: init.id }).catch((error) => claude.ui.warn(`pane:close:${init.id}`, `${name}: the ${init.title} pane stayed open: ${messageOf(error)}`));
459
459
  openPanes.delete(init.id);
460
460
  paneStates.delete(init.id);
461
461
  },
@@ -122,7 +122,7 @@ export function serveWidgets({ claude, router, store, report, turnClosedBy, part
122
122
  }
123
123
  catch (error) {
124
124
  declared.delete(mod);
125
- claude.ui.log(`cmod: ${mod} did not list its widgets: ${messageOf(error)}`, { to: 'debug' });
125
+ claude.ui.warn(`widgets:list:${mod}`, `cmod: ${mod} did not list its widgets: ${messageOf(error)}`);
126
126
  }
127
127
  };
128
128
  const recheck = async () => {
@@ -1,5 +1,8 @@
1
1
  import type { Job } from '../mod.js'
2
+ import { instancePath, storeFolder } from '../records.js'
2
3
  import { engineOf } from '../runtime/engine.js'
4
+ import { isHeld } from '../runtime/programs.js'
5
+ import { ifMissing } from '../utils/paths.js'
3
6
  import { messageOf } from '../utils/text.js'
4
7
  import { basename } from '../vendor.js'
5
8
 
@@ -12,10 +15,16 @@ type Address = Awaited<ReturnType<Program['ready']>>
12
15
 
13
16
  const backoffSeconds = [1, 2, 4, 8, 16] as const
14
17
 
18
+ const leaseCheckMs = 5000
19
+
20
+ const staleMs = 15_000
21
+
22
+ const retryWithinMs = 1000
23
+
15
24
  export function program(options: { readonly command: readonly string[]; readonly environment?: Record<string, string>; readonly singleInstance?: boolean }): Job<Program> {
16
25
  const { command, environment, singleInstance = false } = options
17
26
  return ({ mod, announce, reserveName }) => {
18
- const { claude, report, spawnCmod } = engineOf(mod)
27
+ const { claude, report, spawnCmod, watches } = engineOf(mod)
19
28
  const [executable] = command
20
29
  if (executable === undefined) throw new Error(`${mod.name}: the program has no command. Name the program on PATH and its arguments, such as ['preview-server', '--port', '0'].`)
21
30
  if (singleInstance) reserveName('program', basename(executable), `${mod.name}: the single instance of ${executable} is already added. Give each singleInstance program its own executable.`)
@@ -25,8 +34,17 @@ export function program(options: { readonly command: readonly string[]; readonly
25
34
  let failure: Error | undefined
26
35
  let exits = 0
27
36
  const waiting: { resolve: (address: Address) => void; reject: (error: Error) => void }[] = []
37
+ let isFollowing = false
38
+ let isWatching = false
39
+ let instance: Promise<string> | undefined
40
+ let leaseCheck: Promise<void> | undefined
41
+
42
+ const spawn = () => (singleInstance ? spawnCmod(['program', mod.name, '--no-wait', '--', ...command], environment) : claude.process.spawn(request))
28
43
 
29
- const spawn = () => (singleInstance ? spawnCmod(['program', mod.name, '--', ...command], environment) : claude.process.spawn(request))
44
+ const instanceFile = () =>
45
+ (instance ??= Promise.all([claude.env.home(), claude.env.dataHome()]).then(([home, dataHome]) => instancePath(storeFolder({ HOME: home, XDG_DATA_HOME: dataHome }), mod.name, basename(executable))))
46
+
47
+ const following = (run: Promise<unknown>) => void run.catch((error: unknown) => report({ id: `program:${executable}:follow`, message: `Could not follow the ${executable} program`, error }))
30
48
 
31
49
  const stop = (reason: string) => {
32
50
  address = undefined
@@ -48,26 +66,64 @@ export function program(options: { readonly command: readonly string[]; readonly
48
66
  for (const waiter of waiting.splice(0)) waiter.resolve(next)
49
67
  }
50
68
 
69
+ const checkLease = (file: string) =>
70
+ (leaseCheck ??= (async () => {
71
+ if (!isFollowing || (await isHeld(claude, `${file}.lock`, staleMs))) return
72
+ isFollowing = false
73
+ void start()
74
+ })().finally(() => {
75
+ leaseCheck = undefined
76
+ }))
77
+
78
+ const track = async (file: string) => {
79
+ if (!isFollowing) return
80
+ const recorded = await claude.fs.read(file).catch(ifMissing(undefined))
81
+ const next = recorded === undefined ? undefined : addressOf(String((JSON.parse(recorded) as { readonly address?: unknown }).address).trim())
82
+ if (next !== undefined) return show(next)
83
+ address = undefined
84
+ state = 'starting'
85
+ claude.clock.after(Math.random() * retryWithinMs, () => following(checkLease(file)))
86
+ }
87
+
88
+ const follow = async (file: string) => {
89
+ isFollowing = true
90
+ if (!isWatching) {
91
+ isWatching = true
92
+ watches.add([file], () => following(track(file)))
93
+ claude.clock.every(leaseCheckMs, () => following(checkLease(file)))
94
+ }
95
+ await track(file)
96
+ }
97
+
51
98
  const start = async () => {
99
+ isFollowing = false
100
+ address = undefined
52
101
  state = 'starting'
53
102
  let pending = ''
54
103
  let lastError = ''
104
+ let isShown = false
55
105
  try {
106
+ if (singleInstance) {
107
+ const file = await instanceFile()
108
+ if (await isHeld(claude, `${file}.lock`, staleMs)) return await follow(file)
109
+ }
56
110
  for await (const piece of await spawn()) {
57
111
  if (piece.stream === 'stderr') {
58
112
  lastError = piece.text.trim().split('\n').at(-1) ?? lastError
59
113
  continue
60
114
  }
61
- if (address !== undefined && !singleInstance) continue
115
+ if (isShown) continue
62
116
  const lines = `${pending}${piece.text}`.split('\n')
63
117
  pending = lines.pop() ?? ''
64
- for (const line of singleInstance ? lines : lines.slice(0, 1)) {
118
+ for (const line of lines.slice(0, 1)) {
119
+ if (singleInstance && line.trim() === 'held') return await follow(await instanceFile())
65
120
  const next = addressOf(line.trim())
66
121
  if (next === undefined) {
67
122
  stop(`its first line is "${line.trim()}". Write 127.0.0.1:<port> or unix:<socket path> as the first line on standard output.`)
68
123
  return
69
124
  }
70
125
  show(next)
126
+ isShown = true
71
127
  }
72
128
  }
73
129
  } catch (error) {
package/src/records.ts CHANGED
@@ -307,9 +307,9 @@ function readHotkeys(hotkeys: unknown): Steps {
307
307
  return { hotkeys: checkHotkeys('package.json "cmod"', hotkeys as Record<string, HotkeyInit>) }
308
308
  }
309
309
 
310
- export const coreVersion = '5.2.1'
310
+ export const coreVersion = '5.3.0'
311
311
 
312
- export const oldestCmodVersion = '5.2.0'
312
+ export const oldestCmodVersion = '5.3.0'
313
313
 
314
314
  export function hotkeyCommand(mod: string, hotkey: string): string {
315
315
  return `${mod}--${hotkey}`
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}`
@@ -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