@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,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
@@ -23,6 +23,11 @@ export type SessionData = {
23
23
  readonly isRunning: boolean
24
24
  readonly agentType?: string
25
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']
26
31
  }
27
32
 
28
33
  export type ContextData = Pick<Context, 'number' | 'openedAt' | 'closedAt' | 'task'>
@@ -31,7 +36,7 @@ export type TurnData = Pick<Turn, 'prompt' | 'context' | 'openedAt' | 'closedAt'
31
36
 
32
37
  export type TurnEnding = Pick<Turn, 'answer' | 'reason' | 'failure'>
33
38
 
34
- export type TaskData = Pick<Task, 'id' | 'title' | 'openedBy' | 'openedAt' | 'closedAt' | 'status' | 'name' | 'spawnedBy' | 'isBackground'> & { readonly agentType?: string; readonly model?: string; readonly parent?: string; readonly machine?: string; readonly forkedFrom?: string }
39
+ export type TaskData = Pick<Task, 'id' | 'title' | 'openedBy' | 'openedAt' | 'closedAt' | 'status' | 'name' | 'spawnedBy' | 'isBackground'> & { readonly agentType?: string; readonly model?: string; readonly parent?: string; readonly forkedFrom?: string }
35
40
 
36
41
  export const forkAgentType = 'fork'
37
42
 
@@ -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,7 +149,7 @@ export type TaskStartArgs = {
146
149
  readonly name?: string
147
150
  readonly cwd?: string
148
151
  readonly isBackground?: boolean
149
- readonly machine?: string
152
+ readonly device?: string
150
153
  }
151
154
 
