@cmodjs/core 7.0.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 +104 -70
  2. package/docs/dependencies.md +153 -23
  3. package/docs/index.md +54 -10
  4. package/docs/install-steps.md +20 -17
  5. package/docs/jobs.md +42 -17
  6. package/docs/mod.md +37 -30
  7. package/docs/options.md +2 -2
  8. package/docs/session.md +39 -29
  9. package/docs/testing.md +84 -23
  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 +2 -3
  14. package/jobs/program.d.ts.map +1 -1
  15. package/jobs/program.js +72 -23
  16. package/mod.d.ts +23 -8
  17. package/mod.d.ts.map +1 -1
  18. package/mod.js +3 -3
  19. package/package.json +1 -1
  20. package/records.d.ts +5 -3
  21. package/records.d.ts.map +1 -1
  22. package/records.js +18 -9
  23. package/register.d.ts.map +1 -1
  24. package/register.js +7 -15
  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 +9 -2
  37. package/runtime/conversations.d.ts.map +1 -1
  38. package/runtime/conversations.js +244 -185
  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 +4 -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 +108 -42
  48. package/runtime/interfaces.d.ts.map +1 -1
  49. package/runtime/interfaces.js +639 -143
  50. package/runtime/lifecycle.d.ts +3 -5
  51. package/runtime/lifecycle.d.ts.map +1 -1
  52. package/runtime/lifecycle.js +74 -63
  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 +2 -0
  62. package/runtime/rpc.d.ts.map +1 -1
  63. package/runtime/rpc.js +30 -5
  64. package/runtime/sessions.d.ts +3 -3
  65. package/runtime/sessions.d.ts.map +1 -1
  66. package/runtime/sessions.js +38 -73
  67. package/runtime/toaster.js +1 -1
  68. package/runtime/ui.d.ts +19 -8
  69. package/runtime/ui.d.ts.map +1 -1
  70. package/runtime/ui.js +51 -47
  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 +6 -2
  78. package/session/conversation.d.ts.map +1 -1
  79. package/session/session.d.ts +22 -6
  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 +63 -23
  85. package/src/mod.ts +22 -11
  86. package/src/records.ts +21 -9
  87. package/src/register.ts +7 -15
  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 +247 -182
  93. package/src/runtime/deadline.ts +13 -6
  94. package/src/runtime/engine.ts +4 -4
  95. package/src/runtime/installer.ts +13 -12
  96. package/src/runtime/interfaces.ts +753 -172
  97. package/src/runtime/lifecycle.ts +93 -67
  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 +32 -5
  102. package/src/runtime/sessions.ts +39 -73
  103. package/src/runtime/toaster.ts +1 -1
  104. package/src/runtime/ui.ts +67 -55
  105. package/src/runtime/web.ts +10 -39
  106. package/src/runtime/widgets.ts +20 -18
  107. package/src/session/conversation.ts +7 -2
  108. package/src/session/session.ts +14 -6
  109. package/src/testing/fake-claude.ts +10 -4
  110. package/src/testing/fake-serve.ts +106 -6
  111. package/src/testing/fake-sessions.ts +6 -5
  112. package/src/testing.ts +149 -67
  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 +2 -0
  117. package/testing/fake-claude.d.ts.map +1 -1
  118. package/testing/fake-claude.js +10 -4
  119. package/testing/fake-serve.d.ts +32 -2
  120. package/testing/fake-serve.d.ts.map +1 -1
  121. package/testing/fake-serve.js +81 -6
  122. package/testing/fake-sessions.d.ts.map +1 -1
  123. package/testing/fake-sessions.js +6 -5
  124. package/testing.d.ts +21 -4
  125. package/testing.d.ts.map +1 -1
  126. package/testing.js +131 -55
  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 -34
  136. package/runtime/pages.d.ts.map +0 -1
  137. package/runtime/pages.js +0 -157
  138. package/src/runtime/pages.ts +0 -198
@@ -46,6 +46,8 @@ export type SessionColor = { readonly session: string; readonly color?: string }
46
46
 
