@cmodjs/core 6.3.0 → 8.0.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 (138) hide show
  1. package/docs/commands.md +123 -65
  2. package/docs/dependencies.md +189 -4
  3. package/docs/index.md +56 -12
  4. package/docs/install-steps.md +20 -17
  5. package/docs/jobs.md +43 -16
  6. package/docs/mod.md +43 -27
  7. package/docs/options.md +2 -2
  8. package/docs/session.md +58 -32
  9. package/docs/testing.md +88 -24
  10. package/docs/ui.md +128 -58
  11. package/installer.d.ts +2 -2
  12. package/jobs/context.js +1 -1
  13. package/jobs/program.d.ts +4 -1
  14. package/jobs/program.d.ts.map +1 -1
  15. package/jobs/program.js +79 -20
  16. package/mod.d.ts +59 -9
  17. package/mod.d.ts.map +1 -1
  18. package/mod.js +5 -3
  19. package/package.json +1 -1
  20. package/records.d.ts +15 -2
  21. package/records.d.ts.map +1 -1
  22. package/records.js +24 -10
  23. package/register.d.ts.map +1 -1
  24. package/register.js +7 -4
  25. package/rpc.d.ts +7 -0
  26. package/rpc.d.ts.map +1 -0
  27. package/rpc.js +59 -0
  28. package/runtime/bound.d.ts +1 -0
  29. package/runtime/bound.d.ts.map +1 -1
  30. package/runtime/bound.js +10 -0
  31. package/runtime/bun.d.ts +20 -0
  32. package/runtime/bun.d.ts.map +1 -0
  33. package/runtime/bun.js +20 -0
  34. package/runtime/claude.d.ts +1 -0
  35. package/runtime/claude.d.ts.map +1 -1
  36. package/runtime/conversations.d.ts +12 -1
  37. package/runtime/conversations.d.ts.map +1 -1
  38. package/runtime/conversations.js +472 -362
  39. package/runtime/deadline.d.ts +4 -3
  40. package/runtime/deadline.d.ts.map +1 -1
  41. package/runtime/deadline.js +10 -4
  42. package/runtime/engine.d.ts +5 -4
  43. package/runtime/engine.d.ts.map +1 -1
  44. package/runtime/installer.d.ts +3 -3
  45. package/runtime/installer.d.ts.map +1 -1
  46. package/runtime/installer.js +10 -9
  47. package/runtime/interfaces.d.ts +262 -0
  48. package/runtime/interfaces.d.ts.map +1 -0
  49. package/runtime/interfaces.js +935 -0
  50. package/runtime/lifecycle.d.ts +3 -3
  51. package/runtime/lifecycle.d.ts.map +1 -1
  52. package/runtime/lifecycle.js +83 -52
  53. package/runtime/options.d.ts.map +1 -1
  54. package/runtime/options.js +2 -6
  55. package/runtime/parts.d.ts +64 -1
  56. package/runtime/parts.d.ts.map +1 -1
  57. package/runtime/parts.js +311 -4
  58. package/runtime/programs.d.ts +1 -0
  59. package/runtime/programs.d.ts.map +1 -1
  60. package/runtime/programs.js +5 -3
  61. package/runtime/rpc.d.ts +111 -0
  62. package/runtime/rpc.d.ts.map +1 -0
  63. package/runtime/rpc.js +387 -0
  64. package/runtime/sessions.d.ts +6 -4
  65. package/runtime/sessions.d.ts.map +1 -1
  66. package/runtime/sessions.js +59 -80
  67. package/runtime/toaster.js +1 -1
  68. package/runtime/ui.d.ts +23 -10
  69. package/runtime/ui.d.ts.map +1 -1
  70. package/runtime/ui.js +63 -52
  71. package/runtime/web.d.ts +0 -73
  72. package/runtime/web.d.ts.map +1 -1
  73. package/runtime/web.js +9 -5
  74. package/runtime/widgets.d.ts +4 -2
  75. package/runtime/widgets.d.ts.map +1 -1
  76. package/runtime/widgets.js +17 -16
  77. package/session/conversation.d.ts +7 -1
  78. package/session/conversation.d.ts.map +1 -1
  79. package/session/session.d.ts +31 -7
  80. package/session/session.d.ts.map +1 -1
  81. package/session/session.js +1 -0
  82. package/src/installer.ts +2 -2
  83. package/src/jobs/context.ts +1 -1
  84. package/src/jobs/program.ts +76 -21
  85. package/src/mod.ts +51 -10
  86. package/src/records.ts +33 -9
  87. package/src/register.ts +7 -4
  88. package/src/rpc.ts +67 -0
  89. package/src/runtime/bound.ts +10 -0
  90. package/src/runtime/bun.ts +40 -0
  91. package/src/runtime/claude.ts +1 -0
  92. package/src/runtime/conversations.ts +470 -352
  93. package/src/runtime/deadline.ts +13 -6
  94. package/src/runtime/engine.ts +5 -4
  95. package/src/runtime/installer.ts +13 -12
  96. package/src/runtime/interfaces.ts +1161 -0
  97. package/src/runtime/lifecycle.ts +102 -59
  98. package/src/runtime/options.ts +2 -5
  99. package/src/runtime/parts.ts +364 -5
  100. package/src/runtime/programs.ts +6 -3
  101. package/src/runtime/rpc.ts +457 -0
  102. package/src/runtime/sessions.ts +63 -83
  103. package/src/runtime/toaster.ts +1 -1
  104. package/src/runtime/ui.ts +82 -61
  105. package/src/runtime/web.ts +10 -39
  106. package/src/runtime/widgets.ts +20 -18
  107. package/src/session/conversation.ts +7 -1
  108. package/src/session/session.ts +22 -7
  109. package/src/testing/fake-claude.ts +38 -7
  110. package/src/testing/fake-serve.ts +144 -0
  111. package/src/testing/fake-sessions.ts +21 -6
  112. package/src/testing.ts +156 -68
  113. package/src/ui/areas.ts +2 -2
  114. package/src/ui/elements.ts +21 -16
  115. package/src/ui/panes.ts +14 -7
  116. package/testing/fake-claude.d.ts +6 -0
  117. package/testing/fake-claude.d.ts.map +1 -1
  118. package/testing/fake-claude.js +34 -7
  119. package/testing/fake-serve.d.ts +39 -0
  120. package/testing/fake-serve.d.ts.map +1 -0
  121. package/testing/fake-serve.js +110 -0
  122. package/testing/fake-sessions.d.ts.map +1 -1
  123. package/testing/fake-sessions.js +22 -6
  124. package/testing.d.ts +21 -4
  125. package/testing.d.ts.map +1 -1
  126. package/testing.js +138 -56
  127. package/ui/areas.d.ts +3 -1
  128. package/ui/areas.d.ts.map +1 -1
  129. package/ui/elements.d.ts +18 -9
  130. package/ui/elements.d.ts.map +1 -1
  131. package/ui/elements.js +9 -8
  132. package/ui/panes.d.ts +10 -6
  133. package/ui/panes.d.ts.map +1 -1
  134. package/ui/panes.js +5 -3
  135. package/runtime/pages.d.ts +0 -32
  136. package/runtime/pages.d.ts.map +0 -1
  137. package/runtime/pages.js +0 -142
  138. package/src/runtime/pages.ts +0 -183
