@cmodjs/core 8.9.1 → 8.10.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 (111) hide show
  1. package/docs/commands.md +13 -11
  2. package/docs/dependencies.md +6 -3
  3. package/docs/index.md +1 -1
  4. package/docs/jobs.md +1 -1
  5. package/docs/mod.md +1 -1
  6. package/docs/session.md +8 -7
  7. package/docs/testing.md +2 -2
  8. package/docs/ui.md +6 -5
  9. package/jobs/program.d.ts.map +1 -1
  10. package/jobs/program.js +5 -4
  11. package/mod.d.ts +34 -5
  12. package/mod.d.ts.map +1 -1
  13. package/package.json +1 -1
  14. package/records.d.ts +4 -2
  15. package/records.d.ts.map +1 -1
  16. package/records.js +6 -3
  17. package/register.d.ts.map +1 -1
  18. package/register.js +14 -5
  19. package/rpc.d.ts.map +1 -1
  20. package/rpc.js +1 -0
  21. package/runtime/bun.d.ts +7 -2
  22. package/runtime/bun.d.ts.map +1 -1
  23. package/runtime/bun.js +61 -7
  24. package/runtime/conversations.d.ts +3 -1
  25. package/runtime/conversations.d.ts.map +1 -1
  26. package/runtime/conversations.js +43 -36
  27. package/runtime/device.d.ts +2 -1
  28. package/runtime/device.d.ts.map +1 -1
  29. package/runtime/device.js +22 -1
  30. package/runtime/drawing-rules.d.ts +9 -0
  31. package/runtime/drawing-rules.d.ts.map +1 -0
  32. package/runtime/drawing-rules.js +46 -0
  33. package/runtime/engine.d.ts +3 -1
  34. package/runtime/engine.d.ts.map +1 -1
  35. package/runtime/hooks.d.ts +1 -1
  36. package/runtime/hooks.d.ts.map +1 -1
  37. package/runtime/hotkeys.d.ts.map +1 -1
  38. package/runtime/hotkeys.js +0 -7
  39. package/runtime/installer.js +3 -3
  40. package/runtime/interfaces.d.ts +47 -8
  41. package/runtime/interfaces.d.ts.map +1 -1
  42. package/runtime/interfaces.js +151 -15
  43. package/runtime/lifecycle.d.ts.map +1 -1
  44. package/runtime/lifecycle.js +61 -29
  45. package/runtime/parts.d.ts +2 -2
  46. package/runtime/parts.d.ts.map +1 -1
  47. package/runtime/parts.js +61 -35
  48. package/runtime/rpc.d.ts +11 -3
  49. package/runtime/rpc.d.ts.map +1 -1
  50. package/runtime/rpc.js +56 -19
  51. package/runtime/sessions.d.ts +2 -1
  52. package/runtime/sessions.d.ts.map +1 -1
  53. package/runtime/sessions.js +11 -4
  54. package/runtime/ui.d.ts +1 -0
  55. package/runtime/ui.d.ts.map +1 -1
  56. package/runtime/ui.js +62 -45
  57. package/runtime/widgets.d.ts +4 -2
  58. package/runtime/widgets.d.ts.map +1 -1
  59. package/runtime/widgets.js +6 -5
  60. package/session/session.d.ts +5 -1
  61. package/session/session.d.ts.map +1 -1
  62. package/src/jobs/program.ts +5 -4
  63. package/src/mod.ts +12 -4
  64. package/src/records.ts +8 -4
  65. package/src/register.ts +15 -5
  66. package/src/rpc.ts +2 -1
  67. package/src/runtime/bun.ts +58 -6
  68. package/src/runtime/conversations.ts +45 -36
  69. package/src/runtime/device.ts +21 -1
  70. package/src/runtime/drawing-rules.ts +42 -0
  71. package/src/runtime/engine.ts +3 -1
  72. package/src/runtime/hooks.ts +0 -1
  73. package/src/runtime/hotkeys.ts +0 -7
  74. package/src/runtime/installer.ts +3 -3
  75. package/src/runtime/interfaces.ts +187 -22
  76. package/src/runtime/lifecycle.ts +63 -29
  77. package/src/runtime/parts.ts +61 -33
  78. package/src/runtime/rpc.ts +65 -20
  79. package/src/runtime/sessions.ts +11 -5
  80. package/src/runtime/ui.ts +61 -38
  81. package/src/runtime/widgets.ts +9 -5
  82. package/src/session/session.ts +3 -1
  83. package/src/testing/fake-elements.ts +7 -23
  84. package/src/testing/fake-serve.ts +51 -9
  85. package/src/testing/fake-sessions.ts +5 -3
  86. package/src/testing.ts +9 -3
  87. package/src/ui/components.ts +13 -14
  88. package/src/ui/elements.ts +4 -4
  89. package/src/ui/palette.ts +38 -0
  90. package/src/ui/styles.ts +2 -0
  91. package/testing/fake-elements.d.ts.map +1 -1
  92. package/testing/fake-elements.js +9 -26
  93. package/testing/fake-serve.d.ts +6 -1
  94. package/testing/fake-serve.d.ts.map +1 -1
  95. package/testing/fake-serve.js +42 -5
  96. package/testing/fake-sessions.d.ts +1 -0
  97. package/testing/fake-sessions.d.ts.map +1 -1
  98. package/testing/fake-sessions.js +4 -2
  99. package/testing.d.ts.map +1 -1
  100. package/testing.js +12 -4
  101. package/ui/components.d.ts.map +1 -1
  102. package/ui/components.js +12 -13
  103. package/ui/elements.d.ts +2 -1
  104. package/ui/elements.d.ts.map +1 -1
  105. package/ui/elements.js +3 -3
  106. package/ui/palette.d.ts +17 -0
  107. package/ui/palette.d.ts.map +1 -0
  108. package/ui/palette.js +20 -0
  109. package/ui/styles.d.ts +1 -0
  110. package/ui/styles.d.ts.map +1 -1
  111. package/ui/styles.js +1 -0