47
47
  const resetColors: readonly string[] = ['default', 'reset', 'none', 'gray', 'grey']
48
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
+
49
51
  export function pickedColor(args: string): string | undefined {
50
52
  const picked = args.trim().toLowerCase()
51
53
  return resetColors.includes(picked) ? undefined : picked
@@ -61,9 +63,9 @@ export type Scope = { readonly session?: string; readonly context?: number; read
61
63
 
62
64
  export type SessionsClient = {
63
65
  readonly sessions: Sessions
64
- changed(session: string, change: SessionChange, isInProject: boolean, cancel: AbortSignal): void
65
- answerBefore(session: string, event: BeforeEvent, change: SessionChange, isInProject: boolean, cancel: AbortSignal): Promise<unknown>
66
- 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
67
69
  raise(method: string, payload: Readonly<Record<string, unknown>>, cancel: AbortSignal): Promise<unknown>
68
70
  listen(method: string, args: readonly unknown[]): Subscription
69
71
  turn(data: TurnData): Turn
@@ -151,9 +153,11 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
151
153
  let current: SessionData = { id: '', title: '', project: '', cwd: '', model: '', startedAt: '', lastAt: '', isRunning: true }
152
154
  let told: SessionColor = { session: '' }
153
155
 
156
+ const ownOnly = (method: string) => new Error(`${name}: ${method} works only in a mod's own session.`)
157
+
154
158
  const colored = ({ color: _color, ...data }: SessionData): SessionData => (told.session === data.id && told.color !== undefined ? { ...data, color: told.color } : data)
155
159
 
156
- const keyOf = (scope: Scope) => scope.session ?? everySession
160
+ const keyOf = (scope: Scope) => scope.session ?? current.id
157
161
 
158
162
  const subscribe = (key: string) => {
159
163
  if (queued.has(key)) return
@@ -164,8 +168,8 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
164
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 }) }))
165
169
  const tracksTasks = [...(listening.get(key) ?? []), ...(deciding.get(key) ?? [])].some(({ scope }) => scope.task !== undefined || scope.isGoal === true)
166
170
  const subscriptions = [...heard(listening), ...(tracksTasks ? [{ event: TaskStart }] : [])]
167
- await call(conversationMethods.subscribe, { session: key, subscriptions }).catch((error: unknown) => report(`sessions:${key}`, `Hears nothing from ${key === everySession ? 'the other sessions' : `session ${key}`}`, error))
168
- 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))
169
173
  })
170
174
  }
171
175
 
@@ -240,12 +244,12 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
240
244
  return refusalOf(options, takes, error)
241
245
  })
242
246
 
243
- 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)
244
248
 
245
249
  const decides = async (entry: Listening, session: string, change: SessionChange) => (entry.matcher === undefined || matches(payloadOf(change), entry.matcher)) && (await inScope(entry, session, change))
246
250
 