@@ -10,7 +10,7 @@ import { TurnEnd, TurnStart, type Turn } from '../session/context/turn/turn.js'
10
10
  import { forkAgentType, searchLimit, type ContextData, type GoalData, type SessionChange, type SessionData, type TaskData, type TurnData } from '../session/conversation.js'
11
11
  import { GoalChange, type Goal } from '../session/goal/goal.js'
12
12
  import { TaskEnd, TaskStart, type Task } from '../session/goal/task.js'
13
- import { beforeEvents, processEvents, Session, sessionEvents, type BeforeEvent, type Placement, type BeforeMethods, type Surface, type OnMethods, type ProcessBeforeMethods, type ProcessName, type ProcessOnMethods, type RecordPart, type SearchOptions, type SessionEvent, type SessionScope, type SessionSend, type Sessions, type TaskOwner, type TaskStartArgs, type ToolCallArgs, type Usage } from '../session/session.js'
13
+ import { beforeEvents, processEvents, Session, sessionEvents, type BeforeEvent, type ForkArgs, type Placement, type BeforeMethods, type Surface, type OnMethods, type ProcessBeforeMethods, type ProcessName, type ProcessOnMethods, type RecordPart, type SearchOptions, type SessionEvent, type SessionScope, type SessionSend, type Sessions, type TaskOwner, type TaskStartArgs, type ToolCallArgs, type Usage } from '../session/session.js'
14
14
  import { matches, sentMatcher, type Matcher, type SentMatcher } from '../utils/matcher.js'
15
15
  import { beforeAnswerKeys, foldAnswers, foldBefore, methodOf, takenAnswer, type Answers, type Place } from './before.js'
16
16
  import type { Claude } from './claude.js'
@@ -20,12 +20,13 @@ import { listenerOf, PassedTimeout, withinTime, type ListenOptions, type ListenT
20
20
  import { callFiles, type HomeFolders, type HookFields } from './hooks.js'
21
21
  import type { PermissionRoutes } from './permission-check.js'
22
22
 
23
- export type Listened = { readonly event: SessionEvent; readonly matcher: SentMatcher | undefined; readonly onFailure?: 'refuse'; readonly scope?: Scope }
23
+ export type Listened = { readonly event: SessionEvent; readonly matcher: SentMatcher | undefined; readonly onFailure?: 'refuse'; readonly scope?: Scope; readonly timeoutMs?: number }
24
24
 
25
25
  export const everySession = '*'
26
26
 
27
27
  export const conversationMethods = {
28
28
  sessions: 'cmod:sessions',
29
+ session: 'cmod:session',
29
30
  search: 'cmod:search',
30
31
  messages: 'cmod:messages',
31
32
  turns: 'cmod:turns',
@@ -45,12 +46,14 @@ export type SessionColor = { readonly session: string; readonly color?: string }
45
46
 
46
47
  const resetColors: readonly string[] = ['default', 'reset', 'none', 'gray', 'grey']
47
48
 
49
+ const sessionFields: Readonly<Record<keyof SessionData, true>> = { id: true, title: true, color: true, project: true, cwd: true, model: true, startedAt: true, lastAt: true, forkedFrom: true, isRunning: true, agentType: true, visitedAt: true, device: true, status: true, waitingFor: true, contextPercent: true, lastTurn: true }
50
+
48
51
  export function pickedColor(args: string): string | undefined {
49
52
  const picked = args.trim().toLowerCase()
50
53
  return resetColors.includes(picked) ? undefined : picked
51
54
  }
52
55
 
53
- const acts = ['send', 'startTask', 'fork', 'clone', 'startBackgroundTask', 'callTool', 'usage', 'surfaces', 'abort'] as const
56
+ const acts = ['send', 'startTask', 'fork', 'clone', 'startBackgroundTask', 'callTool', 'usage', 'surfaces', 'abort', 'end', 'visit', 'delete'] as const
54
57
 
55
58
  export type Act = (typeof acts)[number]
56
59
 
@@ -60,9 +63,9 @@ export type Scope = { readonly session?: string; readonly context?: number; read
60
63
 
61
64
  export type SessionsClient = {
62
65
  readonly sessions: Sessions
63
- changed(session: string, change: SessionChange, isInProject: boolean, cancel: AbortSignal): void
64
- answerBefore(session: string, event: BeforeEvent, change: SessionChange, isInProject: boolean, cancel: AbortSignal): Promise<unknown>
65
- failedBefore(session: string, event: BeforeEvent, change: SessionChange, isInProject: boolean, error: Error): { readonly refuse: string } | undefined
66
+ changed(session: string, change: SessionChange, cancel: AbortSignal): void
67
+ answerBefore(session: string, event: BeforeEvent, change: SessionChange, cancel: AbortSignal): Promise<unknown>
68
+ failedBefore(session: string, event: BeforeEvent, change: SessionChange, error: Error): { readonly refuse: string } | undefined
66
69
  raise(method: string, payload: Readonly<Record<string, unknown>>, cancel: AbortSignal): Promise<unknown>
67
70
  listen(method: string, args: readonly unknown[]): Subscription
68
71
  turn(data: TurnData): Turn
@@ -150,9 +153,11 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
150
153
  let current: SessionData = { id: '', title: '', project: '', cwd: '', model: '', startedAt: '', lastAt: '', isRunning: true }
151
154
  let told: SessionColor = { session: '' }
152
155
 
156
+ const ownOnly = (method: string) => new Error(`${name}: ${method} works only in a mod's own session.`)
157
+
153
158
  const colored = ({ color: _color, ...data }: SessionData): SessionData => (told.session === data.id && told.color !== undefined ? { ...data, color: told.color } : data)
154
159
 
155
- const keyOf = (scope: Scope) => scope.session ?? everySession
160
+ const keyOf = (scope: Scope) => scope.session ?? current.id
156
161
 
157
162
  const subscribe = (key: string) => {
158
163
  if (queued.has(key)) return
@@ -160,11 +165,11 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
160
165
  void Promise.resolve().then(async () => {
161
166
  queued.delete(key)
162
167
  const heard = (from: Map<string, Set<Listening>>): Listened[] =>
163
- [...(from.get(key) ?? [])].map(({ event, matcher, options, scope }) => ({ event, matcher: matcher === undefined ? undefined : sentMatcher(matcher), ...(options.onFailure === 'refuse' ? { onFailure: 'refuse' as const, scope } : {}) }))
168
+ [...(from.get(key) ?? [])].map(({ event, matcher, options, scope }) => ({ event, matcher: matcher === undefined ? undefined : sentMatcher(matcher), scope, ...(options.onFailure === 'refuse' ? { onFailure: 'refuse' as const } : {}), ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }) }))
164
169
  const tracksTasks = [...(listening.get(key) ?? []), ...(deciding.get(key) ?? [])].some(({ scope }) => scope.task !== undefined || scope.isGoal === true)
165
170
  const subscriptions = [...heard(listening), ...(tracksTasks ? [{ event: TaskStart }] : [])]
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
- 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))
171
+ await call(conversationMethods.subscribe, { session: key, subscriptions }).catch((error: unknown) => report(`sessions:${key}`, `Hears nothing from session ${key}`, error))
172
+ await call(conversationMethods.watchBefore, { session: key, subscriptions: heard(deciding) }).catch((error: unknown) => report(`before:${key}`, `Changes nothing in session ${key}`, error))
168
173
  })
169
174
  }