@@ -3,10 +3,11 @@ import type { Surface } from '../mod.js'
3
3
  import { isObject } from '../records.js'
4
4
  import type { TurnData } from '../session/conversation.js'
5
5
  import { Dashboard, TurnEnd, type Area } from '../ui/areas.js'
6
- import { elementData, elementOf, Text, type Handler } from '../ui/elements.js'
6
+ import { Box, elementData, elementOf, Text, type Handler } from '../ui/elements.js'
7
7
  import { listed, messageOf } from '../utils/text.js'
8
8
  import type { Claude } from './claude.js'
9
9
  import { cmodPluginName, isNotInstalled, isStillInstalling } from './dependencies.js'
10
+ import { insideData, refusal } from './drawing-rules.js'
10
11
  import { styleInterface, uiParts, type Implementation } from './interfaces.js'
11
12
  import type { Router } from './router.js'
12
13
  import { partMethods, stalePress, type DrawnPart, type PageDeclaration, type PartPress, type PartRequest, type PartsUpdate, type ShownParts, type ViewDeclaration, type WidgetDeclaration } from './ui.js'
@@ -14,33 +15,65 @@ import { areaComponents, widgetsOf, type Widgets } from './widgets.js'
14
15
 
15
16
  export type DrawnParts = {
16
17
  fill(mod: string, cached: string, input: Readonly<Record<string, unknown>>, name: string): Promise<void> | undefined
17
- element(mod: string, cached: string, keyPrefix: string, name: string, reportId: string): RenderElement | undefined
18
+ element(mod: string, cached: string, keyPrefix: string, name: string, reportId: string): RenderElement | null | undefined
18
19
  failure(mod: string, cached: string): string | undefined
19
- forget(mod: string): void
20
+ forget(mod: string, ids?: readonly string[]): void
20
21
  }
21
22
 
22
- type Drawn = { readonly data: DrawnPart | null; readonly failure?: string; readonly generation: number }
23
+ type Drawn = { readonly data: DrawnPart | null; readonly failure?: string; readonly isRefused: boolean; readonly generation: number }
24
+
25
+ function partOf(input: Readonly<Record<string, unknown>>): string | undefined {
26
+ const id = input['widget'] ?? input['page']
27
+ return typeof id === 'string' ? id : undefined
28
+ }
29
+
30
+ const layoutInputs = new Set(['columns', 'isFocused', 'surface'])
31
+
32
+ function shownAs(mod: string, input: Readonly<Record<string, unknown>>): string {
33
+ const part = Object.entries(input)
34
+ .filter(([key]) => !layoutInputs.has(key))
35
+ .map(([key, value]) => [key, key === 'turn' && isObject(value) && isObject(value['prompt']) ? value['prompt']['id'] : value])
36
+ return `${mod}\u0000${JSON.stringify(part)}`
37
+ }
23
38
 
24
39
  const keptDrawings = 200
25
40
 