247
- const combined = async (session: string, event: BeforeEvent, change: SessionChange, isInProject: boolean, cancel: AbortSignal): Promise<Partial<Answers> | undefined> => {
248
- 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)
249
253
  .map((entry) => async (latest: SessionChange) => {
250
254
  if (!(await decides(entry, session, latest))) return undefined
251
255
  const payload = await payloadFor(session, latest)
@@ -258,7 +262,9 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
258
262
  const eventMethods = (scopeOf: () => Scope, hasBefore: boolean, ended?: string): OnMethods & Partial<BeforeMethods> => {
259
263
  const method = (into: Map<string, Set<Listening>>, named: string, event: SessionEvent) => (...args: unknown[]) => {
260
264
  if (ended !== undefined) throw new Error(`${name}: ${ended} has ended, so its ${named} never fires. Listen on its Session.`)
261
- 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)
262
268
  }
263
269
  return Object.fromEntries([
264
270
  ...Object.entries(sessionEvents).map(([named, event]) => [`on${named}`, method(listening, `on${named}`, event)]),
@@ -379,52 +385,17 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
379
385
 
380
386
  const surfacesHere = async (): Promise<Surface[]> => [...(await claude.session.surfaces())]
381
387
 
382
- const sessionOf = (read: () => SessionData, owned?: Owned, isOwner = owned !== undefined) => {
388
+ const sessionOf = (read: () => SessionData, owned?: Owned, isOwner = owned !== undefined, hears = true) => {
383
389
  const id = () => read().id
384
390
  const isHere = () => owned === undefined && id() === current.id
385
391
  const scope = (): Scope => (owned === undefined ? { session: id(), isAgent: true } : { session: owned.session, task: owned.task, isAgent: true })
386
392
  const where = () => (owned === undefined ? { session: id() } : { session: owned.session, task: owned.task })
387
393
  const turnsOf = async (options: { readonly last?: number } = {}): Promise<Turn[]> => (await call<TurnData[]>(conversationMethods.turns, { ...where(), ...options })).map((turn) => turnOf(where(), turn))
388
394
  const contextsOf = async (): Promise<Context[]> => (await call<ContextData[]>(conversationMethods.contexts, where())).map((context) => contextOf(where(), context))
389
- const session = {
390
- get id() {
391
- return read().id
392
- },
393
- get title() {
394
- return read().title
395
- },
396
- get color() {
397
- return read().color
398
- },
399
- get project() {
400
- return read().project
401
- },
402
- get agentType() {
403
- return read().agentType
404
- },
405
- get model() {
406
- return read().model
407
- },
408
- get cwd() {
409
- return read().cwd
410
- },
411
- get isRunning() {
412
- return read().isRunning
413
- },
414
- get startedAt() {
415
- return read().startedAt
416
- },
417
- get lastAt() {
418
- return read().lastAt
419
- },
420
- get forkedFrom() {
421
- return read().forkedFrom
422
- },
423
- get visitedAt() {
424
- return read().visitedAt
425
- },
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, {
426
397
  search: (text: string, matcher?: Matcher<Message>) => recordPart(scope()).search(text, matcher),
427
- ...eventMethods(scope, true),
398
+ ...(hears ? eventMethods(scope, true) : {}),
428
399
  goal: goalOf(where),
429
400
  context: async () => {
430
401
  const all = await contextsOf()
@@ -452,11 +423,11 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
452
423
  async visit(at?: string) {
453
424
  await act(id(), 'visit', at ?? new Date().toISOString(), owned)
454
425
  },
455
- }
426
+ })
456
427
  if (isOwner) return session as unknown as Sessions['current']
457
428
  const started = async (starting: Promise<TaskData>): Promise<Task> => taskOf(id(), await starting.catch((error: unknown) => Promise.reject(new Error(`${name}: ${messageOf(error)}`))))
458
429
  return Object.assign(session, {
459
- startTask: (task: TaskStartArgs): Promise<Task> => started(task.isBackground === true || task.machine !== undefined ? act<TaskData>(id(), 'startBackgroundTask', task) : isHere() ? spawnTask(claude, task) : act<TaskData>(id(), 'startTask', 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)),
460
431
  fork: (task: ForkArgs): Promise<Task> => started(isHere() && task.isBackground !== true && task.at === undefined ? spawnTask(claude, task, current.id) : act<TaskData>(id(), 'fork', task)),
461
432
  delete: async () => {
462
433
  await act(id(), 'delete', null)
@@ -529,7 +500,7 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
529
500
  })
530
501
 
531
502
  const listenTo = (method: string, named: string) => {
532
- 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)
533
504
  const isBefore = method.startsWith('before')
534
505
  if (named === 'PermissionCheck' || named === 'PermissionRequest') {
535
506
  const routes = permissionRoutes?.()
@@ -612,19 +583,17 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
612
583
  },
613
584
  caption: (toolCall: Message & { readonly type: typeof ToolCall }, text: string | undefined) => claude.ui.notice(toolCall.callId, text),
614
585
  })
615
- const every = eventMethods(() => ({}), false)
616
-
617
- const failedBefore = (session: string, event: BeforeEvent, change: SessionChange, isInProject: boolean, error: Error) => {
618
- 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)))
619
588
  return asked.map((entry) => refusalOf(entry.options, beforeAnswerKeys[event], error)).find((answer) => answer !== undefined)
620
589
  }
621
590
 
622
591
  const listed = (data: SessionData) => {
623
592
  if (data.id !== current.id) {
624
593
  known.set(data.id, data)
625
- return sessionOf(() => known.get(data.id) ?? data)
594
+ return sessionOf(() => known.get(data.id) ?? data, undefined, false, false)
626
595
  }
627
- if (current.title === '') current = { ...current, title: data.title }
596
+ current = { ...current, title: current.title || data.title, device: data.device }
628
597
  return currentSession
629
598
  }
630
599
 
@@ -636,24 +605,21 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
636
605
  list: async (scope: SessionScope = {}) => (await call<SessionData[]>(conversationMethods.sessions, scope)).map(listed),
637
606
  get: async (id: string) => (id === current.id ? currentSession : listed(await call<SessionData>(conversationMethods.session, { session: id }))),
638
607
  search: (text, matcher, options = {}) => searched({ text, ...searchOptionsOf(options) }, matcher),
639
- ...every,
640
608
  },
641
- changed(session, change, isInProject, cancel) {
609
+ changed(session, change, cancel) {
642
610
  remember(session, change)
643
611
  let payload: Promise<unknown> | undefined
644
- for (const key of isInProject ? [session, everySession] : [session]) {
645
- for (const entry of listening.get(key) ?? []) {
646
- const { event, method, matcher, listener, options } = entry
647
- const deliver = () => {
648
- payload ??= payloadFor(session, change)
649
- void payload
650
- .then((heard) => invoke(method, options, cancel, (time) => listener(heard as never, time)))
651
- .catch((error: unknown) => report(`session:${method}`, `The ${method} listener failed`, error))
652
- }
653
- const isHeard = isHeardBy(event, matcher, change) && inScope(entry, session, change)
654
- if (isHeard === true) deliver()
655
- 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))
656
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())
657
623
  }
658
624
  },
