@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
@@ -1,9 +1,16 @@
1
- import type { RenderElement } from 'claude-code'
2
- import { elementOf } from '../ui/elements.js'
3
- import { messageOf } from '../utils/text.js'
1
+ import type { RenderComponent, RenderElement } from 'claude-code'
2
+ import type { Surface } from '../mod.js'
3
+ import { isObject } from '../records.js'
4
+ import type { TurnData } from '../session/conversation.js'
5
+ import { Dashboard, TurnEnd, type Area } from '../ui/areas.js'
6
+ import { elementData, elementOf, Text, type Handler } from '../ui/elements.js'
7
+ import { listed, messageOf } from '../utils/text.js'
4
8
  import type { Claude } from './claude.js'
5
- import { isStillInstalling } from './dependencies.js'
6
- import { partMethods, type DrawnPart, type PartPress } from './ui.js'
9
+ import { cmodPluginName, isNotInstalled, isStillInstalling } from './dependencies.js'
10
+ import { styleInterface, type Implementation } from './interfaces.js'
11
+ import type { Router } from './router.js'
12
+ import { partMethods, stalePress, type DrawnPart, type PageDeclaration, type PartPress, type PartRequest, type PartsUpdate, type ShownParts, type ViewDeclaration, type WidgetDeclaration } from './ui.js'
13
+ import { areaComponents, widgetsOf, type Widgets } from './widgets.js'
7
14
 
8
15
  export type DrawnParts = {
9
16
  fill(mod: string, cached: string, input: Readonly<Record<string, unknown>>, name: string): Promise<void> | undefined
@@ -74,3 +81,355 @@ export function drawnParts({ claude, report, press }: { readonly claude: Claude;
74
81
  },
75
82
  }
76
83
  }
