@cmodjs/core 6.3.0 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/docs/commands.md +123 -65
  2. package/docs/dependencies.md +189 -4
  3. package/docs/index.md +56 -12
  4. package/docs/install-steps.md +20 -17
  5. package/docs/jobs.md +43 -16
  6. package/docs/mod.md +43 -27
  7. package/docs/options.md +2 -2
  8. package/docs/session.md +58 -32
  9. package/docs/testing.md +88 -24
  10. package/docs/ui.md +128 -58
  11. package/installer.d.ts +2 -2
  12. package/jobs/context.js +1 -1
  13. package/jobs/program.d.ts +4 -1
  14. package/jobs/program.d.ts.map +1 -1
  15. package/jobs/program.js +79 -20
  16. package/mod.d.ts +59 -9
  17. package/mod.d.ts.map +1 -1
  18. package/mod.js +5 -3
  19. package/package.json +1 -1
  20. package/records.d.ts +15 -2
  21. package/records.d.ts.map +1 -1
  22. package/records.js +24 -10
  23. package/register.d.ts.map +1 -1
  24. package/register.js +7 -4
  25. package/rpc.d.ts +7 -0
  26. package/rpc.d.ts.map +1 -0
  27. package/rpc.js +59 -0
  28. package/runtime/bound.d.ts +1 -0
  29. package/runtime/bound.d.ts.map +1 -1
  30. package/runtime/bound.js +10 -0
  31. package/runtime/bun.d.ts +20 -0
  32. package/runtime/bun.d.ts.map +1 -0
  33. package/runtime/bun.js +20 -0
  34. package/runtime/claude.d.ts +1 -0
  35. package/runtime/claude.d.ts.map +1 -1
  36. package/runtime/conversations.d.ts +12 -1
  37. package/runtime/conversations.d.ts.map +1 -1
  38. package/runtime/conversations.js +472 -362
  39. package/runtime/deadline.d.ts +4 -3
  40. package/runtime/deadline.d.ts.map +1 -1
  41. package/runtime/deadline.js +10 -4
  42. package/runtime/engine.d.ts +5 -4
  43. package/runtime/engine.d.ts.map +1 -1
  44. package/runtime/installer.d.ts +3 -3
  45. package/runtime/installer.d.ts.map +1 -1
  46. package/runtime/installer.js +10 -9
  47. package/runtime/interfaces.d.ts +262 -0
  48. package/runtime/interfaces.d.ts.map +1 -0
  49. package/runtime/interfaces.js +935 -0
  50. package/runtime/lifecycle.d.ts +3 -3
  51. package/runtime/lifecycle.d.ts.map +1 -1
  52. package/runtime/lifecycle.js +83 -52
  53. package/runtime/options.d.ts.map +1 -1
  54. package/runtime/options.js +2 -6
  55. package/runtime/parts.d.ts +64 -1
  56. package/runtime/parts.d.ts.map +1 -1
  57. package/runtime/parts.js +311 -4
  58. package/runtime/programs.d.ts +1 -0
  59. package/runtime/programs.d.ts.map +1 -1
  60. package/runtime/programs.js +5 -3
  61. package/runtime/rpc.d.ts +111 -0
  62. package/runtime/rpc.d.ts.map +1 -0
  63. package/runtime/rpc.js +387 -0
  64. package/runtime/sessions.d.ts +6 -4
  65. package/runtime/sessions.d.ts.map +1 -1
  66. package/runtime/sessions.js +59 -80
  67. package/runtime/toaster.js +1 -1
  68. package/runtime/ui.d.ts +23 -10
  69. package/runtime/ui.d.ts.map +1 -1
  70. package/runtime/ui.js +63 -52
  71. package/runtime/web.d.ts +0 -73
  72. package/runtime/web.d.ts.map +1 -1
  73. package/runtime/web.js +9 -5
  74. package/runtime/widgets.d.ts +4 -2
  75. package/runtime/widgets.d.ts.map +1 -1
  76. package/runtime/widgets.js +17 -16
  77. package/session/conversation.d.ts +7 -1
  78. package/session/conversation.d.ts.map +1 -1
  79. package/session/session.d.ts +31 -7
  80. package/session/session.d.ts.map +1 -1
  81. package/session/session.js +1 -0
  82. package/src/installer.ts +2 -2
  83. package/src/jobs/context.ts +1 -1
  84. package/src/jobs/program.ts +76 -21
  85. package/src/mod.ts +51 -10
  86. package/src/records.ts +33 -9
  87. package/src/register.ts +7 -4
  88. package/src/rpc.ts +67 -0
  89. package/src/runtime/bound.ts +10 -0
  90. package/src/runtime/bun.ts +40 -0
  91. package/src/runtime/claude.ts +1 -0
  92. package/src/runtime/conversations.ts +470 -352
  93. package/src/runtime/deadline.ts +13 -6
  94. package/src/runtime/engine.ts +5 -4
  95. package/src/runtime/installer.ts +13 -12
  96. package/src/runtime/interfaces.ts +1161 -0
  97. package/src/runtime/lifecycle.ts +102 -59
  98. package/src/runtime/options.ts +2 -5
  99. package/src/runtime/parts.ts +364 -5
  100. package/src/runtime/programs.ts +6 -3
  101. package/src/runtime/rpc.ts +457 -0
  102. package/src/runtime/sessions.ts +63 -83
  103. package/src/runtime/toaster.ts +1 -1
  104. package/src/runtime/ui.ts +82 -61
  105. package/src/runtime/web.ts +10 -39
  106. package/src/runtime/widgets.ts +20 -18
  107. package/src/session/conversation.ts +7 -1
  108. package/src/session/session.ts +22 -7
  109. package/src/testing/fake-claude.ts +38 -7
  110. package/src/testing/fake-serve.ts +144 -0
  111. package/src/testing/fake-sessions.ts +21 -6
  112. package/src/testing.ts +156 -68
  113. package/src/ui/areas.ts +2 -2
  114. package/src/ui/elements.ts +21 -16
  115. package/src/ui/panes.ts +14 -7
  116. package/testing/fake-claude.d.ts +6 -0
  117. package/testing/fake-claude.d.ts.map +1 -1
  118. package/testing/fake-claude.js +34 -7
  119. package/testing/fake-serve.d.ts +39 -0
  120. package/testing/fake-serve.d.ts.map +1 -0
  121. package/testing/fake-serve.js +110 -0
  122. package/testing/fake-sessions.d.ts.map +1 -1
  123. package/testing/fake-sessions.js +22 -6
  124. package/testing.d.ts +21 -4
  125. package/testing.d.ts.map +1 -1
  126. package/testing.js +138 -56
  127. package/ui/areas.d.ts +3 -1
  128. package/ui/areas.d.ts.map +1 -1
  129. package/ui/elements.d.ts +18 -9
  130. package/ui/elements.d.ts.map +1 -1
  131. package/ui/elements.js +9 -8
  132. package/ui/panes.d.ts +10 -6
  133. package/ui/panes.d.ts.map +1 -1
  134. package/ui/panes.js +5 -3
  135. package/runtime/pages.d.ts +0 -32
  136. package/runtime/pages.d.ts.map +0 -1
  137. package/runtime/pages.js +0 -142
  138. package/src/runtime/pages.ts +0 -183