659
625
  answerBefore: combined,
@@ -664,7 +630,7 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
664
630
  follow(next) {
665
631
  const moved = next.id !== current.id && current.id !== ''
666
632
  const previous = current.id
667
- 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() })
668
634
  if (!moved) return
669
635
  for (const into of [listening, deciding]) {
670
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,10 +1,10 @@
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'
@@ -25,17 +25,21 @@ export const partMethods = {
25
25
 
26
26
  export const stalePress = 'that button drew before the last redraw. Press the one it shows now.'
27
27
 
28
- export type PagePlace = 'sidebar' | 'settings'
28
+ export type ViewPlace = 'sidebar' | 'settings'
29
29
 
30
30
  export type WidgetDeclaration = { readonly id: string; readonly title: string; readonly areas: readonly Area[]; readonly place?: NonNullable<WidgetInit['place']> }
31
31
 
32
- 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 }
33
33
 
34
- export type PartList = { readonly widgets: readonly WidgetDeclaration[]; readonly pages: readonly PageDeclaration[]; readonly provides?: readonly string[] }
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[] }
35
39
 
36
40
  export type PartDraw =
37
- | { readonly widget: string; readonly area: Area; readonly columns: number; readonly turn?: Turn }
38
- | { 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 }
39
43
  | ({ readonly markdown: string } & StyledAt)
40
44
 
41
45
  export type BorrowedMarkdown = (mod: string, cached: string, input: { readonly markdown: string } & StyledAt, scope: string) => RenderElement | undefined
