@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
@@ -1,7 +1,9 @@
1
- import type { Job } from '../mod.js'
2
- import { instancePath, storeFolder } from '../records.js'
1
+ import type { InterfaceName, InterfaceProvider, Job } from '../mod.js'
2
+ import { instancePath, processTypes, type ProcessType } from '../records.js'
3
+ import { cmodPluginName, isUnanswered } from '../runtime/dependencies.js'
3
4
  import { engineOf } from '../runtime/engine.js'
4
- import { isHeld } from '../runtime/programs.js'
5
+ import { interfaceMethods, type ProviderIdentity } from '../runtime/interfaces.js'
6
+ import { cmodStore, isHeld } from '../runtime/programs.js'
5
7
  import { ifMissing } from '../utils/paths.js'
6
8
  import { messageOf } from '../utils/text.js'
7
9
  import { basename } from '../vendor.js'
@@ -9,6 +11,7 @@ import { basename } from '../vendor.js'
9
11
  export type Program = {
10
12
  readonly state: 'stopped' | 'starting' | 'running' | 'backoff' | 'fatal'
11
13
  ready(): Promise<{ url: string; socketPath?: string; tailnetUrl?: string }>
14
+ provider<Name extends InterfaceName>(name: Name): Promise<InterfaceProvider<Name>>
12
15
  }
13
16
 
14
17
  type Address = Awaited<ReturnType<Program['ready']>>
@@ -21,35 +24,46 @@ const staleMs = 15_000
21
24
 
22
25
  const retryWithinMs = 1000
23
26
 