@@ -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 {
@@ -1,4 +1,4 @@
1
- import type { ElementTable, MarkdownProps, RenderElement } from 'claude-code'
1
+ import type { ElementTable, MarkdownProps, RenderComponent, RenderElement } from 'claude-code'
2
2
  import { isObject, storeChangedPath, widgetsPath } from '../records.js'
3
3
  import type { TurnData } from '../session/conversation.js'
4
4
  import { AbovePrompt, areas, BelowPrompt, TurnEnd, Working, type Area } from '../ui/areas.js'
@@ -29,6 +29,8 @@ export const builtInWidgets: readonly PlacedWidget[] = [
29
29
  { key: claudeModes, mod: 'claude', title: "Claude Code's mode labels", areas: [BelowPrompt] },
30
30
  ]
31
31
 
32
+ export const areaComponents: Readonly<Record<Area, RenderComponent>> = { abovePrompt: 'AbovePrompt', belowPrompt: 'PromptHint', working: 'Spinner', turnEnd: 'TurnDuration', dashboard: 'Pane' }
33
+
32
34
  const promptIndent = 4
33
35
 
34
36
  const transcriptIndent = 2
@@ -45,7 +47,7 @@ export type Widgets = {
45
47
  change(edit: (layout: WidgetLayout) => WidgetLayout): Promise<void>
46
48
  reload(): Promise<void>
47
49
  recheck(): Promise<void>
48
- rows(area: Area, columns: number): RenderElement[]
50
+ rows(area: Area, at: StyledAt): RenderElement[]
49
51
  draw(area: Area, table: ElementTable, at: StyledAt, turn?: TurnData): Promise<RenderElement[]>
50
52
  }
51
53
 
@@ -97,7 +99,7 @@ export function moved(layout: WidgetLayout, widget: PlacedWidget, move: Move): W
97
99
  return withAreas({ [area]: without, [next]: landing })
98
100
  }
99
101
 