@@ -66,7 +70,7 @@ export type PartPress = { readonly draw: number; readonly handler: number; reado
66
70
 
67
71
  export type DrawnPart = { readonly draw: number; readonly tree: unknown }
68
72
 
69
- export type PageRequest =
73
+ export type PartRequest =
70
74
  | { readonly open: string; readonly params?: unknown; readonly focus?: true }
71
75
  | { readonly close: string }
72
76
  | { readonly scroll: string; readonly to: ScrollTarget; readonly block?: ScrollOptions['block'] }
@@ -75,9 +79,9 @@ export type PageRequest =
75
79
 
76
80
  export type SettingsTab = 'changelog' | 'permissions'
77
81
 
78
- 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 }
79
83
 
80
- 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[] }
81
85
 
82
86
 
83
87
  type PaneSize = Pick<PaneOpenArgs, 'columns' | 'rows'>
@@ -190,7 +194,7 @@ type MarkdownRender = {
190
194
 
191
195
  type AddedPane<State extends object> = { readonly init: PaneInit<State, unknown>; params: unknown }
192
196
 
193
- 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 }
194
198
 
195
199
  export type UiOptions<State extends object> = {
196
200
  readonly name: string
@@ -206,7 +210,8 @@ export type UiOptions<State extends object> = {
206
210
 
207
211
  export type UiArea<State extends object> = {
208
212
  readonly panes: Mod<State>['panes']
209
- readonly sidebar: Mod<State>['sidebar']
213
+ readonly views: Mod<State>['views']
214
+ readonly pages: Mod<State>['pages']
210
215
  readonly settings: Mod<State>['settings']
211
216
  readonly widgets: Mod<State>['widgets']
212
217
  readonly styles: Mod<State>['styles']
@@ -249,8 +254,8 @@ export function createUi<State extends object>({ name, claude, router, report, a
249
254
  let isResizeQueued = false
250
255
  const widgets = new Map<string, WidgetInit<State>>()
251
256
  const widgetAreas = new Map<string, Area>()
252
- const pages = new Map<string, AddedPage<State>>()
253
- 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 }
254
259
  const draws = new Map<number, { readonly id: string; readonly handlers: readonly Handler[] }>()
255
260
  const latestDraws = new Map<string, Map<string, SentDrawing>>()
256
261
  const failedDraws = new Set<string>()
@@ -266,7 +271,7 @@ export function createUi<State extends object>({ name, claude, router, report, a
266
271
  const provides = [...provided(), ...(markdownRenders.size > 0 ? [styleInterface] : [])]
267
272
  return {
268
273
  widgets: [...widgets.values()].map(({ id, title, areas: listed, place }) => ({ id, title, areas: listed, ...(place === undefined ? {} : { place }) })),
269
- pages: [...pages.values()].map(({ init: { id, title }, place }) => ({ id, title, place })),
274
+ pages: [...parts.values()].map(({ init: { id, title }, place }) => ({ id, title, ...(place === undefined ? {} : { place }) })),
270
275
  ...(provides.length === 0 ? {} : { provides }),
271
276
  }
272
277
  }
@@ -282,7 +287,7 @@ export function createUi<State extends object>({ name, claude, router, report, a
282
287
 
283
288
  const treeOf = (render: () => RenderElement | undefined, handlers: Handler[]) => {
284
289
  const drawn = render()
285
- return drawn === undefined ? null : elementData(drawn, handlers)
290
+ return drawn === undefined ? null : elementData(drawn, (run) => handlers.push(run) - 1)
286
291
  }
287
292
 
288
293
  const isAnyDrawingChanged = () => {
@@ -323,7 +328,7 @@ export function createUi<State extends object>({ name, claude, router, report, a
323
328
  if (isObject(answer) && name !== cmodPluginName) hear(answer['stylers'], false)
324
329
  },
325
330
  (error: unknown) => {
326
- 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)}`)
327
332
  },
328
333
  )
329
334
  }
@@ -512,8 +517,7 @@ export function createUi<State extends object>({ name, claude, router, report, a
512
517
  })
513
518
 
514
519
  const addPane = <Params>(init: PaneInit<State, Params>): Pane<Params> => {
515
- checkPane(name, init)
516
- 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)
517
521
  const added: AddedPane<State> = { init, params: undefined }
518
522
  panes.set(init.id, added)
519
523
  paneLogs.set(init.id, logOnce(`${init.title} pane`))
@@ -565,58 +569,63 @@ export function createUi<State extends object>({ name, claude, router, report, a
565
569
  return pane
566
570
  }
567
571
 
568
- 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)
569
575
 
570
- const addPage = <Params>(place: PagePlace, init: PageInit<State, Params>): Page<Params> => {
571
- checkPart(name, 'page', init.id, init.title)
572
- if (pages.has(init.id)) throw new Error(`${name}: the page "${init.id}" is already added. Give each page its own id.`)
573
- const added: AddedPage<State> = { init, place, params: undefined }
574
- pages.set(init.id, added)
575
- 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}`)
576
583
  void send({ parts: partList() })
577
- const page: Page<Params> = {
584
+ const part: View<Params> = {
578
585
  id: init.id,
579
586
  get isOpen() {
580
- 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
581
589
  },
582
590
  get isShown() {
583
- return shownPages.shown === init.id
591
+ return [shownParts.shown, ...(shownParts.inApps ?? [])].includes(init.id)
584
592
  },
585
593
  get isFocused() {
586
- return shownPages.shown === init.id && shownPages.isFocused
594
+ return shownParts.shown === init.id && shownParts.isFocused
587
595
  },
588
596
  get params() {
589
- return (pageEntry(init.id)?.params ?? added.params) as Params | undefined
597
+ return (openEntry(init.id)?.params ?? added.params) as Params | undefined
590
598
  },
591
599
  async open(...[options]: [OpenOptions<Params>?]) {
592
600
  if (options !== undefined && 'params' in options) added.params = options.params
601
+ requested = [shownParts, true]
593
602
  await send({ requests: [{ open: init.id, ...(added.params === undefined ? {} : { params: added.params }), ...(options?.focus === true ? { focus: true } : {}) }] })
594
603
  },
595
- 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>)),
596
605
  close: async () => {
606
+ requested = [shownParts, false]
597
607
  await send({ requests: [{ close: init.id }] })
598
608
  },
599
609
  scrollTo: async (target, options) => {
600
610
  await send({ requests: [{ scroll: init.id, to: target, ...(options?.block === undefined ? {} : { block: options.block }) }] })
601
611
  },
602
- focus: async (key) => {
603
- const latest = [...(latestDraws.get(`page:${init.id}`)?.values() ?? [])].at(-1)
604
- 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}".`)
605
- 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 }] })
606
616
  },
607
617
  remove() {
608
- if (pages.get(init.id) !== added) return
609
- pages.delete(init.id)
610
- forgetDraws(`page:${init.id}`)
618
+ if (parts.get(init.id) !== added) return
619
+ parts.delete(init.id)
620
+ forgetDraws(key)
611
621
  void send({ parts: partList(), requests: [{ close: init.id }] })
612
622
  },
613
623
  }
614
- return page
624
+ return part
615
625
  }