24
- export function program(options: { readonly command: readonly string[]; readonly environment?: Record<string, string>; readonly singleInstance?: boolean; readonly isService?: boolean; readonly isWebApp?: boolean }): Job<Program> {
25
- const { command, environment, singleInstance = false, isService = false, isWebApp = false } = options
27
+ export function program(options: {
28
+ readonly command: readonly string[]
29
+ readonly environment?: Record<string, string>
30
+ readonly singleInstance?: boolean
31
+ readonly isService?: boolean
32
+ readonly isWebApp?: boolean
33
+ readonly processType?: ProcessType
34
+ }): Job<Program> {
35
+ const { command, environment, singleInstance = false, isService = false, isWebApp = false, processType } = options
26
36
  return ({ mod, announce, reserveName }) => {
27
- const { claude, report, spawnCmod, isInstalledCopy, watches } = engineOf(mod)
37
+ const { claude, report, spawnCmod, isInstalledCopy, watches, interfaces } = engineOf(mod)
28
38
  const [executable] = command
29
39
  if (executable === undefined) throw new Error(`${mod.name}: the program has no command. Name the program on PATH and its arguments, such as ['preview-server', '--port', '0'].`)
30
40
  if (isService) for (const type of ['program', 'service']) reserveName(type, basename(executable), `${mod.name}: the service ${executable} is already added. Give each isService program its own executable.`)
31
41
  else if (singleInstance) reserveName('program', basename(executable), `${mod.name}: the single instance of ${executable} is already added. Give each singleInstance program its own executable.`)
32
42
  const isElected = singleInstance || isService
33
43
  if (isWebApp && !isElected) throw new Error(`${mod.name}: the web app ${executable} runs a copy per session, and your tailnet reaches one copy per computer. Add singleInstance: true or isService: true.`)
34
- const webApp = isWebApp ? ['--web-app'] : []
35
- const request = { argv: command, ...(environment === undefined ? {} : { env: environment }) }
44
+ if (processType !== undefined && !(processTypes as readonly string[]).includes(processType)) throw new Error(`${mod.name}: ${executable}'s processType is ${String(processType)}. Give ${processTypes.join(' or ')}.`)
45
+ if (processType !== undefined && !isService) throw new Error(`${mod.name}: ${executable}'s processType names the launchd class of a service. Add isService: true.`)
46
+ const holderFlags = isWebApp ? ['--web-app'] : []
47
+ const serviceClass = processType === undefined ? [] : ['--process-type', processType]
48
+ const request = { argv: command, env: { CMOD_DATA: mod.dataFolder, CMOD_CACHE: mod.cacheFolder, ...environment } }
36
49
  let state: Program['state'] = 'stopped'
37
50
  let address: Address | undefined
38
51
  let failure: Error | undefined
39
52
  let exits = 0
40
53
  const waiting: { resolve: (address: Address) => void; reject: (error: Error) => void }[] = []
54
+ const failing = new Set<(error: Error) => void>()
41
55
  let isFollowing = false
42
56
  let isWatching = false
43
57
  let instance: Promise<string> | undefined
44
58
  let leaseCheck: Promise<void> | undefined
45
59
 
46
60
  const spawn = (isOwnService: boolean) => {
47
- if (isOwnService) return spawnCmod(['program', mod.name, ...webApp, '--service', ...Object.keys(environment ?? {}).flatMap((name) => ['--env', name]), '--', ...command], environment)
48
- return isElected ? spawnCmod(['program', mod.name, ...webApp, '--no-wait', '--', ...command], environment) : claude.process.spawn(request)
61
+ if (isOwnService) return spawnCmod(['program', mod.name, ...holderFlags, '--service', ...serviceClass, ...Object.keys(environment ?? {}).flatMap((name) => ['--env', name]), '--', ...command], environment)
62
+ return isElected ? spawnCmod(['program', mod.name, ...holderFlags, '--no-wait', '--', ...command], environment) : claude.process.spawn(request)
49
63
  }
50
64
 
51
65
  const instanceFile = () =>
52
- (instance ??= Promise.all([claude.env.home(), claude.env.dataHome()]).then(([home, dataHome]) => instancePath(storeFolder({ HOME: home, XDG_DATA_HOME: dataHome }), mod.name, basename(executable))))
66
+ (instance ??= cmodStore(claude).then((store) => instancePath(store, mod.name, basename(executable))))
53
67
 
54
68
  const following = (run: Promise<unknown>) => void run.catch((error: unknown) => report({ id: `program:${executable}:follow`, message: `Could not follow the ${executable} program`, error }))
55
69
 
@@ -64,14 +78,34 @@ export function program(options: { readonly command: readonly string[]; readonly
64
78
  }
65
79
  report({ id: `program:${executable}`, message: `The ${executable} program stopped`, description: reason, retry })
66
80
  for (const waiter of waiting.splice(0)) waiter.reject(failure)
81
+ for (const fail of failing) fail(failure)
82
+ failing.clear()
67
83
  }
68
84
 
69
- const recordedAddress = async (file: string): Promise<Address | undefined> => {
85
+ const ownProvider = async (name: string) => {
86
+ const found = (await claude.cmod.call({ to: cmodPluginName, method: interfaceMethods.provider, input: { interface: name, mod: mod.name, program: basename(executable) } })) as ProviderIdentity | null
87
+ if (found === null) return undefined
88
+ return (await interfaces.providers(name)).find((each) => each['mod'] === found.mod && each['program'] === found.program && (each['device'] as ProviderIdentity['device'])?.id === found.device?.id)
89
+ }
90
+
91
+ const providedHere = async (name: string): Promise<unknown> => {
92
+ while (state !== 'fatal') {
93
+ const own = await ownProvider(name).catch((error: unknown) => {
94
+ if (isUnanswered(error)) return undefined
95
+ throw error
96
+ })
97
+ if (own !== undefined) return own
98
+ }
99
+ throw failure
100
+ }
101
+
102
+ const recordedInstance = async (file: string): Promise<{ readonly address?: Address } | undefined> => {
70
103
  const recorded = await claude.fs.read(file).catch(ifMissing(undefined))
71
104
  if (recorded === undefined) return undefined
72
105
  const instance = JSON.parse(recorded) as { readonly address?: unknown; readonly tailnetUrl?: unknown }
73
- const next = addressOf(String(instance.address).trim())
74
- return next !== undefined && typeof instance.tailnetUrl === 'string' ? { ...next, tailnetUrl: instance.tailnetUrl } : next
106
+ const next = typeof instance.address === 'string' ? addressOf(instance.address.trim()) : undefined
107
+ if (next === undefined) return {}
108
+ return { address: typeof instance.tailnetUrl === 'string' ? { ...next, tailnetUrl: instance.tailnetUrl } : next }
75
109
  }
76
110
 
77
111
  const show = (next: Address) => {
@@ -81,6 +115,15 @@ export function program(options: { readonly command: readonly string[]; readonly
81
115
  for (const waiter of waiting.splice(0)) waiter.resolve(next)
82
116
  }
83
117
 
118
+ const noAddress = () => new Error(`${mod.name}: the ${executable} program printed no address, because it only provides interfaces. Reach them through provider(name).`)
119
+
120
+ const started = () => {
121
+ if (state !== 'starting') return
122
+ state = 'running'
123
+ exits = 0
124
+ for (const waiter of waiting.splice(0)) waiter.reject(noAddress())
125
+ }
126
+
84
127
  const checkLease = (file: string) =>
85
128
  (leaseCheck ??= (async () => {
86
129
  if (!isFollowing || (await isHeld(claude, `${file}.lock`, staleMs))) return
@@ -92,8 +135,9 @@ export function program(options: { readonly command: readonly string[]; readonly
92
135
 
93
136
  const track = async (file: string) => {
94
137
  if (!isFollowing) return
95
- const next = await recordedAddress(file)
96
- if (next !== undefined) return show(next)
138
+ const instance = await recordedInstance(file)
139
+ if (instance?.address !== undefined) return show(instance.address)
140
+ if (instance !== undefined) return started()
97
141
  address = undefined
98
142
  state = 'starting'
99
143
  claude.clock.after(Math.random() * retryWithinMs, () => following(checkLease(file)))
@@ -132,13 +176,13 @@ export function program(options: { readonly command: readonly string[]; readonly
132
176
  pending = lines.pop() ?? ''
133
177
  for (const line of lines.slice(0, 1)) {
134
178
  if (isElected && line.trim() === 'held') return await follow(await instanceFile())
179
+ isShown = true
135
180
  const next = addressOf(line.trim())
136
- if (next === undefined) {
181
+ if (isElected && line.trim() === 'provided') started()
182
+ else if (next === undefined) {
137
183
  stop(`its first line is "${line.trim()}". Write 127.0.0.1:<port> or unix:<socket path> as the first line on standard output.`)
138
184
  return
139
- }
140
- show(isWebApp ? ((await recordedAddress(await instanceFile())) ?? next) : next)
141
- isShown = true
185
+ } else show(isWebApp ? ((await recordedInstance(await instanceFile()))?.address ?? next) : next)
142
186
  }
143
187
  }
144
188
  } catch (error) {
@@ -165,11 +209,22 @@ export function program(options: { readonly command: readonly string[]; readonly
165
209
  return state
166
210
  },
167
211
  ready() {
168
- if (state === 'running' && address !== undefined) return Promise.resolve(address)
212
+ if (state === 'running') return address === undefined ? Promise.reject(noAddress()) : Promise.resolve(address)
169
213
  if (state === 'fatal') return Promise.reject(failure)
170
214
  if (state === 'stopped') void start()
171
215
  return new Promise((resolve, reject) => waiting.push({ resolve, reject }))
172
216
  },
217
+ provider<Name extends InterfaceName>(name: Name) {
218
+ if (!isElected) return Promise.reject(new Error(`${mod.name}: provider(${name}) needs the ${executable} program to run as singleInstance or isService, because only one copy of a program can provide an interface.`))
219
+ if (state === 'fatal') return Promise.reject(failure)
220
+ if (state === 'stopped') void start()
221
+ return new Promise<InterfaceProvider<Name>>((resolve, reject) => {
222
+ failing.add(reject)
223
+ void providedHere(name)
224
+ .then((own) => resolve(own as InterfaceProvider<Name>), reject)
225
+ .finally(() => failing.delete(reject))
226
+ })
227
+ },
173
228
  }
174
229
  }
175
230
  }
package/src/mod.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type {
2
2
  AskOptions,
3
3
  CmodDependencies,
4
+ CmodInterfaces,
4
5
  ConfigRow as ClaudeConfigRow,
5
6
  FsStatOptions,
6
7
  HookStream,
@@ -22,9 +23,9 @@ import { checkOptions, type Option, type Options, type OptionValues } from './op
22
23
  import { bound } from './runtime/bound.js'
23
24
  import type { Device } from './session/context/turn/device.js'
24
25
  import { Mod as modSender } from './session/context/turn/message/sender.js'
25
- import { sessionEvents, type BeforeMethod, type CommandRun, type CommandRunAnswer, type OnMethod, type OnMethods, type Sessions } from './session/session.js'
26
+ import type { BeforeMethod, CommandRun, CommandRunAnswer, OnMethod, Sessions } from './session/session.js'
26
27
  import type { Widget, WidgetInit } from './ui/areas.js'
27
- import type { Page, PageInit, Pane, PaneInit } from './ui/panes.js'
28
+ import type { Page, PageInit, Pane, PaneInit, View, ViewInit } from './ui/panes.js'
28
29
  import type { Kind, Style, StyleInit } from './ui/styles.js'
29
30
  import type { Matcher } from './utils/matcher.js'
30
31
  import type { Subscription } from './utils/subscription.js'
@@ -114,6 +115,35 @@ export type CommandInfo = { readonly name: string; readonly description: string;
114
115
 
115
116
  export type CommandRunResult = { readonly text?: string; readonly note?: string }
116
117
 
118
+ export type InterfaceName = Extract<keyof CmodInterfaces, string>
119
+
120
+ type MethodsOf<Name extends InterfaceName> = CmodInterfaces[Name] extends { readonly methods: infer Methods } ? Methods : Record<never, never>
121
+
122
+ type EventsOf<Name extends InterfaceName> = CmodInterfaces[Name] extends { readonly events: infer Events } ? Events : Record<never, never>
123
+
124
+ export type ProviderListenOptions = { readonly timeoutMs?: number; readonly onFailure?: 'pass' | 'refuse' }
125
+
126
+ export type ProviderOn<Payload> = {
127
+ (listener: (payload: Payload, signal: AbortSignal) => unknown, options?: ProviderListenOptions): Subscription
128
+ (matcher: Matcher<Payload>, listener: (payload: Payload, signal: AbortSignal) => unknown, options?: ProviderListenOptions): Subscription
129
+ }
130
+
131
+ export type ProviderBefore<Payload> = {
132
+ (listener: (payload: Payload, signal: AbortSignal) => unknown, options?: ProviderListenOptions): Subscription
133
+ (matcher: Matcher<Payload>, listener: (payload: Payload, signal: AbortSignal) => unknown, options?: ProviderListenOptions): Subscription
134
+ }
135
+
136
+ export type InterfaceMethods<Name extends InterfaceName> = { readonly [Method in keyof MethodsOf<Name>]: MethodsOf<Name>[Method] extends (...args: infer Args) => infer Result ? (...args: Args) => Result | Promise<Awaited<Result>> : never }
137
+
138
+ export type Provided<Name extends InterfaceName> = Subscription & {
139
+ tell<Event extends keyof EventsOf<Name> & string>(event: Event, payload: EventsOf<Name>[Event]): void
140
+ ask<Event extends keyof EventsOf<Name> & string>(event: Event, payload: EventsOf<Name>[Event]): Promise<unknown[]>
141
+ }
142
+
143
+ export type InterfaceProvider<Name extends InterfaceName> = { readonly mod: string; readonly program?: string; readonly device: { readonly id: string; readonly name: string } } & {
144
+ readonly [Method in keyof MethodsOf<Name>]: MethodsOf<Name>[Method] extends (...args: infer Args) => infer Result ? (...args: Args) => Promise<Awaited<Result>> : never
145
+ } & { readonly [Event in keyof EventsOf<Name> & string as `on${Event}`]: ProviderOn<EventsOf<Name>[Event]> } & { readonly [Event in keyof EventsOf<Name> & string as `before${Event}`]: ProviderBefore<EventsOf<Name>[Event]> }
146
+
117
147
  export type Imports = {
118
148
  readonly sessions: Sessions
119
149
  readonly commands: {
@@ -127,8 +157,10 @@ export type Imports = {
127
157
  readonly user: SettingsFile
128
158
  readonly project: SettingsFile
129
159
  readonly local: SettingsFile
130
- beforeFileChange(listener: SettingsFileChangeListener): Subscription
131
- beforeFileChange(matcher: Matcher<SettingsFileChange>, listener: SettingsFileChangeListener): Subscription
160
+ beforeChange(listener: SettingsFileChangeListener): Subscription
161
+ beforeChange(matcher: Matcher<SettingsFileChange>, listener: SettingsFileChangeListener): Subscription
162
+ onChange(listener: (change: SettingsFileChange) => unknown): Subscription
163
+ onChange(matcher: Matcher<SettingsFileChange>, listener: (change: SettingsFileChange) => unknown): Subscription
132
164
  }
133
165
  readonly model: { complete(request: ModelCompleteRequest, options?: ModelCompleteOptions): Promise<ModelCompleteResult> }
134
166
  readonly fs: {
@@ -152,6 +184,8 @@ export type Imports = {
152
184
  readonly device: { read(): Promise<Device> }
153
185
  readonly clipboard: { write(text: string): Promise<void> }
154
186
  readonly mods: { isLoaded(name: string): Promise<boolean> }
187
+ provide<Name extends InterfaceName>(name: Name, methods: InterfaceMethods<Name>): Provided<Name>
188
+ providers<Name extends InterfaceName>(name: Name): Promise<InterfaceProvider<Name>[]>
155
189
  }
156
190
 
157
191
  export const sessions: Imports['sessions'] = {
@@ -159,15 +193,16 @@ export const sessions: Imports['sessions'] = {
159
193
  return bound().sessions.current
160
194
  },
161
195
  list: (options) => bound().sessions.list(options),
196
+ get: (id) => bound().sessions.get(id),
162
197
  search: (text, matcher, options) => bound().sessions.search(text, matcher, options),
163
- ...(Object.fromEntries(Object.keys(sessionEvents).map((named) => [`on${named}`, (...args: unknown[]) => (bound().sessions[`on${named}` as keyof OnMethods] as (...each: unknown[]) => Subscription)(...args)])) as OnMethods),
164
198
  }
165
199
 
166
200
  export const settings: Imports['settings'] = {
167
201
  user: { read: () => bound().settings.user.read(), update: (values) => bound().settings.user.update(values) },
168
202
  project: { read: () => bound().settings.project.read(), update: (values) => bound().settings.project.update(values) },
169
203
  local: { read: () => bound().settings.local.read(), update: (values) => bound().settings.local.update(values) },
170
- beforeFileChange: ((matcherOrListener: never, listener?: never) => bound().settings.beforeFileChange(matcherOrListener, listener as never)) as Imports['settings']['beforeFileChange'],
204
+ beforeChange: ((matcherOrListener: never, listener?: never) => bound().settings.beforeChange(matcherOrListener, listener as never)) as Imports['settings']['beforeChange'],
205
+ onChange: ((matcherOrListener: never, listener?: never) => bound().settings.onChange(matcherOrListener, listener as never)) as Imports['settings']['onChange'],
171
206
  }
172
207
 
173
208
  export const commands: Imports['commands'] = {
@@ -221,10 +256,15 @@ export const mods: Imports['mods'] = {
221
256
  isLoaded: (name) => bound().mods.isLoaded(name),
222
257
  }
223
258
 
259
+ export const provide: Imports['provide'] = (name, methods) => bound().provide(name, methods)
260
+
261
+ export const providers: Imports['providers'] = (name) => bound().providers(name)
262
+
224
263
  export type Mod<State extends object = Record<never, never>, Declared extends Options = Options, Keys extends Hotkeys = Hotkeys> = {
225
264
  readonly name: string
226
265
  readonly folder: string
227
266
  readonly dataFolder: string
267
+ readonly cacheFolder: string
228
268
  readonly secrets: {
229
269
  get(key: string): Promise<string | undefined>
230
270
  store(key: string, value: string): Promise<void>
@@ -238,9 +278,10 @@ export type Mod<State extends object = Record<never, never>, Declared extends Op
238
278
  use<Handle>(job: Job<Handle, State>): Handle
239
279
  log(text: string, options?: { readonly to?: 'debug' | 'transcript'; readonly level?: 'warning' | 'error' }): void
240
280
  readonly panes: { add<Params = undefined>(pane: PaneInit<State, Params>): Pane<Params> }
241
- readonly sidebar: { add<Params = undefined>(page: PageInit<State, Params>): Page<Params> }
281
+ readonly views: { add<Params = undefined>(view: ViewInit<State, Params>): View<Params> }
282
+ readonly pages: { add<Params = undefined>(page: PageInit<State, Params>): Page<Params> }
242
283
  readonly settings: {
243
- add<Params = undefined>(page: PageInit<State, Params>): Page<Params>
284
+ add<Params = undefined>(view: ViewInit<State, Params>): View<Params>
244
285
  open(): Promise<void>
245
286
  }
246
287
  readonly widgets: { add(widget: WidgetInit<State>): Widget }
@@ -296,7 +337,7 @@ export function defineMod<State extends StateGroups = Record<never, never>, Name
296
337
 
297
338
  export type { Matcher } from './utils/matcher.js'
298
339
  export type { Combo, Hotkey, HotkeyInit, Key } from './hotkeys.js'
299
- export type { OpenOptions, Page, PageInit, PageProps, Pane, PaneClose, PaneInit, PaneProps, PaneScroll, ScrollOptions, ScrollTarget } from './ui/panes.js'
340
+ export type { OpenOptions, Page, PageInit, PageProps, Pane, PaneClose, PaneInit, PaneProps, PaneScroll, ScrollOptions, ScrollTarget, View, ViewInit, ViewProps } from './ui/panes.js'
300
341
  export type { Kind, Row, Style, StyleInit, StyleProps } from './ui/styles.js'
301
342
  export type { Block } from './ui/markdown.js'
302
343
  export { AskUserQuestion, CommandOutput, ToolGroup, ToolProgress } from './ui/styles.js'
@@ -304,7 +345,7 @@ export { AbovePrompt, BelowPrompt, Dashboard, TurnEnd, Working, type Area, type
304
345
  export type { Step } from './installer.js'
305
346
  export type { SlashCommand } from './jobs/slash-command.js'
306
347
  export type { Tool } from './jobs/tool.js'
307
- export { Session, type AnswerOptions, type BeforeMethods, type Surface, type Listener, type ListenerTime, type OnMethods, type ReadOptions, type RecordPart, type Refusal, type SearchOptions, type SessionScope, type SessionSend, type Sessions, type CurrentSession, type Placement, type ProjectSetup, type SessionStartAsked, type SessionStarted, type SessionEnded, type ModelChange, type CwdChange, type DirectoryAdd, type Worktree, type Notification, type Elicitation, type ElicitationResponse, type McpServer, type PermissionUpdate, type PermissionCheck, type PermissionRequest, type PermissionDenial, type BatchedCall, type ToolBatch, type Todo, type ReplyDisplay, type TaskOwner, type TaskStartArgs, type ToolCallArgs, type Usage, type RateLimit, type CommandRun, type CommandRunAnswer } from './session/session.js'
348
+ export { Session, type AnswerOptions, type BeforeMethods, type Surface, type Listener, type ListenerTime, type OnMethods, type ReadOptions, type RecordPart, type Refusal, type SearchOptions, type SessionScope, type SessionSend, type Sessions, type ForkArgs, type CurrentSession, type Placement, type ProjectSetup, type SessionStartAsked, type SessionStarted, type SessionEnded, type ModelChange, type CwdChange, type DirectoryAdd, type Worktree, type Notification, type Elicitation, type ElicitationResponse, type McpServer, type PermissionUpdate, type PermissionCheck, type PermissionRequest, type PermissionDenial, type BatchedCall, type ToolBatch, type Todo, type ReplyDisplay, type TaskOwner, type TaskStartArgs, type ToolCallArgs, type Usage, type RateLimit, type CommandRun, type CommandRunAnswer } from './session/session.js'
308
349
  export type { Context } from './session/context/context.js'
309
350
  export type { Turn } from './session/context/turn/turn.js'
310
351
  export type { Device } from './session/context/turn/device.js'
package/src/records.ts CHANGED
@@ -54,12 +54,16 @@ export type RunnerEvent =
54
54
 
55
55
  export const pluginName = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
56
56
 
57
- export function storeFolder(env: Record<string, string | undefined>): string {
58
- const dataHome = env['XDG_DATA_HOME']
57
+ function xdgFolder(env: Record<string, string | undefined>, variable: 'XDG_DATA_HOME' | 'XDG_CACHE_HOME', underHome: string): string {
58
+ const base = env[variable]
59
59
  const home = env['HOME']
60
- if (dataHome) return `${dataHome}/cmod`
61
- if (!home) throw new Error('Neither XDG_DATA_HOME nor HOME is set, so the cmod store has no folder. Set HOME.')
62
- return `${home}/.local/share/cmod`
60
+ if (base) return `${base}/cmod`
61
+ if (!home) throw new Error(`Neither ${variable} nor HOME is set, so cmod has no folder there. Set HOME.`)
62
+ return `${home}/${underHome}/cmod`
63
+ }
64
+
65
+ export function storeFolder(env: Record<string, string | undefined>): string {
66
+ return xdgFolder(env, 'XDG_DATA_HOME', '.local/share')
63
67
  }
64
68
 
65
69
  export function recordPath(store: string, name: string): string {
@@ -96,6 +100,10 @@ export function dataFolder(store: string, name: string): string {
96
100
  return `${store}/data/${checkedName(name)}`
97
101
  }
98
102
 
103
+ export function cacheFolder(env: Record<string, string | undefined>, name: string): string {
104
+ return `${xdgFolder(env, 'XDG_CACHE_HOME', '.cache')}/${checkedName(name)}`
105
+ }
106
+
99
107
  export function configFolder(env: Record<string, string | undefined>, name: string): string {
100
108
  const configRoot = env['CLAUDE_CONFIG_DIR']
101
109
  const home = env['HOME']
@@ -107,10 +115,14 @@ export function configFolder(env: Record<string, string | undefined>, name: stri
107
115
  export function configFolders(env: Record<string, string | undefined>, name: string, root: string): { readonly tier: 'system' | 'project'; readonly folder: string }[] {
108
116
  return [
109
117
  { tier: 'system', folder: configFolder(env, name) },
110
- { tier: 'project', folder: `${root}/.claude/cmods/${checkedName(name)}` },
118
+ { tier: 'project', folder: projectConfigFolder(root, name) },
111
119
  ]
112
120
  }
113
121
 
122
+ export function projectConfigFolder(root: string, name: string): string {
123
+ return `${root}/.claude/cmods/${checkedName(name)}`
124
+ }
125
+
114
126
  function checkedName(name: string): string {
115
127
  if (!pluginName.test(name) || name.includes('..')) {
116
128
  throw new Error(`"${name}" is not a plugin name: use letters, digits, ".", "_", and "-", starting with a letter or digit.`)
@@ -289,6 +301,18 @@ export function instancePath(store: string, mod: string, executable: string): st
289
301
  return `${instanceFolder(store, mod)}/${executable}.json`
290
302
  }
291
303
 
304
+ export function serveSocketPath(store: string): string {
305
+ return `${store}/serve.sock`
306
+ }
307
+
308
+ export type ProgramInstance = { readonly pid: number; readonly started: string; readonly address?: string; readonly tailnetUrl?: string; readonly provides?: readonly string[] }
309
+
310
+ export const processTypes = ['Interactive', 'Background'] as const
311
+
312
+ export type ProcessType = (typeof processTypes)[number]
313
+
314
+ export const interfaceName = /^[a-z0-9][\w.-]*\/[A-Z]\w*$/
315
+
292
316
  export function serviceFolder(store: string, mod: string): string {
293
317
  return `${store}/services/${checkedName(mod)}`
294
318
  }
@@ -469,9 +493,9 @@ function readHotkeys(hotkeys: unknown): Steps {
469
493
  return { hotkeys: checkHotkeys('package.json "cmod"', hotkeys as Record<string, HotkeyInit>) }
470
494
  }
471
495
 
472
- export const coreVersion = '6.3.0'
496
+ export const coreVersion = '8.0.0'
473
497
 
474
- export const oldestCmodVersion = '6.1.0'
498
+ export const oldestCmodVersion = '8.0.0'
475
499
 
476
500
  export function hotkeyCommand(mod: string, hotkey: string): string {
477
501
  return `${mod}--${hotkey}`
@@ -550,7 +574,7 @@ export async function scriptsSha256(steps: Steps, files: { read: ReadFile; list:
550
574
  text += `\0${path}\0${content}`
551
575
  }
552
576
  }
553
- const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
577
+ const digest = await crypto.subtle.digest('SHA-256', Uint8Array.from(new TextEncoder().encode(text)))
554
578
  return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('')
555
579
  }
556
580
 
package/src/register.ts CHANGED
@@ -7,7 +7,7 @@ import { serveConversations } from './runtime/conversations.js'
7
7
  import { settledAfterAbort } from './runtime/deadline.js'
8
8
  import { readDevice } from './runtime/device.js'
9
9
  import { createLifecycle, readPlugin, type Lifecycle, type ServeCmodPlugin } from './runtime/lifecycle.js'
10
- import { servePages } from './runtime/pages.js'
10
+ import { serveParts } from './runtime/parts.js'
11
11
  import { permissionRoutes, type PermissionRoutes } from './runtime/permission-check.js'
12
12
  import { serveWidgets } from './runtime/widgets.js'
13
13
  import { messageOf } from './utils/text.js'
@@ -107,6 +107,7 @@ async function startMod($: EngineInterface, eventInput: Frozen<Args<'session.sta
107
107
  env: {
108
108
  home: () => $.env.get('HOME'),
109
109
  dataHome: () => $.env.get('XDG_DATA_HOME'),
110
+ cacheHome: () => $.env.get('XDG_CACHE_HOME'),
110
111
  configHome: () => $.env.get('CLAUDE_CONFIG_DIR'),
111
112
  browser: () => $.env.get('BROWSER'),
112
113
  sshConnection: () => $.env.get('SSH_CONNECTION'),
@@ -143,10 +144,12 @@ function routeCallFailure(_$: EngineInterface, eventInput: Frozen<Args<'cmod.cal
143
144
  }
144
145
 
145
146
  export const serveCmodPlugin: ServeCmodPlugin = ({ claude, router, store, project, report, clear, tellRefusedPress, parts, markdownIn, tellStylers }) => {
146
- const conversations = serveConversations({ claude, router, store, project, report, clear })
147
+ const conversations = serveConversations({ claude, router, store, project, report, clear, sessionCode: (name) => served.providers(name) })
147
148
  const widgets = serveWidgets({ claude, router, store, report, turnClosedBy: (rowId) => conversations.turnClosedBy(rowId), parts, markdownIn })
148
- const pages = servePages({ claude, router, report, tellRefusedPress, widgets, parts, tellStylers })
149
- return { conversations, widgets, pages }
149
+ const served = serveParts({ claude, router, report, tellRefusedPress, widgets, parts, tellStylers, tellUi: (event, payload) => conversations.tellUi(event, payload) })
150
+ conversations.serveUi(served.ui)
151
+ conversations.onTurnClosed((turn) => served.turnClosed(turn))
152
+ return { conversations, widgets, parts: served }
150
153
  }
151
154
 
152
155
  export type AddHook = On
package/src/rpc.ts ADDED
@@ -0,0 +1,67 @@
1
+ import { serveSocketPath, storeFolder } from './records.js'
2
+ import { bind, importsOnly } from './runtime/bound.js'
3
+ import { connectServe } from './runtime/bun.js'
4
+ import { cmodPluginName } from './runtime/dependencies.js'
5
+ import { createProviders, interfaceListeners, interfaceMethods, programConnection, serveProviders, type Connection } from './runtime/interfaces.js'
6
+ import { RpcError, rpcCodes } from './runtime/rpc.js'
7
+ import { messageOf } from './utils/text.js'
8
+
9
+ declare const process: { readonly env: Readonly<Record<string, string | undefined>>; readonly stderr: { write(text: string): unknown } }
10
+
11
+ declare function setTimeout(run: () => void, ms: number): unknown
12
+
13
+ declare function clearTimeout(timer: unknown): void
14
+
15
+ export type { Connection }
16
+
17
+ export class NotHeld extends Error {
18
+ constructor(session: string) {
19
+ super(`This provider holds no session ${session}.`)
20
+ }
21
+ }
22
+
23
+ const modVariable = 'CMOD_MOD'
24
+
25
+ const programVariable = 'CMOD_PROGRAM'
26
+
27
+ export async function connect(): Promise<Connection> {
28
+ const mod = process.env[modVariable]
29
+ if (mod === undefined || mod === '') throw new Error(`connect() names its mod by ${modVariable}, which cmod program sets for every program it starts, and ${modVariable} is not set. Start this program from a program job with singleInstance or isService.`)
30
+ const report = (error: unknown) => void process.stderr.write(`${mod}: ${messageOf(error)}\n`)
31
+ const socket = serveSocketPath(storeFolder(process.env))
32
+ const listeners = interfaceListeners({ report })
33
+ let isWaitTold = false
34
+ let connected: () => void = () => undefined
35
+ const isConnected = new Promise<void>((resolve) => {
36
+ connected = resolve
37
+ })
38
+ const client = connectServe({
39
+ handle: async (method, params, signal) => {
40
+ const answered = await listeners.handler(method, params, signal)
41
+ if (answered !== undefined) return answered.result
42
+ const provided = served.handler(method, params, signal)
43
+ if (provided !== undefined) return provided.catch((error: unknown) => Promise.reject(error instanceof NotHeld ? new RpcError(rpcCodes.notHeld, error.message) : error))
44
+ throw new RpcError(rpcCodes.methodNotFound, `${mod} answers no ${method}.`)
45
+ },
46
+ onConnect: async (connection) => {
47
+ await served.replay()
48
+ await listeners.replay(connection)
49
+ connected()
50
+ },
51
+ onError: (error) => {
52
+ if (isWaitTold) return
53
+ isWaitTold = true
54
+ report(new Error(`waits for cmod serve at ${socket}: ${messageOf(error)}`))
55
+ },
56
+ keepsConnecting: true,
57
+ })
58
+ const after = (ms: number, run: () => void) => {
59
+ const timer = setTimeout(run, ms)
60
+ return { cancel: () => clearTimeout(timer) }
61
+ }
62
+ const served = serveProviders({ serve: client, listeners, provider: { mod, program: process.env[programVariable] || mod }, tell: async (_caller, heard, signal) => provided.answer(interfaceMethods.heard, heard, cmodPluginName, signal), sessionCode: () => [], after, report })
63
+ const provided = createProviders({ name: mod, call: (_to, method, input) => served.answer(method, input, mod) ?? Promise.reject(new Error(`${mod}'s program reaches no ${method}.`)), changed: () => undefined, after, report })
64
+ bind(importsOnly({ provide: (name, methods) => served.provide(name, methods), providers: (name) => provided.providers(name) as never }, `${mod}'s program`))
65
+ await isConnected
66
+ return programConnection({ client, listeners, served, after })
67
+ }
@@ -1,4 +1,5 @@
1
1
  import type { Imports } from '../mod.js'
2
+ import { listed } from '../utils/text.js'
2
3
 
3
4
  let current: Imports | undefined
4
5
 
@@ -10,3 +11,12 @@ export function bound(): Imports {
10
11
  if (current === undefined) throw new Error("A mod's imports work once its setup runs. Call them from setup or from a hook, never at the top of a module.")
11
12
  return current
12
13
  }
14
+
15
+ export function importsOnly(granted: Partial<Imports>, holder: string): Imports {
16
+ return new Proxy(granted as Imports, {
17
+ get: (target, key) => {
18
+ if (typeof key === 'string' && Object.hasOwn(target, key)) return target[key as keyof Imports]
19
+ throw new Error(`${holder} imports only ${listed(Object.keys(granted))} from @cmodjs/core/mod.js, because ${String(key)} belongs to a Claude Code session.`)
20
+ },
21
+ })
22
+ }
@@ -0,0 +1,40 @@
1
+ import { serveSocketPath, storeFolder } from '../records.js'
2
+ import { addressCall, connectRpc, type RpcClient, type RpcHandler } from './rpc.js'
3
+
4
+ declare const process: { readonly env: Readonly<Record<string, string | undefined>> }
5
+
6
+ declare function fetch(url: string, init: { readonly method?: string; readonly body?: string; readonly headers?: Readonly<Record<string, string>>; readonly unix?: string }): Promise<{ readonly status: number; readonly ok: boolean; readonly headers: Iterable<[string, string]>; text(): Promise<string> }>
7
+
8
+ declare function setTimeout(run: () => void, ms: number): { unref(): unknown }
9
+
10
+ export type BunInit = { readonly method?: string; readonly body?: string; readonly headers?: Readonly<Record<string, string>>; readonly socketPath?: string }
11
+
12
+ export async function bunFetch(url: string, init: BunInit = {}): Promise<{ readonly status: number; readonly ok: boolean; readonly headers: Readonly<Record<string, string>>; readonly text: string }> {
13
+ const answer = await fetch(url, { ...(init.method === undefined ? {} : { method: init.method }), ...(init.body === undefined ? {} : { body: init.body }), ...(init.headers === undefined ? {} : { headers: init.headers }), ...(init.socketPath === undefined ? {} : { unix: init.socketPath }) })
14
+ return { status: answer.status, ok: answer.ok, headers: Object.fromEntries(answer.headers), text: await answer.text() }
15
+ }
16
+
17
+ export function connectServe({
18
+ handle,
19
+ onConnect,
20
+ onError,
21
+ keepsConnecting = false,
22
+ }: {
23
+ readonly handle: RpcHandler
24
+ readonly onConnect?: (client: RpcClient) => unknown
25
+ readonly onError?: (error: unknown) => void
26
+ readonly keepsConnecting?: boolean
27
+ }): RpcClient {
28
+ return connectRpc({
29
+ call: addressCall(bunFetch, `unix:${serveSocketPath(storeFolder(process.env))}`),
30
+ handle,
31
+ ...(onConnect === undefined ? {} : { onConnect }),
32
+ ...(onError === undefined ? {} : { onError }),
33
+ wait: (ms) =>
34
+ new Promise<void>((resolve) => {
35
+ const timer = setTimeout(resolve, ms)
36
+ if (!keepsConnecting) timer.unref()
37
+ }),
38
+ keepsConnecting,
39
+ })
40
+ }
@@ -113,6 +113,7 @@ export type Claude = {
113
113
  readonly env: {
114
114
  home(): Promise<string | undefined>
115
115
  dataHome(): Promise<string | undefined>
116
+ cacheHome(): Promise<string | undefined>
116
117
  configHome(): Promise<string | undefined>
117
118
  browser(): Promise<string | undefined>
118
119
  sshConnection(): Promise<string | undefined>