100
- function declarationsOf(input: unknown): WidgetDeclaration[] {
102
+ export function widgetsOf(input: unknown): WidgetDeclaration[] {
101
103
  const listed = isObject(input) && Array.isArray(input['widgets']) ? (input['widgets'] as unknown[]) : []
102
104
  return listed.filter(isObject).flatMap((each) => {
103
105
  const known = Array.isArray(each['areas']) ? (each['areas'] as unknown[]).filter((area): area is Area => (areas as readonly unknown[]).includes(area)) : []
@@ -180,7 +182,7 @@ export function serveWidgets({
180
182
 
181
183
  const ask = async (mod: string) => {
182
184
  try {
183
- declared.set(mod, declarationsOf(await claude.cmod.call({ to: mod, method: partMethods.list, input: null })))
185
+ declared.set(mod, widgetsOf(await claude.cmod.call({ to: mod, method: partMethods.list, input: null })))
184
186
  } catch (error) {
185
187
  declared.delete(mod)
186
188
  if (!isNotInstalled(mod, error) && !isStillInstalling(mod, error)) claude.ui.warn(`widgets:list:${mod}`, `cmod: ${mod} did not list its widgets: ${messageOf(error)}`)
@@ -212,20 +214,20 @@ export function serveWidgets({
212
214
 
213
215
  const widgetOf = (key: string) => placed().find((widget) => widget.key === key)
214
216
 
215
- const cacheKey = (key: string, area: Area, columns: number, turn: TurnData | undefined) => `${key}\u0000${area}\u0000${columns}\u0000${turn?.prompt.id ?? ''}`
217
+ const cacheKey = (key: string, area: Area, { columns, surface }: StyledAt, turn: TurnData | undefined) => `${key}\u0000${area}\u0000${columns}\u0000${surface}\u0000${turn?.prompt.id ?? ''}`
216
218
 
217
219
  const nameOf = (widget: PlacedWidget) => `The ${widget.title} widget of ${widget.mod}`
218
220
 
219
- const fill = (key: string, area: Area, columns: number, turn: TurnData | undefined): Promise<void> | undefined => {
221
+ const fill = (key: string, area: Area, at: StyledAt, turn: TurnData | undefined): Promise<void> | undefined => {
220
222
  const widget = widgetOf(key)
221
223
  if (widget === undefined || !widget.areas.includes(area)) return undefined
222
- return parts.fill(widget.mod, cacheKey(key, area, columns, turn), { widget: key.slice(widget.mod.length + 1), area, columns, ...(turn === undefined ? {} : { turn }) }, nameOf(widget))
224
+ return parts.fill(widget.mod, cacheKey(key, area, at, turn), { widget: key.slice(widget.mod.length + 1), area, columns: at.columns, surface: at.surface, ...(turn === undefined ? {} : { turn }) }, nameOf(widget))
223
225
  }
224
226
 
225
- const elementFor = (key: string, area: Area, columns: number, turn: TurnData | undefined): RenderElement | undefined => {
227
+ const elementFor = (key: string, area: Area, at: StyledAt, turn: TurnData | undefined): RenderElement | undefined => {
226
228
  const widget = widgetOf(key)
227
229
  if (widget === undefined) return undefined
228
- const element = parts.element(widget.mod, cacheKey(key, area, columns, turn), `${key}:`, nameOf(widget), `widget:${key}`)
230
+ const element = parts.element(widget.mod, cacheKey(key, area, at, turn), `${key}:`, nameOf(widget), `widget:${key}`)
229
231
  return element === undefined ? undefined : Box({ ...widgetSizes[widget.place?.size ?? 'fit'], children: element })
230
232
  }
231
233
 
@@ -233,26 +235,26 @@ export function serveWidgets({
233
235
 
234
236
  const shown = (keys: readonly string[]) => keys.filter((key) => !isHidden(key))
235
237
 
236
- const rowsNow = (area: Area, columns: number, turn: TurnData | undefined): RenderElement[] =>
238
+ const rowsNow = (area: Area, at: StyledAt, turn: TurnData | undefined): RenderElement[] =>
237
239
  layout.areas[area].flatMap((row) => {
238
- const side = (keys: readonly string[]) => shown(keys).map((key) => elementFor(key, area, columns, turn)).filter((each) => each !== undefined)
240
+ const side = (keys: readonly string[]) => shown(keys).map((key) => elementFor(key, area, at, turn)).filter((each) => each !== undefined)
239
241
  const left = side(row.left)
240
242
  const right = side(row.right)
241
243
  const group = (keys: readonly string[], children: readonly RenderElement[]) => Box({ flexShrink: shown(keys).some((key) => widgetOf(key)?.place?.size === 'fill') ? 1 : 0, minWidth: 0, columnGap: 2, children })
242
- return left.length + right.length === 0 ? [] : [Box({ justifyContent: 'space-between', width: columns, columnGap: 2, children: [group(row.left, left), group(row.right, right)] })]
244
+ return left.length + right.length === 0 ? [] : [Box({ justifyContent: 'space-between', width: at.columns, columnGap: 2, children: [group(row.left, left), group(row.right, right)] })]
243
245
  })
244
246
 
245
247
  const keysIn = (area: Area) => layout.areas[area].flatMap((row) => shown([...row.left, ...row.right]))
246
248
 
247
249
  const draw = async (area: Area, table: ElementTable, at: StyledAt, turn?: TurnData): Promise<RenderElement[]> => {
248
- await Promise.all(keysIn(area).map((key) => fill(key, area, at.columns, turn)))
249
- return drawWith(table, () => rowsNow(area, at.columns, turn), markdownIn(table, at))
250
+ await Promise.all(keysIn(area).map((key) => fill(key, area, at, turn)))
251
+ return drawWith(table, () => rowsNow(area, at, turn), markdownIn(table, at))
250
252
  }
251
253
 
252
- const rows = (area: Area, columns: number): RenderElement[] => {
253
- const started = keysIn(area).flatMap((key) => fill(key, area, columns, undefined) ?? [])
254
+ const rows = (area: Area, at: StyledAt): RenderElement[] => {
255
+ const started = keysIn(area).flatMap((key) => fill(key, area, at, undefined) ?? [])
254
256
  if (started.length > 0) void Promise.all(started).then(redraw)
255
- return rowsNow(area, columns, undefined)
257
+ return rowsNow(area, at, undefined)
256
258
  }
257
259
 
258
260
  const column = (table: ElementTable, children: readonly RenderElement[]) => drawWith(table, () => Box({ flexDirection: 'column', children }))
@@ -281,7 +283,7 @@ export function serveWidgets({
281
283
  if (listing === undefined && redraw !== true) return
282
284
  parts.forget(mod)
283
285
  if (listing !== undefined) {
284
- const listed = declarationsOf(listing)
286
+ const listed = widgetsOf(listing)
285
287
  const isNewList = JSON.stringify(listed) !== JSON.stringify(declared.get(mod) ?? [])
286
288
  declared.set(mod, listed)
287
289
  if (isNewList) return place()
@@ -8,7 +8,7 @@ import { ToolResult } from './context/turn/message/tool-result.js'
8
8
  import { TurnEnd, TurnStart, type Turn } from './context/turn/turn.js'
9
9
  import { GoalChange } from './goal/goal.js'
10
10
  import { Task, TaskEnd, TaskStart, type TaskStatus } from './goal/task.js'
11
- import type { UsageChange, Usage } from './session.js'
11
+ import type { Session, UsageChange, Usage } from './session.js'
12
12
 
13
13
  export type SessionData = {
14
14
  readonly id: string
@@ -22,6 +22,12 @@ export type SessionData = {
22
22
  readonly forkedFrom?: string
23
23
  readonly isRunning: boolean
24
24
  readonly agentType?: string
25
+ readonly visitedAt?: string
26
+ readonly device?: Pick<Device, 'id' | 'name'> | undefined
27
+ readonly status?: Session['status']
28
+ readonly waitingFor?: Session['waitingFor']
29
+ readonly contextPercent?: number
30
+ readonly lastTurn?: Session['lastTurn']
25
31
  }
26
32
 
27
33
  export type ContextData = Pick<Context, 'number' | 'openedAt' | 'closedAt' | 'task'>
@@ -2,6 +2,7 @@ import type { Subscription } from '../utils/subscription.js'
2
2
  import type { Matcher } from '../utils/matcher.js'
3
3
  import type { Sender } from './context/turn/message/sender.js'
4
4
  import type { Context, ContextEnd, ContextStart } from './context/context.js'
5
+ import type { Device } from './context/turn/device.js'
5
6
  import type { AttachedFile } from './context/turn/message/attached-file.js'
6
7
  import type { InstructionFile } from './context/turn/message/instruction-file.js'
7
8
  import type { Message, MessageType } from './context/turn/message/message.js'
@@ -72,7 +73,9 @@ export type Usage = {
72
73
 
73
74
  export type RateLimit = { readonly type: string; readonly percent: number; readonly resetsAt?: string }
74
75
 
75
- export type Surface = 'terminal' | 'desktop' | 'mobile' | 'vscode'
76
+ export const surfaces = ['terminal', 'desktop', 'mobile', 'vscode', 'browser', 'herdr'] as const
77
+
78
+ export type Surface = (typeof surfaces)[number]
76
79
 
77
80
  export const sessionEvents = {
78
81
  Message: 'message',
@@ -146,6 +149,7 @@ export type TaskStartArgs = {
146
149
  readonly name?: string
147
150
  readonly cwd?: string
148
151
  readonly isBackground?: boolean
152
+ readonly device?: string
149
153
  }
150
154
 
151
155
  export type ToolCallArgs = {
@@ -153,7 +157,7 @@ export type ToolCallArgs = {
153
157
  readonly input: Readonly<Record<string, unknown>>
154
158
  }
155
159
 
156
- export type Session = RecordPart & {
160
+ export type Session = Pick<RecordPart, 'search'> & {
157
161
  readonly id: string
158
162
  readonly title: string
159
163
  readonly color?: string
@@ -165,6 +169,12 @@ export type Session = RecordPart & {
165
169
  readonly startedAt: string
166
170
  readonly lastAt: string
167
171
  readonly forkedFrom?: string
172
+ readonly visitedAt?: string
173
+ readonly device?: Pick<Device, 'id' | 'name'>
174
+ readonly status?: 'busy' | 'shell' | 'idle' | 'waiting'
175
+ readonly waitingFor?: { readonly dialog: string; readonly tool?: string; readonly input?: Readonly<Record<string, unknown>>; readonly question?: string }
176
+ readonly contextPercent?: number
177
+ readonly lastTurn?: { readonly reason: 'answered' | 'stopped' | 'failed'; readonly at: string; readonly failure?: string }
168
178
  readonly goal: Goal
169
179
  context(): Promise<Context>
170
180
  contexts(): Promise<Context[]>
@@ -173,14 +183,18 @@ export type Session = RecordPart & {
173
183
  messages(options?: { readonly after?: string; readonly last?: number }): Promise<Message[]>
174
184
  send(message: SessionSend): Promise<void>
175
185
  startTask(task: TaskStartArgs): Promise<Task>
176
- fork(task: Pick<TaskStartArgs, 'prompt' | 'title'>): Promise<Task>
177
- clone(task: Pick<TaskStartArgs, 'prompt' | 'title'>): Promise<Task>
186
+ fork(task: ForkArgs): Promise<Task>
178
187
  callTool(call: ToolCallArgs): Promise<ToolResult>
179
188
  usage(): Promise<Usage>
180
189
  surfaces(): Promise<Surface[]>
190
+ end(): Promise<void>
191
+ visit(at?: string): Promise<void>
192
+ delete(): Promise<void>
181
193
  }
182
194
 
183
- export type TaskOwner = Omit<Session, 'startTask' | 'callTool' | 'fork' | 'clone'>
195
+ export type ForkArgs = Pick<TaskStartArgs, 'prompt' | 'title' | 'isBackground'> & { readonly at?: string }
196
+
197
+ export type TaskOwner = Omit<Session, 'startTask' | 'callTool' | 'fork' | 'delete'> & OnMethods & BeforeMethods
184
198
 
185
199
  type ProcessEvent = { readonly on: string; readonly before?: string }
186
200
 
@@ -337,7 +351,7 @@ export type ProcessOnMethods = { readonly [Name in ProcessName as `on${Name}`]:
337
351
 
338
352
  export type ProcessBeforeMethods = { readonly [Name in keyof ProcessAnswer as `before${Name}`]: BeforeMethod<ProcessAsked[Name], ProcessAnswer[Name]> }
339
353
 
340
- export type CurrentSession = Omit<Session, 'goal'> & ProcessOnMethods & ProcessBeforeMethods & {
354
+ export type CurrentSession = Omit<Session, 'goal'> & OnMethods & BeforeMethods & ProcessOnMethods & ProcessBeforeMethods & {
341
355
  readonly goal: Goal & Pick<ProcessBeforeMethods, 'beforeSessionStart'>
342
356
  scrollTo(message: Message, options?: { readonly block?: 'start' | 'center' | 'end' | 'nearest' }): Promise<void>
343
357
  caption(toolCall: Message & { readonly type: typeof ToolCall }, text: string | undefined): void
@@ -351,8 +365,9 @@ export type SessionScope = {
351
365
 
352
366
  export type SearchOptions = SessionScope & { readonly before?: Pick<Message, 'session' | 'id'> }
353
367
 
354
- export type Sessions = OnMethods & {
368
+ export type Sessions = {
355
369
  readonly current: CurrentSession
356
370
  list(options?: SessionScope): Promise<Session[]>
371
+ get(id: string): Promise<Session>
357
372
  search(text: string, matcher?: Matcher<Message>, options?: SearchOptions): AsyncIterable<Message>
358
373
  }
@@ -7,6 +7,8 @@ import { partMethods } from '../runtime/ui.js'
7
7
  import { untagged } from '../session/context/turn/message/note.js'
8
8
  import { elements } from './fake-elements.js'
9
9
  import { fakeFiles } from './fake-files.js'
10
+ import { fakeServe, type FakeServe } from './fake-serve.js'
11
+ import type { SessionComputer } from '../runtime/interfaces.js'
10
12
 
11
13
  export type TestCall = {
12
14
  readonly call: string
@@ -29,9 +31,10 @@ export type Fakes = {
29
31
  cmod: { call?: Claude['cmod']['call'] }
30
32
  tool: { call?: Claude['tool']['call'] }
31
33
  device: { read?: Claude['device']['read'] }
34
+ serve: Partial<SessionComputer>
32
35
  }
33
36
 
34
- const testDevice: Device = { id: '5f0e8c2a9b7d4e31a6c4d2b0e8f71a93', name: 'test-computer', os: 'linux', arch: 'x64' }
37
+ export const testDevice: Device = { id: '5f0e8c2a9b7d4e31a6c4d2b0e8f71a93', name: 'test-computer', os: 'linux', arch: 'x64' }
35
38
 
36
39
  export type ShownSchedule = { readonly id: string; readonly cron: string; readonly prompt: string }
37
40
 
@@ -52,6 +55,7 @@ export type FakeClaude = {
52
55
  readonly fakes: Fakes
53
56
  readonly shown: Shown
54
57
  readonly store: Map<string, unknown>
58
+ readonly serve: FakeServe
55
59
  settle(): Promise<void>
56
60
  placePane(id: string): void
57
61
  }
@@ -63,12 +67,18 @@ export function calledAnswer(caller: string, answer: EventResult<'cmod.call'>):
63
67
 
64
68
  export function fakeClaude(plugin: { readonly name: string; readonly root: string }): FakeClaude {
65
69
  const calls: TestCall[] = []
66
- const fakes: Fakes = { process: {}, fs: {}, http: {}, settings: {}, config: {}, command: {}, ui: {}, session: {}, prompt: {}, model: {}, agent: {}, clock: {}, cmod: {}, tool: {}, device: {} }
70
+ const fakes: Fakes = { process: {}, fs: {}, http: {}, settings: {}, config: {}, command: {}, ui: {}, session: {}, prompt: {}, model: {}, agent: {}, clock: {}, cmod: {}, tool: {}, device: {}, serve: {} }
67
71
  const emptyDisk = fakeFiles({})
68
72
  const shown: Shown = { notes: [], prompts: [], logs: [], debug: [], openPanes: new Set(), commands: [], tools: [], schedules: [] }
69
73
  const unplacedPanes = new Set<string>()
70
74
  let focusedPane: string | undefined
71
75
  const store = new Map<string, unknown>()
76
+ const serve = fakeServe(() => fakes.serve, {
77
+ device: async () => {
78
+ const { id, name } = await (fakes.device.read ?? (async () => testDevice))()
79
+ return { id, name }
80
+ },
81
+ })
72
82
 
73
83
  const faked = <Args extends readonly unknown[], Result>(call: string, answer: () => ((...args: Args) => Result) | undefined) => {
74
84
  return (...args: Args): Result => {
@@ -86,6 +96,8 @@ export function fakeClaude(plugin: { readonly name: string; readonly root: strin
86
96
  }
87
97
 
88
98
  const cmodCall = rejected('cmod.call', () => fakes.cmod.call ?? cmodTakesParts)
99
+ const fetchFake = rejected('http.fetch', () => fakes.http.fetch)
100
+ const spawnFake = faked('process.spawn', () => fakes.process.spawn)
89
101
 
90
102
  const clonedAsClaudeCodeDoes = <Args,>(args: Args): Args => {
91
103
  try {
@@ -167,7 +179,7 @@ export function fakeClaude(plugin: { readonly name: string; readonly root: strin
167
179
  },
168
180
  process: {
169
181
  run: rejected('process.run', () => fakes.process.run),
170
- spawn: faked('process.spawn', () => fakes.process.spawn),
182
+ spawn: (request) => (isServeHolder(request.argv) ? servedHolder(request.argv[0] ?? '') : spawnFake(request)),
171
183
  },
172
184
  fs: {
173
185
  read: rejected('fs.read', () => fakes.fs.read ?? emptyDisk.read),
@@ -176,7 +188,12 @@ export function fakeClaude(plugin: { readonly name: string; readonly root: strin
176
188
  exists: rejected('fs.exists', () => fakes.fs.exists ?? emptyDisk.exists),
177
189
  stat: rejected('fs.stat', () => fakes.fs.stat ?? emptyDisk.stat),
178
190
  },
179
- http: { fetch: rejected('http.fetch', () => fakes.http.fetch) },
191
+ http: {
192
+ fetch: async (url, init) => {
193
+ if (fakes.http.fetch === undefined && init?.socketPath?.endsWith('/serve.sock') === true) return serve.fetch(url, init)
194
+ return fetchFake(url, init)
195
+ },
196
+ },
180
197
  settings: { read: rejected('settings.read', () => fakes.settings.read ?? (async () => ({}))) },
181
198
  config: {
182
199
  list: rejected('config.list', () => fakes.config.list ?? (async () => [])),
@@ -234,6 +251,7 @@ export function fakeClaude(plugin: { readonly name: string; readonly root: strin
234
251
  env: {
235
252
  home: async () => '/test/home',
236
253
  dataHome: async () => undefined,
254
+ cacheHome: async () => undefined,
237
255
  configHome: async () => undefined,
238
256
  browser: async () => undefined,
239
257
  sshConnection: async () => undefined,
@@ -247,21 +265,34 @@ export function fakeClaude(plugin: { readonly name: string; readonly root: strin
247
265
  const settle = async () => {
248
266
  let seen: number
249
267
  do {
250
- seen = calls.length
268
+ seen = calls.length + serve.requests
251
269
  await new Promise<void>((resolve) => setTimeout(resolve, 0))
252
- } while (calls.length !== seen)
270
+ } while (calls.length + serve.requests !== seen)
253
271
  }
254
272
 
255
273
  const placePane = (id: string) => {
256
274
  if (unplacedPanes.delete(id)) shown.openPanes.add(id)
257
275
  }
258
276
 
259
- return { claude, calls, fakes, shown, store, settle, placePane }
277
+ return { claude, calls, fakes, shown, store, serve, settle, placePane }
260
278
  }
261
279
 
262
280
  declare function setTimeout(fn: () => void, ms: number): unknown
263
281
  declare function clearTimeout(timeout: unknown): void
264
282
 
283
+ function isServeHolder(argv: readonly string[]): boolean {
284
+ return argv[1] === 'program' && argv[2] === cmodPluginName && argv.at(-2) === cmodPluginName && argv.at(-1) === 'serve'
285
+ }
286
+
287
+ function servedHolder(program: string): ReturnType<Claude['process']['spawn']> {
288
+ const store = program.slice(0, program.lastIndexOf('/programs/'))
289
+ return (async function* () {
290
+ yield { stream: 'stdout' as const, text: `unix:${store}/serve.sock\n` }
291
+ await new Promise<never>(() => undefined)
292
+ return { code: 0, signal: null }
293
+ })() as never
294
+ }
295
+
265
296
  function realTimer(ms: number, fn: () => void): Timer {
266
297
  const timeout = setTimeout(fn, ms)
267
298
  return { cancel: () => clearTimeout(timeout) }
@@ -0,0 +1,144 @@
1
+ import type { HttpInit, HttpResponse } from 'claude-code'
2
+ import type { Claude } from '../runtime/claude.js'
3
+ import { devicesInterface, interfaceListeners, providerActs, routeSessions, serveProviders, type Implementation, type ProgramReach, type Provided, type ProvidedHeard, type ProviderIdentity, type ServedProviders, type SessionComputer, type SessionRouting } from '../runtime/interfaces.js'
4
+ import { addressCall, connectRpc, RpcError, rpcCodes, type RpcClient } from '../runtime/rpc.js'
5
+ import type { Device } from '../session/context/turn/device.js'
6
+
7
+ type Here = Pick<Device, 'id' | 'name'>
8
+
9
+ export type ServeConnection = {
10
+ readonly provider?: ProviderIdentity
11
+ readonly tell?: (caller: string, heard: ProvidedHeard, signal: AbortSignal) => Promise<unknown>
12
+ readonly sessionCode?: (name: string) => readonly string[]
13
+ readonly device?: () => Promise<Here>
14
+ readonly after: Claude['clock']['after']
15
+ readonly report: (error: unknown) => void
16
+ }
17
+
18
+ export type FakeProgram = { readonly name: string; readonly mod: string; readonly program: string; readonly device?: Here; readonly methods: Implementation }
19
+
20
+ export type FakeServe = {
21
+ readonly routing: SessionRouting
22
+ readonly requests: number
23
+ fetch(url: string, init?: HttpInit): Promise<HttpResponse>
24
+ connect(connection: ServeConnection): ServedProviders
25
+ provide(programs: readonly FakeProgram[], connection: Pick<ServeConnection, 'after' | 'report'>): Promise<Provided[]>
26
+ close(): void
27
+ }
28
+
29
+ export type ServeClock = { now(): number; after(ms: number, run: () => void): unknown }
30
+
31
+ declare function setTimeout(run: () => void, ms: number): unknown
32
+
33
+ const realClock: ServeClock = { now: () => Date.now(), after: (ms, run) => setTimeout(run, ms) }
34
+
35
+ const wait = (ms: number) => new Promise<void>((resolve) => void setTimeout(resolve, ms))
36
+
37
+ const notHere = (session: string) => new RpcError(rpcCodes.notHeld, `No session ${session} on this computer.`)
38
+
39
+ const unfaked: SessionComputer = {
40
+ sessions: () => [],
41
+ search: () => [],
42
+ read: (_session, part) => (part === 'goal' ? { text: '' } : part === 'state' ? null : []),
43
+ unheld: (session) => Promise.reject(notHere(session)),
44
+ visit: async () => undefined,
45
+ remove: async () => undefined,
46
+ }
47
+
48
+ const deviceLink: ProviderIdentity = { mod: 'testMod', program: 'devices' }
49
+
50
+ const socketOf = (device: string) => `/test/devices/${device}/serve.sock`
51
+
52
+ export function fakeServe(
53
+ fakes: () => Partial<SessionComputer>,
54
+ { device, programs, clock = realClock }: { readonly device: () => Promise<Here>; readonly programs?: ProgramReach; readonly clock?: ServeClock },
55
+ ): FakeServe {
56
+ const answer = <Key extends keyof SessionComputer>(key: Key): SessionComputer[Key] => (fakes()[key] ?? unfaked[key])
57
+ const linked = new Map<string, FakeServe>()
58
+ let requests = 0
59
+ const routing = routeSessions({
60
+ device,
61
+ programs: {
62
+ store: programs?.store ?? '/test/store',
63
+ files: programs?.files ?? { list: async () => [], read: async () => undefined },
64
+ fetch: (url, init) => linked.get(init.socketPath ?? '')?.fetch(url, init) ?? programs?.fetch(url, init) ?? Promise.resolve({ status: 404, text: '' }),
65
+ wait: programs?.wait ?? wait,
66
+ },
67
+ now: () => clock.now(),
68
+ after: (ms, run) => clock.after(ms, run),
69
+ report: (error) => {
70
+ throw error
71
+ },
72
+ computer: {
73
+ sessions: (...args) => answer('sessions')(...args),
74
+ search: (...args) => answer('search')(...args),
75
+ read: (...args) => answer('read')(...args),
76
+ unheld: (...args) => answer('unheld')(...args),
77
+ visit: (...args) => answer('visit')(...args),
78
+ remove: (...args) => answer('remove')(...args),
79
+ },
80
+ })
81
+ const serve: FakeServe = {
82
+ routing,
83
+ get requests() {
84
+ return requests + [...linked.values()].reduce((sum, each) => sum + each.requests, 0)
85
+ },
86
+ async fetch(url, init = {}) {
87
+ requests += 1
88
+ const answered = await routing.routes.route({ method: init.method ?? 'GET', path: new URL(url).pathname, signal: new AbortController().signal, json: async () => JSON.parse(String(init.body)) as unknown })
89
+ if (answered === undefined) return { status: 404, ok: false, headers: {}, text: '' }
90
+ return { status: answered.status, ok: answered.status >= 200 && answered.status < 300, headers: {}, text: answered.json === undefined ? '' : JSON.stringify(answered.json) }
91
+ },
92
+ connect: (connection) => connectTo(serve, connection).served,
93
+ async provide(given, connection) {
94
+ if (given.length === 0) return []
95
+ const here = await device()
96
+ const others = new Map(given.flatMap(({ device: on }) => (on === undefined || on.id === here.id ? [] : [[on.id, on] as const])))
97
+ for (const on of others.values()) if (!linked.has(socketOf(on.id))) linked.set(socketOf(on.id), fakeServe(() => ({}), { device: async () => on, clock }))
98
+ const provided = await Promise.all(
99
+ given.map(async ({ name, mod, program, device: on, methods }) => {
100
+ const { client, served } = connectTo((on === undefined ? undefined : linked.get(socketOf(on.id))) ?? serve, { ...connection, provider: { mod, program } })
101
+ const each = served.provide(name, methods)
102
+ await client.request(providerActs.providers, { interface: name })
103
+ return each
104
+ }),
105
+ )
106
+ if (others.size === 0) return provided
107
+ const { client, served } = connectTo(serve, { ...connection, provider: deviceLink })
108
+ served.provide(devicesInterface, {
109
+ devices: () => [...others.values()].map(({ id, name }) => ({ id, name, address: socketOf(id) })),
110
+ send: (to: string) => {
111
+ throw new Error(`The test kit reaches device ${to} at its address, so it carries no message.`)
112
+ },
113
+ })
114
+ await client.request(providerActs.providers, { interface: devicesInterface })
115
+ return provided
116
+ },
117
+ close: () => {
118
+ routing.close()
119
+ for (const each of linked.values()) each.close()
120
+ },
121
+ }
122
+ return serve
123
+ }
124
+
125
+ function connectTo(serve: Pick<FakeServe, 'fetch'>, { provider, tell = async () => null, sessionCode = () => [], device, after, report }: ServeConnection): { readonly client: RpcClient; readonly served: ServedProviders } {
126
+ const listeners = interfaceListeners({ report })
127
+ const client = connectRpc({
128
+ call: addressCall((url, init) => serve.fetch(url, init), 'unix:/test/serve.sock'),
129
+ handle: async (method, params, signal) => {
130
+ const answered = await listeners.handler(method, params, signal)
131
+ if (answered !== undefined) return answered.result
132
+ const provided = served.handler(method, params, signal)
133
+ if (provided !== undefined) return provided
134
+ throw new RpcError(rpcCodes.methodNotFound, `This connection to cmod serve answers no ${method}.`)
135
+ },
136
+ onConnect: async (connected) => {
137
+ await served.replay()
138
+ await listeners.replay(connected)
139
+ },
140
+ wait,
141
+ })
142
+ const served = serveProviders({ serve: client, listeners, ...(provider === undefined ? {} : { provider }), tell, sessionCode, ...(device === undefined ? {} : { device }), after, report })
143
+ return { client, served }
144
+ }