41
+ function remember<Value>(kept: Map<string, Value>, key: string, value: Value): void {
42
+ kept.delete(key)
43
+ kept.set(key, value)
44
+ const [oldest] = kept.keys()
45
+ if (kept.size > keptDrawings && oldest !== undefined) kept.delete(oldest)
46
+ }
47
+
26
48
  export function drawnParts({ claude, report, press }: { readonly claude: Claude; readonly report: (id: string, message: string, error: unknown) => void; readonly press: (mod: string, press: PartPress) => void }): DrawnParts {
27
49
  const drawn = new Map<string, Drawn>()
28
50
  const drawing = new Map<string, Promise<void>>()
51
+ const shownBy = new Map<string, string>()
52
+ const lastGood = new Map<string, DrawnPart>()
29
53
  const generations = new Map<string, number>()
54
+ let forgotten = 0
30
55
  const keyOf = (mod: string, cached: string) => `${mod}\u0000${cached}`
31
- const generationOf = (mod: string) => generations.get(mod) ?? 0
56
+ const generationOf = (mod: string, part: string | undefined) => Math.max(generations.get(mod) ?? 0, part === undefined ? 0 : (generations.get(keyOf(mod, part)) ?? 0))
57
+ const toldRefusals = new Set<string>()
32
58
 
33
59
  return {
34
60
  fill(mod, cached, input, name) {
35
61
  const key = keyOf(mod, cached)
36
- const generation = generationOf(mod)
62
+ const part = partOf(input)
63
+ const shown = shownAs(mod, input)
64
+ remember(shownBy, key, shown)
65
+ const generation = generationOf(mod, part)
37
66
  if (drawn.get(key)?.generation === generation) return undefined
38
67
  const keep = (data: DrawnPart | null, failure?: string) => {
39
- drawn.delete(key)
40
- drawn.set(key, { data, ...(failure === undefined ? {} : { failure }), generation })
41
- const [oldest] = drawn.keys()
42
- if (drawn.size > keptDrawings && oldest !== undefined) drawn.delete(oldest)
43
- if (generationOf(mod) !== generation) claude.ui.invalidate('ui.render')
68
+ const rule = data === null ? undefined : refusal(data.tree, insideData)
69
+ const told = `${mod}\u0000${part ?? ''}\u0000${rule}`
70
+ if (rule !== undefined && !toldRefusals.has(told)) {
71
+ toldRefusals.add(told)
72
+ report(`refused:${mod}/${part ?? 'markdown'}`, `${name} drew what Claude Code refuses`, new Error(rule))
73
+ }
74
+ remember(drawn, key, { data, ...(failure === undefined ? {} : { failure }), isRefused: rule !== undefined, generation })
75
+ if (data !== null && rule === undefined) remember(lastGood, shown, data)
76
+ if (generationOf(mod, part) !== generation) claude.ui.invalidate('ui.render')
44
77
  }
45
78
  const pending =
46
79
  drawing.get(key) ??
@@ -61,11 +94,12 @@ export function drawnParts({ claude, report, press }: { readonly claude: Claude;
61
94
  element(mod, cached, keyPrefix, name, reportId) {
62
95
  const key = keyOf(mod, cached)
63
96
  const entry = drawn.get(key)
64
- if (entry === undefined) return undefined
65
- drawn.delete(key)
66
- drawn.set(key, entry)
67
- const { data } = entry
68
- if (data === null || data.tree === null) return undefined
97
+ const shown = shownBy.get(key) ?? ''
98
+ if (entry !== undefined) remember(drawn, key, entry)
99
+ const data = entry !== undefined && entry.data !== null && !entry.isRefused ? entry.data : lastGood.get(shown)
100
+ if (data === undefined) return undefined
101
+ remember(lastGood, shown, data)
102
+ if (data.tree === null) return null
69
103
  try {
70
104
  return elementOf(data.tree, keyPrefix, (handler, args) => press(mod, { draw: data.draw, handler, args })) as RenderElement
71
105
  } catch (error) {
@@ -76,8 +110,9 @@ export function drawnParts({ claude, report, press }: { readonly claude: Claude;
76
110
  failure(mod, cached) {
77
111
  return drawn.get(keyOf(mod, cached))?.failure
78
112
  },
79
- forget(mod) {
80
- generations.set(mod, generationOf(mod) + 1)
113
+ forget(mod, ids) {
114
+ forgotten += 1
115
+ for (const key of ids?.map((id) => keyOf(mod, id)) ?? [mod]) generations.set(key, forgotten)
81
116
  },
82
117
  }
83
118
  }
@@ -286,13 +321,14 @@ export function serveParts({
286
321
  return true
287
322
  }
288
323
 
289
- const update = (mod: string, { parts: listing, redraw, requests, isAsked, isStart }: PartsUpdate) => {
324
+ const update = (mod: string, { parts: listing, redraw, changed, requests, isAsked, isStart }: PartsUpdate) => {
290
325
  if (isStart === true) started(mod)
291
326
  if (listing !== undefined) declare(mod, listing)
292
327
  if (listing !== undefined) provide(mod, providedBy(listing))
293
- const isRedrawn = redraw === true || requests?.some((request) => 'open' in request) === true
294
- if (listing !== undefined || isRedrawn) widgets.update(mod, { ...(listing === undefined ? {} : { parts: listing }), ...(isRedrawn ? { redraw: true } : {}) })
295
- if (redraw === true) for (const id of idsOf(mod)) tellUi('Redraw', { mod, id })
328
+ const isWhole = redraw === true && changed === undefined
329
+ const redrawn = [...new Set([...(changed ?? []), ...(requests ?? []).flatMap((request) => ('open' in request ? [request.open] : []))])]
330
+ if (listing !== undefined || isWhole || redrawn.length > 0) widgets.update(mod, { ...(listing === undefined ? {} : { parts: listing }), ...(isWhole ? { redraw: true } : {}), ...(redrawn.length === 0 ? {} : { changed: redrawn }) })
331
+ for (const id of isWhole ? idsOf(mod) : (changed ?? [])) tellUi('Redraw', { mod, id })
296
332
  if (requests === undefined || requests.length === 0) return false
297
333
  tellRequested(mod, requests, isAsked === true)
298
334
  if (isAsked !== true) return (void run(mod, requests), false)
@@ -319,25 +355,17 @@ export function serveParts({
319
355
  return pending
320
356
  }
321
357
 
322
- const lastDrawn = new Map<string, { readonly params: string; readonly cached: string }>()
323
-
324
358
  const plain = <Data,>(data: Data): Data => JSON.parse(JSON.stringify(data)) as Data
325
359
 
326
360
  const nameOf = (mod: string, id: string) => `The ${id} ${declared.get(mod)?.pages.some((each) => each.id === id) === true ? 'page' : 'view'} of ${mod}`
327
361
 
328
362
  const element = (mod: string, id: string, params: unknown, columns: number, isFocused: boolean, surface: Surface) => {
329
363
  if (!declared.has(mod)) void ask(mod)
330
- const given = JSON.stringify(params ?? null)
331
- const cached = `${id}\u0000${given}\u0000${columns}\u0000${isFocused}\u0000${surface}`
364
+ const cached = `${id}\u0000${JSON.stringify(params ?? null)}\u0000${columns}\u0000${isFocused}\u0000${surface}`
332
365
  const name = nameOf(mod, id)
333
- const keyPrefix = `${mod}/${id}:`
334
366
  void parts.fill(mod, cached, { page: id, params: plain(params ?? null), columns, isFocused, surface }, name)?.then(() => claude.ui.invalidate('ui.render'))
335
367
  const failure = parts.failure(mod, cached)
336
- const drawnAt = (key: string) => parts.element(mod, key, keyPrefix, name, `page:${mod}/${id}`)
337
- const last = lastDrawn.get(keyPrefix)
338
- const drawn = drawnAt(cached)
339
- if (drawn !== undefined) lastDrawn.set(keyPrefix, { params: given, cached })
340
- return drawn ?? (last?.params === given ? drawnAt(last.cached) : undefined) ?? (failure === undefined ? undefined : Text({ color: 'error', children: `${name} could not draw: ${failure}` }))
368
+ return parts.element(mod, cached, `${mod}/${id}:`, name, `page:${mod}/${id}`) ?? (failure === undefined ? undefined : Text({ color: 'error', children: `${name} could not draw: ${failure}` }))
341
369
  }
342
370
 
343
371
  const pressable = new Map<number, UiHandler>()
@@ -400,7 +428,7 @@ export function serveParts({
400
428
  const failure = parts.failure(part.mod, cached)
401
429
  if (failure !== undefined) throw new Error(`${name} could not draw: ${failure}`)
402
430
  const drawn = parts.element(part.mod, cached, keyPrefix, name, `ui:${part.mod}/${part.id}`)
403
- return drawn === undefined ? null : numbered(part, component, drawn)
431
+ return drawn === undefined ? null : numbered(part, component, drawn ?? Box({}))
404
432
  },
405
433
  async press(_session: string, handler: number, { surface, key, value, kind, link }: UiPress) {
406
434
  const known = pressable.get(handler)
@@ -1,5 +1,9 @@
1
+ import { beforeDeadline, callDeadline } from './deadline.js'
2
+
1
3
  export type RpcId = number | string
2
4
 
5
+ export type RpcClock = { after(ms: number, run: () => void): { cancel(): void } }
6
+
3
7
  export type RpcErrorData = { readonly code: number; readonly message: string; readonly data?: unknown }
4
8
 
5
9
  export type RpcMessage =
@@ -14,6 +18,7 @@ export const rpcCodes = {
14
18
  internal: -32603,
15
19
  closed: -32099,
16
20
  notHeld: -32098,
21
+ notProvided: -32097,
17
22
  cancelled: -32800,
18
23
  } as const
19
24
 
@@ -184,12 +189,13 @@ export const rpcPath = '/rpc'
184
189
  export type RpcConnection = Peer & { readonly id: string }
185
190
 
186
191
  type Held = {
192
+ readonly peer: Peer
187
193
  readonly connection: RpcConnection
188
194
  readonly outbox: RpcMessage[]
189
195
  poll: ((messages: RpcMessage[]) => void) | undefined
190
196
  chars: number | undefined
191
197
  seenAt: number
192
- unpolled?: unknown
198
+ isUnpolled: boolean
193
199
  }
194
200
 
195
201
  export type RpcHttpRequest = { readonly method: string; readonly path: string; readonly signal: AbortSignal; json(): Promise<unknown> }
@@ -208,25 +214,26 @@ const timers = globalThis as unknown as { setTimeout(run: () => void, ms: number
208
214
  export function rpcRoutes({
209
215
  handle,
210
216
  onClose,
217
+ onUnpolled,
211
218
  now,
212
219
  pollMs = 8000,
213
220
  liveMs = 30_000,
214
221
  }: {
215
222
  readonly handle: (connection: RpcConnection) => RpcHandler
216
223
  readonly onClose?: (connection: RpcConnection) => void
224
+ readonly onUnpolled?: (connection: RpcConnection) => void
217
225
  readonly now: () => number
218
226
  readonly pollMs?: number
219
227
  readonly liveMs?: number
220
228
  }): RpcRoutes {
221
229
  const held = new Map<string, Held>()
222
230
 
223
- const drop = (id: string, reason: string) => {
231
+ const drop = (id: string, reason: Error) => {
224
232
  const each = held.get(id)
225
233
  if (each === undefined) return
226
234
  held.delete(id)
227
- timers.clearTimeout(each.unpolled)
228
235
  each.poll?.([])
229
- each.connection.close(new Error(reason))
236
+ each.peer.close(reason)
230
237
  onClose?.(each.connection)
231
238
  }
232
239
 
@@ -239,7 +246,8 @@ export function rpcRoutes({
239
246
  if (entry === undefined) return
240
247
  outbox.push(message)
241
248
  if (entry.poll === undefined) {
242
- entry.unpolled ??= timers.setTimeout(() => drop(id, `no poll for ${pollMs / 1000} s while a message waited`), pollMs)
249
+ if (!entry.isUnpolled) onUnpolled?.(entry.connection)
250
+ entry.isUnpolled = true
243
251
  return
244
252
  }
245
253
  const poll = entry.poll
@@ -248,15 +256,15 @@ export function rpcRoutes({
248
256
  },
249
257
  handle: (method, params, signal) => handler(method, params, signal),
250
258
  })
251
- const connection: RpcConnection = Object.assign(peer, { id })
259
+ const connection: RpcConnection = { ...peer, id, close: (reason) => drop(id, reason) }
252
260
  const handler = handle(connection)
253
- entry = { connection, outbox, poll: undefined, chars: undefined, seenAt: now() }
261
+ entry = { peer, connection, outbox, poll: undefined, chars: undefined, seenAt: now(), isUnpolled: false }
254
262
  held.set(id, entry)
255
263
  return entry
256
264
  }
257
265
 
258
266
  const sweep = () => {
259
- for (const [id, each] of held) if (each.poll === undefined && now() - each.seenAt > liveMs) drop(id, `no poll for ${liveMs / 1000} s`)
267
+ for (const [id, each] of held) if (each.poll === undefined && now() - each.seenAt > liveMs) drop(id, new Error(`no poll for ${liveMs / 1000} s`))
260
268
  }
261
269
 
262
270
  const known = (id: string) => {
@@ -269,8 +277,7 @@ export function rpcRoutes({
269
277
  const poll = (each: Held, signal: AbortSignal, chars: number | undefined) =>
270
278
  new Promise<RpcMessage[]>((resolve) => {
271
279
  each.poll?.([])
272
- timers.clearTimeout(each.unpolled)
273
- each.unpolled = undefined
280
+ each.isUnpolled = false
274
281
  each.chars = chars
275
282
  if (each.outbox.length > 0) return resolve(takenWithin(each.outbox, chars))
276
283
  const timer = timers.setTimeout(() => answer([]), pollMs)
@@ -286,7 +293,7 @@ export function rpcRoutes({
286
293
  each.poll = undefined
287
294
  timers.clearTimeout(timer)
288
295
  resolve([])
289
- drop(each.connection.id, 'the client left its poll')
296
+ drop(each.connection.id, new Error('the client left its poll'))
290
297
  })
291
298
  })
292
299
 
@@ -299,7 +306,7 @@ export function rpcRoutes({
299
306
  if (url.pathname === `${rpcPath}/connect` && request.method === 'POST') return { status: 200, json: { connection: open().connection.id } }
300
307
  if (id === undefined) return { status: 404, json: { error: `cmod has no ${request.method} ${url.pathname}.` } }
301
308
  if (request.method === 'DELETE') {
302
- drop(id, 'the client closed it')
309
+ drop(id, new Error('the client closed it'))
303
310
  return { status: 204 }
304
311
  }
305
312
  const each = known(id)
@@ -339,7 +346,7 @@ export function rpcRoutes({
339
346
  channel,
340
347
  connections: () => [...[...held.values()].map((each) => each.connection), ...channels.values()],
341
348
  close() {
342
- for (const id of held.keys()) drop(id, 'the server stopped')
349
+ for (const id of held.keys()) drop(id, new Error('the server stopped'))
343
350
  for (const each of channels.values()) each.close(new Error('the server stopped'))
344
351
  },
345
352
  }
@@ -382,7 +389,8 @@ export function connectRpc({
382
389
  handle,
383
390
  onConnect,
384
391
  onError,
385
- wait,
392
+ onLost,
393
+ clock,
386
394
  retryMs = 2000,
387
395
  keepsConnecting = false,
388
396
  }: {
@@ -390,7 +398,8 @@ export function connectRpc({
390
398
  readonly handle: RpcHandler
391
399
  readonly onConnect?: (client: RpcClient) => unknown
392
400
  readonly onError?: (error: unknown) => void
393
- readonly wait: (ms: number) => Promise<void>
401
+ readonly onLost?: () => void
402
+ readonly clock: RpcClock
394
403
  readonly retryMs?: number
395
404
  readonly keepsConnecting?: boolean
396
405
  }): RpcClient {
@@ -429,6 +438,7 @@ export function connectRpc({
429
438
  queued = []
430
439
  link.peer.close(reason)
431
440
  reconnect()
441
+ onLost?.()
432
442
  }
433
443
 
434
444
  const pollLoop = async (link: Link) => {
@@ -452,12 +462,17 @@ export function connectRpc({
452
462
  }
453
463
 
454
464
  let hasConnected = false
465
+ let isRetrying = false
466
+ const waiting = new Set<{ resolve(link: Link): void; reject(error: Error): void }>()
455
467
 
456
468
  const reconnect = () => {
457
- if (isClosed || !(keepsConnecting || hasConnected)) return
458
- void wait(retryMs).then(async () => {
459
- await Promise.allSettled([connecting])
460
- if (!isClosed && current === undefined) void connection().catch(() => undefined)
469
+ if (isClosed || isRetrying || !(keepsConnecting || hasConnected)) return
470
+ isRetrying = true
471
+ clock.after(retryMs, () => {
472
+ isRetrying = false
473
+ void Promise.allSettled([connecting]).then(() => {
474
+ if (!isClosed && current === undefined) void connection().catch(() => undefined)
475
+ })
461
476
  })
462
477
  }
463
478
 
@@ -485,6 +500,7 @@ export function connectRpc({
485
500
  hasConnected = true
486
501
  void pollLoop(link)
487
502
  void (async () => onConnect?.(client))().catch((error: unknown) => onError?.(error))
503
+ for (const each of waiting) each.resolve(link)
488
504
  return current
489
505
  } catch (error) {
490
506
  onError?.(error)
@@ -501,12 +517,40 @@ export function connectRpc({
501
517
  return connecting
502
518
  }
503
519
 
520
+ const nextLink = (method: string, signal: AbortSignal | undefined): Promise<Link> => {
521
+ if (current !== undefined) return Promise.resolve(current)
522
+ if (isClosed || !(keepsConnecting || hasConnected)) return connection()
523
+ if (!isRetrying) void connection().catch(() => undefined)
524
+ return beforeDeadline(
525
+ clock,
526
+ callDeadline,
527
+ method,
528
+ (passed) =>
529
+ new Promise<Link>((resolve, reject) => {
530
+ const settled = () => {
531
+ waiting.delete(waiter)
532
+ signal?.removeEventListener('abort', stop)
533
+ passed.removeEventListener('abort', stop)
534
+ }
535
+ const waiter = {
536
+ resolve: (link: Link) => (settled(), resolve(link)),
537
+ reject: (error: Error) => (settled(), reject(error)),
538
+ }
539
+ const stop = () => waiter.reject(passed.aborted ? (passed.reason as Error) : new RpcError(rpcCodes.cancelled, `${method} was cancelled.`))
540
+ if (signal?.aborted === true) return stop()
541
+ signal?.addEventListener('abort', stop, { once: true })
542
+ passed.addEventListener('abort', stop, { once: true })
543
+ waiting.add(waiter)
544
+ }),
545
+ )
546
+ }
547
+
504
548
  const client: RpcClient = {
505
549
  get isConnected() {
506
550
  return current !== undefined
507
551
  },
508
552
  async request<Result>(method: string, params?: unknown, signal?: AbortSignal): Promise<Result> {
509
- const link = await connection()
553
+ const link = await nextLink(method, signal)
510
554
  const answer = link.peer.request<Result>(method, params, signal)
511
555
  const sent = link.lastAsked
512
556
  try {
@@ -523,6 +567,7 @@ export function connectRpc({
523
567
  },
524
568
  async close() {
525
569
  isClosed = true
570
+ for (const each of waiting) each.reject(closedError(new Error('the client closed it')))
526
571
  const was = current
527
572
  current = undefined
528
573
  if (was === undefined) return
@@ -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 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'
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 SendReceipt, 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'
@@ -33,6 +33,7 @@ export const conversationMethods = {
33
33
  contexts: 'cmod:contexts',
34
34
  tasks: 'cmod:tasks',
35
35
  goal: 'cmod:goal',
36
+ mail: 'cmod:mail',
36
37
  updateGoal: 'cmod:updateGoal',
37
38
  subscribe: 'cmod:subscribe',
38
39
  watchBefore: 'cmod:watchBefore',
@@ -57,7 +58,7 @@ export function pickedColor(args: string): string | undefined {
57
58
  return resetColors.includes(picked) ? undefined : picked
58
59
  }
59
60
 
60
- const acts = ['send', 'startTask', 'fork', 'clone', 'startBackgroundTask', 'callTool', 'usage', 'surfaces', 'abort', 'end', 'visit', 'delete', 'compact', 'sendTo'] as const
61
+ const acts = ['send', 'startTask', 'fork', 'clone', 'startBackgroundTask', 'callTool', 'usage', 'surfaces', 'abort', 'end', 'visit', 'delete', 'compact'] as const
61
62
 
62
63
  export type Act = (typeof acts)[number]
63
64
 
@@ -416,10 +417,15 @@ export function createSessionsClient({ name, claude, report, hookOn, routeOn, pe
416
417
  messages: (options: { readonly after?: string; readonly last?: number } = {}) => messagesFrom(conversationMethods.messages, { ...where(), ...options }),
417
418
  usage: async (): Promise<Usage> => (isHere() ? usageOf(claude) : act<Usage>(id(), 'usage', null, owned)),
418
419
  surfaces: async (): Promise<Surface[]> => (isHere() ? surfacesHere() : act<Surface[]>(id(), 'surfaces', null, owned)),
419
- async send(message: SessionSend) {
420
+ async send(message: SessionSend): Promise<SendReceipt> {
420
421
  if (message.text.trim() === '') throw new Error(`${name}: send needs text.`)
421
- if (isHere() && message.as !== Session) return sendHere(message)
422
- await act(id(), 'send', message, owned)
422
+ if (message.as === Session && isHere()) throw new Error(`${name}: session ${id()} cannot send as itself to itself.`)
423
+ if (message.as === Session && current.id === '') throw new Error(`${name}: as: Session sends from the session the code runs in, and a cmod run script runs in none.`)
424
+ if (isHere()) {
425
+ await sendHere(message)
426
+ return { state: 'delivered' }
427
+ }
428
+ return (await act<SendReceipt | null>(id(), 'send', message, owned)) ?? { state: 'delivered' }
423
429
  },
424
430
  async end() {
425
431
  await act(id(), 'end', null, owned)
package/src/runtime/ui.ts CHANGED
@@ -79,7 +79,7 @@ export type PartRequest =
79
79
 
80
80
  export type SettingsTab = 'changelog' | 'permissions'
81
81
 
82
- export type PartsUpdate = { readonly parts?: PartList; readonly redraw?: true; readonly requests?: readonly PartRequest[]; readonly isAsked?: true; readonly isStart?: true }
82
+ export type PartsUpdate = { readonly parts?: PartList; readonly redraw?: true; readonly changed?: readonly string[]; readonly requests?: readonly PartRequest[]; readonly isAsked?: true; readonly isStart?: true }
83
83
 
84
84
  export type ShownParts = { readonly open: readonly { readonly id: string; readonly params: unknown }[]; readonly shown: string | null; readonly isFocused: boolean; readonly inApps?: readonly string[] }
85
85
 
@@ -183,8 +183,9 @@ export function merged(updates: readonly PartsUpdate[]): PartsUpdate {
183
183
  const parts = updates.findLast((update) => update.parts !== undefined)?.parts
184
184
  const requests = updates.flatMap((update) => update.requests ?? [])
185
185
  const isRedrawn = updates.some((update) => update.redraw === true)
186
+ const changed = [...new Set(updates.flatMap((update) => update.changed ?? []))]
186
187
  const isStart = updates.some((update) => update.isStart === true)
187
- return { ...(parts === undefined ? {} : { parts }), ...(isRedrawn ? { redraw: true } : {}), ...(requests.length === 0 ? {} : { requests }), ...(isStart ? { isStart } : {}) }
188
+ return { ...(parts === undefined ? {} : { parts }), ...(isRedrawn ? { redraw: true } : {}), ...(changed.length === 0 ? {} : { changed }), ...(requests.length === 0 ? {} : { requests }), ...(isStart ? { isStart } : {}) }
188
189
  }
189
190
 
190
191
  type MarkdownRender = {
@@ -228,6 +229,8 @@ export type UiArea<State extends object> = {
228
229
 
229
230
  export const keptDrawInputs = 200
230
231
 
232
+ const tellGapMs = 100
233
+
231
234
  export function createUi<State extends object>({ name, claude, router, report, announce, mod, borrowed, nextDraw, provided }: UiOptions<State>): UiArea<State> {
232
235
  const panes = new Map<string, AddedPane<State>>()
233
236
  const paneLogs = new Map<string, (failure: string) => void>()
@@ -266,6 +269,7 @@ export function createUi<State extends object>({ name, claude, router, report, a
266
269
  let collected: PartsUpdate[] | undefined
267
270
  let collecting = 0
268
271
  let queued: PartsUpdate[] | undefined
272
+ let isCooling = false
269
273
 
270
274
  const partList = (): PartList => {
271
275
  const provides = [...provided(), ...(markdownRenders.size > 0 ? [styleInterface] : [])]
@@ -290,50 +294,69 @@ export function createUi<State extends object>({ name, claude, router, report, a
290
294
  return drawn === undefined ? null : elementData(drawn, (run) => handlers.push(run) - 1)
291
295
  }
292
296
 
293
- const isAnyDrawingChanged = () => {
294
- for (const [key, inputs] of latestDraws) {
295
- if (key === 'markdown') continue
296
- for (const sent of inputs.values()) {
297
- const handlers: Handler[] = []
298
- try {
299
- if (JSON.stringify(treeOf(sent.render, handlers)) !== sent.tree) return true
300
- } catch (error) {
301
- claude.ui.warn(`drawing:${key}`, `${name}: the ${key} drawing threw, so the cmod plugin asks for it again: ${messageOf(error)}`)
302
- return true
303
- }
304
- const latest = sent.draws.at(-1)
305
- if (latest !== undefined && draws.has(latest)) draws.set(latest, { id: key, handlers })
297
+ const isDrawingChanged = (key: string, inputs: ReadonlyMap<string, SentDrawing>) => {
298
+ const unchanged: (readonly [SentDrawing, Handler[]])[] = []
299
+ for (const sent of inputs.values()) {
300
+ const handlers: Handler[] = []
301
+ try {
302
+ if (JSON.stringify(treeOf(sent.render, handlers)) !== sent.tree) return true
303
+ } catch (error) {
304
+ claude.ui.warn(`drawing:${key}`, `${name}: the ${key} drawing threw, so the cmod plugin asks for it again: ${messageOf(error)}`)
305
+ return true
306
306
  }
307
+ unchanged.push([sent, handlers])
308
+ }
309
+ for (const [sent, handlers] of unchanged) {
310
+ const latest = sent.draws.at(-1)
311
+ if (latest !== undefined && draws.has(latest)) draws.set(latest, { id: key, handlers })
307
312
  }
308
313
  return false
309
314
  }
310
315
 
311
- const withNeededRedraw = ({ redraw, ...update }: PartsUpdate): PartsUpdate => (redraw === true && isAnyDrawingChanged() ? { ...update, redraw } : update)
316
+ const changedParts = () => [...latestDraws].filter(([key, inputs]) => key !== 'markdown' && isDrawingChanged(key, inputs)).map(([key]) => key.slice(key.indexOf(':') + 1))
317
+
318
+ const withChangedParts = ({ redraw, ...update }: PartsUpdate): PartsUpdate => {
319
+ if (redraw !== true) return update
320
+ const changed = changedParts()
321
+ return changed.length === 0 ? update : { ...update, redraw, changed }
322
+ }
323
+
324
+ const tell = async (needed: PartsUpdate, isAsked: boolean) => {
325
+ if (Object.keys(needed).length === 0) return
326
+ const input = { ...needed, ...(isAsked ? { isAsked: true as const } : {}) }
327
+ return claude.cmod.call({ to: cmodPluginName, method: partMethods.changed, input }).then(
328
+ (answer) => {
329
+ if (isAsked && input.requests !== undefined && !(isObject(answer) && answer['isHeld'] === true)) unheldRequests += 1
330
+ if (isObject(answer) && name !== cmodPluginName) hear(answer['stylers'], false)
331
+ },
332
+ (error: unknown) => {
333
+ claude.ui.warn('parts:tell', `${name}: the cmod plugin did not hear about its widgets, views, and pages: ${messageOf(error)}`)
334
+ },
335
+ )
336
+ }
337
+
338
+ const tellQueued = async () => {
339
+ const needed = withChangedParts(merged(queued ?? []))
340
+ queued = undefined
341
+ if (needed.changed !== undefined) {
342
+ isCooling = true
343
+ claude.clock.after(tellGapMs, () => {
344
+ isCooling = false
345
+ if (queued !== undefined) void tellQueued()
346
+ })
347
+ }
348
+ await tell(needed, false)
349
+ }
312
350
 
313
351
  const send = (update: PartsUpdate) => {
314
352
  if (collected !== undefined) return void collected.push(update)
315
353
  if (beforeStart !== undefined) return void beforeStart.push(update)
316
- const isAsked = askedDepth > 0
317
- if (queued !== undefined && !isAsked) return void queued.push(update)
318
- const batch: PartsUpdate[] = [update]
319
- if (!isAsked) queued = batch
320
- const tell = async () => {
321
- if (queued === batch) queued = undefined
322
- const needed = withNeededRedraw(merged(batch))
323
- if (Object.keys(needed).length === 0) return
324
- const input = { ...needed, ...(isAsked ? { isAsked: true as const } : {}) }
325
- return claude.cmod.call({ to: cmodPluginName, method: partMethods.changed, input }).then(
326
- (answer) => {
327
- if (isAsked && input.requests !== undefined && !(isObject(answer) && answer['isHeld'] === true)) unheldRequests += 1
328
- if (isObject(answer) && name !== cmodPluginName) hear(answer['stylers'], false)
329
- },
330
- (error: unknown) => {
331
- claude.ui.warn('parts:tell', `${name}: the cmod plugin did not hear about its widgets, views, and pages: ${messageOf(error)}`)
332
- },
333
- )
354
+ if (askedDepth === 0) {
355
+ if (queued !== undefined) return void queued.push(update)
356
+ queued = [update]
357
+ return isCooling ? undefined : Promise.resolve().then(tellQueued)
334
358
  }
335
- if (!isAsked) return Promise.resolve().then(tell)
336
- const told = tell().finally(() => askedCalls.delete(told))
359
+ const told = tell(withChangedParts(update), true).finally(() => askedCalls.delete(told))
337
360
  askedCalls.add(told)
338
361
  return told
339
362
  }
@@ -359,7 +382,7 @@ export function createUi<State extends object>({ name, claude, router, report, a
359
382
  }
360
383
  const mine = collected
361
384
  collected = collecting === 0 ? undefined : []
362
- return withNeededRedraw(merged(mine))
385
+ return withChangedParts(merged(mine))
363
386
  }
364
387
 
365
388
  const logOnce = (what: string) => {
@@ -800,7 +823,7 @@ export function createUi<State extends object>({ name, claude, router, report, a
800
823
  },
801
824
  changed() {
802
825
  if (widgets.size > 0 || parts.size > 0) void send({ redraw: true })
803
- if (panes.size === 0 && styles.size === 0) return
826
+ if (openPanes.size === 0 && styles.size === 0) return
804
827
  claude.ui.invalidate('ui.render')
805
828
  if (isResizeQueued) return
806
829
  isResizeQueued = true