616
626
 
617
627
  const addWidget = (init: WidgetInit<State>): Widget => {
618
- checkPart(name, 'widget', init.id, init.title)
619
- 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))
620
629
  widgets.set(init.id, init)
621
630
  announce(`the ${init.title} widget`)
622
631
  void send({ parts: partList() })
@@ -713,16 +722,18 @@ export function createUi<State extends object>({ name, claude, router, report, a
713
722
  const draw = (input: PartDraw): DrawnPart | null => {
714
723
  if ('markdown' in input) return drawPart('markdown', 'markdown style', input, () => markdownDrawing(input.markdown, { surface: input.surface, columns: input.columns }))
715
724
  if ('page' in input) {
716
- const added = pages.get(input.page)
717
- if (added === undefined) throw new Error(`${name} has no ${input.page} page.`)
718
- const title = `${added.init.title} page`
719
- 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)}` }))
720
730
  }
721
- const widget = widgets.get(input.widget)
722
- if (widget === undefined || !widget.areas.includes(input.area)) return null
723
- widgetAreas.set(widget.id, input.area)
724
- 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
725
- 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))
726
737
  }
727
738
 
728
739
  const press = async ({ draw: drawn, handler, args }: PartPress, caller: string): Promise<PartsUpdate | null> => {
@@ -744,9 +755,10 @@ export function createUi<State extends object>({ name, claude, router, report, a
744
755
 
745
756
  return {
746
757
  panes: { add: addPane },
747
- sidebar: { add: (init) => addPage('sidebar', init) },
758
+ views: { add: (init) => addPart('view', init, 'sidebar') },
759
+ pages: { add: (init) => addPart('page', init) },
748
760
  settings: {
749
- add: (init) => addPage('settings', init),
761
+ add: (init) => addPart('view', init, 'settings'),
750
762
  open: async () => {
751
763
  await send({ requests: [{ settings: true }] })
752
764
  },
@@ -767,7 +779,7 @@ export function createUi<State extends object>({ name, claude, router, report, a
767
779
  if (method === partMethods.draw) return Promise.resolve().then(() => ({ value: draw(input as PartDraw) }))
768
780
  if (method === partMethods.press) return press(input as PartPress, caller).then((value) => ({ value }))
769
781
  if (method === partMethods.shown) {
770
- shownPages = input as ShownPages
782
+ shownParts = input as ShownParts
771
783
  return Promise.resolve({ value: null })
772
784
  }
773
785
  if (method === partMethods.stylers) {
@@ -787,7 +799,7 @@ export function createUi<State extends object>({ name, claude, router, report, a
787
799
  void send({ ...held, parts: partList(), isStart: true })
788
800
  },
789
801
  changed() {
790
- if (widgets.size > 0 || pages.size > 0) void send({ redraw: true })
802
+ if (widgets.size > 0 || parts.size > 0) void send({ redraw: true })
791
803
  if (panes.size === 0 && styles.size === 0) return
792
804
  claude.ui.invalidate('ui.render')
793
805
  if (isResizeQueued) return
@@ -42,44 +42,10 @@ const markdownOptions = { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown
42
42
 
43
43
  type Markdown = { readonly link: number | undefined; readonly pressable: readonly string[] | undefined }
44
44
 
45
- export type SidebarTab = { readonly key: string; readonly label: string; readonly isClosable: boolean }
46
-
47
- export type ClosedPage = { readonly mod: string; readonly page: string; readonly title: string }
48
-
49
- export type SessionWait = { readonly kind: 'permission'; readonly tool: string; readonly input: Readonly<Record<string, unknown>> } | { readonly kind: 'question'; readonly question: string }
50
-
51
- export type TurnOutcome = { readonly reason: 'answered' | 'stopped' | 'failed'; readonly at: string; readonly failure?: string }
52
-
53
- export type SessionAbout = {
54
- readonly tabs: readonly SidebarTab[]
55
- readonly pages: readonly ClosedPage[]
56
- readonly isWorking?: boolean
57
- readonly waiting?: SessionWait
58
- readonly lastTurn?: TurnOutcome
59
- readonly contextPercent?: number
60
- }
61
-
62
- export type WebView = { readonly id: string; readonly tab: string; readonly columns: number }
63
-
64
- export type WebInput = { readonly draw: number; readonly handler: number; readonly key: string; readonly kind: 'press' | 'change' | 'submit' | 'select' | 'link'; readonly value?: string; readonly href?: string }
65
-
66
- export type WebAction =
67
- | ({ readonly type: 'press'; readonly view: string } & WebInput)
68
- | { readonly type: 'open'; readonly mod: string; readonly page: string }
69
- | { readonly type: 'close'; readonly tab: string }
70
- | { readonly type: 'prompt'; readonly text: string }
71
- | { readonly type: 'stop' }
72
-
73
45
  export type ElementData = { readonly $cmodElement: string; readonly props: Readonly<Record<string, unknown>> }
74
46
 
75
47
  export type HandlerData = { readonly $cmodHandler: number }
76
48
 
77
- export type SessionEvents = { readonly views: readonly WebView[]; readonly actions: readonly WebAction[] }
78
-
79
- export type WebDrawing = { readonly view: string; readonly draw: number; readonly tree: unknown }
80
-
81
- export type SessionPost = { readonly about?: SessionAbout; readonly drawings?: readonly WebDrawing[] }
82
-
83
49
  export function htmlOf(tree: unknown): string {
84
50
  const drawing: Drawing = { rules: [], groups: new Map(), scopes: 0, scope: undefined }
85
51
  const body = nodeHtml(tree, drawing)
@@ -162,7 +128,7 @@ const elements: Readonly<Record<string, (props: Props, drawing: Drawing) => stri
162
128
  },
163
129
  Image: (props) => {
164
130
  const source = props['source'] as Props | undefined
165
- const alt = typeof props['alt'] === 'string' ? props['alt'] : ''
131
+ const alt = accessibleName(props)
166
132
  const size = attribute('style', `width:${across(numberOr(props['columns'], 1))};height:${down(numberOr(props['rows'], 1))}`)
167
133
  if (typeof source?.['png'] === 'string' && base64.test(source['png'])) return `<img class="image" alt="${escaped(alt)}" src="data:image/png;base64,${source['png']}"${size}>`
168
134
  const [width, height] = [source?.['width'], source?.['height']]
@@ -172,9 +138,14 @@ const elements: Readonly<Record<string, (props: Props, drawing: Drawing) => stri
172
138
  Svg: (props) => {
173
139
  const source = typeof props['source'] === 'string' ? props['source'] : ''
174
140
  const size = [typeof props['width'] === 'number' ? `width:${props['width']}px` : '', typeof props['height'] === 'number' ? `height:${props['height']}px` : ''].filter((each) => each !== '').join(';')
175
- return `<img class="svg" alt="${escaped(typeof props['alt'] === 'string' ? props['alt'] : '')}" src="data:image/svg+xml,${encodeURIComponent(source)}"${attribute('style', size === '' ? undefined : size)}>`
141
+ return `<img class="svg" alt="${escaped(accessibleName(props))}" src="data:image/svg+xml,${encodeURIComponent(source)}"${attribute('style', size === '' ? undefined : size)}>`
176
142
  },
177
- Raster: (props) => rasterHtml(typeof props['cells'] === 'string' ? props['cells'] : '', numberOr(props['columns'], 1)),
143
+ Raster: (props) => rasterHtml(typeof props['cells'] === 'string' ? props['cells'] : '', numberOr(props['columns'], 1), accessibleName(props)),
144
+ }
145
+
146
+ function accessibleName(props: Props): string {
147
+ const name = props['label'] ?? props['alt']
148
+ return typeof name === 'string' ? name : ''
178
149
  }
179
150
 
180
151
  function escaped(text: string): string {
@@ -359,7 +330,7 @@ function codeHtml(source: string, startLine: number | undefined, isDiff: boolean
359
330
  return `<pre class="${isCut ? 'code cut' : 'code'}">${rows.join('\n')}</pre>`
360
331
  }
361
332
 
362
- function rasterHtml(cells: string, columns: number): string {
333
+ function rasterHtml(cells: string, columns: number, name: string): string {
363
334
  if (cells.length % 4 !== 0 || !base64.test(cells)) return '<span class="gap">The browser draws no Raster whose cells are not base64.</span>'
364
335
  const bytes = Uint8Array.from(atob(cells), (character) => character.charCodeAt(0))
365
336
  const words = new DataView(bytes.buffer)
@@ -377,7 +348,7 @@ function rasterHtml(cells: string, columns: number): string {
377
348
  }
378
349
  }
379
350
  if (row !== '') rows.push(row)
380
- return `<pre class="raster">${rows.join('\n')}</pre>`
351
+ return `<pre class="raster"${name === '' ? '' : ` role="img"${attribute('aria-label', name)}`}>${rows.join('\n')}</pre>`
381
352
  }
382
353
 
383
354
  function linkHtml(href: string, inner: string, markdown: Markdown): string {