152
155
  export type ToolCallArgs = {
@@ -154,7 +157,7 @@ export type ToolCallArgs = {
154
157
  readonly input: Readonly<Record<string, unknown>>
155
158
  }
156
159
 
157
- export type Session = RecordPart & {
160
+ export type Session = Pick<RecordPart, 'search'> & {
158
161
  readonly id: string
159
162
  readonly title: string
160
163
  readonly color?: string
@@ -167,6 +170,11 @@ export type Session = RecordPart & {
167
170
  readonly lastAt: string
168
171
  readonly forkedFrom?: string
169
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 }
170
178
  readonly goal: Goal
171
179
  context(): Promise<Context>
172
180
  contexts(): Promise<Context[]>
@@ -186,7 +194,7 @@ export type Session = RecordPart & {
186
194
 
187
195
  export type ForkArgs = Pick<TaskStartArgs, 'prompt' | 'title' | 'isBackground'> & { readonly at?: string }
188
196
 
189
- export type TaskOwner = Omit<Session, 'startTask' | 'callTool' | 'fork' | 'delete'>
197
+ export type TaskOwner = Omit<Session, 'startTask' | 'callTool' | 'fork' | 'delete'> & OnMethods & BeforeMethods
190
198
 
191
199
  type ProcessEvent = { readonly on: string; readonly before?: string }
192
200
 
@@ -343,7 +351,7 @@ export type ProcessOnMethods = { readonly [Name in ProcessName as `on${Name}`]:
343
351
 
344
352
  export type ProcessBeforeMethods = { readonly [Name in keyof ProcessAnswer as `before${Name}`]: BeforeMethod<ProcessAsked[Name], ProcessAnswer[Name]> }
345
353
 
346
- export type CurrentSession = Omit<Session, 'goal'> & ProcessOnMethods & ProcessBeforeMethods & {
354
+ export type CurrentSession = Omit<Session, 'goal'> & OnMethods & BeforeMethods & ProcessOnMethods & ProcessBeforeMethods & {
347
355
  readonly goal: Goal & Pick<ProcessBeforeMethods, 'beforeSessionStart'>
348
356
  scrollTo(message: Message, options?: { readonly block?: 'start' | 'center' | 'end' | 'nearest' }): Promise<void>
349
357
  caption(toolCall: Message & { readonly type: typeof ToolCall }, text: string | undefined): void
@@ -357,7 +365,7 @@ export type SessionScope = {
357
365
 
358
366
  export type SearchOptions = SessionScope & { readonly before?: Pick<Message, 'session' | 'id'> }
359
367
 
360
- export type Sessions = OnMethods & {
368
+ export type Sessions = {
361
369
  readonly current: CurrentSession
362
370
  list(options?: SessionScope): Promise<Session[]>
363
371
  get(id: string): Promise<Session>
@@ -34,7 +34,7 @@ export type Fakes = {
34
34
  serve: Partial<SessionComputer>
35
35
  }
36
36
 
37
- 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' }
38
38
 
39
39
  export type ShownSchedule = { readonly id: string; readonly cron: string; readonly prompt: string }
40
40
 
@@ -73,7 +73,12 @@ export function fakeClaude(plugin: { readonly name: string; readonly root: strin
73
73
  const unplacedPanes = new Set<string>()
74
74
  let focusedPane: string | undefined
75
75
  const store = new Map<string, unknown>()
76
- const serve = fakeServe(() => fakes.serve)
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
+ })
77
82
 
78
83
  const faked = <Args extends readonly unknown[], Result>(call: string, answer: () => ((...args: Args) => Result) | undefined) => {
79
84
  return (...args: Args): Result => {
@@ -246,6 +251,7 @@ export function fakeClaude(plugin: { readonly name: string; readonly root: strin
246
251
  env: {
247
252
  home: async () => '/test/home',
248
253
  dataHome: async () => undefined,
254
+ cacheHome: async () => undefined,
249
255
  configHome: async () => undefined,
250
256
  browser: async () => undefined,
251
257
  sshConnection: async () => undefined,
@@ -259,9 +265,9 @@ export function fakeClaude(plugin: { readonly name: string; readonly root: strin
259
265
  const settle = async () => {
260
266
  let seen: number
261
267
  do {
262
- seen = calls.length
268
+ seen = calls.length + serve.requests
263
269
  await new Promise<void>((resolve) => setTimeout(resolve, 0))
264
- } while (calls.length !== seen)
270
+ } while (calls.length + serve.requests !== seen)
265
271
  }
266
272
 
267
273
  const placePane = (id: string) => {
@@ -1,13 +1,39 @@
1
1
  import type { HttpInit, HttpResponse } from 'claude-code'
2
- import { routeSessions, type SessionComputer, type SessionRouting } from '../runtime/interfaces.js'
3
- import { RpcError, rpcCodes } from '../runtime/rpc.js'
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 }
4
19
 
5
20
  export type FakeServe = {
6
21
  readonly routing: SessionRouting
22
+ readonly requests: number
7
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[]>
8
26
  close(): void
9
27
  }
10
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
+
11
37
  const notHere = (session: string) => new RpcError(rpcCodes.notHeld, `No session ${session} on this computer.`)
12
38
 
13
39
  const unfaked: SessionComputer = {
@@ -19,10 +45,30 @@ const unfaked: SessionComputer = {
19
45
  remove: async () => undefined,
20
46
  }
21
47
 
22
- export function fakeServe(fakes: () => Partial<SessionComputer>): FakeServe {
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 {
23
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
24
59
  const routing = routeSessions({
25
- now: () => new Date().getTime(),
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
+ },
26
72
  computer: {
27
73
  sessions: (...args) => answer('sessions')(...args),
28
74
  search: (...args) => answer('search')(...args),
@@ -32,13 +78,67 @@ export function fakeServe(fakes: () => Partial<SessionComputer>): FakeServe {
32
78
  remove: (...args) => answer('remove')(...args),
33
79
  },
34
80
  })
35
- return {
81
+ const serve: FakeServe = {
36
82
  routing,
83
+ get requests() {
84
+ return requests + [...linked.values()].reduce((sum, each) => sum + each.requests, 0)
85
+ },
37
86
  async fetch(url, init = {}) {
87
+ requests += 1
38
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 })
39
89
  if (answered === undefined) return { status: 404, ok: false, headers: {}, text: '' }
40
90
  return { status: answered.status, ok: answered.status >= 200 && answered.status < 300, headers: {}, text: answered.json === undefined ? '' : JSON.stringify(answered.json) }
41
91
  },
42
- close: () => routing.close(),
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
+ },
43
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 }
44
144
  }
@@ -15,7 +15,8 @@ import { ToolResult } from '../session/context/turn/message/tool-result.js'
15
15
  import { createConversation, emptyConversation, searchLimit, tasksWithAgents, type ContextData, type Conversation, type SessionChange, type SessionData, type TaskData, type TurnData, type TurnEnding } from '../session/conversation.js'
16
16
  import type { Decide, Place } from '../runtime/before.js'
17
17
  import type { Claude } from '../runtime/claude.js'
18
- import { conversationMethods, everySession, isHeardBy, resultOf, type Listened, type SessionColor } from '../runtime/sessions.js'
18
+ import { testDevice } from './fake-claude.js'
19
+ import { conversationMethods, isHeardBy, resultOf, type Listened, type SessionColor } from '../runtime/sessions.js'
19
20
  import { receivedMatcher } from '../utils/matcher.js'
20
21
  import { firstLine, messageOf } from '../utils/text.js'
21
22
 
@@ -78,7 +79,7 @@ export function fakeSessions({ project, cwd, given, push, callTool, listAgents,
78
79
  const now = () => new Date((clock += 1000)).toISOString()
79
80
 
80
81
  const keep = (data: SessionData): Kept => {
81
- const session: Kept = { data, conversation: createConversation(emptyConversation(data.id)), messages: [], turns: new Map(), contexts: new Map(), tasks: new Map() }
82
+ const session: Kept = { data: { device: { id: testDevice.id, name: testDevice.name }, ...data }, conversation: createConversation(emptyConversation(data.id)), messages: [], turns: new Map(), contexts: new Map(), tasks: new Map() }
82
83
  kept.set(data.id, session)
83
84
  return session
84
85
  }
@@ -91,7 +92,7 @@ export function fakeSessions({ project, cwd, given, push, callTool, listAgents,
91
92
  if ('task' in change) session.tasks.set(change.task.id, change.task)
92
93
  session.data = { ...session.data, lastAt: change.type === Message ? change.message.at : session.data.lastAt, ...(session.data.title === '' && change.type === Message && change.message.type === Prompt && change.message.from.type === Person ? { title: firstLine(change.message.text) } : {}) }
93
94
  for (const [mod, sessions] of heard) {
94
- if ([...(sessions.get(session.data.id) ?? []), ...(sessions.get(everySession) ?? [])].some(({ event, matcher }) => isHeardBy(event, matcher, change))) push(mod, session.data.id, change)
95
+ if ((sessions.get(session.data.id) ?? []).some(({ event, matcher }) => isHeardBy(event, matcher, change))) push(mod, session.data.id, change)
95
96
  }
96
97
  }
97
98
  }
@@ -131,7 +132,7 @@ export function fakeSessions({ project, cwd, given, push, callTool, listAgents,
131
132
  return { session, context, contextOpenedAt, ...(turn === undefined ? {} : { turn }), tasks, taskTurns, ...(openCalls === undefined ? {} : { openCalls }) }
132
133
  }
133
134
 
134
- const wantsBefore = (mod: string, event: string) => [current, everySession].some((target) => (watches.get(mod)?.get(target) ?? []).includes(event))
135
+ const wantsBefore = (mod: string, event: string) => (watches.get(mod)?.get(current) ?? []).includes(event)
135
136
 
136
137
  const taskOf = (session: Kept, id: string) => {
137
138
  const task = session.tasks.get(id)
@@ -160,7 +161,7 @@ export function fakeSessions({ project, cwd, given, push, callTool, listAgents,
160
161
  [conversationMethods.session]: (request) => sessionOf(String(request['session'])).data,
161
162
  [conversationMethods.search](request) {
162
163
  const text = String(request['text'])
163
- if ([...text].length < 3) throw new Error('cmod history search takes at least 3 characters.')
164
+ if ([...text].length < 3) throw new Error('cmod sessions search takes at least 3 characters.')
164
165
  const inRecord = (message: Message) => {
165
166
  const session = kept.get(message.session)
166
167
  const task = request['task']