84
+
85
+ const askedWaitMs = 1000
86
+
87
+ const keptUiDraws = 2
88
+
89
+ export type ModParts = { readonly mod: string; readonly widgets: readonly WidgetDeclaration[]; readonly views: readonly ViewDeclaration[]; readonly pages: readonly PageDeclaration[] }
90
+
91
+ export type PartApply = (mod: string, requests: readonly PartRequest[]) => Promise<void>
92
+
93
+ export type PartOpen = (mod: string, id: string, isOpen: boolean) => Promise<void>
94
+
95
+ type UiPart = { readonly mod: string; readonly id: string }
96
+
97
+ type UiHandler = UiPart & { readonly component: RenderComponent; readonly run: Handler }
98
+
99
+ export type UiEvent = { readonly Change: { readonly part: 'widgets' | 'views' | 'pages' }; readonly Redraw: UiPart; readonly Open: UiPart; readonly Close: UiPart }
100
+
101
+ export type UiTell = <Event extends keyof UiEvent>(event: Event, payload: UiEvent[Event]) => void
102
+
103
+ export type UiPress = { readonly surface: Surface; readonly key?: string; readonly value?: string; readonly kind?: 'change' | 'submit'; readonly link?: { readonly href: string } }
104
+
105
+ export type Parts = {
106
+ declared(): readonly ModParts[]
107
+ providers(name: string): readonly string[]
108
+ stylers(): readonly string[]
109
+ element(mod: string, id: string, params: unknown, columns: number, isFocused: boolean, surface: Surface): RenderElement | undefined
110
+ press(mod: string, press: PartPress): Promise<void>
111
+ update(mod: string, update: PartsUpdate): boolean
112
+ tell(mod: string, shown: ShownParts): void
113
+ apply(listener: PartApply): void
114
+ onOpen(listener: PartOpen): void
115
+ onStart(listener: (mod: string) => void): void
116
+ turnClosed(turn: TurnData): void
117
+ readonly ui: Implementation
118
+ }
119
+
120
+ export function providedBy(listing: unknown): readonly string[] {
121
+ if (!isObject(listing)) return []
122
+ const named = Array.isArray(listing['provides']) ? listing['provides'].filter((each): each is string => typeof each === 'string') : []
123
+ return listing['stylesMarkdown'] === true && !named.includes(styleInterface) ? [...named, styleInterface] : named
124
+ }
125
+
126
+ const listedIn = (input: unknown, field: string) => (isObject(input) && Array.isArray(input[field]) ? (input[field] as unknown[]).filter(isObject) : [])
127
+
128
+ const isNamed = (each: Readonly<Record<string, unknown>>): each is Readonly<Record<string, unknown>> & { readonly id: string; readonly title: string } => typeof each['id'] === 'string' && typeof each['title'] === 'string'
129
+
130
+ export function viewsOf(input: unknown): ViewDeclaration[] {
131
+ return listedIn(input, 'pages').flatMap((each) => (isNamed(each) && (each['place'] === 'sidebar' || each['place'] === 'settings') ? [{ id: each.id, title: each.title, place: each['place'] }] : []))
132
+ }
133
+
134
+ export function pagesOf(input: unknown): PageDeclaration[] {
135
+ return listedIn(input, 'pages').flatMap((each) => (isNamed(each) && each['place'] === undefined ? [{ id: each.id, title: each.title }] : []))
136
+ }
137
+
138
+ function partsOf(mod: string, listing: unknown): ModParts {
139
+ return { mod, widgets: widgetsOf(listing), views: viewsOf(listing), pages: pagesOf(listing) }
140
+ }
141
+
142
+ export function serveParts({
143
+ claude,
144
+ router,
145
+ report,
146
+ tellRefusedPress,
147
+ widgets,
148
+ parts,
149
+ tellStylers,
150
+ tellUi,
151
+ }: {
152
+ readonly claude: Claude
153
+ readonly router: Router
154
+ readonly report: (id: string, message: string, error: unknown) => void
155
+ readonly tellRefusedPress: (mod: string, error: unknown) => void
156
+ readonly widgets: Pick<Widgets, 'update'>
157
+ readonly parts: DrawnParts
158
+ readonly tellStylers: (stylers: readonly string[]) => void
159
+ readonly tellUi: UiTell
160
+ }): Parts {
161
+ const declared = new Map<string, ModParts>()
162
+ const provided = new Map<string, Set<string>>()
163
+ const providersOf = (name: string) => [...(provided.get(name) ?? [])]
164
+ const shownBy = new Map<string, ShownParts>()
165
+ let inApps = new Map<string, readonly string[]>()
166
+ const tellShown = (mod: string) => {
167
+ const shown: ShownParts = { ...(shownBy.get(mod) ?? { open: [], shown: null, isFocused: false }), inApps: inApps.get(mod) ?? [] }
168
+ void claude.cmod.call({ to: mod, method: partMethods.shown, input: plain(shown) }).catch((error: unknown) => claude.ui.warn(`pages:shown:${mod}`, `cmod: ${mod} did not hear which of its views and pages show: ${messageOf(error)}`))
169
+ }
170
+ const asking = new Map<string, Promise<void>>()
171
+ const pressing = new Set<Promise<void>>()
172
+ let waiting: { readonly mod: string; readonly requests: readonly PartRequest[] }[] = []
173
+ let inputDepth = 0
174
+ let applyTo: PartApply = async () => undefined
175
+ let openIn: PartOpen = async () => undefined
176
+ let started: (mod: string) => void = () => undefined
177
+
178
+ const run = (mod: string, requests: readonly PartRequest[]) =>
179
+ applyTo(mod, requests).catch((error: unknown) => report(`pages:${mod}`, `Could not show the view or page ${mod} asked for`, error))
180
+
181
+ const takeWaiting = async () => {
182
+ const taken = waiting
183
+ waiting = []
184
+ for (const { mod, requests } of taken) await run(mod, requests)
185
+ }
186
+
187
+ const settle = async (earlier: ReadonlySet<Promise<void>>) => {
188
+ const own = () => [...pressing].filter((pending) => !earlier.has(pending))
189
+ for (let pending = own(); pending.length > 0; pending = own()) await Promise.allSettled(pending)
190
+ await takeWaiting()
191
+ }
192
+
193
+ const wrapped = async <Answer>(next: () => Promise<Answer>): Promise<Answer> => {
194
+ inputDepth += 1
195
+ const earlier = new Set(pressing)
196
+ try {
197
+ const answer = await next()
198
+ await settle(earlier)
199
+ return answer
200
+ } finally {
201
+ inputDepth -= 1
202
+ }
203
+ }
204
+
205
+ router.add('command.run', (e, next) => wrapped(async () => (waiting.length > 0 ? {} : next(e))))
206
+ router.add('ui.press', (e, next) => wrapped(() => next(e)))
207
+
208
+ const declare = (mod: string, listing: unknown) => {
209
+ const before = declared.get(mod)
210
+ const after = partsOf(mod, listing)
211
+ declared.set(mod, after)
212
+ for (const part of ['widgets', 'views', 'pages'] as const) if (JSON.stringify(before?.[part] ?? []) !== JSON.stringify(after[part])) tellUi('Change', { part })
213
+ }
214
+
215
+ const ask = (mod: string) => {
216
+ const pending =
217
+ asking.get(mod) ??
218
+ claude.cmod
219
+ .call({ to: mod, method: partMethods.list, input: null })
220
+ .then(
221
+ (listing) => declare(mod, listing),
222
+ (error: unknown) => {
223
+ if (!isNotInstalled(mod, error) && !isStillInstalling(mod, error)) claude.ui.warn(`pages:list:${mod}`, `cmod: ${mod} did not list its views and pages: ${messageOf(error)}`)
224
+ },
225
+ )
226
+ .finally(() => asking.delete(mod))
227
+ asking.set(mod, pending)
228
+ return pending
229
+ }
230
+
231
+ const provide = (mod: string, names: readonly string[]) => {
232
+ const wasStyler = provided.get(styleInterface)?.has(mod) === true
233
+ for (const [name, mods] of provided) if (!names.includes(name)) mods.delete(mod)
234
+ for (const name of names) provided.set(name, (provided.get(name) ?? new Set<string>()).add(mod))
235
+ if (wasStyler || names.includes(styleInterface)) restyle(mod)
236
+ }
237
+
238
+ const restyle = (mod: string) => {
239
+ parts.forget(mod)
240
+ const listed = providersOf(styleInterface)
241
+ tellStylers(listed)
242
+ for (const told of declared.keys()) {
243
+ if (told === cmodPluginName) continue
244
+ void claude.cmod.call({ to: told, method: partMethods.stylers, input: listed }).catch((error: unknown) => {
245
+ if (!isStillInstalling(told, error)) claude.ui.warn(`pages:stylers:${told}`, `cmod: ${told} did not hear which mods style markdown: ${messageOf(error)}`)
246
+ })
247
+ }
248
+ }
249
+
250
+ const idsOf = (mod: string) => {
251
+ const known = declared.get(mod)
252
+ return [...(known?.widgets ?? []), ...(known?.views ?? []), ...(known?.pages ?? [])].map(({ id }) => id)
253
+ }
254
+
255
+ const isShownByApps = (mod: string, id: string) => {
256
+ const known = declared.get(mod)
257
+ return known?.views.some((each) => each.id === id && each.place === 'sidebar') === true || known?.pages.some((each) => each.id === id) === true
258
+ }
259
+
260
+ const tellRequested = (mod: string, requests: readonly PartRequest[]) => {
261
+ for (const request of requests) {
262
+ if ('open' in request && isShownByApps(mod, request.open)) tellUi('Open', { mod, id: request.open })
263
+ if ('close' in request && isShownByApps(mod, request.close)) tellUi('Close', { mod, id: request.close })
264
+ }
265
+ }
266
+
267
+ const update = (mod: string, { parts: listing, redraw, requests, isAsked, isStart }: PartsUpdate) => {
268
+ if (isStart === true) started(mod)
269
+ if (listing !== undefined) declare(mod, listing)
270
+ if (listing !== undefined) provide(mod, providedBy(listing))
271
+ const isRedrawn = redraw === true || requests?.some((request) => 'open' in request) === true
272
+ if (listing !== undefined || isRedrawn) widgets.update(mod, { ...(listing === undefined ? {} : { parts: listing }), ...(isRedrawn ? { redraw: true } : {}) })
273
+ if (redraw === true) for (const id of idsOf(mod)) tellUi('Redraw', { mod, id })
274
+ if (requests === undefined || requests.length === 0) return false
275
+ tellRequested(mod, requests)
276
+ if (isAsked !== true) return (void run(mod, requests), false)
277
+ waiting.push({ mod, requests })
278
+ if (inputDepth > 0) return true
279
+ claude.clock.after(askedWaitMs, () => void takeWaiting())
280
+ return false
281
+ }
282
+
283
+ const press = (mod: string, input: PartPress) => {
284
+ const pending = claude.cmod
285
+ .call({ to: mod, method: partMethods.press, input })
286
+ .then(
287
+ (answer) => void update(mod, (isObject(answer) ? answer : {}) as PartsUpdate),
288
+ (error: unknown) => {
289
+ parts.forget(mod)
290
+ claude.ui.invalidate('ui.render')
291
+ tellRefusedPress(mod, error)
292
+ },
293
+ )
294
+ .finally(() => pressing.delete(pending))
295
+ pressing.add(pending)
296
+ if (inputDepth === 0) void pending.then(takeWaiting)
297
+ return pending
298
+ }
299
+
300
+ const lastDrawn = new Map<string, { readonly params: string; readonly cached: string }>()
301
+
302
+ const plain = <Data,>(data: Data): Data => JSON.parse(JSON.stringify(data)) as Data
303
+
304
+ const nameOf = (mod: string, id: string) => `The ${id} ${declared.get(mod)?.pages.some((each) => each.id === id) === true ? 'page' : 'view'} of ${mod}`
305
+
306
+ const element = (mod: string, id: string, params: unknown, columns: number, isFocused: boolean, surface: Surface) => {
307
+ if (!declared.has(mod)) void ask(mod)
308
+ const given = JSON.stringify(params ?? null)
309
+ const cached = `${id}\u0000${given}\u0000${columns}\u0000${isFocused}\u0000${surface}`
310
+ const name = nameOf(mod, id)
311
+ const keyPrefix = `${mod}/${id}:`
312
+ void parts.fill(mod, cached, { page: id, params: plain(params ?? null), columns, isFocused, surface }, name)?.then(() => claude.ui.invalidate('ui.render'))
313
+ const failure = parts.failure(mod, cached)
314
+ const drawnAt = (key: string) => parts.element(mod, key, keyPrefix, name, `page:${mod}/${id}`)
315
+ const last = lastDrawn.get(keyPrefix)
316
+ const drawn = drawnAt(cached)
317
+ if (drawn !== undefined) lastDrawn.set(keyPrefix, { params: given, cached })
318
+ return drawn ?? (last?.params === given ? drawnAt(last.cached) : undefined) ?? (failure === undefined ? undefined : Text({ color: 'error', children: `${name} could not draw: ${failure}` }))
319
+ }
320
+
321
+ const pressable = new Map<number, UiHandler>()
322
+ const uiDraws = new Map<string, readonly (readonly number[])[]>()
323
+ let lastHandler = 0
324
+
325
+ const numbered = (part: UiPart, component: RenderComponent, drawn: RenderElement) => {
326
+ const numbers: number[] = []
327
+ const tree = elementData(drawn, (run) => {
328
+ lastHandler += 1
329
+ pressable.set(lastHandler, { ...part, component, run })
330
+ numbers.push(lastHandler)
331
+ return lastHandler
332
+ })
333
+ const key = `${part.mod}/${part.id}`
334
+ const earlier = uiDraws.get(key) ?? []
335
+ const kept = [...earlier, numbers].slice(-keptUiDraws)
336
+ for (const draw of earlier) if (!kept.includes(draw)) for (const handler of draw) pressable.delete(handler)
337
+ uiDraws.set(key, kept)
338
+ return tree
339
+ }
340
+
341
+ const viewOrPage = ({ mod, id }: UiPart) => {
342
+ const known = declared.get(mod)
343
+ return known?.views.find((each) => each.id === id) ?? known?.pages.find((each) => each.id === id)
344
+ }
345
+
346
+ let closedTurn: TurnData | undefined
347
+
348
+ const drawnPart = async (part: UiPart, columns: number, surface: Surface, shownIn: Area | undefined): Promise<{ readonly cached: string; readonly name: string; readonly keyPrefix: string; readonly component: RenderComponent } | undefined> => {
349
+ const { mod, id } = part
350
+ if (viewOrPage(part) !== undefined) {
351
+ const params = shownBy.get(mod)?.open.find((each) => each.id === id)?.params ?? null
352
+ const cached = `${id}\u0000${JSON.stringify(params)}\u0000${columns}\u0000true\u0000${surface}`
353
+ const name = nameOf(mod, id)
354
+ await parts.fill(mod, cached, { page: id, params: plain(params), columns, isFocused: true, surface }, name)
355
+ return { cached, name, keyPrefix: `${mod}/${id}:`, component: 'Pane' }
356
+ }
357
+ const widget = declared.get(mod)?.widgets.find((each) => each.id === id)
358
+ if (widget === undefined) throw new Error(`${mod} has no widget, view, or page ${id} in this session.`)
359
+ const name = `The ${widget.title} widget of ${mod}`
360
+ if (shownIn !== undefined && !widget.areas.includes(shownIn)) throw new Error(`${name} draws in ${listed(widget.areas)}, not ${shownIn}.`)
361
+ const area = shownIn ?? (widget.areas.includes(Dashboard) ? Dashboard : (widget.areas[0] ?? Dashboard))
362
+ const turn = area === TurnEnd ? closedTurn : undefined
363
+ if (area === TurnEnd && turn === undefined) return undefined
364
+ const key = `${mod}/${id}`
365
+ const cached = `${key}\u0000${area}\u0000${columns}\u0000${surface}\u0000${turn?.prompt.id ?? ''}`
366
+ await parts.fill(mod, cached, { widget: id, area, columns, surface, ...(turn === undefined ? {} : { turn }) }, name)
367
+ return { cached, name, keyPrefix: `${key}:`, component: areaComponents[area] }
368
+ }
369
+
370
+ const ui: Implementation = {
371
+ widgets: () => [...declared.values()].flatMap(({ mod, widgets: listed }) => listed.map(({ id, areas }) => ({ mod, id, areas }))),
372
+ views: () => [...declared.values()].flatMap(({ mod, views }) => views.flatMap(({ id, title, place }) => (place === 'sidebar' ? [{ mod, id, title }] : []))),
373
+ pages: () => [...declared.values()].flatMap(({ mod, pages }) => pages.map(({ id, title }) => ({ mod, id, title }))),
374
+ async draw(_session: string, part: UiPart, { columns, surface, area }: { readonly columns: number; readonly surface: Surface; readonly area?: Area }) {
375
+ const drawing = await drawnPart(part, columns, surface, area)
376
+ if (drawing === undefined) return null
377
+ const { cached, name, keyPrefix, component } = drawing
378
+ const failure = parts.failure(part.mod, cached)
379
+ if (failure !== undefined) throw new Error(`${name} could not draw: ${failure}`)
380
+ const drawn = parts.element(part.mod, cached, keyPrefix, name, `ui:${part.mod}/${part.id}`)
381
+ return drawn === undefined ? null : numbered(part, component, drawn)
382
+ },
383
+ async press(_session: string, handler: number, { surface, key, value, kind, link }: UiPress) {
384
+ const known = pressable.get(handler)
385
+ if (known === undefined) throw new Error(`cmod: ${stalePress}`)
386
+ const pressed = { plugin: known.mod, element: key ?? '', component: known.component, requestId: known.id, surface, ...(kind === undefined ? {} : { kind }), ...(value === undefined ? {} : { value }), ...(link === undefined ? {} : { link }) }
387
+ await known.run(...(link !== undefined ? [link, pressed] : value !== undefined ? [value, pressed] : [pressed]))
388
+ return null
389
+ },
390
+ async open(_session: string, part: UiPart) {
391
+ if (viewOrPage(part) === undefined) throw new Error(`${part.mod} has no view or page ${part.id} in this session.`)
392
+ await openIn(part.mod, part.id, true)
393
+ return null
394
+ },
395
+ async close(_session: string, part: UiPart) {
396
+ await openIn(part.mod, part.id, false)
397
+ return null
398
+ },
399
+ shown(_session: string, listed: readonly UiPart[]) {
400
+ const next = new Map<string, string[]>()
401
+ for (const { mod, id } of listed) next.set(mod, [...(next.get(mod) ?? []), id])
402
+ const changed = [...new Set([...inApps.keys(), ...next.keys()])].filter((mod) => JSON.stringify(inApps.get(mod) ?? []) !== JSON.stringify(next.get(mod) ?? []))
403
+ inApps = next
404
+ for (const mod of changed) tellShown(mod)
405
+ return null
406
+ },
407
+ }
408
+
409
+ return {
410
+ declared: () => [...declared.values()],
411
+ providers: providersOf,
412
+ stylers: () => providersOf(styleInterface),
413
+ element,
414
+ press,
415
+ update,
416
+ tell(mod, shown) {
417
+ shownBy.set(mod, shown)
418
+ tellShown(mod)
419
+ },
420
+ apply(listener) {
421
+ applyTo = listener
422
+ },
423
+ onOpen(listener) {
424
+ openIn = listener
425
+ },
426
+ onStart(listener) {
427
+ started = listener
428
+ },
429
+ turnClosed(turn) {
430
+ closedTurn = turn
431
+ for (const { mod, widgets: listed } of declared.values()) for (const { id, areas } of listed) if (areas.includes(TurnEnd)) tellUi('Redraw', { mod, id })
432
+ },
433
+ ui,
434
+ }
435
+ }
@@ -46,8 +46,12 @@ export async function isHeld(claude: Claude, lock: string, staleMs: number): Pro
46
46
  return touched.some((at) => now - at < staleMs)