170
175
 
@@ -239,12 +244,12 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
239
244
  return refusalOf(options, takes, error)
240
245
  })
241
246
 
242
- const decidersOf = (session: string, event: BeforeEvent, isInProject: boolean) => [...(deciding.get(session) ?? []), ...(isInProject ? (deciding.get(everySession) ?? []) : [])].filter((entry) => entry.event === event)
247
+ const decidersOf = (session: string, event: BeforeEvent) => [...(deciding.get(session) ?? [])].filter((entry) => entry.event === event)
243
248
 
244
249
  const decides = async (entry: Listening, session: string, change: SessionChange) => (entry.matcher === undefined || matches(payloadOf(change), entry.matcher)) && (await inScope(entry, session, change))
245
250
 
246
- const combined = async (session: string, event: BeforeEvent, change: SessionChange, isInProject: boolean, cancel: AbortSignal): Promise<Partial<Answers> | undefined> => {
247
- const askers = decidersOf(session, event, isInProject)
251
+ const combined = async (session: string, event: BeforeEvent, change: SessionChange, cancel: AbortSignal): Promise<Partial<Answers> | undefined> => {
252
+ const askers = decidersOf(session, event)
248
253
  .map((entry) => async (latest: SessionChange) => {
249
254
  if (!(await decides(entry, session, latest))) return undefined
250
255
  const payload = await payloadFor(session, latest)
@@ -257,7 +262,9 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
257
262
  const eventMethods = (scopeOf: () => Scope, hasBefore: boolean, ended?: string): OnMethods & Partial<BeforeMethods> => {
258
263
  const method = (into: Map<string, Set<Listening>>, named: string, event: SessionEvent) => (...args: unknown[]) => {
259
264
  if (ended !== undefined) throw new Error(`${name}: ${ended} has ended, so its ${named} never fires. Listen on its Session.`)
260
- return add(into, scopeOf(), event, named, args, subscribe)
265
+ const scope = scopeOf()
266
+ if (routeOn === undefined || keyOf(scope) !== current.id) throw ownOnly(named)
267
+ return add(into, scope, event, named, args, subscribe)
261
268
  }
262
269
  return Object.fromEntries([
263
270
  ...Object.entries(sessionEvents).map(([named, event]) => [`on${named}`, method(listening, `on${named}`, event)]),
@@ -378,49 +385,17 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
378
385
 
379
386
  const surfacesHere = async (): Promise<Surface[]> => [...(await claude.session.surfaces())]
380
387
 
381
- const sessionOf = (read: () => SessionData, owned?: Owned, isOwner = owned !== undefined) => {
388
+ const sessionOf = (read: () => SessionData, owned?: Owned, isOwner = owned !== undefined, hears = true) => {
382
389
  const id = () => read().id
383
390
  const isHere = () => owned === undefined && id() === current.id
384
391
  const scope = (): Scope => (owned === undefined ? { session: id(), isAgent: true } : { session: owned.session, task: owned.task, isAgent: true })
385
392
  const where = () => (owned === undefined ? { session: id() } : { session: owned.session, task: owned.task })
386
393
  const turnsOf = async (options: { readonly last?: number } = {}): Promise<Turn[]> => (await call<TurnData[]>(conversationMethods.turns, { ...where(), ...options })).map((turn) => turnOf(where(), turn))
387
394
  const contextsOf = async (): Promise<Context[]> => (await call<ContextData[]>(conversationMethods.contexts, where())).map((context) => contextOf(where(), context))
388
- const session = {
389
- get id() {
390
- return read().id
391
- },
392
- get title() {
393
- return read().title
394
- },
395
- get color() {
396
- return read().color
397
- },
398
- get project() {
399
- return read().project
400
- },
401
- get agentType() {
402
- return read().agentType
403
- },
404
- get model() {
405
- return read().model
406
- },
407
- get cwd() {
408
- return read().cwd
409
- },
410
- get isRunning() {
411
- return read().isRunning
412
- },
413
- get startedAt() {
414
- return read().startedAt
415
- },
416
- get lastAt() {
417
- return read().lastAt
418
- },
419
- get forkedFrom() {
420
- return read().forkedFrom
421
- },
395
+ const data = Object.defineProperties({}, Object.fromEntries(Object.keys(sessionFields).map((key) => [key, { get: () => read()[key as keyof SessionData], enumerable: true, configurable: true }]))) as Readonly<SessionData>
396
+ const session = Object.assign(data, {
422
397
  search: (text: string, matcher?: Matcher<Message>) => recordPart(scope()).search(text, matcher),
423
- ...eventMethods(scope, true),
398
+ ...(hears ? eventMethods(scope, true) : {}),
424
399
  goal: goalOf(where),
425
400
  context: async () => {
426
401
  const all = await contextsOf()
@@ -442,13 +417,21 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
442
417
  if (isHere() && message.as !== Session) return sendHere(message)
443
418
  await act(id(), 'send', message, owned)
444
419
  },
445
- }
420
+ async end() {
421
+ await act(id(), 'end', null, owned)
422
+ },
423
+ async visit(at?: string) {
424
+ await act(id(), 'visit', at ?? new Date().toISOString(), owned)
425
+ },
426
+ })
446
427
  if (isOwner) return session as unknown as Sessions['current']
447
428
  const started = async (starting: Promise<TaskData>): Promise<Task> => taskOf(id(), await starting.catch((error: unknown) => Promise.reject(new Error(`${name}: ${messageOf(error)}`))))
448
429
  return Object.assign(session, {
449
- startTask: (task: TaskStartArgs): Promise<Task> => started(task.isBackground === true ? act<TaskData>(id(), 'startBackgroundTask', task) : isHere() ? spawnTask(claude, task) : act<TaskData>(id(), 'startTask', task)),
450
- fork: (task: Pick<TaskStartArgs, 'prompt' | 'title'>): Promise<Task> => started(isHere() ? spawnTask(claude, task, current.id) : act<TaskData>(id(), 'fork', task)),
451
- clone: (task: Pick<TaskStartArgs, 'prompt' | 'title'>): Promise<Task> => started(act<TaskData>(id(), 'clone', task)),
430
+ startTask: (task: TaskStartArgs): Promise<Task> => started(task.isBackground === true || task.device !== undefined ? act<TaskData>(id(), 'startBackgroundTask', task) : isHere() ? spawnTask(claude, task) : act<TaskData>(id(), 'startTask', task)),
431
+ fork: (task: ForkArgs): Promise<Task> => started(isHere() && task.isBackground !== true && task.at === undefined ? spawnTask(claude, task, current.id) : act<TaskData>(id(), 'fork', task)),
432
+ delete: async () => {
433
+ await act(id(), 'delete', null)
434
+ },
452
435
  callTool: async (toolCall: ToolCallArgs): Promise<ToolResult> => (await withFiles(await act<ToolResult>(id(), 'callTool', toolCall))) as ToolResult,
453
436
  }) as unknown as Sessions['current']
454
437
  }
@@ -517,7 +500,7 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
517
500
  })
518
501
 
519
502
  const listenTo = (method: string, named: string) => {
520
- if (hookOn === undefined || routeOn === undefined) throw new Error(`${name}: ${method} works only in a mod's own session.`)
503
+ if (hookOn === undefined || routeOn === undefined) throw ownOnly(method)
521
504
  const isBefore = method.startsWith('before')
522
505
  if (named === 'PermissionCheck' || named === 'PermissionRequest') {
523
506
  const routes = permissionRoutes?.()
@@ -600,46 +583,43 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
600
583
  },
601
584
  caption: (toolCall: Message & { readonly type: typeof ToolCall }, text: string | undefined) => claude.ui.notice(toolCall.callId, text),
602
585
  })
603
- const every = eventMethods(() => ({}), false)
604
-
605
- const failedBefore = (session: string, event: BeforeEvent, change: SessionChange, isInProject: boolean, error: Error) => {
606
- 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)))
586
+ const failedBefore = (session: string, event: BeforeEvent, change: SessionChange, error: Error) => {
587
+ const asked = decidersOf(session, event).filter((entry) => isInScope(entry.scope, session, change, isUnderIn(parents.get(session))) && (entry.matcher === undefined || matches(payloadOf(change), entry.matcher)))
607
588
  return asked.map((entry) => refusalOf(entry.options, beforeAnswerKeys[event], error)).find((answer) => answer !== undefined)
608
589
  }
609
590
 
591
+ const listed = (data: SessionData) => {
592
+ if (data.id !== current.id) {
593
+ known.set(data.id, data)
594
+ return sessionOf(() => known.get(data.id) ?? data, undefined, false, false)
595
+ }
596
+ current = { ...current, title: current.title || data.title, device: data.device }
597
+ return currentSession
598
+ }
599
+
610
600
  return {
611
601
  sessions: {
612
602
  get current() {
613
603
  return currentSession
614
604
  },
615
- list: async (scope: SessionScope = {}) =>
616
- (await call<SessionData[]>(conversationMethods.sessions, scope)).map((data) => {
617
- if (data.id !== current.id) {
618
- known.set(data.id, data)
619
- return sessionOf(() => known.get(data.id) ?? data)
620
- }
621
- if (current.title === '') current = { ...current, title: data.title }
622
- return currentSession
623
- }),
605
+ list: async (scope: SessionScope = {}) => (await call<SessionData[]>(conversationMethods.sessions, scope)).map(listed),
606
+ get: async (id: string) => (id === current.id ? currentSession : listed(await call<SessionData>(conversationMethods.session, { session: id }))),
624
607
  search: (text, matcher, options = {}) => searched({ text, ...searchOptionsOf(options) }, matcher),
625
- ...every,
626
608
  },
627
- changed(session, change, isInProject, cancel) {
609
+ changed(session, change, cancel) {
628
610
  remember(session, change)
629
611
  let payload: Promise<unknown> | undefined
630
- for (const key of isInProject ? [session, everySession] : [session]) {
631
- for (const entry of listening.get(key) ?? []) {
632
- const { event, method, matcher, listener, options } = entry
633
- const deliver = () => {
634
- payload ??= payloadFor(session, change)
635
- void payload
636
- .then((heard) => invoke(method, options, cancel, (time) => listener(heard as never, time)))
637
- .catch((error: unknown) => report(`session:${method}`, `The ${method} listener failed`, error))
638
- }
639
- const isHeard = isHeardBy(event, matcher, change) && inScope(entry, session, change)
640
- if (isHeard === true) deliver()
641
- else if (isHeard !== false) void isHeard.then((isIn) => isIn && deliver())
612
+ for (const entry of listening.get(session) ?? []) {
613
+ const { event, method, matcher, listener, options } = entry
614
+ const deliver = () => {
615
+ payload ??= payloadFor(session, change)
616
+ void payload
617
+ .then((heard) => invoke(method, options, cancel, (time) => listener(heard as never, time)))
618
+ .catch((error: unknown) => report(`session:${method}`, `The ${method} listener failed`, error))
642
619
  }
620
+ const isHeard = isHeardBy(event, matcher, change) && inScope(entry, session, change)
621
+ if (isHeard === true) deliver()
622
+ else if (isHeard !== false) void isHeard.then((isIn) => isIn && deliver())
643
623
  }
644
624
  },
645
625
  answerBefore: combined,
@@ -650,7 +630,7 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
650
630
  follow(next) {
651
631
  const moved = next.id !== current.id && current.id !== ''
652
632
  const previous = current.id
653
- current = colored({ ...next, title: next.title || (next.id === current.id ? current.title : ''), isRunning: true, lastAt: new Date().toISOString() })
633
+ current = colored({ device: current.device, ...next, title: next.title || (next.id === current.id ? current.title : ''), isRunning: true, lastAt: new Date().toISOString() })
654
634
  if (!moved) return
655
635
  for (const into of [listening, deciding]) {
656
636
  const kept = into.get(previous)
@@ -245,7 +245,7 @@ export function createToaster(claude: Claude, name: string, version: () => strin
245
245
  const call = { isSettled: false }
246
246
  try {
247
247
  const logged = logFailure(failure).finally(() => void (call.isSettled = true))
248
- const answer = await (isShown ? logged : beforeDeadline(claude, { ms: failedCallMs }, failedMethod, logged))
248
+ const answer = await (isShown ? logged : beforeDeadline(claude.clock, { ms: failedCallMs }, failedMethod, () => logged))
249
249
  if (isObject(answer) && typeof answer['showsToast'] === 'boolean') return answer['showsToast']
250
250
  throw new Error(`cmod answered ${answer === undefined ? 'nothing' : JSON.stringify(answer)}, not { showsToast: true or false }`)
251
251
  } catch (error) {
package/src/runtime/ui.ts CHANGED
@@ -1,14 +1,15 @@
1
1
  import type { Args, ElementTable, Frozen, MarkdownProps, PaneOpenArgs, RenderElement, RenderSurface } from 'claude-code'
2
- import type { Mod, Turn } from '../mod.js'
2
+ import type { Mod, Surface, Turn } from '../mod.js'
3
3
  import { browserCommand, isObject } from '../records.js'
4
4
  import { TurnEnd, type Area, type Widget, type WidgetContext, type WidgetInit } from '../ui/areas.js'
5
5
  import { Box, drawKeyed, drawsFocusable, drawWith, elementData, Markdown, Text, type Handler } from '../ui/elements.js'
6
6
  import type { Block, MarkdownPiece, MarkdownReader } from '../ui/markdown.js'
7
- import { checkPane, checkPart, sizeKeys, type OpenOptions, type Page, type PageInit, type Pane, type PaneInit, type ScrollOptions, type ScrollTarget } from '../ui/panes.js'
7
+ import { checkPane, checkPart, sizeKeys, type OpenOptions, type Pane, type PaneInit, type ScrollOptions, type ScrollTarget, type View, type ViewInit } from '../ui/panes.js'
8
8
  import { componentOf, nameOf, type Kind, type Style, type StyledAt, type StyleInit } from '../ui/styles.js'
9
9
  import type { Subscription } from '../utils/subscription.js'
10
10
  import { messageOf } from '../utils/text.js'
11
11
  import type { Claude } from './claude.js'
12
+ import { styleInterface } from './interfaces.js'
12
13
  import { cmodPluginName } from './dependencies.js'
13
14
  import type { Router } from './router.js'
14
15
  import type { Failure } from './toaster.js'
@@ -24,17 +25,21 @@ export const partMethods = {
24
25
 
25
26
  export const stalePress = 'that button drew before the last redraw. Press the one it shows now.'
26
27
 
27
- export type PagePlace = 'sidebar' | 'settings'
28
+ export type ViewPlace = 'sidebar' | 'settings'
28
29
 
29
30
  export type WidgetDeclaration = { readonly id: string; readonly title: string; readonly areas: readonly Area[]; readonly place?: NonNullable<WidgetInit['place']> }
30
31
 
31
- export type PageDeclaration = { readonly id: string; readonly title: string; readonly place: PagePlace }
32
+ export type ViewDeclaration = { readonly id: string; readonly title: string; readonly place: ViewPlace }
32
33
 
33
- export type PartList = { readonly widgets: readonly WidgetDeclaration[]; readonly pages: readonly PageDeclaration[]; readonly stylesMarkdown?: true }
34
+ export type PageDeclaration = { readonly id: string; readonly title: string }
35
+
36
+ export type PartDeclaration = PageDeclaration & { readonly place?: ViewPlace }
37
+
38
+ export type PartList = { readonly widgets: readonly WidgetDeclaration[]; readonly pages: readonly PartDeclaration[]; readonly provides?: readonly string[] }
34
39
 
35
40
  export type PartDraw =
36
- | { readonly widget: string; readonly area: Area; readonly columns: number; readonly turn?: Turn }
37
- | { readonly page: string; readonly params: unknown; readonly columns: number; readonly isFocused: boolean }
41
+ | { readonly widget: string; readonly area: Area; readonly columns: number; readonly surface: Surface; readonly turn?: Turn }
42
+ | { readonly page: string; readonly params: unknown; readonly columns: number; readonly isFocused: boolean; readonly surface: Surface }
38
43
  | ({ readonly markdown: string } & StyledAt)
39
44
 
40
45
  export type BorrowedMarkdown = (mod: string, cached: string, input: { readonly markdown: string } & StyledAt, scope: string) => RenderElement | undefined
@@ -65,7 +70,7 @@ export type PartPress = { readonly draw: number; readonly handler: number; reado
65
70
 
66
71
  export type DrawnPart = { readonly draw: number; readonly tree: unknown }
67
72
 
68
- export type PageRequest =
73
+ export type PartRequest =
69
74
  | { readonly open: string; readonly params?: unknown; readonly focus?: true }
70
75
  | { readonly close: string }
71
76
  | { readonly scroll: string; readonly to: ScrollTarget; readonly block?: ScrollOptions['block'] }
@@ -74,9 +79,9 @@ export type PageRequest =
74
79
 
75
80
  export type SettingsTab = 'changelog' | 'permissions'
76
81
 
77
- export type PartsUpdate = { readonly parts?: PartList; readonly redraw?: true; readonly requests?: readonly PageRequest[]; readonly isAsked?: true; readonly isStart?: true }
82
+ export type PartsUpdate = { readonly parts?: PartList; readonly redraw?: true; readonly requests?: readonly PartRequest[]; readonly isAsked?: true; readonly isStart?: true }
78
83
 
79
- export type ShownPages = { readonly open: readonly { readonly id: string; readonly params: unknown }[]; readonly shown: string | null; readonly isFocused: boolean }
84
+ export type ShownParts = { readonly open: readonly { readonly id: string; readonly params: unknown }[]; readonly shown: string | null; readonly isFocused: boolean; readonly inApps?: readonly string[] }
80
85
 
81
86
 
82
87
  type PaneSize = Pick<PaneOpenArgs, 'columns' | 'rows'>
@@ -189,7 +194,7 @@ type MarkdownRender = {
189
194
 
190
195
  type AddedPane<State extends object> = { readonly init: PaneInit<State, unknown>; params: unknown }
191
196
 
192
- type AddedPage<State extends object> = { readonly init: PageInit<State, unknown>; readonly place: PagePlace; params: unknown }
197
+ type AddedPart<State extends object> = { readonly init: ViewInit<State, unknown>; readonly kind: 'view' | 'page'; readonly place: ViewPlace | undefined; params: unknown }
193
198
 
194
199
  export type UiOptions<State extends object> = {
195
200
  readonly name: string
@@ -200,11 +205,13 @@ export type UiOptions<State extends object> = {
200
205
  readonly mod: () => Mod<State>
201
206
  readonly borrowed: BorrowedMarkdown
202
207
  readonly nextDraw: () => number
208
+ readonly provided: () => readonly string[]
203
209
  }
204
210
 
205
211
  export type UiArea<State extends object> = {
206
212
  readonly panes: Mod<State>['panes']
207
- readonly sidebar: Mod<State>['sidebar']
213
+ readonly views: Mod<State>['views']
214
+ readonly pages: Mod<State>['pages']
208
215
  readonly settings: Mod<State>['settings']
209
216
  readonly widgets: Mod<State>['widgets']
210
217
  readonly styles: Mod<State>['styles']
@@ -213,6 +220,7 @@ export type UiArea<State extends object> = {
213
220
  answer(method: string, input: unknown, caller: string): Promise<{ readonly value: unknown }> | undefined
214
221
  markdownIn(table: ElementTable, at: StyledAt): ((props: MarkdownProps) => RenderElement) | undefined
215
222
  restyled(stylers: readonly string[]): void
223
+ relisted(): void
216
224
  started(): void
217
225
  changed(): void
218
226
  restorePanes(): Promise<void>
@@ -220,7 +228,7 @@ export type UiArea<State extends object> = {
220
228
 
221
229
  export const keptDrawInputs = 200
222
230
 
223
- export function createUi<State extends object>({ name, claude, router, report, announce, mod, borrowed, nextDraw }: UiOptions<State>): UiArea<State> {
231
+ export function createUi<State extends object>({ name, claude, router, report, announce, mod, borrowed, nextDraw, provided }: UiOptions<State>): UiArea<State> {
224
232
  const panes = new Map<string, AddedPane<State>>()
225
233
  const paneLogs = new Map<string, (failure: string) => void>()
226
234
  const openPanes = new Set<string>()
@@ -246,8 +254,8 @@ export function createUi<State extends object>({ name, claude, router, report, a
246
254
  let isResizeQueued = false
247
255
  const widgets = new Map<string, WidgetInit<State>>()
248
256
  const widgetAreas = new Map<string, Area>()
249
- const pages = new Map<string, AddedPage<State>>()
250
- let shownPages: ShownPages = { open: [], shown: null, isFocused: false }
257
+ const parts = new Map<string, AddedPart<State>>()
258
+ let shownParts: ShownParts = { open: [], shown: null, isFocused: false }
251
259
  const draws = new Map<number, { readonly id: string; readonly handlers: readonly Handler[] }>()
252
260
  const latestDraws = new Map<string, Map<string, SentDrawing>>()
253
261
  const failedDraws = new Set<string>()
@@ -259,11 +267,14 @@ export function createUi<State extends object>({ name, claude, router, report, a
259
267
  let collecting = 0
260
268
  let queued: PartsUpdate[] | undefined
261
269
 
262
- const partList = (): PartList => ({
263
- widgets: [...widgets.values()].map(({ id, title, areas: listed, place }) => ({ id, title, areas: listed, ...(place === undefined ? {} : { place }) })),
264
- pages: [...pages.values()].map(({ init: { id, title }, place }) => ({ id, title, place })),
265
- ...(markdownRenders.size > 0 ? { stylesMarkdown: true } : {}),
266
- })
270
+ const partList = (): PartList => {
271
+ const provides = [...provided(), ...(markdownRenders.size > 0 ? [styleInterface] : [])]
272
+ return {
273
+ widgets: [...widgets.values()].map(({ id, title, areas: listed, place }) => ({ id, title, areas: listed, ...(place === undefined ? {} : { place }) })),
274
+ pages: [...parts.values()].map(({ init: { id, title }, place }) => ({ id, title, ...(place === undefined ? {} : { place }) })),
275
+ ...(provides.length === 0 ? {} : { provides }),
276
+ }
277
+ }
267
278
 
268
279
  const hear = (listed: unknown, isRestyled: boolean) => {
269
280
  if (!Array.isArray(listed)) return
@@ -276,7 +287,7 @@ export function createUi<State extends object>({ name, claude, router, report, a
276
287
 
277
288
  const treeOf = (render: () => RenderElement | undefined, handlers: Handler[]) => {
278
289
  const drawn = render()
279
- return drawn === undefined ? null : elementData(drawn, handlers)
290
+ return drawn === undefined ? null : elementData(drawn, (run) => handlers.push(run) - 1)
280
291
  }
281
292
 
282
293
  const isAnyDrawingChanged = () => {
@@ -317,7 +328,7 @@ export function createUi<State extends object>({ name, claude, router, report, a
317
328
  if (isObject(answer) && name !== cmodPluginName) hear(answer['stylers'], false)
318
329
  },
319
330
  (error: unknown) => {
320
- claude.ui.warn('parts:tell', `${name}: the cmod plugin did not hear about its pages and widgets: ${messageOf(error)}`)
331
+ claude.ui.warn('parts:tell', `${name}: the cmod plugin did not hear about its widgets, views, and pages: ${messageOf(error)}`)
321
332
  },
322
333
  )
323
334
  }
@@ -506,8 +517,7 @@ export function createUi<State extends object>({ name, claude, router, report, a
506
517
  })
507
518
 
508
519
  const addPane = <Params>(init: PaneInit<State, Params>): Pane<Params> => {
509
- checkPane(name, init)
510
- if (panes.has(init.id)) throw new Error(`${name}: the pane "${init.id}" is already added. Give each pane its own id.`)
520
+ checkPane(name, init, panes.has(init.id) ? 'pane' : undefined)
511
521
  const added: AddedPane<State> = { init, params: undefined }
512
522
  panes.set(init.id, added)
513
523
  paneLogs.set(init.id, logOnce(`${init.title} pane`))
@@ -559,58 +569,63 @@ export function createUi<State extends object>({ name, claude, router, report, a
559
569
  return pane
560
570
  }
561
571
 
562
- const pageEntry = (id: string) => shownPages.open.find((each) => each.id === id)
572
+ const openEntry = (id: string) => shownParts.open.find((each) => each.id === id)
573
+
574
+ const takenBy = (id: string) => (widgets.has(id) ? 'widget' : parts.get(id)?.kind)
563
575
 
564
- const addPage = <Params>(place: PagePlace, init: PageInit<State, Params>): Page<Params> => {
565
- checkPart(name, 'page', init.id, init.title)
566
- if (pages.has(init.id)) throw new Error(`${name}: the page "${init.id}" is already added. Give each page its own id.`)
567
- const added: AddedPage<State> = { init, place, params: undefined }
568
- pages.set(init.id, added)
569
- announce(place === 'settings' ? `the ${init.title} page in Settings` : `the ${init.title} page in the Sidebar`)
576
+ const addPart = <Params>(kind: AddedPart<State>['kind'], init: ViewInit<State, Params>, place?: ViewPlace): View<Params> => {
577
+ checkPart(name, kind, init.id, init.title, takenBy(init.id))
578
+ const added: AddedPart<State> = { init, kind, place, params: undefined }
579
+ const key = `${kind}:${init.id}`
580
+ let requested: readonly [since: ShownParts, isOpen: boolean] | undefined
581
+ parts.set(init.id, added)
582
+ announce(place === 'settings' ? `the ${init.title} view in Settings` : `the ${init.title} ${kind}`)
570
583
  void send({ parts: partList() })
571
- const page: Page<Params> = {
584
+ const part: View<Params> = {
572
585
  id: init.id,
573
586
  get isOpen() {
574
- return place === 'settings' ? shownPages.shown === init.id : pageEntry(init.id) !== undefined
587
+ if (requested?.[0] === shownParts) return requested[1]
588
+ return place === 'settings' ? shownParts.shown === init.id : openEntry(init.id) !== undefined
575
589
  },
576
590
  get isShown() {
577
- return shownPages.shown === init.id
591
+ return [shownParts.shown, ...(shownParts.inApps ?? [])].includes(init.id)
578
592
  },
579
593
  get isFocused() {
580
- return shownPages.shown === init.id && shownPages.isFocused
594
+ return shownParts.shown === init.id && shownParts.isFocused
581
595
  },
582
596
  get params() {
583
- return (pageEntry(init.id)?.params ?? added.params) as Params | undefined
597
+ return (openEntry(init.id)?.params ?? added.params) as Params | undefined
584
598
  },
585
599
  async open(...[options]: [OpenOptions<Params>?]) {
586
600
  if (options !== undefined && 'params' in options) added.params = options.params
601
+ requested = [shownParts, true]
587
602
  await send({ requests: [{ open: init.id, ...(added.params === undefined ? {} : { params: added.params }), ...(options?.focus === true ? { focus: true } : {}) }] })
588
603
  },
589
- toggle: (options) => (page.isOpen ? page.close() : (page.open as (options?: OpenOptions<Params>) => Promise<void>)(options as OpenOptions<Params>)),
604
+ toggle: (options) => (part.isOpen ? part.close() : (part.open as (options?: OpenOptions<Params>) => Promise<void>)(options as OpenOptions<Params>)),
590
605
  close: async () => {
606
+ requested = [shownParts, false]
591
607
  await send({ requests: [{ close: init.id }] })
592
608
  },
593
609
  scrollTo: async (target, options) => {
594
610
  await send({ requests: [{ scroll: init.id, to: target, ...(options?.block === undefined ? {} : { block: options.block }) }] })
595
611
  },
596
- focus: async (key) => {
597
- const latest = [...(latestDraws.get(`page:${init.id}`)?.values() ?? [])].at(-1)
598
- if (latest === undefined || !drawsFocusable(treeOf(latest.render, []), key)) throw new Error(`${name}: the ${init.title} page draws no Button, Input, or Select with the key "${key}".`)
599
- await send({ requests: [{ focus: init.id, key }] })
612
+ focus: async (focused) => {
613
+ const latest = [...(latestDraws.get(key)?.values() ?? [])].at(-1)
614
+ if (latest === undefined || !drawsFocusable(treeOf(latest.render, []), focused)) throw new Error(`${name}: the ${init.title} ${kind} draws no Button, Input, or Select with the key "${focused}".`)
615
+ await send({ requests: [{ focus: init.id, key: focused }] })
600
616
  },
601
617
  remove() {
602
- if (pages.get(init.id) !== added) return
603
- pages.delete(init.id)
604
- forgetDraws(`page:${init.id}`)
618
+ if (parts.get(init.id) !== added) return
619
+ parts.delete(init.id)
620
+ forgetDraws(key)
605
621
  void send({ parts: partList(), requests: [{ close: init.id }] })
606
622
  },
607
623
  }
608
- return page
624
+ return part
609
625
  }
610
626
 
611
627
  const addWidget = (init: WidgetInit<State>): Widget => {
612
- checkPart(name, 'widget', init.id, init.title)
613
- if (widgets.has(init.id)) throw new Error(`${name}: the widget "${init.id}" is already added. Give each widget its own id.`)
628
+ checkPart(name, 'widget', init.id, init.title, takenBy(init.id))
614
629
  widgets.set(init.id, init)
615
630
  announce(`the ${init.title} widget`)
616
631
  void send({ parts: partList() })
@@ -707,16 +722,18 @@ export function createUi<State extends object>({ name, claude, router, report, a
707
722
  const draw = (input: PartDraw): DrawnPart | null => {
708
723
  if ('markdown' in input) return drawPart('markdown', 'markdown style', input, () => markdownDrawing(input.markdown, { surface: input.surface, columns: input.columns }))
709
724
  if ('page' in input) {
710
- const added = pages.get(input.page)
711
- if (added === undefined) throw new Error(`${name} has no ${input.page} page.`)
712
- const title = `${added.init.title} page`
713
- return drawPart(`page:${input.page}`, title, input, () => added.init.render(mod(), { params: input.params, isFocused: input.isFocused, columns: input.columns }), (error) => Text({ color: 'error', children: `The ${title} could not draw: ${messageOf(error)}` }))
725
+ const { page, ...props } = input
726
+ const added = parts.get(page)
727
+ if (added === undefined) throw new Error(`${name} has no view or page ${page}.`)
728
+ const title = `${added.init.title} ${added.kind}`
729
+ return drawPart(`${added.kind}:${page}`, title, input, () => added.init.render(mod(), props), (error) => Text({ color: 'error', children: `The ${title} could not draw: ${messageOf(error)}` }))
714
730
  }
715
- const widget = widgets.get(input.widget)
716
- if (widget === undefined || !widget.areas.includes(input.area)) return null
717
- widgetAreas.set(widget.id, input.area)
718
- const context = (input.area === TurnEnd && input.turn !== undefined ? { area: input.area, columns: input.columns, turn: input.turn } : { area: input.area, columns: input.columns }) as WidgetContext
719
- return drawPart(`widget:${widget.id}`, `${widget.title} widget`, input, () => widget.render(mod(), context))
731
+ const { widget: id, turn, ...given } = input
732
+ const widget = widgets.get(id)
733
+ if (widget === undefined || !widget.areas.includes(given.area)) return null
734
+ widgetAreas.set(id, given.area)
735
+ const context = (given.area === TurnEnd && turn !== undefined ? { ...given, turn } : given) as WidgetContext
736
+ return drawPart(`widget:${id}`, `${widget.title} widget`, input, () => widget.render(mod(), context))
720
737
  }
721
738
 
722
739
  const press = async ({ draw: drawn, handler, args }: PartPress, caller: string): Promise<PartsUpdate | null> => {
@@ -738,9 +755,10 @@ export function createUi<State extends object>({ name, claude, router, report, a
738
755
 
739
756
  return {
740
757
  panes: { add: addPane },
741
- sidebar: { add: (init) => addPage('sidebar', init) },
758
+ views: { add: (init) => addPart('view', init, 'sidebar') },
759
+ pages: { add: (init) => addPart('page', init) },
742
760
  settings: {
743
- add: (init) => addPage('settings', init),
761
+ add: (init) => addPart('view', init, 'settings'),
744
762
  open: async () => {
745
763
  await send({ requests: [{ settings: true }] })
746
764
  },
@@ -761,7 +779,7 @@ export function createUi<State extends object>({ name, claude, router, report, a
761
779
  if (method === partMethods.draw) return Promise.resolve().then(() => ({ value: draw(input as PartDraw) }))
762
780
  if (method === partMethods.press) return press(input as PartPress, caller).then((value) => ({ value }))
763
781
  if (method === partMethods.shown) {
764
- shownPages = input as ShownPages
782
+ shownParts = input as ShownParts
765
783
  return Promise.resolve({ value: null })
766
784
  }
767
785
  if (method === partMethods.stylers) {
@@ -772,13 +790,16 @@ export function createUi<State extends object>({ name, claude, router, report, a
772
790
  },
773
791
  markdownIn,
774
792
  restyled: (stylers) => hear(stylers, true),
775
- started() {
793
+ relisted() {
794
+ void send({ parts: partList() })
795
+ },
796
+ started() {
776
797
  const held = merged(beforeStart ?? [])
777
798
  beforeStart = undefined
778
799
  void send({ ...held, parts: partList(), isStart: true })
779
800
  },
780
801
  changed() {
781
- if (widgets.size > 0 || pages.size > 0) void send({ redraw: true })
802
+ if (widgets.size > 0 || parts.size > 0) void send({ redraw: true })
782
803
  if (panes.size === 0 && styles.size === 0) return
783
804
  claude.ui.invalidate('ui.render')
784
805
  if (isResizeQueued) return