47
47
  }
48
48
 
49
+ export async function cmodStore(claude: Claude): Promise<string> {
50
+ return storeFolder({ HOME: await claude.env.home(), XDG_DATA_HOME: await claude.env.dataHome() })
51
+ }
52
+
49
53
  export async function newestCmodVersion(claude: Claude): Promise<string | undefined> {
50
- const store = storeFolder({ HOME: await claude.env.home(), XDG_DATA_HOME: await claude.env.dataHome() })
54
+ const store = await cmodStore(claude)
51
55
  return readCmodVersion(
52
56
  {
53
57
  list: async (folder) => (await claude.fs.list(folder).catch(ifMissing([]))).map((entry) => entry.name),
@@ -117,8 +121,7 @@ export function locatingPrograms(claude: Claude): Programs {
117
121
  downloading = current
118
122
  },
119
123
  async refresh() {
120
- const [home, dataHome] = await Promise.all([claude.env.home(), claude.env.dataHome()])
121
- const programs = `${storeFolder({ HOME: home, XDG_DATA_HOME: dataHome })}/programs`
124
+ const programs = `${await cmodStore(claude)}/programs`
122
125
  names = new Set((await claude.fs.list(programs).catch(ifMissing([]))).map((entry) => entry.name))
123
126
  folder = programs
124
127
  },
@@ -160,6 +160,7 @@ export type RpcHttpAnswer = { readonly status: number; readonly json?: unknown }
160
160
 
161
161
  export type RpcRoutes = {
162
162
  route(request: RpcHttpRequest): Promise<RpcHttpAnswer> | undefined
163
+ channel(send: (message: RpcMessage) => void): RpcConnection
163
164
  connections(): RpcConnection[]
164
165
  close(): void
165
166
  }
@@ -238,8 +239,8 @@ export function rpcRoutes({
238
239
  if (each.poll !== answer) return
239
240
  each.poll = undefined
240
241
  timers.clearTimeout(timer)
241
- each.seenAt = now()
242
242
  resolve([])
243
+ drop(each.connection.id, 'the client left its poll')
243
244
  })
244
245
  })
245
246
 
@@ -266,17 +267,42 @@ export function rpcRoutes({
266
267
  }
267
268
  }
268
269
 
270
+ const channels = new Map<string, RpcConnection>()
271
+
272
+ const channel = (send: (message: RpcMessage) => void): RpcConnection => {
273
+ const id = crypto.randomUUID()
274
+ const peer = createPeer({ send, handle: (method, params, signal) => handler(method, params, signal) })
275
+ const connection: RpcConnection = {
276
+ ...peer,
277
+ id,
278
+ close(reason) {
279
+ if (!channels.delete(id)) return
280
+ peer.close(reason)
281
+ onClose?.(connection)
282
+ },
283
+ }
284
+ const handler = handle(connection)
285
+ channels.set(id, connection)
286
+ return connection
287
+ }
288
+
269
289
  return {
270
290
  route: (request) => (request.path.startsWith(rpcPath) ? route(request) : undefined),
271
- connections: () => [...held.values()].map((each) => each.connection),
291
+ channel,
292
+ connections: () => [...[...held.values()].map((each) => each.connection), ...channels.values()],
272
293
  close() {
273
294
  for (const id of held.keys()) drop(id, 'the server stopped')
295
+ for (const each of channels.values()) each.close(new Error('the server stopped'))
274
296
  },
275
297
  }
276
298
  }
277
299
 
278
300
  export class RpcUnreached extends Error {}
279
301
 
302
+ export function isConnectionGone(error: unknown): boolean {
303
+ return error instanceof RpcUnreached || (error instanceof RpcError && error.code === rpcCodes.closed)
304
+ }
305
+
280
306
  class GoneError extends Error {
281
307
  constructor(id: string) {
282
308
  super(`cmod has no connection ${id}: it closed, or the server started again. Connect again.`)
@@ -288,8 +314,8 @@ export type HttpCall = (path: string, init: { readonly method: 'GET' | 'POST' |
288
314
  export type HttpFetch = (url: string, init: { readonly method: string; readonly body?: string; readonly headers?: Readonly<Record<string, string>>; readonly socketPath?: string }) => Promise<{ readonly status: number; readonly text: string }>
289
315
 
290
316
  export function addressCall(fetch: HttpFetch, address: string): HttpCall {
291
- const socketPath = address.startsWith('unix:') ? address.slice('unix:'.length) : undefined
292
- const base = socketPath === undefined ? `http://${address}` : 'http://localhost'
317
+ const socketPath = address.startsWith('unix:') ? address.slice('unix:'.length) : address.startsWith('/') ? address : undefined
318
+ const base = socketPath !== undefined ? 'http://localhost' : /^https?:\/\//.test(address) ? address.replace(/\/+$/, '') : `http://${address}`
293
319
  return async (path, init) => {
294
320
  const answer = await fetch(`${base}${path}`, { method: init.method, ...(init.body === undefined ? {} : { body: init.body, headers: { 'content-type': 'application/json' } }), ...(socketPath === undefined ? {} : { socketPath }) })
295
321
  return { status: answer.status, text: answer.text }
@@ -365,7 +391,8 @@ export function connectRpc({
365
391
 
366
392
  const reconnect = () => {
367
393
  if (isClosed || !(keepsConnecting || hasConnected)) return
368
- void wait(retryMs).then(() => {
394
+ void wait(retryMs).then(async () => {
395
+ await Promise.allSettled([connecting])
369
396
  if (!isClosed && current === undefined) void connection().catch(() => undefined)
370
397
  })
371
398
  }